All files / src/hooks useAgentChat.js

46.13% Statements 161/349
26.89% Branches 64/238
40.9% Functions 18/44
51.5% Lines 154/299

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525          2x                                                       25x   25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x   25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x   25x 2x 2x 2x 2x 2x 2x 2x                     25x                   25x   25x                       25x       25x 11x         25x                                               25x 1x 2x 1x 1x 1x 1x 1x     1x   1x 1x   1x 1x             1x 1x                                       25x 1x 1x 1x 1x   1x 1x   1x 1x 1x 1x 1x 1x   1x 1x                   1x 1x 1x             1x 1x 1x 1x 1x 1x 1x     1x 1x                                           25x                                       25x 11x 10x 10x   10x   1x 1x                   6x 6x 6x 6x 3x 3x     6x 6x 6x         6x         6x 6x 6x     1x 1x 1x 1x 1x 1x                                                   1x 1x 1x 1x 1x 1x       1x 1x     11x 11x         25x 11x 10x 10x 10x 10x                     10x                                     10x             10x     10x     10x       11x 11x         25x 17x         25x 11x                                                                                           11x 11x         25x 11x 8x       25x                                                        
import { useState, useRef, useEffect } from 'react';
import { api } from '../api';
import { MSG_TYPES } from '../constants';
import { vscodeNative } from '../vscodeNative';
 
const PARAM_SHIM = `<script>
window.simParams={};
window._paramSetters={};
window.registerParam=function(name,setter){window._paramSetters[name]=setter;if(name in window.simParams)setter(window.simParams[name]);};
window.addEventListener('message',function(e){
  if(e.data&&e.data.type==='PARAM_UPDATE'){
    var p=e.data.params;
    Object.assign(window.simParams,p);
    for(var k in p){window[k]=p[k];if(window._paramSetters[k])window._paramSetters[k](p[k]);}
    window.dispatchEvent(new CustomEvent('paramupdate',{detail:p}));
  }
});
</script>`;
 
