File size: 13,463 Bytes
34450be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import re

with open("App.tsx", "r") as f:
    content = f.read()

# 1. Imports
imports_old = """import { TemplateFillerModal } from './components/TemplateFillerModal';
import { HFCueWizardModal } from './components/HFCueWizardModal';"""
imports_new = """import { TemplateFillerModal } from './components/TemplateFillerModal';
import { WorkflowPanel } from './components/WorkflowPanel';
import { Workflow } from './types';"""
content = content.replace(imports_old, imports_new)

# 2. Tabs
tab_old = "const [activeTab, setActiveTab] = useState<'chat' | 'merge' | 'import'>('chat');"
tab_new = "const [activeTab, setActiveTab] = useState<'chat' | 'merge' | 'import' | 'workflows'>('chat');"
content = content.replace(tab_old, tab_new)

# 3. Workflow State
state_old = "const [hfWizardOpen, setHfWizardOpen] = useState(false);"
state_new = """const [activeWorkflow, setActiveWorkflow] = useState<{ workflow: Workflow, stepIndex: number, sessionId: string | null } | null>(null);"""
content = content.replace(state_old, state_new)

# 4. Timer Logic
# Look for the timer interval we wrote earlier
timer_regex = re.compile(r"  // Timer interval to process HF Deployment Cues every 10 seconds.*?// --- Message Sending & Event Streaming ---", re.DOTALL)
new_timer = """  // Timer interval to process Workflow/HF Cues every 10 seconds
  useEffect(() => {
      const interval = setInterval(() => {
          const stored = localStorage.getItem('jules_hf_timer_queue');
          if (!stored) return;

          let currentQueue = JSON.parse(stored);
          const now = Date.now();
          let hasChanges = false;

          for (const sessionId of Object.keys(currentQueue)) {
              const queueData = currentQueue[sessionId];
              // Support both the old format {templates: string[]} and the new format {messages: QueuedMessage[]}
              // Let's assume we use the new format where each message has its own fireAt
              if (queueData.messages && queueData.messages.length > 0) {
                  const pending = [];
                  for (let i = 0; i < queueData.messages.length; i++) {
                      const msg = queueData.messages[i];
                      if (now >= msg.fireAt) {
                          console.log(`[TimerQueue] Firing queued message for session ${sessionId}`);
                          setTimeout(() => {
                              _sendText(sessionId, msg.text).catch(e => console.error("Timer send failed", e));
                          }, 0);
                          hasChanges = true;
                      } else {
                          pending.push(msg);
                      }
                  }

                  if (pending.length !== queueData.messages.length) {
                      if (pending.length > 0) {
                          currentQueue[sessionId].messages = pending;
                      } else {
                          delete currentQueue[sessionId];
                      }
                      hasChanges = true;
                  }
              }
          }

          if (hasChanges) {
              setHfTimerQueue(currentQueue);
              localStorage.setItem('jules_hf_timer_queue', JSON.stringify(currentQueue));
          }
      }, 10000);
      return () => clearInterval(interval);
  }, []);

  // --- Message Sending & Event Streaming ---"""
content = timer_regex.sub(new_timer, content)

# 5. handleStartWorkflow Logic
handler_old = """  const handleHuggingFaceCue = () => {
      setHfWizardOpen(true);
  };"""

