-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
3441 lines (3006 loc) · 98.5 KB
/
main.go
File metadata and controls
3441 lines (3006 loc) · 98.5 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
/* *
* Webmux - a browser-based terminal multiplexer
* Copyright (C) 2026 Webmux contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package main
import (
"archive/zip"
"compress/gzip"
"crypto/sha256"
"embed"
"encoding/base64"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
shellinit "webmux/internal/shell"
)
//go:embed static/*
var staticFiles embed.FS
// SECTION: LOGGING
// RotatingLogWriter writes to both stdout and a rotating log file
type RotatingLogWriter struct {
file *os.File
filePath string
maxLines int
lineCount int
mu sync.Mutex
}
// Global log writer for the application
var logWriter *RotatingLogWriter
// NewRotatingLogWriter creates a log writer that tees to stdout and a file in temp dir
func NewRotatingLogWriter(maxLines int) (*RotatingLogWriter, error) {
logPath := filepath.Join(os.TempDir(), fmt.Sprintf("webmux-%d.log", os.Getpid()))
// Use 0600 permissions - logs may contain sensitive paths or error details
file, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
if err != nil {
return nil, fmt.Errorf("failed to create log file: %w", err)
}
return &RotatingLogWriter{
file: file,
filePath: logPath,
maxLines: maxLines,
}, nil
}
// Write implements io.Writer, writing to both stdout and the log file
func (w *RotatingLogWriter) Write(p []byte) (n int, err error) {
w.mu.Lock()
defer w.mu.Unlock()
// Always write to stdout
os.Stdout.Write(p)
// Count newlines in the data
newLines := 0
for _, b := range p {
if b == '\n' {
newLines++
}
}
// Check if we need to rotate (simple rotation: truncate when limit reached)
if w.lineCount+newLines > w.maxLines {
w.file.Truncate(0)
w.file.Seek(0, 0)
w.lineCount = 0
// Write rotation marker
w.file.WriteString(fmt.Sprintf("[%s] --- Log rotated (max %d lines) ---\n",
time.Now().Format("2006/01/02 15:04:05"), w.maxLines))
w.lineCount++
}
// Write to file
n, err = w.file.Write(p)
w.lineCount += newLines
return n, err
}
// Path returns the log file path
func (w *RotatingLogWriter) Path() string {
return w.filePath
}
// ReadLogs reads the last n lines from the log file
func (w *RotatingLogWriter) ReadLogs(maxLines int) (string, error) {
w.mu.Lock()
defer w.mu.Unlock()
// Validate input
if maxLines <= 0 {
maxLines = 1000
}
// Sync file to ensure all writes are visible
if err := w.file.Sync(); err != nil {
return "", fmt.Errorf("sync failed: %w", err)
}
// Read the entire file
content, err := os.ReadFile(w.filePath)
if err != nil {
return "", fmt.Errorf("read failed: %w", err)
}
// Handle empty file
if len(content) == 0 {
return "", nil
}
lines := strings.Split(string(content), "\n")
// Return last maxLines lines
if len(lines) > maxLines {
lines = lines[len(lines)-maxLines:]
}
return strings.Join(lines, "\n"), nil
}
// Close closes the log file
func (w *RotatingLogWriter) Close() error {
w.mu.Lock()
defer w.mu.Unlock()
if w.file != nil {
return w.file.Close()
}
return nil
}
// SECTION: TYPES
// Session represents a terminal session backed by tmux + ttyd
type Session struct {
ID string `json:"id"`
Name string `json:"name"`
Port int `json:"port"`
CreatedAt time.Time `json:"createdAt"`
CurrentProcess string `json:"currentProcess,omitempty"`
tmuxSession string // tmux session name (e.g., "mux-7701")
ttydCmd *exec.Cmd // current ttyd process (restarts if it exits while tmux persists)
}
// Settings represents user-configurable settings
type Settings struct {
// Multiplexer UI colors
UI UIColors `json:"ui"`
// Terminal colors
Terminal TerminalColors `json:"terminal"`
// Keybar configuration
Keybar KeybarSettings `json:"keybar"`
}
// KeybarSettings represents keybar button configuration
type KeybarSettings struct {
Buttons []string `json:"buttons"`
}
// UIColors represents the multiplexer UI color scheme
type UIColors struct {
BgPrimary string `json:"bgPrimary"`
BgSecondary string `json:"bgSecondary"`
BgTertiary string `json:"bgTertiary"`
TextPrimary string `json:"textPrimary"`
TextSecondary string `json:"textSecondary"`
TextMuted string `json:"textMuted"`
Accent string `json:"accent"`
AccentHover string `json:"accentHover"`
Border string `json:"border"`
}
// TerminalColors represents terminal color scheme using Base24 naming
// Base24 maps: base00=bg, base01-03=grays, base04-05=fg, base06-07=bright fg
// base08-0F=colors (red,orange,yellow,green,cyan,blue,magenta,brown)
// base10-11=darker bg, base12-17=bright colors
type TerminalColors struct {
Base00 string `json:"base00"` // Background
Base01 string `json:"base01"` // Lighter Background (status bars)
Base02 string `json:"base02"` // Selection Background
Base03 string `json:"base03"` // Comments, Invisibles
Base04 string `json:"base04"` // Dark Foreground (status bars)
Base05 string `json:"base05"` // Default Foreground
Base06 string `json:"base06"` // Light Foreground
Base07 string `json:"base07"` // Lightest Foreground
Base08 string `json:"base08"` // Red
Base09 string `json:"base09"` // Orange
Base0A string `json:"base0A"` // Yellow
Base0B string `json:"base0B"` // Green
Base0C string `json:"base0C"` // Cyan
Base0D string `json:"base0D"` // Blue
Base0E string `json:"base0E"` // Magenta
Base0F string `json:"base0F"` // Brown/Dark Red
Base10 string `json:"base10"` // Darker Background
Base11 string `json:"base11"` // Darkest Background
Base12 string `json:"base12"` // Bright Red
Base13 string `json:"base13"` // Bright Yellow
Base14 string `json:"base14"` // Bright Green
Base15 string `json:"base15"` // Bright Cyan
Base16 string `json:"base16"` // Bright Blue
Base17 string `json:"base17"` // Bright Magenta
}
// SECTION: SETTINGS
// DefaultSettings returns the default settings
func DefaultSettings() *Settings {
return &Settings{
UI: UIColors{
BgPrimary: "#1e1e2e",
BgSecondary: "#181825",
BgTertiary: "#313244",
TextPrimary: "#cdd6f4",
TextSecondary: "#a6adc8",
TextMuted: "#6c7086",
Accent: "#89b4fa",
AccentHover: "#b4befe",
Border: "#45475a",
},
Terminal: TerminalColors{
Base00: "#1e1e2e", // Background
Base01: "#181825", // Lighter Background
Base02: "#313244", // Selection
Base03: "#45475a", // Comments
Base04: "#585b70", // Dark Foreground
Base05: "#cdd6f4", // Foreground
Base06: "#f5e0dc", // Light Foreground
Base07: "#ffffff", // Lightest
Base08: "#f38ba8", // Red
Base09: "#fab387", // Orange
Base0A: "#f9e2af", // Yellow
Base0B: "#a6e3a1", // Green
Base0C: "#94e2d5", // Cyan
Base0D: "#89b4fa", // Blue
Base0E: "#cba6f7", // Magenta
Base0F: "#f2cdcd", // Brown
Base10: "#11111b", // Darker Background
Base11: "#0a0a0f", // Darkest Background
Base12: "#f38ba8", // Bright Red
Base13: "#f9e2af", // Bright Yellow
Base14: "#a6e3a1", // Bright Green
Base15: "#94e2d5", // Bright Cyan
Base16: "#89b4fa", // Bright Blue
Base17: "#cba6f7", // Bright Magenta
},
Keybar: KeybarSettings{
Buttons: []string{"C-c", "C-d", "C-z", "C-\\", "C-l", "C-r", "C-u", "C-w"},
},
}
}
// xdgConfigHome returns XDG_CONFIG_HOME or ~/.config
func xdgConfigHome() string {
if dir := os.Getenv("XDG_CONFIG_HOME"); dir != "" {
return dir
}
home, _ := os.UserHomeDir()
return filepath.Join(home, ".config")
}
// xdgDataHome returns XDG_DATA_HOME or ~/.local/share
func xdgDataHome() string {
if dir := os.Getenv("XDG_DATA_HOME"); dir != "" {
return dir
}
home, _ := os.UserHomeDir()
return filepath.Join(home, ".local", "share")
}
// xdgStateHome returns XDG_STATE_HOME or ~/.local/state
// _ for now to silence unused function warning
func _() string {
if dir := os.Getenv("XDG_STATE_HOME"); dir != "" {
return dir
}
home, _ := os.UserHomeDir()
return filepath.Join(home, ".local", "state")
}
// settingsFilePath returns the path to the settings file
func settingsFilePath() string {
return filepath.Join(xdgConfigHome(), "webmux", "settings.json")
}
// LoadSettings loads settings from disk or returns defaults
func LoadSettings() *Settings {
path := settingsFilePath()
data, err := os.ReadFile(path)
if err != nil {
return DefaultSettings()
}
var settings Settings
if err := json.Unmarshal(data, &settings); err != nil {
return DefaultSettings()
}
// Merge with defaults to fill in any missing values
mergeWithDefaults(&settings)
return &settings
}
// mergeWithDefaults fills in empty string values with defaults
func mergeWithDefaults(s *Settings) {
d := DefaultSettings()
// UI colors
if s.UI.BgPrimary == "" {
s.UI.BgPrimary = d.UI.BgPrimary
}
if s.UI.BgSecondary == "" {
s.UI.BgSecondary = d.UI.BgSecondary
}
if s.UI.BgTertiary == "" {
s.UI.BgTertiary = d.UI.BgTertiary
}
if s.UI.TextPrimary == "" {
s.UI.TextPrimary = d.UI.TextPrimary
}
if s.UI.TextSecondary == "" {
s.UI.TextSecondary = d.UI.TextSecondary
}
if s.UI.TextMuted == "" {
s.UI.TextMuted = d.UI.TextMuted
}
if s.UI.Accent == "" {
s.UI.Accent = d.UI.Accent
}
if s.UI.AccentHover == "" {
s.UI.AccentHover = d.UI.AccentHover
}
if s.UI.Border == "" {
s.UI.Border = d.UI.Border
}
// Terminal colors
if s.Terminal.Base00 == "" {
s.Terminal.Base00 = d.Terminal.Base00
}
if s.Terminal.Base01 == "" {
s.Terminal.Base01 = d.Terminal.Base01
}
if s.Terminal.Base02 == "" {
s.Terminal.Base02 = d.Terminal.Base02
}
if s.Terminal.Base03 == "" {
s.Terminal.Base03 = d.Terminal.Base03
}
if s.Terminal.Base04 == "" {
s.Terminal.Base04 = d.Terminal.Base04
}
if s.Terminal.Base05 == "" {
s.Terminal.Base05 = d.Terminal.Base05
}
if s.Terminal.Base06 == "" {
s.Terminal.Base06 = d.Terminal.Base06
}
if s.Terminal.Base07 == "" {
s.Terminal.Base07 = d.Terminal.Base07
}
if s.Terminal.Base08 == "" {
s.Terminal.Base08 = d.Terminal.Base08
}
if s.Terminal.Base09 == "" {
s.Terminal.Base09 = d.Terminal.Base09
}
if s.Terminal.Base0A == "" {
s.Terminal.Base0A = d.Terminal.Base0A
}
if s.Terminal.Base0B == "" {
s.Terminal.Base0B = d.Terminal.Base0B
}
if s.Terminal.Base0C == "" {
s.Terminal.Base0C = d.Terminal.Base0C
}
if s.Terminal.Base0D == "" {
s.Terminal.Base0D = d.Terminal.Base0D
}
if s.Terminal.Base0E == "" {
s.Terminal.Base0E = d.Terminal.Base0E
}
if s.Terminal.Base0F == "" {
s.Terminal.Base0F = d.Terminal.Base0F
}
if s.Terminal.Base10 == "" {
s.Terminal.Base10 = d.Terminal.Base10
}
if s.Terminal.Base11 == "" {
s.Terminal.Base11 = d.Terminal.Base11
}
if s.Terminal.Base12 == "" {
s.Terminal.Base12 = d.Terminal.Base12
}
if s.Terminal.Base13 == "" {
s.Terminal.Base13 = d.Terminal.Base13
}
if s.Terminal.Base14 == "" {
s.Terminal.Base14 = d.Terminal.Base14
}
if s.Terminal.Base15 == "" {
s.Terminal.Base15 = d.Terminal.Base15
}
if s.Terminal.Base16 == "" {
s.Terminal.Base16 = d.Terminal.Base16
}
if s.Terminal.Base17 == "" {
s.Terminal.Base17 = d.Terminal.Base17
}
// Keybar settings - use defaults if empty
if len(s.Keybar.Buttons) == 0 {
s.Keybar.Buttons = d.Keybar.Buttons
}
}
// SaveSettings saves settings to disk
func SaveSettings(settings *Settings) error {
path := settingsFilePath()
// Ensure directory exists
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
data, err := json.MarshalIndent(settings, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, data, 0644)
}
// Display-related environment variables that can be forwarded to sessions
// These are connection variables that allow GUI apps to connect to the display server
var displayEnvVars = []string{
"DISPLAY",
"WAYLAND_DISPLAY",
}
// SECTION: SESSIONS
// SessionManager handles multiple ttyd sessions
type SessionManager struct {
sessions map[string]*Session
mu sync.RWMutex
nextPort int32
startPort int32 // Initial port to reset to when all sessions close
shell string
workDir string // Starting directory for new sessions
tmuxConfigPath string
wmBinDir string // Directory containing wm binary (added to PATH)
getSettings func() *Settings // Function to get current settings
serverPort string // HTTP server port for WEBMUX_PORT env var
onSessionClosed func(string) // Callback when a session is closed/dies
}
// NewSessionManager creates a new session manager
func NewSessionManager(startPort int, shell, workDir, serverPort string) *SessionManager {
sm := &SessionManager{
sessions: make(map[string]*Session),
nextPort: int32(startPort),
startPort: int32(startPort),
shell: shell,
workDir: workDir,
serverPort: serverPort,
}
// Extract tmux config to temp file
tmuxConf, err := staticFiles.ReadFile("static/tmux.conf")
if err != nil {
log.Printf("Warning: could not read tmux.conf: %v", err)
} else {
tmpFile, err := os.CreateTemp("", "mux-tmux-*.conf")
if err != nil {
log.Printf("Warning: could not create temp file for tmux config: %v", err)
} else {
tmpFile.Write(tmuxConf)
tmpFile.Close()
sm.tmuxConfigPath = tmpFile.Name()
log.Printf("Using custom tmux config: %s", sm.tmuxConfigPath)
}
}
// Extract wm binary to temp directory (makes it available in terminal PATH)
wmBin, err := staticFiles.ReadFile("static/wm")
if err != nil {
log.Printf("Warning: could not read embedded wm binary: %v", err)
} else {
tmpDir, err := os.MkdirTemp("", "webmux-bin-*")
if err != nil {
log.Printf("Warning: could not create temp dir for wm: %v", err)
} else {
wmPath := filepath.Join(tmpDir, "wm")
if err := os.WriteFile(wmPath, wmBin, 0755); err != nil {
log.Printf("Warning: could not write wm binary: %v", err)
os.RemoveAll(tmpDir)
} else {
sm.wmBinDir = tmpDir
log.Printf("Extracted wm binary to: %s", wmPath)
}
}
}
// Create shell init script that defines the wm function and sets up clipboard tools
// This will be sourced via ENV (POSIX shells) or BASH_ENV (bash)
if sm.wmBinDir != "" {
wmPath := filepath.Join(sm.wmBinDir, "wm")
initPath := filepath.Join(sm.wmBinDir, "init.sh")
// Generate the init script content using the shared shell package
initContent := shellinit.InitScript(wmPath, sm.wmBinDir)
if err := os.WriteFile(initPath, []byte(initContent), 0644); err != nil {
log.Printf("Warning: could not write init script: %v", err)
}
// Create wl-copy wrapper that uses the webmux clipboard API (via wm copy)
// This allows programs like neovim to use wl-copy transparently
wlCopyPath := filepath.Join(sm.wmBinDir, "wl-copy")
wlCopyContent := fmt.Sprintf(`#!/bin/sh
# webmux wl-copy wrapper - copies to browser clipboard via HTTP API
# Supports: wl-copy [text], echo text | wl-copy, wl-copy < file
# Ignores wl-copy-specific flags for compatibility
# Skip flags (wl-copy has -n, -p, -t, etc.)
while [ $# -gt 0 ]; do
case "$1" in
-n|--trim-newline|-p|--primary|-o|--paste-once|-f|--foreground|-c|--clear)
shift ;;
-t|--type|-s|--seat)
shift 2 ;; # these take an argument
--)
shift; break ;;
-*)
shift ;; # skip unknown flags
*)
break ;;
esac
done
if [ $# -gt 0 ]; then
# Text provided as arguments
printf "%%s" "$*" | %q copy
else
# Read from stdin
%q copy
fi
`, wmPath, wmPath)
if err := os.WriteFile(wlCopyPath, []byte(wlCopyContent), 0755); err != nil {
log.Printf("Warning: could not write wl-copy wrapper: %v", err)
}
// Create wl-paste wrapper that uses the webmux clipboard API (via wm paste)
wlPastePath := filepath.Join(sm.wmBinDir, "wl-paste")
wlPasteContent := fmt.Sprintf(`#!/bin/sh
# webmux wl-paste wrapper - pastes from server-side clipboard via HTTP API
# Ignores wl-paste-specific flags for compatibility
# Skip flags
while [ $# -gt 0 ]; do
case "$1" in
-n|--no-newline|-l|--list-types|-p|--primary)
shift ;;
-t|--type|-s|--seat)
shift 2 ;;
-w|--watch)
# --watch is not supported, just exit
echo "wl-paste --watch not supported in webmux" >&2
exit 1 ;;
--)
shift; break ;;
-*)
shift ;;
*)
break ;;
esac
done
%q paste
`, wmPath)
if err := os.WriteFile(wlPastePath, []byte(wlPasteContent), 0755); err != nil {
log.Printf("Warning: could not write wl-paste wrapper: %v", err)
}
// Create xclip wrapper for X11 clipboard compatibility
// xclip is used by many programs when DISPLAY is set
xclipPath := filepath.Join(sm.wmBinDir, "xclip")
xclipContent := fmt.Sprintf(`#!/bin/sh
# webmux xclip wrapper - copies/pastes to browser clipboard via HTTP API
# Supports: xclip -selection clipboard -i, xclip -selection clipboard -o
selection="clipboard"
mode="in" # default is copy (input)
while [ $# -gt 0 ]; do
case "$1" in
-selection|-sel)
shift
selection="$1"
shift ;;
-i|-in)
mode="in"
shift ;;
-o|-out)
mode="out"
shift ;;
-d|-display|-target|-t|-loops|-l|-quiet|-q|-verbose|-v|-silent|-f|-r|-rmlastnl|-sensitive|-noutf8)
shift ;; # ignore these flags
-*)
shift ;;
*)
shift ;;
esac
done
# Only handle clipboard selection (primary selection not supported via OSC 52)
if [ "$mode" = "out" ]; then
%q paste
else
%q copy
fi
`, wmPath, wmPath)
if err := os.WriteFile(xclipPath, []byte(xclipContent), 0755); err != nil {
log.Printf("Warning: could not write xclip wrapper: %v", err)
}
// Create xsel wrapper for X11 clipboard compatibility
xselPath := filepath.Join(sm.wmBinDir, "xsel")
xselContent := fmt.Sprintf(`#!/bin/sh
# webmux xsel wrapper - copies/pastes to browser clipboard via HTTP API
# Supports: xsel -b -i, xsel -b -o, xsel --clipboard --input, etc.
mode="in" # default is copy (input)
while [ $# -gt 0 ]; do
case "$1" in
-i|--input)
mode="in"
shift ;;
-o|--output)
mode="out"
shift ;;
-a|--append)
mode="in"
shift ;;
-c|--clear)
# Clear clipboard - just copy empty string
echo -n "" | %q copy
exit 0 ;;
-b|--clipboard|-p|--primary|-s|--secondary)
shift ;; # ignore selection type (we only support clipboard)
-d|--display|-t|--selectionTimeout|-l|--logfile|-n|--nodetach|-k|--keep|-x|--delete|-f|--follow|-z|--zeroflush|-v|--verbose)
shift ;;
-*)
shift ;;
*)
shift ;;
esac
done
if [ "$mode" = "out" ]; then
%q paste
else
%q copy
fi
`, wmPath, wmPath, wmPath)
if err := os.WriteFile(xselPath, []byte(xselContent), 0755); err != nil {
log.Printf("Warning: could not write xsel wrapper: %v", err)
}
// Create pbcopy wrapper (macOS compatibility)
pbcopyPath := filepath.Join(sm.wmBinDir, "pbcopy")
pbcopyContent := fmt.Sprintf(`#!/bin/sh
# webmux pbcopy wrapper - copies to clipboard via HTTP API
%q copy
`, wmPath)
if err := os.WriteFile(pbcopyPath, []byte(pbcopyContent), 0755); err != nil {
log.Printf("Warning: could not write pbcopy wrapper: %v", err)
}
// Create pbpaste wrapper (macOS compatibility)
pbpastePath := filepath.Join(sm.wmBinDir, "pbpaste")
pbpasteContent := fmt.Sprintf(`#!/bin/sh
# webmux pbpaste wrapper - pastes from clipboard via HTTP API
%q paste
`, wmPath)
if err := os.WriteFile(pbpastePath, []byte(pbpasteContent), 0755); err != nil {
log.Printf("Warning: could not write pbpaste wrapper: %v", err)
}
}
return sm
}
// tmuxSocketPath returns the path to our dedicated tmux socket
func (sm *SessionManager) tmuxSocketPath() string {
// Use XDG_DATA_HOME (~/.local/share) for the socket to avoid issues with
// XDG_RUNTIME_DIR being cleaned up by systemd when user has no active sessions
// (which happens when accessing webmux only via web/VPN without a local login)
dataDir := xdgDataHome()
socketDir := filepath.Join(dataDir, "webmux")
os.MkdirAll(socketDir, 0700)
return filepath.Join(socketDir, "tmux.sock")
}
// sessionEnvArgs returns tmux -e arguments for setting session environment variables
func (sm *SessionManager) sessionEnvArgs() []string {
var args []string
// Add WEBMUX_PORT so wm CLI knows which server to talk to
args = append(args, "-e", "WEBMUX_PORT="+sm.serverPort)
// Set _wm_bin env var to the path of the wm binary (used by shell wrapper)
if sm.wmBinDir != "" {
args = append(args, "-e", "_wm_bin="+filepath.Join(sm.wmBinDir, "wm"))
}
return args
}
// CreateSession spawns a new tmux session with ttyd attached
func (sm *SessionManager) CreateSession(name string) (*Session, error) {
port := int(atomic.AddInt32(&sm.nextPort, 1))
id := fmt.Sprintf("session-%d", port)
tmuxSession := fmt.Sprintf("mux-%d", port)
if name == "" {
// Find the highest numeric name among active sessions and increment from there
sm.mu.RLock()
maxNum := 0
for _, s := range sm.sessions {
if num, err := strconv.Atoi(s.Name); err == nil && num > maxNum {
maxNum = num
}
}
sm.mu.RUnlock()
name = strconv.Itoa(maxNum + 1)
}
tmuxSocket := sm.tmuxSocketPath()
// Build tmux command with our custom config
// -S: socket path, -f: config file, -d: detached, -s: session name, -x/-y: initial size, -c: start dir
// -e: environment variables for the session
tmuxArgs := []string{"-S", tmuxSocket}
if sm.tmuxConfigPath != "" {
tmuxArgs = append(tmuxArgs, "-f", sm.tmuxConfigPath)
}
tmuxArgs = append(tmuxArgs, "new-session", "-d", "-s", tmuxSession, "-x", "200", "-y", "50")
// Add environment variables (-e must come after new-session)
tmuxArgs = append(tmuxArgs, sm.sessionEnvArgs()...)
// Add session ID so wm CLI knows which session it's in
tmuxArgs = append(tmuxArgs, "-e", "WEBMUX_SESSION="+id)
// Signal that OSC 52 clipboard is supported (webmux intercepts and handles it)
// Apps can check this to enable OSC 52 clipboard integration
tmuxArgs = append(tmuxArgs, "-e", "WEBMUX_CLIPBOARD=osc52")
// Set COLORTERM to help apps detect modern terminal features
tmuxArgs = append(tmuxArgs, "-e", "COLORTERM=truecolor")
// Clear display environment variables by default (clean terminal session)
// We set them to a dummy value rather than empty, because some shell init
// scripts check `[ -z "$DISPLAY" ]` to detect headless sessions and may
// try to start a display server if DISPLAY is empty
for _, key := range displayEnvVars {
tmuxArgs = append(tmuxArgs, "-e", key+"=none")
}
// Set WEBMUX_INIT to our init script path (defines wm function)
if sm.wmBinDir != "" {
initPath := filepath.Join(sm.wmBinDir, "init.sh")
tmuxArgs = append(tmuxArgs, "-e", "WEBMUX_INIT="+initPath)
}
if sm.workDir != "" {
tmuxArgs = append(tmuxArgs, "-c", sm.workDir)
}
// Determine how to inject our init based on shell type
shellBase := filepath.Base(sm.shell)
if sm.wmBinDir != "" {
initPath := filepath.Join(sm.wmBinDir, "init.sh")
switch shellBase {
case "bash":
// bash: use --rcfile to source our init, which also sources user's .bashrc
rcPath := filepath.Join(sm.wmBinDir, "bashrc")
rcContent := fmt.Sprintf(`[ -f ~/.bashrc ] && . ~/.bashrc
. %s
`, initPath)
os.WriteFile(rcPath, []byte(rcContent), 0644)
tmuxArgs = append(tmuxArgs, sm.shell, "--rcfile", rcPath)
case "zsh":
// zsh: use ZDOTDIR with custom rc files that source user's config then our init
zdotdir := filepath.Join(sm.wmBinDir, "zsh")
os.MkdirAll(zdotdir, 0755)
// Create .zshenv that sources user's .zshenv (but keeps our ZDOTDIR)
zshenvContent := `[ -f "$HOME/.zshenv" ] && . "$HOME/.zshenv"
`
os.WriteFile(filepath.Join(zdotdir, ".zshenv"), []byte(zshenvContent), 0644)
// Create .zprofile that sources user's .zprofile
zprofileContent := `[ -f "$HOME/.zprofile" ] && . "$HOME/.zprofile"
`
os.WriteFile(filepath.Join(zdotdir, ".zprofile"), []byte(zprofileContent), 0644)
// Create .zshrc that sources user's .zshrc then our init
zshrcContent := fmt.Sprintf(`[ -f "$HOME/.zshrc" ] && . "$HOME/.zshrc"
. %s
`, initPath)
os.WriteFile(filepath.Join(zdotdir, ".zshrc"), []byte(zshrcContent), 0644)
tmuxArgs = append(tmuxArgs, "-e", "ZDOTDIR="+zdotdir)
tmuxArgs = append(tmuxArgs, sm.shell)
default:
// Other shells: set ENV for POSIX compliance
tmuxArgs = append(tmuxArgs, "-e", "ENV="+initPath)
tmuxArgs = append(tmuxArgs, sm.shell)
}
} else {
tmuxArgs = append(tmuxArgs, sm.shell)
}
tmuxCmd := exec.Command("tmux", tmuxArgs...)
tmuxCmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
if out, err := tmuxCmd.CombinedOutput(); err != nil {
return nil, fmt.Errorf("failed to create tmux session: %w: %s", err, string(out))
}
// Wait for tmux session to be ready
for range 50 {
checkCmd := exec.Command("tmux", "-S", tmuxSocket, "has-session", "-t", tmuxSession)
if checkCmd.Run() == nil {
break
}
time.Sleep(10 * time.Millisecond)
}
session := &Session{
ID: id,
Name: name,
Port: port,
CreatedAt: time.Now(),
tmuxSession: tmuxSession,
}
// Start ttyd attached to the tmux session (must be called without lock)
if err := sm.startTtyd(session); err != nil {
// Clean up tmux session
exec.Command("tmux", "-S", tmuxSocket, "kill-session", "-t", tmuxSession).Run()
return nil, err
}
// Add to sessions map
sm.mu.Lock()
sm.sessions[id] = session
sm.mu.Unlock()
// Monitor tmux session to detect when shell exits
go sm.monitorSession(session)
log.Printf("Created session %s on port %d", id, port)
return session, nil
}
// startTtyd starts a ttyd process attached to the session's tmux session
// NOTE: This must be called WITHOUT holding sm.mu lock
func (sm *SessionManager) startTtyd(session *Session) error {
tmuxSocket := sm.tmuxSocketPath()
tmuxSession := session.tmuxSession
// Get terminal colors from settings
var termColors TerminalColors
if sm.getSettings != nil {
termColors = sm.getSettings().Terminal
} else {
termColors = DefaultSettings().Terminal
}
// Build theme JSON for ttyd using Base24 mapping
// ttyd xterm.js theme format -> Base24 mapping:
// background=base00, foreground=base05, cursor=base06, cursorAccent=base00
// selection=base02, black=base03, red=base08, green=base0B, yellow=base0A
// blue=base0D, magenta=base0E, cyan=base0C, white=base06
// brightBlack=base04, brightRed=base12, brightGreen=base14, brightYellow=base13
// brightBlue=base16, brightMagenta=base17, brightCyan=base15, brightWhite=base07
themeJSON := fmt.Sprintf(`{"background":"%s","foreground":"%s","cursor":"%s","cursorAccent":"%s","selection":"%s","black":"%s","red":"%s","green":"%s","yellow":"%s","blue":"%s","magenta":"%s","cyan":"%s","white":"%s","brightBlack":"%s","brightRed":"%s","brightGreen":"%s","brightYellow":"%s","brightBlue":"%s","brightMagenta":"%s","brightCyan":"%s","brightWhite":"%s"}`,
termColors.Base00, termColors.Base05, termColors.Base06, termColors.Base00,
termColors.Base02, termColors.Base03, termColors.Base08, termColors.Base0B, termColors.Base0A,
termColors.Base0D, termColors.Base0E, termColors.Base0C, termColors.Base06,
termColors.Base04, termColors.Base12, termColors.Base14, termColors.Base13,
termColors.Base16, termColors.Base17, termColors.Base15, termColors.Base07)
// No --once: ttyd stays running and each client connection runs tmux attach
// Multiple tmux attach calls to the same session share the view
args := []string{
"--port", strconv.Itoa(session.Port),
"--writable",
"--client-option", "fontSize=14",
"--client-option", "fontFamily=JetBrains Mono,Fira Code,SF Mono,Menlo,Monaco,Courier New,monospace",
"--client-option", "theme=" + themeJSON,
"--client-option", "disableLeaveAlert=true",
"--client-option", "scrollback=50000",
"--client-option", "allowProposedApi=true",
"--client-option", "rightClickSelectsWord=true",
}
// Build tmux attach command with our config
tmuxArgs := []string{"-S", tmuxSocket}
if sm.tmuxConfigPath != "" {
tmuxArgs = append(tmuxArgs, "-f", sm.tmuxConfigPath)
}
tmuxArgs = append(tmuxArgs, "attach-session", "-t", tmuxSession)
args = append(args, "tmux")
args = append(args, tmuxArgs...)
cmd := exec.Command("ttyd", args...)
// Don't inherit stdout/stderr to avoid echoing to parent terminal
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
if err := cmd.Start(); err != nil {
return fmt.Errorf("failed to start ttyd: %w", err)
}
session.ttydCmd = cmd
// Monitor ttyd process and restart when client disconnects
go sm.handleTtydExit(session, cmd)
// Wait for ttyd to be ready (port accepting connections)
addr := fmt.Sprintf("127.0.0.1:%d", session.Port)
for range 50 {
conn, err := net.DialTimeout("tcp", addr, 10*time.Millisecond)
if err == nil {
conn.Close()
break
}
time.Sleep(10 * time.Millisecond)
}
return nil
}
// handleTtydExit handles ttyd process exit and restarts for reconnection
func (sm *SessionManager) handleTtydExit(session *Session, cmd *exec.Cmd) {
exitState := cmd.Wait()
log.Printf("Session %s: ttyd process exited with: %v", session.ID, exitState)
sm.mu.Lock()
// Check if session still exists
s, ok := sm.sessions[session.ID]
if !ok {
log.Printf("Session %s: already removed from sessions map", session.ID)
sm.mu.Unlock()
return
}
// Check if tmux session still exists
tmuxSocket := sm.tmuxSocketPath()
checkCmd := exec.Command("tmux", "-S", tmuxSocket, "has-session", "-t", session.tmuxSession)
if err := checkCmd.Run(); err != nil {
// tmux session is gone, clean up
log.Printf("Session %s: tmux session %s no longer exists, cleaning up", session.ID, session.tmuxSession)
sm.deleteSession(session.ID)
if len(sm.sessions) == 0 {
sm.resetCounters()
}
sm.mu.Unlock()
return
}
log.Printf("Session %s: ttyd exited but tmux session %s still exists, restarting ttyd...", session.ID, session.tmuxSession)
sm.mu.Unlock()