File size: 9,749 Bytes
1bb18a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useState, useEffect, useCallback, useRef } from 'react';
import './App.css';
import SimulationControls from './components/SimulationControls';
import InboxPanel from './components/InboxPanel';
import ActionPanel from './components/ActionPanel';
import TimelinePanel from './components/TimelinePanel';
import ScorePanel from './components/ScorePanel';
import { resetEnv, stepEnv, getGrade } from './api';

const STEP_DELAY = 1400; // ~0.5× — realistic LLM response cadence

/* Greedy agent: match pending goals first, then highest priority*urgency */
function pickBestAction(obs) {
  if (!obs) return null;
  const unhandled = (obs.inbox || []).filter(e => !e.handled);
  if (!unhandled.length) return null;

  const pendingGoals = [...(obs.pending_goals || [])].sort((a, b) => b.priority - a.priority);
  for (const goal of pendingGoals) {
    const email = unhandled.find(e => e.id === goal.target_email_id);
    if (email) return { type: goal.required_action, email_id: email.id };
  }

  const best = [...unhandled].sort(
    (a, b) => b.priority * b.urgency - a.priority * a.urgency
  )[0];
  return { type: best.priority <= 2 ? 'delegate' : 'reply', email_id: best.id };
}

const sleep = ms => new Promise(r => setTimeout(r, ms));

