mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23:34 +00:00
Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
029f3f6c58 | ||
|
|
1f685296de | ||
|
|
e0accea7ab | ||
|
|
c768f5fbe6 | ||
|
|
2db50808d5 | ||
|
|
b7a55f7fd7 | ||
|
|
7fb9d765be | ||
|
|
1f570a0d8f | ||
|
|
d2a8ee36f7 | ||
|
|
f148bee88b | ||
|
|
199043e4bc | ||
|
|
4f73d99f64 | ||
|
|
3050e93555 | ||
|
|
fcc2b9902a | ||
|
|
30ead01178 | ||
|
|
393ed3ebca | ||
|
|
870b7ffb93 | ||
|
|
e2f816b6c1 | ||
|
|
c22332a7ce | ||
|
|
8199ca5a18 | ||
|
|
dc549e64bd | ||
|
|
e88b8c90d9 | ||
|
|
766aea14b9 | ||
|
|
653a7c0f0c | ||
|
|
42637458c9 |
No files matched your search
Generated
+668
-41
File diff suppressed because it is too large.
Load diff
@@ -29,6 +29,7 @@
|
|||||||
"@getalby/sdk": "^6.0.1",
|
"@getalby/sdk": "^6.0.1",
|
||||||
"@hookform/resolvers": "^3.9.0",
|
"@hookform/resolvers": "^3.9.0",
|
||||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||||
|
"@modelcontextprotocol/sdk": "^1.22.0",
|
||||||
"@mozilla/readability": "^0.6.0",
|
"@mozilla/readability": "^0.6.0",
|
||||||
"@nostrify/nostrify": "^0.47.1",
|
"@nostrify/nostrify": "^0.47.1",
|
||||||
"@nostrify/react": "^0.2.17",
|
"@nostrify/react": "^0.2.17",
|
||||||
|
|||||||
+6
-1
@@ -48,7 +48,7 @@ const queryClient = new QueryClient({
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Get OS-specific default paths for Electron
|
// Get OS-specific default paths for Electron
|
||||||
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string } {
|
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string; fsPathTemplates: string } {
|
||||||
if (!globalThis.electron) {
|
if (!globalThis.electron) {
|
||||||
// Browser defaults - use virtual filesystem paths
|
// Browser defaults - use virtual filesystem paths
|
||||||
return {
|
return {
|
||||||
@@ -56,6 +56,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
|
|||||||
fsPathConfig: "/config",
|
fsPathConfig: "/config",
|
||||||
fsPathTmp: "/tmp",
|
fsPathTmp: "/tmp",
|
||||||
fsPathPlugins: "/plugins",
|
fsPathPlugins: "/plugins",
|
||||||
|
fsPathTemplates: "/templates",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,6 +71,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
|
|||||||
fsPathConfig: "~/AppData/Local/shakespeare",
|
fsPathConfig: "~/AppData/Local/shakespeare",
|
||||||
fsPathTmp: "~/AppData/Local/Temp/shakespeare",
|
fsPathTmp: "~/AppData/Local/Temp/shakespeare",
|
||||||
fsPathPlugins: "~/AppData/Local/shakespeare/plugins",
|
fsPathPlugins: "~/AppData/Local/shakespeare/plugins",
|
||||||
|
fsPathTemplates: "~/AppData/Local/shakespeare/templates",
|
||||||
};
|
};
|
||||||
} else if (platform.includes('mac')) {
|
} else if (platform.includes('mac')) {
|
||||||
// macOS
|
// macOS
|
||||||
@@ -78,6 +80,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
|
|||||||
fsPathConfig: "~/Library/Application Support/shakespeare",
|
fsPathConfig: "~/Library/Application Support/shakespeare",
|
||||||
fsPathTmp: "/tmp/shakespeare",
|
fsPathTmp: "/tmp/shakespeare",
|
||||||
fsPathPlugins: "~/Library/Application Support/shakespeare/plugins",
|
fsPathPlugins: "~/Library/Application Support/shakespeare/plugins",
|
||||||
|
fsPathTemplates: "~/Library/Application Support/shakespeare/templates",
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
// Linux and other Unix-like systems
|
// Linux and other Unix-like systems
|
||||||
@@ -86,6 +89,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
|
|||||||
fsPathConfig: "~/.config/shakespeare",
|
fsPathConfig: "~/.config/shakespeare",
|
||||||
fsPathTmp: "/tmp/shakespeare",
|
fsPathTmp: "/tmp/shakespeare",
|
||||||
fsPathPlugins: "~/.config/shakespeare/plugins",
|
fsPathPlugins: "~/.config/shakespeare/plugins",
|
||||||
|
fsPathTemplates: "~/.config/shakespeare/templates",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -114,6 +118,7 @@ const defaultConfig: AppConfig = {
|
|||||||
fsPathConfig: electronPaths.fsPathConfig,
|
fsPathConfig: electronPaths.fsPathConfig,
|
||||||
fsPathTmp: electronPaths.fsPathTmp,
|
fsPathTmp: electronPaths.fsPathTmp,
|
||||||
fsPathPlugins: electronPaths.fsPathPlugins,
|
fsPathPlugins: electronPaths.fsPathPlugins,
|
||||||
|
fsPathTemplates: electronPaths.fsPathTemplates,
|
||||||
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
|
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
|
||||||
sentryEnabled: true,
|
sentryEnabled: true,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import { UserMessage } from '@/components/UserMessage';
|
|||||||
import OpenAI from 'openai';
|
import OpenAI from 'openai';
|
||||||
import { useTheme } from '@/hooks/useTheme';
|
import { useTheme } from '@/hooks/useTheme';
|
||||||
import { isEmptyMessage } from '@/lib/isEmptyMessage';
|
import { isEmptyMessage } from '@/lib/isEmptyMessage';
|
||||||
|
import { Dialog, DialogPortal, DialogOverlay } from '@/components/ui/dialog';
|
||||||
|
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||||
|
|
||||||
// Type guard to check if message has reasoning content
|
// Type guard to check if message has reasoning content
|
||||||
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
|
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
|
||||||
@@ -26,6 +28,7 @@ export const AIMessageItem = memo(({
|
|||||||
}: AIMessageItemProps) => {
|
}: AIMessageItemProps) => {
|
||||||
const [isToolExpanded, setIsToolExpanded] = useState(false);
|
const [isToolExpanded, setIsToolExpanded] = useState(false);
|
||||||
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
|
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
|
||||||
|
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
|
||||||
const { displayTheme } = useTheme();
|
const { displayTheme } = useTheme();
|
||||||
|
|
||||||
// Get content to display
|
// Get content to display
|
||||||
@@ -295,20 +298,90 @@ export const AIMessageItem = memo(({
|
|||||||
// Regular rendering for non-tool messages
|
// Regular rendering for non-tool messages
|
||||||
if (message.role === 'user') {
|
if (message.role === 'user') {
|
||||||
// User messages: right-aligned bubble without avatar/name
|
// User messages: right-aligned bubble without avatar/name
|
||||||
|
// Extract text and image parts from message content
|
||||||
|
const contentArray = Array.isArray(message.content) ? message.content : null;
|
||||||
|
const textParts = contentArray
|
||||||
|
? contentArray.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
|
||||||
|
: [];
|
||||||
const userContent = typeof message.content === 'string'
|
const userContent = typeof message.content === 'string'
|
||||||
? message.content
|
? message.content
|
||||||
: Array.isArray(message.content)
|
: textParts.length > 0
|
||||||
? message.content.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
|
? textParts.map(part => part.text).join('\n')
|
||||||
: '';
|
: '';
|
||||||
|
|
||||||
|
// Extract image URLs from content array
|
||||||
|
const imageUrls = contentArray
|
||||||
|
? contentArray
|
||||||
|
.filter(part => part.type === 'image_url')
|
||||||
|
.map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage).image_url.url)
|
||||||
|
: [];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex justify-end py-6">
|
<>
|
||||||
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
|
<div className="flex justify-end py-6">
|
||||||
<div className="text-sm break-words">
|
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
|
||||||
<UserMessage content={userContent} />
|
<div className="text-sm break-words space-y-2">
|
||||||
|
{/* Render text content and attachments first */}
|
||||||
|
{userContent && <UserMessage content={userContent} />}
|
||||||
|
{/* Render images after text and attachments */}
|
||||||
|
{imageUrls.length > 0 && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{imageUrls.map((url, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="rounded-lg overflow-hidden border border-border cursor-pointer hover:opacity-90 transition-opacity"
|
||||||
|
onClick={() => setExpandedImageUrl(url)}
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
src={url}
|
||||||
|
alt={`User uploaded image ${index + 1}`}
|
||||||
|
className="max-w-full h-auto max-h-96 object-contain"
|
||||||
|
loading="lazy"
|
||||||
|
onError={(e) => {
|
||||||
|
// Fallback if image fails to load
|
||||||
|
const target = e.target as HTMLImageElement;
|
||||||
|
target.style.display = 'none';
|
||||||
|
const fallback = document.createElement('div');
|
||||||
|
fallback.className = 'p-2 text-xs text-muted-foreground bg-muted rounded';
|
||||||
|
fallback.textContent = `Image failed to load: ${url}`;
|
||||||
|
target.parentElement?.appendChild(fallback);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
{/* Image expansion dialog */}
|
||||||
|
<Dialog open={!!expandedImageUrl} onOpenChange={(open) => !open && setExpandedImageUrl(null)}>
|
||||||
|
<DialogPortal>
|
||||||
|
<DialogOverlay className="bg-black/95" />
|
||||||
|
<DialogPrimitive.Content
|
||||||
|
className={cn(
|
||||||
|
"fixed left-[50%] top-[50%] z-50 max-w-[95vw] max-h-[95vh] translate-x-[-50%] translate-y-[-50%] p-0 bg-transparent border-0 shadow-none",
|
||||||
|
"data-[state=open]:animate-in data-[state=closed]:animate-out",
|
||||||
|
"data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||||
|
"data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95"
|
||||||
|
)}
|
||||||
|
onPointerDownOutside={() => setExpandedImageUrl(null)}
|
||||||
|
onEscapeKeyDown={() => setExpandedImageUrl(null)}
|
||||||
|
>
|
||||||
|
{expandedImageUrl && (
|
||||||
|
<div className="relative flex items-center justify-center">
|
||||||
|
<img
|
||||||
|
src={expandedImageUrl}
|
||||||
|
alt="Expanded image"
|
||||||
|
className="max-w-full max-h-[95vh] w-auto h-auto object-contain rounded-lg"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DialogPrimitive.Content>
|
||||||
|
</DialogPortal>
|
||||||
|
</Dialog>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useQueryClient } from '@tanstack/react-query';
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
import { ReactNode, useState, useEffect } from 'react';
|
import { ReactNode, useState, useEffect } from 'react';
|
||||||
import { AISettingsContext, type AISettings, type AIProvider, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
import { AISettingsContext, type AISettings, type AIProvider, type MCPServer, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||||
import { readAISettings, writeAISettings } from '@/lib/configUtils';
|
import { readAISettings, writeAISettings } from '@/lib/configUtils';
|
||||||
@@ -12,6 +12,7 @@ interface AISettingsProviderProps {
|
|||||||
const DEFAULT_SETTINGS: AISettings = {
|
const DEFAULT_SETTINGS: AISettings = {
|
||||||
providers: [],
|
providers: [],
|
||||||
recentlyUsedModels: [],
|
recentlyUsedModels: [],
|
||||||
|
mcpServers: {},
|
||||||
};
|
};
|
||||||
|
|
||||||
export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||||
@@ -128,6 +129,27 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const setMCPServer = (name: string, server: MCPServer) => {
|
||||||
|
setSettings(prev => ({
|
||||||
|
...prev,
|
||||||
|
mcpServers: {
|
||||||
|
...(prev.mcpServers || {}),
|
||||||
|
[name]: server,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeMCPServer = (name: string) => {
|
||||||
|
setSettings(prev => {
|
||||||
|
const newMCPServers = { ...(prev.mcpServers || {}) };
|
||||||
|
delete newMCPServers[name];
|
||||||
|
return {
|
||||||
|
...prev,
|
||||||
|
mcpServers: newMCPServers,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const isConfigured = settings.providers.length > 0;
|
const isConfigured = settings.providers.length > 0;
|
||||||
|
|
||||||
const contextValue: AISettingsContextType = {
|
const contextValue: AISettingsContextType = {
|
||||||
@@ -137,6 +159,8 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
|||||||
removeProvider,
|
removeProvider,
|
||||||
setProviders,
|
setProviders,
|
||||||
addRecentlyUsedModel,
|
addRecentlyUsedModel,
|
||||||
|
setMCPServer,
|
||||||
|
removeMCPServer,
|
||||||
isConfigured,
|
isConfigured,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ const AppConfigSchema = z.object({
|
|||||||
fsPathConfig: z.string().min(1),
|
fsPathConfig: z.string().min(1),
|
||||||
fsPathTmp: z.string().min(1),
|
fsPathTmp: z.string().min(1),
|
||||||
fsPathPlugins: z.string().min(1),
|
fsPathPlugins: z.string().min(1),
|
||||||
|
fsPathTemplates: z.string().min(1),
|
||||||
sentryDsn: z.string(),
|
sentryDsn: z.string(),
|
||||||
sentryEnabled: z.boolean(),
|
sentryEnabled: z.boolean(),
|
||||||
}) satisfies z.ZodType<AppConfig>;
|
}) satisfies z.ZodType<AppConfig>;
|
||||||
@@ -76,6 +77,7 @@ export function AppProvider(props: AppProviderProps) {
|
|||||||
config.fsPathProjects = expandPath(config.fsPathProjects);
|
config.fsPathProjects = expandPath(config.fsPathProjects);
|
||||||
config.fsPathTmp = expandPath(config.fsPathTmp);
|
config.fsPathTmp = expandPath(config.fsPathTmp);
|
||||||
config.fsPathPlugins = expandPath(config.fsPathPlugins);
|
config.fsPathPlugins = expandPath(config.fsPathPlugins);
|
||||||
|
config.fsPathTemplates = expandPath(config.fsPathTemplates);
|
||||||
|
|
||||||
const appContextValue: AppContextType = {
|
const appContextValue: AppContextType = {
|
||||||
config,
|
config,
|
||||||
|
|||||||
@@ -0,0 +1,339 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Server, Trash2, Check, Plus, X } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
|
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||||
|
import { Separator } from '@/components/ui/separator';
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||||
|
import { useAISettings } from '@/hooks/useAISettings';
|
||||||
|
import { useToast } from '@/hooks/useToast';
|
||||||
|
import { useMCPServerStatus } from '@/hooks/useMCPServerStatus';
|
||||||
|
import type { MCPServer } from '@/contexts/AISettingsContext';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
function MCPConnectionStatus({ server }: { server: MCPServer }) {
|
||||||
|
const status = useMCPServerStatus(server);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-1.5 ml-auto mr-2">
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'h-2 w-2 rounded-full',
|
||||||
|
status === 'connected' && 'bg-green-500',
|
||||||
|
status === 'offline' && 'bg-red-500',
|
||||||
|
status === 'checking' && 'bg-yellow-500 animate-pulse'
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<span className="text-xs text-muted-foreground capitalize">
|
||||||
|
{status}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface HeadersEditorProps {
|
||||||
|
headers: Record<string, string> | undefined;
|
||||||
|
onChange: (headers: Record<string, string> | undefined) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function HeadersEditor({ headers, onChange }: HeadersEditorProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [newHeaderName, setNewHeaderName] = useState('');
|
||||||
|
const [newHeaderValue, setNewHeaderValue] = useState('');
|
||||||
|
|
||||||
|
const headerEntries = Object.entries(headers || {});
|
||||||
|
|
||||||
|
const handleAddHeader = () => {
|
||||||
|
if (!newHeaderName.trim() || !newHeaderValue.trim()) return;
|
||||||
|
|
||||||
|
const updatedHeaders = {
|
||||||
|
...(headers || {}),
|
||||||
|
[newHeaderName.trim()]: newHeaderValue.trim(),
|
||||||
|
};
|
||||||
|
|
||||||
|
onChange(updatedHeaders);
|
||||||
|
setNewHeaderName('');
|
||||||
|
setNewHeaderValue('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoveHeader = (name: string) => {
|
||||||
|
const updatedHeaders = { ...(headers || {}) };
|
||||||
|
delete updatedHeaders[name];
|
||||||
|
|
||||||
|
// If no headers left, set to undefined
|
||||||
|
onChange(Object.keys(updatedHeaders).length > 0 ? updatedHeaders : undefined);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleUpdateHeader = (oldName: string, newName: string, newValue: string) => {
|
||||||
|
const updatedHeaders = { ...(headers || {}) };
|
||||||
|
delete updatedHeaders[oldName];
|
||||||
|
updatedHeaders[newName] = newValue;
|
||||||
|
onChange(updatedHeaders);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<Label>{t('mcpServerHeaders')}</Label>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{t('mcpServerHeadersDescription')}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{/* Existing Headers */}
|
||||||
|
{headerEntries.length > 0 && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{headerEntries.map(([name, value]) => (
|
||||||
|
<div key={name} className="flex gap-2">
|
||||||
|
<Input
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => handleUpdateHeader(name, e.target.value, value)}
|
||||||
|
placeholder="Header name"
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => handleUpdateHeader(name, name, e.target.value)}
|
||||||
|
placeholder="Header value"
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => handleRemoveHeader(name)}
|
||||||
|
className="shrink-0"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Add New Header */}
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Input
|
||||||
|
value={newHeaderName}
|
||||||
|
onChange={(e) => setNewHeaderName(e.target.value)}
|
||||||
|
placeholder="Header name (e.g., Authorization)"
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
value={newHeaderValue}
|
||||||
|
onChange={(e) => setNewHeaderValue(e.target.value)}
|
||||||
|
placeholder="Header value"
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
onClick={handleAddHeader}
|
||||||
|
disabled={!newHeaderName.trim() || !newHeaderValue.trim()}
|
||||||
|
className="shrink-0"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MCPServersSection() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { settings, setMCPServer, removeMCPServer } = useAISettings();
|
||||||
|
const { toast } = useToast();
|
||||||
|
const [serverName, setServerName] = useState('');
|
||||||
|
const [serverUrl, setServerUrl] = useState('');
|
||||||
|
const [serverHeaders, setServerHeaders] = useState<Record<string, string> | undefined>(undefined);
|
||||||
|
const [serverType] = useState<'streamable-http'>('streamable-http'); // Only streamable-http is supported
|
||||||
|
|
||||||
|
const mcpServers = settings.mcpServers || {};
|
||||||
|
const serverEntries = Object.entries(mcpServers);
|
||||||
|
|
||||||
|
const handleAddServer = () => {
|
||||||
|
if (!serverName.trim() || !serverUrl.trim()) return;
|
||||||
|
|
||||||
|
if (mcpServers[serverName.trim()]) {
|
||||||
|
toast({
|
||||||
|
title: t('error'),
|
||||||
|
description: t('mcpServerAddFailed'),
|
||||||
|
variant: 'destructive',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const newServer: MCPServer = {
|
||||||
|
type: serverType,
|
||||||
|
url: serverUrl.trim(),
|
||||||
|
headers: serverHeaders,
|
||||||
|
};
|
||||||
|
|
||||||
|
setMCPServer(serverName.trim(), newServer);
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: t('mcpServerAdded'),
|
||||||
|
description: t('mcpServerAddedDescription', { name: serverName.trim() }),
|
||||||
|
});
|
||||||
|
|
||||||
|
setServerName('');
|
||||||
|
setServerUrl('');
|
||||||
|
setServerHeaders(undefined);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoveServer = (name: string) => {
|
||||||
|
removeMCPServer(name);
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: t('mcpServerDeleted'),
|
||||||
|
description: t('mcpServerDeletedDescription', { name }),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Divider */}
|
||||||
|
<Separator className="my-6" />
|
||||||
|
|
||||||
|
{/* MCP Servers Header */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Server className="h-5 w-5 text-primary" />
|
||||||
|
<h3 className="text-lg font-semibold">{t('mcpServers')}</h3>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{t('mcpServersDescription')}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Configured MCP Servers List */}
|
||||||
|
{serverEntries.length > 0 ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{serverEntries.map(([name, server]) => (
|
||||||
|
<Accordion key={name} type="single" collapsible className="w-full">
|
||||||
|
<AccordionItem value={name} className="border rounded-lg">
|
||||||
|
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||||
|
<div className="flex items-center gap-2 w-full mr-3">
|
||||||
|
<Server size={16} className="text-primary" />
|
||||||
|
<span className="font-medium">{name}</span>
|
||||||
|
<MCPConnectionStatus server={server} />
|
||||||
|
</div>
|
||||||
|
</AccordionTrigger>
|
||||||
|
<AccordionContent className="px-4 pb-4">
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor={`${name}-type`}>{t('mcpServerType')}</Label>
|
||||||
|
<Select value={server.type} disabled>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="streamable-http">{t('mcpServerTypeStreamableHttp')}</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor={`${name}-url`}>{t('mcpServerUrl')}</Label>
|
||||||
|
<Input
|
||||||
|
id={`${name}-url`}
|
||||||
|
value={server.url}
|
||||||
|
onChange={(e) => setMCPServer(name, { ...server, url: e.target.value })}
|
||||||
|
placeholder="https://example.com/mcp"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<HeadersEditor
|
||||||
|
headers={server.headers}
|
||||||
|
onChange={(headers) => setMCPServer(name, { ...server, headers })}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleRemoveServer(name)}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4 mr-2" />
|
||||||
|
{t('delete')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</AccordionContent>
|
||||||
|
</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<Alert>
|
||||||
|
<AlertDescription className="text-sm">
|
||||||
|
{t('noMcpServersConfigured')}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Add New MCP Server */}
|
||||||
|
<Accordion type="single" collapsible className="w-full">
|
||||||
|
<AccordionItem value="add-server" className="border rounded-lg">
|
||||||
|
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
<span className="text-sm font-medium">{t('addMcpServer')}</span>
|
||||||
|
</div>
|
||||||
|
</AccordionTrigger>
|
||||||
|
<AccordionContent className="px-4 pb-4">
|
||||||
|
<div className="space-y-3">
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{t('mcpServerDescription')}
|
||||||
|
</p>
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor="new-server-name">{t('mcpServerName')}</Label>
|
||||||
|
<Input
|
||||||
|
id="new-server-name"
|
||||||
|
placeholder="e.g., my-mcp-server"
|
||||||
|
value={serverName}
|
||||||
|
onChange={(e) => setServerName(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor="new-server-type">{t('mcpServerType')}</Label>
|
||||||
|
<Select value={serverType} disabled>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="streamable-http">{t('mcpServerTypeStreamableHttp')}</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Only Streamable HTTP transport is currently supported
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor="new-server-url">{t('mcpServerUrl')}</Label>
|
||||||
|
<Input
|
||||||
|
id="new-server-url"
|
||||||
|
placeholder="https://example.com/mcp"
|
||||||
|
value={serverUrl}
|
||||||
|
onChange={(e) => setServerUrl(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<HeadersEditor
|
||||||
|
headers={serverHeaders}
|
||||||
|
onChange={setServerHeaders}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
onClick={handleAddServer}
|
||||||
|
disabled={!serverName.trim() || !serverUrl.trim() || !!mcpServers[serverName.trim()]}
|
||||||
|
className="gap-2 w-full"
|
||||||
|
>
|
||||||
|
<Check className="h-4 w-4" />
|
||||||
|
{t('add')}
|
||||||
|
</Button>
|
||||||
|
{mcpServers[serverName.trim()] && (
|
||||||
|
<p className="text-sm text-destructive">
|
||||||
|
A server with this name already exists
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</AccordionContent>
|
||||||
|
</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -42,14 +42,15 @@ describe('ModelSelector', () => {
|
|||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
|
|
||||||
mockUseAISettings.mockReturnValue({
|
mockUseAISettings.mockReturnValue({
|
||||||
settings: { providers: [], recentlyUsedModels: [] },
|
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
|
||||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||||
isConfigured: true,
|
isConfigured: true,
|
||||||
updateSettings: vi.fn(),
|
updateSettings: vi.fn(),
|
||||||
removeProvider: vi.fn(),
|
removeProvider: vi.fn(),
|
||||||
setProvider: vi.fn(),
|
setProvider: vi.fn(),
|
||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
});
|
});
|
||||||
|
|
||||||
mockUseProviderModels.mockReturnValue({
|
mockUseProviderModels.mockReturnValue({
|
||||||
@@ -87,6 +88,8 @@ describe('ModelSelector', () => {
|
|||||||
removeProvider: vi.fn(),
|
removeProvider: vi.fn(),
|
||||||
setProvider: vi.fn(),
|
setProvider: vi.fn(),
|
||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -140,6 +143,8 @@ describe('ModelSelector', () => {
|
|||||||
removeProvider: vi.fn(),
|
removeProvider: vi.fn(),
|
||||||
setProvider: vi.fn(),
|
setProvider: vi.fn(),
|
||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -189,6 +194,8 @@ describe('ModelSelector', () => {
|
|||||||
removeProvider: vi.fn(),
|
removeProvider: vi.fn(),
|
||||||
setProvider: vi.fn(),
|
setProvider: vi.fn(),
|
||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -233,13 +240,15 @@ describe('ModelSelector', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
mockUseAISettings.mockReturnValue({
|
mockUseAISettings.mockReturnValue({
|
||||||
settings: { providers: [], recentlyUsedModels: [] }, // No recently used models
|
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} }, // No recently used models
|
||||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||||
isConfigured: true,
|
isConfigured: true,
|
||||||
updateSettings: vi.fn(),
|
updateSettings: vi.fn(),
|
||||||
removeProvider: vi.fn(),
|
removeProvider: vi.fn(),
|
||||||
setProvider: vi.fn(),
|
setProvider: vi.fn(),
|
||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ describe('SentryProvider', () => {
|
|||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
fsPathTmp: '/tmp',
|
fsPathTmp: '/tmp',
|
||||||
fsPathPlugins: '/plugins',
|
fsPathPlugins: '/plugins',
|
||||||
|
fsPathTemplates: '/templates',
|
||||||
};
|
};
|
||||||
|
|
||||||
render(
|
render(
|
||||||
@@ -75,6 +76,7 @@ describe('SentryProvider', () => {
|
|||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
fsPathTmp: '/tmp',
|
fsPathTmp: '/tmp',
|
||||||
fsPathPlugins: '/plugins',
|
fsPathPlugins: '/plugins',
|
||||||
|
fsPathTemplates: '/templates',
|
||||||
};
|
};
|
||||||
|
|
||||||
render(
|
render(
|
||||||
@@ -112,6 +114,7 @@ describe('SentryProvider', () => {
|
|||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
fsPathTmp: '/tmp',
|
fsPathTmp: '/tmp',
|
||||||
fsPathPlugins: '/plugins',
|
fsPathPlugins: '/plugins',
|
||||||
|
fsPathTemplates: '/templates',
|
||||||
};
|
};
|
||||||
|
|
||||||
render(
|
render(
|
||||||
@@ -152,6 +155,7 @@ describe('SentryProvider', () => {
|
|||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
fsPathTmp: '/tmp',
|
fsPathTmp: '/tmp',
|
||||||
fsPathPlugins: '/plugins',
|
fsPathPlugins: '/plugins',
|
||||||
|
fsPathTemplates: '/templates',
|
||||||
};
|
};
|
||||||
|
|
||||||
render(
|
render(
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { useAppContext } from '@/hooks/useAppContext';
|
|||||||
import { useAIChat } from '@/hooks/useAIChat';
|
import { useAIChat } from '@/hooks/useAIChat';
|
||||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||||
|
import { useMCPTools } from '@/hooks/useMCPTools';
|
||||||
import { AIMessageItem } from '@/components/AIMessageItem';
|
import { AIMessageItem } from '@/components/AIMessageItem';
|
||||||
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
|
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
|
||||||
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
|
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
|
||||||
@@ -35,15 +36,16 @@ import { ShellTool } from '@/lib/tools/ShellTool';
|
|||||||
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
||||||
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
|
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||||
import { SkillTool } from '@/lib/tools/SkillTool';
|
import { SkillTool } from '@/lib/tools/SkillTool';
|
||||||
|
import { createMCPTools } from '@/lib/tools/MCPTool';
|
||||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||||
import { Tool } from '@/lib/tools/Tool';
|
import { Tool } from '@/lib/tools/Tool';
|
||||||
import OpenAI from 'openai';
|
import OpenAI from 'openai';
|
||||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
|
||||||
import { useGit } from '@/hooks/useGit';
|
import { useGit } from '@/hooks/useGit';
|
||||||
import { Quilly } from '@/components/Quilly';
|
import { Quilly } from '@/components/Quilly';
|
||||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||||
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
||||||
|
import { buildMessageContent } from '@/lib/buildMessageContent';
|
||||||
|
|
||||||
// Clean interfaces now handled by proper hooks
|
// Clean interfaces now handled by proper hooks
|
||||||
|
|
||||||
@@ -148,8 +150,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
sessionManager.emit('fileChanged', projectId, filePath);
|
sessionManager.emit('fileChanged', projectId, filePath);
|
||||||
}, [sessionManager, projectId]);
|
}, [sessionManager, projectId]);
|
||||||
|
|
||||||
const customTools = useMemo(() => {
|
// Fetch MCP tools
|
||||||
const baseTools = {
|
const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools();
|
||||||
|
|
||||||
|
// Separate built-in tools from MCP tools for clarity
|
||||||
|
const builtInTools = useMemo(() => {
|
||||||
|
const tools: Record<string, Tool<unknown>> = {
|
||||||
git_commit: new GitCommitTool(fs, cwd, git),
|
git_commit: new GitCommitTool(fs, cwd, git),
|
||||||
text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }),
|
text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }),
|
||||||
text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
|
text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
|
||||||
@@ -166,30 +172,42 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||||
nostr_publish_events: new NostrPublishEventsTool(),
|
nostr_publish_events: new NostrPublishEventsTool(),
|
||||||
shell: new ShellTool(fs, cwd, git, projectsPath, config.corsProxy, user?.signer),
|
shell: new ShellTool(fs, cwd, git, config.corsProxy, user?.signer),
|
||||||
read_console_messages: new ReadConsoleMessagesTool(),
|
read_console_messages: new ReadConsoleMessagesTool(),
|
||||||
skill: new SkillTool(fs, pluginsPath),
|
skill: new SkillTool(fs, pluginsPath),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Add deploy tool only if user is logged in
|
// Add deploy tool only if user is logged in
|
||||||
if (user && user.signer) {
|
if (user && user.signer) {
|
||||||
return {
|
tools.deploy_project = new DeployProjectTool(fs, cwd, user.signer, projectId);
|
||||||
...baseTools,
|
|
||||||
deploy_project: new DeployProjectTool(fs, cwd, user.signer, projectId),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return baseTools;
|
return tools;
|
||||||
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, handleFileChanged]);
|
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, handleFileChanged]);
|
||||||
|
|
||||||
// Convert tools to OpenAI format
|
// MCP tools wrapped for execution
|
||||||
|
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
|
||||||
|
|
||||||
|
// Combined tool executors (for SessionManager to call)
|
||||||
|
const customTools = useMemo(() => ({
|
||||||
|
...builtInTools,
|
||||||
|
...mcpToolWrappers,
|
||||||
|
}), [builtInTools, mcpToolWrappers]);
|
||||||
|
|
||||||
|
// Convert tools to OpenAI format for AI provider
|
||||||
const tools = useMemo(() => {
|
const tools = useMemo(() => {
|
||||||
const result: Record<string, OpenAI.Chat.Completions.ChatCompletionTool> = {};
|
const result: Record<string, OpenAI.Chat.Completions.ChatCompletionTool> = {};
|
||||||
for (const [name, tool] of Object.entries(customTools)) {
|
|
||||||
|
// Convert built-in tools to OpenAI format
|
||||||
|
for (const [name, tool] of Object.entries(builtInTools)) {
|
||||||
result[name] = toolToOpenAI(name, tool as Tool<unknown>);
|
result[name] = toolToOpenAI(name, tool as Tool<unknown>);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add MCP tools (already in OpenAI format from useMCPTools)
|
||||||
|
Object.assign(result, mcpOpenAITools);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}, [customTools]);
|
}, [builtInTools, mcpOpenAITools]);
|
||||||
|
|
||||||
// Keep-alive functionality to prevent tab throttling during AI processing
|
// Keep-alive functionality to prevent tab throttling during AI processing
|
||||||
const { updateMetadata } = useKeepAlive({
|
const { updateMetadata } = useKeepAlive({
|
||||||
@@ -438,45 +456,18 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
|
|
||||||
const modelToUse = providerModel.trim();
|
const modelToUse = providerModel.trim();
|
||||||
|
|
||||||
// Build message content as text parts
|
// Build message content from input and attached files
|
||||||
const contentParts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
|
// Images are converted to base64-encoded data URLs
|
||||||
|
const messageContent = await buildMessageContent(
|
||||||
// Add user input as text part if present
|
input,
|
||||||
if (input.trim()) {
|
attachedFiles,
|
||||||
contentParts.push({
|
fs,
|
||||||
type: 'text',
|
tmpPath
|
||||||
text: input.trim()
|
);
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process attached files and add as separate text parts
|
|
||||||
if (attachedFiles.length > 0) {
|
|
||||||
const filePromises = attachedFiles.map(async (file) => {
|
|
||||||
try {
|
|
||||||
const savedPath = await saveFileToTmp(fs, file, tmpPath);
|
|
||||||
return `Added file: ${savedPath}`;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to save file:', error);
|
|
||||||
return `Failed to save file: ${file.name}`;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const fileResults = await Promise.all(filePromises);
|
|
||||||
|
|
||||||
// Add each file as a separate text part
|
|
||||||
fileResults.forEach(fileResult => {
|
|
||||||
contentParts.push({
|
|
||||||
type: 'text',
|
|
||||||
text: fileResult
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add model to recently used when sending a message
|
// Add model to recently used when sending a message
|
||||||
addRecentlyUsedModel(modelToUse);
|
addRecentlyUsedModel(modelToUse);
|
||||||
|
|
||||||
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
|
|
||||||
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
|
|
||||||
await sendMessage(messageContent, modelToUse);
|
await sendMessage(messageContent, modelToUse);
|
||||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
|
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
|
||||||
|
|
||||||
|
|||||||
@@ -3,9 +3,10 @@ import { useTranslation } from 'react-i18next';
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Textarea } from '@/components/ui/textarea';
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
import { CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
import { CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { Save, Loader2 } from 'lucide-react';
|
import { Save, Loader2, ImageOff } from 'lucide-react';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||||
|
import { isMediaFile } from '@/lib/fileUtils';
|
||||||
|
|
||||||
interface FileEditorProps {
|
interface FileEditorProps {
|
||||||
filePath: string;
|
filePath: string;
|
||||||
@@ -93,6 +94,7 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
|
|||||||
// Get git status for the current file
|
// Get git status for the current file
|
||||||
const currentFileGitStatus = getFileGitStatus(filePath);
|
const currentFileGitStatus = getFileGitStatus(filePath);
|
||||||
const gitStatusClasses = getGitStatusClasses(currentFileGitStatus);
|
const gitStatusClasses = getGitStatusClasses(currentFileGitStatus);
|
||||||
|
const isMedia = isMediaFile(filePath);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="h-full flex flex-col">
|
<div className="h-full flex flex-col">
|
||||||
@@ -100,32 +102,36 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
|
|||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<CardTitle className={cn("text-sm sm:text-base truncate flex-1 mr-2", gitStatusClasses)}>{filePath}</CardTitle>
|
<CardTitle className={cn("text-sm sm:text-base truncate flex-1 mr-2", gitStatusClasses)}>{filePath}</CardTitle>
|
||||||
<div className="flex items-center space-x-1 sm:space-x-2">
|
<div className="flex items-center space-x-1 sm:space-x-2">
|
||||||
{hasChanges && (
|
{hasChanges && !isMedia && (
|
||||||
<span className="text-xs sm:text-sm text-muted-foreground hidden sm:inline">{t('unsavedChanges')}</span>
|
<span className="text-xs sm:text-sm text-muted-foreground hidden sm:inline">{t('unsavedChanges')}</span>
|
||||||
)}
|
)}
|
||||||
<Button
|
{!isMedia && (
|
||||||
onClick={handleSave}
|
<Button
|
||||||
disabled={!hasChanges || isSaving || isLoading}
|
onClick={handleSave}
|
||||||
size="sm"
|
disabled={!hasChanges || isSaving || isLoading}
|
||||||
className="focus-ring"
|
size="sm"
|
||||||
>
|
className="focus-ring"
|
||||||
{isSaving ? (
|
>
|
||||||
<>
|
{isSaving ? (
|
||||||
<Loader2 className="mr-1 sm:mr-2 h-4 w-4 animate-spin" />
|
<>
|
||||||
<span className="hidden sm:inline">{t('saving')}</span>
|
<Loader2 className="mr-1 sm:mr-2 h-4 w-4 animate-spin" />
|
||||||
</>
|
<span className="hidden sm:inline">{t('saving')}</span>
|
||||||
) : (
|
</>
|
||||||
<>
|
) : (
|
||||||
<Save className="sm:mr-2 h-4 w-4" />
|
<>
|
||||||
<span className="hidden sm:inline">{t('save')}</span>
|
<Save className="sm:mr-2 h-4 w-4" />
|
||||||
</>
|
<span className="hidden sm:inline">{t('save')}</span>
|
||||||
)}
|
</>
|
||||||
</Button>
|
)}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs text-muted-foreground mt-1">
|
{!isMedia && (
|
||||||
{t('languageLabel')}: {getLanguageFromPath(filePath)}
|
<div className="text-xs text-muted-foreground mt-1">
|
||||||
</div>
|
{t('languageLabel')}: {getLanguageFromPath(filePath)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
<CardContent className="flex-1 p-0">
|
<CardContent className="flex-1 p-0">
|
||||||
@@ -133,6 +139,10 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
|
|||||||
<div className="flex items-center justify-center h-full">
|
<div className="flex items-center justify-center h-full">
|
||||||
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
|
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
|
||||||
</div>
|
</div>
|
||||||
|
) : isMedia ? (
|
||||||
|
<div className="flex flex-col items-center justify-center h-full p-8 text-center">
|
||||||
|
<ImageOff className="h-16 w-16 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<Textarea
|
<Textarea
|
||||||
value={editedContent}
|
value={editedContent}
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
import { encodeBase64 } from '@std/encoding/base64';
|
import { encodeBase64 } from '@std/encoding/base64';
|
||||||
import { useState, useEffect, useCallback, useRef, useMemo, memo } from 'react';
|
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||||
import { addConsoleMessage, getConsoleMessages, addConsoleMessageListener, removeConsoleMessageListener, type ConsoleMessage } from '@/lib/consoleMessages';
|
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages';
|
||||||
import { useConsoleError } from '@/hooks/useConsoleError';
|
import { useConsoleError } from '@/hooks/useConsoleError';
|
||||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, Rocket, Terminal, Trash2, ChevronRight } from 'lucide-react';
|
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, Rocket, X, Terminal } from 'lucide-react';
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||||
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
||||||
@@ -20,6 +20,11 @@ import {
|
|||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu';
|
} from '@/components/ui/dropdown-menu';
|
||||||
|
import {
|
||||||
|
Popover,
|
||||||
|
PopoverContent,
|
||||||
|
PopoverTrigger,
|
||||||
|
} from '@/components/ui/popover';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { FileTree } from './FileTree';
|
import { FileTree } from './FileTree';
|
||||||
import { FileEditor } from './FileEditor';
|
import { FileEditor } from './FileEditor';
|
||||||
@@ -27,6 +32,7 @@ import { DeployDialog } from '@/components/DeployDialog';
|
|||||||
import { Terminal as TerminalComponent } from '@/components/Terminal';
|
import { Terminal as TerminalComponent } from '@/components/Terminal';
|
||||||
import { useSearchParams } from 'react-router-dom';
|
import { useSearchParams } from 'react-router-dom';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
|
import { isMediaFile } from '@/lib/fileUtils';
|
||||||
|
|
||||||
interface PreviewPaneProps {
|
interface PreviewPaneProps {
|
||||||
projectId: string;
|
projectId: string;
|
||||||
@@ -83,7 +89,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
const [historyIndex, setHistoryIndex] = useState(0);
|
const [historyIndex, setHistoryIndex] = useState(0);
|
||||||
|
|
||||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||||
const [showConsoleView, setShowConsoleView] = useState(false);
|
|
||||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||||
const { fs } = useFS();
|
const { fs } = useFS();
|
||||||
const { projectsPath } = useFSPaths();
|
const { projectsPath } = useFSPaths();
|
||||||
@@ -126,6 +131,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
}, [isBuildLoading, isPreviewable, handleBuildProject, shouldBuild]);
|
}, [isBuildLoading, isPreviewable, handleBuildProject, shouldBuild]);
|
||||||
|
|
||||||
const loadFileContent = useCallback(async (filePath: string) => {
|
const loadFileContent = useCallback(async (filePath: string) => {
|
||||||
|
// Skip loading media files - they can't be edited as text
|
||||||
|
if (isMediaFile(filePath)) {
|
||||||
|
setFileContent('');
|
||||||
|
setIsLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
try {
|
try {
|
||||||
const content = await projectsManager.readFile(projectId, filePath);
|
const content = await projectsManager.readFile(projectId, filePath);
|
||||||
@@ -461,7 +473,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
setFileContent('');
|
setFileContent('');
|
||||||
setMobileCodeView('explorer');
|
setMobileCodeView('explorer');
|
||||||
setDesktopCodeView('files');
|
setDesktopCodeView('files');
|
||||||
setShowConsoleView(false);
|
|
||||||
|
|
||||||
// Reset navigation history and state
|
// Reset navigation history and state
|
||||||
setCurrentPath('/');
|
setCurrentPath('/');
|
||||||
@@ -518,282 +529,102 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Constants
|
const ConsoleDropdown = () => {
|
||||||
const CONSOLE_SORT_ORDER_KEY = 'consoleSortOrder';
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
const COPY_FEEDBACK_DURATION = 2000;
|
|
||||||
const MAX_CONSOLE_MESSAGES = 500; // Limit displayed messages for performance
|
|
||||||
|
|
||||||
// Helper function to get message level color
|
|
||||||
const getMessageLevelColor = (level: ConsoleMessage['level']): string => {
|
|
||||||
switch (level) {
|
|
||||||
case 'error': return 'text-destructive';
|
|
||||||
case 'warn': return 'text-warning';
|
|
||||||
case 'info': return 'text-primary';
|
|
||||||
default: return 'text-muted-foreground';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const ConsoleToggleButton = () => {
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
variant={showConsoleView ? "secondary" : "ghost"}
|
|
||||||
size="sm"
|
|
||||||
className="h-8 w-8 p-0 relative"
|
|
||||||
onClick={() => setShowConsoleView(!showConsoleView)}
|
|
||||||
title={showConsoleView ? "Show preview" : "Show console"}
|
|
||||||
>
|
|
||||||
<Bug className="h-4 w-4" />
|
|
||||||
{hasConsoleErrors && (
|
|
||||||
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Individual console message component - memoized for performance
|
|
||||||
const ConsoleMessage = memo(({ msg, index, copiedMessageIndex, onCopy }: {
|
|
||||||
msg: ConsoleMessage;
|
|
||||||
index: number;
|
|
||||||
copiedMessageIndex: number | null;
|
|
||||||
onCopy: (msg: ConsoleMessage, index: number) => void;
|
|
||||||
}) => {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
onCopy(msg, index);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div className={cn(
|
|
||||||
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
|
|
||||||
getMessageLevelColor(msg.level)
|
|
||||||
)}>
|
|
||||||
{msg.message}
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
onCopy(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>
|
|
||||||
);
|
|
||||||
});
|
|
||||||
ConsoleMessage.displayName = 'ConsoleMessage';
|
|
||||||
|
|
||||||
const ConsoleView = () => {
|
|
||||||
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
||||||
const [isInitialLoad, setIsInitialLoad] = useState(true);
|
|
||||||
const [rawMessages, setRawMessages] = useState<ConsoleMessage[]>([]);
|
|
||||||
const [totalMessageCount, setTotalMessageCount] = useState(0);
|
|
||||||
|
|
||||||
// Load sort order from localStorage, default to 'newest-first'
|
|
||||||
const [sortOrder, setSortOrder] = useState<'newest-first' | 'oldest-first'>(() => {
|
|
||||||
const saved = localStorage.getItem(CONSOLE_SORT_ORDER_KEY);
|
|
||||||
return (saved === 'oldest-first' || saved === 'newest-first') ? saved : 'newest-first';
|
|
||||||
});
|
|
||||||
|
|
||||||
// Save sort order to localStorage whenever it changes
|
const messages = isOpen ? getConsoleMessages() : [];
|
||||||
useEffect(() => {
|
|
||||||
localStorage.setItem(CONSOLE_SORT_ORDER_KEY, sortOrder);
|
|
||||||
}, [sortOrder]);
|
|
||||||
|
|
||||||
// Track rapid message bursts for intelligent batching
|
|
||||||
const lastMessageTimeRef = useRef<number>(0);
|
|
||||||
const pendingUpdateRef = useRef<number>();
|
|
||||||
const messageCountSinceUpdateRef = useRef<number>(0);
|
|
||||||
|
|
||||||
// Update messages from the global store - optimized for immediate updates
|
|
||||||
const updateMessages = useCallback(() => {
|
|
||||||
const allMessages = getConsoleMessages();
|
|
||||||
setTotalMessageCount(allMessages.length);
|
|
||||||
|
|
||||||
// Limit messages for performance (keep most recent)
|
|
||||||
const limitedMessages = allMessages.length > MAX_CONSOLE_MESSAGES
|
|
||||||
? allMessages.slice(-MAX_CONSOLE_MESSAGES)
|
|
||||||
: allMessages;
|
|
||||||
|
|
||||||
setRawMessages(limitedMessages);
|
|
||||||
setIsInitialLoad(false);
|
|
||||||
messageCountSinceUpdateRef.current = 0;
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Smart update handler: immediate for single messages, batched for rapid bursts
|
|
||||||
const handleMessageUpdate = useCallback(() => {
|
|
||||||
const now = Date.now();
|
|
||||||
const timeSinceLastMessage = now - lastMessageTimeRef.current;
|
|
||||||
lastMessageTimeRef.current = now;
|
|
||||||
messageCountSinceUpdateRef.current += 1;
|
|
||||||
|
|
||||||
// Detect rapid bursts: if we get more than 3 messages within 50ms, batch them
|
|
||||||
const isRapidBurst = messageCountSinceUpdateRef.current > 3 && timeSinceLastMessage < 50;
|
|
||||||
|
|
||||||
// Clear any pending update
|
|
||||||
if (pendingUpdateRef.current) {
|
|
||||||
cancelAnimationFrame(pendingUpdateRef.current);
|
|
||||||
pendingUpdateRef.current = undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isRapidBurst) {
|
|
||||||
// Batch rapid updates using requestAnimationFrame for smooth rendering
|
|
||||||
// This prevents UI blocking during loops that log many messages
|
|
||||||
pendingUpdateRef.current = requestAnimationFrame(() => {
|
|
||||||
updateMessages();
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// Immediate update for normal console.log calls (like browser console)
|
|
||||||
// Single messages appear instantly, just like native browser console
|
|
||||||
updateMessages();
|
|
||||||
}
|
|
||||||
}, [updateMessages]);
|
|
||||||
|
|
||||||
// Initial load and listener setup
|
|
||||||
useEffect(() => {
|
|
||||||
// Initial load - check if we have many messages
|
|
||||||
const allMessages = getConsoleMessages();
|
|
||||||
if (allMessages.length > 500) {
|
|
||||||
setIsInitialLoad(true);
|
|
||||||
// Use requestIdleCallback for non-blocking initial render, fallback to setTimeout
|
|
||||||
const scheduleUpdate = () => {
|
|
||||||
if ('requestIdleCallback' in window) {
|
|
||||||
requestIdleCallback(() => {
|
|
||||||
updateMessages();
|
|
||||||
}, { timeout: 100 });
|
|
||||||
} else {
|
|
||||||
setTimeout(() => {
|
|
||||||
updateMessages();
|
|
||||||
}, 0);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
scheduleUpdate();
|
|
||||||
} else {
|
|
||||||
updateMessages();
|
|
||||||
}
|
|
||||||
|
|
||||||
addConsoleMessageListener(handleMessageUpdate);
|
|
||||||
return () => {
|
|
||||||
removeConsoleMessageListener(handleMessageUpdate);
|
|
||||||
if (pendingUpdateRef.current) {
|
|
||||||
cancelAnimationFrame(pendingUpdateRef.current);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, [handleMessageUpdate, updateMessages]);
|
|
||||||
|
|
||||||
// Memoize sorted messages to avoid recalculation on every render
|
|
||||||
const messages = useMemo(() => {
|
|
||||||
if (sortOrder === 'newest-first') {
|
|
||||||
// For newest-first, reverse the array (messages are stored oldest-first)
|
|
||||||
return [...rawMessages].reverse();
|
|
||||||
}
|
|
||||||
return rawMessages;
|
|
||||||
}, [rawMessages, sortOrder]);
|
|
||||||
|
|
||||||
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
|
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
|
||||||
try {
|
try {
|
||||||
await navigator.clipboard.writeText(msg.message);
|
await navigator.clipboard.writeText(msg.message);
|
||||||
setCopiedMessageIndex(index);
|
setCopiedMessageIndex(index);
|
||||||
setTimeout(() => setCopiedMessageIndex(null), COPY_FEEDBACK_DURATION);
|
setTimeout(() => setCopiedMessageIndex(null), 2000);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to copy message to clipboard:', error);
|
console.error('Failed to copy message to clipboard:', error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleClearMessages = () => {
|
|
||||||
clearErrors();
|
|
||||||
setCopiedMessageIndex(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
const messageCount = messages.length;
|
const messageCount = messages.length;
|
||||||
const hasMoreMessages = rawMessages.length >= MAX_CONSOLE_MESSAGES;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="h-full w-full flex flex-col bg-background">
|
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||||
{/* Header */}
|
<PopoverTrigger asChild>
|
||||||
<div className="h-12 flex-shrink-0 flex items-center justify-between px-4 border-b">
|
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => setShowConsoleView(false)}
|
className="h-8 w-8 p-0 relative"
|
||||||
className="h-8 gap-2 text-muted-foreground hover:text-foreground"
|
|
||||||
>
|
>
|
||||||
<ArrowLeft className="h-4 w-4" />
|
<Bug className="h-4 w-4" />
|
||||||
Back
|
{hasConsoleErrors && (
|
||||||
</Button>
|
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
{messageCount > 0 && (
|
|
||||||
<>
|
|
||||||
{hasMoreMessages && (
|
|
||||||
<span className="text-xs text-muted-foreground">
|
|
||||||
Showing last {MAX_CONSOLE_MESSAGES.toLocaleString()} of {totalMessageCount.toLocaleString()}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => setSortOrder(sortOrder === 'newest-first' ? 'oldest-first' : 'newest-first')}
|
|
||||||
className="h-8 text-muted-foreground hover:text-foreground"
|
|
||||||
>
|
|
||||||
{sortOrder === 'newest-first' ? t('latestFirst') : t('oldestFirst')}
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={handleClearMessages}
|
|
||||||
className="h-8 w-8 p-0 text-destructive/80 hover:text-destructive"
|
|
||||||
>
|
|
||||||
<Trash2 className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</Button>
|
||||||
</div>
|
</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 */}
|
{/* Messages */}
|
||||||
<div className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none] bg-background text-foreground font-mono text-xs relative">
|
<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]">
|
||||||
{isInitialLoad ? (
|
|
||||||
<div className="absolute inset-0 flex items-center justify-center z-10 bg-background">
|
|
||||||
<div className="flex flex-col items-center gap-2">
|
|
||||||
<Loader2 className="h-5 w-5 animate-spin text-primary" />
|
|
||||||
<span className="text-sm text-muted-foreground">Loading console messages...</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="py-2 px-1 space-y-0">
|
<div className="py-2 px-1 space-y-0">
|
||||||
{/* Console prompt indicator - at top for newest-first, bottom for oldest-first */}
|
{messageCount === 0 ? (
|
||||||
{sortOrder === 'newest-first' && (
|
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||||
<div className="py-0.5 px-1 flex items-center">
|
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
|
||||||
<ChevronRight className="h-3 w-3 text-muted-foreground" />
|
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{messages.map((msg, index) => (
|
|
||||||
<ConsoleMessage
|
|
||||||
key={`${index}-${msg.message.slice(0, 20)}`}
|
|
||||||
msg={msg}
|
|
||||||
index={index}
|
|
||||||
copiedMessageIndex={copiedMessageIndex}
|
|
||||||
onCopy={copyMessageToClipboard}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
{sortOrder === 'oldest-first' && (
|
|
||||||
<div className="py-0.5 px-1 flex items-center">
|
|
||||||
<ChevronRight className="h-3 w-3 text-muted-foreground" />
|
|
||||||
</div>
|
</div>
|
||||||
|
) : (
|
||||||
|
messages.map((msg, index) => (
|
||||||
|
<div
|
||||||
|
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={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>
|
</div>
|
||||||
)}
|
</div>
|
||||||
</div>
|
|
||||||
</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>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -866,7 +697,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
<Code className="h-4 w-4" />
|
<Code className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<ConsoleToggleButton />
|
<ConsoleDropdown />
|
||||||
<Menu />
|
<Menu />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -874,25 +705,16 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Content area */}
|
{/* Content area */}
|
||||||
<div className="flex-1 min-h-0 relative">
|
<div className="flex-1">
|
||||||
{/* Console View */}
|
{hasBuiltProject ? (
|
||||||
<div className={cn("absolute inset-0", showConsoleView ? "block" : "hidden")}>
|
|
||||||
<ConsoleView />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Preview iframe */}
|
|
||||||
{hasBuiltProject && (
|
|
||||||
<iframe
|
<iframe
|
||||||
ref={iframeRef}
|
ref={iframeRef}
|
||||||
src={`https://${projectId}.${previewDomain}/`}
|
src={`https://${projectId}.${previewDomain}/`}
|
||||||
className={cn("w-full h-full border-0", showConsoleView ? "hidden" : "block")}
|
className="w-full h-full border-0"
|
||||||
title="Project Preview"
|
title="Project Preview"
|
||||||
sandbox="allow-scripts allow-same-origin"
|
sandbox="allow-scripts allow-same-origin"
|
||||||
/>
|
/>
|
||||||
)}
|
) : (
|
||||||
|
|
||||||
{/* Build prompt */}
|
|
||||||
{!hasBuiltProject && !showConsoleView && (
|
|
||||||
<div className="h-full flex items-center justify-center bg-muted">
|
<div className="h-full flex items-center justify-center bg-muted">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
|
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
|
||||||
@@ -979,7 +801,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
</h3>
|
</h3>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1 min-h-0">
|
<div className="flex-1 min-h-0">
|
||||||
<TerminalComponent projectId={projectId} />
|
<TerminalComponent cwd={`${projectsPath}/${projectId}`} />
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
@@ -1073,7 +895,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
<div className="flex-1 flex min-h-0">
|
<div className="flex-1 flex min-h-0">
|
||||||
{desktopCodeView === 'terminal' ? (
|
{desktopCodeView === 'terminal' ? (
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
<TerminalComponent projectId={projectId} />
|
<TerminalComponent cwd={`${projectsPath}/${projectId}`} />
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -5,14 +5,13 @@ import { Copy } from 'lucide-react';
|
|||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
|
||||||
import { useGit } from '@/hooks/useGit';
|
import { useGit } from '@/hooks/useGit';
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml';
|
import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml';
|
||||||
|
|
||||||
interface TerminalProps {
|
interface TerminalProps {
|
||||||
projectId: string;
|
cwd: string;
|
||||||
className?: string;
|
className?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,7 +22,7 @@ interface TerminalLine {
|
|||||||
timestamp: Date;
|
timestamp: Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Terminal({ projectId, className }: TerminalProps) {
|
export function Terminal({ cwd, className }: TerminalProps) {
|
||||||
const [lines, setLines] = useState<TerminalLine[]>([]);
|
const [lines, setLines] = useState<TerminalLine[]>([]);
|
||||||
const [currentInput, setCurrentInput] = useState('');
|
const [currentInput, setCurrentInput] = useState('');
|
||||||
const [isExecuting, setIsExecuting] = useState(false);
|
const [isExecuting, setIsExecuting] = useState(false);
|
||||||
@@ -35,14 +34,13 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
|||||||
const shellToolRef = useRef<ShellTool | null>(null);
|
const shellToolRef = useRef<ShellTool | null>(null);
|
||||||
|
|
||||||
const { fs } = useFS();
|
const { fs } = useFS();
|
||||||
const { projectsPath } = useFSPaths();
|
|
||||||
const { git } = useGit();
|
const { git } = useGit();
|
||||||
const { user } = useCurrentUser();
|
const { user } = useCurrentUser();
|
||||||
const { config } = useAppContext();
|
const { config } = useAppContext();
|
||||||
|
|
||||||
// Initialize ShellTool
|
// Initialize ShellTool
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath, config.corsProxy, user?.signer);
|
shellToolRef.current = new ShellTool(fs, cwd, git, config.corsProxy, user?.signer);
|
||||||
|
|
||||||
// Add welcome message
|
// Add welcome message
|
||||||
setLines([{
|
setLines([{
|
||||||
@@ -51,7 +49,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
|||||||
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
|
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
|
||||||
timestamp: new Date()
|
timestamp: new Date()
|
||||||
}]);
|
}]);
|
||||||
}, [projectId, fs, git, projectsPath, config.corsProxy, user?.signer]);
|
}, [cwd, fs, git, config.corsProxy, user?.signer]);
|
||||||
|
|
||||||
// Auto-scroll to bottom when new lines are added or execution state changes
|
// Auto-scroll to bottom when new lines are added or execution state changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -108,10 +106,8 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
|||||||
|
|
||||||
// Check if running in Electron - use real shell
|
// Check if running in Electron - use real shell
|
||||||
if (window.electron?.shell) {
|
if (window.electron?.shell) {
|
||||||
// Use the full path (with ~ if present) - Electron will expand it
|
// Use the provided cwd (Electron will expand ~ if present)
|
||||||
const fullCwd = `${projectsPath}/${projectId}`;
|
const result = await window.electron.shell.exec(command, cwd);
|
||||||
|
|
||||||
const result = await window.electron.shell.exec(command, fullCwd);
|
|
||||||
|
|
||||||
// Format output
|
// Format output
|
||||||
let output = '';
|
let output = '';
|
||||||
@@ -159,7 +155,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
|||||||
} finally {
|
} finally {
|
||||||
setIsExecuting(false);
|
setIsExecuting(false);
|
||||||
}
|
}
|
||||||
}, [addLine, commandHistory, projectId, projectsPath]);
|
}, [addLine, commandHistory, cwd]);
|
||||||
|
|
||||||
const handleSubmit = useCallback((e: React.FormEvent) => {
|
const handleSubmit = useCallback((e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { Terminal } from './Terminal';
|
|||||||
export function TerminalTest() {
|
export function TerminalTest() {
|
||||||
return (
|
return (
|
||||||
<div className="h-[500px] w-full">
|
<div className="h-[500px] w-full">
|
||||||
<Terminal projectId="test" />
|
<Terminal cwd="/projects/test" />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -16,8 +16,11 @@ describe('UserMessage', () => {
|
|||||||
|
|
||||||
render(<UserMessage content={content} />);
|
render(<UserMessage content={content} />);
|
||||||
|
|
||||||
// When using string content, it should still work but won't separate file attachments
|
// When using string content, it should parse and separate file attachments
|
||||||
expect(screen.getByText(content)).toBeInTheDocument();
|
expect(screen.getByText('Here is my file:')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('test.txt')).toBeInTheDocument();
|
||||||
|
// Full path should not be displayed
|
||||||
|
expect(screen.queryByText('/tmp/test.txt')).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('renders file attachment badges for single file with text parts', () => {
|
it('renders file attachment badges for single file with text parts', () => {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { FileText, File } from 'lucide-react';
|
import { Paperclip } from 'lucide-react';
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import type OpenAI from 'openai';
|
import type OpenAI from 'openai';
|
||||||
|
|
||||||
@@ -18,21 +18,60 @@ export function UserMessage({ content }: UserMessageProps) {
|
|||||||
: content.filter(part => part.type === 'text') as Array<{ type: 'text'; text: string }>;
|
: content.filter(part => part.type === 'text') as Array<{ type: 'text'; text: string }>;
|
||||||
|
|
||||||
// Regular expression to match "Added file: /tmp/<filename>" patterns
|
// Regular expression to match "Added file: /tmp/<filename>" patterns
|
||||||
const filePattern = /^Added file: (\/tmp\/[^\s\n]+)$/;
|
// Matches the pattern anywhere in the text
|
||||||
|
const filePattern = /Added file:\s*(\/tmp\/[^\s\n]+)/g;
|
||||||
|
|
||||||
// Process each content part and categorize as text or file
|
// Process each content part and categorize as text or file
|
||||||
const processedParts: Array<{ type: 'text' | 'file'; content: string; filepath?: string }> = [];
|
const processedParts: Array<{ type: 'text' | 'file'; content: string; filepath?: string }> = [];
|
||||||
|
|
||||||
contentParts.forEach(part => {
|
contentParts.forEach(part => {
|
||||||
const text = part.text.trim();
|
const text = part.text.trim();
|
||||||
const match = text.match(filePattern);
|
|
||||||
|
// Find all file patterns in this text part
|
||||||
|
const fileMatches: Array<{ filepath: string; index: number; length: number }> = [];
|
||||||
|
let match;
|
||||||
|
filePattern.lastIndex = 0; // Reset regex
|
||||||
|
|
||||||
|
while ((match = filePattern.exec(text)) !== null) {
|
||||||
|
fileMatches.push({
|
||||||
|
filepath: match[1], // "/tmp/filename.txt"
|
||||||
|
index: match.index,
|
||||||
|
length: match[0].length
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (match) {
|
if (fileMatches.length > 0) {
|
||||||
// This is a file attachment
|
// Split text around file patterns and process each segment
|
||||||
const filepath = match[1]; // "/tmp/filename.txt"
|
let lastIndex = 0;
|
||||||
processedParts.push({ type: 'file', content: text, filepath });
|
|
||||||
|
fileMatches.forEach((fileMatch) => {
|
||||||
|
// Add text before the file pattern
|
||||||
|
if (fileMatch.index > lastIndex) {
|
||||||
|
const textBefore = text.substring(lastIndex, fileMatch.index).trim();
|
||||||
|
if (textBefore) {
|
||||||
|
processedParts.push({ type: 'text', content: textBefore });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add the file attachment badge (without showing "Added file:" text)
|
||||||
|
processedParts.push({
|
||||||
|
type: 'file',
|
||||||
|
content: '', // Empty - badge will show filename only
|
||||||
|
filepath: fileMatch.filepath
|
||||||
|
});
|
||||||
|
|
||||||
|
lastIndex = fileMatch.index + fileMatch.length;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add remaining text after the last file pattern
|
||||||
|
if (lastIndex < text.length) {
|
||||||
|
const textAfter = text.substring(lastIndex).trim();
|
||||||
|
if (textAfter) {
|
||||||
|
processedParts.push({ type: 'text', content: textAfter });
|
||||||
|
}
|
||||||
|
}
|
||||||
} else if (text) {
|
} else if (text) {
|
||||||
// This is regular text content
|
// No file patterns found, treat as regular text
|
||||||
processedParts.push({ type: 'text', content: text });
|
processedParts.push({ type: 'text', content: text });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -42,19 +81,6 @@ export function UserMessage({ content }: UserMessageProps) {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const getFileIcon = (filename: string) => {
|
|
||||||
const extension = filename.split('.').pop()?.toLowerCase();
|
|
||||||
|
|
||||||
// Return FileText icon for text-like files, File icon for others
|
|
||||||
const textExtensions = ['txt', 'md', 'json', 'js', 'ts', 'jsx', 'tsx', 'css', 'html', 'xml', 'yml', 'yaml'];
|
|
||||||
|
|
||||||
if (extension && textExtensions.includes(extension)) {
|
|
||||||
return <FileText className="h-3 w-3" />;
|
|
||||||
}
|
|
||||||
|
|
||||||
return <File className="h-3 w-3" />;
|
|
||||||
};
|
|
||||||
|
|
||||||
const getFileName = (filepath: string) => {
|
const getFileName = (filepath: string) => {
|
||||||
return filepath.split('/').pop() || filepath;
|
return filepath.split('/').pop() || filepath;
|
||||||
};
|
};
|
||||||
@@ -63,18 +89,25 @@ export function UserMessage({ content }: UserMessageProps) {
|
|||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
{processedParts.map((part, index) => {
|
{processedParts.map((part, index) => {
|
||||||
if (part.type === 'text') {
|
if (part.type === 'text') {
|
||||||
|
// Only render text if it has content
|
||||||
|
if (!part.content.trim()) return null;
|
||||||
return (
|
return (
|
||||||
<div key={index} className="whitespace-pre-wrap">
|
<div key={index} className="whitespace-pre-wrap">
|
||||||
{part.content}
|
{part.content}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
|
// Render file attachment badge (no "Added file:" text)
|
||||||
const filename = getFileName(part.filepath!);
|
const filename = getFileName(part.filepath!);
|
||||||
return (
|
return (
|
||||||
<div key={index} className="flex items-center gap-2">
|
<div key={index} className="flex items-center gap-2 max-w-full min-w-0">
|
||||||
<Badge variant="secondary" className="flex items-center gap-1.5 px-2 py-1">
|
<Badge variant="secondary" className="inline-flex items-center gap-1.5 px-2 py-1 max-w-full">
|
||||||
{getFileIcon(filename)}
|
<span className="flex-shrink-0">
|
||||||
<span className="text-xs font-medium">{filename}</span>
|
<Paperclip className="h-3 w-3" />
|
||||||
|
</span>
|
||||||
|
<span className="text-xs font-medium truncate min-w-0" title={filename}>
|
||||||
|
{filename}
|
||||||
|
</span>
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -410,7 +410,7 @@ export function AnnounceRepositoryDialog({
|
|||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<ScrollArea className="max-h-[60vh]">
|
<ScrollArea className="max-h-[60vh]">
|
||||||
<div className="space-y-6 pr-4">
|
<div className="space-y-6 p-1 pr-4">
|
||||||
{/* Error alert */}
|
{/* Error alert */}
|
||||||
{error && (
|
{error && (
|
||||||
<Alert variant="destructive">
|
<Alert variant="destructive">
|
||||||
|
|||||||
@@ -8,9 +8,20 @@ export interface AIProvider {
|
|||||||
proxy?: boolean;
|
proxy?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface MCPServer {
|
||||||
|
type: 'streamable-http';
|
||||||
|
url: string;
|
||||||
|
headers?: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MCPServers {
|
||||||
|
[key: string]: MCPServer;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AISettings {
|
export interface AISettings {
|
||||||
providers: AIProvider[];
|
providers: AIProvider[];
|
||||||
recentlyUsedModels: string[];
|
recentlyUsedModels: string[];
|
||||||
|
mcpServers?: MCPServers;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AISettingsContextType {
|
export interface AISettingsContextType {
|
||||||
@@ -20,6 +31,8 @@ export interface AISettingsContextType {
|
|||||||
removeProvider: (id: string) => void;
|
removeProvider: (id: string) => void;
|
||||||
setProviders: (providers: AIProvider[]) => void;
|
setProviders: (providers: AIProvider[]) => void;
|
||||||
addRecentlyUsedModel: (modelId: string) => void;
|
addRecentlyUsedModel: (modelId: string) => void;
|
||||||
|
setMCPServer: (name: string, server: MCPServer) => void;
|
||||||
|
removeMCPServer: (name: string) => void;
|
||||||
isConfigured: boolean;
|
isConfigured: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ export interface AppConfig {
|
|||||||
fsPathTmp: string;
|
fsPathTmp: string;
|
||||||
/** VFS path for plugins directory */
|
/** VFS path for plugins directory */
|
||||||
fsPathPlugins: string;
|
fsPathPlugins: string;
|
||||||
|
/** VFS path for templates directory */
|
||||||
|
fsPathTemplates: string;
|
||||||
/** Sentry DSN for error reporting (empty string = disabled) */
|
/** Sentry DSN for error reporting (empty string = disabled) */
|
||||||
sentryDsn: string;
|
sentryDsn: string;
|
||||||
/** Whether the user has enabled Sentry error reporting */
|
/** Whether the user has enabled Sentry error reporting */
|
||||||
|
|||||||
@@ -114,7 +114,10 @@ export function useAIChat({
|
|||||||
}, [projectId]);
|
}, [projectId]);
|
||||||
|
|
||||||
// Actions
|
// Actions
|
||||||
const sendMessage = useCallback(async (content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string) => {
|
const sendMessage = useCallback(async (
|
||||||
|
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
|
||||||
|
providerModel: string
|
||||||
|
) => {
|
||||||
try {
|
try {
|
||||||
await initSession();
|
await initSession();
|
||||||
await sessionManager.sendMessage(projectId, content, providerModel);
|
await sessionManager.sendMessage(projectId, content, providerModel);
|
||||||
|
|||||||
@@ -56,6 +56,7 @@ describe('useAIProjectId', () => {
|
|||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
fsPathTmp: '/tmp',
|
fsPathTmp: '/tmp',
|
||||||
fsPathPlugins: '/plugins',
|
fsPathPlugins: '/plugins',
|
||||||
|
fsPathTemplates: '/templates',
|
||||||
sentryDsn: '',
|
sentryDsn: '',
|
||||||
sentryEnabled: false,
|
sentryEnabled: false,
|
||||||
};
|
};
|
||||||
@@ -93,13 +94,15 @@ describe('useAIProjectId', () => {
|
|||||||
|
|
||||||
it('should return not configured when AI settings are not configured', () => {
|
it('should return not configured when AI settings are not configured', () => {
|
||||||
mockUseAISettings.mockReturnValue({
|
mockUseAISettings.mockReturnValue({
|
||||||
settings: { providers: [], recentlyUsedModels: [] },
|
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
|
||||||
isConfigured: false,
|
isConfigured: false,
|
||||||
updateSettings: vi.fn(),
|
updateSettings: vi.fn(),
|
||||||
setProvider: vi.fn(),
|
setProvider: vi.fn(),
|
||||||
removeProvider: vi.fn(),
|
removeProvider: vi.fn(),
|
||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
addRecentlyUsedModel: vi.fn(),
|
addRecentlyUsedModel: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const { result } = renderHook(() => useAIProjectId());
|
const { result } = renderHook(() => useAIProjectId());
|
||||||
@@ -110,7 +113,7 @@ describe('useAIProjectId', () => {
|
|||||||
|
|
||||||
it('should throw error when trying to generate ID without configuration', async () => {
|
it('should throw error when trying to generate ID without configuration', async () => {
|
||||||
mockUseAISettings.mockReturnValue({
|
mockUseAISettings.mockReturnValue({
|
||||||
settings: { providers: [], recentlyUsedModels: [] },
|
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
|
||||||
isConfigured: false,
|
isConfigured: false,
|
||||||
updateSettings: vi.fn(),
|
updateSettings: vi.fn(),
|
||||||
setProvider: vi.fn(),
|
setProvider: vi.fn(),
|
||||||
@@ -118,6 +121,8 @@ describe('useAIProjectId', () => {
|
|||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
|
||||||
addRecentlyUsedModel: vi.fn(),
|
addRecentlyUsedModel: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const { result } = renderHook(() => useAIProjectId());
|
const { result } = renderHook(() => useAIProjectId());
|
||||||
@@ -142,6 +147,8 @@ describe('useAIProjectId', () => {
|
|||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
|
||||||
addRecentlyUsedModel: vi.fn(),
|
addRecentlyUsedModel: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const { result } = renderHook(() => useAIProjectId());
|
const { result } = renderHook(() => useAIProjectId());
|
||||||
@@ -166,6 +173,8 @@ describe('useAIProjectId', () => {
|
|||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
|
||||||
addRecentlyUsedModel: vi.fn(),
|
addRecentlyUsedModel: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const { result } = renderHook(() => useAIProjectId());
|
const { result } = renderHook(() => useAIProjectId());
|
||||||
@@ -189,6 +198,8 @@ describe('useAIProjectId', () => {
|
|||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
|
||||||
addRecentlyUsedModel: vi.fn(),
|
addRecentlyUsedModel: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const { result } = renderHook(() => useAIProjectId());
|
const { result } = renderHook(() => useAIProjectId());
|
||||||
@@ -221,6 +232,8 @@ describe('useAIProjectId', () => {
|
|||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
|
||||||
addRecentlyUsedModel: vi.fn(),
|
addRecentlyUsedModel: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Mock AI response - returns a project name that already exists
|
// Mock AI response - returns a project name that already exists
|
||||||
@@ -274,6 +287,8 @@ describe('useAIProjectId', () => {
|
|||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
|
||||||
addRecentlyUsedModel: vi.fn(),
|
addRecentlyUsedModel: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Mock AI to return a project name that already exists
|
// Mock AI to return a project name that already exists
|
||||||
@@ -329,6 +344,8 @@ describe('useAIProjectId', () => {
|
|||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
|
||||||
addRecentlyUsedModel: vi.fn(),
|
addRecentlyUsedModel: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Mock AI to return a very long project name (over 50 characters)
|
// Mock AI to return a very long project name (over 50 characters)
|
||||||
@@ -379,6 +396,8 @@ describe('useAIProjectId', () => {
|
|||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
|
||||||
addRecentlyUsedModel: vi.fn(),
|
addRecentlyUsedModel: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Mock AI to return an invalid project name (doesn't match regex)
|
// Mock AI to return an invalid project name (doesn't match regex)
|
||||||
@@ -429,6 +448,8 @@ describe('useAIProjectId', () => {
|
|||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
|
||||||
addRecentlyUsedModel: vi.fn(),
|
addRecentlyUsedModel: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Mock AI to return a project name that already exists
|
// Mock AI to return a project name that already exists
|
||||||
@@ -486,6 +507,8 @@ describe('useAIProjectId', () => {
|
|||||||
setProviders: vi.fn(),
|
setProviders: vi.fn(),
|
||||||
|
|
||||||
addRecentlyUsedModel: vi.fn(),
|
addRecentlyUsedModel: vi.fn(),
|
||||||
|
setMCPServer: vi.fn(),
|
||||||
|
removeMCPServer: vi.fn(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const { result } = renderHook(() => useAIProjectId());
|
const { result } = renderHook(() => useAIProjectId());
|
||||||
|
|||||||
@@ -17,5 +17,7 @@ export function useFSPaths() {
|
|||||||
tmpPath: config.fsPathTmp,
|
tmpPath: config.fsPathTmp,
|
||||||
/** Plugins directory path (default: /plugins) */
|
/** Plugins directory path (default: /plugins) */
|
||||||
pluginsPath: config.fsPathPlugins,
|
pluginsPath: config.fsPathPlugins,
|
||||||
|
/** Templates directory path (default: /templates) */
|
||||||
|
templatesPath: config.fsPathTemplates,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -49,6 +49,7 @@ function createWrapper(corsProxy: string) {
|
|||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
fsPathTmp: '/tmp',
|
fsPathTmp: '/tmp',
|
||||||
fsPathPlugins: '/plugins',
|
fsPathPlugins: '/plugins',
|
||||||
|
fsPathTemplates: '/templates',
|
||||||
sentryDsn: '',
|
sentryDsn: '',
|
||||||
sentryEnabled: false,
|
sentryEnabled: false,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { MCPClient } from '@/lib/MCPClient';
|
||||||
|
import type { MCPServer } from '@/contexts/AISettingsContext';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hook to check the connection status of an MCP server.
|
||||||
|
* Returns 'connected', 'offline', or 'checking'.
|
||||||
|
*/
|
||||||
|
export function useMCPServerStatus(server: MCPServer): 'connected' | 'offline' | 'checking' {
|
||||||
|
const [status, setStatus] = useState<'connected' | 'offline' | 'checking'>('checking');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
|
||||||
|
async function checkConnection() {
|
||||||
|
setStatus('checking');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const client = new MCPClient(server);
|
||||||
|
await client.connect();
|
||||||
|
|
||||||
|
// Try to list tools to verify the connection is working
|
||||||
|
await client.listTools();
|
||||||
|
|
||||||
|
await client.close();
|
||||||
|
|
||||||
|
if (!cancelled) {
|
||||||
|
setStatus('connected');
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
if (!cancelled) {
|
||||||
|
setStatus('offline');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
checkConnection();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [server]); // Re-check when server config changes
|
||||||
|
|
||||||
|
return status;
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useAISettings } from './useAISettings';
|
||||||
|
import { discoverMCPTools } from '@/lib/MCPClient';
|
||||||
|
import type OpenAI from 'openai';
|
||||||
|
import type { MCPClient } from '@/lib/MCPClient';
|
||||||
|
|
||||||
|
interface UseMCPToolsResult {
|
||||||
|
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||||
|
clients: Record<string, MCPClient>;
|
||||||
|
isLoading: boolean;
|
||||||
|
error: Error | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hook to discover and manage MCP tools from configured servers.
|
||||||
|
*/
|
||||||
|
export function useMCPTools(): UseMCPToolsResult {
|
||||||
|
const { settings } = useAISettings();
|
||||||
|
const mcpServers = settings.mcpServers || {};
|
||||||
|
|
||||||
|
const { data, isLoading, error } = useQuery({
|
||||||
|
queryKey: ['mcp-tools', mcpServers],
|
||||||
|
queryFn: async () => {
|
||||||
|
if (Object.keys(mcpServers).length === 0) {
|
||||||
|
return { tools: {}, clients: {} };
|
||||||
|
}
|
||||||
|
return await discoverMCPTools(mcpServers);
|
||||||
|
},
|
||||||
|
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
|
||||||
|
retry: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
tools: data?.tools || {},
|
||||||
|
clients: data?.clients || {},
|
||||||
|
isLoading,
|
||||||
|
error: error as Error | null,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -11,11 +11,11 @@ import { useGit } from './useGit';
|
|||||||
export function useProjectsManager() {
|
export function useProjectsManager() {
|
||||||
const { fs } = useFS();
|
const { fs } = useFS();
|
||||||
const { git } = useGit();
|
const { git } = useGit();
|
||||||
const { projectsPath } = useFSPaths();
|
const { projectsPath, templatesPath } = useFSPaths();
|
||||||
|
|
||||||
const projectsManager = useMemo(() => {
|
const projectsManager = useMemo(() => {
|
||||||
return new ProjectsManager({ fs, git, projectsPath });
|
return new ProjectsManager({ fs, git, projectsPath, templatesPath });
|
||||||
}, [fs, git, projectsPath]);
|
}, [fs, git, projectsPath, templatesPath]);
|
||||||
|
|
||||||
return projectsManager;
|
return projectsManager;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
||||||
|
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
||||||
|
import type { MCPServer } from '@/contexts/AISettingsContext';
|
||||||
|
import type OpenAI from 'openai';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MCP (Model Context Protocol) Client for discovering and executing tools from MCP servers.
|
||||||
|
* Uses the official @modelcontextprotocol/sdk library.
|
||||||
|
*/
|
||||||
|
export class MCPClient {
|
||||||
|
private client: Client;
|
||||||
|
private transport: StreamableHTTPClientTransport;
|
||||||
|
private connected = false;
|
||||||
|
|
||||||
|
constructor(server: MCPServer) {
|
||||||
|
// Create the client
|
||||||
|
this.client = new Client({
|
||||||
|
name: 'shakespeare',
|
||||||
|
version: '1.0.0',
|
||||||
|
}, {
|
||||||
|
capabilities: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create HTTP transport with optional custom headers
|
||||||
|
this.transport = new StreamableHTTPClientTransport(new URL(server.url), {
|
||||||
|
requestInit: server.headers ? {
|
||||||
|
headers: server.headers,
|
||||||
|
} : undefined,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Connect to the MCP server.
|
||||||
|
*/
|
||||||
|
async connect(): Promise<void> {
|
||||||
|
if (this.connected) return;
|
||||||
|
|
||||||
|
await this.client.connect(this.transport);
|
||||||
|
this.connected = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List all available tools from the MCP server.
|
||||||
|
*/
|
||||||
|
async listTools(): Promise<Array<{
|
||||||
|
name: string;
|
||||||
|
description?: string;
|
||||||
|
inputSchema: {
|
||||||
|
type: 'object';
|
||||||
|
properties?: Record<string, object>;
|
||||||
|
required?: string[];
|
||||||
|
};
|
||||||
|
}>> {
|
||||||
|
await this.connect();
|
||||||
|
|
||||||
|
const result = await this.client.listTools();
|
||||||
|
return result.tools;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Call a tool on the MCP server.
|
||||||
|
*/
|
||||||
|
async callTool(name: string, args: Record<string, unknown>): Promise<string> {
|
||||||
|
await this.connect();
|
||||||
|
|
||||||
|
const result = await this.client.callTool({
|
||||||
|
name,
|
||||||
|
arguments: args,
|
||||||
|
});
|
||||||
|
|
||||||
|
const content = Array.isArray(result.content) ? result.content : [];
|
||||||
|
|
||||||
|
if (result.isError) {
|
||||||
|
const errorText = content
|
||||||
|
.filter((c): c is { type: 'text'; text: string } => c.type === 'text')
|
||||||
|
.map(c => c.text)
|
||||||
|
.join('\n');
|
||||||
|
throw new Error(`MCP tool error: ${errorText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Concatenate all text content from the response
|
||||||
|
return content
|
||||||
|
.filter((c): c is { type: 'text'; text: string } => c.type === 'text')
|
||||||
|
.map(c => c.text)
|
||||||
|
.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Close the connection to the MCP server.
|
||||||
|
*/
|
||||||
|
async close(): Promise<void> {
|
||||||
|
if (!this.connected) return;
|
||||||
|
|
||||||
|
await this.client.close();
|
||||||
|
this.connected = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert MCP tools to OpenAI tool format.
|
||||||
|
*/
|
||||||
|
static toOpenAITools(mcpTools: Array<{
|
||||||
|
name: string;
|
||||||
|
description?: string;
|
||||||
|
inputSchema: {
|
||||||
|
type: 'object';
|
||||||
|
properties?: Record<string, object>;
|
||||||
|
required?: string[];
|
||||||
|
};
|
||||||
|
}>): Record<string, OpenAI.Chat.Completions.ChatCompletionTool> {
|
||||||
|
const tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool> = {};
|
||||||
|
|
||||||
|
for (const tool of mcpTools) {
|
||||||
|
tools[tool.name] = {
|
||||||
|
type: 'function',
|
||||||
|
function: {
|
||||||
|
name: tool.name,
|
||||||
|
description: tool.description || '',
|
||||||
|
parameters: tool.inputSchema as Record<string, unknown>,
|
||||||
|
},
|
||||||
|
} as OpenAI.Chat.Completions.ChatCompletionTool;
|
||||||
|
}
|
||||||
|
|
||||||
|
return tools;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Discover tools from all configured MCP servers.
|
||||||
|
*/
|
||||||
|
export async function discoverMCPTools(
|
||||||
|
mcpServers: Record<string, MCPServer>
|
||||||
|
): Promise<{
|
||||||
|
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||||
|
clients: Record<string, MCPClient>;
|
||||||
|
}> {
|
||||||
|
const allTools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool> = {};
|
||||||
|
const clients: Record<string, MCPClient> = {};
|
||||||
|
|
||||||
|
for (const [serverName, serverConfig] of Object.entries(mcpServers)) {
|
||||||
|
try {
|
||||||
|
const client = new MCPClient(serverConfig);
|
||||||
|
const mcpTools = await client.listTools();
|
||||||
|
const openAITools = MCPClient.toOpenAITools(mcpTools);
|
||||||
|
|
||||||
|
// Store tools with server prefix to avoid name collisions
|
||||||
|
for (const [toolName, tool] of Object.entries(openAITools)) {
|
||||||
|
const prefixedName = `${serverName}__${toolName}`;
|
||||||
|
const functionTool = tool as OpenAI.Chat.Completions.ChatCompletionTool & {
|
||||||
|
function: { name: string; description: string; parameters: Record<string, unknown> }
|
||||||
|
};
|
||||||
|
allTools[prefixedName] = {
|
||||||
|
type: 'function',
|
||||||
|
function: {
|
||||||
|
...functionTool.function,
|
||||||
|
name: prefixedName,
|
||||||
|
description: `[${serverName}] ${functionTool.function.description}`,
|
||||||
|
},
|
||||||
|
} as OpenAI.Chat.Completions.ChatCompletionTool;
|
||||||
|
clients[prefixedName] = client;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Failed to discover tools from MCP server "${serverName}":`, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { tools: allTools, clients };
|
||||||
|
}
|
||||||
@@ -219,7 +219,7 @@ describe('ProjectsManager', () => {
|
|||||||
fs = new MockFS() as unknown as JSRuntimeFS;
|
fs = new MockFS() as unknown as JSRuntimeFS;
|
||||||
nostr = createMockNostr();
|
nostr = createMockNostr();
|
||||||
git = new Git({ fs, nostr });
|
git = new Git({ fs, nostr });
|
||||||
projectsManager = new ProjectsManager({ fs, git });
|
projectsManager = new ProjectsManager({ fs, git, projectsPath: '/projects', templatesPath: '/templates' });
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('getProjects', () => {
|
describe('getProjects', () => {
|
||||||
|
|||||||
+225
-40
@@ -20,18 +20,22 @@ export interface ProjectsManagerOptions {
|
|||||||
fs: JSRuntimeFS;
|
fs: JSRuntimeFS;
|
||||||
git: Git;
|
git: Git;
|
||||||
/** Projects directory path (default: /projects) */
|
/** Projects directory path (default: /projects) */
|
||||||
projectsPath?: string;
|
projectsPath: string;
|
||||||
|
/** Templates directory path (default: /templates) */
|
||||||
|
templatesPath: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class ProjectsManager {
|
export class ProjectsManager {
|
||||||
fs: JSRuntimeFS;
|
fs: JSRuntimeFS;
|
||||||
git: Git;
|
git: Git;
|
||||||
dir: string;
|
dir: string;
|
||||||
|
templatesDir: string;
|
||||||
|
|
||||||
constructor(options: ProjectsManagerOptions) {
|
constructor(options: ProjectsManagerOptions) {
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.dir = options.projectsPath || '/projects';
|
this.dir = options.projectsPath;
|
||||||
|
this.templatesDir = options.templatesPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
async init() {
|
async init() {
|
||||||
@@ -40,58 +44,239 @@ export class ProjectsManager {
|
|||||||
} catch {
|
} catch {
|
||||||
// Directory might already exist
|
// Directory might already exist
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
await this.fs.mkdir(this.templatesDir);
|
||||||
|
} catch {
|
||||||
|
// Directory might already exist
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async createProject(name: string, templateUrl: string, customId?: string): Promise<Project> {
|
/**
|
||||||
const project = await this.cloneProject(name, templateUrl, customId, { depth: 1 });
|
* Ensure a template is cached locally and up-to-date.
|
||||||
|
* Returns the path to the cached template.
|
||||||
|
*
|
||||||
|
* @param templateUrl - Git repository URL of the template
|
||||||
|
* @param onUpdateError - Optional callback when template update fails (non-critical)
|
||||||
|
* @returns Path to the cached template directory
|
||||||
|
*/
|
||||||
|
async updateTemplate(templateUrl: string, onUpdateError?: (error: Error) => void): Promise<string> {
|
||||||
|
// Generate a safe directory name from the template URL
|
||||||
|
const templateName = this.getTemplateNameFromUrl(templateUrl);
|
||||||
|
const templatePath = `${this.templatesDir}/${templateName}`;
|
||||||
|
|
||||||
// Delete README.md if it exists
|
|
||||||
try {
|
try {
|
||||||
await this.fs.unlink(`${project.path}/README.md`);
|
// Check if template already exists
|
||||||
|
await this.fs.stat(templatePath);
|
||||||
|
|
||||||
|
// Template exists, try to update it with force pull
|
||||||
|
try {
|
||||||
|
await this.forcePullTemplate(templatePath);
|
||||||
|
} catch (updateError) {
|
||||||
|
// Update failed, but we can continue with the existing template
|
||||||
|
console.warn(`Failed to update template at ${templatePath}:`, updateError);
|
||||||
|
if (onUpdateError) {
|
||||||
|
onUpdateError(updateError instanceof Error ? updateError : new Error(String(updateError)));
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// README.md might not exist, ignore error
|
// Template doesn't exist, clone it shallowly
|
||||||
}
|
await this.fs.mkdir(templatePath, { recursive: true });
|
||||||
|
|
||||||
// Delete .git directory and reinitialize
|
try {
|
||||||
try {
|
await this.git.clone({
|
||||||
await this.deleteDirectory(`${project.path}/.git`);
|
dir: templatePath,
|
||||||
} catch {
|
url: templateUrl,
|
||||||
// .git directory might not exist, ignore error
|
singleBranch: true,
|
||||||
}
|
depth: 1,
|
||||||
|
|
||||||
// Initialize new git repository
|
|
||||||
await this.git.init({
|
|
||||||
dir: project.path,
|
|
||||||
defaultBranch: 'main',
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add all files to git
|
|
||||||
const files = await this.getAllFiles(project.path);
|
|
||||||
for (const file of files) {
|
|
||||||
// Skip .git directory
|
|
||||||
if (!file.startsWith('.git/')) {
|
|
||||||
await this.git.add({
|
|
||||||
dir: project.path,
|
|
||||||
filepath: file,
|
|
||||||
});
|
});
|
||||||
|
} catch (cloneError) {
|
||||||
|
// Clean up on clone failure
|
||||||
|
try {
|
||||||
|
await this.deleteDirectory(templatePath);
|
||||||
|
} catch {
|
||||||
|
// Ignore cleanup errors
|
||||||
|
}
|
||||||
|
throw cloneError;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Make initial commit
|
return templatePath;
|
||||||
await this.git.commit({
|
}
|
||||||
dir: project.path,
|
|
||||||
message: 'New project created with Shakespeare',
|
/**
|
||||||
|
* Force pull the template repository to match remote, discarding any local changes.
|
||||||
|
* This ensures the template is always up-to-date with the remote.
|
||||||
|
*/
|
||||||
|
private async forcePullTemplate(templatePath: string): Promise<void> {
|
||||||
|
// Fetch the latest changes from remote
|
||||||
|
const fetchResult = await this.git.fetch({
|
||||||
|
dir: templatePath,
|
||||||
|
singleBranch: true,
|
||||||
|
depth: 1,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Automatically request persistent storage after project creation
|
// Get the current branch name
|
||||||
try {
|
const branch = fetchResult.defaultBranch;
|
||||||
await ensurePersistentStorage();
|
|
||||||
} catch (error) {
|
if (!branch) {
|
||||||
// Don't fail project creation if persistent storage request fails
|
throw new Error('Could not determine current branch');
|
||||||
console.warn('Failed to request persistent storage after project creation:', error);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return project;
|
// Reset hard to the remote branch, discarding all local changes
|
||||||
|
await this.git.checkout({
|
||||||
|
dir: templatePath,
|
||||||
|
ref: branch,
|
||||||
|
force: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a safe directory name from a template URL
|
||||||
|
*/
|
||||||
|
private getTemplateNameFromUrl(url: string): string {
|
||||||
|
// Extract a meaningful name from the URL
|
||||||
|
// e.g., "https://gitlab.com/soapbox-pub/mkstack.git" -> "mkstack"
|
||||||
|
// e.g., "nostr://[email protected]/shakespeare.diy/mkstack" -> "mkstack"
|
||||||
|
|
||||||
|
let name = url;
|
||||||
|
|
||||||
|
// Remove .git suffix if present
|
||||||
|
name = name.replace(/\.git$/, '');
|
||||||
|
|
||||||
|
// Remove trailing slash
|
||||||
|
name = name.replace(/\/$/, '');
|
||||||
|
|
||||||
|
// Extract the last part of the path
|
||||||
|
const parts = name.split('/');
|
||||||
|
name = parts[parts.length - 1] || '';
|
||||||
|
|
||||||
|
// Sanitize the name to be filesystem-safe
|
||||||
|
name = name
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, '-')
|
||||||
|
.replace(/^-+|-+$/g, '');
|
||||||
|
|
||||||
|
if (!name) {
|
||||||
|
throw new Error(`Could not derive template name from URL: ${url}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copy a directory recursively from source to destination
|
||||||
|
*/
|
||||||
|
private async copyDirectory(sourcePath: string, destPath: string): Promise<void> {
|
||||||
|
// Ensure destination directory exists
|
||||||
|
await this.fs.mkdir(destPath, { recursive: true });
|
||||||
|
|
||||||
|
const entries = await this.fs.readdir(sourcePath);
|
||||||
|
|
||||||
|
for (const entry of entries) {
|
||||||
|
// Skip .git directory
|
||||||
|
if (entry === '.git') continue;
|
||||||
|
|
||||||
|
const sourceFullPath = `${sourcePath}/${entry}`;
|
||||||
|
const destFullPath = `${destPath}/${entry}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const stat = await this.fs.lstat(sourceFullPath);
|
||||||
|
|
||||||
|
if (stat.isDirectory()) {
|
||||||
|
// Recursively copy subdirectories
|
||||||
|
await this.copyDirectory(sourceFullPath, destFullPath);
|
||||||
|
} else if (stat.isFile()) {
|
||||||
|
// Copy file
|
||||||
|
const content = await this.fs.readFile(sourceFullPath);
|
||||||
|
await this.fs.writeFile(destFullPath, content);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(`Failed to copy ${sourceFullPath}:`, error);
|
||||||
|
// Continue copying other files
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async createProject(name: string, templateUrl: string, customId?: string, onTemplateUpdateError?: (error: Error) => void): Promise<Project> {
|
||||||
|
const id = customId || await this.generateUniqueProjectId(name);
|
||||||
|
|
||||||
|
// Check if project with this ID already exists when using custom ID
|
||||||
|
if (customId && await this.projectExists(id)) {
|
||||||
|
throw new Error(`Project with ID "${id}" already exists`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const projectPath = `${this.dir}/${id}`;
|
||||||
|
|
||||||
|
// Ensure template is cached and up-to-date
|
||||||
|
const templatePath = await this.updateTemplate(templateUrl, onTemplateUpdateError);
|
||||||
|
|
||||||
|
// Create project directory
|
||||||
|
await this.fs.mkdir(projectPath, { recursive: true });
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Copy template to project directory (excluding .git)
|
||||||
|
await this.copyDirectory(templatePath, projectPath);
|
||||||
|
|
||||||
|
// Delete README.md if it exists
|
||||||
|
try {
|
||||||
|
await this.fs.unlink(`${projectPath}/README.md`);
|
||||||
|
} catch {
|
||||||
|
// README.md might not exist, ignore error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize new git repository
|
||||||
|
await this.git.init({
|
||||||
|
dir: projectPath,
|
||||||
|
defaultBranch: 'main',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add all files to git
|
||||||
|
const files = await this.getAllFiles(projectPath);
|
||||||
|
for (const file of files) {
|
||||||
|
// Skip .git directory
|
||||||
|
if (!file.startsWith('.git/')) {
|
||||||
|
await this.git.add({
|
||||||
|
dir: projectPath,
|
||||||
|
filepath: file,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make initial commit
|
||||||
|
await this.git.commit({
|
||||||
|
dir: projectPath,
|
||||||
|
message: 'New project created with Shakespeare',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get filesystem stats for timestamps
|
||||||
|
const stats = await this.fs.stat(projectPath);
|
||||||
|
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
id,
|
||||||
|
name: this.formatProjectName(id),
|
||||||
|
path: projectPath,
|
||||||
|
lastModified: timestamp,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
// Clean up the directory that was created if project creation fails
|
||||||
|
try {
|
||||||
|
await this.deleteDirectory(projectPath);
|
||||||
|
} catch (cleanupError) {
|
||||||
|
// Log cleanup error but don't mask the original error
|
||||||
|
console.warn('Failed to clean up directory after project creation failure:', cleanupError);
|
||||||
|
}
|
||||||
|
// Re-throw the original error
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise<Project> {
|
async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise<Project> {
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ const testConfig: AppConfig = {
|
|||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
fsPathTmp: '/tmp',
|
fsPathTmp: '/tmp',
|
||||||
fsPathPlugins: '/plugins',
|
fsPathPlugins: '/plugins',
|
||||||
|
fsPathTemplates: '/templates',
|
||||||
sentryDsn: '',
|
sentryDsn: '',
|
||||||
sentryEnabled: false,
|
sentryEnabled: false,
|
||||||
};
|
};
|
||||||
@@ -155,4 +156,25 @@ describe('SessionManager', () => {
|
|||||||
expect(updatedSession?.messages).toHaveLength(1); // Only the user message
|
expect(updatedSession?.messages).toHaveLength(1); // Only the user message
|
||||||
expect(updatedSession?.messages[0].role).toBe('user');
|
expect(updatedSession?.messages[0].role).toBe('user');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should track when images are not supported and strip them on subsequent requests', async () => {
|
||||||
|
const projectId = 'test-project';
|
||||||
|
const tools = {};
|
||||||
|
const customTools = {};
|
||||||
|
|
||||||
|
// Load a session
|
||||||
|
const session = await sessionManager.loadSession(projectId, tools, customTools);
|
||||||
|
|
||||||
|
// Initially, images should not be marked as unsupported
|
||||||
|
expect(session.imagesNotSupported).toBeUndefined();
|
||||||
|
|
||||||
|
// Simulate marking images as not supported (this would happen after an API error)
|
||||||
|
session.imagesNotSupported = true;
|
||||||
|
|
||||||
|
// Verify the flag is set
|
||||||
|
expect(session.imagesNotSupported).toBe(true);
|
||||||
|
|
||||||
|
// On subsequent requests, the SessionManager should proactively strip images
|
||||||
|
// This prevents retrying with images on every message/tool call
|
||||||
|
});
|
||||||
});
|
});
|
||||||
+121
-7
@@ -40,6 +40,7 @@ export interface SessionState {
|
|||||||
abortController?: AbortController;
|
abortController?: AbortController;
|
||||||
totalCost?: number; // Total cost in USD for this session
|
totalCost?: number; // Total cost in USD for this session
|
||||||
lastInputTokens?: number; // Input tokens from the last AI request
|
lastInputTokens?: number; // Input tokens from the last AI request
|
||||||
|
imagesNotSupported?: boolean; // Track if this session's model doesn't support images
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SessionManagerEvents {
|
export interface SessionManagerEvents {
|
||||||
@@ -187,7 +188,11 @@ export class SessionManager {
|
|||||||
/**
|
/**
|
||||||
* Send a message and start AI generation
|
* Send a message and start AI generation
|
||||||
*/
|
*/
|
||||||
async sendMessage(projectId: string, content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string): Promise<void> {
|
async sendMessage(
|
||||||
|
projectId: string,
|
||||||
|
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
|
||||||
|
providerModel: string
|
||||||
|
): Promise<void> {
|
||||||
const session = this.sessions.get(projectId);
|
const session = this.sessions.get(projectId);
|
||||||
|
|
||||||
if (!session || session.isLoading) return;
|
if (!session || session.isLoading) return;
|
||||||
@@ -274,10 +279,73 @@ export class SessionManager {
|
|||||||
template: config.systemPrompt,
|
template: config.systemPrompt,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Helper function to filter out unsupported image formats (keep only JPG/JPEG/PNG)
|
||||||
|
const filterSupportedImages = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
|
||||||
|
return msgs.map(msg => {
|
||||||
|
if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) {
|
||||||
|
const filteredContent = msg.content.filter(part => {
|
||||||
|
if (part.type !== 'image_url') return true;
|
||||||
|
|
||||||
|
const imagePart = part as OpenAI.Chat.Completions.ChatCompletionContentPartImage;
|
||||||
|
const url = imagePart.image_url.url.toLowerCase();
|
||||||
|
|
||||||
|
// Keep only JPG/JPEG/PNG images
|
||||||
|
// Check file extension or data URL MIME type
|
||||||
|
return /\.(jpg|jpeg|png)(\?|$)/.test(url) ||
|
||||||
|
url.startsWith('data:image/jpeg') ||
|
||||||
|
url.startsWith('data:image/png') ||
|
||||||
|
url.startsWith('data:image/jpg');
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
...msg,
|
||||||
|
content: filteredContent
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return msg;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper function to strip all image_url parts but keep text parts (including VFS paths)
|
||||||
|
const stripImageUrls = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
|
||||||
|
return msgs.map(msg => {
|
||||||
|
if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) {
|
||||||
|
// Keep only text parts (this includes "Added file: /tmp/..." paths)
|
||||||
|
const textParts = msg.content.filter(part => part.type === 'text');
|
||||||
|
|
||||||
|
// If we had images, convert to string content (or empty if no text)
|
||||||
|
if (textParts.length > 0) {
|
||||||
|
return {
|
||||||
|
...msg,
|
||||||
|
content: textParts.map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartText).text).join('\n')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no text parts, return empty string
|
||||||
|
return {
|
||||||
|
...msg,
|
||||||
|
content: ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return msg;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
// Prepare messages for AI
|
// Prepare messages for AI
|
||||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = systemPrompt
|
// Note: User messages with image_url content parts are valid ChatCompletionMessageParam types
|
||||||
|
// The AIMessage type includes ChatCompletionMessageParam, so this cast is safe
|
||||||
|
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = (systemPrompt
|
||||||
? [{ role: 'system', content: systemPrompt }, ...session.messages]
|
? [{ role: 'system', content: systemPrompt }, ...session.messages]
|
||||||
: session.messages;
|
: session.messages) as OpenAI.Chat.Completions.ChatCompletionMessageParam[];
|
||||||
|
|
||||||
|
// Filter out unsupported image formats (keep only JPG/JPEG/PNG for API)
|
||||||
|
// This ensures the UI shows all image types, but API only receives supported formats
|
||||||
|
messages = filterSupportedImages(messages);
|
||||||
|
|
||||||
|
// If this session has already determined images aren't supported, strip them proactively
|
||||||
|
if (session.imagesNotSupported) {
|
||||||
|
messages = stripImageUrls(messages);
|
||||||
|
}
|
||||||
|
|
||||||
// Prepare completion options
|
// Prepare completion options
|
||||||
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||||
@@ -290,11 +358,56 @@ export class SessionManager {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// Generate streaming response
|
// Check if messages contain any images (for retry logic)
|
||||||
const stream = await openai.chat.completions.create(completionOptions, {
|
const hasImages = messages.some(msg => {
|
||||||
signal: session.abortController?.signal
|
if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) {
|
||||||
|
return msg.content.some(part => part.type === 'image_url');
|
||||||
|
}
|
||||||
|
return false;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Generate streaming response with retry logic for models that don't support images
|
||||||
|
let stream: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>;
|
||||||
|
let retriedWithoutImages = false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
stream = await openai.chat.completions.create(completionOptions, {
|
||||||
|
signal: session.abortController?.signal
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Check if this might be an image-related error and we have images to strip
|
||||||
|
const errorObj = error as Record<string, unknown>;
|
||||||
|
const errorStatus = typeof errorObj?.status === 'number' ? errorObj.status : undefined;
|
||||||
|
const isPotentialImageError = errorStatus === 400 || errorStatus === 404 || errorStatus === 500;
|
||||||
|
|
||||||
|
if (isPotentialImageError && hasImages && !retriedWithoutImages) {
|
||||||
|
console.warn('API call failed, retrying without image_url parts (keeping VFS paths):', error);
|
||||||
|
retriedWithoutImages = true;
|
||||||
|
|
||||||
|
// Strip image_url parts but keep text parts (including VFS paths)
|
||||||
|
const messagesWithoutImages = stripImageUrls(messages);
|
||||||
|
|
||||||
|
// Update completion options with stripped messages
|
||||||
|
const retryOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||||
|
...completionOptions,
|
||||||
|
messages: messagesWithoutImages
|
||||||
|
};
|
||||||
|
|
||||||
|
// Retry the API call - if this succeeds, we know images were the problem
|
||||||
|
stream = await openai.chat.completions.create(retryOptions, {
|
||||||
|
signal: session.abortController?.signal
|
||||||
|
});
|
||||||
|
|
||||||
|
// SUCCESS: The retry without images worked, so this model doesn't support images
|
||||||
|
// Mark this session as not supporting images to avoid future retries
|
||||||
|
session.imagesNotSupported = true;
|
||||||
|
console.log('Retry without images succeeded - marking this session as not supporting images');
|
||||||
|
} else {
|
||||||
|
// Re-throw if not a potential image error or already retried
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let accumulatedContent = '';
|
let accumulatedContent = '';
|
||||||
let accumulatedReasoningContent = '';
|
let accumulatedReasoningContent = '';
|
||||||
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
|
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
|
||||||
@@ -609,7 +722,8 @@ export class SessionManager {
|
|||||||
try {
|
try {
|
||||||
const config = this.getConfig();
|
const config = this.getConfig();
|
||||||
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${session.projectId}`);
|
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${session.projectId}`);
|
||||||
await dotAI.setHistory(session.sessionName, session.messages);
|
// Cast to ChatCompletionMessageParam[] - user messages with image arrays are valid
|
||||||
|
await dotAI.setHistory(session.sessionName, session.messages as OpenAI.Chat.Completions.ChatCompletionMessageParam[]);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('Failed to save session history:', error);
|
console.warn('Failed to save session history:', error);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import type OpenAI from 'openai';
|
||||||
|
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||||
|
import { saveFileToTmp } from './fileUtils';
|
||||||
|
import { fileToUrl } from './imageUtils';
|
||||||
|
|
||||||
|
type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds message content from text input and attached files.
|
||||||
|
*
|
||||||
|
* - All image formats are included in the message content for UI display
|
||||||
|
* - SessionManager filters to only pass JPG/JPEG/PNG to the OpenAI API
|
||||||
|
* - All files are saved to VFS and get a text part with the path
|
||||||
|
* - Images are converted to base64-encoded data URLs for API consumption
|
||||||
|
*
|
||||||
|
* Returns content as either a string (for simple text) or an array of content parts.
|
||||||
|
*
|
||||||
|
* @param input - User text input
|
||||||
|
* @param attachedFiles - Array of files to attach
|
||||||
|
* @param fs - Filesystem instance for saving files
|
||||||
|
* @param tmpPath - Temporary directory path for file storage
|
||||||
|
* @returns Promise resolving to message content (string or array of content parts)
|
||||||
|
*/
|
||||||
|
export async function buildMessageContent(
|
||||||
|
input: string,
|
||||||
|
attachedFiles: File[],
|
||||||
|
fs: JSRuntimeFS,
|
||||||
|
tmpPath = '/tmp'
|
||||||
|
): Promise<string | ContentPart[]> {
|
||||||
|
const contentParts: ContentPart[] = [];
|
||||||
|
|
||||||
|
// Add user input as text part if present
|
||||||
|
if (input.trim()) {
|
||||||
|
contentParts.push({
|
||||||
|
type: 'text',
|
||||||
|
text: input.trim()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process attached files: save to VFS and add image_url for UI display (all image types)
|
||||||
|
if (attachedFiles.length > 0) {
|
||||||
|
const filePromises = attachedFiles.map(async (file) => {
|
||||||
|
try {
|
||||||
|
// Save file to VFS (always do this)
|
||||||
|
const savedPath = await saveFileToTmp(fs, file, tmpPath);
|
||||||
|
|
||||||
|
// Always add text part with VFS path
|
||||||
|
const textPart: ContentPart = {
|
||||||
|
type: 'text',
|
||||||
|
text: `Added file: ${savedPath}`
|
||||||
|
};
|
||||||
|
|
||||||
|
// For all image types, also add as image_url for UI display with base64 encoding
|
||||||
|
const isImage = file.type.startsWith('image/');
|
||||||
|
if (isImage) {
|
||||||
|
try {
|
||||||
|
const imageUrl = await fileToUrl(file);
|
||||||
|
// Return both parts: image_url for UI display and text for VFS path
|
||||||
|
return [textPart, {
|
||||||
|
type: 'image_url' as const,
|
||||||
|
image_url: { url: imageUrl }
|
||||||
|
}];
|
||||||
|
} catch (error) {
|
||||||
|
// If URL conversion fails, just use text part
|
||||||
|
console.warn('Failed to convert image to base64, using text part only:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [textPart];
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to save file:', error);
|
||||||
|
return [{
|
||||||
|
type: 'text' as const,
|
||||||
|
text: `Failed to save file: ${file.name}`
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const fileResults = await Promise.all(filePromises);
|
||||||
|
|
||||||
|
// Flatten the results (each file can return multiple parts)
|
||||||
|
for (const parts of fileResults) {
|
||||||
|
contentParts.push(...parts);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return as string if single text part, otherwise return array
|
||||||
|
if (contentParts.length === 1 && contentParts[0].type === 'text') {
|
||||||
|
return contentParts[0].text;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return array for multiple parts or if contains image URLs
|
||||||
|
return contentParts;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -609,7 +609,7 @@ Commands are executed through the `ShellTool` which handles:
|
|||||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||||
|
|
||||||
// Create shell tool with filesystem and working directory
|
// Create shell tool with filesystem and working directory
|
||||||
const shell = new ShellTool(fs, '/project/root');
|
const shell = new ShellTool(fs, '/project/root', ...rest);
|
||||||
|
|
||||||
// Execute commands
|
// Execute commands
|
||||||
const result = await shell.execute({ command: 'cat package.json' });
|
const result = await shell.execute({ command: 'cat package.json' });
|
||||||
|
|||||||
@@ -28,13 +28,12 @@ export interface GitSubcommand {
|
|||||||
name: string;
|
name: string;
|
||||||
description: string;
|
description: string;
|
||||||
usage: string;
|
usage: string;
|
||||||
execute(args: string[]): Promise<ShellCommandResult>;
|
execute(args: string[], cwd: string): Promise<ShellCommandResult>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GitSubcommandOptions {
|
export interface GitSubcommandOptions {
|
||||||
git: Git;
|
git: Git;
|
||||||
fs: JSRuntimeFS;
|
fs: JSRuntimeFS;
|
||||||
pwd: string;
|
|
||||||
signer?: NostrSigner;
|
signer?: NostrSigner;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,7 +70,6 @@ export class GitCommand implements ShellCommand {
|
|||||||
const subcommandOptions: GitSubcommandOptions = {
|
const subcommandOptions: GitSubcommandOptions = {
|
||||||
git: this.git,
|
git: this.git,
|
||||||
fs: this.fs,
|
fs: this.fs,
|
||||||
pwd: this.cwd,
|
|
||||||
signer: this.signer,
|
signer: this.signer,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -99,7 +97,7 @@ export class GitCommand implements ShellCommand {
|
|||||||
this.subcommands.set(subcommand.name, subcommand);
|
this.subcommands.set(subcommand.name, subcommand);
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[], _cwd: string, _input?: string): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Handle no arguments or help
|
// Handle no arguments or help
|
||||||
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
||||||
@@ -120,8 +118,9 @@ export class GitCommand implements ShellCommand {
|
|||||||
return createErrorResult(`git: '${subcommandName}' is not a git command. See 'git --help'.`);
|
return createErrorResult(`git: '${subcommandName}' is not a git command. See 'git --help'.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Execute the subcommand
|
// Execute the subcommand, passing the current working directory
|
||||||
return await subcommand.execute(subcommandArgs);
|
// This ensures git commands use the correct directory after 'cd' commands
|
||||||
|
return await subcommand.execute(subcommandArgs, cwd);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return createErrorResult(`git: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
return createErrorResult(`git: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||||
|
|||||||
@@ -57,7 +57,6 @@ describe('GitAddCommand', () => {
|
|||||||
addCommand = new GitAddCommand({
|
addCommand = new GitAddCommand({
|
||||||
git: mockGit,
|
git: mockGit,
|
||||||
fs: mockFS,
|
fs: mockFS,
|
||||||
pwd: testCwd,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -71,14 +70,14 @@ describe('GitAddCommand', () => {
|
|||||||
// Mock stat to throw error for .git directory
|
// Mock stat to throw error for .git directory
|
||||||
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
||||||
|
|
||||||
const result = await addCommand.execute(['file.txt']);
|
const result = await addCommand.execute(['file.txt'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('fatal: not a git repository');
|
expect(result.stderr).toContain('fatal: not a git repository');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return error when no files specified', async () => {
|
it('should return error when no files specified', async () => {
|
||||||
const result = await addCommand.execute([]);
|
const result = await addCommand.execute([], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('Nothing specified, nothing added');
|
expect(result.stderr).toContain('Nothing specified, nothing added');
|
||||||
@@ -95,7 +94,7 @@ describe('GitAddCommand', () => {
|
|||||||
['staged.txt', 1, 2, 2], // Already staged file
|
['staged.txt', 1, 2, 2], // Already staged file
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const result = await addCommand.execute(['--all']);
|
const result = await addCommand.execute(['--all'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toBe(''); // Git add is silent on success
|
expect(result.stdout).toBe(''); // Git add is silent on success
|
||||||
@@ -118,7 +117,7 @@ describe('GitAddCommand', () => {
|
|||||||
['deleted.txt', 1, 0, 1], // Deleted file (not staged)
|
['deleted.txt', 1, 0, 1], // Deleted file (not staged)
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const result = await addCommand.execute(['--all']);
|
const result = await addCommand.execute(['--all'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toBe('');
|
expect(result.stdout).toBe('');
|
||||||
@@ -132,7 +131,7 @@ describe('GitAddCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should add specific file', async () => {
|
it('should add specific file', async () => {
|
||||||
const result = await addCommand.execute(['file.txt']);
|
const result = await addCommand.execute(['file.txt'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toBe('');
|
expect(result.stdout).toBe('');
|
||||||
@@ -151,7 +150,7 @@ describe('GitAddCommand', () => {
|
|||||||
['deleted.txt', 1, 0, 1], // Deleted file
|
['deleted.txt', 1, 0, 1], // Deleted file
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const result = await addCommand.execute(['.']);
|
const result = await addCommand.execute(['.'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toBe('');
|
expect(result.stdout).toBe('');
|
||||||
@@ -174,7 +173,7 @@ describe('GitAddCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should reject absolute paths', async () => {
|
it('should reject absolute paths', async () => {
|
||||||
const result = await addCommand.execute(['/absolute/path/file.txt']);
|
const result = await addCommand.execute(['/absolute/path/file.txt'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('absolute paths are not supported');
|
expect(result.stderr).toContain('absolute paths are not supported');
|
||||||
@@ -205,7 +204,7 @@ describe('GitAddCommand', () => {
|
|||||||
// Mock git.remove to also throw error (file doesn't exist in git either)
|
// Mock git.remove to also throw error (file doesn't exist in git either)
|
||||||
vi.mocked(mockGit.remove).mockRejectedValueOnce(new Error('File not found'));
|
vi.mocked(mockGit.remove).mockRejectedValueOnce(new Error('File not found'));
|
||||||
|
|
||||||
const result = await addCommand.execute(['nonexistent.txt']);
|
const result = await addCommand.execute(['nonexistent.txt'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('pathspec \'nonexistent.txt\' did not match any files');
|
expect(result.stderr).toContain('pathspec \'nonexistent.txt\' did not match any files');
|
||||||
@@ -216,7 +215,7 @@ describe('GitAddCommand', () => {
|
|||||||
['modified.txt', 1, 2, 1], // Modified file
|
['modified.txt', 1, 2, 1], // Modified file
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const result = await addCommand.execute(['-A']);
|
const result = await addCommand.execute(['-A'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toBe('');
|
expect(result.stdout).toBe('');
|
||||||
@@ -233,7 +232,7 @@ describe('GitAddCommand', () => {
|
|||||||
['modified.txt', 1, 2, 1], // Modified file
|
['modified.txt', 1, 2, 1], // Modified file
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const result = await addCommand.execute(['--all', 'specific.txt']);
|
const result = await addCommand.execute(['--all', 'specific.txt'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
|
|
||||||
@@ -242,7 +241,7 @@ describe('GitAddCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should handle double dash separator', async () => {
|
it('should handle double dash separator', async () => {
|
||||||
const result = await addCommand.execute(['--', 'file.txt']);
|
const result = await addCommand.execute(['--', 'file.txt'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toBe('');
|
expect(result.stdout).toBe('');
|
||||||
@@ -267,7 +266,7 @@ describe('GitAddCommand', () => {
|
|||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await addCommand.execute(['--all']);
|
const result = await addCommand.execute(['--all'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0); // Should still succeed overall
|
expect(result.exitCode).toBe(0); // Should still succeed overall
|
||||||
expect(mockGit.add).toHaveBeenCalledTimes(2);
|
expect(mockGit.add).toHaveBeenCalledTimes(2);
|
||||||
|
|||||||
+21
-31
@@ -12,19 +12,17 @@ export class GitAddCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -33,12 +31,12 @@ export class GitAddCommand implements GitSubcommand {
|
|||||||
|
|
||||||
if (options.all) {
|
if (options.all) {
|
||||||
// Add all files (git add -A)
|
// Add all files (git add -A)
|
||||||
return await this.addAllFiles();
|
return await this.addAllFiles(cwd);
|
||||||
} else if (paths.length === 0) {
|
} else if (paths.length === 0) {
|
||||||
return createErrorResult('Nothing specified, nothing added.\nMaybe you wanted to say \'git add .\'?');
|
return createErrorResult('Nothing specified, nothing added.\nMaybe you wanted to say \'git add .\'?');
|
||||||
} else {
|
} else {
|
||||||
// Add specific files
|
// Add specific files
|
||||||
return await this.addSpecificFiles(paths);
|
return await this.addSpecificFiles(paths, cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -70,11 +68,11 @@ export class GitAddCommand implements GitSubcommand {
|
|||||||
return { options, paths };
|
return { options, paths };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async addAllFiles(): Promise<ShellCommandResult> {
|
private async addAllFiles(cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Get status to find all changed files
|
// Get status to find all changed files
|
||||||
const statusMatrix = await this.git.statusMatrix({
|
const statusMatrix = await this.git.statusMatrix({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||||
@@ -82,15 +80,13 @@ export class GitAddCommand implements GitSubcommand {
|
|||||||
if (workdirStatus === 0 && headStatus === 1) {
|
if (workdirStatus === 0 && headStatus === 1) {
|
||||||
// File was deleted in working directory
|
// File was deleted in working directory
|
||||||
await this.git.remove({
|
await this.git.remove({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
filepath,
|
filepath,
|
||||||
});
|
});
|
||||||
} else if (workdirStatus === 2 && stageStatus !== 2) {
|
} else if (workdirStatus === 2 && stageStatus !== 2) {
|
||||||
// File exists and has changes that aren't staged yet
|
// File exists and has changes that aren't staged yet
|
||||||
await this.git.add({
|
await this.git.add({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
filepath,
|
filepath,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -108,7 +104,7 @@ export class GitAddCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async addSpecificFiles(paths: string[]): Promise<ShellCommandResult> {
|
private async addSpecificFiles(paths: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
const addedFiles: string[] = [];
|
const addedFiles: string[] = [];
|
||||||
const errors: string[] = [];
|
const errors: string[] = [];
|
||||||
|
|
||||||
@@ -117,8 +113,7 @@ export class GitAddCommand implements GitSubcommand {
|
|||||||
if (path === '.') {
|
if (path === '.') {
|
||||||
// Add current directory (all files in it)
|
// Add current directory (all files in it)
|
||||||
const statusMatrix = await this.git.statusMatrix({
|
const statusMatrix = await this.git.statusMatrix({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||||
@@ -126,16 +121,14 @@ export class GitAddCommand implements GitSubcommand {
|
|||||||
if (workdirStatus === 0 && headStatus === 1) {
|
if (workdirStatus === 0 && headStatus === 1) {
|
||||||
// File was deleted in working directory
|
// File was deleted in working directory
|
||||||
await this.git.remove({
|
await this.git.remove({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
filepath,
|
filepath,
|
||||||
});
|
});
|
||||||
addedFiles.push(filepath);
|
addedFiles.push(filepath);
|
||||||
} else if (workdirStatus === 2 && stageStatus !== 2) {
|
} else if (workdirStatus === 2 && stageStatus !== 2) {
|
||||||
// File exists and has changes that aren't staged yet
|
// File exists and has changes that aren't staged yet
|
||||||
await this.git.add({
|
await this.git.add({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
filepath,
|
filepath,
|
||||||
});
|
});
|
||||||
addedFiles.push(filepath);
|
addedFiles.push(filepath);
|
||||||
@@ -151,7 +144,7 @@ export class GitAddCommand implements GitSubcommand {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const absolutePath = join(this.pwd, path);
|
const absolutePath = join(cwd, path);
|
||||||
|
|
||||||
// Check if file/directory exists
|
// Check if file/directory exists
|
||||||
try {
|
try {
|
||||||
@@ -159,12 +152,11 @@ export class GitAddCommand implements GitSubcommand {
|
|||||||
|
|
||||||
if (stats.isDirectory()) {
|
if (stats.isDirectory()) {
|
||||||
// Add all files in directory
|
// Add all files in directory
|
||||||
await this.addDirectory(path, addedFiles);
|
await this.addDirectory(path, addedFiles, cwd);
|
||||||
} else {
|
} else {
|
||||||
// Add single file
|
// Add single file
|
||||||
await this.git.add({
|
await this.git.add({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
filepath: path,
|
filepath: path,
|
||||||
});
|
});
|
||||||
addedFiles.push(path);
|
addedFiles.push(path);
|
||||||
@@ -173,8 +165,7 @@ export class GitAddCommand implements GitSubcommand {
|
|||||||
// Check if it's a deleted file
|
// Check if it's a deleted file
|
||||||
try {
|
try {
|
||||||
await this.git.remove({
|
await this.git.remove({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
filepath: path,
|
filepath: path,
|
||||||
});
|
});
|
||||||
addedFiles.push(path);
|
addedFiles.push(path);
|
||||||
@@ -196,8 +187,8 @@ export class GitAddCommand implements GitSubcommand {
|
|||||||
return createSuccessResult('');
|
return createSuccessResult('');
|
||||||
}
|
}
|
||||||
|
|
||||||
private async addDirectory(dirPath: string, addedFiles: string[]): Promise<void> {
|
private async addDirectory(dirPath: string, addedFiles: string[], cwd: string): Promise<void> {
|
||||||
const absolutePath = join(this.pwd, dirPath);
|
const absolutePath = join(cwd, dirPath);
|
||||||
const entries = await this.fs.readdir(absolutePath, { withFileTypes: true });
|
const entries = await this.fs.readdir(absolutePath, { withFileTypes: true });
|
||||||
|
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
@@ -208,12 +199,11 @@ export class GitAddCommand implements GitSubcommand {
|
|||||||
const entryPath = join(dirPath, entry.name);
|
const entryPath = join(dirPath, entry.name);
|
||||||
|
|
||||||
if (entry.isDirectory()) {
|
if (entry.isDirectory()) {
|
||||||
await this.addDirectory(entryPath, addedFiles);
|
await this.addDirectory(entryPath, addedFiles, cwd);
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
await this.git.add({
|
await this.git.add({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
filepath: entryPath,
|
filepath: entryPath,
|
||||||
});
|
});
|
||||||
addedFiles.push(entryPath);
|
addedFiles.push(entryPath);
|
||||||
@@ -223,4 +213,4 @@ export class GitAddCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,19 +11,17 @@ export class GitBranchCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -32,13 +30,13 @@ export class GitBranchCommand implements GitSubcommand {
|
|||||||
|
|
||||||
switch (action) {
|
switch (action) {
|
||||||
case 'list':
|
case 'list':
|
||||||
return await this.listBranches();
|
return await this.listBranches(cwd);
|
||||||
case 'create':
|
case 'create':
|
||||||
return await this.createBranch(branchName!);
|
return await this.createBranch(branchName!, cwd);
|
||||||
case 'delete':
|
case 'delete':
|
||||||
return await this.deleteBranch(branchName!, options.force);
|
return await this.deleteBranch(branchName!, options.force, cwd);
|
||||||
default:
|
default:
|
||||||
return await this.listBranches();
|
return await this.listBranches(cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -83,10 +81,10 @@ export class GitBranchCommand implements GitSubcommand {
|
|||||||
return { action, branchName, options };
|
return { action, branchName, options };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async listBranches(): Promise<ShellCommandResult> {
|
private async listBranches(cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
const branches = await this.git.listBranches({
|
const branches = await this.git.listBranches({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (branches.length === 0) {
|
if (branches.length === 0) {
|
||||||
@@ -98,7 +96,7 @@ export class GitBranchCommand implements GitSubcommand {
|
|||||||
try {
|
try {
|
||||||
currentBranch = await this.git.currentBranch({
|
currentBranch = await this.git.currentBranch({
|
||||||
|
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
}) || null;
|
}) || null;
|
||||||
} catch {
|
} catch {
|
||||||
// Might be in detached HEAD state
|
// Might be in detached HEAD state
|
||||||
@@ -120,11 +118,11 @@ export class GitBranchCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async createBranch(branchName: string): Promise<ShellCommandResult> {
|
private async createBranch(branchName: string, cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if branch already exists
|
// Check if branch already exists
|
||||||
const branches = await this.git.listBranches({
|
const branches = await this.git.listBranches({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (branches.includes(branchName)) {
|
if (branches.includes(branchName)) {
|
||||||
@@ -136,7 +134,7 @@ export class GitBranchCommand implements GitSubcommand {
|
|||||||
try {
|
try {
|
||||||
currentRef = await this.git.resolveRef({
|
currentRef = await this.git.resolveRef({
|
||||||
|
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: 'HEAD',
|
ref: 'HEAD',
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
@@ -145,7 +143,7 @@ export class GitBranchCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Create the new branch
|
// Create the new branch
|
||||||
await this.git.branch({
|
await this.git.branch({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: branchName,
|
ref: branchName,
|
||||||
object: currentRef,
|
object: currentRef,
|
||||||
});
|
});
|
||||||
@@ -157,11 +155,11 @@ export class GitBranchCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async deleteBranch(branchName: string, force: boolean): Promise<ShellCommandResult> {
|
private async deleteBranch(branchName: string, force: boolean, cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if branch exists
|
// Check if branch exists
|
||||||
const branches = await this.git.listBranches({
|
const branches = await this.git.listBranches({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!branches.includes(branchName)) {
|
if (!branches.includes(branchName)) {
|
||||||
@@ -173,19 +171,19 @@ export class GitBranchCommand implements GitSubcommand {
|
|||||||
try {
|
try {
|
||||||
currentBranch = await this.git.currentBranch({
|
currentBranch = await this.git.currentBranch({
|
||||||
|
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
}) || null;
|
}) || null;
|
||||||
} catch {
|
} catch {
|
||||||
// Continue
|
// Continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if (currentBranch === branchName) {
|
if (currentBranch === branchName) {
|
||||||
return createErrorResult(`error: Cannot delete branch '${branchName}' checked out at '${this.pwd}'`);
|
return createErrorResult(`error: Cannot delete branch '${branchName}' checked out at '${cwd}'`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete the branch
|
// Delete the branch
|
||||||
await this.git.deleteBranch({
|
await this.git.deleteBranch({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: branchName,
|
ref: branchName,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -198,4 +196,4 @@ export class GitBranchCommand implements GitSubcommand {
|
|||||||
return createErrorResult(`Failed to delete branch: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
return createErrorResult(`Failed to delete branch: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,19 +11,17 @@ export class GitCheckoutCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -32,11 +30,11 @@ export class GitCheckoutCommand implements GitSubcommand {
|
|||||||
|
|
||||||
switch (action) {
|
switch (action) {
|
||||||
case 'switch':
|
case 'switch':
|
||||||
return await this.switchBranch(target!);
|
return await this.switchBranch(target!, cwd);
|
||||||
case 'create':
|
case 'create':
|
||||||
return await this.createAndSwitchBranch(target!);
|
return await this.createAndSwitchBranch(target!, cwd);
|
||||||
case 'restore':
|
case 'restore':
|
||||||
return await this.restoreFiles(target!);
|
return await this.restoreFiles(target!, cwd);
|
||||||
default:
|
default:
|
||||||
return createErrorResult('error: pathspec did not match any file(s) known to git');
|
return createErrorResult('error: pathspec did not match any file(s) known to git');
|
||||||
}
|
}
|
||||||
@@ -82,11 +80,11 @@ export class GitCheckoutCommand implements GitSubcommand {
|
|||||||
return { action, target, options };
|
return { action, target, options };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async switchBranch(branchName: string): Promise<ShellCommandResult> {
|
private async switchBranch(branchName: string, cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if branch exists
|
// Check if branch exists
|
||||||
const branches = await this.git.listBranches({
|
const branches = await this.git.listBranches({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!branches.includes(branchName)) {
|
if (!branches.includes(branchName)) {
|
||||||
@@ -97,8 +95,7 @@ export class GitCheckoutCommand implements GitSubcommand {
|
|||||||
let currentBranch: string | null = null;
|
let currentBranch: string | null = null;
|
||||||
try {
|
try {
|
||||||
currentBranch = await this.git.currentBranch({
|
currentBranch = await this.git.currentBranch({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
}) || null;
|
}) || null;
|
||||||
} catch {
|
} catch {
|
||||||
// Continue
|
// Continue
|
||||||
@@ -110,7 +107,7 @@ export class GitCheckoutCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Check for uncommitted changes
|
// Check for uncommitted changes
|
||||||
const statusMatrix = await this.git.statusMatrix({
|
const statusMatrix = await this.git.statusMatrix({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
const hasChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => {
|
const hasChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => {
|
||||||
@@ -123,7 +120,7 @@ export class GitCheckoutCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Switch to the branch
|
// Switch to the branch
|
||||||
await this.git.checkout({
|
await this.git.checkout({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: branchName,
|
ref: branchName,
|
||||||
force: true,
|
force: true,
|
||||||
});
|
});
|
||||||
@@ -135,11 +132,11 @@ export class GitCheckoutCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async createAndSwitchBranch(branchName: string): Promise<ShellCommandResult> {
|
private async createAndSwitchBranch(branchName: string, cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if branch already exists
|
// Check if branch already exists
|
||||||
const branches = await this.git.listBranches({
|
const branches = await this.git.listBranches({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (branches.includes(branchName)) {
|
if (branches.includes(branchName)) {
|
||||||
@@ -150,8 +147,7 @@ export class GitCheckoutCommand implements GitSubcommand {
|
|||||||
let currentRef: string;
|
let currentRef: string;
|
||||||
try {
|
try {
|
||||||
currentRef = await this.git.resolveRef({
|
currentRef = await this.git.resolveRef({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
ref: 'HEAD',
|
ref: 'HEAD',
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
@@ -160,14 +156,14 @@ export class GitCheckoutCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Create the branch
|
// Create the branch
|
||||||
await this.git.branch({
|
await this.git.branch({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: branchName,
|
ref: branchName,
|
||||||
object: currentRef,
|
object: currentRef,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Switch to the new branch
|
// Switch to the new branch
|
||||||
await this.git.checkout({
|
await this.git.checkout({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: branchName,
|
ref: branchName,
|
||||||
force: true,
|
force: true,
|
||||||
});
|
});
|
||||||
@@ -179,7 +175,7 @@ export class GitCheckoutCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async restoreFiles(filePath: string): Promise<ShellCommandResult> {
|
private async restoreFiles(filePath: string, cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// This is a simplified implementation
|
// This is a simplified implementation
|
||||||
// In a full git implementation, this would restore files from the index or HEAD
|
// In a full git implementation, this would restore files from the index or HEAD
|
||||||
@@ -187,8 +183,7 @@ export class GitCheckoutCommand implements GitSubcommand {
|
|||||||
// Get the file from HEAD
|
// Get the file from HEAD
|
||||||
try {
|
try {
|
||||||
await this.git.checkout({
|
await this.git.checkout({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
ref: 'HEAD',
|
ref: 'HEAD',
|
||||||
filepaths: [filePath],
|
filepaths: [filePath],
|
||||||
});
|
});
|
||||||
@@ -205,4 +200,4 @@ export class GitCheckoutCommand implements GitSubcommand {
|
|||||||
return createErrorResult(`Failed to restore file: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
return createErrorResult(`Failed to restore file: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -12,15 +12,13 @@ export class GitCloneCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
const { options, repository, directory } = this.parseArgs(args);
|
const { options, repository, directory } = this.parseArgs(args);
|
||||||
|
|
||||||
@@ -37,7 +35,7 @@ export class GitCloneCommand implements GitSubcommand {
|
|||||||
targetDir = repoName.replace(/\.git$/, ''); // Remove .git suffix if present
|
targetDir = repoName.replace(/\.git$/, ''); // Remove .git suffix if present
|
||||||
}
|
}
|
||||||
|
|
||||||
const targetPath = `${this.pwd}/${targetDir}`;
|
const targetPath = `${cwd}/${targetDir}`;
|
||||||
|
|
||||||
// Check if target directory already exists
|
// Check if target directory already exists
|
||||||
try {
|
try {
|
||||||
@@ -117,4 +115,4 @@ export class GitCloneCommand implements GitSubcommand {
|
|||||||
|
|
||||||
return { options, repository, directory };
|
return { options, repository, directory };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -75,12 +75,11 @@ describe('GitCommitCommand', () => {
|
|||||||
commitCommand = new GitCommitCommand({
|
commitCommand = new GitCommitCommand({
|
||||||
git: mockGit as Git,
|
git: mockGit as Git,
|
||||||
fs: mockFS as JSRuntimeFS,
|
fs: mockFS as JSRuntimeFS,
|
||||||
pwd: mockPwd,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should commit with a message', async () => {
|
it('should commit with a message', async () => {
|
||||||
const result = await commitCommand.execute(['-m', 'Test commit']);
|
const result = await commitCommand.execute(['-m', 'Test commit'], mockPwd);
|
||||||
|
|
||||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
dir: mockPwd,
|
dir: mockPwd,
|
||||||
@@ -92,7 +91,7 @@ describe('GitCommitCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should fail without a message', async () => {
|
it('should fail without a message', async () => {
|
||||||
const result = await commitCommand.execute([]);
|
const result = await commitCommand.execute([], mockPwd);
|
||||||
|
|
||||||
expect(mockGit.commit).not.toHaveBeenCalled();
|
expect(mockGit.commit).not.toHaveBeenCalled();
|
||||||
|
|
||||||
@@ -101,7 +100,7 @@ describe('GitCommitCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should handle --amend flag', async () => {
|
it('should handle --amend flag', async () => {
|
||||||
const result = await commitCommand.execute(['--amend', '-m', 'Amended commit']);
|
const result = await commitCommand.execute(['--amend', '-m', 'Amended commit'], mockPwd);
|
||||||
|
|
||||||
expect(mockGit.log).toHaveBeenCalledWith({
|
expect(mockGit.log).toHaveBeenCalledWith({
|
||||||
dir: mockPwd,
|
dir: mockPwd,
|
||||||
@@ -119,7 +118,7 @@ describe('GitCommitCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should handle --amend flag without message', async () => {
|
it('should handle --amend flag without message', async () => {
|
||||||
const result = await commitCommand.execute(['--amend']);
|
const result = await commitCommand.execute(['--amend'], mockPwd);
|
||||||
|
|
||||||
expect(mockGit.log).toHaveBeenCalledWith({
|
expect(mockGit.log).toHaveBeenCalledWith({
|
||||||
dir: mockPwd,
|
dir: mockPwd,
|
||||||
@@ -135,7 +134,7 @@ describe('GitCommitCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should handle -a flag to stage all tracked modified files', async () => {
|
it('should handle -a flag to stage all tracked modified files', async () => {
|
||||||
const result = await commitCommand.execute(['-a', '-m', 'Commit with auto-stage']);
|
const result = await commitCommand.execute(['-a', '-m', 'Commit with auto-stage'], mockPwd);
|
||||||
|
|
||||||
// Should call add for the modified tracked file
|
// Should call add for the modified tracked file
|
||||||
expect(mockGit.add).toHaveBeenCalledWith({
|
expect(mockGit.add).toHaveBeenCalledWith({
|
||||||
@@ -165,7 +164,7 @@ describe('GitCommitCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should handle -am flag for combined auto-stage and message', async () => {
|
it('should handle -am flag for combined auto-stage and message', async () => {
|
||||||
const result = await commitCommand.execute(['-am', 'Combined flag commit']);
|
const result = await commitCommand.execute(['-am', 'Combined flag commit'], mockPwd);
|
||||||
|
|
||||||
// Should call add for the modified tracked file
|
// Should call add for the modified tracked file
|
||||||
expect(mockGit.add).toHaveBeenCalledWith({
|
expect(mockGit.add).toHaveBeenCalledWith({
|
||||||
@@ -192,7 +191,7 @@ describe('GitCommitCommand', () => {
|
|||||||
// Mock empty status
|
// Mock empty status
|
||||||
mockGit.statusMatrix = vi.fn().mockResolvedValue([]);
|
mockGit.statusMatrix = vi.fn().mockResolvedValue([]);
|
||||||
|
|
||||||
const result = await commitCommand.execute(['--allow-empty', '-m', 'Empty commit']);
|
const result = await commitCommand.execute(['--allow-empty', '-m', 'Empty commit'], mockPwd);
|
||||||
|
|
||||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
dir: mockPwd,
|
dir: mockPwd,
|
||||||
@@ -209,7 +208,7 @@ describe('GitCommitCommand', () => {
|
|||||||
['file1.txt', 1, 2, 1], // modified in workdir only
|
['file1.txt', 1, 2, 1], // modified in workdir only
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const result = await commitCommand.execute(['-m', 'Should fail']);
|
const result = await commitCommand.execute(['-m', 'Should fail'], mockPwd);
|
||||||
|
|
||||||
expect(mockGit.commit).not.toHaveBeenCalled();
|
expect(mockGit.commit).not.toHaveBeenCalled();
|
||||||
|
|
||||||
@@ -220,7 +219,7 @@ describe('GitCommitCommand', () => {
|
|||||||
it('should handle not being in a git repository', async () => {
|
it('should handle not being in a git repository', async () => {
|
||||||
mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory'));
|
mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory'));
|
||||||
|
|
||||||
const result = await commitCommand.execute(['-m', 'Test commit']);
|
const result = await commitCommand.execute(['-m', 'Test commit'], mockPwd);
|
||||||
|
|
||||||
expect(mockGit.commit).not.toHaveBeenCalled();
|
expect(mockGit.commit).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
|||||||
@@ -11,19 +11,17 @@ export class GitCommitCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -36,12 +34,12 @@ export class GitCommitCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// If -a flag is provided, stage all tracked files with modifications
|
// If -a flag is provided, stage all tracked files with modifications
|
||||||
if (options.addAll) {
|
if (options.addAll) {
|
||||||
await this.stageTrackedChanges();
|
await this.stageTrackedChanges(cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get current status
|
// Get current status
|
||||||
const statusMatrix = await this.git.statusMatrix({
|
const statusMatrix = await this.git.statusMatrix({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Check for staged changes
|
// Check for staged changes
|
||||||
@@ -58,8 +56,7 @@ export class GitCommitCommand implements GitSubcommand {
|
|||||||
// Get the last commit message if amending
|
// Get the last commit message if amending
|
||||||
try {
|
try {
|
||||||
const commits = await this.git.log({
|
const commits = await this.git.log({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
depth: 1,
|
depth: 1,
|
||||||
});
|
});
|
||||||
if (commits.length > 0 && !message) {
|
if (commits.length > 0 && !message) {
|
||||||
@@ -77,8 +74,7 @@ export class GitCommitCommand implements GitSubcommand {
|
|||||||
let currentBranch = 'main';
|
let currentBranch = 'main';
|
||||||
try {
|
try {
|
||||||
currentBranch = await this.git.currentBranch({
|
currentBranch = await this.git.currentBranch({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
}) || 'main';
|
}) || 'main';
|
||||||
} catch {
|
} catch {
|
||||||
// Use default
|
// Use default
|
||||||
@@ -90,7 +86,7 @@ export class GitCommitCommand implements GitSubcommand {
|
|||||||
message: string;
|
message: string;
|
||||||
parent?: string[];
|
parent?: string[];
|
||||||
} = {
|
} = {
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
message: commitMessage || 'Empty commit',
|
message: commitMessage || 'Empty commit',
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -98,7 +94,7 @@ export class GitCommitCommand implements GitSubcommand {
|
|||||||
// For amend, we need to reset to the parent of the current commit
|
// For amend, we need to reset to the parent of the current commit
|
||||||
try {
|
try {
|
||||||
const commits = await this.git.log({
|
const commits = await this.git.log({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
depth: 2,
|
depth: 2,
|
||||||
});
|
});
|
||||||
if (commits.length > 1) {
|
if (commits.length > 1) {
|
||||||
@@ -151,11 +147,11 @@ export class GitCommitCommand implements GitSubcommand {
|
|||||||
* Stage all tracked files with modifications
|
* Stage all tracked files with modifications
|
||||||
* This is used when the -a flag is provided
|
* This is used when the -a flag is provided
|
||||||
*/
|
*/
|
||||||
private async stageTrackedChanges(): Promise<void> {
|
private async stageTrackedChanges(cwd: string): Promise<void> {
|
||||||
try {
|
try {
|
||||||
// Get the status matrix
|
// Get the status matrix
|
||||||
const statusMatrix = await this.git.statusMatrix({
|
const statusMatrix = await this.git.statusMatrix({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Process each file based on its status
|
// Process each file based on its status
|
||||||
@@ -165,13 +161,13 @@ export class GitCommitCommand implements GitSubcommand {
|
|||||||
if (workdirStatus === 0) {
|
if (workdirStatus === 0) {
|
||||||
// File was deleted, use remove
|
// File was deleted, use remove
|
||||||
await this.git.remove({
|
await this.git.remove({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
filepath,
|
filepath,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// File was modified, use add
|
// File was modified, use add
|
||||||
await this.git.add({
|
await this.git.add({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
filepath,
|
filepath,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -218,4 +214,4 @@ export class GitCommitCommand implements GitSubcommand {
|
|||||||
|
|
||||||
return { options, message };
|
return { options, message };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,22 +11,20 @@ export class GitConfigCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
const { action, key, value, options } = this.parseArgs(args);
|
const { action, key, value, options } = this.parseArgs(args);
|
||||||
|
|
||||||
// Check if we're in a git repository (unless --global is used)
|
// Check if we're in a git repository (unless --global is used)
|
||||||
if (!options.global) {
|
if (!options.global) {
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -34,11 +32,11 @@ export class GitConfigCommand implements GitSubcommand {
|
|||||||
|
|
||||||
switch (action) {
|
switch (action) {
|
||||||
case 'list':
|
case 'list':
|
||||||
return await this.listConfig(options.global);
|
return await this.listConfig(options.global, cwd);
|
||||||
case 'get':
|
case 'get':
|
||||||
return await this.getConfig(key!, options.global);
|
return await this.getConfig(key!, options.global, cwd);
|
||||||
case 'set':
|
case 'set':
|
||||||
return await this.setConfig(key!, value!, options.global);
|
return await this.setConfig(key!, value!, options.global, cwd);
|
||||||
default:
|
default:
|
||||||
return createErrorResult('usage: git config [--global] <name> [<value>] | git config [--global] --list');
|
return createErrorResult('usage: git config [--global] <name> [<value>] | git config [--global] --list');
|
||||||
}
|
}
|
||||||
@@ -80,7 +78,7 @@ export class GitConfigCommand implements GitSubcommand {
|
|||||||
return { action, key, value, options };
|
return { action, key, value, options };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async listConfig(global: boolean): Promise<ShellCommandResult> {
|
private async listConfig(global: boolean, cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// For simplicity, we'll only show the most common config values
|
// For simplicity, we'll only show the most common config values
|
||||||
// isomorphic-git doesn't have a direct way to list all config
|
// isomorphic-git doesn't have a direct way to list all config
|
||||||
@@ -97,8 +95,7 @@ export class GitConfigCommand implements GitSubcommand {
|
|||||||
for (const key of commonKeys) {
|
for (const key of commonKeys) {
|
||||||
try {
|
try {
|
||||||
const value = await this.git.getConfig({
|
const value = await this.git.getConfig({
|
||||||
|
dir: global ? undefined : cwd,
|
||||||
dir: global ? undefined : this.pwd,
|
|
||||||
path: key,
|
path: key,
|
||||||
});
|
});
|
||||||
if (value !== undefined) {
|
if (value !== undefined) {
|
||||||
@@ -116,11 +113,10 @@ export class GitConfigCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async getConfig(key: string, global: boolean): Promise<ShellCommandResult> {
|
private async getConfig(key: string, global: boolean, cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
const value = await this.git.getConfig({
|
const value = await this.git.getConfig({
|
||||||
|
dir: global ? undefined : cwd,
|
||||||
dir: global ? undefined : this.pwd,
|
|
||||||
path: key,
|
path: key,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -135,10 +131,10 @@ export class GitConfigCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async setConfig(key: string, value: string, global: boolean): Promise<ShellCommandResult> {
|
private async setConfig(key: string, value: string, global: boolean, cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
await this.git.setConfig({
|
await this.git.setConfig({
|
||||||
dir: global ? undefined : this.pwd,
|
dir: global ? undefined : cwd,
|
||||||
path: key,
|
path: key,
|
||||||
value: value,
|
value: value,
|
||||||
});
|
});
|
||||||
@@ -149,4 +145,4 @@ export class GitConfigCommand implements GitSubcommand {
|
|||||||
return createErrorResult(`Failed to set config: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
return createErrorResult(`Failed to set config: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -50,7 +50,6 @@ const mockFS = {
|
|||||||
const mockOptions: GitSubcommandOptions = {
|
const mockOptions: GitSubcommandOptions = {
|
||||||
git: mockGit,
|
git: mockGit,
|
||||||
fs: mockFS,
|
fs: mockFS,
|
||||||
pwd: '/test/repo',
|
|
||||||
};
|
};
|
||||||
|
|
||||||
describe('GitDiffCommand', () => {
|
describe('GitDiffCommand', () => {
|
||||||
@@ -106,14 +105,14 @@ describe('GitDiffCommand', () => {
|
|||||||
} as unknown as JSRuntimeFS,
|
} as unknown as JSRuntimeFS,
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await commandWithoutGit.execute([]);
|
const result = await commandWithoutGit.execute([], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('fatal: not a git repository');
|
expect(result.stderr).toContain('fatal: not a git repository');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should show working directory diff for modified files', async () => {
|
it('should show working directory diff for modified files', async () => {
|
||||||
const result = await command.execute([]);
|
const result = await command.execute([], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('diff --git a/modified.txt b/modified.txt');
|
expect(result.stdout).toContain('diff --git a/modified.txt b/modified.txt');
|
||||||
@@ -125,7 +124,7 @@ describe('GitDiffCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT show untracked files in diff', async () => {
|
it('should NOT show untracked files in diff', async () => {
|
||||||
const result = await command.execute([]);
|
const result = await command.execute([], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
// Untracked files should not appear in git diff output
|
// Untracked files should not appear in git diff output
|
||||||
@@ -135,7 +134,7 @@ describe('GitDiffCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should show deleted files in diff', async () => {
|
it('should show deleted files in diff', async () => {
|
||||||
const result = await command.execute([]);
|
const result = await command.execute([], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('diff --git a/deleted.txt b/deleted.txt');
|
expect(result.stdout).toContain('diff --git a/deleted.txt b/deleted.txt');
|
||||||
@@ -146,7 +145,7 @@ describe('GitDiffCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should show staged diff with --cached option', async () => {
|
it('should show staged diff with --cached option', async () => {
|
||||||
const result = await command.execute(['--cached']);
|
const result = await command.execute(['--cached'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('diff --git a/staged.txt b/staged.txt');
|
expect(result.stdout).toContain('diff --git a/staged.txt b/staged.txt');
|
||||||
@@ -166,7 +165,7 @@ describe('GitDiffCommand', () => {
|
|||||||
} as unknown as Git,
|
} as unknown as Git,
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await commandWithStagedNew.execute(['--cached']);
|
const result = await commandWithStagedNew.execute(['--cached'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('diff --git a/new-staged.txt b/new-staged.txt');
|
expect(result.stdout).toContain('diff --git a/new-staged.txt b/new-staged.txt');
|
||||||
@@ -184,14 +183,14 @@ describe('GitDiffCommand', () => {
|
|||||||
} as unknown as Git,
|
} as unknown as Git,
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await commandWithNoChanges.execute([]);
|
const result = await commandWithNoChanges.execute([], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toBe('');
|
expect(result.stdout).toBe('');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should filter by path when specified', async () => {
|
it('should filter by path when specified', async () => {
|
||||||
const result = await command.execute(['--', 'modified.txt']);
|
const result = await command.execute(['--', 'modified.txt'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('diff --git a/modified.txt b/modified.txt');
|
expect(result.stdout).toContain('diff --git a/modified.txt b/modified.txt');
|
||||||
|
|||||||
@@ -12,19 +12,17 @@ export class GitDiffCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -33,16 +31,16 @@ export class GitDiffCommand implements GitSubcommand {
|
|||||||
|
|
||||||
if (options.cached || options.staged) {
|
if (options.cached || options.staged) {
|
||||||
// Show staged changes (index vs HEAD)
|
// Show staged changes (index vs HEAD)
|
||||||
return await this.showStagedDiff(paths);
|
return await this.showStagedDiff(paths, cwd);
|
||||||
} else if (commits.length === 0) {
|
} else if (commits.length === 0) {
|
||||||
// Show working directory changes vs index
|
// Show working directory changes vs index
|
||||||
return await this.showWorkingDirectoryDiff(paths);
|
return await this.showWorkingDirectoryDiff(paths, cwd);
|
||||||
} else if (commits.length === 1) {
|
} else if (commits.length === 1) {
|
||||||
// Show changes between commit and working directory
|
// Show changes between commit and working directory
|
||||||
return await this.showCommitDiff(commits[0], paths);
|
return await this.showCommitDiff(commits[0], paths, cwd);
|
||||||
} else if (commits.length === 2) {
|
} else if (commits.length === 2) {
|
||||||
// Show changes between two commits
|
// Show changes between two commits
|
||||||
return await this.showCommitRangeDiff(commits[0], commits[1], paths);
|
return await this.showCommitRangeDiff(commits[0], commits[1], paths, cwd);
|
||||||
} else {
|
} else {
|
||||||
return createErrorResult('usage: git diff [<commit>] [<commit>] [-- <path>...]');
|
return createErrorResult('usage: git diff [<commit>] [<commit>] [-- <path>...]');
|
||||||
}
|
}
|
||||||
@@ -82,11 +80,11 @@ export class GitDiffCommand implements GitSubcommand {
|
|||||||
return { commits, paths, options };
|
return { commits, paths, options };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async showWorkingDirectoryDiff(paths: string[]): Promise<ShellCommandResult> {
|
private async showWorkingDirectoryDiff(paths: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Get status to find changed files
|
// Get status to find changed files
|
||||||
const statusMatrix = await this.git.statusMatrix({
|
const statusMatrix = await this.git.statusMatrix({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Filter for files with working directory changes
|
// Filter for files with working directory changes
|
||||||
@@ -120,7 +118,7 @@ export class GitDiffCommand implements GitSubcommand {
|
|||||||
// For files in the index, read from HEAD as the baseline
|
// For files in the index, read from HEAD as the baseline
|
||||||
// This represents the last committed version for comparison
|
// This represents the last committed version for comparison
|
||||||
const headBlob = await this.git.readBlob({
|
const headBlob = await this.git.readBlob({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
oid: 'HEAD',
|
oid: 'HEAD',
|
||||||
filepath,
|
filepath,
|
||||||
});
|
});
|
||||||
@@ -135,7 +133,7 @@ export class GitDiffCommand implements GitSubcommand {
|
|||||||
let workdirContent = '';
|
let workdirContent = '';
|
||||||
if (workdirStatus === 2) {
|
if (workdirStatus === 2) {
|
||||||
try {
|
try {
|
||||||
workdirContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8');
|
workdirContent = await this.fs.readFile(`${cwd}/${filepath}`, 'utf8');
|
||||||
} catch {
|
} catch {
|
||||||
// File might be deleted
|
// File might be deleted
|
||||||
workdirContent = '';
|
workdirContent = '';
|
||||||
@@ -156,12 +154,12 @@ export class GitDiffCommand implements GitSubcommand {
|
|||||||
if (workdirStatus === 0 && (stageStatus === 1 || stageStatus === 2)) {
|
if (workdirStatus === 0 && (stageStatus === 1 || stageStatus === 2)) {
|
||||||
// Deleted file
|
// Deleted file
|
||||||
diffLines.push('deleted file mode 100644');
|
diffLines.push('deleted file mode 100644');
|
||||||
diffLines.push(`index ${this.getShortHash(indexContent)}..0000000`);
|
diffLines.push(`index ${this.getShortHash(indexContent, cwd)}..0000000`);
|
||||||
diffLines.push(`--- a/${filepath}`);
|
diffLines.push(`--- a/${filepath}`);
|
||||||
diffLines.push('+++ /dev/null');
|
diffLines.push('+++ /dev/null');
|
||||||
} else {
|
} else {
|
||||||
// Modified file
|
// Modified file
|
||||||
diffLines.push(`index ${this.getShortHash(indexContent)}..${this.getShortHash(workdirContent)} 100644`);
|
diffLines.push(`index ${this.getShortHash(indexContent, cwd)}..${this.getShortHash(workdirContent, cwd)} 100644`);
|
||||||
diffLines.push(`--- a/${filepath}`);
|
diffLines.push(`--- a/${filepath}`);
|
||||||
diffLines.push(`+++ b/${filepath}`);
|
diffLines.push(`+++ b/${filepath}`);
|
||||||
}
|
}
|
||||||
@@ -211,12 +209,11 @@ export class GitDiffCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async showCommitDiff(commit: string, _paths: string[]): Promise<ShellCommandResult> {
|
private async showCommitDiff(commit: string, _paths: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// For simplicity, show the commit message and changed files
|
// For simplicity, show the commit message and changed files
|
||||||
const commits = await this.git.log({
|
const commits = await this.git.log({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
depth: 1,
|
depth: 1,
|
||||||
ref: commit,
|
ref: commit,
|
||||||
});
|
});
|
||||||
@@ -245,16 +242,16 @@ export class GitDiffCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async showCommitRangeDiff(_commit1: string, _commit2: string, _paths: string[]): Promise<ShellCommandResult> {
|
private async showCommitRangeDiff(_commit1: string, _commit2: string, _paths: string[], _cwd: string): Promise<ShellCommandResult> {
|
||||||
// This would require complex implementation to compare two commits
|
// This would require complex implementation to compare two commits
|
||||||
return createErrorResult('Commit range diff is not implemented in this git command');
|
return createErrorResult('Commit range diff is not implemented in this git command');
|
||||||
}
|
}
|
||||||
|
|
||||||
private async showStagedDiff(paths: string[]): Promise<ShellCommandResult> {
|
private async showStagedDiff(paths: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Get status to find staged files
|
// Get status to find staged files
|
||||||
const statusMatrix = await this.git.statusMatrix({
|
const statusMatrix = await this.git.statusMatrix({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Filter for files with staged changes (index differs from HEAD)
|
// Filter for files with staged changes (index differs from HEAD)
|
||||||
@@ -282,7 +279,7 @@ export class GitDiffCommand implements GitSubcommand {
|
|||||||
if (headStatus === 1) {
|
if (headStatus === 1) {
|
||||||
try {
|
try {
|
||||||
const headBlob = await this.git.readBlob({
|
const headBlob = await this.git.readBlob({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
oid: 'HEAD',
|
oid: 'HEAD',
|
||||||
filepath,
|
filepath,
|
||||||
});
|
});
|
||||||
@@ -296,7 +293,7 @@ export class GitDiffCommand implements GitSubcommand {
|
|||||||
let stagedContent = '';
|
let stagedContent = '';
|
||||||
if (stageStatus === 1 || stageStatus === 2) {
|
if (stageStatus === 1 || stageStatus === 2) {
|
||||||
try {
|
try {
|
||||||
stagedContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8');
|
stagedContent = await this.fs.readFile(`${cwd}/${filepath}`, 'utf8');
|
||||||
} catch {
|
} catch {
|
||||||
stagedContent = '';
|
stagedContent = '';
|
||||||
}
|
}
|
||||||
@@ -308,18 +305,18 @@ export class GitDiffCommand implements GitSubcommand {
|
|||||||
if (headStatus === 0 && stageStatus === 2) {
|
if (headStatus === 0 && stageStatus === 2) {
|
||||||
// New file staged
|
// New file staged
|
||||||
diffLines.push('new file mode 100644');
|
diffLines.push('new file mode 100644');
|
||||||
diffLines.push(`index 0000000..${this.getShortHash(stagedContent)}`);
|
diffLines.push(`index 0000000..${this.getShortHash(stagedContent, cwd)}`);
|
||||||
diffLines.push('--- /dev/null');
|
diffLines.push('--- /dev/null');
|
||||||
diffLines.push(`+++ b/${filepath}`);
|
diffLines.push(`+++ b/${filepath}`);
|
||||||
} else if (headStatus === 1 && stageStatus === 0) {
|
} else if (headStatus === 1 && stageStatus === 0) {
|
||||||
// File deleted from stage
|
// File deleted from stage
|
||||||
diffLines.push('deleted file mode 100644');
|
diffLines.push('deleted file mode 100644');
|
||||||
diffLines.push(`index ${this.getShortHash(headContent)}..0000000`);
|
diffLines.push(`index ${this.getShortHash(headContent, cwd)}..0000000`);
|
||||||
diffLines.push(`--- a/${filepath}`);
|
diffLines.push(`--- a/${filepath}`);
|
||||||
diffLines.push('+++ /dev/null');
|
diffLines.push('+++ /dev/null');
|
||||||
} else {
|
} else {
|
||||||
// Modified file
|
// Modified file
|
||||||
diffLines.push(`index ${this.getShortHash(headContent)}..${this.getShortHash(stagedContent)} 100644`);
|
diffLines.push(`index ${this.getShortHash(headContent, cwd)}..${this.getShortHash(stagedContent, cwd)} 100644`);
|
||||||
diffLines.push(`--- a/${filepath}`);
|
diffLines.push(`--- a/${filepath}`);
|
||||||
diffLines.push(`+++ b/${filepath}`);
|
diffLines.push(`+++ b/${filepath}`);
|
||||||
}
|
}
|
||||||
@@ -367,7 +364,7 @@ export class GitDiffCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private getShortHash(content: string): string {
|
private getShortHash(content: string, _cwd: string): string {
|
||||||
// Simple hash for demo purposes - not a real git hash
|
// Simple hash for demo purposes - not a real git hash
|
||||||
let hash = 0;
|
let hash = 0;
|
||||||
for (let i = 0; i < content.length; i++) {
|
for (let i = 0; i < content.length; i++) {
|
||||||
@@ -377,4 +374,4 @@ export class GitDiffCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
return Math.abs(hash).toString(16).substring(0, 7).padStart(7, '0');
|
return Math.abs(hash).toString(16).substring(0, 7).padStart(7, '0');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -26,7 +26,6 @@ const mockFS = {
|
|||||||
const mockOptions: GitSubcommandOptions = {
|
const mockOptions: GitSubcommandOptions = {
|
||||||
git: mockGit,
|
git: mockGit,
|
||||||
fs: mockFS,
|
fs: mockFS,
|
||||||
pwd: '/test/repo',
|
|
||||||
};
|
};
|
||||||
|
|
||||||
describe('GitFetchCommand', () => {
|
describe('GitFetchCommand', () => {
|
||||||
@@ -144,21 +143,21 @@ describe('GitFetchCommand', () => {
|
|||||||
} as unknown as JSRuntimeFS,
|
} as unknown as JSRuntimeFS,
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await commandWithoutGit.execute([]);
|
const result = await commandWithoutGit.execute([], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('fatal: not a git repository');
|
expect(result.stderr).toContain('fatal: not a git repository');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fail when remote does not exist', async () => {
|
it('should fail when remote does not exist', async () => {
|
||||||
const result = await command.execute(['nonexistent']);
|
const result = await command.execute(['nonexistent'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain("fatal: 'nonexistent' does not appear to be a git repository");
|
expect(result.stderr).toContain("fatal: 'nonexistent' does not appear to be a git repository");
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch from default remote successfully', async () => {
|
it('should fetch from default remote successfully', async () => {
|
||||||
const result = await command.execute([]);
|
const result = await command.execute([], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
||||||
@@ -166,7 +165,7 @@ describe('GitFetchCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch from specific remote successfully', async () => {
|
it('should fetch from specific remote successfully', async () => {
|
||||||
const result = await command.execute(['upstream']);
|
const result = await command.execute(['upstream'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('From https://github.com/upstream/repo.git');
|
expect(result.stdout).toContain('From https://github.com/upstream/repo.git');
|
||||||
@@ -174,7 +173,7 @@ describe('GitFetchCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch specific refs successfully', async () => {
|
it('should fetch specific refs successfully', async () => {
|
||||||
const result = await command.execute(['origin', 'main']);
|
const result = await command.execute(['origin', 'main'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
||||||
@@ -182,7 +181,7 @@ describe('GitFetchCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch multiple specific refs successfully', async () => {
|
it('should fetch multiple specific refs successfully', async () => {
|
||||||
const result = await command.execute(['origin', 'main', 'develop']);
|
const result = await command.execute(['origin', 'main', 'develop'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
||||||
@@ -201,7 +200,7 @@ describe('GitFetchCommand', () => {
|
|||||||
} as unknown as Git,
|
} as unknown as Git,
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await commandWithAuthError.execute([]);
|
const result = await commandWithAuthError.execute([], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('fatal: Authentication failed');
|
expect(result.stderr).toContain('fatal: Authentication failed');
|
||||||
@@ -218,7 +217,7 @@ describe('GitFetchCommand', () => {
|
|||||||
} as unknown as Git,
|
} as unknown as Git,
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await commandWithNetworkError.execute([]);
|
const result = await commandWithNetworkError.execute([], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('fatal: unable to access remote repository');
|
expect(result.stderr).toContain('fatal: unable to access remote repository');
|
||||||
|
|||||||
@@ -11,19 +11,17 @@ export class GitFetchCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -34,7 +32,7 @@ export class GitFetchCommand implements GitSubcommand {
|
|||||||
let remoteUrl: string;
|
let remoteUrl: string;
|
||||||
try {
|
try {
|
||||||
const remotes = await this.git.listRemotes({
|
const remotes = await this.git.listRemotes({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
const targetRemote = remotes.find(r => r.remote === remote);
|
const targetRemote = remotes.find(r => r.remote === remote);
|
||||||
@@ -52,7 +50,7 @@ export class GitFetchCommand implements GitSubcommand {
|
|||||||
// Fetch specific refs
|
// Fetch specific refs
|
||||||
for (const ref of refs) {
|
for (const ref of refs) {
|
||||||
await this.git.fetch({
|
await this.git.fetch({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
remote: remote,
|
remote: remote,
|
||||||
ref: ref,
|
ref: ref,
|
||||||
});
|
});
|
||||||
@@ -60,7 +58,7 @@ export class GitFetchCommand implements GitSubcommand {
|
|||||||
} else {
|
} else {
|
||||||
// Fetch all refs (default behavior)
|
// Fetch all refs (default behavior)
|
||||||
await this.git.fetch({
|
await this.git.fetch({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
remote: remote,
|
remote: remote,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -74,7 +72,7 @@ export class GitFetchCommand implements GitSubcommand {
|
|||||||
for (const ref of refs) {
|
for (const ref of refs) {
|
||||||
try {
|
try {
|
||||||
await this.git.resolveRef({
|
await this.git.resolveRef({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: `refs/remotes/${remote}/${ref}`,
|
ref: `refs/remotes/${remote}/${ref}`,
|
||||||
});
|
});
|
||||||
lines.push(` * branch ${ref} -> ${remote}/${ref}`);
|
lines.push(` * branch ${ref} -> ${remote}/${ref}`);
|
||||||
@@ -170,4 +168,4 @@ export class GitFetchCommand implements GitSubcommand {
|
|||||||
|
|
||||||
return { remote, refs, options };
|
return { remote, refs, options };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,19 +11,17 @@ export class GitInitCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Parse arguments
|
// Parse arguments
|
||||||
const { options, directory } = this.parseArgs(args);
|
const { options, directory } = this.parseArgs(args);
|
||||||
const targetDir = directory || this.pwd;
|
const targetDir = directory || cwd;
|
||||||
|
|
||||||
// Check if directory exists, create if needed
|
// Check if directory exists, create if needed
|
||||||
if (directory) {
|
if (directory) {
|
||||||
@@ -88,4 +86,4 @@ export class GitInitCommand implements GitSubcommand {
|
|||||||
|
|
||||||
return { options, directory };
|
return { options, directory };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,19 +11,17 @@ export class GitLogCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -32,8 +30,7 @@ export class GitLogCommand implements GitSubcommand {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const commits = await this.git.log({
|
const commits = await this.git.log({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
depth: limit,
|
depth: limit,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -42,9 +39,9 @@ export class GitLogCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (options.oneline) {
|
if (options.oneline) {
|
||||||
return this.formatOnelineLog(commits);
|
return this.formatOnelineLog(commits, cwd);
|
||||||
} else {
|
} else {
|
||||||
return this.formatFullLog(commits, options.graph);
|
return this.formatFullLog(commits, options.graph, cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -103,7 +100,7 @@ export class GitLogCommand implements GitSubcommand {
|
|||||||
return { options, limit };
|
return { options, limit };
|
||||||
}
|
}
|
||||||
|
|
||||||
private formatOnelineLog(commits: Array<{ oid: string; commit: { message: string } }>): ShellCommandResult {
|
private formatOnelineLog(commits: Array<{ oid: string; commit: { message: string } }>, _cwd: string): ShellCommandResult {
|
||||||
const lines: string[] = [];
|
const lines: string[] = [];
|
||||||
|
|
||||||
for (const commit of commits) {
|
for (const commit of commits) {
|
||||||
@@ -115,7 +112,7 @@ export class GitLogCommand implements GitSubcommand {
|
|||||||
return createSuccessResult(lines.join('\n') + '\n');
|
return createSuccessResult(lines.join('\n') + '\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
private formatFullLog(commits: Array<{ oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number } } }>, showGraph: boolean): ShellCommandResult {
|
private formatFullLog(commits: Array<{ oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number } } }>, showGraph: boolean, _cwd: string): ShellCommandResult {
|
||||||
const lines: string[] = [];
|
const lines: string[] = [];
|
||||||
|
|
||||||
for (let i = 0; i < commits.length; i++) {
|
for (let i = 0; i < commits.length; i++) {
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ const mockFS = {
|
|||||||
const mockOptions: GitSubcommandOptions = {
|
const mockOptions: GitSubcommandOptions = {
|
||||||
git: mockGit,
|
git: mockGit,
|
||||||
fs: mockFS,
|
fs: mockFS,
|
||||||
pwd: '/test/repo',
|
|
||||||
};
|
};
|
||||||
|
|
||||||
describe('GitPullCommand', () => {
|
describe('GitPullCommand', () => {
|
||||||
@@ -107,10 +106,9 @@ describe('GitPullCommand', () => {
|
|||||||
const commandWithChanges = new GitPullCommand({
|
const commandWithChanges = new GitPullCommand({
|
||||||
git: mockGitWithChanges,
|
git: mockGitWithChanges,
|
||||||
fs: mockFSWithGit,
|
fs: mockFSWithGit,
|
||||||
pwd: '/test/repo',
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await commandWithChanges.execute(['origin', 'main']);
|
const result = await commandWithChanges.execute(['origin', 'main'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
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('error: Your local changes to the following files would be overwritten by merge:');
|
||||||
|
|||||||
@@ -11,19 +11,17 @@ export class GitPullCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -35,8 +33,7 @@ export class GitPullCommand implements GitSubcommand {
|
|||||||
let currentBranch: string | null = null;
|
let currentBranch: string | null = null;
|
||||||
try {
|
try {
|
||||||
currentBranch = await this.git.currentBranch({
|
currentBranch = await this.git.currentBranch({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
}) || null;
|
}) || null;
|
||||||
if (!targetBranch) {
|
if (!targetBranch) {
|
||||||
targetBranch = currentBranch || 'main';
|
targetBranch = currentBranch || 'main';
|
||||||
@@ -51,8 +48,7 @@ export class GitPullCommand implements GitSubcommand {
|
|||||||
let remoteUrl: string;
|
let remoteUrl: string;
|
||||||
try {
|
try {
|
||||||
const remotes = await this.git.listRemotes({
|
const remotes = await this.git.listRemotes({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const targetRemote = remotes.find(r => r.remote === remote);
|
const targetRemote = remotes.find(r => r.remote === remote);
|
||||||
@@ -66,7 +62,7 @@ export class GitPullCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Check for uncommitted changes
|
// Check for uncommitted changes
|
||||||
const statusMatrix = await this.git.statusMatrix({
|
const statusMatrix = await this.git.statusMatrix({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
const modifiedFiles = statusMatrix
|
const modifiedFiles = statusMatrix
|
||||||
@@ -84,7 +80,7 @@ export class GitPullCommand implements GitSubcommand {
|
|||||||
try {
|
try {
|
||||||
// Fetch from remote
|
// Fetch from remote
|
||||||
await this.git.fetch({
|
await this.git.fetch({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
remote: remote,
|
remote: remote,
|
||||||
ref: targetBranch,
|
ref: targetBranch,
|
||||||
});
|
});
|
||||||
@@ -94,8 +90,7 @@ export class GitPullCommand implements GitSubcommand {
|
|||||||
let remoteOid: string;
|
let remoteOid: string;
|
||||||
try {
|
try {
|
||||||
remoteOid = await this.git.resolveRef({
|
remoteOid = await this.git.resolveRef({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
ref: remoteRef,
|
ref: remoteRef,
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
@@ -106,15 +101,13 @@ export class GitPullCommand implements GitSubcommand {
|
|||||||
let currentOid: string;
|
let currentOid: string;
|
||||||
try {
|
try {
|
||||||
currentOid = await this.git.resolveRef({
|
currentOid = await this.git.resolveRef({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
ref: 'HEAD',
|
ref: 'HEAD',
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
// Empty repository, just checkout the remote branch
|
// Empty repository, just checkout the remote branch
|
||||||
await this.git.checkout({
|
await this.git.checkout({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
ref: targetBranch,
|
ref: targetBranch,
|
||||||
});
|
});
|
||||||
return createSuccessResult(`From ${remoteUrl}\n * branch ${targetBranch} -> FETCH_HEAD\nUpdating empty repository\nFast-forward\n`);
|
return createSuccessResult(`From ${remoteUrl}\n * branch ${targetBranch} -> FETCH_HEAD\nUpdating empty repository\nFast-forward\n`);
|
||||||
@@ -127,8 +120,7 @@ export class GitPullCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Perform fast-forward merge (simplified)
|
// Perform fast-forward merge (simplified)
|
||||||
await this.git.merge({
|
await this.git.merge({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
ours: currentBranch || 'HEAD',
|
ours: currentBranch || 'HEAD',
|
||||||
theirs: remoteRef,
|
theirs: remoteRef,
|
||||||
fastForwardOnly: true,
|
fastForwardOnly: true,
|
||||||
@@ -172,4 +164,4 @@ export class GitPullCommand implements GitSubcommand {
|
|||||||
|
|
||||||
return { remote, branch };
|
return { remote, branch };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -25,7 +25,6 @@ describe('GitPushCommand', () => {
|
|||||||
pushCommand = new GitPushCommand({
|
pushCommand = new GitPushCommand({
|
||||||
git: mockGit as Git,
|
git: mockGit as Git,
|
||||||
fs: mockFS as JSRuntimeFS,
|
fs: mockFS as JSRuntimeFS,
|
||||||
pwd: mockPwd,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -37,17 +36,16 @@ describe('GitPushCommand', () => {
|
|||||||
const cmd = new GitPushCommand({
|
const cmd = new GitPushCommand({
|
||||||
git: mockGit as Git,
|
git: mockGit as Git,
|
||||||
fs: mockFSNoRepo as JSRuntimeFS,
|
fs: mockFSNoRepo as JSRuntimeFS,
|
||||||
pwd: '/non-existent',
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await cmd.execute(['origin', 'main']);
|
const result = await cmd.execute(['origin', 'main'], mockPwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('not a git repository');
|
expect(result.stderr).toContain('not a git repository');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should fail when no remote is configured', async () => {
|
it('should fail when no remote is configured', async () => {
|
||||||
const result = await pushCommand.execute(['origin', 'main']);
|
const result = await pushCommand.execute(['origin', 'main'], mockPwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('does not appear to be a git repository');
|
expect(result.stderr).toContain('does not appear to be a git repository');
|
||||||
@@ -59,7 +57,7 @@ describe('GitPushCommand', () => {
|
|||||||
{ remote: 'origin', url: 'https://example.com/repo.git' },
|
{ remote: 'origin', url: 'https://example.com/repo.git' },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
await pushCommand.execute(['origin', 'main', '--force']);
|
await pushCommand.execute(['origin', 'main', '--force'], mockPwd);
|
||||||
|
|
||||||
// Verify that git.push was called with force: true
|
// Verify that git.push was called with force: true
|
||||||
expect(mockGit.push).toHaveBeenCalledWith(
|
expect(mockGit.push).toHaveBeenCalledWith(
|
||||||
@@ -75,7 +73,7 @@ describe('GitPushCommand', () => {
|
|||||||
{ remote: 'origin', url: 'https://example.com/repo.git' },
|
{ remote: 'origin', url: 'https://example.com/repo.git' },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
await pushCommand.execute(['origin', 'main', '-f']);
|
await pushCommand.execute(['origin', 'main', '-f'], mockPwd);
|
||||||
|
|
||||||
// Verify that git.push was called with force: true
|
// Verify that git.push was called with force: true
|
||||||
expect(mockGit.push).toHaveBeenCalledWith(
|
expect(mockGit.push).toHaveBeenCalledWith(
|
||||||
@@ -91,7 +89,7 @@ describe('GitPushCommand', () => {
|
|||||||
{ remote: 'origin', url: 'https://example.com/repo.git' },
|
{ remote: 'origin', url: 'https://example.com/repo.git' },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
await pushCommand.execute(['origin', 'main']);
|
await pushCommand.execute(['origin', 'main'], mockPwd);
|
||||||
|
|
||||||
// Verify that git.push was called with force: false
|
// Verify that git.push was called with force: false
|
||||||
expect(mockGit.push).toHaveBeenCalledWith(
|
expect(mockGit.push).toHaveBeenCalledWith(
|
||||||
|
|||||||
@@ -14,21 +14,19 @@ export class GitPushCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
private signer?: NostrSigner;
|
private signer?: NostrSigner;
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
this.signer = options.signer;
|
this.signer = options.signer;
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -40,8 +38,7 @@ export class GitPushCommand implements GitSubcommand {
|
|||||||
if (!targetBranch) {
|
if (!targetBranch) {
|
||||||
try {
|
try {
|
||||||
targetBranch = await this.git.currentBranch({
|
targetBranch = await this.git.currentBranch({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
}) || undefined;
|
}) || undefined;
|
||||||
if (!targetBranch) {
|
if (!targetBranch) {
|
||||||
return createErrorResult('fatal: You are not currently on a branch.');
|
return createErrorResult('fatal: You are not currently on a branch.');
|
||||||
@@ -55,7 +52,7 @@ export class GitPushCommand implements GitSubcommand {
|
|||||||
let remoteUrl: string;
|
let remoteUrl: string;
|
||||||
try {
|
try {
|
||||||
const remotes = await this.git.listRemotes({
|
const remotes = await this.git.listRemotes({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
const targetRemote = remotes.find(r => r.remote === remote);
|
const targetRemote = remotes.find(r => r.remote === remote);
|
||||||
@@ -71,7 +68,7 @@ export class GitPushCommand implements GitSubcommand {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await this.git.push({
|
await this.git.push({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
remote: remote,
|
remote: remote,
|
||||||
ref: targetBranch,
|
ref: targetBranch,
|
||||||
remoteRef: targetBranch,
|
remoteRef: targetBranch,
|
||||||
@@ -138,4 +135,4 @@ export class GitPushCommand implements GitSubcommand {
|
|||||||
|
|
||||||
return { remote, branch, options };
|
return { remote, branch, options };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -12,19 +12,17 @@ export class GitRemoteCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -33,13 +31,13 @@ export class GitRemoteCommand implements GitSubcommand {
|
|||||||
|
|
||||||
switch (action) {
|
switch (action) {
|
||||||
case 'list':
|
case 'list':
|
||||||
return await this.listRemotes(options.verbose);
|
return await this.listRemotes(options.verbose, cwd);
|
||||||
case 'add':
|
case 'add':
|
||||||
return await this.addRemote(name!, url!);
|
return await this.addRemote(name!, url!, cwd);
|
||||||
case 'remove':
|
case 'remove':
|
||||||
return await this.removeRemote(name!);
|
return await this.removeRemote(name!, cwd);
|
||||||
default:
|
default:
|
||||||
return await this.listRemotes(options.verbose);
|
return await this.listRemotes(options.verbose, cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -85,10 +83,10 @@ export class GitRemoteCommand implements GitSubcommand {
|
|||||||
return { action, name, url, options };
|
return { action, name, url, options };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async listRemotes(verbose: boolean): Promise<ShellCommandResult> {
|
private async listRemotes(verbose: boolean, cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
const remotes = await this.git.listRemotes({
|
const remotes = await this.git.listRemotes({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (remotes.length === 0) {
|
if (remotes.length === 0) {
|
||||||
@@ -115,7 +113,7 @@ export class GitRemoteCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async addRemote(name: string, url: string): Promise<ShellCommandResult> {
|
private async addRemote(name: string, url: string, cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
if (!name || !url) {
|
if (!name || !url) {
|
||||||
return createErrorResult('usage: git remote add <name> <url>');
|
return createErrorResult('usage: git remote add <name> <url>');
|
||||||
@@ -125,7 +123,7 @@ export class GitRemoteCommand implements GitSubcommand {
|
|||||||
try {
|
try {
|
||||||
const remotes = await this.git.listRemotes({
|
const remotes = await this.git.listRemotes({
|
||||||
|
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
const existingRemote = remotes.find(r => r.remote === name);
|
const existingRemote = remotes.find(r => r.remote === name);
|
||||||
@@ -138,7 +136,7 @@ export class GitRemoteCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Add the remote
|
// Add the remote
|
||||||
await this.git.addRemote({
|
await this.git.addRemote({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
remote: name,
|
remote: name,
|
||||||
url: url,
|
url: url,
|
||||||
});
|
});
|
||||||
@@ -150,7 +148,7 @@ export class GitRemoteCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async removeRemote(name: string): Promise<ShellCommandResult> {
|
private async removeRemote(name: string, cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
if (!name) {
|
if (!name) {
|
||||||
return createErrorResult('usage: git remote remove <name>');
|
return createErrorResult('usage: git remote remove <name>');
|
||||||
@@ -160,7 +158,7 @@ export class GitRemoteCommand implements GitSubcommand {
|
|||||||
try {
|
try {
|
||||||
const remotes = await this.git.listRemotes({
|
const remotes = await this.git.listRemotes({
|
||||||
|
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
const existingRemote = remotes.find(r => r.remote === name);
|
const existingRemote = remotes.find(r => r.remote === name);
|
||||||
@@ -173,7 +171,7 @@ export class GitRemoteCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Remove the remote
|
// Remove the remote
|
||||||
await this.git.deleteRemote({
|
await this.git.deleteRemote({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
remote: name,
|
remote: name,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -183,4 +181,4 @@ export class GitRemoteCommand implements GitSubcommand {
|
|||||||
return createErrorResult(`Failed to remove remote: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
return createErrorResult(`Failed to remove remote: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -56,7 +56,6 @@ const mockFS = {
|
|||||||
const mockOptions: GitSubcommandOptions = {
|
const mockOptions: GitSubcommandOptions = {
|
||||||
git: mockGit,
|
git: mockGit,
|
||||||
fs: mockFS,
|
fs: mockFS,
|
||||||
pwd: '/test/repo',
|
|
||||||
};
|
};
|
||||||
|
|
||||||
describe('GitResetCommand', () => {
|
describe('GitResetCommand', () => {
|
||||||
@@ -146,14 +145,14 @@ describe('GitResetCommand', () => {
|
|||||||
} as unknown as JSRuntimeFS,
|
} as unknown as JSRuntimeFS,
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await commandWithoutGit.execute([]);
|
const result = await commandWithoutGit.execute([], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('fatal: not a git repository');
|
expect(result.stderr).toContain('fatal: not a git repository');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should unstage all files when called without arguments', async () => {
|
it('should unstage all files when called without arguments', async () => {
|
||||||
const result = await command.execute([]);
|
const result = await command.execute([], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('Unstaged changes after reset:');
|
expect(result.stdout).toContain('Unstaged changes after reset:');
|
||||||
@@ -165,7 +164,7 @@ describe('GitResetCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should unstage all files when called with HEAD', async () => {
|
it('should unstage all files when called with HEAD', async () => {
|
||||||
const result = await command.execute(['HEAD']);
|
const result = await command.execute(['HEAD'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('Unstaged changes after reset:');
|
expect(result.stdout).toContain('Unstaged changes after reset:');
|
||||||
@@ -174,7 +173,7 @@ describe('GitResetCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should unstage specific files when called with HEAD and file paths', async () => {
|
it('should unstage specific files when called with HEAD and file paths', async () => {
|
||||||
const result = await command.execute(['HEAD', 'staged.txt']);
|
const result = await command.execute(['HEAD', 'staged.txt'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('Unstaged changes after reset:');
|
expect(result.stdout).toContain('Unstaged changes after reset:');
|
||||||
@@ -194,7 +193,7 @@ describe('GitResetCommand', () => {
|
|||||||
} as unknown as Git,
|
} as unknown as Git,
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await commandWithNoStaged.execute([]);
|
const result = await commandWithNoStaged.execute([], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toBe('');
|
expect(result.stdout).toBe('');
|
||||||
@@ -214,35 +213,35 @@ describe('GitResetCommand', () => {
|
|||||||
} as unknown as Git,
|
} as unknown as Git,
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await commandWithError.execute(['HEAD', 'nonexistent.txt']);
|
const result = await commandWithError.execute(['HEAD', 'nonexistent.txt'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain("error: pathspec 'nonexistent.txt' did not match any file(s) known to git");
|
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 () => {
|
it('should handle commit reset with hard mode', async () => {
|
||||||
const result = await command.execute(['--hard', 'HEAD~1']);
|
const result = await command.execute(['--hard', 'HEAD~1'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('HEAD is now at def456a');
|
expect(result.stdout).toContain('HEAD is now at def456a');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle commit reset with mixed mode', async () => {
|
it('should handle commit reset with mixed mode', async () => {
|
||||||
const result = await command.execute(['--mixed', 'HEAD~1']);
|
const result = await command.execute(['--mixed', 'HEAD~1'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('HEAD is now at def456a');
|
expect(result.stdout).toContain('HEAD is now at def456a');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return error for soft reset (not implemented)', async () => {
|
it('should return error for soft reset (not implemented)', async () => {
|
||||||
const result = await command.execute(['--soft', 'HEAD~1']);
|
const result = await command.execute(['--soft', 'HEAD~1'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('--soft reset is not implemented');
|
expect(result.stderr).toContain('--soft reset is not implemented');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle invalid commit reference', async () => {
|
it('should handle invalid commit reference', async () => {
|
||||||
const result = await command.execute(['abcdef12345']);
|
const result = await command.execute(['abcdef12345'], '/test/repo');
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain("fatal: ambiguous argument 'abcdef12345'");
|
expect(result.stderr).toContain("fatal: ambiguous argument 'abcdef12345'");
|
||||||
|
|||||||
@@ -12,19 +12,17 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -33,10 +31,10 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
|
|
||||||
if (isFileReset) {
|
if (isFileReset) {
|
||||||
// Reset specific files or all files (unstage)
|
// Reset specific files or all files (unstage)
|
||||||
return await this.resetFiles(files);
|
return await this.resetFiles(files, cwd);
|
||||||
} else {
|
} else {
|
||||||
// Reset to commit
|
// Reset to commit
|
||||||
return await this.resetToCommit(target, mode);
|
return await this.resetToCommit(target, mode, cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -89,7 +87,7 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
return { mode, target, files, isFileReset };
|
return { mode, target, files, isFileReset };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async resetFiles(files: string[]): Promise<ShellCommandResult> {
|
private async resetFiles(files: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
const resetFiles: string[] = [];
|
const resetFiles: string[] = [];
|
||||||
const errors: string[] = [];
|
const errors: string[] = [];
|
||||||
@@ -99,7 +97,7 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
try {
|
try {
|
||||||
// Get the status matrix to find all staged files
|
// Get the status matrix to find all staged files
|
||||||
const statusMatrix = await this.git.statusMatrix({
|
const statusMatrix = await this.git.statusMatrix({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Find files that are staged (differ from HEAD)
|
// Find files that are staged (differ from HEAD)
|
||||||
@@ -117,7 +115,7 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
for (const file of stagedFiles) {
|
for (const file of stagedFiles) {
|
||||||
try {
|
try {
|
||||||
await this.git.resetIndex({
|
await this.git.resetIndex({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
filepath: file,
|
filepath: file,
|
||||||
});
|
});
|
||||||
resetFiles.push(file);
|
resetFiles.push(file);
|
||||||
@@ -134,7 +132,7 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
try {
|
try {
|
||||||
// Remove from staging area (reset to HEAD)
|
// Remove from staging area (reset to HEAD)
|
||||||
await this.git.resetIndex({
|
await this.git.resetIndex({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
filepath: file,
|
filepath: file,
|
||||||
});
|
});
|
||||||
resetFiles.push(file);
|
resetFiles.push(file);
|
||||||
@@ -159,14 +157,13 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async resetToCommit(target: string, mode: 'soft' | 'mixed' | 'hard'): Promise<ShellCommandResult> {
|
private async resetToCommit(target: string, mode: 'soft' | 'mixed' | 'hard', cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Resolve the target commit
|
// Resolve the target commit
|
||||||
let targetOid: string;
|
let targetOid: string;
|
||||||
try {
|
try {
|
||||||
targetOid = await this.git.resolveRef({
|
targetOid = await this.git.resolveRef({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
ref: target,
|
ref: target,
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
@@ -177,8 +174,7 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
let currentOid: string;
|
let currentOid: string;
|
||||||
try {
|
try {
|
||||||
currentOid = await this.git.resolveRef({
|
currentOid = await this.git.resolveRef({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
ref: 'HEAD',
|
ref: 'HEAD',
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
@@ -205,7 +201,7 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
let currentBranch: string | null = null;
|
let currentBranch: string | null = null;
|
||||||
try {
|
try {
|
||||||
currentBranch = await this.git.currentBranch({
|
currentBranch = await this.git.currentBranch({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
}) || null;
|
}) || null;
|
||||||
} catch {
|
} catch {
|
||||||
// Detached HEAD state
|
// Detached HEAD state
|
||||||
@@ -215,14 +211,14 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
if (currentOid !== targetOid) {
|
if (currentOid !== targetOid) {
|
||||||
if (currentBranch) {
|
if (currentBranch) {
|
||||||
await this.git.writeRef({
|
await this.git.writeRef({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: `refs/heads/${currentBranch}`,
|
ref: `refs/heads/${currentBranch}`,
|
||||||
value: targetOid,
|
value: targetOid,
|
||||||
force: true,
|
force: true,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
await this.git.writeRef({
|
await this.git.writeRef({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: 'HEAD',
|
ref: 'HEAD',
|
||||||
value: targetOid,
|
value: targetOid,
|
||||||
force: true,
|
force: true,
|
||||||
@@ -233,7 +229,7 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
// Reset the index only (not the working directory)
|
// Reset the index only (not the working directory)
|
||||||
// Using noCheckout: true to only update the index, not the working directory
|
// Using noCheckout: true to only update the index, not the working directory
|
||||||
await this.git.checkout({
|
await this.git.checkout({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: targetOid,
|
ref: targetOid,
|
||||||
noCheckout: true,
|
noCheckout: true,
|
||||||
noUpdateHead: true,
|
noUpdateHead: true,
|
||||||
@@ -253,7 +249,7 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Get the commit object to ensure it exists
|
// Get the commit object to ensure it exists
|
||||||
await this.git.readCommit({
|
await this.git.readCommit({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
oid: targetOid,
|
oid: targetOid,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -261,7 +257,7 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
let currentBranch: string | null = null;
|
let currentBranch: string | null = null;
|
||||||
try {
|
try {
|
||||||
currentBranch = await this.git.currentBranch({
|
currentBranch = await this.git.currentBranch({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
}) || null;
|
}) || null;
|
||||||
} catch {
|
} catch {
|
||||||
// Detached HEAD state
|
// Detached HEAD state
|
||||||
@@ -272,14 +268,14 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
if (currentOid !== targetOid) {
|
if (currentOid !== targetOid) {
|
||||||
if (currentBranch) {
|
if (currentBranch) {
|
||||||
await this.git.writeRef({
|
await this.git.writeRef({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: `refs/heads/${currentBranch}`,
|
ref: `refs/heads/${currentBranch}`,
|
||||||
value: targetOid,
|
value: targetOid,
|
||||||
force: true,
|
force: true,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
await this.git.writeRef({
|
await this.git.writeRef({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: 'HEAD',
|
ref: 'HEAD',
|
||||||
value: targetOid,
|
value: targetOid,
|
||||||
force: true,
|
force: true,
|
||||||
@@ -291,7 +287,7 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
// Using noUpdateHead: true because we already updated HEAD above
|
// Using noUpdateHead: true because we already updated HEAD above
|
||||||
// Using force: true to overwrite any local changes
|
// Using force: true to overwrite any local changes
|
||||||
await this.git.checkout({
|
await this.git.checkout({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: targetOid,
|
ref: targetOid,
|
||||||
force: true,
|
force: true,
|
||||||
noUpdateHead: true,
|
noUpdateHead: true,
|
||||||
@@ -310,4 +306,4 @@ export class GitResetCommand implements GitSubcommand {
|
|||||||
return createErrorResult(`Failed to reset: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
return createErrorResult(`Failed to reset: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -319,12 +319,11 @@ describe('GitShowCommand', () => {
|
|||||||
showCommand = new GitShowCommand({
|
showCommand = new GitShowCommand({
|
||||||
git: mockGit as Git,
|
git: mockGit as Git,
|
||||||
fs: mockFS as JSRuntimeFS,
|
fs: mockFS as JSRuntimeFS,
|
||||||
pwd: mockPwd,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should show basic commit information', async () => {
|
it('should show basic commit information', async () => {
|
||||||
const result = await showCommand.execute(['simple-commit']);
|
const result = await showCommand.execute(['simple-commit'], mockPwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('commit simple-commit');
|
expect(result.stdout).toContain('commit simple-commit');
|
||||||
@@ -333,7 +332,7 @@ describe('GitShowCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should handle initial commits properly', async () => {
|
it('should handle initial commits properly', async () => {
|
||||||
const result = await showCommand.execute(['initial-commit']);
|
const result = await showCommand.execute(['initial-commit'], mockPwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('Initial commit');
|
expect(result.stdout).toContain('Initial commit');
|
||||||
@@ -344,7 +343,7 @@ describe('GitShowCommand', () => {
|
|||||||
|
|
||||||
it('should resolve HEAD~1 correctly', async () => {
|
it('should resolve HEAD~1 correctly', async () => {
|
||||||
// First, check that the implementation correctly resolves HEAD~1
|
// First, check that the implementation correctly resolves HEAD~1
|
||||||
const result = await showCommand.execute(['HEAD~1']);
|
const result = await showCommand.execute(['HEAD~1'], mockPwd);
|
||||||
|
|
||||||
// Verify that resolveRef was called with HEAD
|
// Verify that resolveRef was called with HEAD
|
||||||
expect(mockGit.resolveRef).toHaveBeenCalledWith({
|
expect(mockGit.resolveRef).toHaveBeenCalledWith({
|
||||||
@@ -363,7 +362,7 @@ describe('GitShowCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should resolve HEAD^2 correctly', async () => {
|
it('should resolve HEAD^2 correctly', async () => {
|
||||||
const result = await showCommand.execute(['HEAD^2']);
|
const result = await showCommand.execute(['HEAD^2'], mockPwd);
|
||||||
|
|
||||||
// Verify that resolveRef was called with HEAD
|
// Verify that resolveRef was called with HEAD
|
||||||
expect(mockGit.resolveRef).toHaveBeenCalledWith({
|
expect(mockGit.resolveRef).toHaveBeenCalledWith({
|
||||||
@@ -411,7 +410,7 @@ describe('GitShowCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Execute the command
|
// Execute the command
|
||||||
const result = await showCommand.execute(['simple-commit']);
|
const result = await showCommand.execute(['simple-commit'], mockPwd);
|
||||||
|
|
||||||
// Check that the command output contains the commit message
|
// Check that the command output contains the commit message
|
||||||
expect(result.stdout).toContain('Simple changes');
|
expect(result.stdout).toContain('Simple changes');
|
||||||
@@ -569,7 +568,7 @@ describe('GitShowCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Execute the command
|
// Execute the command
|
||||||
const result = await showCommand.execute(['diff-test-commit']);
|
const result = await showCommand.execute(['diff-test-commit'], mockPwd);
|
||||||
|
|
||||||
// Debug output
|
// Debug output
|
||||||
console.log('Test output:', result.stdout);
|
console.log('Test output:', result.stdout);
|
||||||
@@ -596,7 +595,7 @@ describe('GitShowCommand', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should return an error for invalid references', async () => {
|
it('should return an error for invalid references', async () => {
|
||||||
const result = await showCommand.execute(['non-existent-ref']);
|
const result = await showCommand.execute(['non-existent-ref'], mockPwd);
|
||||||
|
|
||||||
expect(result.exitCode).not.toBe(0);
|
expect(result.exitCode).not.toBe(0);
|
||||||
expect(result.stderr).toContain('bad revision');
|
expect(result.stderr).toContain('bad revision');
|
||||||
@@ -605,7 +604,7 @@ describe('GitShowCommand', () => {
|
|||||||
it('should return an error when not in a git repository', async () => {
|
it('should return an error when not in a git repository', async () => {
|
||||||
mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory'));
|
mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory'));
|
||||||
|
|
||||||
const result = await showCommand.execute([]);
|
const result = await showCommand.execute([], mockPwd);
|
||||||
|
|
||||||
expect(result.exitCode).not.toBe(0);
|
expect(result.exitCode).not.toBe(0);
|
||||||
expect(result.stderr).toContain('not a git repository');
|
expect(result.stderr).toContain('not a git repository');
|
||||||
|
|||||||
@@ -11,19 +11,17 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -31,12 +29,12 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
const { commit } = this.parseArgs(args);
|
const { commit } = this.parseArgs(args);
|
||||||
|
|
||||||
// Resolve the commit reference (handling relative refs like HEAD~1)
|
// Resolve the commit reference (handling relative refs like HEAD~1)
|
||||||
const resolvedCommit = await this.resolveCommitRef(commit);
|
const resolvedCommit = await this.resolveCommitRef(commit, cwd);
|
||||||
if (!resolvedCommit) {
|
if (!resolvedCommit) {
|
||||||
return createErrorResult(`fatal: bad revision '${commit}'`);
|
return createErrorResult(`fatal: bad revision '${commit}'`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return await this.showCommit(resolvedCommit);
|
return await this.showCommit(resolvedCommit, cwd);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return createErrorResult(`git show: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
return createErrorResult(`git show: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||||
@@ -59,7 +57,7 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
/**
|
/**
|
||||||
* Resolve a commit reference, handling special syntax like HEAD~N and HEAD^N
|
* Resolve a commit reference, handling special syntax like HEAD~N and HEAD^N
|
||||||
*/
|
*/
|
||||||
private async resolveCommitRef(ref: string): Promise<string | null> {
|
private async resolveCommitRef(ref: string, cwd: string): Promise<string | null> {
|
||||||
try {
|
try {
|
||||||
// Handle HEAD~N syntax (ancestor)
|
// Handle HEAD~N syntax (ancestor)
|
||||||
const tildeMatch = ref.match(/^(.+)~(\d+)$/);
|
const tildeMatch = ref.match(/^(.+)~(\d+)$/);
|
||||||
@@ -69,17 +67,17 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
|
|
||||||
if (numSteps === 0) {
|
if (numSteps === 0) {
|
||||||
// ~0 is the commit itself
|
// ~0 is the commit itself
|
||||||
return this.resolveCommitRef(baseRef);
|
return this.resolveCommitRef(baseRef, cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
// First resolve the base reference
|
// First resolve the base reference
|
||||||
const baseCommit = await this.resolveCommitRef(baseRef);
|
const baseCommit = await this.resolveCommitRef(baseRef, cwd);
|
||||||
if (!baseCommit) {
|
if (!baseCommit) {
|
||||||
throw new Error(`Could not resolve base reference: ${baseRef}`);
|
throw new Error(`Could not resolve base reference: ${baseRef}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Walk back N steps in history
|
// Walk back N steps in history
|
||||||
return this.walkBackNCommits(baseCommit, numSteps);
|
return this.walkBackNCommits(baseCommit, numSteps, cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle HEAD^N syntax (Nth parent)
|
// Handle HEAD^N syntax (Nth parent)
|
||||||
@@ -89,19 +87,19 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
const parentIndex = parentNum ? parseInt(parentNum, 10) - 1 : 0; // Default to first parent
|
const parentIndex = parentNum ? parseInt(parentNum, 10) - 1 : 0; // Default to first parent
|
||||||
|
|
||||||
// First resolve the base reference
|
// First resolve the base reference
|
||||||
const baseCommit = await this.resolveCommitRef(baseRef);
|
const baseCommit = await this.resolveCommitRef(baseRef, cwd);
|
||||||
if (!baseCommit) {
|
if (!baseCommit) {
|
||||||
throw new Error(`Could not resolve base reference: ${baseRef}`);
|
throw new Error(`Could not resolve base reference: ${baseRef}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the specified parent
|
// Get the specified parent
|
||||||
return this.getNthParent(baseCommit, parentIndex);
|
return this.getNthParent(baseCommit, parentIndex, cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle simple reference (direct resolution)
|
// Handle simple reference (direct resolution)
|
||||||
try {
|
try {
|
||||||
return await this.git.resolveRef({
|
return await this.git.resolveRef({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref,
|
ref,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -119,14 +117,14 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
/**
|
/**
|
||||||
* Walk back N commits from the given commit
|
* Walk back N commits from the given commit
|
||||||
*/
|
*/
|
||||||
private async walkBackNCommits(startCommit: string, steps: number): Promise<string | null> {
|
private async walkBackNCommits(startCommit: string, steps: number, cwd: string): Promise<string | null> {
|
||||||
try {
|
try {
|
||||||
let currentCommit = startCommit;
|
let currentCommit = startCommit;
|
||||||
|
|
||||||
for (let i = 0; i < steps; i++) {
|
for (let i = 0; i < steps; i++) {
|
||||||
// Get the commit object
|
// Get the commit object
|
||||||
const commit = await this.git.readCommit({
|
const commit = await this.git.readCommit({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
oid: currentCommit,
|
oid: currentCommit,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -149,11 +147,11 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
/**
|
/**
|
||||||
* Get the Nth parent of the given commit
|
* Get the Nth parent of the given commit
|
||||||
*/
|
*/
|
||||||
private async getNthParent(commit: string, parentIndex: number): Promise<string | null> {
|
private async getNthParent(commit: string, parentIndex: number, cwd: string): Promise<string | null> {
|
||||||
try {
|
try {
|
||||||
// Get the commit object
|
// Get the commit object
|
||||||
const commitObj = await this.git.readCommit({
|
const commitObj = await this.git.readCommit({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
oid: commit,
|
oid: commit,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -175,11 +173,11 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async showCommit(commitRef: string): Promise<ShellCommandResult> {
|
private async showCommit(commitRef: string, cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Get the commit
|
// Get the commit
|
||||||
const commits = await this.git.log({
|
const commits = await this.git.log({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
depth: 1,
|
depth: 1,
|
||||||
ref: commitRef,
|
ref: commitRef,
|
||||||
});
|
});
|
||||||
@@ -220,7 +218,7 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Get the tree for this commit
|
// Get the tree for this commit
|
||||||
const tree = await this.git.readTree({
|
const tree = await this.git.readTree({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
oid: commit.oid,
|
oid: commit.oid,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -237,12 +235,12 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Get the trees for both commits
|
// Get the trees for both commits
|
||||||
const parentTree = await this.git.readTree({
|
const parentTree = await this.git.readTree({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
oid: parentCommit,
|
oid: parentCommit,
|
||||||
});
|
});
|
||||||
|
|
||||||
const commitTree = await this.git.readTree({
|
const commitTree = await this.git.readTree({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
oid: commit.oid,
|
oid: commit.oid,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -285,7 +283,7 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
const result = new Map<string, TreeEntry>();
|
const result = new Map<string, TreeEntry>();
|
||||||
try {
|
try {
|
||||||
const tree = await this.git.readTree({
|
const tree = await this.git.readTree({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
oid,
|
oid,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -435,7 +433,7 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
let parentContent = '';
|
let parentContent = '';
|
||||||
try {
|
try {
|
||||||
const parentBlob = await this.git.readBlob({
|
const parentBlob = await this.git.readBlob({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
oid: parentCommit,
|
oid: parentCommit,
|
||||||
filepath: change.path,
|
filepath: change.path,
|
||||||
});
|
});
|
||||||
@@ -449,7 +447,7 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
let currentContent = '';
|
let currentContent = '';
|
||||||
try {
|
try {
|
||||||
const currentBlob = await this.git.readBlob({
|
const currentBlob = await this.git.readBlob({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
oid: commit.oid,
|
oid: commit.oid,
|
||||||
filepath: change.path,
|
filepath: change.path,
|
||||||
});
|
});
|
||||||
@@ -689,4 +687,4 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
return createErrorResult(`Failed to show commit: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
return createErrorResult(`Failed to show commit: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -65,7 +65,6 @@ describe('GitStashCommand', () => {
|
|||||||
stashCommand = new GitStashCommand({
|
stashCommand = new GitStashCommand({
|
||||||
git: mockGit,
|
git: mockGit,
|
||||||
fs: mockFS,
|
fs: mockFS,
|
||||||
pwd: testCwd,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -78,14 +77,14 @@ describe('GitStashCommand', () => {
|
|||||||
it('should return error when not in a git repository', async () => {
|
it('should return error when not in a git repository', async () => {
|
||||||
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['push']);
|
const result = await stashCommand.execute(['push'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('fatal: not a git repository');
|
expect(result.stderr).toContain('fatal: not a git repository');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should show help with --help flag', async () => {
|
it('should show help with --help flag', async () => {
|
||||||
const result = await stashCommand.execute(['--help']);
|
const result = await stashCommand.execute(['--help'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('git stash list');
|
expect(result.stdout).toContain('git stash list');
|
||||||
@@ -99,7 +98,7 @@ describe('GitStashCommand', () => {
|
|||||||
['unchanged.txt', 1, 1, 1], // No changes
|
['unchanged.txt', 1, 1, 1], // No changes
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const result = await stashCommand.execute(['push']);
|
const result = await stashCommand.execute(['push'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('No local changes to save');
|
expect(result.stderr).toContain('No local changes to save');
|
||||||
@@ -119,7 +118,7 @@ describe('GitStashCommand', () => {
|
|||||||
return Promise.resolve('');
|
return Promise.resolve('');
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await stashCommand.execute(['push']);
|
const result = await stashCommand.execute(['push'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('Saved working directory and index state');
|
expect(result.stdout).toContain('Saved working directory and index state');
|
||||||
@@ -145,7 +144,7 @@ describe('GitStashCommand', () => {
|
|||||||
return Promise.resolve('');
|
return Promise.resolve('');
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await stashCommand.execute(['push', '-m', 'my custom message']);
|
const result = await stashCommand.execute(['push', '-m', 'my custom message'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('my custom message');
|
expect(result.stdout).toContain('my custom message');
|
||||||
@@ -165,7 +164,7 @@ describe('GitStashCommand', () => {
|
|||||||
return Promise.resolve('');
|
return Promise.resolve('');
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await stashCommand.execute(['push', '-u']);
|
const result = await stashCommand.execute(['push', '-u'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('Saved working directory');
|
expect(result.stdout).toContain('Saved working directory');
|
||||||
@@ -183,7 +182,7 @@ describe('GitStashCommand', () => {
|
|||||||
return Promise.resolve('');
|
return Promise.resolve('');
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await stashCommand.execute(['push']);
|
const result = await stashCommand.execute(['push'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(mockGit.checkout).toHaveBeenCalledWith({
|
expect(mockGit.checkout).toHaveBeenCalledWith({
|
||||||
@@ -207,7 +206,7 @@ describe('GitStashCommand', () => {
|
|||||||
return Promise.resolve('');
|
return Promise.resolve('');
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await stashCommand.execute(['push']);
|
const result = await stashCommand.execute(['push'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(mockGit.resetIndex).toHaveBeenCalledWith({
|
expect(mockGit.resetIndex).toHaveBeenCalledWith({
|
||||||
@@ -221,7 +220,7 @@ describe('GitStashCommand', () => {
|
|||||||
it('should return empty when no stashes', async () => {
|
it('should return empty when no stashes', async () => {
|
||||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['list']);
|
const result = await stashCommand.execute(['list'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toBe('');
|
expect(result.stdout).toBe('');
|
||||||
@@ -234,7 +233,7 @@ describe('GitStashCommand', () => {
|
|||||||
];
|
];
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['list']);
|
const result = await stashCommand.execute(['list'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('stash@{0}: first stash');
|
expect(result.stdout).toContain('stash@{0}: first stash');
|
||||||
@@ -246,7 +245,7 @@ describe('GitStashCommand', () => {
|
|||||||
it('should return error when no stashes', async () => {
|
it('should return error when no stashes', async () => {
|
||||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['show']);
|
const result = await stashCommand.execute(['show'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('No stash entries found');
|
expect(result.stderr).toContain('No stash entries found');
|
||||||
@@ -267,7 +266,7 @@ describe('GitStashCommand', () => {
|
|||||||
];
|
];
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['show']);
|
const result = await stashCommand.execute(['show'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('M\tmodified.txt');
|
expect(result.stdout).toContain('M\tmodified.txt');
|
||||||
@@ -293,7 +292,7 @@ describe('GitStashCommand', () => {
|
|||||||
];
|
];
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['show', 'stash@{1}']);
|
const result = await stashCommand.execute(['show', 'stash@{1}'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('file1.txt');
|
expect(result.stdout).toContain('file1.txt');
|
||||||
@@ -305,7 +304,7 @@ describe('GitStashCommand', () => {
|
|||||||
it('should return error when no stashes', async () => {
|
it('should return error when no stashes', async () => {
|
||||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['apply']);
|
const result = await stashCommand.execute(['apply'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('No stash entries found');
|
expect(result.stderr).toContain('No stash entries found');
|
||||||
@@ -325,7 +324,7 @@ describe('GitStashCommand', () => {
|
|||||||
];
|
];
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['apply']);
|
const result = await stashCommand.execute(['apply'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('test stash');
|
expect(result.stdout).toContain('test stash');
|
||||||
@@ -358,7 +357,7 @@ describe('GitStashCommand', () => {
|
|||||||
];
|
];
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['apply', 'stash@{1}']);
|
const result = await stashCommand.execute(['apply', 'stash@{1}'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||||
@@ -379,7 +378,7 @@ describe('GitStashCommand', () => {
|
|||||||
];
|
];
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['apply']);
|
const result = await stashCommand.execute(['apply'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(mockFS.unlink).toHaveBeenCalledWith(expect.stringContaining('deleted.txt'));
|
expect(mockFS.unlink).toHaveBeenCalledWith(expect.stringContaining('deleted.txt'));
|
||||||
@@ -399,7 +398,7 @@ describe('GitStashCommand', () => {
|
|||||||
];
|
];
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['pop']);
|
const result = await stashCommand.execute(['pop'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||||
@@ -418,7 +417,7 @@ describe('GitStashCommand', () => {
|
|||||||
it('should return error when no stashes', async () => {
|
it('should return error when no stashes', async () => {
|
||||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['drop']);
|
const result = await stashCommand.execute(['drop'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('No stash entries found');
|
expect(result.stderr).toContain('No stash entries found');
|
||||||
@@ -431,7 +430,7 @@ describe('GitStashCommand', () => {
|
|||||||
];
|
];
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['drop']);
|
const result = await stashCommand.execute(['drop'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('Dropped stash@{0}');
|
expect(result.stdout).toContain('Dropped stash@{0}');
|
||||||
@@ -449,7 +448,7 @@ describe('GitStashCommand', () => {
|
|||||||
];
|
];
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['drop', 'stash@{1}']);
|
const result = await stashCommand.execute(['drop', 'stash@{1}'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('Dropped stash@{1}');
|
expect(result.stdout).toContain('Dropped stash@{1}');
|
||||||
@@ -461,7 +460,7 @@ describe('GitStashCommand', () => {
|
|||||||
];
|
];
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['drop', 'stash@{5}']);
|
const result = await stashCommand.execute(['drop', 'stash@{5}'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('is not a valid reference');
|
expect(result.stderr).toContain('is not a valid reference');
|
||||||
@@ -476,7 +475,7 @@ describe('GitStashCommand', () => {
|
|||||||
];
|
];
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||||
|
|
||||||
const result = await stashCommand.execute(['clear']);
|
const result = await stashCommand.execute(['clear'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||||
@@ -501,7 +500,7 @@ describe('GitStashCommand', () => {
|
|||||||
return Promise.resolve('');
|
return Promise.resolve('');
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await stashCommand.execute(['save']);
|
const result = await stashCommand.execute(['save'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('Saved working directory');
|
expect(result.stdout).toContain('Saved working directory');
|
||||||
@@ -521,7 +520,7 @@ describe('GitStashCommand', () => {
|
|||||||
return Promise.resolve('');
|
return Promise.resolve('');
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await stashCommand.execute([]);
|
const result = await stashCommand.execute([], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('Saved working directory');
|
expect(result.stdout).toContain('Saved working directory');
|
||||||
|
|||||||
@@ -24,19 +24,17 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -47,26 +45,26 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
switch (subcommand) {
|
switch (subcommand) {
|
||||||
case 'push':
|
case 'push':
|
||||||
case 'save':
|
case 'save':
|
||||||
return await this.stashPush(subcommandArgs);
|
return await this.stashPush(subcommandArgs, cwd);
|
||||||
case 'list':
|
case 'list':
|
||||||
return await this.stashList();
|
return await this.stashList(cwd);
|
||||||
case 'apply':
|
case 'apply':
|
||||||
return await this.stashApply(subcommandArgs);
|
return await this.stashApply(subcommandArgs, cwd);
|
||||||
case 'pop':
|
case 'pop':
|
||||||
return await this.stashPop(subcommandArgs);
|
return await this.stashPop(subcommandArgs, cwd);
|
||||||
case 'drop':
|
case 'drop':
|
||||||
return await this.stashDrop(subcommandArgs);
|
return await this.stashDrop(subcommandArgs, cwd);
|
||||||
case 'clear':
|
case 'clear':
|
||||||
return await this.stashClear();
|
return await this.stashClear(cwd);
|
||||||
case 'show':
|
case 'show':
|
||||||
return await this.stashShow(subcommandArgs);
|
return await this.stashShow(subcommandArgs, cwd);
|
||||||
case '--help':
|
case '--help':
|
||||||
case '-h':
|
case '-h':
|
||||||
return this.showHelp();
|
return this.showHelp(cwd);
|
||||||
default:
|
default:
|
||||||
// If first arg doesn't look like a subcommand, treat it as 'push'
|
// If first arg doesn't look like a subcommand, treat it as 'push'
|
||||||
if (subcommand.startsWith('-')) {
|
if (subcommand.startsWith('-')) {
|
||||||
return await this.stashPush(args);
|
return await this.stashPush(args, cwd);
|
||||||
}
|
}
|
||||||
return createErrorResult(`git stash: '${subcommand}' is not a stash command. See 'git stash --help'.`);
|
return createErrorResult(`git stash: '${subcommand}' is not a stash command. See 'git stash --help'.`);
|
||||||
}
|
}
|
||||||
@@ -76,7 +74,7 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async stashPush(args: string[]): Promise<ShellCommandResult> {
|
private async stashPush(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Parse arguments
|
// Parse arguments
|
||||||
let message = 'WIP on';
|
let message = 'WIP on';
|
||||||
@@ -96,13 +94,13 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
// Get current branch
|
// Get current branch
|
||||||
let currentBranch: string | null = null;
|
let currentBranch: string | null = null;
|
||||||
try {
|
try {
|
||||||
currentBranch = await this.git.currentBranch({ dir: this.pwd }) || null;
|
currentBranch = await this.git.currentBranch({ dir: cwd }) || null;
|
||||||
} catch {
|
} catch {
|
||||||
currentBranch = 'HEAD';
|
currentBranch = 'HEAD';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get status to find changed files
|
// Get status to find changed files
|
||||||
const statusMatrix = await this.git.statusMatrix({ dir: this.pwd });
|
const statusMatrix = await this.git.statusMatrix({ dir: cwd });
|
||||||
|
|
||||||
const filesToStash: StashEntry['files'] = [];
|
const filesToStash: StashEntry['files'] = [];
|
||||||
const stagedFiles: string[] = [];
|
const stagedFiles: string[] = [];
|
||||||
@@ -124,7 +122,7 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Untracked files (only with -u flag)
|
// Untracked files (only with -u flag)
|
||||||
if (includeUntracked && headStatus === 0 && stageStatus === 0 && workdirStatus === 2) {
|
if (includeUntracked && headStatus === 0 && stageStatus === 0 && workdirStatus === 2) {
|
||||||
const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8');
|
const content = await this.fs.readFile(join(cwd, filepath), 'utf8');
|
||||||
filesToStash.push({
|
filesToStash.push({
|
||||||
filepath,
|
filepath,
|
||||||
content,
|
content,
|
||||||
@@ -141,7 +139,7 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
// Staged new files or modified files (staged changes)
|
// Staged new files or modified files (staged changes)
|
||||||
else if (hasStagedChanges && workdirStatus === 2) {
|
else if (hasStagedChanges && workdirStatus === 2) {
|
||||||
const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8');
|
const content = await this.fs.readFile(join(cwd, filepath), 'utf8');
|
||||||
const status = headStatus === 0 ? 'added' : 'modified';
|
const status = headStatus === 0 ? 'added' : 'modified';
|
||||||
filesToStash.push({
|
filesToStash.push({
|
||||||
filepath,
|
filepath,
|
||||||
@@ -151,7 +149,7 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
// Unstaged modifications in working directory
|
// Unstaged modifications in working directory
|
||||||
else if (hasWorkdirChanges && workdirStatus === 2) {
|
else if (hasWorkdirChanges && workdirStatus === 2) {
|
||||||
const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8');
|
const content = await this.fs.readFile(join(cwd, filepath), 'utf8');
|
||||||
filesToStash.push({
|
filesToStash.push({
|
||||||
filepath,
|
filepath,
|
||||||
content,
|
content,
|
||||||
@@ -177,7 +175,7 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Save stash
|
// Save stash
|
||||||
await this.saveStash(stashEntry);
|
await this.saveStash(stashEntry, cwd);
|
||||||
|
|
||||||
// Revert changes in working directory
|
// Revert changes in working directory
|
||||||
for (const file of filesToStash) {
|
for (const file of filesToStash) {
|
||||||
@@ -185,21 +183,21 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
if (file.status === 'deleted') {
|
if (file.status === 'deleted') {
|
||||||
// Restore deleted file from HEAD
|
// Restore deleted file from HEAD
|
||||||
await this.git.checkout({
|
await this.git.checkout({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
filepaths: [file.filepath],
|
filepaths: [file.filepath],
|
||||||
force: true,
|
force: true,
|
||||||
});
|
});
|
||||||
} else if (file.status === 'modified') {
|
} else if (file.status === 'modified') {
|
||||||
// Restore file from HEAD using checkout
|
// Restore file from HEAD using checkout
|
||||||
await this.git.checkout({
|
await this.git.checkout({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
filepaths: [file.filepath],
|
filepaths: [file.filepath],
|
||||||
force: true,
|
force: true,
|
||||||
});
|
});
|
||||||
} else if (file.status === 'added') {
|
} else if (file.status === 'added') {
|
||||||
// Delete new file (it doesn't exist in HEAD)
|
// Delete new file (it doesn't exist in HEAD)
|
||||||
try {
|
try {
|
||||||
await this.fs.unlink(join(this.pwd, file.filepath));
|
await this.fs.unlink(join(cwd, file.filepath));
|
||||||
} catch {
|
} catch {
|
||||||
// File might already be gone
|
// File might already be gone
|
||||||
}
|
}
|
||||||
@@ -213,7 +211,7 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
for (const file of stagedFiles) {
|
for (const file of stagedFiles) {
|
||||||
try {
|
try {
|
||||||
await this.git.resetIndex({
|
await this.git.resetIndex({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
filepath: file,
|
filepath: file,
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
@@ -228,9 +226,9 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async stashList(): Promise<ShellCommandResult> {
|
private async stashList(cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
const stashes = await this.loadStashes();
|
const stashes = await this.loadStashes(cwd);
|
||||||
|
|
||||||
if (stashes.length === 0) {
|
if (stashes.length === 0) {
|
||||||
return createSuccessResult('');
|
return createSuccessResult('');
|
||||||
@@ -247,9 +245,9 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async stashApply(args: string[]): Promise<ShellCommandResult> {
|
private async stashApply(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
const stashes = await this.loadStashes();
|
const stashes = await this.loadStashes(cwd);
|
||||||
|
|
||||||
if (stashes.length === 0) {
|
if (stashes.length === 0) {
|
||||||
return createErrorResult('No stash entries found.');
|
return createErrorResult('No stash entries found.');
|
||||||
@@ -257,7 +255,7 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Parse stash reference (e.g., stash@{0} or just 0)
|
// Parse stash reference (e.g., stash@{0} or just 0)
|
||||||
const stashRef = args[0] || 'stash@{0}';
|
const stashRef = args[0] || 'stash@{0}';
|
||||||
const index = this.parseStashRef(stashRef);
|
const index = this.parseStashRef(stashRef, cwd);
|
||||||
|
|
||||||
if (index < 0 || index >= stashes.length) {
|
if (index < 0 || index >= stashes.length) {
|
||||||
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
||||||
@@ -271,19 +269,19 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
if (file.status === 'deleted') {
|
if (file.status === 'deleted') {
|
||||||
// Delete the file
|
// Delete the file
|
||||||
try {
|
try {
|
||||||
await this.fs.unlink(join(this.pwd, file.filepath));
|
await this.fs.unlink(join(cwd, file.filepath));
|
||||||
} catch {
|
} catch {
|
||||||
// File might not exist
|
// File might not exist
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Create file with stashed content
|
// Create file with stashed content
|
||||||
const dir = join(this.pwd, file.filepath, '..');
|
const dir = join(cwd, file.filepath, '..');
|
||||||
try {
|
try {
|
||||||
await this.fs.mkdir(dir, { recursive: true });
|
await this.fs.mkdir(dir, { recursive: true });
|
||||||
} catch {
|
} catch {
|
||||||
// Directory might exist
|
// Directory might exist
|
||||||
}
|
}
|
||||||
await this.fs.writeFile(join(this.pwd, file.filepath), file.content);
|
await this.fs.writeFile(join(cwd, file.filepath), file.content);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(`Failed to apply ${file.filepath}:`, error);
|
console.warn(`Failed to apply ${file.filepath}:`, error);
|
||||||
@@ -294,7 +292,7 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
for (const filepath of stash.stagedFiles) {
|
for (const filepath of stash.stagedFiles) {
|
||||||
try {
|
try {
|
||||||
await this.git.add({
|
await this.git.add({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
filepath,
|
filepath,
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
@@ -309,17 +307,17 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async stashPop(args: string[]): Promise<ShellCommandResult> {
|
private async stashPop(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Apply the stash first
|
// Apply the stash first
|
||||||
const result = await this.stashApply(args);
|
const result = await this.stashApply(args, cwd);
|
||||||
|
|
||||||
if (result.exitCode !== 0) {
|
if (result.exitCode !== 0) {
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If apply succeeded, drop the stash
|
// If apply succeeded, drop the stash
|
||||||
const dropResult = await this.stashDrop(args);
|
const dropResult = await this.stashDrop(args, cwd);
|
||||||
|
|
||||||
if (dropResult.exitCode !== 0) {
|
if (dropResult.exitCode !== 0) {
|
||||||
return createErrorResult(`Applied stash successfully but failed to drop: ${dropResult.stderr}`);
|
return createErrorResult(`Applied stash successfully but failed to drop: ${dropResult.stderr}`);
|
||||||
@@ -332,9 +330,9 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async stashDrop(args: string[]): Promise<ShellCommandResult> {
|
private async stashDrop(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
const stashes = await this.loadStashes();
|
const stashes = await this.loadStashes(cwd);
|
||||||
|
|
||||||
if (stashes.length === 0) {
|
if (stashes.length === 0) {
|
||||||
return createErrorResult('No stash entries found.');
|
return createErrorResult('No stash entries found.');
|
||||||
@@ -342,7 +340,7 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Parse stash reference
|
// Parse stash reference
|
||||||
const stashRef = args[0] || 'stash@{0}';
|
const stashRef = args[0] || 'stash@{0}';
|
||||||
const index = this.parseStashRef(stashRef);
|
const index = this.parseStashRef(stashRef, cwd);
|
||||||
|
|
||||||
if (index < 0 || index >= stashes.length) {
|
if (index < 0 || index >= stashes.length) {
|
||||||
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
||||||
@@ -350,7 +348,7 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Remove the stash
|
// Remove the stash
|
||||||
stashes.splice(index, 1);
|
stashes.splice(index, 1);
|
||||||
await this.saveStashes(stashes);
|
await this.saveStashes(stashes, cwd);
|
||||||
|
|
||||||
return createSuccessResult(`Dropped stash@{${index}}\n`);
|
return createSuccessResult(`Dropped stash@{${index}}\n`);
|
||||||
|
|
||||||
@@ -359,9 +357,9 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async stashClear(): Promise<ShellCommandResult> {
|
private async stashClear(cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
await this.saveStashes([]);
|
await this.saveStashes([], cwd);
|
||||||
return createSuccessResult('');
|
return createSuccessResult('');
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -369,9 +367,9 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async stashShow(args: string[]): Promise<ShellCommandResult> {
|
private async stashShow(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
const stashes = await this.loadStashes();
|
const stashes = await this.loadStashes(cwd);
|
||||||
|
|
||||||
if (stashes.length === 0) {
|
if (stashes.length === 0) {
|
||||||
return createErrorResult('No stash entries found.');
|
return createErrorResult('No stash entries found.');
|
||||||
@@ -379,7 +377,7 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Parse stash reference
|
// Parse stash reference
|
||||||
const stashRef = args[0] || 'stash@{0}';
|
const stashRef = args[0] || 'stash@{0}';
|
||||||
const index = this.parseStashRef(stashRef);
|
const index = this.parseStashRef(stashRef, cwd);
|
||||||
|
|
||||||
if (index < 0 || index >= stashes.length) {
|
if (index < 0 || index >= stashes.length) {
|
||||||
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
||||||
@@ -405,7 +403,7 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private parseStashRef(ref: string): number {
|
private parseStashRef(ref: string, _cwd: string): number {
|
||||||
// Parse stash@{N} or just N
|
// Parse stash@{N} or just N
|
||||||
const match = ref.match(/^(?:stash@\{)?(\d+)\}?$/);
|
const match = ref.match(/^(?:stash@\{)?(\d+)\}?$/);
|
||||||
if (match) {
|
if (match) {
|
||||||
@@ -414,9 +412,9 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
return 0; // Default to stash@{0}
|
return 0; // Default to stash@{0}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async loadStashes(): Promise<StashEntry[]> {
|
private async loadStashes(cwd: string): Promise<StashEntry[]> {
|
||||||
try {
|
try {
|
||||||
const stashPath = join(this.pwd, '.git', 'shakespeare_stash.json');
|
const stashPath = join(cwd, '.git', 'shakespeare_stash.json');
|
||||||
const data = await this.fs.readFile(stashPath, 'utf8');
|
const data = await this.fs.readFile(stashPath, 'utf8');
|
||||||
return JSON.parse(data) as StashEntry[];
|
return JSON.parse(data) as StashEntry[];
|
||||||
} catch {
|
} catch {
|
||||||
@@ -424,18 +422,18 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async saveStash(stash: StashEntry): Promise<void> {
|
private async saveStash(stash: StashEntry, cwd: string): Promise<void> {
|
||||||
const stashes = await this.loadStashes();
|
const stashes = await this.loadStashes(cwd);
|
||||||
stashes.unshift(stash); // Add to beginning of array
|
stashes.unshift(stash); // Add to beginning of array
|
||||||
await this.saveStashes(stashes);
|
await this.saveStashes(stashes, cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async saveStashes(stashes: StashEntry[]): Promise<void> {
|
private async saveStashes(stashes: StashEntry[], cwd: string): Promise<void> {
|
||||||
const stashPath = join(this.pwd, '.git', 'shakespeare_stash.json');
|
const stashPath = join(cwd, '.git', 'shakespeare_stash.json');
|
||||||
await this.fs.writeFile(stashPath, JSON.stringify(stashes, null, 2));
|
await this.fs.writeFile(stashPath, JSON.stringify(stashes, null, 2));
|
||||||
}
|
}
|
||||||
|
|
||||||
private showHelp(): ShellCommandResult {
|
private showHelp(_cwd: string): ShellCommandResult {
|
||||||
const helpText = `usage: git stash list [<options>]
|
const helpText = `usage: git stash list [<options>]
|
||||||
or: git stash show [<stash>]
|
or: git stash show [<stash>]
|
||||||
or: git stash drop [<stash>]
|
or: git stash drop [<stash>]
|
||||||
@@ -446,4 +444,4 @@ export class GitStashCommand implements GitSubcommand {
|
|||||||
|
|
||||||
return createSuccessResult(helpText);
|
return createSuccessResult(helpText);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -52,7 +52,6 @@ describe('GitStatusCommand', () => {
|
|||||||
statusCommand = new GitStatusCommand({
|
statusCommand = new GitStatusCommand({
|
||||||
git: mockGit,
|
git: mockGit,
|
||||||
fs: mockFS,
|
fs: mockFS,
|
||||||
pwd: testCwd,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -66,7 +65,7 @@ describe('GitStatusCommand', () => {
|
|||||||
// Mock stat to throw error for .git directory
|
// Mock stat to throw error for .git directory
|
||||||
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
||||||
|
|
||||||
const result = await statusCommand.execute([]);
|
const result = await statusCommand.execute([], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
expect(result.exitCode).toBe(1);
|
||||||
expect(result.stderr).toContain('fatal: not a git repository');
|
expect(result.stderr).toContain('fatal: not a git repository');
|
||||||
@@ -77,7 +76,7 @@ describe('GitStatusCommand', () => {
|
|||||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([]);
|
vi.mocked(mockGit.statusMatrix).mockResolvedValue([]);
|
||||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||||
|
|
||||||
const result = await statusCommand.execute([]);
|
const result = await statusCommand.execute([], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('On branch main');
|
expect(result.stdout).toContain('On branch main');
|
||||||
@@ -93,7 +92,7 @@ describe('GitStatusCommand', () => {
|
|||||||
]);
|
]);
|
||||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||||
|
|
||||||
const result = await statusCommand.execute([]);
|
const result = await statusCommand.execute([], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('On branch main');
|
expect(result.stdout).toContain('On branch main');
|
||||||
@@ -109,7 +108,7 @@ describe('GitStatusCommand', () => {
|
|||||||
]);
|
]);
|
||||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||||
|
|
||||||
const result = await statusCommand.execute([]);
|
const result = await statusCommand.execute([], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('On branch main');
|
expect(result.stdout).toContain('On branch main');
|
||||||
@@ -125,7 +124,7 @@ describe('GitStatusCommand', () => {
|
|||||||
]);
|
]);
|
||||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||||
|
|
||||||
const result = await statusCommand.execute([]);
|
const result = await statusCommand.execute([], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('On branch main');
|
expect(result.stdout).toContain('On branch main');
|
||||||
@@ -141,7 +140,7 @@ describe('GitStatusCommand', () => {
|
|||||||
]);
|
]);
|
||||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||||
|
|
||||||
const result = await statusCommand.execute([]);
|
const result = await statusCommand.execute([], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('On branch main');
|
expect(result.stdout).toContain('On branch main');
|
||||||
@@ -159,7 +158,7 @@ describe('GitStatusCommand', () => {
|
|||||||
]);
|
]);
|
||||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||||
|
|
||||||
const result = await statusCommand.execute(['--porcelain']);
|
const result = await statusCommand.execute(['--porcelain'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('?? untracked.txt');
|
expect(result.stdout).toContain('?? untracked.txt');
|
||||||
@@ -175,7 +174,7 @@ describe('GitStatusCommand', () => {
|
|||||||
]);
|
]);
|
||||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||||
|
|
||||||
const result = await statusCommand.execute(['--short']);
|
const result = await statusCommand.execute(['--short'], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('?? untracked.txt');
|
expect(result.stdout).toContain('?? untracked.txt');
|
||||||
@@ -191,7 +190,7 @@ describe('GitStatusCommand', () => {
|
|||||||
]);
|
]);
|
||||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('feature-branch');
|
vi.mocked(mockGit.currentBranch).mockResolvedValue('feature-branch');
|
||||||
|
|
||||||
const result = await statusCommand.execute([]);
|
const result = await statusCommand.execute([], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('On branch feature-branch');
|
expect(result.stdout).toContain('On branch feature-branch');
|
||||||
@@ -209,7 +208,7 @@ describe('GitStatusCommand', () => {
|
|||||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([]);
|
vi.mocked(mockGit.statusMatrix).mockResolvedValue([]);
|
||||||
vi.mocked(mockGit.currentBranch).mockResolvedValue(undefined);
|
vi.mocked(mockGit.currentBranch).mockResolvedValue(undefined);
|
||||||
|
|
||||||
const result = await statusCommand.execute([]);
|
const result = await statusCommand.execute([], testCwd);
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(result.stdout).toContain('HEAD detached at unknown');
|
expect(result.stdout).toContain('HEAD detached at unknown');
|
||||||
|
|||||||
@@ -11,19 +11,18 @@ export class GitStatusCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -32,23 +31,23 @@ export class GitStatusCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Get the status matrix
|
// Get the status matrix
|
||||||
const statusMatrix = await this.git.statusMatrix({
|
const statusMatrix = await this.git.statusMatrix({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Get current branch
|
// Get current branch
|
||||||
let currentBranch: string | null = null;
|
let currentBranch: string | null = null;
|
||||||
try {
|
try {
|
||||||
currentBranch = await this.git.currentBranch({
|
currentBranch = await this.git.currentBranch({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
}) || null;
|
}) || null;
|
||||||
} catch {
|
} catch {
|
||||||
// Might be an empty repository
|
// Might be an empty repository
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.porcelain || options.short) {
|
if (options.porcelain || options.short) {
|
||||||
return this.formatPorcelainStatus(statusMatrix);
|
return this.formatPorcelainStatus(statusMatrix, cwd);
|
||||||
} else {
|
} else {
|
||||||
return this.formatHumanStatus(statusMatrix, currentBranch);
|
return this.formatHumanStatus(statusMatrix, currentBranch, cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -70,7 +69,7 @@ export class GitStatusCommand implements GitSubcommand {
|
|||||||
return options;
|
return options;
|
||||||
}
|
}
|
||||||
|
|
||||||
private formatPorcelainStatus(statusMatrix: Array<[string, number, number, number]>): ShellCommandResult {
|
private formatPorcelainStatus(statusMatrix: Array<[string, number, number, number]>, _cwd: string): ShellCommandResult {
|
||||||
const lines: string[] = [];
|
const lines: string[] = [];
|
||||||
|
|
||||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||||
@@ -108,7 +107,7 @@ export class GitStatusCommand implements GitSubcommand {
|
|||||||
return createSuccessResult(lines.join('\n') + (lines.length > 0 ? '\n' : ''));
|
return createSuccessResult(lines.join('\n') + (lines.length > 0 ? '\n' : ''));
|
||||||
}
|
}
|
||||||
|
|
||||||
private formatHumanStatus(statusMatrix: Array<[string, number, number, number]>, currentBranch: string | null): ShellCommandResult {
|
private formatHumanStatus(statusMatrix: Array<[string, number, number, number]>, currentBranch: string | null, _cwd: string): ShellCommandResult {
|
||||||
const lines: string[] = [];
|
const lines: string[] = [];
|
||||||
|
|
||||||
// Show current branch
|
// Show current branch
|
||||||
@@ -186,4 +185,4 @@ export class GitStatusCommand implements GitSubcommand {
|
|||||||
lines.push('');
|
lines.push('');
|
||||||
return createSuccessResult(lines.join('\n'));
|
return createSuccessResult(lines.join('\n'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+16
-21
@@ -12,19 +12,17 @@ export class GitTagCommand implements GitSubcommand {
|
|||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
constructor(options: GitSubcommandOptions) {
|
||||||
this.git = options.git;
|
this.git = options.git;
|
||||||
this.fs = options.fs;
|
this.fs = options.fs;
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Check if we're in a git repository
|
// Check if we're in a git repository
|
||||||
try {
|
try {
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
await this.fs.stat(`${cwd}/.git`);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||||
}
|
}
|
||||||
@@ -33,13 +31,13 @@ export class GitTagCommand implements GitSubcommand {
|
|||||||
|
|
||||||
switch (action) {
|
switch (action) {
|
||||||
case 'list':
|
case 'list':
|
||||||
return await this.listTags();
|
return await this.listTags(cwd);
|
||||||
case 'create':
|
case 'create':
|
||||||
return await this.createTag(tagName!, commit);
|
return await this.createTag(tagName!, cwd, commit);
|
||||||
case 'delete':
|
case 'delete':
|
||||||
return await this.deleteTag(tagName!);
|
return await this.deleteTag(tagName!, cwd);
|
||||||
default:
|
default:
|
||||||
return await this.listTags();
|
return await this.listTags(cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -84,10 +82,10 @@ export class GitTagCommand implements GitSubcommand {
|
|||||||
return { action, tagName, commit, options };
|
return { action, tagName, commit, options };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async listTags(): Promise<ShellCommandResult> {
|
private async listTags(cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
const tags = await this.git.listTags({
|
const tags = await this.git.listTags({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (tags.length === 0) {
|
if (tags.length === 0) {
|
||||||
@@ -104,7 +102,7 @@ export class GitTagCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async createTag(tagName: string, commit?: string): Promise<ShellCommandResult> {
|
private async createTag(tagName: string, cwd: string, commit?: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
if (!tagName) {
|
if (!tagName) {
|
||||||
return createErrorResult('usage: git tag <tagname> [<commit>]');
|
return createErrorResult('usage: git tag <tagname> [<commit>]');
|
||||||
@@ -113,8 +111,7 @@ export class GitTagCommand implements GitSubcommand {
|
|||||||
// Check if tag already exists
|
// Check if tag already exists
|
||||||
try {
|
try {
|
||||||
const tags = await this.git.listTags({
|
const tags = await this.git.listTags({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (tags.includes(tagName)) {
|
if (tags.includes(tagName)) {
|
||||||
@@ -128,8 +125,7 @@ export class GitTagCommand implements GitSubcommand {
|
|||||||
let targetOid: string;
|
let targetOid: string;
|
||||||
try {
|
try {
|
||||||
targetOid = await this.git.resolveRef({
|
targetOid = await this.git.resolveRef({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
ref: commit || 'HEAD',
|
ref: commit || 'HEAD',
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
@@ -138,7 +134,7 @@ export class GitTagCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Create the tag
|
// Create the tag
|
||||||
await this.git.tag({
|
await this.git.tag({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: tagName,
|
ref: tagName,
|
||||||
object: targetOid,
|
object: targetOid,
|
||||||
});
|
});
|
||||||
@@ -150,7 +146,7 @@ export class GitTagCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async deleteTag(tagName: string): Promise<ShellCommandResult> {
|
private async deleteTag(tagName: string, cwd: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
if (!tagName) {
|
if (!tagName) {
|
||||||
return createErrorResult('usage: git tag -d <tagname>');
|
return createErrorResult('usage: git tag -d <tagname>');
|
||||||
@@ -159,8 +155,7 @@ export class GitTagCommand implements GitSubcommand {
|
|||||||
// Check if tag exists
|
// Check if tag exists
|
||||||
try {
|
try {
|
||||||
const tags = await this.git.listTags({
|
const tags = await this.git.listTags({
|
||||||
|
dir: cwd,
|
||||||
dir: this.pwd,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!tags.includes(tagName)) {
|
if (!tags.includes(tagName)) {
|
||||||
@@ -172,7 +167,7 @@ export class GitTagCommand implements GitSubcommand {
|
|||||||
|
|
||||||
// Delete the tag
|
// Delete the tag
|
||||||
await this.git.deleteTag({
|
await this.git.deleteTag({
|
||||||
dir: this.pwd,
|
dir: cwd,
|
||||||
ref: tagName,
|
ref: tagName,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -182,4 +177,4 @@ export class GitTagCommand implements GitSubcommand {
|
|||||||
return createErrorResult(`Failed to delete tag: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
return createErrorResult(`Failed to delete tag: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,7 +74,10 @@ describe('configUtils', () => {
|
|||||||
const result = await readAISettings(mockFS);
|
const result = await readAISettings(mockFS);
|
||||||
|
|
||||||
expect(mockFS.readFile).toHaveBeenCalledWith('/config/ai.json', 'utf8');
|
expect(mockFS.readFile).toHaveBeenCalledWith('/config/ai.json', 'utf8');
|
||||||
expect(result).toEqual(sampleAISettings);
|
expect(result).toEqual({
|
||||||
|
...sampleAISettings,
|
||||||
|
mcpServers: {},
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return default settings if file does not exist and no localStorage data', async () => {
|
it('should return default settings if file does not exist and no localStorage data', async () => {
|
||||||
@@ -86,6 +89,7 @@ describe('configUtils', () => {
|
|||||||
expect(result).toEqual({
|
expect(result).toEqual({
|
||||||
providers: [],
|
providers: [],
|
||||||
recentlyUsedModels: [],
|
recentlyUsedModels: [],
|
||||||
|
mcpServers: {},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -98,6 +102,7 @@ describe('configUtils', () => {
|
|||||||
expect(result).toEqual({
|
expect(result).toEqual({
|
||||||
providers: [],
|
providers: [],
|
||||||
recentlyUsedModels: [],
|
recentlyUsedModels: [],
|
||||||
|
mcpServers: {},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+15
-2
@@ -1,7 +1,7 @@
|
|||||||
import z from 'zod';
|
import z from 'zod';
|
||||||
import { filteredArray } from '@/lib/schema';
|
import { filteredArray } from '@/lib/schema';
|
||||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||||
import type { AIProvider, AISettings } from '@/contexts/AISettingsContext';
|
import type { AIProvider, AISettings, MCPServer } from '@/contexts/AISettingsContext';
|
||||||
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
||||||
import type { DeployProvider, DeploySettings } from '@/contexts/DeploySettingsContext';
|
import type { DeployProvider, DeploySettings } from '@/contexts/DeploySettingsContext';
|
||||||
|
|
||||||
@@ -42,9 +42,16 @@ const providerModelSchema = z.string().regex(
|
|||||||
'Must be in format provider/model (e.g., "openai/gpt-4o")',
|
'Must be in format provider/model (e.g., "openai/gpt-4o")',
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const mcpServerSchema: z.ZodType<MCPServer> = z.object({
|
||||||
|
type: z.literal('streamable-http'),
|
||||||
|
url: z.string().url(),
|
||||||
|
headers: z.record(z.string(), z.string()).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
const aiSettingsSchema = z.object({
|
const aiSettingsSchema = z.object({
|
||||||
providers: filteredArray(aiProviderSchema),
|
providers: filteredArray(aiProviderSchema),
|
||||||
recentlyUsedModels: filteredArray(providerModelSchema),
|
recentlyUsedModels: filteredArray(providerModelSchema),
|
||||||
|
mcpServers: z.record(z.string(), mcpServerSchema).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const gitCredentialSchema = z.object({
|
const gitCredentialSchema = z.object({
|
||||||
@@ -130,13 +137,19 @@ export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): P
|
|||||||
const defaultSettings: AISettings = {
|
const defaultSettings: AISettings = {
|
||||||
providers: [],
|
providers: [],
|
||||||
recentlyUsedModels: [],
|
recentlyUsedModels: [],
|
||||||
|
mcpServers: {},
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const aiConfigPath = getAIConfigPath(configPath);
|
const aiConfigPath = getAIConfigPath(configPath);
|
||||||
const content = await fs.readFile(aiConfigPath, 'utf8');
|
const content = await fs.readFile(aiConfigPath, 'utf8');
|
||||||
const data = JSON.parse(content);
|
const data = JSON.parse(content);
|
||||||
return aiSettingsSchema.parse(data);
|
const parsed = aiSettingsSchema.parse(data);
|
||||||
|
// Ensure mcpServers exists even if not in parsed data
|
||||||
|
return {
|
||||||
|
...parsed,
|
||||||
|
mcpServers: parsed.mcpServers || {},
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof z.ZodError) {
|
if (error instanceof z.ZodError) {
|
||||||
console.error('AI settings parsing error:', error.errors);
|
console.error('AI settings parsing error:', error.errors);
|
||||||
|
|||||||
@@ -67,4 +67,27 @@ export async function saveFileToTmp(fs: JSRuntimeFS, file: File, tmpPath = '/tmp
|
|||||||
await fs.writeFile(fullPath, uint8Array);
|
await fs.writeFile(fullPath, uint8Array);
|
||||||
|
|
||||||
return fullPath;
|
return fullPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a file path represents a media/binary file that cannot be edited as text
|
||||||
|
* @param path - File path to check
|
||||||
|
* @returns boolean - True if the file is a media/binary file
|
||||||
|
*/
|
||||||
|
export function isMediaFile(path: string): boolean {
|
||||||
|
const extension = path.split('.').pop()?.toLowerCase();
|
||||||
|
if (!extension) return false;
|
||||||
|
|
||||||
|
const mediaExtensions = [
|
||||||
|
// Images
|
||||||
|
'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif', 'heic', 'heif',
|
||||||
|
// Videos
|
||||||
|
'mp4', 'webm', 'avi', 'mov', 'mkv', 'flv', 'wmv', 'm4v',
|
||||||
|
// Audio
|
||||||
|
'mp3', 'wav', 'ogg', 'flac', 'm4a', 'aac', 'wma',
|
||||||
|
// Other binary formats
|
||||||
|
'pdf', 'zip', 'tar', 'gz', 'rar', '7z',
|
||||||
|
];
|
||||||
|
|
||||||
|
return mediaExtensions.includes(extension);
|
||||||
}
|
}
|
||||||
+8
-6
@@ -1,4 +1,4 @@
|
|||||||
import git, { GitHttpRequest, GitHttpResponse, HttpClient } from 'isomorphic-git';
|
import git, { FetchResult, GitHttpRequest, GitHttpResponse, HttpClient } from 'isomorphic-git';
|
||||||
import { NIP05 } from '@nostrify/nostrify';
|
import { NIP05 } from '@nostrify/nostrify';
|
||||||
import { nip19 } from 'nostr-tools';
|
import { nip19 } from 'nostr-tools';
|
||||||
import { proxyUrl } from './proxyUrl';
|
import { proxyUrl } from './proxyUrl';
|
||||||
@@ -1615,7 +1615,7 @@ export class Git {
|
|||||||
return differences;
|
return differences;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async nostrFetch(nostrUrl: string, options: Omit<Parameters<typeof git.fetch>[0], 'fs' | 'http' | 'corsProxy'> & { remote: string; dir: string }): Promise<{ fetchHead?: string; fetchHeadDescription?: string }> {
|
private async nostrFetch(nostrUrl: string, options: Omit<Parameters<typeof git.fetch>[0], 'fs' | 'http' | 'corsProxy'> & { remote: string; dir: string }): Promise<FetchResult> {
|
||||||
// Parse the Nostr URI
|
// Parse the Nostr URI
|
||||||
const nostrURI = await this.parseNostrCloneURI(nostrUrl);
|
const nostrURI = await this.parseNostrCloneURI(nostrUrl);
|
||||||
if (!nostrURI) {
|
if (!nostrURI) {
|
||||||
@@ -1629,7 +1629,7 @@ export class Git {
|
|||||||
|
|
||||||
// If we have a state event, update our refs to match
|
// If we have a state event, update our refs to match
|
||||||
if (state) {
|
if (state) {
|
||||||
const foundAllData = async () => {
|
const foundAllData = async (): Promise<FetchResult> => {
|
||||||
// identify out-of-sync grasp servers are in sync
|
// identify out-of-sync grasp servers are in sync
|
||||||
const cloneURLsStates = await this.listFromCloneUrls(repo);
|
const cloneURLsStates = await this.listFromCloneUrls(repo);
|
||||||
const outOfSyncRefsPerCloneUrl = this.nostrIdentifyCloneUrlStateDifferences(state, cloneURLsStates);
|
const outOfSyncRefsPerCloneUrl = this.nostrIdentifyCloneUrlStateDifferences(state, cloneURLsStates);
|
||||||
@@ -1657,8 +1657,9 @@ export class Git {
|
|||||||
);
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
fetchHead: state.headCommit,
|
fetchHead: state.headCommit || null,
|
||||||
fetchHeadDescription: `Fetched from Nostr repository state`,
|
fetchHeadDescription: `Fetched from Nostr repository state`,
|
||||||
|
defaultBranch: state.headBranch || null,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -2002,7 +2003,7 @@ export class Git {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* just fetching the branches and tags so some refs (eg refs/nostr/<event-id>) wont be fetched (unless the remote refspec specifies?) */
|
/* just fetching the branches and tags so some refs (eg refs/nostr/<event-id>) wont be fetched (unless the remote refspec specifies?) */
|
||||||
private async nostrFetchDataFromGitRemote(httpsCloneUrl:string, dir: string): Promise<{ fetchHead?: string; fetchHeadDescription?: string }> {
|
private async nostrFetchDataFromGitRemote(httpsCloneUrl:string, dir: string): Promise<FetchResult> {
|
||||||
try {
|
try {
|
||||||
console.log(`Fetching from Git remote: ${httpsCloneUrl}`);
|
console.log(`Fetching from Git remote: ${httpsCloneUrl}`);
|
||||||
|
|
||||||
@@ -2033,8 +2034,9 @@ export class Git {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
fetchHead: fetchResult.fetchHead || undefined,
|
fetchHead: fetchResult.fetchHead || null,
|
||||||
fetchHeadDescription: `Fetched from Git remote: ${httpsCloneUrl}`,
|
fetchHeadDescription: `Fetched from Git remote: ${httpsCloneUrl}`,
|
||||||
|
defaultBranch: fetchResult.defaultBranch || null,
|
||||||
};
|
};
|
||||||
} catch (fetchError) {
|
} catch (fetchError) {
|
||||||
// Clean up the temporary remote
|
// Clean up the temporary remote
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
/**
|
||||||
|
* Converts a File to a base64-encoded data URL for API consumption.
|
||||||
|
*
|
||||||
|
* @param file - The file to convert
|
||||||
|
* @returns Promise resolving to base64 data URL string
|
||||||
|
*/
|
||||||
|
export async function fileToUrl(file: File): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = () => {
|
||||||
|
if (typeof reader.result === 'string') {
|
||||||
|
resolve(reader.result);
|
||||||
|
} else {
|
||||||
|
reject(new Error('Failed to read file as data URL'));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.onerror = () => {
|
||||||
|
reject(new Error('Failed to read file'));
|
||||||
|
};
|
||||||
|
reader.readAsDataURL(file);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@@ -40,6 +40,7 @@ const testConfig: AppConfig = {
|
|||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
fsPathTmp: '/tmp',
|
fsPathTmp: '/tmp',
|
||||||
fsPathPlugins: '/plugins',
|
fsPathPlugins: '/plugins',
|
||||||
|
fsPathTemplates: '/templates',
|
||||||
sentryDsn: '',
|
sentryDsn: '',
|
||||||
sentryEnabled: false,
|
sentryEnabled: false,
|
||||||
};
|
};
|
||||||
|
|||||||
+5
-5
@@ -200,11 +200,11 @@ This project has a repository URL configured, so you can create an "Edit with Sh
|
|||||||
|
|
||||||
Note: the badge should be displayed at its natural size. It is recommended to omit width/height attributes to ensure proper scaling, or use \`height: auto\` in CSS (or \`"h-auto"\` in Tailwind CSS) when applicable.{% else %}
|
Note: the badge should be displayed at its natural size. It is recommended to omit width/height attributes to ensure proper scaling, or use \`height: auto\` in CSS (or \`"h-auto"\` in Tailwind CSS) when applicable.{% else %}
|
||||||
|
|
||||||
**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.{% endif %}{% if readmeText %}
|
**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.{% endif %}{% if README %}
|
||||||
|
|
||||||
{{ readmeText }}{% endif %}{% if agentsText %}
|
{{ README }}{% endif %}{% if AGENTS %}
|
||||||
|
|
||||||
{{ agentsText }}{% endif %}`;
|
{{ AGENTS }}{% endif %}`;
|
||||||
|
|
||||||
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
|
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
|
||||||
const { tools, mode, fs, cwd, config, defaultConfig, user, metadata, repositoryUrl, template } = opts;
|
const { tools, mode, fs, cwd, config, defaultConfig, user, metadata, repositoryUrl, template } = opts;
|
||||||
@@ -286,8 +286,8 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<stri
|
|||||||
},
|
},
|
||||||
badgeUrl,
|
badgeUrl,
|
||||||
editUrl,
|
editUrl,
|
||||||
readmeText,
|
README: readmeText,
|
||||||
agentsText,
|
AGENTS: agentsText,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Render the template with the context
|
// Render the template with the context
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import type { Tool } from './Tool';
|
||||||
|
import type { MCPClient } from '@/lib/MCPClient';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wrapper for MCP tools to integrate with Shakespeare's tool system.
|
||||||
|
*/
|
||||||
|
export class MCPTool implements Tool<Record<string, unknown>> {
|
||||||
|
description: string;
|
||||||
|
private client: MCPClient;
|
||||||
|
private originalToolName: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
description: string,
|
||||||
|
client: MCPClient,
|
||||||
|
originalToolName: string
|
||||||
|
) {
|
||||||
|
this.description = description;
|
||||||
|
this.client = client;
|
||||||
|
this.originalToolName = originalToolName;
|
||||||
|
}
|
||||||
|
|
||||||
|
async execute(args: Record<string, unknown>): Promise<string> {
|
||||||
|
return await this.client.callTool(this.originalToolName, args);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create MCPTool instances from discovered MCP tools.
|
||||||
|
*/
|
||||||
|
export function createMCPTools(
|
||||||
|
clients: Record<string, MCPClient>
|
||||||
|
): Record<string, Tool<unknown>> {
|
||||||
|
const tools: Record<string, Tool<unknown>> = {};
|
||||||
|
|
||||||
|
for (const [prefixedName, client] of Object.entries(clients)) {
|
||||||
|
// Extract original tool name by removing server prefix
|
||||||
|
const parts = prefixedName.split('__');
|
||||||
|
const originalToolName = parts.slice(1).join('__');
|
||||||
|
|
||||||
|
tools[prefixedName] = new MCPTool(
|
||||||
|
`MCP tool: ${prefixedName}`,
|
||||||
|
client,
|
||||||
|
originalToolName
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return tools;
|
||||||
|
}
|
||||||
@@ -41,7 +41,7 @@ describe('ShellTool', () => {
|
|||||||
mockFS = createMockFS();
|
mockFS = createMockFS();
|
||||||
mockNostr = createMockNostr();
|
mockNostr = createMockNostr();
|
||||||
mockGit = new Git({ fs: mockFS, nostr: mockNostr });
|
mockGit = new Git({ fs: mockFS, nostr: mockNostr });
|
||||||
shellTool = new ShellTool(mockFS, testCwd, mockGit, '/projects', testCorsProxy);
|
shellTool = new ShellTool(mockFS, testCwd, mockGit, testCorsProxy);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should have correct tool properties', () => {
|
it('should have correct tool properties', () => {
|
||||||
|
|||||||
@@ -51,7 +51,6 @@ export class ShellTool implements Tool<ShellToolParams> {
|
|||||||
private cwd: string;
|
private cwd: string;
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private commands: Map<string, ShellCommand>;
|
private commands: Map<string, ShellCommand>;
|
||||||
private projectsPath: string;
|
|
||||||
private signer?: NostrSigner;
|
private signer?: NostrSigner;
|
||||||
private corsProxy: string;
|
private corsProxy: string;
|
||||||
|
|
||||||
@@ -63,11 +62,10 @@ export class ShellTool implements Tool<ShellToolParams> {
|
|||||||
),
|
),
|
||||||
});
|
});
|
||||||
|
|
||||||
constructor(fs: JSRuntimeFS, cwd: string, git: Git, projectsPath: string = '/projects', corsProxy: string, signer?: NostrSigner) {
|
constructor(fs: JSRuntimeFS, cwd: string, git: Git, corsProxy: string, signer?: NostrSigner) {
|
||||||
this.fs = fs;
|
this.fs = fs;
|
||||||
this.cwd = cwd;
|
this.cwd = cwd;
|
||||||
this.git = git;
|
this.git = git;
|
||||||
this.projectsPath = projectsPath;
|
|
||||||
this.corsProxy = corsProxy;
|
this.corsProxy = corsProxy;
|
||||||
this.signer = signer;
|
this.signer = signer;
|
||||||
this.commands = new Map();
|
this.commands = new Map();
|
||||||
|
|||||||
+30
-7
@@ -11,7 +11,7 @@
|
|||||||
"themeDescription": "Choose between light, dark, or system theme preference.",
|
"themeDescription": "Choose between light, dark, or system theme preference.",
|
||||||
"language": "Language",
|
"language": "Language",
|
||||||
"languageDescription": "Select your preferred language for the interface.",
|
"languageDescription": "Select your preferred language for the interface.",
|
||||||
"systemSettings": "System Settings",
|
"systemSettings": "System",
|
||||||
"systemSettingsDescription": "Configure system-level settings and advanced options.",
|
"systemSettingsDescription": "Configure system-level settings and advanced options.",
|
||||||
"esmUrl": "Javascript CDN",
|
"esmUrl": "Javascript CDN",
|
||||||
"esmUrlDescription": "Javascript CDN URL for package imports.",
|
"esmUrlDescription": "Javascript CDN URL for package imports.",
|
||||||
@@ -87,8 +87,6 @@
|
|||||||
"add": "Add",
|
"add": "Add",
|
||||||
"remove": "Remove",
|
"remove": "Remove",
|
||||||
"retry": "Retry",
|
"retry": "Retry",
|
||||||
"latestFirst": "Latest First",
|
|
||||||
"oldestFirst": "Oldest First",
|
|
||||||
"name": "Name",
|
"name": "Name",
|
||||||
"email": "Email",
|
"email": "Email",
|
||||||
"buildNostrApps": "Build apps with AI",
|
"buildNostrApps": "Build apps with AI",
|
||||||
@@ -97,14 +95,14 @@
|
|||||||
"selectModelToDescribe": "Please select a model below, then describe what you'd like to build...",
|
"selectModelToDescribe": "Please select a model below, then describe what you'd like to build...",
|
||||||
"examplePrompt": "e.g., Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies...",
|
"examplePrompt": "e.g., Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies...",
|
||||||
"settingsDescription": "Manage your application settings and preferences.",
|
"settingsDescription": "Manage your application settings and preferences.",
|
||||||
"aiSettings": "AI Settings",
|
"aiSettings": "AI",
|
||||||
"aiSettingsDescription": "Configure AI providers and API keys",
|
"aiSettingsDescription": "Configure AI providers and API keys",
|
||||||
"gitSettings": "Git Settings",
|
"gitSettings": "Git",
|
||||||
"gitSettingsDescription": "Configure Git credentials for HTTP authentication",
|
"gitSettingsDescription": "Configure Git credentials for HTTP authentication",
|
||||||
"deploySettings": "Deployment",
|
"deploySettings": "Deployment",
|
||||||
"deploySettingsDescription": "Configure deployment providers",
|
"deploySettingsDescription": "Configure deployment providers",
|
||||||
"deploySettingsDescriptionLong": "Configure deployment providers to deploy your projects to various hosting platforms.",
|
"deploySettingsDescriptionLong": "Configure deployment providers to deploy your projects to various hosting platforms.",
|
||||||
"nostrSettings": "Nostr Settings",
|
"nostrSettings": "Nostr",
|
||||||
"nostrSettingsDescription": "Configure relay connections and Nostr preferences",
|
"nostrSettingsDescription": "Configure relay connections and Nostr preferences",
|
||||||
"storageSettings": "Storage",
|
"storageSettings": "Storage",
|
||||||
"storageSettingsDescription": "Export files and manage local data",
|
"storageSettingsDescription": "Export files and manage local data",
|
||||||
@@ -480,6 +478,26 @@
|
|||||||
"noPluginsConfigured": "No plugins configured. Add a plugin to get started.",
|
"noPluginsConfigured": "No plugins configured. Add a plugin to get started.",
|
||||||
"pluginsDirectory": "Plugins Directory",
|
"pluginsDirectory": "Plugins Directory",
|
||||||
"pluginsDirectoryDescription": "Directory where plugins are stored in the virtual filesystem.",
|
"pluginsDirectoryDescription": "Directory where plugins are stored in the virtual filesystem.",
|
||||||
|
"mcpServers": "MCP Servers",
|
||||||
|
"mcpServersDescription": "Connect to Model Context Protocol servers to extend the AI's capabilities with external tools.",
|
||||||
|
"addMcpServer": "Add MCP Server",
|
||||||
|
"mcpServerName": "Server Name",
|
||||||
|
"mcpServerUrl": "Server URL",
|
||||||
|
"mcpServerType": "Server Type",
|
||||||
|
"mcpServerTypeStreamableHttp": "Streamable HTTP",
|
||||||
|
"mcpServerDescription": "MCP servers provide tools that can be discovered and used by the AI assistant.",
|
||||||
|
"noMcpServersConfigured": "No MCP servers configured. Add a server to get started.",
|
||||||
|
"mcpServerAdded": "MCP Server Added",
|
||||||
|
"mcpServerAddedDescription": "MCP server \"{{name}}\" has been added successfully.",
|
||||||
|
"mcpServerAddFailed": "Failed to Add MCP Server",
|
||||||
|
"mcpServerDeleted": "MCP Server Deleted",
|
||||||
|
"mcpServerDeletedDescription": "MCP server \"{{name}}\" has been deleted successfully.",
|
||||||
|
"mcpServerDeleteFailed": "Failed to Delete MCP Server",
|
||||||
|
"mcpServerHeaders": "Headers",
|
||||||
|
"mcpServerHeadersDescription": "Add custom HTTP headers to be sent with requests to this MCP server (e.g., Authorization headers).",
|
||||||
|
"discoveringTools": "Discovering tools...",
|
||||||
|
"toolsDiscovered": "{{count}} tool(s) discovered",
|
||||||
|
"toolDiscoveryFailed": "Failed to discover tools from this server",
|
||||||
"filesystemPaths": "Filesystem Paths",
|
"filesystemPaths": "Filesystem Paths",
|
||||||
"projectsDirectory": "Projects Directory",
|
"projectsDirectory": "Projects Directory",
|
||||||
"projectsDirectoryDescription": "Directory where projects are stored in the virtual filesystem.",
|
"projectsDirectoryDescription": "Directory where projects are stored in the virtual filesystem.",
|
||||||
@@ -490,5 +508,10 @@
|
|||||||
"deleting": "Deleting...",
|
"deleting": "Deleting...",
|
||||||
"modified": "Modified",
|
"modified": "Modified",
|
||||||
"restoreToDefault": "Restore to default",
|
"restoreToDefault": "Restore to default",
|
||||||
"restoredToDefault": "Restored to Default"
|
"restoredToDefault": "Restored to Default",
|
||||||
|
"templateUpdateFailed": "Template Update Failed",
|
||||||
|
"templateUpdateFailedDescription": "Failed to update the project template from the remote repository. Using the cached version instead.",
|
||||||
|
"templatesDirectory": "Templates Directory",
|
||||||
|
"templatesDirectoryDescription": "Directory where project templates are cached in the virtual filesystem.",
|
||||||
|
"terminal": "Terminal"
|
||||||
}
|
}
|
||||||
+6
-7
@@ -11,7 +11,7 @@
|
|||||||
"themeDescription": "Zaɓi tsakanin haske, duhu, ko zaɓin jigogi na tsarin.",
|
"themeDescription": "Zaɓi tsakanin haske, duhu, ko zaɓin jigogi na tsarin.",
|
||||||
"language": "Harshe",
|
"language": "Harshe",
|
||||||
"languageDescription": "Zaɓi harshen da kuke so don dubawa.",
|
"languageDescription": "Zaɓi harshen da kuke so don dubawa.",
|
||||||
"systemSettings": "Saitunan Tsarin",
|
"systemSettings": "Tsarin",
|
||||||
"systemSettingsDescription": "Saita saitunan matakin tsari da zaɓuɓɓuka na ci gaba.",
|
"systemSettingsDescription": "Saita saitunan matakin tsari da zaɓuɓɓuka na ci gaba.",
|
||||||
"esmUrl": "URL na CDN Javascript",
|
"esmUrl": "URL na CDN Javascript",
|
||||||
"esmUrlDescription": "URL na CDN Javascript don shigo da fakitin.",
|
"esmUrlDescription": "URL na CDN Javascript don shigo da fakitin.",
|
||||||
@@ -83,8 +83,6 @@
|
|||||||
"add": "Ƙara",
|
"add": "Ƙara",
|
||||||
"remove": "Cire",
|
"remove": "Cire",
|
||||||
"retry": "Sake gwadawa",
|
"retry": "Sake gwadawa",
|
||||||
"latestFirst": "Na Baya-bayan nan Da farko",
|
|
||||||
"oldestFirst": "Na Dā Da farko",
|
|
||||||
"name": "Suna",
|
"name": "Suna",
|
||||||
"email": "Imel",
|
"email": "Imel",
|
||||||
"buildNostrApps": "Gina aikace-aikace da AI",
|
"buildNostrApps": "Gina aikace-aikace da AI",
|
||||||
@@ -93,11 +91,11 @@
|
|||||||
"selectModelToDescribe": "Da fatan za a zaɓi samfuri a ƙasa, sannan a bayyana abin da kuke son ginawa...",
|
"selectModelToDescribe": "Da fatan za a zaɓi samfuri a ƙasa, sannan a bayyana abin da kuke son ginawa...",
|
||||||
"examplePrompt": "misali, Ƙirƙiri kasuwar kayan aikin noma don manoma na yankin su sayi da sayar da taraktoci, kayan aiki, da kayayyaki...",
|
"examplePrompt": "misali, Ƙirƙiri kasuwar kayan aikin noma don manoma na yankin su sayi da sayar da taraktoci, kayan aiki, da kayayyaki...",
|
||||||
"settingsDescription": "Sarrafa saitunan aikace-aikacenku da zaɓuɓɓuka.",
|
"settingsDescription": "Sarrafa saitunan aikace-aikacenku da zaɓuɓɓuka.",
|
||||||
"aiSettings": "Saitunan AI",
|
"aiSettings": "AI",
|
||||||
"aiSettingsDescription": "Saita masu samar da AI da maɓallan API",
|
"aiSettingsDescription": "Saita masu samar da AI da maɓallan API",
|
||||||
"gitSettings": "Saitunan Git",
|
"gitSettings": "Git",
|
||||||
"gitSettingsDescription": "Saita bayanan shaidar Git don tabbatar da HTTP",
|
"gitSettingsDescription": "Saita bayanan shaidar Git don tabbatar da HTTP",
|
||||||
"nostrSettings": "Saitunan Nostr",
|
"nostrSettings": "Nostr",
|
||||||
"nostrSettingsDescription": "Saita haɗin relay da zaɓuɓɓukan Nostr",
|
"nostrSettingsDescription": "Saita haɗin relay da zaɓuɓɓukan Nostr",
|
||||||
"storageSettings": "Ajiya",
|
"storageSettings": "Ajiya",
|
||||||
"storageSettingsDescription": "Fitar da fayiloli da sarrafa bayanan gida",
|
"storageSettingsDescription": "Fitar da fayiloli da sarrafa bayanan gida",
|
||||||
@@ -429,5 +427,6 @@
|
|||||||
"giftCardAlreadyRedeemed": "An riga an fanshi wannan katin kyauta.",
|
"giftCardAlreadyRedeemed": "An riga an fanshi wannan katin kyauta.",
|
||||||
"modified": "An Canza",
|
"modified": "An Canza",
|
||||||
"restoreToDefault": "Mayar da asali",
|
"restoreToDefault": "Mayar da asali",
|
||||||
"restoredToDefault": "An Mayar da Asali"
|
"restoredToDefault": "An Mayar da Asali",
|
||||||
|
"terminal": "Terminal"
|
||||||
}
|
}
|
||||||
+6
-7
@@ -11,7 +11,7 @@
|
|||||||
"themeDescription": "Họrọ n'etiti ìhè, ọchịchịrị, ma ọ bụ nhọrọ isiokwu sistemu.",
|
"themeDescription": "Họrọ n'etiti ìhè, ọchịchịrị, ma ọ bụ nhọrọ isiokwu sistemu.",
|
||||||
"language": "Asụsụ",
|
"language": "Asụsụ",
|
||||||
"languageDescription": "Họrọ asụsụ ị chọrọ maka interface.",
|
"languageDescription": "Họrọ asụsụ ị chọrọ maka interface.",
|
||||||
"systemSettings": "Ntọala Sistemu",
|
"systemSettings": "Sistemu",
|
||||||
"systemSettingsDescription": "Hazie ntọala ọkwa sistemu na nhọrọ ndị ọganihu.",
|
"systemSettingsDescription": "Hazie ntọala ọkwa sistemu na nhọrọ ndị ọganihu.",
|
||||||
"esmUrl": "URL CDN Javascript",
|
"esmUrl": "URL CDN Javascript",
|
||||||
"esmUrlDescription": "URL CDN Javascript maka mbubata ngwugwu.",
|
"esmUrlDescription": "URL CDN Javascript maka mbubata ngwugwu.",
|
||||||
@@ -83,8 +83,6 @@
|
|||||||
"add": "Tinye",
|
"add": "Tinye",
|
||||||
"remove": "Wepụ",
|
"remove": "Wepụ",
|
||||||
"retry": "Nwaa ọzọ",
|
"retry": "Nwaa ọzọ",
|
||||||
"latestFirst": "Nke Ọhụrụ Mbụ",
|
|
||||||
"oldestFirst": "Nke Ochie Mbụ",
|
|
||||||
"name": "Aha",
|
"name": "Aha",
|
||||||
"email": "Ozi-eletrọniki",
|
"email": "Ozi-eletrọniki",
|
||||||
"buildNostrApps": "Wuo ngwa na AI",
|
"buildNostrApps": "Wuo ngwa na AI",
|
||||||
@@ -93,11 +91,11 @@
|
|||||||
"selectModelToDescribe": "Biko họrọ ụdịdị n'okpuru, wee kọwaa ihe ị chọrọ iwu...",
|
"selectModelToDescribe": "Biko họrọ ụdịdị n'okpuru, wee kọwaa ihe ị chọrọ iwu...",
|
||||||
"examplePrompt": "ọmụmaatụ, Mepụta ahịa ngwá ọrụ ugbo maka ndị ọrụ ugbo mpaghara ịzụta na ire traktọ, ngwá ọrụ, na ngwa...",
|
"examplePrompt": "ọmụmaatụ, Mepụta ahịa ngwá ọrụ ugbo maka ndị ọrụ ugbo mpaghara ịzụta na ire traktọ, ngwá ọrụ, na ngwa...",
|
||||||
"settingsDescription": "Jikwaa ntọala ngwa gị na nhọrọ.",
|
"settingsDescription": "Jikwaa ntọala ngwa gị na nhọrọ.",
|
||||||
"aiSettings": "Ntọala AI",
|
"aiSettings": "AI",
|
||||||
"aiSettingsDescription": "Hazie ndị na-enye AI na igodo API",
|
"aiSettingsDescription": "Hazie ndị na-enye AI na igodo API",
|
||||||
"gitSettings": "Ntọala Git",
|
"gitSettings": "Git",
|
||||||
"gitSettingsDescription": "Hazie nzere Git maka nkwenye HTTP",
|
"gitSettingsDescription": "Hazie nzere Git maka nkwenye HTTP",
|
||||||
"nostrSettings": "Ntọala Nostr",
|
"nostrSettings": "Nostr",
|
||||||
"nostrSettingsDescription": "Hazie njikọ relay na nhọrọ Nostr",
|
"nostrSettingsDescription": "Hazie njikọ relay na nhọrọ Nostr",
|
||||||
"storageSettings": "Nchekwa",
|
"storageSettings": "Nchekwa",
|
||||||
"storageSettingsDescription": "Bupụta faịlụ na jikwaa data mpaghara",
|
"storageSettingsDescription": "Bupụta faịlụ na jikwaa data mpaghara",
|
||||||
@@ -426,5 +424,6 @@
|
|||||||
"giftCardAlreadyRedeemed": "Egbapụtalarị kaadị onyinye a.",
|
"giftCardAlreadyRedeemed": "Egbapụtalarị kaadị onyinye a.",
|
||||||
"modified": "Gbanwere",
|
"modified": "Gbanwere",
|
||||||
"restoreToDefault": "Weghachi na nke mbụ",
|
"restoreToDefault": "Weghachi na nke mbụ",
|
||||||
"restoredToDefault": "Weghachiri na Nke Mbụ"
|
"restoredToDefault": "Weghachiri na Nke Mbụ",
|
||||||
|
"terminal": "Terminal"
|
||||||
}
|
}
|
||||||
+6
-7
@@ -11,7 +11,7 @@
|
|||||||
"themeDescription": "Escolha entre preferência de tema claro, escuro ou do sistema.",
|
"themeDescription": "Escolha entre preferência de tema claro, escuro ou do sistema.",
|
||||||
"language": "Idioma",
|
"language": "Idioma",
|
||||||
"languageDescription": "Selecione seu idioma preferido para a interface.",
|
"languageDescription": "Selecione seu idioma preferido para a interface.",
|
||||||
"systemSettings": "Configurações do Sistema",
|
"systemSettings": "Sistema",
|
||||||
"systemSettingsDescription": "Configure configurações de nível de sistema e opções avançadas.",
|
"systemSettingsDescription": "Configure configurações de nível de sistema e opções avançadas.",
|
||||||
"esmUrl": "URL do CDN Javascript",
|
"esmUrl": "URL do CDN Javascript",
|
||||||
"esmUrlDescription": "URL do CDN Javascript para importações de pacotes.",
|
"esmUrlDescription": "URL do CDN Javascript para importações de pacotes.",
|
||||||
@@ -83,8 +83,6 @@
|
|||||||
"add": "Adicionar",
|
"add": "Adicionar",
|
||||||
"remove": "Remover",
|
"remove": "Remover",
|
||||||
"retry": "Tentar novamente",
|
"retry": "Tentar novamente",
|
||||||
"latestFirst": "Mais Recentes Primeiro",
|
|
||||||
"oldestFirst": "Mais Antigos Primeiro",
|
|
||||||
"name": "Nome",
|
"name": "Nome",
|
||||||
"email": "Email",
|
"email": "Email",
|
||||||
"buildNostrApps": "Construa aplicativos com IA",
|
"buildNostrApps": "Construa aplicativos com IA",
|
||||||
@@ -93,14 +91,14 @@
|
|||||||
"selectModelToDescribe": "Por favor, selecione um modelo abaixo e depois descreva o que gostaria de construir...",
|
"selectModelToDescribe": "Por favor, selecione um modelo abaixo e depois descreva o que gostaria de construir...",
|
||||||
"examplePrompt": "ex., Criar um marketplace de equipamentos agrícolas para fazendeiros locais comprarem e venderem tratores, ferramentas e suprimentos...",
|
"examplePrompt": "ex., Criar um marketplace de equipamentos agrícolas para fazendeiros locais comprarem e venderem tratores, ferramentas e suprimentos...",
|
||||||
"settingsDescription": "Gerencie as configurações e preferências da aplicação.",
|
"settingsDescription": "Gerencie as configurações e preferências da aplicação.",
|
||||||
"aiSettings": "Configurações de IA",
|
"aiSettings": "IA",
|
||||||
"aiSettingsDescription": "Configure provedores de IA e chaves de API",
|
"aiSettingsDescription": "Configure provedores de IA e chaves de API",
|
||||||
"gitSettings": "Configurações do Git",
|
"gitSettings": "Git",
|
||||||
"gitSettingsDescription": "Configure credenciais do Git para autenticação HTTP",
|
"gitSettingsDescription": "Configure credenciais do Git para autenticação HTTP",
|
||||||
"deploySettings": "Implantação",
|
"deploySettings": "Implantação",
|
||||||
"deploySettingsDescription": "Configure provedores de implantação",
|
"deploySettingsDescription": "Configure provedores de implantação",
|
||||||
"deploySettingsDescriptionLong": "Configure provedores de implantação para implantar seus projetos em várias plataformas de hospedagem.",
|
"deploySettingsDescriptionLong": "Configure provedores de implantação para implantar seus projetos em várias plataformas de hospedagem.",
|
||||||
"nostrSettings": "Configurações do Nostr",
|
"nostrSettings": "Nostr",
|
||||||
"nostrSettingsDescription": "Configure conexões de relay e preferências do Nostr",
|
"nostrSettingsDescription": "Configure conexões de relay e preferências do Nostr",
|
||||||
"storageSettings": "Armazenamento",
|
"storageSettings": "Armazenamento",
|
||||||
"storageSettingsDescription": "Exporte arquivos e gerencie dados locais",
|
"storageSettingsDescription": "Exporte arquivos e gerencie dados locais",
|
||||||
@@ -439,5 +437,6 @@
|
|||||||
"giftCardAlreadyRedeemed": "Este cartão presente já foi resgatado.",
|
"giftCardAlreadyRedeemed": "Este cartão presente já foi resgatado.",
|
||||||
"modified": "Modificado",
|
"modified": "Modificado",
|
||||||
"restoreToDefault": "Restaurar para padrão",
|
"restoreToDefault": "Restaurar para padrão",
|
||||||
"restoredToDefault": "Restaurado para Padrão"
|
"restoredToDefault": "Restaurado para Padrão",
|
||||||
|
"terminal": "Terminal"
|
||||||
}
|
}
|
||||||
+6
-7
@@ -11,7 +11,7 @@
|
|||||||
"themeDescription": "Yan laarin imọlẹ, okunkun, tabi ayanfẹ akori eto.",
|
"themeDescription": "Yan laarin imọlẹ, okunkun, tabi ayanfẹ akori eto.",
|
||||||
"language": "Ede",
|
"language": "Ede",
|
||||||
"languageDescription": "Yan ede ti o fẹran fun wiwo.",
|
"languageDescription": "Yan ede ti o fẹran fun wiwo.",
|
||||||
"systemSettings": "Saitunan Eto",
|
"systemSettings": "Eto",
|
||||||
"systemSettingsDescription": "Tunto awọn saitan eto ati awọn ayanfẹ ti o pọju.",
|
"systemSettingsDescription": "Tunto awọn saitan eto ati awọn ayanfẹ ti o pọju.",
|
||||||
"esmUrl": "URL CDN Javascript",
|
"esmUrl": "URL CDN Javascript",
|
||||||
"esmUrlDescription": "URL CDN Javascript fun gbigbe awọn package.",
|
"esmUrlDescription": "URL CDN Javascript fun gbigbe awọn package.",
|
||||||
@@ -83,8 +83,6 @@
|
|||||||
"add": "Fi kun",
|
"add": "Fi kun",
|
||||||
"remove": "Yọ kuro",
|
"remove": "Yọ kuro",
|
||||||
"retry": "Tun gbiyanju",
|
"retry": "Tun gbiyanju",
|
||||||
"latestFirst": "Tuntun Akọkọ",
|
|
||||||
"oldestFirst": "Atijọ Akọkọ",
|
|
||||||
"name": "Orukọ",
|
"name": "Orukọ",
|
||||||
"email": "Imeeli",
|
"email": "Imeeli",
|
||||||
"buildNostrApps": "Kọ awọn ohun elo pẹlu AI",
|
"buildNostrApps": "Kọ awọn ohun elo pẹlu AI",
|
||||||
@@ -93,11 +91,11 @@
|
|||||||
"selectModelToDescribe": "Jọwọ yan awoṣe ni isalẹ, lẹhinna ṣapejuwe ohun ti o fẹ kọ...",
|
"selectModelToDescribe": "Jọwọ yan awoṣe ni isalẹ, lẹhinna ṣapejuwe ohun ti o fẹ kọ...",
|
||||||
"examplePrompt": "apeere, Ṣẹda ọja ẹrọ ogbin fun awọn agbe agbegbe lati ra ati ta awọn traktọ, awọn irinṣẹ, ati awọn ipese...",
|
"examplePrompt": "apeere, Ṣẹda ọja ẹrọ ogbin fun awọn agbe agbegbe lati ra ati ta awọn traktọ, awọn irinṣẹ, ati awọn ipese...",
|
||||||
"settingsDescription": "Ṣakoso awọn eto ohun elo rẹ ati awọn ayanfẹ.",
|
"settingsDescription": "Ṣakoso awọn eto ohun elo rẹ ati awọn ayanfẹ.",
|
||||||
"aiSettings": "Awọn eto AI",
|
"aiSettings": "AI",
|
||||||
"aiSettingsDescription": "Tunto awọn olupese AI ati awọn bọtini API",
|
"aiSettingsDescription": "Tunto awọn olupese AI ati awọn bọtini API",
|
||||||
"gitSettings": "Awọn eto Git",
|
"gitSettings": "Git",
|
||||||
"gitSettingsDescription": "Tunto awọn ẹri Git fun ijẹrisi HTTP",
|
"gitSettingsDescription": "Tunto awọn ẹri Git fun ijẹrisi HTTP",
|
||||||
"nostrSettings": "Awọn eto Nostr",
|
"nostrSettings": "Nostr",
|
||||||
"nostrSettingsDescription": "Tunto awọn asopọ relay ati awọn ayanfẹ Nostr",
|
"nostrSettingsDescription": "Tunto awọn asopọ relay ati awọn ayanfẹ Nostr",
|
||||||
"storageSettings": "Ibi ipamọ",
|
"storageSettings": "Ibi ipamọ",
|
||||||
"storageSettingsDescription": "Gbe awọn faili jade ati ṣakoso data agbegbe",
|
"storageSettingsDescription": "Gbe awọn faili jade ati ṣakoso data agbegbe",
|
||||||
@@ -426,5 +424,6 @@
|
|||||||
"giftCardAlreadyRedeemed": "A ti ra kaadi ẹbun yii tẹlẹ.",
|
"giftCardAlreadyRedeemed": "A ti ra kaadi ẹbun yii tẹlẹ.",
|
||||||
"modified": "Ti Yipada",
|
"modified": "Ti Yipada",
|
||||||
"restoreToDefault": "Pada si atilẹwa",
|
"restoreToDefault": "Pada si atilẹwa",
|
||||||
"restoredToDefault": "Ti Pada si Atilẹwa"
|
"restoredToDefault": "Ti Pada si Atilẹwa",
|
||||||
|
"terminal": "Terminal"
|
||||||
}
|
}
|
||||||
+6
-7
@@ -11,7 +11,7 @@
|
|||||||
"themeDescription": "选择浅色、深色或系统主题偏好。",
|
"themeDescription": "选择浅色、深色或系统主题偏好。",
|
||||||
"language": "语言",
|
"language": "语言",
|
||||||
"languageDescription": "选择您的界面首选语言。",
|
"languageDescription": "选择您的界面首选语言。",
|
||||||
"systemSettings": "系统设置",
|
"systemSettings": "系统",
|
||||||
"systemSettingsDescription": "配置系统级设置和高级选项。",
|
"systemSettingsDescription": "配置系统级设置和高级选项。",
|
||||||
"esmUrl": "Javascript CDN URL",
|
"esmUrl": "Javascript CDN URL",
|
||||||
"esmUrlDescription": "包导入的 Javascript CDN URL。",
|
"esmUrlDescription": "包导入的 Javascript CDN URL。",
|
||||||
@@ -83,8 +83,6 @@
|
|||||||
"add": "添加",
|
"add": "添加",
|
||||||
"remove": "移除",
|
"remove": "移除",
|
||||||
"retry": "重试",
|
"retry": "重试",
|
||||||
"latestFirst": "最新优先",
|
|
||||||
"oldestFirst": "最旧优先",
|
|
||||||
"name": "名称",
|
"name": "名称",
|
||||||
"email": "邮箱",
|
"email": "邮箱",
|
||||||
"buildNostrApps": "使用AI构建应用",
|
"buildNostrApps": "使用AI构建应用",
|
||||||
@@ -93,14 +91,14 @@
|
|||||||
"selectModelToDescribe": "请在下方选择一个模型,然后描述您想要构建的内容...",
|
"selectModelToDescribe": "请在下方选择一个模型,然后描述您想要构建的内容...",
|
||||||
"examplePrompt": "例如:为当地农民创建一个农业设备市场,用于买卖拖拉机、工具和用品...",
|
"examplePrompt": "例如:为当地农民创建一个农业设备市场,用于买卖拖拉机、工具和用品...",
|
||||||
"settingsDescription": "管理您的应用程序设置和偏好。",
|
"settingsDescription": "管理您的应用程序设置和偏好。",
|
||||||
"aiSettings": "AI设置",
|
"aiSettings": "AI",
|
||||||
"aiSettingsDescription": "配置AI提供商和API密钥",
|
"aiSettingsDescription": "配置AI提供商和API密钥",
|
||||||
"gitSettings": "Git设置",
|
"gitSettings": "Git",
|
||||||
"gitSettingsDescription": "配置HTTP身份验证的Git凭据",
|
"gitSettingsDescription": "配置HTTP身份验证的Git凭据",
|
||||||
"deploySettings": "部署",
|
"deploySettings": "部署",
|
||||||
"deploySettingsDescription": "配置部署提供商",
|
"deploySettingsDescription": "配置部署提供商",
|
||||||
"deploySettingsDescriptionLong": "配置部署提供商以将您的项目部署到各种托管平台。",
|
"deploySettingsDescriptionLong": "配置部署提供商以将您的项目部署到各种托管平台。",
|
||||||
"nostrSettings": "Nostr设置",
|
"nostrSettings": "Nostr",
|
||||||
"nostrSettingsDescription": "配置中继连接和Nostr偏好",
|
"nostrSettingsDescription": "配置中继连接和Nostr偏好",
|
||||||
"storageSettings": "存储",
|
"storageSettings": "存储",
|
||||||
"storageSettingsDescription": "导出文件和管理本地数据",
|
"storageSettingsDescription": "导出文件和管理本地数据",
|
||||||
@@ -439,5 +437,6 @@
|
|||||||
"giftCardAlreadyRedeemed": "此礼品卡已被兑换。",
|
"giftCardAlreadyRedeemed": "此礼品卡已被兑换。",
|
||||||
"modified": "已修改",
|
"modified": "已修改",
|
||||||
"restoreToDefault": "恢复默认值",
|
"restoreToDefault": "恢复默认值",
|
||||||
"restoredToDefault": "已恢复默认值"
|
"restoredToDefault": "已恢复默认值",
|
||||||
|
"terminal": "终端"
|
||||||
}
|
}
|
||||||
@@ -36,6 +36,7 @@ import { useNavigate, Link } from 'react-router-dom';
|
|||||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||||
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
||||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||||
|
import { MCPServersSection } from '@/components/MCPServersSection';
|
||||||
import { PluginsSection } from '@/components/PluginsSection';
|
import { PluginsSection } from '@/components/PluginsSection';
|
||||||
|
|
||||||
interface SortableProviderItemProps {
|
interface SortableProviderItemProps {
|
||||||
@@ -566,6 +567,9 @@ export function AISettings() {
|
|||||||
</Accordion>
|
</Accordion>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* MCP Servers Section */}
|
||||||
|
<MCPServersSection />
|
||||||
|
|
||||||
{/* Plugins Section */}
|
{/* Plugins Section */}
|
||||||
<PluginsSection />
|
<PluginsSection />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+56
-192
@@ -4,8 +4,6 @@ import { useTranslation } from 'react-i18next';
|
|||||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||||
import { useAIProjectId } from '@/hooks/useAIProjectId';
|
import { useAIProjectId } from '@/hooks/useAIProjectId';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
|
||||||
import { useAISettings } from '@/hooks/useAISettings';
|
import { useAISettings } from '@/hooks/useAISettings';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
import { AppLayout } from '@/components/AppLayout';
|
import { AppLayout } from '@/components/AppLayout';
|
||||||
@@ -15,22 +13,17 @@ import { GiftCardRedeemDialog } from '@/components/GiftCardRedeemDialog';
|
|||||||
import { Quilly } from '@/components/Quilly';
|
import { Quilly } from '@/components/Quilly';
|
||||||
import { DotAI } from '@/lib/DotAI';
|
import { DotAI } from '@/lib/DotAI';
|
||||||
import type { AIMessage } from '@/lib/SessionManager';
|
import type { AIMessage } from '@/lib/SessionManager';
|
||||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
import { buildMessageContent } from '@/lib/buildMessageContent';
|
||||||
import type OpenAI from 'openai';
|
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
||||||
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 { ArrowUp } from 'lucide-react';
|
|
||||||
import { useSeoMeta } from '@unhead/react';
|
import { useSeoMeta } from '@unhead/react';
|
||||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||||
import { AppShowcase } from '@/components/AppShowcase';
|
import { AppShowcase } from '@/components/AppShowcase';
|
||||||
|
import { useToast } from '@/hooks/useToast';
|
||||||
|
|
||||||
export default function Index() {
|
export default function Index() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [prompt, setPrompt] = useState('');
|
const { toast } = useToast();
|
||||||
const [isCreating, setIsCreating] = useState(false);
|
const [isCreating, setIsCreating] = useState(false);
|
||||||
const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', '');
|
|
||||||
const [showOnboarding, setShowOnboarding] = useState(false);
|
const [showOnboarding, setShowOnboarding] = useState(false);
|
||||||
const [showAct1Dialog, setShowAct1Dialog] = useState(false);
|
const [showAct1Dialog, setShowAct1Dialog] = useState(false);
|
||||||
const [showGiftCardDialog, setShowGiftCardDialog] = useState(false);
|
const [showGiftCardDialog, setShowGiftCardDialog] = useState(false);
|
||||||
@@ -47,10 +40,9 @@ export default function Index() {
|
|||||||
// Initialize with first recently used model if available, otherwise empty
|
// Initialize with first recently used model if available, otherwise empty
|
||||||
return settings.recentlyUsedModels?.[0] || '';
|
return settings.recentlyUsedModels?.[0] || '';
|
||||||
});
|
});
|
||||||
const isMobile = useIsMobile();
|
|
||||||
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
|
||||||
const [isDragOver, setIsDragOver] = useState(false);
|
const [isDragOver, setIsDragOver] = useState(false);
|
||||||
const [quillyError, setQuillyError] = useState<Error | null>(null);
|
const [quillyError, setQuillyError] = useState<Error | null>(null);
|
||||||
|
const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
|
||||||
|
|
||||||
// Check if any providers are configured
|
// Check if any providers are configured
|
||||||
const hasProvidersConfigured = settings.providers.length > 0;
|
const hasProvidersConfigured = settings.providers.length > 0;
|
||||||
@@ -66,12 +58,6 @@ export default function Index() {
|
|||||||
description: 'Build custom apps with AI assistance using Shakespeare, an AI-powered development environment.',
|
description: 'Build custom apps with AI assistance using Shakespeare, an AI-powered development environment.',
|
||||||
});
|
});
|
||||||
|
|
||||||
// Restore prompt from local storage on mount
|
|
||||||
useEffect(() => {
|
|
||||||
if (storedPrompt) {
|
|
||||||
setPrompt(storedPrompt);
|
|
||||||
}
|
|
||||||
}, [storedPrompt]);
|
|
||||||
|
|
||||||
// Check for Act 1 users and show welcome dialog
|
// Check for Act 1 users and show welcome dialog
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -105,21 +91,6 @@ export default function Index() {
|
|||||||
}
|
}
|
||||||
}, [location, navigate]);
|
}, [location, navigate]);
|
||||||
|
|
||||||
// Sync prompt with local storage
|
|
||||||
const handlePromptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
|
||||||
const newPrompt = e.target.value;
|
|
||||||
setPrompt(newPrompt);
|
|
||||||
setStoredPrompt(newPrompt);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleFileSelect = (file: File) => {
|
|
||||||
setAttachedFiles(prev => [...prev, file]);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleFileRemove = (fileToRemove: File) => {
|
|
||||||
setAttachedFiles(prev => prev.filter(file => file !== fileToRemove));
|
|
||||||
};
|
|
||||||
|
|
||||||
// Drag and drop handlers
|
// Drag and drop handlers
|
||||||
const handleDragEnter = (e: React.DragEvent) => {
|
const handleDragEnter = (e: React.DragEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -153,41 +124,10 @@ export default function Index() {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
setIsDragOver(false);
|
setIsDragOver(false);
|
||||||
|
|
||||||
if (isCreating || isGeneratingId || !providerModel.trim()) return;
|
|
||||||
|
|
||||||
const files = Array.from(e.dataTransfer.files);
|
|
||||||
if (files.length === 0) return;
|
|
||||||
|
|
||||||
// Add all files without validation
|
|
||||||
setAttachedFiles(prev => [...prev, ...files]);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Handle keyboard shortcuts (physical keyboards only)
|
// Handle textarea focus - show onboarding if no providers configured
|
||||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
const handleTextareaFocus = () => {
|
||||||
if (e.key === 'Enter') {
|
|
||||||
// On mobile devices, always allow Enter to create new lines
|
|
||||||
// since there's no Shift key available for multi-line input
|
|
||||||
if (isMobile) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (e.shiftKey) {
|
|
||||||
// Shift+Enter on desktop: Allow new line (default behavior)
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Enter without Shift on desktop: Submit only if no newlines exist in prompt and model is selected
|
|
||||||
if (!prompt.includes('\n') && providerModel.trim()) {
|
|
||||||
e.preventDefault();
|
|
||||||
handleCreateProject();
|
|
||||||
}
|
|
||||||
// If prompt contains newlines or no model selected, allow Enter to create new line (default behavior)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Handle textarea click - show onboarding if no providers configured
|
|
||||||
const handleTextareaClick = () => {
|
|
||||||
if (!hasProvidersConfigured) {
|
if (!hasProvidersConfigured) {
|
||||||
setShowOnboarding(true);
|
setShowOnboarding(true);
|
||||||
}
|
}
|
||||||
@@ -199,10 +139,7 @@ export default function Index() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleQuillyNewChat = () => {
|
const handleQuillyNewChat = () => {
|
||||||
// Clear current prompt and start fresh
|
// Clear error - ChatInput manages its own state
|
||||||
setPrompt('');
|
|
||||||
setStoredPrompt('');
|
|
||||||
setAttachedFiles([]);
|
|
||||||
setQuillyError(null);
|
setQuillyError(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -214,71 +151,52 @@ export default function Index() {
|
|||||||
setQuillyError(null);
|
setQuillyError(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCreateProject = async () => {
|
const handleSend = async (input: string, files: File[]) => {
|
||||||
if (!prompt.trim() || !providerModel.trim()) return;
|
if (!input.trim() && files.length === 0) return;
|
||||||
|
if (!providerModel.trim()) return;
|
||||||
// Clear stored prompt when creating project
|
|
||||||
setStoredPrompt('');
|
|
||||||
|
|
||||||
setIsCreating(true);
|
setIsCreating(true);
|
||||||
try {
|
try {
|
||||||
// Use AI to generate project ID
|
// Use AI to generate project ID
|
||||||
const projectId = await generateProjectId(providerModel, prompt.trim());
|
const projectId = await generateProjectId(providerModel, input.trim());
|
||||||
|
|
||||||
// Add model to recently used when creating project with AI
|
// Add model to recently used when creating project with AI
|
||||||
addRecentlyUsedModel(providerModel.trim());
|
addRecentlyUsedModel(providerModel.trim());
|
||||||
|
|
||||||
// Create project with AI-generated ID
|
// Create project with AI-generated ID and handle template update errors
|
||||||
const project = await projectsManager.createProject(prompt.trim(), config.projectTemplate, projectId);
|
const project = await projectsManager.createProject(
|
||||||
|
input.trim(),
|
||||||
// Build message content as text parts (same as ChatPane)
|
config.projectTemplate,
|
||||||
const contentParts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
|
projectId,
|
||||||
|
() => {
|
||||||
// Add user input as text part if present
|
// Show a toast if template update fails (non-critical)
|
||||||
if (prompt.trim()) {
|
toast({
|
||||||
contentParts.push({
|
title: t('templateUpdateFailed'),
|
||||||
type: 'text',
|
description: t('templateUpdateFailedDescription'),
|
||||||
text: prompt.trim()
|
variant: 'default',
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process attached files and add as separate text parts
|
|
||||||
if (attachedFiles.length > 0) {
|
|
||||||
const filePromises = attachedFiles.map(async (file) => {
|
|
||||||
try {
|
|
||||||
const savedPath = await saveFileToTmp(fs, file);
|
|
||||||
return `Added file: ${savedPath}`;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to save file:', error);
|
|
||||||
return `Failed to save file: ${file.name}`;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const fileResults = await Promise.all(filePromises);
|
|
||||||
|
|
||||||
// Add each file as a separate text part
|
|
||||||
fileResults.forEach(fileResult => {
|
|
||||||
contentParts.push({
|
|
||||||
type: 'text',
|
|
||||||
text: fileResult
|
|
||||||
});
|
});
|
||||||
});
|
}
|
||||||
}
|
);
|
||||||
|
|
||||||
|
// Build message content from input and attached files
|
||||||
|
// Images are converted to base64-encoded data URLs
|
||||||
|
const messageContent = await buildMessageContent(
|
||||||
|
input.trim(),
|
||||||
|
files,
|
||||||
|
fs,
|
||||||
|
undefined
|
||||||
|
);
|
||||||
|
|
||||||
// Store the initial message in chat history using DotAI
|
// Store the initial message in chat history using DotAI
|
||||||
const dotAI = new DotAI(fs, `${config.fsPathProjects}/${project.id}`);
|
const dotAI = new DotAI(fs, `${config.fsPathProjects}/${project.id}`);
|
||||||
const sessionName = DotAI.generateSessionName();
|
const sessionName = DotAI.generateSessionName();
|
||||||
|
|
||||||
// Create initial message with content parts (same format as ChatPane)
|
|
||||||
const initialMessage: AIMessage = {
|
const initialMessage: AIMessage = {
|
||||||
role: 'user',
|
role: 'user',
|
||||||
content: contentParts.length === 1 ? contentParts[0].text : contentParts
|
content: messageContent
|
||||||
};
|
};
|
||||||
await dotAI.setHistory(sessionName, [initialMessage]);
|
await dotAI.setHistory(sessionName, [initialMessage]);
|
||||||
|
|
||||||
// Clear attached files after successful creation
|
|
||||||
setAttachedFiles([]);
|
|
||||||
|
|
||||||
// Navigate to the project with autostart parameter and model
|
// Navigate to the project with autostart parameter and model
|
||||||
const searchParams = new URLSearchParams({
|
const searchParams = new URLSearchParams({
|
||||||
autostart: 'true',
|
autostart: 'true',
|
||||||
@@ -302,7 +220,7 @@ export default function Index() {
|
|||||||
<div className="max-w-4xl mx-auto">
|
<div className="max-w-4xl mx-auto">
|
||||||
<div className="text-center mb-8 md:mb-12">
|
<div className="text-center mb-8 md:mb-12">
|
||||||
<div className="mb-4 md:mb-6">
|
<div className="mb-4 md:mb-6">
|
||||||
<ShakespeareLogo className="w-20 h-20 md:w-24 md:h-24 mx-auto" />
|
<ShakespeareLogo className={`w-20 h-20 md:w-24 md:h-24 mx-auto transition-transform duration-300 ${isCreating || isGeneratingId ? 'animate-spin' : ''}`} />
|
||||||
</div>
|
</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">
|
<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')}
|
{t('buildNostrApps')}
|
||||||
@@ -326,84 +244,30 @@ export default function Index() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Chat Input Container - matching the ChatPane style */}
|
{/* Chat Input */}
|
||||||
<div
|
<ChatInput
|
||||||
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' : ''
|
isLoading={isCreating || isGeneratingId}
|
||||||
}`}
|
isConfigured={hasProvidersConfigured}
|
||||||
|
providerModel={providerModel}
|
||||||
|
onProviderModelChange={setProviderModel}
|
||||||
|
onSend={handleSend}
|
||||||
|
onStop={() => {
|
||||||
|
// No-op for Index page - project creation can't be stopped
|
||||||
|
}}
|
||||||
|
onFocus={handleTextareaFocus}
|
||||||
|
onFirstInteraction={() => {
|
||||||
|
// No-op for Index page
|
||||||
|
}}
|
||||||
|
isModelSelectorOpen={isModelSelectorOpen}
|
||||||
|
onModelSelectorOpenChange={setIsModelSelectorOpen}
|
||||||
|
contextUsagePercentage={0}
|
||||||
|
totalCost={0}
|
||||||
|
isDragOver={isDragOver}
|
||||||
onDragEnter={handleDragEnter}
|
onDragEnter={handleDragEnter}
|
||||||
onDragOver={handleDragOver}
|
onDragOver={handleDragOver}
|
||||||
onDragLeave={handleDragLeave}
|
onDragLeave={handleDragLeave}
|
||||||
onDrop={handleDrop}
|
onDrop={handleDrop}
|
||||||
>
|
/>
|
||||||
<Textarea
|
|
||||||
placeholder={
|
|
||||||
!hasProvidersConfigured
|
|
||||||
? t('examplePrompt')
|
|
||||||
: !providerModel.trim()
|
|
||||||
? t('selectModelToDescribe')
|
|
||||||
: t('examplePrompt')
|
|
||||||
}
|
|
||||||
value={prompt}
|
|
||||||
onChange={handlePromptChange}
|
|
||||||
onKeyDown={handleKeyDown}
|
|
||||||
onClick={handleTextareaClick}
|
|
||||||
className="min-h-[120px] max-h-64 resize-none border-0 bg-transparent px-4 py-3 pb-16 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
|
|
||||||
disabled={isCreating || isGeneratingId || (hasProvidersConfigured && !providerModel.trim())}
|
|
||||||
rows={4}
|
|
||||||
style={{
|
|
||||||
height: 'auto',
|
|
||||||
minHeight: '120px'
|
|
||||||
}}
|
|
||||||
onInput={(e) => {
|
|
||||||
const target = e.target as HTMLTextAreaElement;
|
|
||||||
target.style.height = 'auto';
|
|
||||||
target.style.height = Math.min(target.scrollHeight, 256) + 'px';
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Bottom Controls Row */}
|
|
||||||
<div className="absolute bottom-3 left-3 right-3 flex items-center justify-end gap-4 overflow-hidden">
|
|
||||||
{/* File Attachment */}
|
|
||||||
<FileAttachment
|
|
||||||
className="mr-auto"
|
|
||||||
onFileSelect={handleFileSelect}
|
|
||||||
onFileRemove={handleFileRemove}
|
|
||||||
selectedFiles={attachedFiles}
|
|
||||||
disabled={isCreating || isGeneratingId}
|
|
||||||
multiple={true}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Model Selector - always show to allow configuration */}
|
|
||||||
<div className="overflow-hidden">
|
|
||||||
<ModelSelector
|
|
||||||
value={providerModel}
|
|
||||||
onChange={setProviderModel}
|
|
||||||
className="w-full"
|
|
||||||
disabled={isCreating || isGeneratingId}
|
|
||||||
placeholder={t('chooseModel')}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Create Project Button */}
|
|
||||||
<Button
|
|
||||||
onClick={handleCreateProject}
|
|
||||||
disabled={
|
|
||||||
!prompt.trim() ||
|
|
||||||
isCreating ||
|
|
||||||
isGeneratingId ||
|
|
||||||
(hasProvidersConfigured && !providerModel.trim())
|
|
||||||
}
|
|
||||||
size="sm"
|
|
||||||
className="size-8 [&_svg]:size-5 rounded-full p-0"
|
|
||||||
>
|
|
||||||
{isCreating || isGeneratingId ? (
|
|
||||||
<div className="animate-spin rounded-full h-3 w-3 border-b-2 border-white" />
|
|
||||||
) : (
|
|
||||||
<ArrowUp />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
+123
-16
@@ -13,6 +13,7 @@ import { useAppContext } from "@/hooks/useAppContext";
|
|||||||
import { useOffline } from "@/hooks/useOffline";
|
import { useOffline } from "@/hooks/useOffline";
|
||||||
import { useToast } from "@/hooks/useToast";
|
import { useToast } from "@/hooks/useToast";
|
||||||
import { defaultSystemPrompt } from "@/lib/system";
|
import { defaultSystemPrompt } from "@/lib/system";
|
||||||
|
import { Terminal } from "@/components/Terminal";
|
||||||
|
|
||||||
export function SystemSettings() {
|
export function SystemSettings() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -32,6 +33,7 @@ export function SystemSettings() {
|
|||||||
const [fsPathConfigInput, setFsPathConfigInput] = useState(config.fsPathConfig);
|
const [fsPathConfigInput, setFsPathConfigInput] = useState(config.fsPathConfig);
|
||||||
const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp);
|
const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp);
|
||||||
const [fsPathPluginsInput, setFsPathPluginsInput] = useState(config.fsPathPlugins);
|
const [fsPathPluginsInput, setFsPathPluginsInput] = useState(config.fsPathPlugins);
|
||||||
|
const [fsPathTemplatesInput, setFsPathTemplatesInput] = useState(config.fsPathTemplates);
|
||||||
const [sentryDsnInput, setSentryDsnInput] = useState(config.sentryDsn);
|
const [sentryDsnInput, setSentryDsnInput] = useState(config.sentryDsn);
|
||||||
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
|
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
|
||||||
|
|
||||||
@@ -48,86 +50,134 @@ export function SystemSettings() {
|
|||||||
fsPathConfig: config.fsPathConfig !== defaultConfig.fsPathConfig,
|
fsPathConfig: config.fsPathConfig !== defaultConfig.fsPathConfig,
|
||||||
fsPathTmp: config.fsPathTmp !== defaultConfig.fsPathTmp,
|
fsPathTmp: config.fsPathTmp !== defaultConfig.fsPathTmp,
|
||||||
fsPathPlugins: config.fsPathPlugins !== defaultConfig.fsPathPlugins,
|
fsPathPlugins: config.fsPathPlugins !== defaultConfig.fsPathPlugins,
|
||||||
|
fsPathTemplates: config.fsPathTemplates !== defaultConfig.fsPathTemplates,
|
||||||
sentryDsn: config.sentryDsn !== defaultConfig.sentryDsn,
|
sentryDsn: config.sentryDsn !== defaultConfig.sentryDsn,
|
||||||
systemPrompt: (config.systemPrompt || defaultSystemPrompt) !== (defaultConfig.systemPrompt || defaultSystemPrompt),
|
systemPrompt: (config.systemPrompt || defaultSystemPrompt) !== (defaultConfig.systemPrompt || defaultSystemPrompt),
|
||||||
}), [config, defaultConfig]);
|
}), [config, defaultConfig]);
|
||||||
|
|
||||||
// Restore functions
|
// Restore functions - clear the value from config to use the default
|
||||||
const restoreProjectTemplate = () => {
|
const restoreProjectTemplate = () => {
|
||||||
const defaultValue = defaultConfig.projectTemplate;
|
const defaultValue = defaultConfig.projectTemplate;
|
||||||
setProjectTemplateInput(defaultValue);
|
setProjectTemplateInput(defaultValue);
|
||||||
updateConfig((current) => ({ ...current, projectTemplate: defaultValue }));
|
updateConfig((current) => {
|
||||||
|
const { projectTemplate, ...rest } = current;
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const restoreEsmUrl = () => {
|
const restoreEsmUrl = () => {
|
||||||
const defaultValue = defaultConfig.esmUrl;
|
const defaultValue = defaultConfig.esmUrl;
|
||||||
setEsmUrlInput(defaultValue);
|
setEsmUrlInput(defaultValue);
|
||||||
updateConfig((current) => ({ ...current, esmUrl: defaultValue }));
|
updateConfig((current) => {
|
||||||
|
const { esmUrl, ...rest } = current;
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const restoreCorsProxy = () => {
|
const restoreCorsProxy = () => {
|
||||||
const defaultValue = defaultConfig.corsProxy;
|
const defaultValue = defaultConfig.corsProxy;
|
||||||
setCorsProxyInput(defaultValue);
|
setCorsProxyInput(defaultValue);
|
||||||
updateConfig((current) => ({ ...current, corsProxy: defaultValue }));
|
updateConfig((current) => {
|
||||||
|
const { corsProxy, ...rest } = current;
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const restoreFaviconUrl = () => {
|
const restoreFaviconUrl = () => {
|
||||||
const defaultValue = defaultConfig.faviconUrl;
|
const defaultValue = defaultConfig.faviconUrl;
|
||||||
setFaviconUrlInput(defaultValue);
|
setFaviconUrlInput(defaultValue);
|
||||||
updateConfig((current) => ({ ...current, faviconUrl: defaultValue }));
|
updateConfig((current) => {
|
||||||
|
const { faviconUrl, ...rest } = current;
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const restorePreviewDomain = () => {
|
const restorePreviewDomain = () => {
|
||||||
const defaultValue = defaultConfig.previewDomain;
|
const defaultValue = defaultConfig.previewDomain;
|
||||||
setPreviewDomainInput(defaultValue);
|
setPreviewDomainInput(defaultValue);
|
||||||
updateConfig((current) => ({ ...current, previewDomain: defaultValue }));
|
updateConfig((current) => {
|
||||||
|
const { previewDomain, ...rest } = current;
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const restoreShowcaseEnabled = () => {
|
const restoreShowcaseEnabled = () => {
|
||||||
const defaultValue = defaultConfig.showcaseEnabled;
|
updateConfig((current) => {
|
||||||
updateConfig((current) => ({ ...current, showcaseEnabled: defaultValue }));
|
const { showcaseEnabled, ...rest } = current;
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const restoreShowcaseModerator = () => {
|
const restoreShowcaseModerator = () => {
|
||||||
const defaultValue = defaultConfig.showcaseModerator;
|
const defaultValue = defaultConfig.showcaseModerator;
|
||||||
setShowcaseModeratorInput(defaultValue);
|
setShowcaseModeratorInput(defaultValue);
|
||||||
updateConfig((current) => ({ ...current, showcaseModerator: defaultValue }));
|
updateConfig((current) => {
|
||||||
|
const { showcaseModerator, ...rest } = current;
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const restoreFsPathProjects = () => {
|
const restoreFsPathProjects = () => {
|
||||||
const defaultValue = defaultConfig.fsPathProjects;
|
const defaultValue = defaultConfig.fsPathProjects;
|
||||||
setFsPathProjectsInput(defaultValue);
|
setFsPathProjectsInput(defaultValue);
|
||||||
updateConfig((current) => ({ ...current, fsPathProjects: defaultValue }));
|
updateConfig((current) => {
|
||||||
|
const { fsPathProjects, ...rest } = current;
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const restoreFsPathConfig = () => {
|
const restoreFsPathConfig = () => {
|
||||||
const defaultValue = defaultConfig.fsPathConfig;
|
const defaultValue = defaultConfig.fsPathConfig;
|
||||||
setFsPathConfigInput(defaultValue);
|
setFsPathConfigInput(defaultValue);
|
||||||
updateConfig((current) => ({ ...current, fsPathConfig: defaultValue }));
|
updateConfig((current) => {
|
||||||
|
const { fsPathConfig, ...rest } = current;
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const restoreFsPathTmp = () => {
|
const restoreFsPathTmp = () => {
|
||||||
const defaultValue = defaultConfig.fsPathTmp;
|
const defaultValue = defaultConfig.fsPathTmp;
|
||||||
setFsPathTmpInput(defaultValue);
|
setFsPathTmpInput(defaultValue);
|
||||||
updateConfig((current) => ({ ...current, fsPathTmp: defaultValue }));
|
updateConfig((current) => {
|
||||||
|
const { fsPathTmp, ...rest } = current;
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const restoreFsPathPlugins = () => {
|
const restoreFsPathPlugins = () => {
|
||||||
const defaultValue = defaultConfig.fsPathPlugins;
|
const defaultValue = defaultConfig.fsPathPlugins;
|
||||||
setFsPathPluginsInput(defaultValue);
|
setFsPathPluginsInput(defaultValue);
|
||||||
updateConfig((current) => ({ ...current, fsPathPlugins: defaultValue }));
|
updateConfig((current) => {
|
||||||
|
const { fsPathPlugins, ...rest } = current;
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const restoreFsPathTemplates = () => {
|
||||||
|
const defaultValue = defaultConfig.fsPathTemplates;
|
||||||
|
setFsPathTemplatesInput(defaultValue);
|
||||||
|
updateConfig((current) => {
|
||||||
|
const { fsPathTemplates, ...rest } = current;
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const restoreSentryDsn = () => {
|
const restoreSentryDsn = () => {
|
||||||
const defaultValue = defaultConfig.sentryDsn;
|
const defaultValue = defaultConfig.sentryDsn;
|
||||||
setSentryDsnInput(defaultValue);
|
setSentryDsnInput(defaultValue);
|
||||||
updateConfig((current) => ({ ...current, sentryDsn: defaultValue }));
|
updateConfig((current) => {
|
||||||
|
const { sentryDsn, ...rest } = current;
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const restoreSystemPrompt = () => {
|
const restoreSystemPrompt = () => {
|
||||||
const defaultValue = defaultSystemPrompt;
|
const defaultValue = defaultSystemPrompt;
|
||||||
setSystemPromptInput(defaultValue);
|
setSystemPromptInput(defaultValue);
|
||||||
updateConfig((current) => ({ ...current, systemPrompt: defaultValue }));
|
updateConfig((current) => {
|
||||||
|
const { systemPrompt, ...rest } = current;
|
||||||
|
return rest;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Service Worker state
|
// Service Worker state
|
||||||
@@ -748,7 +798,7 @@ export function SystemSettings() {
|
|||||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<h4 className="text-sm font-medium">{t('filesystemPaths')}</h4>
|
<h4 className="text-sm font-medium">{t('filesystemPaths')}</h4>
|
||||||
{(isModified.fsPathProjects || isModified.fsPathConfig || isModified.fsPathTmp || isModified.fsPathPlugins) && (
|
{(isModified.fsPathProjects || isModified.fsPathConfig || isModified.fsPathTmp || isModified.fsPathPlugins || isModified.fsPathTemplates) && (
|
||||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -918,6 +968,47 @@ export function SystemSettings() {
|
|||||||
{t('pluginsDirectoryDescription')}
|
{t('pluginsDirectoryDescription')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Label htmlFor="fs-path-templates" className="text-sm font-medium">
|
||||||
|
{t('templatesDirectory')}
|
||||||
|
</Label>
|
||||||
|
{isModified.fsPathTemplates && (
|
||||||
|
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Input
|
||||||
|
id="fs-path-templates"
|
||||||
|
type="text"
|
||||||
|
placeholder="/templates"
|
||||||
|
value={fsPathTemplatesInput}
|
||||||
|
onChange={(e) => {
|
||||||
|
const value = e.target.value;
|
||||||
|
setFsPathTemplatesInput(value);
|
||||||
|
updateConfig((current) => ({
|
||||||
|
...current,
|
||||||
|
fsPathTemplates: value,
|
||||||
|
}));
|
||||||
|
}}
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
{isModified.fsPathTemplates && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
onClick={restoreFsPathTemplates}
|
||||||
|
title={t('restoreToDefault')}
|
||||||
|
>
|
||||||
|
<RotateCcw className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{t('templatesDirectoryDescription')}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</AccordionContent>
|
</AccordionContent>
|
||||||
</AccordionItem>
|
</AccordionItem>
|
||||||
@@ -969,6 +1060,22 @@ export function SystemSettings() {
|
|||||||
</AccordionContent>
|
</AccordionContent>
|
||||||
</AccordionItem>
|
</AccordionItem>
|
||||||
</Accordion>
|
</Accordion>
|
||||||
|
|
||||||
|
{/* Terminal */}
|
||||||
|
<Accordion type="single" collapsible className="w-full">
|
||||||
|
<AccordionItem value="terminal" className="border rounded-lg">
|
||||||
|
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<h4 className="text-sm font-medium">{t('terminal')}</h4>
|
||||||
|
</div>
|
||||||
|
</AccordionTrigger>
|
||||||
|
<AccordionContent className="px-0 pb-0">
|
||||||
|
<div className="h-[500px]">
|
||||||
|
<Terminal cwd="/" />
|
||||||
|
</div>
|
||||||
|
</AccordionContent>
|
||||||
|
</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ export function TestApp({ children }: TestAppProps) {
|
|||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
fsPathTmp: '/tmp',
|
fsPathTmp: '/tmp',
|
||||||
fsPathPlugins: '/plugins',
|
fsPathPlugins: '/plugins',
|
||||||
|
fsPathTemplates: '/templates',
|
||||||
sentryDsn: '',
|
sentryDsn: '',
|
||||||
sentryEnabled: false,
|
sentryEnabled: false,
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in new issue
Block a user