-
Notifications
You must be signed in to change notification settings - Fork 992
Expand file tree
/
Copy pathipc-handlers.ts
More file actions
1893 lines (1681 loc) · 62 KB
/
ipc-handlers.ts
File metadata and controls
1893 lines (1681 loc) · 62 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
/**
* IPC Handlers
* Registers all IPC handlers for main-renderer communication
*/
import { ipcMain, BrowserWindow, shell, dialog, app, nativeImage } from 'electron';
import { existsSync, copyFileSync, statSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { homedir } from 'node:os';
import { join, extname, basename } from 'node:path';
import crypto from 'node:crypto';
import { GatewayManager } from '../gateway/manager';
import { ClawHubService, ClawHubSearchParams, ClawHubInstallParams, ClawHubUninstallParams } from '../gateway/clawhub';
import {
storeApiKey,
getApiKey,
deleteApiKey,
hasApiKey,
saveProvider,
getProvider,
deleteProvider,
setDefaultProvider,
getDefaultProvider,
getAllProvidersWithKeyInfo,
type ProviderConfig,
} from '../utils/secure-storage';
import { getOpenClawStatus, getOpenClawDir, getOpenClawConfigDir, getOpenClawSkillsDir, ensureDir } from '../utils/paths';
import { getOpenClawCliCommand, installOpenClawCliMac } from '../utils/openclaw-cli';
import { getSetting } from '../utils/store';
import {
saveProviderKeyToOpenClaw,
removeProviderFromOpenClaw,
setOpenClawDefaultModel,
setOpenClawDefaultModelWithOverride,
syncProviderConfigToOpenClaw,
updateAgentModelProvider,
} from '../utils/openclaw-auth';
import { logger } from '../utils/logger';
import {
saveChannelConfig,
getChannelConfig,
getChannelFormValues,
deleteChannelConfig,
listConfiguredChannels,
setChannelEnabled,
validateChannelConfig,
validateChannelCredentials,
} from '../utils/channel-config';
import { checkUvInstalled, installUv, setupManagedPython } from '../utils/uv-setup';
import { updateSkillConfig, getSkillConfig, getAllSkillConfigs } from '../utils/skill-config';
import { whatsAppLoginManager } from '../utils/whatsapp-login';
import { getProviderConfig } from '../utils/provider-registry';
import { deviceOAuthManager, OAuthProviderType } from '../utils/device-oauth';
/**
* For custom/ollama providers, derive a unique key for OpenClaw config files
* so that multiple instances of the same type don't overwrite each other.
* For all other providers the key is simply the provider type.
*
* @param type - Provider type (e.g. 'custom', 'ollama', 'openrouter')
* @param providerId - Unique provider ID from secure-storage (UUID-like)
* @returns A string like 'custom-a1b2c3d4' or 'openrouter'
*/
export function getOpenClawProviderKey(type: string, providerId: string): string {
if (type === 'custom' || type === 'ollama') {
const suffix = providerId.replace(/-/g, '').slice(0, 8);
return `${type}-${suffix}`;
}
if (type === 'minimax-portal-cn') {
return 'minimax-portal';
}
return type;
}
/**
* Register all IPC handlers
*/
export function registerIpcHandlers(
gatewayManager: GatewayManager,
clawHubService: ClawHubService,
mainWindow: BrowserWindow
): void {
// Gateway handlers
registerGatewayHandlers(gatewayManager, mainWindow);
// ClawHub handlers
registerClawHubHandlers(clawHubService);
// OpenClaw handlers
registerOpenClawHandlers();
// Provider handlers
registerProviderHandlers(gatewayManager);
// Shell handlers
registerShellHandlers();
// Dialog handlers
registerDialogHandlers();
// App handlers
registerAppHandlers();
// UV handlers
registerUvHandlers();
// Log handlers (for UI to read gateway/app logs)
registerLogHandlers();
// Skill config handlers (direct file access, no Gateway RPC)
registerSkillConfigHandlers();
// Cron task handlers (proxy to Gateway RPC)
registerCronHandlers(gatewayManager);
// Window control handlers (for custom title bar on Windows/Linux)
registerWindowHandlers(mainWindow);
// WhatsApp handlers
registerWhatsAppHandlers(mainWindow);
// Device OAuth handlers (Code Plan)
registerDeviceOAuthHandlers(mainWindow);
// File staging handlers (upload/send separation)
registerFileHandlers();
}
/**
* Skill config IPC handlers
* Direct read/write to ~/.openclaw/openclaw.json (bypasses Gateway RPC)
*/
function registerSkillConfigHandlers(): void {
// Update skill config (apiKey and env)
ipcMain.handle('skill:updateConfig', async (_, params: {
skillKey: string;
apiKey?: string;
env?: Record<string, string>;
}) => {
return updateSkillConfig(params.skillKey, {
apiKey: params.apiKey,
env: params.env,
});
});
// Get skill config
ipcMain.handle('skill:getConfig', async (_, skillKey: string) => {
return getSkillConfig(skillKey);
});
// Get all skill configs
ipcMain.handle('skill:getAllConfigs', async () => {
return getAllSkillConfigs();
});
}
/**
* Gateway CronJob type (as returned by cron.list RPC)
*/
interface GatewayCronJob {
id: string;
name: string;
description?: string;
enabled: boolean;
createdAtMs: number;
updatedAtMs: number;
schedule: { kind: string; expr?: string; everyMs?: number; at?: string; tz?: string };
payload: { kind: string; message?: string; text?: string };
delivery?: { mode: string; channel?: string; to?: string };
state: {
nextRunAtMs?: number;
lastRunAtMs?: number;
lastStatus?: string;
lastError?: string;
lastDurationMs?: number;
};
}
/**
* Transform a Gateway CronJob to the frontend CronJob format
*/
function transformCronJob(job: GatewayCronJob) {
// Extract message from payload
const message = job.payload?.message || job.payload?.text || '';
// Build target from delivery info
const channelType = job.delivery?.channel || 'unknown';
const target = {
channelType,
channelId: channelType,
channelName: channelType,
};
// Build lastRun from state
const lastRun = job.state?.lastRunAtMs
? {
time: new Date(job.state.lastRunAtMs).toISOString(),
success: job.state.lastStatus === 'ok',
error: job.state.lastError,
duration: job.state.lastDurationMs,
}
: undefined;
// Build nextRun from state
const nextRun = job.state?.nextRunAtMs
? new Date(job.state.nextRunAtMs).toISOString()
: undefined;
return {
id: job.id,
name: job.name,
message,
schedule: job.schedule, // Pass the object through; frontend parseCronSchedule handles it
target,
enabled: job.enabled,
createdAt: new Date(job.createdAtMs).toISOString(),
updatedAt: new Date(job.updatedAtMs).toISOString(),
lastRun,
nextRun,
};
}
/**
* Cron task IPC handlers
* Proxies cron operations to the Gateway RPC service.
* The frontend works with plain cron expression strings, but the Gateway
* expects CronSchedule objects ({ kind: "cron", expr: "..." }).
* These handlers bridge the two formats.
*/
function registerCronHandlers(gatewayManager: GatewayManager): void {
// List all cron jobs — transforms Gateway CronJob format to frontend CronJob format
ipcMain.handle('cron:list', async () => {
try {
const result = await gatewayManager.rpc('cron.list', { includeDisabled: true });
const data = result as { jobs?: GatewayCronJob[] };
const jobs = data?.jobs ?? [];
// Transform Gateway format to frontend format
return jobs.map(transformCronJob);
} catch (error) {
console.error('Failed to list cron jobs:', error);
throw error;
}
});
// Create a new cron job
ipcMain.handle('cron:create', async (_, input: {
name: string;
message: string;
schedule: string;
target: { channelType: string; channelId: string; channelName: string };
enabled?: boolean;
}) => {
try {
// Transform frontend input to Gateway cron.add format
// For Discord, the recipient must be prefixed with "channel:" or "user:"
const recipientId = input.target.channelId;
const deliveryTo = input.target.channelType === 'discord' && recipientId
? `channel:${recipientId}`
: recipientId;
const gatewayInput = {
name: input.name,
schedule: { kind: 'cron', expr: input.schedule },
payload: { kind: 'agentTurn', message: input.message },
enabled: input.enabled ?? true,
wakeMode: 'next-heartbeat',
sessionTarget: 'isolated',
delivery: {
mode: 'announce',
channel: input.target.channelType,
to: deliveryTo,
},
};
const result = await gatewayManager.rpc('cron.add', gatewayInput);
// Transform the returned job to frontend format
if (result && typeof result === 'object') {
return transformCronJob(result as GatewayCronJob);
}
return result;
} catch (error) {
console.error('Failed to create cron job:', error);
throw error;
}
});
// Update an existing cron job
ipcMain.handle('cron:update', async (_, id: string, input: Record<string, unknown>) => {
try {
// Transform schedule string to CronSchedule object if present
const patch = { ...input };
if (typeof patch.schedule === 'string') {
patch.schedule = { kind: 'cron', expr: patch.schedule };
}
// Transform message to payload format if present
if (typeof patch.message === 'string') {
patch.payload = { kind: 'agentTurn', message: patch.message };
delete patch.message;
}
const result = await gatewayManager.rpc('cron.update', { id, patch });
return result;
} catch (error) {
console.error('Failed to update cron job:', error);
throw error;
}
});
// Delete a cron job
ipcMain.handle('cron:delete', async (_, id: string) => {
try {
const result = await gatewayManager.rpc('cron.remove', { id });
return result;
} catch (error) {
console.error('Failed to delete cron job:', error);
throw error;
}
});
// Toggle a cron job enabled/disabled
ipcMain.handle('cron:toggle', async (_, id: string, enabled: boolean) => {
try {
const result = await gatewayManager.rpc('cron.update', { id, patch: { enabled } });
return result;
} catch (error) {
console.error('Failed to toggle cron job:', error);
throw error;
}
});
// Trigger a cron job manually
ipcMain.handle('cron:trigger', async (_, id: string) => {
try {
const result = await gatewayManager.rpc('cron.run', { id, mode: 'force' });
return result;
} catch (error) {
console.error('Failed to trigger cron job:', error);
throw error;
}
});
}
/**
* UV-related IPC handlers
*/
function registerUvHandlers(): void {
// Check if uv is installed
ipcMain.handle('uv:check', async () => {
return await checkUvInstalled();
});
// Install uv and setup managed Python
ipcMain.handle('uv:install-all', async () => {
try {
const isInstalled = await checkUvInstalled();
if (!isInstalled) {
await installUv();
}
// Always run python setup to ensure it exists in uv's cache
await setupManagedPython();
return { success: true };
} catch (error) {
console.error('Failed to setup uv/python:', error);
return { success: false, error: String(error) };
}
});
}
/**
* Log-related IPC handlers
* Allows the renderer to read application logs for diagnostics
*/
function registerLogHandlers(): void {
// Get recent logs from memory ring buffer
ipcMain.handle('log:getRecent', async (_, count?: number) => {
return logger.getRecentLogs(count);
});
// Read log file content (last N lines)
ipcMain.handle('log:readFile', async (_, tailLines?: number) => {
return logger.readLogFile(tailLines);
});
// Get log file path (so user can open in file explorer)
ipcMain.handle('log:getFilePath', async () => {
return logger.getLogFilePath();
});
// Get log directory path
ipcMain.handle('log:getDir', async () => {
return logger.getLogDir();
});
// List all log files
ipcMain.handle('log:listFiles', async () => {
return logger.listLogFiles();
});
}
/**
* Gateway-related IPC handlers
*/
function registerGatewayHandlers(
gatewayManager: GatewayManager,
mainWindow: BrowserWindow
): void {
// Get Gateway status
ipcMain.handle('gateway:status', () => {
return gatewayManager.getStatus();
});
// Check if Gateway is connected
ipcMain.handle('gateway:isConnected', () => {
return gatewayManager.isConnected();
});
// Start Gateway
ipcMain.handle('gateway:start', async () => {
try {
await gatewayManager.start();
return { success: true };
} catch (error) {
return { success: false, error: String(error) };
}
});
// Stop Gateway
ipcMain.handle('gateway:stop', async () => {
try {
await gatewayManager.stop();
return { success: true };
} catch (error) {
return { success: false, error: String(error) };
}
});
// Restart Gateway
ipcMain.handle('gateway:restart', async () => {
try {
await gatewayManager.restart();
return { success: true };
} catch (error) {
return { success: false, error: String(error) };
}
});
// Gateway RPC call
ipcMain.handle('gateway:rpc', async (_, method: string, params?: unknown, timeoutMs?: number) => {
try {
const result = await gatewayManager.rpc(method, params, timeoutMs);
return { success: true, result };
} catch (error) {
return { success: false, error: String(error) };
}
});
// Chat send with media — reads staged files from disk and builds attachments.
// Raster images (png/jpg/gif/webp) are inlined as base64 vision attachments.
// All other files are referenced by path in the message text so the model
// can access them via tools (the same format channels use).
const VISION_MIME_TYPES = new Set([
'image/png', 'image/jpeg', 'image/bmp', 'image/webp',
]);
ipcMain.handle('chat:sendWithMedia', async (_, params: {
sessionKey: string;
message: string;
deliver?: boolean;
idempotencyKey: string;
media?: Array<{ filePath: string; mimeType: string; fileName: string }>;
}) => {
try {
let message = params.message;
// The Gateway processes image attachments through TWO parallel paths:
// Path A: `attachments` param → parsed via `parseMessageWithAttachments` →
// injected as inline vision content when the model supports images.
// Format: { content: base64, mimeType: string, fileName?: string }
// Path B: `[media attached: ...]` in message text → Gateway's native image
// detection (`detectAndLoadPromptImages`) reads the file from disk and
// injects it as inline vision content. Also works for history messages.
// We use BOTH paths for maximum reliability.
const imageAttachments: Array<Record<string, unknown>> = [];
const fileReferences: string[] = [];
if (params.media && params.media.length > 0) {
for (const m of params.media) {
logger.info(`[chat:sendWithMedia] Processing file: ${m.fileName} (${m.mimeType}), path: ${m.filePath}, exists: ${existsSync(m.filePath)}, isVision: ${VISION_MIME_TYPES.has(m.mimeType)}`);
// Always add file path reference so the model can access it via tools
fileReferences.push(
`[media attached: ${m.filePath} (${m.mimeType}) | ${m.filePath}]`,
);
if (VISION_MIME_TYPES.has(m.mimeType)) {
// Send as base64 attachment in the format the Gateway expects:
// { content: base64String, mimeType: string, fileName?: string }
// The Gateway normalizer looks for `a.content` (NOT `a.source.data`).
const fileBuffer = readFileSync(m.filePath);
const base64Data = fileBuffer.toString('base64');
logger.info(`[chat:sendWithMedia] Read ${fileBuffer.length} bytes, base64 length: ${base64Data.length}`);
imageAttachments.push({
content: base64Data,
mimeType: m.mimeType,
fileName: m.fileName,
});
}
}
}
// Append file references to message text so the model knows about them
if (fileReferences.length > 0) {
const refs = fileReferences.join('\n');
message = message ? `${message}\n\n${refs}` : refs;
}
const rpcParams: Record<string, unknown> = {
sessionKey: params.sessionKey,
message,
deliver: params.deliver ?? false,
idempotencyKey: params.idempotencyKey,
};
if (imageAttachments.length > 0) {
rpcParams.attachments = imageAttachments;
}
logger.info(`[chat:sendWithMedia] Sending: message="${message.substring(0, 100)}", attachments=${imageAttachments.length}, fileRefs=${fileReferences.length}`);
// Use a longer timeout when images are present (120s vs default 30s)
const timeoutMs = imageAttachments.length > 0 ? 120000 : 30000;
const result = await gatewayManager.rpc('chat.send', rpcParams, timeoutMs);
logger.info(`[chat:sendWithMedia] RPC result: ${JSON.stringify(result)}`);
return { success: true, result };
} catch (error) {
logger.error(`[chat:sendWithMedia] Error: ${String(error)}`);
return { success: false, error: String(error) };
}
});
// Get the Control UI URL with token for embedding
ipcMain.handle('gateway:getControlUiUrl', async () => {
try {
const status = gatewayManager.getStatus();
const token = await getSetting('gatewayToken');
const port = status.port || 18789;
// Pass token as query param - Control UI will store it in localStorage
const url = `http://127.0.0.1:${port}/?token=${encodeURIComponent(token)}`;
return { success: true, url, port, token };
} catch (error) {
return { success: false, error: String(error) };
}
});
// Health check
ipcMain.handle('gateway:health', async () => {
try {
const health = await gatewayManager.checkHealth();
return { success: true, ...health };
} catch (error) {
return { success: false, ok: false, error: String(error) };
}
});
// Forward Gateway events to renderer
gatewayManager.on('status', (status) => {
if (!mainWindow.isDestroyed()) {
mainWindow.webContents.send('gateway:status-changed', status);
}
});
gatewayManager.on('message', (message) => {
if (!mainWindow.isDestroyed()) {
mainWindow.webContents.send('gateway:message', message);
}
});
gatewayManager.on('notification', (notification) => {
if (!mainWindow.isDestroyed()) {
mainWindow.webContents.send('gateway:notification', notification);
}
});
gatewayManager.on('channel:status', (data) => {
if (!mainWindow.isDestroyed()) {
mainWindow.webContents.send('gateway:channel-status', data);
}
});
gatewayManager.on('chat:message', (data) => {
if (!mainWindow.isDestroyed()) {
mainWindow.webContents.send('gateway:chat-message', data);
}
});
gatewayManager.on('exit', (code) => {
if (!mainWindow.isDestroyed()) {
mainWindow.webContents.send('gateway:exit', code);
}
});
gatewayManager.on('error', (error) => {
if (!mainWindow.isDestroyed()) {
mainWindow.webContents.send('gateway:error', error.message);
}
});
}
/**
* OpenClaw-related IPC handlers
* For checking package status and channel configuration
*/
function registerOpenClawHandlers(): void {
// Get OpenClaw package status
ipcMain.handle('openclaw:status', () => {
const status = getOpenClawStatus();
logger.info('openclaw:status IPC called', status);
return status;
});
// Check if OpenClaw is ready (package present)
ipcMain.handle('openclaw:isReady', () => {
const status = getOpenClawStatus();
return status.packageExists;
});
// Get the resolved OpenClaw directory path (for diagnostics)
ipcMain.handle('openclaw:getDir', () => {
return getOpenClawDir();
});
// Get the OpenClaw config directory (~/.openclaw)
ipcMain.handle('openclaw:getConfigDir', () => {
return getOpenClawConfigDir();
});
// Get the OpenClaw skills directory (~/.openclaw/skills)
ipcMain.handle('openclaw:getSkillsDir', () => {
const dir = getOpenClawSkillsDir();
ensureDir(dir);
return dir;
});
// Get a shell command to run OpenClaw CLI without modifying PATH
ipcMain.handle('openclaw:getCliCommand', () => {
try {
const status = getOpenClawStatus();
if (!status.packageExists) {
return { success: false, error: `OpenClaw package not found at: ${status.dir}` };
}
if (!existsSync(status.entryPath)) {
return { success: false, error: `OpenClaw entry script not found at: ${status.entryPath}` };
}
return { success: true, command: getOpenClawCliCommand() };
} catch (error) {
return { success: false, error: String(error) };
}
});
// Install a system-wide openclaw command on macOS (requires admin prompt)
ipcMain.handle('openclaw:installCliMac', async () => {
return installOpenClawCliMac();
});
// ==================== Channel Configuration Handlers ====================
// Save channel configuration
ipcMain.handle('channel:saveConfig', async (_, channelType: string, config: Record<string, unknown>) => {
try {
logger.info('channel:saveConfig', { channelType, keys: Object.keys(config || {}) });
saveChannelConfig(channelType, config);
return { success: true };
} catch (error) {
console.error('Failed to save channel config:', error);
return { success: false, error: String(error) };
}
});
// Get channel configuration
ipcMain.handle('channel:getConfig', async (_, channelType: string) => {
try {
const config = getChannelConfig(channelType);
return { success: true, config };
} catch (error) {
console.error('Failed to get channel config:', error);
return { success: false, error: String(error) };
}
});
// Get channel form values (reverse-transformed for UI pre-fill)
ipcMain.handle('channel:getFormValues', async (_, channelType: string) => {
try {
const values = getChannelFormValues(channelType);
return { success: true, values };
} catch (error) {
console.error('Failed to get channel form values:', error);
return { success: false, error: String(error) };
}
});
// Delete channel configuration
ipcMain.handle('channel:deleteConfig', async (_, channelType: string) => {
try {
deleteChannelConfig(channelType);
return { success: true };
} catch (error) {
console.error('Failed to delete channel config:', error);
return { success: false, error: String(error) };
}
});
// List configured channels
ipcMain.handle('channel:listConfigured', async () => {
try {
const channels = listConfiguredChannels();
return { success: true, channels };
} catch (error) {
console.error('Failed to list channels:', error);
return { success: false, error: String(error) };
}
});
// Enable or disable a channel
ipcMain.handle('channel:setEnabled', async (_, channelType: string, enabled: boolean) => {
try {
setChannelEnabled(channelType, enabled);
return { success: true };
} catch (error) {
console.error('Failed to set channel enabled:', error);
return { success: false, error: String(error) };
}
});
// Validate channel configuration
ipcMain.handle('channel:validate', async (_, channelType: string) => {
try {
const result = await validateChannelConfig(channelType);
return { success: true, ...result };
} catch (error) {
console.error('Failed to validate channel:', error);
return { success: false, valid: false, errors: [String(error)], warnings: [] };
}
});
// Validate channel credentials by calling actual service APIs (before saving)
ipcMain.handle('channel:validateCredentials', async (_, channelType: string, config: Record<string, string>) => {
try {
const result = await validateChannelCredentials(channelType, config);
return { success: true, ...result };
} catch (error) {
console.error('Failed to validate channel credentials:', error);
return { success: false, valid: false, errors: [String(error)], warnings: [] };
}
});
}
/**
* WhatsApp Login Handlers
*/
function registerWhatsAppHandlers(mainWindow: BrowserWindow): void {
// Request WhatsApp QR code
ipcMain.handle('channel:requestWhatsAppQr', async (_, accountId: string) => {
try {
logger.info('channel:requestWhatsAppQr', { accountId });
await whatsAppLoginManager.start(accountId);
return { success: true };
} catch (error) {
logger.error('channel:requestWhatsAppQr failed', error);
return { success: false, error: String(error) };
}
});
// Cancel WhatsApp login
ipcMain.handle('channel:cancelWhatsAppQr', async () => {
try {
await whatsAppLoginManager.stop();
return { success: true };
} catch (error) {
logger.error('channel:cancelWhatsAppQr failed', error);
return { success: false, error: String(error) };
}
});
// Check WhatsApp status (is it active?)
// ipcMain.handle('channel:checkWhatsAppStatus', ...)
// Forward events to renderer
whatsAppLoginManager.on('qr', (data) => {
if (!mainWindow.isDestroyed()) {
mainWindow.webContents.send('channel:whatsapp-qr', data);
}
});
whatsAppLoginManager.on('success', (data) => {
if (!mainWindow.isDestroyed()) {
logger.info('whatsapp:login-success', data);
mainWindow.webContents.send('channel:whatsapp-success', data);
}
});
whatsAppLoginManager.on('error', (error) => {
if (!mainWindow.isDestroyed()) {
logger.error('whatsapp:login-error', error);
mainWindow.webContents.send('channel:whatsapp-error', error);
}
});
}
/**
* Device OAuth Handlers (Code Plan)
*/
function registerDeviceOAuthHandlers(mainWindow: BrowserWindow): void {
deviceOAuthManager.setWindow(mainWindow);
// Request Provider OAuth initialization
ipcMain.handle('provider:requestOAuth', async (_, provider: OAuthProviderType, region?: 'global' | 'cn') => {
try {
logger.info(`provider:requestOAuth for ${provider}`);
await deviceOAuthManager.startFlow(provider, region);
return { success: true };
} catch (error) {
logger.error('provider:requestOAuth failed', error);
return { success: false, error: String(error) };
}
});
// Cancel Provider OAuth
ipcMain.handle('provider:cancelOAuth', async () => {
try {
await deviceOAuthManager.stopFlow();
return { success: true };
} catch (error) {
logger.error('provider:cancelOAuth failed', error);
return { success: false, error: String(error) };
}
});
}
/**
* Provider-related IPC handlers
*/
function registerProviderHandlers(gatewayManager: GatewayManager): void {
// Listen for OAuth success to automatically restart the Gateway with new tokens/configs
deviceOAuthManager.on('oauth:success', (providerType) => {
logger.info(`[IPC] Restarting Gateway after ${providerType} OAuth success...`);
void gatewayManager.restart().catch(err => {
logger.error('Failed to restart Gateway after OAuth success:', err);
});
});
// Get all providers with key info
ipcMain.handle('provider:list', async () => {
return await getAllProvidersWithKeyInfo();
});
// Get a specific provider
ipcMain.handle('provider:get', async (_, providerId: string) => {
return await getProvider(providerId);
});
// Save a provider configuration
ipcMain.handle('provider:save', async (_, config: ProviderConfig, apiKey?: string) => {
try {
// Save the provider config
await saveProvider(config);
// Derive the unique OpenClaw key for this provider instance
const ock = getOpenClawProviderKey(config.type, config.id);
// Store the API key if provided
if (apiKey !== undefined) {
const trimmedKey = apiKey.trim();
if (trimmedKey) {
await storeApiKey(config.id, trimmedKey);
// Also write to OpenClaw auth-profiles.json so the gateway can use it
try {
saveProviderKeyToOpenClaw(ock, trimmedKey);
} catch (err) {
console.warn('Failed to save key to OpenClaw auth-profiles:', err);
}
}
}
// Sync the provider configuration to openclaw.json so Gateway knows about it
try {
const meta = getProviderConfig(config.type);
const api = config.type === 'custom' || config.type === 'ollama' ? 'openai-completions' : meta?.api;
if (api) {
syncProviderConfigToOpenClaw(ock, config.model, {
baseUrl: config.baseUrl || meta?.baseUrl,
api,
apiKeyEnv: meta?.apiKeyEnv,
headers: meta?.headers,
});
if (config.type === 'custom' || config.type === 'ollama') {
const resolvedKey = apiKey !== undefined
? (apiKey.trim() || null)
: await getApiKey(config.id);
if (resolvedKey && config.baseUrl) {
const modelId = config.model;
updateAgentModelProvider(ock, {
baseUrl: config.baseUrl,
api: 'openai-completions',
models: modelId ? [{ id: modelId, name: modelId }] : [],
apiKey: resolvedKey,
});
}
}
// Restart Gateway so it picks up the new config and env vars
logger.info(`Restarting Gateway after saving provider "${ock}" config`);
void gatewayManager.restart().catch((err) => {
logger.warn('Gateway restart after provider save failed:', err);
});
}
} catch (err) {
console.warn('Failed to sync openclaw provider config:', err);
}
return { success: true };
} catch (error) {
return { success: false, error: String(error) };
}
});
// Delete a provider
ipcMain.handle('provider:delete', async (_, providerId: string) => {
try {
const existing = await getProvider(providerId);
await deleteProvider(providerId);
// Best-effort cleanup in OpenClaw auth profiles & openclaw.json config
if (existing?.type) {
try {
const ock = getOpenClawProviderKey(existing.type, providerId);
removeProviderFromOpenClaw(ock);
// Restart Gateway so it no longer loads the deleted provider's plugin/config
logger.info(`Restarting Gateway after deleting provider "${ock}"`);
void gatewayManager.restart().catch((err) => {
logger.warn('Gateway restart after provider delete failed:', err);
});
} catch (err) {
console.warn('Failed to completely remove provider from OpenClaw:', err);
}
}
return { success: true };
} catch (error) {
return { success: false, error: String(error) };
}
});
// Update API key for a provider
ipcMain.handle('provider:setApiKey', async (_, providerId: string, apiKey: string) => {
try {
await storeApiKey(providerId, apiKey);
// Also write to OpenClaw auth-profiles.json
const provider = await getProvider(providerId);
const providerType = provider?.type || providerId;
const ock = getOpenClawProviderKey(providerType, providerId);
try {
saveProviderKeyToOpenClaw(ock, apiKey);
} catch (err) {
console.warn('Failed to save key to OpenClaw auth-profiles:', err);
}
return { success: true };
} catch (error) {
return { success: false, error: String(error) };
}
});
// Atomically update provider config and API key
ipcMain.handle(
'provider:updateWithKey',
async (
_,
providerId: string,
updates: Partial<ProviderConfig>,
apiKey?: string
) => {
const existing = await getProvider(providerId);
if (!existing) {
return { success: false, error: 'Provider not found' };
}
const previousKey = await getApiKey(providerId);
const previousOck = getOpenClawProviderKey(existing.type, providerId);
try {
const nextConfig: ProviderConfig = {
...existing,
...updates,
updatedAt: new Date().toISOString(),
};
const ock = getOpenClawProviderKey(nextConfig.type, providerId);
await saveProvider(nextConfig);