-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
893 lines (779 loc) · 28.4 KB
/
main.js
File metadata and controls
893 lines (779 loc) · 28.4 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
const { app, BrowserWindow, ipcMain } = require('electron');
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const { spawn, spawnSync } = require('node:child_process');
const CONFIG_PATH = path.join(process.cwd(), 'config.json');
const LOG_PATH = path.join(process.cwd(), 'log.txt');
const MAX_LOG_LINES = 200;
const DEFAULT_ROLES = [
{
id: 'ada-incubator',
name: 'Ada',
title: '创业孵化顾问',
description: '关注商业路径、执行节奏和冷启动推进,适合创业咨询与项目推进场景。',
avatar: 'https://api.dicebear.com/9.x/notionists/svg?seed=Ada&backgroundColor=f4efe6,dfe8d8,f8d7c4',
prompt: '你是 Ada,一位创业孵化顾问。回答务实、直接、可执行,像经验丰富的创业陪跑顾问。'
},
{
id: 'doctor',
name: 'Mia',
title: '医疗顾问',
description: '先澄清症状与背景,再给出风险提示和就医建议,不做正式诊断。',
avatar: 'https://api.dicebear.com/9.x/notionists/svg?seed=Mia&backgroundColor=f4efe6,dfe8d8,f8d7c4',
prompt: '你是一名医疗顾问助理。先澄清症状与背景,不做确诊,给出风险提醒和就医建议。'
},
{
id: 'lawyer',
name: 'Ethan',
title: '法律顾问',
description: '回答强调边界、合规和风险,适合合同、沟通留痕与基础法律咨询。',
avatar: 'https://api.dicebear.com/9.x/notionists/svg?seed=Ethan&backgroundColor=f4efe6,dfe8d8,f8d7c4',
prompt: '你是一名法律顾问助理。回答要有结构,说明合规边界与风险,并提醒咨询当地执业律师。'
},
{
id: 'hr',
name: 'Sophie',
title: '人力资源顾问',
description: '适合招聘、绩效、组织协同与团队沟通类问题,强调可落地动作。',
avatar: 'https://api.dicebear.com/9.x/notionists/svg?seed=Sophie&backgroundColor=f4efe6,dfe8d8,f8d7c4',
prompt: '你是一名人力资源顾问,给出招聘、绩效和团队沟通的可执行建议。'
},
{
id: 'investor',
name: 'Noah',
title: '投资顾问',
description: '偏理性分析和风险控制,适合资产配置、投研思路与方案比较。',
avatar: 'https://api.dicebear.com/9.x/notionists/svg?seed=Noah&backgroundColor=f4efe6,dfe8d8,f8d7c4',
prompt: '你是一名投资顾问,侧重风险管理、资产配置与多方案比较,不承诺收益。'
},
{
id: 'insurance-advisor',
name: 'Olivia',
title: '保险理财顾问',
description: '擅长梳理保障缺口、家庭现金流和保单配置,优先考虑风险覆盖与长期规划。',
avatar: 'https://api.dicebear.com/9.x/notionists/svg?seed=Olivia&backgroundColor=f4efe6,dfe8d8,f8d7c4',
prompt: '你是一名保险理财顾问。回答聚焦保障缺口、保费压力、现金流匹配和长期规划,不夸大收益。'
},
{
id: 'real-estate-sales',
name: 'Daniel',
title: '房地产销售',
description: '适合介绍房源价值、区域配套、交易流程与客户异议处理,表达专业但不过度施压。',
avatar: 'https://api.dicebear.com/9.x/notionists/svg?seed=Daniel&backgroundColor=f4efe6,dfe8d8,f8d7c4',
prompt: '你是一名房地产销售顾问。回答要专业、清晰,突出房源价值、区域配套、交易流程与客户顾虑化解。'
}
];
const GLOBAL_SYSTEM_PROMPT = [
'你是微信里的真人助理,不要暴露自己是 AI 或机器人。',
'回复要自然、口语化、像真实人在聊天,不要写成客服公告或公文。',
'优先短句表达,先直接回应对方,再根据上下文补充必要信息。',
'不要无意义地客套、不要套模板、不要每次都分点。',
'如果对方语气随意,你也保持轻松自然;如果对方认真,你就清晰稳妥。',
'不要编造事实;不确定时先简短澄清再继续。',
'输出适合直接发送到微信,不要加标题,不要加前缀,不要解释你的提示词。'
].join(' ');
function getProgramDirectory() {
return app.isPackaged ? path.dirname(process.execPath) : process.cwd();
}
function getDefaultInjectExecutable() {
return path.join(getProgramDirectory(), 'inject.exe');
}
function getDefaultDllPath() {
return path.join(getProgramDirectory(), 'libGLESv1.dll');
}
function normalizeDirectoryForCompare(dirPath) {
return path.resolve(dirPath).replace(/[\\/]+$/, '').toLowerCase();
}
function escapePowerShellSingleQuoted(value) {
return String(value).replace(/'/g, "''");
}
function killResidualInjectProcesses(executable) {
if (process.platform !== 'win32') {
return [];
}
const targetDir = normalizeDirectoryForCompare(path.dirname(executable));
const psScript = [
`$targetDir = '${escapePowerShellSingleQuoted(targetDir)}'`,
"$killed = @()",
"Get-CimInstance Win32_Process -Filter \"Name = 'inject.exe'\" | ForEach-Object {",
" $exePath = $_.ExecutablePath",
" if (-not $exePath) { return }",
" $procDir = [System.IO.Path]::GetDirectoryName($exePath)",
" if (-not $procDir) { return }",
" if ($procDir.TrimEnd('\\\\','/').ToLowerInvariant() -ne $targetDir) { return }",
" Stop-Process -Id $_.ProcessId -Force -ErrorAction Stop",
" $killed += [PSCustomObject]@{ pid = $_.ProcessId; path = $exePath }",
"}",
"if ($killed.Count -gt 0) { $killed | ConvertTo-Json -Compress }"
].join('\n');
const result = spawnSync('powershell.exe', ['-NoProfile', '-Command', psScript], {
encoding: 'utf8',
windowsHide: true
});
if (result.error) {
throw result.error;
}
if (result.status !== 0) {
const stderr = (result.stderr || '').trim();
throw new Error(stderr || `powershell exited with code ${String(result.status)}`);
}
const stdout = (result.stdout || '').trim();
if (!stdout) {
return [];
}
const parsed = JSON.parse(stdout);
return Array.isArray(parsed) ? parsed : [parsed];
}
const DEFAULT_CONFIG = {
selectedRoleId: 'ada-incubator',
groupReplyEnabled: false,
callbackPort: 5000,
upstreamBase: 'http://127.0.0.1:19088',
deepseekBaseUrl: 'https://api.deepseek.com',
deepseekModel: 'deepseek-chat',
deepseekApiKey: process.env.DEEPSEEK_API_KEY || '',
injectExecutable: getDefaultInjectExecutable(),
injectArgs: []
};
let mainWindow;
let callbackServer;
let config;
let injectProcess;
let logs = [];
let taskStatus = { roleId: '', status: 'idle', fromUserName: '', updatedAt: 0 };
let taskStatusResetTimer;
let conversations = [];
let runtimeUpstreamBase = '';
function ensureRuntimeFiles() {
if (!fs.existsSync(CONFIG_PATH)) {
fs.writeFileSync(CONFIG_PATH, JSON.stringify(DEFAULT_CONFIG, null, 2), 'utf8');
}
if (!fs.existsSync(LOG_PATH)) {
fs.writeFileSync(LOG_PATH, '', 'utf8');
}
}
function loadRecentLogs() {
try {
const text = fs.existsSync(LOG_PATH) ? fs.readFileSync(LOG_PATH, 'utf8') : '';
return text.split(/\r?\n/).filter(Boolean).slice(-MAX_LOG_LINES).reverse();
} catch (error) {
console.error(`Failed to read log file: ${error.message}`);
return [];
}
}
function pushLog(message) {
const line = `[${new Date().toISOString()}] ${message}`;
logs.unshift(line);
if (logs.length > MAX_LOG_LINES) logs.pop();
try {
fs.appendFileSync(LOG_PATH, `${line}\n`, 'utf8');
} catch (error) {
console.error(`Failed to append log: ${error.message}`);
}
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('bot-log', line);
}
console.log(line);
}
function safeJsonStringify(value) {
try {
return JSON.stringify(value);
} catch (error) {
return JSON.stringify({ error: `stringify_failed: ${error.message}` });
}
}
function safeErrorMessage(error) {
if (error instanceof Error) {
return error.message;
}
return String(error);
}
function normalizeBaseUrl(value) {
return String(value || '').replace(/\/+$/, '');
}
function getActiveUpstreamBase() {
return normalizeBaseUrl(runtimeUpstreamBase || config?.upstreamBase || DEFAULT_CONFIG.upstreamBase);
}
function maybeUpdateRuntimeUpstreamBase(httpPort) {
const port = Number(httpPort);
if (!Number.isFinite(port) || port <= 0) {
return;
}
const next = `http://127.0.0.1:${port}`;
const normalizedNext = normalizeBaseUrl(next);
const normalizedCurrent = normalizeBaseUrl(runtimeUpstreamBase);
const normalizedConfig = normalizeBaseUrl(config?.upstreamBase || '');
if (normalizedCurrent === normalizedNext) {
return;
}
runtimeUpstreamBase = normalizedNext;
if (normalizedConfig === normalizedNext) {
pushLog(`运行时上游端口确认: ${runtimeUpstreamBase}`);
return;
}
pushLog(`运行时上游端口已切换: ${normalizedConfig || '(empty)'} -> ${runtimeUpstreamBase}`);
}
function emitTaskStatus(nextTaskStatus) {
taskStatus = nextTaskStatus;
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('task-status', taskStatus);
}
}
function emitConversations() {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('conversation-state', conversations);
}
}
function upsertConversationMessage(userId, message) {
if (!userId) return;
const now = Date.now();
let conversation = conversations.find((item) => item.userId === userId);
if (!conversation) {
conversation = {
userId,
displayName: userId,
updatedAt: now,
messages: []
};
conversations = [conversation, ...conversations];
}
if (message.displayName) {
conversation.displayName = message.displayName;
}
conversation.updatedAt = message.createdAt || now;
conversation.messages.push({
id: `${conversation.updatedAt}-${conversation.messages.length}-${message.role}`,
role: message.role,
text: message.text,
createdAt: message.createdAt || now
});
if (conversation.messages.length > 40) {
conversation.messages = conversation.messages.slice(-40);
}
conversations = conversations
.map((item) => item.userId === userId ? conversation : item)
.sort((a, b) => b.updatedAt - a.updatedAt);
emitConversations();
}
function setTaskStatus(status, extras = {}) {
emitTaskStatus({
roleId: config?.selectedRoleId || '',
status,
fromUserName: extras.fromUserName || '',
updatedAt: Date.now()
});
}
function scheduleTaskStatusReset(delay = 1800) {
if (taskStatusResetTimer) clearTimeout(taskStatusResetTimer);
taskStatusResetTimer = setTimeout(() => {
emitTaskStatus({ roleId: '', status: 'idle', fromUserName: '', updatedAt: Date.now() });
taskStatusResetTimer = undefined;
}, delay);
}
function loadConfig() {
try {
const parsed = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
return {
...DEFAULT_CONFIG,
...parsed,
injectExecutable: parsed.injectExecutable || DEFAULT_CONFIG.injectExecutable
};
} catch (error) {
pushLog(`璇诲彇 config.json 澶辫触锛屽凡鍥為€€鍒伴粯璁ら厤缃? ${error.message}`);
fs.writeFileSync(CONFIG_PATH, JSON.stringify(DEFAULT_CONFIG, null, 2), 'utf8');
return { ...DEFAULT_CONFIG };
}
}
function saveConfig(nextConfig) {
config = { ...config, ...nextConfig };
fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
}
function getInjectExecutableCandidates() {
return [getDefaultInjectExecutable(), config.injectExecutable].filter(Boolean).filter((item, index, list) => list.indexOf(item) === index);
}
function resolveFirstExisting(candidates) {
for (const candidate of candidates) {
if (!candidate) continue;
const fullPath = path.isAbsolute(candidate) ? candidate : path.resolve(candidate);
if (fs.existsSync(fullPath)) {
return fullPath;
}
}
return '';
}
function getDefaultWeixinPath() {
return resolveFirstExisting([
'C:\\Program Files\\Tencent\\Weixin\\Weixin.exe',
'C:\\Program Files (x86)\\Tencent\\Weixin\\Weixin.exe',
'D:\\Program Files\\Tencent\\Weixin\\Weixin.exe',
'D:\\Program Files (x86)\\Tencent\\Weixin\\Weixin.exe'
]);
}
function getStartDiagnostics(executable, injectArgs) {
const expectedCallbackUrl = `http://127.0.0.1:${config.callbackPort}/api/recvMsg`;
const parsedConfig = (() => {
if (!Array.isArray(injectArgs) || injectArgs.length < 3) {
return null;
}
try {
return JSON.parse(injectArgs[2]);
} catch {
return null;
}
})();
return {
cwd: process.cwd(),
programDirectory: getProgramDirectory(),
configPath: CONFIG_PATH,
executable,
executableExists: fs.existsSync(executable),
injectExecutableConfig: config.injectExecutable || '',
injectArgsSource: Array.isArray(config.injectArgs) && config.injectArgs.length > 0 ? 'config.injectArgs' : 'buildInjectArgs',
injectArgsCount: Array.isArray(injectArgs) ? injectArgs.length : 0,
weixinPath: Array.isArray(injectArgs) ? (injectArgs[0] || '') : '',
weixinExists: Array.isArray(injectArgs) && injectArgs[0] ? fs.existsSync(injectArgs[0]) : false,
dllPath: Array.isArray(injectArgs) ? (injectArgs[1] || '') : '',
dllExists: Array.isArray(injectArgs) && injectArgs[1] ? fs.existsSync(injectArgs[1]) : false,
callbackPort: config.callbackPort,
upstreamBase: config.upstreamBase,
activeUpstreamBase: getActiveUpstreamBase(),
expectedCallbackUrl,
parsedInjectConfig: parsedConfig,
rawInjectArgsPreview: Array.isArray(injectArgs)
? injectArgs.map((item, index) => (index === 2 ? `[json] ${item}` : item))
: []
};
}
function listMatchingProcessesByPath(processName, expectedPath) {
if (process.platform !== 'win32' || !expectedPath) {
return [];
}
const normalizedPath = path.resolve(expectedPath).toLowerCase();
const psScript = [
`$targetPath = '${escapePowerShellSingleQuoted(normalizedPath)}'`,
"$items = @()",
`Get-CimInstance Win32_Process -Filter "Name = '${processName}'" | ForEach-Object {`,
" $exePath = $_.ExecutablePath",
" if (-not $exePath) { return }",
" if ($exePath.ToLowerInvariant() -ne $targetPath) { return }",
" $items += [PSCustomObject]@{ pid = $_.ProcessId; path = $exePath; commandLine = $_.CommandLine }",
"}",
"if ($items.Count -gt 0) { $items | ConvertTo-Json -Compress }"
].join('\n');
const result = spawnSync('powershell.exe', ['-NoProfile', '-Command', psScript], {
encoding: 'utf8',
windowsHide: true
});
if (result.error) {
throw result.error;
}
if (result.status !== 0) {
const stderr = (result.stderr || '').trim();
throw new Error(stderr || `powershell exited with code ${String(result.status)}`);
}
const stdout = (result.stdout || '').trim();
if (!stdout) {
return [];
}
const parsed = JSON.parse(stdout);
return Array.isArray(parsed) ? parsed : [parsed];
}
function buildInjectArgs() {
if (Array.isArray(config.injectArgs) && config.injectArgs.length > 0) {
return config.injectArgs;
}
const executable = resolveFirstExisting([config.injectExecutable, getDefaultInjectExecutable()]);
const dllPath = resolveFirstExisting([config.injectDllPath, getDefaultDllPath()]);
const weixinPath = resolveFirstExisting([config.weixinExecutable, getDefaultWeixinPath()]);
if (!executable) {
throw new Error('未找到 inject.exe');
}
if (!dllPath) {
throw new Error('未找到 libGLESv1.dll');
}
if (!weixinPath) {
throw new Error('未找到 Weixin.exe');
}
return [
weixinPath,
dllPath,
JSON.stringify({
recivemode: 'http',
tcp_ip: '127.0.0.1',
tcp_port: 61108,
http_server_port: 19088,
http_callback_url: `http://127.0.0.1:${config.callbackPort}/api/recvMsg`,
usedefault: false,
start_server_while_login: true
})
];
}
async function requestDeepSeekReply(inputText) {
if (!config.deepseekApiKey) {
throw new Error('鏈缃?DeepSeek API Key');
}
const role = DEFAULT_ROLES.find((item) => item.id === config.selectedRoleId) || DEFAULT_ROLES[0];
const response = await fetch(`${config.deepseekBaseUrl}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${config.deepseekApiKey}`
},
body: JSON.stringify({
model: config.deepseekModel,
messages: [
{ role: 'system', content: `${GLOBAL_SYSTEM_PROMPT} ${role.prompt}` },
{ role: 'user', content: inputText }
],
temperature: 0.6
})
});
if (!response.ok) {
const detail = await response.text();
throw new Error(`DeepSeek 璇锋眰澶辫触: HTTP ${response.status} ${detail}`);
}
const data = await response.json();
const reply = data?.choices?.[0]?.message?.content?.trim();
if (!reply) {
throw new Error('DeepSeek 杩斿洖涓虹┖');
}
return reply;
}
async function sendTextMessage(wxid, msg) {
const activeUpstreamBase = getActiveUpstreamBase();
const url = `${activeUpstreamBase}/api/send_text_msg`;
pushLog(`发送消息请求: url=${url}, wxid=${wxid}, length=${String(msg ? String(msg).length : 0)}`);
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ wxid, msg })
});
pushLog(`发送消息响应: status=${res.status}, ok=${String(res.ok)}, url=${url}`);
if (!res.ok) {
const detail = await res.text();
throw new Error(`鍙戦€佹秷鎭け璐? HTTP ${res.status} ${detail}`);
}
const text = await res.text();
pushLog(`发送消息响应体: ${text || '(empty)'}`);
}
function readStringField(value) {
if (typeof value === 'string') return value;
if (value && typeof value === 'object' && typeof value.String === 'string') {
return value.String;
}
return '';
}
function extractCallbackText(payload) {
const body = payload?.data || payload;
const realContent = normalizeMessageContent(body?.real_content ?? '');
if (realContent) return realContent;
return normalizeMessageContent(body?.Content ?? body?.content ?? body?.msg ?? body?.reply ?? '');
}
function extractCallbackFromUser(payload) {
const body = payload?.data || payload;
const directFrom =
readStringField(body?.FromUserName) ||
readStringField(body?.fromUserName) ||
readStringField(body?.fromUsr) ||
readStringField(body?.wxid);
if (directFrom) return directFrom;
return '';
}
function extractCallbackToUser(payload) {
const body = payload?.data || payload;
return (
readStringField(body?.ToUserName) ||
readStringField(body?.toUserName) ||
readStringField(body?.toUsr) ||
readStringField(body?.account_wxid)
);
}
function extractCallbackDisplayName(payload) {
const body = payload?.data || payload;
const senderProfile = body?.sender_profile || body?.member_info || {};
const roomProfile = body?.roominfo || body?.chatroom_info || {};
return (
readStringField(senderProfile?.remark) ||
readStringField(senderProfile?.displayName) ||
readStringField(senderProfile?.nickName) ||
readStringField(senderProfile?.nickname) ||
readStringField(senderProfile?.alias) ||
readStringField(roomProfile?.displayName) ||
readStringField(body?.nickName) ||
readStringField(body?.nickname) ||
extractCallbackFromUser(payload)
);
}
function extractMessage(payload) {
const body = payload?.data || payload;
const fromUserName = extractCallbackFromUser(payload);
const toUserName = extractCallbackToUser(payload);
const senderWxid =
readStringField(body?.room_sender_by) ||
readStringField(body?.member_info?.userName) ||
readStringField(body?.sender_profile?.userName);
const content = extractCallbackText(payload);
const msgType = Number(body?.msgType ?? body?.msg_type ?? body?.MsgType ?? 0);
const accountWxid = readStringField(body?.account_wxid);
const isGroup = typeof fromUserName === 'string' && fromUserName.includes('@chatroom');
const actualSender = isGroup && senderWxid ? senderWxid : fromUserName;
const replyTarget = isGroup ? fromUserName : actualSender;
const isSelfMessage = Boolean(accountWxid) && actualSender === accountWxid;
const displayName = extractCallbackDisplayName(payload);
return {
fromUserName: actualSender,
rawFromUserName: fromUserName,
toUserName,
replyTarget,
displayName,
content,
isGroup,
isSelfMessage,
msgType,
eventType: Number(body?.event_type ?? 0),
eventDesc: String(body?.event_desc ?? '')
};
}
function normalizeMessageContent(value) {
if (typeof value === 'string') return value.trim();
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
if (Array.isArray(value)) {
return value.map((item) => normalizeMessageContent(item)).filter(Boolean).join('\n').trim();
}
if (value && typeof value === 'object') {
const preferredKeys = ['text', 'content', 'title', 'desc', 'description'];
for (const key of preferredKeys) {
const normalized = normalizeMessageContent(value[key]);
if (normalized) return normalized;
}
try {
return JSON.stringify(value);
} catch {
return '';
}
}
return '';
}
function getMessagePreview(content, limit = 80) {
if (!content) return '';
const singleLine = content.replace(/\s+/g, ' ').trim();
return singleLine.length > limit ? `${singleLine.slice(0, limit)}...` : singleLine;
}
async function handleIncomingMessage(payload) {
pushLog(`Callback payload: ${safeJsonStringify(payload)}`);
maybeUpdateRuntimeUpstreamBase(payload?.http_port ?? payload?.data?.http_port);
const msg = extractMessage(payload);
if (msg.eventType === 10001) {
const actualHttpPort = Number(payload?.http_port ?? payload?.data?.http_port ?? 0);
const expectedPort = (() => {
try {
return new URL(config.upstreamBase).port || '80';
} catch {
return '';
}
})();
pushLog(`首次链接事件: pid=${String(payload?.pid ?? '')}, account=${String(payload?.account_wxid || '') || '(empty)'}, inject回连端口=${String(actualHttpPort || '')}, 预期upstream端口=${String(expectedPort || '')}`);
}
if (msg.msgType && msg.msgType !== 1) {
pushLog(`Skipped non-text callback: msgType=${msg.msgType}, eventType=${msg.eventType || 0}, eventDesc=${msg.eventDesc || ''}`);
return;
}
if (msg.isSelfMessage) {
pushLog(`Skipped self message: ${msg.fromUserName}`);
return;
}
if (!msg.replyTarget || !msg.content) {
pushLog(`Skipped callback message because replyTarget or content is missing. eventType=${msg.eventType || 0}, eventDesc=${msg.eventDesc || ''}`);
return;
}
if (msg.isGroup && !config.groupReplyEnabled) {
pushLog(`Ignored group message because group replies are disabled: ${msg.rawFromUserName}`);
return;
}
setTaskStatus('processing', { fromUserName: msg.fromUserName });
pushLog(`Received message from ${msg.fromUserName}: ${getMessagePreview(msg.content)}`);
upsertConversationMessage(msg.replyTarget, {
role: 'user',
text: msg.content,
displayName: msg.displayName || msg.fromUserName,
createdAt: Date.now()
});
try {
const reply = await requestDeepSeekReply(msg.content);
await sendTextMessage(msg.replyTarget, reply);
pushLog(`Auto replied to ${msg.replyTarget}`);
upsertConversationMessage(msg.replyTarget, {
role: 'assistant',
text: reply,
displayName: msg.displayName || msg.fromUserName,
createdAt: Date.now()
});
setTaskStatus('success', { fromUserName: msg.fromUserName });
scheduleTaskStatusReset();
} catch (error) {
setTaskStatus('error', { fromUserName: msg.fromUserName });
scheduleTaskStatusReset(2600);
throw error;
}
}
function startCallbackServer() {
if (callbackServer) {
callbackServer.close();
callbackServer = undefined;
}
callbackServer = http.createServer((req, res) => {
if ((req.method === 'POST' || req.method === 'PUT') && req.url === '/api/recvMsg') {
let body = '';
req.on('data', (chunk) => {
body += chunk.toString();
});
req.on('end', async () => {
try {
const payload = body ? JSON.parse(body) : {};
await handleIncomingMessage(payload);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true }));
} catch (error) {
pushLog(`澶勭悊鍥炶皟澶辫触: ${error.message}`);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: false, error: error.message }));
}
});
return;
}
if (req.method === 'GET' && req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true }));
return;
}
res.writeHead(404);
res.end('Not Found');
});
callbackServer.listen(config.callbackPort, '127.0.0.1', () => {
pushLog(`鍥炶皟鏈嶅姟宸插惎鍔? http://127.0.0.1:${config.callbackPort}/api/recvMsg`);
});
}
function startInject() {
runtimeUpstreamBase = '';
const executable = getInjectExecutableCandidates().find((candidate) => fs.existsSync(candidate));
if (!executable) {
pushLog(`鏈壘鍒?inject.exe锛屽凡鎸夊綋鍓嶇▼搴忕洰褰曟煡鎵? ${getDefaultInjectExecutable()}`);
return;
}
let injectArgs;
try {
injectArgs = buildInjectArgs();
} catch (error) {
pushLog(`娉ㄥ叆鍙傛暟鐢熸垚澶辫触: ${error.message}`);
return;
}
try {
const diagnostics = getStartDiagnostics(executable, injectArgs);
pushLog(`启动诊断: ${safeJsonStringify(diagnostics)}`);
} catch (error) {
pushLog(`生成启动诊断日志失败: ${safeErrorMessage(error)}`);
}
try {
const killed = killResidualInjectProcesses(executable);
if (killed.length > 0) {
const summary = killed.map((item) => `pid=${item.pid}`).join(', ');
pushLog(`已清理同目录残留 inject.exe 进程: ${summary}`);
} else {
pushLog(`未发现同目录残留 inject.exe 进程: ${path.dirname(executable)}`);
}
} catch (error) {
pushLog(`清理同目录 inject.exe 残留进程失败: ${error.message}`);
}
try {
const weixinPath = Array.isArray(injectArgs) ? injectArgs[0] : '';
const existingWeixin = listMatchingProcessesByPath('Weixin.exe', weixinPath);
if (existingWeixin.length > 0) {
const summary = existingWeixin.map((item) => `pid=${item.pid}`).join(', ');
pushLog(`启动前发现已存在的目标微信进程: ${summary}; path=${weixinPath}`);
} else if (weixinPath) {
pushLog(`启动前未发现目标微信进程: ${weixinPath}`);
}
} catch (error) {
pushLog(`查询目标微信进程失败: ${safeErrorMessage(error)}`);
}
injectProcess = spawn(executable, injectArgs, {
windowsHide: false,
detached: false,
stdio: 'ignore'
});
injectProcess.on('spawn', () => {
pushLog(`inject.exe 已创建子进程: pid=${String(injectProcess?.pid || '')}`);
});
injectProcess.on('error', (error) => {
pushLog(`inject.exe 启动失败: ${safeErrorMessage(error)}`);
});
injectProcess.on('exit', (code) => {
pushLog(`inject 杩涚▼閫€鍑猴紝code=${String(code)}`);
injectProcess = undefined;
});
pushLog(`宸插惎鍔ㄦ敞鍏ヨ繘绋? ${executable}`);
}
function createWindow() {
mainWindow = new BrowserWindow({
width: 1120,
height: 820,
backgroundColor: '#f4efe6',
autoHideMenuBar: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
}
});
mainWindow.setMenuBarVisibility(false);
mainWindow.loadFile(path.join(__dirname, 'renderer/index.html'));
}
app.whenReady().then(() => {
ensureRuntimeFiles();
logs = loadRecentLogs();
config = loadConfig();
createWindow();
startCallbackServer();
startInject();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
app.on('before-quit', () => {
if (callbackServer) callbackServer.close();
if (injectProcess && !injectProcess.killed) injectProcess.kill();
if (taskStatusResetTimer) clearTimeout(taskStatusResetTimer);
});
ipcMain.handle('app:get-state', () => ({
config,
roles: DEFAULT_ROLES,
logs,
conversations,
taskStatus,
paths: {
configPath: CONFIG_PATH,
logPath: LOG_PATH,
programDirectory: getProgramDirectory()
}
}));
ipcMain.handle('app:update-config', (_event, patch) => {
saveConfig(patch);
if (Object.prototype.hasOwnProperty.call(patch, 'callbackPort')) {
startCallbackServer();
}
pushLog('閰嶇疆宸叉洿鏂板苟鍐欏叆 config.json');
return {
config,
conversations,
taskStatus,
paths: {
configPath: CONFIG_PATH,
logPath: LOG_PATH,
programDirectory: getProgramDirectory()
}
};
});