diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index ecd1a5d4..d18a9717 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -13,6 +13,7 @@ import { useKeepAlive } from '@/hooks/useKeepAlive'; import { useAppContext } from '@/hooks/useAppContext'; import { useAIChat } from '@/hooks/useAIChat'; import { useProviderModels } from '@/hooks/useProviderModels'; +import { useSessionManager } from '@/hooks/useSessionManager'; import { AIMessageItem } from '@/components/AIMessageItem'; import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool'; import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool'; @@ -138,12 +139,20 @@ export const ChatPane = forwardRef(({ // Initialize AI chat with tools const cwd = `${projectsPath}/${projectId}`; const esmUrlRef = useRef(config.esmUrl); + const sessionManager = useSessionManager(); + + // Callback to emit file changes for auto-build + const handleFileChanged = useCallback((filePath: string) => { + // Emit the fileChanged event through the session manager + sessionManager.emit('fileChanged', projectId, filePath); + }, [sessionManager, projectId]); + const customTools = useMemo(() => { const baseTools = { git_commit: new GitCommitTool(fs, cwd, git), text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }), - text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath }), - text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd, { projectsPath, tmpPath }), + text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }), + text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }), npm_add_package: new NpmAddPackageTool(fs, cwd), npm_remove_package: new NpmRemovePackageTool(fs, cwd), build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current), @@ -169,7 +178,7 @@ export const ChatPane = forwardRef(({ } return baseTools; - }, [fs, git, cwd, user, projectId, projectsPath, tmpPath]); + }, [fs, git, cwd, user, projectId, projectsPath, tmpPath, handleFileChanged]); // Convert tools to OpenAI format const tools = useMemo(() => { diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index a802b8a9..6ab9e75b 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -741,7 +741,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
- Building project... +
+ Building project... + Preview will update automatically +
)} diff --git a/src/hooks/useAutoBuild.ts b/src/hooks/useAutoBuild.ts new file mode 100644 index 00000000..7fc9fb3f --- /dev/null +++ b/src/hooks/useAutoBuild.ts @@ -0,0 +1,81 @@ +import { useEffect, useRef, useCallback } from 'react'; +import { BuildDebouncer } from '@/lib/BuildDebouncer'; +import { useBuildProject } from './useBuildProject'; +import { useSessionSubscription } from './useSessionSubscription'; + +interface UseAutoBuildOptions { + projectId: string; + enabled?: boolean; + debounceMs?: number; +} + +/** + * Hook that automatically builds a project when files are changed by the AI. + * Uses a debouncer to avoid excessive builds. + */ +export function useAutoBuild({ + projectId, + enabled = true, + debounceMs = 2000 +}: UseAutoBuildOptions) { + const { mutate: buildProject, isPending: isBuildPending } = useBuildProject(projectId); + + const debouncerRef = useRef(null); + + // Initialize debouncer + useEffect(() => { + if (!enabled) { + return; + } + + const handleBuild = (buildProjectId: string, changedFiles: string[]) => { + console.log(`Auto-building project ${buildProjectId} after changes to:`, changedFiles); + buildProject(); + }; + + debouncerRef.current = new BuildDebouncer(debounceMs, handleBuild); + + return () => { + debouncerRef.current?.cleanup(); + debouncerRef.current = null; + }; + }, [enabled, debounceMs, buildProject]); + + // Listen for file changes from the session manager + useSessionSubscription('fileChanged', (changedProjectId: string, filePath: string) => { + if (changedProjectId === projectId && enabled && debouncerRef.current) { + console.log(`File changed in project ${projectId}:`, filePath); + debouncerRef.current.registerFileChange(projectId, filePath); + } + }, [projectId, enabled]); + + // Cancel pending builds when AI stops loading + useSessionSubscription('loadingChanged', (changedProjectId: string, isLoading: boolean) => { + if (changedProjectId === projectId && !isLoading && enabled && debouncerRef.current) { + // When AI stops, trigger any pending build immediately + if (debouncerRef.current.hasPendingChanges(projectId)) { + console.log(`AI stopped, triggering pending build for ${projectId}`); + debouncerRef.current.triggerBuild(projectId); + } + } + }, [projectId, enabled]); + + const triggerBuild = useCallback(() => { + debouncerRef.current?.triggerBuild(projectId); + }, [projectId]); + + const cancelBuild = useCallback(() => { + debouncerRef.current?.cancel(projectId); + }, [projectId]); + + const hasPendingChanges = useCallback(() => { + return debouncerRef.current?.hasPendingChanges(projectId) || false; + }, [projectId]); + + return { + triggerBuild, + cancelBuild, + hasPendingChanges, + isBuildPending, + }; +} diff --git a/src/lib/BuildDebouncer.ts b/src/lib/BuildDebouncer.ts new file mode 100644 index 00000000..9c8124fc --- /dev/null +++ b/src/lib/BuildDebouncer.ts @@ -0,0 +1,102 @@ +/** + * BuildDebouncer manages automatic builds triggered by file changes. + * It debounces build requests to avoid excessive builds while the AI is working. + */ +export class BuildDebouncer { + private debounceTimers = new Map(); + private pendingBuilds = new Map>(); + private readonly debounceMs: number; + private readonly onBuild: (projectId: string, changedFiles: string[]) => void; + + constructor( + debounceMs: number = 2000, + onBuild: (projectId: string, changedFiles: string[]) => void + ) { + this.debounceMs = debounceMs; + this.onBuild = onBuild; + } + + /** + * Register a file change for a project. + * This will trigger a debounced build after the configured delay. + */ + registerFileChange(projectId: string, filePath: string): void { + // Track the changed file + if (!this.pendingBuilds.has(projectId)) { + this.pendingBuilds.set(projectId, new Set()); + } + this.pendingBuilds.get(projectId)!.add(filePath); + + // Clear existing timer + const existingTimer = this.debounceTimers.get(projectId); + if (existingTimer) { + clearTimeout(existingTimer); + } + + // Set new timer + const timer = setTimeout(() => { + this.triggerBuild(projectId); + }, this.debounceMs); + + this.debounceTimers.set(projectId, timer); + } + + /** + * Trigger an immediate build for a project, bypassing the debounce. + */ + triggerBuild(projectId: string): void { + const changedFiles = Array.from(this.pendingBuilds.get(projectId) || []); + + if (changedFiles.length === 0) { + return; + } + + // Clear the pending builds and timer + this.pendingBuilds.delete(projectId); + const timer = this.debounceTimers.get(projectId); + if (timer) { + clearTimeout(timer); + this.debounceTimers.delete(projectId); + } + + // Trigger the build + this.onBuild(projectId, changedFiles); + } + + /** + * Cancel any pending builds for a project. + */ + cancel(projectId: string): void { + const timer = this.debounceTimers.get(projectId); + if (timer) { + clearTimeout(timer); + this.debounceTimers.delete(projectId); + } + this.pendingBuilds.delete(projectId); + } + + /** + * Check if a project has pending file changes. + */ + hasPendingChanges(projectId: string): boolean { + return (this.pendingBuilds.get(projectId)?.size || 0) > 0; + } + + /** + * Get the list of pending changed files for a project. + */ + getPendingFiles(projectId: string): string[] { + return Array.from(this.pendingBuilds.get(projectId) || []); + } + + /** + * Cleanup all timers (call on unmount/cleanup). + */ + cleanup(): void { + for (const timer of this.debounceTimers.values()) { + clearTimeout(timer); + } + this.debounceTimers.clear(); + this.pendingBuilds.clear(); + } +} diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 302f5530..9d247923 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -47,6 +47,7 @@ export interface SessionManagerEvents { loadingChanged: (projectId: string, isLoading: boolean) => void; costUpdated: (projectId: string, totalCost: number) => void; contextUsageUpdated: (projectId: string, inputTokens: number) => void; + fileChanged: (projectId: string, filePath: string) => void; } /** diff --git a/src/lib/tools/TextEditorStrReplaceTool.ts b/src/lib/tools/TextEditorStrReplaceTool.ts index f39ffc42..f8e312b4 100644 --- a/src/lib/tools/TextEditorStrReplaceTool.ts +++ b/src/lib/tools/TextEditorStrReplaceTool.ts @@ -17,6 +17,7 @@ export class TextEditorStrReplaceTool implements Tool void; readonly description = "Replace a string in a file with a new string"; @@ -29,11 +30,12 @@ export class TextEditorStrReplaceTool implements Tool void }) { this.fs = fs; this.cwd = cwd; this.projectsPath = options?.projectsPath || '/projects'; this.tmpPath = options?.tmpPath || '/tmp'; + this.onFileChanged = options?.onFileChanged; } async execute(args: TextEditorStrReplaceParams): Promise { @@ -172,6 +174,11 @@ export class TextEditorStrReplaceTool implements Tool 1) { successMessage += ` (${occurrences} occurrences found, only first occurrence replaced)`; diff --git a/src/lib/tools/TextEditorWriteTool.ts b/src/lib/tools/TextEditorWriteTool.ts index e0518e60..81a23ba5 100644 --- a/src/lib/tools/TextEditorWriteTool.ts +++ b/src/lib/tools/TextEditorWriteTool.ts @@ -15,6 +15,7 @@ export class TextEditorWriteTool implements Tool { private cwd: string; private projectsPath: string; private tmpPath: string; + private onFileChanged?: (filePath: string) => void; readonly description = "Create or overwrite a file with new content"; @@ -25,11 +26,12 @@ export class TextEditorWriteTool implements Tool { file_text: z.string().describe("Content to write to the file"), }); - constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string; tmpPath?: string }) { + constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string; tmpPath?: string; onFileChanged?: (filePath: string) => void }) { this.fs = fs; this.cwd = cwd; this.projectsPath = options?.projectsPath || '/projects'; this.tmpPath = options?.tmpPath || '/tmp'; + this.onFileChanged = options?.onFileChanged; } async execute(args: TextEditorWriteParams): Promise { @@ -58,6 +60,12 @@ export class TextEditorWriteTool implements Tool { await this.fs.mkdir(dirname(absolutePath), { recursive: true }); await this.fs.writeFile(absolutePath, file_text, "utf8"); + + // Notify about file change (for auto-build) + if (this.onFileChanged) { + this.onFileChanged(path); + } + return `File successfully written to ${path}`; } catch (error) { throw new Error(String(error)); diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index 87a3af2e..7f7b00ed 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -19,6 +19,7 @@ import { StarButton } from '@/components/StarButton'; import { useBuildProject } from '@/hooks/useBuildProject'; import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable'; import { useConsoleError } from '@/hooks/useConsoleError'; +import { useAutoBuild } from '@/hooks/useAutoBuild'; export function ProjectView() { const { projectId } = useParams<{ projectId: string }>(); @@ -43,6 +44,13 @@ export function ProjectView() { const build = useBuildProject(projectId!); const { data: isPreviewable = false } = useIsProjectPreviewable(projectId!); + // Enable auto-build for previewable projects + useAutoBuild({ + projectId: projectId!, + enabled: isPreviewable, + debounceMs: 2000, + }); + const loadProject = useCallback(async () => { if (!projectId) return;