-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
1732 lines (1619 loc) · 53.2 KB
/
Copy pathapp.go
File metadata and controls
1732 lines (1619 loc) · 53.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"errors"
"fmt"
"os"
"path"
"strings"
"sync"
"github.com/google/uuid"
"github.com/wailsapp/wails/v2/pkg/runtime"
"nodeshell/internal/agent"
"nodeshell/internal/apperror"
"nodeshell/internal/configdir"
"nodeshell/internal/credentials"
"nodeshell/internal/credentials/keyring"
"nodeshell/internal/fonts"
"nodeshell/internal/hosts"
"nodeshell/internal/knownhosts"
"nodeshell/internal/mcpcli"
"nodeshell/internal/mcpregistration"
"nodeshell/internal/monitor"
"nodeshell/internal/permission"
"nodeshell/internal/sessions"
"nodeshell/internal/settings"
"nodeshell/internal/sftpservice"
"nodeshell/internal/tunnel"
)
// errBackendNotInitialised is returned by bound methods until startup has
// wired the domain services, so the frontend never sees a fake success.
var errBackendNotInitialised = errors.New("nodeshell: backend not initialised")
// resolveDataDir is a seam so tests can pin the data directory without
// touching the real user profile.
var resolveDataDir = configdir.DataDir
// listFonts is the seam for FontsList; production delegates to the stateless
// internal/fonts package, tests inject a fake. Font enumeration needs no
// service, so FontsList stays available before startup (Electron parity).
var listFonts = fonts.List
// newMcpRegistration is the seam for startup's MCP registration service.
// Production uses the stateless mcpregistration package (os.Executable +
// os.UserHomeDir); tests inject a service pinned to a fake executable and
// home so binding tests never touch the real user's MCP configs.
var newMcpRegistration = mcpregistration.New
// newAgentKeyBackend is the seam for the assistant's API-key store. It is the
// same OS keyring the host credentials use; tests inject an in-memory backend
// so no binding test writes to the real keyring. Each provider's key is stored
// under agent-api-key:<providerId>. The unprefixed agent-api-key account is
// the pre-multi-provider location and is copied once on migrate.
var newAgentKeyBackend = func() credentials.Backend { return keyring.NewBackend() }
const (
agentKeyAccount = "agent-api-key"
agentKeyAccountPrefix = "agent-api-key:"
agentKeyMaxLen = 4096
)
func agentKeyAccountFor(providerID string) string {
return agentKeyAccountPrefix + providerID
}
// App is the narrow Wails-bound facade. Hosts and settings methods delegate
// to the domain stores; known-hosts stays an internal service until the SSH
// task consumes it. Credentials are stored in the OS keyring; sessions,
// SFTP, monitor, fonts and MCP registration ride the services wired by
// startup.
//
// mu guards the service pointers: startup wires them and bound methods read
// them, and the WebView can call back before OnStartup has finished. Reads
// happen under the shared lock; a nil pointer is reported as an observable
// error (never fake success), so a call racing with startup either fails
// loudly or runs against a fully wired store.
type App struct {
mu sync.RWMutex
dataDir string
hosts *hosts.Store
settings *settings.Store
known *knownhosts.Store
creds *credentials.Store
readKey credentials.PrivateKeyReader
sessions *sessions.Manager
sftp *sftpservice.Service
transfer *sftpservice.TransferManager
monitor *monitor.Service
tunnels *tunnel.Service
// agent is the sidebar assistant; it runs tools only against sessions
// this manager owns, so it can never reach a host the user is not on.
agent *agent.Service
// agentKeys stores the assistant's API key in the OS keyring, separately
// from the per-host credentials store.
agentKeys credentials.Backend
// perms gates sensitive agent (and, in --mcp, MCP) tool calls. The GUI
// uses permGate to wait on the in-app permission modal.
perms *permission.Service
permGate *permission.ChannelGate
// mcpReg writes the native MCP launcher config into Cursor / Claude Code
// / Codex / OpenCode (this executable with --mcp).
mcpReg *mcpregistration.Service
// home is the symlink-resolved user home boundary for local paths
// (upload sources, download targets); an empty home rejects every local
// path in the SFTP service.
home string
// ctx is the Wails runtime context captured at OnStartup. It is nil
// outside the GUI (unit tests), where session events have no receiver.
ctx context.Context
}
// NewApp constructs an App whose services are initialised from the OS data
// directory during startup.
func NewApp() *App {
return &App{}
}
// NewAppWithServices constructs an App with pre-wired services (test
// injection); startup leaves an already-wired App untouched. The sessions
// manager is wired when both the host store and the known-hosts store exist,
// and the SFTP and monitor services ride the same session manager and sink.
// home is the local-path boundary used by uploads and downloads.
func NewAppWithServices(dataDir string, h *hosts.Store, s *settings.Store, k *knownhosts.Store, c *credentials.Store, readKey credentials.PrivateKeyReader, home string) *App {
app := &App{dataDir: dataDir, hosts: h, settings: s, known: k, creds: c, readKey: readKey, home: home,
mcpReg: newMcpRegistration(), agentKeys: newAgentKeyBackend()}
sink := &disposeSink{
next: &wailsSink{},
sftp: func() *sftpservice.Service { return app.sftp },
monitor: func() *monitor.Service { return app.monitor },
tunnels: func() *tunnel.Service { return app.tunnels },
agent: func() *agent.Service { return app.agent },
perms: func() *permission.Service { return app.perms },
}
app.wireSessions(h, k, c, readKey, sink)
app.sftp = sftpservice.New(sftpservice.Deps{Opener: app.sessions, Sink: sink, Home: home})
app.transfer = sftpservice.NewTransferManager(sftpservice.TransferManagerDeps{SFTP: app.sftp, Sink: sink, Home: home})
app.wireMonitor(sink)
app.wireTunnels()
app.wirePermission(sink)
app.wireAgent(sink)
return app
}
// wireSessions builds the sessions manager from the stores, guarded against a
// partially wired App. The sink drops events when its context is nil. Events
// flow through disposeSink so a closed session also releases its cached SFTP
// client and stops its monitor poller.
func (a *App) wireSessions(h *hosts.Store, k *knownhosts.Store, c *credentials.Store, readKey credentials.PrivateKeyReader, sink sessions.EventSink) {
if h == nil || k == nil {
return
}
a.sessions = sessions.New(sessions.Deps{
Hosts: h,
HostKeys: k,
Creds: c,
ReadKey: readKey,
Sink: sink,
})
}
// wireMonitor builds the monitor service over the sessions execer; without a
// sessions manager there is nothing to poll, so the monitor stays nil and
// MonitorSetActive fails observably.
func (a *App) wireMonitor(sink sessions.EventSink) {
if a.sessions == nil {
return
}
a.monitor = monitor.New(monitor.Deps{Execer: a.sessions, Sink: sink})
}
// wireTunnels builds the local-forward service over the same session manager
// used for exec and SFTP. Without a sessions manager there is nothing to
// forward through, so the service stays nil and the bindings fail observably.
func (a *App) wireTunnels() {
if a.sessions == nil {
return
}
a.tunnels = tunnel.New(tunnel.Deps{
Execer: a.sessions,
Dialer: a.sessions,
Ready: a.sessions,
})
}
// wireAgent builds the sidebar assistant over a guest MCP runtime on the GUI
// session manager and SFTP service. The BoundCaller injects the current tab's
// session so the model cannot pick another host or a local path. Without a
// session manager there is nothing to operate on, so the agent stays nil and
// its bindings fail observably. Endpoint config is resolved per prompt from
// the named provider list, which is how a key or model changed in settings
// applies without rebuilding the service. The guest runtime never starts an
// idle reaper.
func (a *App) wireAgent(sink sessions.EventSink) {
if a.sessions == nil || a.sftp == nil {
return
}
rt := mcpcli.New(mcpcli.Deps{
Manager: a.sessions,
SFTP: a.sftp,
Auth: a.perms,
GuestSessions: true,
})
a.agent = agent.New(agent.Deps{
Tools: &agent.BoundCaller{MCP: rt},
Sink: sink,
})
// Do not StartReaper: this runtime shares GUI sessions, and idle reap
// would disconnect the tab the user is looking at.
}
// wirePermission builds the in-app permission gate over the same Wails sink
// the agent uses, so a sensitive tool blocks on the renderer modal instead
// of running immediately. MCP stdio mode never calls this: it has no
// WebView and uses NativeGate instead.
func (a *App) wirePermission(sink sessions.EventSink) {
gate := permission.NewChannelGate(sink)
a.permGate = gate
a.perms = permission.NewService(permission.ServiceDeps{
Gate: gate,
Policy: a.permissionPolicy,
})
}
func (a *App) permissionPolicy() permission.Policy {
a.mu.RLock()
s := a.settings
a.mu.RUnlock()
if s == nil {
return permission.PolicyAsk
}
current, err := s.Get()
if err != nil {
return permission.PolicyAsk
}
return permission.ParsePolicy(current.PermissionPolicy)
}
// disposeSink forwards every event to the next sink and, on session:closed,
// disposes the session's cached SFTP client, stops its monitor poller,
// closes its local port forwards and drops its agent conversation — a
// torn-down SSH session can never leave a stale SFTP channel, a polling
// goroutine, a listening local port or a running agent loop behind. The
// getters resolve lazily so wiring order (sessions before sftp/monitor/agent)
// never matters.
type disposeSink struct {
next sessions.EventSink
sftp func() *sftpservice.Service
monitor func() *monitor.Service
tunnels func() *tunnel.Service
agent func() *agent.Service
perms func() *permission.Service
}
func (s *disposeSink) Emit(event string, payload any) {
if event == sessions.EventSessionClosed {
if e, ok := payload.(sessions.ClosedEvent); ok {
s.disposeSession(e.SessionID)
}
}
if s.next != nil {
s.next.Emit(event, payload)
}
}
// disposeSession releases everything the closed session owned. Each getter is
// optional, so a sink wired for one service only (unit tests) cannot panic
// here.
func (s *disposeSink) disposeSession(sessionID string) {
if s.sftp != nil {
if svc := s.sftp(); svc != nil {
svc.Dispose(sessionID)
}
}
if s.monitor != nil {
if m := s.monitor(); m != nil {
m.Dispose(sessionID)
}
}
if s.tunnels != nil {
if tun := s.tunnels(); tun != nil {
tun.Dispose(sessionID)
}
}
// A closed session's conversation is dropped with it, so a reconnect
// never inherits the previous connection's transcript and no agent loop
// outlives its SSH session.
if s.agent != nil {
if ag := s.agent(); ag != nil {
ag.Dispose(sessionID)
}
}
if s.perms != nil {
if p := s.perms(); p != nil {
p.ForgetSession(sessionID)
}
}
}
// boolPtr returns a pointer to b, for hosts.Patch flag fields.
func boolPtr(b bool) *bool { return &b }
// logRollbackFailure records a failed credential rollback to stderr. The
// message is generic — never a host id, path or secret — and the original
// error the caller is about to return is never replaced.
func logRollbackFailure(err error) {
fmt.Fprintf(os.Stderr, "nodeshell: failed to restore previous credentials: %v\n", err)
}
// startup is invoked by Wails once the WebView is initialised. It resolves
// and creates the data directory and wires the domain services. Failures are
// written to stderr; bound methods keep failing observably until services
// exist rather than returning partial data.
func (a *App) startup(ctx context.Context) {
a.mu.Lock()
defer a.mu.Unlock()
if a.mcpReg == nil {
a.mcpReg = newMcpRegistration()
}
if a.agentKeys == nil {
a.agentKeys = newAgentKeyBackend()
}
if a.hosts != nil && a.settings != nil {
return
}
dir, err := resolveDataDir()
if err != nil {
fmt.Fprintf(os.Stderr, "nodeshell: resolve data dir: %v\n", err)
return
}
if err := os.MkdirAll(dir, 0o700); err != nil {
fmt.Fprintf(os.Stderr, "nodeshell: create data dir: %v\n", err)
return
}
a.dataDir = dir
a.hosts = hosts.New(dir)
a.settings = settings.New(dir)
a.known = knownhosts.New(dir)
if err := a.known.Load(); err != nil {
fmt.Fprintf(os.Stderr, "nodeshell: load known hosts: %v\n", err)
}
// Credentials live in the OS keyring, not in the data dir, so no path
// under dir is ever passed to the credentials service — the old Electron
// credentials.json stays untouched for rollback.
a.creds = credentials.New(keyring.NewBackend())
home, err := os.UserHomeDir()
if err != nil {
fmt.Fprintf(os.Stderr, "nodeshell: resolve user home: %v\n", err)
}
a.home = home
a.readKey = credentials.NewHomeReader(home)
// The runtime context is captured for event emission; a nil context (the
// ctx can only come from Wails OnStartup) simply drops events.
a.ctx = ctx
sink := &disposeSink{
next: &wailsSink{ctx: ctx},
sftp: func() *sftpservice.Service { return a.sftp },
monitor: func() *monitor.Service { return a.monitor },
tunnels: func() *tunnel.Service { return a.tunnels },
agent: func() *agent.Service { return a.agent },
perms: func() *permission.Service { return a.perms },
}
a.wireSessions(a.hosts, a.known, a.creds, a.readKey, sink)
a.sftp = sftpservice.New(sftpservice.Deps{Opener: a.sessions, Sink: sink, Home: home})
a.transfer = sftpservice.NewTransferManager(sftpservice.TransferManagerDeps{SFTP: a.sftp, Sink: sink, Home: home})
a.wireMonitor(sink)
a.wireTunnels()
a.wirePermission(sink)
a.wireAgent(sink)
}
// shutdown is the Wails OnShutdown hook: the agent loops and the monitor
// poller are stopped before the sessions, so nothing is ever mid-exec against
// a torn-down session and no event can be emitted while the WebView tears
// down. Sessions and SFTP clients are then disposed quietly.
func (a *App) shutdown(context.Context) {
a.mu.RLock()
m := a.sessions
svc := a.sftp
tm := a.transfer
mon := a.monitor
tun := a.tunnels
ag := a.agent
a.mu.RUnlock()
if ag != nil {
ag.DisposeAll()
}
if tm != nil {
tm.Dispose()
}
if mon != nil {
mon.DisposeAll()
}
if tun != nil {
tun.DisposeAll()
}
if m != nil {
m.DisposeAll()
}
if svc != nil {
svc.DisposeAll()
}
}
// HostsList returns all host configurations. Hosts whose persisted
// credentialsSaved flag is true but that have no keyring entry (old Electron
// saves never migrated into the OS keyring) or an unrecoverable (corrupt)
// entry are returned with the flag normalised to false, so the UI prompts for
// credentials instead of trusting a stale flag. The normalisation is
// view-only: the file is left as-is until a successful save persists the
// flags, and hosts without a stale flag never touch the keyring. Only a real
// backend failure is an observable error — a host whose secret state is
// unknown never takes down the rest of the list.
func (a *App) HostsList() ([]hosts.HostConfig, error) {
a.mu.RLock()
h := a.hosts
creds := a.creds
a.mu.RUnlock()
if h == nil {
return nil, errBackendNotInitialised
}
list, err := h.List()
if err != nil {
return nil, err
}
if creds == nil {
return list, nil
}
for i := range list {
if !list[i].CredentialsSaved {
continue
}
_, found, err := creds.Get(list[i].Id)
if err != nil {
// A corrupt entry means this host's secret state is unknowable:
// normalise the stale flags away and keep the other hosts.
// Anything else (backend down) must reach the caller.
if !errors.Is(err, credentials.ErrCorrupt) {
return nil, err
}
list[i].CredentialsSaved = false
list[i].CredentialsPrompted = false
continue
}
if !found {
list[i].CredentialsSaved = false
list[i].CredentialsPrompted = false
}
}
return list, nil
}
// HostsCreate adds a host and returns it with its generated id.
func (a *App) HostsCreate(input hosts.HostInput) (hosts.HostConfig, error) {
a.mu.RLock()
h := a.hosts
a.mu.RUnlock()
if h == nil {
return hosts.HostConfig{}, errBackendNotInitialised
}
return h.Create(input)
}
// HostsUpdate applies patch to the host with the given id.
func (a *App) HostsUpdate(id string, patch hosts.Patch) (hosts.HostConfig, error) {
a.mu.RLock()
h := a.hosts
a.mu.RUnlock()
if h == nil {
return hosts.HostConfig{}, errBackendNotInitialised
}
return h.Update(id, patch)
}
// HostsRemove deletes the host with the given id and its keyring secrets.
// The keyring entry is deleted first (a missing entry counts as success) so a
// host can never be removed while its secret lingers; any real keyring delete
// error aborts the removal, leaving the host in place. If the host-store
// write fails after the keyring was cleared, the previous secret is restored
// so it never disappears while the host survives.
func (a *App) HostsRemove(id string) error {
a.mu.RLock()
h := a.hosts
creds := a.creds
a.mu.RUnlock()
if h == nil {
return errBackendNotInitialised
}
if creds == nil {
return h.Remove(id)
}
prev, prevFound, err := creds.Get(id)
if err != nil {
// A corrupt entry can still be cleared; there is nothing meaningful
// to roll back to if the host-store write fails.
prevFound = false
}
if err := creds.Clear(id); err != nil {
return err
}
if err := h.Remove(id); err != nil {
if prevFound {
if err := creds.Save(id, credentials.SavePatch{Password: &prev.Password, PrivateKey: &prev.PrivateKey}); err != nil {
logRollbackFailure(err)
}
}
return err
}
return nil
}
// SettingsGet returns the current settings.
func (a *App) SettingsGet() (settings.AppSettings, error) {
a.mu.RLock()
s := a.settings
a.mu.RUnlock()
if s == nil {
return settings.AppSettings{}, errBackendNotInitialised
}
return s.Get()
}
// SettingsSet merges patch into the settings, persists and returns the result.
func (a *App) SettingsSet(patch settings.Patch) (settings.AppSettings, error) {
a.mu.RLock()
s := a.settings
a.mu.RUnlock()
if s == nil {
return settings.AppSettings{}, errBackendNotInitialised
}
return s.Set(patch)
}
// CredentialsIsAvailable reports whether the OS keyring is worth attempting.
func (a *App) CredentialsIsAvailable() (bool, error) {
a.mu.RLock()
c := a.creds
a.mu.RUnlock()
if c == nil {
return false, errBackendNotInitialised
}
return c.Available(), nil
}
// CredentialsSave stores secrets for the host in the OS keyring and marks the
// host saved. The Electron save payload {password?, privateKeyPath?} is
// accepted; privateKeyPath is resolved inside the user home directory and read
// (symlinks re-validated) before anything is stored. The host must exist: an
// unknown or empty host id is rejected before any keyring write, so an orphan
// secret can never be created. A successful save persists
// credentialsPrompted=true and credentialsSaved=true exactly like the
// Electron main did; a failed save leaves the host flags untouched, and if
// the keyring write succeeded but the flag update failed, the keyring is
// rolled back to the previous credential.
func (a *App) CredentialsSave(hostId string, payload credentials.SavePayload) error {
a.mu.RLock()
c := a.creds
h := a.hosts
readKey := a.readKey
a.mu.RUnlock()
if c == nil || h == nil {
return errBackendNotInitialised
}
// The keyring must never receive an account for an unknown or empty host:
// validate existence first (a read failure keeps its CONFIG_READ_FAILED
// code) so orphan secrets cannot be created for ids that do not exist.
if _, ok, err := h.GetByID(hostId); err != nil {
return err
} else if !ok {
return &hosts.Error{Code: apperror.Unknown, Message: fmt.Sprintf("Host not found: %s", hostId)}
}
// Remember the previous credential so a failed flag update can roll the
// keyring back instead of leaving a saved secret with an unsaved flag.
prev, prevFound, err := c.Get(hostId)
if err != nil {
return err
}
patch := credentials.SavePatch{}
if payload.Password != nil && *payload.Password != "" {
patch.Password = payload.Password
}
if payload.PrivateKeyPath != nil && *payload.PrivateKeyPath != "" {
if readKey == nil {
return errBackendNotInitialised
}
content, err := readKey(*payload.PrivateKeyPath)
if err != nil {
return err
}
patch.PrivateKey = &content
}
if err := c.Save(hostId, patch); err != nil {
return err
}
if _, err := h.Update(hostId, hosts.Patch{CredentialsPrompted: boolPtr(true), CredentialsSaved: boolPtr(true)}); err != nil {
// The keyring write succeeded but the flag update failed: roll the
// keyring back so no secret survives without its saved flag.
if prevFound {
if err := c.Save(hostId, credentials.SavePatch{Password: &prev.Password, PrivateKey: &prev.PrivateKey}); err != nil {
logRollbackFailure(err)
}
} else if err := c.Clear(hostId); err != nil {
logRollbackFailure(err)
}
return err
}
return nil
}
// CredentialsClear removes the host's keyring entry (missing counts as
// success) and persists credentialsSaved=false, mirroring the Electron main.
// If the flag update fails after the keyring was cleared, the previous secret
// is restored.
func (a *App) CredentialsClear(hostId string) error {
a.mu.RLock()
c := a.creds
h := a.hosts
a.mu.RUnlock()
if c == nil || h == nil {
return errBackendNotInitialised
}
prev, prevFound, err := c.Get(hostId)
if err != nil {
// A corrupt entry can still be cleared; there is nothing meaningful
// to roll back to if the flag update fails.
prevFound = false
}
if err := c.Clear(hostId); err != nil {
return err
}
if _, err := h.Update(hostId, hosts.Patch{CredentialsSaved: boolPtr(false)}); err != nil {
if prevFound {
if err := c.Save(hostId, credentials.SavePatch{Password: &prev.Password, PrivateKey: &prev.PrivateKey}); err != nil {
logRollbackFailure(err)
}
}
return err
}
return nil
}
// CredentialsMarkPrompted records that the user was asked about saving
// credentials, mirroring the Electron main. saved=true is only honoured when
// a keyring entry for the host really exists; otherwise it is forced to false
// so the host can never be marked saved without a stored secret.
func (a *App) CredentialsMarkPrompted(hostId string, saved bool) error {
a.mu.RLock()
c := a.creds
h := a.hosts
a.mu.RUnlock()
if c == nil {
return errBackendNotInitialised
}
if saved {
_, found, err := c.Get(hostId)
if err != nil {
return err
}
saved = found
}
if h == nil {
return errBackendNotInitialised
}
_, err := h.Update(hostId, hosts.Patch{CredentialsPrompted: boolPtr(true), CredentialsSaved: boolPtr(saved)})
return err
}
// SessionsConnect establishes an interactive SSH session for the host. The
// connect runs in the background of the Wails runtime; the returned promise
// resolves once the connection, PTY and shell are fully usable, or fails with
// a stable SSH error code.
func (a *App) SessionsConnect(hostID string, opts sessions.ConnectOptions) (sessions.ConnectResult, error) {
a.mu.RLock()
m := a.sessions
a.mu.RUnlock()
if m == nil {
return sessions.ConnectResult{}, errBackendNotInitialised
}
return m.Connect(context.Background(), hostID, opts)
}
// SessionsWrite sends terminal input to the session's stdin. Input is
// fire-and-forget from the frontend; failures are returned for the adapter to
// surface observably.
func (a *App) SessionsWrite(sessionID string, data string) error {
a.mu.RLock()
m := a.sessions
a.mu.RUnlock()
if m == nil {
return errBackendNotInitialised
}
return m.Write(sessionID, data)
}
// SessionsResize forwards an SSH window-change request for the session.
func (a *App) SessionsResize(sessionID string, cols, rows int) error {
a.mu.RLock()
m := a.sessions
a.mu.RUnlock()
if m == nil {
return errBackendNotInitialised
}
return m.Resize(sessionID, cols, rows)
}
// SessionsDisconnect ends the session; unknown ids are a no-op success
// (Electron parity).
func (a *App) SessionsDisconnect(sessionID string) error {
a.mu.RLock()
m := a.sessions
a.mu.RUnlock()
if m == nil {
return errBackendNotInitialised
}
return m.Disconnect(sessionID)
}
// SessionsCancelConnect aborts every in-flight connect; established sessions
// are unaffected.
func (a *App) SessionsCancelConnect() error {
a.mu.RLock()
m := a.sessions
a.mu.RUnlock()
if m == nil {
return errBackendNotInitialised
}
m.CancelConnect()
return nil
}
// MonitorSetActive starts polling the session for the remote Linux monitor,
// or clears the monitor when sessionID is empty (the UI switches or closes a
// tab). Errors surface as monitor:update events and never touch the session;
// an uninitialised backend is an observable error, never fake success.
func (a *App) MonitorSetActive(sessionID, title string) error {
a.mu.RLock()
m := a.monitor
a.mu.RUnlock()
if m == nil {
return errBackendNotInitialised
}
m.SetActive(sessionID, title)
return nil
}
func (a *App) tunnelService() (*tunnel.Service, error) {
a.mu.RLock()
svc := a.tunnels
a.mu.RUnlock()
if svc == nil {
return nil, errBackendNotInitialised
}
return svc, nil
}
// TunnelsDiscover lists TCP ports currently listening on the remote session.
func (a *App) TunnelsDiscover(sessionID string) ([]tunnel.Listener, error) {
svc, err := a.tunnelService()
if err != nil {
return nil, err
}
return svc.Discover(context.Background(), sessionID)
}
// TunnelsStart opens a local 127.0.0.1 listener that forwards to the remote
// address and port over the SSH session.
func (a *App) TunnelsStart(sessionID, remoteAddr string, remotePort int) (tunnel.Tunnel, error) {
svc, err := a.tunnelService()
if err != nil {
return tunnel.Tunnel{}, err
}
return svc.Start(sessionID, remoteAddr, remotePort)
}
// TunnelsStop closes one local forward. Unknown ids are a no-op success.
func (a *App) TunnelsStop(sessionID, tunnelID string) error {
svc, err := a.tunnelService()
if err != nil {
return err
}
return svc.Stop(sessionID, tunnelID)
}
// TunnelsList returns the live local forwards for the session.
func (a *App) TunnelsList(sessionID string) ([]tunnel.Tunnel, error) {
svc, err := a.tunnelService()
if err != nil {
return nil, err
}
return svc.List(sessionID), nil
}
// --- SFTP bindings (ElectronApi.sftp contract) ---
func (a *App) sftpService() (*sftpservice.Service, error) {
a.mu.RLock()
svc := a.sftp
a.mu.RUnlock()
if svc == nil {
return nil, errBackendNotInitialised
}
return svc, nil
}
// SftpList returns the session's current remote directory listing.
func (a *App) SftpList(sessionID string) ([]sftpservice.Entry, error) {
svc, err := a.sftpService()
if err != nil {
return nil, err
}
return svc.List(sessionID, "")
}
// SftpCwd returns the session's current remote directory.
func (a *App) SftpCwd(sessionID string) (string, error) {
svc, err := a.sftpService()
if err != nil {
return "", err
}
return svc.Cwd(sessionID)
}
// SftpChdir changes the session's remote directory and returns the new one.
func (a *App) SftpChdir(sessionID, remotePath string) (string, error) {
svc, err := a.sftpService()
if err != nil {
return "", err
}
return svc.Chdir(sessionID, remotePath)
}
// SftpMkdir creates a directory under the session's current remote directory.
func (a *App) SftpMkdir(sessionID, name string) error {
svc, err := a.sftpService()
if err != nil {
return err
}
return svc.Mkdir(sessionID, name)
}
// SftpRename moves a remote entry under the session's current directory.
func (a *App) SftpRename(sessionID, from, to string) error {
svc, err := a.sftpService()
if err != nil {
return err
}
return svc.Rename(sessionID, from, to)
}
// SftpRemove deletes a remote entry recursively (never following symlinks).
func (a *App) SftpRemove(sessionID, remotePath string) error {
svc, err := a.sftpService()
if err != nil {
return err
}
return svc.Remove(sessionID, remotePath)
}
// openUploadDialog is a seam: production opens the Wails multi-file dialog;
// tests inject a fake (the runtime dialogs fatal-exit on a non-Wails
// context). An empty result means the user cancelled.
var openUploadDialog = func(ctx context.Context) ([]string, error) {
return runtime.OpenMultipleFilesDialog(ctx, runtime.OpenDialogOptions{Title: "Upload files"})
}
// openSaveDialog is the seam for the download save dialog; an empty result
// means the user cancelled.
var openSaveDialog = func(ctx context.Context, defaultName string) (string, error) {
return runtime.SaveFileDialog(ctx, runtime.SaveDialogOptions{Title: "Save file", DefaultFilename: defaultName})
}
// openPrivateKeyDialog is the seam for the private-key picker; an empty
// result means the user cancelled.
var openPrivateKeyDialog = func(ctx context.Context) (string, error) {
return runtime.OpenFileDialog(ctx, runtime.OpenDialogOptions{Title: "Select private key"})
}
// dialogCtx returns the runtime context or a coded error when the app is not
// running inside the GUI (unit tests), where dialogs would fatal-exit.
func (a *App) dialogCtx() (context.Context, error) {
a.mu.RLock()
ctx := a.ctx
a.mu.RUnlock()
if ctx == nil {
return nil, &sftpservice.Error{Code: apperror.Unknown, Message: "File dialogs are unavailable outside the GUI"}
}
return ctx, nil
}
// SftpUpload opens the multi-file selection dialog and uploads every chosen
// file into the session's current remote directory.
func (a *App) SftpUpload(sessionID string) error {
svc, err := a.sftpService()
if err != nil {
return err
}
ctx, err := a.dialogCtx()
if err != nil {
return err
}
paths, err := openUploadDialog(ctx)
if err != nil {
return err
}
if len(paths) == 0 {
return nil // cancelled
}
return svc.UploadPaths(sessionID, paths)
}
// SftpUploadPaths validates and uploads the given local paths (drag-drop or
// dialog results). Paths must resolve inside the user home directory; non-
// files are skipped.
func (a *App) SftpUploadPaths(sessionID string, localPaths []string) error {
svc, err := a.sftpService()
if err != nil {
return err
}
return svc.UploadPaths(sessionID, localPaths)
}
// SftpDownload opens the save dialog with defaultName and downloads the
// remote file into the chosen (home-boundary checked) target.
func (a *App) SftpDownload(sessionID, remotePath, defaultName string) error {
svc, err := a.sftpService()
if err != nil {
return err
}
ctx, err := a.dialogCtx()
if err != nil {
return err
}
target, err := openSaveDialog(ctx, defaultName)
if err != nil {
return err
}
if target == "" {
return nil // cancelled
}
return svc.Download(sessionID, remotePath, target)
}
// sftpGUITextMaxBytes is the GUI text-editor cap; kept identical to the MCP
// MaxFileBytes (512KiB) so the same remote files are editable in both paths.
const sftpGUITextMaxBytes int64 = 512 * 1024
// SftpTextContent is the SftpReadText IPC payload.
type SftpTextContent struct {
Path string `json:"path"`
Content string `json:"content"`
}
// SftpTextPath is the SftpWriteText IPC payload.
type SftpTextPath struct {
Path string `json:"path"`
}
// SftpReadText reads a remote text file (512KiB cap) for the in-app editor.
func (a *App) SftpReadText(sessionID, remotePath string) (SftpTextContent, error) {
svc, err := a.sftpService()
if err != nil {
return SftpTextContent{}, err
}
resolved, content, err := svc.ReadText(sessionID, remotePath, sftpGUITextMaxBytes)
if err != nil {
return SftpTextContent{}, err
}
return SftpTextContent{Path: resolved, Content: content}, nil
}
// SftpWriteText writes UTF-8 text to a remote file (512KiB cap) from the
// in-app editor. The service commits via temp+rename so a failed write never
// truncates an existing target.
func (a *App) SftpWriteText(sessionID, remotePath, content string) (SftpTextPath, error) {
svc, err := a.sftpService()
if err != nil {
return SftpTextPath{}, err
}
resolved, err := svc.WriteText(sessionID, remotePath, content, sftpGUITextMaxBytes)
if err != nil {
return SftpTextPath{}, err
}
return SftpTextPath{Path: resolved}, nil
}
// --- Agent bindings (ElectronApi.agent contract) ---
// AgentProviderStatus is one named provider as returned to the renderer. The
// API key is never included, only whether one is stored.
type AgentProviderStatus struct {
ID string `json:"id"`
Name string `json:"name"`
BaseURL string `json:"baseUrl"`
Models []string `json:"models"`
HasKey bool `json:"hasKey"`
}
// AgentConfigStatus is the AgentStatus payload. The API key is never