-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathpr117_diff.txt
More file actions
3148 lines (3031 loc) · 119 KB
/
pr117_diff.txt
File metadata and controls
3148 lines (3031 loc) · 119 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
From c263c5ce18a349379be9aa21c6bdd7de46ad087d Mon Sep 17 00:00:00 2001
From: sytone <github@sytone.com>
Date: Sat, 28 Mar 2026 15:41:57 -0700
Subject: [PATCH 1/3] feat: add SSH tunnel configuration and management to
settings
---
src/OpenClaw.Shared/SettingsData.cs | 5 +
src/OpenClaw.Tray.WinUI/App.xaml.cs | 62 ++++++-
.../Services/SettingsManager.cs | 25 +++
.../Services/SshTunnelService.cs | 165 ++++++++++++++++++
.../Windows/SettingsWindow.xaml | 29 +++
.../Windows/SettingsWindow.xaml.cs | 150 +++++++++++++++-
.../SettingsRoundTripTests.cs | 20 +++
7 files changed, 446 insertions(+), 10 deletions(-)
create mode 100644 src/OpenClaw.Tray.WinUI/Services/SshTunnelService.cs
diff --git a/src/OpenClaw.Shared/SettingsData.cs b/src/OpenClaw.Shared/SettingsData.cs
index 4c7b075..7a2d4b5 100644
--- a/src/OpenClaw.Shared/SettingsData.cs
+++ b/src/OpenClaw.Shared/SettingsData.cs
@@ -9,6 +9,11 @@ public class SettingsData
{
public string? GatewayUrl { get; set; }
public string? Token { get; set; }
+ public bool UseSshTunnel { get; set; } = false;
+ public string? SshTunnelUser { get; set; }
+ public string? SshTunnelHost { get; set; }
+ public int SshTunnelRemotePort { get; set; } = 18789;
+ public int SshTunnelLocalPort { get; set; } = 18789;
public bool AutoStart { get; set; }
public bool GlobalHotkeyEnabled { get; set; } = true;
public bool ShowNotifications { get; set; } = true;
diff --git a/src/OpenClaw.Tray.WinUI/App.xaml.cs b/src/OpenClaw.Tray.WinUI/App.xaml.cs
index de0780f..caff372 100644
--- a/src/OpenClaw.Tray.WinUI/App.xaml.cs
+++ b/src/OpenClaw.Tray.WinUI/App.xaml.cs
@@ -34,6 +34,7 @@ public partial class App : Application
private TrayIcon? _trayIcon;
private OpenClawGatewayClient? _gatewayClient;
private SettingsManager? _settings;
+ private SshTunnelService? _sshTunnelService;
private GlobalHotkeyService? _globalHotkey;
private System.Timers.Timer? _healthCheckTimer;
private System.Timers.Timer? _sessionPollTimer;
@@ -250,6 +251,7 @@ protected override async void OnLaunched(LaunchActivatedEventArgs args)
// Initialize settings
_settings = new SettingsManager();
+ _sshTunnelService = new SshTunnelService(new AppLogger());
// First-run check
if (string.IsNullOrWhiteSpace(_settings.Token))
@@ -1080,11 +1082,12 @@ private void BuildTrayMenu(MenuFlyout flyout)
private void InitializeGatewayClient()
{
if (_settings == null) return;
+ if (!EnsureSshTunnelConfigured()) return;
// Unsubscribe from old client if exists
UnsubscribeGatewayEvents();
- _gatewayClient = new OpenClawGatewayClient(_settings.GatewayUrl, _settings.Token, new AppLogger());
+ _gatewayClient = new OpenClawGatewayClient(_settings.GetEffectiveGatewayUrl(), _settings.Token, new AppLogger());
_gatewayClient.StatusChanged += OnConnectionStatusChanged;
_gatewayClient.ActivityChanged += OnActivityChanged;
_gatewayClient.NotificationReceived += OnNotificationReceived;
@@ -1121,6 +1124,7 @@ private void InitializeNodeService()
{
if (_settings == null || !_settings.EnableNodeMode) return;
if (_dispatcherQueue == null) return;
+ if (!EnsureSshTunnelConfigured()) return;
try
{
@@ -1132,7 +1136,7 @@ private void InitializeNodeService()
_nodeService.PairingStatusChanged += OnPairingStatusChanged;
// Connect to gateway as a node (separate connection from operator)
- _ = _nodeService.ConnectAsync(_settings.GatewayUrl, _settings.Token);
+ _ = _nodeService.ConnectAsync(_settings.GetEffectiveGatewayUrl(), _settings.Token);
}
catch (Exception ex)
{
@@ -1609,6 +1613,10 @@ private void OnSettingsSaved(object? sender, EventArgs e)
var oldNodeService = _nodeService;
_nodeService = null;
try { oldNodeService?.Dispose(); } catch (Exception ex) { Logger.Warn($"Node dispose error: {ex.Message}"); }
+ if (_settings?.UseSshTunnel != true)
+ {
+ _sshTunnelService?.Stop();
+ }
if (_settings?.EnableNodeMode == true)
{
@@ -1638,9 +1646,12 @@ private void OnSettingsSaved(object? sender, EventArgs e)
private void ShowWebChat()
{
+ if (_settings == null) return;
+ if (!EnsureSshTunnelConfigured()) return;
+
if (_webChatWindow == null || _webChatWindow.IsClosed)
{
- _webChatWindow = new WebChatWindow(_settings!.GatewayUrl, _settings.Token);
+ _webChatWindow = new WebChatWindow(_settings.GetEffectiveGatewayUrl(), _settings.Token);
_webChatWindow.Closed += (s, e) => _webChatWindow = null;
}
_webChatWindow.Activate();
@@ -1770,8 +1781,9 @@ private void ShowSurfaceImprovementsTipIfNeeded()
private void OpenDashboard(string? path = null)
{
if (_settings == null) return;
+ if (!EnsureSshTunnelConfigured()) return;
- var baseUrl = _settings.GatewayUrl
+ var baseUrl = _settings.GetEffectiveGatewayUrl()
.Replace("ws://", "http://")
.Replace("wss://", "https://")
.TrimEnd('/');
@@ -2063,6 +2075,7 @@ private void ExitApplication()
// Unsubscribe and dispose gateway client
UnsubscribeGatewayEvents();
_gatewayClient?.Dispose();
+ _sshTunnelService?.Dispose();
// Dispose tray and mutex
_trayIcon?.Dispose();
@@ -2074,6 +2087,47 @@ private void ExitApplication()
Exit();
}
+ private bool EnsureSshTunnelConfigured()
+ {
+ if (_settings == null)
+ {
+ return false;
+ }
+
+ if (_settings.UseSshTunnel)
+ {
+ if (string.IsNullOrWhiteSpace(_settings.SshTunnelUser) ||
+ string.IsNullOrWhiteSpace(_settings.SshTunnelHost) ||
+ _settings.SshTunnelRemotePort is < 1 or > 65535 ||
+ _settings.SshTunnelLocalPort is < 1 or > 65535)
+ {
+ Logger.Warn("SSH tunnel is enabled but settings are incomplete");
+ _currentStatus = ConnectionStatus.Error;
+ UpdateTrayIcon();
+ return false;
+ }
+
+ try
+ {
+ _sshTunnelService ??= new SshTunnelService(new AppLogger());
+ _sshTunnelService.EnsureStarted(_settings);
+ }
+ catch (Exception ex)
+ {
+ Logger.Error($"Failed to start SSH tunnel: {ex.Message}");
+ _currentStatus = ConnectionStatus.Error;
+ UpdateTrayIcon();
+ return false;
+ }
+ }
+ else
+ {
+ _sshTunnelService?.Stop();
+ }
+
+ return true;
+ }
+
#endregion
private Microsoft.UI.Dispatching.DispatcherQueue? AppDispatcherQueue =>
diff --git a/src/OpenClaw.Tray.WinUI/Services/SettingsManager.cs b/src/OpenClaw.Tray.WinUI/Services/SettingsManager.cs
index 0c343f1..5347a6b 100644
--- a/src/OpenClaw.Tray.WinUI/Services/SettingsManager.cs
+++ b/src/OpenClaw.Tray.WinUI/Services/SettingsManager.cs
@@ -19,6 +19,11 @@ public class SettingsManager
// Connection
public string GatewayUrl { get; set; } = "ws://localhost:18789";
public string Token { get; set; } = "";
+ public bool UseSshTunnel { get; set; } = false;
+ public string SshTunnelUser { get; set; } = "";
+ public string SshTunnelHost { get; set; } = "";
+ public int SshTunnelRemotePort { get; set; } = 18789;
+ public int SshTunnelLocalPort { get; set; } = 18789;
// Startup
public bool AutoStart { get; set; } = false;
@@ -64,6 +69,11 @@ public void Load()
{
GatewayUrl = loaded.GatewayUrl ?? GatewayUrl;
Token = loaded.Token ?? Token;
+ UseSshTunnel = loaded.UseSshTunnel;
+ SshTunnelUser = loaded.SshTunnelUser ?? SshTunnelUser;
+ SshTunnelHost = loaded.SshTunnelHost ?? SshTunnelHost;
+ SshTunnelRemotePort = loaded.SshTunnelRemotePort <= 0 ? SshTunnelRemotePort : loaded.SshTunnelRemotePort;
+ SshTunnelLocalPort = loaded.SshTunnelLocalPort <= 0 ? SshTunnelLocalPort : loaded.SshTunnelLocalPort;
AutoStart = loaded.AutoStart;
GlobalHotkeyEnabled = loaded.GlobalHotkeyEnabled;
ShowNotifications = loaded.ShowNotifications;
@@ -101,6 +111,11 @@ public void Save()
{
GatewayUrl = GatewayUrl,
Token = Token,
+ UseSshTunnel = UseSshTunnel,
+ SshTunnelUser = SshTunnelUser,
+ SshTunnelHost = SshTunnelHost,
+ SshTunnelRemotePort = SshTunnelRemotePort,
+ SshTunnelLocalPort = SshTunnelLocalPort,
AutoStart = AutoStart,
GlobalHotkeyEnabled = GlobalHotkeyEnabled,
ShowNotifications = ShowNotifications,
@@ -130,4 +145,14 @@ public void Save()
Logger.Error($"Failed to save settings: {ex.Message}");
}
}
+
+ public string GetEffectiveGatewayUrl()
+ {
+ if (!UseSshTunnel)
+ {
+ return GatewayUrl;
+ }
+
+ return $"ws://127.0.0.1:{SshTunnelLocalPort}";
+ }
}
diff --git a/src/OpenClaw.Tray.WinUI/Services/SshTunnelService.cs b/src/OpenClaw.Tray.WinUI/Services/SshTunnelService.cs
new file mode 100644
index 0000000..18b7764
--- /dev/null
+++ b/src/OpenClaw.Tray.WinUI/Services/SshTunnelService.cs
@@ -0,0 +1,165 @@
+using OpenClaw.Shared;
+using System;
+using System.Diagnostics;
+using System.Text;
+
+namespace OpenClawTray.Services;
+
+/// <summary>
+/// Manages an SSH local port-forward process for gateway access.
+/// </summary>
+public sealed class SshTunnelService : IDisposable
+{
+ private readonly IOpenClawLogger _logger;
+ private Process? _process;
+ private string? _lastSpec;
+
+ public SshTunnelService(IOpenClawLogger logger)
+ {
+ _logger = logger;
+ }
+
+ public bool IsRunning => _process is { HasExited: false };
+
+ public void EnsureStarted(SettingsManager settings)
+ {
+ if (!settings.UseSshTunnel)
+ {
+ Stop();
+ return;
+ }
+
+ EnsureStarted(
+ settings.SshTunnelUser,
+ settings.SshTunnelHost,
+ settings.SshTunnelRemotePort,
+ settings.SshTunnelLocalPort);
+ }
+
+ public void EnsureStarted(string user, string host, int remotePort, int localPort)
+ {
+ user = user.Trim();
+ host = host.Trim();
+
+ var spec = BuildSpec(user, host, remotePort, localPort);
+
+ if (IsRunning && string.Equals(_lastSpec, spec, StringComparison.Ordinal))
+ {
+ return;
+ }
+
+ Stop();
+ StartProcess(user, host, remotePort, localPort);
+ _lastSpec = spec;
+ }
+
+ public void Stop()
+ {
+ if (_process == null)
+ {
+ return;
+ }
+
+ try
+ {
+ if (!_process.HasExited)
+ {
+ _process.Kill(entireProcessTree: true);
+ _process.WaitForExit(3000);
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.Warn($"SSH tunnel stop failed: {ex.Message}");
+ }
+ finally
+ {
+ try { _process.Dispose(); } catch { }
+ _process = null;
+ _lastSpec = null;
+ }
+ }
+
+ private void StartProcess(string user, string host, int remotePort, int localPort)
+ {
+ var psi = new ProcessStartInfo
+ {
+ FileName = "ssh",
+ Arguments = BuildArguments(user, host, remotePort, localPort),
+ UseShellExecute = false,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ CreateNoWindow = true,
+ };
+
+ var process = new Process
+ {
+ StartInfo = psi,
+ EnableRaisingEvents = true,
+ };
+
+ process.OutputDataReceived += (_, e) =>
+ {
+ if (!string.IsNullOrWhiteSpace(e.Data))
+ {
+ _logger.Info($"[SSH] {e.Data}");
+ }
+ };
+
+ process.ErrorDataReceived += (_, e) =>
+ {
+ if (!string.IsNullOrWhiteSpace(e.Data))
+ {
+ _logger.Warn($"[SSH] {e.Data}");
+ }
+ };
+
+ process.Exited += (_, _) =>
+ {
+ var exitCode = process.ExitCode;
+ _logger.Warn($"SSH tunnel exited (code {exitCode})");
+ };
+
+ try
+ {
+ if (!process.Start())
+ {
+ throw new InvalidOperationException("Failed to start ssh process");
+ }
+ }
+ catch (Exception ex)
+ {
+ process.Dispose();
+ throw new InvalidOperationException("Unable to start SSH tunnel process. Ensure OpenSSH client is installed and available in PATH.", ex);
+ }
+
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
+ _process = process;
+
+ _logger.Info($"SSH tunnel started: 127.0.0.1:{localPort} -> 127.0.0.1:{remotePort} via {user}@{host}");
+ }
+
+ private static string BuildSpec(string user, string host, int remotePort, int localPort)
+ => $"{user}@{host}:{localPort}:{remotePort}";
+
+ private static string BuildArguments(string user, string host, int remotePort, int localPort)
+ {
+ var sb = new StringBuilder();
+ sb.Append("-N ");
+ sb.Append("-L ");
+ sb.Append(localPort);
+ sb.Append(":127.0.0.1:");
+ sb.Append(remotePort);
+ sb.Append(' ');
+ sb.Append(user);
+ sb.Append('@');
+ sb.Append(host);
+ return sb.ToString();
+ }
+
+ public void Dispose()
+ {
+ Stop();
+ }
+}
diff --git a/src/OpenClaw.Tray.WinUI/Windows/SettingsWindow.xaml b/src/OpenClaw.Tray.WinUI/Windows/SettingsWindow.xaml
index f8631f5..e0f15ac 100644
--- a/src/OpenClaw.Tray.WinUI/Windows/SettingsWindow.xaml
+++ b/src/OpenClaw.Tray.WinUI/Windows/SettingsWindow.xaml
@@ -25,6 +25,35 @@
<StackPanel Spacing="8">
<TextBlock x:Uid="SettingsConnectionHeader" Text="CONNECTION" Style="{StaticResource CaptionTextBlockStyle}"
Foreground="#E74C3C" FontWeight="Bold"/>
+
+ <ToggleSwitch x:Name="UseSshTunnelToggle" Header="Connect through SSH tunnel" Toggled="OnUseSshTunnelToggled"/>
+
+ <StackPanel x:Name="SshTunnelDetailsPanel" Spacing="8" Visibility="Collapsed">
+ <TextBlock Text="When enabled, the app will connect through ws://127.0.0.1:<local-port> and create an SSH forward to the remote gateway host."
+ Style="{StaticResource CaptionTextBlockStyle}"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}"
+ TextWrapping="Wrap"/>
+
+ <Grid ColumnSpacing="8">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*"/>
+ <ColumnDefinition Width="*"/>
+ </Grid.ColumnDefinitions>
+
+ <TextBox x:Name="SshTunnelUserTextBox" Grid.Column="0" Header="SSH User" PlaceholderText="user"/>
+ <TextBox x:Name="SshTunnelHostTextBox" Grid.Column="1" Header="SSH Host" PlaceholderText="machine-name or IP"/>
+ </Grid>
+
+ <Grid ColumnSpacing="8">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*"/>
+ <ColumnDefinition Width="*"/>
+ </Grid.ColumnDefinitions>
+
+ <TextBox x:Name="SshTunnelRemotePortTextBox" Grid.Column="0" Header="Remote Gateway Port" PlaceholderText="18789"/>
+ <TextBox x:Name="SshTunnelLocalPortTextBox" Grid.Column="1" Header="Local Forward Port" PlaceholderText="18789" TextChanged="OnSshTunnelLocalPortTextChanged"/>
+ </Grid>
+ </StackPanel>
<TextBox x:Name="GatewayUrlTextBox" x:Uid="SettingsGatewayUrlTextBox" Header="Gateway URL"
PlaceholderText="ws://localhost:18789 or https://host.tailnet.ts.net"/>
diff --git a/src/OpenClaw.Tray.WinUI/Windows/SettingsWindow.xaml.cs b/src/OpenClaw.Tray.WinUI/Windows/SettingsWindow.xaml.cs
index e4224a8..2308c6f 100644
--- a/src/OpenClaw.Tray.WinUI/Windows/SettingsWindow.xaml.cs
+++ b/src/OpenClaw.Tray.WinUI/Windows/SettingsWindow.xaml.cs
@@ -12,6 +12,7 @@ namespace OpenClawTray.Windows;
public sealed partial class SettingsWindow : WindowEx
{
private readonly SettingsManager _settings;
+ private string _manualGatewayUrl = "";
public bool IsClosed { get; private set; }
public event EventHandler? SettingsSaved;
@@ -37,7 +38,14 @@ public SettingsWindow(SettingsManager settings)
private void LoadSettings()
{
+ UseSshTunnelToggle.IsOn = _settings.UseSshTunnel;
+ SshTunnelUserTextBox.Text = _settings.SshTunnelUser;
+ SshTunnelHostTextBox.Text = _settings.SshTunnelHost;
+ SshTunnelRemotePortTextBox.Text = _settings.SshTunnelRemotePort.ToString();
+ SshTunnelLocalPortTextBox.Text = _settings.SshTunnelLocalPort.ToString();
+ _manualGatewayUrl = _settings.GatewayUrl;
GatewayUrlTextBox.Text = _settings.GatewayUrl;
+ UpdateSshTunnelUiState();
TokenTextBox.Text = _settings.Token;
AutoStartToggle.IsOn = _settings.AutoStart;
GlobalHotkeyToggle.IsOn = _settings.GlobalHotkeyEnabled;
@@ -72,7 +80,16 @@ private void LoadSettings()
private void SaveSettings()
{
- _settings.GatewayUrl = GatewayUrlTextBox.Text.Trim();
+ _settings.UseSshTunnel = UseSshTunnelToggle.IsOn;
+ _settings.SshTunnelUser = SshTunnelUserTextBox.Text.Trim();
+ _settings.SshTunnelHost = SshTunnelHostTextBox.Text.Trim();
+ _settings.SshTunnelRemotePort = ParsePortOrDefault(SshTunnelRemotePortTextBox.Text, _settings.SshTunnelRemotePort);
+ _settings.SshTunnelLocalPort = ParsePortOrDefault(SshTunnelLocalPortTextBox.Text, _settings.SshTunnelLocalPort);
+ if (!_settings.UseSshTunnel)
+ {
+ _settings.GatewayUrl = GatewayUrlTextBox.Text.Trim();
+ _manualGatewayUrl = _settings.GatewayUrl;
+ }
_settings.Token = TokenTextBox.Text.Trim();
_settings.AutoStart = AutoStartToggle.IsOn;
_settings.GlobalHotkeyEnabled = GlobalHotkeyToggle.IsOn;
@@ -101,13 +118,26 @@ private void SaveSettings()
private async void OnTestConnection(object sender, RoutedEventArgs e)
{
+ var useSshTunnel = UseSshTunnelToggle.IsOn;
+ var sshUser = "";
+ var sshHost = "";
+ var remotePort = 0;
+ var localPort = 0;
+ SshTunnelService? testTunnel = null;
+
var gatewayUrl = GatewayUrlTextBox.Text.Trim();
- if (!GatewayUrlHelper.IsValidGatewayUrl(gatewayUrl))
+ if (!useSshTunnel && !GatewayUrlHelper.IsValidGatewayUrl(gatewayUrl))
{
StatusLabel.Text = $"❌ {GatewayUrlHelper.ValidationMessage}";
return;
}
+ if (useSshTunnel && !TryReadTunnelSettings(out sshUser, out sshHost, out remotePort, out localPort, out var tunnelError))
+ {
+ StatusLabel.Text = $"❌ {tunnelError}";
+ return;
+ }
+
Logger.Info("[Settings] Test connection initiated");
StatusLabel.Text = LocalizationHelper.GetString("Status_Testing");
TestConnectionButton.IsEnabled = false;
@@ -115,8 +145,15 @@ private async void OnTestConnection(object sender, RoutedEventArgs e)
try
{
var testLogger = new TestLogger();
+ if (useSshTunnel)
+ {
+ testTunnel = new SshTunnelService(testLogger);
+ Logger.Info($"[Settings] Starting temporary SSH tunnel for test: {sshUser}@{sshHost} local:{localPort} remote:{remotePort}");
+ testTunnel.EnsureStarted(sshUser, sshHost, remotePort, localPort);
+ }
+
var client = new OpenClawGatewayClient(
- gatewayUrl,
+ useSshTunnel ? $"ws://127.0.0.1:{localPort}" : gatewayUrl,
TokenTextBox.Text.Trim(),
testLogger);
@@ -167,6 +204,7 @@ private async void OnTestConnection(object sender, RoutedEventArgs e)
}
finally
{
+ testTunnel?.Dispose();
TestConnectionButton.IsEnabled = true;
}
}
@@ -188,14 +226,22 @@ private void OnTestNotification(object sender, RoutedEventArgs e)
private void OnSave(object sender, RoutedEventArgs e)
{
+ var useSshTunnel = UseSshTunnelToggle.IsOn;
var gatewayUrl = GatewayUrlTextBox.Text.Trim();
- if (!GatewayUrlHelper.IsValidGatewayUrl(gatewayUrl))
+ if (!useSshTunnel && !GatewayUrlHelper.IsValidGatewayUrl(gatewayUrl))
{
Logger.Warn($"[Settings] Save blocked ΓÇö invalid gateway URL");
StatusLabel.Text = $"❌ {GatewayUrlHelper.ValidationMessage}";
return;
}
+ if (useSshTunnel && !TryReadTunnelSettings(out _, out _, out _, out _, out var tunnelError))
+ {
+ Logger.Warn("[Settings] Save blocked ΓÇö invalid SSH tunnel settings");
+ StatusLabel.Text = $"❌ {tunnelError}";
+ return;
+ }
+
// Log key setting changes before saving
var oldGateway = _settings.GatewayUrl;
var oldAutoStart = _settings.AutoStart;
@@ -220,6 +266,96 @@ private void OnCancel(object sender, RoutedEventArgs e)
Close();
}
+ private static int ParsePortOrDefault(string? value, int fallback)
+ {
+ if (int.TryParse(value?.Trim(), out var parsed) && parsed is >= 1 and <= 65535)
+ {
+ return parsed;
+ }
+
+ return fallback;
+ }
+
+ private bool TryReadTunnelSettings(
+ out string user,
+ out string host,
+ out int remotePort,
+ out int localPort,
+ out string? error)
+ {
+ user = SshTunnelUserTextBox.Text.Trim();
+ host = SshTunnelHostTextBox.Text.Trim();
+ remotePort = 0;
+ localPort = 0;
+ error = null;
+
+ if (string.IsNullOrWhiteSpace(user))
+ {
+ error = "SSH User is required when tunnel mode is enabled.";
+ return false;
+ }
+
+ if (string.IsNullOrWhiteSpace(host))
+ {
+ error = "SSH Host is required when tunnel mode is enabled.";
+ return false;
+ }
+
+ if (!int.TryParse(SshTunnelRemotePortTextBox.Text.Trim(), out remotePort) || remotePort is < 1 or > 65535)
+ {
+ error = "Remote Gateway Port must be a number from 1 to 65535.";
+ return false;
+ }
+
+ if (!int.TryParse(SshTunnelLocalPortTextBox.Text.Trim(), out localPort) || localPort is < 1 or > 65535)
+ {
+ error = "Local Forward Port must be a number from 1 to 65535.";
+ return false;
+ }
+
+ return true;
+ }
+
+ private void OnUseSshTunnelToggled(object sender, RoutedEventArgs e)
+ {
+ UpdateSshTunnelUiState();
+ }
+
+ private void OnSshTunnelLocalPortTextChanged(object sender, Microsoft.UI.Xaml.Controls.TextChangedEventArgs e)
+ {
+ if (UseSshTunnelToggle.IsOn)
+ {
+ UpdateSshTunnelUiState();
+ }
+ }
+
+ private void UpdateSshTunnelUiState()
+ {
+ var useSshTunnel = UseSshTunnelToggle.IsOn;
+ var wasReadOnly = GatewayUrlTextBox.IsReadOnly;
+
+ SshTunnelDetailsPanel.Visibility = useSshTunnel ? Visibility.Visible : Visibility.Collapsed;
+ GatewayUrlTextBox.IsReadOnly = useSshTunnel;
+
+ if (useSshTunnel)
+ {
+ if (!wasReadOnly)
+ {
+ _manualGatewayUrl = GatewayUrlTextBox.Text.Trim();
+ }
+
+ var localPort = ParsePortOrDefault(SshTunnelLocalPortTextBox.Text, 18789);
+ GatewayUrlTextBox.Text = $"ws://127.0.0.1:{localPort}";
+ }
+ else
+ {
+ if (GatewayUrlTextBox.Text.StartsWith("ws://127.0.0.1:", StringComparison.OrdinalIgnoreCase))
+ {
+ GatewayUrlTextBox.Text = _manualGatewayUrl;
+ }
+ }
+ }
+
private class TestLogger : IOpenClawLogger
{
public string? LastError { get; private set; }
@@ -233,8 +369,10 @@ public void Warn(string message)
}
public void Error(string message, Exception? ex = null)
{
- LastError = message;
- Logger.Error($"[Settings:TestClient] {message}");
+ LastError = ex != null
+ ? $"{message}: {ex.Message}"
+ : message;
+ Logger.Error($"[Settings:TestClient] {LastError}");
}
}
}
diff --git a/tests/OpenClaw.Tray.Tests/SettingsRoundTripTests.cs b/tests/OpenClaw.Tray.Tests/SettingsRoundTripTests.cs
index 8b09519..887df5b 100644
--- a/tests/OpenClaw.Tray.Tests/SettingsRoundTripTests.cs
+++ b/tests/OpenClaw.Tray.Tests/SettingsRoundTripTests.cs
@@ -12,6 +12,11 @@ public void RoundTrip_AllFields_Preserved()
{
GatewayUrl = "ws://localhost:18789",
Token = "secret-token",
+ UseSshTunnel = true,
+ SshTunnelUser = "user1",
+ SshTunnelHost = "remote-host",
+ SshTunnelRemotePort = 18789,
+ SshTunnelLocalPort = 28789,
AutoStart = true,
GlobalHotkeyEnabled = false,
ShowNotifications = true,
@@ -40,6 +45,11 @@ public void RoundTrip_AllFields_Preserved()
Assert.NotNull(restored);
Assert.Equal(original.GatewayUrl, restored.GatewayUrl);
Assert.Equal(original.Token, restored.Token);
+ Assert.Equal(original.UseSshTunnel, restored.UseSshTunnel);
+ Assert.Equal(original.SshTunnelUser, restored.SshTunnelUser);
+ Assert.Equal(original.SshTunnelHost, restored.SshTunnelHost);
+ Assert.Equal(original.SshTunnelRemotePort, restored.SshTunnelRemotePort);
+ Assert.Equal(original.SshTunnelLocalPort, restored.SshTunnelLocalPort);
Assert.Equal(original.AutoStart, restored.AutoStart);
Assert.Equal(original.GlobalHotkeyEnabled, restored.GlobalHotkeyEnabled);
Assert.Equal(original.ShowNotifications, restored.ShowNotifications);
@@ -85,6 +95,11 @@ public void MissingFields_UseDefaults()
Assert.NotNull(settings);
Assert.Null(settings.GatewayUrl);
Assert.Null(settings.Token);
+ Assert.False(settings.UseSshTunnel);
+ Assert.Null(settings.SshTunnelUser);
+ Assert.Null(settings.SshTunnelHost);
+ Assert.Equal(18789, settings.SshTunnelRemotePort);
+ Assert.Equal(18789, settings.SshTunnelLocalPort);
Assert.False(settings.AutoStart);
Assert.True(settings.GlobalHotkeyEnabled);
Assert.True(settings.ShowNotifications);
@@ -131,6 +146,11 @@ public void BackwardCompatibility_OldSettingsWithoutNewFields()
Assert.NotNull(settings);
Assert.Equal("ws://localhost:18789", settings.GatewayUrl);
Assert.Equal("abc", settings.Token);
+ Assert.False(settings.UseSshTunnel);
+ Assert.Null(settings.SshTunnelUser);
+ Assert.Null(settings.SshTunnelHost);
+ Assert.Equal(18789, settings.SshTunnelRemotePort);
+ Assert.Equal(18789, settings.SshTunnelLocalPort);
// New fields should have sensible defaults
Assert.True(settings.NotifyChatResponses);
Assert.True(settings.PreferStructuredCategories);
From 98f48c2ef96656ce622f28f92a7eb15e0359f134 Mon Sep 17 00:00:00 2001
From: sytone <github@sytone.com>
Date: Sat, 28 Mar 2026 18:22:15 -0700
Subject: [PATCH 2/3] feat: Add SkippedUpdateTag to settings and enhance update
handling
- Introduced SkippedUpdateTag property in SettingsData and SettingsManager to remember skipped updates.
- Updated App.xaml.cs to initialize settings before update checks and handle skipped updates.
- Enhanced QuickSendDialog to provide detailed error messages and focus handling.
- Improved WebSocketClientBase with better auto-reconnect logic and error handling.
- Added integration tests for DeviceIdentity payload formats and OpenClawGatewayClient response handling.
- Updated SettingsRoundTripTests to validate SkippedUpdateTag persistence.
---
AGENTS.md | 25 +
README.md | 35 +-
build.ps1 | 7 +-
moltbot-windows-hub.slnx | 1 +
src/OpenClaw.Cli/OpenClaw.Cli.csproj | 12 +
src/OpenClaw.Cli/Program.cs | 300 +++++++++++
src/OpenClaw.Shared/DeviceIdentity.cs | 112 +++++
src/OpenClaw.Shared/OpenClawGatewayClient.cs | 465 +++++++++++++++++-
src/OpenClaw.Shared/SettingsData.cs | 1 +
src/OpenClaw.Shared/WebSocketClientBase.cs | 72 ++-
src/OpenClaw.Tray.WinUI/App.xaml.cs | 167 ++++++-
.../Dialogs/QuickSendDialog.cs | 205 +++++++-
.../Services/SettingsManager.cs | 3 +
.../Services/SshTunnelService.cs | 14 +-
.../DeviceIdentityTests.cs | 60 +++
.../OpenClawGatewayClientTests.cs | 141 ++++++
.../WebSocketClientBaseTests.cs | 4 +-
.../SettingsRoundTripTests.cs | 4 +
18 files changed, 1553 insertions(+), 75 deletions(-)
create mode 100644 AGENTS.md
create mode 100644 src/OpenClaw.Cli/OpenClaw.Cli.csproj
create mode 100644 src/OpenClaw.Cli/Program.cs
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..07e3ac6
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,25 @@
+# AGENTS.md
+
+## Required Validation After Every Change
+
+All agents working in this repository must run validation after each code change before marking work complete.
+
+Required steps:
+
+1. Run full repo build:
+ - `./build.ps1`
+2. Run shared tests:
+ - `dotnet test ./tests/OpenClaw.Shared.Tests/OpenClaw.Shared.Tests.csproj --no-restore`
+3. Run tray tests:
+ - `dotnet test ./tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj --no-restore`
+
+If a command fails:
+
+1. Fix the issue.
+2. Re-run the failed command.
+3. Re-run all required validation commands before completion.
+
+Notes:
+
+- If a build/test is blocked by an environmental lock (for example running executable locking output assemblies), stop/close the locking process and rerun.
+- Do not claim completion without reporting validation results.
diff --git a/README.md b/README.md
index b0c3e40..d74620a 100644
--- a/README.md
+++ b/README.md
@@ -10,12 +10,13 @@ A Windows companion suite for [OpenClaw](https://openclaw.ai) - the AI-powered p
## Projects
-This monorepo contains three projects:
+This monorepo contains four projects:
| Project | Description |
|---------|-------------|
| **OpenClaw.Tray.WinUI** | System tray application (WinUI 3) for quick access to OpenClaw |
| **OpenClaw.Shared** | Shared gateway client library |
+| **OpenClaw.Cli** | CLI validator for WebSocket connect/send/probe using tray settings |
| **OpenClaw.CommandPalette** | PowerToys Command Palette extension |
## 🚀 Quick Start
@@ -65,6 +66,24 @@ dotnet build src/OpenClaw.Tray.WinUI -r win-x64 -p:PackageMsix=true # x64 MSI
.\src\OpenClaw.Tray.WinUI\bin\Debug\net10.0-windows10.0.19041.0\win-x64\OpenClaw.Tray.WinUI.exe # x64
```
+### Run CLI WebSocket Validator
+
+Use the CLI to validate gateway connectivity and `chat.send` outside the tray UI.
+
+```powershell
+# Show help
+dotnet run --project src/OpenClaw.Cli -- --help
+
+# Use tray settings from %APPDATA%\OpenClawTray\settings.json and send one message
+dotnet run --project src/OpenClaw.Cli -- --message "quick send validation"
+
+# Loop sends and also probe sessions/usage/nodes APIs
+dotnet run --project src/OpenClaw.Cli -- --repeat 5 --delay-ms 1000 --probe-read --verbose
+
+# Override gateway URL/token for isolated testing
+dotnet run --project src/OpenClaw.Cli -- --url ws://127.0.0.1:18789 --token "<token>" --message "override test"
+```
+
## 📦 OpenClaw.Tray (Molty)
Modern Windows 11-style system tray companion that connects to your local OpenClaw gateway.
@@ -85,6 +104,20 @@ Modern Windows 11-style system tray companion that connects to your local OpenCl
- ⚙️ **Settings** - Full configuration dialog
- 🎯 **First-run experience** - Welcome dialog guides new users
+#### Quick Send scope requirement
+
+Quick Send uses the gateway `chat.send` method and requires the operator device to have `operator.write` scope.
+
+If Quick Send fails with `missing scope: operator.write`, Molty now copies identity + remediation guidance to your clipboard, including:
+
+- operator role and `client.id` used by the tray app
+- gateway-reported operator device id (if provided)
+- currently granted scopes (if provided)
+
+For this specific error (`missing scope: operator.write`), the cause is an **operator token scope issue**. Update the token used by the tray app so it includes `operator.write`, then retry Quick Send.
+
+If Quick Send fails with `pairing required` / `NOT_PAIRED`, that is a **device approval** issue. Approve the tray device in gateway pairing approvals, reconnect, and retry.
+
### Menu Sections
- **Status** - Gateway connection status with click-to-view details
- **Sessions** - Active agent sessions with preview and per-session controls
diff --git a/build.ps1 b/build.ps1
index bd24b54..13cb7e8 100644
--- a/build.ps1
+++ b/build.ps1
@@ -6,7 +6,7 @@
Builds all projects, checks prerequisites, and provides clear guidance.
.PARAMETER Project
- Which project to build: All, Tray, WinUI, Shared, CommandPalette
+ Which project to build: All, Tray, WinUI, Shared, CommandPalette, Cli
Default: All
.PARAMETER Configuration
@@ -23,7 +23,7 @@
#>
param(
- [ValidateSet("All", "Tray", "WinUI", "Shared", "CommandPalette")]
+ [ValidateSet("All", "Tray", "WinUI", "Shared", "CommandPalette", "Cli")]
[string]$Project = "All",
[ValidateSet("Debug", "Release")]
@@ -187,12 +187,13 @@ function Build-Project($name, $path, $useRid = $false) {
$projects = @{
"Shared" = @{ Path = "src/OpenClaw.Shared/OpenClaw.Shared.csproj"; UseRid = $false }
+ "Cli" = @{ Path = "src/OpenClaw.Cli/OpenClaw.Cli.csproj"; UseRid = $false }
"Tray" = @{ Path = "src/OpenClaw.Tray.WinUI/OpenClaw.Tray.WinUI.csproj"; UseRid = $true }
"WinUI" = @{ Path = "src/OpenClaw.Tray.WinUI/OpenClaw.Tray.WinUI.csproj"; UseRid = $true }
"CommandPalette" = @{ Path = "src/OpenClaw.CommandPalette/OpenClaw.CommandPalette.csproj"; UseRid = $false }
}
-$toBuild = if ($Project -eq "All") { @("Shared", "WinUI") } else { @($Project) }
+$toBuild = if ($Project -eq "All") { @("Shared", "Cli", "WinUI") } else { @($Project) }
# Always build Shared first if building other projects
if ($Project -ne "Shared" -and $Project -ne "All" -and $toBuild -notcontains "Shared") {
diff --git a/moltbot-windows-hub.slnx b/moltbot-windows-hub.slnx
index 627f0f5..79eaf12 100644
--- a/moltbot-windows-hub.slnx
+++ b/moltbot-windows-hub.slnx
@@ -1,5 +1,6 @@
<Solution>
<Folder Name="/src/">
+ <Project Path="src/OpenClaw.Cli/OpenClaw.Cli.csproj" />
<Project Path="src/OpenClaw.CommandPalette/OpenClaw.CommandPalette.csproj">
<Platform Project="x64" />
</Project>
diff --git a/src/OpenClaw.Cli/OpenClaw.Cli.csproj b/src/OpenClaw.Cli/OpenClaw.Cli.csproj
new file mode 100644
index 0000000..2eecce4
--- /dev/null
+++ b/src/OpenClaw.Cli/OpenClaw.Cli.csproj
@@ -0,0 +1,12 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\OpenClaw.Shared\OpenClaw.Shared.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/src/OpenClaw.Cli/Program.cs b/src/OpenClaw.Cli/Program.cs
new file mode 100644
index 0000000..7fb544c
--- /dev/null
+++ b/src/OpenClaw.Cli/Program.cs
@@ -0,0 +1,300 @@
+using System.Globalization;
+using System.Text;
+using OpenClaw.Shared;
+
+internal sealed class CliOptions
+{
+ public string SettingsPath { get; set; } = Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
+ "OpenClawTray",
+ "settings.json");
+
+ public string? GatewayUrlOverride { get; set; }
+ public string? TokenOverride { get; set; }
+ public string Message { get; set; } = "openclaw-cli validation ping";
+ public int Repeat { get; set; } = 1;
+ public int DelayMs { get; set; } = 500;
+ public int ConnectTimeoutMs { get; set; } = 10000;
+ public bool ProbeReadApis { get; set; }
+ public bool Verbose { get; set; }
+}
+
+internal static class Program
+{
+ private static async Task<int> Main(string[] args)
+ {
+ if (args.Any(a => a is "--help" or "-h"))
+ {
+ PrintUsage();
+ return 0;
+ }
+
+ CliOptions options;
+ try
+ {
+ options = ParseArgs(args);
+ }
+ catch (Exception ex)
+ {
+ Console.Error.WriteLine($"Argument error: {ex.Message}");
+ PrintUsage();
+ return 2;
+ }
+
+ var (gatewayUrl, token, loaded) = LoadConnectionFromSettings(options);
+ if (string.IsNullOrWhiteSpace(gatewayUrl))
+ {
+ Console.Error.WriteLine("Gateway URL is missing. Set it in tray settings or pass --url.");
+ return 2;
+ }
+
+ if (string.IsNullOrWhiteSpace(token))
+ {
+ Console.Error.WriteLine("Token is missing. Set it in tray settings or pass --token.");
+ return 2;
+ }
+
+ Console.WriteLine($"Settings file: {options.SettingsPath}");
+ Console.WriteLine($"Gateway URL: {GatewayUrlHelper.SanitizeForDisplay(gatewayUrl)}");
+ Console.WriteLine($"Token source: {(options.TokenOverride is null ? "settings" : "--token override")}");
+ if (loaded is not null)
+ {
+ Console.WriteLine($"Node mode in settings: {loaded.EnableNodeMode}");
+ Console.WriteLine($"SSH tunnel in settings: {loaded.UseSshTunnel} (local port {loaded.SshTunnelLocalPort})");
+ }
+
+ IOpenClawLogger logger = options.Verbose ? new ConsoleLogger() : NullLogger.Instance;
+ using var client = new OpenClawGatewayClient(gatewayUrl, token, logger);
+
+ var lastStatus = ConnectionStatus.Disconnected;