-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathframe-fix-wrapper.js
More file actions
1624 lines (1472 loc) · 66.8 KB
/
Copy pathframe-fix-wrapper.js
File metadata and controls
1624 lines (1472 loc) · 66.8 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
{
const _fs = require('fs');
const _path = require('path');
const _existing = _path.join(_path.dirname(process.resourcesPath || ''), 'Helpers', 'disclaimer');
let _haveSystemDisclaimer = false;
try {
const _stat = _fs.statSync(_existing);
_haveSystemDisclaimer = _stat.uid === 0;
} catch (_) {}
if (!_haveSystemDisclaimer) {
const _xdgConfigHome = process.env.XDG_CONFIG_HOME || _path.join(require('os').userInfo().homedir, '.config');
Object.defineProperty(process, 'resourcesPath', {
value: _path.join(_xdgConfigHome, 'Claude', 'cowork-resources'),
writable: true,
configurable: true,
enumerable: true,
});
}
}
// Patch macOS-only systemPreferences methods that don't exist on Linux
const { systemPreferences, app: _earlyApp } = require('electron');
if (typeof systemPreferences.setUserDefault !== 'function') {
systemPreferences.setUserDefault = function(key, type, value) {
// no-op on Linux
};
}
if (typeof systemPreferences.getUserDefault !== 'function') {
systemPreferences.getUserDefault = function(key, type) {
return undefined;
};
}
if (typeof systemPreferences.promptTouchID !== 'function') {
systemPreferences.promptTouchID = function(reason) {
return Promise.reject(new Error('Touch ID unavailable on Linux'));
};
}
// Patch macOS-only Electron app methods (NSUserActivity / Handoff APIs).
// We spoof process.platform === "darwin" so the asar's darwin-gated callsites
// reach these methods; on Linux Electron they don't exist, throwing
// `TypeError: app.invalidateCurrentActivity is not a function` and crashing
// the main process with a JS error dialog.
// See: claude-cowork-linux issues #104, #106
if (_earlyApp) {
const _macOnlyAppMethods = [
'invalidateCurrentActivity',
'setUserActivity',
'updateCurrentActivity',
'resignCurrentActivity',
'getCurrentActivityType',
// WebAuthn (passkey/security-key) setup is macOS-only; absent on Linux
// Electron, so the darwin-gated callsite throws and crashes launch. See #128.
'configureWebAuthn',
];
for (const _m of _macOnlyAppMethods) {
if (typeof _earlyApp[_m] !== 'function') {
_earlyApp[_m] = function() { /* no-op on Linux */ };
}
}
// moveToApplicationsFolder is macOS-only; the asar's prompt path is gated
// by a confirm dialog but stub it defensively so a stray call can't crash.
if (typeof _earlyApp.moveToApplicationsFolder !== 'function') {
_earlyApp.moveToApplicationsFolder = function() { return false; };
}
}
// Inject frame fix and Cowork support before main app loads
const Module = require('module');
const originalRequire = Module.prototype.require;
const path = require('path');
const os = require('os');
const fs = require('fs');
// Authoritative homedir from /etc/passwd (getpwuid_r), NOT from $HOME.
// os.homedir() trusts the HOME env var, which can be set to any path.
// os.userInfo().homedir reads from the system password database — the
// user's environment can't override it. Use this for all security
// boundaries (allowlists, path validation). Expose via global so
// downstream modules (ipc_overrides, spaces_store) use the same source.
const PASSWD_HOMEDIR = os.userInfo().homedir;
global.__coworkPasswdHomedir = PASSWD_HOMEDIR;
const {
createAsarAdapter,
DEFAULT_FILESYSTEM_PATH_ALIASES,
isFileSystemPathRewriteChannel,
rewriteAliasedFilePath,
} = require('./cowork/asar_adapter.js');
const { createDirs } = require('./cowork/dirs.js');
const { createSessionOrchestrator } = require('./cowork/session_orchestrator.js');
const { createSessionStore } = require('./cowork/session_store.js');
const { createIpcTap } = require('./cowork/ipc_tap.js');
const { createOverrideRegistry, matchOverride, extractEipcUuid, proactivelyRegisterOverrides, isProactiveChannel } = require('./cowork/ipc_overrides.js');
const { createAutoPermissionsCap } = require('./cowork/auto_permissions_cap.js');
const { createBridgeCanary } = require('./cowork/bridge_canary.js');
// Single cap instance for the process. Closure-private state lives inside
// the factory; we just keep the wrapHandler reference. The cap is one of
// the "wrapper-side rails" that bounds the manual permission flow which
// Phase 1 stopped shadowing -- see SECURITY notes in the cap module.
const _autoPermissionsCap = createAutoPermissionsCap();
// Opt-in canary that observes bridge-related channel registrations and
// warns once when a previously-unseen one shows up. The regression alarm
// for "Anthropic shipped a new bridge channel between releases."
const _bridgeCanary = createBridgeCanary();
// Suppress EPIPE errors on stdout/stderr (normal in piped/Electron environments)
// and prevent them from becoming uncaught exception crash dialogs.
function _epipeHandler(err) {
if (err.code === 'EPIPE') return;
throw err;
}
if (process.stdout && typeof process.stdout.on === 'function') {
process.stdout.on('error', _epipeHandler);
}
if (process.stderr && typeof process.stderr.on === 'function') {
process.stderr.on('error', _epipeHandler);
}
// Catch EPIPE from any other pipe (IPC, Winston transports, CCD subprocess)
// that would otherwise surface as uncaught exception error dialogs.
const _origListeners = process.listeners('uncaughtException');
process.removeAllListeners('uncaughtException');
process.on('uncaughtException', (err, origin) => {
if (err && err.code === 'EPIPE') {
// Log once, don't crash
try { fs.appendFileSync(
path.join(process.env.CLAUDE_LOG_DIR || path.join(PASSWD_HOMEDIR, '.local', 'state', 'claude-cowork', 'logs'), 'epipe-suppressed.log'),
`[${new Date().toISOString()}] EPIPE suppressed: ${err.stack || err.message}\n`,
{ mode: 0o600 }
); } catch (_) {}
return;
}
// Re-throw to existing handlers (Electron's dialog, etc.)
for (const listener of _origListeners) {
listener(err, origin);
}
});
console.log('[Frame Fix] Wrapper v2.5 loaded');
console.log('[Frame Fix] EPIPE suppression enabled');
if (process.env.CLAUDE_DEVTOOLS === '1') console.log('[Frame Fix] DevTools mode enabled');
// ── Bridge forwardEvent patch ──────────────────────────────────────────
// The asar's sessions-bridge class has a forwardEvent method that drops
// "result" and "stream_event" types. On macOS the VM's MITM proxy
// forwards those to CCR instead. On Linux there's no proxy, so we patch
// forwardEvent to stop dropping them — the bridge transport (already
// connected) will POST them to CCR directly.
//
// Detection: the bridge class extends EventEmitter and subscribes to
// "remote_session_start" immediately after creation. We intercept that
// subscription to find the instance and patch its forwardEvent.
(function patchBridgeForwardEvent() {
const EventEmitter = require('events').EventEmitter;
const origOn = EventEmitter.prototype.on;
let patched = false;
EventEmitter.prototype.on = function patchedOn(event) {
if (!patched && event === 'remote_session_start' && typeof this.forwardEvent === 'function') {
patched = true;
const originalForwardEvent = this.forwardEvent.bind(this);
const bridge = this;
this.forwardEvent = async function patchedForwardEvent(e) {
// The original filter drops result/stream_event. We need those
// forwarded on Linux since there's no VM proxy to handle it.
const session = bridge.activeSessions && bridge.activeSessions.get(e.sessionId);
const msg = e.message;
const msgType = msg && msg.type;
console.log('[bridge-patch] forwardEvent called: type=' + e.type
+ ' msgType=' + msgType
+ ' sessionId=' + e.sessionId
+ ' hasSession=' + !!session
+ ' hasTransport=' + !!(session && session.transport));
if (!session || e.type !== 'message' || !e.message) {
return originalForwardEvent(e);
}
// For types the original would NOT drop, call the original
if (msgType !== 'result' && msgType !== 'stream_event') {
return originalForwardEvent(e);
}
// For result/stream_event: POST via the bridge transport directly
if (!session.transport) {
console.warn('[bridge-patch] No transport for session ' + e.sessionId + ', dropping ' + msgType);
return;
}
// Build event with userMessageUuid if present (matches original logic)
let eventPayload = msg;
if (e.userMessageUuid && msgType !== 'user') {
eventPayload = { ...msg, user_message_uuid: e.userMessageUuid };
}
// Serialize writes through the session's writeQueue (same pattern
// as the original forwardEvent) to prevent interleaving.
session.writeQueue = (session.writeQueue || Promise.resolve()).then(async () => {
try {
if (!session.transport) return;
if (session.transport.closed) {
console.warn('[bridge-patch] transport closed for ' + e.sessionId);
return;
}
await session.transport.write(eventPayload);
console.log('[bridge-patch] write OK: ' + msgType + ' session=' + e.sessionId);
} catch (err) {
console.warn('[bridge-patch] Failed to write ' + msgType + ' for session '
+ e.sessionId + ': ' + (err && err.message));
}
});
await session.writeQueue;
};
console.log('[bridge-patch] forwardEvent patched on sessions-bridge instance');
// Restore original .on to avoid overhead on all future subscriptions
EventEmitter.prototype.on = origOn;
}
return origOn.apply(this, arguments);
};
})();
// ── Asset Dumper (--devtools only) ──────────────────────────────────────
// Saves JS/CSS/JSON from claude.ai and *.anthropic.com to:
// ~/.local/state/claude-cowork/logs/webapp-assets/
// Previous dump is rotated to webapp-assets.bak/ on each launch.
function setupAssetDumper(win) {
const logDir = process.env.CLAUDE_LOG_DIR || path.join(PASSWD_HOMEDIR, '.local', 'state', 'claude-cowork', 'logs');
const dumpDir = path.join(logDir, 'webapp-assets');
const bakDir = dumpDir + '.bak';
// Rotate: remove old .bak, rename current to .bak
try { fs.rmSync(bakDir, { recursive: true, force: true }); } catch (_) {}
try { fs.renameSync(dumpDir, bakDir); } catch (_) {}
try { fs.mkdirSync(dumpDir, { recursive: true }); } catch (_) {}
const dumped = new Set();
let dumpCount = 0;
win.webContents.session.webRequest.onCompleted(
{ urls: ['*://*.anthropic.com/*', '*://claude.ai/*'] },
(details) => {
if (details.statusCode !== 200) return;
const url = details.url;
if (dumped.has(url)) return;
const ext = path.extname(new URL(url).pathname).toLowerCase();
if (!['.js', '.css', '.json', '.html'].includes(ext)) return;
dumped.add(url);
win.webContents.session.fetch(url).then(r => r.text()).then(body => {
const safeName = new URL(url).pathname.replace(/\//g, '_').replace(/^_/, '');
fs.writeFile(path.join(dumpDir, safeName), body, () => {
dumpCount++;
if (dumpCount <= 5 || dumpCount % 10 === 0) {
console.log('[Asset Dump] ' + dumpCount + ' files -> ' + dumpDir);
}
});
}).catch(() => {});
}
);
console.log('');
console.log('╔══════════════════════════════════════════════════════════════╗');
console.log('║ DEVTOOLS MODE — Asset dumper active ║');
console.log('║ Current: ' + dumpDir.padEnd(49) + '║');
console.log('║ Backup: ' + bakDir.padEnd(49) + '║');
console.log('║ Diff with: diff <dir> <dir.bak> to spot protocol changes ║');
console.log('╚══════════════════════════════════════════════════════════════╝');
console.log('');
}
function wrapAliasedFileSystemHandler(channel, handler, getAdapter) {
if (typeof handler !== 'function' || !isFileSystemPathRewriteChannel(channel)) {
return handler;
}
if (handler.__coworkAliasedFileSystemWrapped) {
return handler;
}
const normalizedChannel = typeof channel === 'string' ? channel.toLowerCase() : '';
function isPotentialIpcEvent(value) {
if (!value || typeof value !== 'object') {
return false;
}
return !!(
value.sender ||
value.senderFrame ||
value.frameId ||
value.processId
);
}
function splitHandlerArgs(args) {
if (!Array.isArray(args) || args.length === 0) {
return {
eventArg: null,
payloadArgs: [],
};
}
if (isPotentialIpcEvent(args[0])) {
return {
eventArg: args[0],
payloadArgs: args.slice(1),
};
}
return {
eventArg: null,
payloadArgs: args.slice(),
};
}
function joinHandlerArgs(eventArg, payloadArgs) {
return eventArg ? [eventArg, ...(payloadArgs || [])] : (payloadArgs || []);
}
function isSessionScopedFileSystemChannelName(value) {
return value.endsWith('filesystem_$_readlocalfile') ||
value.endsWith('filesystem_$_openlocalfile');
}
let delegatedHandler = null;
const wrappedHandler = async function(...args) {
if (!delegatedHandler && typeof getAdapter === 'function') {
const adapter = getAdapter();
if (adapter && typeof adapter.wrapHandler === 'function') {
delegatedHandler = adapter.wrapHandler(channel, handler);
}
}
if (delegatedHandler) {
return delegatedHandler(...args);
}
if (!Array.isArray(args) || args.length === 0) {
return handler(...args);
}
const { eventArg, payloadArgs } = splitHandlerArgs(args);
const hasExplicitSessionId = isSessionScopedFileSystemChannelName(normalizedChannel) &&
typeof payloadArgs[0] === 'string' &&
payloadArgs[0].startsWith('local_');
const targetPath = hasExplicitSessionId ? payloadArgs[1] : payloadArgs[0];
const rest = hasExplicitSessionId ? payloadArgs.slice(2) : payloadArgs.slice(1);
if (typeof targetPath !== 'string') {
return handler(...args);
}
const rewrittenPath = rewriteAliasedFilePath(targetPath, DEFAULT_FILESYSTEM_PATH_ALIASES);
if (rewrittenPath !== targetPath) {
console.log('[Cowork] Rewrote stale FileSystem path:', targetPath, '->', rewrittenPath);
}
const nextPayloadArgs = hasExplicitSessionId
? [payloadArgs[0], rewrittenPath, ...rest]
: [rewrittenPath, ...rest];
return handler(...joinHandlerArgs(eventArg, nextPayloadArgs));
};
wrappedHandler.__coworkAliasedFileSystemWrapped = true;
return wrappedHandler;
}
function resolveElectronApp(electronModule) {
const candidate = electronModule && typeof electronModule === 'object'
? electronModule.app
: null;
if (candidate && typeof candidate.on === 'function') {
return candidate;
}
try {
const electron = require('electron');
if (electron && electron.app && typeof electron.app.on === 'function') {
return electron.app;
}
} catch (_) {}
return null;
}
function registerElectronAppListener(electronModule, eventName, listener, description) {
const label = description || eventName;
try {
const app = resolveElectronApp(electronModule);
if (!app) {
console.log('[Frame Fix] Skipping app listener registration for ' + label + ': app unavailable');
return false;
}
app.on(eventName, listener);
return true;
} catch (error) {
console.log('[Frame Fix] Failed to register app listener for ' + label + ': ' + error.message);
return false;
}
}
function hideLinuxMenuBars(electronModule) {
if (REAL_PLATFORM !== 'linux') {
return;
}
const BrowserWindow = electronModule && electronModule.BrowserWindow;
if (!BrowserWindow || typeof BrowserWindow.getAllWindows !== 'function') {
console.log('[Frame Fix] Skipping menu bar hide: BrowserWindow.getAllWindows unavailable');
return;
}
try {
for (const win of BrowserWindow.getAllWindows()) {
if (win && typeof win.setMenuBarVisibility === 'function') {
win.setMenuBarVisibility(false);
}
}
} catch (error) {
console.log('[Frame Fix] setMenuBarVisibility error:', error.message);
}
}
function describeLinuxMenuApiShape(electronModule) {
const menuApi = electronModule && electronModule.Menu;
const app = resolveElectronApp(electronModule);
const shape = {
hasMenuObject: !!(menuApi && (typeof menuApi === 'object' || typeof menuApi === 'function')),
hasMenuSetApplicationMenu: !!(menuApi && typeof menuApi.setApplicationMenu === 'function'),
hasMenuSetDefaultApplicationMenu: !!(menuApi && typeof menuApi.setDefaultApplicationMenu === 'function'),
hasAppObject: !!app,
hasAppSetApplicationMenu: !!(app && typeof app.setApplicationMenu === 'function'),
missing: [],
};
if (!shape.hasMenuObject) {
shape.missing.push('Menu');
}
if (shape.hasMenuObject && !shape.hasMenuSetApplicationMenu) {
shape.missing.push('Menu.setApplicationMenu');
}
if (shape.hasMenuObject && !shape.hasMenuSetDefaultApplicationMenu) {
shape.missing.push('Menu.setDefaultApplicationMenu');
}
if (shape.hasAppObject && !shape.hasAppSetApplicationMenu) {
shape.missing.push('app.setApplicationMenu');
}
return shape;
}
function installLinuxMenuInterceptors(electronModule) {
if (!electronModule || typeof electronModule !== 'object') {
return;
}
if (global.__coworkLinuxMenuInterceptorsInstalled) {
return;
}
const menuApi = electronModule.Menu;
const app = resolveElectronApp(electronModule);
const menuApiShape = describeLinuxMenuApiShape(electronModule);
if (!menuApi || (!menuApiShape.hasMenuObject && !menuApiShape.hasMenuSetApplicationMenu && !menuApiShape.hasMenuSetDefaultApplicationMenu)) {
console.log('[Frame Fix] Skipping menu interception: Menu API unavailable');
console.log('[Frame Fix] Menu API shape:', JSON.stringify(menuApiShape));
return;
}
global.__coworkLinuxMenuInterceptorsInstalled = true;
const originalSetAppMenu = typeof menuApi.setApplicationMenu === 'function'
? menuApi.setApplicationMenu.bind(menuApi)
: null;
const originalSetDefaultAppMenu = typeof menuApi.setDefaultApplicationMenu === 'function'
? menuApi.setDefaultApplicationMenu.bind(menuApi)
: null;
if (menuApiShape.missing.length > 0) {
console.log('[Frame Fix] Menu API coverage gaps:', menuApiShape.missing.join(', '));
}
if (app && typeof app.setApplicationMenu !== 'function') {
app.setApplicationMenu = function(menu) {
global.__coworkApplicationMenu = menu;
hideLinuxMenuBars(electronModule);
return undefined;
};
}
menuApi.setApplicationMenu = function(menu) {
global.__coworkApplicationMenu = menu;
// Call the original so Electron's native binding stays intact
if (originalSetAppMenu) {
try { originalSetAppMenu(menu); } catch (_) {}
}
hideLinuxMenuBars(electronModule);
return undefined;
};
if (originalSetDefaultAppMenu) {
menuApi.setDefaultApplicationMenu = function(...args) {
if (REAL_PLATFORM === 'linux') {
hideLinuxMenuBars(electronModule);
return undefined;
}
return originalSetDefaultAppMenu(...args);
};
}
}
// ============================================================
// IPC TAP — must be created before the early ipcMain patch so
// it can instrument _invokeHandlers before any asar code runs.
// ============================================================
const ipcTap = createIpcTap();
// ============================================================
// CRITICAL: Patch ipcMain IMMEDIATELY before any asar code runs
// ============================================================
// NOTE: _invokeHandlers.get() is dead code — Electron dispatches via C++
// and never calls Map.get() from JavaScript. Synthetic handlers MUST be
// registered via ipcMain.handle() to land in Electron's C++ dispatch map.
// The .set() override here only wraps filesystem handlers with alias
// rewriting. Linux IPC overrides are applied at registration time via
// matchOverride() in both ipcMain.handle() and webContents.ipc.handle().
try {
const electron = require('electron');
const { ipcMain } = electron;
if (ipcMain && ipcMain._invokeHandlers && !global.__coworkIpcMainAliasPatched) {
global.__coworkIpcMainAliasPatched = true;
const invokeHandlers = ipcMain._invokeHandlers;
// Tap _invokeHandlers BEFORE our overrides so the tap sees raw handler behavior
if (ipcTap.enabled) ipcTap.wrapInvokeHandlers(invokeHandlers);
const originalSet = invokeHandlers.set.bind(invokeHandlers);
invokeHandlers.set = function(channel, handler) {
return originalSet(channel, wrapAliasedFileSystemHandler(channel, handler, () => global.__coworkAsarAdapter || null));
};
console.log('[Cowork] ipcMain._invokeHandlers patched (filesystem aliasing)');
}
} catch (e) {
console.error('[Cowork] Failed to patch ipcMain:', e.message);
}
// ============================================================
// CRITICAL: Register CoworkSpaces handlers on ipcMain IMMEDIATELY
// ============================================================
// The asar's native SpacesStore only registers handlers after account IPC
// from the renderer, which is unreliable on Linux. Without a handler,
// ipcRenderer.invoke() fails silently and the Projects page stays empty.
//
// We register our file-backed handlers on ipcMain.handle() BEFORE any
// webContents exists. When no webContents.ipc.handle() exists for a channel,
// Electron falls back to ipcMain.handle(). If/when the asar's native handler
// registers later (account init succeeds), it uses webContents.ipc.handle()
// which takes priority over our ipcMain handler.
try {
const _electron = require('electron');
const { createSpacesStore } = require('./cowork/spaces_store.js');
const _earlyAllowedRoots = [PASSWD_HOMEDIR];
function _earlyIsPathAllowed(filePath) {
if (typeof filePath !== 'string' || !path.isAbsolute(filePath)) return false;
const normalized = path.normalize(filePath);
let resolved;
try {
resolved = fs.realpathSync(normalized);
} catch (_) {
let current = path.dirname(normalized);
let tail = path.basename(normalized);
resolved = null;
while (current !== path.dirname(current)) {
try {
resolved = path.join(fs.realpathSync(current), tail);
break;
} catch (_) {
tail = path.join(path.basename(current), tail);
current = path.dirname(current);
}
}
if (!resolved) resolved = normalized;
}
return _earlyAllowedRoots.some(root => resolved === root || resolved.startsWith(root + path.sep));
}
// Publish the early-created store to a global so ipc_overrides.js
// (loaded later) reuses the same instance instead of creating a second
// one with divergent validators and separate rate-limit state.
const _spacesStore = createSpacesStore({
localAgentRoot: path.join(
process.env.XDG_CONFIG_HOME || path.join(PASSWD_HOMEDIR, '.config'),
'Claude', 'local-agent-mode-sessions'
),
isPathAllowed: _earlyIsPathAllowed,
trace: (msg) => console.log(msg),
});
global.__coworkSpacesStore = _spacesStore;
const EIPC_UUID = 'c42bb833-f6f9-4563-9861-03480449cfb1';
const EIPC_NS = 'claude.web';
const prefix = `$eipc_message$_${EIPC_UUID}_$_${EIPC_NS}_$_CoworkSpaces_$_`;
const handlers = {
getAllSpaces: async () => _spacesStore.getAllSpaces(),
getSpace: async (_e, id) => _spacesStore.getSpace(_e, id),
createSpace: async (_e, data) => _spacesStore.createSpace(_e, data),
updateSpace: async (_e, id, upd) => _spacesStore.updateSpace(_e, id, upd),
deleteSpace: async (_e, id) => _spacesStore.deleteSpace(_e, id),
addFolderToSpace: async (_e, id, p) => _spacesStore.addFolderToSpace(_e, id, p),
removeFolderFromSpace: async (_e, id, p) => _spacesStore.removeFolderFromSpace(_e, id, p),
addProjectToSpace: async (_e, id, p) => _spacesStore.addProjectToSpace(_e, id, p),
removeProjectFromSpace: async (_e, id, p) => _spacesStore.removeProjectFromSpace(_e, id, p),
addLinkToSpace: async (_e, id, l) => _spacesStore.addLinkToSpace(_e, id, l),
removeLinkFromSpace: async (_e, id, l) => _spacesStore.removeLinkFromSpace(_e, id, l),
getAutoMemoryDir: async (_e, id) => _spacesStore.getAutoMemoryDir(_e, id),
listFolderContents: async (_e, p) => _spacesStore.listFolderContents(_e, p),
readFileContents: async (_e, p) => _spacesStore.readFileContents(_e, p),
openFile: async (_e, p) => _spacesStore.openFile(_e, p),
copyFilesToSpaceFolder: async (_e, id, f) => _spacesStore.copyFilesToSpaceFolder(_e, id, f),
createSpaceFolder: async (_e, id, n) => _spacesStore.createSpaceFolder(_e, id, n),
classifySessions: async (_e, s) => _spacesStore.classifySessions(_e, s),
setAutoDescription: async (_e, id, d) => _spacesStore.setAutoDescription(_e, id, d),
summarizeSpace: async (_e, id) => _spacesStore.summarizeSpace(_e, id),
onSpaceEvent: async () => ({ dispose: () => {} }),
};
let registered = 0;
for (const [method, handler] of Object.entries(handlers)) {
const channel = prefix + method;
try {
_electron.ipcMain.handle(channel, handler);
registered++;
} catch (e) {
// Already registered — skip
}
}
console.log('[Cowork] Registered ' + registered + ' CoworkSpaces handlers on ipcMain (fallback)');
} catch (earlyRegErr) {
console.error('[Cowork] EARLY CoworkSpaces registration FAILED:', earlyRegErr.message, earlyRegErr.stack);
}
// ============================================================
// 0. TMPDIR FIX - MUST BE ABSOLUTELY FIRST
// ============================================================
// Fix EXDEV error: App downloads VM to /tmp (tmpfs) then tries to
// rename() to ~/.config/Claude/ (disk). rename() can't cross filesystems.
const REAL_PLATFORM = process.platform;
const REAL_ARCH = process.arch;
const DIRS = createDirs();
// ── Global shortcut default ───────────────────────────────────────────
// The asar defaults to Alt+Space on darwin, Ctrl+Alt+Space on Linux.
// Since we spoof darwin, it picks Alt+Space which conflicts with most
// Linux WM launchers. Set the Linux default if the user hasn't chosen one.
try {
const configPath = path.join(DIRS.claudeConfigRoot, 'config.json');
const cfg = JSON.parse(fs.readFileSync(configPath, 'utf8'));
if (!cfg.globalShortcut) {
cfg.globalShortcut = 'Ctrl+Alt+Space';
fs.writeFileSync(configPath, JSON.stringify(cfg, null, 2) + '\n');
console.log('[Frame Fix] Set default global shortcut to Ctrl+Alt+Space');
}
} catch (_) {}
const vmBundleDir = DIRS.claudeVmBundlesDir;
const vmTmpDir = path.join(vmBundleDir, 'tmp');
const claudeVmBundle = path.join(vmBundleDir, 'claudevm.bundle');
const LOCAL_AGENT_ROOT = DIRS.claudeLocalAgentRoot;
const localSessionStore = createSessionStore({ localAgentRoot: LOCAL_AGENT_ROOT });
const ipcSessionOrchestrator = createSessionOrchestrator({
dirs: DIRS,
sessionStore: localSessionStore,
});
const asarAdapter = createAsarAdapter({
sessionOrchestrator: ipcSessionOrchestrator,
sessionStore: localSessionStore,
});
global.__coworkAsarAdapter = asarAdapter;
global.__coworkSessionStore = localSessionStore;
global.__coworkSessionOrchestrator = ipcSessionOrchestrator;
global.__coworkDirs = DIRS;
localSessionStore.installMetadataPersistenceGuard();
global.__coworkIpcTap = ipcTap;
try {
// Create temp dir on same filesystem as target
fs.mkdirSync(vmTmpDir, { recursive: true, mode: 0o700 });
// Set env vars for any code that reads them directly
process.env.TMPDIR = vmTmpDir;
process.env.TMP = vmTmpDir;
process.env.TEMP = vmTmpDir;
// CRITICAL: Patch os.tmpdir() directly - it may have cached /tmp already
const originalTmpdir = os.tmpdir;
os.tmpdir = function() {
return vmTmpDir;
};
// Pre-create VM bundle to skip download entirely
fs.mkdirSync(claudeVmBundle, { recursive: true, mode: 0o755 });
// Create marker files the app checks
const markers = ['bundle_complete', 'rootfs.img', 'rootfs.img.zst', 'vmlinux', 'config.json'];
for (const m of markers) {
const p = path.join(claudeVmBundle, m);
if (!fs.existsSync(p)) {
if (m === 'config.json') {
fs.writeFileSync(p, '{"version":"linux-native","skip_vm":true}', { mode: 0o644 });
} else {
fs.writeFileSync(p, 'linux-native-placeholder', { mode: 0o644 });
}
}
}
fs.writeFileSync(path.join(claudeVmBundle, 'version'), '999.0.0-linux-native', { mode: 0o644 });
console.log('[TMPDIR] Fixed: ' + vmTmpDir);
console.log('[TMPDIR] os.tmpdir() patched');
console.log('[VM_BUNDLE] Ready: ' + claudeVmBundle);
// The asar wraps all git commands with a "disclaimer" binary on macOS
// (Helpers/disclaimer git <args>). Since we spoof process.platform to
// "darwin", this codepath activates on Linux too. The binary doesn't
// exist in the Linux Electron distribution, causing ENOENT on every
// git operation (diff, status, etc). Create a transparent passthrough
// so the wrapper is a no-op — identical to what the asar's own
// non-darwin branch does (returns the command unchanged).
const disclaimerDir = path.join(path.dirname(process.resourcesPath), 'Helpers');
const disclaimerBin = path.join(disclaimerDir, 'disclaimer');
{
try {
fs.mkdirSync(disclaimerDir, { recursive: true, mode: 0o755 });
fs.writeFileSync(disclaimerBin, '#!/bin/sh\nexit 127\n', { mode: 0o444 });
} catch (_) {}
const _cp = require('child_process');
const _origExecFile = _cp.execFile;
const _origSpawn = _cp.spawn;
const { createExecCapabilityRegistry } = require('../cowork/exec_capability_registry');
const _execRegistry = createExecCapabilityRegistry({
homedir: PASSWD_HOMEDIR,
});
global.__coworkExecRegistry = _execRegistry;
function _resolveDisclaimerArgs(file, args) {
if (file !== disclaimerBin) return null;
return _execRegistry.resolveDisclaimerCommand(args);
}
_cp.execFile = function(file, args, ...rest) {
const resolved = _resolveDisclaimerArgs(file, args);
if (resolved) return _origExecFile.call(_cp, resolved.cmd, resolved.rest, ...rest);
return _origExecFile.call(_cp, file, args, ...rest);
};
Object.assign(_cp.execFile, _origExecFile);
_cp.spawn = function(file, args, ...rest) {
const resolved = _resolveDisclaimerArgs(file, args);
if (resolved) return _origSpawn.call(_cp, resolved.cmd, resolved.rest, ...rest);
return _origSpawn.call(_cp, file, args, ...rest);
};
Object.assign(_cp.spawn, _origSpawn);
console.log('[disclaimer] Intercepting exec calls at ' + disclaimerBin);
}
} catch (e) {
console.error('[TMPDIR] Setup failed:', e.message);
}
// ============================================================
// 0a. PATCH fs TO REDIRECT /sessions/ PATHS TO SESSIONS_BASE
// ============================================================
// The asar and our stubs use /sessions/<name>/... as the VM-internal path
// prefix. On macOS a /sessions root symlink is created. On Linux we can't
// always create root symlinks (immutable rootfs, no sudo). Instead, patch
// all fs calls to rewrite /sessions/ -> SESSIONS_BASE/ transparently.
//
// SESSIONS_BASE is resolved lazily (DIRS is created below) so we capture
// a getter that reads from the global set during createDirs().
(function patchFsSessionsPaths() {
const VM_SESSIONS_PREFIX = '/sessions/';
function rewritePath(p) {
if (typeof p === 'string' && p.startsWith(VM_SESSIONS_PREFIX)) {
const base = (typeof SESSIONS_BASE !== 'undefined' ? SESSIONS_BASE : null)
|| (global.__coworkDirs && global.__coworkDirs.claudeSessionsBase)
|| require('path').join(
(process.env.XDG_CONFIG_HOME || require('path').join(require('os').homedir(), '.config')),
'Claude', 'local-agent-mode-sessions', 'sessions'
);
return base + '/' + p.slice(VM_SESSIONS_PREFIX.length);
}
return p;
}
function wrapFsMethod(obj, name) {
const orig = obj[name];
if (typeof orig !== 'function' || obj[name].__coworkSessionsPatched) return;
obj[name] = function(p, ...rest) {
return orig.call(this, rewritePath(p), ...rest);
};
obj[name].__coworkSessionsPatched = true;
}
const PATH_METHODS = [
'access', 'accessSync',
'chmod', 'chmodSync',
'chown', 'chownSync',
'copyFile', 'copyFileSync',
'createReadStream', 'createWriteStream',
'exists', 'existsSync',
'lchmod', 'lchmodSync',
'lchown', 'lchownSync',
'lstat', 'lstatSync',
'mkdir', 'mkdirSync',
'mkdtemp', 'mkdtempSync',
'open', 'openSync',
'opendir', 'opendirSync',
'readdir', 'readdirSync',
'readFile', 'readFileSync',
'readlink', 'readlinkSync',
'realpath', 'realpathSync',
'rmdir', 'rmdirSync',
'rm', 'rmSync',
'stat', 'statSync',
'symlink', 'symlinkSync',
'truncate', 'truncateSync',
'unlink', 'unlinkSync',
'utimes', 'utimesSync',
'watch', 'watchFile',
'writeFile', 'writeFileSync',
'appendFile', 'appendFileSync',
];
for (const name of PATH_METHODS) {
if (typeof fs[name] === 'function') wrapFsMethod(fs, name);
}
const origRenameForSessions = fs.rename;
if (origRenameForSessions && !origRenameForSessions.__coworkSessionsRenamePatched) {
fs.rename = function(oldPath, newPath, cb) {
return origRenameForSessions.call(this, rewritePath(oldPath), rewritePath(newPath), cb);
};
fs.rename.__coworkSessionsRenamePatched = true;
}
const origRenameSyncForSessions = fs.renameSync;
if (origRenameSyncForSessions && !origRenameSyncForSessions.__coworkSessionsRenamePatched) {
fs.renameSync = function(oldPath, newPath) {
return origRenameSyncForSessions.call(this, rewritePath(oldPath), rewritePath(newPath));
};
fs.renameSync.__coworkSessionsRenamePatched = true;
}
try {
const fsp = require('fs/promises') || fs.promises;
if (fsp) {
const ASYNC_PATH_METHODS = [
'access', 'chmod', 'chown', 'copyFile', 'lchmod', 'lchown',
'lstat', 'mkdir', 'mkdtemp', 'open', 'opendir', 'readdir',
'readFile', 'readlink', 'realpath', 'rmdir', 'rm', 'stat',
'symlink', 'truncate', 'unlink', 'utimes', 'writeFile', 'appendFile',
];
for (const name of ASYNC_PATH_METHODS) {
if (typeof fsp[name] === 'function' && !fsp[name].__coworkSessionsPatched) {
const origFsp = fsp[name];
fsp[name] = function(p, ...rest) {
return origFsp.call(this, rewritePath(p), ...rest);
};
fsp[name].__coworkSessionsPatched = true;
}
}
if (typeof fsp.rename === 'function' && !fsp.rename.__coworkSessionsRenamePatched) {
const origFspRename = fsp.rename;
fsp.rename = function(oldPath, newPath) {
return origFspRename.call(this, rewritePath(oldPath), rewritePath(newPath));
};
fsp.rename.__coworkSessionsRenamePatched = true;
}
}
} catch (_) {}
console.log('[Sessions] fs path redirect /sessions/ -> SESSIONS_BASE installed');
})();
// ============================================================
// 0b. PATCH fs.rename TO HANDLE EXDEV ERRORS
// ============================================================
const originalRename = fs.rename;
const originalRenameSync = fs.renameSync;
fs.rename = function(oldPath, newPath, callback) {
originalRename(oldPath, newPath, (err) => {
if (err && err.code === 'EXDEV') {
// Cross-filesystem rename — fall back to copy+delete
const readStream = fs.createReadStream(oldPath);
const writeStream = fs.createWriteStream(newPath);
readStream.on('error', callback);
writeStream.on('error', callback);
writeStream.on('close', () => {
fs.unlink(oldPath, () => callback(null));
});
readStream.pipe(writeStream);
} else {
callback(err);
}
});
};
fs.renameSync = function(oldPath, newPath) {
try {
return originalRenameSync(oldPath, newPath);
} catch (err) {
if (err.code === 'EXDEV') {
// Cross-filesystem rename — fall back to copy+delete
fs.copyFileSync(oldPath, newPath);
fs.unlinkSync(oldPath);
return;
}
throw err;
}
};
// ============================================================
// 1. PLATFORM SPOOFING - Immediate, before any app code
// ============================================================
// ── Platform spoofing (performance-critical) ──────────────────────────
// App code must see darwin/arm64; Electron/Node internals need the real
// platform. The old approach used new Error().stack on every access —
// stack trace generation is extremely expensive in V8 and process.platform
// is read thousands of times per second (CSS, feature detection, Node APIs).
//
// New approach: default to 'darwin' (the common case — app code dominates
// runtime reads) and only use the real platform during the brief module-
// loading phase when Electron internals call it. A reentrant guard flips
// to real values when OUR code is executing (frame-fix-wrapper, stubs).
let _inOurCode = false;
function withRealPlatform(fn) {
_inOurCode = true;
try { return fn(); }
finally { _inOurCode = false; }
}
Object.defineProperty(process, 'platform', {
get() { return _inOurCode ? REAL_PLATFORM : 'darwin'; },
configurable: true
});
Object.defineProperty(process, 'arch', {
get() { return _inOurCode ? REAL_ARCH : 'arm64'; },
configurable: true
});
const originalOsPlatform = os.platform;
const originalOsArch = os.arch;
os.platform = function() { return _inOurCode ? originalOsPlatform.call(os) : 'darwin'; };
os.arch = function() { return _inOurCode ? originalOsArch.call(os) : 'arm64'; };
// Spoof macOS version
const originalGetSystemVersion = process.getSystemVersion;
process.getSystemVersion = function() {
return '14.0.0';
};
console.log('[Platform] Spoofing: darwin/arm64 macOS 14.0 (immediate)');
console.log('[Platform] Real platform was:', REAL_PLATFORM);
// ============================================================
// Cowork/YukonSilver Support for Linux
// On Linux we run Claude Code directly without a VM
// ============================================================
// Global state for Cowork
global.__cowork = {
supported: true,
status: 'supported', // This is what the app checks
processes: new Map(),
};
const SESSIONS_BASE = DIRS.claudeSessionsBase;
// Items 9, 10: dead support-status overrides removed (handled by IPC stubs).
console.log('[Cowork] Linux support enabled - VM will be emulated');
const { isIgnoredLiveEventType } = require('./cowork/session_normalization.js');
function parseRequestedProcessId(args) {
for (const arg of args) {
if (typeof arg === 'string') {
return arg;
}
if (arg && typeof arg === 'object' && typeof arg.id === 'string') {
return arg.id;
}
}
return null;
}
async function getCoworkProcessRunningState(processId) {
const stub = global.__coworkSwiftStub;
const specialKeepalive = processId === '__keepalive__' || processId === '__heartbeat__';
try {
if (stub && typeof stub.isProcessRunning === 'function' && !stub.isProcessRunning.__coworkSyntheticWrapper) {
const result = await Promise.resolve(stub.isProcessRunning(processId));
if (result && typeof result === 'object' && 'running' in result) {
return {
running: !!result.running,
exitCode: result.exitCode ?? null,