Merge console messaging systems - resolve conflicts between parallel console log implementations

- Unified the global console message system with local state passing
- Maintained backward compatibility for external systems
- Added proper synchronization between global and local console states
- Resolved conflicts in PreviewPane.tsx and ProjectView.tsx
- Both console messaging systems now co-exist peacefully
This commit is contained in:
Chad Curtis committed 2025-09-24 16:30:50 +00:00
commit 662f95d35d
43 files changed
+2477 -307

No files matched your search

+122 -1
View File
@@ -59,7 +59,7 @@ class MockFS implements JSRuntimeFS {
error.code = 'ENOENT';
throw error;
}
const entries: string[] = [];
// Find subdirectories
@@ -125,6 +125,63 @@ class MockFS implements JSRuntimeFS {
async rmdir(path: string): Promise<void> {
this.dirs.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
// Handle both files and directories
if (this.files.has(oldPath)) {
const content = this.files.get(oldPath);
this.files.delete(oldPath);
this.files.set(newPath, content!);
}
if (this.dirs.has(oldPath)) {
this.dirs.delete(oldPath);
this.dirs.add(newPath);
// Also move all subdirectories and files
const itemsToMove: Array<{ oldPath: string; newPath: string; isDir: boolean }> = [];
// Collect directories to move
for (const dir of this.dirs) {
if (dir.startsWith(oldPath + '/')) {
const relativePath = dir.slice(oldPath.length);
itemsToMove.push({
oldPath: dir,
newPath: newPath + relativePath,
isDir: true
});
}
}
// Collect files to move
for (const file of this.files.keys()) {
if (file.startsWith(oldPath + '/')) {
const relativePath = file.slice(oldPath.length);
itemsToMove.push({
oldPath: file,
newPath: newPath + relativePath,
isDir: false
});
}
}
// Move all items
for (const item of itemsToMove) {
if (item.isDir) {
this.dirs.delete(item.oldPath);
this.dirs.add(item.newPath);
} else {
const content = this.files.get(item.oldPath);
this.files.delete(item.oldPath);
this.files.set(item.newPath, content!);
}
}
}
}
async lstat(path: string): Promise<{ isDirectory(): boolean; isFile(): boolean; mtimeMs?: number }> {
return this.stat(path);
}
}
describe('ProjectsManager', () => {
@@ -211,4 +268,68 @@ describe('ProjectsManager', () => {
expect(project).toBeNull();
});
});
describe('renameProject', () => {
it('should rename a project directory', async () => {
await projectsManager.init();
// Create a project
await fs.mkdir('/projects/old-name');
await fs.writeFile('/projects/old-name/package.json', '{}');
// Verify the project exists
const originalProject = await projectsManager.getProject('old-name');
expect(originalProject).not.toBeNull();
// Rename the project
const renamedProject = await projectsManager.renameProject('old-name', 'new-name');
// Verify the renamed project
expect(renamedProject.id).toBe('new-name');
expect(renamedProject.name).toBe('new-name');
expect(renamedProject.path).toBe('/projects/new-name');
// Verify old project no longer exists
const oldProject = await projectsManager.getProject('old-name');
expect(oldProject).toBeNull();
// Verify new project exists
const newProject = await projectsManager.getProject('new-name');
expect(newProject).not.toBeNull();
expect(newProject?.id).toBe('new-name');
});
it('should throw error when old project does not exist', async () => {
await projectsManager.init();
await expect(projectsManager.renameProject('non-existent', 'new-name'))
.rejects.toThrow('Project with ID "non-existent" does not exist');
});
it('should throw error when new project name already exists', async () => {
await projectsManager.init();
// Create two projects
await fs.mkdir('/projects/project-1');
await fs.mkdir('/projects/project-2');
await expect(projectsManager.renameProject('project-1', 'project-2'))
.rejects.toThrow('Project with ID "project-2" already exists');
});
it('should validate and normalize project names', async () => {
await projectsManager.init();
// Create a project
await fs.mkdir('/projects/old-name');
// Try to rename with invalid characters
await expect(projectsManager.renameProject('old-name', 'New Name With Spaces'))
.rejects.toThrow('Project name must contain only lowercase letters, numbers, and hyphens');
// Try to rename with empty name
await expect(projectsManager.renameProject('old-name', ''))
.rejects.toThrow('Project name cannot be empty');
});
});
});
+44
View File
@@ -264,6 +264,50 @@ export class ProjectsManager {
await this.deleteDirectory(projectPath);
}
async renameProject(oldId: string, newId: string): Promise<Project> {
// Validate that the old project exists
const oldProject = await this.getProject(oldId);
if (!oldProject) {
throw new Error(`Project with ID "${oldId}" does not exist`);
}
// Validate that the new ID doesn't already exist
if (await this.projectExists(newId)) {
throw new Error(`Project with ID "${newId}" already exists`);
}
// Validate the new ID format (same rules as generateUniqueProjectId)
const validatedNewId = newId
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
if (validatedNewId !== newId) {
throw new Error(`Project name must contain only lowercase letters, numbers, and hyphens`);
}
if (!validatedNewId) {
throw new Error(`Project name cannot be empty`);
}
const oldPath = `${this.dir}/${oldId}`;
const newPath = `${this.dir}/${newId}`;
// Rename the directory
await this.fs.rename(oldPath, newPath);
// Return the updated project object
const stats = await this.fs.stat(newPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
return {
id: newId,
name: this.formatProjectName(newId),
path: newPath,
lastModified: timestamp,
};
}
private async deleteDirectory(dirPath: string): Promise<void> {
const files = await this.fs.readdir(dirPath);
+47 -19
View File
@@ -6,6 +6,8 @@ import { createAIClient } from './ai-client';
import type { Tool } from './tools/Tool';
import type { NUser } from '@nostrify/react/login';
import type { AIProvider } from '@/contexts/AISettingsContext';
import { makeSystemPrompt } from './system';
import { NostrMetadata } from '@nostrify/nostrify';
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
role: 'assistant';
@@ -18,7 +20,6 @@ export interface SessionState {
projectId: string;
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
customTools: Record<string, Tool<unknown>>;
systemPrompt?: string;
maxSteps?: number;
messages: AIMessage[];
streamingMessage?: {
@@ -55,13 +56,13 @@ export class SessionManager {
private fs: JSRuntimeFS;
private aiSettings: { providers: AIProvider[] };
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
private getCurrentUser?: () => NUser | undefined;
private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata };
constructor(
fs: JSRuntimeFS,
aiSettings: { providers: AIProvider[] },
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
getCurrentUser?: () => NUser | undefined
getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata },
) {
this.fs = fs;
this.aiSettings = aiSettings;
@@ -76,7 +77,6 @@ export class SessionManager {
projectId: string,
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>,
customTools: Record<string, Tool<unknown>>,
systemPrompt?: string,
maxSteps?: number
): Promise<SessionState> {
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
@@ -98,7 +98,6 @@ export class SessionManager {
projectId,
tools,
customTools,
systemPrompt,
maxSteps,
isLoading: false,
lastActivity: new Date(),
@@ -114,7 +113,6 @@ export class SessionManager {
session.tools = tools;
session.customTools = customTools;
session.systemPrompt = systemPrompt;
session.maxSteps = maxSteps;
this.sessions.set(projectId, session);
@@ -203,12 +201,12 @@ export class SessionManager {
try {
// Parse provider and model
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
const connectionConfig = parsed.connection;
const modelName = parsed.model;
const provider = parsed.provider;
const model = parsed.model;
// Initialize OpenAI client
const currentUser = this.getCurrentUser?.();
const openai = createAIClient(connectionConfig, currentUser);
const { user, metadata } = this.getCurrentUser?.() ?? {};
const openai = createAIClient(provider, user);
let stepCount = 0;
const maxSteps = session.maxSteps || 50;
@@ -230,14 +228,25 @@ export class SessionManager {
tool_calls: undefined
};
const systemPrompt = await makeSystemPrompt({
cwd: `/projects/${projectId}`,
fs: this.fs,
mode: "agent",
name: "Shakespeare",
profession: "software extraordinaire",
tools: Object.values(session.tools),
user,
metadata,
});
// Prepare messages for AI
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = session.systemPrompt
? [{ role: 'system', content: session.systemPrompt }, ...session.messages]
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = systemPrompt
? [{ role: 'system', content: systemPrompt }, ...session.messages]
: session.messages;
// Prepare completion options
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
model: modelName,
model,
messages,
tools: session.tools && Object.keys(session.tools).length > 0 ? Object.values(session.tools) : undefined,
tool_choice: session.tools && Object.keys(session.tools).length > 0 ? 'auto' : undefined,
@@ -258,7 +267,7 @@ export class SessionManager {
let finishReason: string | null = null;
// Process the stream
let usage: { prompt_tokens: number; completion_tokens: number } | undefined;
let usage: { prompt_tokens: number; completion_tokens: number; cost?: number } | undefined;
for await (const chunk of stream) {
// Check if session was cancelled
if (!session.isLoading) break;
@@ -319,13 +328,25 @@ export class SessionManager {
// Capture usage data if available (some providers include it in the final chunk)
if (chunk.usage) {
const cost = 'cost' in chunk.usage && typeof chunk.usage.cost === 'number'
? chunk.usage.cost
: undefined;
usage = {
prompt_tokens: chunk.usage.prompt_tokens || 0,
completion_tokens: chunk.usage.completion_tokens || 0
completion_tokens: chunk.usage.completion_tokens || 0,
cost,
};
}
}
// Fix tool calls with empty arguments
for (const toolCall of accumulatedToolCalls) {
if (toolCall.type === 'function') {
toolCall.function.arguments = toolCall.function.arguments || '{}';
}
}
// Create final assistant message
const assistantMessage: AIMessage = {
role: 'assistant',
@@ -461,20 +482,28 @@ export class SessionManager {
/**
* Update session cost and context usage based on usage data
*/
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number }, providerModel: string): void {
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): void {
if (!this.getProviderModels) return;
const session = this.sessions.get(projectId);
if (!session) return;
// If provider gives direct cost, use it
if (typeof usage.cost === 'number') {
session.totalCost = (session.totalCost || 0) + usage.cost;
this.emit('costUpdated', projectId, session.totalCost);
return;
}
// Otherwise, get the cost from the models endpoint
try {
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
const modelName = parsed.model;
const providerName = parsed.provider;
const provider = parsed.provider;
// Find the model in provider models to get pricing and context length
const models = this.getProviderModels();
const model = models.find(m => m.id === modelName && m.provider === providerName);
const model = models.find(m => m.id === modelName && m.provider === provider.id);
// Update input tokens for context usage tracking
session.lastInputTokens = usage.prompt_tokens;
@@ -491,7 +520,6 @@ export class SessionManager {
// Update session total cost
session.totalCost = (session.totalCost || 0) + requestCost;
this.emit('costUpdated', projectId, session.totalCost);
} catch (error) {
console.warn('Failed to calculate session cost:', error);
+30 -11
View File
@@ -1,33 +1,52 @@
import OpenAI from 'openai';
import { NIP98Client } from '@nostrify/nostrify';
import type { NUser } from '@nostrify/react/login';
import type { AIProvider } from '@/contexts/AISettingsContext';
/**
* Create an OpenAI client instance with the appropriate configuration.
* If the connection requires Nostr authentication (NIP-98), it will use
* the NIP98Client for authenticated requests.
*/
export function createAIClient(connection: {
baseURL: string;
apiKey?: string;
nostr?: boolean;
}, user?: NUser): OpenAI {
export function createAIClient(provider: AIProvider, user?: NUser): OpenAI {
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
baseURL: connection.baseURL,
apiKey: connection.apiKey ?? '',
baseURL: provider.baseURL,
apiKey: provider.apiKey ?? '',
dangerouslyAllowBrowser: true,
defaultHeaders: {
// https://openrouter.ai/docs/app-attribution
'HTTP-Referer': 'https://shakespeare.diy',
'X-Title': 'Shakespeare',
},
};
let openai: OpenAI;
// If Nostr authentication is required and we have a user, use NIP-98
if (connection.nostr && user?.signer) {
if (provider.nostr && user?.signer) {
const nip98Client = new NIP98Client({ signer: user.signer });
return new OpenAI({
openai = new OpenAI({
...baseConfig,
fetch: (input, init) => nip98Client.fetch(input, init),
});
} else {
// Standard OpenAI client
openai = new OpenAI(baseConfig);
}
// Standard OpenAI client
return new OpenAI(baseConfig);
const createCompletion: typeof openai.chat.completions.create
= openai.chat.completions.create.bind(openai.chat.completions);
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
// OpenRouter usage accounting
// https://openrouter.ai/docs/use-cases/usage-accounting
if (provider.id === 'openrouter') {
(body as { usage?: { include?: boolean } }).usage = { include: true };
}
return createCompletion(body, options);
}) as typeof createCompletion;
return openai;
}
+229
View File
@@ -0,0 +1,229 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { HexdumpCommand } from './hexdump';
import type { JSRuntimeFS } from '../JSRuntime';
// Mock filesystem
const createMockFS = (): JSRuntimeFS => ({
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
mkdir: vi.fn(),
stat: vi.fn(),
lstat: vi.fn(),
unlink: vi.fn(),
rmdir: vi.fn(),
rename: vi.fn(),
readlink: vi.fn(),
symlink: vi.fn(),
});
describe('HexdumpCommand', () => {
let mockFS: JSRuntimeFS;
let command: HexdumpCommand;
const testCwd = '/test/dir';
beforeEach(() => {
mockFS = createMockFS();
command = new HexdumpCommand(mockFS);
});
it('should have correct name and description', () => {
expect(command.name).toBe('hexdump');
expect(command.description).toBe('Display file contents in hexadecimal format');
expect(command.usage).toBe('hexdump [-C] [-n length] [-s skip] [file...]');
});
it('should show error when no file is specified', async () => {
const result = await command.execute([], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('missing file operand');
});
it('should show error for non-existent file', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
const result = await command.execute(['nonexistent.txt'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('No such file or directory');
});
it('should show error for directory', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
const result = await command.execute(['testdir'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('Is a directory');
});
it('should display hexdump in default format', async () => {
const content = 'Hello, World!\n';
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
const result = await command.execute(['test.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('0000000');
expect(result.stdout).toContain('000000e'); // Final offset
});
it('should display hexdump in canonical format with -C', async () => {
const content = 'Hello, World!\n';
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
const result = await command.execute(['-C', 'test.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('00000000');
expect(result.stdout).toContain('|Hello, World!');
expect(result.stdout).toContain('|'); // Should have ASCII representation
});
it('should handle -n length option', async () => {
const content = 'Hello, World!\nThis is a longer line.';
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
const result = await command.execute(['-C', '-n', '5', 'test.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('|Hello|');
expect(result.stdout).not.toContain('World');
});
it('should handle -s skip option', async () => {
const content = 'Hello, World!\n';
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
const result = await command.execute(['-C', '-s', '7', 'test.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('00000007');
expect(result.stdout).toContain('|World!');
expect(result.stdout).not.toContain('Hello');
});
it('should handle -n and -s together', async () => {
const content = 'Hello, World!\n';
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
const result = await command.execute(['-C', '-s', '7', '-n', '5', 'test.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('00000007');
expect(result.stdout).toContain('|World|');
expect(result.stdout).not.toContain('Hello');
expect(result.stdout).not.toContain('!');
});
it('should show error for invalid -n value', async () => {
const result = await command.execute(['-n', 'invalid'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('invalid length');
});
it('should show error for invalid -s value', async () => {
const result = await command.execute(['-s', 'invalid'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('invalid skip offset');
});
it('should show error for missing -n argument', async () => {
const result = await command.execute(['-n'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('option requires an argument -- n');
});
it('should show error for missing -s argument', async () => {
const result = await command.execute(['-s'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('option requires an argument -- s');
});
it('should show error for invalid option', async () => {
const result = await command.execute(['-x'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('invalid option -- x');
});
it('should handle multiple files', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile)
.mockResolvedValueOnce(Buffer.from('ABC'))
.mockResolvedValueOnce(Buffer.from('XYZ'));
const result = await command.execute(['-C', 'file1.txt', 'file2.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('==> file1.txt <==');
expect(result.stdout).toContain('==> file2.txt <==');
expect(result.stdout).toContain('|ABC|');
expect(result.stdout).toContain('|XYZ|');
});
it('should handle piped input', async () => {
const input = 'Hello, World!';
const result = await command.execute(['-C'], testCwd, input);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('00000000');
expect(result.stdout).toContain('|Hello, World!|');
});
it('should handle binary data correctly', async () => {
// Create binary data with non-printable characters
const binaryData = Buffer.from([0x00, 0x01, 0x02, 0x7F, 0x80, 0xFF, 0x41, 0x42, 0x43]);
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(binaryData);
const result = await command.execute(['-C', 'binary.dat'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('00000000');
expect(result.stdout).toContain('00 01 02 7f 80 ff 41 42 43');
expect(result.stdout).toContain('|......ABC|'); // Non-printable chars shown as dots
});
it('should handle empty file', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(''));
const result = await command.execute(['-C', 'empty.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe(''); // No output for empty file
});
it('should handle skip beyond file length', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from('Hi'));
const result = await command.execute(['-C', '-s', '10', 'short.txt'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe(''); // No output since skip is beyond file
});
});
+272
View File
@@ -0,0 +1,272 @@
import { join } from "path-browserify";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'hexdump' command
* Display file contents in hexadecimal format
*/
export class HexdumpCommand implements ShellCommand {
name = 'hexdump';
description = 'Display file contents in hexadecimal format';
usage = 'hexdump [-C] [-n length] [-s skip] [file...]';
private fs: JSRuntimeFS;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
}
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
// Parse command line options
const options = this.parseOptions(args);
if (options.error) {
return createErrorResult(options.error);
}
// If input is provided (from pipe), process it
if (input !== undefined) {
const buffer = Buffer.from(input, 'utf8');
const output = this.formatHexdump(buffer, options);
return createSuccessResult(output);
}
// If no files specified, show usage
if (options.files.length === 0) {
return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`);
}
try {
const outputs: string[] = [];
for (const filePath of options.files) {
try {
// Handle both absolute and relative paths
let absolutePath: string;
if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) {
// It's an absolute path - use it directly
absolutePath = filePath;
} else {
// It's a relative path - resolve it relative to the current working directory
absolutePath = join(cwd, filePath);
}
// Check if path exists and is a file
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${filePath}: Is a directory`);
}
// Read file content as binary
const content = await this.fs.readFile(absolutePath);
const buffer = Buffer.from(content);
// Format the hexdump
const hexOutput = this.formatHexdump(buffer, options);
// Add filename header if multiple files
if (options.files.length > 1) {
outputs.push(`==> ${filePath} <==`);
outputs.push(hexOutput);
} else {
outputs.push(hexOutput);
}
} catch (error) {
// Handle file not found or permission errors
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${filePath}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${filePath}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${filePath}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${filePath}: Unknown error`);
}
}
}
const result = outputs.join('\n');
return createSuccessResult(result);
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Parse command line options
*/
private parseOptions(args: string[]): {
canonical: boolean;
length?: number;
skip: number;
files: string[];
error?: string;
} {
const options = {
canonical: false,
length: undefined as number | undefined,
skip: 0,
files: [] as string[],
};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '-C') {
options.canonical = true;
} else if (arg === '-n') {
// Next argument should be the length
if (i + 1 >= args.length) {
return { ...options, error: `${this.name}: option requires an argument -- n` };
}
const lengthStr = args[++i];
const length = parseInt(lengthStr, 10);
if (isNaN(length) || length < 0) {
return { ...options, error: `${this.name}: invalid length: ${lengthStr}` };
}
options.length = length;
} else if (arg === '-s') {
// Next argument should be the skip offset
if (i + 1 >= args.length) {
return { ...options, error: `${this.name}: option requires an argument -- s` };
}
const skipStr = args[++i];
const skip = parseInt(skipStr, 10);
if (isNaN(skip) || skip < 0) {
return { ...options, error: `${this.name}: invalid skip offset: ${skipStr}` };
}
options.skip = skip;
} else if (arg.startsWith('-')) {
return { ...options, error: `${this.name}: invalid option -- ${arg.slice(1)}` };
} else {
// It's a filename
options.files.push(arg);
}
}
return options;
}
/**
* Format buffer content as hexdump
*/
private formatHexdump(buffer: Buffer, options: {
canonical: boolean;
length?: number;
skip: number;
}): string {
const lines: string[] = [];
const bytesPerLine = 16;
// Apply skip offset
const startOffset = options.skip;
if (startOffset >= buffer.length) {
return ''; // Nothing to display
}
// Apply length limit
let endOffset = buffer.length;
if (options.length !== undefined) {
endOffset = Math.min(startOffset + options.length, buffer.length);
}
for (let offset = startOffset; offset < endOffset; offset += bytesPerLine) {
const lineEnd = Math.min(offset + bytesPerLine, endOffset);
const lineBytes = buffer.subarray(offset, lineEnd);
if (options.canonical) {
// Canonical format (-C): address, hex bytes, ASCII
lines.push(this.formatCanonicalLine(offset, lineBytes));
} else {
// Default format: address followed by 16-bit words in hex
lines.push(this.formatDefaultLine(offset, lineBytes));
}
}
// Add final offset line if we have data
if (endOffset > startOffset) {
const finalOffset = endOffset;
lines.push(this.formatOffsetLine(finalOffset));
}
return lines.join('\n');
}
/**
* Format a line in canonical format (-C option)
*/
private formatCanonicalLine(offset: number, bytes: Buffer): string {
const addressStr = offset.toString(16).padStart(8, '0');
// Format hex bytes (2 groups of 8 bytes each)
const group1: string[] = [];
const group2: string[] = [];
for (let i = 0; i < 16; i++) {
const hexByte = i < bytes.length
? bytes[i].toString(16).padStart(2, '0')
: ' ';
if (i < 8) {
group1.push(hexByte);
} else {
group2.push(hexByte);
}
}
const hexStr = group1.join(' ') + ' ' + group2.join(' ');
// Format ASCII representation
let asciiStr = '';
for (let i = 0; i < bytes.length; i++) {
const byte = bytes[i];
if (byte >= 32 && byte <= 126) {
// Printable ASCII character
asciiStr += String.fromCharCode(byte);
} else {
// Non-printable character
asciiStr += '.';
}
}
return `${addressStr} ${hexStr} |${asciiStr}|`;
}
/**
* Format a line in default format
*/
private formatDefaultLine(offset: number, bytes: Buffer): string {
const addressStr = offset.toString(16).padStart(7, '0');
// Group bytes into 16-bit words (little-endian)
const words: string[] = [];
for (let i = 0; i < bytes.length; i += 2) {
if (i + 1 < bytes.length) {
// Full 16-bit word (little-endian)
const word = (bytes[i + 1] << 8) | bytes[i];
words.push(word.toString(16).padStart(4, '0'));
} else {
// Partial word (only one byte)
const word = bytes[i];
words.push(word.toString(16).padStart(2, '0') + ' ');
}
}
return `${addressStr} ${words.join(' ')}`;
}
/**
* Format the final offset line
*/
private formatOffsetLine(offset: number): string {
return offset.toString(16).padStart(7, '0');
}
}
+3 -1
View File
@@ -13,6 +13,7 @@ export { FindCommand } from './find';
export { GitCommand } from './git';
export { GrepCommand } from './grep';
export { HeadCommand } from './head';
export { HexdumpCommand } from './hexdump';
export { LsCommand } from './ls';
export { MkdirCommand } from './mkdir';
export { MvCommand } from './mv';
@@ -25,4 +26,5 @@ export { TrCommand } from './tr';
export { UniqCommand } from './uniq';
export { WcCommand } from './wc';
export { WhoamiCommand } from './whoami';
export { WhichCommand } from './which';
export { WhichCommand } from './which';
export { UnzipCommand } from './unzip';
+303
View File
@@ -0,0 +1,303 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import JSZip from 'jszip';
import { UnzipCommand } from './unzip';
import type { JSRuntimeFS } from '../JSRuntime';
// Mock filesystem
const createMockFS = (): JSRuntimeFS => ({
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
mkdir: vi.fn(),
stat: vi.fn(),
lstat: vi.fn(),
unlink: vi.fn(),
rmdir: vi.fn(),
rename: vi.fn(),
readlink: vi.fn(),
symlink: vi.fn(),
});
describe('UnzipCommand', () => {
let mockFS: JSRuntimeFS;
let command: UnzipCommand;
beforeEach(() => {
mockFS = createMockFS();
command = new UnzipCommand(mockFS);
});
const createTestZip = async (files: Record<string, string | Uint8Array>): Promise<Uint8Array> => {
const zip = new JSZip();
for (const [path, content] of Object.entries(files)) {
if (path.endsWith('/')) {
zip.folder(path.slice(0, -1));
} else {
zip.file(path, content);
}
}
return zip.generateAsync({ type: 'uint8array' });
};
it('should show usage when no arguments provided', async () => {
const result = await command.execute([], '/home');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('missing archive operand');
expect(result.stderr).toContain('Usage:');
});
it('should show error for invalid options', async () => {
const result = await command.execute(['-x', 'test.zip'], '/home');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("invalid option '-x'");
});
it('should show error for non-existent archive', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
const result = await command.execute(['nonexistent.zip'], '/home');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('No such file or directory');
});
it('should show error when trying to unzip a directory', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
const result = await command.execute(['testdir'], '/home');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('Is a directory');
});
it('should list archive contents with -l option', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World',
'dir1/': '',
'dir1/file2.txt': 'Test content'
});
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
const result = await command.execute(['-l', 'test.zip'], '/home');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Archive: test.zip');
expect(result.stdout).toContain('file1.txt');
expect(result.stdout).toContain('dir1/');
expect(result.stdout).toContain('dir1/file2.txt');
});
it('should extract files to current directory', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World'
});
// Mock file operations - keep it simple
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
const result = await command.execute(['test.zip'], '/home');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Archive: test.zip');
expect(result.stdout).toContain('inflating: file1.txt');
// Verify writeFile was called for extracted files
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/file1.txt', expect.any(Uint8Array));
});
it('should handle command line options correctly', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World'
});
// Test -d option
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
const result = await command.execute(['-d', 'extract', 'test.zip'], '/home');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('inflating: file1.txt');
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/extract/file1.txt', expect.any(Uint8Array));
});
it('should handle overwrite option', async () => {
const zipData = await createTestZip({
'file1.txt': 'New content'
});
// Mock file exists scenario
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }); // file exists
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
// Without -o option, should fail
const resultWithoutOverwrite = await command.execute(['test.zip'], '/home');
expect(resultWithoutOverwrite.exitCode).toBe(1);
expect(resultWithoutOverwrite.stderr).toContain('File exists (use -o to overwrite)');
// Reset mocks
vi.clearAllMocks();
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }); // file exists
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
// With -o option, should succeed
const resultWithOverwrite = await command.execute(['-o', 'test.zip'], '/home');
expect(resultWithOverwrite.exitCode).toBe(0);
expect(resultWithOverwrite.stdout).toContain('inflating: file1.txt');
});
it('should prevent extraction outside allowed directories', async () => {
// Since JSZip normalizes paths during creation, we'll test the security logic
// by mocking the internal zip.files object to simulate a malicious ZIP
const zipData = await createTestZip({
'normal.txt': 'safe content'
});
// Mock the zip loading to return a ZIP with malicious paths
const originalLoadAsync = JSZip.loadAsync;
vi.spyOn(JSZip, 'loadAsync').mockImplementation(async () => {
const zip = new JSZip();
// Simulate malicious ZIP file entries that would escape the directory
(zip as unknown as { files: Record<string, { name: string; dir: boolean; async: () => Promise<Uint8Array> }> }).files = {
'../../../etc/passwd': {
name: '../../../etc/passwd',
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3])),
},
'../../outside.txt': {
name: '../../outside.txt',
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6])),
},
'normal.txt': {
name: 'normal.txt',
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9])),
}
};
return zip;
});
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
const result = await command.execute(['test.zip'], '/home/user');
// Should return error because some files were skipped
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('Path is outside allowed directories');
expect(result.stderr).toContain('../../../etc/passwd');
expect(result.stderr).toContain('../../outside.txt');
// Should only extract the safe file
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/user/normal.txt', expect.any(Uint8Array));
expect(mockFS.writeFile).toHaveBeenCalledTimes(1);
// Restore the original method
JSZip.loadAsync = originalLoadAsync;
});
it('should allow extraction to /tmp directory', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World'
});
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockRejectedValueOnce(new Error('ENOENT')) // extraction dir doesn't exist
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
const result = await command.execute(['-d', '/tmp', 'test.zip'], '/home/user');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('inflating: file1.txt');
expect(mockFS.writeFile).toHaveBeenCalledWith('/tmp/file1.txt', expect.any(Uint8Array));
});
it('should reject extraction directory outside allowed paths', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World'
});
// Mock that the archive exists and provide zip data
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => false,
isFile: () => true,
});
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
const result = await command.execute(['-d', '/etc', 'test.zip'], '/home/user');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("extraction directory '/etc' is outside allowed paths");
});
it('should support quiet mode with -q flag', async () => {
const zipData = await createTestZip({
'file1.txt': 'Hello World',
'dir1/': '',
'dir1/file2.txt': 'Test content'
});
vi.mocked(mockFS.stat)
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
const result = await command.execute(['-q', 'test.zip'], '/home');
expect(result.exitCode).toBe(0);
// In quiet mode, should not show archive header or extraction messages
expect(result.stdout).toBe('');
// But files should still be extracted
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/file1.txt', expect.any(Uint8Array));
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/dir1/file2.txt', expect.any(Uint8Array));
});
});
+220
View File
@@ -0,0 +1,220 @@
import { join, dirname, normalize } from "path-browserify";
import JSZip from "jszip";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
/**
* Implementation of the 'unzip' command
* Extract files from ZIP archives
*/
export class UnzipCommand implements ShellCommand {
name = 'unzip';
description = 'Extract files from ZIP archives';
usage = 'unzip [-d directory] [-o] [-l] [-q] archive.zip';
private fs: JSRuntimeFS;
constructor(fs: JSRuntimeFS) {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
if (args.length === 0) {
return createErrorResult(`${this.name}: missing archive operand\nUsage: ${this.usage}`);
}
let archivePath = '';
let extractDir = cwd;
let overwrite = false;
let listOnly = false;
let quiet = false;
// Parse command line options
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '-d' && i + 1 < args.length) {
// Extract to specific directory
extractDir = args[i + 1];
i++; // Skip next argument
} else if (arg === '-o') {
// Overwrite existing files
overwrite = true;
} else if (arg === '-l') {
// List archive contents only
listOnly = true;
} else if (arg === '-q') {
// Quiet mode - suppress output
quiet = true;
} else if (arg.startsWith('-')) {
return createErrorResult(`${this.name}: invalid option '${arg}'\nUsage: ${this.usage}`);
} else {
// This should be the archive path
archivePath = arg;
}
}
if (!archivePath) {
return createErrorResult(`${this.name}: no archive specified\nUsage: ${this.usage}`);
}
try {
// Resolve archive path
let absoluteArchivePath: string;
if (archivePath.startsWith('/') || archivePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(archivePath)) {
absoluteArchivePath = archivePath;
} else {
absoluteArchivePath = join(cwd, archivePath);
}
// Check if archive exists
try {
const stats = await this.fs.stat(absoluteArchivePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${archivePath}: Is a directory`);
}
} catch {
return createErrorResult(`${this.name}: ${archivePath}: No such file or directory`);
}
// Read the ZIP file
const zipData = await this.fs.readFile(absoluteArchivePath);
const zip = await JSZip.loadAsync(zipData);
// Resolve extraction directory
let absoluteExtractDir: string;
if (extractDir.startsWith('/') || extractDir.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(extractDir)) {
absoluteExtractDir = extractDir;
} else {
absoluteExtractDir = join(cwd, extractDir);
}
// Security check: ensure extraction directory is within allowed paths
if (!this.isPathAllowed(absoluteExtractDir, cwd)) {
return createErrorResult(`${this.name}: extraction directory '${extractDir}' is outside allowed paths (cwd or /tmp)`);
}
if (listOnly) {
// List contents only
const entries: string[] = [];
zip.forEach((relativePath, file) => {
const date = file.date || new Date();
const type = file.dir ? 'd' : '-';
const sizeStr = file.dir ? '0' : '?';
entries.push(`${type}rw-r--r-- 1 user user ${sizeStr.padStart(8)} ${date.toISOString().slice(0, 19).replace('T', ' ')} ${relativePath}`);
});
return createSuccessResult(`Archive: ${archivePath}\n${entries.join('\n')}`);
}
// Create extraction directory if it doesn't exist
try {
await this.fs.stat(absoluteExtractDir);
} catch {
await this.fs.mkdir(absoluteExtractDir, { recursive: true });
}
const extractedFiles: string[] = [];
const errors: string[] = [];
// Extract all files
for (const [relativePath, file] of Object.entries(zip.files)) {
const extractPath = join(absoluteExtractDir, relativePath);
// Security check: ensure each file path is within allowed directories
if (!this.isPathAllowed(extractPath, cwd)) {
errors.push(`${this.name}: ${relativePath}: Path is outside allowed directories (skipped for security)`);
continue;
}
try {
if (file.dir) {
// Create directory
await this.fs.mkdir(extractPath, { recursive: true });
if (!quiet) {
extractedFiles.push(` creating: ${relativePath}`);
}
} else {
// Check if file exists and handle overwrite
if (!overwrite) {
try {
await this.fs.stat(extractPath);
errors.push(`${this.name}: ${relativePath}: File exists (use -o to overwrite)`);
continue;
} catch {
// File doesn't exist, proceed with extraction
}
}
// Create parent directories if needed
const parentDir = dirname(extractPath);
try {
await this.fs.stat(parentDir);
} catch {
await this.fs.mkdir(parentDir, { recursive: true });
}
// Extract file content
const content = await file.async('uint8array');
await this.fs.writeFile(extractPath, content);
if (!quiet) {
extractedFiles.push(` inflating: ${relativePath}`);
}
}
} catch (error) {
errors.push(`${this.name}: ${relativePath}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
let output = '';
if (!quiet) {
output = `Archive: ${archivePath}\n`;
if (extractedFiles.length > 0) {
output += extractedFiles.join('\n');
}
}
if (errors.length > 0) {
if (!quiet && extractedFiles.length > 0) {
output += '\n';
}
return createErrorResult(output + '\n' + errors.join('\n'));
}
return createSuccessResult(output);
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('corrupted') || error.message.includes('invalid')) {
return createErrorResult(`${this.name}: ${archivePath}: Archive is corrupted or invalid`);
} else {
return createErrorResult(`${this.name}: ${archivePath}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${archivePath}: Unknown error`);
}
}
}
/**
* Check if a path is within allowed extraction directories (cwd or /tmp and their subdirectories)
*/
private isPathAllowed(extractPath: string, cwd: string): boolean {
// Normalize the paths without using resolve() since we're in browser environment
const normalizedPath = normalize(extractPath);
const normalizedCwd = normalize(cwd);
const tmpPath = '/tmp';
// Ensure paths are absolute for comparison
const absolutePath = normalizedPath.startsWith('/') ? normalizedPath : normalize(join(normalizedCwd, normalizedPath));
const absoluteCwd = normalizedCwd.startsWith('/') ? normalizedCwd : '/' + normalizedCwd;
// Check if path is within cwd or /tmp
return absolutePath.startsWith(absoluteCwd + '/') ||
absolutePath === absoluteCwd ||
absolutePath.startsWith(tmpPath + '/') ||
absolutePath === tmpPath;
}
}
+20 -12
View File
@@ -98,8 +98,6 @@ const resources = {
getHelp: '🔧 Get help with debugging and optimization',
buildDeploy: '🚀 Build and deploy your project',
aiNotConfigured: 'AI Assistant Not Configured',
configureAI: 'Please configure your AI settings to start building with AI assistance.',
useMenuForAI: 'Use the menu in the top bar to access AI Settings.',
askToAddFeatures: 'Ask me to add features, edit files, or build your project...',
selectModelFirst: 'Please select a model to start chatting...',
sendMessage: 'Send message',
@@ -256,6 +254,11 @@ const resources = {
recentlyUsed: 'Recently Used',
errorLoadingModels: 'Error Loading Models',
// API Authentication Errors
apiAuthenticationFailed: 'API Authentication Failed',
invalidApiKey: 'Invalid API key for {{provider}}. Please check your API key in Settings.',
checkApiKeySettings: 'Check API Key Settings',
// Context and Cost
contextUsage: 'Context usage: {{tokens}} / {{total}} tokens ({{percentage}}%)',
totalCostSession: 'Total cost for this chat session',
@@ -394,8 +397,6 @@ const resources = {
getHelp: '🔧 Obtenha ajuda com depuração e otimização',
buildDeploy: '🚀 Construa e implante seu projeto',
aiNotConfigured: 'Assistente de IA Não Configurado',
configureAI: 'Configure suas configurações de IA para começar a construir com assistência de IA.',
useMenuForAI: 'Use o menu na barra superior para acessar as Configurações de IA.',
askToAddFeatures: 'Peça para adicionar recursos, editar arquivos ou construir seu projeto...',
selectModelFirst: 'Selecione um modelo para começar a conversar...',
sendMessage: 'Enviar mensagem',
@@ -552,6 +553,11 @@ const resources = {
recentlyUsed: 'Usados Recentemente',
errorLoadingModels: 'Erro ao Carregar Modelos',
// API Authentication Errors
apiAuthenticationFailed: 'Falha na Autenticação da API',
invalidApiKey: 'Chave de API inválida para {{provider}}. Verifique sua chave de API nas Configurações.',
checkApiKeySettings: 'Verificar Configurações da Chave de API',
// Context and Cost
contextUsage: 'Uso de contexto: {{tokens}} / {{total}} tokens ({{percentage}}%)',
totalCostSession: 'Custo total para esta sessão de chat',
@@ -690,8 +696,6 @@ const resources = {
getHelp: '🔧 获得调试和优化帮助',
buildDeploy: '🚀 构建和部署您的项目',
aiNotConfigured: 'AI助手未配置',
configureAI: '请配置您的AI设置以开始使用AI助手构建。',
useMenuForAI: '使用顶部栏中的菜单访问AI设置。',
askToAddFeatures: '请我添加功能、编辑文件或构建您的项目...',
selectModelFirst: '请先选择一个模型开始聊天...',
sendMessage: '发送消息',
@@ -848,6 +852,11 @@ const resources = {
recentlyUsed: '最近使用',
errorLoadingModels: '加载模型时出错',
// API Authentication Errors
apiAuthenticationFailed: 'API身份验证失败',
invalidApiKey: '{{provider}}的API密钥无效。请在设置中检查您的API密钥。',
checkApiKeySettings: '检查API密钥设置',
// Context and Cost
contextUsage: '上下文使用:{{tokens}} / {{total}} 令牌 ({{percentage}}%)',
totalCostSession: '此聊天会话的总费用',
@@ -986,8 +995,6 @@ const resources = {
getHelp: '🔧 Sami taimako da gyara kuskure da haɓakawa',
buildDeploy: '🚀 Gina da tura aikinku',
aiNotConfigured: 'Mataimakin AI Ba a Saita ba',
configureAI: 'Da fatan za a saita saitunan AI don farawa ginawa da taimakon AI.',
useMenuForAI: 'Yi amfani da menu a saman mashigi don shiga Saitunan AI.',
askToAddFeatures: 'Roƙe ni in ƙara fasaloli, gyara fayiloli, ko gina aikinku...',
selectModelFirst: 'Da fatan za a zaɓi samfuri don farawa hira...',
sendMessage: 'Aika saƙo',
@@ -1144,6 +1151,11 @@ const resources = {
recentlyUsed: 'An yi amfani da su kwanan nan',
errorLoadingModels: 'Kuskure wajen Lodin Samfura',
// API Authentication Errors
apiAuthenticationFailed: 'Gazawar Tabbatarwar API',
invalidApiKey: 'Maɓallin API na {{provider}} ba daidai ba ne. Da fatan za a duba maɓallin API a cikin Saitunan.',
checkApiKeySettings: 'Duba Saitunan Maɓallin API',
// Context and Cost
contextUsage: 'Amfanin mahallin: {{tokens}} / {{total}} alamomi ({{percentage}}%)',
totalCostSession: 'Jimlar farashi don wannan zaman hira',
@@ -1282,8 +1294,6 @@ const resources = {
getHelp: '🔧 Gba iranlọwọ pẹlu atunṣe ati imudara',
buildDeploy: '🚀 Kọ ati gbe iṣẹ akanṣe rẹ lọ',
aiNotConfigured: 'Oluranlọwọ AI Ko Tunto',
configureAI: 'Jọwọ tunto awọn eto AI rẹ lati bẹrẹ kikọ pẹlu iranlọwọ AI.',
useMenuForAI: 'Lo akojọ aṣayan ni oke ọpa lati wọle si Awọn eto AI.',
askToAddFeatures: 'Beere mi lati fi awọn ẹya kun, ṣatunkọ awọn faili, tabi kọ iṣẹ akanṣe rẹ...',
selectModelFirst: 'Jọwọ yan awoṣe lati bẹrẹ ibaraẹnisọrọ...',
sendMessage: 'Fi ifiranṣẹ ranṣẹ',
@@ -1578,8 +1588,6 @@ const resources = {
getHelp: '🔧 Nweta enyemaka na debugging na optimization',
buildDeploy: '🚀 Wuo ma bufee ọrụ gị',
aiNotConfigured: 'Onye Enyemaka AI Ahazighị',
configureAI: 'Biko hazie ntọala AI gị iji malite iwu na enyemaka AI.',
useMenuForAI: 'Jiri menu dị n\'elu okporo iji nweta Ntọala AI.',
askToAddFeatures: 'Rịọ m ka m tinye atụmatụ, dezie faịlụ, ma ọ bụ wuo ọrụ gị...',
selectModelFirst: 'Biko họrọ ụdịdị iji malite ikwu okwu...',
sendMessage: 'Ziga ozi',
+6 -6
View File
@@ -29,9 +29,9 @@ describe('parseProviderModel', () => {
it('should parse simple provider/model format', () => {
const result = parseProviderModel('openai/gpt-4o', mockProviders);
expect(result.provider).toBe('openai');
expect(result.model).toBe('gpt-4o');
expect(result.connection).toEqual({
expect(result.provider).toEqual({
id: 'openai',
baseURL: mockProviders[0].baseURL,
apiKey: mockProviders[0].apiKey,
nostr: mockProviders[0].nostr,
@@ -41,9 +41,9 @@ describe('parseProviderModel', () => {
it('should parse complex model names with slashes', () => {
const result = parseProviderModel('openrouter/anthropic/claude-sonnet-4', mockProviders);
expect(result.provider).toBe('openrouter');
expect(result.model).toBe('anthropic/claude-sonnet-4');
expect(result.connection).toEqual({
expect(result.provider).toEqual({
id: 'openrouter',
baseURL: mockProviders[1].baseURL,
apiKey: mockProviders[1].apiKey,
nostr: mockProviders[1].nostr,
@@ -53,9 +53,9 @@ describe('parseProviderModel', () => {
it('should handle model names with multiple slashes', () => {
const result = parseProviderModel('openrouter/meta/llama-3.1-405b-instruct', mockProviders);
expect(result.provider).toBe('openrouter');
expect(result.model).toBe('meta/llama-3.1-405b-instruct');
expect(result.connection).toEqual({
expect(result.provider).toEqual({
id: 'openrouter',
baseURL: mockProviders[1].baseURL,
apiKey: mockProviders[1].apiKey,
nostr: mockProviders[1].nostr,
+7 -17
View File
@@ -1,13 +1,8 @@
import type { AIProvider } from '@/contexts/AISettingsContext';
export interface ParsedProviderModel {
provider: string;
model: string;
connection: {
baseURL: string;
apiKey?: string;
nostr?: boolean;
};
provider: AIProvider;
}
/**
@@ -25,25 +20,20 @@ export function parseProviderModel(
throw new Error('Invalid format. Use provider/model (e.g., "openai/gpt-4o")');
}
const provider = providerModelString.substring(0, firstSlashIndex);
const providerId = providerModelString.substring(0, firstSlashIndex);
const model = providerModelString.substring(firstSlashIndex + 1);
if (!provider || !model) {
if (!providerId || !model) {
throw new Error('Invalid format. Both provider and model must be specified');
}
const providerObj = providers.find(p => p.id === provider);
if (!providerObj) {
throw new Error(`Provider "${provider}" not found. Available providers: ${providers.map(p => p.id).join(', ')}`);
const provider = providers.find(p => p.id === providerId);
if (!provider) {
throw new Error(`Provider "${providerId}" not found. Available providers: ${providers.map(p => p.id).join(', ')}`);
}
return {
provider,
model,
connection: {
baseURL: providerObj.baseURL,
apiKey: providerObj.apiKey,
nostr: providerObj.nostr,
},
provider,
};
}
+1 -1
View File
@@ -44,7 +44,7 @@ describe('ShellTool', () => {
});
it('should have correct tool properties', () => {
expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators');
expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators');
expect(shellTool.inputSchema).toBeDefined();
});
+5 -1
View File
@@ -18,6 +18,7 @@ import {
GitCommand,
GrepCommand,
HeadCommand,
HexdumpCommand,
LsCommand,
MkdirCommand,
MvCommand,
@@ -28,6 +29,7 @@ import {
TouchCommand,
TrCommand,
UniqCommand,
UnzipCommand,
WcCommand,
WhoamiCommand,
WhichCommand
@@ -46,7 +48,7 @@ export class ShellTool implements Tool<ShellToolParams> {
private git: Git;
private commands: Map<string, ShellCommand>;
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators";
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators";
readonly inputSchema = z.object({
command: z.string().describe(
@@ -75,6 +77,7 @@ export class ShellTool implements Tool<ShellToolParams> {
this.registerCommand(new GitCommand({ git: this.git, fs, cwd: this.cwd }));
this.registerCommand(new GrepCommand(fs));
this.registerCommand(new HeadCommand(fs));
this.registerCommand(new HexdumpCommand(fs));
this.registerCommand(new LsCommand(fs));
this.registerCommand(new MkdirCommand(fs));
this.registerCommand(new MvCommand(fs));
@@ -85,6 +88,7 @@ export class ShellTool implements Tool<ShellToolParams> {
this.registerCommand(new TouchCommand(fs));
this.registerCommand(new TrCommand(fs));
this.registerCommand(new UniqCommand(fs));
this.registerCommand(new UnzipCommand(fs));
this.registerCommand(new WcCommand(fs));
this.registerCommand(new WhoamiCommand());