handler_new = """  const handleHuggingFaceCue = () => {
      setActiveTab('workflows');
  };

  const handleStartWorkflow = (workflow: Workflow) => {
      setActiveWorkflow({ workflow, stepIndex: 0, sessionId: null });
      if (workflow.steps.length > 0) {
          const template = notes.find(n => n.id === workflow.steps[0].templateId);
          if (template) {
              handleUseTemplate(template);
          } else {
              alert(`Template ${workflow.steps[0].templateId} not found.`);
              setActiveWorkflow(null);
          }
      }
  };

  // Called when a template is submitted to chat
  const handleTemplateSubmitted = async (text: string, isNewSession: boolean, sessionIdOverride?: string) => {
      if (activeWorkflow) {
          const { workflow, stepIndex, sessionId } = activeWorkflow;
          const targetSessionId = sessionId || sessionIdOverride || currentSessionId;

          if (isNewSession && !targetSessionId) {
             // Let the session creation logic handle setting the sessionId and continuing the workflow!
             return;
          }

          if (!isNewSession && targetSessionId) {
              // Send the current step text to chat
              await _sendText(targetSessionId, text);
          }

          // Proceed to next step
          const nextIndex = stepIndex + 1;
          if (nextIndex < workflow.steps.length) {
              setActiveWorkflow({ workflow, stepIndex: nextIndex, sessionId: targetSessionId });
              const nextTemplate = notes.find(n => n.id === workflow.steps[nextIndex].templateId);
              if (nextTemplate) {
                  handleUseTemplate(nextTemplate);
              }
          } else {
              setActiveWorkflow(null);
          }
      } else {
          // Standard template use
          if (!isNewSession && currentSessionId) {
              await _sendText(currentSessionId, text);
          }
      }
  };

  const queueWorkflowStep = (text: string, targetSessionId: string, delayMinutes: number) => {
      const fireAt = Date.now() + (delayMinutes * 60 * 1000);
      setHfTimerQueue(prev => {
          const newQueue = { ...prev };
          if (!newQueue[targetSessionId]) {
              newQueue[targetSessionId] = { messages: [] };
          } else if (!newQueue[targetSessionId].messages) {
              // Migration from old array
              newQueue[targetSessionId].messages = [];
          }

          newQueue[targetSessionId].messages.push({
              id: `queue-${Date.now()}`,
              text,
              fireAt,
              sessionId: targetSessionId
          });

          return newQueue;
      });
  };
"""
content = content.replace(handler_old, handler_new)

# Update the HFCue handler
hf_old = """  const handleStartHfTimer = async (config: any) => {"""
content = content.replace(hf_old, "  // Obsolete HF Wizard removed\n  /*")
hf_end = """              }
          }
      }
  };"""
content = content.replace(hf_end, "  */\n")


# 6. Session Creation handling of Workflow
session_old = """        setCurrentSessionId(newSession.id);

        // Queue HF Deployment Cue if checked
        if (config.runHfDeploymentCue) {
            const templates = [
                "Based on the investigation, create a detailed project vision and implementation plan. Outline the necessary changes and new components. READY",
                "Implement the changes according to the plan and prepare for deployment. Ensure all tests pass and documentation is updated. READY"
            ];

            // The first template is config.prompt which is already sent
            setHfTimerQueue(prev => ({
                ...prev,
                [newSession.id]: {
                    templates: templates,
                    nextExecutionTime: Date.now() + 30 * 60 * 1000
                }
            }));
        }

        setNewSessionModalOpen(false);"""

session_new = """        setCurrentSessionId(newSession.id);

        if (activeWorkflow && activeWorkflow.stepIndex === 0) {
            // First step created the session. Move to next step!
            const nextIndex = 1;
            if (nextIndex < activeWorkflow.workflow.steps.length) {
                setActiveWorkflow({ ...activeWorkflow, stepIndex: nextIndex, sessionId: newSession.id });
                const nextTemplate = notes.find(n => n.id === activeWorkflow.workflow.steps[nextIndex].templateId);
                if (nextTemplate) {
                    setTimeout(() => handleUseTemplate(nextTemplate), 500); // Small delay to let modal close
                }
            } else {
                setActiveWorkflow(null);
            }
        }

        setNewSessionModalOpen(false);"""
content = content.replace(session_old, session_new)


# 7. Update TemplateFillerModal integration
modal_old = """      <TemplateFillerModal
        note={selectedNoteForTemplate}
        isOpen={templateModalOpen}
        onClose={() => setTemplateModalOpen(false)}
        onSubmit={async (text) => {
            if (!currentSessionId) return;
            await _sendText(currentSessionId, text);
        }}
        onStartNewChat={handleStartNewChatFromTemplate}
        hfProfileData={hfProfiles[currentAgent.id]}
      />"""

