mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Add DotAI class
This commit is contained in:
4 files changed
+412
-25
No files matched your search
@@ -1,5 +1,4 @@
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { generateId } from 'ai';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Send, Settings, Play, CloudUpload, Loader2 } from 'lucide-react';
|
||||
@@ -83,7 +82,6 @@ When creating new components or pages, follow the existing patterns in the codeb
|
||||
sendMessage,
|
||||
stopStreaming,
|
||||
clearMessages,
|
||||
addMessage
|
||||
} = useStreamingChat({
|
||||
projectId,
|
||||
projectName,
|
||||
@@ -198,18 +196,6 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
clearMessages();
|
||||
}, [projectId, clearMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
// Add welcome message
|
||||
if (!messages.length) {
|
||||
addMessage({
|
||||
id: generateId(),
|
||||
role: 'assistant' as const,
|
||||
content: `Hello! I'm here to help you build "${projectName}". I can help you edit files, add new features, and build your Nostr website. What would you like to work on?`,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
}
|
||||
}, [projectName, messages, addMessage]);
|
||||
|
||||
useEffect(() => {
|
||||
if (scrollAreaRef.current && messages) {
|
||||
// Check if user was already at or near the bottom (within 100px threshold)
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useState, useCallback, useRef } from 'react';
|
||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
|
||||
import { streamText, ModelMessage, generateId, Tool, stepCountIs } from 'ai';
|
||||
import type { TextPart, ToolCallPart, ToolResultPart } from 'ai';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
|
||||
// Extend ModelMessage with additional UI state
|
||||
export type ChatMessage = ModelMessage & {
|
||||
@@ -21,6 +23,7 @@ interface UseStreamingChatOptions {
|
||||
}
|
||||
|
||||
export function useStreamingChat({
|
||||
projectId,
|
||||
projectName,
|
||||
tools = {},
|
||||
systemPrompt,
|
||||
@@ -30,8 +33,116 @@ export function useStreamingChat({
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [isStreaming, setIsStreaming] = useState(false);
|
||||
const [currentStreamingMessageId, setCurrentStreamingMessageId] = useState<string | null>(null);
|
||||
const [sessionName, setSessionName] = useState<string>('');
|
||||
const [isHistoryLoaded, setIsHistoryLoaded] = useState(false);
|
||||
const abortControllerRef = useRef<AbortController | null>(null);
|
||||
const { settings, isConfigured } = useAISettings();
|
||||
const { fs } = useFS();
|
||||
const dotAIRef = useRef<DotAI | null>(null);
|
||||
|
||||
// Initialize DotAI for this project
|
||||
useEffect(() => {
|
||||
const initializeDotAI = async () => {
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `/projects/${projectId}`);
|
||||
dotAIRef.current = dotAI;
|
||||
|
||||
// Generate session name if not already set
|
||||
if (!sessionName) {
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to initialize DotAI:', error);
|
||||
}
|
||||
};
|
||||
|
||||
initializeDotAI();
|
||||
}, [fs, projectId, sessionName]);
|
||||
|
||||
// Load message history when project changes
|
||||
useEffect(() => {
|
||||
const loadMessageHistory = async () => {
|
||||
if (!dotAIRef.current || isHistoryLoaded) return;
|
||||
|
||||
try {
|
||||
const historyDir = `/projects/${projectId}/.ai/history`;
|
||||
|
||||
// Check if history directory exists
|
||||
try {
|
||||
await fs.stat(historyDir);
|
||||
} catch {
|
||||
// History directory doesn't exist, no history to load
|
||||
setIsHistoryLoaded(true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get all session files
|
||||
const files = await fs.readdir(historyDir);
|
||||
const sessionFiles = files.filter(file => file.endsWith('.jsonl'));
|
||||
|
||||
if (sessionFiles.length === 0) {
|
||||
setIsHistoryLoaded(true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Sort by filename (which includes timestamp) to get the latest session
|
||||
sessionFiles.sort();
|
||||
const latestSessionFile = sessionFiles[sessionFiles.length - 1];
|
||||
const latestSessionName = latestSessionFile.replace('.jsonl', '');
|
||||
|
||||
// Load messages from the latest session
|
||||
const sessionPath = `${historyDir}/${latestSessionFile}`;
|
||||
const sessionContent = await fs.readFile(sessionPath, 'utf8');
|
||||
|
||||
const loadedMessages: ChatMessage[] = [];
|
||||
const lines = sessionContent.split('\n').filter(line => line.trim());
|
||||
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const messageData = JSON.parse(line);
|
||||
// Convert to ChatMessage format
|
||||
const chatMessage: ChatMessage = {
|
||||
id: generateId(),
|
||||
role: messageData.role,
|
||||
content: messageData.content,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
loadedMessages.push(chatMessage);
|
||||
} catch (error) {
|
||||
console.warn('Failed to parse message from history:', error);
|
||||
}
|
||||
}
|
||||
|
||||
if (loadedMessages.length > 0) {
|
||||
setMessages(loadedMessages);
|
||||
setSessionName(latestSessionName);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load message history:', error);
|
||||
} finally {
|
||||
setIsHistoryLoaded(true);
|
||||
}
|
||||
};
|
||||
|
||||
loadMessageHistory();
|
||||
}, [fs, projectId, isHistoryLoaded]);
|
||||
|
||||
// Save message to history
|
||||
const saveMessageToHistory = useCallback(async (message: ChatMessage) => {
|
||||
if (!dotAIRef.current || !sessionName) return;
|
||||
|
||||
try {
|
||||
// Convert ChatMessage to DotAI format
|
||||
const aiMessage = {
|
||||
role: message.role,
|
||||
content: message.content
|
||||
};
|
||||
|
||||
await dotAIRef.current.addToHistory(sessionName, aiMessage);
|
||||
} catch (error) {
|
||||
console.warn('Failed to save message to history:', error);
|
||||
}
|
||||
}, [sessionName]);
|
||||
|
||||
// Convert ChatMessage to ModelMessage for AI SDK
|
||||
const convertToModelMessages = useCallback((chatMessages: ChatMessage[]): ModelMessage[] => {
|
||||
@@ -44,17 +155,27 @@ export function useStreamingChat({
|
||||
messageMap.set(message.id, message);
|
||||
return Array.from(messageMap.values());
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Save to history (async, don't block UI)
|
||||
saveMessageToHistory(message);
|
||||
}, [saveMessageToHistory]);
|
||||
|
||||
const updateMessage = useCallback((id: string, updates: Partial<ChatMessage> | ((prev: ChatMessage) => Partial<ChatMessage>)) => {
|
||||
setMessages(prev => prev.map(msg => {
|
||||
if (msg.id === id) {
|
||||
const updatesObj = typeof updates === 'function' ? updates(msg) : updates;
|
||||
return { ...msg, ...updatesObj } as ChatMessage;
|
||||
const updatedMessage = { ...msg, ...updatesObj } as ChatMessage;
|
||||
|
||||
// Save to history when message is finalized (streaming stops)
|
||||
if (updatesObj.isStreaming === false && msg.isStreaming === true) {
|
||||
saveMessageToHistory(updatedMessage);
|
||||
}
|
||||
|
||||
return updatedMessage;
|
||||
}
|
||||
return msg;
|
||||
}));
|
||||
}, []);
|
||||
}, [saveMessageToHistory]);
|
||||
|
||||
const sendMessage = useCallback(async (content: string) => {
|
||||
if (!isConfigured || isStreaming) return;
|
||||
@@ -297,6 +418,8 @@ export function useStreamingChat({
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
setMessages([]);
|
||||
// Start a new session when clearing messages
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}, []);
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
import { join } from "@std/path";
|
||||
import { JSRuntimeFS } from "./JSRuntime";
|
||||
|
||||
interface AIMessage {
|
||||
role: string;
|
||||
content: string | { type: string }[];
|
||||
}
|
||||
|
||||
/** NodeFS interface for file system operations */
|
||||
export interface NodeFS {
|
||||
access(path: string): Promise<void>;
|
||||
readFile(path: string, encoding: "utf8"): Promise<string>;
|
||||
writeFile(path: string, data: string, encoding: "utf8"): Promise<void>;
|
||||
appendFile(path: string, data: string, encoding: "utf8"): Promise<void>;
|
||||
mkdir(path: string, options: { recursive: boolean }): Promise<unknown>;
|
||||
}
|
||||
|
||||
/** AI message history manager and .ai directory utilities */
|
||||
export class DotAI {
|
||||
private readonly fs: JSRuntimeFS;
|
||||
private readonly historyDir: string;
|
||||
private readonly workingDir: string;
|
||||
|
||||
constructor(fs: JSRuntimeFS, workingDir: string = process.cwd()) {
|
||||
this.fs = fs;
|
||||
this.workingDir = workingDir;
|
||||
this.historyDir = join(workingDir, ".ai", "history");
|
||||
}
|
||||
|
||||
/** Generate a unique session name based on the current date and time */
|
||||
static generateSessionName(): string {
|
||||
// Generate filename with date, time in milliseconds, and random value
|
||||
const now = new Date();
|
||||
const dateString = now.toISOString();
|
||||
|
||||
// Generate a random 3-character suffix to avoid collisions
|
||||
const randomSuffix = Math.random().toString(36).substring(2, 5);
|
||||
|
||||
// Format: YYYY-MM-DDTHH-MM-SSZ-suffix.jsonl
|
||||
const filename = `${
|
||||
dateString.replace(/:/g, "-").slice(0, dateString.indexOf("."))
|
||||
}Z-${randomSuffix}`;
|
||||
|
||||
return filename;
|
||||
}
|
||||
|
||||
/** Check if AI history should be enabled based on the new criteria */
|
||||
async isEnabled(): Promise<boolean> {
|
||||
// Check if .ai directory exists
|
||||
try {
|
||||
const stat = await this.fs.stat(join(this.workingDir, ".ai"));
|
||||
return stat.isDirectory();
|
||||
} catch {
|
||||
// Continue to next check
|
||||
}
|
||||
|
||||
// Check if .ai/ or .ai is gitignored
|
||||
try {
|
||||
const gitignorePath = join(this.workingDir, ".gitignore");
|
||||
const gitignoreContent = await this.fs.readFile(gitignorePath, "utf8");
|
||||
const lines = gitignoreContent.split("\n").map((line) => line.trim());
|
||||
|
||||
// Check for .ai/ or .ai patterns (ignore comments and empty lines)
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("#") || line === "") {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check for various .ai patterns
|
||||
if (
|
||||
line === ".ai" || line === ".ai/" || line === "/.ai" ||
|
||||
line === "/.ai/" ||
|
||||
line === ".ai/*" || line === "/.ai/*"
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// .gitignore doesn't exist or can't be read
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Check if the history directory exists */
|
||||
async historyDirExists(): Promise<boolean> {
|
||||
try {
|
||||
const stat = await this.fs.stat(this.historyDir);
|
||||
return stat.isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Save a message to the history file */
|
||||
async addToHistory(sessionName: string, message: AIMessage): Promise<void> {
|
||||
// Only save if history should be enabled based on the new criteria
|
||||
if (!(await this.isEnabled())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Create the history directory if it doesn't exist
|
||||
if (!(await this.historyDirExists())) {
|
||||
await this.setupAiHistoryDir();
|
||||
}
|
||||
|
||||
const jsonLine = JSON.stringify(message);
|
||||
const sessionFile = join(this.historyDir, sessionName + ".jsonl");
|
||||
|
||||
try {
|
||||
// Try to read existing content
|
||||
const existingContent = await this.fs.readFile(sessionFile, "utf8");
|
||||
await this.fs.writeFile(sessionFile, existingContent + "\n" + jsonLine, "utf8");
|
||||
} catch {
|
||||
// File doesn't exist, create it with the data
|
||||
await this.fs.writeFile(sessionFile, jsonLine, "utf8");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates .ai/history directory and ensures .ai/ is gitignored at the project root.
|
||||
*/
|
||||
async setupAiHistoryDir(): Promise<void> {
|
||||
const aiHistoryDir = join(this.workingDir, ".ai", "history");
|
||||
|
||||
try {
|
||||
// Create .ai/history directory
|
||||
await this.fs.mkdir(aiHistoryDir, { recursive: true });
|
||||
|
||||
// Ensure .ai/ is gitignored at the project root
|
||||
await this.ensureAiGitignored();
|
||||
} catch (error) {
|
||||
// Log error but don't fail the main operation
|
||||
console.warn(`Failed to setup .ai/history directory: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the model from .ai/MODEL file
|
||||
*/
|
||||
async readAiModel(): Promise<string | undefined> {
|
||||
try {
|
||||
const modelPath = join(this.workingDir, ".ai", "MODEL");
|
||||
const content = await this.fs.readFile(modelPath, "utf8");
|
||||
return content.trim();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the model to .ai/MODEL file
|
||||
*/
|
||||
async writeAiModel(model: string): Promise<void> {
|
||||
const aiDir = join(this.workingDir, ".ai");
|
||||
const modelPath = join(aiDir, "MODEL");
|
||||
|
||||
try {
|
||||
// Ensure .ai directory exists
|
||||
await this.fs.mkdir(aiDir, { recursive: true });
|
||||
|
||||
// Write the model
|
||||
await this.fs.writeFile(modelPath, model.trim() + "\n", "utf8");
|
||||
} catch (error) {
|
||||
console.warn(`Failed to write .ai/MODEL file: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read parameters from .ai/PARAMETERS file
|
||||
*/
|
||||
async readAiParameters(): Promise<Record<string, string>> {
|
||||
try {
|
||||
const parametersPath = join(this.workingDir, ".ai", "PARAMETERS");
|
||||
const content = await this.fs.readFile(parametersPath, "utf8");
|
||||
|
||||
const parameters: Record<string, string> = {};
|
||||
const lines = content.split("\n");
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine && !trimmedLine.startsWith("#")) {
|
||||
const equalIndex = trimmedLine.indexOf("=");
|
||||
if (equalIndex > 0) {
|
||||
const key = trimmedLine.substring(0, equalIndex).trim();
|
||||
const value = trimmedLine.substring(equalIndex + 1).trim();
|
||||
parameters[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return parameters;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write parameters to .ai/PARAMETERS file
|
||||
*/
|
||||
async writeAiParameters(parameters: Record<string, string>): Promise<void> {
|
||||
// Check if we should create the .ai directory based on the same logic as MODEL
|
||||
const shouldCreate = await this.isEnabled();
|
||||
|
||||
if (!shouldCreate) {
|
||||
return;
|
||||
}
|
||||
|
||||
const aiDir = join(this.workingDir, ".ai");
|
||||
const parametersPath = join(aiDir, "PARAMETERS");
|
||||
|
||||
try {
|
||||
// Ensure .ai directory exists
|
||||
await this.fs.mkdir(aiDir, { recursive: true });
|
||||
|
||||
// Format parameters as key=value pairs
|
||||
const lines = Object.entries(parameters).map(([key, value]) =>
|
||||
`${key}=${value}`
|
||||
);
|
||||
const content = lines.join("\n") + (lines.length > 0 ? "\n" : "");
|
||||
|
||||
// Write the parameters
|
||||
await this.fs.writeFile(parametersPath, content, "utf8");
|
||||
} catch (error) {
|
||||
console.warn(`Failed to write .ai/PARAMETERS file: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a single parameter in .ai/PARAMETERS file
|
||||
*/
|
||||
async updateAiParameter(key: string, value: string): Promise<void> {
|
||||
const currentParameters = await this.readAiParameters();
|
||||
currentParameters[key] = value;
|
||||
await this.writeAiParameters(currentParameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that .ai/ is gitignored at the project root level.
|
||||
* Creates a .gitignore file if it doesn't exist, or adds the line if not already present.
|
||||
*/
|
||||
async ensureAiGitignored(): Promise<void> {
|
||||
const gitignorePath = join(this.workingDir, ".gitignore");
|
||||
const aiPattern = ".ai/";
|
||||
|
||||
try {
|
||||
// Try to read existing .gitignore
|
||||
let gitignoreContent = "";
|
||||
try {
|
||||
gitignoreContent = await this.fs.readFile(gitignorePath, "utf8");
|
||||
} catch {
|
||||
// .gitignore doesn't exist, will create it
|
||||
}
|
||||
|
||||
// Check if .ai/ is already gitignored
|
||||
const lines = gitignoreContent.split("\n").map((line) => line.trim());
|
||||
const hasAiPattern = lines.some((line) => {
|
||||
if (line.startsWith("#") || line === "") {
|
||||
return false;
|
||||
}
|
||||
// Check for various .ai patterns
|
||||
return line === ".ai" || line === ".ai/" || line === "/.ai" ||
|
||||
line === "/.ai/" ||
|
||||
line === ".ai/*" || line === "/.ai/*";
|
||||
});
|
||||
|
||||
if (!hasAiPattern) {
|
||||
// Add .ai/ to .gitignore
|
||||
const newContent = gitignoreContent.trim() === ""
|
||||
? aiPattern
|
||||
: gitignoreContent.trim() + "\n" + aiPattern;
|
||||
|
||||
await this.fs.writeFile(gitignorePath, newContent + "\n", "utf8");
|
||||
}
|
||||
} catch (error) {
|
||||
// Log error but don't fail the main operation
|
||||
console.warn(`Failed to ensure .ai/ is gitignored: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import git from 'isomorphic-git';
|
||||
import http from 'isomorphic-git/http/web';
|
||||
import { Buffer } from 'buffer';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import { DotAI } from './DotAI';
|
||||
|
||||
// Polyfill Buffer for browser
|
||||
if (typeof window !== 'undefined') {
|
||||
@@ -36,7 +37,10 @@ export class ProjectsManager {
|
||||
}
|
||||
|
||||
async createProject(name: string): Promise<Project> {
|
||||
return this.cloneProject(name, GIT_TEMPLATE_URL);
|
||||
const project = await this.cloneProject(name, GIT_TEMPLATE_URL);
|
||||
const dotAI = new DotAI(this.fs, project.path);
|
||||
await dotAI.setupAiHistoryDir();
|
||||
return project;
|
||||
}
|
||||
|
||||
async cloneProject(name: string, repoUrl: string): Promise<Project> {
|
||||
@@ -74,8 +78,6 @@ export class ProjectsManager {
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
async getProjects(): Promise<Project[]> {
|
||||
try {
|
||||
const projectDirs = await this.fs.readdir(this.dir);
|
||||
@@ -259,10 +261,6 @@ export class ProjectsManager {
|
||||
return naddr !== null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
private formatProjectName(dirName: string): string {
|
||||
// Return the original directory name without formatting
|
||||
return dirName;
|
||||
|
||||
Reference in new issue
Block a user