-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcouple-space.js
More file actions
2081 lines (1806 loc) · 92.1 KB
/
couple-space.js
File metadata and controls
2081 lines (1806 loc) · 92.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
// Couple Space Core & UI - Phase 0, 1, 2
// Phase 0: Data Structure & Utils
// Phase 1: UI Framework
// Phase 2: Refresh Logic & Mock Data
(function (global) {
// ==================== Constants & Keys ====================
const KEYS = {
COUPLE_SPACE: 'vibe_couple_space',
COUPLE_MEMORY: 'vibe_couple_memory_bank',
CONTACTS: 'vibe_contacts',
TRAVEL_CARDS_PREFIX: 'travelCards_'
};
// ==================== Storage Helpers ====================
function safeParse(raw, fallback) {
if (!raw) return fallback;
try {
const data = JSON.parse(raw);
return data == null ? fallback : data;
} catch (e) {
console.error('JSON parse error:', e);
return fallback;
}
}
function getStorage(key, fallback = {}) {
return safeParse(localStorage.getItem(key), fallback);
}
function setStorage(key, data) {
localStorage.setItem(key, JSON.stringify(data));
}
// ==================== Core Data Logic (Phase 0) ====================
const CoupleSpace = {
// --- Data Access ---
loadCoupleSpace: function(contactId) {
const store = getStorage(KEYS.COUPLE_SPACE);
const key = String(contactId);
if (!store[key]) {
store[key] = {
settings: this._getDefaultSpaceSettings(),
days: {}
};
setStorage(KEYS.COUPLE_SPACE, store);
} else {
store[key].settings = { ...this._getDefaultSpaceSettings(), ...store[key].settings };
}
return store[key];
},
saveCoupleSpace: function(contactId, data) {
const store = getStorage(KEYS.COUPLE_SPACE);
store[String(contactId)] = data;
setStorage(KEYS.COUPLE_SPACE, store);
},
_getDefaultSpaceSettings: function() {
return {
timeBlocks: {
morning: { time: '08:00', modules: ['sleep', 'bowel', 'meals_breakfast'] },
noon: { time: '13:00', modules: ['meals_lunch', 'mood_am'] },
evening: { time: '19:00', modules: ['meals_dinner', 'exercise'] },
night: { time: '22:00', modules: ['finance', 'diary', 'summary', 'mood_pm'] }
},
autoBackfillDays: 0,
moodEmojiScheme: {
"开心": "😄",
"平淡": "😐",
"难过": "😢",
"生气": "😠",
"兴奋": "🤩"
}
};
},
loadCoupleMemoryBank: function(contactId) {
const store = getStorage(KEYS.COUPLE_MEMORY);
const key = String(contactId);
if (!store[key]) {
store[key] = {
daily: [],
weekly: [],
monthly: [],
yearly: [],
settings: {
injectDaily: 3,
injectWeekly: 1,
injectMonthly: 1,
injectYearly: 1
}
};
setStorage(KEYS.COUPLE_MEMORY, store);
}
return store[key];
},
saveCoupleMemoryBank: function(contactId, data) {
const store = getStorage(KEYS.COUPLE_MEMORY);
store[String(contactId)] = data;
setStorage(KEYS.COUPLE_MEMORY, store);
},
getContactInfo: function(contactId) {
const contacts = getStorage(KEYS.CONTACTS, []);
// Use loose comparison for ID as it might be number or string
return contacts.find(c => String(c.id) === String(contactId)) || null;
},
getAllContacts: function() {
return getStorage(KEYS.CONTACTS, []);
},
getTravelData: function(contactId, dateStr) {
const key = `${KEYS.TRAVEL_CARDS_PREFIX}${contactId}`;
const cards = getStorage(key, {});
return cards[dateStr] || null;
},
// --- Timezone Utilities ---
getCharNow: function(contact) {
if (!contact) return new Date();
let timezone = 'Asia/Shanghai';
if (contact.timezoneSettings) {
if (contact.timezoneSettings.mode === 'different' && contact.timezoneSettings.aiTimezone) {
timezone = contact.timezoneSettings.aiTimezone;
} else if (contact.timezoneSettings.mode === 'same' && contact.timezoneSettings.sharedTimezone) {
timezone = contact.timezoneSettings.sharedTimezone;
}
}
const now = new Date();
const fmt = new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false
});
const parts = fmt.formatToParts(now);
const partMap = {};
parts.forEach(p => partMap[p.type] = p.value);
return new Date(
parseInt(partMap.year),
parseInt(partMap.month) - 1,
parseInt(partMap.day),
parseInt(partMap.hour),
parseInt(partMap.minute),
parseInt(partMap.second)
);
},
getCharDateStr: function(contact, now = new Date()) {
if (!contact) {
const y = now.getFullYear();
const m = String(now.getMonth() + 1).padStart(2, '0');
const d = String(now.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
let timezone = 'Asia/Shanghai';
if (contact.timezoneSettings) {
if (contact.timezoneSettings.mode === 'different' && contact.timezoneSettings.aiTimezone) {
timezone = contact.timezoneSettings.aiTimezone;
} else if (contact.timezoneSettings.mode === 'same' && contact.timezoneSettings.sharedTimezone) {
timezone = contact.timezoneSettings.sharedTimezone;
}
}
const fmt = new Intl.DateTimeFormat('en-CA', {
timeZone: timezone,
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
return fmt.format(now);
},
// --- Memory Bank Logic ---
// Add memory to bank
addMemory: function(contactId, type, content, dateStr) {
const bank = this.loadCoupleMemoryBank(contactId);
const list = bank[type] || [];
// Check if already exists for this date/id to avoid dupes?
// For daily, key is date. For others, maybe ID or range.
// Let's just append for now, or check date.
const existingIndex = list.findIndex(m => m.date === dateStr);
if (existingIndex >= 0) {
list[existingIndex].content = content;
list[existingIndex].updatedAt = new Date().toISOString();
} else {
list.push({
id: Date.now().toString(),
date: dateStr,
content: content,
active: true, // Default active
createdAt: new Date().toISOString()
});
}
// Sort by date desc
list.sort((a, b) => new Date(b.date) - new Date(a.date));
this.saveCoupleMemoryBank(contactId, bank);
},
getMemories: function(contactId, type) {
const bank = this.loadCoupleMemoryBank(contactId);
return bank[type] || [];
},
upgradeMemories: async function(contactId, fromType, selectedIds) {
const bank = this.loadCoupleMemoryBank(contactId);
const sourceList = bank[fromType] || [];
const selectedItems = sourceList.filter(m => selectedIds.includes(m.id));
if (selectedItems.length === 0) return null;
const contact = this.getContactInfo(contactId);
// Call AI to summarize
const content = selectedItems.map(m => `[${m.date}] ${m.content}`).join('\n');
const prompt = `Summarize these ${fromType} memories into a single ${this._getNextLevel(fromType)} summary. Keep it concise (under 100 words). Focus on key events and emotional shifts.\n\n${content}`;
// Use callAI generic or raw fetch? callAI expects module. Let's add a 'memory_upgrade' module or just raw fetch here.
// I'll reuse callAI with a special module name or just do raw fetch to keep it simple within CoupleSpace object?
// Let's extend callAI to handle custom prompts if needed, or just add 'memory_upgrade' case.
const summary = await this.callAI('memory_upgrade', contact, new Date().toISOString().split('T')[0], prompt);
if (summary && summary.content) {
const nextLevel = this._getNextLevel(fromType);
const dateStr = new Date().toISOString().split('T')[0]; // Use current date for the upgrade action
this.addMemory(contactId, nextLevel, summary.content, dateStr);
// Deactivate source memories? User requirement: "Generated: daily active=false, weekly active=true".
selectedItems.forEach(m => m.active = false);
this.saveCoupleMemoryBank(contactId, bank);
return true;
}
return false;
},
_getNextLevel: function(level) {
if (level === 'daily') return 'weekly';
if (level === 'weekly') return 'monthly';
if (level === 'monthly') return 'yearly';
return 'yearly';
},
// --- Mock Data Generators (Phase 2) ---
generateMockData: function(module, contact) {
// Keep original mock data logic as fallback
switch(module) {
case 'sleep':
const sleepHours = 6 + Math.random() * 3; // 6-9 hours
return {
duration: sleepHours.toFixed(1),
quality: ['Deep', 'Light', 'Restless'][Math.floor(Math.random() * 3)],
bedtime: '23:30',
wakeup: '07:30',
summary: 'Sleep was okay.'
};
case 'bowel':
const hasPoop = Math.random() > 0.3;
return {
count: hasPoop ? 1 : 0,
type: hasPoop ? ['Normal', 'Hard', 'Soft'][Math.floor(Math.random() * 3)] : null,
time: hasPoop ? '08:30' : null
};
case 'exercise':
const steps = Math.floor(Math.random() * 10000);
const hasExercise = Math.random() > 0.5;
return {
steps: steps,
workout: hasExercise ? 'Running 30min' : 'None',
calories: hasExercise ? 300 : 0
};
case 'meals':
return {
breakfast: 'Toast & Coffee',
lunch: 'Salad',
dinner: 'Steak',
score: Math.floor(Math.random() * 5) + 1
};
case 'finance':
return {
spent: (Math.random() * 200).toFixed(2),
items: [{ item: 'Coffee', cost: 5.5 }, { item: 'Lunch', cost: 15 }]
};
case 'mood':
const moods = ['开心', '平淡', '难过', '生气', '兴奋'];
return {
mood: moods[Math.floor(Math.random() * moods.length)],
reason: 'Nothing special.'
};
case 'diary':
return {
title: 'A regular day',
content: 'Today was just a normal day. Worked a bit, ate some food.',
style: 'Casual'
};
default:
return {};
}
},
// --- AI Integration (Phase 3) ---
callAI: async function(module, contact, dateStr, customPrompt) {
console.log(`[AI] Generating ${module} for ${contact && contact.name} on ${dateStr}...`);
console.log('[AI] contact info (id, apiScheme, model):', contact && { id: contact.id, apiScheme: contact.apiScheme, model: contact.model });
// Get API Config
let apiUrl = localStorage.getItem('apiUrl');
let apiKey = localStorage.getItem('apiKey');
let model = contact.model || localStorage.getItem('selectedModel');
// Use contact's API scheme if available (Primary Source)
let selectedScheme = null;
// Explicitly load contacts again to ensure we have the latest apiScheme
const contacts = CoupleSpace.getAllContacts();
const freshContact = contacts.find(c => String(c.id) === String(contact.id));
const contactApiSchemeId = freshContact ? freshContact.apiScheme : (contact ? contact.apiScheme : null);
if (contactApiSchemeId) {
const schemes = JSON.parse(localStorage.getItem('vibe_api_schemes') || '[]');
console.log('[AI] Looking for scheme ID:', contactApiSchemeId);
// Try loose matching by id or name
selectedScheme = schemes.find(s => String(s.id) === String(contactApiSchemeId) || s.name === contactApiSchemeId);
if (selectedScheme) {
apiUrl = selectedScheme.apiUrl || apiUrl;
apiKey = selectedScheme.apiKey || apiKey;
model = selectedScheme.model || model;
console.log('[AI] Using contact API scheme:', { id: selectedScheme.id, name: selectedScheme.name });
} else {
console.warn('[AI] Contact has apiScheme ID but scheme not found in storage:', contactApiSchemeId);
}
} else {
console.log('[AI] Contact has no API scheme assigned.');
}
// If still no API config, try to pick a default saved scheme (first valid) as a fallback
if ((!apiUrl || !apiKey)) {
try {
const schemesAll = JSON.parse(localStorage.getItem('vibe_api_schemes') || '[]');
const firstValid = schemesAll.find(s => s.apiUrl && s.apiKey) || schemesAll[0];
if (firstValid) {
selectedScheme = selectedScheme || firstValid;
apiUrl = firstValid.apiUrl || apiUrl;
apiKey = firstValid.apiKey || apiKey;
model = firstValid.model || model;
console.log('[AI] picked default saved scheme as fallback:', { id: firstValid.id, name: firstValid.name });
}
} catch (e) {
console.warn('[AI] Failed to parse saved schemes for fallback', e);
}
}
console.log('[AI] resolved API config:', { apiUrl, hasKey: !!apiKey, model, selectedScheme });
if (!apiUrl || !apiKey) {
console.warn('[AI] No API configured, falling back to mock.');
return this.generateMockData(module, contact);
}
// Build enriched context (CHAR/USER/memory/travel/couple data)
const aiContext = this.buildAIContext(contact, dateStr, module);
// Determine target language based on bilingual settings
const isBilingual = contact.bilingualSettings?.enabled || false;
const targetLanguage = isBilingual ? 'English' : '简体中文';
// Construct Prompt based on module
let systemPrompt = `你是角色"${contact.name || '未知'}"。请根据角色人设和行程生成今天的生活记录数据。回复纯JSON,不要包含任何其他文字。
【语言要求】:所有文本字段(summary、reason、content、note、title、workout、item名称等)必须使用${targetLanguage}来填写。
【语气要求】:所有心得、感想、日记类字段(summary、reason、content、note)必须使用第一人称"我"来写,语气自然随意,像在自己的备忘录里记录一样。感想类字段请写2-5句话,不要太简短,要有细节和情绪。
【人设参考】:${contact.personality || contact.persona || '默认角色'}`;
let userPrompt = customPrompt || `为角色"${contact.name}"生成${dateStr}的${module}数据。`;
// Prepend context to user prompt to help the model only fill missing fields
try {
const ctxText = JSON.stringify(aiContext, null, 2);
userPrompt = `Context:\n${ctxText}\n\nInstructions:\n${userPrompt}`;
} catch (e) {
console.warn('[AI] Failed to stringify context', e);
}
if (module === 'mood') {
const moods = ["开心", "平淡", "难过", "生气", "兴奋"];
userPrompt += `
返回JSON对象:
- mood: 从 ${JSON.stringify(moods)} 中选一个
- reason: 用${targetLanguage}写一句话解释原因(第一人称,符合角色人设)
示例: {"mood": "开心", "reason": "今天吃到了好吃的蛋糕,心情超好~"}
`;
} else if (module === 'exercise') {
userPrompt += `
返回JSON对象:
- steps: 整数 (0-20000)
- workout: 用${targetLanguage}描述运动内容(如"跑步5公里"、"没运动"、"瑜伽")
- calories: 整数(估算消耗卡路里)
- summary: 用${targetLanguage}写2-5句第一人称运动感想(如"今天跑了五公里,腿有点酸但是心情很好。回来的路上买了杯冰美式犒劳自己。")
`;
} else if (module === 'meals') {
userPrompt += `
返回JSON对象:
- breakfast: 用${targetLanguage}描述早餐内容
- lunch: 用${targetLanguage}描述午餐内容
- dinner: 用${targetLanguage}描述晚餐内容(如果时间还没到可以为null)
- score: 整数 1-5(这是角色今天吃得健不健康的评分,5分满分)
- summary: 用${targetLanguage}写2-5句第一人称饮食感想(如"早上吃了个全麦三明治,感觉还挺健康的。中午没忍住点了炸鸡,罪恶感满满但是真的好吃啊。")
`;
} else if (module === 'finance') {
const fSettings = (CoupleSpace.loadCoupleSpace(contact.id).settings.financeSettings) || {};
userPrompt += `
财务设定:
- 收入模式: ${fSettings.incomePattern || 'stable'}
- 收入水平: ${fSettings.incomeLevel || 'medium'}
- 消费风格: ${fSettings.spendingStyle || 'moderate'}
返回JSON对象:
- items: 数组 [{item: "用${targetLanguage}写物品名", cost: 数字, category: "分类", note: "用${targetLanguage}写一句第一人称购物感想"}]
- spent: 总花费(数字)
- summary: 用${targetLanguage}写2-5句第一人称今日消费总结感想
生成1-3个消费项目,符合消费风格。每个item都要有note感想。
`;
} else if (module === 'diary') {
userPrompt += `
返回JSON对象:
- title: 用${targetLanguage}写日记标题
- content: 用${targetLanguage}写500-800字的第一人称日记,语气自然随意,像真的在写日记一样。可以适当加入一些手写日记的效果,比如用~~划掉的文字~~表示涂改、用(括号吐槽)表示内心OS、用"……"表示欲言又止、用大写或感叹号表示激动情绪,让日记有真实感和生活气息。
- style: 日记风格(如"感性"、"记录"、"吐槽"、"碎碎念")
`;
} else if (module === 'summary') {
userPrompt += `
返回JSON对象:
- content: 用${targetLanguage}写一句话总结今天。
`;
} else if (module === 'memory_upgrade') {
userPrompt = customPrompt || '总结记忆。';
userPrompt += `\n返回JSON对象:\n- content: 用${targetLanguage}写总结文本。`;
} else if (module === 'sleep') {
userPrompt += `
返回JSON对象:
- duration: 数字 (6-9)
- quality: "Deep" / "Light" / "Restless"
- bedtime: "HH:MM"(如 23:30)
- wakeup: "HH:MM"(如 07:30)
- summary: 用${targetLanguage}写2-5句第一人称的睡眠感想(如"昨晚睡得还不错,一觉到天亮。就是半夜被猫踩醒了一次,迷迷糊糊又睡过去了。早上闹钟响了三次才起来,周末就该这样赖床。")
`;
} else if (module === 'bowel') {
userPrompt += `
返回JSON对象:
- count: 数字 (0 或 1)
- type: "Normal" / "Hard" / "Soft"(count > 0 时填写,否则 null)
- time: "HH:MM"(count > 0 时填写,否则 null)
- summary: 用${targetLanguage}写2-5句第一人称的排便感想,语气轻松搞笑(如"终于拉出来了,感觉整个人都轻松了。蹲了十分钟刷了半个小时手机,腿都麻了。")。如果count为0,就写没拉出来的感想(如"今天肚子咕噜咕噜的但就是没动静,明天多喝点水吧。")
`;
} else if (module === 'time_slice' || module === 'full_day') {
// Combined handler for bulk generation
const isFullDay = (module === 'full_day');
const targets = isFullDay
? ['sleep', 'bowel', 'exercise', 'meals', 'finance', 'mood', 'diary', 'summary']
: JSON.parse(customPrompt || '[]');
userPrompt = `为以下模块生成数据: ${JSON.stringify(targets)}。\n`;
userPrompt += `返回一个JSON对象,key是模块名(如 "sleep", "meals"),value是对应的数据对象。\n`;
userPrompt += `
所有文本字段必须使用${targetLanguage},心得/感想类字段用第一人称"我"来写,每个感想写2-5句话,要有细节和情绪。
数据格式说明:
- sleep: { duration: 数字6-9, quality: "Deep/Light/Restless", bedtime: "HH:MM", wakeup: "HH:MM", summary: "2-5句第一人称睡眠感想" }
- bowel: { count: 数字, type: "Normal/Hard/Soft", time: "HH:MM", summary: "2-5句第一人称排便感想,轻松搞笑风格" } (count为0也要写感想)
- exercise: { steps: 数字, workout: "运动描述", calories: 数字, summary: "2-5句第一人称运动感想" }
- meals: { breakfast: "早餐描述", lunch: "午餐描述", dinner: "晚餐描述", score: 1-5(健康评分5分满分), summary: "2-5句第一人称饮食感想" }
- finance: { spent: 数字, items: [{item: "物品名", cost: 数字, note: "一句购物感想"}], summary: "2-5句第一人称消费总结" } (收入: ${contact.settings?.financeSettings?.incomeLevel || 'medium'}, 消费: ${contact.settings?.financeSettings?.spendingStyle || 'moderate'})
- mood: { mood: "开心/平淡/难过/生气/兴奋", reason: "2-5句第一人称原因" }
- diary: { title: "标题", content: "500-800字第一人称日记,可用~~划线~~、(括号吐槽)等手写效果", style: "风格" }
- summary: { content: "一句话总结" }
确保数据与角色人设和行程上下文一致。
`;
} else {
// For other modules (sleep, bowel) in Phase 3/4, we can stick to mock or implement simple prompts
console.log(`[AI] Using mock for ${module} as fallback.`);
return this.generateMockData(module, contact);
}
try {
const endpoint = `${apiUrl}/chat/completions`.replace(/([^:]\/)\/+/g, '$1');
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt }
],
temperature: 0.7
})
});
if (!response.ok) throw new Error('API Error');
const data = await response.json();
const content = data.choices[0].message.content;
// 健壮的 JSON 解析:处理 AI 返回的各种非标准格式
let jsonStr = content
.replace(/```json\s*/gi, '') // 去掉 ```json
.replace(/```\s*/g, '') // 去掉 ```
.trim();
// 尝试直接解析
try {
return JSON.parse(jsonStr);
} catch (e1) {
console.warn('[AI] Direct JSON.parse failed, attempting cleanup...', e1.message);
// 提取第一个 { ... } 或 [ ... ] 块
const braceMatch = jsonStr.match(/(\{[\s\S]*\})/);
const bracketMatch = jsonStr.match(/(\[[\s\S]*\])/);
let extracted = (braceMatch && braceMatch[1]) || (bracketMatch && bracketMatch[1]) || jsonStr;
// 清理常见问题:
// 1. 去掉行尾注释 // ...
extracted = extracted.replace(/\/\/[^\n]*/g, '');
// 2. 去掉块注释 /* ... */
extracted = extracted.replace(/\/\*[\s\S]*?\*\//g, '');
// 3. 去掉尾逗号 (,} 或 ,])
extracted = extracted.replace(/,\s*([\]}])/g, '$1');
// 4. 把单引号键值换成双引号(简单处理)
// 匹配 'key': 或 'value' 但不破坏字符串内的撇号
extracted = extracted.replace(/(?<=[\{,\[]\s*)'([^']+)'\s*:/g, '"$1":');
// 5. 值中的单引号 → 双引号(仅对简单值)
extracted = extracted.replace(/:\s*'([^']*)'/g, ': "$1"');
try {
return JSON.parse(extracted);
} catch (e2) {
console.warn('[AI] Cleanup JSON.parse also failed, trying eval fallback...', e2.message);
// 最后手段:用 Function 构造器(比 eval 安全一点)
try {
return (new Function('return (' + extracted + ')'))();
} catch (e3) {
console.error('[AI] All JSON parse attempts failed. Raw content:', content);
throw e3;
}
}
}
} catch (e) {
console.error('[AI] Generation failed:', e);
return this.generateMockData(module, contact);
}
}
// Build AI context payload combining CHAR, USER, travel, couple space and couple memory
,buildAIContext: function(contact, dateStr, module) {
const ctx = { CHAR: {}, USER: {}, TRAVEL: null, COUPLE_SPACE_DAY: null, COUPLE_SETTINGS: {}, COUPLE_MEMORY: {} };
if (!contact) return ctx;
// CHAR related
ctx.CHAR.personality = contact.personality || contact.persona || contact.personaDescription || null;
ctx.CHAR.timezoneSettings = contact.timezoneSettings || null;
ctx.CHAR.contextWindowSize = (contact.summarySettings && contact.summarySettings.contextWindowSize) || null;
// USER related
ctx.USER.name = contact.userPersonaName || contact.userPersona || contact.name || null;
ctx.USER.bio = contact.userBio || (contact.profile && contact.profile.bio) || null;
// Chat memory bank (Personal Long-term Memory)
try {
// contact.memoryBank might be an array or object depending on implementation
// usually it's an array of summaries or key-value pairs
ctx.CHAT_MEMORY = contact.memoryBank || [];
} catch (e) {
ctx.CHAT_MEMORY = [];
}
// Travel cards / timeline for date
try {
ctx.TRAVEL = this.getTravelData(contact.id, dateStr) || null;
} catch (e) {
ctx.TRAVEL = null;
}
// Couple space today's data & settings
try {
const space = this.loadCoupleSpace(contact.id);
ctx.COUPLE_SETTINGS = space.settings || {};
// Clone data to avoid mutation and allow masking
ctx.COUPLE_SPACE_DAY = (space.days && space.days[dateStr]) ? { ...space.days[dateStr] } : {};
// If generating a specific module, mask its current value in context
// so AI generates fresh data instead of repeating existing data.
if (module && ctx.COUPLE_SPACE_DAY[module]) {
// For bulk modules like 'time_slice', we might need to parse the module string?
// But 'module' here is usually a simple key like 'sleep'.
// If module is 'time_slice', it's a special case handled in callAI prompts usually,
// but masking 'time_slice' key doesn't make sense as it's not a data key.
// The data keys are sleep, meals, etc.
// For single module refresh (e.g. 'sleep'), this works perfectly.
delete ctx.COUPLE_SPACE_DAY[module];
}
} catch (e) {
ctx.COUPLE_SPACE_DAY = {};
ctx.COUPLE_SETTINGS = {};
}
// Couple memory bank: pick recent active items per settings
try {
const mem = this.loadCoupleMemoryBank(contact.id);
const settings = (mem && mem.settings) ? mem.settings : { injectDaily: 3, injectWeekly: 1, injectMonthly: 1, injectYearly: 1 };
function pickActive(list, n) {
if (!Array.isArray(list) || n <= 0) return [];
const sorted = [...list].sort((a, b) => new Date((b.date || b.week || b.month || b.year) || 0) - new Date((a.date || a.week || a.month || a.year) || 0));
const active = sorted.filter(m => m && (m.active !== false));
return active.slice(0, n);
}
ctx.COUPLE_MEMORY.daily = pickActive(mem.daily, settings.injectDaily || 0);
ctx.COUPLE_MEMORY.weekly = pickActive(mem.weekly, settings.injectWeekly || 0);
ctx.COUPLE_MEMORY.monthly = pickActive(mem.monthly, settings.injectMonthly || 0);
ctx.COUPLE_MEMORY.yearly = pickActive(mem.yearly, settings.injectYearly || 0);
ctx.COUPLE_MEMORY.settings = settings;
} catch (e) {
ctx.COUPLE_MEMORY = { daily: [], weekly: [], monthly: [], yearly: [], settings: {} };
}
return ctx;
}
};
// ==================== UI Logic (Phase 1 & 2 & 3) ====================
const CoupleSpaceUI = {
currentContactId: null,
currentMonthOffset: 0, // 0 = current month, -1 = prev month
_refreshInProgress: false, // 防止并发刷新导致数据串台
init: function() {
// 防止被重复初始化(页面中多处可能调用 init)
if (this._inited) return;
this._inited = true;
console.log('CoupleSpaceUI initializing...');
this.bindEvents();
this.renderAvatarStrip();
this.initCssScheme();
},
bindEvents: function() {
// Refresh Button
const refreshBtn = document.getElementById('coupleRefreshButton');
if (refreshBtn) {
refreshBtn.addEventListener('click', () => this.handleRefreshAll());
}
// Settings Button
const settingsBtn = document.getElementById('coupleSettingsButton');
if (settingsBtn) {
settingsBtn.addEventListener('click', () => this.openSettings());
}
// Settings Modal Close
const settingsClose = document.getElementById('coupleSettingsClose');
if (settingsClose) {
settingsClose.addEventListener('click', () => {
document.getElementById('coupleSettingsModal').style.display = 'none';
});
}
// Save Settings
const saveSettingsBtn = document.getElementById('coupleSettingsSave');
if (saveSettingsBtn) {
saveSettingsBtn.addEventListener('click', () => this.saveSettings());
}
// Clear Data
const clearDataBtn = document.getElementById('coupleClearData');
if (clearDataBtn) {
clearDataBtn.addEventListener('click', () => this.clearCurrentContactData());
}
// Module Refresh Buttons
document.querySelectorAll('.couple-card-refresh').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const module = e.target.getAttribute('data-module');
this.handleRefreshModule(module);
});
});
// Details Modal Close
const detailsClose = document.getElementById('coupleDetailsClose');
if (detailsClose) {
detailsClose.addEventListener('click', () => {
document.getElementById('coupleDetailsModal').style.display = 'none';
});
}
// Memory Bank Buttons
const memoryBtn = document.getElementById('coupleMemoryButton');
if (memoryBtn) {
memoryBtn.addEventListener('click', () => this.openMemoryBank());
}
const memoryClose = document.getElementById('coupleMemoryClose');
if (memoryClose) {
memoryClose.addEventListener('click', () => {
document.getElementById('coupleMemoryModal').style.display = 'none';
});
}
const memoryUpgrade = document.getElementById('coupleMemoryUpgrade');
if (memoryUpgrade) {
memoryUpgrade.addEventListener('click', () => this.handleUpgradeMemories());
}
document.querySelectorAll('.memory-tab').forEach(tab => {
tab.addEventListener('click', (e) => {
document.querySelectorAll('.memory-tab').forEach(t => t.classList.remove('active'));
e.target.classList.add('active');
this.renderMemoryList(e.target.dataset.tab);
});
});
},
// --- Memory Bank UI ---
currentMemoryTab: 'daily',
openMemoryBank: function() {
if (!this.currentContactId) return;
document.getElementById('coupleMemoryModal').style.display = 'flex';
this.renderMemoryList('daily');
},
renderMemoryList: function(type) {
this.currentMemoryTab = type;
const container = document.getElementById('coupleMemoryList');
const memories = CoupleSpace.getMemories(this.currentContactId, type);
if (memories.length === 0) {
container.innerHTML = '<div style="text-align:center; padding: 20px; color:#999;">暂无记忆</div>';
return;
}
container.innerHTML = memories.map(m => `
<div style="padding: 10px; border-bottom: 1px solid #eee; display: flex; align-items: flex-start; gap: 10px; background: ${m.active ? '#fff' : '#f9f9f9'}; opacity: ${m.active ? 1 : 0.6};">
<input type="checkbox" class="memory-select" value="${m.id}" style="margin-top: 5px;">
<div style="flex: 1;">
<div style="font-size: 12px; color: #888; margin-bottom: 4px;">${m.date} <span style="float:right;">${m.active ? '🟢 Active' : '⚪ Archived'}</span></div>
<div style="font-size: 13px; line-height: 1.4;">${m.content}</div>
</div>
</div>
`).join('');
},
handleUpgradeMemories: async function() {
const selected = Array.from(document.querySelectorAll('.memory-select:checked')).map(cb => cb.value);
if (selected.length === 0) {
alert('请先选择要总结的记忆条目');
return;
}
// 🔒 锁定当前角色ID
const lockedContactId = String(this.currentContactId);
const btn = document.getElementById('coupleMemoryUpgrade');
btn.textContent = '生成中...';
btn.disabled = true;
try {
const result = await CoupleSpace.upgradeMemories(lockedContactId, this.currentMemoryTab, selected);
if (result) {
alert('总结生成成功!已存入上一级记忆库。');
this.renderMemoryList(this.currentMemoryTab);
} else {
alert('生成失败');
}
} catch (e) {
console.error(e);
alert('发生错误');
}
btn.textContent = '生成上级总结';
btn.disabled = false;
},
renderAvatarStrip: function() {
const container = document.getElementById('coupleAvatarStrip');
if (!container) return;
const contacts = CoupleSpace.getAllContacts();
container.innerHTML = contacts.map(c => `
<div class="couple-avatar-item ${this.currentContactId === String(c.id) ? 'active' : ''}"
onclick="CoupleSpaceUI.switchContact('${c.id}')">
<div class="couple-avatar-circle">
${c.avatarUrl ? `<img src="${c.avatarUrl}">` : (c.name[0] || '?')}
</div>
<div class="couple-avatar-label">${c.nickname || c.name}</div>
</div>
`).join('');
// Auto-select first if none selected
if (!this.currentContactId && contacts.length > 0) {
this.switchContact(contacts[0].id);
}
},
switchContact: function(contactId) {
this.currentContactId = String(contactId);
// Update Avatar UI
document.querySelectorAll('.couple-avatar-item').forEach(el => el.classList.remove('active'));
// Re-render strip to set active class
this.renderAvatarStrip();
const contact = CoupleSpace.getContactInfo(contactId);
if (contact) {
document.getElementById('coupleActiveName').textContent = contact.nickname || contact.name;
}
this.renderDashboard();
},
renderDashboard: function() {
if (!this.currentContactId) return;
const space = CoupleSpace.loadCoupleSpace(this.currentContactId);
const contact = CoupleSpace.getContactInfo(this.currentContactId);
// Use today (char time)
const dateStr = CoupleSpace.getCharDateStr(contact);
const todayData = space.days[dateStr] || {};
console.log(`Rendering dashboard for ${contact.name} on ${dateStr}`, todayData);
// Phase 3: Render Calendars for specific modules
this.renderCalendarModule('sleep', space.days, contact);
this.renderCalendarModule('bowel', space.days, contact);
this.renderCalendarModule('mood', space.days, contact);
// Render others as simple view for now (Phase 4 will update these)
this.renderSimpleModule('exercise', todayData.exercise);
this.renderSimpleModule('meals', todayData.meals);
this.renderSimpleModule('finance', todayData.finance);
this.renderSimpleModule('diary', todayData.diary);
this.renderSimpleModule('summary', todayData.summary);
// Update refresh buttons text based on data existence
document.querySelectorAll('.couple-card-refresh').forEach(btn => {
const module = btn.getAttribute('data-module');
if (todayData && todayData[module] && (Object.keys(todayData[module]).length > 0)) {
btn.textContent = '重新生成';
} else {
btn.textContent = '生成';
}
});
},
renderSimpleModule: function(module, data) {
const container = document.getElementById(`couple${module.charAt(0).toUpperCase() + module.slice(1)}Body`);
if (!container) return;
if (!data) {
container.innerHTML = '<div style="text-align:center; padding: 20px; color: #ccc;">暂无数据</div>';
return;
}
let html = '';
if (module === 'exercise') {
html = `
<div style="font-size: 12px; color: #555; margin-bottom: 5px; line-height: 1.4;">${data.summary || ''}</div>
<div style="font-size: 11px; color: #999;">👣 ${data.steps || 0} 步 · 🏋️ ${data.workout || '无运动'} · 🔥 ${data.calories || 0} kcal</div>
`;
} else if (module === 'meals') {
// Helper to extract string from potential object
const formatMeal = (m) => {
if (!m) return '-';
if (typeof m === 'string') {
// Try parsing string as JSON
if (m.trim().startsWith('{')) {
try {
const parsed = JSON.parse(m);
return parsed.text || parsed.food || parsed.description || m;
} catch (e) {
return m;
}
}
return m;
}
if (typeof m === 'object') return m.text || m.food || m.description || JSON.stringify(m);
return String(m);
};
html = `
<div style="font-size: 12px; margin-bottom: 4px; word-break: break-all;">🥣 <b>早:</b> ${formatMeal(data.breakfast)}</div>
<div style="font-size: 12px; margin-bottom: 4px; word-break: break-all;">🍱 <b>午:</b> ${formatMeal(data.lunch)}</div>
<div style="font-size: 12px; margin-bottom: 4px; word-break: break-all;">🍲 <b>晚:</b> ${formatMeal(data.dinner)}</div>
<div style="font-size: 12px; color: #888; margin-top: 5px;">⭐ 健康分: ${data.score || 0}/5</div>
`;
} else if (module === 'finance') {
const items = Array.isArray(data.items) ? data.items : [];
const list = items.map(i => {
// Safe access to item properties
const name = i && (i.item || i.name || '未知项');
let cost = i && (i.cost !== undefined ? i.cost : i.amount !== undefined ? i.amount : 0);
// Ensure cost is positive for display if it's meant to be spent amount
if (cost < 0) cost = Math.abs(cost);
return `<div style="display:flex; justify-content:space-between; margin-bottom: 2px;">
<span style="flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; margin-right:8px;">${name}</span>
<span style="flex-shrink:0;">¥${cost}</span>
</div>${i.note ? `<div style="font-size:10px;color:#aaa;margin-bottom:4px;padding-left:4px;">💬 ${i.note}</div>` : ''}`;
}).join('');
// Fix total spent display
let totalSpent = data.spent || 0;
if (totalSpent < 0) totalSpent = Math.abs(totalSpent);
html = `
<div style="font-weight: bold; font-size: 14px; margin-bottom: 5px; color: #d4a574;">💸 总计: ¥${totalSpent}</div>
<div style="font-size: 11px; color: #666; max-height: 120px; overflow-y: auto;">
${list || '无消费记录'}
</div>
`;
} else if (module === 'diary') {
html = `
<div style="font-weight: bold; font-size: 13px; margin-bottom: 5px;">${data.title || '无题'}</div>
<div style="font-size: 11px; line-height: 1.4; max-height: 80px; overflow-y: auto; color: #555;">${data.content || '...'}</div>
<div style="font-size: 10px; color: #999; margin-top: 5px; text-align: right;">${data.style || ''}</div>
`;
} else if (module === 'summary') {
html = `<div style="font-size: 12px; color: #555; line-height: 1.5;">${data.content || '暂无总结'}</div>`;
} else if (module === 'sleep') {
const qualityMap = { Deep: '深度', Light: '浅睡', Restless: '辗转' };
html = `
<div style="font-size: 12px; color: #555; line-height: 1.5;">${data.summary || ''}</div>
<div style="font-size: 11px; color: #999; margin-top: 4px;">⏱️ ${data.duration || '?'}h · ${qualityMap[data.quality] || data.quality || ''}</div>
`;
} else if (module === 'bowel') {
if (!data.count || data.count === 0) {
html = `<div style="font-size: 12px; color: #555; line-height: 1.4;">${data.summary || '无记录'}</div>`;
} else {
const typeMap = { Normal: '正常', Hard: '偏硬', Soft: '偏软' };
html = `
<div style="font-size: 12px; color: #555; margin-bottom: 4px; line-height: 1.4;">${data.summary || ''}</div>
<div style="font-size: 11px; color: #999;">� ${data.count}次 · ${typeMap[data.type] || data.type || ''} · � ${data.time || ''}</div>
`;
}
} else if (module === 'mood') {
const emojiMap = { "开心": "😄", "平淡": "😐", "难过": "😢", "生气": "😠", "兴奋": "🤩" };
html = `
<div style="font-size: 18px; margin-bottom: 4px;">${emojiMap[data.mood] || ''} ${data.mood || ''}</div>
<div style="font-size: 11px; color: #666;">${data.reason || ''}</div>
`;
} else {
html = `<pre style="white-space: pre-wrap; font-family: inherit; font-size: 12px;">${JSON.stringify(data, null, 2)}</pre>`;
}
container.innerHTML = html;
},
renderCalendarModule: function(module, allDaysData, contact) {
const container = document.getElementById(`couple${module.charAt(0).toUpperCase() + module.slice(1)}Body`);
if (!container) return;
// Calculate month based on char time + offset
const charNow = CoupleSpace.getCharNow(contact);
const targetDate = new Date(charNow.getFullYear(), charNow.getMonth() + this.currentMonthOffset, 1);
const year = targetDate.getFullYear();