export function useAgentChat(deps) {
  const {
    knowledge, setKnowledge,
    workspaceFiles, workspaceCache, getWorkspaceFileContext,
    researchMission, setResearchMission,
    researchRoadmap, setResearchRoadmap,
    models, selectedModelId, selectedModelObj,
    selectableModels, deepResearchModels,
    getProvider, getModelId,
    speakText,
    notify, logAgentAction,
    setAgentLog,
    journalEntries, setJournalEntries,
    backgroundTasks, setBackgroundTasks,
  } = deps;
 
  const [input, setInput] = useState('');
  const [messages, setMessages] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedArtifact, setSelectedArtifact] = useState(null);
  const [isAutoLoopEnabled, setIsAutoLoopEnabled] = useState(false);
  const [isAutoRunning, setIsAutoRunning] = useState(false);
  const [isWaitingForTelemetry, setIsWaitingForTelemetry] = useState(false);
  const [currentObjective, setCurrentObjective] = useState({ task: '', wait: 0 });
  const [telemetryLog, setTelemetryLog] = useState([]);
  const [cycleCount, setCycleCount] = useState(0);
  const [timeLeft, setTimeLeft] = useState(0);
  const [imageContext, setImageContext] = useState(null);
  const [runtimeParams, setRuntimeParams] = useState({});
  const [paramValues, setRuntimeParamValues] = useState({});
  const [webGroundingEnabled, setWebGroundingEnabled] = useState(false);
 
  const messagesRef = useRef(messages);
  messagesRef.current = messages;
  const scrollRef = useRef(null);
  const debugTimeoutRef = useRef(null);
  const autonomyTimeoutRef = useRef(null);
  const timerIntervalRef = useRef(null);
  const lastTelemetryTimeRef = useRef(0);
  const iframeRef = useRef(null);
  const lastFinalCodeRef = useRef('');
  const autoFixedArtifacts = useRef(new Set());
  const observerInputRef = useRef(null);
  const isLoadingRef = useRef(isLoading);
  isLoadingRef.current = isLoading;
  const loadingTimeoutRef = useRef(null);
  const selectedArtifactRef = useRef(selectedArtifact);
  selectedArtifactRef.current = selectedArtifact;
  const isAutoRunningRef = useRef(isAutoRunning);
  isAutoRunningRef.current = isAutoRunning;
  const cycleCountRef = useRef(cycleCount);
  cycleCountRef.current = cycleCount;
 
  const injectParamShim = (html) => {
    Iif (!html) return html;
    try {
      const doc = new DOMParser().parseFromString(html, 'text/html');
      const script = doc.createElement('script');
      script.textContent = PARAM_SHIM.replace(/<\/?script[^>]*>/gi, '');
      (doc.head || doc.documentElement).appendChild(script);
      return '<!DOCTYPE html>' + doc.documentElement.outerHTML;
    } catch {
      const lower = html.toLowerCase();
      const headClose = lower.indexOf('</head>');
      if (headClose !== -1) return html.slice(0, headClose) + PARAM_SHIM + html.slice(headClose);
      const bodyOpen = lower.indexOf('<body');
      if (bodyOpen !== -1) return html.slice(0, bodyOpen) + PARAM_SHIM + html.slice(bodyOpen);
      return PARAM_SHIM + html;
    }
  };
 
  const loadImageFile = (file) => {
    if (!file || !file.type.startsWith('image/')) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      setImageContext(ev.target.result);
      logAgentAction("Observer", "Visual context loaded.");
    };
    reader.readAsDataURL(file);
  };
 
  const handleImageUpload = (e) => { loadImageFile(e.target.files[0]); };
 
  const handlePaste = (e) => {
    const items = e.clipboardData?.items;
    if (!items) return;
    for (const item of items) {
      if (item.type.startsWith('image/')) {
        e.preventDefault();
        loadImageFile(item.getAsFile());
        return;
      }
    }
  };
 
  const handleParamChange = (key, value) => {
    setRuntimeParamValues(prev => ({ ...prev, [key]: value }));
  };
 
  useEffect(() => {
    Iif (iframeRef.current && Object.keys(paramValues).length > 0) {
      iframeRef.current.contentWindow.postMessage({ type: 'PARAM_UPDATE', params: paramValues }, '*');
    }
  }, [paramValues]);
 
  const captureSimScreenshot = async () => {
    const iframe = iframeRef.current;
    if (!iframe) return null;
    try {
      const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
      if (!iframe.contentWindow.html2canvas) {
        const script = iframeDoc.createElement('script');
        script.src = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js';
        await new Promise((resolve, reject) => {
          script.onload = resolve;
          script.onerror = reject;
          iframeDoc.head.appendChild(script);
        });
      }
      const canvas = await iframe.contentWindow.html2canvas(iframeDoc.body, { backgroundColor: '#000', scale: 2 });
      return canvas.toDataURL('image/png');
    } catch (err) {
      console.warn('Screenshot capture failed:', err.message);
      return null;
    }
  };
 
  // --- Send user message to extension host agent ---
 
  const handleRerun = (assistantMsg) => {
    Iif (isLoadingRef.current) return;
    const idx = messagesRef.current.findIndex(m => m.id === assistantMsg.id);
    let prompt = '';
    for (let i = idx - 1; i >= 0; i--) {
      Eif (messagesRef.current[i].role === 'user') {
        prompt = messagesRef.current[i].content;
        break;
      }
    }
    Iif (!prompt) return;
 
    setIsLoading(true);
    setAgentLog([]);
 
    Iif (loadingTimeoutRef.current) clearTimeout(loadingTimeoutRef.current);
    loadingTimeoutRef.current = setTimeout(() => {
      if (isLoadingRef.current) {
        setIsLoading(false);
        notify('Agent request timed out. Try again.');
      }
    }, 120000);
 
    Eif (vscodeNative.isVscode) {
      window.vscode.postMessage({
        type: 'agentTask',
        prompt,
        modelId: selectedModelId,
        options: {
          mode: selectedArtifactRef.current ? 'ENHANCE' : 'CREATE',
          existingCode: selectedArtifactRef.current?.content || '',
          cycleCount: cycleCountRef.current,
          autoLoop: isAutoLoopEnabled,
        },
        knowledge,
        messages: messagesRef.current.slice(-10),
        roadmap: researchRoadmap,
        mission: researchMission,
        workspaceFiles,
        telemetryLog,
      });
    }
  };
 
  const handleSend = async () => {
    const hasActiveBG = backgroundTasks.some(t => t.status === 'running');
    Iif (!input.trim() || isLoadingRef.current || hasActiveBG) return;
    Iif (autonomyTimeoutRef.current) clearTimeout(autonomyTimeoutRef.current);
    Iif (timerIntervalRef.current) clearInterval(timerIntervalRef.current);
 
    const activeMessages = messages.filter(m => !m.archived);
    const hasExistingWork = selectedArtifact && activeMessages.some(m => m.role === 'assistant' && !m.archived);
 
    const prompt = input;
    setInput('');
    setIsAutoRunning(false);
    setIsWaitingForTelemetry(false);
    setIsLoading(true);
    setAgentLog([]);
 
    Iif (loadingTimeoutRef.current) clearTimeout(loadingTimeoutRef.current);
    loadingTimeoutRef.current = setTimeout(() => {
      if (isLoadingRef.current) {
        console.warn('Agent loading timeout — resetting');
        setIsLoading(false);
        setIsAutoRunning(false);
        notify('Agent request timed out. Try again.');
        logAgentAction("Timeout", "No response received — input re-enabled");
      }
    }, 120000);
 
    try {
      const savedMsg = await api.addMessage({ role: 'user', content: prompt, timestamp: Date.now() });
      setMessages(prev => [...prev, savedMsg]);
    } catch (err) {
      console.error('Failed to save message:', err);
      const localMsg = { id: 'local-' + Date.now(), role: 'user', content: prompt, timestamp: Date.now() };
      setMessages(prev => [...prev, localMsg]);
    }
 
    Eif (!hasExistingWork) {
      setResearchRoadmap([]);
      setResearchMission('');
      setCycleCount(0);
      setCurrentObjective({ task: '', wait: 0 });
      lastFinalCodeRef.current = '';
      api.updateWorkspace({ researchMission: '', researchRoadmap: [], cycleCount: 0 }).catch(() => {});
    }
 
    if (vscodeNative.isVscode) {
      window.vscode.postMessage({
        type: 'agentTask',
        prompt,
        modelId: selectedModelId,
        options: {
          mode: hasExistingWork ? 'ENHANCE' : 'CREATE',
          existingCode: hasExistingWork ? selectedArtifact.content : '',
          cycleCount: cycleCountRef.current,
          autoLoop: isAutoLoopEnabled,
        },
        knowledge,
        messages: messagesRef.current.slice(-10),
        roadmap: researchRoadmap,
        mission: researchMission,
        workspaceFiles,
        telemetryLog,
      });
    } else E{
      setIsLoading(false);
    }
  };
 
  const forceNextStep = () => {
    if (autonomyTimeoutRef.current) {
      clearTimeout(autonomyTimeoutRef.current);
      if (timerIntervalRef.current) clearInterval(timerIntervalRef.current);
      autonomyTimeoutRef.current = null;
      setIsWaitingForTelemetry(false);
    }
    logAgentAction("Manual Snap", "Skipping observation — asking now.");
    if (vscodeNative.isVscode) {
      window.vscode.postMessage({
        type: 'agentAutoLoop',
        existingCode: lastFinalCodeRef.current,
        cycleCount: cycleCountRef.current,
        telemetryLog,
      });
    }
  };
 
  // --- Listen for agent events from extension host ---
 
  useEffect(() => {
    const handleAgentEvent = (event) => {
      const msg = event.data;
      Iif (!msg || !msg.type) return;
 
      switch (msg.type) {
        case 'agent:thinking':
          logAgentAction("Thinking", msg.data?.prompt?.substring(0, 80) || "Processing...");
          break;
 
        case 'agent:streaming':
          if (msg.data?.token) {
            const preview = msg.data.token.length > 120 ? '...' + msg.data.token.slice(-120) : msg.data.token;
            logAgentAction("Streaming", preview.replace(/\n/g, ' '));
          }
          break;
 
        case 'agent:complete':
          Iif (loadingTimeoutRef.current) clearTimeout(loadingTimeoutRef.current);
          Eif (msg.data?.message) {
            setMessages(prev => [...prev, msg.data.message]);
            if (msg.data.message.content && /<html/i.test(msg.data.message.content)) {
              setSelectedArtifact(msg.data.message);
              lastFinalCodeRef.current = msg.data.message.content;
            }
          }
          Iif (msg.data?.mission) setResearchMission(msg.data.mission);
          Iif (msg.data?.roadmap) setResearchRoadmap(msg.data.roadmap);
          Iif (msg.data?.knowledge) {
            for (const k of msg.data.knowledge) {
              setKnowledge(prev => [...prev, k]);
            }
          }
          Iif (msg.data?.journal) {
            for (const j of msg.data.journal) {
              setJournalEntries(prev => [...prev, j]);
            }
          }
          setIsLoading(false);
          logAgentAction("Complete", "Agent turn finished");
          break;
 
        case 'agent:error':
          Iif (loadingTimeoutRef.current) clearTimeout(loadingTimeoutRef.current);
          setIsLoading(false);
          setIsAutoRunning(false);
          notify(msg.data?.error || 'Agent error');
          logAgentAction("Error", msg.data?.error || 'Unknown error');
          break;
 
        case 'tool:start':
          logAgentAction(`Tool: ${msg.data?.tool || 'unknown'}`, "Executing...");
          break;
 
        case 'tool:complete':
          logAgentAction(`Tool: ${msg.data?.tool || 'unknown'}`, msg.data?.result?.substring(0, 100) || "Done");
          break;
 
        case 'tool:error':
          logAgentAction(`Tool Error`, msg.data?.error || 'Unknown');
          break;
 
        case 'cycle:start':
          setIsAutoRunning(true);
          setCycleCount(msg.data?.cycleCount || 0);
          logAgentAction("Autonomous Cycle", `Starting cycle ${msg.data?.cycleCount || 0}`);
          break;
 
        case 'cycle:complete':
          setIsAutoRunning(false);
          logAgentAction("Cycle Complete", msg.data?.reason || 'Done');
          break;
 
        case 'cycle:autonomous_tick':
          setIsWaitingForTelemetry(true);
          setIsAutoRunning(true);
          Eif (msg.data?.waitTime) {
            setTimeLeft(Math.ceil(msg.data.waitTime / 1000));
            Iif (timerIntervalRef.current) clearInterval(timerIntervalRef.current);
            timerIntervalRef.current = setInterval(() => {
              setTimeLeft(prev => Math.max(0, prev - 1));
            }, 1000);
          }
          logAgentAction("Observing", `Gathering telemetry for ${msg.data?.waitTime || 8000}ms...`);
          break;
      }
    };
    window.addEventListener('message', handleAgentEvent);
    return () => window.removeEventListener('message', handleAgentEvent);
  }, []);
 
  // --- Iframe message handler (simulation events) ---
 
  useEffect(() => {
    const handleMessage = (event) => {
      Iif (iframeRef.current && event.source !== iframeRef.current.contentWindow) return;
      const { type } = event.data || {};
      Iif (type === MSG_TYPES.NARRATE) speakText(event.data.text);
      Iif (type === MSG_TYPES.TELEMETRY) {
        const now = Date.now();
        if (now - lastTelemetryTimeRef.current < 400) return;
        lastTelemetryTimeRef.current = now;
        const data = typeof event.data.data === 'object' ? JSON.stringify(event.data.data) : String(event.data.data);
        setTelemetryLog(prev => [...prev, data].slice(-20));
        logAgentAction("Telemetry Rx", data);
        if (vscodeNative.isVscode) {
          window.vscode.postMessage({ type: 'telemetryUpdate', data });
        }
      }
      Iif (type === MSG_TYPES.ARTIFACT_ERROR) {
        if (isLoadingRef.current || !selectedArtifactRef.current) return;
        if (autoFixedArtifacts.current.has(selectedArtifactRef.current.id)) return;
        if (debugTimeoutRef.current) clearTimeout(debugTimeoutRef.current);
        debugTimeoutRef.current = setTimeout(() => {
          const artifact = selectedArtifactRef.current;
          if (!artifact) return;
          autoFixedArtifacts.current.add(artifact.id);
          logAgentAction("Self-Repair", "Stabilizing state...");
          if (vscodeNative.isVscode) {
            window.vscode.postMessage({
              type: 'agentFixError',
              error: event.data.error,
              code: artifact.content,
            });
          }
          debugTimeoutRef.current = null;
        }, 3000);
      }
      Iif (type === MSG_TYPES.PARAMS_REGISTER) {
        setRuntimeParams(event.data.params || {});
        const defaults = {};
        Object.entries(event.data.params || {}).forEach(([k, v]) => { defaults[k] = v.default ?? v.min ?? 0; });
        setRuntimeParamValues(prev => ({ ...defaults, ...prev }));
        logAgentAction("Params Registered", `${Object.keys(event.data.params || {}).length} variables`);
      }
      Iif (type === MSG_TYPES.SIMULATION_READY) {
        logAgentAction("Sim Ready", event.data.info || "Simulation loaded");
      }
      Iif (type === MSG_TYPES.DATA_EXPORT) {
        logAgentAction("Data Export", event.data.payload?.name || "Export received");
      }
      Iif (type === MSG_TYPES.STATE_SNAPSHOT) {
        logAgentAction("State Snapshot", "Simulation state captured");
      }
    };
    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, []);
 
  // --- Auto-scroll ---
 
  useEffect(() => {
    Iif (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages.length]);
 
  // --- Keyboard shortcuts ---
 
  useEffect(() => {
    const handleKeyboard = (e) => {
      if (!(e.metaKey || e.ctrlKey)) return;
      const el = document.activeElement;
      const isInput = el && (el.tagName === 'TEXTAREA' || el.tagName === 'INPUT' || el.isContentEditable);
      if (e.key === 'a' && isInput) {
        e.preventDefault();
        el.select?.();
      } else if (e.key === 'c') {
        e.preventDefault();
        const text = window.getSelection()?.toString() || '';
        if (text) navigator.clipboard.writeText(text);
      } else if (e.key === 'x' && isInput) {
        e.preventDefault();
        const text = window.getSelection()?.toString() || '';
        if (text) {
          navigator.clipboard.writeText(text);
          if (el.tagName === 'TEXTAREA' || el.tagName === 'INPUT') {
            const start = el.selectionStart;
            const end = el.selectionEnd;
            const val = el.value;
            const proto = el.tagName === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype;
            const nativeSet = Object.getOwnPropertyDescriptor(proto, 'value')?.set;
            nativeSet?.call(el, val.substring(0, start) + val.substring(end));
            el.selectionStart = el.selectionEnd = start;
            el.dispatchEvent(new Event('input', { bubbles: true }));
          }
        }
      } else if (e.key === 'v' && isInput) {
        e.preventDefault();
        navigator.clipboard.readText().then(text => {
          if (!text) return;
          if (el.tagName === 'TEXTAREA' || el.tagName === 'INPUT') {
            const start = el.selectionStart;
            const end = el.selectionEnd;
            const val = el.value;
            const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value')?.set || Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;
            nativeInputValueSetter?.call(el, val.substring(0, start) + text + val.substring(end));
            el.selectionStart = el.selectionEnd = start + text.length;
            el.dispatchEvent(new Event('input', { bubbles: true }));
          }
        });
      } else if (e.key === 'z') {
        e.preventDefault();
        document.execCommand(e.shiftKey ? 'redo' : 'undo');
      }
    };
    document.addEventListener('keydown', handleKeyboard, true);
    return () => document.removeEventListener('keydown', handleKeyboard, true);
  }, []);
 
  // --- Notify extension host when auto-loop toggle changes ---
 
  useEffect(() => {
    if (vscodeNative.isVscode) {
      window.vscode.postMessage({ type: 'agentSetAutoLoop', enabled: isAutoLoopEnabled });
    }
  }, [isAutoLoopEnabled]);
 
  return {
    input, setInput,
    messages, setMessages,
    isLoading, setIsLoading,
    selectedArtifact, setSelectedArtifact,
    isAutoLoopEnabled, setIsAutoLoopEnabled,
    isAutoRunning, setIsAutoRunning,
    isWaitingForTelemetry, setIsWaitingForTelemetry,
    currentObjective, setCurrentObjective,
    telemetryLog, setTelemetryLog,
    cycleCount, setCycleCount,
    timeLeft, setTimeLeft,
    imageContext, setImageContext,
    runtimeParams, setRuntimeParams,
    paramValues, setRuntimeParamValues,
    webGroundingEnabled, setWebGroundingEnabled,
    messagesRef, scrollRef, debugTimeoutRef, autonomyTimeoutRef, timerIntervalRef,
    lastTelemetryTimeRef, iframeRef, lastFinalCodeRef, autoFixedArtifacts, observerInputRef,
    isLoadingRef, selectedArtifactRef, isAutoRunningRef, cycleCountRef,
    injectParamShim,
    loadImageFile, handleImageUpload, handlePaste,
    handleParamChange,
    forceNextStep,
    handleSend,
    handleRerun,
    captureSimScreenshot,
  };
}