-
Notifications
You must be signed in to change notification settings - Fork 992
Expand file tree
/
Copy pathindex.ts
More file actions
243 lines (208 loc) · 7.51 KB
/
index.ts
File metadata and controls
243 lines (208 loc) · 7.51 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
/**
* Electron Main Process Entry
* Manages window creation, system tray, and IPC handlers
*/
import { app, BrowserWindow, nativeImage, session, shell } from 'electron';
import { join } from 'path';
import { GatewayManager } from '../gateway/manager';
import { registerIpcHandlers } from './ipc-handlers';
import { createTray } from './tray';
import { createMenu } from './menu';
import { appUpdater, registerUpdateHandlers } from './updater';
import { logger } from '../utils/logger';
import { warmupNetworkOptimization } from '../utils/uv-env';
import { ClawHubService } from '../gateway/clawhub';
import { ensureClawXContext, repairClawXOnlyBootstrapFiles } from '../utils/openclaw-workspace';
// Disable GPU acceleration for better compatibility
app.disableHardwareAcceleration();
// Global references
let mainWindow: BrowserWindow | null = null;
let isQuitting = false;
const gatewayManager = new GatewayManager();
const clawHubService = new ClawHubService();
/**
* Resolve the icons directory path (works in both dev and packaged mode)
*/
function getIconsDir(): string {
if (app.isPackaged) {
// Packaged: icons are in extraResources → process.resourcesPath/resources/icons
return join(process.resourcesPath, 'resources', 'icons');
}
// Development: relative to dist-electron/main/
return join(__dirname, '../../resources/icons');
}
/**
* Get the app icon for the current platform
*/
function getAppIcon(): Electron.NativeImage | undefined {
if (process.platform === 'darwin') return undefined; // macOS uses the app bundle icon
const iconsDir = getIconsDir();
const iconPath =
process.platform === 'win32'
? join(iconsDir, 'icon.ico')
: join(iconsDir, 'icon.png');
const icon = nativeImage.createFromPath(iconPath);
return icon.isEmpty() ? undefined : icon;
}
/**
* Create the main application window
*/
function createWindow(): BrowserWindow {
const isMac = process.platform === 'darwin';
const win = new BrowserWindow({
width: 1280,
height: 800,
minWidth: 960,
minHeight: 600,
icon: getAppIcon(),
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
nodeIntegration: false,
contextIsolation: true,
sandbox: false,
webviewTag: true, // Enable <webview> for embedding OpenClaw Control UI
},
titleBarStyle: isMac ? 'hiddenInset' : 'hidden',
trafficLightPosition: isMac ? { x: 16, y: 16 } : undefined,
frame: isMac,
show: false,
});
// Show window when ready to prevent visual flash
win.once('ready-to-show', () => {
win.show();
});
// Handle external links
win.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
// Load the app
if (process.env.VITE_DEV_SERVER_URL) {
win.loadURL(process.env.VITE_DEV_SERVER_URL);
win.webContents.openDevTools();
} else {
win.loadFile(join(__dirname, '../../dist/index.html'));
}
return win;
}
/**
* Initialize the application
*/
async function initialize(): Promise<void> {
// Initialize logger first
logger.init();
logger.info('=== ClawX Application Starting ===');
logger.debug(
`Runtime: platform=${process.platform}/${process.arch}, electron=${process.versions.electron}, node=${process.versions.node}, packaged=${app.isPackaged}`
);
// Warm up network optimization (non-blocking)
void warmupNetworkOptimization();
// Set application menu
createMenu();
// Create the main window
mainWindow = createWindow();
// Create system tray
createTray(mainWindow);
// Inject OpenRouter site headers (HTTP-Referer & X-Title) for rankings on openrouter.ai
session.defaultSession.webRequest.onBeforeSendHeaders(
{ urls: ['https://openrouter.ai/*'] },
(details, callback) => {
details.requestHeaders['HTTP-Referer'] = 'https://claw-x.com';
details.requestHeaders['X-Title'] = 'ClawX';
callback({ requestHeaders: details.requestHeaders });
},
);
// Override security headers ONLY for the OpenClaw Gateway Control UI
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
const isGatewayUrl = details.url.includes('127.0.0.1:18789') || details.url.includes('localhost:18789');
if (!isGatewayUrl) {
callback({ responseHeaders: details.responseHeaders });
return;
}
const headers = { ...details.responseHeaders };
delete headers['X-Frame-Options'];
delete headers['x-frame-options'];
if (headers['Content-Security-Policy']) {
headers['Content-Security-Policy'] = headers['Content-Security-Policy'].map(
(csp) => csp.replace(/frame-ancestors\s+'none'/g, "frame-ancestors 'self' *")
);
}
if (headers['content-security-policy']) {
headers['content-security-policy'] = headers['content-security-policy'].map(
(csp) => csp.replace(/frame-ancestors\s+'none'/g, "frame-ancestors 'self' *")
);
}
callback({ responseHeaders: headers });
});
// Register IPC handlers
registerIpcHandlers(gatewayManager, clawHubService, mainWindow);
// Register update handlers
registerUpdateHandlers(appUpdater, mainWindow);
// Note: Auto-check for updates is driven by the renderer (update store init)
// so it respects the user's "Auto-check for updates" setting.
// Minimize to tray on close instead of quitting (macOS & Windows)
mainWindow.on('close', (event) => {
if (!isQuitting) {
event.preventDefault();
mainWindow?.hide();
}
});
mainWindow.on('closed', () => {
mainWindow = null;
});
// Repair any bootstrap files that only contain ClawX markers (no OpenClaw
// template content). This fixes a race condition where ensureClawXContext()
// previously created the file before the gateway could seed the full template.
try {
repairClawXOnlyBootstrapFiles();
} catch (error) {
logger.warn('Failed to repair bootstrap files:', error);
}
// Start Gateway automatically (this seeds missing bootstrap files with full templates)
try {
logger.debug('Auto-starting Gateway...');
await gatewayManager.start();
logger.info('Gateway auto-start succeeded');
} catch (error) {
logger.error('Gateway auto-start failed:', error);
mainWindow?.webContents.send('gateway:error', String(error));
}
// Merge ClawX context snippets into the (now fully-seeded) bootstrap files
try {
ensureClawXContext();
} catch (error) {
logger.warn('Failed to merge ClawX context into workspace:', error);
}
}
// Application lifecycle
app.whenReady().then(() => {
initialize();
// Register activate handler AFTER app is ready to prevent
// "Cannot create BrowserWindow before app is ready" on macOS.
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
mainWindow = createWindow();
} else if (mainWindow && !mainWindow.isDestroyed()) {
// On macOS, clicking the dock icon should show the window if it's hidden
mainWindow.show();
mainWindow.focus();
}
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('before-quit', () => {
isQuitting = true;
// Fire-and-forget: do not await gatewayManager.stop() here.
// Awaiting inside a before-quit handler can stall Electron's
// replyToApplicationShouldTerminate: call when the quit is initiated
// by Squirrel.Mac (quitAndInstall), preventing the app from ever exiting.
void gatewayManager.stop().catch((err) => {
logger.warn('gatewayManager.stop() error during quit:', err);
});
});
// Export for testing
export { mainWindow, gatewayManager };