mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Merge branch 'electron' into 'main'
Electron See merge request soapbox-pub/shakespeare!68
This commit is contained in:
commit
695b56c3cb
27 files changed
+5954
-47
No files matched your search
+51
-6
@@ -20,6 +20,7 @@ import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { ElectronFSAdapter } from '@/lib/ElectronFSAdapter';
|
||||
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
||||
import { DynamicFavicon } from '@/components/DynamicFavicon';
|
||||
import { OfflineIndicator } from '@/components/OfflineIndicator';
|
||||
@@ -43,6 +44,47 @@ const queryClient = new QueryClient({
|
||||
},
|
||||
});
|
||||
|
||||
// Get OS-specific default paths for Electron
|
||||
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string } {
|
||||
if (!globalThis.electron) {
|
||||
// Browser defaults - use virtual filesystem paths
|
||||
return {
|
||||
fsPathProjects: "/projects",
|
||||
fsPathConfig: "/config",
|
||||
fsPathTmp: "/tmp",
|
||||
};
|
||||
}
|
||||
|
||||
// Electron defaults - use OS-specific paths
|
||||
// Note: The ~ will be expanded by the Electron main process
|
||||
const platform = navigator.platform.toLowerCase();
|
||||
|
||||
if (platform.includes('win')) {
|
||||
// Windows
|
||||
return {
|
||||
fsPathProjects: "~/Documents/Projects",
|
||||
fsPathConfig: "~/AppData/Local/shakespeare",
|
||||
fsPathTmp: "~/AppData/Local/Temp/shakespeare",
|
||||
};
|
||||
} else if (platform.includes('mac')) {
|
||||
// macOS
|
||||
return {
|
||||
fsPathProjects: "~/Projects",
|
||||
fsPathConfig: "~/Library/Application Support/shakespeare",
|
||||
fsPathTmp: "/tmp/shakespeare",
|
||||
};
|
||||
} else {
|
||||
// Linux and other Unix-like systems
|
||||
return {
|
||||
fsPathProjects: "~/Projects",
|
||||
fsPathConfig: "~/.config/shakespeare",
|
||||
fsPathTmp: "/tmp/shakespeare",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const electronPaths = getElectronDefaultPaths();
|
||||
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "system",
|
||||
relayUrl: "wss://relay.ditto.pub",
|
||||
@@ -54,9 +96,9 @@ const defaultConfig: AppConfig = {
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
|
||||
ngitServers: ["git.shakespeare.diy", "relay.ngit.dev"],
|
||||
fsPathProjects: "/projects",
|
||||
fsPathConfig: "/config",
|
||||
fsPathTmp: "/tmp",
|
||||
fsPathProjects: electronPaths.fsPathProjects,
|
||||
fsPathConfig: electronPaths.fsPathConfig,
|
||||
fsPathTmp: electronPaths.fsPathTmp,
|
||||
};
|
||||
|
||||
const presetRelays = [
|
||||
@@ -66,9 +108,12 @@ const presetRelays = [
|
||||
{ url: 'wss://relay.primal.net', name: 'Primal' },
|
||||
];
|
||||
|
||||
// Initialize LightningFS
|
||||
const lightningFS = new LightningFS('shakespeare-fs');
|
||||
const fs = new LightningFSAdapter(lightningFS.promises);
|
||||
// Initialize filesystem adapter based on environment
|
||||
// In Electron, use Electron filesystem at ~/shakespeare
|
||||
// In browser, use LightningFS (IndexedDB-backed virtual filesystem)
|
||||
const fs = globalThis.electron
|
||||
? new ElectronFSAdapter()
|
||||
: new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
|
||||
|
||||
// Component to handle filesystem cleanup on startup
|
||||
// Automatically removes files older than 1 hour from tmp directory
|
||||
|
||||
+6
-3
@@ -1,4 +1,4 @@
|
||||
import { BrowserRouter, Route, Routes } from "react-router-dom";
|
||||
import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
|
||||
import { ScrollToTop } from "./components/ScrollToTop";
|
||||
import { SessionMonitor } from "./components/SessionMonitor";
|
||||
import { URLFragmentHandler } from "./components/URLFragmentHandler";
|
||||
@@ -24,8 +24,11 @@ import { ProjectView } from "./pages/ProjectView";
|
||||
import { SettingsLayout } from "./components/SettingsLayout";
|
||||
|
||||
export function AppRouter() {
|
||||
// Use HashRouter in Electron, BrowserRouter in web
|
||||
const Router = globalThis.electron ? HashRouter : BrowserRouter;
|
||||
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Router>
|
||||
<ScrollToTop />
|
||||
<SessionMonitor />
|
||||
<URLFragmentHandler />
|
||||
@@ -53,7 +56,7 @@ export function AppRouter() {
|
||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
export default AppRouter;
|
||||
@@ -154,7 +154,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
nostr_read_protocol: new NostrReadProtocolTool(),
|
||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||
shell: new ShellTool(fs, cwd, git),
|
||||
shell: new ShellTool(fs, cwd, git, projectsPath),
|
||||
read_console_messages: new ReadConsoleMessagesTool(),
|
||||
};
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@ export interface ShakespeareLogoProps {
|
||||
|
||||
export function ShakespeareLogo({ className }: ShakespeareLogoProps) {
|
||||
return (
|
||||
<img
|
||||
src="/shakespeare.svg"
|
||||
alt="Shakespeare"
|
||||
<img
|
||||
src="/shakespeare.svg"
|
||||
alt="Shakespeare"
|
||||
className={className}
|
||||
/>
|
||||
);
|
||||
|
||||
+62
-16
@@ -38,7 +38,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
|
||||
// Initialize ShellTool
|
||||
useEffect(() => {
|
||||
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git);
|
||||
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath);
|
||||
|
||||
// Add welcome message
|
||||
setLines([{
|
||||
@@ -81,7 +81,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
}, []);
|
||||
|
||||
const executeCommand = useCallback(async (command: string) => {
|
||||
if (!shellToolRef.current || !command.trim()) return;
|
||||
if (!command.trim()) return;
|
||||
|
||||
// Add command to history
|
||||
if (command.trim() && !commandHistory.includes(command.trim())) {
|
||||
@@ -95,21 +95,67 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
setIsExecuting(true);
|
||||
|
||||
try {
|
||||
// Handle special help command
|
||||
if (command.trim() === 'help') {
|
||||
const availableCommands = shellToolRef.current.getAvailableCommands();
|
||||
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
|
||||
`${cmd.name.padEnd(12)} - ${cmd.description}`
|
||||
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
|
||||
addLine('output', helpText);
|
||||
} else if (command.trim() === 'clear') {
|
||||
// Handle special clear command
|
||||
if (command.trim() === 'clear') {
|
||||
setLines([]);
|
||||
} else {
|
||||
const result = await shellToolRef.current.execute({ command });
|
||||
setIsExecuting(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Add output
|
||||
if (result && result.trim()) {
|
||||
addLine('output', result);
|
||||
// Check if running in Electron - use real shell
|
||||
if (window.electron?.shell) {
|
||||
// Get relative path from projects root
|
||||
// Remove the projectsPath prefix to get the relative path for the OS
|
||||
const projectsPrefix = projectsPath.endsWith('/')
|
||||
? projectsPath
|
||||
: projectsPath + '/';
|
||||
|
||||
const fullCwd = `${projectsPath}/${projectId}`;
|
||||
const relativeCwd = fullCwd.startsWith(projectsPrefix)
|
||||
? fullCwd.substring(projectsPrefix.length)
|
||||
: fullCwd;
|
||||
|
||||
const result = await window.electron.shell.exec(command, relativeCwd);
|
||||
|
||||
// Format output
|
||||
let output = '';
|
||||
|
||||
if (result.stdout) {
|
||||
output += result.stdout;
|
||||
}
|
||||
|
||||
if (result.stderr) {
|
||||
if (output) output += '\n';
|
||||
output += result.stderr;
|
||||
}
|
||||
|
||||
// Add exit code info for non-zero exits
|
||||
if (result.exitCode !== 0) {
|
||||
if (output) output += '\n';
|
||||
output += `Exit code: ${result.exitCode}`;
|
||||
}
|
||||
|
||||
if (output) {
|
||||
addLine('output', output);
|
||||
}
|
||||
} else {
|
||||
// Use virtual shell (browser mode)
|
||||
if (!shellToolRef.current) return;
|
||||
|
||||
// Handle special help command
|
||||
if (command.trim() === 'help') {
|
||||
const availableCommands = shellToolRef.current.getAvailableCommands();
|
||||
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
|
||||
`${cmd.name.padEnd(12)} - ${cmd.description}`
|
||||
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
|
||||
addLine('output', helpText);
|
||||
} else {
|
||||
const result = await shellToolRef.current.execute({ command });
|
||||
|
||||
// Add output
|
||||
if (result && result.trim()) {
|
||||
addLine('output', result);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -117,7 +163,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
} finally {
|
||||
setIsExecuting(false);
|
||||
}
|
||||
}, [addLine, commandHistory]);
|
||||
}, [addLine, commandHistory, projectId, projectsPath]);
|
||||
|
||||
const handleSubmit = useCallback((e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -42,7 +42,7 @@ export interface ProjectDeploySettings {
|
||||
* Hook to manage project-specific deployment settings
|
||||
* Stores settings in .git/shakespeare/deploy.json
|
||||
*/
|
||||
export function useProjectDeploySettings(projectId: string) {
|
||||
export function useProjectDeploySettings(projectId: string | null) {
|
||||
const fs = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const [settings, setSettings] = useState<ProjectDeploySettings>({ providers: {} });
|
||||
@@ -51,6 +51,13 @@ export function useProjectDeploySettings(projectId: string) {
|
||||
const settingsPath = `${projectsPath}/${projectId}/.git/shakespeare/deploy.json`;
|
||||
|
||||
const loadSettings = useCallback(async () => {
|
||||
// Don't try to load if projectId is falsy
|
||||
if (!projectId) {
|
||||
setSettings({ providers: {} });
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const content = await fs.fs.readFile(settingsPath, 'utf8');
|
||||
@@ -71,13 +78,17 @@ export function useProjectDeploySettings(projectId: string) {
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [fs.fs, settingsPath]);
|
||||
}, [fs.fs, settingsPath, projectId]);
|
||||
|
||||
useEffect(() => {
|
||||
loadSettings();
|
||||
}, [loadSettings]);
|
||||
|
||||
const saveSettings = async (newSettings: ProjectDeploySettings) => {
|
||||
if (!projectId) {
|
||||
throw new Error('Cannot save settings: no project selected');
|
||||
}
|
||||
|
||||
try {
|
||||
// Ensure .git/shakespeare directory exists
|
||||
const shakespeareDir = `${projectsPath}/${projectId}/.git/shakespeare`;
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
|
||||
|
||||
/**
|
||||
* Electron filesystem adapter that implements JSRuntimeFS interface
|
||||
* This adapter communicates with Electron's main process via IPC to perform
|
||||
* filesystem operations on the actual OS filesystem.
|
||||
*
|
||||
* Note: This adapter should only be instantiated when running in Electron.
|
||||
*/
|
||||
export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
private get electron() {
|
||||
if (!window.electron) {
|
||||
throw new Error('ElectronFSAdapter can only be used in Electron environment');
|
||||
}
|
||||
return window.electron;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unwrap Electron IPC errors to preserve error codes.
|
||||
* Electron wraps errors in "Error invoking remote method..." messages,
|
||||
* but we need to preserve the original error code for isomorphic-git.
|
||||
*/
|
||||
private unwrapElectronError(error: unknown): Error {
|
||||
if (!(error instanceof Error)) {
|
||||
return error as Error;
|
||||
}
|
||||
|
||||
// Extract error code from the error object if it exists
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
|
||||
// If there's already a code, preserve it
|
||||
if (code) {
|
||||
const err = new Error(error.message);
|
||||
(err as NodeJS.ErrnoException).code = code;
|
||||
return err;
|
||||
}
|
||||
|
||||
// If no code property, try to extract from the message
|
||||
// Messages look like: "Error invoking remote method 'fs:stat': Error: Failed to stat /path: ENOENT: no such file or directory"
|
||||
const match = error.message.match(/:\s*(E[A-Z]+):/);
|
||||
if (match) {
|
||||
const err = new Error(error.message);
|
||||
(err as NodeJS.ErrnoException).code = match[1];
|
||||
return err;
|
||||
}
|
||||
|
||||
return error;
|
||||
}
|
||||
|
||||
async readFile(path: string): Promise<Uint8Array<ArrayBuffer>>;
|
||||
async readFile(path: string, options: 'utf8'): Promise<string>;
|
||||
async readFile(path: string, options: string): Promise<string>;
|
||||
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
||||
async readFile(path: string, options: { encoding: string }): Promise<string>;
|
||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBuffer>>;
|
||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBuffer>> {
|
||||
try {
|
||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
||||
const result = await this.electron.fs.readFile(path, encoding);
|
||||
|
||||
// If no encoding, convert array to Uint8Array
|
||||
if (!encoding && Array.isArray(result)) {
|
||||
return new Uint8Array(result);
|
||||
}
|
||||
|
||||
return result as string;
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async writeFile(path: string, data: string | Uint8Array, options?: string | { encoding?: string }): Promise<void> {
|
||||
try {
|
||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
||||
// Convert Uint8Array to regular array for IPC serialization
|
||||
const dataToWrite = data instanceof Uint8Array ? Array.from(data) : data;
|
||||
return await this.electron.fs.writeFile(path, dataToWrite, encoding);
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async readdir(path: string): Promise<string[]>;
|
||||
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
|
||||
try {
|
||||
const result = await this.electron.fs.readdir(path, options?.withFileTypes);
|
||||
|
||||
if (options?.withFileTypes) {
|
||||
// Convert plain objects to DirectoryEntry format
|
||||
return (result as Array<{ name: string; isDirectory: boolean; isFile: boolean }>).map(entry => ({
|
||||
name: entry.name,
|
||||
isDirectory: () => entry.isDirectory,
|
||||
isFile: () => entry.isFile,
|
||||
}));
|
||||
}
|
||||
|
||||
return result as string[];
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
|
||||
try {
|
||||
// Default to recursive: true for isomorphic-git compatibility
|
||||
// isomorphic-git expects mkdir to behave like 'mkdir -p'
|
||||
const recursive = options?.recursive !== false;
|
||||
return await this.electron.fs.mkdir(path, recursive);
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async stat(path: string): Promise<{
|
||||
isDirectory(): boolean;
|
||||
isFile(): boolean;
|
||||
isBlockDevice(): boolean;
|
||||
isCharacterDevice(): boolean;
|
||||
isSymbolicLink(): boolean;
|
||||
isFIFO(): boolean;
|
||||
isSocket(): boolean;
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
ctimeMs: number;
|
||||
atimeMs: number;
|
||||
mtime: Date;
|
||||
ctime: Date;
|
||||
atime: Date;
|
||||
}> {
|
||||
try {
|
||||
const result = await this.electron.fs.stat(path);
|
||||
const now = Date.now();
|
||||
return {
|
||||
isDirectory: () => result.isDirectory,
|
||||
isFile: () => result.isFile,
|
||||
isBlockDevice: () => result.isBlockDevice,
|
||||
isCharacterDevice: () => result.isCharacterDevice,
|
||||
isSymbolicLink: () => result.isSymbolicLink,
|
||||
isFIFO: () => result.isFIFO,
|
||||
isSocket: () => result.isSocket,
|
||||
size: result.size ?? 0,
|
||||
mtimeMs: result.mtimeMs ?? now,
|
||||
ctimeMs: result.ctimeMs ?? now,
|
||||
atimeMs: result.atimeMs ?? now,
|
||||
// Convert timestamps back to Date objects
|
||||
mtime: new Date(result.mtime ?? now),
|
||||
ctime: new Date(result.ctime ?? now),
|
||||
atime: new Date(result.atime ?? now),
|
||||
};
|
||||
} catch (error) {
|
||||
// Electron IPC wraps errors, extract the original error code
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async lstat(path: string): Promise<{
|
||||
isDirectory(): boolean;
|
||||
isFile(): boolean;
|
||||
isBlockDevice(): boolean;
|
||||
isCharacterDevice(): boolean;
|
||||
isSymbolicLink(): boolean;
|
||||
isFIFO(): boolean;
|
||||
isSocket(): boolean;
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
ctimeMs: number;
|
||||
atimeMs: number;
|
||||
mtime: Date;
|
||||
ctime: Date;
|
||||
atime: Date;
|
||||
}> {
|
||||
try {
|
||||
const result = await this.electron.fs.lstat(path);
|
||||
const now = Date.now();
|
||||
return {
|
||||
isDirectory: () => result.isDirectory,
|
||||
isFile: () => result.isFile,
|
||||
isBlockDevice: () => result.isBlockDevice,
|
||||
isCharacterDevice: () => result.isCharacterDevice,
|
||||
isSymbolicLink: () => result.isSymbolicLink,
|
||||
isFIFO: () => result.isFIFO,
|
||||
isSocket: () => result.isSocket,
|
||||
size: result.size ?? 0,
|
||||
mtimeMs: result.mtimeMs ?? now,
|
||||
ctimeMs: result.ctimeMs ?? now,
|
||||
atimeMs: result.atimeMs ?? now,
|
||||
// Convert timestamps back to Date objects
|
||||
mtime: new Date(result.mtime ?? now),
|
||||
ctime: new Date(result.ctime ?? now),
|
||||
atime: new Date(result.atime ?? now),
|
||||
};
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async unlink(path: string): Promise<void> {
|
||||
try {
|
||||
return await this.electron.fs.unlink(path);
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async rmdir(path: string): Promise<void> {
|
||||
try {
|
||||
return await this.electron.fs.rmdir(path);
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async rename(oldPath: string, newPath: string): Promise<void> {
|
||||
try {
|
||||
return await this.electron.fs.rename(oldPath, newPath);
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async readlink(path: string): Promise<string> {
|
||||
try {
|
||||
return await this.electron.fs.readlink(path);
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async symlink(target: string, path: string): Promise<void> {
|
||||
try {
|
||||
return await this.electron.fs.symlink(target, path);
|
||||
} catch (error) {
|
||||
throw this.unwrapElectronError(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ansiToHtml, containsAnsiCodes, stripAnsiCodes } from './ansiToHtml';
|
||||
|
||||
describe('ansiToHtml', () => {
|
||||
it('should convert basic color codes to HTML', () => {
|
||||
const input = '\u001b[31mRed text\u001b[0m';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toContain('text-red-500');
|
||||
expect(output).toContain('Red text');
|
||||
});
|
||||
|
||||
it('should handle multiple color codes', () => {
|
||||
const input = '\u001b[31mRed\u001b[0m \u001b[32mGreen\u001b[0m';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toContain('text-red-500');
|
||||
expect(output).toContain('text-green-500');
|
||||
});
|
||||
|
||||
it('should return original text if no ANSI codes', () => {
|
||||
const input = 'Plain text';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toBe(input);
|
||||
});
|
||||
|
||||
it('should handle bold text', () => {
|
||||
const input = '\u001b[1mBold text\u001b[0m';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toContain('font-bold');
|
||||
});
|
||||
|
||||
it('should handle background colors', () => {
|
||||
const input = '\u001b[41mRed background\u001b[0m';
|
||||
const output = ansiToHtml(input);
|
||||
expect(output).toContain('bg-red-500');
|
||||
});
|
||||
});
|
||||
|
||||
describe('containsAnsiCodes', () => {
|
||||
it('should detect ANSI codes', () => {
|
||||
expect(containsAnsiCodes('\u001b[31mRed\u001b[0m')).toBe(true);
|
||||
expect(containsAnsiCodes('\u001b[1mBold\u001b[0m')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for plain text', () => {
|
||||
expect(containsAnsiCodes('Plain text')).toBe(false);
|
||||
expect(containsAnsiCodes('')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stripAnsiCodes', () => {
|
||||
it('should remove basic color codes', () => {
|
||||
const input = '\u001b[31mRed text\u001b[0m';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('Red text');
|
||||
});
|
||||
|
||||
it('should remove multiple ANSI codes', () => {
|
||||
const input = '\u001b[31mRed\u001b[0m \u001b[32mGreen\u001b[0m \u001b[1mBold\u001b[0m';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('Red Green Bold');
|
||||
});
|
||||
|
||||
it('should remove cursor movement codes', () => {
|
||||
const input = 'Text\u001b[2AMove up\u001b[1BMove down';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('TextMove upMove down');
|
||||
});
|
||||
|
||||
it('should remove clear screen codes', () => {
|
||||
const input = 'Before\u001b[2JAfter';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('BeforeAfter');
|
||||
});
|
||||
|
||||
it('should handle text without ANSI codes', () => {
|
||||
const input = 'Plain text';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe(input);
|
||||
});
|
||||
|
||||
it('should handle empty string', () => {
|
||||
const output = stripAnsiCodes('');
|
||||
expect(output).toBe('');
|
||||
});
|
||||
|
||||
it('should handle npm output with ANSI codes', () => {
|
||||
const input = '\u001b[1m\u001b[32madded 142 packages\u001b[39m\u001b[22m in 3s';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('added 142 packages in 3s');
|
||||
});
|
||||
|
||||
it('should handle git status output with ANSI codes', () => {
|
||||
const input = 'On branch \u001b[32mmain\u001b[m\nYour branch is up to date';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('On branch main\nYour branch is up to date');
|
||||
});
|
||||
|
||||
it('should preserve newlines and spaces', () => {
|
||||
const input = '\u001b[31mLine 1\u001b[0m\n\u001b[32mLine 2\u001b[0m\n Indented';
|
||||
const output = stripAnsiCodes(input);
|
||||
expect(output).toBe('Line 1\nLine 2\n Indented');
|
||||
});
|
||||
});
|
||||
+25
-11
@@ -49,15 +49,15 @@ const styleMap: Record<string, string> = {
|
||||
export function ansiToHtml(text: string): string {
|
||||
// Regular expression to match ANSI escape sequences
|
||||
const ansiRegex = /\u001b\[((?:\d+;)*\d+)m/g;
|
||||
|
||||
|
||||
// Initialize result and current style classes
|
||||
let result = '';
|
||||
let currentClasses: string[] = [];
|
||||
|
||||
|
||||
// Find all matches and their positions
|
||||
const matches: Array<{index: number, length: number, codes: string}> = [];
|
||||
let match;
|
||||
|
||||
|
||||
while ((match = ansiRegex.exec(text)) !== null) {
|
||||
matches.push({
|
||||
index: match.index,
|
||||
@@ -65,15 +65,15 @@ export function ansiToHtml(text: string): string {
|
||||
codes: match[1]
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// If no ANSI codes found, return the original text
|
||||
if (matches.length === 0) {
|
||||
return text;
|
||||
}
|
||||
|
||||
|
||||
// Process the text with ANSI codes
|
||||
let lastIndex = 0;
|
||||
|
||||
|
||||
for (const match of matches) {
|
||||
// Add text before this match with current styling
|
||||
if (match.index > lastIndex) {
|
||||
@@ -84,10 +84,10 @@ export function ansiToHtml(text: string): string {
|
||||
result += textSegment;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Update current classes based on ANSI codes
|
||||
const codes = match.codes.split(';');
|
||||
|
||||
|
||||
for (const code of codes) {
|
||||
if (code === '0') {
|
||||
// Reset all styles
|
||||
@@ -109,11 +109,11 @@ export function ansiToHtml(text: string): string {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Update lastIndex to after this match
|
||||
lastIndex = match.index + match.length;
|
||||
}
|
||||
|
||||
|
||||
// Add any remaining text
|
||||
if (lastIndex < text.length) {
|
||||
const textSegment = text.substring(lastIndex);
|
||||
@@ -123,7 +123,7 @@ export function ansiToHtml(text: string): string {
|
||||
result += textSegment;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -132,4 +132,18 @@ export function ansiToHtml(text: string): string {
|
||||
*/
|
||||
export function containsAnsiCodes(text: string): boolean {
|
||||
return /\u001b\[(?:\d+;)*\d+m/.test(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip all ANSI escape sequences from a string
|
||||
* This removes color codes, cursor movements, and other terminal control sequences
|
||||
*/
|
||||
export function stripAnsiCodes(text: string): string {
|
||||
// Remove all ANSI escape sequences
|
||||
// This regex matches:
|
||||
// - Color codes: \u001b[...m
|
||||
// - Cursor movement: \u001b[...H, \u001b[...A, etc.
|
||||
// - Clear screen: \u001b[...J, \u001b[...K
|
||||
// - Other escape sequences
|
||||
return text.replace(/\u001b\[[0-9;]*[a-zA-Z]/g, '');
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import type { Tool } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand } from "../commands/ShellCommand";
|
||||
import { Git } from "../git";
|
||||
import { stripAnsiCodes } from "../ansiToHtml";
|
||||
import {
|
||||
CatCommand,
|
||||
CdCommand,
|
||||
@@ -49,6 +50,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
private cwd: string;
|
||||
private git: Git;
|
||||
private commands: Map<string, ShellCommand>;
|
||||
private projectsPath: string;
|
||||
|
||||
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, sed, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators, and output redirection with > and >> operators";
|
||||
|
||||
@@ -58,10 +60,11 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
),
|
||||
});
|
||||
|
||||
constructor(fs: JSRuntimeFS, cwd: string, git: Git) {
|
||||
constructor(fs: JSRuntimeFS, cwd: string, git: Git, projectsPath: string = '/projects') {
|
||||
this.fs = fs;
|
||||
this.cwd = cwd;
|
||||
this.git = git;
|
||||
this.projectsPath = projectsPath;
|
||||
this.commands = new Map();
|
||||
|
||||
// Register available commands
|
||||
@@ -324,6 +327,11 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
return "Error: Empty command";
|
||||
}
|
||||
|
||||
// Check if running in Electron - if so, use real shell execution
|
||||
if (window.electron?.shell) {
|
||||
return this.executeRealShell(commandStr);
|
||||
}
|
||||
|
||||
// Parse compound commands
|
||||
const commands = this.parseCompoundCommand(commandStr);
|
||||
|
||||
@@ -340,6 +348,56 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
return this.executeCompoundCommands(commands);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute command using real shell in Electron
|
||||
*/
|
||||
private async executeRealShell(commandStr: string): Promise<string> {
|
||||
if (!window.electron?.shell) {
|
||||
throw new Error('Real shell execution is only available in Electron');
|
||||
}
|
||||
|
||||
try {
|
||||
// Get relative path from projects root
|
||||
// Remove the projectsPath prefix to get the relative path for the OS
|
||||
const projectsPrefix = this.projectsPath.endsWith('/')
|
||||
? this.projectsPath
|
||||
: this.projectsPath + '/';
|
||||
|
||||
const relativeCwd = this.cwd.startsWith(projectsPrefix)
|
||||
? this.cwd.substring(projectsPrefix.length)
|
||||
: this.cwd;
|
||||
|
||||
const result = await window.electron.shell.exec(commandStr, relativeCwd);
|
||||
|
||||
// Strip ANSI codes from output (color codes, cursor movements, etc.)
|
||||
// This is important for AI consumption and consistent output
|
||||
const cleanStdout = result.stdout ? stripAnsiCodes(result.stdout) : '';
|
||||
const cleanStderr = result.stderr ? stripAnsiCodes(result.stderr) : '';
|
||||
|
||||
// Format output
|
||||
let output = '';
|
||||
|
||||
if (cleanStdout) {
|
||||
output += cleanStdout;
|
||||
}
|
||||
|
||||
if (cleanStderr) {
|
||||
if (output) output += '\n';
|
||||
output += cleanStderr;
|
||||
}
|
||||
|
||||
// Add exit code info for non-zero exits
|
||||
if (result.exitCode !== 0) {
|
||||
if (output) output += '\n';
|
||||
output += `Exit code: ${result.exitCode}`;
|
||||
}
|
||||
|
||||
return output || '(no output)';
|
||||
} catch (error) {
|
||||
return `Error: ${error instanceof Error ? error.message : 'Unknown error'}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a simple command (no compound operators)
|
||||
*/
|
||||
|
||||
+1
-1
@@ -15,4 +15,4 @@ import '@fontsource-variable/inter';
|
||||
// Prism syntax highlighting
|
||||
import 'prismjs/themes/prism.css';
|
||||
|
||||
createRoot(document.getElementById("root")!).render(<App />);
|
||||
createRoot(document.getElementById("root")!).render(<App />);
|
||||
Reference in new issue
Block a user