export default function App() {
  const [obs, setObs]               = useState(null);
  const [history, setHistory]       = useState([]);
  const [selectedEmail, setSelectedEmail] = useState(null);
  const [taskId, setTaskId]         = useState('easy');
  const [score, setScore]           = useState(0);
  const [loading, setLoading]       = useState(false);
  const [error, setError]           = useState(null);
  const [isAutoRunning, setIsAutoRunning] = useState(false);
  const [rewardPopups, setRewardPopups] = useState([]);
  const [firstLoad, setFirstLoad]   = useState(true); // eslint-disable-line no-unused-vars

  const obsRef        = useRef(obs);
  const autoRunRef    = useRef(false);
  const popupIdRef    = useRef(0);

  useEffect(() => { obsRef.current = obs; }, [obs]);

  /* ── helpers ─────────────────────────────────────── */
  const showRewardPopup = (reward, subject) => {
    const id = ++popupIdRef.current;
    setRewardPopups(prev => [...prev.slice(-4), { id, reward, label: subject?.slice(0, 32) }]);
    setTimeout(() => setRewardPopups(prev => prev.filter(p => p.id !== id)), 2200);
  };

  /* ── reset ───────────────────────────────────────── */
  const handleReset = useCallback(async (task = taskId) => {
    autoRunRef.current = false;
    setIsAutoRunning(false);
    setLoading(true);
    setError(null);
    try {
      const fresh = await resetEnv(task);
      setObs(fresh);
      setHistory([]);
      setSelectedEmail(null);
      setScore(0);
      setRewardPopups([]);
      setFirstLoad(false);
    } catch {
      setError('Cannot connect to server.');
    } finally {
      setLoading(false);
    }
  }, [taskId]);

  const handleTaskChange = useCallback((t) => {
    setTaskId(t);
    handleReset(t);
  }, [handleReset]);

  useEffect(() => { handleReset('easy'); }, []); // eslint-disable-line

  /* ── single step (returns new obs or null) ────────── */
  const executeStep = useCallback(async (action, currentObs) => {
    try {
      const result = await stepEnv(action);
      const newObs = result.observation || result;
      if (!('done' in newObs)) newObs.done = result.done ?? false;

      const entry = {
        step:           currentObs.step ?? 0,
        time:           currentObs.time,
        action:         action.type,
        email_id:       action.email_id,
        email_subject:  result.info?.email_subject ?? action.email_id,
        email_priority: (currentObs.inbox || []).find(e => e.id === action.email_id)?.priority,
        reward:         result.reward ?? 0,
      };

      setObs(newObs);
      setHistory(h => [...h, entry]);
      showRewardPopup(result.reward, entry.email_subject);

      if (newObs.done) {
        const g = await getGrade().catch(() => null);
        if (g) setScore(g.score);
      }

      return newObs;
    } catch (e) {
      setError(e?.detail || 'Step failed.');
      return null;
    }
  }, []);

  /* ── manual action ────────────────────────────────── */
  const handleAction = useCallback(async (action) => {
    if (!obs || obs.done || loading || isAutoRunning) return;
    setLoading(true);
    setError(null);
    await executeStep(action, obs);
    setSelectedEmail(null);
    setLoading(false);
  }, [obs, loading, isAutoRunning, executeStep]);

  /* ── auto-run ─────────────────────────────────────── */
  const handleAutoRun = useCallback(async () => {
    if (autoRunRef.current) {
      autoRunRef.current = false;
      setIsAutoRunning(false);
      return;
    }

    autoRunRef.current = true;
    setIsAutoRunning(true);
    setError(null);


    let current = obsRef.current;

    // Auto-reset if episode already finished
    if (current?.done) {
      setLoading(true);
      try {
        const fresh = await resetEnv(taskId);
        setObs(fresh);
        setHistory([]);
        setScore(0);
        setRewardPopups([]);
        setSelectedEmail(null);
        obsRef.current = fresh;
        current = fresh;
        await sleep(600);
      } finally {
        setLoading(false);
      }
    }

    while (autoRunRef.current && current && !current.done) {
      const action = pickBestAction(current);
      if (!action) break;

      // Highlight email briefly — looks like AI "thinking"
      const email = (current.inbox || []).find(e => e.id === action.email_id);
      if (email) {
        setSelectedEmail(email);
        await sleep(STEP_DELAY * 0.4);
      }
      if (!autoRunRef.current) break;

      current = await executeStep(action, current);
      if (!current) break;

      setSelectedEmail(null);
      await sleep(STEP_DELAY * 0.6);
    }

    autoRunRef.current = false;
    setIsAutoRunning(false);
    setSelectedEmail(null);
  }, [taskId, executeStep]);

  /* ── render ───────────────────────────────────────── */
  if (!obs && !error) {
    return (
      <div className="loading-screen">
        <div className="loading-spinner" />
        <div className="loading-text">Initializing NovaTech AI — CEO Simulation</div>
      </div>
    );
  }

  const inbox    = obs?.inbox    || [];
  const goals    = obs?.goals    || [];
  const calendar = obs?.calendar || [];

  return (
    <div className={`app ${isAutoRunning ? 'app--autorunning' : ''}`}>

      {/* Floating reward popups */}
      <div className="reward-popups">
        {rewardPopups.map(p => (
          <div key={p.id} className={`reward-popup ${p.reward >= 0 ? 'positive' : 'negative'}`}>
            <span className="popup-reward">{p.reward >= 0 ? '+' : ''}{p.reward.toFixed(3)}</span>
            <span className="popup-label">{p.label}</span>
          </div>
        ))}
      </div>

      {error && (
        <div className="error-banner">
          ⚠ {error}
          <button onClick={() => setError(null)}>✕</button>
        </div>
      )}

      <SimulationControls
        taskId={taskId}
        currentTime={obs?.time || '9:00 AM'}
        currentStep={obs?.step || 0}
        maxSteps={obs?.max_steps || 6}
        totalReward={obs?.total_reward || 0}
        done={obs?.done || false}
        taskName={obs?.task_name || ''}
        onReset={() => handleReset(taskId)}
        onTaskChange={handleTaskChange}
        loading={loading}
        isAutoRunning={isAutoRunning}
        onAutoRun={handleAutoRun}
      />

      <div className="main-grid">
        <div className="left-col">
          <InboxPanel
            emails={inbox}
            selectedEmailId={selectedEmail?.id}
            onSelect={setSelectedEmail}
            isAutoRunning={isAutoRunning}
          />
        </div>

        <div className="center-col">
          <ActionPanel
            selectedEmail={selectedEmail}
            onAction={handleAction}
            done={obs?.done || false}
            loading={loading || isAutoRunning}
          />

          {calendar.length > 0 && (
            <div className="panel calendar-panel">
              <div className="panel-header">
                <span className="panel-title">📅 Calendar</span>
              </div>
              <div className="calendar-list">
                {[...calendar]
                  .sort((a, b) => a.time_slot - b.time_slot)
                  .map((ev, i) => (
                    <div key={i} className={`calendar-event ${ev.locked ? 'locked' : 'scheduled'}`}>
                      <span className="cal-time">Slot {ev.time_slot + 1}</span>
                      <span className="cal-title">{ev.title}</span>
                      {ev.locked && <span className="cal-locked">🔒</span>}
                    </div>
                  ))}
              </div>
            </div>
          )}
        </div>

        <div className="right-col">
          <ScorePanel
            goals={goals}
            score={score}
            done={obs?.done || false}
            totalReward={obs?.total_reward || 0}
            currentStep={obs?.step || 0}
            maxSteps={obs?.max_steps || 6}
          />
        </div>
      </div>

      <div className="bottom-row">
        <TimelinePanel history={history} />
      </div>
    </div>
  );
}