All files / src/contexts LabStateContext.jsx

52.77% Statements 57/108
31.25% Branches 20/64
50% Functions 10/20
58.51% Lines 55/94

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                      1x     10x 10x 10x     10x 10x 10x   10x 10x 10x   10x                                   10x                   10x       10x       10x 3x     10x                                                     10x               10x   10x 7x 1x 1x 1x 1x           10x 3x 3x 3x 1x                                   1x 1x 1x   1x                                             3x           3x             3x 3x       10x 3x   3x 3x 3x 3x 3x 3x       3x 3x     3x     3x     10x                                 10x               10x 10x 10x    
import React, { createContext, useContext, useEffect, useState, useRef } from 'react';
import { useUI } from '../hooks/useUI';
import { useNotifications } from '../hooks/useNotifications';
import { useModels } from '../hooks/useModels';
import { useAudio } from '../hooks/useAudio';
import { useWorkspace } from '../hooks/useWorkspace';
import { useResearch } from '../hooks/useResearch';
import { useAgentChat } from '../hooks/useAgentChat';
import { api } from '../api';
import { vscodeNative } from '../vscodeNative';
 
const LabStateContext = createContext(null);
 
export function LabStateProvider({ children }) {
  const ui = useUI();
  const notifications = useNotifications();
  const models = useModels({ notify: notifications.notify });
 
  // Settings state (previously in useSettings, now backed by VS Code config/secrets)
  const [voiceEnabled, setVoiceEnabled] = useState(false);
  const voiceEnabledRef = useRef(voiceEnabled);
  voiceEnabledRef.current = voiceEnabled;
 
  const audio = useAudio({ voiceEnabledRef, logAgentAction: notifications.logAgentAction });
  const workspace = useWorkspace({ notify: notifications.notify, logAgentAction: notifications.logAgentAction });
  const research = useResearch({ notify: notifications.notify, logAgentAction: notifications.logAgentAction });
 
  const agentChat = useAgentChat({
    knowledge: research.knowledge, setKnowledge: research.setKnowledge,
    workspaceFiles: workspace.workspaceFiles, workspaceCache: workspace.workspaceCache,
    getWorkspaceFileContext: workspace.getWorkspaceFileContext,
    researchMission: research.researchMission, setResearchMission: research.setResearchMission,
    researchRoadmap: research.researchRoadmap, setResearchRoadmap: research.setResearchRoadmap,
    models: models.models, selectedModelId: models.selectedModelId, selectedModelObj: models.selectedModelObj,
    selectableModels: models.selectableModels, deepResearchModels: models.deepResearchModels,
    getProvider: models.getProvider, getModelId: models.getModelId,
    speakText: audio.speakText,
    notify: notifications.notify,
    logAgentAction: notifications.logAgentAction,
    setAgentLog: notifications.setAgentLog,
    journalEntries: research.journalEntries, setJournalEntries: research.setJournalEntries,
    backgroundTasks: research.backgroundTasks, setBackgroundTasks: research.setBackgroundTasks,
  });
 
  // Cross-hook workspace callbacks
  const workspaceCallbacks = {
    setMessages: agentChat.setMessages,
    setKnowledge: research.setKnowledge,
    setJournalEntries: research.setJournalEntries,
    setSelectedArtifact: agentChat.setSelectedArtifact,
    setResearchMission: research.setResearchMission,
    setResearchRoadmap: research.setResearchRoadmap,
    setCycleCount: agentChat.setCycleCount,
  };
 
  const handleOpenWorkspace = (folderPath, name) => {
    return workspace.handleOpenWorkspace(folderPath, name, workspaceCallbacks);
  };
 
  const loadWorkspaceData = (ws) => {
    return workspace.loadWorkspaceData(ws, workspaceCallbacks);
  };
 
  const showWorkspacePickerNative = () => {
    return workspace.showWorkspacePicker(workspaceCallbacks);
  };
 
  const startDeepResearch = (prompt) => {
    agentChat.setIsLoading(true);
    notifications.setAgentLog([]);
    return research.startDeepResearch(prompt, {
      models: models.models,
      selectedModelObj: models.selectedModelObj,
      selectedModelId: models.selectedModelId,
      runAgentTask: (taskDesc, mode, code, autoStep, cycle) => {
        agentChat.setIsLoading(false);
        if (window.vscode) {
          window.vscode.postMessage({
            type: 'agentTask',
            prompt: taskDesc,
            modelId: models.selectedModelId,
            options: { mode: mode || 'CREATE', existingCode: code || '', cycleCount: cycle || 0 },
            knowledge: research.knowledge,
            messages: agentChat.messages.slice(-10),
            roadmap: research.researchRoadmap,
            mission: research.researchMission,
          });
        }
      },
    }).then(() => {}).catch(() => {
      agentChat.setIsLoading(false);
    });
  };
 
  const generatePaper = () => {
    return research.generatePaper({
      messages: agentChat.messages,
      selectedArtifact: agentChat.selectedArtifact,
      captureSimScreenshot: agentChat.captureSimScreenshot,
    });
  };
 
  const [pendingSelectArtifact, setPendingSelectArtifact] = useState(null);
 
  useEffect(() => {
    if (pendingSelectArtifact && agentChat.messages.length > 0) {
      const found = agentChat.messages.find(m => m.id === pendingSelectArtifact);
      Eif (found) {
        agentChat.setSelectedArtifact(found);
        setPendingSelectArtifact(null);
      }
    }
  }, [pendingSelectArtifact, agentChat.messages]);
 
  // Listen for commands from extension host
  useEffect(() => {
    const handleExtensionMessage = async (event) => {
      const msg = event.data;
      if (msg.type === 'command') {
        switch (msg.command) {
          case 'newSession':
            agentChat.setSelectedArtifact(null);
            agentChat.setInput('');
            ui.setIsSidebarOpen(true);
            agentChat.setIsAutoRunning(false);
            research.setResearchRoadmap([]);
            research.setResearchMission('');
            agentChat.setCycleCount(0);
            api.updateWorkspace({ researchMission: '', researchRoadmap: [], cycleCount: 0 }).catch(() => {});
            break;
          case 'requestModelPick':
            models.selectModelViaPicker();
            break;
          case 'requestWorkspacePick':
            showWorkspacePickerNative();
            break;
          case 'selectArtifact': {
            const targetId = msg.args?.id;
            Eif (targetId) {
              setPendingSelectArtifact(targetId);
            }
            break;
          }
          case 'refreshData': {
            const ws = await api.getCurrentWorkspace().catch(() => ({ path: null }));
            if (ws.path) await loadWorkspaceData(ws);
            break;
          }
          case 'loadSimulation': {
            const { html, fileName } = msg.args || {};
            if (html) {
              const simMsg = {
                id: 'sim-' + Date.now(),
                role: 'assistant',
                prompt: `Simulation: ${fileName || 'untitled'}`,
                content: html,
                timestamp: Date.now(),
              };
              agentChat.setSelectedArtifact(simMsg);
            }
            break;
          }
        }
      }
      Iif (msg.type === 'debugCommand') {
        const iframe = agentChat.iframeRef?.current;
        if (iframe?.contentWindow) {
          iframe.contentWindow.postMessage({ type: msg.command, expression: msg.expression, id: msg.id }, '*');
        }
      }
      Iif (msg.type === 'configChanged' && msg.values) {
        if (msg.values.voiceEnabled !== undefined) setVoiceEnabled(msg.values.voiceEnabled);
        if (msg.values.webGrounding !== undefined) agentChat.setWebGroundingEnabled(msg.values.webGrounding);
        if (msg.values.autoLoop !== undefined) agentChat.setIsAutoLoopEnabled(msg.values.autoLoop);
        if (msg.values.hasGeminiKey !== undefined) research.setHasGeminiKey(msg.values.hasGeminiKey);
      }
    };
    window.addEventListener('message', handleExtensionMessage);
    return () => window.removeEventListener('message', handleExtensionMessage);
  }, []);
 
  // Boot sequence
  useEffect(() => {
    const boot = async () => {
      // Load VS Code config
      const config = await vscodeNative.getConfig();
      Eif (config) {
        Iif (config.voiceEnabled) setVoiceEnabled(config.voiceEnabled);
        Iif (config.webGrounding) agentChat.setWebGroundingEnabled(config.webGrounding);
        Iif (config.autoLoop) agentChat.setIsAutoLoopEnabled(config.autoLoop);
        Iif (config.defaultModel && !models.selectedModelId) models.setSelectedModelId(config.defaultModel);
      }
 
      // Load workspace
      const ws = await api.getCurrentWorkspace().catch(() => ({ path: null }));
      Iif (ws.path) {
        await loadWorkspaceData(ws);
      } else {
        showWorkspacePickerNative();
      }
    };
    boot();
  }, []);
 
  const value = {
    ...ui,
    ...notifications,
    ...models,
    ...audio,
    ...workspace,
    ...research,
    ...agentChat,
    voiceEnabled, setVoiceEnabled,
    handleOpenWorkspace,
    loadWorkspaceData,
    showWorkspacePickerNative,
    startDeepResearch,
    generatePaper,
    hasActiveBackgroundTasks: research.hasActiveBackgroundTasks,
  };
 
  return (
    <LabStateContext.Provider value={value}>
      {children}
    </LabStateContext.Provider>
  );
}
 
export function useLabContext() {
  const ctx = useContext(LabStateContext);
  Iif (!ctx) throw new Error('useLabContext must be used within LabStateProvider');
  return ctx;
}