-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2258 lines (2005 loc) · 78.1 KB
/
Copy pathapp.js
File metadata and controls
2258 lines (2005 loc) · 78.1 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
const STORAGE_KEY = "lps-state-v1";
const PRIORITY_WEIGHT = {
high: 30,
normal: 16,
low: 8,
};
const DEFAULT_STATE = {
todos: [],
focusSessions: [],
memos: [],
chatHistory: [
{
id: cryptoId(),
role: "assistant",
message: "안녕하세요. 일정, 메모, 건강 상태, 집중 시간을 말해주시면 대화하면서 스케줄을 짜드릴게요.",
createdAt: new Date().toISOString(),
},
],
pendingChat: null,
routines: [
{ id: cryptoId(), name: "운동", checkedDates: [], streak: 0, lastCheckedAt: null },
{ id: cryptoId(), name: "약 복용", checkedDates: [], streak: 0, lastCheckedAt: null },
{ id: cryptoId(), name: "독서", checkedDates: [], streak: 0, lastCheckedAt: null },
],
health: {
sleepHours: 7,
fatigue: 4,
exerciseDone: false,
medsTaken: false,
focusWindowStart: "09:00",
focusWindowEnd: "18:00",
},
timer: {
durationMinutes: 25,
remainingSeconds: 25 * 60,
running: false,
startedAt: null,
activeSessionId: null,
},
activityLog: [],
voiceDraft: "",
aiMode: true,
auth: {
users: [],
currentUser: null,
},
userSettings: {},
llm: {
enabled: false,
provider: "azure",
endpoint: "http://localhost:8787/api/llm/chat",
model: "gpt-4o-mini",
apiKey: "",
dailyLimit: 20,
usageDate: todayKey(),
usageCount: 0,
},
};
const appState = loadState();
let timerTickHandle = null;
const elements = {
todoForm: document.getElementById("todo-form"),
todoTitle: document.getElementById("todo-title"),
todoPriority: document.getElementById("todo-priority"),
todoDue: document.getElementById("todo-due"),
todoTime: document.getElementById("todo-time"),
todoEstimate: document.getElementById("todo-estimate"),
todoNote: document.getElementById("todo-note"),
clearForm: document.getElementById("clear-form"),
healthForm: document.getElementById("health-form"),
sleepHours: document.getElementById("sleep-hours"),
fatigue: document.getElementById("fatigue"),
exerciseDone: document.getElementById("exercise-done"),
medsTaken: document.getElementById("meds-taken"),
focusWindowStart: document.getElementById("focus-window-start"),
focusWindowEnd: document.getElementById("focus-window-end"),
todoList: document.getElementById("todo-list"),
activityList: document.getElementById("activity-list"),
routineList: document.getElementById("routine-list"),
memoForm: document.getElementById("memo-form"),
memoTitle: document.getElementById("memo-title"),
memoBody: document.getElementById("memo-body"),
memoTag: document.getElementById("memo-tag"),
memoPinned: document.getElementById("memo-pinned"),
memoReset: document.getElementById("memo-reset"),
memoClearDone: document.getElementById("memo-clear-done"),
memoList: document.getElementById("memo-list"),
memoCount: document.getElementById("memo-count"),
chatForm: document.getElementById("chat-form"),
chatInput: document.getElementById("chat-input"),
chatThread: document.getElementById("chat-thread"),
chatClear: document.getElementById("chat-clear"),
authForm: document.getElementById("auth-form"),
authUsername: document.getElementById("auth-username"),
authPassword: document.getElementById("auth-password"),
authRegister: document.getElementById("auth-register"),
authLogout: document.getElementById("auth-logout"),
authState: document.getElementById("auth-state"),
settingsPanel: document.querySelector(".settings-panel"),
settingsForm: document.getElementById("settings-form"),
settingsLLMEnabled: document.getElementById("settings-llm-enabled"),
settingsLLMProvider: document.getElementById("settings-llm-provider"),
settingsLLMEndpoint: document.getElementById("settings-llm-endpoint"),
settingsLLMModel: document.getElementById("settings-llm-model"),
settingsLLMApiKey: document.getElementById("settings-llm-api-key"),
settingsLLMApiKeyLabel: document.getElementById("settings-llm-api-key-label"),
settingsLLMDailyLimit: document.getElementById("settings-llm-daily-limit"),
settingsSave: document.getElementById("settings-save"),
llmUsage: document.getElementById("llm-usage"),
llmStatusLabel: document.getElementById("llm-status-label"),
aiList: document.getElementById("ai-list"),
aiSummary: document.getElementById("ai-summary"),
aiConfidence: document.getElementById("ai-confidence"),
aiApply: document.querySelector('[data-action="apply-ai"]'),
recalculateAI: document.getElementById("recalculate-ai-secondary"),
voiceText: document.getElementById("voice-text"),
voicePreview: document.getElementById("voice-preview"),
startVoice: document.getElementById("start-voice"),
applyVoice: document.getElementById("apply-voice"),
timerValue: document.getElementById("timer-value"),
timerState: document.getElementById("timer-state"),
timerStart: document.getElementById("timer-start"),
timerPause: document.getElementById("timer-pause"),
timerReset: document.getElementById("timer-reset"),
timerPresets: Array.from(document.querySelectorAll(".chip-btn[data-duration]")),
todoCount: document.getElementById("todo-count"),
doneCount: document.getElementById("done-count"),
sessionCount: document.getElementById("session-count"),
streakBest: document.getElementById("streak-best"),
statusMessage: document.getElementById("status-message"),
};
(async () => {
await boot();
})();
async function boot() {
const currentUser = appState.auth?.currentUser;
if (currentUser && appState.auth.users.some((item) => item.username === currentUser)) {
loadSettingsForUser(currentUser);
} else {
appState.auth.currentUser = null;
}
// Azure OpenAI 상태 감지
await detectAzureStatus();
bindEvents();
syncFormFromState();
renderAll();
updateVoicePreview();
if (appState.timer.running) {
startTimerTick();
}
}
async function detectAzureStatus() {
try {
const response = await fetch("http://localhost:8787/health");
if (response.ok) {
const data = await response.json();
if (data?.providers?.azure?.configured) {
appState.llm.provider = "azure";
appState.llm.endpoint = "http://localhost:8787/api/llm/chat";
const statusLabel = document.getElementById('llm-status-label');
if (statusLabel) {
statusLabel.textContent = '✓ Azure OpenAI 연결됨';
statusLabel.style.color = '#4caf50';
}
persistState();
return;
}
}
} catch (e) {
console.log('Azure detection error:', e.message);
}
// Azure 미설정 또는 오류
const statusLabel = document.getElementById('llm-status-label');
if (statusLabel) {
statusLabel.textContent = 'Azure OpenAI 설정 필요';
statusLabel.style.color = '#ff9800';
}
}
function bindEvents() {
elements.todoForm.addEventListener("submit", handleTodoSubmit);
elements.clearForm.addEventListener("click", resetTodoForm);
if (elements.chatForm) {
elements.chatForm.addEventListener("submit", handleChatSubmit);
}
if (elements.chatClear) {
elements.chatClear.addEventListener("click", clearChatHistory);
}
if (elements.authForm) {
elements.authForm.addEventListener("submit", handleAuthLogin);
}
if (elements.authRegister) {
elements.authRegister.addEventListener("click", handleAuthRegister);
}
if (elements.authLogout) {
elements.authLogout.addEventListener("click", handleAuthLogout);
}
if (elements.settingsForm) {
elements.settingsForm.addEventListener("submit", handleSettingsSave);
}
if (elements.settingsLLMProvider) {
elements.settingsLLMProvider.addEventListener("change", handleProviderChange);
}
if (elements.memoForm) {
elements.memoForm.addEventListener("submit", handleMemoSubmit);
}
if (elements.memoReset) {
elements.memoReset.addEventListener("click", resetMemoForm);
}
if (elements.memoClearDone) {
elements.memoClearDone.addEventListener("click", clearAllMemos);
}
[
elements.sleepHours,
elements.fatigue,
elements.exerciseDone,
elements.medsTaken,
elements.focusWindowStart,
elements.focusWindowEnd,
].forEach((element) => {
element.addEventListener("input", handleHealthChange);
element.addEventListener("change", handleHealthChange);
});
elements.recalculateAI.addEventListener("click", () => {
renderAI();
showStatus("AI 추천을 다시 계산했습니다.", "info");
addLog("ai", "AI 추천을 다시 계산함");
});
if (elements.aiApply) {
elements.aiApply.addEventListener("click", applyAIOrdering);
}
elements.startVoice.addEventListener("click", startVoiceRecognition);
elements.applyVoice.addEventListener("click", applyVoiceDraft);
elements.voiceText.addEventListener("input", () => {
appState.voiceDraft = elements.voiceText.value;
updateVoicePreview();
persistState();
});
elements.timerStart.addEventListener("click", startTimer);
elements.timerPause.addEventListener("click", pauseTimer);
elements.timerReset.addEventListener("click", resetTimer);
elements.timerPresets.forEach((button) => {
button.addEventListener("click", () => {
const minutes = Number(button.dataset.duration);
setTimerDuration(minutes);
elements.timerPresets.forEach((presetButton) => presetButton.classList.toggle("is-active", presetButton === button));
showStatus(`${minutes}분 타이머로 설정했습니다.`, "info");
addLog("timer", `${minutes}분 프리셋 선택`);
});
});
document.querySelectorAll(".routine-btn").forEach((button) => {
button.addEventListener("click", () => {
toggleRoutine(button.dataset.routine);
});
});
elements.todoList.addEventListener("click", handleTodoActions);
elements.activityList.addEventListener("click", handleActivityActions);
elements.routineList.addEventListener("click", handleRoutineActions);
if (elements.memoList) {
elements.memoList.addEventListener("click", handleMemoActions);
}
}
async function handleChatSubmit(event) {
event.preventDefault();
const message = elements.chatInput.value.trim();
if (!message) {
showStatus("메시지를 입력해 주세요.", "warning");
return;
}
pushChatMessage("user", message);
elements.chatInput.value = "";
const response = await resolveChatResponse(message);
if (Array.isArray(response.actions)) {
response.actions.forEach((action) => {
if (action.type === "todo") {
appState.todos.unshift(action.todo);
addLog("todo", `챗봇 추가: ${action.todo.title}`);
}
if (action.type === "memo") {
appState.memos.unshift(action.memo);
appState.memos = sortMemos(appState.memos);
addLog("memo", `챗봇 메모 저장: ${action.memo.title}`);
}
if (action.type === "health") {
appState.health = {
...appState.health,
...action.health,
};
}
if (action.type === "chat-clear-pending") {
appState.pendingChat = null;
}
if (action.type === "chat-pending") {
appState.pendingChat = action.pending;
}
});
}
if (response.todo) {
appState.todos.unshift(response.todo);
addLog("todo", `챗봇 추가: ${response.todo.title}`);
}
if (response.memo) {
appState.memos.unshift(response.memo);
appState.memos = sortMemos(appState.memos);
addLog("memo", `챗봇 메모 저장: ${response.memo.title}`);
}
if (response.pending) {
appState.pendingChat = response.pending;
}
if (response.health) {
appState.health = {
...appState.health,
...response.health,
};
updateRangeLabels();
}
pushChatMessage("assistant", response.message, response.meta);
console.log("[DEBUG] After pushChatMessage, chatHistory:", appState.chatHistory?.length);
persistState();
console.log("[DEBUG] Calling renderAll()");
renderAll();
console.log("[DEBUG] After renderAll, threadHTML:", document.querySelector('#chat-thread')?.innerHTML?.substring(0, 50));
if (response.message) {
showStatus(response.message, response.tone || "info");
}
}
async function resolveChatResponse(message) {
if (!appState.llm?.enabled) {
return generateChatResponse(message);
}
refreshLLMQuotaForToday();
if ((appState.llm.usageCount || 0) >= (appState.llm.dailyLimit || 20)) {
const fallback = generateChatResponse(message);
fallback.meta = [...(fallback.meta || []), `오늘 LLM 한도 ${appState.llm.dailyLimit}회 사용 완료`];
fallback.tone = "warning";
showStatus(`오늘 LLM 한도(${appState.llm.dailyLimit}회)를 모두 사용해 규칙 엔진으로 답변했습니다.`, "warning");
addLog("chat", `LLM 일일 한도 도달 (${appState.llm.usageCount}/${appState.llm.dailyLimit})`);
return fallback;
}
try {
const llmResponse = await requestLLMResponse(message);
if (llmResponse?.message) {
appState.llm.usageCount = (appState.llm.usageCount || 0) + 1;
persistState();
return llmResponse;
}
} catch (error) {
console.warn("LLM response failed, fallback to rules", error);
addLog("chat", "LLM 호출 실패로 규칙 엔진으로 전환");
showStatus("LLM 연결이 실패해 규칙 엔진으로 답변했습니다.", "warning");
}
return generateChatResponse(message);
}
async function requestLLMResponse(message) {
const endpoint = normalizeText(appState.llm?.endpoint || "");
if (!endpoint) {
throw new Error("LLM endpoint is empty");
}
const recent = appState.chatHistory.slice(0, 10).reverse().map((item) => ({
role: item.role === "assistant" ? "assistant" : "user",
content: item.message,
}));
const context = {
now: new Date().toISOString(),
pendingChat: appState.pendingChat,
health: appState.health,
todosTop: appState.todos.slice(0, 6).map((todo) => ({
title: todo.title,
dueDate: todo.dueDate,
dueTime: todo.dueTime,
priority: todo.priority,
estimateMinutes: todo.estimateMinutes,
})),
};
const payload = {
provider: appState.llm.provider || "azure",
model: appState.llm.model || "gpt-4o-mini",
apiKey: appState.llm.apiKey || "",
messages: [
{
role: "system",
content: [
"당신은 일정/메모/건강 코치 역할의 한국어 비서입니다.",
"반드시 JSON만 출력하세요. 코드블록 사용 금지.",
"스키마: {message:string,tone:'info'|'success'|'warning'|'danger',meta:string[],todo?:object,memo?:object,health?:object,pending?:object,actions?:array}",
"사용자 의도가 일정 추가가 아니면 날짜/시간을 강요하지 마세요.",
"부상/복용/날씨 질문은 조언형 답변으로 처리하세요.",
"todo 생성 시 필수: title,dueDate(YYYY-MM-DD),dueTime(HH:MM),priority(high|normal|low),estimateMinutes,note.",
"memo 생성 시 필수: title,body,tag(general|work|health|idea|study).",
].join(" "),
},
{
role: "system",
content: `앱 상태 컨텍스트: ${JSON.stringify(context)}`,
},
...recent,
{
role: "user",
content: message,
},
],
temperature: 0.3,
max_tokens: 520,
};
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
if (!response.ok) {
const text = await response.text();
throw new Error(`LLM endpoint error ${response.status}: ${text.slice(0, 200)}`);
}
const data = await response.json();
const parsed = normalizeLLMResponse(data);
return parsed;
}
function normalizeLLMResponse(data) {
// 프록시 응답 우선 처리: data.content
let rawText = "";
if (data?.content) {
rawText = data.content;
} else if (typeof data?.message === "string") {
rawText = data.message;
} else if (data?.output) {
rawText = data.output;
}
const json = safeJsonParse(extractJsonObject(rawText));
if (!json || typeof json !== "object") {
return { message: normalizeText(rawText) || "응답을 이해하지 못해 기본 모드로 처리합니다.", tone: "info" };
}
const tone = ["info", "success", "warning", "danger"].includes(json.tone) ? json.tone : "info";
const meta = Array.isArray(json.meta) ? json.meta.map((item) => normalizeText(String(item))).filter(Boolean).slice(0, 4) : [];
const normalized = {
message: normalizeText(String(json.message || "")) || "응답을 생성했습니다.",
tone,
meta,
};
if (json.todo && typeof json.todo === "object") {
normalized.todo = {
id: cryptoId(),
title: normalizeText(String(json.todo.title || "새 일정")),
priority: ["high", "normal", "low"].includes(json.todo.priority) ? json.todo.priority : "normal",
dueDate: normalizeText(String(json.todo.dueDate || "")) || null,
dueTime: normalizeText(String(json.todo.dueTime || "")) || null,
estimateMinutes: clampNumber(Number(json.todo.estimateMinutes || 30), 5, 480),
note: normalizeText(String(json.todo.note || "AI 챗봇으로 추가됨")),
completed: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
source: "chatbot-llm",
};
}
if (json.memo && typeof json.memo === "object") {
const body = normalizeText(String(json.memo.body || ""));
normalized.memo = {
id: cryptoId(),
title: normalizeText(String(json.memo.title || makeShortTitle(body) || "대화 메모")),
body,
tag: ["general", "work", "health", "idea", "study"].includes(json.memo.tag) ? json.memo.tag : "general",
pinned: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
}
if (json.health && typeof json.health === "object") {
normalized.health = {
fatigue: json.health.fatigue != null ? clampNumber(Number(json.health.fatigue), 1, 10) : appState.health.fatigue,
sleepHours: json.health.sleepHours != null ? clampNumber(Number(json.health.sleepHours), 0, 12) : appState.health.sleepHours,
exerciseDone: json.health.exerciseDone != null ? Boolean(json.health.exerciseDone) : appState.health.exerciseDone,
medsTaken: json.health.medsTaken != null ? Boolean(json.health.medsTaken) : appState.health.medsTaken,
focusWindowStart: normalizeText(String(json.health.focusWindowStart || appState.health.focusWindowStart)),
focusWindowEnd: normalizeText(String(json.health.focusWindowEnd || appState.health.focusWindowEnd)),
};
}
if (json.pending && typeof json.pending === "object") {
normalized.pending = json.pending;
}
if (Array.isArray(json.actions)) {
normalized.actions = json.actions;
}
return normalized;
}
function extractJsonObject(rawText) {
const text = String(rawText || "").trim();
if (!text) return "{}";
const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
if (fenced?.[1]) return fenced[1].trim();
const start = text.indexOf("{");
const end = text.lastIndexOf("}");
if (start >= 0 && end > start) {
return text.slice(start, end + 1);
}
return text;
}
function safeJsonParse(text) {
try {
return JSON.parse(text);
} catch {
return null;
}
}
function handleAuthLogin(event) {
event.preventDefault();
const username = normalizeText(elements.authUsername?.value || "").toLowerCase();
const password = elements.authPassword?.value || "";
if (!username || !password) {
showStatus("아이디와 비밀번호를 입력해 주세요.", "warning");
return;
}
const user = appState.auth.users.find((item) => item.username === username);
if (!user || user.passwordHash !== simpleHash(password)) {
showStatus("로그인에 실패했습니다. 계정을 확인해 주세요.", "danger");
return;
}
appState.auth.currentUser = username;
loadSettingsForUser(username);
persistState();
renderAll();
showStatus(`${username} 계정으로 로그인했습니다.`, "success");
addLog("chat", `로그인: ${username}`);
}
function handleAuthRegister() {
const username = normalizeText(elements.authUsername?.value || "").toLowerCase();
const password = elements.authPassword?.value || "";
if (!username || !password) {
showStatus("회원 생성을 위해 아이디와 비밀번호를 입력해 주세요.", "warning");
return;
}
if (appState.auth.users.some((item) => item.username === username)) {
showStatus("이미 존재하는 아이디입니다.", "warning");
return;
}
appState.auth.users.push({
id: cryptoId(),
username,
passwordHash: simpleHash(password),
createdAt: new Date().toISOString(),
});
appState.auth.currentUser = username;
loadSettingsForUser(username);
persistState();
renderAll();
showStatus(`${username} 계정을 생성하고 로그인했습니다.`, "success");
addLog("chat", `회원 생성: ${username}`);
}
function handleAuthLogout() {
if (!appState.auth.currentUser) {
showStatus("이미 로그아웃 상태입니다.", "warning");
return;
}
appState.auth.currentUser = null;
appState.pendingChat = null;
persistState();
renderAll();
showStatus("로그아웃되었습니다.", "info");
}
function handleSettingsSave(event) {
event.preventDefault();
if (!appState.auth.currentUser) {
showStatus("설정 저장은 로그인 후 가능합니다.", "warning");
return;
}
refreshLLMQuotaForToday();
appState.llm = {
...appState.llm,
enabled: Boolean(elements.settingsLLMEnabled?.checked),
provider: "azure",
endpoint: normalizeText(elements.settingsLLMEndpoint?.value || ""),
model: normalizeText(elements.settingsLLMModel?.value || "") || "gpt-4o-mini",
apiKey: normalizeText(elements.settingsLLMApiKey?.value || ""),
dailyLimit: clampNumber(Number(elements.settingsLLMDailyLimit?.value || appState.llm.dailyLimit || 20), 1, 500, 20),
};
saveSettingsForCurrentUser();
persistState();
renderLLMUsage();
const modeLabel = appState.llm.enabled ? "활성화" : "비활성화";
showStatus(`설정을 저장했습니다. LLM ${modeLabel} 상태입니다.`, "info");
addLog("chat", `설정 저장: ${appState.auth.currentUser}`);
}
function loadSettingsForUser(username) {
const saved = appState.userSettings?.[username]?.llm || {};
appState.llm = {
...DEFAULT_STATE.llm,
...saved,
};
refreshLLMQuotaForToday();
}
function saveSettingsForCurrentUser() {
const username = appState.auth.currentUser;
if (!username) return;
if (!appState.userSettings || typeof appState.userSettings !== "object") {
appState.userSettings = {};
}
appState.userSettings[username] = {
llm: {
...appState.llm,
},
updatedAt: new Date().toISOString(),
};
}
function handleProviderChange() {
const provider = elements.settingsLLMProvider?.value || "azure";
if (elements.settingsLLMApiKeyLabel) {
elements.settingsLLMApiKeyLabel.style.display = provider === "azure" ? "grid" : "none";
}
}
function renderProviderUI() {
const provider = elements.settingsLLMProvider?.value || "azure";
if (elements.settingsLLMApiKeyLabel) {
elements.settingsLLMApiKeyLabel.style.display = provider === "azure" ? "grid" : "none";
}
}
let hash = 0;
const value = String(text || "");
for (let index = 0; index < value.length; index += 1) {
hash = ((hash << 5) - hash + value.charCodeAt(index)) | 0;
}
return String(hash);
}
function refreshLLMQuotaForToday() {
if (!appState.llm) return;
const today = todayKey();
if (appState.llm.usageDate !== today) {
appState.llm.usageDate = today;
appState.llm.usageCount = 0;
}
}
function renderLLMUsage() {
if (!elements.llmUsage) return;
if (!appState.auth?.currentUser) {
elements.llmUsage.textContent = "로그인 후 사용량이 표시됩니다.";
return;
}
refreshLLMQuotaForToday();
const used = appState.llm?.usageCount || 0;
const limit = appState.llm?.dailyLimit || 20;
elements.llmUsage.textContent = `오늘 LLM 사용 ${used}/${limit}`;
}
function clearChatHistory() {
appState.chatHistory = [
{
id: cryptoId(),
role: "assistant",
message: "대화를 초기화했습니다. 다시 일정을 말해 주세요.",
createdAt: new Date().toISOString(),
},
];
appState.pendingChat = null;
persistState();
renderAll();
showStatus("챗봇 대화를 초기화했습니다.", "warning");
}
function pushChatMessage(role, message, meta = []) {
appState.chatHistory.unshift({
id: cryptoId(),
role,
message,
meta,
createdAt: new Date().toISOString(),
});
appState.chatHistory = appState.chatHistory.slice(0, 30);
}
function renderChat() {
const chatThread = document.querySelector('#chat-thread');
if (!chatThread) return;
const items = appState.chatHistory.slice(0, 12).reverse();
chatThread.innerHTML = items.map((item) => {
const role = item.role === "assistant" ? "AI" : item.role === "system" ? "안내" : "나";
const meta = item.meta?.length ? `<div class="memo-meta">${item.meta.map(t => `<span>${escapeHtml(t)}</span>`).join("")}</div>` : "";
return `<article class="chat-message ${escapeHtml(item.role)}">
<div class="chat-message-head"><strong>${role}</strong><span class="subtle">${formatRelativeTime(item.createdAt)}</span></div>
<div class="chat-message-body">${escapeHtml(item.message)}</div>${meta}</article>`;
}).join("");
}
function generateChatResponse(message) {
const normalized = normalizeText(message);
const lower = normalized.toLowerCase();
const hasPending = Boolean(appState.pendingChat);
if (isInjuryExerciseQuestion(normalized)) {
return {
message: buildInjuryExerciseGuidance(normalized),
tone: "warning",
meta: ["부상 상태 우선", "무리 없는 운동 권장"],
};
}
if (isMedicationGuidanceText(normalized)) {
return {
message: buildMedicationGuidance(normalized),
tone: "info",
meta: ["약 복용 안내", "처방전 우선 확인"],
};
}
if (hasPending) {
return resolvePendingChat(normalized, appState.pendingChat);
}
if (/(오늘|이번주|스케줄|일정|계획).*(짜|정리|만들)/.test(normalized)) {
const ranked = scoreTodos();
const nextItem = ranked[0]?.todo;
const focusAdvice = buildFocusAdvice();
return {
message: nextItem
? `오늘은 ${nextItem.title}부터 시작하는 게 좋겠습니다.\n${focusAdvice}\n원하면 "30분 단위로 짜줘"처럼 말해 더 세분화할 수 있어요.`
: `아직 일정이 비어 있습니다. 할 일, 메모, 건강 상태를 말해주시면 함께 계획을 짜드릴게요.\n${focusAdvice}`,
meta: nextItem ? [
`추천 1순위: ${nextItem.title}`,
`예상 ${nextItem.estimateMinutes}분`,
] : ["일정 초안 없음"],
tone: "info",
};
}
if (/피곤|피로|졸리|잠/.test(lower)) {
return {
message: "피로가 높을 때는 고부하 작업을 뒤로 미루고, 20~30분짜리 가벼운 작업을 먼저 두는 편이 좋습니다. 필요한 경우 오늘 일정을 줄여드릴게요.",
health: { fatigue: Math.min(10, Math.max(appState.health.fatigue, 7)) },
tone: "warning",
meta: ["고부하 작업 뒤로 이동", "짧은 작업 우선"],
};
}
if (/날씨|기온|온도|비|강수|흐림|맑음|우산/.test(lower) && !/(일정|계획|할 일|메모|추가|등록|짜|정리|만들)/.test(lower)) {
return {
message: "이 앱은 실시간 날씨를 직접 가져오지 못합니다. 날씨를 알려주시면 조깅하기 좋은지, 실내 운동으로 바꿀지 기준을 같이 정리해드릴게요.",
tone: "info",
meta: ["날씨 입력 후 조깅 판단", "실내 운동 대안 가능"],
};
}
if (/수면|잠을.?못|잠이.?적/.test(lower)) {
return {
message: "수면이 부족한 날은 집중 블록을 짧게 쪼개고, 쉬운 일부터 처리하는 편이 안정적입니다. 수면 상태를 반영해 추천 순서를 다시 계산했습니다.",
health: { sleepHours: Math.min(appState.health.sleepHours, 5.5) },
tone: "warning",
meta: ["짧은 집중 블록 추천", "쉬운 일 먼저"],
};
}
if (/(먹을|먹어|먹는|마실|마셔|복용|섭취).*(언제|몇 시|어느|조금|바로)/.test(lower) && !/(일정|계획|할 일|메모|추가|등록|짜|정리|만들)/.test(lower)) {
return {
message: "실시간 건강 정보는 없어서 정확한 식사 시간은 단정할 수 없지만, 보통은 아침 식사 후나 오후 간식 시간처럼 부담이 적은 때가 무난합니다. 속이 비어 있거나 운동 전후라면 그 조건도 같이 말해주면 더 맞게 조언할 수 있어요.",
tone: "info",
meta: ["식사/복용 시간 조언", "조건을 주면 더 구체화 가능"],
};
}
if (/메모|기억|남겨/.test(lower)) {
const memo = buildMemoFromChat(normalized);
return {
message: `메모로 정리해 두었습니다: ${memo.title}`,
memo,
tone: "success",
meta: [memo.tag === "idea" ? "아이디어 메모" : "빠른 메모"],
};
}
const parsed = parseScheduleFromChat(normalized);
if (parsed.intent === "todo") {
if (parsed.missing.length) {
return {
message: `좋아요. ${parsed.baseTitle || "일정"}을/를 추가하려고 합니다. ${parsed.missing.join(" 그리고 ")}만 알려주면 바로 초안을 만들어드릴게요.`,
pending: {
type: "todo",
baseTitle: parsed.baseTitle,
missing: parsed.missing,
draft: parsed.draft,
},
tone: "info",
meta: ["추가 정보 대기"],
};
}
return {
message: `일정을 추가했습니다. ${parsed.todo.title}\n원하시면 "오늘 일정 짜줘"라고 말해 우선순위를 다시 맞춰드릴 수 있어요.`,
todo: parsed.todo,
tone: "success",
meta: [
parsed.todo.dueDate ? `날짜 ${parsed.todo.dueDate}` : "날짜 미지정",
parsed.todo.dueTime ? `시간 ${parsed.todo.dueTime}` : "시간 미지정",
],
};
}
if (/오늘.*정리|우선순위|추천/.test(normalized)) {
const ranked = scoreTodos();
const top = ranked[0]?.todo;
return {
message: top
? `지금 가장 먼저 할 일은 ${top.title} 입니다.\n건강 상태와 마감일을 함께 고려해 전체 순서를 정리해 두었습니다.`
: "아직 정리할 할 일이 없습니다. 먼저 하고 싶은 일을 말해 주세요.",
tone: "info",
meta: ranked.slice(0, 3).map((item) => item.todo.title),
};
}
if (/도와|어떻게|뭐부터|추천/.test(lower)) {
return {
message: `원하시는 방식으로 도와드릴게요.\n1. "내일 3시에 회의 추가"처럼 말하면 일정으로 바꿉니다.\n2. "오늘 일정 짜줘"라고 말하면 우선순위를 정리합니다.\n3. "피곤하니까 가볍게"라고 말하면 컨디션을 반영합니다.`,
tone: "info",
};
}
return {
message: `들으신 내용은 "${normalized}" 입니다.\n일정으로 만들려면 날짜와 시간을 함께 말해 주세요. 예: "내일 오전 9시에 회의"`,
pending: null,
tone: "info",
};
}
function parseScheduleFromChat(text) {
const normalized = normalizeText(text);
const result = {
intent: "todo",
baseTitle: normalized,
missing: [],
draft: null,
todo: null,
};
const dateMatch = normalized.match(/(오늘|내일|모레|그저께)/);
const timeMatch = normalized.match(/(오전|오후)?\s*(\d{1,2})(?:[:시](\d{1,2}))?\s*(?:분)?/);
const title = cleanupChatText(normalized)
.replace(/(추가해?줘|만들어?줘|넣어?줘|적어?줘|등록해?줘|정리해?줘|보여?줘|해줘|해 줘|줘)/g, "")
.replace(/(일정|할 일|메모|계획)/g, "")
.replace(/\s+/g, " ")
.trim();
const dueDate = dateMatch ? relativeDateKey(dateMatch[1]) : null;
const dueTime = timeMatch ? normalizeTimeMatch(timeMatch[1], timeMatch[2], timeMatch[3]) : null;
if (!dueDate) result.missing.push("날짜");
if (!dueTime) result.missing.push("시간");
if (!title) result.missing.push("제목");
result.baseTitle = title || normalized;
if (!result.missing.length) {
result.todo = {
id: cryptoId(),
title,
priority: appState.health.fatigue >= 7 ? "normal" : "high",
dueDate,
dueTime,
estimateMinutes: 30,
note: "AI 챗봇으로 추가됨",
completed: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
source: "chatbot",
};
}
return result;
}
function resolvePendingChat(text, pending) {
if (pending.type !== "todo") {
appState.pendingChat = null;
return {
message: "대기 중인 요청을 처리할 수 없어 초기화했습니다.",
tone: "warning",
};
}
if (isInjuryExerciseQuestion(text)) {
appState.pendingChat = null;
return {
message: buildInjuryExerciseGuidance(text),
tone: "warning",
meta: ["부상 상태 우선", "대기 요청 초기화"],
};
}
if (isMedicationGuidanceText(text)) {
appState.pendingChat = null;
return {
message: buildMedicationGuidance(text),
tone: "info",
meta: ["약 복용 안내", "대기 요청 초기화"],
};
}
if (/날씨|기온|온도|비|강수|흐림|맑음|우산/.test(text) && !/(일정|계획|할 일|메모|추가|등록|짜|정리|만들)/.test(text)) {
appState.pendingChat = null;
return {
message: "이 앱은 실시간 날씨를 직접 가져오지 못합니다. 날씨를 알려주시면 조깅해도 되는지 바로 같이 판단해드릴게요.",
tone: "info",
meta: ["날씨 입력 후 조깅 판단", "대기 요청 초기화"],
};
}
const draft = pending.draft || {};
let { baseTitle } = pending;
let dueDate = draft.dueDate || null;
let dueTime = draft.dueTime || null;
const dateMatch = text.match(/(오늘|내일|모레|그저께)/);
const timeMatch = text.match(/(오전|오후)?\s*(\d{1,2})(?:[:시](\d{1,2}))?\s*(?:분)?/);
if (dateMatch) {
dueDate = relativeDateKey(dateMatch[1]);
}
if (timeMatch) {
dueTime = normalizeTimeMatch(timeMatch[1], timeMatch[2], timeMatch[3]);
}
const cleaned = normalizeText(
text
.replace(/(오늘|내일|모레|그저께)/g, "")
.replace(/(오전|오후|새벽|아침|점심|저녁|밤)/g, "")
.replace(/\d{1,2}\s*(?:[:시]\s*\d{1,2})?\s*시?\s*(?:분)?\s*에?/g, "")
.replace(/(추가|만들어|넣어줘|적어줘|등록|그리고|와|및)/g, "")
);
if (cleaned && cleaned.length > 1) {
baseTitle = cleaned;
}
if (!dueDate) {
appState.pendingChat = {