-
-
Notifications
You must be signed in to change notification settings - Fork 953
Expand file tree
/
Copy pathwshserver.go
More file actions
1581 lines (1417 loc) · 50.6 KB
/
wshserver.go
File metadata and controls
1581 lines (1417 loc) · 50.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
// Copyright 2025, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
package wshserver
// this file contains the implementation of the wsh server methods
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"github.com/skratchdot/open-golang/open"
"github.com/wavetermdev/waveterm/pkg/aiusechat"
"github.com/wavetermdev/waveterm/pkg/aiusechat/chatstore"
"github.com/wavetermdev/waveterm/pkg/aiusechat/uctypes"
"github.com/wavetermdev/waveterm/pkg/baseds"
"github.com/wavetermdev/waveterm/pkg/blockcontroller"
"github.com/wavetermdev/waveterm/pkg/blocklogger"
"github.com/wavetermdev/waveterm/pkg/buildercontroller"
"github.com/wavetermdev/waveterm/pkg/filebackup"
"github.com/wavetermdev/waveterm/pkg/filestore"
"github.com/wavetermdev/waveterm/pkg/genconn"
"github.com/wavetermdev/waveterm/pkg/jobcontroller"
"github.com/wavetermdev/waveterm/pkg/panichandler"
"github.com/wavetermdev/waveterm/pkg/remote"
"github.com/wavetermdev/waveterm/pkg/remote/conncontroller"
"github.com/wavetermdev/waveterm/pkg/remote/fileshare/wshfs"
"github.com/wavetermdev/waveterm/pkg/secretstore"
"github.com/wavetermdev/waveterm/pkg/suggestion"
"github.com/wavetermdev/waveterm/pkg/telemetry"
"github.com/wavetermdev/waveterm/pkg/telemetry/telemetrydata"
"github.com/wavetermdev/waveterm/pkg/util/envutil"
"github.com/wavetermdev/waveterm/pkg/util/shellutil"
"github.com/wavetermdev/waveterm/pkg/util/utilfn"
"github.com/wavetermdev/waveterm/pkg/waveai"
"github.com/wavetermdev/waveterm/pkg/waveappstore"
"github.com/wavetermdev/waveterm/pkg/waveapputil"
"github.com/wavetermdev/waveterm/pkg/wavebase"
"github.com/wavetermdev/waveterm/pkg/wavejwt"
"github.com/wavetermdev/waveterm/pkg/waveobj"
"github.com/wavetermdev/waveterm/pkg/wcloud"
"github.com/wavetermdev/waveterm/pkg/wconfig"
"github.com/wavetermdev/waveterm/pkg/wcore"
"github.com/wavetermdev/waveterm/pkg/wps"
"github.com/wavetermdev/waveterm/pkg/wshrpc"
"github.com/wavetermdev/waveterm/pkg/wshutil"
"github.com/wavetermdev/waveterm/pkg/wsl"
"github.com/wavetermdev/waveterm/pkg/wslconn"
"github.com/wavetermdev/waveterm/pkg/wstore"
"github.com/wavetermdev/waveterm/tsunami/build"
)
var InvalidWslDistroNames = []string{"docker-desktop", "docker-desktop-data"}
type WshServer struct{}
func (*WshServer) WshServerImpl() {}
var WshServerImpl = WshServer{}
func (ws *WshServer) GetJwtPublicKeyCommand(ctx context.Context) (string, error) {
return wavejwt.GetPublicKeyBase64(), nil
}
func (ws *WshServer) TestCommand(ctx context.Context, data string) error {
defer func() {
panichandler.PanicHandler("TestCommand", recover())
}()
rpcSource := wshutil.GetRpcSourceFromContext(ctx)
log.Printf("TEST src:%s | %s\n", rpcSource, data)
return nil
}
func (ws *WshServer) TestMultiArgCommand(ctx context.Context, arg1 string, arg2 int, arg3 bool) (string, error) {
defer func() {
panichandler.PanicHandler("TestMultiArgCommand", recover())
}()
rpcSource := wshutil.GetRpcSourceFromContext(ctx)
rtn := fmt.Sprintf("src:%s arg1:%q arg2:%d arg3:%t", rpcSource, arg1, arg2, arg3)
log.Printf("TESTMULTI %s\n", rtn)
return rtn, nil
}
// for testing
func (ws *WshServer) MessageCommand(ctx context.Context, data wshrpc.CommandMessageData) error {
log.Printf("MESSAGE: %s\n", data.Message)
return nil
}
// for testing
func (ws *WshServer) StreamTestCommand(ctx context.Context) chan wshrpc.RespOrErrorUnion[int] {
rtn := make(chan wshrpc.RespOrErrorUnion[int])
go func() {
defer func() {
panichandler.PanicHandler("StreamTestCommand", recover())
}()
for i := 1; i <= 5; i++ {
rtn <- wshrpc.RespOrErrorUnion[int]{Response: i}
time.Sleep(1 * time.Second)
}
close(rtn)
}()
return rtn
}
func (ws *WshServer) StreamWaveAiCommand(ctx context.Context, request wshrpc.WaveAIStreamRequest) chan wshrpc.RespOrErrorUnion[wshrpc.WaveAIPacketType] {
return waveai.RunAICommand(ctx, request)
}
func MakePlotData(ctx context.Context, blockId string) error {
block, err := wstore.DBMustGet[*waveobj.Block](ctx, blockId)
if err != nil {
return err
}
viewName := block.Meta.GetString(waveobj.MetaKey_View, "")
if viewName != "cpuplot" && viewName != "sysinfo" {
return fmt.Errorf("invalid view type: %s", viewName)
}
return filestore.WFS.MakeFile(ctx, blockId, "cpuplotdata", nil, wshrpc.FileOpts{})
}
func SavePlotData(ctx context.Context, blockId string, history string) error {
block, err := wstore.DBMustGet[*waveobj.Block](ctx, blockId)
if err != nil {
return err
}
viewName := block.Meta.GetString(waveobj.MetaKey_View, "")
if viewName != "cpuplot" && viewName != "sysinfo" {
return fmt.Errorf("invalid view type: %s", viewName)
}
// todo: interpret the data being passed
// for now, this is just to throw an error if the block was closed
historyBytes, err := json.Marshal(history)
if err != nil {
return fmt.Errorf("unable to serialize plot data: %v", err)
}
// ignore MakeFile error (already exists is ok)
return filestore.WFS.WriteFile(ctx, blockId, "cpuplotdata", historyBytes)
}
func (ws *WshServer) GetMetaCommand(ctx context.Context, data wshrpc.CommandGetMetaData) (waveobj.MetaMapType, error) {
obj, err := wstore.DBGetORef(ctx, data.ORef)
if err != nil {
return nil, fmt.Errorf("error getting object: %w", err)
}
if obj == nil {
return nil, fmt.Errorf("object not found: %s", data.ORef)
}
return waveobj.GetMeta(obj), nil
}
func (ws *WshServer) UpdateTabNameCommand(ctx context.Context, tabId string, newName string) error {
oref := waveobj.ORef{OType: waveobj.OType_Tab, OID: tabId}
err := wstore.UpdateTabName(ctx, tabId, newName)
if err != nil {
return fmt.Errorf("error updating tab name: %w", err)
}
wcore.SendWaveObjUpdate(oref)
return nil
}
func (ws *WshServer) UpdateWorkspaceTabIdsCommand(ctx context.Context, workspaceId string, tabIds []string) error {
oref := waveobj.ORef{OType: waveobj.OType_Workspace, OID: workspaceId}
err := wcore.UpdateWorkspaceTabIds(ctx, workspaceId, tabIds)
if err != nil {
return fmt.Errorf("error updating workspace tab ids: %w", err)
}
wcore.SendWaveObjUpdate(oref)
return nil
}
func (ws *WshServer) SetMetaCommand(ctx context.Context, data wshrpc.CommandSetMetaData) error {
log.Printf("SetMetaCommand: %s | %v\n", data.ORef, data.Meta)
oref := data.ORef
err := wstore.UpdateObjectMeta(ctx, oref, data.Meta, false)
if err != nil {
return fmt.Errorf("error updating object meta: %w", err)
}
wcore.SendWaveObjUpdate(oref)
return nil
}
func (ws *WshServer) GetRTInfoCommand(ctx context.Context, data wshrpc.CommandGetRTInfoData) (*waveobj.ObjRTInfo, error) {
return wstore.GetRTInfo(data.ORef), nil
}
func (ws *WshServer) SetRTInfoCommand(ctx context.Context, data wshrpc.CommandSetRTInfoData) error {
if data.Delete {
wstore.DeleteRTInfo(data.ORef)
return nil
}
wstore.SetRTInfo(data.ORef, data.Data)
return nil
}
func (ws *WshServer) ResolveIdsCommand(ctx context.Context, data wshrpc.CommandResolveIdsData) (wshrpc.CommandResolveIdsRtnData, error) {
rtn := wshrpc.CommandResolveIdsRtnData{}
rtn.ResolvedIds = make(map[string]waveobj.ORef)
var firstErr error
for _, simpleId := range data.Ids {
oref, err := resolveSimpleId(ctx, data, simpleId)
if err != nil {
if firstErr == nil {
firstErr = err
}
continue
}
if oref == nil {
continue
}
rtn.ResolvedIds[simpleId] = *oref
}
if firstErr != nil && len(data.Ids) == 1 {
return rtn, firstErr
}
return rtn, nil
}
func (ws *WshServer) CreateBlockCommand(ctx context.Context, data wshrpc.CommandCreateBlockData) (*waveobj.ORef, error) {
ctx = waveobj.ContextWithUpdates(ctx)
tabId := data.TabId
blockData, err := wcore.CreateBlock(ctx, tabId, data.BlockDef, data.RtOpts)
if err != nil {
return nil, fmt.Errorf("error creating block: %w", err)
}
var layoutAction *waveobj.LayoutActionData
if data.TargetBlockId != "" {
switch data.TargetAction {
case "replace":
layoutAction = &waveobj.LayoutActionData{
ActionType: wcore.LayoutActionDataType_Replace,
TargetBlockId: data.TargetBlockId,
BlockId: blockData.OID,
Focused: data.Focused,
}
err = wcore.DeleteBlock(ctx, data.TargetBlockId, false)
if err != nil {
return nil, fmt.Errorf("error deleting block (trying to do block replace): %w", err)
}
case "splitright":
layoutAction = &waveobj.LayoutActionData{
ActionType: wcore.LayoutActionDataType_SplitHorizontal,
BlockId: blockData.OID,
TargetBlockId: data.TargetBlockId,
Position: "after",
Focused: data.Focused,
}
case "splitleft":
layoutAction = &waveobj.LayoutActionData{
ActionType: wcore.LayoutActionDataType_SplitHorizontal,
BlockId: blockData.OID,
TargetBlockId: data.TargetBlockId,
Position: "before",
Focused: data.Focused,
}
case "splitup":
layoutAction = &waveobj.LayoutActionData{
ActionType: wcore.LayoutActionDataType_SplitVertical,
BlockId: blockData.OID,
TargetBlockId: data.TargetBlockId,
Position: "before",
Focused: data.Focused,
}
case "splitdown":
layoutAction = &waveobj.LayoutActionData{
ActionType: wcore.LayoutActionDataType_SplitVertical,
BlockId: blockData.OID,
TargetBlockId: data.TargetBlockId,
Position: "after",
Focused: data.Focused,
}
default:
return nil, fmt.Errorf("invalid target action: %s", data.TargetAction)
}
} else {
layoutAction = &waveobj.LayoutActionData{
ActionType: wcore.LayoutActionDataType_Insert,
BlockId: blockData.OID,
Magnified: data.Magnified,
Ephemeral: data.Ephemeral,
Focused: data.Focused,
}
}
err = wcore.QueueLayoutActionForTab(ctx, tabId, *layoutAction)
if err != nil {
return nil, fmt.Errorf("error queuing layout action: %w", err)
}
updates := waveobj.ContextGetUpdatesRtn(ctx)
wps.Broker.SendUpdateEvents(updates)
return &waveobj.ORef{OType: waveobj.OType_Block, OID: blockData.OID}, nil
}
func (ws *WshServer) CreateSubBlockCommand(ctx context.Context, data wshrpc.CommandCreateSubBlockData) (*waveobj.ORef, error) {
parentBlockId := data.ParentBlockId
blockData, err := wcore.CreateSubBlock(ctx, parentBlockId, data.BlockDef)
if err != nil {
return nil, fmt.Errorf("error creating block: %w", err)
}
blockRef := &waveobj.ORef{OType: waveobj.OType_Block, OID: blockData.OID}
return blockRef, nil
}
func (ws *WshServer) ControllerDestroyCommand(ctx context.Context, blockId string) error {
blockcontroller.DestroyBlockController(blockId)
return nil
}
func (ws *WshServer) ControllerResyncCommand(ctx context.Context, data wshrpc.CommandControllerResyncData) error {
ctx = genconn.ContextWithConnData(ctx, data.BlockId)
ctx = termCtxWithLogBlockId(ctx, data.BlockId)
return blockcontroller.ResyncController(ctx, data.TabId, data.BlockId, data.RtOpts, data.ForceRestart)
}
func (ws *WshServer) ControllerInputCommand(ctx context.Context, data wshrpc.CommandBlockInputData) error {
inputUnion := &blockcontroller.BlockInputUnion{
SigName: data.SigName,
TermSize: data.TermSize,
}
if len(data.InputData64) > 0 {
inputBuf := make([]byte, base64.StdEncoding.DecodedLen(len(data.InputData64)))
nw, err := base64.StdEncoding.Decode(inputBuf, []byte(data.InputData64))
if err != nil {
return fmt.Errorf("error decoding input data: %w", err)
}
inputUnion.InputData = inputBuf[:nw]
}
return blockcontroller.SendInput(data.BlockId, inputUnion)
}
func (ws *WshServer) ControllerAppendOutputCommand(ctx context.Context, data wshrpc.CommandControllerAppendOutputData) error {
outputBuf := make([]byte, base64.StdEncoding.DecodedLen(len(data.Data64)))
nw, err := base64.StdEncoding.Decode(outputBuf, []byte(data.Data64))
if err != nil {
return fmt.Errorf("error decoding output data: %w", err)
}
err = blockcontroller.HandleAppendBlockFile(data.BlockId, wavebase.BlockFile_Term, outputBuf[:nw])
if err != nil {
return fmt.Errorf("error appending to block file: %w", err)
}
return nil
}
func (ws *WshServer) FileCreateCommand(ctx context.Context, data wshrpc.FileData) error {
data.Data64 = ""
err := wshfs.PutFile(ctx, data)
if err != nil {
return fmt.Errorf("error creating file: %w", err)
}
return nil
}
func (ws *WshServer) FileMkdirCommand(ctx context.Context, data wshrpc.FileData) error {
return wshfs.Mkdir(ctx, data.Info.Path)
}
func (ws *WshServer) FileDeleteCommand(ctx context.Context, data wshrpc.CommandDeleteFileData) error {
return wshfs.Delete(ctx, data)
}
func (ws *WshServer) FileInfoCommand(ctx context.Context, data wshrpc.FileData) (*wshrpc.FileInfo, error) {
return wshfs.Stat(ctx, data.Info.Path)
}
func (ws *WshServer) FileListCommand(ctx context.Context, data wshrpc.FileListData) ([]*wshrpc.FileInfo, error) {
return wshfs.ListEntries(ctx, data.Path, data.Opts)
}
func (ws *WshServer) FileListStreamCommand(ctx context.Context, data wshrpc.FileListData) <-chan wshrpc.RespOrErrorUnion[wshrpc.CommandRemoteListEntriesRtnData] {
return wshfs.ListEntriesStream(ctx, data.Path, data.Opts)
}
func (ws *WshServer) FileWriteCommand(ctx context.Context, data wshrpc.FileData) error {
return wshfs.PutFile(ctx, data)
}
func (ws *WshServer) FileReadCommand(ctx context.Context, data wshrpc.FileData) (*wshrpc.FileData, error) {
return wshfs.Read(ctx, data)
}
func (ws *WshServer) FileStreamCommand(ctx context.Context, data wshrpc.CommandFileStreamData) (*wshrpc.FileInfo, error) {
return wshfs.FileStream(ctx, data)
}
func (ws *WshServer) FileCopyCommand(ctx context.Context, data wshrpc.CommandFileCopyData) error {
return wshfs.Copy(ctx, data)
}
func (ws *WshServer) FileMoveCommand(ctx context.Context, data wshrpc.CommandFileCopyData) error {
return wshfs.Move(ctx, data)
}
func (ws *WshServer) FileAppendCommand(ctx context.Context, data wshrpc.FileData) error {
return wshfs.Append(ctx, data)
}
func (ws *WshServer) FileJoinCommand(ctx context.Context, paths []string) (*wshrpc.FileInfo, error) {
if len(paths) < 2 {
if len(paths) == 0 {
return nil, fmt.Errorf("no paths provided")
}
return wshfs.Stat(ctx, paths[0])
}
return wshfs.Join(ctx, paths[0], paths[1:]...)
}
func (ws *WshServer) FileRestoreBackupCommand(ctx context.Context, data wshrpc.CommandFileRestoreBackupData) error {
expandedBackupPath, err := wavebase.ExpandHomeDir(data.BackupFilePath)
if err != nil {
return fmt.Errorf("failed to expand backup file path: %w", err)
}
expandedRestorePath, err := wavebase.ExpandHomeDir(data.RestoreToFileName)
if err != nil {
return fmt.Errorf("failed to expand restore file path: %w", err)
}
return filebackup.RestoreBackup(expandedBackupPath, expandedRestorePath)
}
func (ws *WshServer) GetTempDirCommand(ctx context.Context, data wshrpc.CommandGetTempDirData) (string, error) {
tempDir := os.TempDir()
if data.FileName != "" {
// Reduce to a simple file name to avoid absolute paths or traversal
name := filepath.Base(data.FileName)
// Normalize/trim any stray separators and whitespace
name = strings.Trim(name, `/\`+" ")
if name == "" || name == "." {
return tempDir, nil
}
return filepath.Join(tempDir, name), nil
}
return tempDir, nil
}
func (ws *WshServer) WriteTempFileCommand(ctx context.Context, data wshrpc.CommandWriteTempFileData) (string, error) {
if data.FileName == "" {
return "", fmt.Errorf("filename is required")
}
name := filepath.Base(data.FileName)
if name == "" || name == "." || name == ".." {
return "", fmt.Errorf("invalid filename")
}
tempDir, err := os.MkdirTemp("", "waveterm-")
if err != nil {
return "", fmt.Errorf("error creating temp directory: %w", err)
}
decoded, err := base64.StdEncoding.DecodeString(data.Data64)
if err != nil {
return "", fmt.Errorf("error decoding base64 data: %w", err)
}
tempPath := filepath.Join(tempDir, name)
err = os.WriteFile(tempPath, decoded, 0600)
if err != nil {
return "", fmt.Errorf("error writing temp file: %w", err)
}
return tempPath, nil
}
func (ws *WshServer) DeleteSubBlockCommand(ctx context.Context, data wshrpc.CommandDeleteBlockData) error {
if data.BlockId == "" {
return fmt.Errorf("blockid is required")
}
err := wcore.DeleteBlock(ctx, data.BlockId, false)
if err != nil {
return fmt.Errorf("error deleting block: %w", err)
}
return nil
}
func (ws *WshServer) DeleteBlockCommand(ctx context.Context, data wshrpc.CommandDeleteBlockData) error {
if data.BlockId == "" {
return fmt.Errorf("blockid is required")
}
ctx = waveobj.ContextWithUpdates(ctx)
tabId, err := wstore.DBFindTabForBlockId(ctx, data.BlockId)
if err != nil {
return fmt.Errorf("error finding tab for block: %w", err)
}
if tabId == "" {
return fmt.Errorf("no tab found for block")
}
err = wcore.DeleteBlock(ctx, data.BlockId, true)
if err != nil {
return fmt.Errorf("error deleting block: %w", err)
}
wcore.QueueLayoutActionForTab(ctx, tabId, waveobj.LayoutActionData{
ActionType: wcore.LayoutActionDataType_Remove,
BlockId: data.BlockId,
})
updates := waveobj.ContextGetUpdatesRtn(ctx)
wps.Broker.SendUpdateEvents(updates)
return nil
}
func (ws *WshServer) WaitForRouteCommand(ctx context.Context, data wshrpc.CommandWaitForRouteData) (bool, error) {
waitCtx, cancelFn := context.WithTimeout(ctx, time.Duration(data.WaitMs)*time.Millisecond)
defer cancelFn()
err := wshutil.DefaultRouter.WaitForRegister(waitCtx, data.RouteId)
return err == nil, nil
}
func (ws *WshServer) EventRecvCommand(ctx context.Context, data wps.WaveEvent) error {
return nil
}
func (ws *WshServer) EventPublishCommand(ctx context.Context, data wps.WaveEvent) error {
rpcSource := wshutil.GetRpcSourceFromContext(ctx)
if rpcSource == "" {
return fmt.Errorf("no rpc source set")
}
if data.Sender == "" {
data.Sender = rpcSource
}
wps.Broker.Publish(data)
return nil
}
func (ws *WshServer) EventSubCommand(ctx context.Context, data wps.SubscriptionRequest) error {
rpcSource := wshutil.GetRpcSourceFromContext(ctx)
if rpcSource == "" {
return fmt.Errorf("no rpc source set")
}
wps.Broker.Subscribe(rpcSource, data)
return nil
}
func (ws *WshServer) EventUnsubCommand(ctx context.Context, data string) error {
rpcSource := wshutil.GetRpcSourceFromContext(ctx)
if rpcSource == "" {
return fmt.Errorf("no rpc source set")
}
wps.Broker.Unsubscribe(rpcSource, data)
return nil
}
func (ws *WshServer) EventUnsubAllCommand(ctx context.Context) error {
rpcSource := wshutil.GetRpcSourceFromContext(ctx)
if rpcSource == "" {
return fmt.Errorf("no rpc source set")
}
wps.Broker.UnsubscribeAll(rpcSource)
return nil
}
func (ws *WshServer) EventReadHistoryCommand(ctx context.Context, data wshrpc.CommandEventReadHistoryData) ([]*wps.WaveEvent, error) {
events := wps.Broker.ReadEventHistory(data.Event, data.Scope, data.MaxItems)
return events, nil
}
func (ws *WshServer) SetConfigCommand(ctx context.Context, data wshrpc.MetaSettingsType) error {
return wconfig.SetBaseConfigValue(data.MetaMapType)
}
func (ws *WshServer) SetConnectionsConfigCommand(ctx context.Context, data wshrpc.ConnConfigRequest) error {
return wconfig.SetConnectionsConfigValue(data.Host, data.MetaMapType)
}
func (ws *WshServer) GetFullConfigCommand(ctx context.Context) (wconfig.FullConfigType, error) {
watcher := wconfig.GetWatcher()
return watcher.GetFullConfig(), nil
}
func (ws *WshServer) GetWaveAIModeConfigCommand(ctx context.Context) (wconfig.AIModeConfigUpdate, error) {
fullConfig := wconfig.GetWatcher().GetFullConfig()
resolvedConfigs := aiusechat.ComputeResolvedAIModeConfigs(fullConfig)
return wconfig.AIModeConfigUpdate{Configs: resolvedConfigs}, nil
}
func (ws *WshServer) ConnStatusCommand(ctx context.Context) ([]wshrpc.ConnStatus, error) {
rtn := conncontroller.GetAllConnStatus()
return rtn, nil
}
func (ws *WshServer) WslStatusCommand(ctx context.Context) ([]wshrpc.ConnStatus, error) {
rtn := wslconn.GetAllConnStatus()
return rtn, nil
}
func termCtxWithLogBlockId(ctx context.Context, logBlockId string) context.Context {
if logBlockId == "" {
return ctx
}
block, err := wstore.DBMustGet[*waveobj.Block](ctx, logBlockId)
if err != nil {
return ctx
}
connDebug := block.Meta.GetString(waveobj.MetaKey_TermConnDebug, "")
if connDebug == "" {
return ctx
}
return blocklogger.ContextWithLogBlockId(ctx, logBlockId, connDebug == "debug")
}
func (ws *WshServer) ConnEnsureCommand(ctx context.Context, data wshrpc.ConnExtData) error {
ctx = genconn.ContextWithConnData(ctx, data.LogBlockId)
ctx = termCtxWithLogBlockId(ctx, data.LogBlockId)
if strings.HasPrefix(data.ConnName, "wsl://") {
distroName := strings.TrimPrefix(data.ConnName, "wsl://")
return wslconn.EnsureConnection(ctx, distroName)
}
return conncontroller.EnsureConnection(ctx, data.ConnName)
}
func (ws *WshServer) ConnDisconnectCommand(ctx context.Context, connName string) error {
if conncontroller.IsLocalConnName(connName) {
return nil
}
if strings.HasPrefix(connName, "wsl://") {
distroName := strings.TrimPrefix(connName, "wsl://")
conn := wslconn.GetWslConn(distroName)
if conn == nil {
return fmt.Errorf("distro not found: %s", connName)
}
return conn.Close()
}
connOpts, err := remote.ParseOpts(connName)
if err != nil {
return fmt.Errorf("error parsing connection name: %w", err)
}
conn := conncontroller.MaybeGetConn(connOpts)
if conn == nil {
return fmt.Errorf("connection not found: %s", connName)
}
return conn.Close()
}
func (ws *WshServer) ConnConnectCommand(ctx context.Context, connRequest wshrpc.ConnRequest) error {
if conncontroller.IsLocalConnName(connRequest.Host) {
return nil
}
ctx = genconn.ContextWithConnData(ctx, connRequest.LogBlockId)
ctx = termCtxWithLogBlockId(ctx, connRequest.LogBlockId)
connName := connRequest.Host
if strings.HasPrefix(connName, "wsl://") {
distroName := strings.TrimPrefix(connName, "wsl://")
conn := wslconn.GetWslConn(distroName)
if conn == nil {
return fmt.Errorf("connection not found: %s", connName)
}
return conn.Connect(ctx)
}
connOpts, err := remote.ParseOpts(connName)
if err != nil {
return fmt.Errorf("error parsing connection name: %w", err)
}
conn := conncontroller.GetConn(connOpts)
if conn == nil {
return fmt.Errorf("connection not found: %s", connName)
}
return conn.Connect(ctx, &connRequest.Keywords)
}
func (ws *WshServer) ConnReinstallWshCommand(ctx context.Context, data wshrpc.ConnExtData) error {
if conncontroller.IsLocalConnName(data.ConnName) {
return nil
}
ctx = genconn.ContextWithConnData(ctx, data.LogBlockId)
ctx = termCtxWithLogBlockId(ctx, data.LogBlockId)
connName := data.ConnName
if strings.HasPrefix(connName, "wsl://") {
distroName := strings.TrimPrefix(connName, "wsl://")
conn := wslconn.GetWslConn(distroName)
if conn == nil {
return fmt.Errorf("connection not found: %s", connName)
}
return conn.InstallWsh(ctx, "")
}
connOpts, err := remote.ParseOpts(connName)
if err != nil {
return fmt.Errorf("error parsing connection name: %w", err)
}
conn := conncontroller.GetConn(connOpts)
if conn == nil {
return fmt.Errorf("connection not found: %s", connName)
}
return conn.InstallWsh(ctx, "")
}
func (ws *WshServer) ConnUpdateWshCommand(ctx context.Context, remoteInfo wshrpc.RemoteInfo) (bool, error) {
handler := wshutil.GetRpcResponseHandlerFromContext(ctx)
if handler == nil {
return false, fmt.Errorf("could not determine handler from context")
}
connName := handler.GetRpcContext().Conn
if connName == "" {
return false, fmt.Errorf("invalid remote info: missing connection name")
}
log.Printf("checking wsh version for connection %s (current: %s)", connName, remoteInfo.ClientVersion)
upToDate, _, _, err := conncontroller.IsWshVersionUpToDate(ctx, remoteInfo.ClientVersion)
if err != nil {
return false, fmt.Errorf("unable to compare wsh version: %w", err)
}
if upToDate {
// no need to update
log.Printf("wsh is already up to date for connection %s", connName)
return false, nil
}
// todo: need to add user input code here for validation
if strings.HasPrefix(connName, "wsl://") {
return false, fmt.Errorf("connupdatewshcommand is not supported for wsl connections")
}
connOpts, err := remote.ParseOpts(connName)
if err != nil {
return false, fmt.Errorf("error parsing connection name: %w", err)
}
conn := conncontroller.GetConn(connOpts)
if conn == nil {
return false, fmt.Errorf("connection not found: %s", connName)
}
err = conn.UpdateWsh(ctx, connName, &remoteInfo)
if err != nil {
return false, fmt.Errorf("wsh update failed for connection %s: %w", connName, err)
}
// todo: need to add code for modifying configs?
return true, nil
}
func (ws *WshServer) ConnListCommand(ctx context.Context) ([]string, error) {
return conncontroller.GetConnectionsList()
}
func (ws *WshServer) WslListCommand(ctx context.Context) ([]string, error) {
distros, err := wsl.RegisteredDistros(ctx)
if err != nil {
return nil, err
}
var distroNames []string
for _, distro := range distros {
distroName := distro.Name()
if utilfn.ContainsStr(InvalidWslDistroNames, distroName) {
continue
}
distroNames = append(distroNames, distroName)
}
return distroNames, nil
}
func (ws *WshServer) WslDefaultDistroCommand(ctx context.Context) (string, error) {
distro, ok, err := wsl.DefaultDistro(ctx)
if err != nil {
return "", fmt.Errorf("unable to determine default distro: %w", err)
}
if !ok {
return "", fmt.Errorf("unable to determine default distro")
}
return distro.Name(), nil
}
/**
* Dismisses the WshFail Command in runtime memory on the backend
*/
func (ws *WshServer) DismissWshFailCommand(ctx context.Context, connName string) error {
if strings.HasPrefix(connName, "wsl://") {
distroName := strings.TrimPrefix(connName, "wsl://")
conn := wslconn.GetWslConn(distroName)
if conn == nil {
return fmt.Errorf("connection not found: %s", connName)
}
conn.ClearWshError()
conn.FireConnChangeEvent()
return nil
}
opts, err := remote.ParseOpts(connName)
if err != nil {
return err
}
conn := conncontroller.GetConn(opts)
if conn == nil {
return fmt.Errorf("connection %s not found", connName)
}
conn.ClearWshError()
conn.FireConnChangeEvent()
return nil
}
func (ws *WshServer) NotifySystemResumeCommand(ctx context.Context) error {
log.Printf("NotifySystemResumeCommand called\n")
return nil
}
func (ws *WshServer) FindGitBashCommand(ctx context.Context, rescan bool) (string, error) {
fullConfig := wconfig.GetWatcher().GetFullConfig()
return shellutil.FindGitBash(&fullConfig, rescan), nil
}
func waveFileToWaveFileInfo(wf *filestore.WaveFile) *wshrpc.WaveFileInfo {
return &wshrpc.WaveFileInfo{
ZoneId: wf.ZoneId,
Name: wf.Name,
Opts: wf.Opts,
CreatedTs: wf.CreatedTs,
Size: wf.Size,
ModTs: wf.ModTs,
Meta: wf.Meta,
}
}
func (ws *WshServer) BlockInfoCommand(ctx context.Context, blockId string) (*wshrpc.BlockInfoData, error) {
blockData, err := wstore.DBMustGet[*waveobj.Block](ctx, blockId)
if err != nil {
return nil, fmt.Errorf("error getting block: %w", err)
}
tabId, err := wstore.DBFindTabForBlockId(ctx, blockId)
if err != nil {
return nil, fmt.Errorf("error finding tab for block: %w", err)
}
workspaceId, err := wstore.DBFindWorkspaceForTabId(ctx, tabId)
if err != nil {
return nil, fmt.Errorf("error finding window for tab: %w", err)
}
fileList, err := filestore.WFS.ListFiles(ctx, blockId)
if err != nil {
return nil, fmt.Errorf("error listing blockfiles: %w", err)
}
var fileInfoList []*wshrpc.WaveFileInfo
for _, wf := range fileList {
fileInfoList = append(fileInfoList, waveFileToWaveFileInfo(wf))
}
return &wshrpc.BlockInfoData{
BlockId: blockId,
TabId: tabId,
WorkspaceId: workspaceId,
Block: blockData,
Files: fileInfoList,
}, nil
}
func (ws *WshServer) DebugTermCommand(ctx context.Context, data wshrpc.CommandDebugTermData) (*wshrpc.CommandDebugTermRtnData, error) {
if data.BlockId == "" {
return nil, fmt.Errorf("blockid is required")
}
if data.Size <= 0 {
return nil, fmt.Errorf("size must be greater than 0")
}
waveFile, err := filestore.WFS.Stat(ctx, data.BlockId, wavebase.BlockFile_Term)
if err == fs.ErrNotExist {
return &wshrpc.CommandDebugTermRtnData{}, nil
}
if err != nil {
return nil, fmt.Errorf("error statting term file: %w", err)
}
readSize := data.Size
dataLength := waveFile.DataLength()
if readSize > dataLength {
readSize = dataLength
}
readOffset := waveFile.Size - readSize
readOffset, readData, err := filestore.WFS.ReadAt(ctx, data.BlockId, wavebase.BlockFile_Term, readOffset, readSize)
if err != nil {
return nil, fmt.Errorf("error reading term file: %w", err)
}
return &wshrpc.CommandDebugTermRtnData{
Offset: readOffset,
Data64: base64.StdEncoding.EncodeToString(readData),
}, nil
}
func (ws *WshServer) WaveInfoCommand(ctx context.Context) (*wshrpc.WaveInfoData, error) {
return &wshrpc.WaveInfoData{
Version: wavebase.WaveVersion,
ClientId: wstore.GetClientId(),
BuildTime: wavebase.BuildTime,
ConfigDir: wavebase.GetWaveConfigDir(),
DataDir: wavebase.GetWaveDataDir(),
}, nil
}
func (ws *WshServer) MacOSVersionCommand(ctx context.Context) (string, error) {
return wavebase.ClientMacOSVersion(), nil
}
// BlocksListCommand returns every block visible in the requested
// scope (current workspace by default).
func (ws *WshServer) BlocksListCommand(
ctx context.Context,
req wshrpc.BlocksListRequest) ([]wshrpc.BlocksListEntry, error) {
var results []wshrpc.BlocksListEntry
// Resolve the set of workspaces to inspect
var workspaceIDs []string
if req.WorkspaceId != "" {
workspaceIDs = []string{req.WorkspaceId}
} else if req.WindowId != "" {
win, err := wcore.GetWindow(ctx, req.WindowId)
if err != nil {
return nil, err
}
workspaceIDs = []string{win.WorkspaceId}
} else {
// "current" == first workspace in client focus list
client, err := wstore.DBGetSingleton[*waveobj.Client](ctx)
if err != nil {
return nil, err
}
if len(client.WindowIds) == 0 {
return nil, fmt.Errorf("no active window")
}
win, err := wcore.GetWindow(ctx, client.WindowIds[0])
if err != nil {
return nil, err
}
workspaceIDs = []string{win.WorkspaceId}
}
for _, wsID := range workspaceIDs {
wsData, err := wcore.GetWorkspace(ctx, wsID)
if err != nil {
return nil, err
}
windowId, err := wstore.DBFindWindowForWorkspaceId(ctx, wsID)
if err != nil {
log.Printf("error finding window for workspace %s: %v", wsID, err)
}
for _, tabID := range wsData.TabIds {
tab, err := wstore.DBMustGet[*waveobj.Tab](ctx, tabID)
if err != nil {
return nil, err
}
for _, blkID := range tab.BlockIds {
blk, err := wstore.DBMustGet[*waveobj.Block](ctx, blkID)
if err != nil {
return nil, err
}
results = append(results, wshrpc.BlocksListEntry{
WindowId: windowId,
WorkspaceId: wsID,
TabId: tabID,
BlockId: blkID,
Meta: blk.Meta,
})
}
}
}
return results, nil
}
func (ws *WshServer) WorkspaceListCommand(ctx context.Context) ([]wshrpc.WorkspaceInfoData, error) {
workspaceList, err := wcore.ListWorkspaces(ctx)
if err != nil {
return nil, fmt.Errorf("error listing workspaces: %w", err)
}
var rtn []wshrpc.WorkspaceInfoData
for _, workspaceEntry := range workspaceList {
workspaceData, err := wcore.GetWorkspace(ctx, workspaceEntry.WorkspaceId)
if err != nil {
return nil, fmt.Errorf("error getting workspace: %w", err)
}
rtn = append(rtn, wshrpc.WorkspaceInfoData{
WindowId: workspaceEntry.WindowId,
WorkspaceData: workspaceData,
})
}
return rtn, nil
}
func (ws *WshServer) ListAllAppsCommand(ctx context.Context) ([]wshrpc.AppInfo, error) {
return waveappstore.ListAllApps()
}
func (ws *WshServer) ListAllEditableAppsCommand(ctx context.Context) ([]wshrpc.AppInfo, error) {
return waveappstore.ListAllEditableApps()
}
func (ws *WshServer) ListAllAppFilesCommand(ctx context.Context, data wshrpc.CommandListAllAppFilesData) (*wshrpc.CommandListAllAppFilesRtnData, error) {
if data.AppId == "" {
return nil, fmt.Errorf("must provide an appId to ListAllAppFilesCommand")
}
result, err := waveappstore.ListAllAppFiles(data.AppId)
if err != nil {
return nil, err
}
entries := make([]wshrpc.DirEntryOut, len(result.Entries))
for i, entry := range result.Entries {
entries[i] = wshrpc.DirEntryOut{
Name: entry.Name,
Dir: entry.Dir,
Symlink: entry.Symlink,
Size: entry.Size,
Mode: entry.Mode,
Modified: entry.Modified,
ModifiedTime: entry.ModifiedTime,
}
}
return &wshrpc.CommandListAllAppFilesRtnData{
Path: result.Path,