modal_new = """      <TemplateFillerModal
        note={selectedNoteForTemplate}
        isOpen={templateModalOpen}
        onClose={() => {
            setTemplateModalOpen(false);
            if (activeWorkflow && activeWorkflow.stepIndex > 0) {
                // If they close during a workflow, cancel the rest
                if (confirm('Cancel the rest of the workflow?')) {
                    setActiveWorkflow(null);
                }
            }
        }}
        onSubmit={async (text) => {
            if (activeWorkflow && activeWorkflow.stepIndex > 0 && activeWorkflow.sessionId) {
                const delay = activeWorkflow.workflow.steps[activeWorkflow.stepIndex].delayMinutes;
                queueWorkflowStep(text, activeWorkflow.sessionId, delay);

                // Move to next
                const nextIndex = activeWorkflow.stepIndex + 1;
                if (nextIndex < activeWorkflow.workflow.steps.length) {
                    setActiveWorkflow({ ...activeWorkflow, stepIndex: nextIndex });
                    const nextTemplate = notes.find(n => n.id === activeWorkflow.workflow.steps[nextIndex].templateId);
                    if (nextTemplate) handleUseTemplate(nextTemplate);
                } else {
                    setActiveWorkflow(null);
                    setTemplateModalOpen(false);
                }
            } else {
                await handleTemplateSubmitted(text, false);
                setTemplateModalOpen(false);
            }
        }}
        onStartNewChat={(text) => {
            if (activeWorkflow) {
                handleStartNewChatFromTemplate(text);
            } else {
                handleStartNewChatFromTemplate(text);
            }
        }}
        hfProfileData={hfProfiles[currentAgent.id]}
        workflowContext={activeWorkflow ? {
            stepIndex: activeWorkflow.stepIndex,
            totalSteps: activeWorkflow.workflow.steps.length,
            delayMinutes: activeWorkflow.workflow.steps[activeWorkflow.stepIndex].delayMinutes
        } : undefined}
      />"""
content = content.replace(modal_old, modal_new)

# 8. Update UI Tab rendering
tab_ui_old = """                  <button
                      onClick={() => setActiveTab('import')}
                      className={`flex items-center gap-2 px-4 py-1.5 rounded-lg text-sm font-bold transition-all ${activeTab === 'import' ? 'bg-white text-indigo-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}
                  >
                      <DownloadCloud className="w-4 h-4" />
                      Import
                  </button>
              </div>"""

tab_ui_new = """                  <button
                      onClick={() => setActiveTab('import')}
                      className={`flex items-center gap-2 px-4 py-1.5 rounded-lg text-sm font-bold transition-all ${activeTab === 'import' ? 'bg-white text-indigo-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}
                  >
                      <DownloadCloud className="w-4 h-4" />
                      Import
                  </button>
                  <button
                      onClick={() => setActiveTab('workflows')}
                      className={`flex items-center gap-2 px-4 py-1.5 rounded-lg text-sm font-bold transition-all ${activeTab === 'workflows' ? 'bg-white text-indigo-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}
                  >
                      <Rocket className="w-4 h-4" />
                      Workflows
                  </button>
              </div>"""
content = content.replace(tab_ui_old, tab_ui_new)

render_ui_old = """                  ) : (
                      <ImportPanel
                        githubToken={settings.githubTokens[currentAgent.id] || ''}
                        profile={settings.githubProfiles[currentAgent.id]}
                      />
                  )}"""

render_ui_new = """                  ) : activeTab === 'import' ? (
                      <ImportPanel
                        githubToken={settings.githubTokens[currentAgent.id] || ''}
                        profile={settings.githubProfiles[currentAgent.id]}
                      />
                  ) : (
                      <WorkflowPanel
                        templates={notes}
                        onStartWorkflow={handleStartWorkflow}
                      />
                  )}"""
content = content.replace(render_ui_old, render_ui_new)

# 9. Remove obsolete HFCueWizardModal
content = re.sub(r'<HFCueWizardModal\s+isOpen=\{hfWizardOpen\}(.*?)\/>\s+', '', content, flags=re.DOTALL)

with open("App.tsx", "w") as f:
    f.write(content)