Update app.js
Browse files20 unmodified lines21222324252678 unmodified lines10510610710810911017 unmodified lines1281291301311321331341351361371385 unmodified lines1441451461471481491501511521535 unmodified lines1591601611621631641651 unmodified line16716816917017117217317417517634 unmodified lines2112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442453 unmodified lines2492502512522532542552562572582597 unmodified lines2672682692702712722732742752762772782792802812822834 unmodified lines2882892902912922932942952962972982993003013023033043055 unmodified lines3113123133143153163173183193203213223233243253263274 unmodified lines332333334335336337338339340341342343344345346166 unmodified lines51351451551651751851952052152252352452552652720 unmodified linesconst MIN_BASIC_REQUIRED = 50;const MIN_DIAMOND_REQUIRED = 50;async function checkMinimumCredits(userId, type = 'basic') {if (!supabase) return;78 unmodified linesreturn out;}async function runBackgroundInitialization(projectId, userId, description) {if (StateManager.isLocked(projectId)) {console.log(`[Init Guard] Project ${projectId} is already initializing. Skipping.`);17 unmodified linesconst pmHistory = [];StateManager.setStatus(projectId, "Project Manager: Writing Design Doc...");const gddPrompt = `Create a comprehensive Game Design Document (GDD) for: ${description}`;const gddResult = await AIEngine.callPM(pmHistory, gddPrompt);if (!gddResult?.text) throw new Error("PM failed to generate GDD");const gddText = gddResult.text;5 unmodified linespmHistory.push({ role: 'user', parts: [{ text: gddPrompt }] });pmHistory.push({ role: 'model', parts: [{ text: gddText }] });StateManager.setStatus(projectId, "Project Manager: Planning Tasks...");const taskPrompt = "Based on the GDD, generate the first technical milestone.\nOutput format:\nTASK_NAME: <Name>\nWORKER_PROMPT: <Specific, isolated instructions for the worker>";const taskResult = await AIEngine.callPM(pmHistory, taskPrompt);if (!taskResult?.text) throw new Error("PM failed to generate Task");const taskText = taskResult.text;5 unmodified linesconst initialWorkerInstruction = extractWorkerPrompt(taskText) || `Initialize structure for: ${description}`;const initialWorkerPrompt = `CONTEXT: New Project. \nINSTRUCTION: ${initialWorkerInstruction}`;StateManager.setStatus(projectId, "Worker: Initializing...");let workerTextAccumulated = "";1 unmodified line[],initialWorkerPrompt,(thought) => {StateManager.setStatus(projectId, "Worker: Thinking...");StateManager.appendSnapshotOnly(projectId, thought);},(chunk) => {StateManager.setStatus(projectId, "Worker: Coding...");workerTextAccumulated += chunk;StateManager.appendStream(projectId, chunk);34 unmodified lines// 1. Clear previous ghost textStateManager.clearSnapshot(projectId);StateManager.setStatus(projectId, "Worker: Starting...");let responseText = ""; // The actual codelet thoughtText = ""; // The reasoning (optional to save, we generally discard)// 2. Call Workerawait AIEngine.callWorkerStream(project.workerHistory,fullInput,(thought) => {thoughtText += thought;StateManager.setStatus(projectId, "Worker: Thinking...");StateManager.appendSnapshotOnly(projectId, thought);},(chunk) => {responseText += chunk;StateManager.setStatus(projectId, "Worker: Coding...");StateManager.appendStream(projectId, chunk);});// 3. Interceptorsconst routeTask = extractRouteToPM(responseText);const pmQuestion = extractPMQuestion(responseText);if (routeTask) {console.log(`[${projectId}] Routing task to PM...`);StateManager.clearSnapshot(projectId);StateManager.setStatus(projectId, "Project Manager: Reviewing...");const pmPrompt = `[ROUTED TASK]: ${routeTask}\nWrite the backend/logic. Then use WORKER_PROMPT: <task> to delegate.`;3 unmodified linesproject.pmHistory,pmPrompt,(thought) => {StateManager.setStatus(projectId, "Project Manager: Thinking...");StateManager.appendSnapshotOnly(projectId, thought);},(chunk) => {StateManager.setStatus(projectId, "Project Manager: Planning...");pmResponseText += chunk;StateManager.appendSnapshotOnly(projectId, chunk);}7 unmodified linesconst nextInstruction = extractWorkerPrompt(pmResponseText);if (nextInstruction) {StateManager.clearSnapshot(projectId);StateManager.setStatus(projectId, "Worker: Applying Changes...");let subResponse = "";await AIEngine.callWorkerStream(project.workerHistory,`[PM DELEGATION]: ${nextInstruction}`,(thought) => {StateManager.setStatus(projectId, "Worker: Thinking...");StateManager.appendSnapshotOnly(projectId, thought);},(chunk) => {StateManager.setStatus(projectId, "Worker: Coding...");subResponse += chunk;StateManager.appendStream(projectId, chunk);4 unmodified lines} else if (pmQuestion) {console.log(`[${projectId}] Worker consulting PM...`);StateManager.clearSnapshot(projectId);StateManager.setStatus(projectId, "Project Manager: Consulting...");let pmResponseText = "";await AIEngine.callPMStream(project.pmHistory,pmQuestion,(thought) => {StateManager.setStatus(projectId, "Project Manager: Thinking...");StateManager.appendSnapshotOnly(projectId, thought);},(chunk) => {StateManager.setStatus(projectId, "Project Manager: Advising...");pmResponseText += chunk;StateManager.appendSnapshotOnly(projectId, chunk);}5 unmodified linesawait StateManager.addHistory(projectId, 'pm', 'model', pmResponseText);StateManager.clearSnapshot(projectId);StateManager.setStatus(projectId, "Worker: Implementing Answer...");let subResponse = "";await AIEngine.callWorkerStream(project.workerHistory,`[PM ANSWER]: ${pmResponseText}`,(thought) => {StateManager.setStatus(projectId, "Worker: Thinking...");StateManager.appendSnapshotOnly(projectId, thought);},(chunk) => {StateManager.setStatus(projectId, "Worker: Coding...");subResponse += chunk;StateManager.appendStream(projectId, chunk);4 unmodified linesStateManager.setStatus(projectId, "Finalizing...");// 4. PERSISTENCE (CRITICAL: Wait for this before IDLE)await StateManager.addHistory(projectId, 'worker', 'user', fullInput);// Save the FINAL accumulated text (responseText), not a stream fragmentawait StateManager.addHistory(projectId, 'worker', 'model', responseText);await processAndQueueResponse(projectId, responseText, userId);// 5. FINISHawait StateManager.updateProject(projectId, { status: "idle" });if (diamondUsage > 0) await deductUserCredits(userId, diamondUsage, 'diamond');166 unmodified linesconst overrideMsg = `[SYSTEM OVERRIDE]: ${instruction}`;let overrideText = "";AIEngine.callWorkerStream(project.workerHistory,overrideMsg,(thought) => {StateManager.setStatus(projectId, "Worker: Thinking...");StateManager.appendSnapshotOnly(projectId, thought);},(chunk) => {StateManager.setStatus(projectId, "Worker: Coding...");overrideText += chunk;StateManager.appendStream(projectId, chunk);20 unmodified lines2122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686978 unmodified lines14814915015115215315415517 unmodified lines1731741751761771781791801811821831841851865 unmodified lines1921931941951961971981992002012022032042055 unmodified lines2112122132142152162172181 unmodified line22022122222322422522622722822923023134 unmodified lines2662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063 unmodified lines3103113123133143153163173183193203213227 unmodified lines3303313323333343353363373383393403413423433443453463473483493504 unmodified lines3553563573583593603613623633643653663673683693703713723733743753765 unmodified lines3823833843853863873883893903913923933943953963973983994004014024 unmodified lines407408409410411412413414415416417418419166 unmodified lines58658758858959059159259359459559659759859960060160260320 unmodified linesconst MIN_BASIC_REQUIRED = 50;const MIN_DIAMOND_REQUIRED = 50;// --- STATUS PHASES ---const WORKER_PHASES = ["Worker: Analyzing Request...","Worker: Reading Context...","Worker: Checking Hierarchy...","Worker: Planning Logic...","Worker: Preparing Environment...","Worker: Thinking..." // Settles here];const PM_PHASES = ["Manager: Reviewing Request...","Manager: Analyzing Project Structure...","Manager: Consulting Guidelines...","Manager: Formulating Strategy...","Manager: Delegating Tasks...","Manager: Thinking..." // Settles here];// --- HELPERS ---// Starts cycling status messages in the background. Returns a stop() function.function startStatusLoop(projectId, type = 'worker') {const phases = type === 'pm' ? PM_PHASES : WORKER_PHASES;let index = 0;// Set initial status immediatelyStateManager.setStatus(projectId, phases[0]);const interval = setInterval(() => {index++;if (index < phases.length) {StateManager.setStatus(projectId, phases[index]);} else {// Stop incrementing, but keep the interval running (or clear it)// We just let it sit on the last messageclearInterval(interval);}}, 1500); // Change status every 1.5 secondsreturn () => clearInterval(interval);}async function checkMinimumCredits(userId, type = 'basic') {if (!supabase) return;78 unmodified linesreturn out;}// --- CORE BACKGROUND LOGIC ---async function runBackgroundInitialization(projectId, userId, description) {if (StateManager.isLocked(projectId)) {console.log(`[Init Guard] Project ${projectId} is already initializing. Skipping.`);17 unmodified linesconst pmHistory = [];// Start PM Status Looplet stopStatus = startStatusLoop(projectId, 'pm');const gddPrompt = `Create a comprehensive Game Design Document (GDD) for: ${description}`;const gddResult = await AIEngine.callPM(pmHistory, gddPrompt);stopStatus(); // Stop loop when doneif (!gddResult?.text) throw new Error("PM failed to generate GDD");const gddText = gddResult.text;5 unmodified linespmHistory.push({ role: 'user', parts: [{ text: gddPrompt }] });pmHistory.push({ role: 'model', parts: [{ text: gddText }] });// Start PM Status Loop again for next taskstopStatus = startStatusLoop(projectId, 'pm');const taskPrompt = "Based on the GDD, generate the first technical milestone.\nOutput format:\nTASK_NAME: <Name>\nWORKER_PROMPT: <Specific, isolated instructions for the worker>";const taskResult = await AIEngine.callPM(pmHistory, taskPrompt);stopStatus();if (!taskResult?.text) throw new Error("PM failed to generate Task");const taskText = taskResult.text;5 unmodified linesconst initialWorkerInstruction = extractWorkerPrompt(taskText) || `Initialize structure for: ${description}`;const initialWorkerPrompt = `CONTEXT: New Project. \nINSTRUCTION: ${initialWorkerInstruction}`;// Start Worker LoopstopStatus = startStatusLoop(projectId, 'worker');let workerTextAccumulated = "";1 unmodified line[],initialWorkerPrompt,(thought) => {stopStatus(); // Stop fake loop, switch to real thoughtStateManager.setStatus(projectId, "Worker: Thinking...");StateManager.appendSnapshotOnly(projectId, thought);},(chunk) => {stopStatus(); // Stop fake loopStateManager.setStatus(projectId, "Worker: Coding...");workerTextAccumulated += chunk;StateManager.appendStream(projectId, chunk);34 unmodified lines// 1. Clear previous ghost textStateManager.clearSnapshot(projectId);// 2. Start Status Loop (Worker)let stopStatus = startStatusLoop(projectId, 'worker');let responseText = "";let thoughtText = "";// 3. Call Workerawait AIEngine.callWorkerStream(project.workerHistory,fullInput,(thought) => {stopStatus(); // Stop cyclingthoughtText += thought;StateManager.setStatus(projectId, "Worker: Thinking...");StateManager.appendSnapshotOnly(projectId, thought);},(chunk) => {stopStatus(); // Stop cyclingresponseText += chunk;StateManager.setStatus(projectId, "Worker: Coding...");StateManager.appendStream(projectId, chunk);});// 4. Interceptorsconst routeTask = extractRouteToPM(responseText);const pmQuestion = extractPMQuestion(responseText);if (routeTask) {console.log(`[${projectId}] Routing task to PM...`);StateManager.clearSnapshot(projectId);// Start PM LoopstopStatus = startStatusLoop(projectId, 'pm');const pmPrompt = `[ROUTED TASK]: ${routeTask}\nWrite the backend/logic. Then use WORKER_PROMPT: <task> to delegate.`;3 unmodified linesproject.pmHistory,pmPrompt,(thought) => {stopStatus();StateManager.setStatus(projectId, "Manager: Thinking...");StateManager.appendSnapshotOnly(projectId, thought);},(chunk) => {stopStatus();StateManager.setStatus(projectId, "Manager: Planning...");pmResponseText += chunk;StateManager.appendSnapshotOnly(projectId, chunk);}7 unmodified linesconst nextInstruction = extractWorkerPrompt(pmResponseText);if (nextInstruction) {StateManager.clearSnapshot(projectId);// Back to Worker LoopstopStatus = startStatusLoop(projectId, 'worker');let subResponse = "";await AIEngine.callWorkerStream(project.workerHistory,`[PM DELEGATION]: ${nextInstruction}`,(thought) => {stopStatus();StateManager.setStatus(projectId, "Worker: Thinking...");StateManager.appendSnapshotOnly(projectId, thought);},(chunk) => {stopStatus();StateManager.setStatus(projectId, "Worker: Coding...");subResponse += chunk;StateManager.appendStream(projectId, chunk);4 unmodified lines} else if (pmQuestion) {console.log(`[${projectId}] Worker consulting PM...`);StateManager.clearSnapshot(projectId);// Start PM LoopstopStatus = startStatusLoop(projectId, 'pm');let pmResponseText = "";await AIEngine.callPMStream(project.pmHistory,pmQuestion,(thought) => {stopStatus();StateManager.setStatus(projectId, "Manager: Thinking...");StateManager.appendSnapshotOnly(projectId, thought);},(chunk) => {stopStatus();StateManager.setStatus(projectId, "Manager: Advising...");pmResponseText += chunk;StateManager.appendSnapshotOnly(projectId, chunk);}5 unmodified linesawait StateManager.addHistory(projectId, 'pm', 'model', pmResponseText);StateManager.clearSnapshot(projectId);// Back to Worker LoopstopStatus = startStatusLoop(projectId, 'worker');let subResponse = "";await AIEngine.callWorkerStream(project.workerHistory,`[PM ANSWER]: ${pmResponseText}`,(thought) => {stopStatus();StateManager.setStatus(projectId, "Worker: Thinking...");StateManager.appendSnapshotOnly(projectId, thought);},(chunk) => {stopStatus();StateManager.setStatus(projectId, "Worker: Coding...");subResponse += chunk;StateManager.appendStream(projectId, chunk);4 unmodified linesStateManager.setStatus(projectId, "Finalizing...");// 5. PERSISTENCE (Wait for DB)await StateManager.addHistory(projectId, 'worker', 'user', fullInput);await StateManager.addHistory(projectId, 'worker', 'model', responseText);await processAndQueueResponse(projectId, responseText, userId);// 6. FINISHawait StateManager.updateProject(projectId, { status: "idle" });if (diamondUsage > 0) await deductUserCredits(userId, diamondUsage, 'diamond');166 unmodified linesconst overrideMsg = `[SYSTEM OVERRIDE]: ${instruction}`;let overrideText = "";let stopStatus = startStatusLoop(projectId, 'worker');AIEngine.callWorkerStream(project.workerHistory,overrideMsg,(thought) => {stopStatus();StateManager.setStatus(projectId, "Worker: Thinking...");StateManager.appendSnapshotOnly(projectId, thought);},(chunk) => {stopStatus();StateManager.setStatus(projectId, "Worker: Coding...");overrideText += chunk;StateManager.appendStream(projectId, chunk);
app.js+96-20