Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1312 lines (1132 loc) · 52.7 KB
/
Copy pathscript.js
File metadata and controls
1312 lines (1132 loc) · 52.7 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
class OllamaChat {
constructor() {
this.settings = {
url: 'http://localhost:11434',
model: 'gemma3:12b',
temperature: 0.7,
maxTokens: 1000
};
this.chatHistory = [];
this.isGenerating = false;
// Dialog mode properties
this.dialogMode = false;
this.dialogActive = false;
this.dialogHistory = [];
this.currentBot = 1; // 1 or 2
this.dialogMessageCount = 0;
this.dialogTimer = null;
// Office meeting properties
this.isMeetingMode = true;
this.activeEmployees = ['ceo', 'developer', 'intern', 'marketing', 'hr', 'support'];
this.currentEmployee = 0;
this.userRole = 'observer';
this.meetingTopic = 'normal';
this.officeEmployees = this.initializeOfficeEmployees();
// Character state tracking system
this.characterStates = this.initializeCharacterStates();
this.stateUpdateHistory = [];
this.initializeElements();
this.loadSettings();
this.loadCharacterStates(); // Character states'i yükle
this.bindEvents();
this.checkConnection();
this.updateTime();
setInterval(() => this.updateTime(), 30000); // Update time every 30 seconds
}
initializeElements() {
this.chatContainer = document.getElementById('chatContainer');
this.messageInput = document.getElementById('messageInput');
this.sendButton = document.getElementById('sendButton');
this.clearButton = document.getElementById('clearChat');
this.settingsButton = document.getElementById('settingsBtn');
this.settingsModal = document.getElementById('settingsModal');
this.closeSettingsButton = document.getElementById('closeSettings');
this.saveSettingsButton = document.getElementById('saveSettings');
this.testConnectionButton = document.getElementById('testConnection');
this.statusIndicator = document.getElementById('status');
this.charCount = document.getElementById('charCount');
// Settings inputs
this.ollamaUrlInput = document.getElementById('ollamaUrl');
this.modelNameInput = document.getElementById('modelName');
this.temperatureInput = document.getElementById('temperature');
this.maxTokensInput = document.getElementById('maxTokens');
this.tempValueSpan = document.getElementById('tempValue');
// Dialog mode elements
this.dialogModeButton = document.getElementById('dialogModeBtn');
this.dialogModal = document.getElementById('dialogModal');
this.closeDialogButton = document.getElementById('closeDialog');
this.startDialogButton = document.getElementById('startDialog');
this.pauseDialogButton = document.getElementById('pauseDialog');
this.resetDialogButton = document.getElementById('resetDialog');
this.dialogStatus = document.getElementById('dialogStatus');
// Dialog settings
this.bot1NameInput = document.getElementById('bot1Name');
this.bot1PersonaInput = document.getElementById('bot1Persona');
this.bot2NameInput = document.getElementById('bot2Name');
this.bot2PersonaInput = document.getElementById('bot2Persona');
this.dialogTopicInput = document.getElementById('dialogTopic');
this.messageDelayInput = document.getElementById('messageDelay');
this.maxDialogMessagesInput = document.getElementById('maxDialogMessages');
this.delayValueSpan = document.getElementById('delayValue');
// Office meeting elements
this.officeCharactersDiv = document.getElementById('officeCharacters');
this.triggerSectionDiv = document.getElementById('triggerSection');
this.officeScenarioSelect = document.getElementById('officeScenario');
this.userRoleSelect = document.getElementById('userRole');
}
bindEvents() {
// Send button
this.sendButton.addEventListener('click', () => this.sendMessage());
// Enter key to send, Shift+Enter for new line
this.messageInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
this.sendMessage();
}
});
// Auto-resize textarea
this.messageInput.addEventListener('input', () => {
this.autoResizeTextarea();
this.updateCharCount();
});
// Clear chat
this.clearButton.addEventListener('click', () => this.clearChat());
// Settings modal
this.settingsButton.addEventListener('click', () => this.openSettings());
this.closeSettingsButton.addEventListener('click', () => this.closeSettings());
this.saveSettingsButton.addEventListener('click', () => this.saveSettings());
this.testConnectionButton.addEventListener('click', () => this.testConnection());
// Temperature slider
this.temperatureInput.addEventListener('input', () => {
this.tempValueSpan.textContent = this.temperatureInput.value;
});
// Click outside modal to close
this.settingsModal.addEventListener('click', (e) => {
if (e.target === this.settingsModal) {
this.closeSettings();
}
});
// Dialog mode events
this.dialogModeButton.addEventListener('click', () => this.openDialogModal());
this.closeDialogButton.addEventListener('click', () => this.closeDialogModal());
this.startDialogButton.addEventListener('click', () => this.startDialog());
this.pauseDialogButton.addEventListener('click', () => this.pauseDialog());
this.resetDialogButton.addEventListener('click', () => this.resetDialog());
// Message delay slider
this.messageDelayInput.addEventListener('input', () => {
this.delayValueSpan.textContent = `${this.messageDelayInput.value} saniye`;
});
// Click outside dialog modal to close
this.dialogModal.addEventListener('click', (e) => {
if (e.target === this.dialogModal) {
this.closeDialogModal();
}
});
// Office meeting events
this.officeScenarioSelect.addEventListener('change', () => this.updateMeetingTopic());
this.userRoleSelect.addEventListener('change', () => this.updateUserRole());
// Employee selection events
if (this.officeCharactersDiv) {
this.officeCharactersDiv.addEventListener('click', (e) => {
const employee = e.target.closest('.employee-card');
if (employee) {
this.toggleEmployee(employee.dataset.char);
}
});
}
// Intervention button events
if (this.triggerSectionDiv) {
this.triggerSectionDiv.addEventListener('click', (e) => {
const intervention = e.target.closest('.intervention-btn');
if (intervention) {
this.executeIntervention(intervention.dataset.trigger);
}
});
}
}
autoResizeTextarea() {
this.messageInput.style.height = 'auto';
this.messageInput.style.height = Math.min(this.messageInput.scrollHeight, 120) + 'px';
}
updateCharCount() {
const count = this.messageInput.value.length;
this.charCount.textContent = `${count}/2000`;
this.charCount.style.color = count > 1800 ? '#ef4444' : '#666';
}
loadSettings() {
const saved = localStorage.getItem('ollamaSettings');
if (saved) {
this.settings = { ...this.settings, ...JSON.parse(saved) };
}
this.updateSettingsInputs();
}
updateSettingsInputs() {
this.ollamaUrlInput.value = this.settings.url;
this.modelNameInput.value = this.settings.model;
this.temperatureInput.value = this.settings.temperature;
this.maxTokensInput.value = this.settings.maxTokens;
this.tempValueSpan.textContent = this.settings.temperature;
}
saveSettings() {
this.settings = {
url: this.ollamaUrlInput.value.trim(),
model: this.modelNameInput.value.trim(),
temperature: parseFloat(this.temperatureInput.value),
maxTokens: parseInt(this.maxTokensInput.value)
};
localStorage.setItem('ollamaSettings', JSON.stringify(this.settings));
this.showNotification('Ayarlar kaydedildi!', 'success');
this.closeSettings();
this.checkConnection();
}
openSettings() {
this.settingsModal.style.display = 'block';
}
closeSettings() {
this.settingsModal.style.display = 'none';
}
async checkConnection() {
try {
const response = await fetch(`${this.settings.url}/api/tags`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
});
if (response.ok) {
this.setConnectionStatus(true);
const data = await response.json();
console.log('Mevcut modeller:', data.models);
} else {
this.setConnectionStatus(false);
}
} catch (error) {
console.error('Bağlantı hatası:', error);
this.setConnectionStatus(false);
}
}
async testConnection() {
this.testConnectionButton.disabled = true;
this.testConnectionButton.textContent = 'Test ediliyor...';
try {
const response = await fetch(`${this.ollamaUrlInput.value.trim()}/api/tags`);
if (response.ok) {
this.showNotification('Bağlantı başarılı!', 'success');
} else {
this.showNotification('Bağlantı başarısız!', 'error');
}
} catch (error) {
this.showNotification('Bağlantı hatası: ' + error.message, 'error');
}
this.testConnectionButton.disabled = false;
this.testConnectionButton.textContent = 'Bağlantıyı Test Et';
}
setConnectionStatus(connected) {
if (connected) {
this.statusIndicator.classList.remove('disconnected');
this.statusIndicator.title = 'Bağlı';
} else {
this.statusIndicator.classList.add('disconnected');
this.statusIndicator.title = 'Bağlantı yok';
}
}
showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.className = `${type}-message`;
notification.textContent = message;
const modalBody = document.querySelector('.modal-body');
modalBody.insertBefore(notification, modalBody.firstChild);
setTimeout(() => {
notification.remove();
}, 3000);
}
addMessage(content, isUser = false, timestamp = new Date(), botName = null, botType = null) {
const messageDiv = document.createElement('div');
let messageClass = `message ${isUser ? 'user-message' : 'bot-message'}`;
// Dialog mode için özel bot sınıfları
if (botType) {
messageClass = `message ${botType}-message`;
}
messageDiv.className = messageClass;
const timeString = timestamp.toLocaleTimeString('tr-TR', {
hour: '2-digit',
minute: '2-digit'
});
let messageHTML = '';
// Avatar için fotoğraf veya placeholder
let avatarHTML = '';
if (isUser) {
avatarHTML = `
<div class="message-avatar">
<div class="avatar-placeholder">👤</div>
</div>
`;
} else if (botType && this.officeEmployees[botType]) {
const character = this.officeEmployees[botType];
avatarHTML = `
<div class="message-avatar">
<img src="photos/${botType}.jpg" alt="${character.name}"
onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
<div class="avatar-placeholder" style="display: none;">${this.getCharacterEmoji(botType)}</div>
</div>
`;
} else {
avatarHTML = `
<div class="message-avatar">
<div class="avatar-placeholder">🤖</div>
</div>
`;
}
if (isUser) {
messageHTML = `
<div class="message-wrapper">
${avatarHTML}
<div class="message-content-wrapper">
<div class="message-header">
<span class="message-sender">Sen</span>
<span class="message-time">${timeString}</span>
</div>
<div class="message-content">${this.formatMessage(content)}</div>
</div>
</div>
`;
} else {
const senderName = botName || (botType && this.officeEmployees[botType] ? this.officeEmployees[botType].name : 'AI Asistan');
messageHTML = `
<div class="message-wrapper">
${avatarHTML}
<div class="message-content-wrapper">
<div class="message-header">
<span class="message-sender">${senderName}</span>
<span class="message-time">${timeString}</span>
</div>
<div class="message-content">${this.formatMessage(content)}</div>
</div>
</div>
`;
}
messageDiv.innerHTML = messageHTML;
this.chatContainer.appendChild(messageDiv);
this.scrollToBottom();
// Character state update için mesajı analiz et
if (botType && !isUser) {
this.analyzeMessageForStateUpdates(content, botType);
}
return messageDiv;
}
getCharacterEmoji(characterId) {
const emojis = {
ceo: '👔',
developer: '💻',
intern: '🎓',
marketing: '📈',
hr: '👩💼',
support: '🛠️'
};
return emojis[characterId] || '👤';
}
formatMessage(content) {
// Basit markdown formatlaması
return content
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.*?)\*/g, '<em>$1</em>')
.replace(/`(.*?)`/g, '<code>$1</code>')
.replace(/\n/g, '<br>');
}
showTypingIndicator(characterId = null, characterName = null) {
const typingDiv = document.createElement('div');
typingDiv.className = 'typing-indicator';
let avatarHTML = '';
if (characterId && this.officeEmployees[characterId]) {
const character = this.officeEmployees[characterId];
avatarHTML = `
<div class="message-avatar">
<img src="photos/${characterId}.jpg" alt="${character.name}"
onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
<div class="avatar-placeholder" style="display: none;">${this.getCharacterEmoji(characterId)}</div>
</div>
`;
} else {
avatarHTML = `
<div class="message-avatar">
<div class="avatar-placeholder">🤖</div>
</div>
`;
}
typingDiv.innerHTML = `
${avatarHTML}
<div class="typing-content">
<div class="typing-dots">
<span></span>
<span></span>
<span></span>
</div>
</div>
`;
this.chatContainer.appendChild(typingDiv);
this.scrollToBottom();
return typingDiv;
}
scrollToBottom() {
this.chatContainer.scrollTop = this.chatContainer.scrollHeight;
}
clearChat() {
if (confirm('Tüm konuşma geçmişi silinecek. Emin misiniz?')) {
this.chatHistory = [];
this.chatContainer.innerHTML = `
<div class="welcome-message">
<div class="office-announcement">
<div class="announcement-header">
<i class="fas fa-bullhorn"></i>
<span>TechCorp Ofis Duyuru Sistemi</span>
</div>
<div class="announcement-content">
<h3>🏢 Hoş geldiniz! TechCorp ofis sohbet platformu</h3>
<p>📅 Bugün: <strong>Proje geliştirme günü</strong> | 🕐 Saat: <span id="currentTime">${new Date().toLocaleTimeString('tr-TR', { hour: '2-digit', minute: '2-digit' })}</span></p>
<p>💼 Ekip üyeleri aktif - toplantı başlatmak için "Toplantı" butonuna tıklayın</p>
<div class="quick-status">
<span class="status-item">🟢 Sistem Normal</span>
<span class="status-item">📊 Proje %75 Tamamlandı</span>
<span class="status-item">☕ Kahve makinesi çalışıyor</span>
<span class="status-item">🤖 AI State Tracking Aktif</span>
</div>
</div>
</div>
</div>
`;
}
}
async sendMessage() {
const message = this.messageInput.value.trim();
if (!message || this.isGenerating) return;
// Kullanıcı mesajını ekle
this.addMessage(message, true);
this.chatHistory.push({ role: 'user', content: message });
// Input'u temizle
this.messageInput.value = '';
this.updateCharCount();
this.autoResizeTextarea();
// Typing indicator göster
const typingIndicator = this.showTypingIndicator();
this.isGenerating = true;
this.sendButton.disabled = true;
try {
const response = await fetch(`${this.settings.url}/api/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: this.settings.model,
messages: this.chatHistory,
stream: true,
options: {
temperature: this.settings.temperature,
num_predict: this.settings.maxTokens
}
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Typing indicator'ı kaldır ve bot mesajı başlat
typingIndicator.remove();
const botMessageDiv = this.addMessage('');
const messageContent = botMessageDiv.querySelector('.message-content');
let fullResponse = '';
const reader = response.body.getReader();
const decoder = new TextDecoder();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.trim() && line.startsWith('{')) {
try {
const data = JSON.parse(line);
if (data.message && data.message.content) {
fullResponse += data.message.content;
messageContent.innerHTML = this.formatMessage(fullResponse);
this.scrollToBottom();
}
} catch (e) {
// Ignore parsing errors for incomplete JSON
}
}
}
}
// Konuşma geçmişine ekle
this.chatHistory.push({ role: 'assistant', content: fullResponse });
} catch (streamError) {
console.error('Stream error:', streamError);
messageContent.innerHTML = 'Yanıt alınırken bir hata oluştu.';
}
} catch (error) {
console.error('Hata:', error);
typingIndicator.remove();
this.addMessage(`Hata: ${error.message}. Ollama servisinin çalıştığından ve model'in yüklü olduğundan emin olun.`);
} finally {
this.isGenerating = false;
this.sendButton.disabled = false;
this.messageInput.focus();
}
}
// Office Employees Methods
initializeOfficeEmployees() {
return {
ceo: {
name: 'Mehmet Korkmaz',
title: 'Genel Müdür',
department: 'Yönetim',
experience: '15 yıl',
personality: `Sen Mehmet Korkmaz'sın, TechCorp'un Genel Müdürüsün. 15 yıllık tecrubeli bir lidersin. Vizyoner ama pragmatik yaklaşımlısın. "İnovasyon", "sürdürülebilirlik", "dijital dönüşüm" gibi terimleri kullanmayı seversin. Ekibini motive etmeye odaklısın ama sonuç odaklı çalışırsın. Toplantılarda her konuya stratejik açıdan yaklaşırsın.`,
communication_style: 'Otoriteyi seven, vizyon odaklı, bazen baskıcı ama destekleyici',
traits: ['authoritative', 'visionary', 'strategic', 'results-driven']
},
developer: {
name: 'Ahmet Yılmaz',
title: 'Senior Developer',
department: 'Yazılım',
experience: '8 yıl',
personality: `Sen Ahmet Yılmaz'sın, TechCorp'un senior yazılımcısısın. 8 yıldır kodlama yapıyorsun ve teknik konularda uzman sayılırsın. Perfeksiyonist bir yaklaşımın var, kod kalitesi senin için çok önemli. Deadline baskısı altında streslenirsin ama çözüm odaklısın. "Clean code", "refactoring", "teknik borç" gibi terimler sık kullandığın kelimeler.`,
communication_style: 'Teknik detaylı, bazen eleştirel, çözüm odaklı',
traits: ['perfectionist', 'technical', 'detail-oriented', 'sometimes-stressed']
},
intern: {
name: 'Zeynep Demir',
title: 'Yazılım Stajyeri',
department: 'Yazılım',
experience: '3 ay',
personality: `Sen Zeynep Demir'sin, TechCorp'ta yeni başlayan bir yazılım stajyerisin. Üniversite son sınıf öğrencisisin ve bu sektörde çok heveslisin. Her şeyi öğrenmeye çok isteklisin, sürekli soru sorarsın. Bazen temel hataları yapabilirsin ama öğrenme isteğin çok yüksek. Modern teknolojilere çok ilgi duyuyorsun.`,
communication_style: 'Meraklı, soru soran, heyecanlı, saygılı',
traits: ['curious', 'enthusiastic', 'learner', 'sometimes-nervous']
},
marketing: {
name: 'Ayşe Kaya',
title: 'Pazarlama Müdürü',
department: 'Pazarlama',
experience: '6 yıl',
personality: `Sen Ayşe Kaya'sın, TechCorp'un enerjik pazarlama müdürüsün. 6 yıldır dijital pazarlama alanında çalışıyorsun. Sosyal medya trendlerini yakından takip edersin, "viral", "engagement", "conversion" gibi pazarlama terimlerini sık kullanırsın. Her şeyi pazarlama gözüyle değerlendirirsin ve çok konuşkansın.`,
communication_style: 'Enerjik, hızlı konuşan, pazarlama odaklı, iyimser',
traits: ['energetic', 'trend-conscious', 'social', 'optimistic']
},
hr: {
name: 'Fatma Özkan',
title: 'İK Uzmanı',
department: 'İnsan Kaynakları',
experience: '10 yıl',
personality: `Sen Fatma Özkan'sın, TechCorp'un deneyimli İK uzmanısın. 10 yıldır insan kaynakları alanında çalışıyorsun. Personel ilişkilerinde uzman sayılırsın, empatin yüksek ama gerektiğinde kararlı olabilirsin. Ofisteki sosyal dinamikleri çok iyi gözlemlersin. "Team building", "performans", "motivasyon" gibi HR terimlerini kullanırsın.`,
communication_style: 'Empatik, diplomatik, gözlemci, sosyal',
traits: ['diplomatic', 'observant', 'people-focused', 'experienced']
},
support: {
name: 'Can Şahin',
title: 'IT Support',
department: 'Teknik Destek',
experience: '4 yıl',
personality: `Sen Can Şahin'sin, TechCorp'un IT destek uzmanısın. 4 yıldır teknik sorunları çözüyorsun. Sabırlı ve çözüm odaklısın ama bazen teknik olmayan kişilere açıklama yapmakta zorlanırsın. Sistemler, ağ, güvenlik konularında bilgilisin. "Reboot", "update", "backup" gibi teknik terimler senin dilin.`,
communication_style: 'Sabırlı, teknik, açıklayıcı, pragmatik',
traits: ['patient', 'technical', 'helpful', 'systematic']
}
};
}
// Dialog Mode Methods
openDialogModal() {
this.dialogModal.style.display = 'block';
}
closeDialogModal() {
this.dialogModal.style.display = 'none';
}
startDialog() {
if (this.dialogActive) return;
this.dialogActive = true;
this.dialogMode = true;
this.dialogMessageCount = 0;
this.currentBot = 1;
// UI güncelleme
this.updateDialogUI();
this.closeDialogModal();
// Sohbeti temizle ve başlangıç mesajını ekle
this.clearChatForDialog();
// İlk mesajı gönder
this.sendInitialDialogMessage();
}
pauseDialog() {
this.dialogActive = false;
if (this.dialogTimer) {
clearTimeout(this.dialogTimer);
this.dialogTimer = null;
}
this.updateDialogUI();
}
resetDialog() {
this.pauseDialog();
this.dialogMode = false;
this.dialogHistory = [];
this.dialogMessageCount = 0;
this.currentBot = 1;
this.updateDialogUI();
// Normal welcome mesajını geri getir
this.clearChat();
}
updateDialogUI() {
const statusDiv = this.dialogStatus;
const startBtn = this.startDialogButton;
const pauseBtn = this.pauseDialogButton;
if (this.dialogActive) {
statusDiv.innerHTML = '<i class="fas fa-play"></i> Aktif';
statusDiv.className = 'status-display active';
startBtn.disabled = true;
pauseBtn.disabled = false;
} else if (this.dialogMode) {
statusDiv.innerHTML = '<i class="fas fa-pause"></i> Duraklatıldı';
statusDiv.className = 'status-display paused';
startBtn.disabled = false;
startBtn.innerHTML = '<i class="fas fa-play"></i> Devam Et';
pauseBtn.disabled = true;
} else {
statusDiv.innerHTML = '<i class="fas fa-pause"></i> Durduruldu';
statusDiv.className = 'status-display';
startBtn.disabled = false;
startBtn.innerHTML = '<i class="fas fa-play"></i> Başlat';
pauseBtn.disabled = true;
}
}
clearChatForDialog() {
this.chatHistory = [];
this.chatContainer.innerHTML = `
<div class="welcome-message">
<div class="message bot-message">
<div class="message-content">
<h3>🤖💬 AI Diyalog Modu Başlatıldı</h3>
<p><strong>${this.bot1NameInput.value}</strong> ve <strong>${this.bot2NameInput.value}</strong> birbirleriyle konuşuyor...</p>
<p><em>Konu: ${this.dialogTopicInput.value}</em></p>
</div>
<div class="message-time">Şimdi</div>
</div>
</div>
`;
}
sendInitialDialogMessage() {
const topic = this.dialogTopicInput.value;
const bot1Name = this.bot1NameInput.value;
const bot2Name = this.bot2NameInput.value;
const initialPrompt = `${topic}. ${bot2Name} ile sohbet et.`;
this.sendDialogMessage(initialPrompt, 1);
}
async sendDialogMessage(message, botNumber) {
if (!this.dialogActive || this.dialogMessageCount >= parseInt(this.maxDialogMessagesInput.value)) {
this.pauseDialog();
return;
}
const currentBotName = botNumber === 1 ? this.bot1NameInput.value : this.bot2NameInput.value;
const currentBotPersona = botNumber === 1 ? this.bot1PersonaInput.value : this.bot2PersonaInput.value;
const botType = botNumber === 1 ? 'bot1' : 'bot2';
// Typing indicator göster
const typingIndicator = this.showTypingIndicator(currentBotName, botType);
try {
// Bot'un kişiliği ve geçmiş konuşmaları dahil et
let contextMessages = [
{ role: 'system', content: currentBotPersona }
];
// Dialog geçmişini ekle
contextMessages = contextMessages.concat(this.dialogHistory);
// Mevcut mesajı ekle
contextMessages.push({ role: 'user', content: message });
const response = await fetch(`${this.settings.url}/api/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: this.settings.model,
messages: contextMessages,
stream: true,
options: {
temperature: this.settings.temperature,
num_predict: this.settings.maxTokens
}
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Typing indicator'ı kaldır ve bot mesajı başlat
typingIndicator.remove();
const botMessageDiv = this.addMessage('', false, new Date(), currentBotName, botType);
const messageContent = botMessageDiv.querySelector('.message-content');
let fullResponse = '';
const reader = response.body.getReader();
const decoder = new TextDecoder();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.trim() && line.startsWith('{')) {
try {
const data = JSON.parse(line);
if (data.message && data.message.content) {
fullResponse += data.message.content;
messageContent.innerHTML = this.formatMessage(fullResponse);
this.scrollToBottom();
}
} catch (e) {
// Ignore parsing errors for incomplete JSON
}
}
}
}
// Dialog geçmişine ekle
this.dialogHistory.push({ role: 'assistant', content: fullResponse });
this.dialogMessageCount++;
// Diğer bot'a mesaj göndermek için zamanlayıcı ayarla
if (this.dialogActive && this.dialogMessageCount < parseInt(this.maxDialogMessagesInput.value)) {
const delay = parseInt(this.messageDelayInput.value) * 1000;
const nextBot = botNumber === 1 ? 2 : 1;
this.dialogTimer = setTimeout(() => {
if (this.dialogActive) {
this.sendDialogMessage(fullResponse, nextBot);
}
}, delay);
}
} catch (streamError) {
console.error('Stream error:', streamError);
typingIndicator.remove();
this.addMessage('Yanıt alınırken bir hata oluştu.', false, new Date(), currentBotName, botType);
}
} catch (error) {
console.error('Dialog error:', error);
typingIndicator.remove();
this.addMessage(`Hata: ${error.message}`, false, new Date(), currentBotName, botType);
this.pauseDialog();
}
}
toggleEmployee(empId) {
const empElement = this.officeCharactersDiv.querySelector(`[data-char="${empId}"]`);
const isActive = this.activeEmployees.includes(empId);
if (isActive) {
this.activeEmployees = this.activeEmployees.filter(id => id !== empId);
empElement.classList.remove('active');
} else {
this.activeEmployees.push(empId);
empElement.classList.add('active');
}
}
updateMeetingTopic() {
this.meetingTopic = this.officeScenarioSelect.value;
}
updateUserRole() {
this.userRole = this.userRoleSelect.value;
}
async startOfficeSimulation() {
if (this.activeEmployees.length < 2) {
alert('En az 2 çalışan seçmelisiniz!');
return;
}
this.dialogActive = true;
this.dialogMode = true;
this.dialogMessageCount = 0;
this.currentEmployee = 0;
this.updateDialogUI();
this.closeDialogModal();
this.clearChatForOffice();
this.sendOfficeStatusMessage();
// İlk çalışanla başla
setTimeout(() => {
this.sendOfficeMessage(this.getScenarioStartMessage(), this.activeEmployees[0]);
}, 2000);
}
clearChatForOffice() {
this.chatHistory = [];
this.dialogHistory = [];
this.loadCharacterStates(); // State'leri yükle
const scenarioText = this.getScenarioDescription();
const charactersText = this.activeEmployees.map(id =>
`${this.officeEmployees[id].name} (${this.officeEmployees[id].title})`
).join(', ');
this.chatContainer.innerHTML = `
<div class="welcome-message">
<div class="message bot-message">
<div class="message-wrapper">
<div class="message-avatar">
<div class="avatar-placeholder">🏢</div>
</div>
<div class="message-content-wrapper">
<div class="message-header">
<span class="message-sender">TechCorp Sistem</span>
<span class="message-time">${new Date().toLocaleTimeString('tr-TR', { hour: '2-digit', minute: '2-digit' })}</span>
</div>
<div class="message-content">
<h3>🏢 Toplantı Başlatıldı</h3>
<p><strong>Konu:</strong> ${scenarioText}</p>
<p><strong>Katılımcılar:</strong> ${charactersText}</p>
<p><strong>Rolünüz:</strong> ${this.getUserRoleDescription()}</p>
<p><em>💡 Önemli gelişmeler otomatik olarak takip edilecek ve karakterler bilgilendirilecek.</em></p>
</div>
</div>
</div>
</div>
</div>
`;
}
getScenarioDescription() {
const scenarios = {
normal: 'Haftalık Ekip Toplantısı',
deadline: 'Acil Proje Değerlendirmesi',
meeting: 'Strateji Planlama',
launch: 'Ürün Lansman Hazırlığı',
crisis: 'Kriz Yönetimi'
};
return scenarios[this.meetingTopic];
}
getUserRoleDescription() {
const roles = {
observer: '👀 Katılımcı (Dinleyici)',
manager: '👨💼 Toplantı Lideri',
moderator: '🎯 Moderatör',
participant: '🗣️ Aktif Katılımcı'
};
return roles[this.userRole];
}
getScenarioStartMessage() {
const messages = {
normal: 'Günaydın ekip! Haftalık toplantımıza başlayalım. Bu haftaki durumumuzu konuşalım.',
deadline: 'ACİL TOPLANTI! Proje teslim tarihi yaklaşıyor, durumu değerlendirmemiz lazım.',
meeting: 'Strateji planlama toplantımıza hoş geldiniz. Yol haritamızı belirleyelim.',
launch: 'Ürün lansmanına az kaldı! Son hazırlıkları gözden geçirelim.',
crisis: 'Acil durum toplantısı! Karşılaştığımız sorunu birlikte çözelim.'
};
return messages[this.meetingTopic];
}
sendOfficeStatusMessage() {
const time = new Date().toLocaleTimeString('tr-TR', { hour: '2-digit', minute: '2-digit' });
const statusDiv = document.createElement('div');
statusDiv.className = 'office-status';
statusDiv.innerHTML = `🕐 ${time} - Toplantı başladı • ${this.activeEmployees.length} katılımcı aktif • 📊 State tracking etkin`;
this.chatContainer.appendChild(statusDiv);
this.scrollToBottom();
}
async sendOfficeMessage(message, characterId) {
if (!this.dialogActive || this.dialogMessageCount >= parseInt(this.maxDialogMessagesInput.value)) {
this.pauseDialog();
return;
}
const character = this.officeEmployees[characterId];
// Typing indicator göster
const typingIndicator = this.showTypingIndicator(characterId, character.name);
try {
// Karakter kişiliği ve ofis bağlamı + güncel state bilgileri
const characterContext = this.getCharacterContext(characterId);
let contextMessages = [
{ role: 'system', content: `${character.personality}${characterContext}
TOPLANTI BAĞLAMI:
- Toplantı Konusu: ${this.getScenarioDescription()}
- Katılımcılar: ${this.activeEmployees.map(id => this.officeEmployees[id].name).join(', ')}
- Sen ${character.name} olarak rol yapıyorsun (${character.title}).
- Kısa, profesyonel toplantı konuşması yap (1-3 cümle).
- Departmanına ve deneyimine uygun yaklaşım sergile.
- Diğer katılımcılara saygılı şekilde atıfta bulunabilirsin.
- Güncel bilgilerin ve durumun farkındasın.
İLETİŞİM STİLİ: ${character.communication_style}` }
];
// Dialog geçmişini ekle
contextMessages = contextMessages.concat(this.dialogHistory);
// Mevcut mesajı ekle
contextMessages.push({ role: 'user', content: message });
const response = await fetch(`${this.settings.url}/api/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: this.settings.model,
messages: contextMessages,
stream: true,
options: {
temperature: this.settings.temperature + 0.1, // Biraz daha yaratıcı
num_predict: Math.min(this.settings.maxTokens, 200) // Kısa yanıtlar için
}
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Typing indicator'ı kaldır ve karakter mesajı başlat
typingIndicator.remove();
const messageDiv = this.addMessage('', false, new Date(), character.name, characterId);
const messageContent = messageDiv.querySelector('.message-content');
let fullResponse = '';
const reader = response.body.getReader();