forked from aaddrick/claude-desktop-debian
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.sh
More file actions
executable file
·1889 lines (1669 loc) · 67.2 KB
/
build.sh
File metadata and controls
executable file
·1889 lines (1669 loc) · 67.2 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
#!/usr/bin/env bash
#===============================================================================
# Claude Desktop Debian Build Script
# Repackages Claude Desktop (Electron app) for Debian/Ubuntu Linux
#===============================================================================
# Global variables (set by functions, used throughout)
architecture=''
distro_family='' # debian, rpm, nix, or unknown
claude_download_url=''
claude_exe_sha256=''
claude_exe_filename=''
version=''
release_tag='' # Optional release tag (e.g., v1.3.2+claude1.1.799) for unique package versions
build_format='' # Will be set based on distro if not specified
cleanup_action='yes'
perform_cleanup=false
test_flags_mode=false
local_exe_path=''
node_pty_dir=''
source_dir=''
original_user=''
original_home=''
project_root=''
work_dir=''
app_staging_dir=''
chosen_electron_module_path=''
electron_var=''
electron_var_re=''
asar_exec=''
claude_extract_dir=''
electron_resources_dest=''
node_pty_build_dir=''
final_output_path=''
# Package metadata (constants)
readonly PACKAGE_NAME='claude-desktop'
readonly MAINTAINER='Claude Desktop Linux Maintainers'
readonly DESCRIPTION='Claude Desktop for Linux'
#===============================================================================
# Utility Functions
#===============================================================================
check_command() {
if ! command -v "$1" &> /dev/null; then
echo "$1 not found"
return 1
else
echo "$1 found"
return 0
fi
}
section_header() {
echo -e "\033[1;36m--- $1 ---\033[0m"
}
section_footer() {
echo -e "\033[1;36m--- End $1 ---\033[0m"
}
verify_sha256() {
local file_path="$1"
local expected_hash="$2"
local label="${3:-file}"
if [[ -z $expected_hash ]]; then
echo "Warning: No SHA-256 hash for ${label}," \
'skipping verification' >&2
return 0
fi
echo "Verifying SHA-256 checksum for ${label}..."
local actual_hash _
read -r actual_hash _ < <(sha256sum "$file_path")
if [[ $actual_hash != "$expected_hash" ]]; then
echo "SHA-256 mismatch for ${label}!" >&2
echo " Expected: $expected_hash" >&2
echo " Actual: $actual_hash" >&2
return 1
fi
echo "SHA-256 verified: ${label}"
}
#===============================================================================
# Setup Functions
#===============================================================================
detect_architecture() {
section_header 'Architecture Detection'
echo 'Detecting system architecture...'
local raw_arch
raw_arch=$(uname -m) || {
echo 'Failed to detect architecture' >&2
exit 1
}
echo "Detected machine architecture: $raw_arch"
case "$raw_arch" in
x86_64)
claude_download_url='https://downloads.claude.ai/releases/win32/x64/1.569.0/Claude-49894ad878c985b0dd77178b75b353f11481ebf4.exe'
claude_exe_sha256='34d6c8371ec8a5f57c690192b134bba64433103becd254f28058738ef4031ced'
architecture='amd64'
claude_exe_filename='Claude-Setup-x64.exe'
echo 'Configured for amd64 (x86_64) build.'
;;
aarch64)
claude_download_url='https://downloads.claude.ai/releases/win32/arm64/1.569.0/Claude-49894ad878c985b0dd77178b75b353f11481ebf4.exe'
claude_exe_sha256='fd9110fe113de039b79f7d693d9a9a660e54cfc2c6af120ff403e07315b27bf3'
architecture='arm64'
claude_exe_filename='Claude-Setup-arm64.exe'
echo 'Configured for arm64 (aarch64) build.'
;;
*)
echo "Unsupported architecture: $raw_arch. This script supports x86_64 (amd64) and aarch64 (arm64)." >&2
exit 1
;;
esac
echo "Target Architecture: $architecture"
section_footer 'Architecture Detection'
}
detect_distro() {
section_header 'Distribution Detection'
echo 'Detecting Linux distribution family...'
if [[ -f /etc/debian_version ]]; then
distro_family='debian'
echo "Detected Debian-based distribution"
echo " Debian version: $(cat /etc/debian_version)"
elif [[ -f /etc/fedora-release ]]; then
distro_family='rpm'
echo "Detected Fedora"
echo " $(cat /etc/fedora-release)"
elif [[ -f /etc/redhat-release ]]; then
distro_family='rpm'
echo "Detected Red Hat-based distribution"
echo " $(cat /etc/redhat-release)"
elif [[ -f /etc/NIXOS ]]; then
distro_family='nix'
echo "Detected NixOS"
else
distro_family='unknown'
echo "Warning: Could not detect distribution family"
echo " AppImage build will still work, but native packages (deb/rpm) may not"
fi
echo "Distribution: $(grep 'PRETTY_NAME' /etc/os-release 2>/dev/null | cut -d'"' -f2 || echo 'Unknown')"
echo "Distribution family: $distro_family"
section_footer 'Distribution Detection'
}
check_system_requirements() {
# Allow running as root in CI/container environments
if (( EUID == 0 )); then
if [[ -n ${CI:-} || -n ${GITHUB_ACTIONS:-} || -f /.dockerenv ]]; then
echo 'Running as root in CI/container environment (allowed)'
else
echo 'This script should not be run using sudo or as the root user.' >&2
echo 'It will use sudo when needed for specific actions (may prompt for password).' >&2
echo 'Please run as a normal user.' >&2
exit 1
fi
fi
original_user=$(whoami)
original_home=$(getent passwd "$original_user" | cut -d: -f6)
if [[ -z $original_home ]]; then
echo "Could not determine home directory for user $original_user." >&2
exit 1
fi
echo "Running as user: $original_user (Home: $original_home)"
# Check for NVM and source it if found
if [[ -d $original_home/.nvm ]]; then
echo "Found NVM installation for user $original_user, checking for Node.js 20+..."
export NVM_DIR="$original_home/.nvm"
if [[ -s $NVM_DIR/nvm.sh ]]; then
# shellcheck disable=SC1091
\. "$NVM_DIR/nvm.sh"
local node_bin_path=''
node_bin_path=$(nvm which current | xargs dirname 2>/dev/null || \
find "$NVM_DIR/versions/node" -maxdepth 2 -type d -name 'bin' | sort -V | tail -n 1)
if [[ -n $node_bin_path && -d $node_bin_path ]]; then
echo "Adding NVM Node bin path to PATH: $node_bin_path"
export PATH="$node_bin_path:$PATH"
else
echo 'Warning: Could not determine NVM Node bin path.'
fi
else
echo 'Warning: nvm.sh script not found or not sourceable.'
fi
fi
echo 'System Information:'
echo "Distribution: $(grep 'PRETTY_NAME' /etc/os-release 2>/dev/null | cut -d'"' -f2 || echo 'Unknown')"
echo "Distribution family: $distro_family"
echo "Target Architecture: $architecture"
}
parse_arguments() {
section_header 'Argument Parsing'
project_root="$(pwd)"
work_dir="$project_root/build"
app_staging_dir="$work_dir/electron-app"
# Set default build format based on detected distro
case "$distro_family" in
debian) build_format='deb' ;;
rpm) build_format='rpm' ;;
nix) build_format='nix' ;;
*) build_format='appimage' ;;
esac
while (( $# > 0 )); do
case "$1" in
-b|--build|-c|--clean|-e|--exe|-r|--release-tag|-s|--source-dir|--node-pty-dir)
if [[ -z ${2:-} || $2 == -* ]]; then
echo "Error: Argument for $1 is missing" >&2
exit 1
fi
case "$1" in
-b|--build) build_format="$2" ;;
-c|--clean) cleanup_action="$2" ;;
-e|--exe) local_exe_path="$2" ;;
-r|--release-tag) release_tag="$2" ;;
-s|--source-dir) source_dir="$2" ;;
--node-pty-dir) node_pty_dir="$2" ;;
esac
shift 2
;;
--test-flags)
test_flags_mode=true
shift
;;
-h|--help)
echo "Usage: $0 [--build deb|rpm|appimage|nix] [--clean yes|no] [--exe /path/to/installer.exe] [--source-dir /path] [--release-tag TAG] [--test-flags]"
echo ' --build: Specify the build format (deb, rpm, appimage, or nix).'
echo " Default: auto-detected based on distro (current: $build_format)"
echo ' --clean: Specify whether to clean intermediate build files (yes or no). Default: yes'
echo ' --exe: Use a local Claude installer exe instead of downloading'
echo ' --source-dir: Path to repo root for scripts/ and assets (default: project root)'
echo ' --node-pty-dir: Path to pre-built node-pty package (skips npm install)'
echo ' --release-tag: Release tag (e.g., v1.3.2+claude1.1.799) to append wrapper version to package'
echo ' --test-flags: Parse flags, print results, and exit without building.'
exit 0
;;
*)
echo "Unknown option: $1" >&2
echo 'Use -h or --help for usage information.' >&2
exit 1
;;
esac
done
# source_dir is where scripts/assets live (default: project_root)
source_dir="${source_dir:-$project_root}"
# Validate arguments
build_format="${build_format,,}"
cleanup_action="${cleanup_action,,}"
if [[ ! -d $source_dir ]]; then
echo "Error: --source-dir path does not exist: $source_dir" >&2
exit 1
fi
if [[ -n $node_pty_dir && ! -d $node_pty_dir ]]; then
echo "Error: --node-pty-dir path does not exist: $node_pty_dir" >&2
exit 1
fi
if [[ $build_format != 'deb' && $build_format != 'rpm' && $build_format != 'appimage' && $build_format != 'nix' ]]; then
echo "Invalid build format specified: '$build_format'. Must be 'deb', 'rpm', 'appimage', or 'nix'." >&2
exit 1
fi
# Warn if building native package for wrong distro
if [[ $build_format == 'deb' && $distro_family != 'debian' ]]; then
echo "Warning: Building .deb package on non-Debian system ($distro_family). This may fail." >&2
elif [[ $build_format == 'rpm' && $distro_family != 'rpm' ]]; then
echo "Warning: Building .rpm package on non-RPM system ($distro_family). This may fail." >&2
fi
if [[ $cleanup_action != 'yes' && $cleanup_action != 'no' ]]; then
echo "Invalid cleanup option specified: '$cleanup_action'. Must be 'yes' or 'no'." >&2
exit 1
fi
echo "Selected build format: $build_format"
echo "Cleanup intermediate files: $cleanup_action"
[[ $cleanup_action == 'yes' ]] && perform_cleanup=true
section_footer 'Argument Parsing'
}
check_dependencies() {
echo 'Checking dependencies...'
local deps_to_install=''
local common_deps='p7zip wget wrestool icotool convert'
local all_deps="$common_deps"
# Add format-specific dependencies
case "$build_format" in
deb) all_deps="$all_deps dpkg-deb" ;;
rpm) all_deps="$all_deps rpmbuild" ;;
esac
# Command-to-package mappings per distro family
declare -A debian_pkgs=(
[p7zip]='p7zip-full' [wget]='wget' [wrestool]='icoutils'
[icotool]='icoutils' [convert]='imagemagick'
[dpkg-deb]='dpkg-dev' [rpmbuild]='rpm'
)
declare -A rpm_pkgs=(
[p7zip]='p7zip p7zip-plugins' [wget]='wget' [wrestool]='icoutils'
[icotool]='icoutils' [convert]='ImageMagick'
[dpkg-deb]='dpkg' [rpmbuild]='rpm-build'
)
local cmd
for cmd in $all_deps; do
if ! check_command "$cmd"; then
case "$distro_family" in
debian)
deps_to_install="$deps_to_install ${debian_pkgs[$cmd]}"
;;
rpm)
deps_to_install="$deps_to_install ${rpm_pkgs[$cmd]}"
;;
*)
echo "Warning: Cannot auto-install '$cmd' on unknown distro. Please install manually." >&2
;;
esac
fi
done
if [[ -n $deps_to_install ]]; then
echo "System dependencies needed:$deps_to_install"
# Determine if we need sudo (skip if already root)
local sudo_cmd='sudo'
if (( EUID == 0 )); then
sudo_cmd=''
echo 'Installing as root (no sudo needed)...'
else
echo 'Attempting to install using sudo...'
# Check if we can sudo without a password first
if sudo -n true 2>/dev/null; then
echo 'Passwordless sudo detected.'
elif ! sudo -v; then
echo 'Failed to validate sudo credentials. Please ensure you can run sudo.' >&2
exit 1
fi
fi
case "$distro_family" in
debian)
if ! $sudo_cmd apt update; then
echo "Failed to run 'apt update'." >&2
exit 1
fi
# shellcheck disable=SC2086
if ! $sudo_cmd apt install -y $deps_to_install; then
echo "Failed to install dependencies using 'apt install'." >&2
exit 1
fi
;;
rpm)
# shellcheck disable=SC2086
if ! $sudo_cmd dnf install -y $deps_to_install; then
echo "Failed to install dependencies using 'dnf install'." >&2
exit 1
fi
;;
*)
echo "Cannot auto-install dependencies on unknown distro." >&2
echo "Please install these packages manually: $deps_to_install" >&2
exit 1
;;
esac
echo 'System dependencies installed successfully.'
fi
}
setup_work_directory() {
rm -rf "$work_dir"
mkdir -p "$work_dir" || exit 1
mkdir -p "$app_staging_dir" || exit 1
}
setup_nodejs() {
section_header 'Node.js Setup'
echo 'Checking Node.js version...'
local node_version_ok=false
if command -v node &> /dev/null; then
local node_version node_major
node_version=$(node --version | cut -d'v' -f2)
node_major="${node_version%%.*}"
echo "System Node.js version: v$node_version"
if (( node_major >= 20 )); then
echo "System Node.js version is adequate (v$node_version)"
node_version_ok=true
else
echo "System Node.js version is too old (v$node_version). Need v20+"
fi
else
echo 'Node.js not found in system'
fi
if [[ $node_version_ok == true ]]; then
section_footer 'Node.js Setup'
return 0
fi
# Node.js version inadequate - install locally
echo 'Installing Node.js v20 locally in build directory...'
local node_arch
case "$architecture" in
amd64) node_arch='x64' ;;
arm64) node_arch='arm64' ;;
*)
echo "Unsupported architecture for Node.js: $architecture" >&2
exit 1
;;
esac
local node_version_to_install='20.18.1'
local node_tarball="node-v${node_version_to_install}-linux-${node_arch}.tar.xz"
local node_url="https://nodejs.org/dist/v${node_version_to_install}/${node_tarball}"
local node_install_dir="$work_dir/node"
echo "Downloading Node.js v${node_version_to_install} for ${node_arch}..."
cd "$work_dir" || exit 1
if ! wget -O "$node_tarball" "$node_url"; then
echo "Failed to download Node.js from $node_url" >&2
cd "$project_root" || exit 1
exit 1
fi
# Verify against official Node.js checksums
local shasums_url node_expected_sha256
shasums_url="https://nodejs.org/dist/v${node_version_to_install}/SHASUMS256.txt"
node_expected_sha256=$(
wget -qO- "$shasums_url" \
| grep -F "$node_tarball" \
| awk '{print $1}'
) || true
if ! verify_sha256 "$work_dir/$node_tarball" \
"$node_expected_sha256" 'Node.js tarball'; then
cd "$project_root" || exit 1
exit 1
fi
echo 'Extracting Node.js...'
if ! tar -xf "$node_tarball"; then
echo 'Failed to extract Node.js tarball' >&2
cd "$project_root" || exit 1
exit 1
fi
mv "node-v${node_version_to_install}-linux-${node_arch}" "$node_install_dir" || exit 1
export PATH="$node_install_dir/bin:$PATH"
if command -v node &> /dev/null; then
echo "Local Node.js installed successfully: $(node --version)"
else
echo 'Failed to install local Node.js' >&2
cd "$project_root" || exit 1
exit 1
fi
rm -f "$node_tarball"
cd "$project_root" || exit 1
section_footer 'Node.js Setup'
}
setup_electron_asar() {
section_header 'Electron & Asar Handling'
echo "Ensuring local Electron and Asar installation in $work_dir..."
cd "$work_dir" || exit 1
if [[ ! -f package.json ]]; then
echo "Creating temporary package.json in $work_dir for local install..."
echo '{"name":"claude-desktop-build","version":"0.0.1","private":true}' > package.json
fi
local electron_dist_path="$work_dir/node_modules/electron/dist"
local asar_bin_path="$work_dir/node_modules/.bin/asar"
local install_needed=false
[[ ! -d $electron_dist_path ]] && echo 'Electron distribution not found.' && install_needed=true
[[ ! -f $asar_bin_path ]] && echo 'Asar binary not found.' && install_needed=true
if [[ $install_needed == true ]]; then
echo "Installing Electron and Asar locally into $work_dir..."
if ! npm install --no-save electron @electron/asar; then
echo 'Failed to install Electron and/or Asar locally.' >&2
cd "$project_root" || exit 1
exit 1
fi
echo 'Electron and Asar installation command finished.'
else
echo 'Local Electron distribution and Asar binary already present.'
fi
if [[ -d $electron_dist_path ]]; then
echo "Found Electron distribution directory at $electron_dist_path."
chosen_electron_module_path="$(realpath "$work_dir/node_modules/electron")"
echo "Setting Electron module path for copying to $chosen_electron_module_path."
else
echo "Failed to find Electron distribution directory at '$electron_dist_path' after installation attempt." >&2
cd "$project_root" || exit 1
exit 1
fi
if [[ -f $asar_bin_path ]]; then
asar_exec="$(realpath "$asar_bin_path")"
echo "Found local Asar binary at $asar_exec."
else
echo "Failed to find Asar binary at '$asar_bin_path' after installation attempt." >&2
cd "$project_root" || exit 1
exit 1
fi
cd "$project_root" || exit 1
if [[ -z $chosen_electron_module_path || ! -d $chosen_electron_module_path ]]; then
echo 'Critical error: Could not resolve a valid Electron module path to copy.' >&2
exit 1
fi
echo "Using Electron module path: $chosen_electron_module_path"
echo "Using asar executable: $asar_exec"
section_footer 'Electron & Asar Handling'
}
#===============================================================================
# Download and Extract Functions
#===============================================================================
download_claude_installer() {
section_header 'Download the latest Claude executable'
local claude_exe_path="$work_dir/$claude_exe_filename"
if [[ -n $local_exe_path ]]; then
echo "Using local Claude installer: $local_exe_path"
if [[ ! -f $local_exe_path ]]; then
echo "Local installer file not found: $local_exe_path" >&2
exit 1
fi
cp "$local_exe_path" "$claude_exe_path" || exit 1
echo 'Local installer copied to build directory'
else
echo "Downloading Claude Desktop installer for $architecture..."
if ! wget -O "$claude_exe_path" "$claude_download_url"; then
echo "Failed to download Claude Desktop installer from $claude_download_url" >&2
exit 1
fi
echo "Download complete: $claude_exe_filename"
if ! verify_sha256 "$claude_exe_path" \
"$claude_exe_sha256" 'Claude Desktop installer'; then
exit 1
fi
fi
echo "Extracting resources from $claude_exe_filename into separate directory..."
claude_extract_dir="$work_dir/claude-extract"
mkdir -p "$claude_extract_dir" || exit 1
if ! 7z x -y "$claude_exe_path" -o"$claude_extract_dir"; then
echo 'Failed to extract installer' >&2
cd "$project_root" || exit 1
exit 1
fi
cd "$claude_extract_dir" || exit 1
local nupkg_path_relative
nupkg_path_relative=$(find . -maxdepth 1 -name 'AnthropicClaude-*.nupkg' | head -1)
if [[ -z $nupkg_path_relative ]]; then
echo "Could not find AnthropicClaude nupkg file in $claude_extract_dir" >&2
cd "$project_root" || exit 1
exit 1
fi
echo "Found nupkg: $nupkg_path_relative (in $claude_extract_dir)"
version=$(echo "$nupkg_path_relative" | LC_ALL=C grep -oP 'AnthropicClaude-\K[0-9]+\.[0-9]+\.[0-9]+(?=-full|-arm64-full)')
if [[ -z $version ]]; then
echo "Could not extract version from nupkg filename: $nupkg_path_relative" >&2
cd "$project_root" || exit 1
exit 1
fi
echo "Detected Claude version: $version"
# Extract wrapper version from release tag if provided (e.g., v1.3.2+claude1.1.799 -> 1.3.2)
if [[ -n $release_tag ]]; then
local wrapper_version
# Extract version between 'v' and '+claude' (e.g., v1.3.2+claude1.1.799 -> 1.3.2)
wrapper_version=$(echo "$release_tag" | LC_ALL=C grep -oP '^v\K[0-9]+\.[0-9]+\.[0-9]+(?=\+claude)')
if [[ -n $wrapper_version ]]; then
version="${version}-${wrapper_version}"
echo "Package version with wrapper suffix: $version"
else
echo "Warning: Could not extract wrapper version from release tag: $release_tag" >&2
fi
fi
if ! 7z x -y "$nupkg_path_relative"; then
echo 'Failed to extract nupkg' >&2
cd "$project_root" || exit 1
exit 1
fi
echo 'Resources extracted from nupkg'
cd "$project_root" || exit 1
}
#===============================================================================
# Patching Functions
#===============================================================================
patch_app_asar() {
echo 'Processing app.asar...'
cp "$claude_extract_dir/lib/net45/resources/app.asar" "$app_staging_dir/" || exit 1
cp -a "$claude_extract_dir/lib/net45/resources/app.asar.unpacked" "$app_staging_dir/" || exit 1
cd "$app_staging_dir" || exit 1
"$asar_exec" extract app.asar app.asar.contents || exit 1
# Frame fix wrapper
echo 'Creating BrowserWindow frame fix wrapper...'
local original_main
original_main=$(node -e "const pkg = require('./app.asar.contents/package.json'); console.log(pkg.main);")
echo "Original main entry: $original_main"
cp "$source_dir/scripts/frame-fix-wrapper.js" app.asar.contents/frame-fix-wrapper.js || exit 1
cat > app.asar.contents/frame-fix-entry.js << EOFENTRY
// Load frame fix first
require('./frame-fix-wrapper.js');
// Then load original main
require('./${original_main}');
EOFENTRY
# BrowserWindow frame/titleBarStyle patching is handled at runtime by
# frame-fix-wrapper.js via a Proxy on require('electron'). No sed patches
# needed — the wrapper detects popup vs main windows by their options and
# applies frame:true/false accordingly.
# Update package.json
echo 'Modifying package.json to load frame fix and add node-pty...'
node -e "
const fs = require('fs');
const pkg = require('./app.asar.contents/package.json');
pkg.originalMain = pkg.main;
pkg.main = 'frame-fix-entry.js';
pkg.optionalDependencies = pkg.optionalDependencies || {};
pkg.optionalDependencies['node-pty'] = '^1.0.0';
fs.writeFileSync('./app.asar.contents/package.json', JSON.stringify(pkg, null, 2));
console.log('Updated package.json: main entry and node-pty dependency');
"
# Create stub native module
echo 'Creating stub native module...'
mkdir -p app.asar.contents/node_modules/@ant/claude-native || exit 1
cp "$source_dir/scripts/claude-native-stub.js" \
app.asar.contents/node_modules/@ant/claude-native/index.js || exit 1
mkdir -p app.asar.contents/resources/i18n || exit 1
cp "$claude_extract_dir/lib/net45/resources/"*-*.json app.asar.contents/resources/i18n/ || exit 1
# Copy tray icons into asar so both packaged (process.resourcesPath)
# and unpackaged (app.getAppPath()) code paths can find them
cp "$claude_extract_dir/lib/net45/resources/Tray"* app.asar.contents/resources/ 2>/dev/null || \
echo 'Warning: No tray icon files found for asar inclusion'
# Patch title bar detection
patch_titlebar_detection
# Extract electron module variable name for tray patches
extract_electron_variable
# Fix incorrect nativeTheme variable references
fix_native_theme_references
# Patch tray menu handler
patch_tray_menu_handler
# Patch tray icon selection
patch_tray_icon_selection
# Patch menuBarEnabled to default to true when unset
patch_menu_bar_default
# Patch quick window
patch_quick_window
# Add Linux Claude Code support
patch_linux_claude_code
# Patch Cowork mode for Linux (TypeScript VM client + Unix socket)
patch_cowork_linux
# Copy cowork VM service daemon for Linux Cowork mode
echo 'Installing cowork VM service daemon...'
cp "$source_dir/scripts/cowork-vm-service.js" \
app.asar.contents/cowork-vm-service.js || exit 1
echo 'Cowork VM service daemon installed'
}
patch_titlebar_detection() {
echo '##############################################################'
echo "Removing '!' from 'if (\"!\"isWindows && isMainWindow) return null;'"
echo 'detection flag to enable title bar'
local search_base='app.asar.contents/.vite/renderer/main_window/assets'
local target_pattern='MainWindowPage-*.js'
echo "Searching for '$target_pattern' within '$search_base'..."
local target_files
mapfile -t target_files < <(find "$search_base" -type f -name "$target_pattern")
local num_files=${#target_files[@]}
case $num_files in
0)
echo "Error: No file matching '$target_pattern' found within '$search_base'." >&2
exit 1
;;
1)
local target_file="${target_files[0]}"
echo "Found target file: $target_file"
sed -i -E 's/if\(!([a-zA-Z]+)[[:space:]]*&&[[:space:]]*([a-zA-Z]+)\)/if(\1 \&\& \2)/g' "$target_file"
if grep -q -E 'if\(![a-zA-Z]+[[:space:]]*&&[[:space:]]*[a-zA-Z]+\)' "$target_file"; then
echo "Error: Failed to replace patterns in $target_file." >&2
exit 1
fi
echo "Successfully replaced patterns in $target_file"
;;
*)
echo "Error: Expected exactly one file matching '$target_pattern' within '$search_base', but found $num_files." >&2
exit 1
;;
esac
echo '##############################################################'
}
extract_electron_variable() {
echo 'Extracting electron module variable name...'
local index_js='app.asar.contents/.vite/build/index.js'
electron_var=$(grep -oP '\$?\w+(?=\s*=\s*require\("electron"\))' \
"$index_js" | head -1)
if [[ -z $electron_var ]]; then
electron_var=$(grep -oP '(?<=new )\$?\w+(?=\.Tray\b)' \
"$index_js" | head -1)
fi
if [[ -z $electron_var ]]; then
echo 'Failed to extract electron variable name' >&2
cd "$project_root" || exit 1
exit 1
fi
electron_var_re="${electron_var//\$/\\$}"
echo " Found electron variable: $electron_var"
echo '##############################################################'
}
fix_native_theme_references() {
echo 'Fixing incorrect nativeTheme variable references...'
local index_js='app.asar.contents/.vite/build/index.js'
local wrong_refs
mapfile -t wrong_refs < <(
grep -oP '\$?\w+(?=\.nativeTheme)' "$index_js" \
| sort -u \
| grep -Fxv "$electron_var" || true
)
if (( ${#wrong_refs[@]} == 0 )); then
echo ' All nativeTheme references are correct'
echo '##############################################################'
return
fi
local ref ref_re
for ref in "${wrong_refs[@]}"; do
echo " Replacing: $ref.nativeTheme -> $electron_var.nativeTheme"
ref_re="${ref//\$/\\$}"
sed -i -E \
"s/${ref_re}\.nativeTheme/${electron_var_re}.nativeTheme/g" \
"$index_js"
done
echo '##############################################################'
}
patch_tray_menu_handler() {
echo 'Patching tray menu handler...'
local index_js='app.asar.contents/.vite/build/index.js'
local tray_func tray_var first_const
tray_func=$(grep -oP \
'on\("menuBarEnabled",\(\)=>\{\K\w+(?=\(\)\})' "$index_js")
if [[ -z $tray_func ]]; then
echo 'Failed to extract tray menu function name' >&2
cd "$project_root" || exit 1
exit 1
fi
echo " Found tray function: $tray_func"
tray_var=$(grep -oP \
"\}\);let \K\w+(?==null;(?:async )?function ${tray_func})" \
"$index_js")
if [[ -z $tray_var ]]; then
echo 'Failed to extract tray variable name' >&2
cd "$project_root" || exit 1
exit 1
fi
echo " Found tray variable: $tray_var"
sed -i "s/function ${tray_func}(){/async function ${tray_func}(){/g" \
"$index_js"
first_const=$(grep -oP \
"async function ${tray_func}\(\)\{.*?const \K\w+(?==)" \
"$index_js" | head -1)
if [[ -z $first_const ]]; then
echo 'Failed to extract first const in function' >&2
cd "$project_root" || exit 1
exit 1
fi
echo " Found first const variable: $first_const"
# Add mutex guard to prevent concurrent tray rebuilds
if ! grep -q "${tray_func}._running" "$index_js"; then
sed -i "s/async function ${tray_func}(){/async function ${tray_func}(){if(${tray_func}._running)return;${tray_func}._running=true;setTimeout(()=>${tray_func}._running=false,1500);/g" \
"$index_js"
echo " Added mutex guard to ${tray_func}()"
fi
# Add DBus cleanup delay after tray destroy
if ! grep -q "await new Promise.*setTimeout" "$index_js" \
| grep -q "$tray_var"; then
sed -i "s/${tray_var}\&\&(${tray_var}\.destroy(),${tray_var}=null)/${tray_var}\&\&(${tray_var}.destroy(),${tray_var}=null,await new Promise(r=>setTimeout(r,250)))/g" \
"$index_js"
echo " Added DBus cleanup delay after $tray_var.destroy()"
fi
echo 'Tray menu handler patched'
echo '##############################################################'
# Skip tray updates during startup (3 second window)
echo 'Patching nativeTheme handler for startup delay...'
if ! grep -q '_trayStartTime' "$index_js"; then
sed -i -E \
"s/(${electron_var_re}\.nativeTheme\.on\(\s*\"updated\"\s*,\s*\(\)\s*=>\s*\{)/let _trayStartTime=Date.now();\1/g" \
"$index_js"
sed -i -E \
"s/\((\w+\([^)]*\))\s*,\s*${tray_func}\(\)\s*,/(\1,Date.now()-_trayStartTime>3e3\&\&${tray_func}(),/g" \
"$index_js"
echo ' Added startup delay check (3 second window)'
fi
echo '##############################################################'
}
patch_tray_icon_selection() {
echo 'Patching tray icon selection for Linux visibility...'
local index_js='app.asar.contents/.vite/build/index.js'
local dark_check="${electron_var_re}.nativeTheme.shouldUseDarkColors"
if grep -qP ':\$?\w+="TrayIconTemplate\.png"' "$index_js"; then
sed -i -E \
"s/:(\\\$?\w+)=\"TrayIconTemplate\.png\"/:\1=${dark_check}?\"TrayIconTemplate-Dark.png\":\"TrayIconTemplate.png\"/g" \
"$index_js"
echo 'Patched tray icon selection for Linux theme support'
else
echo 'Tray icon selection pattern not found or already patched'
fi
echo '##############################################################'
}
patch_menu_bar_default() {
echo 'Patching menuBarEnabled to default to true when unset...'
local index_js='app.asar.contents/.vite/build/index.js'
local menu_bar_var
menu_bar_var=$(grep -oP \
'const \K\w+(?=\s*=\s*\w+\("menuBarEnabled"\))' \
"$index_js" | head -1)
if [[ -z $menu_bar_var ]]; then
echo ' Could not extract menuBarEnabled variable name'
echo '##############################################################'
return
fi
echo " Found menuBarEnabled variable: $menu_bar_var"
# Change !!var to var!==false so undefined defaults to true
if grep -qP ",\s*!!${menu_bar_var}\s*\)" "$index_js"; then
sed -i -E \
"s/,\s*!!${menu_bar_var}\s*\)/,${menu_bar_var}!==false)/g" \
"$index_js"
echo ' Patched menuBarEnabled to default to true'
else
echo ' menuBarEnabled pattern not found or already patched'
fi
echo '##############################################################'
}
patch_quick_window() {
if ! grep -q 'e.blur(),e.hide()' app.asar.contents/.vite/build/index.js; then
sed -i 's/e.hide()/e.blur(),e.hide()/' app.asar.contents/.vite/build/index.js
echo 'Added blur() call to fix quick window submit issue'
fi
}
patch_linux_claude_code() {
local index_js='app.asar.contents/.vite/build/index.js'
if grep -q 'process.platform==="linux".*linux-arm64.*linux-x64' "$index_js"; then
echo 'Linux claude code binary support already present'
return
fi
# New format (Claude >= 1.1.3541): getHostPlatform includes arch detection for win32
# Pattern: if(process.platform==="win32")return e==="arm64"?"win32-arm64":"win32-x64";throw new Error(...)
if grep -qP 'if\(process\.platform==="win32"\)return \w+==="arm64"\?"win32-arm64":"win32-x64";throw' "$index_js"; then
sed -i -E 's/if\(process\.platform==="win32"\)return (\w+)==="arm64"\?"win32-arm64":"win32-x64";throw/if(process.platform==="win32")return \1==="arm64"?"win32-arm64":"win32-x64";if(process.platform==="linux")return \1==="arm64"?"linux-arm64":"linux-x64";throw/' "$index_js"
echo 'Added linux claude code support (new arch-aware format)'
# Old format (Claude <= 1.1.3363): no arch detection for win32
elif grep -q 'if(process.platform==="win32")return"win32-x64";' "$index_js"; then
sed -i 's/if(process.platform==="win32")return"win32-x64";/if(process.platform==="win32")return"win32-x64";if(process.platform==="linux")return process.arch==="arm64"?"linux-arm64":"linux-x64";/' "$index_js"
echo 'Added linux claude code support (legacy format)'
else
echo 'Warning: Could not find getHostPlatform pattern to patch for Linux claude code support'
fi
}
patch_cowork_linux() {
echo 'Patching Cowork mode for Linux...'
local index_js='app.asar.contents/.vite/build/index.js'
if ! grep -q 'vmClient (TypeScript)' "$index_js"; then
echo ' Cowork mode code not found in this version, skipping'
echo '##############################################################'
return
fi
# All complex patches are done via node to avoid shell escaping issues
# with minified JavaScript. Uses unique string anchors and dynamic
# variable extraction to be version-agnostic per CLAUDE.md guidelines.
if ! INDEX_JS="$index_js" SVC_PATH="cowork-vm-service.js" \
node << 'COWORK_PATCH'
const fs = require('fs');
const indexJs = process.env.INDEX_JS;
let code = fs.readFileSync(indexJs, 'utf8');
let patchCount = 0;
// Helper: extract a balanced block starting at a delimiter.
// Returns the substring from open to close (inclusive), or null.
// Works for {} [] () by specifying the open char.
function extractBlock(str, startIdx, open = '{') {
const close = { '{': '}', '[': ']', '(': ')' }[open];
const blockStart = str.indexOf(open, startIdx);
if (blockStart === -1) return null;
let depth = 1;
let pos = blockStart + 1;
while (depth > 0 && pos < str.length) {
if (str[pos] === open) depth++;
else if (str[pos] === close) depth--;
pos++;
}
return depth === 0 ? str.substring(blockStart, pos) : null;
}
// ============================================================
// Patch 1: Platform check - allow Linux through fz()
// Pattern: VAR!=="darwin"&&VAR!=="win32" (unique in platform gate)
// Anchor: appears near 'unsupported_platform' code value
// ============================================================
const platformGateRe = /(\w+)(\s*!==\s*"darwin"\s*&&\s*)\1(\s*!==\s*"win32")/g;
const origCode = code;
code = code.replace(platformGateRe, (match, varName, mid, end) => {
// Only patch the instance near the "unsupported_platform" code value
const matchIdx = origCode.indexOf(match);
const nearbyText = origCode.substring(matchIdx, matchIdx + 200);
if (nearbyText.includes('unsupported_platform') || nearbyText.includes('Unsupported platform')) {
return `${varName}${mid}${varName}${end}&&${varName}!=="linux"`;
}