Progressively rebuild when files change

This commit is contained in:
Alex Gleason committed 2025-11-04 17:22:12 -06:00
1 parent adc4dd19b7
commit ef6962d7c7
8 files changed
+225 -6

No files matched your search

+12 -3
View File
@@ -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<ChatPaneRef, ChatPaneProps>(({
// 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<ChatPaneRef, ChatPaneProps>(({
}
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(() => {
+4 -1
View File
@@ -741,7 +741,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<div className="absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10">
<div className="bg-background/90 border rounded-lg p-4 shadow-lg flex items-center gap-3">
<Loader2 className="h-5 w-5 animate-spin text-primary" />
<span className="text-sm font-medium">Building project...</span>
<div className="flex flex-col">
<span className="text-sm font-medium">Building project...</span>
<span className="text-xs text-muted-foreground">Preview will update automatically</span>
</div>
</div>
</div>
)}
+81
View File
@@ -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<BuildDebouncer | null>(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,
};
}
+102
View File
@@ -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<string, NodeJS.Timeout>();
private pendingBuilds = new Map<string, Set<string>>();
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();
}
}
+1
View File
@@ -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;
}
/**
+8 -1
View File
@@ -17,6 +17,7 @@ export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams
private cwd: string;
private projectsPath: string;
private tmpPath: string;
private onFileChanged?: (filePath: string) => void;
readonly description = "Replace a string in a file with a new string";
@@ -29,11 +30,12 @@ export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams
),
});
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: TextEditorStrReplaceParams): Promise<string> {
@@ -172,6 +174,11 @@ export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams
await this.fs.writeFile(absolutePath, newContent, "utf8");
// Notify about file change (for auto-build)
if (this.onFileChanged) {
this.onFileChanged(path);
}
let successMessage = `String successfully replaced in ${path}`;
if (occurrences > 1) {
successMessage += ` (${occurrences} occurrences found, only first occurrence replaced)`;
+9 -1
View File
@@ -15,6 +15,7 @@ export class TextEditorWriteTool implements Tool<TextEditorWriteParams> {
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<TextEditorWriteParams> {
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<string> {
@@ -58,6 +60,12 @@ export class TextEditorWriteTool implements Tool<TextEditorWriteParams> {
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));
+8
View File
@@ -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;