-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
2262 lines (2038 loc) · 83.5 KB
/
Copy pathmain.js
File metadata and controls
2262 lines (2038 loc) · 83.5 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
'use strict';
const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
const http = require('http');
const crypto = require('crypto');
const { openCharx, saveCharx, openRisum, saveRisum } = require('./src/charx-io');
let mainWindow;
let currentFilePath = null;
let currentData = null;
let ptyProcess = null;
let popoutWindows = {}; // { terminal: BrowserWindow, sidebar: BrowserWindow }
// MCP confirmation via renderer (MomoTalk style popup)
let mcpConfirmId = 0;
const mcpConfirmCallbacks = {};
function askRendererConfirm(title, message) {
return new Promise((resolve) => {
if (!mainWindow || mainWindow.isDestroyed()) { resolve(false); return; }
const id = ++mcpConfirmId;
mcpConfirmCallbacks[id] = resolve;
mainWindow.webContents.send('mcp-confirm-request', id, title, message);
// Timeout fallback (30s)
setTimeout(() => { if (mcpConfirmCallbacks[id]) { delete mcpConfirmCallbacks[id]; resolve(false); } }, 30000);
});
}
ipcMain.on('mcp-confirm-response', (_, id, allowed) => {
if (mcpConfirmCallbacks[id]) {
mcpConfirmCallbacks[id](allowed);
delete mcpConfirmCallbacks[id];
}
});
// Close confirm via renderer (MomoTalk style, 3 buttons)
function askRendererCloseConfirm() {
return new Promise((resolve) => {
if (!mainWindow || mainWindow.isDestroyed()) { resolve(1); return; }
const id = ++mcpConfirmId;
mcpConfirmCallbacks[id] = resolve;
mainWindow.webContents.send('close-confirm-request', id);
});
}
ipcMain.on('close-confirm-response', (_, id, choice) => {
if (mcpConfirmCallbacks[id]) {
mcpConfirmCallbacks[id](choice);
delete mcpConfirmCallbacks[id];
}
});
// MCP API server
let apiServer = null;
let apiPort = null;
let apiToken = null;
// Sync server (RisuAI live sync)
let syncServer = null;
let syncHash = 0;
// Reference files (read-only, shared with MCP)
let referenceFiles = []; // [{ fileName, data }]
// Editor popout data relay
let editorPopoutData = null; // { tabId, label, language, content, readOnly }
// Preview popout data relay
let previewPopoutData = null;
// Broadcast to main window + all popout windows
function broadcastToAll(channel, ...args) {
if (channel === 'data-updated') syncHash++;
const allWindows = [mainWindow, ...Object.values(popoutWindows)];
for (const win of allWindows) {
if (win && !win.isDestroyed()) {
win.webContents.send(channel, ...args);
}
}
}
function createWindow() {
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 900,
minHeight: 600,
title: 'RisuToki',
icon: path.join(__dirname, 'assets', 'icon.png'),
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
}
});
mainWindow.loadFile('src/renderer/index.html');
mainWindow.setMenuBarVisibility(false);
// F12 → DevTools 토글
mainWindow.webContents.on('before-input-event', (event, input) => {
if (input.key === 'F12') {
mainWindow.webContents.toggleDevTools();
event.preventDefault();
}
});
// 창 닫기 전 저장 확인 (MomoTalk 스타일)
let isClosingForReal = false;
mainWindow.on('close', (e) => {
if (currentData && !isClosingForReal) {
e.preventDefault();
askRendererCloseConfirm().then((choice) => {
if (choice === 0) {
// 저장하고 닫기
if (currentFilePath) {
try { saveCharx(currentFilePath, currentData); } catch (err) {}
}
isClosingForReal = true;
mainWindow.close();
} else if (choice === 1) {
// 저장 안 하고 닫기
isClosingForReal = true;
mainWindow.close();
}
// choice === 2: 취소 — 아무것도 안 함
});
}
});
}
app.whenReady().then(() => {
createWindow();
startApiServer();
});
app.on('window-all-closed', () => {
if (ptyProcess) { ptyProcess.kill(); ptyProcess = null; }
if (apiServer) { apiServer.close(); apiServer = null; }
// Cleanup risutoki from ~/.mcp.json (preserve other servers)
try {
const mcpPath = path.join(os.homedir(), '.mcp.json');
if (fs.existsSync(mcpPath)) {
const config = JSON.parse(fs.readFileSync(mcpPath, 'utf-8'));
if (config.mcpServers && config.mcpServers.risutoki) {
delete config.mcpServers.risutoki;
if (Object.keys(config.mcpServers).length === 0) {
fs.unlinkSync(mcpPath);
} else {
fs.writeFileSync(mcpPath, JSON.stringify(config, null, 2), 'utf-8');
}
}
}
} catch (e) { /* ignore */ }
// Cleanup Codex MCP config
cleanupCodexMcpConfig();
// Cleanup AGENTS.md from CWD
try {
const cwd = currentFilePath ? path.dirname(currentFilePath) : process.cwd();
const agentsPath = path.join(cwd, 'AGENTS.md');
if (fs.existsSync(agentsPath)) fs.unlinkSync(agentsPath);
} catch (e) { /* ignore */ }
// Cleanup autosave file
if (currentFilePath) {
try {
const dir = path.dirname(currentFilePath);
const base = path.basename(currentFilePath);
const autosavePath = path.join(dir, `.${base}.autosave.charx`);
if (fs.existsSync(autosavePath)) fs.unlinkSync(autosavePath);
} catch (e) { /* ignore */ }
}
app.quit();
});
// --- IPC Handlers ---
// New file
ipcMain.handle('new-file', async () => {
currentFilePath = null;
currentData = {
spec: 'chara_card_v3',
specVersion: '3.0',
name: 'New Character',
description: '',
personality: '',
scenario: '',
creatorcomment: '',
tags: [],
firstMessage: '{{char}}가 당신을 바라봅니다.\n\n"안녕하세요, 처음 뵙겠습니다."',
globalNote: '[시스템 노트]\n이 캐릭터의 대화 스타일과 성격을 여기에 작성하세요.',
css: '/* ============================================================\n main\n ============================================================ */\n/* 메인 스타일시트 */\n\n/* ============================================================\n layout\n ============================================================ */\n/* 레이아웃 관련 스타일 */\n',
defaultVariables: '',
lua: '-- ===== main =====\n-- 메인 트리거 스크립트\n\n-- ===== utils =====\n-- 유틸리티 함수\n',
lorebook: [
{
key: '캐릭터,이름',
secondkey: '',
comment: '캐릭터 기본 정보 (샘플)',
content: '{{char}}은(는) 샘플 캐릭터입니다.\n이 항목을 수정하거나 삭제하고, 원하는 로어북을 추가하세요.',
order: 100,
priority: 0,
selective: false,
alwaysActive: false,
mode: 'normal',
extentions: {}
}
],
regex: [
{
comment: '샘플 정규식',
type: 'editoutput',
find: '\\*\\*(.+?)\\*\\*',
replace: '<b>$1</b>',
flag: 'g'
}
],
moduleId: '',
moduleName: 'New Module',
moduleDescription: '',
assets: [],
xMeta: {},
risumAssets: [],
cardAssets: [],
_risuExt: {},
_card: { spec: 'chara_card_v3', spec_version: '3.0', data: { extensions: { risuai: {} } } },
_moduleData: null
};
mainWindow.setTitle('RisuToki - New');
return serializeForRenderer(currentData);
});
// Open file dialog + parse charx
ipcMain.handle('open-file', async () => {
try {
const result = await dialog.showOpenDialog(mainWindow, {
filters: [
{ name: 'RisuAI Files', extensions: ['charx', 'risum'] },
{ name: 'Character Card', extensions: ['charx'] },
{ name: 'RisuAI Module', extensions: ['risum'] }
],
properties: ['openFile']
});
if (result.canceled || !result.filePaths[0]) return null;
currentFilePath = result.filePaths[0];
console.log('[main] Opening:', currentFilePath);
if (currentFilePath.endsWith('.risum')) {
currentData = openRisum(currentFilePath);
} else {
currentData = openCharx(currentFilePath);
}
console.log('[main] Parsed OK, name:', currentData.name, 'type:', currentData._fileType || 'charx');
invalidateAssetsMapCache();
invalidateSectionCaches();
mainWindow.setTitle(`RisuToki - ${path.basename(currentFilePath)}`);
// Update .mcp.json in the file's directory so Claude Code can find it
if (apiPort) writeCurrentMcpConfig();
return serializeForRenderer(currentData);
} catch (err) {
console.error('[main] open-file error:', err);
return null;
}
});
// Save to current path
ipcMain.handle('save-file', async (_, updatedFields) => {
if (!currentData) return { success: false, error: 'No file open' };
applyUpdates(currentData, updatedFields);
invalidateAssetsMapCache();
invalidateSectionCaches();
if (!currentFilePath) {
return await saveAs(updatedFields);
}
if (currentData._fileType === 'risum') {
saveRisum(currentFilePath, currentData);
} else {
saveCharx(currentFilePath, currentData);
}
return { success: true, path: currentFilePath };
});
// Save As
ipcMain.handle('save-file-as', async (_, updatedFields) => {
if (!currentData) return { success: false, error: 'No file open' };
applyUpdates(currentData, updatedFields);
const isRisum = currentData._fileType === 'risum';
const filters = isRisum
? [{ name: 'RisuAI Module', extensions: ['risum'] }]
: [{ name: 'Character Card', extensions: ['charx'] }];
const defaultExt = isRisum ? '.risum' : '.charx';
const result = await dialog.showSaveDialog(mainWindow, {
filters,
defaultPath: currentFilePath || `untitled${defaultExt}`
});
if (result.canceled || !result.filePath) return { success: false, error: 'Cancelled' };
currentFilePath = result.filePath;
if (isRisum) {
saveRisum(currentFilePath, currentData);
} else {
saveCharx(currentFilePath, currentData);
}
mainWindow.setTitle(`RisuToki - ${path.basename(currentFilePath)}`);
return { success: true, path: currentFilePath };
});
// Get current file path (for terminal context)
ipcMain.handle('get-file-path', () => currentFilePath);
// Open reference file (read-only, doesn't replace main file) — supports multi-select
ipcMain.handle('open-reference', async () => {
try {
const result = await dialog.showOpenDialog(mainWindow, {
filters: [
{ name: 'RisuAI Files', extensions: ['charx', 'risum'] },
{ name: 'Character Card', extensions: ['charx'] },
{ name: 'RisuAI Module', extensions: ['risum'] }
],
properties: ['openFile', 'multiSelections']
});
if (result.canceled || !result.filePaths.length) return null;
const refs = [];
for (const refPath of result.filePaths) {
try {
const refData = refPath.endsWith('.risum') ? openRisum(refPath) : openCharx(refPath);
const ref = {
fileName: path.basename(refPath),
filePath: refPath,
data: serializeForRenderer(refData)
};
if (!referenceFiles.some(r => r.fileName === ref.fileName)) {
referenceFiles.push(ref);
}
refs.push(ref);
} catch (e) {
console.error('[main] open-reference error for:', refPath, e);
}
}
return refs.length === 1 ? refs[0] : refs;
} catch (err) {
console.error('[main] open-reference error:', err);
return null;
}
});
// Open reference file by path (for drag-and-drop)
ipcMain.handle('open-reference-path', async (_, filePath) => {
try {
const refData = filePath.endsWith('.risum') ? openRisum(filePath) : openCharx(filePath);
const ref = {
fileName: path.basename(filePath),
filePath: filePath,
data: serializeForRenderer(refData)
};
if (!referenceFiles.some(r => r.fileName === ref.fileName)) {
referenceFiles.push(ref);
}
return ref;
} catch (err) {
console.error('[main] open-reference-path error:', err);
return null;
}
});
// Remove reference file
ipcMain.handle('remove-reference', (_, fileName) => {
const idx = referenceFiles.findIndex(r => r.fileName === fileName);
if (idx !== -1) referenceFiles.splice(idx, 1);
return true;
});
// Remove all reference files
ipcMain.handle('remove-all-references', () => {
referenceFiles = [];
return true;
});
// Pick background image (gif/png/jpg)
ipcMain.handle('pick-bg-image', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
filters: [{ name: 'Images', extensions: ['gif', 'png', 'jpg', 'jpeg', 'webp'] }],
properties: ['openFile']
});
if (result.canceled || !result.filePaths[0]) return null;
const filePath = result.filePaths[0];
const data = fs.readFileSync(filePath);
const ext = path.extname(filePath).replace('.', '').toLowerCase();
const mime = ext === 'gif' ? 'image/gif' : ext === 'png' ? 'image/png' :
ext === 'webp' ? 'image/webp' : 'image/jpeg';
return `data:${mime};base64,${data.toString('base64')}`;
});
// Pick BGM audio file
ipcMain.handle('pick-bgm', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
filters: [{ name: 'Audio', extensions: ['mp3', 'ogg', 'wav', 'flac', 'm4a', 'aac'] }],
properties: ['openFile']
});
if (result.canceled || !result.filePaths[0]) return null;
return result.filePaths[0];
});
// Get working directory for terminal
ipcMain.handle('get-cwd', () => {
return currentFilePath ? path.dirname(currentFilePath) : process.cwd();
});
// --- DevTools ---
ipcMain.handle('toggle-devtools', () => {
mainWindow.webContents.toggleDevTools();
});
// --- Open folder in file explorer ---
ipcMain.handle('open-folder', (_, folderPath) => {
const { shell } = require('electron');
shell.openPath(folderPath);
});
// --- Get autosave info ---
ipcMain.handle('get-autosave-info', (_, customDir) => {
const dir = customDir || (currentFilePath ? path.dirname(currentFilePath) : null);
if (!dir) return null;
const base = currentFilePath ? path.basename(currentFilePath, path.extname(currentFilePath)) : '';
return { dir, prefix: base ? `${base}_autosave_` : '', hasFile: !!currentFilePath };
});
// --- Terminal (node-pty) ---
ipcMain.handle('terminal-start', async (_, cols, rows) => {
if (ptyProcess) {
ptyProcess.kill();
ptyProcess = null;
}
const pty = require('node-pty');
const shell = process.platform === 'win32' ? 'powershell.exe' : (process.env.SHELL || 'bash');
const cwd = currentFilePath ? path.dirname(currentFilePath) : process.cwd();
// Clean env: remove CLAUDECODE so nested claude sessions work
const cleanEnv = Object.assign({}, process.env);
delete cleanEnv.CLAUDECODE;
// Inject MCP API info for toki-mcp-server
if (apiPort && apiToken) {
cleanEnv.TOKI_PORT = String(apiPort);
cleanEnv.TOKI_TOKEN = apiToken;
}
ptyProcess = pty.spawn(shell, [], {
name: 'xterm-256color',
cols: cols || 120,
rows: rows || 24,
cwd,
env: cleanEnv
});
ptyProcess.onData((data) => broadcastToAll('terminal-data', data));
ptyProcess.onExit(() => {
broadcastToAll('terminal-exit');
ptyProcess = null;
});
return true;
});
ipcMain.on('terminal-input', (_, data) => {
if (ptyProcess) ptyProcess.write(data);
});
ipcMain.on('terminal-resize', (_, cols, rows) => {
if (ptyProcess) ptyProcess.resize(cols, rows);
});
ipcMain.handle('terminal-stop', () => {
if (ptyProcess) {
ptyProcess.kill();
ptyProcess = null;
}
return true;
});
// --- Claude prompt ---
ipcMain.handle('get-claude-prompt', () => {
if (!currentData) return null;
const fileName = currentFilePath ? path.basename(currentFilePath) : 'new file';
const stats = [];
if (currentData.lua) stats.push(`Lua: ${(currentData.lua.length/1024).toFixed(0)}KB`);
if (currentData.lorebook?.length) stats.push(`로어북: ${currentData.lorebook.length}개`);
if (currentData.regex?.length) stats.push(`정규식: ${currentData.regex.length}개`);
if (currentData.globalNote) stats.push(`글로벌노트: ${(currentData.globalNote.length/1024).toFixed(0)}KB`);
if (currentData.css) stats.push(`CSS: ${(currentData.css.length/1024).toFixed(0)}KB`);
return {
fileName,
name: currentData.name || '',
stats: stats.join(', '),
cwd: currentFilePath ? path.dirname(currentFilePath) : process.cwd()
};
});
// --- MCP ---
ipcMain.handle('get-mcp-info', () => {
if (!apiPort || !apiToken) return null;
return {
port: apiPort,
token: apiToken,
mcpServerPath: path.join(__dirname, 'toki-mcp-server.js')
};
});
function writeCurrentMcpConfig() {
if (!apiPort || !apiToken) return null;
// Write to home directory (~/.mcp.json) for user-level MCP config
// Claude Code reads this regardless of project context
// Merge with existing config to preserve other MCP servers
const configPath = path.join(os.homedir(), '.mcp.json');
let serverPath = path.join(__dirname, 'toki-mcp-server.js');
if (app.isPackaged) {
serverPath = serverPath.replace('app.asar', 'app.asar.unpacked');
}
let existing = {};
try {
if (fs.existsSync(configPath)) {
existing = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
}
} catch (e) { /* ignore parse errors */ }
if (!existing.mcpServers) existing.mcpServers = {};
existing.mcpServers['risutoki'] = {
type: 'stdio',
command: 'node',
args: [serverPath],
env: {
TOKI_PORT: String(apiPort),
TOKI_TOKEN: apiToken
}
};
fs.writeFileSync(configPath, JSON.stringify(existing, null, 2), 'utf-8');
console.log('[main] MCP config written:', configPath);
return configPath;
}
ipcMain.handle('write-mcp-config', () => {
return writeCurrentMcpConfig();
});
// --- Codex MCP config (config.toml) ---
function writeCodexMcpConfig() {
if (!apiPort || !apiToken) return null;
const codexDir = path.join(os.homedir(), '.codex');
if (!fs.existsSync(codexDir)) fs.mkdirSync(codexDir, { recursive: true });
const configPath = path.join(codexDir, 'config.toml');
let serverPath = path.join(__dirname, 'toki-mcp-server.js');
if (app.isPackaged) {
serverPath = serverPath.replace('app.asar', 'app.asar.unpacked');
}
// Normalize backslashes for TOML
serverPath = serverPath.replace(/\\/g, '/');
const risutokiBlock = [
'',
'# --- RisuToki MCP (auto-generated, do not edit) ---',
'[mcp_servers.risutoki]',
`command = "node"`,
`args = ["${serverPath}"]`,
'',
'[mcp_servers.risutoki.env]',
`TOKI_PORT = "${apiPort}"`,
`TOKI_TOKEN = "${apiToken}"`,
'# --- /RisuToki MCP ---',
'',
].join('\n');
let existing = '';
if (fs.existsSync(configPath)) {
existing = fs.readFileSync(configPath, 'utf-8');
// Remove old risutoki block if present
existing = existing.replace(/\n?# --- RisuToki MCP \(auto-generated.*?\n# --- \/RisuToki MCP ---\n?/s, '');
}
fs.writeFileSync(configPath, existing.trimEnd() + '\n' + risutokiBlock, 'utf-8');
console.log('[main] Codex MCP config written:', configPath);
return configPath;
}
function cleanupCodexMcpConfig() {
try {
const configPath = path.join(os.homedir(), '.codex', 'config.toml');
if (!fs.existsSync(configPath)) return;
let content = fs.readFileSync(configPath, 'utf-8');
const cleaned = content.replace(/\n?# --- RisuToki MCP \(auto-generated.*?\n# --- \/RisuToki MCP ---\n?/s, '');
fs.writeFileSync(configPath, cleaned, 'utf-8');
console.log('[main] Codex MCP config cleaned up');
} catch (e) { /* ignore */ }
}
ipcMain.handle('write-codex-mcp-config', () => {
return writeCodexMcpConfig();
});
// Write AGENTS.md for Codex (system prompt)
ipcMain.handle('write-codex-agents-md', (_, content) => {
const cwd = currentFilePath ? path.dirname(currentFilePath) : process.cwd();
const agentsPath = path.join(cwd, 'AGENTS.md');
fs.writeFileSync(agentsPath, content, 'utf-8');
console.log('[main] AGENTS.md written:', agentsPath);
return agentsPath;
});
// --- Image assets ---
ipcMain.handle('get-asset-list', () => {
if (!currentData) return [];
return (currentData.assets || []).map(a => ({
path: a.path,
size: a.data.length
}));
});
ipcMain.handle('get-asset-data', (_, assetPath) => {
if (!currentData) return null;
const asset = currentData.assets.find(a => a.path === assetPath);
if (!asset) return null;
return asset.data.toString('base64');
});
// Get all assets as name → data URI map (for preview {{raw::name}} / {{asset::name}})
let _assetsMapCache = null;
function invalidateAssetsMapCache() { _assetsMapCache = null; }
ipcMain.handle('get-all-assets-map', () => {
if (!currentData) return { assets: {}, debug: 'no data' };
if (_assetsMapCache) return _assetsMapCache;
const result = {};
const debug = {};
// 1) risuExt.additionalAssets — [[name, dataUri], ...]
const risuExt = currentData._risuExt || {};
const additionalAssets = risuExt.additionalAssets || [];
debug.additionalAssets = additionalAssets.length;
for (const aa of additionalAssets) {
if (Array.isArray(aa) && aa[0]) {
result[aa[0]] = aa[1] || '';
}
}
// 2) cardAssets (card.json data.assets) — all URI types
const cardAssets = currentData.cardAssets || [];
debug.cardAssets = cardAssets.length;
let cardResolved = 0, cardFailed = [];
for (const ca of cardAssets) {
const name = ca.name || '';
if (!name || result[name]) continue;
let uri = ca.uri || '';
if (uri.startsWith('ccdefault:')) {
const zipPath = uri.slice('ccdefault:'.length);
const asset = currentData.assets.find(a => a.path === zipPath);
if (asset) {
const ext = (ca.ext || 'png').toLowerCase();
const mime = ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' :
ext === 'gif' ? 'image/gif' : ext === 'svg' ? 'image/svg+xml' : 'image/jpeg';
result[name] = `data:${mime};base64,${asset.data.toString('base64')}`;
cardResolved++;
} else {
// ccdefault path not found in zip — try filename match fallback
const targetName = zipPath.split('/').pop().replace(/\.[^.]+$/, '');
const fallback = currentData.assets.find(a => {
const fn = a.path.split('/').pop().replace(/\.[^.]+$/, '');
return fn === targetName;
});
if (fallback) {
const ext = (ca.ext || 'png').toLowerCase();
const mime = ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' :
ext === 'gif' ? 'image/gif' : ext === 'svg' ? 'image/svg+xml' : 'image/jpeg';
result[name] = `data:${mime};base64,${fallback.data.toString('base64')}`;
cardResolved++;
} else {
cardFailed.push(name);
}
}
} else if (uri.startsWith('embeded://')) {
// RisuAI embeded:// scheme — maps to zip assets
const zipPath = uri.slice('embeded://'.length);
const asset = currentData.assets.find(a => a.path === zipPath);
if (asset) {
const ext = (ca.ext || zipPath.split('.').pop() || 'png').toLowerCase();
const mime = ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' :
ext === 'gif' ? 'image/gif' : ext === 'svg' ? 'image/svg+xml' : 'image/jpeg';
result[name] = `data:${mime};base64,${asset.data.toString('base64')}`;
cardResolved++;
} else {
cardFailed.push(name);
}
} else if (uri.startsWith('data:')) {
// Inline data URI — use directly
result[name] = uri;
cardResolved++;
} else if (uri.startsWith('http://') || uri.startsWith('https://')) {
// External URL — pass through
result[name] = uri;
cardResolved++;
} else if (uri) {
// Unknown URI scheme — try as-is
result[name] = uri;
cardResolved++;
} else {
cardFailed.push(name);
}
}
debug.cardResolved = cardResolved;
if (cardFailed.length > 0) debug.cardFailed = cardFailed.slice(0, 20);
// 3) module.risum assets (risumAssets + module.assets metadata)
const modAssets = currentData._moduleData?.module?.assets || [];
const risumBinaries = currentData.risumAssets || [];
debug.modAssets = modAssets.length;
debug.risumBinaries = risumBinaries.length;
if (modAssets.length > 0) debug.modAssetSample = JSON.stringify(modAssets[0]).substring(0, 300);
for (let i = 0; i < modAssets.length; i++) {
const ma = modAssets[i];
const name = ma.name || (Array.isArray(ma) ? ma[0] : '') || '';
if (!name || result[name]) continue;
const idx = typeof ma.index === 'number' ? ma.index : i;
const bin = risumBinaries[idx];
if (bin) {
const ext = (ma.ext || (Array.isArray(ma) ? ma[2] : '') || 'png').toLowerCase();
const mime = ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' :
ext === 'gif' ? 'image/gif' : ext === 'svg' ? 'image/svg+xml' : 'image/jpeg';
result[name] = `data:${mime};base64,${Buffer.isBuffer(bin) ? bin.toString('base64') : Buffer.from(bin).toString('base64')}`;
}
}
// 4) zip assets — filename-based mapping (fallback)
debug.zipAssets = (currentData.assets || []).length;
for (const asset of (currentData.assets || [])) {
const fileName = asset.path.split('/').pop();
const nameNoExt = fileName.replace(/\.[^.]+$/, '');
if (result[nameNoExt]) continue;
const ext = fileName.split('.').pop().toLowerCase();
const mime = ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' :
ext === 'gif' ? 'image/gif' : ext === 'svg' ? 'image/svg+xml' : 'image/jpeg';
result[nameNoExt] = `data:${mime};base64,${asset.data.toString('base64')}`;
}
debug.totalResolved = Object.keys(result).length;
_assetsMapCache = { assets: result, debug };
return _assetsMapCache;
});
// Add asset via file dialog (targetFolder: 'icon' or 'other')
ipcMain.handle('add-asset', async (_, targetFolder) => {
if (!currentData) return null;
invalidateAssetsMapCache();
const folder = targetFolder || 'other';
const basePath = folder === 'icon' ? 'assets/icon' : 'assets/other/image';
const result = await dialog.showOpenDialog(mainWindow, {
filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'webp', 'gif'] }],
properties: ['openFile', 'multiSelections']
});
if (result.canceled || !result.filePaths.length) return null;
const added = [];
for (const filePath of result.filePaths) {
const fileName = path.basename(filePath);
const assetPath = `${basePath}/${fileName}`;
// Avoid duplicates
if (currentData.assets.find(a => a.path === assetPath)) continue;
const data = fs.readFileSync(filePath);
currentData.assets.push({ path: assetPath, data });
// Add x_meta
const ext = path.extname(fileName).replace('.', '').toUpperCase();
const metaName = path.basename(fileName, path.extname(fileName));
currentData.xMeta[metaName] = { type: ext === 'JPG' ? 'JPEG' : ext };
added.push({ path: assetPath, size: data.length });
}
return added;
});
// Add asset from drag-dropped buffer (targetFolder: 'icon' or 'other')
ipcMain.handle('add-asset-buffer', (_, fileName, base64Data, targetFolder) => {
if (!currentData) return null;
invalidateAssetsMapCache();
const folder = targetFolder || 'other';
const basePath = folder === 'icon' ? 'assets/icon' : 'assets/other/image';
const assetPath = `${basePath}/${fileName}`;
if (currentData.assets.find(a => a.path === assetPath)) return null;
const data = Buffer.from(base64Data, 'base64');
currentData.assets.push({ path: assetPath, data });
const ext = path.extname(fileName).replace('.', '').toUpperCase();
const metaName = path.basename(fileName, path.extname(fileName));
currentData.xMeta[metaName] = { type: ext === 'JPG' ? 'JPEG' : ext };
return { path: assetPath, size: data.length };
});
// Delete asset
ipcMain.handle('delete-asset', (_, assetPath) => {
if (!currentData) return false;
invalidateAssetsMapCache();
const idx = currentData.assets.findIndex(a => a.path === assetPath);
if (idx === -1) return false;
currentData.assets.splice(idx, 1);
return true;
});
// Rename asset
ipcMain.handle('rename-asset', (_, oldPath, newName) => {
if (!currentData) return null;
const asset = currentData.assets.find(a => a.path === oldPath);
if (!asset) return null;
const dir = oldPath.substring(0, oldPath.lastIndexOf('/') + 1);
const newPath = dir + newName;
asset.path = newPath;
return newPath;
});
// Import JSON file (for lorebook/regex)
ipcMain.handle('import-json', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
filters: [{ name: 'JSON', extensions: ['json'] }],
properties: ['openFile', 'multiSelections']
});
if (result.canceled || !result.filePaths.length) return null;
const imported = [];
for (const filePath of result.filePaths) {
try {
const content = fs.readFileSync(filePath, 'utf-8');
const json = JSON.parse(content);
imported.push({ fileName: path.basename(filePath), data: json });
} catch (e) { /* skip invalid */ }
}
return imported;
});
// --- Autosave ---
ipcMain.handle('autosave-file', async (_, updatedFields) => {
if (!currentData) return { success: false, error: 'No data' };
const customDir = updatedFields._autosaveDir;
if (!currentFilePath && !customDir) return { success: false, error: 'No file path and no autosave dir' };
applyUpdates(currentData, updatedFields);
const dir = customDir || path.dirname(currentFilePath);
const base = currentFilePath ? path.basename(currentFilePath, path.extname(currentFilePath)) : (currentData.name || 'untitled');
const ts = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 15); // 20260224_123456
const autosaveName = `${base}_autosave_${ts}.charx`;
const autosavePath = path.join(dir, autosaveName);
try {
fs.mkdirSync(dir, { recursive: true });
saveCharx(autosavePath, currentData);
return { success: true, path: autosavePath };
} catch (err) {
console.error('[main] autosave error:', err);
return { success: false, error: err.message };
}
});
ipcMain.handle('cleanup-autosave', (_, customDir) => {
// Cleanup old autosave files (keep latest 5)
if (!currentFilePath) return false;
const dir = customDir || path.dirname(currentFilePath);
const base = path.basename(currentFilePath, path.extname(currentFilePath));
const prefix = `${base}_autosave_`;
try {
const files = fs.readdirSync(dir)
.filter(f => f.startsWith(prefix) && f.endsWith('.charx'))
.sort().reverse();
// Delete all autosave files (called on manual save)
for (const f of files) {
fs.unlinkSync(path.join(dir, f));
console.log('[main] Autosave cleaned:', f);
}
return true;
} catch (e) {
console.error('[main] cleanup-autosave error:', e);
return false;
}
});
ipcMain.handle('pick-autosave-dir', async () => {
const { dialog } = require('electron');
const result = await dialog.showOpenDialog(mainWindow, {
title: '자동저장 폴더 선택',
properties: ['openDirectory']
});
if (result.canceled || !result.filePaths.length) return null;
return result.filePaths[0];
});
// --- Persona files ---
ipcMain.handle('read-persona', (_, name) => {
const filePath = path.join(__dirname, 'assets', 'persona', `${name}.txt`);
try { return fs.readFileSync(filePath, 'utf-8'); } catch (e) { return null; }
});
ipcMain.handle('write-persona', (_, name, content) => {
const dir = path.join(__dirname, 'assets', 'persona');
try { fs.mkdirSync(dir, { recursive: true }); } catch (e) { /* exists */ }
const filePath = path.join(dir, `${name}.txt`);
try { fs.writeFileSync(filePath, content, 'utf-8'); return true; } catch (e) { return false; }
});
ipcMain.handle('list-personas', () => {
const dir = path.join(__dirname, 'assets', 'persona');
try { return fs.readdirSync(dir).filter(f => f.endsWith('.txt')).map(f => f.replace('.txt', '')); } catch (e) { return []; }
});
// --- System Prompt (temp file for Claude CLI) ---
ipcMain.handle('write-system-prompt', (_, content) => {
const tmpFile = path.join(os.tmpdir(), 'toki-system-prompt.txt');
fs.writeFileSync(tmpFile, content, 'utf-8');
return { filePath: tmpFile, platform: process.platform };
});
// --- Guides ---
// Packaged: extraResources → process.resourcesPath/guides
// Dev: __dirname/guides
// Session guides: imported guides stored in memory only (not saved to disk)
let sessionGuides = []; // [{ filename, content }]
function getGuidesDir() {
return app.isPackaged
? path.join(process.resourcesPath, 'guides')
: path.join(__dirname, 'guides');
}
ipcMain.handle('list-guides', () => {
const guidesDir = getGuidesDir();
let builtIn = [];
try {
builtIn = fs.readdirSync(guidesDir).filter(f => f.endsWith('.md')).sort();
} catch (e) { /* ignore */ }
const sessionNames = sessionGuides.map(g => g.filename);
// Return { builtIn, session } so renderer can distinguish
return { builtIn, session: sessionNames };
});
ipcMain.handle('read-guide', (_, filename) => {
// Check session guides first
const sg = sessionGuides.find(g => g.filename === filename);
if (sg) return sg.content;
// Fall back to disk
const filePath = path.join(getGuidesDir(), filename);
try {
return fs.readFileSync(filePath, 'utf-8');
} catch (e) { return null; }
});
ipcMain.handle('write-guide', (_, filename, content) => {
// Check if it's a session guide
const sg = sessionGuides.find(g => g.filename === filename);
if (sg) { sg.content = content; return true; }
// Otherwise write to disk (built-in)
const guidesDir = getGuidesDir();
try { fs.mkdirSync(guidesDir, { recursive: true }); } catch (e) { /* exists */ }
try { fs.writeFileSync(path.join(guidesDir, filename), content, 'utf-8'); return true; } catch (e) { return false; }
});
ipcMain.handle('import-guide', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
title: '가이드 파일 불러오기 (세션 전용)',
filters: [{ name: 'Markdown / Text', extensions: ['md', 'txt'] }],
properties: ['openFile', 'multiSelections']
});
if (result.canceled || !result.filePaths.length) return [];
const imported = [];
// Collect all existing names (built-in + session) for dedup
const guidesDir = getGuidesDir();
let builtInNames = [];
try { builtInNames = fs.readdirSync(guidesDir).filter(f => f.endsWith('.md')); } catch (e) { /* ignore */ }
for (const fp of result.filePaths) {
let name = path.basename(fp);
try {
const content = fs.readFileSync(fp, 'utf-8');
// Auto-rename if name conflicts with built-in or existing session guide
const ext = path.extname(name);
const base = name.slice(0, -ext.length);
let n = 1;
while (builtInNames.includes(name) || sessionGuides.some(g => g.filename === name)) {
n++;
name = `${base} (${n})${ext}`;
}
sessionGuides.push({ filename: name, content });
imported.push(name);
} catch (e) { /* skip */ }
}
return imported;
});
ipcMain.handle('delete-guide', (_, filename) => {
// Check session guide first