Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
1503 lines (1371 loc) · 39.6 KB
/
Copy pathmain.go
File metadata and controls
1503 lines (1371 loc) · 39.6 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
package main
import (
"bufio"
"bytes"
"crypto/ed25519"
"crypto/rand"
"encoding/binary"
"encoding/json"
"encoding/pem"
"errors"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"sshit/internal/persist"
"sshit/internal/update"
"github.com/creack/pty"
"github.com/gliderlabs/ssh"
"github.com/gorilla/websocket"
gossh "golang.org/x/crypto/ssh"
)
// version is injected at build time via -ldflags "-X main.version=..." so that
// every release binary reports the tag it was built from (see scripts/release).
var version = "0.0.0-dev"
const (
repoOwner = "oboard"
repoName = "sshit"
)
func defaultShell() string {
shell := os.Getenv("SHELL")
if shell == "" {
shell = "/bin/sh"
}
return shell
}
// shellWithCwdReporting launches the supported interactive shells with an OSC 7
// prompt hook. OSC 7 reports $PWD to xterm immediately after a prompt redraw,
// so a successful `cd` updates the web title without waiting for cwd polling.
// Unknown shells retain their normal startup behavior and use polling as a
// fallback.
func shellWithCwdReporting(shell string) *exec.Cmd {
base := filepath.Base(shell)
osc7 := `printf '\033]7;file://%s%s\033\\' "${HOSTNAME:-localhost}" "$PWD"`
switch base {
case "bash":
rc, err := os.CreateTemp("", "sshit-bash-*.rc")
if err == nil {
_, _ = fmt.Fprintf(rc, "[ -f ~/.bashrc ] && . ~/.bashrc\n__sshit_osc7() { %s; }\nPROMPT_COMMAND=\"__sshit_osc7${PROMPT_COMMAND:+; $PROMPT_COMMAND}\"\n", osc7)
_ = rc.Close()
return exec.Command(shell, "--rcfile", rc.Name(), "-i")
}
case "zsh":
dir, err := os.MkdirTemp("", "sshit-zsh-")
if err == nil {
rcPath := filepath.Join(dir, ".zshrc")
rc := fmt.Sprintf("[ -f $HOME/.zshrc ] && source $HOME/.zshrc\n__sshit_osc7() { %s; }\nprecmd_functions+=(__sshit_osc7)\n", osc7)
if os.WriteFile(rcPath, []byte(rc), 0600) == nil {
cmd := exec.Command(shell, "-i")
cmd.Env = appendEnv(os.Environ(), "ZDOTDIR", dir)
return cmd
}
}
case "fish":
init := "function __sshit_osc7 --on-event fish_prompt; printf '\\e]7;file://%s%s\\e\\\\' (hostname) $PWD; end"
return exec.Command(shell, "--init-command", init, "-i")
}
return exec.Command(shell)
}
func terminalCommandEnv(term string, overrides []string) []string {
env := terminalEnv(term)
for _, item := range overrides {
key, value, ok := strings.Cut(item, "=")
if !ok {
continue
}
// terminalEnv owns the terminal identity. A login shell's custom
// environment (notably a parent Codex process with TERM=dumb) must not
// overwrite it after we selected the terminal type for the browser PTY.
switch key {
case "TERM", "COLORTERM", "TERM_PROGRAM", "TERM_PROGRAM_VERSION":
continue
}
env = appendEnv(env, key, value)
}
return env
}
func terminalEnv(term string) []string {
if term == "" || term == "dumb" {
term = "xterm-256color"
}
env := os.Environ()
env = appendEnv(env, "TERM", term)
env = appendEnv(env, "COLORTERM", "truecolor")
env = appendEnv(env, "TERM_PROGRAM", "sshit")
env = removeEnv(env, "TERM_PROGRAM_VERSION")
return env
}
func appendEnv(env []string, key, value string) []string {
prefix := key + "="
for i, item := range env {
if strings.HasPrefix(item, prefix) {
env[i] = prefix + value
return env
}
}
return append(env, prefix+value)
}
func removeEnv(env []string, key string) []string {
prefix := key + "="
out := env[:0]
for _, item := range env {
if !strings.HasPrefix(item, prefix) {
out = append(out, item)
}
}
return out
}
func hostKeyPath() (string, error) {
sshDir := filepath.Join(os.Getenv("HOME"), ".ssh")
if home, err := os.UserHomeDir(); err == nil {
sshDir = filepath.Join(home, ".ssh")
}
return filepath.Join(sshDir, "sshit_host_ed25519_key"), os.MkdirAll(sshDir, 0700)
}
func loadOrCreateHostKey() (ssh.Signer, string, error) {
path, err := hostKeyPath()
if err != nil {
return nil, "", err
}
if key, err := os.ReadFile(path); err == nil {
signer, err := gossh.ParsePrivateKey(key)
if err != nil {
return nil, path, fmt.Errorf("parse host key: %w", err)
}
return signer, path, nil
} else if !os.IsNotExist(err) {
return nil, path, err
}
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, path, err
}
block, err := gossh.MarshalPrivateKey(privateKey, "sshit host key")
if err != nil {
return nil, path, err
}
if err := os.WriteFile(path, pem.EncodeToMemory(block), 0600); err != nil {
return nil, path, err
}
signer, err := gossh.NewSignerFromKey(privateKey)
if err != nil {
return nil, path, err
}
return signer, path, nil
}
type bufferedConn struct {
net.Conn
r *bufio.Reader
}
func (c *bufferedConn) Read(p []byte) (int, error) {
return c.r.Read(p)
}
type singleConnListener struct {
conn chan net.Conn
}
func newSingleConnListener(c net.Conn) *singleConnListener {
l := &singleConnListener{conn: make(chan net.Conn, 1)}
l.conn <- c
close(l.conn)
return l
}
func (l *singleConnListener) Accept() (net.Conn, error) {
conn, ok := <-l.conn
if !ok {
return nil, net.ErrClosed
}
return conn, nil
}
func (l *singleConnListener) Close() error { return nil }
func (l *singleConnListener) Addr() net.Addr { return dummyAddr("single-connection") }
type dummyAddr string
func (a dummyAddr) Network() string { return string(a) }
func (a dummyAddr) String() string { return string(a) }
type tcpKeepAliveListener struct {
*net.TCPListener
}
func (l tcpKeepAliveListener) Accept() (net.Conn, error) {
conn, err := l.AcceptTCP()
if err != nil {
return nil, err
}
_ = conn.SetKeepAlive(true)
_ = conn.SetKeepAlivePeriod(3 * time.Minute)
return conn, nil
}
func isSSH(r *bufio.Reader) bool {
prefix, err := r.Peek(4)
return err == nil && string(prefix) == "SSH-"
}
func serveMux(listener net.Listener, sshServer *ssh.Server, httpServer *http.Server) error {
for {
conn, err := listener.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
return nil
}
return err
}
go func(conn net.Conn) {
reader := bufio.NewReader(conn)
buffered := &bufferedConn{Conn: conn, r: reader}
if isSSH(reader) {
sshServer.HandleConn(buffered)
return
}
if err := httpServer.Serve(newSingleConnListener(buffered)); err != nil && !errors.Is(err, net.ErrClosed) {
log.Printf("http connection error: %v", err)
}
}(conn)
}
}
func shellHandler(s ssh.Session) {
cmd := exec.Command(defaultShell())
ptyReq, winCh, isPty := s.Pty()
cmd.Env = terminalEnv(ptyReq.Term)
if !isPty {
io.WriteString(s, "PTY required\n")
return
}
p, err := pty.StartWithAttrs(
cmd,
&pty.Winsize{
Cols: uint16(ptyReq.Window.Width),
Rows: uint16(ptyReq.Window.Height),
},
nil,
)
if err != nil {
log.Printf("failed to start pty: %v", err)
return
}
defer p.Close()
go func() {
for win := range winCh {
_ = pty.Setsize(p, &pty.Winsize{
Cols: uint16(win.Width),
Rows: uint16(win.Height),
})
}
}()
go io.Copy(p, s)
io.Copy(s, p)
}
type wsEnvelope struct {
Type string `json:"type"`
ID int64 `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Color string `json:"color,omitempty"`
ClientID string `json:"clientId,omitempty"`
UserID int `json:"userId,omitempty"`
Awareness json.RawMessage `json:"awareness,omitempty"`
X int `json:"x,omitempty"`
Y int `json:"y,omitempty"`
CursorStyle string `json:"cursorStyle,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
Cols uint16 `json:"cols,omitempty"`
Rows uint16 `json:"rows,omitempty"`
Data string `json:"data,omitempty"`
Password string `json:"password,omitempty"`
Update string `json:"update,omitempty"`
TileLayout json.RawMessage `json:"tileLayout,omitempty"`
Kind string `json:"kind,omitempty"`
DocID string `json:"docId,omitempty"`
Users []webUser `json:"users"`
Windows []windowState `json:"windows"`
User *webUser `json:"user,omitempty"`
Patch *windowPatch `json:"patch,omitempty"`
WindowID int64 `json:"windowId,omitempty"`
}
// windowPatch carries optional updates to a window's geometry, z-order and
// (for shells) terminal size. Nil fields are left unchanged.
type windowPatch struct {
X *int `json:"x,omitempty"`
Y *int `json:"y,omitempty"`
Width *int `json:"width,omitempty"`
Height *int `json:"height,omitempty"`
ZIndex *int `json:"zIndex,omitempty"`
Cols *uint16 `json:"cols,omitempty"`
Rows *uint16 `json:"rows,omitempty"`
}
type webUser struct {
ID int `json:"id"`
Name string `json:"name"`
X int `json:"x"`
Y int `json:"y"`
Cursor bool `json:"cursor"`
CursorStyle string `json:"cursorStyle,omitempty"`
}
// windowState is the serializable state of one workspace window. Shell and
// editor windows share this shape and are told apart by Kind.
type windowState struct {
ID int64 `json:"id"`
Kind string `json:"kind"`
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
ZIndex int `json:"zIndex"`
// Shell-only.
Cols uint16 `json:"cols,omitempty"`
Rows uint16 `json:"rows,omitempty"`
Buffer string `json:"buffer,omitempty"`
Cwd string `json:"cwd,omitempty"`
Home string `json:"home,omitempty"`
// Editor-only.
DocID string `json:"docId,omitempty"`
}
// webWindow is the runtime form of a window. PTY/buffer/cwd/agent only apply
// to shell windows; editor windows are pure layout state.
type webWindow struct {
windowState
pty *os.File
pid int
buffer []byte
cwd string
home string
agentKind string
agentSession string
historyOffset int
}
type webClient struct {
id int
name string
x int
y int
authenticated bool
conn *websocket.Conn
send chan wsEnvelope
out chan wsBinOut
hub *webHub
}
// terminalOutputQueue is deliberately large enough to cover a complete
// multi-part Kitty frame (terminal-browser commonly emits roughly 500 APC
// chunks for a 1920×1280 image). Terminal bytes are a stream: dropping one
// full queue item corrupts the following KGP base64 transmission. A client
// that cannot drain this much is disconnected instead of being fed a damaged
// stream.
const terminalOutputQueue = 512
// wsBinOut carries one terminal-output payload destined for a single client.
// Channeling raw bytes lets the hot path skip JSON marshaling and parse costs.
type wsBinOut struct {
// data is the fully framed WebSocket payload. It is immutable and shared by
// every connected client, avoiding one header+payload allocation per client.
data []byte
}
// WebSocket binary frame layout (big-endian, versioned for future message
// types such as image output):
//
// offset 0 : byte version/category (1 = terminal output)
// offset 1..8 : int64 window id
// offset 9.. : payload bytes
const wsBurstCode = uint8(1)
type collabMessage struct {
messageType int
payload []byte
}
type collabClient struct {
conn *websocket.Conn
send chan collabMessage
clientID string
userID int
name string
color string
awareness json.RawMessage
authenticated bool
closed bool
}
var collabColors = []string{"#f472b6", "#60a5fa", "#34d399", "#fbbf24", "#a78bfa", "#fb7185", "#22d3ee", "#fb923c"}
type webHub struct {
mu sync.Mutex
nextID int
collabSeq int
clients map[int]*webClient
windows map[int64]*webWindow
idSeq int64
topZ int
password string
collabClients map[*collabClient]bool
collabUpdates [][]byte
tileLayout json.RawMessage
persistDir string
persist bool
saveHistory bool
dirty bool
snapMu sync.Mutex
}
func newWebHub(password, persistDir string, persistEnabled, saveHistory bool) *webHub {
return &webHub{
clients: make(map[int]*webClient),
windows: make(map[int64]*webWindow),
password: password,
collabClients: make(map[*collabClient]bool),
persistDir: persistDir,
persist: persistEnabled,
saveHistory: saveHistory,
}
}
// snapshotLocked returns the user list and all windows sorted by ID. The
// caller must hold h.mu.
//
// Terminal scrollback is only attached when includeBuffers is true — used for
// the one-time `hello` handshake a fresh client needs in order to replay the
// screen. Routine `state` broadcasts omit it: re-serializing up to 1 MiB of
// scrollback on every create/move/resize would otherwise flood the socket.
func (h *webHub) snapshotLocked(includeBuffers bool) (users []webUser, windows []windowState) {
users = make([]webUser, 0, len(h.clients))
windows = make([]windowState, 0, len(h.windows))
for _, c := range h.clients {
users = append(users, webUser{ID: c.id, Name: c.name, X: c.x, Y: c.y, Cursor: true})
}
for _, w := range h.windows {
state := w.windowState
if w.Kind == persist.KindShell {
state.Cwd = w.cwd
state.Home = w.home
if includeBuffers {
state.Buffer = string(w.buffer)
}
}
windows = append(windows, state)
}
sort.Slice(windows, func(i, j int) bool { return windows[i].ID < windows[j].ID })
return users, windows
}
func (h *webHub) tileLayoutLocked() json.RawMessage {
return append(json.RawMessage(nil), h.tileLayout...)
}
func (h *webHub) markDirty() {
h.mu.Lock()
h.dirty = true
h.mu.Unlock()
}
// setTileLayout stores the complete tiled-layout snapshot received over the
// normal workspace socket. The JSON is validated before it becomes room state.
func (h *webHub) setTileLayout(layout json.RawMessage) {
if !json.Valid(layout) {
return
}
h.mu.Lock()
if bytes.Equal(h.tileLayout, layout) {
h.mu.Unlock()
return
}
h.tileLayout = append(h.tileLayout[:0], layout...)
h.dirty = true
h.mu.Unlock()
h.broadcastState()
}
func (h *webHub) broadcast(msg wsEnvelope) {
h.mu.Lock()
defer h.mu.Unlock()
for _, c := range h.clients {
select {
case c.send <- msg:
default:
}
}
}
// broadcastOut fans one already-framed terminal payload out to every connected
// client. The frame is immutable and shared; the writer can pass it straight to
// Gorilla without re-encoding or copying it for each subscriber.
//
// Do not silently drop output here. PTY output is a byte stream, not a sequence
// of independent screen updates: losing one WebSocket message in the middle of
// Kitty's m=1/m=0 base64 stream leaves the client unable to decode every frame
// that follows. A genuinely stalled client is removed after its bounded queue
// fills; healthy clients continue to receive an exact, ordered stream.
func (h *webHub) broadcastOut(frame []byte) {
h.mu.Lock()
slow := make([]int, 0)
for id, c := range h.clients {
select {
case c.out <- wsBinOut{data: frame}:
default:
slow = append(slow, id)
}
}
h.mu.Unlock()
// removeClient takes the hub lock itself. Doing it after the fan-out keeps a
// slow peer from holding the lock while its connection is torn down.
for _, id := range slow {
h.removeClient(id)
}
}
func (h *webHub) broadcastState() {
h.mu.Lock()
// Routine state updates carry geometry/z-order/user list only. Terminal
// scrollback is handled by the one-time `hello` handshake; including it
// here on every create/move/resize would re-ship the full buffer to every
// client repeatedly.
users, windows := h.snapshotLocked(false)
h.mu.Unlock()
h.mu.Lock()
tileLayout := h.tileLayoutLocked()
h.mu.Unlock()
h.broadcast(wsEnvelope{Type: "state", Users: users, Windows: windows, TileLayout: tileLayout})
}
func (h *webHub) addClient(conn *websocket.Conn) *webClient {
h.mu.Lock()
h.nextID++
client := &webClient{
id: h.nextID,
name: fmt.Sprintf("user-%d", h.nextID),
authenticated: h.password == "",
conn: conn,
send: make(chan wsEnvelope, 64),
out: make(chan wsBinOut, terminalOutputQueue),
hub: h,
}
if client.authenticated {
h.clients[client.id] = client
}
users, windows := h.snapshotLocked(true)
h.mu.Unlock()
if client.authenticated {
client.send <- wsEnvelope{Type: "hello", ID: int64(client.id), Users: users, Windows: windows}
h.broadcastState()
} else {
client.send <- wsEnvelope{Type: "authRequired"}
}
return client
}
func (h *webHub) removeClient(id int) {
h.mu.Lock()
removed := false
if c, ok := h.clients[id]; ok {
delete(h.clients, id)
close(c.send)
close(c.out)
removed = true
}
h.mu.Unlock()
if removed {
h.broadcastState()
}
}
// createShell starts a new shell window running command (or the default shell
// when command is empty) in cwd, and registers it with the hub.
func (h *webHub) createShell(x, y int, cols, rows, width, height, zIndex int, cwd string, command []string) (*webWindow, error) {
if cols == 0 {
cols = 80
}
if rows == 0 {
rows = 24
}
if width == 0 {
width = 760
}
if height == 0 {
height = 420
}
home, _ := os.UserHomeDir()
if cwd == "" {
cwd = home
}
var cmd *exec.Cmd
if len(command) > 0 {
cmd = exec.Command(command[0], command[1:]...)
} else {
cmd = shellWithCwdReporting(defaultShell())
}
cmd.Dir = cwd
cmd.Env = terminalCommandEnv("xterm-256color", cmd.Env)
p, err := pty.StartWithSize(cmd, &pty.Winsize{Cols: uint16(cols), Rows: uint16(rows)})
if err != nil {
return nil, err
}
h.mu.Lock()
h.idSeq++
h.topZ++
if zIndex <= 0 {
zIndex = h.topZ
}
if zIndex > h.topZ {
h.topZ = zIndex
}
win := &webWindow{
windowState: windowState{
ID: h.idSeq, Kind: persist.KindShell,
X: x, Y: y, Width: width, Height: height, ZIndex: zIndex,
Cols: uint16(cols), Rows: uint16(rows),
Cwd: cwd, Home: home,
},
pty: p,
pid: cmd.Process.Pid,
cwd: cwd,
home: home,
}
h.windows[win.ID] = win
h.dirty = true
h.mu.Unlock()
go h.readShell(win)
h.broadcastState()
return win, nil
}
func (h *webHub) readShell(win *webWindow) {
buf := make([]byte, 32*1024)
for {
n, err := win.pty.Read(buf)
if n > 0 {
// Copy the live PTY read buffer exactly once into its final wire frame.
// That immutable frame is shared by all client writers; only the bounded
// server-side scrollback needs its own additional copy.
frame := encodeBinOut(win.ID, buf[:n])
h.mu.Lock()
win.buffer = append(win.buffer, frame[9:]...)
if len(win.buffer) > 1<<20 {
win.buffer = win.buffer[len(win.buffer)-(1<<20):]
}
h.dirty = true
h.mu.Unlock()
// Send raw bytes in their binary frame, skipping JSON escaping/parsing.
h.broadcastOut(frame)
}
if err != nil {
h.closeWindow(win.ID)
return
}
}
}
// createEditorWindow registers a new editor window. The ID is assigned by the
// hub so shell and editor windows share one ID space.
func (h *webHub) createEditorWindow(x, y, width, height int, docID string) {
if width == 0 {
width = 980
}
if height == 0 {
height = 620
}
if docID == "" {
docID = fmt.Sprintf("doc-%d", time.Now().UnixNano())
}
h.mu.Lock()
h.idSeq++
h.topZ++
win := &webWindow{
windowState: windowState{
ID: h.idSeq, Kind: persist.KindEditor, DocID: docID,
X: x, Y: y, Width: width, Height: height, ZIndex: h.topZ,
},
}
h.windows[win.ID] = win
h.dirty = true
h.mu.Unlock()
h.broadcastState()
}
// patchWindow applies a geometry/z-order/size patch to any window. For shells
// with a terminal size change it also resizes the PTY.
func (h *webHub) patchWindow(id int64, patch windowPatch) {
h.mu.Lock()
win, ok := h.windows[id]
if ok {
if patch.X != nil {
win.X = *patch.X
}
if patch.Y != nil {
win.Y = *patch.Y
}
if patch.Width != nil {
win.Width = *patch.Width
}
if patch.Height != nil {
win.Height = *patch.Height
}
if patch.ZIndex != nil {
win.ZIndex = *patch.ZIndex
if *patch.ZIndex > h.topZ {
h.topZ = *patch.ZIndex
}
}
if win.Kind == persist.KindShell {
if patch.Cols != nil {
win.Cols = *patch.Cols
}
if patch.Rows != nil {
win.Rows = *patch.Rows
}
}
h.dirty = true
}
h.mu.Unlock()
if ok && win.Kind == persist.KindShell && (patch.Cols != nil || patch.Rows != nil) {
_ = pty.Setsize(win.pty, &pty.Winsize{Cols: win.Cols, Rows: win.Rows})
}
if ok {
h.broadcastState()
}
}
func (h *webHub) closeWindow(id int64) {
h.mu.Lock()
win, ok := h.windows[id]
if ok {
delete(h.windows, id)
h.dirty = true
}
h.mu.Unlock()
if ok {
if win.pty != nil {
_ = win.pty.Close()
}
if h.persist {
_ = persist.DeleteHistory(h.persistDir, id)
}
h.broadcastState()
}
}
func (h *webHub) window(id int64) *webWindow {
h.mu.Lock()
defer h.mu.Unlock()
return h.windows[id]
}
const restoredMarker = "\r\n\x1b[2m── session restored after restart ──\x1b[0m\r\n"
// restore rebuilds the workspace from the on-disk snapshot. It returns true
// when at least one window was restored; the caller creates a default shell
// when it returns false.
func (h *webHub) restore() bool {
if !h.persist {
return false
}
snap, err := persist.Load(h.persistDir)
if err != nil {
log.Printf("failed to load session snapshot: %v", err)
return false
}
if len(snap.Windows) == 0 {
return false
}
h.tileLayout = append(json.RawMessage(nil), snap.TileLayout...)
// Reload the collaborative document (markdown content and drawings) so
// editor windows come back with their contents, not just their frames.
if updates, err := persist.LoadCollab(h.persistDir); err != nil {
log.Printf("failed to load collab state: %v", err)
} else if len(updates) > 0 {
h.collabUpdates = updates
}
restored := false
for _, saved := range snap.Windows {
switch saved.Kind {
case persist.KindEditor:
h.mu.Lock()
h.idSeq = saved.ID
if saved.ZIndex > h.topZ {
h.topZ = saved.ZIndex
}
win := &webWindow{windowState: windowState{
ID: saved.ID, Kind: persist.KindEditor, DocID: saved.DocID,
X: saved.X, Y: saved.Y, Width: saved.Width, Height: saved.Height, ZIndex: saved.ZIndex,
}}
h.windows[win.ID] = win
h.mu.Unlock()
restored = true
case persist.KindShell:
if err := h.restoreShell(saved); err != nil {
log.Printf("failed to restore shell %d: %v", saved.ID, err)
continue
}
restored = true
}
}
if snap.IDSeq > h.idSeq {
h.idSeq = snap.IDSeq
}
if restored {
h.mu.Lock()
shells, editors := 0, 0
for _, w := range h.windows {
if w.Kind == persist.KindShell {
shells++
} else {
editors++
}
}
h.mu.Unlock()
log.Printf("restored %d window(s) from %s (%d shell, %d editor)", shells+editors, h.persistDir, shells, editors)
}
return restored
}
// restoreShell rebuilds one shell window: it resumes the agent session when one
// was recorded, otherwise starts a fresh shell in the saved working directory,
// then replays any saved scrollback into the buffer for visual continuity.
func (h *webHub) restoreShell(saved persist.Window) error {
command := persist.ResumeCommand(saved.Agent)
if cols := saved.Cols; cols == 0 {
saved.Cols = 80
}
if rows := saved.Rows; rows == 0 {
saved.Rows = 24
}
var cmd *exec.Cmd
if len(command) > 0 {
cmd = exec.Command(command[0], command[1:]...)
} else {
cmd = shellWithCwdReporting(defaultShell())
}
cwd := saved.Cwd
home, _ := os.UserHomeDir()
if cwd == "" {
cwd = home
}
cmd.Dir = cwd
cmd.Env = terminalCommandEnv("xterm-256color", cmd.Env)
p, err := pty.StartWithSize(cmd, &pty.Winsize{Cols: saved.Cols, Rows: saved.Rows})
if err != nil {
return err
}
win := &webWindow{
windowState: windowState{
ID: saved.ID, Kind: persist.KindShell,
X: saved.X, Y: saved.Y, Width: saved.Width, Height: saved.Height, ZIndex: saved.ZIndex,
Cols: saved.Cols, Rows: saved.Rows,
Cwd: cwd, Home: home,
},
pty: p,
pid: cmd.Process.Pid,
cwd: cwd,
home: home,
}
// Replay saved scrollback so the pane shows its previous screen contents.
// Replay whenever a history file exists, even if this run has
// -persist-history off: the flag gates *writing* history, not reading back
// what a previous run already saved.
if history, err := persist.ReadHistory(h.persistDir, saved.ID); err == nil && len(history) > 0 {
win.buffer = append(win.buffer, history...)
win.buffer = append(win.buffer, restoredMarker...)
win.historyOffset = len(win.buffer)
}
h.mu.Lock()
h.windows[win.ID] = win
if saved.ZIndex > h.topZ {
h.topZ = saved.ZIndex
}
h.dirty = true
h.mu.Unlock()
go h.readShell(win)
return nil
}
// snapshotLoop periodically refreshes live shell metadata and persists the
// workspace when it has changed.
func (h *webHub) snapshotLoop(interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for range ticker.C {
h.refreshAgents()
if !h.persist {
continue
}
if err := h.snapshot(); err != nil {
log.Printf("failed to persist session: %v", err)
}
}
}
// snapshot writes the current window layout (and optional history) to disk if
// anything changed since the last snapshot.
func (h *webHub) snapshot() error {
h.mu.Lock()
if !h.dirty {
h.mu.Unlock()
return nil
}
h.dirty = false
snap := &persist.Snapshot{
IDSeq: h.idSeq,
Windows: make([]persist.Window, 0, len(h.windows)),
TileLayout: append(json.RawMessage(nil), h.tileLayout...),
}
collabUpdates := make([][]byte, len(h.collabUpdates))
for i, u := range h.collabUpdates {
collabUpdates[i] = append([]byte(nil), u...)
}
type historyWrite struct {
id int64
data []byte
}
var histories []historyWrite
keep := make(map[int64]bool)
for _, w := range h.windows {
pw := persist.Window{
ID: w.ID, Kind: w.Kind,
X: w.X, Y: w.Y, Width: w.Width, Height: w.Height, ZIndex: w.ZIndex,
DocID: w.DocID,
}
if w.Kind == persist.KindShell {
pw.Cols, pw.Rows, pw.Cwd = w.Cols, w.Rows, w.cwd
if w.agentKind != "" {