File size: 21,304 Bytes
28a3944
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>AI Browser Co-Pilot Studio</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-gradient: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);
            --card-bg: rgba(255, 255, 255, 0.92);
            --card-border: rgba(255, 255, 255, 0.5);
            --text-main: #2d3436;
            --text-muted: #636e72;
            --color-emerald: #55efc4;
            --color-amber: #ffeaa7;
            --color-rose: #ff7675;
            --color-blue: #74b9ff;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: var(--bg-gradient);
            background-attachment: fixed;
            color: var(--text-main);
            min-height: 100vh;
            padding: 24px;
        }
        .header {
            max-width: 1550px; margin: 0 auto 24px auto;
            display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;
            padding: 16px 24px;
            background: var(--card-bg); backdrop-filter: blur(10px);
            border: 1px solid var(--card-border); border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.06);
        }
        .header h1 {
            font-size: 24px; font-weight: 800;
            background: linear-gradient(90deg, #ff758c 0%, #ff7eb3 100%);
            -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent;
        }
        .badges-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
        .badge-pill {
            font-size: 11px; font-weight: 800; padding: 5px 12px; border-radius: 20px;
            text-transform: uppercase; letter-spacing: 0.5px; box-shadow: 0 4px 10px rgba(0,0,0,0.05);
        }
        .badge-live { background: #81ecec; color: #00b894; }
        .badge-cursor { background: #a29bfe; color: #ffffff; }

        .grid { display: grid; grid-template-columns: 460px 1fr; gap: 24px; max-width: 1550px; margin: 0 auto; }
        @media (max-width: 1000px) { .grid { grid-template-columns: 1fr; } body { padding: 12px; } }

        .card {
            background: var(--card-bg); backdrop-filter: blur(10px);
            border: 1px solid var(--card-border); border-radius: 24px; padding: 24px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.08);
            display: flex; flex-direction: column; gap: 16px; min-width: 0;
        }
        .card h3 {
            font-size: 16px; font-weight: 700; display: flex; align-items: center;
            justify-content: space-between; gap: 8px; letter-spacing: 0.3px;
        }
        .input-group { display: flex; gap: 10px; }
        .actions { gap: 8px; flex-wrap: wrap; }
        .actions .btn { flex: 1 1 auto; padding: 12px 14px; }
        input, textarea {
            width: 100%; padding: 12px 16px; background: #f1f2f6; border: 1px solid #dfe4ea;
            border-radius: 12px; color: #2f3542; font-family: inherit; font-size: 14px; transition: all 0.2s;
        }
        textarea { resize: vertical; }
        input:focus, textarea:focus { outline: none; border-color: #70a1ff; background: #fff; box-shadow: 0 0 0 3px rgba(112,161,255,0.3); }

        .btn {
            padding: 12px 18px; border: none; border-radius: 12px; font-weight: 700; font-size: 14px;
            font-family: inherit; cursor: pointer; transition: all 0.2s ease-in-out;
            display: inline-flex; align-items: center; justify-content: center; gap: 8px;
            color: #2d3436; box-shadow: 0 4px 15px rgba(0,0,0,0.05); white-space: nowrap;
        }
        .btn:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0,0,0,0.1); filter: brightness(1.05); }
        .btn:active { transform: translateY(0); }
        .btn:disabled { opacity: .55; cursor: not-allowed; transform: none; }
        .btn-blue { background: var(--color-blue); color: #fff; }
        .btn-emerald { background: var(--color-emerald); }
        .btn-amber { background: var(--color-amber); }
        .btn-rose { background: var(--color-rose); color: #fff; }
        .btn-orange { background: #ff9f43; color: #fff; }

        #logs {
            background: #fff; border: 1px solid #dfe4ea; border-radius: 12px; padding: 14px;
            font-family: 'Courier New', monospace; height: 290px; overflow-y: auto;
            font-size: 13px; line-height: 1.6; color: #57606f; white-space: pre-wrap; word-break: break-word;
            box-shadow: inset 0 2px 4px rgba(0,0,0,0.02);
        }
        .live-preview-container {
            position: relative; width: 100%; max-width: 1280px; aspect-ratio: 16 / 10; max-height: 65vh;
            margin: 0 auto; border-radius: 16px; overflow: hidden; border: 2px solid #f1f2f6;
            box-shadow: 0 15px 35px rgba(0,0,0,0.1); background: #fff; outline: none;
        }
        .live-preview-container:focus { border-color: var(--color-blue); box-shadow: 0 0 0 3px rgba(116,185,255,0.4); }
        .live-preview { width: 100%; height: 100%; object-fit: contain; display: block; cursor: crosshair; user-select: none; -webkit-user-drag: none; }
        .stream-status, .cursor-indicator {
            position: absolute; top: 12px; padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: 700;
            display: flex; align-items: center; gap: 6px; pointer-events: none; z-index: 5; box-shadow: 0 4px 10px rgba(0,0,0,0.05);
        }
        .stream-status { right: 12px; background: rgba(255,255,255,0.9); backdrop-filter: blur(8px); color: #00b894; border: 1px solid #55efc4; }
        .cursor-indicator { left: 12px; background: rgba(116,185,255,0.95); color: #fff; font-size: 11px; font-weight: 800; letter-spacing: 0.5px; }
        .pulse-dot { width: 8px; height: 8px; background: #00b894; border-radius: 50%; animation: pulse 1.5s infinite; }
        @keyframes pulse { 0%,100% { transform: scale(0.95); opacity: 1; } 50% { transform: scale(1.1); opacity: 0.6; } }

        #userControlBanner {
            display: none; background: linear-gradient(90deg, #ff9f43, #ff7f50); color: #fff;
            padding: 14px 20px; border-radius: 16px; font-weight: 600; font-size: 13px;
            align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;
            box-shadow: 0 6px 20px rgba(255,127,80,0.25); animation: fadeIn 0.3s ease-out;
        }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(-8px); } to { opacity: 1; transform: translateY(0); } }

        .modal { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.4); backdrop-filter: blur(4px); z-index: 99999; align-items: center; justify-content: center; padding: 16px; }
        .modal-inner { background: #fff; border-radius: 24px; padding: 32px; max-width: 520px; width: 100%; box-shadow: 0 25px 50px rgba(0,0,0,0.15); text-align: center; }
        .modal-msg { color: #2d3436; font-size: 14px; line-height: 1.6; margin-bottom: 22px; text-align: left; background: #f1f2f6; padding: 16px; border-radius: 12px; border: 1px solid #dfe4ea; }
        .meta-row { font-size: 13px; color: var(--text-muted); display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
        #urlDisplay { font-weight: 600; word-break: break-all; }
    </style>
</head>
<body>

    <div class="header">
        <h1>✨ AI Browser Co-Pilot Studio</h1>
        <div class="badges-row">
            <span class="badge-pill badge-cursor">🖱️ Human-like Cursor</span>
            <span class="badge-pill badge-live">⚡ Live Stream</span>
        </div>
    </div>

    <div class="grid">
        <div class="card">
            <h3>
                <span>🎨 Control &amp; Guidance</span>
                <span id="statusBadge" style="font-size: 12px; color: var(--text-muted);">IDLE</span>
            </h3>

            <div class="input-group">
                <input type="text" id="urlInput" value="https://www.google.com" placeholder="Enter web address (e.g. google.com)..." />
                <button class="btn btn-blue" onclick="goUrl()">Go</button>
            </div>

            <div class="input-group">
                <textarea id="taskInput" rows="3" placeholder="Describe what you want the AI to do (e.g. 'Search for iPhone 16 and open the first result')..."></textarea>
            </div>

            <div class="input-group actions">
                <button class="btn btn-emerald" id="startBtn" onclick="handleStartBtn()">▶ Start Task</button>
                <button class="btn btn-amber" id="pauseBtn" onclick="togglePause()">⏸ Pause</button>
                <button class="btn btn-orange" onclick="stopTaskForUserControl()" title="Pause the AI and take manual control (solve CAPTCHA or fill info)">✋ Take Over</button>
                <button class="btn btn-rose" onclick="api('cancel-ai', {})" title="Abort the whole task">⏹ Abort</button>
            </div>

            <div class="input-group">
                <input type="text" id="manualText" placeholder="Send manual text to the focused element..." onkeydown="if(event.key==='Enter'){sendManualText()}" />
                <button class="btn btn-blue" onclick="sendManualText()">Type</button>
                <button class="btn btn-blue" onclick="api('key-press', {key: 'Enter'})">↵</button>
            </div>

            <h3>📜 Action Stream Logs</h3>
            <div id="logs">Ready for prompt...</div>
        </div>

        <div class="card">
            <div id="userControlBanner">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <span style="font-size: 24px;">🎮</span>
                    <div>
                        <div style="font-weight: 800; font-size: 14px;">USER CONTROL MODE ACTIVE</div>
                        <div style="font-size: 12px; opacity: 0.95;">The AI is paused. Solve the CAPTCHA or enter your information directly on the live screen below, then click "Done &amp; Resume AI".</div>
                    </div>
                </div>
                <button class="btn btn-emerald" style="padding: 10px 18px; font-size: 13px;" onclick="resumeFromUserControl()">▶ Done &amp; Resume AI</button>
            </div>

            <h3>
                <span>📹 Live Browser View</span>
                <span style="font-size: 12px; color: #74b9ff; font-weight: 600;">✨ AI cursor enabled</span>
            </h3>

            <div class="live-preview-container" id="streamContainer" tabindex="0">
                <div class="cursor-indicator"><span style="display:inline-block;width:6px;height:6px;background:#fff;border-radius:50%;"></span> AI CURSOR</div>
                <div class="stream-status"><div class="pulse-dot"></div> LIVE</div>
                <img id="interactiveScreen" class="live-preview" alt="Live browser view" draggable="false" onclick="handleScreenClick(event)" />
            </div>
            <div class="meta-row">
                <span>🎯 Click, scroll or type directly on the live view (works any time, not only in Take Over).</span>
                <span id="urlDisplay">URL: https://www.google.com</span>
            </div>
        </div>
    </div>

    <!-- Help modal -->
    <div id="helpModal" class="modal">
        <div class="modal-inner">
            <div style="font-size: 42px; margin-bottom: 12px;">🆘</div>
            <h3 style="color: #ff7675; font-size: 20px; margin-bottom: 12px; font-weight: 800; justify-content:center;">The AI needs a human</h3>
            <p id="helpMessageText" class="modal-msg"></p>
            <div id="helpButtons" style="display: flex; gap: 10px; justify-content: center; flex-wrap: wrap;"></div>
            <div id="helpHint" style="margin-top: 16px; font-size: 12px; color: #636e72;"></div>
        </div>
    </div>

    <!-- Password modal (the browser's prompt() is blocked inside iframes, so we use our own) -->
    <div id="authModal" class="modal">
        <div class="modal-inner">
            <div style="font-size: 42px; margin-bottom: 12px;">🔒</div>
            <h3 style="font-size: 20px; margin-bottom: 14px; font-weight: 800; justify-content:center;">Password required</h3>
            <input type="password" id="authInput" placeholder="Enter the access password" style="margin-bottom: 8px;" onkeydown="if(event.key==='Enter'){submitKey()}" />
            <div id="authErr" style="color:#d63031; font-size:13px; min-height:20px; margin-bottom:10px;"></div>
            <button class="btn btn-blue" style="width:100%" onclick="submitKey()">Unlock</button>
        </div>
    </div>

    <script>
        const $ = (id) => document.getElementById(id);
        let KEY = '';
        try { KEY = sessionStorage.getItem('ba_key') || ''; } catch (e) {}
        let isPaused = false, isRunning = false, lastStatus = '', helpDismissed = false, started = false;

        function headers() { const h = { 'Content-Type': 'application/json' }; if (KEY) h['x-ba-key'] = KEY; return h; }

        async function api(path, body) {
            try {
                const r = await fetch('/api/ba/' + path, {
                    method: body === undefined ? 'GET' : 'POST',
                    headers: headers(),
                    body: body === undefined ? undefined : JSON.stringify(body)
                });
                if (r.status === 401) { showAuth(KEY ? 'Wrong password, try again.' : ''); return null; }
                return r;
            } catch (e) { return null; }
        }

        function showAuth(msg) { $('authErr').textContent = msg || ''; $('authModal').style.display = 'flex'; setTimeout(() => $('authInput').focus(), 50); }
        async function submitKey() {
            KEY = $('authInput').value;
            const r = await fetch('/api/ba/status', { headers: headers() });
            if (r.status === 401) { $('authErr').textContent = 'Wrong password, try again.'; return; }
            try { sessionStorage.setItem('ba_key', KEY); } catch (e) {}
            $('authModal').style.display = 'none';
            connectStream();
        }

        function connectStream() {
            $('interactiveScreen').src = '/api/ba/stream?key=' + encodeURIComponent(KEY) + '&t=' + Date.now();
        }
        $('interactiveScreen').addEventListener('error', () => { if (started) setTimeout(connectStream, 2000); });   // server restarted / network hiccup

        async function goUrl() {
            const r = await api('navigate', { url: $('urlInput').value });
            if (r && !r.ok) { const d = await r.json().catch(() => ({})); alert(d.error || 'Could not open that address.'); }
        }

        async function handleStartBtn() {
            if (isRunning && isPaused) return resumeFromUserControl();
            const r = await api('start-ai', { task: $('taskInput').value });
            if (r) { const d = await r.json().catch(() => ({})); if (d.error) alert(d.error); }
        }
        async function stopTaskForUserControl() { closeHelp(); await api('take-control', {}); }
        async function resumeFromUserControl() { closeHelp(); await api('resume-ai', {}); }
        async function togglePause() { if (isPaused) await resumeFromUserControl(); else await api('pause-ai', {}); }
        async function sendManualText() {
            const i = $('manualText'); if (!i.value) return;
            await api('type-text', { text: i.value }); i.value = '';
        }

        // ---- direct control on the live view ----
        async function handleScreenClick(event) {
            $('streamContainer').focus();
            const img = $('interactiveScreen'), rect = img.getBoundingClientRect();
            const ratio = 1280 / 800;
            let w = rect.width, h = rect.height, ox = 0, oy = 0;
            if (rect.width / rect.height > ratio) { w = rect.height * ratio; ox = (rect.width - w) / 2; }
            else { h = rect.width / ratio; oy = (rect.height - h) / 2; }
            const x = Math.max(0, Math.min(1280, ((event.clientX - rect.left - ox) / w) * 1280));
            const y = Math.max(0, Math.min(800, ((event.clientY - rect.top - oy) / h) * 800));
            await api('click-coords', { x, y });
        }
        const sc = $('streamContainer');
        sc.addEventListener('wheel', async (e) => { e.preventDefault(); await api('scroll-wheel', { delta_x: e.deltaX, delta_y: e.deltaY }); }, { passive: false });
        sc.addEventListener('keydown', async (e) => {
            if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', ' ', 'Backspace', 'Tab', 'Enter'].includes(e.key)) e.preventDefault();
            if (e.key.length === 1 && !e.ctrlKey && !e.metaKey) await api('type-text', { text: e.key });
            else if (e.key.length > 1 && !['Shift', 'Control', 'Alt', 'Meta', 'CapsLock'].includes(e.key)) await api('key-press', { key: e.key });
        });

        // ---- help modal ----
        function closeHelp() { $('helpModal').style.display = 'none'; }
        function showHelp(msg, canResume) {
            $('helpMessageText').textContent = msg || 'Manual intervention or CAPTCHA solving is needed.';
            const b = $('helpButtons'); b.innerHTML = '';
            const add = (cls, label, fn, style) => { const x = document.createElement('button'); x.className = 'btn ' + cls; x.textContent = label; if (style) x.style.cssText = style; x.onclick = fn; b.appendChild(x); };
            if (canResume) {
                add('btn-orange', "✋ Stop Task (I'll solve it)", stopTaskForUserControl, 'flex:1;min-width:180px');
                add('btn-emerald', '▶ Resume AI', resumeFromUserControl, 'flex:1;min-width:140px');
                add('btn-rose', '❌ Abort', () => { closeHelp(); api('cancel-ai', {}); });
                $('helpHint').innerHTML = 'Click <b>"Stop Task"</b> to take control, solve the CAPTCHA or fill credentials on the live view, then click <b>"Done &amp; Resume AI"</b>.';
            } else {
                add('btn-blue', 'OK', () => { helpDismissed = true; closeHelp(); }, 'min-width:120px');
                $('helpHint').textContent = '';
            }
            $('helpModal').style.display = 'flex';
        }

        // ---- status polling ----
        async function pollStatus() {
            if ($('authModal').style.display === 'flex') { setTimeout(pollStatus, 700); return; }   // wait for the password
            try {
                const r = await api('status');
                if (r && r.ok) {
                    const d = await r.json();
                    isPaused = d.paused; isRunning = d.running;
                    const status = d.status || 'idle', max = d.max_steps || 50, step = d.step || 0;
                    $('pauseBtn').textContent = isPaused ? '▶ Resume' : '⏸ Pause';
                    $('startBtn').textContent = (isRunning && isPaused) ? '▶ Resume Task' : isRunning ? '⚡ Running...' : '▶ Start Task';
                    const badge = $('statusBadge'), banner = $('userControlBanner');
                    const label = { user_control: ['🎮 USER CONTROL (PAUSED)', '#e1b12c'], help_needed: ['🆘 HELP NEEDED', '#c23616'], running: ['⚡ RUNNING', '#44bd32'], paused: ['⏸ PAUSED', '#e1b12c'] }[status];
                    badge.textContent = (label ? label[0] : status.toUpperCase()) + ' • STEP ' + step + '/' + max;
                    badge.style.color = label ? label[1] : 'var(--text-muted)';
                    banner.style.display = (status === 'user_control') ? 'flex' : 'none';

                    if (status !== lastStatus) {
                        if (status === 'help_needed') { helpDismissed = false; showHelp(d.help_message, d.running); }
                        else closeHelp();
                        lastStatus = status;
                    }
                    const logs = $('logs'), text = d.logs.join('\n');
                    if (logs.textContent !== text) {
                        const atBottom = logs.scrollHeight - logs.scrollTop - logs.clientHeight < 40;
                        logs.textContent = text;
                        if (atBottom) logs.scrollTop = logs.scrollHeight;
                    }
                    if (d.current_url) $('urlDisplay').textContent = 'URL: ' + d.current_url;
                    if (d.current_task && !$('taskInput').value) $('taskInput').value = d.current_task;
                }
            } catch (e) {}
            setTimeout(pollStatus, 700);
        }

        // ---- start ----
        (async function init() {
            let required = false;
            try { required = (await (await fetch('/api/ba/auth')).json()).required; } catch (e) {}
            if (required && !KEY) showAuth('');
            else {
                const r = await fetch('/api/ba/status', { headers: headers() }).catch(() => null);
                if (r && r.status === 401) showAuth('Wrong password, try again.'); else connectStream();
            }
            started = true;
            pollStatus();
        })();
    </script>
</body>
</html>