-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsidepanel.js
More file actions
1086 lines (959 loc) · 34.6 KB
/
Copy pathsidepanel.js
File metadata and controls
1086 lines (959 loc) · 34.6 KB
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let currentSession = null;
let activeSSEController = null;
let lastSeq = 0;
const CLIENT_VERSION = '0.2.0';
function extractClusterName(baseUrl) {
try {
const hostname = new URL(baseUrl).hostname;
const rosaMatch = hostname.match(/apps\.rosa\.([^.]+)\./);
if (rosaMatch) return rosaMatch[1];
const ocpMatch = hostname.match(/apps\.([^.]+)\./);
if (ocpMatch) return ocpMatch[1];
return hostname.split('.')[0];
} catch (_) {
return baseUrl || '';
}
}
function updateConnectionStatus(state) {
const el = document.getElementById('title-connection');
if (!el) return;
el.className = 'title-connection ' + state;
const clusterEl = document.getElementById('title-cluster');
const serverEl = document.getElementById('version-server');
const clientEl = document.getElementById('version-client');
if (state === 'disconnected') {
if (clusterEl) clusterEl.textContent = '';
if (serverEl) serverEl.textContent = '';
if (clientEl) clientEl.textContent = '';
return;
}
getConfig().then(cfg => {
if (clusterEl) clusterEl.textContent = extractClusterName(cfg.baseUrl);
if (serverEl) {
serverEl.textContent = 'server:unknown';
serverEl.title = `Click to copy: ${cfg.baseUrl}`;
}
if (clientEl) clientEl.textContent = `extension:v${CLIENT_VERSION}`;
});
}
function showWizard() {
hideApp();
document.getElementById('wizard').style.display = '';
}
function showApp() {
document.getElementById('wizard').style.display = 'none';
document.getElementById('title-bar').style.display = '';
document.getElementById('app').style.display = '';
loadToolbarProjects();
}
async function loadToolbarProjects() {
try {
const cfg = await getConfig();
await populateProjectSelect('toolbar-project', cfg.projectName);
} catch (_) {}
}
function hideApp() {
document.getElementById('title-bar').style.display = 'none';
document.getElementById('app').style.display = 'none';
}
function showPanel(panelId) {
document.getElementById(panelId).classList.add('active');
}
function hidePanel(panelId) {
document.getElementById(panelId).classList.remove('active');
}
function hidePanels() {
document.querySelectorAll('.overlay-panel').forEach(p => p.classList.remove('active'));
}
async function populateProjectSelect(selectId, selectedName) {
const data = await api.projects.list();
const projects = data.items || [];
const select = document.getElementById(selectId);
select.innerHTML = '';
if (projects.length === 0) {
const opt = document.createElement('option');
opt.value = '';
opt.textContent = 'No workspaces — create one below';
select.appendChild(opt);
} else {
projects.forEach(p => {
const opt = document.createElement('option');
opt.value = p.name;
opt.textContent = p.displayName || p.name;
if (p.name === selectedName) opt.selected = true;
select.appendChild(opt);
});
}
return projects;
}
async function loadWizardWorkspaces() {
try {
await populateProjectSelect('wizard-workspace');
} catch (err) {
showToast('Failed to load workspaces: ' + err.message, 'error');
}
}
async function loadSessions() {
const data = await chrome.storage.local.get('cachedSessions');
const sessions = data.cachedSessions || [];
renderSessions(sessions);
try {
const resp = await chrome.runtime.sendMessage({ type: 'REFRESH_SESSIONS' });
if (resp?.ok) updateConnectionStatus('connected');
} catch (_) {}
}
function renderSessions(sessions) {
const list = document.getElementById('session-list');
if (!sessions || sessions.length === 0) {
list.innerHTML = '';
const empty = document.createElement('div');
empty.className = 'empty-state';
empty.textContent = 'No sessions yet. Create one to get started.';
list.appendChild(empty);
return;
}
list.innerHTML = '';
sessions.forEach(s => {
const phaseLower = (s.phase || '').toLowerCase();
const item = document.createElement('div');
item.className = 'session-item';
item.dataset.id = s.id;
const info = document.createElement('div');
info.className = 'session-info';
const nameEl = document.createElement('div');
nameEl.className = 'session-name';
nameEl.textContent = s.name;
const meta = document.createElement('div');
meta.className = 'session-meta';
const badge = document.createElement('span');
badge.className = 'phase-badge phase-' + phaseLower;
badge.textContent = s.phase;
const modelSpan = document.createElement('span');
modelSpan.className = 'text-muted';
modelSpan.textContent = s.llm_model || '';
const timeSpan = document.createElement('span');
timeSpan.className = 'text-muted';
timeSpan.textContent = timeAgo(s.created_at);
meta.appendChild(badge);
meta.appendChild(modelSpan);
meta.appendChild(timeSpan);
info.appendChild(nameEl);
info.appendChild(meta);
if (s.prompt) {
const preview = document.createElement('div');
preview.className = 'session-preview';
preview.textContent = s.prompt;
info.appendChild(preview);
}
const actions = document.createElement('div');
actions.className = 'session-actions';
if (s.phase === 'Running') {
const chatBtn = document.createElement('button');
chatBtn.className = 'btn btn-primary';
chatBtn.textContent = 'Chat';
chatBtn.addEventListener('click', (e) => {
e.stopPropagation();
openChat(s);
});
actions.appendChild(chatBtn);
const stopBtn = document.createElement('button');
stopBtn.className = 'btn btn-secondary';
stopBtn.textContent = 'Stop';
stopBtn.addEventListener('click', (e) => {
e.stopPropagation();
stopBtn.style.display = 'none';
const confirmBtn = document.createElement('button');
confirmBtn.className = 'btn btn-danger';
confirmBtn.textContent = 'Stop?';
const cancelBtn = document.createElement('button');
cancelBtn.className = 'btn btn-secondary';
cancelBtn.textContent = 'No';
confirmBtn.addEventListener('click', (e2) => {
e2.stopPropagation();
transitionSession(s.id, 'stop');
});
cancelBtn.addEventListener('click', (e2) => {
e2.stopPropagation();
confirmBtn.remove();
cancelBtn.remove();
stopBtn.style.display = '';
});
actions.appendChild(confirmBtn);
actions.appendChild(cancelBtn);
});
actions.appendChild(stopBtn);
} else if (s.phase === 'Stopped' || s.phase === 'Completed' || s.phase === 'Failed') {
const startBtn = document.createElement('button');
startBtn.className = 'btn btn-primary';
startBtn.textContent = 'Start';
startBtn.addEventListener('click', (e) => {
e.stopPropagation();
transitionSession(s.id, 'start');
});
actions.appendChild(startBtn);
const delBtn = document.createElement('button');
delBtn.className = 'btn btn-secondary';
delBtn.textContent = 'Delete';
delBtn.addEventListener('click', (e) => {
e.stopPropagation();
delBtn.style.display = 'none';
startBtn.style.display = 'none';
const confirmBtn = document.createElement('button');
confirmBtn.className = 'btn btn-danger';
confirmBtn.textContent = 'Delete?';
const cancelBtn = document.createElement('button');
cancelBtn.className = 'btn btn-secondary';
cancelBtn.textContent = 'No';
confirmBtn.addEventListener('click', async (e2) => {
e2.stopPropagation();
try {
await api.sessions.delete(s.id);
showToast('Session deleted', 'success');
loadSessions();
} catch (err) {
showToast(`Failed to delete: ${err.message}`, 'error');
}
});
cancelBtn.addEventListener('click', (e2) => {
e2.stopPropagation();
confirmBtn.remove();
cancelBtn.remove();
delBtn.style.display = '';
startBtn.style.display = '';
});
actions.appendChild(confirmBtn);
actions.appendChild(cancelBtn);
});
actions.appendChild(delBtn);
}
item.appendChild(info);
item.appendChild(actions);
item.addEventListener('click', (e) => {
if (e.target.closest('button')) return;
openChat(s);
});
list.appendChild(item);
});
}
async function transitionSession(id, action) {
try {
await api.sessions[action](id);
try { chrome.runtime.sendMessage({ type: 'SESSION_TRANSITIONING' }); } catch (_) {}
try { chrome.runtime.sendMessage({ type: 'REFRESH_SESSIONS' }); } catch (_) {}
loadSessions();
const pastTense = action === 'stop' ? 'stopped' : 'started';
showToast(`Session ${pastTense}`, 'success');
} catch (err) {
showToast(`Failed to ${action} session: ${err.message}`, 'error');
}
}
function openChat(session) {
currentSession = { id: session.id, name: session.name, phase: session.phase };
document.getElementById('chat-title').textContent = session.name;
const phaseEl = document.getElementById('chat-phase');
phaseEl.textContent = session.phase;
phaseEl.className = 'phase-badge phase-' + (session.phase || '').toLowerCase();
document.getElementById('chat-messages').innerHTML = '';
lastSeq = 0;
showPanel('chat-panel');
loadChatHistory(session.id);
if (session.phase === 'Running') {
connectChatSSE(session.id);
}
}
async function loadChatHistory(sessionId) {
const container = document.getElementById('chat-messages');
const loading = document.createElement('div');
loading.className = 'loading-indicator';
loading.innerHTML = loadingDotsSVG();
container.appendChild(loading);
try {
const messages = await api.sessions.listMessages(sessionId, 0);
loading.remove();
if (messages && messages.length > 0) {
messages.forEach(msg => renderMessage(msg));
lastSeq = Math.max(...messages.map(m => m.seq), 0);
}
scrollChatToBottom();
} catch (err) {
loading.remove();
const errDiv = document.createElement('div');
errDiv.className = 'empty-state';
errDiv.textContent = 'Failed to load messages: ' + err.message;
container.appendChild(errDiv);
}
}
function renderMessage(msg) {
const container = document.getElementById('chat-messages');
const div = document.createElement('div');
div.dataset.timestamp = msg.created_at || new Date().toISOString();
switch (msg.event_type) {
case 'user':
div.className = 'chat-bubble user';
div.textContent = msg.payload;
break;
case 'assistant':
div.className = 'chat-bubble assistant';
div.textContent = msg.payload;
break;
case 'tool_use': {
div.className = 'tool-call';
const nameDiv = document.createElement('div');
nameDiv.className = 'tool-call-name';
nameDiv.textContent = msg.payload?.name || 'tool';
const argsPre = document.createElement('pre');
argsPre.className = 'tool-call-args';
argsPre.textContent = typeof msg.payload?.arguments === 'string'
? msg.payload.arguments
: JSON.stringify(msg.payload?.arguments, null, 2);
div.appendChild(nameDiv);
div.appendChild(argsPre);
break;
}
case 'tool_result': {
div.className = 'tool-call';
const resultLabel = document.createElement('div');
resultLabel.className = 'tool-call-name';
resultLabel.textContent = 'Result';
const resultPre = document.createElement('pre');
resultPre.className = 'tool-call-args';
resultPre.textContent = typeof msg.payload === 'string'
? msg.payload
: JSON.stringify(msg.payload, null, 2);
div.appendChild(resultLabel);
div.appendChild(resultPre);
break;
}
case 'error':
div.className = 'chat-bubble error';
div.textContent = typeof msg.payload === 'string'
? msg.payload
: (msg.payload?.message || 'Error');
break;
case 'system':
div.className = 'chat-bubble system';
div.textContent = typeof msg.payload === 'string'
? msg.payload
: JSON.stringify(msg.payload);
break;
default:
div.className = 'chat-bubble system';
div.textContent = typeof msg.payload === 'string'
? msg.payload
: JSON.stringify(msg.payload);
break;
}
container.appendChild(div);
scrollChatIfAtBottom();
}
function scrollChatToBottom() {
const container = document.getElementById('chat-messages');
container.scrollTop = container.scrollHeight;
}
function scrollChatIfAtBottom() {
const container = document.getElementById('chat-messages');
const atBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 100;
if (atBottom) {
container.scrollTop = container.scrollHeight;
}
}
let chatSSEBackoff = 1000;
let chatSSEReconnectTimer = null;
function connectChatSSE(sessionId) {
if (activeSSEController) {
activeSSEController.abort();
}
activeSSEController = new AbortController();
chatSSEBackoff = 1000;
const signal = activeSSEController.signal;
(async () => {
try {
const response = await api.sessions.streamMessages(sessionId, lastSeq);
chatSSEBackoff = 1000;
await parseSSEStream(
response,
(msg) => {
if (msg.seq > lastSeq) {
renderMessage(msg);
lastSeq = msg.seq;
}
},
(err) => {
if (signal.aborted) return;
const delay = Math.min(chatSSEBackoff, 30000) * (0.5 + Math.random());
chatSSEBackoff *= 2;
chatSSEReconnectTimer = setTimeout(() => {
chatSSEReconnectTimer = null;
if (!signal.aborted && currentSession?.id === sessionId) {
connectChatSSE(sessionId);
}
}, delay);
},
signal
);
} catch (err) {
if (signal.aborted) return;
showToast('SSE connection failed', 'error');
}
})();
}
function disconnectChatSSE() {
if (chatSSEReconnectTimer) {
clearTimeout(chatSSEReconnectTimer);
chatSSEReconnectTimer = null;
}
if (activeSSEController) {
activeSSEController.abort();
activeSSEController = null;
}
}
function downloadTranscript(containerId, sessionMeta) {
const container = document.getElementById(containerId);
if (!container) return;
const bubbles = container.querySelectorAll('.chat-bubble');
if (!bubbles.length) {
showToast('No messages to download', 'info');
return;
}
const now = new Date();
const dateStr = now.toISOString().slice(0, 10);
const lines = [];
if (sessionMeta) {
lines.push(`# ACP Session Transcript`);
lines.push('');
lines.push(`| Field | Value |`);
lines.push(`|-------|-------|`);
if (sessionMeta.name) lines.push(`| Name | ${sessionMeta.name} |`);
if (sessionMeta.id) lines.push(`| ID | ${sessionMeta.id} |`);
if (sessionMeta.status) lines.push(`| Status | ${sessionMeta.status} |`);
if (sessionMeta.model) lines.push(`| Model | ${sessionMeta.model} |`);
if (sessionMeta.workspace) lines.push(`| Workspace | ${sessionMeta.workspace} |`);
if (sessionMeta.created) lines.push(`| Created | ${new Date(sessionMeta.created).toLocaleString()} |`);
lines.push(`| Exported | ${now.toLocaleString()} |`);
} else {
lines.push(`# ACP Help Chat Transcript`);
lines.push('');
lines.push(`Exported: ${now.toLocaleString()}`);
}
lines.push('');
lines.push('---');
lines.push('');
bubbles.forEach((bubble) => {
const role = bubble.classList.contains('user') ? 'user' : 'assistant';
const text = bubble.textContent;
const ts = bubble.dataset.timestamp || now.toISOString();
const time = new Date(ts).toLocaleString();
lines.push(`[${time}] **${role}:** ${text}`);
lines.push('');
});
const filename = sessionMeta
? `acp-session-${(sessionMeta.name || 'chat').replace(/[^a-z0-9-]/gi, '_')}-${dateStr}.md`
: `acp-help-chat-${dateStr}.md`;
const blob = new Blob([lines.join('\n')], { type: 'text/markdown' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
let helpSessionId = null;
let helpPendingMessages = [];
async function sendHelpMessage() {
const input = document.getElementById('help-input');
const text = input.value.trim();
if (!text) return;
input.value = '';
const container = document.getElementById('help-messages');
const userBubble = document.createElement('div');
userBubble.className = 'chat-bubble user';
userBubble.dataset.timestamp = new Date().toISOString();
userBubble.textContent = text;
container.appendChild(userBubble);
const status = document.getElementById('help-status');
if (!helpSessionId) {
status.textContent = 'Starting help session...';
helpPendingMessages.push(text);
try {
const cfg = await getConfig();
const session = await api.sessions.create({
name: 'help-' + Date.now(),
prompt: HELP_AGENT_PROMPT,
project_id: cfg.projectName,
llm_model: 'claude-haiku-4-5',
timeout: 300,
max_turns: 20,
});
helpSessionId = session.id;
await api.sessions.start(helpSessionId);
status.textContent = 'Connected';
for (const msg of helpPendingMessages) {
await api.sessions.sendMessage(helpSessionId, '[User Question]\n' + msg + '\n[End User Question]');
}
helpPendingMessages = [];
connectChatSSEForHelp(helpSessionId, container);
setTimeout(() => { status.textContent = ''; }, 2000);
} catch (err) {
status.textContent = 'Failed to start help session: ' + err.message;
helpPendingMessages = [];
}
return;
}
try {
await api.sessions.sendMessage(helpSessionId, '[User Question]\n' + text + '\n[End User Question]');
} catch (err) {
showToast('Failed to send: ' + err.message, 'error');
}
}
function connectChatSSEForHelp(sessionId, container) {
let seq = 0;
(async () => {
try {
const response = await api.sessions.streamMessages(sessionId, seq);
await parseSSEStream(
response,
(msg) => {
if (msg.seq > seq && msg.event_type === 'assistant') {
const bubble = document.createElement('div');
bubble.className = 'chat-bubble assistant';
bubble.dataset.timestamp = msg.created_at || new Date().toISOString();
bubble.textContent = msg.payload;
container.appendChild(bubble);
container.scrollTop = container.scrollHeight;
seq = msg.seq;
}
},
() => {},
new AbortController().signal
);
} catch (_) {}
})();
}
async function sendMessage() {
const input = document.getElementById('chat-input');
const text = input.value.trim();
if (!text) return;
input.value = '';
renderMessage({ event_type: 'user', payload: text, seq: lastSeq + 0.5 });
try {
await api.sessions.sendMessage(currentSession.id, '[User Question]\n' + text + '\n[End User Question]');
} catch (err) {
showToast('Failed to send message: ' + err.message, 'error');
input.value = text;
}
}
async function loadSettingsPanel() {
const authenticated = await isAuthenticated();
const authStatus = document.getElementById('auth-status');
authStatus.innerHTML = '';
if (authenticated) {
const badge = document.createElement('span');
badge.className = 'auth-user-badge';
badge.textContent = 'Logged in';
const logoutBtn = document.createElement('button');
logoutBtn.className = 'btn btn-secondary';
logoutBtn.textContent = 'Logout';
logoutBtn.addEventListener('click', () => {
chrome.runtime.sendMessage({ type: 'OAUTH_LOGOUT' });
showWizard();
});
authStatus.appendChild(badge);
authStatus.appendChild(logoutBtn);
} else {
const label = document.createElement('span');
label.className = 'text-muted';
label.textContent = 'Not logged in';
const loginBtn = document.createElement('button');
loginBtn.className = 'btn btn-primary';
loginBtn.textContent = 'Login';
loginBtn.addEventListener('click', () => {
hidePanel('settings-panel');
showWizard();
});
authStatus.appendChild(label);
authStatus.appendChild(loginBtn);
}
const config = await getConfig();
try {
await populateProjectSelect('settings-workspace', config.projectName);
} catch (_) {}
document.getElementById('settings-server-url').textContent = config.baseUrl || 'Not set';
const themeData = await chrome.storage.local.get('theme');
const themeSelect = document.getElementById('settings-theme');
if (themeSelect) {
themeSelect.value = themeData.theme || 'dark';
}
}
async function saveUrlToHistory(url) {
const { urlHistory = [] } = await chrome.storage.local.get('urlHistory');
const clean = url.replace(/\/+$/, '');
if (!urlHistory.includes(clean)) {
urlHistory.unshift(clean);
await chrome.storage.local.set({ urlHistory: urlHistory.slice(0, 10) });
}
}
document.addEventListener('DOMContentLoaded', async () => {
const authenticated = await isAuthenticated();
const config = await getConfig();
// Populate URL history datalist
const { urlHistory = [] } = await chrome.storage.local.get('urlHistory');
const urlDatalist = document.getElementById('url-history');
if (urlDatalist) {
urlHistory.forEach(u => {
const opt = document.createElement('option');
opt.value = u;
urlDatalist.appendChild(opt);
});
}
if (config.baseUrl) {
document.getElementById('wizard-url').value = config.baseUrl;
}
if (!authenticated) {
updateConnectionStatus('disconnected');
showWizard();
} else if (!config.projectName) {
updateConnectionStatus('connecting');
showWizard();
document.getElementById('wizard-step-1').classList.remove('active');
document.getElementById('wizard-step-2').classList.add('active');
loadWizardWorkspaces();
} else {
updateConnectionStatus('connecting');
showApp();
loadSessions();
}
// Wizard: Reset/logout from step 1
document.getElementById('wizard-reset-1').addEventListener('click', async () => {
await chrome.storage.local.remove(['oauthTokens', 'baseUrl', 'projectName', 'cachedSessions']);
chrome.runtime.sendMessage({ type: 'OAUTH_LOGOUT' });
document.getElementById('wizard-url').value = '';
document.getElementById('wizard-token').value = '';
document.getElementById('wizard-login-status').textContent = '';
updateConnectionStatus('disconnected');
showToast('Connection reset');
});
// Wizard: Back from step 2 to step 1 (logout)
document.getElementById('wizard-back-to-login').addEventListener('click', async () => {
await chrome.storage.local.remove(['oauthTokens', 'projectName', 'cachedSessions']);
chrome.runtime.sendMessage({ type: 'OAUTH_LOGOUT' });
document.getElementById('wizard-step-2').classList.remove('active');
document.getElementById('wizard-step-1').classList.add('active');
updateConnectionStatus('disconnected');
});
// Wizard Step 1: Login
document.getElementById('wizard-login-btn').addEventListener('click', async () => {
const urlInput = document.getElementById('wizard-url');
const url = urlInput.value.trim();
const status = document.getElementById('wizard-login-status');
if (!url.startsWith('http://') && !url.startsWith('https://')) {
status.textContent = 'URL must start with http:// or https://';
status.className = 'status-error';
return;
}
status.textContent = 'Connecting...';
status.className = 'status-info';
try {
const response = await chrome.runtime.sendMessage({ type: 'OAUTH_LOGIN', serverUrl: url });
if (response.error) {
status.textContent = response.error;
status.className = 'status-error';
return;
}
await saveUrlToHistory(url);
status.textContent = '';
document.getElementById('wizard-step-1').classList.remove('active');
document.getElementById('wizard-step-2').classList.add('active');
await loadWizardWorkspaces();
} catch (err) {
status.textContent = 'Connection failed: ' + err.message;
status.className = 'status-error';
}
});
// Wizard: Manual token login
document.getElementById('wizard-token-btn').addEventListener('click', async () => {
const urlInput = document.getElementById('wizard-url');
const tokenInput = document.getElementById('wizard-token');
const url = urlInput.value.trim();
const token = tokenInput.value.trim();
if (!url.startsWith('http://') && !url.startsWith('https://')) {
showToast('URL must start with http:// or https://', 'error');
return;
}
if (!token) {
showToast('Token is required', 'error');
return;
}
let expiresAt = Date.now() + 86400000;
try {
const parts = token.split('.');
if (parts.length === 3) {
const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')));
if (payload.exp) expiresAt = payload.exp * 1000;
}
} catch (_) {}
await saveUrlToHistory(url);
await chrome.storage.local.set({
baseUrl: url.replace(/\/+$/, ''),
oauthTokens: {
access_token: token,
refresh_token: null,
expires_at: expiresAt,
issuer_url: null,
},
});
try {
await api.projects.list();
} catch (err) {
await chrome.storage.local.remove('oauthTokens');
showToast('Token rejected by server: ' + (err.message || 'invalid'), 'error');
return;
}
document.getElementById('wizard-step-1').classList.remove('active');
document.getElementById('wizard-step-2').classList.add('active');
await loadWizardWorkspaces();
});
// Wizard Step 2: Create workspace
document.getElementById('wizard-create-workspace-btn').addEventListener('click', async () => {
const nameInput = document.getElementById('wizard-new-workspace');
const name = nameInput.value.trim();
if (!name) return;
try {
await api.projects.create({ name });
nameInput.value = '';
await loadWizardWorkspaces();
document.getElementById('wizard-workspace').value = name;
} catch (err) {
showToast('Failed to create workspace: ' + err.message, 'error');
}
});
// Wizard Step 2: Go button
document.getElementById('wizard-go-btn').addEventListener('click', async () => {
const projectName = document.getElementById('wizard-workspace').value;
if (!projectName) {
showToast('Select a workspace first', 'warning');
return;
}
await chrome.storage.local.set({ projectName });
updateConnectionStatus('connecting');
showApp();
chrome.runtime.sendMessage({ type: 'REFRESH_SESSIONS' });
loadSessions();
});
// Title bar: cluster name click → copy full server URL
document.getElementById('title-cluster').addEventListener('click', async () => {
const cfg = await getConfig();
if (cfg.baseUrl) {
await navigator.clipboard.writeText(cfg.baseUrl);
showToast('Server URL copied', 'success');
}
});
// Toolbar: project switcher
document.getElementById('toolbar-project').addEventListener('change', async (e) => {
const projectName = e.target.value;
if (!projectName) return;
await chrome.storage.local.set({ projectName });
try { chrome.runtime.sendMessage({ type: 'REFRESH_SESSIONS' }); } catch (_) {}
loadSessions();
showToast(`Switched to ${projectName}`, 'success');
});
// Title bar: server version click → copy hostname
document.getElementById('version-server').addEventListener('click', async () => {
const cfg = await getConfig();
if (cfg.baseUrl) {
await navigator.clipboard.writeText(cfg.baseUrl);
showToast('Server URL copied to clipboard');
}
});
// Title bar: client version click → open GitHub
document.getElementById('version-client').addEventListener('click', () => {
window.open('https://github.com/ambient-code/browser-extension', '_blank');
});
// Help panel
document.getElementById('btn-help').addEventListener('click', () => {
showPanel('help-panel');
});
document.getElementById('help-back').addEventListener('click', () => {
hidePanel('help-panel');
});
document.getElementById('help-send').addEventListener('click', sendHelpMessage);
document.getElementById('help-download').addEventListener('click', () => {
downloadTranscript('help-messages', null);
});
document.getElementById('help-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendHelpMessage();
}
});
// Create session panel
document.getElementById('create-submit').addEventListener('click', async () => {
const name = document.getElementById('create-name').value.trim();
const prompt = document.getElementById('create-prompt').value.trim();
const repo = document.getElementById('create-repo').value.trim();
const model = document.getElementById('create-model').value.trim();
if (!name) {
showToast('Session name is required', 'warning');
return;
}
const cfg = await getConfig();
try {
await api.sessions.create({
name,
prompt: prompt || undefined,
project_id: cfg.projectName,
repo_url: repo || undefined,
llm_model: model || undefined,
});
if (repo) {
const { repoHistory = [] } = await chrome.storage.local.get('repoHistory');
if (!repoHistory.includes(repo)) {
repoHistory.unshift(repo);
await chrome.storage.local.set({ repoHistory: repoHistory.slice(0, 20) });
}
}
hidePanel('create-panel');
showToast('Session created');
chrome.runtime.sendMessage({ type: 'REFRESH_SESSIONS' });
loadSessions();
} catch (err) {
showToast('Failed to create session: ' + err.message, 'error');
}
});
document.getElementById('create-back').addEventListener('click', () => {
hidePanel('create-panel');
});
// Toolbar
document.getElementById('btn-create').addEventListener('click', async () => {
const { repoHistory = [] } = await chrome.storage.local.get('repoHistory');
const datalist = document.getElementById('repo-history');
datalist.innerHTML = '';
repoHistory.forEach(url => {
const opt = document.createElement('option');
opt.value = url;
datalist.appendChild(opt);
});
showPanel('create-panel');
});
document.getElementById('btn-settings').addEventListener('click', () => {
loadSettingsPanel();
showPanel('settings-panel');
});
document.getElementById('btn-refresh').addEventListener('click', () => {
loadSessions();
});
// Chat controls
document.getElementById('chat-back').addEventListener('click', () => {
disconnectChatSSE();
hidePanel('chat-panel');
currentSession = null;
});
document.getElementById('chat-send').addEventListener('click', sendMessage);
document.getElementById('chat-download').addEventListener('click', async () => {
if (!currentSession) return;
const cfg = await getConfig();
downloadTranscript('chat-messages', {
name: currentSession.name,
id: currentSession.id,
status: currentSession.phase || currentSession.status,
model: currentSession.llm_model,
workspace: cfg.projectName,
created: currentSession.created_at,
});
});
document.getElementById('chat-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
// Settings controls
document.getElementById('settings-back').addEventListener('click', () => {
hidePanel('settings-panel');
});
document.getElementById('settings-workspace').addEventListener('change', async (e) => {
await chrome.storage.local.set({ projectName: e.target.value });
chrome.runtime.sendMessage({ type: 'REFRESH_SESSIONS' });
loadSessions();
});