Stabilität: Absturzschutz, Zeitgrenzen, Selbstprüfung, mehr Tests, Dauerlauf (#175)

* Absturzschutz: Fehler in Hintergrundarbeit beenden sshTermy nicht mehr; Zeitgrenzen für Update-Download und Team-Abo; Gast-Tasten über Warteschlange

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUkBzZ657Au6Rz4BPXj

* CI: Zeitgrenzen je Job, alte Läufe abbrechen, Tests in zufälliger Reihenfolge; make check; Bibliotheken aktualisiert

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUkBzZ657Au6Rz4BPXj

* update: Stillstand auch ohne Lesefehler erkennen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUkBzZ657Au6Rz4BPXj

* Zufallstests für Teilen, Vermittler, MCP, Syslog, KI-Antworten, Sync und Fenster-Rahmen; Syslog-Empfang übersteht kaputte Pakete; MCP antwortet auch nach Fehler

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUkBzZ657Au6Rz4BPXj

* Tests: Tresor (Passwortwechsel, Sperre, Blobs, KDF-Grenzen), SFTP-Rundreise, serielle Konsole mit Ersatzkabel

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUkBzZ657Au6Rz4BPXj

* Dauerlauf-Test (make soak) und nächtlicher Lauf mit langen Zufallstests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUkBzZ657Au6Rz4BPXj

* Fuzz: Zeitlimit je Eingabe auch für die neuen Tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUkBzZ657Au6Rz4BPXj

* Selbstprüfung: sshtermy doctor und Palette › Hilfe › Fehlersuche; versehentlich eingecheckte Programmdatei entfernt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUkBzZ657Au6Rz4BPXj

* Oberfläche aufteilen, erster Schritt: Mausbereiche (ui/clickzone) und abgelegte Dateien (ui/dropped) als eigene Pakete

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUkBzZ657Au6Rz4BPXj

* Doku: Absturzschutz und Selbstprüfung in README, Webseite und Handbuch; Plan zur Aufteilung von internal/ui; Zusehen-WASM neu gebaut

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUkBzZ657Au6Rz4BPXj

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
db9979andClaude Opus 5.5 authored and GitHub committed 2026-11-20 12:23:50 +01:00
1 parent 1b968d4614
commit d315d06e77
147 files changed
+2914 -474

No files matched your search

+15 -1
View File
@@ -4,9 +4,15 @@ name: ci
on:
pull_request:
# Neuer Push auf denselben PR: den alten Lauf abbrechen (spart Wartezeit)
concurrency:
group: ci-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 30 # hängender Test bricht ab statt stundenlang zu laufen
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
@@ -14,7 +20,9 @@ jobs:
# neuester Patch von Go 1.27: Sicherheitskorrekturen der Standardbibliothek
go-version: "1.27.x"
check-latest: true
- run: go vet ./... && go test ./...
# zufällige Reihenfolge: Tests, die voneinander abhängen, fallen auf
# (bei Fehlern steht „-test.shuffle N“ im Protokoll zum Nachstellen)
- run: go vet ./... && go test -shuffle=on ./...
- name: Terminal-Emulator (eigene Kopie in third_party/vt)
run: cd third_party/vt && go test ./...
- name: ANSI-Parser (eigene Kopie in third_party/ansi)
@@ -39,6 +47,7 @@ jobs:
# Datenrennen (Terminal-Emulator, Vermittler, SSH) früh finden
race:
runs-on: ubuntu-latest
timeout-minutes: 30 # hängender Test bricht ab statt stundenlang zu laufen
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
@@ -52,6 +61,7 @@ jobs:
# wahre Bedingungen. Abweichungen von der Vorgabe in staticcheck.conf.
lint:
runs-on: ubuntu-latest
timeout-minutes: 15 # hängender Test bricht ab statt stundenlang zu laufen
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
@@ -71,6 +81,7 @@ jobs:
matrix:
os: [windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
timeout-minutes: 40 # hängender Test bricht ab statt stundenlang zu laufen
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
@@ -90,6 +101,7 @@ jobs:
# Bekannte Sicherheitslücken in Go und allen Bibliotheken, die wirklich aufgerufen werden
vuln:
runs-on: ubuntu-latest
timeout-minutes: 10 # hängender Test bricht ab statt stundenlang zu laufen
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
@@ -101,6 +113,7 @@ jobs:
# Parser für Daten von fremden Geräten kurz mit Zufallsdaten beschießen
fuzz:
runs-on: ubuntu-latest
timeout-minutes: 20 # hängender Test bricht ab statt stundenlang zu laufen
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
@@ -121,6 +134,7 @@ jobs:
# ubuntu-latest (26.04) holte apt-utils am 2026-11-11 stundenlang nur von
# security.ubuntu.com, das der Runner nicht auflösen konnte.
runs-on: ubuntu-24.04
timeout-minutes: 15 # Paketquellen können hängen
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# Paketquellen können kurz nicht erreichbar sein (DNS beim Runner):
+41
View File
@@ -0,0 +1,41 @@
# Nachts: Dauerlauf (Lecks über lange Zeit) und längere Zufallstests als im
# PR. Fehler kommen als rote Markierung in Actions und per Mail von GitHub.
name: nightly
on:
schedule:
- cron: "17 2 * * *" # 2:17 UTC, außerhalb der Stoßzeiten
workflow_dispatch:
inputs:
soak:
description: "Dauer des Dauerlaufs"
default: "45m"
jobs:
soak:
runs-on: ubuntu-latest
timeout-minutes: 90
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.27.x"
check-latest: true
- run: make soak SOAK=${{ github.event.inputs.soak || '45m' }}
fuzz-long:
runs-on: ubuntu-latest
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.27.x"
check-latest: true
- run: FUZZTIME=3m tools/fuzz/run.sh
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: failure()
with:
name: fuzz-funde-nachts
path: internal/**/testdata/fuzz/
if-no-files-found: ignore
+1
View File
@@ -8,3 +8,4 @@ tools/dev/gifs/out/
*.test
*.out
/internal/ui/testdata/golden-actual/
/cmd/sshtermy/sshtermy
+17 -1
View File
@@ -6,7 +6,7 @@ PKG := github.com/db9979/sshtermy/internal/version
LDFLAGS := -s -w -X $(PKG).Version=$(VERSION) -X $(PKG).Commit=$(COMMIT) -X $(PKG).Date=$(DATE) -X $(PKG).UpdatePubKey=$(UPDATE_PUBKEY)
TARGETS := windows/arm64 windows/386 windows/amd64 darwin/arm64 darwin/amd64 linux/amd64 linux/arm64 linux/arm linux/riscv64
.PHONY: build test bench loadtest dist clean run golden handout fuzz vuln icon zusehen
.PHONY: build test check soak bench loadtest dist clean run golden handout fuzz vuln icon zusehen
build:
CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o bin/sshtermy ./cmd/sshtermy
@@ -15,6 +15,17 @@ test:
cd third_party/vt && go test ./...
cd third_party/ansi && go test ./...
# Vor dem Push: dasselbe wie die CI-Jobs test + lint (Format, vet, staticcheck,
# Tests in zufälliger Reihenfolge). Spart den Umweg über einen roten CI-Lauf.
check:
tools/check-fmt.sh
go vet ./...
# staticcheck mit dem Go dieses Projekts bauen (sonst versteht es neuere Sprachstände nicht)
GOTOOLCHAIN=$$(go env GOVERSION) go run honnef.co/go/tools/cmd/staticcheck@v0.8.2 ./...
go test -shuffle=on ./...
cd third_party/vt && go test ./...
cd third_party/ansi && go test ./...
# Leistung: Terminal-Durchsatz, Speicher pro Tab, Manager mit 500 Verbindungen
bench:
go test -run '^$$' -bench . -benchtime 2s ./internal/termemu ./internal/ui ./internal/store
@@ -23,6 +34,11 @@ bench:
loadtest:
SSHTERMY_LOAD=1 go test -run TestLoad1000 -v -count=1 ./internal/ui
# Dauerlauf: Tabs öffnen/schließen, Verbindungen abreißen, Lecks messen (nachts in CI)
SOAK ?= 10m
soak:
SSHTERMY_SOAK=$(SOAK) go test -run TestSoak -v -count=1 -timeout 0 ./internal/ui
# Fuzz-Tests (Parser für Daten von fremden Geräten), je FUZZTIME lang
FUZZTIME ?= 20s
fuzz:
+12 -2
View File
@@ -260,6 +260,8 @@ nicht als Beweis. Die Liste: Palette *Logwache: Meldungen* oder `w` im Log-Blick
Schlüssel aus dem Store signiert; geänderte, gelöschte oder umsortierte Zeilen fallen auf. „Audit-Protokoll prüfen
und speichern“ legt Prüfergebnis und lesbare Fassung in Downloads. Befehle mit führendem Leerzeichen erscheinen nur
als „(privat)“
- **Läuft nach Fehlern weiter:** Ein Fehler an einer Stelle (KI-Antwort, Geräteausgabe, Dateiansicht) wird abgefangen,
statt sshTermy samt allen Verbindungen zu beenden; **Selbstprüfung** mit `sshtermy doctor` oder Palette › Hilfe › Fehlersuche.
- **Debug-Protokoll für Fehlerberichte** (Einstellungen oder `sshtermy --debug`): Verbindungsversuche, Abbrüche,
Updates, KI-Anfragen und Sync als Ereignisse, nie Passwörter oder Bildschirminhalte. Hilfe › „Debug-Protokoll
bereinigt speichern“ legt eine Kopie ohne Hosts, IPs und Benutzernamen in Downloads, fertig für ein GitHub-Issue.
@@ -338,6 +340,7 @@ sshtermy --debug # Debug-Protokoll für diesen Start (debug.log im Konfigur
sshtermy backup [datei] # Gesamtsicherung aller Daten (fragt das Master-Passwort)
sshtermy restore <datei> # Gesamtsicherung einspielen (ersetzt alles, alter Ordner bleibt)
sshtermy mcp # MCP-Server für KI-Clients (stdin/stdout), siehe „sshTermy als MCP-Server“
sshtermy doctor # Selbstprüfung: Datenordner, Tresor, Schlüsselbund, SSH-Agent, Update-Signatur, Internet, Uhr
```
## Bedienung
@@ -742,11 +745,18 @@ Claude Desktop (`claude_desktop_config.json`): `{"mcpServers": {"sshtermy": {"co
die Stelle im Programm (Stack). **Vor dem Speichern** werden alle Passwörter, Keys, Passphrasen und API-Keys aus
dem Store wörtlich entfernt, dazu Hosts, Aliase, IP-Adressen, der Home-Ordner und typische Muster
(`password=…`, `Bearer …`, Private Keys).
- Ein Absturz in der Oberfläche wird abgefangen: Das Terminal wird wiederhergestellt und sshTermy fragt, ob der
- **Absturzschutz:** Ein Fehler an einer Stelle (KI-Antwort auslesen, Geräteausgabe auswerten, Dateiansicht,
Hintergrundarbeit) beendet sshTermy nicht mehr samt allen Verbindungen. Der Fehler wird abgefangen, ein Bericht
geschrieben, oben rechts erscheint eine Meldung, und alles andere läuft weiter. Erst wenn sich Fehler häufen
(mehr als 5 in einer Minute), endet sshTermy wie früher.
- Ein Absturz in der Oberfläche, der sich nicht abfangen lässt: Das Terminal wird wiederhergestellt und sshTermy fragt, ob der
Bericht als GitHub-Issue gemeldet werden soll. Bei einem harten Absturz (Prozess endet sofort) entsteht der
Bericht nach dem nächsten Entsperren und erscheint in einem Dialog (`g` = als Issue melden, `o` = Bericht öffnen).
- Nichts wird automatisch verschickt. Das Issue öffnet sich im Browser mit dem Bericht; du siehst alles vor dem
Absenden. Die letzten 10 Berichte bleiben liegen. Ausprobieren: `sshtermy -crash-test ui` (oder `cmd`, `fatal`).
Absenden. Die letzten 10 Berichte bleiben liegen. Ausprobieren: `sshtermy -crash-test ui` oder `cmd` (abgefangen, sshTermy läuft weiter) oder `fatal`.
- **Selbstprüfung** (Palette › Hilfe › Fehlersuche › „Selbstprüfung“ oder `sshtermy doctor`): Datenordner und Rechte,
Tresor, Schlüsselbund, SSH-Agent, Update-Signatur, Internet und Uhr (eine falsche Uhr lässt Einmal-Codes und
Zertifikate scheitern), Absturzberichte und in der App der KI-Endpunkt. `c` kopiert das Ergebnis für den Fehlerbericht.
### Auto-Update
+12 -2
View File
@@ -251,6 +251,8 @@ lets them in. The AI status report treats syslog lines as hints, not as proof. T
AI requests (host/model only). Each line is chained and signed with a key from the store, so changes, deleted or
reordered lines are detected. “Verify and save audit log” writes the check result and a readable copy to Downloads.
Commands with a leading space appear only as “(privat)”
- **Keeps running after errors:** an error in one part (AI answer, device output, file view) is caught instead of
ending sshTermy with all connections; **self-check** with `sshtermy doctor` or palette › Help › Troubleshooting.
- **Debug log for bug reports** (Settings or `sshtermy --debug`): connection attempts, drops, updates, AI requests and
sync as events, never passwords or screen content. Help › “Save cleaned debug log” writes a copy without hosts, IPs and
user names to Downloads, ready to attach to a GitHub issue. Very slow frames (over 50 ms) are logged there too
@@ -327,6 +329,7 @@ sshtermy --debug # write a debug log for this run (debug.log in the config
sshtermy backup [file] # full backup of all data (asks for the master password)
sshtermy restore <file> # restore a full backup (replaces all data, keeps the old folder)
sshtermy mcp # MCP server for AI clients (stdin/stdout), see “sshTermy as MCP server”
sshtermy doctor # self-check: data folder, vault, keychain, SSH agent, update signature, internet, clock
```
## Usage
@@ -727,11 +730,18 @@ Claude Desktop (`claude_desktop_config.json`): `{"mcpServers": {"sshtermy": {"co
stack trace. **Before saving**, all passwords, keys, passphrases and API keys from the store are removed
verbatim, as are hosts, aliases, IP addresses, the home folder and typical patterns (`password=…`, `Bearer …`,
private keys).
- A crash in the interface is caught: the terminal is restored and sshTermy asks whether to report it as a
- **Crash protection:** an error in one part (reading an AI answer, parsing device output, the file view, a
background task) no longer ends sshTermy and all your connections. The error is caught, a report is written,
a message appears top right, and everything else keeps running. Only if errors pile up (more than 5 in a
minute) does sshTermy end as before.
- A crash in the interface that cannot be caught: the terminal is restored and sshTermy asks whether to report it as a
GitHub issue. A hard crash (the process ends immediately) is turned into a report after the next unlock and
shown in a dialog (`g` = report as issue, `o` = open report).
- Nothing is sent automatically. The issue opens in the browser with the report pre-filled; you see everything
before you submit. The last 10 reports are kept. Try it: `sshtermy -crash-test ui` (or `cmd`, `fatal`).
before you submit. The last 10 reports are kept. Try it: `sshtermy -crash-test ui` or `cmd` (caught, sshTermy keeps running) or `fatal`.
- **Self-check** (palette › Help › Troubleshooting › “Self-check” or `sshtermy doctor`): data folder and permissions,
vault, keychain, SSH agent, update signature, internet and clock (a wrong clock breaks one-time codes and
certificates), crash reports and, in the app, the AI endpoint. `c` copies the result for a bug report.
### Auto-update
+45
View File
@@ -0,0 +1,45 @@
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/charmbracelet/x/term"
"github.com/db9979/sshtermy/internal/doctor"
"github.com/db9979/sshtermy/internal/i18n"
)
// runDoctor: „sshtermy doctor“ prüft die Umgebung ohne Oberfläche und ohne
// Master-Passwort. 0 = in Ordnung (auch mit Hinweisen), 1 = Probleme.
func runDoctor(dir string) int {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
fmt.Println(i18n.T("sshTermy-Selbstprüfung …"))
rs := doctor.Run(ctx, doctor.Env{Dir: dir, Extra: []doctor.Check{checkTerminal}})
fmt.Print("\n" + doctor.Format(rs))
if doctor.Worst(rs) == doctor.Fail {
return 1
}
return 0
}
// checkTerminal: Farben und Größe des Terminals, in dem sshtermy läuft.
func checkTerminal(context.Context) doctor.Result {
name := i18n.T("Terminal")
t, ct := os.Getenv("TERM"), os.Getenv("COLORTERM")
if !term.IsTerminal(os.Stdout.Fd()) {
return doctor.Result{Name: name, Status: doctor.Info, Detail: i18n.T("Ausgabe ist kein Terminal (umgeleitet)")}
}
w, h, _ := term.GetSize(os.Stdout.Fd())
d := fmt.Sprintf("%dx%d, TERM=%s", w, h, t)
if ct != "" {
d += ", COLORTERM=" + ct
}
if w > 0 && (w < 80 || h < 20) {
return doctor.Result{Name: name, Status: doctor.Warn, Detail: d + i18n.T(" (kleiner als 80×20: manches wird gekürzt)")}
}
return doctor.Result{Name: name, Status: doctor.OK, Detail: d}
}
+5
View File
@@ -17,6 +17,7 @@ import (
"github.com/db9979/sshtermy/internal/crash"
"github.com/db9979/sshtermy/internal/detach"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
"github.com/db9979/sshtermy/internal/store"
"github.com/db9979/sshtermy/internal/ui"
"github.com/db9979/sshtermy/internal/update"
@@ -130,6 +131,7 @@ func runKeepServe(dir string, noIntro, debug bool) int {
scr.Attach(c, i18n.T("sshTermy wurde in einem anderen Fenster angehängt."))
// Send wartet, bis die Oberfläche läuft: daher nebenher
go func() {
defer safe.Recover("cmd/sshtermy/keep.go")
if again {
p.Send(tea.WindowSizeMsg{Width: cols, Height: rows})
p.Send(tea.ClearScreen()) // neues Fenster: alles neu zeichnen
@@ -137,6 +139,7 @@ func runKeepServe(dir string, noIntro, debug bool) int {
p.Send(tea.FocusMsg{})
}()
go func() {
defer safe.Recover("cmd/sshtermy/keep.go")
for {
ev, err := c.Read()
if err != nil {
@@ -156,6 +159,7 @@ func runKeepServe(dir string, noIntro, debug bool) int {
}
serve(f.c, f.cols, f.rows, false)
go func() {
defer safe.Recover("cmd/sshtermy/keep.go")
for {
c, cols, rows, err := hub.Accept()
if err != nil {
@@ -165,6 +169,7 @@ func runKeepServe(dir string, noIntro, debug bool) int {
}
}()
guard := crash.Start(st.Dir)
app.CatchPanics() // einzelne Fehler abfangen statt alles zu beenden (internal/safe)
_, err = p.Run()
bye := ""
if errors.Is(err, tea.ErrProgramPanic) {
+5
View File
@@ -56,6 +56,9 @@ func main() {
os.Exit(runBackup(os.Args[2:]))
case "restore", "einspielen":
os.Exit(runRestore(os.Args[2:]))
case "doctor", "pruefen", "prüfen":
// Selbstprüfung für Fehlerberichte (internal/doctor)
os.Exit(runDoctor(dir))
case "mcp":
// MCP-Server für KI-Clients über stdin/stdout (internal/mcp)
if err := mcp.Serve(os.Stdin, os.Stdout, &mcp.Remote{DataDir: dir}); err != nil {
@@ -160,6 +163,8 @@ func main() {
}
// Absturzbericht: ab hier landen Paniken im crash-Ordner (internal/crash).
guard := crash.Start(st.Dir)
// Absturzschutz: einzelne Fehler abfangen statt alles zu beenden (internal/safe)
app.CatchPanics()
// Bibliotheken (z. B. der SSH-Agent bei der Weiterleitung) schreiben
// Meldungen mit log.Printf nach stderr: das würde das Bild zerreißen.
log.SetOutput(io.Discard)
Binary file not shown.
+32
View File
@@ -0,0 +1,32 @@
# internal/ui aufteilen
`internal/ui` ist mit über 300 Dateien und gut 80.000 Zeilen ein einziges Paket. Das macht Änderungen
riskanter (alles sieht alles) und die Tests langsam (jede Änderung baut und testet das ganze Paket).
## Stand
Erster Schritt (2026-11-20): zwei Teile ohne Bezug zu `App`/`session` sind eigene Pakete:
| Paket | Inhalt |
|---|---|
| `internal/ui/clickzone` | klickbare Bereiche im fertigen Bild (`Map`, `Action`, `Rect`) |
| `internal/ui/dropped` | ins Fenster gezogene Dateien erkennen (`Paths`, `Split`) |
| `internal/ui/theme` | Farben der Themes (schon vorher) |
## Vorgehen für weitere Teile
1. Datei probeweise in ein leeres Paket kopieren und bauen: die Meldungen `undefined: …` zeigen, was sie
noch aus `ui` braucht. Gut geeignet sind Dateien ohne `*App`, `*session`, `modal`, `Styles`.
2. Mit `gopls rename -w datei.go:Zeile:Spalte NeuerName` erst alle Namen in `ui` auf eindeutige
Zwischennamen bringen (z. B. `CzMap`), Felder und Methoden gleich exportiert benennen.
3. Datei mit `git mv` verschieben, Paketzeile ändern, Zwischennamen im neuen Paket kürzen (`CzMap` → `Map`)
und in `ui` durch den qualifizierten Namen ersetzen (`clickzone.Map`). Weil die Zwischennamen eindeutig
sind, ist das ein sicheres Suchen/Ersetzen.
4. `go build ./... && go test ./internal/ui/...`
## Nächste Kandidaten
- `logtree.go` (Baum der Sitzungsprotokolle, braucht nur `plural`) → `ui/logtree`
- `stamp.go` + `fillbg.go` (Overlays zusammensetzen) → `ui/canvas`
- `graph.go` (Kurven, braucht `mixColor`) zusammen mit den Farbhilfen
- danach Bereiche mit eigenem Zustand (Dateiansicht F5, Teilen, KI-Begleiter) hinter kleinen Schnittstellen
+6 -6
View File
@@ -4,15 +4,15 @@ go 1.27.0
require (
charm.land/bubbles/v2 v2.2.1
charm.land/bubbletea/v2 v2.1.1
charm.land/lipgloss/v2 v2.1.0
charm.land/bubbletea/v2 v2.1.2
charm.land/lipgloss/v2 v2.1.1
filippo.io/cpace v0.0.0-20210101143347-24d601e2e469
github.com/Microsoft/go-winio v0.6.4
github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e
github.com/atotto/clipboard v0.1.4
github.com/charmbracelet/colorprofile v0.4.3
github.com/charmbracelet/ultraviolet v0.0.0-20261023060817-a45b7c86333f
github.com/charmbracelet/x/ansi v0.11.9
github.com/charmbracelet/ultraviolet v0.0.0-20261119151026-8ecbcf0e188c
github.com/charmbracelet/x/ansi v0.11.10
github.com/charmbracelet/x/term v0.2.2
github.com/charmbracelet/x/vt v0.1.0
github.com/charmbracelet/x/xpty v0.1.4
@@ -21,7 +21,7 @@ require (
github.com/hajimehoshi/ebiten/v2 v2.10.6
github.com/jcmturner/gofork v1.7.6
github.com/jcmturner/gokrb5/v8 v8.4.4
github.com/masterzen/winrm v0.0.0-20261004123143-57b335310d59
github.com/masterzen/winrm v0.0.0-20261114181639-d693523ae428
github.com/pkg/sftp v1.13.12
go.bug.st/serial v1.8.0
golang.org/x/crypto v0.59.0
@@ -32,7 +32,7 @@ require (
require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/Azure/go-ntlmssp v0.1.2-0.20260824092057-1c8077778c2c // indirect
github.com/Azure/go-ntlmssp v0.1.2-0.20261111092545-5846b35b583b // indirect
github.com/ChrisTrenkamp/goxpath v0.0.0-20210404020558-97928f7e12b6 // indirect
github.com/charmbracelet/x/conpty v0.2.0 // indirect
github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect
+10 -10
View File
@@ -1,15 +1,15 @@
charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU=
charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc=
charm.land/bubbletea/v2 v2.1.1 h1:S1S9l37pCZGrj1JexBcr9x4Nr3MVeM42InqCYM/tDpU=
charm.land/bubbletea/v2 v2.1.1/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
charm.land/lipgloss/v2 v2.1.0 h1:RLCNLhSQST+NPOmvUSbRWZ3UFOXsf3ZXFmJ5E/2tHEU=
charm.land/lipgloss/v2 v2.1.0/go.mod h1:wwfOgrNqUA9yjL8nmG6BIO0qQnmkEgJ8ISptbme83gI=
charm.land/bubbletea/v2 v2.1.2 h1:vB3XAcHhLB2gR3HOHpwO3lHB3nbvaowIgL3e5x/DUZo=
charm.land/bubbletea/v2 v2.1.2/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
charm.land/lipgloss/v2 v2.1.1 h1:F+vKWis9Kz3MFRsbICSDFtT1ZwVL+8f+36Dtg+OpKwc=
charm.land/lipgloss/v2 v2.1.1/go.mod h1:k79y/56yThpkJvbwyrcHr8MyZF42e84Q5fW9Ibu6LFc=
filippo.io/cpace v0.0.0-20210101143347-24d601e2e469 h1:+gAICE3DIgwMKUzUuVCjd5R4ws+HFL19bKegPYkcgmQ=
filippo.io/cpace v0.0.0-20210101143347-24d601e2e469/go.mod h1:b8UFwXF0HGYD8OWBGJEPwu3IMDHqTpzCtGFtY2xRwTU=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/Azure/go-ntlmssp v0.1.2-0.20260824092057-1c8077778c2c h1:HyK5+m8TFO4iAmMJ7u8tyUjE9C/y4/mvFRT0nqEPfJY=
github.com/Azure/go-ntlmssp v0.1.2-0.20260824092057-1c8077778c2c/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
github.com/Azure/go-ntlmssp v0.1.2-0.20261111092545-5846b35b583b h1:bjbfDOR1AKL94pAT8/sD6RFm+MtcWskNqt8ELP33c+w=
github.com/Azure/go-ntlmssp v0.1.2-0.20261111092545-5846b35b583b/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
github.com/ChrisTrenkamp/goxpath v0.0.0-20210404020558-97928f7e12b6 h1:w0E0fgc1YafGEh5cROhlROMWXiNoZqApk2PDN0M1+Ns=
github.com/ChrisTrenkamp/goxpath v0.0.0-20210404020558-97928f7e12b6/go.mod h1:nuWgzSkT5PnyOd+272uUmV0dnAnAn42Mk7PiQC5VzN4=
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
@@ -24,8 +24,8 @@ github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ
github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w=
github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
github.com/charmbracelet/ultraviolet v0.0.0-20261023060817-a45b7c86333f h1:D2JpB65eehsnkEwEG401dMBSNYtTDgvKXZZSl7ZCxWI=
github.com/charmbracelet/ultraviolet v0.0.0-20261023060817-a45b7c86333f/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio=
github.com/charmbracelet/ultraviolet v0.0.0-20261119151026-8ecbcf0e188c h1:izHJ6cjHd9HGtre1J+c/+QE3rQZ2t4EZH6BqykQbpjc=
github.com/charmbracelet/ultraviolet v0.0.0-20261119151026-8ecbcf0e188c/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio=
github.com/charmbracelet/x/conpty v0.2.0 h1:eKtA2hm34qNfgJCDp/M6Dc0gLy7e07YEK4qAdNGOvVY=
github.com/charmbracelet/x/conpty v0.2.0/go.mod h1:fexgUnVrZgw8scD49f6VSi0Ggj9GWYIrpedRthAwW/8=
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA=
@@ -102,8 +102,8 @@ github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBql
github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/masterzen/simplexml v0.0.0-20190410153822-31eea3082786 h1:2ZKn+w/BJeL43sCxI2jhPLRv73oVVOjEKZjKkflyqxg=
github.com/masterzen/simplexml v0.0.0-20190410153822-31eea3082786/go.mod h1:kCEbxUJlNDEBNbdQMkPSp6yaKcRXVI6f4ddk8Riv4bc=
github.com/masterzen/winrm v0.0.0-20261004123143-57b335310d59 h1:ZvQGbOpXorIxtua/7uFpXUZ1FyarecLn9BoxqJI6miY=
github.com/masterzen/winrm v0.0.0-20261004123143-57b335310d59/go.mod h1:56p25CXdyKsQWriUDfygyVGv5OvFBDY27/yzRy7NuSs=
github.com/masterzen/winrm v0.0.0-20261114181639-d693523ae428 h1:pmewvRot1g5dLBFnnaIoOzuE1b5+QK2XiFLO4+wpqQ0=
github.com/masterzen/winrm v0.0.0-20261114181639-d693523ae428/go.mod h1:cA0bunbrhVEbw3G1WdgFifKsQFaZFvcEXmUIOGZRwf0=
github.com/mattn/go-runewidth v0.0.31 h1:1oCV4ReTlosDBc6rYRw5cL8S/4y8iv5oRl4SJ5IBgwo=
github.com/mattn/go-runewidth v0.0.31/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
+30
View File
@@ -0,0 +1,30 @@
package agent
import (
"testing"
"github.com/db9979/sshtermy/internal/fuzzguard"
)
// Antworten der KI sind fremder Text: halbes JSON, Markdown drumherum,
// falsche Typen. Lesen darf scheitern, aber nie abstürzen.
func FuzzAnswers(f *testing.F) {
f.Add(`{"cmd":"uptime","why":"Last","done":false}`)
f.Add("```json\n{\"plan\":[{\"cmd\":\"ls\"}],\"files\":[{\"path\":\"/tmp/x\",\"content\":\"a\"}]}\n```")
f.Add(`{"windows":[{"n":1,"cmd":"df -h"}],"options":["a",2,null]}`)
f.Add(`{"pick":3}`)
f.Add(`[`)
f.Fuzz(func(t *testing.T, s string) {
fuzzguard.Run(t, func() {
for _, kind := range []string{"unix", "windows", "network"} {
_, _ = parseStep(s, kind)
_, _ = parsePlan(s, kind, true)
_, _ = parseAuto(s, kind, true)
_, _ = parseReview(s, 3, kind)
_ = ParseStepCommand(s, kind)
}
_, _ = ParseMulti(s, []Window{{N: 1, Name: "web"}, {N: 2, Name: "db", Prod: true}})
_ = ParseMenuPick(s, 5)
})
})
}
+2 -1
View File
@@ -20,6 +20,7 @@ import (
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
"github.com/db9979/sshtermy/internal/safety"
"github.com/db9979/sshtermy/internal/sshx"
)
@@ -165,7 +166,7 @@ func Run(ctx context.Context, j Job, dial Dialer, update func(i int, r Result))
}
for i := first; i < len(j.Conns); i++ {
wg.Add(1)
go start(i, j.Conns[i])
safe.Go("broadcast/broadcast.go", func() { start(i, j.Conns[i]) })
}
wg.Wait()
return res
+7 -3
View File
@@ -178,8 +178,9 @@ func Resolve(base string) { _ = os.Remove(filepath.Join(Dir(base), prevName)) }
type Kind int
const (
KindUI Kind = iota // Panik in der Oberfläche, Terminal wurde wiederhergestellt
KindFatal // Prozess sofort beendet, Bericht beim nächsten Start
KindUI Kind = iota // Panik in der Oberfläche, Terminal wurde wiederhergestellt
KindFatal // Prozess sofort beendet, Bericht beim nächsten Start
KindCaught // Fehler abgefangen (internal/safe), sshTermy lief weiter
)
// Report ist ein fertiger, bereinigter Bericht.
@@ -210,8 +211,11 @@ func Write(base string, kind Kind, raw string, sensitive []string) (*Report, err
func Build(kind Kind, raw string, sensitive []string, at time.Time) *Report {
clean := Clean(raw, sensitive)
what := i18n.T("Absturz in der Oberfläche (Terminal wurde wiederhergestellt)")
if kind == KindFatal {
switch kind {
case KindFatal:
what = i18n.T("Programm wurde sofort beendet (Bericht beim nächsten Start erstellt)")
case KindCaught:
what = i18n.T("Fehler abgefangen, sshTermy lief weiter")
}
msg := firstMeaningful(clean)
var b strings.Builder
+5 -1
View File
@@ -9,6 +9,8 @@ import (
"time"
"github.com/charmbracelet/x/term"
"github.com/db9979/sshtermy/internal/safe"
)
// Texte des Fensters; sshTermy setzt sie übersetzt (i18n liegt eine Ebene höher).
@@ -53,6 +55,7 @@ func Attach(dir string) int {
// Tasten → sshTermy
go func() {
defer safe.Recover("detach/client.go")
buf := make([]byte, 4096)
for {
n, err := os.Stdin.Read(buf)
@@ -69,7 +72,7 @@ func Attach(dir string) int {
// Fenstergröße beobachten
stop := make(chan struct{})
defer close(stop)
go watchSize(out, stop, func(c, r int) { _ = fw.write(frResize, sizePayload(c, r)) })
safe.Go("detach/client.go", func() { watchSize(out, stop, func(c, r int) { _ = fw.write(frResize, sizePayload(c, r)) }) })
for {
f, err := readFrame(nc)
@@ -110,6 +113,7 @@ func waitKey() {
fmt.Print(MsgPressKey)
done := make(chan struct{})
go func() {
defer safe.Recover("detach/client.go")
b := make([]byte, 1)
_, _ = os.Stdin.Read(b)
close(done)
+27
View File
@@ -0,0 +1,27 @@
package detach
import (
"bytes"
"testing"
"github.com/db9979/sshtermy/internal/fuzzguard"
)
// Rahmen aus der lokalen Verbindung zum abgetrennten Fenster.
func FuzzFrame(f *testing.F) {
f.Add([]byte{1, 0, 0, 0, 4, 0, 80, 0, 24})
f.Add([]byte{0, 0xff, 0xff, 0xff, 0xff})
f.Add([]byte{})
f.Fuzz(func(t *testing.T, b []byte) {
fuzzguard.Run(t, func() {
r := bytes.NewReader(b)
for {
fr, err := readFrame(r)
if err != nil {
return
}
_, _, _ = parseSize(fr.p)
}
})
})
}
+5 -1
View File
@@ -9,6 +9,8 @@ import (
"path/filepath"
"sync"
"time"
"github.com/db9979/sshtermy/internal/safe"
)
// Hintergrunddienst (Idee aus herdr): sshTermy läuft als eigener Prozess
@@ -64,7 +66,7 @@ func ListenHub(dir string) (*Hub, error) {
h.Close()
return nil, err
}
go h.acceptLoop()
safe.Go("detach/hub.go", func() { h.acceptLoop() })
return h, nil
}
@@ -79,6 +81,7 @@ func (h *Hub) acceptLoop() {
return
}
go func() {
defer safe.Recover("detach/hub.go")
c, cols, rows, err := handshake(nc, h.token)
if err != nil {
nc.Close() // Probe von HubAlive oder falsches Zugangswort
@@ -157,6 +160,7 @@ func dialTimeout(network, addr string, d time.Duration) (net.Conn, error) {
return r.c, r.err
case <-time.After(d):
go func() {
defer safe.Recover("detach/hub.go")
if r := <-ch; r.c != nil {
r.c.Close()
}
+3
View File
@@ -12,6 +12,8 @@ import (
"strings"
"sync"
"time"
"github.com/db9979/sshtermy/internal/safe"
)
const (
@@ -79,6 +81,7 @@ func (s *Server) Accept(timeout time.Duration) (*Conn, int, int, error) {
}
ch := make(chan res, 1)
go func() {
defer safe.Recover("detach/server.go")
for {
nc, err := s.ln.Accept()
if err != nil {
+253
View File
@@ -0,0 +1,253 @@
// Package doctor ist die Selbstprüfung (sshtermy doctor, Palette › Hilfe ›
// Fehlersuche › Selbstprüfung): Datenordner und Rechte, Tresor,
// Schlüsselbund, SSH-Agent, Update-Signatur, Internet und Uhrzeit,
// Absturzberichte. Das Ergebnis ist reiner Text ohne Geheimnisse und Hosts,
// damit man es in einen Fehlerbericht kopieren kann.
package doctor
import (
"context"
"fmt"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/db9979/sshtermy/internal/crash"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/keychain"
"github.com/db9979/sshtermy/internal/sshx"
"github.com/db9979/sshtermy/internal/update"
"github.com/db9979/sshtermy/internal/vault"
"github.com/db9979/sshtermy/internal/version"
)
// Status einer Prüfung.
type Status int
const (
OK Status = iota
Info // nur zur Kenntnis (z. B. Version)
Warn // geht, aber etwas fehlt
Fail // so funktioniert etwas nicht
)
// Mark: Zeichen vor der Zeile (nur ASCII/Cascadia-sicher).
func (s Status) Mark() string {
switch s {
case OK:
return "✓"
case Warn:
return "!"
case Fail:
return "×"
}
return "·"
}
// Result ist eine Zeile der Selbstprüfung.
type Result struct {
Name string
Status Status
Detail string
}
// Check ist eine einzelne Prüfung.
type Check func(ctx context.Context) Result
// Env: Umgebung der Prüfungen. Leere Felder = Standard.
type Env struct {
Dir string // Datenordner
HTTP *http.Client // für Internet/Uhrzeit (Tests setzen einen eigenen)
Probe string // Adresse für Internet/Uhrzeit (Standard: GitHub-API)
Now func() time.Time
Extra []Check // z. B. KI-Endpunkt (Oberfläche) oder Terminal (Kommandozeile)
}
// Run führt alle Prüfungen aus (Reihenfolge fest, jede mit eigener Frist).
func Run(ctx context.Context, env Env) []Result {
if env.HTTP == nil {
env.HTTP = &http.Client{Timeout: 8 * time.Second}
}
if env.Probe == "" {
env.Probe = "https://api.github.com"
}
if env.Now == nil {
env.Now = time.Now
}
checks := []Check{
func(context.Context) Result { return checkVersion() },
func(context.Context) Result { return checkDir(env.Dir) },
func(context.Context) Result { return checkVault(env.Dir) },
func(context.Context) Result { return checkKeychain() },
func(context.Context) Result { return checkAgent() },
func(context.Context) Result { return checkSigned() },
func(ctx context.Context) Result { return checkNet(ctx, env) },
func(context.Context) Result { return checkCrashes(env.Dir) },
}
checks = append(checks, env.Extra...)
out := make([]Result, 0, len(checks))
for _, c := range checks {
cctx, cancel := context.WithTimeout(ctx, 15*time.Second)
out = append(out, c(cctx))
cancel()
}
return out
}
// Worst: schlechtester Status (für den Rückgabewert der Kommandozeile).
func Worst(rs []Result) Status {
w := OK
for _, r := range rs {
if r.Status != Info && r.Status > w {
w = r.Status
}
}
return w
}
// Format: Text zum Anzeigen und Kopieren.
func Format(rs []Result) string {
n := 0
for _, r := range rs {
n = max(n, len([]rune(r.Name)))
}
var b strings.Builder
for _, r := range rs {
pad := strings.Repeat(" ", n-len([]rune(r.Name)))
fmt.Fprintf(&b, "%s %s%s %s\n", r.Status.Mark(), r.Name, pad, r.Detail)
}
switch Worst(rs) {
case OK:
b.WriteString("\n" + i18n.T("Alles in Ordnung.") + "\n")
case Warn:
b.WriteString("\n" + i18n.T("Läuft, aber nicht alles ist eingerichtet (Zeilen mit !).") + "\n")
default:
b.WriteString("\n" + i18n.T("Es gibt Probleme (Zeilen mit ×). Text kopieren und dem Fehlerbericht beilegen.") + "\n")
}
return b.String()
}
func checkVersion() Result {
return Result{i18n.T("Version"), Info, fmt.Sprintf("%s · %s/%s · %s", version.Short(), runtime.GOOS, runtime.GOARCH, runtime.Version())}
}
func checkDir(dir string) Result {
name := i18n.T("Datenordner")
if dir == "" {
return Result{name, Fail, i18n.T("unbekannt (kein Benutzerordner?)")}
}
fi, err := os.Stat(dir)
if os.IsNotExist(err) {
return Result{name, Info, i18n.T("noch nicht angelegt (erster Start)")}
}
if err != nil {
return Result{name, Fail, err.Error()}
}
if !fi.IsDir() {
return Result{name, Fail, i18n.T("ist eine Datei, kein Ordner")}
}
probe := filepath.Join(dir, ".doctor-probe")
if err := os.WriteFile(probe, []byte("ok"), 0o600); err != nil {
return Result{name, Fail, i18n.T("nicht beschreibbar: ") + err.Error()}
}
_ = os.Remove(probe)
if runtime.GOOS != "windows" && fi.Mode().Perm()&0o077 != 0 {
return Result{name, Warn, fmt.Sprintf(i18n.T("für andere lesbar (%o), besser: chmod 700"), fi.Mode().Perm())}
}
return Result{name, OK, i18n.T("beschreibbar")}
}
func checkVault(dir string) Result {
name := i18n.T("Tresor")
p := filepath.Join(dir, "store.vault")
if _, err := os.Stat(p); os.IsNotExist(err) {
return Result{name, Info, i18n.T("noch nicht angelegt (erster Start)")}
}
v, err := vault.Open(p)
if err != nil {
return Result{name, Fail, err.Error()}
}
d := i18n.T("lesbar, Master-Passwort")
if v.HasDPAPI() {
d += i18n.T(" + Windows-Konto")
}
return Result{name, OK, d}
}
func checkKeychain() Result {
name := i18n.T("Schlüsselbund")
if keychain.Available() {
return Result{name, OK, i18n.T("verfügbar (Passwörter können dort liegen)")}
}
return Result{name, Warn, i18n.T("nicht verfügbar: Passwörter liegen nur im Tresor")}
}
func checkAgent() Result {
name := i18n.T("SSH-Agent")
if err := sshx.AgentReachable(); err != nil {
return Result{name, Info, i18n.T("nicht erreichbar (nur nötig für Schlüssel im Agenten): ") + err.Error()}
}
return Result{name, OK, i18n.T("erreichbar")}
}
func checkSigned() Result {
name := i18n.T("Update-Signatur")
if update.Signed() {
return Result{name, OK, i18n.T("Updates werden vor dem Einspielen geprüft")}
}
return Result{name, Warn, i18n.T("eigener Build ohne Schlüssel: Updates werden nicht geprüft")}
}
// checkNet: Internet (für Updates) und Uhrzeit (falsche Uhr ⇒ Zertifikate,
// Einmal-Codes und SSH-Zertifikate scheitern scheinbar grundlos).
func checkNet(ctx context.Context, env Env) Result {
name := i18n.T("Internet und Uhr")
req, err := http.NewRequestWithContext(ctx, http.MethodHead, env.Probe, nil)
if err != nil {
return Result{name, Warn, err.Error()}
}
req.Header.Set("User-Agent", version.Short())
resp, err := env.HTTP.Do(req)
if err != nil {
return Result{name, Warn, i18n.T("GitHub nicht erreichbar, Updates gehen nicht: ") + err.Error()}
}
resp.Body.Close()
srv, err := http.ParseTime(resp.Header.Get("Date"))
if err != nil {
return Result{name, OK, i18n.T("GitHub erreichbar")}
}
diff := env.Now().Sub(srv)
if diff < 0 {
diff = -diff
}
if diff > 2*time.Minute {
return Result{name, Warn, fmt.Sprintf(i18n.T("Uhr geht %s falsch: Anmeldung mit Einmal-Codes oder Zertifikaten kann scheitern"), diff.Round(time.Second))}
}
return Result{name, OK, i18n.T("GitHub erreichbar, Uhr stimmt")}
}
func checkCrashes(dir string) Result {
name := i18n.T("Absturzberichte")
es, _ := os.ReadDir(crash.Dir(dir))
n := 0
for _, e := range es {
if strings.HasPrefix(e.Name(), "sshtermy-crash-") {
n++
}
}
if n == 0 {
return Result{name, OK, i18n.T("keine")}
}
return Result{name, Info, fmt.Sprintf(i18n.T("%d im Ordner %s"), n, tilde(crash.Dir(dir)))}
}
// tilde: Home-Ordner als ~ (der Text landet ggf. in einem Fehlerbericht).
func tilde(p string) string {
if h, err := os.UserHomeDir(); err == nil && h != "" && strings.HasPrefix(p, h) {
return "~" + p[len(h):]
}
return p
}
+111
View File
@@ -0,0 +1,111 @@
package doctor
import (
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
func server(t *testing.T, date time.Time) string {
t.Helper()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Date", date.UTC().Format(http.TimeFormat))
}))
t.Cleanup(ts.Close)
return ts.URL
}
func find(t *testing.T, rs []Result, prefix string) Result {
t.Helper()
for _, r := range rs {
if strings.HasPrefix(r.Name, prefix) {
return r
}
}
t.Fatalf("keine Zeile %q", prefix)
return Result{}
}
func TestRunFreshDir(t *testing.T) {
dir := t.TempDir()
now := time.Now()
rs := Run(context.Background(), Env{Dir: dir, Probe: server(t, now), Now: func() time.Time { return now }})
if r := find(t, rs, "Datenordner"); r.Status != OK && !(runtime.GOOS != "windows" && r.Status == Warn) {
t.Fatalf("Datenordner: %+v", r)
}
if r := find(t, rs, "Tresor"); r.Status != Info {
t.Fatalf("Tresor bei erstem Start: %+v", r)
}
if r := find(t, rs, "Internet"); r.Status != OK {
t.Fatalf("Internet: %+v", r)
}
if r := find(t, rs, "Absturz"); r.Status != OK {
t.Fatalf("Absturzberichte: %+v", r)
}
if _, err := os.Stat(filepath.Join(dir, ".doctor-probe")); !os.IsNotExist(err) {
t.Fatal("Probedatei liegen geblieben")
}
txt := Format(rs)
if !strings.Contains(txt, "Version") || !strings.Contains(txt, "✓") {
t.Fatalf("Format: %s", txt)
}
}
func TestClockSkew(t *testing.T) {
now := time.Now()
rs := Run(context.Background(), Env{Dir: t.TempDir(), Probe: server(t, now.Add(-10*time.Minute)), Now: func() time.Time { return now }})
r := find(t, rs, "Internet")
if r.Status != Warn || !strings.Contains(r.Detail, "10m") {
t.Fatalf("falsche Uhr nicht erkannt: %+v", r)
}
}
func TestOfflineAndBrokenDir(t *testing.T) {
dir := filepath.Join(t.TempDir(), "datei")
_ = os.WriteFile(dir, []byte("x"), 0o600)
if r := checkDir(filepath.Join(t.TempDir(), "fehlt")); r.Status != Info {
t.Fatalf("erster Start: %+v", r)
}
rs := Run(context.Background(), Env{Dir: dir, Probe: "http://127.0.0.1:1"})
if r := find(t, rs, "Datenordner"); r.Status != Fail {
t.Fatalf("Datei statt Ordner: %+v", r)
}
if r := find(t, rs, "Internet"); r.Status != Warn {
t.Fatalf("offline: %+v", r)
}
if Worst(rs) != Fail {
t.Fatal("Worst")
}
if !strings.Contains(Format(rs), "×") {
t.Fatal("Fehlerzeile fehlt")
}
}
func TestCrashesAndExtra(t *testing.T) {
dir := t.TempDir()
_ = os.MkdirAll(filepath.Join(dir, "crash"), 0o700)
_ = os.WriteFile(filepath.Join(dir, "crash", "sshtermy-crash-1.txt"), []byte("x"), 0o600)
extra := func(context.Context) Result { return Result{"KI", Fail, "antwortet nicht"} }
rs := Run(context.Background(), Env{Dir: dir, Probe: server(t, time.Now()), Extra: []Check{extra}})
if r := find(t, rs, "Absturz"); r.Status != Info || !strings.HasPrefix(r.Detail, "1 ") {
t.Fatalf("Absturzberichte: %+v", r)
}
if rs[len(rs)-1].Name != "KI" {
t.Fatal("Zusatzprüfung fehlt am Ende")
}
}
func TestVaultGarbage(t *testing.T) {
dir := t.TempDir()
_ = os.WriteFile(filepath.Join(dir, "store.vault"), []byte("{kaputt"), 0o600)
r := checkVault(dir)
if r.Status != Fail {
t.Fatalf("kaputter Tresor: %+v", r)
}
}
+2
View File
@@ -6,6 +6,7 @@ import (
"time"
"github.com/db9979/sshtermy/internal/detach"
"github.com/db9979/sshtermy/internal/safe"
)
// RunAttach: abgetrennter Tab (⇧F10) im zweiten eigenen Fenster. Das
@@ -27,6 +28,7 @@ func RunAttach(dir string, opts Options) int {
w.onQuit = c.Close
out := w.output()
go func() {
defer safe.Recover("gui/attach.go")
defer close(w.done)
for {
m, err := c.Next()
+3 -1
View File
@@ -3,6 +3,8 @@ package gui
import (
"io"
"sync"
"github.com/db9979/sshtermy/internal/safe"
)
// queueWriter reicht Bytes in eigener Goroutine weiter, in Reihenfolge, und
@@ -25,7 +27,7 @@ type queueWriter struct {
func newQueueWriter(dst io.Writer) *queueWriter {
q := &queueWriter{dst: dst}
q.cond = sync.NewCond(&q.mu)
go q.loop()
safe.Go("gui/queue.go", func() { q.loop() })
return q
}
+4 -1
View File
@@ -24,6 +24,7 @@ import (
"github.com/hajimehoshi/ebiten/v2/inpututil"
"github.com/hajimehoshi/ebiten/v2/text/v2"
"github.com/db9979/sshtermy/internal/safe"
"github.com/db9979/sshtermy/internal/termemu"
"github.com/db9979/sshtermy/internal/winstate"
)
@@ -96,6 +97,7 @@ func Run(model tea.Model, opts Options) (tea.Model, error) {
var final tea.Model
var runErr error
go func() {
defer safe.Recover("gui/window.go")
final, runErr = prog.Run()
close(w.done)
}()
@@ -161,7 +163,7 @@ func (w *window) output() io.Writer {
// run öffnet das Fenster und kehrt zurück, wenn done zu ist.
func (w *window) run() error {
go w.resizer()
safe.Go("gui/window.go", func() { w.resizer() })
w.setFaces(1)
ebiten.SetWindowTitle(w.opts.Title)
ebiten.SetWindowSize(int(float64(startCols)*w.cellW+2*padding), int(float64(startRows)*w.cellH+2*padding))
@@ -524,6 +526,7 @@ func keyRune(k ebiten.Key) rune {
func (w *window) paste() {
go func() {
defer safe.Recover("gui/window.go")
s, err := clipboard.ReadAll()
if err == nil && s != "" {
w.term.Paste(s)
+49
View File
@@ -0,0 +1,49 @@
package i18n
// Stabilität (2026-11-20): Absturzschutz (ui/safety.go, internal/safe),
// Selbstprüfung (sshtermy doctor).
func init() {
for k, v := range enStability {
en[k] = v
}
}
var enStability = map[string]string{
"Fehler abgefangen, sshTermy lief weiter": "Error caught, sshTermy kept running",
"Interner Fehler abgefangen, sshTermy läuft weiter.": "Internal error caught, sshTermy keeps running.",
"update: Download kam %s lang nicht voran": "update: download made no progress for %s",
" (kleiner als 80×20: manches wird gekürzt)": " (smaller than 80×20: some things get cut off)",
" + Windows-Konto": " + Windows account",
" antwortet": " answers",
" antwortet nicht: ": " does not answer: ",
"%d im Ordner %s": "%d in folder %s",
"Absturzberichte": "Crash reports",
"Alles in Ordnung.": "Everything is fine.",
"Ausgabe ist kein Terminal (umgeleitet)": "Output is not a terminal (redirected)",
"Es gibt Probleme (Zeilen mit ×). Text kopieren und dem Fehlerbericht beilegen.": "There are problems (lines with ×). Copy this text and attach it to your bug report.",
"GitHub erreichbar": "GitHub reachable",
"GitHub erreichbar, Uhr stimmt": "GitHub reachable, clock is correct",
"GitHub nicht erreichbar, Updates gehen nicht: ": "GitHub not reachable, updates won't work: ",
"Internet und Uhr": "Internet and clock",
"Läuft, aber nicht alles ist eingerichtet (Zeilen mit !).": "Works, but not everything is set up (lines with !).",
"Selbstprüfung": "Self-check",
"Selbstprüfung (Ordner, Tresor, KI, Internet, Uhr)": "Self-check (folder, vault, AI, internet, clock)",
"Selbstprüfung läuft …": "Self-check running …",
"Tresor": "Vault",
"Uhr geht %s falsch: Anmeldung mit Einmal-Codes oder Zertifikaten kann scheitern": "Clock is off by %s: sign-in with one-time codes or certificates may fail",
"Update-Signatur": "Update signature",
"Updates werden vor dem Einspielen geprüft": "Updates are verified before installing",
"beschreibbar": "writable",
"eigener Build ohne Schlüssel: Updates werden nicht geprüft": "own build without key: updates are not verified",
"für andere lesbar (%o), besser: chmod 700": "readable by others (%o), better: chmod 700",
"ist eine Datei, kein Ordner": "is a file, not a folder",
"lesbar, Master-Passwort": "readable, master password",
"nicht beschreibbar: ": "not writable: ",
"nicht eingerichtet": "not set up",
"nicht erreichbar (nur nötig für Schlüssel im Agenten): ": "not reachable (only needed for keys in the agent): ",
"nicht verfügbar: Passwörter liegen nur im Tresor": "not available: passwords are kept in the vault only",
"noch nicht angelegt (erster Start)": "not created yet (first start)",
"sshTermy-Selbstprüfung …": "sshTermy self-check …",
"unbekannt (kein Benutzerordner?)": "unknown (no user folder?)",
"verfügbar (Passwörter können dort liegen)": "available (passwords can be stored there)",
}
+4
View File
@@ -15,6 +15,8 @@ import (
"sync"
"sync/atomic"
"time"
"github.com/db9979/sshtermy/internal/safe"
)
// ptyFile: Pseudo-Terminal je System (pty_unix.go, pty_windows.go).
@@ -62,10 +64,12 @@ func Start(shell, dir string, cols, rows int, out io.Writer) (*Stream, error) {
s := &Stream{Shell: argv[0], Done: make(chan error, 1), pty: p, cmd: cmd}
readDone := make(chan struct{})
go func() {
defer safe.Recover("localsh/localsh.go")
defer close(readDone)
_, _ = io.Copy(out, p)
}()
go func() {
defer safe.Recover("localsh/localsh.go")
err := waitProcess(cmd)
// Nach dem Ende der Shell den Rest der Ausgabe noch abholen. Hält ein
// Hintergrundprozess das Terminal offen (oder bei ConPTY, das erst
+30
View File
@@ -0,0 +1,30 @@
package logscan
import (
"testing"
"time"
"github.com/db9979/sshtermy/internal/hostinfo"
"github.com/db9979/sshtermy/internal/fuzzguard"
)
// Syslog kommt per UDP von irgendwem, Protokolle von fremden Servern und
// Switches: beliebige Bytes dürfen nichts kaputt machen.
func FuzzSyslog(f *testing.F) {
now := time.Date(2026, 11, 20, 10, 0, 0, 0, time.UTC)
f.Add("<187>Nov 20 09:59:01 sw1 %LINK-3-UPDOWN: Interface Gi1/0/1, changed state to down")
f.Add("<34>1 2026-11-20T09:00:00Z host app 1 ID47 - BOM'su root' failed")
f.Add("2026-11-20T09:00:00+01:00 web kernel: EXT4-fs error (device sda1)")
f.Add("<999999999999999999999>")
f.Fuzz(func(t *testing.T, s string) {
fuzzguard.Run(t, func() {
_, _ = SyslogPacket(s, now)
_ = ParseUnix(s, 24, now)
_ = ParseWindows(s, 24, now)
for _, v := range []hostinfo.Vendor{hostinfo.VendorUnknown, hostinfo.VendorProCurve, hostinfo.VendorCisco, hostinfo.VendorUniFi} {
_ = ParseNetwork(v, []string{s, s}, s, 24, now)
}
})
})
}
+38
View File
@@ -0,0 +1,38 @@
package mcp
import (
"bytes"
"encoding/json"
"io"
"strings"
"testing"
"github.com/db9979/sshtermy/internal/fuzzguard"
)
type nopBackend struct{}
func (nopBackend) Call(tool string, args json.RawMessage) (string, error) { return "ok", nil }
// Anfragen kommen von einem fremden Programm (KI-Werkzeug): jede Zeile muss
// beantwortet oder verworfen werden, ohne Absturz und ohne Hänger.
func FuzzServe(f *testing.F) {
f.Add(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}`)
f.Add(`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"list_connections"}}`)
f.Add(`{"jsonrpc":"2.0","id":"x","method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":1}}}`)
f.Add(`{"id":null}`)
f.Add("\x00{\n}")
f.Fuzz(func(t *testing.T, in string) {
fuzzguard.Run(t, func() {
var out bytes.Buffer
if err := Serve(strings.NewReader(in), &out, nopBackend{}); err != nil && err != io.EOF {
return // z. B. Zeile zu lang: Fehler ist erlaubt, Absturz nicht
}
for _, line := range strings.Split(strings.TrimSpace(out.String()), "\n") {
if line != "" && !json.Valid([]byte(line)) {
t.Errorf("Antwort ist kein JSON: %q", line)
}
}
})
})
}
+5 -3
View File
@@ -14,6 +14,7 @@ import (
"time"
"github.com/db9979/sshtermy/internal/localsock"
"github.com/db9979/sshtermy/internal/safe"
)
// Verbindung Brücke ↔ App: erste Zeile das Token aus mcp.json, danach je
@@ -71,7 +72,7 @@ func Listen(dataDir string, h Handler) (*Host, error) {
x.Close()
return nil, err
}
go x.accept()
safe.Go("mcp/host.go", func() { x.accept() })
return x, nil
}
@@ -88,7 +89,7 @@ func (x *Host) accept() {
if err != nil {
return
}
go x.serve(nc)
safe.Go("mcp/host.go", func() { x.serve(nc) })
}
}
@@ -110,6 +111,7 @@ func (x *Host) serve(nc net.Conn) {
return
}
go func() {
defer safe.Recover("mcp/host.go")
text, err := x.handle(q.Tool, q.Args)
resp := wireResp{ID: q.ID, Text: text}
if err != nil {
@@ -162,7 +164,7 @@ func (r *Remote) connect() error {
return ErrNotRunning
}
r.nc, r.enc, r.wait = nc, json.NewEncoder(nc), map[int64]chan wireResp{}
go r.read(nc)
safe.Go("mcp/host.go", func() { r.read(nc) })
return nil
}
+7 -1
View File
@@ -14,6 +14,7 @@ import (
"io"
"sync"
"github.com/db9979/sshtermy/internal/safe"
"github.com/db9979/sshtermy/internal/version"
)
@@ -223,7 +224,12 @@ func Serve(in io.Reader, out io.Writer, b Backend) error {
wg.Add(1)
go func(id json.RawMessage) {
defer wg.Done()
text, err := b.Call(p.Name, p.Arguments)
var text string
var err error
// Fehler im Werkzeug: dem Client trotzdem antworten, sonst wartet er ewig
if !safe.Run("mcp/mcp.go "+p.Name, func() { text, err = b.Call(p.Name, p.Arguments) }) {
err = errors.New("internal error in sshTermy (report written)")
}
res := map[string]any{"content": []textContent{{"text", text}}}
if err != nil {
res = map[string]any{"content": []textContent{{"text", err.Error()}}, "isError": true}
+2
View File
@@ -18,6 +18,7 @@ import (
"time"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
"github.com/db9979/sshtermy/internal/sshx"
)
@@ -208,6 +209,7 @@ func Scan(ctx context.Context, addrs []netip.Addr, o Options, progress func(done
case sem <- struct{}{}:
wg.Add(1)
go func(a netip.Addr) {
defer safe.Recover("netscan/netscan.go")
defer wg.Done()
defer func() { <-sem }()
h, ok := probe(ctx, a, o)
+6 -2
View File
@@ -12,6 +12,8 @@ import (
"unicode/utf8"
"github.com/charmbracelet/x/ansi"
"github.com/db9979/sshtermy/internal/safe"
)
// backend: wo PowerShell läuft (WinRM, in Tests ein lokaler Prozess).
@@ -103,7 +105,7 @@ func newStream(be backend, cols int, out io.Writer, timeout time.Duration) (*Str
}
s := &Stream{Done: make(chan error, 1), be: be, out: out, cols: cols, atBOL: true, compWait: -1,
ready1: make(chan struct{}), sendq: make(chan sendItem, 256)}
go s.sender()
safe.Go("psremote/stream.go", func() { s.sender() })
if err := s.startProc(""); err != nil {
close(s.sendq)
be.close()
@@ -228,6 +230,7 @@ func (s *Stream) finish(err error) {
close(s.sendq)
s.mu.Unlock()
go func() {
defer safe.Recover("psremote/stream.go")
if p != nil {
p.stop()
}
@@ -737,7 +740,7 @@ func (s *Stream) basePrompt() string {
// finishLater: exit/Strg+D; finish nimmt s.mu selbst.
func (s *Stream) finishLater() {
s.ready = false
go s.finish(nil)
safe.Go("psremote/stream.go", func() { s.finish(nil) })
}
func (s *Stream) enter() {
@@ -812,6 +815,7 @@ func (s *Stream) interrupt() {
s.p = nil
s.gen++ // Ausgaben des alten Prozesses verwerfen
go func() {
defer safe.Recover("psremote/stream.go")
if old != nil {
old.stop()
}
+5 -1
View File
@@ -25,6 +25,8 @@ import (
"github.com/masterzen/winrm"
"github.com/masterzen/winrm/soap"
"github.com/db9979/sshtermy/internal/safe"
)
// Auth: Anmeldeverfahren.
@@ -70,6 +72,7 @@ func Dial(ctx context.Context, cfg Config, cols int, out io.Writer) (*Stream, er
}
ch := make(chan res, 1)
go func() {
defer safe.Recover("psremote/winrm.go")
w, err := openWSMan(cfg)
ch <- res{w, err}
}()
@@ -82,6 +85,7 @@ func Dial(ctx context.Context, cfg Config, cols int, out io.Writer) (*Stream, er
w = r.w
case <-ctx.Done():
go func() {
defer safe.Recover("psremote/winrm.go")
if r := <-ch; r.w != nil {
r.w.close()
}
@@ -196,7 +200,7 @@ func (w *wsman) start(dir string, h handlers) (proc, error) {
return nil, err
}
c := &wsCmd{w: w, id: id, quit: make(chan struct{})}
go c.receive(h)
safe.Go("psremote/winrm.go", func() { c.receive(h) })
return c, nil
}
+3 -1
View File
@@ -21,6 +21,7 @@ import (
"golang.org/x/crypto/ssh"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
)
// AnchorConfig: was der Anker auf dem Server weiß (anker.json, 0600).
@@ -234,6 +235,7 @@ func (a *Anchor) once(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
defer safe.Recover("relay/anchor.go")
t := time.NewTicker(pingEvery)
defer t.Stop()
for {
@@ -263,7 +265,7 @@ func (a *Anchor) once(ctx context.Context) error {
if json.Unmarshal(b, &m) != nil || m.Typ != "kanal" || len(m.ID) != 32 {
continue
}
go a.channel(ctx, m.ID)
safe.Go("relay/anchor.go", func() { a.channel(ctx, m.ID) })
}
}
+22
View File
@@ -0,0 +1,22 @@
package relay
import (
"testing"
"github.com/db9979/sshtermy/internal/fuzzguard"
)
// Kopplungszeilen und Teilen-Links tippt oder fügt man ein; sie können
// beliebig kaputt sein.
func FuzzParse(f *testing.F) {
f.Add("sshtermy-pair https://relay.example:8443 abcd 0123")
f.Add("sshtermy://zusehen/7-taube-kompass-ofen")
f.Add("")
f.Add("\x00%%%://")
f.Fuzz(func(t *testing.T, s string) {
fuzzguard.Run(t, func() {
_, _ = ParseLine(s)
_, _ = ParseShareLink(s)
})
})
}
+2 -1
View File
@@ -20,6 +20,7 @@ import (
"time"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
"github.com/db9979/sshtermy/internal/webwatch"
)
@@ -86,7 +87,7 @@ func StartLAN() (*LAN, error) {
}
if u, err := net.ListenUDP("udp4", &net.UDPAddr{Port: LANPort}); err == nil {
l.udp = u
go l.answer()
safe.Go("relay/lan.go", func() { l.answer() })
}
return l, nil
}
+3 -1
View File
@@ -19,6 +19,7 @@ import (
"time"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
)
// ServeOptions für `sshtermy vermittler start`.
@@ -101,8 +102,9 @@ func Serve(ctx context.Context, o ServeOptions) error {
if cert != nil {
hs.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{*cert}}
}
go s.Watch(ctx)
safe.Go("relay/serve.go", func() { s.Watch(ctx) })
go func() {
defer safe.Recover("relay/serve.go")
<-ctx.Done()
sc, c := context.WithTimeout(context.Background(), 3*time.Second)
defer c()
+2
View File
@@ -15,6 +15,7 @@ import (
"time"
"github.com/coder/websocket"
"github.com/db9979/sshtermy/internal/safe"
"github.com/db9979/sshtermy/internal/webwatch"
"golang.org/x/crypto/ssh"
)
@@ -493,6 +494,7 @@ func (s *Server) anchorCtrl(w http.ResponseWriter, r *http.Request) {
s.log("anker_zu", n)
}()
go func() {
defer safe.Recover("relay/server.go")
t := time.NewTicker(pingEvery)
defer t.Stop()
for {
+2 -1
View File
@@ -19,6 +19,7 @@ import (
"golang.org/x/crypto/chacha20poly1305"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
)
// Sitzung live teilen
@@ -136,7 +137,7 @@ func (c *Client) StartShare(ctx context.Context) (*ShareHost, error) {
ws.SetReadLimit(64 * 1024)
sh := &ShareHost{Link: ShareLink{Base: c.Base, ID: r.ID, Key: key, FP: c.FP}, ws: ws,
viewers: make(chan int, 8), done: make(chan struct{})}
go sh.readCtrl()
safe.Go("relay/share.go", func() { sh.readCtrl() })
return sh, nil
}
+3 -1
View File
@@ -12,6 +12,7 @@ import (
"github.com/coder/websocket"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
)
// Teilen v2: Einladung mit Code, Zulassung durch den Gastgeber
@@ -348,6 +349,7 @@ func (s *Server) watch2(w http.ResponseWriter, r *http.Request) {
hostText(host, map[string]any{"typ": "neu", "v": id, "ip": ip})
// Wer nicht zugelassen wird, fliegt nach pendingWait raus.
go func() {
defer safe.Recover("relay/share2.go")
t := time.NewTimer(pendingWait)
defer t.Stop()
select {
@@ -439,7 +441,7 @@ func (c *Client) StartShare2(ctx context.Context, minutes int) (*Share2, error)
ws.SetReadLimit(guestMsgMax + 64)
sh := &Share2{ID: r.ID, Platz: r.Platz, Base: c.Base, FP: c.FP, Until: time.Unix(r.Bis, 0), ws: ws,
ev: make(chan HostEvent, 64), done: make(chan struct{})}
go sh.read()
safe.Go("relay/share2.go", func() { sh.read() })
return sh, nil
}
+3
View File
@@ -14,6 +14,7 @@ import (
"golang.org/x/crypto/chacha20poly1305"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
)
// Gastgeber-Seite einer Freigabe v2 (Ablauf: siehe internal/sharewire/guest.go).
@@ -155,6 +156,7 @@ func (h *HostSession) guestMsg(g *GuestState, b []byte) (HostUI, bool) {
// Nicht stumm bleiben: sonst wartet der Zuschauer ewig auf „Prüfe den Code“.
v := g.V
go func() {
defer safe.Recover("relay/sharesess.go")
_ = h.Sh.To(v, append([]byte{MsgNo}, "gesperrt"...))
_ = h.Sh.Kick(v)
}()
@@ -176,6 +178,7 @@ func (h *HostSession) guestMsg(g *GuestState, b []byte) (HostUI, bool) {
h.burn()
v := g.V
go func() {
defer safe.Recover("relay/sharesess.go")
_ = h.Sh.To(v, append([]byte{MsgNo}, "Code passt nicht"...))
_ = h.Sh.Kick(v)
}()
+122
View File
@@ -0,0 +1,122 @@
// Package safe fängt Paniken in Hintergrundarbeit ab, damit ein Fehler an
// einer Stelle (KI-Antwort auslesen, Geräteausgabe auswerten, Dateiansicht …)
// nicht das ganze Programm mit allen offenen Verbindungen beendet.
//
// Ohne Handler (Tests, Unterbefehle) wird die Panik unverändert
// weitergereicht: Fehler fallen dort weiterhin sofort auf. Erst die
// Oberfläche setzt mit SetHandler einen Handler, der einen Absturzbericht
// schreibt und eine Meldung zeigt.
//
// Häufen sich die Paniken (Sturm: mehr als StormN in StormWindow), ist der
// Zustand vermutlich kaputt: dann wird wie früher weitergereicht und das
// Programm endet mit dem gewohnten Absturzbericht.
package safe
import (
"fmt"
"runtime/debug"
"sync"
"sync/atomic"
"time"
)
// Caught beschreibt eine abgefangene Panik.
type Caught struct {
Where string // Stelle, z. B. „ui.Update“ oder „sshx/client.go:464“
Value any // Wert aus panic(…)
Stack []byte
At time.Time
}
// Raw: Text wie bei einer echten Panik (für den Absturzbericht).
func (c Caught) Raw() string {
return fmt.Sprintf("panic: %v [recovered in %s]\n\n%s", c.Value, c.Where, c.Stack)
}
const (
StormN = 5
StormWindow = time.Minute
)
var (
handler atomic.Pointer[func(Caught)]
count atomic.Int64
mu sync.Mutex
recent []time.Time
)
// SetHandler legt fest, was mit abgefangenen Paniken passiert. nil schaltet
// das Abfangen ab (Paniken laufen dann wie gewohnt durch).
func SetHandler(fn func(Caught)) {
if fn == nil {
handler.Store(nil)
return
}
handler.Store(&fn)
}
// Active: ist ein Handler gesetzt?
func Active() bool { return handler.Load() != nil }
// Count: so viele Paniken wurden seit dem Start abgefangen.
func Count() int64 { return count.Load() }
// Recover gehört direkt hinter defer: `defer safe.Recover("wo")`.
func Recover(where string) {
if r := recover(); r != nil {
handle(where, r)
}
}
// Go startet fn nebenher mit Absturzschutz.
func Go(where string, fn func()) {
go func() {
defer Recover(where)
fn()
}()
}
// Run führt fn aus; false, wenn dabei eine Panik abgefangen wurde.
func Run(where string, fn func()) (ok bool) {
defer func() {
if r := recover(); r != nil {
handle(where, r)
ok = false
}
}()
fn()
return true
}
func handle(where string, r any) {
h := handler.Load()
if h == nil || storm(time.Now()) {
panic(r)
}
count.Add(1)
(*h)(Caught{Where: where, Value: r, Stack: debug.Stack(), At: time.Now()})
}
// storm merkt sich den Zeitpunkt und meldet, ob es zu viele waren.
func storm(now time.Time) bool {
mu.Lock()
defer mu.Unlock()
keep := recent[:0]
for _, t := range recent {
if now.Sub(t) < StormWindow {
keep = append(keep, t)
}
}
recent = append(keep, now)
return len(recent) > StormN
}
// Reset: nur für Tests (Zähler, Sturm-Fenster, Handler zurücksetzen).
func Reset() {
mu.Lock()
recent = nil
mu.Unlock()
count.Store(0)
handler.Store(nil)
}
+86
View File
@@ -0,0 +1,86 @@
package safe
import (
"strings"
"sync"
"testing"
"time"
)
func TestRunWithoutHandlerRepanics(t *testing.T) {
Reset()
defer func() {
if recover() == nil {
t.Fatal("ohne Handler muss die Panik durchlaufen")
}
}()
Run("x", func() { panic("boom") })
}
func TestRunCatches(t *testing.T) {
Reset()
defer Reset()
var got Caught
SetHandler(func(c Caught) { got = c })
if Run("ui.Update", func() { panic("boom") }) {
t.Fatal("Run meldet ok trotz Panik")
}
if got.Where != "ui.Update" || got.Value != "boom" || !strings.Contains(got.Raw(), "panic: boom") {
t.Fatalf("falsch erfasst: %+v", got)
}
if !Run("x", func() {}) {
t.Fatal("ohne Panik muss Run ok melden")
}
if Count() != 1 {
t.Fatalf("Count = %d", Count())
}
}
func TestGoCatches(t *testing.T) {
Reset()
defer Reset()
var wg sync.WaitGroup
wg.Add(1)
SetHandler(func(c Caught) { wg.Done() })
Go("bg", func() {
var xs []int
i := len(xs)
_ = xs[i] // Index außerhalb: echte Laufzeit-Panik
})
done := make(chan struct{})
go func() { wg.Wait(); close(done) }()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("Handler nicht aufgerufen")
}
}
func TestStormRepanics(t *testing.T) {
Reset()
defer Reset()
SetHandler(func(Caught) {})
for i := 0; i < StormN; i++ {
Run("x", func() { panic(i) })
}
defer func() {
if recover() == nil {
t.Fatal("beim Sturm muss die Panik durchlaufen")
}
}()
Run("x", func() { panic("zu viel") })
}
func TestStormForgets(t *testing.T) {
Reset()
defer Reset()
now := time.Now()
for i := 0; i < StormN; i++ {
if storm(now) {
t.Fatal("zu früh Sturm")
}
}
if storm(now.Add(StormWindow + time.Second)) {
t.Fatal("alte Paniken müssen vergessen werden")
}
}
+7 -2
View File
@@ -14,6 +14,8 @@ import (
"time"
"go.bug.st/serial"
"github.com/db9979/sshtermy/internal/safe"
)
// Port: eine gefundene serielle Schnittstelle.
@@ -151,13 +153,16 @@ type Stream struct {
closed atomic.Bool
}
// openPort: Variable für Tests (Gerät ohne echtes Kabel).
var openPort = serial.Open
// Open öffnet die Schnittstelle; alles, was ankommt, geht an out.
func Open(name string, baud int, frame string, out io.Writer) (*Stream, error) {
mode, err := Mode(baud, frame)
if err != nil {
return nil, err
}
p, err := serial.Open(name, mode)
p, err := openPort(name, mode)
if err != nil {
return nil, explain(name, err)
}
@@ -165,7 +170,7 @@ func Open(name string, baud int, frame string, out io.Writer) (*Stream, error) {
_ = p.SetDTR(true)
_ = p.SetRTS(true)
s := &Stream{Name: name, Done: make(chan error, 1), p: p}
go s.read(out)
safe.Go("serialx/serial.go", func() { s.read(out) })
return s, nil
}
+189
View File
@@ -0,0 +1,189 @@
package serialx
import (
"bytes"
"errors"
"strings"
"sync"
"testing"
"time"
"go.bug.st/serial"
)
// fakePort: Konsolenkabel ohne Kabel. Liefert die Stücke aus in, danach
// je nach gone: (0, nil) wie ein abgezogenes Kabel unter Linux/macOS oder
// blockiert, bis Close kommt.
type fakePort struct {
mu sync.Mutex
in [][]byte
readErr error
gone bool
closed chan struct{}
written bytes.Buffer
breaks int
dtr bool
}
func newFake(chunks ...string) *fakePort {
f := &fakePort{closed: make(chan struct{})}
for _, c := range chunks {
f.in = append(f.in, []byte(c))
}
return f
}
func (f *fakePort) Read(p []byte) (int, error) {
f.mu.Lock()
if len(f.in) > 0 {
n := copy(p, f.in[0])
f.in = f.in[1:]
f.mu.Unlock()
return n, nil
}
err, gone := f.readErr, f.gone
f.mu.Unlock()
if err != nil {
return 0, err
}
if gone {
return 0, nil
}
<-f.closed
return 0, errors.New("closed")
}
func (f *fakePort) Write(p []byte) (int, error) {
f.mu.Lock()
defer f.mu.Unlock()
return f.written.Write(p)
}
func (f *fakePort) SetMode(*serial.Mode) error { return nil }
func (f *fakePort) Drain() error { return nil }
func (f *fakePort) ResetInputBuffer() error { return nil }
func (f *fakePort) ResetOutputBuffer() error { return nil }
func (f *fakePort) SetDTR(on bool) error { f.dtr = on; return nil }
func (f *fakePort) SetRTS(bool) error { return nil }
func (f *fakePort) SetReadTimeout(time.Duration) error { return nil }
func (f *fakePort) Break(time.Duration) error { f.breaks++; return nil }
func (f *fakePort) Close() error { close(f.closed); return nil }
func (f *fakePort) GetModemStatusBits() (*serial.ModemStatusBits, error) {
return &serial.ModemStatusBits{}, nil
}
type syncBuf struct {
mu sync.Mutex
b bytes.Buffer
}
func (s *syncBuf) Write(p []byte) (int, error) { s.mu.Lock(); defer s.mu.Unlock(); return s.b.Write(p) }
func (s *syncBuf) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() }
func withFake(t *testing.T, f *fakePort) {
t.Helper()
old := openPort
openPort = func(string, *serial.Mode) (serial.Port, error) { return f, nil }
t.Cleanup(func() { openPort = old })
}
func waitDone(t *testing.T, s *Stream) error {
t.Helper()
select {
case err := <-s.Done:
return err
case <-time.After(5 * time.Second):
t.Fatal("Stream meldet kein Ende")
return nil
}
}
func TestStreamReadWriteClose(t *testing.T) {
f := newFake("Switch login: ", "\r\n")
withFake(t, f)
var out syncBuf
s, err := Open("/dev/ttyUSB0", 9600, "8N1", &out)
if err != nil {
t.Fatal(err)
}
if !f.dtr {
t.Fatal("DTR nicht gesetzt (manche Adapter schweigen sonst)")
}
deadline := time.Now().Add(2 * time.Second)
for !strings.Contains(out.String(), "login:") && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if !strings.Contains(out.String(), "Switch login: ") {
t.Fatalf("Ausgabe: %q", out.String())
}
if _, err := s.Write([]byte("admin\r")); err != nil || f.written.String() != "admin\r" {
t.Fatalf("Write: %v %q", err, f.written.String())
}
if err := s.Break(); err != nil || f.breaks != 1 {
t.Fatal("Break nicht gesendet")
}
if s.Resize(80, 24) != nil {
t.Fatal("Resize")
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
if s.Close() != nil {
t.Fatal("zweites Close")
}
if err := waitDone(t, s); err != nil {
t.Fatalf("selbst geschlossen muss nil melden: %v", err)
}
}
// Kabel gezogen: Read liefert ständig 0 Bytes ohne Fehler.
func TestStreamCableGone(t *testing.T) {
f := newFake("x")
f.gone = true
withFake(t, f)
s, err := Open("/dev/ttyUSB0", 115200, "", &syncBuf{})
if err != nil {
t.Fatal(err)
}
if err := waitDone(t, s); err == nil || !strings.Contains(err.Error(), "gone") {
t.Fatalf("abgezogenes Kabel: %v", err)
}
}
func TestStreamReadError(t *testing.T) {
f := newFake()
f.readErr = errors.New("I/O error")
withFake(t, f)
s, err := Open("COM3", 9600, "8N1", &syncBuf{})
if err != nil {
t.Fatal(err)
}
if err := waitDone(t, s); err == nil || err.Error() != "I/O error" {
t.Fatalf("Lesefehler: %v", err)
}
}
func TestOpenErrors(t *testing.T) {
if _, err := Open("COM3", 9600, "9Z9", &syncBuf{}); err == nil {
t.Fatal("kaputter Rahmen angenommen")
}
old := openPort
defer func() { openPort = old }()
openPort = func(string, *serial.Mode) (serial.Port, error) { return nil, errors.New("kaputt") }
if _, err := Open("COM9", 9600, "8N1", &syncBuf{}); err == nil || !strings.HasPrefix(err.Error(), "COM9: ") {
t.Fatalf("Fehler ohne Schnittstellenname: %v", err)
}
}
func TestPortNamesAndVendors(t *testing.T) {
if (Port{Name: "COM3"}).String() != "COM3" || (Port{Name: "COM3", Desc: "FTDI"}).String() != "COM3 (FTDI)" {
t.Fatal("Port.String")
}
for vid, want := range map[string]string{"0403": "FTDI", "067B": "Prolific", "10c4": "Silicon Labs", "1a86": "WCH", "05ad": "Cisco", "dead": "USB dead"} {
if got := usbVendor(vid); got != want {
t.Errorf("%s: %q", vid, got)
}
}
e := &AmbiguousError{Ports: []Port{{Name: "COM3"}, {Name: "COM4"}}}
if e.Error() != "several serial ports: COM3, COM4" {
t.Fatal(e.Error())
}
}
+47
View File
@@ -0,0 +1,47 @@
package sharewire
import (
"bytes"
"testing"
"github.com/db9979/sshtermy/internal/fuzzguard"
)
// Rahmen und Einladungen kommen von fremden Rechnern (Zuschauer, Vermittler):
// nichts davon darf sshTermy zum Absturz bringen.
func FuzzOpen(f *testing.F) {
key := bytes.Repeat([]byte{7}, 32)
good, _ := Seal(key, "sitzung", 3, []byte("hallo"))
f.Add(good, "sitzung")
f.Add([]byte{}, "")
f.Add(make([]byte, 41), "x")
f.Fuzz(func(t *testing.T, frame []byte, id string) {
fuzzguard.Run(t, func() {
typ, p, err := Open(key, id, frame)
if err == nil {
// nur echte Rahmen gehen durch: neu versiegelt wieder lesbar
again, _ := Seal(key, id, typ, p)
if t2, p2, err := Open(key, id, again); err != nil || t2 != typ || !bytes.Equal(p2, p) {
t.Errorf("Rundreise kaputt: %v", err)
}
}
})
})
}
func FuzzInvite(f *testing.F) {
f.Add("7-taube-kompass-ofen")
f.Add("sshtermy://zusehen/7-taube-kompass-ofen")
f.Add("https://example.org/zusehen/#7 taube")
f.Add("\x00\xff 🐟")
f.Fuzz(func(t *testing.T, s string) {
fuzzguard.Run(t, func() {
_, _ = ParseInvite(s)
_, _ = NormBase(s)
_ = IsFP(s)
if c := Clean(s, 40); len(c) > 40+4 {
t.Errorf("Clean zu lang: %d", len(c))
}
})
})
}
+9
View File
@@ -19,3 +19,12 @@ func dialAgent() (net.Conn, error) {
}
return net.Dial("unix", sock)
}
// AgentReachable: läuft ein SSH-Agent, den sshTermy erreicht (Selbstprüfung)?
func AgentReachable() error {
c, err := dialAgent()
if err != nil {
return err
}
return c.Close()
}
+10
View File
@@ -21,3 +21,13 @@ func dialAgent() (net.Conn, error) {
t := 3 * time.Second
return winio.DialPipe(pipe, &t)
}
// AgentReachable: läuft ein SSH-Agent (Pageant oder OpenSSH-Dienst), den
// sshTermy erreicht (Selbstprüfung)?
func AgentReachable() error {
c, err := dialAgent()
if err != nil {
return err
}
return c.Close()
}
+5 -1
View File
@@ -21,6 +21,7 @@ import (
"github.com/db9979/sshtermy/internal/debuglog"
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
"github.com/db9979/sshtermy/internal/sysprof"
)
@@ -461,7 +462,7 @@ func dial(ctx context.Context, c domain.Connection, o Options) (*Client, error)
cl.Remote.OS = i18n.T("Windows (OpenSSH) oder unbekannt")
}
}
go cl.keepAlive(kctx, c.KeepAlive)
safe.Go("sshx/client.go", func() { cl.keepAlive(kctx, c.KeepAlive) })
return cl, nil
}
@@ -471,6 +472,7 @@ func dial(ctx context.Context, c domain.Connection, o Options) (*Client, error)
func (c *Client) alive() bool {
done := make(chan error, 1)
go func() {
defer safe.Recover("sshx/client.go")
_, _, err := c.SendRequest("keepalive@openssh.com", true, nil)
done <- err
}()
@@ -492,6 +494,7 @@ func (c *Client) Check(d time.Duration) bool {
}
done := make(chan error, 1)
go func() {
defer safe.Recover("sshx/client.go")
_, _, err := c.SendRequest("keepalive@openssh.com", true, nil)
done <- err
}()
@@ -612,6 +615,7 @@ func (c *Client) keepAliveLoop(ctx context.Context, ping, deadAfter time.Duratio
send := func() {
inflight, sent = true, time.Now()
go func() {
defer safe.Recover("sshx/client.go")
_, _, err := c.SendRequest("keepalive@openssh.com", true, nil)
res <- err
}()
+2
View File
@@ -6,6 +6,7 @@ import (
"strings"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
)
// ErrNetDevice: Exec-Abfragen sind bei Netzwerkgeräten tabu, weil z. B.
@@ -62,6 +63,7 @@ func (c *Client) StreamScript(ctx context.Context, script string, line func(stri
return err
}
go func() {
defer safe.Recover("sshx/run.go")
<-ctx.Done()
_ = s.Close() // beendet auch das Lesen unten
}()
+178
View File
@@ -0,0 +1,178 @@
package sshx
import (
"context"
"crypto/ed25519"
"crypto/rand"
"io"
"net"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"github.com/db9979/sshtermy/internal/domain"
)
// startSFTPServer: SSH-Server mit sftp-Subsystem auf einem echten Ordner.
func startSFTPServer(t *testing.T, root string) string {
t.Helper()
_, priv, _ := ed25519.GenerateKey(rand.Reader)
signer, _ := ssh.NewSignerFromKey(priv)
cfg := &ssh.ServerConfig{PasswordCallback: func(ssh.ConnMetadata, []byte) (*ssh.Permissions, error) { return nil, nil }}
cfg.AddHostKey(signer)
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ln.Close() })
go func() {
for {
nc, err := ln.Accept()
if err != nil {
return
}
go func() {
sc, chans, reqs, err := ssh.NewServerConn(nc, cfg)
if err != nil {
return
}
defer sc.Close()
go ssh.DiscardRequests(reqs)
for nch := range chans {
ch, creqs, err := nch.Accept()
if err != nil {
continue
}
go func() {
for r := range creqs {
ok := r.Type == "subsystem" && len(r.Payload) > 4 && string(r.Payload[4:]) == "sftp"
_ = r.Reply(ok, nil)
if ok {
srv, err := sftp.NewServer(ch, sftp.WithServerWorkingDirectory(root))
if err == nil {
_ = srv.Serve()
}
ch.Close()
return
}
}
}()
}
}()
}
}()
return ln.Addr().String()
}
func TestSFTPRoundTrip(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Server-Pfade im Test sind Unix-Pfade")
}
remote := t.TempDir()
cl := dialAddr(t, startSFTPServer(t, remote), domain.DeviceServer)
r, err := cl.OpenSFTP()
if err != nil {
t.Fatal(err)
}
defer r.Close()
if r.Label() != "x" || r.Home() == "" {
t.Fatalf("Label/Home: %q %q", r.Label(), r.Home())
}
dir := r.Join(remote, "ordner", "unter")
if err := r.Mkdir(dir); err != nil {
t.Fatal(err)
}
if r.Dir(dir) != filepath.ToSlash(filepath.Join(remote, "ordner")) && r.Dir(dir) != r.Join(remote, "ordner") {
t.Fatalf("Dir: %q", r.Dir(dir))
}
f := r.Join(dir, "a.txt")
w, err := r.Create(f, 0o640)
if err != nil {
t.Fatal(err)
}
_, _ = io.WriteString(w, "hallo welt")
if err := w.Close(); err != nil {
t.Fatal(err)
}
if err := r.Rewrite(f, []byte("neu")); err != nil {
t.Fatal(err)
}
rc, err := r.Open(f)
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(rc)
rc.Close()
if string(b) != "neu" {
t.Fatalf("Inhalt: %q", b)
}
e, err := r.Stat(f)
if err != nil || e.IsDir || e.Size != 3 {
t.Fatalf("Stat: %+v %v", e, err)
}
if err := r.Chmod(f, 0o600); err != nil {
t.Fatal(err)
}
// Umbenennen überschreibt nie
g := r.Join(dir, "b.txt")
if err := r.Rewrite(g, []byte("b")); err != nil {
t.Fatal(err)
}
if err := r.Rename(f, g); err == nil || !strings.Contains(err.Error(), "b.txt") {
t.Fatalf("Umbenennen auf vorhandene Datei: %v", err)
}
h := r.Join(dir, "c.txt")
if err := r.Rename(f, h); err != nil {
t.Fatal(err)
}
es, err := r.ReadDir(dir)
if err != nil || len(es) != 2 {
t.Fatalf("ReadDir: %+v %v", es, err)
}
if _, err := r.Stat(r.Join(remote, "gibt-es-nicht")); err == nil {
t.Fatal("Stat auf fehlende Datei ohne Fehler")
}
// Kopieren in beide Richtungen mit Fortschritt
local := t.TempDir()
var pr Progress
if err := Copy(context.Background(), r, r.Join(remote, "ordner"), LocalFS{}, local, &pr); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(filepath.Join(local, "ordner", "unter", "c.txt"))
if err != nil || string(got) != "neu" {
t.Fatalf("heruntergeladen: %q %v", got, err)
}
if pr.Files.Load() != 2 {
t.Fatalf("Fortschritt Dateien: %d", pr.Files.Load())
}
up := r.Join(remote, "hoch")
_ = r.Mkdir(up)
if err := Copy(context.Background(), LocalFS{}, filepath.Join(local, "ordner"), r, up, &Progress{}); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(remote, "hoch", "ordner", "unter", "b.txt")); err != nil {
t.Fatalf("hochgeladen: %v", err)
}
n, files, err := Size(context.Background(), r, up)
if err != nil || files != 2 || n != 4 {
t.Fatalf("Size: %d %d %v", n, files, err)
}
// Abbrechen
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := Copy(ctx, r, up, LocalFS{}, t.TempDir(), &Progress{}); err == nil {
t.Fatal("abgebrochene Kopie ohne Fehler")
}
if err := r.RemoveAll(r.Join(remote, "ordner")); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(remote, "ordner")); !os.IsNotExist(err) {
t.Fatalf("RemoveAll: %v", err)
}
}
+3 -1
View File
@@ -14,6 +14,7 @@ import (
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
)
// ActiveTunnel ist ein laufendes Forwarding mit Zählern für die Oberfläche.
@@ -122,7 +123,7 @@ func (m *TunnelManager) Start(t domain.Tunnel) (*ActiveTunnel, error) {
m.active[t.ID] = a
m.mu.Unlock()
go m.serve(a)
safe.Go("sshx/tunnel.go", func() { m.serve(a) })
if t.AutoOpen && a.URL() != "" {
_ = OpenBrowser(a.URL())
}
@@ -140,6 +141,7 @@ func (m *TunnelManager) serve(a *ActiveTunnel) {
a.Conns.Add(1)
a.Total.Add(1)
go func() {
defer safe.Recover("sshx/tunnel.go")
defer a.Conns.Add(-1)
defer in.Close()
switch a.Spec.Kind {
+4 -1
View File
@@ -21,6 +21,7 @@ import (
"golang.org/x/crypto/ssh"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
)
// X11-Weiterleitung (wie ssh -X)
@@ -69,8 +70,9 @@ func (c *Client) requestX11(sess *ssh.Session) {
}
c.x11 = f
go func() {
defer safe.Recover("sshx/x11.go")
for nc := range ch {
go f.serve(nc)
safe.Go("sshx/x11.go", func() { f.serve(nc) })
}
}()
})
@@ -193,6 +195,7 @@ func (f *x11Fwd) serve(nc ssh.NewChannel) {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer safe.Recover("sshx/x11.go")
defer wg.Done()
_, _ = io.Copy(local, ch)
if cw, ok := local.(interface{ CloseWrite() error }); ok {
+29
View File
@@ -0,0 +1,29 @@
package syncx
import (
"testing"
"github.com/db9979/sshtermy/internal/fuzzguard"
)
// Die Sync-Datei liegt in einem fremden Ordner (Cloud, WebDAV, USB-Stick):
// kaputte oder manipulierte Dateien müssen sauber abgelehnt werden.
func FuzzDecode(f *testing.F) {
k, err := NewKey([]byte("ein langes sync passwort"))
if err != nil {
f.Fatal(err)
}
good, err := Encode(k, &Payload{})
if err != nil {
f.Fatal(err)
}
f.Add(good)
f.Add([]byte(`{"format":"sshtermy-sync","version":99}`))
f.Add([]byte(`{}`))
f.Fuzz(func(t *testing.T, raw []byte) {
fuzzguard.Run(t, func() {
_, _ = Decode(k, raw)
_, _ = ParseKey(string(raw))
})
})
}
+5 -1
View File
@@ -68,9 +68,13 @@ func request(ctx context.Context, method, loc string, body []byte) (*http.Respon
if user != "" {
req.SetBasicAuth(user, pass)
}
return http.DefaultClient.Do(req)
return linkClient.Do(req)
}
// linkClient: eigene Zeitgrenze, auch wenn ein Aufrufer keine setzt (ein
// hängender WebDAV-/HTTP-Server darf den Abgleich nicht ewig festhalten).
var linkClient = &http.Client{Timeout: 60 * time.Second}
// ReadLoc liest das Team-Paket von einem Ort.
func ReadLoc(ctx context.Context, loc string) ([]byte, error) {
if !IsURL(loc) {
+3 -1
View File
@@ -12,6 +12,8 @@ import (
"sync"
"sync/atomic"
"time"
"github.com/db9979/sshtermy/internal/safe"
)
// Telnet-Befehle und -Optionen.
@@ -73,7 +75,7 @@ func Dial(ctx context.Context, addr string, cols, rows int, out io.Writer) (*Con
func newConn(nc net.Conn, cols, rows int, out io.Writer) *Conn {
c := &Conn{c: nc, Done: make(chan error, 1), cols: cols, rows: rows}
go c.read(out)
safe.Go("telnet/telnet.go", func() { c.read(out) })
return c
}
+3 -1
View File
@@ -4,6 +4,8 @@ import (
"io"
"sync"
"time"
"github.com/db9979/sshtermy/internal/safe"
)
// hostQueueMax: so viel darf auf dem Weg zum Server warten. Mehr sammelt sich
@@ -28,7 +30,7 @@ type hostQueue struct {
func newHostQueue(w io.Writer) *hostQueue {
q := &hostQueue{w: w}
q.cond = sync.NewCond(&q.mu)
go q.run()
safe.Go("termemu/hostqueue.go", func() { q.run() })
return q
}
+8
View File
@@ -22,6 +22,8 @@ import (
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/vt"
"github.com/db9979/sshtermy/internal/safe"
)
// Term ist ein emuliertes Terminal für genau eine SSH-Shell.
@@ -133,6 +135,7 @@ func New(cols, rows int, toHost io.Writer) *Term {
return true
})
go func() {
defer safe.Recover("termemu/term.go")
buf := make([]byte, 4096)
for {
n, err := t.emu.Read(buf)
@@ -294,6 +297,11 @@ func (t *Term) SendText(s string) {
t.emu.SendText(s)
}
// SendRaw schickt Bytes unverändert in die Warteschlange zum Server, in
// derselben Reihenfolge wie Tasten. Kehrt sofort zurück, auch wenn die
// Verbindung hängt (anders als ein direktes Schreiben in die Shell).
func (t *Term) SendRaw(p []byte) { _, _ = t.host.Write(p) }
// Paste nutzt Bracketed Paste, wenn die Shell es eingeschaltet hat.
func (t *Term) Paste(s string) {
if t.muted.Load() {
+1 -1
View File
@@ -95,7 +95,7 @@ func (a *App) activityBlock(rb *strings.Builder, logs []*sessionlog.Log, w int,
}
if n := perDay[d]; n > 0 {
day := d
cell = a.z.click(cell, func(tea.Mouse, bool) tea.Cmd { a.jumpToDay(day); return nil })
cell = a.z.Click(cell, func(tea.Mouse, bool) tea.Cmd { a.jumpToDay(day); return nil })
}
line.WriteString(cell + " ")
}
+1 -1
View File
@@ -36,7 +36,7 @@ func (a *App) viewModeChoice(b *strings.Builder, s *session, w int) {
}
line := mark + style.Render(trunc(o.name, max(4, w-2)))
o := o
b.WriteString(a.z.click(line, func(tea.Mouse, bool) tea.Cmd {
b.WriteString(a.z.Click(line, func(tea.Mouse, bool) tea.Cmd {
s.panelFocus = true
g.auto, g.level, g.planFirst = o.auto, o.level, o.plan
return g.input.Focus()
+5 -3
View File
@@ -13,6 +13,8 @@ import (
"github.com/db9979/sshtermy/internal/agent"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safety"
"github.com/db9979/sshtermy/internal/ui/clickzone"
)
// KI-Antworten als Karten: Befehle aus Codeblöcken stehen in eigenen,
@@ -224,7 +226,7 @@ func (a *App) viewAnswer(b *strings.Builder, s *session, ans string, w int) {
arrow, hint = "▸ ", i18n.T("ausklappen")
}
head := st.AI.Render(arrow+i18n.T("Erklärung")) + st.Muted.Render(" z "+hint)
b.WriteString(a.z.click(head, func(tea.Mouse, bool) tea.Cmd {
b.WriteString(a.z.Click(head, func(tea.Mouse, bool) tea.Cmd {
q.collapsed = !q.collapsed
s.panelFocus = true
return nil
@@ -357,7 +359,7 @@ func (a *App) commandCard(s *session, i int, cd card, sel, armed bool, kind stri
if withText && (!armed || bt.key == "a") { // scharf: nur die Rückfrage zählt
txt += lipgloss.NewStyle().Foreground(st.T.Muted).Render(" " + bt.text)
}
out = append(out, a.z.click(txt, func(tea.Mouse, bool) tea.Cmd {
out = append(out, a.z.Click(txt, func(tea.Mouse, bool) tea.Cmd {
s.ask.sel = i
return bt.f()
}))
@@ -377,7 +379,7 @@ func (a *App) commandCard(s *session, i int, cd card, sel, armed bool, kind stri
content += "\n" + bar
}
card := box.Render(content)
return a.z.mark(card, zoneAction{block: true, click: func(_ tea.Mouse, double bool) tea.Cmd {
return a.z.Mark(card, clickzone.Action{Block: true, Click: func(_ tea.Mouse, double bool) tea.Cmd {
s.ask.sel, s.panelFocus = i, true
if double && cd.runnable() {
return a.cardInsert(s, i)
+27 -15
View File
@@ -25,6 +25,7 @@ import (
"image/color"
"os"
"strings"
"sync/atomic"
"time"
tea "charm.land/bubbletea/v2"
@@ -44,6 +45,8 @@ import (
"github.com/db9979/sshtermy/internal/vault"
"github.com/db9979/sshtermy/internal/version"
"github.com/db9979/sshtermy/internal/vuln"
"github.com/db9979/sshtermy/internal/ui/clickzone"
)
type screen int
@@ -88,6 +91,10 @@ const (
// App ist das Wurzel-Modell.
type App struct {
// Absturzschutz (safety.go): letztes gutes Bild, wartende Empfänger
lastView tea.View
listening atomic.Int32
// asyncModals: Rückfragen, die von selbst kamen, während schon ein Dialog
// offen war (modalguard.go). Sie überschreiben ihn nicht, sie warten.
asyncModals []*modal
@@ -222,8 +229,8 @@ type App struct {
keys keymap // aktuelle Tastenbelegung
lookSig string // Theme+Tasten, zuletzt übernommen
z zones // klickbare Bereiche des letzten Bildes
click clickState // für Doppel-/Dreifachklick
z clickzone.Map // klickbare Bereiche des letzten Bildes
click clickState // für Doppel-/Dreifachklick
pick *picker // Auswahlliste mit Suche (Jump-Host, Ordner, Tag)
@@ -261,7 +268,11 @@ func New(st *store.Store) (*App, error) {
func (a *App) listen() tea.Cmd {
ev := a.events
return func() tea.Msg { return <-ev }
return func() tea.Msg {
a.listening.Add(1) // safety.go: nach abgefangenem Fehler neu anstoßen?
defer a.listening.Add(-1)
return <-ev
}
}
type tickMsg time.Time
@@ -289,7 +300,7 @@ func (a *App) checkUpdate() tea.Cmd {
// checkRelease: Variable für Tests.
var checkRelease = update.CheckAged
func (a *App) Init() tea.Cmd {
func (a *App) init0() tea.Cmd {
var intro tea.Cmd
if a.intro != nil {
a.intro.start = time.Now()
@@ -314,7 +325,7 @@ func (a *App) byID(id int) *session {
return nil
}
func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
func (a *App) update0(msg tea.Msg) (tea.Model, tea.Cmd) {
if a.scr != scrManager {
a.mgr.forTab = false // „+“-Auswahl gilt nur, solange der Manager offen ist
}
@@ -614,6 +625,10 @@ func (a *App) coreMsg(msg tea.Msg) (tea.Cmd, bool) {
// featureMsg reicht die Nachricht an die Bereiche weiter (Broadcast, Sync,
// KI, Dateien …); jeder nimmt nur seine eigenen.
func (a *App) featureMsg(msg tea.Msg) (tea.Cmd, bool) {
if m, ok := msg.(doctorMsg); ok { // Selbstprüfung (doctor.go)
a.doctorDone(m)
return nil, true
}
if m, ok := msg.(palFindMsg); ok { // „Wo finde ich …?“ (palask.go)
return a.palFindDone(m), true
}
@@ -935,11 +950,8 @@ func (a *App) onTick() tea.Cmd {
// ---------------------------------------------------------------- Layout
// View: gemessen, bei Ausgabeflut gedrosselt (perf.go).
func (a *App) View() tea.View { return a.view() }
func (a *App) viewFrame() tea.View {
a.z.reset()
a.z.Reset()
var body string
var cur *tea.Cursor
switch a.scr {
@@ -996,9 +1008,9 @@ func (a *App) viewFrame() tea.View {
case scrScan:
body = a.frame(a.viewScan(), a.scanKeys())
}
body = a.z.scan(body, 0, 0)
body = a.z.Scan(body, 0, 0)
if a.lock != nil {
a.z.reset() // gesperrt: nichts klickbar, nichts zu sehen
a.z.Reset() // gesperrt: nichts klickbar, nichts zu sehen
body, cur = a.viewLock(), nil
} else if a.modal != nil {
body = a.overlay(body, a.modalView())
@@ -1021,7 +1033,7 @@ func (a *App) viewFrame() tea.View {
body = a.withPerf(body)
}
if a.intro != nil && introFits(a.w, a.h) {
a.z.reset() // während der Animation ist nichts klickbar
a.z.Reset() // während der Animation ist nichts klickbar
body, cur = a.viewIntro(), nil
}
if cur != nil && !a.s.T.Dark {
@@ -1052,7 +1064,7 @@ func (a *App) headerLeft() string {
logo := a.logoChip(">_ " + version.Name) // gradient.go
if a.scr == scrTerminal && len(a.sessions) > 0 {
// Klick aufs Logo: Manager für einen weiteren Tab, wie „+“ (tabs.go)
return a.z.click(logo, func(tea.Mouse, bool) tea.Cmd { return a.openNewTab() })
return a.z.Click(logo, func(tea.Mouse, bool) tea.Cmd { return a.openNewTab() })
}
return logo
}
@@ -1276,8 +1288,8 @@ func (a *App) overlay(base, box string) string {
if k, run := a.fadeLevel(); run && !a.fx.out {
box = fadeANSI(box, a.s.T, k)
}
a.z.rects = a.z.rects[:0]
box = a.z.scan(box, x, y)
a.z.ClearRects()
box = a.z.Scan(box, x, y)
return stamp(a.overlayBackground(base, x, y, bw, bh), box, x, y, a.w)
}
+6 -4
View File
@@ -18,6 +18,8 @@ import (
"github.com/db9979/sshtermy/internal/broadcast"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/ui/clickzone"
)
const (
@@ -137,16 +139,16 @@ func (a *App) bcTile(i, w, h, bodyH int) (string, int) {
}
tb.WriteString(bs.Render(string(bc[0]) + strings.Repeat("─", inner) + string(bc[1])))
i2 := i
tile := a.z.mark(tb.String(), zoneAction{
block: true,
click: func(_ tea.Mouse, double bool) tea.Cmd {
tile := a.z.Mark(tb.String(), clickzone.Action{
Block: true,
Click: func(_ tea.Mouse, double bool) tea.Cmd {
b.sel = i2
if double {
b.zoom = !b.zoom
}
return nil
},
wheel: func(up bool) tea.Cmd {
Wheel: func(up bool) tea.Cmd {
if up {
b.scroll = max(0, b.scroll-3)
} else {
+5 -3
View File
@@ -18,6 +18,7 @@ import (
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/runbook"
"github.com/db9979/sshtermy/internal/safe"
"github.com/db9979/sshtermy/internal/sshx"
)
@@ -363,6 +364,7 @@ func (a *App) bcStart(targets []domain.Connection, steps []string, per [][]strin
job.Canary, job.StopAfter = !b.noCanary, bcStopAfter
}
go func() {
defer safe.Recover("ui/broadcast.go")
broadcast.Run(ctx, job, dial, func(i int, r broadcast.Result) { ev <- bcUpdateMsg{seq, i, r} })
ev <- bcDoneMsg{seq}
}()
@@ -601,7 +603,7 @@ func (a *App) viewBcSetup() string {
m = s.Accent.Render("▌ ")
st = lipgloss.NewStyle().Foreground(s.T.Text).Bold(true).Width(20)
}
return m + a.z.click(st.Render(title), func(tea.Mouse, bool) tea.Cmd { return b.setFocus(focus) })
return m + a.z.Click(st.Render(title), func(tea.Mouse, bool) tea.Cmd { return b.setFocus(focus) })
}
// Hosts
@@ -646,7 +648,7 @@ func (a *App) viewBcSetup() string {
line = s.Selected.Width(w - 4).Render(ansi.Strip(line))
}
i, id := i, c.ID
line = a.z.click(line, func(tea.Mouse, bool) tea.Cmd {
line = a.z.Click(line, func(tea.Mouse, bool) tea.Cmd {
b.cur, b.picked[id], b.err = i, !b.picked[id], ""
return b.setFocus(bcFocusHosts)
})
@@ -663,7 +665,7 @@ func (a *App) viewBcSetup() string {
p = s.Selected.Render(" " + trunc(n, 24) + " ")
}
i := i
parts = append(parts, a.z.click(p, func(tea.Mouse, bool) tea.Cmd { b.src = i; return b.setFocus(bcFocusSource) }))
parts = append(parts, a.z.Click(p, func(tea.Mouse, bool) tea.Cmd { b.src = i; return b.setFocus(bcFocusSource) }))
}
src := strings.Join(parts, "")
if lipgloss.Width(src) > w-24 {
+222
View File
@@ -0,0 +1,222 @@
// Package clickzone: klickbare Bereiche im fertigen Bild (Maus), aus
// internal/ui ausgelagert (erster Schritt der Aufteilung).
package clickzone
import (
"math"
"strconv"
"strings"
tea "charm.land/bubbletea/v2"
"github.com/charmbracelet/x/ansi"
)
// Klickbare Bereiche (Zonen)
//
// Beim Zeichnen wird anklickbarer Text mit zwei unsichtbaren Markern
// umschlossen (CSI <n> z, eine Sequenz, die kein Terminal kennt und die
// lipgloss als Breite 0 behandelt). Nach dem Zusammensetzen eines Bildes
// sucht Map.Scan die Marker, merkt sich die Rechtecke und entfernt die
// Marker wieder. So bleibt jede Ansicht frei in ihrem Layout, und die
// Mausbehandlung muss keine Positionen nachrechnen.
const Base = 71000
type Action struct {
Click func(m tea.Mouse, double bool) tea.Cmd // nil = nicht klickbar
Menu func(m tea.Mouse) tea.Cmd // Rechts- oder Mittelklick, nil = keiner
Wheel func(up bool) tea.Cmd // nil = Rad geht weiter nach außen
Block bool // rechteckiger Block (Box), sonst Fließtext
Row int // Manager: Zeile+1 als Ziel beim Ziehen (0 = keins); Dateien: Eintrag+1
Pane int // Dateien: Seite+1 (0 = keine)
Tab int // Tab-Leiste: Tab+1 als Ziel beim Ziehen (0 = keins)
Tip func() string // Karte beim Verweilen der Maus (motion.go)
}
type Rect struct {
X0, Y0, X1, Y1 int // inklusive
id int
block bool
}
func (r Rect) Contains(x, y int) bool {
if y < r.Y0 || y > r.Y1 {
return false
}
if r.Y0 == r.Y1 || r.block {
return x >= r.X0 && x <= r.X1
}
// mehrzeilig: wie Fließtext (erste Zeile ab x0, letzte bis x1)
switch y {
case r.Y0:
return x >= r.X0
case r.Y1:
return x <= r.X1
}
return true
}
type Map struct {
acts []Action
rects []Rect
}
func (z *Map) Reset() { z.acts, z.rects = z.acts[:0], z.rects[:0] }
// ClearRects vergisst nur die Rechtecke (Overlay wird neu vermessen).
func (z *Map) ClearRects() { z.rects = z.rects[:0] }
func Marker(id int) string { return "\x1b[" + strconv.Itoa(Base+id) + "z" }
// Mark umschließt s mit einer Zone.
func (z *Map) Mark(s string, act Action) string {
if s == "" {
return s
}
id := len(z.acts)
z.acts = append(z.acts, act)
m := Marker(id)
return m + s + m
}
func (z *Map) Click(s string, f func(m tea.Mouse, double bool) tea.Cmd) string {
return z.Mark(s, Action{Click: f})
}
// Scan entfernt die Marker aus s und merkt sich die Rechtecke, verschoben
// um ox/oy (für Overlays).
func (z *Map) Scan(s string, ox, oy int) string {
if !strings.Contains(s, "\x1b[") {
return s
}
var out strings.Builder
out.Grow(len(s))
open := map[int][2]int{}
x, y := 0, 0
state := byte(0)
for len(s) > 0 {
seq, width, n, newState := ansi.DecodeSequence(s, state, nil)
state = newState
if n <= 0 {
break
}
if seq == "\n" {
x, y = 0, y+1
out.WriteString(seq)
s = s[n:]
continue
}
if width == 0 && len(seq) > 3 && seq[0] == 0x1b && seq[1] == '[' && seq[len(seq)-1] == 'z' {
if v, err := strconv.Atoi(seq[2 : len(seq)-1]); err == nil && v >= Base && v-Base < len(z.acts) {
id := v - Base
if st, ok := open[id]; ok {
delete(open, id)
if x > st[0] || y > st[1] {
z.rects = append(z.rects, Rect{st[0] + ox, st[1] + oy, x - 1 + ox, y + oy, id, z.acts[id].Block})
}
} else {
open[id] = [2]int{x, y}
}
s = s[n:]
continue
}
}
out.WriteString(seq)
x += width
s = s[n:]
}
for id, st := range open { // Ende abgeschnitten: bis zum Bildende
z.rects = append(z.rects, Rect{st[0] + ox, st[1] + oy, 1 << 20, y + oy, id, z.acts[id].Block})
}
return out.String()
}
// At: die innerste (zuletzt geöffnete, also kleinste) Zone unter x/y, die
// die gewünschte Aktion hat.
func (z *Map) At(x, y int, wheel bool) *Action {
var best *Action
bestArea := math.MaxInt
for _, r := range z.rects {
if !r.Contains(x, y) {
continue
}
act := &z.acts[r.id]
if (wheel && act.Wheel == nil) || (!wheel && act.Click == nil) {
continue
}
area := (r.Y1-r.Y0+1)*4096 + (r.X1 - r.X0)
if area <= bestArea {
best, bestArea = act, area
}
}
return best
}
// TipAt: die innerste Zone unter x/y mit Hover-Karte.
func (z *Map) TipAt(x, y int) (*Action, Rect) {
var best *Action
var br Rect
bestArea := math.MaxInt
for _, r := range z.rects {
if !r.Contains(x, y) || z.acts[r.id].Tip == nil {
continue
}
if area := (r.Y1-r.Y0+1)*4096 + (r.X1 - r.X0); area <= bestArea {
best, br, bestArea = &z.acts[r.id], r, area
}
}
return best, br
}
// AtMenu: die innerste Zone unter x/y mit Rechtsklick-Aktion (Tabs).
func (z *Map) AtMenu(x, y int) *Action {
var best *Action
bestArea := math.MaxInt
for _, r := range z.rects {
if !r.Contains(x, y) || z.acts[r.id].Menu == nil {
continue
}
if area := (r.Y1-r.Y0+1)*4096 + (r.X1 - r.X0); area <= bestArea {
best, bestArea = &z.acts[r.id], area
}
}
return best
}
// RowAt: Zeile (row-1) unter x/y für das Ziehen im Manager, sonst -1.
func (z *Map) RowAt(x, y int) int {
for _, r := range z.rects {
if y >= r.Y0 && y <= r.Y1 && z.acts[r.id].Row > 0 && z.acts[r.id].Pane == 0 { // nur die Zeile zählt
_ = x
return z.acts[r.id].Row - 1
}
}
return -1
}
// TabAt: Tab (tab-1) unter x/y für das Ziehen in der Tab-Leiste, sonst -1.
func (z *Map) TabAt(x, y int) int {
for _, r := range z.rects {
if z.acts[r.id].Tab > 0 && r.Contains(x, y) {
return z.acts[r.id].Tab - 1
}
}
return -1
}
// FileAt: Seite und Eintrag des Dateibrowsers unter x/y (je -1 = keiner).
func (z *Map) FileAt(x, y int) (side, row int) {
side, row = -1, -1
bestArea := math.MaxInt
for _, r := range z.rects {
act := z.acts[r.id]
if act.Pane == 0 || !r.Contains(x, y) {
continue
}
area := (r.Y1-r.Y0+1)*4096 + (r.X1 - r.X0)
if area <= bestArea {
bestArea, side, row = area, act.Pane-1, act.Row-1
}
}
return side, row
}
@@ -1,4 +1,4 @@
package ui
package clickzone
import (
"strings"
@@ -10,17 +10,17 @@ import (
)
func TestZonesSurviveLayout(t *testing.T) {
var z zones
var z Map
hit := ""
mk := func(name, s string) string {
return z.click(s, func(tea.Mouse, bool) tea.Cmd { hit = name; return nil })
return z.Click(s, func(tea.Mouse, bool) tea.Cmd { hit = name; return nil })
}
st := lipgloss.NewStyle().Background(lipgloss.Color("#333")).Padding(0, 1)
left := lipgloss.NewStyle().Width(20).Render("Liste\n" + st.Render(mk("a", "Eintrag A")) + "\n" + mk("b", "Eintrag B"))
right := lipgloss.NewStyle().Width(30).Render("Detail " + mk("c", lipgloss.NewStyle().Bold(true).Render("Knopf")))
body := lipgloss.JoinHorizontal(lipgloss.Top, left, "│", right)
body = lipgloss.Place(60, 6, lipgloss.Center, lipgloss.Center, body)
clean := z.scan(body, 0, 0)
clean := z.Scan(body, 0, 0)
if strings.Contains(clean, "71000z") || strings.Contains(clean, "\x1b[710") {
t.Fatalf("Marker nicht entfernt: %q", clean)
}
@@ -37,14 +37,14 @@ func TestZonesSurviveLayout(t *testing.T) {
for _, c := range []struct{ word, want string }{{"Eintrag A", "a"}, {"Eintrag B", "b"}, {"Knopf", "c"}} {
x, y := find(c.word)
hit = ""
if act := z.at(x+2, y, false); act != nil {
act.click(tea.Mouse{}, false)
if act := z.At(x+2, y, false); act != nil {
act.Click(tea.Mouse{}, false)
}
if hit != c.want {
t.Errorf("%s bei %d,%d: Treffer %q, erwartet %q", c.word, x+2, y, hit, c.want)
}
}
if act := z.at(0, 0, false); act != nil {
if act := z.At(0, 0, false); act != nil {
t.Errorf("Treffer außerhalb aller Zonen")
}
}
+1 -1
View File
@@ -281,7 +281,7 @@ func (a *App) viewCmdSets() string {
line = s.Text.Render(name) + " " + s.Muted.Render(id) + " " + s.Muted.Render(src) + " "
}
i := i
b.WriteString(a.z.click(" "+mark+line+state, func(_ tea.Mouse, double bool) tea.Cmd {
b.WriteString(a.z.Click(" "+mark+line+state, func(_ tea.Mouse, double bool) tea.Cmd {
c.sel = i
if double {
a.modal = textModal(rows[i].Set.Name, a.cmdsetDetails(rows[i]))
+2 -2
View File
@@ -215,7 +215,7 @@ func (a *App) viewColors() string {
if th.Name == ThemeByName(e.c.Base).Name {
chip = s.Badge.Foreground(t.Accent).Bold(true).Render("✓ " + short)
}
line += a.z.click(chip, func(tea.Mouse, bool) tea.Cmd {
line += a.z.Click(chip, func(tea.Mouse, bool) tea.Cmd {
e.sel, e.c = 0, domain.CustomColors{Base: th.Name}
a.previewColors()
return nil
@@ -245,7 +245,7 @@ func (a *App) viewColors() string {
name = s.Text.Render(name)
}
row := name + sw + " " + val + mark
b.WriteString(a.z.click(row, func(_ tea.Mouse, double bool) tea.Cmd {
b.WriteString(a.z.Click(row, func(_ tea.Mouse, double bool) tea.Cmd {
e.sel = i + 1
if double {
e.editing, e.buf = true, hexOf(f.of(CustomTheme(e.c)))
+1 -1
View File
@@ -91,7 +91,7 @@ func (a *App) companionLine(s *session) string {
l += strings.Repeat(" ", max(0, a.w-lipgloss.Width(l)-lipgloss.Width(end))) + end
out[i] = ansi.Truncate(l, a.w, "")
}
return a.z.click(strings.Join(out, "\n"), func(tea.Mouse, bool) tea.Cmd { return a.toggleCompanionBar(s) })
return a.z.Click(strings.Join(out, "\n"), func(tea.Mouse, bool) tea.Cmd { return a.toggleCompanionBar(s) })
}
// toggleCompanionBar: Leiste ein/aus (Taste, Klick).
+3
View File
@@ -12,6 +12,7 @@ import (
"github.com/db9979/sshtermy/internal/detach"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
"github.com/db9979/sshtermy/internal/termemu"
"github.com/db9979/sshtermy/internal/version"
)
@@ -100,6 +101,7 @@ func (a *App) toggleDetach(s *session) tea.Cmd {
s.panelFocus = false
sid, ev := s.id, a.events
go func() {
defer safe.Recover("ui/detach.go")
c, cols, rows, err := srv.Accept(20 * time.Second)
ev <- detachConnMsg{sid, srv, c, cols, rows, err}
}()
@@ -148,6 +150,7 @@ func (a *App) onDetachConn(m detachConnMsg) {
// Tasten und Größe aus dem Fenster
sid, ev, c := s.id, a.events, m.conn
go func() {
defer safe.Recover("ui/detach.go")
for {
e, err := c.Read()
if err != nil {
+58
View File
@@ -0,0 +1,58 @@
package ui
import (
"context"
"strings"
"time"
tea "charm.land/bubbletea/v2"
"github.com/db9979/sshtermy/internal/doctor"
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/llm"
)
// Selbstprüfung (internal/doctor) aus der Palette: wie „sshtermy doctor“,
// dazu der KI-Endpunkt (dafür muss der Tresor offen sein). Das Ergebnis
// steht in einem Textfenster, c kopiert es für den Fehlerbericht.
type doctorMsg struct{ text string }
func (a *App) runDoctor() tea.Cmd {
a.flash(i18n.T("Selbstprüfung läuft …"))
dir := a.st.Dir
chain := a.st.LLM().Chain()
return func() tea.Msg {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
rs := doctor.Run(ctx, doctor.Env{Dir: dir, Extra: []doctor.Check{aiCheck(chain[0])}})
return doctorMsg{doctor.Format(rs)}
}
}
// aiCheck: antwortet der eingestellte KI-Endpunkt? (ohne Schlüssel im Text)
func aiCheck(cfg domain.LLMConfig) doctor.Check {
return func(ctx context.Context) doctor.Result {
name := i18n.T("KI")
if cfg.Model == "" && cfg.BaseURL == "" {
return doctor.Result{Name: name, Status: doctor.Info, Detail: i18n.T("nicht eingerichtet")}
}
what := cfg.Model
if what == "" {
what = string(cfg.Provider)
}
cctx, cancel := context.WithTimeout(ctx, testTimeout(cfg))
defer cancel()
if err := llm.Probe(cctx, cfg); err != nil {
return doctor.Result{Name: name, Status: doctor.Warn, Detail: what + i18n.T(" antwortet nicht: ") + err.Error()}
}
return doctor.Result{Name: name, Status: doctor.OK, Detail: what + i18n.T(" antwortet")}
}
}
func (a *App) doctorDone(m doctorMsg) {
md := textModal(i18n.T("Selbstprüfung"), strings.Split(strings.TrimRight(m.text, "\n"), "\n"))
md.copy = m.text
a.modal = md
}
+46
View File
@@ -0,0 +1,46 @@
package ui
import (
"context"
"strings"
"testing"
"github.com/db9979/sshtermy/internal/doctor"
"github.com/db9979/sshtermy/internal/domain"
)
func TestDoctorModal(t *testing.T) {
a := newPaletteTestApp(t)
a.modal = nil
a.Update(doctorMsg{"✓ Datenordner beschreibbar\n\nAlles in Ordnung.\n"})
if a.modal == nil || a.modal.kind != mText || a.modal.title != "Selbstprüfung" {
t.Fatalf("kein Ergebnisfenster: %+v", a.modal)
}
if !strings.Contains(a.modal.copy, "Alles in Ordnung.") {
t.Fatal("c kopiert nicht das Ergebnis")
}
}
func TestDoctorAICheck(t *testing.T) {
r := aiCheck(domain.LLMConfig{})(context.Background())
if r.Status != doctor.Info {
t.Fatalf("ohne KI: %+v", r)
}
r = aiCheck(domain.LLMConfig{Provider: domain.ProviderOllama, BaseURL: "http://127.0.0.1:1", Model: "test", TimeoutSec: 2})(context.Background())
if r.Status != doctor.Warn || !strings.HasPrefix(r.Detail, "test") {
t.Fatalf("KI nicht erreichbar: %+v", r)
}
}
func TestDoctorInPalette(t *testing.T) {
a := newPaletteTestApp(t)
found := false
for _, it := range a.palMenuItems() {
if it.menu == "help/debug" && strings.HasPrefix(it.label, "Selbstprüfung") {
found = true
}
}
if !found {
t.Fatal("Selbstprüfung fehlt unter Hilfe › Fehlersuche")
}
}
@@ -1,4 +1,6 @@
package ui
// Package dropped erkennt Dateien, die ins Terminalfenster gezogen wurden
// (aus internal/ui ausgelagert, erster Schritt der Aufteilung).
package dropped
import (
"net/url"
@@ -20,16 +22,16 @@ import (
// GNOME/Konsole '/home/me/My File.txt' '/home/me/b.txt'
// manche Linux-DEs file:///home/me/My%20File.txt
//
// droppedPaths erkennt das: Nur wenn der eingefügte Text ausschließlich aus
// Paths erkennt das: Nur wenn der eingefügte Text ausschließlich aus
// absoluten Pfaden besteht, die es auf diesem Rechner gibt, gilt er als
// „abgelegte Dateien“. Sonst ist es normaler Text.
const maxDropped = 500
const Max = 500
// droppedPaths: die abgelegten Dateien, oder nil, wenn der Text keine ist.
func droppedPaths(text string) []string {
toks := splitDropped(text, runtime.GOOS == "windows")
if len(toks) == 0 || len(toks) > maxDropped {
// Paths: die abgelegten Dateien, oder nil, wenn der Text keine ist.
func Paths(text string) []string {
toks := Split(text, runtime.GOOS == "windows")
if len(toks) == 0 || len(toks) > Max {
return nil
}
for _, p := range toks {
@@ -40,10 +42,10 @@ func droppedPaths(text string) []string {
return toks
}
// splitDropped zerlegt den Text in Pfade (ohne Prüfung, ob es sie gibt).
// Split zerlegt den Text in Pfade (ohne Prüfung, ob es sie gibt).
// nil, wenn ein Teil kein absoluter Pfad ist. win: Backslash ist dann
// Pfadtrenner und kein Fluchtzeichen.
func splitDropped(text string, win bool) []string {
func Split(text string, win bool) []string {
text = strings.TrimSpace(strings.TrimPrefix(text, "\ufeff"))
if text == "" {
return nil
@@ -101,7 +103,7 @@ func splitDropped(text string, win bool) []string {
p = p[1:] // /C:/x → C:/x
}
}
if !isAbsPath(p, win) {
if !IsAbs(p, win) {
return nil
}
out[i] = p
@@ -109,7 +111,7 @@ func splitDropped(text string, win bool) []string {
return out
}
func isAbsPath(p string, win bool) bool {
func IsAbs(p string, win bool) bool {
if !win {
return strings.HasPrefix(p, "/")
}
@@ -1,4 +1,4 @@
package ui
package dropped
import (
"os"
@@ -29,7 +29,7 @@ func TestSplitDropped(t *testing.T) {
{`/tmp`, true, nil}, // unter Windows nicht absolut
}
for _, c := range cases {
if got := splitDropped(c.in, c.win); !reflect.DeepEqual(got, c.want) {
if got := Split(c.in, c.win); !reflect.DeepEqual(got, c.want) {
t.Errorf("splitDropped(%q, %v) = %q, want %q", c.in, c.win, got, c.want)
}
}
@@ -44,10 +44,10 @@ func TestDroppedPathsMustExist(t *testing.T) {
if filepath.Separator != '/' {
t.Skip("Pfade im Test sind Unix-Schreibweise")
}
if got := droppedPaths("'" + a + "' "); !reflect.DeepEqual(got, []string{a}) {
if got := Paths("'" + a + "' "); !reflect.DeepEqual(got, []string{a}) {
t.Fatalf("got %q", got)
}
if got := droppedPaths("'" + a + "' " + filepath.Join(dir, "fehlt")); got != nil {
if got := Paths("'" + a + "' " + filepath.Join(dir, "fehlt")); got != nil {
t.Fatalf("fehlende Datei: got %q", got)
}
}
+5 -3
View File
@@ -15,6 +15,8 @@ import (
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/sshx"
"github.com/db9979/sshtermy/internal/ui/clickzone"
)
// Orte und Verlauf im Dateien-Fenster (F5)
@@ -339,9 +341,9 @@ func (a *App) viewPlacesBar(s *session, w, h int) string {
style = st.Selected.Width(w)
}
target := pl.path
b.WriteString(a.z.mark(style.Render(label), zoneAction{
click: func(tea.Mouse, bool) tea.Cmd { return a.goPlace(s, side, target) },
tip: func() string { return target },
b.WriteString(a.z.Mark(style.Render(label), clickzone.Action{
Click: func(tea.Mouse, bool) tea.Cmd { return a.goPlace(s, side, target) },
Tip: func() string { return target },
}) + "\n")
n++
}
+15 -11
View File
@@ -16,6 +16,10 @@ import (
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/sshx"
"github.com/db9979/sshtermy/internal/ui/clickzone"
"github.com/db9979/sshtermy/internal/ui/dropped"
)
// Dateien (F5): links lokal, rechts der Server, per SFTP über dieselbe
@@ -417,7 +421,7 @@ func (a *App) filesPaste(s *session, m tea.PasteMsg) tea.Cmd {
*f.mkdir, cmd = f.mkdir.Update(m)
return cmd
}
if paths := droppedPaths(m.Content); paths != nil {
if paths := dropped.Paths(m.Content); paths != nil {
return a.uploadDropped(s, paths)
}
a.flash(i18n.T("Hier lassen sich nur Dateien aus dem Explorer/Finder ablegen"))
@@ -445,7 +449,7 @@ func (a *App) filesDragMouse(s *session, msg tea.MouseMsg) tea.Cmd {
f := &s.files
d := f.drag
m := msg.Mouse()
side, row := a.z.fileAt(m.X, m.Y)
side, row := a.z.FileAt(m.X, m.Y)
switch msg.(type) {
case tea.MouseMotionMsg:
d.over, d.overRow = side, row
@@ -823,9 +827,9 @@ func (a *App) viewPane(s *session, side, w, h int) string {
line = st.Text.Render(line)
}
i := i
line = a.z.mark(line, zoneAction{pane: side + 1, row: i + 1,
click: func(m tea.Mouse, double bool) tea.Cmd { return a.entryClick(s, side, i, m, double) },
menu: func(m tea.Mouse) tea.Cmd { return a.fileMenu(s, side, i, m.X, m.Y) },
line = a.z.Mark(line, clickzone.Action{Pane: side + 1, Row: i + 1,
Click: func(m tea.Mouse, double bool) tea.Cmd { return a.entryClick(s, side, i, m, double) },
Menu: func(m tea.Mouse) tea.Cmd { return a.fileMenu(s, side, i, m.X, m.Y) },
})
b.WriteString(line + "\n")
}
@@ -837,12 +841,12 @@ func (a *App) viewPane(s *session, side, w, h int) string {
list += "\n" + a.viewPeek(s, p, side, w, peekH)
}
box := lipgloss.NewStyle().Width(w).Height(h).MaxHeight(h).Render(list)
return a.z.mark(box, zoneAction{
block: true,
pane: side + 1,
click: func(tea.Mouse, bool) tea.Cmd { f.side = side; return nil },
menu: func(m tea.Mouse) tea.Cmd { return a.fileMenu(s, side, -1, m.X, m.Y) },
wheel: func(up bool) tea.Cmd {
return a.z.Mark(box, clickzone.Action{
Block: true,
Pane: side + 1,
Click: func(tea.Mouse, bool) tea.Cmd { f.side = side; return nil },
Menu: func(m tea.Mouse) tea.Cmd { return a.fileMenu(s, side, -1, m.X, m.Y) },
Wheel: func(up bool) tea.Cmd {
f.side = side
if up {
p.sel = max(0, p.sel-3)
+13 -11
View File
@@ -15,6 +15,8 @@ import (
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/packx"
"github.com/db9979/sshtermy/internal/sshx"
"github.com/db9979/sshtermy/internal/ui/clickzone"
)
// Dateien (F5) mit der Maus
@@ -154,7 +156,7 @@ func (a *App) filesPaneTitle(s *session, f *filesState, side, w int) string {
if active {
ts = st.TabActive.Foreground(st.T.Accent)
}
tr := a.z.click(ts.Render(title), func(tea.Mouse, bool) tea.Cmd { f.side = side; return a.filesPeek(s) })
tr := a.z.Click(ts.Render(title), func(tea.Mouse, bool) tea.Cmd { f.side = side; return a.filesPeek(s) })
// Knöpfe rechts (nur wenn Platz ist)
btn := lipgloss.NewStyle().Background(st.T.Surface2).Foreground(st.T.Accent)
@@ -178,9 +180,9 @@ func (a *App) filesPaneTitle(s *session, f *filesState, side, w int) string {
if w >= 48 {
for _, b := range buttons {
b := b
bar += " " + a.z.mark(btn.Render(" "+b.label+" "), zoneAction{
click: func(tea.Mouse, bool) tea.Cmd { f.side = side; return b.run() },
tip: func() string { return b.tip },
bar += " " + a.z.Mark(btn.Render(" "+b.label+" "), clickzone.Action{
Click: func(tea.Mouse, bool) tea.Cmd { f.side = side; return b.run() },
Tip: func() string { return b.tip },
})
}
}
@@ -207,9 +209,9 @@ func (a *App) filesPaneTitle(s *session, f *filesState, side, w int) string {
if i == len(parts)-1 {
style = st.Text
}
shown = append(shown, a.z.mark(style.Render(label), zoneAction{
click: func(tea.Mouse, bool) tea.Cmd { f.side = side; p.goTo(target, f.hidden); return nil },
tip: func() string { return target },
shown = append(shown, a.z.Mark(style.Render(label), clickzone.Action{
Click: func(tea.Mouse, bool) tea.Cmd { f.side = side; p.goTo(target, f.hidden); return nil },
Tip: func() string { return target },
}))
used += wid
}
@@ -243,9 +245,9 @@ func (a *App) paneHeader(p *pane, f *filesState, side, nameW, sizeW, dateW int)
if right {
txt = fmt.Sprintf("%*s", wid, trunc(label, wid))
}
return a.z.mark(style.Render(txt), zoneAction{
click: func(tea.Mouse, bool) tea.Cmd { f.side = side; p.sortClick(c, f.hidden); return nil },
tip: func() string { return i18n.T("sortieren (s)") },
return a.z.Mark(style.Render(txt), clickzone.Action{
Click: func(tea.Mouse, bool) tea.Cmd { f.side = side; p.sortClick(c, f.hidden); return nil },
Tip: func() string { return i18n.T("sortieren (s)") },
})
}
return " " + col(sortName, nameW, false) + " " + col(sortSize, sizeW, true) + " " + col(sortTime, dateW, true)
@@ -599,7 +601,7 @@ func (a *App) filesBack(s *session, x, y int) tea.Cmd {
if f.panes[0] == nil {
return nil
}
side, _ := a.z.fileAt(x, y)
side, _ := a.z.FileAt(x, y)
if side < 0 {
side = f.side
}
+9 -7
View File
@@ -20,6 +20,8 @@ import (
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/sshx"
"github.com/db9979/sshtermy/internal/ui/clickzone"
)
// Datei ansehen (Dateien, F5)
@@ -750,7 +752,7 @@ func (a *App) viewPeek(s *session, p *pane, side int, w, h int) string {
body = append(body, "")
}
b.WriteString(strings.Join(body[:rows], "\n"))
return a.z.mark(lipgloss.NewStyle().Width(w).Height(h).MaxHeight(h).Render(b.String()), zoneAction{block: true, click: func(tea.Mouse, bool) tea.Cmd {
return a.z.Mark(lipgloss.NewStyle().Width(w).Height(h).MaxHeight(h).Render(b.String()), clickzone.Action{Block: true, Click: func(tea.Mouse, bool) tea.Cmd {
return a.openEntry(s, side, p.sel)
}})
}
@@ -811,7 +813,7 @@ func (a *App) viewFileView(s *session, w, h int) string {
if v.follow {
info += i18n.T(" · liest mit")
}
closeBtn := a.z.click(st.Danger.Render(i18n.T(" × zu ")), func(tea.Mouse, bool) tea.Cmd { f.view = nil; return nil })
closeBtn := a.z.Click(st.Danger.Render(i18n.T(" × zu ")), func(tea.Mouse, bool) tea.Cmd { f.view = nil; return nil })
tag := st.TabActive.Foreground(st.T.Accent).Render(i18n.T("Ansehen"))
if v.follow {
tag = st.TabActive.Foreground(st.T.OK).Render(i18n.T("Mitlesen"))
@@ -899,10 +901,10 @@ func (a *App) viewFileView(s *session, w, h int) string {
lines = append(lines, "")
}
text := lipgloss.NewStyle().Width(w).Height(bodyH).MaxHeight(bodyH).Render(strings.Join(lines[:bodyH], "\n"))
text = a.z.mark(text, zoneAction{
block: true,
click: func(m tea.Mouse, double bool) tea.Cmd { return a.viewClick(s, m, double) },
menu: func(tea.Mouse) tea.Cmd {
text = a.z.Mark(text, clickzone.Action{
Block: true,
Click: func(m tea.Mouse, double bool) tea.Cmd { return a.viewClick(s, m, double) },
Menu: func(tea.Mouse) tea.Cmd {
if v.sel != nil && v.sel.a != v.sel.b {
cmd := a.copyViewSel(v)
v.sel = nil
@@ -910,7 +912,7 @@ func (a *App) viewFileView(s *session, w, h int) string {
}
return nil
},
wheel: func(up bool) tea.Cmd {
Wheel: func(up bool) tea.Cmd {
if up {
v.scroll(-3)
} else {
+2
View File
@@ -15,6 +15,7 @@ import (
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/hostinfo"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
"github.com/db9979/sshtermy/internal/vuln"
)
@@ -198,6 +199,7 @@ func (a *App) runFirmware(title string, ts []fwTarget, single bool) tea.Cmd {
seq, ev := f.seq, a.events
get := fwProduct(a)
go func() {
defer safe.Recover("ui/firmware.go")
defer cancel()
ev <- fwDoneMsg{seq: seq, res: firmwareCheck(ctx, ts, get, fwKEV, func(s string) { ev <- fwStepMsg{seq, s} })}
}()
+8 -6
View File
@@ -12,6 +12,8 @@ import (
"github.com/charmbracelet/x/ansi"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/ui/clickzone"
)
// fieldKind: Text, Geheimnis, Zahl, Auswahl oder Schalter.
@@ -271,7 +273,7 @@ func (f *form) update(msg tea.Msg) (submit bool, cmd tea.Cmd) {
// Ruhig gehalten: Auswahlfelder zeigen ohne Fokus nur den gewählten Wert,
// die Hilfe steht in einer festen Zeile unten (statt sich unter das Feld
// zu schieben) und das Formular wird nie wieder kleiner, solange es offen ist.
func (f *form) view(s Styles, width int, z *zones) string {
func (f *form) view(s Styles, width int, z *clickzone.Map) string {
var b strings.Builder
lines := 0
out := func(str string) { b.WriteString(str + "\n"); lines++ }
@@ -343,7 +345,7 @@ func (f *form) view(s Styles, width int, z *zones) string {
row := marker + label + val
if z != nil {
i, fl := i, fl
row = z.click(row, func(_ tea.Mouse, _ bool) tea.Cmd {
row = z.Click(row, func(_ tea.Mouse, _ bool) tea.Cmd {
if fl.kind == fBool {
fl.on = !fl.on
}
@@ -413,7 +415,7 @@ func (f *form) view(s Styles, width int, z *zones) string {
// choiceView: mit Fokus alle Optionen (passt es nicht, ‹ Wert › zum
// Durchschalten), ohne Fokus nur der gewählte Wert.
func (f *form) choiceView(s Styles, i int, fl *field, focused bool, tint color.Color, inW int, z *zones) string {
func (f *form) choiceView(s Styles, i int, fl *field, focused bool, tint color.Color, inW int, z *clickzone.Map) string {
if fl.opt >= len(fl.options) {
return ""
}
@@ -448,7 +450,7 @@ func (f *form) choiceView(s Styles, i int, fl *field, focused bool, tint color.C
}
if z != nil {
j := j
parts[j] = z.click(parts[j], func(tea.Mouse, bool) tea.Cmd { fl.opt = j; return f.setFocus(i) })
parts[j] = z.Click(parts[j], func(tea.Mouse, bool) tea.Cmd { fl.opt = j; return f.setFocus(i) })
}
}
val := strings.Join(parts, "")
@@ -460,7 +462,7 @@ func (f *form) choiceView(s Styles, i int, fl *field, focused bool, tint color.C
}
// headerRow: „── Anmeldung ──────“; einklappbar mit ▸/▾ und Zusammenfassung.
func (f *form) headerRow(s Styles, i int, fl *field, focused bool, tint color.Color, width int, z *zones) string {
func (f *form) headerRow(s Styles, i int, fl *field, focused bool, tint color.Color, width int, z *clickzone.Map) string {
tc := lipgloss.NewStyle().Foreground(tint)
title := tc.Bold(true).Render(fl.label)
lead := tc.Render("━━ ")
@@ -484,7 +486,7 @@ func (f *form) headerRow(s Styles, i int, fl *field, focused bool, tint color.Co
row += tc.Faint(true).Render(strings.Repeat("─", rest))
}
if fl.fold && z != nil {
row = z.click(row, func(tea.Mouse, bool) tea.Cmd { fl.on = !fl.on; return f.setFocus(i) })
row = z.Click(row, func(tea.Mouse, bool) tea.Cmd { fl.on = !fl.on; return f.setFocus(i) })
}
return row
}
+1 -1
View File
@@ -161,7 +161,7 @@ func (a *App) viewGoalHist(b *strings.Builder, s *session, w, base int) {
row = st.Selected.Width(w).Render(line + strings.Repeat(" ", gap) + meta)
}
r := r
b.WriteString(a.z.click(row, func(_ tea.Mouse, double bool) tea.Cmd {
b.WriteString(a.z.Click(row, func(_ tea.Mouse, double bool) tea.Cmd {
s.panelFocus = true
a.goalPickSet(s, idx)
if double {
+4 -2
View File
@@ -32,6 +32,7 @@ import (
"github.com/db9979/sshtermy/internal/agent"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
"github.com/db9979/sshtermy/internal/sessionlog"
"github.com/db9979/sshtermy/internal/sshx"
)
@@ -174,7 +175,7 @@ func (a *App) viewInputWait(b *strings.Builder, s *session, w int) {
for _, k := range agent.InputKeys(g.inputWait) {
send := k.Send
lbl := st.Accent.Render("["+inputKeyLabel(k.Key)+"]") + " " + st.Text.Render(i18n.T(k.Label))
row = append(row, a.z.click(lbl, func(tea.Mouse, bool) tea.Cmd {
row = append(row, a.z.Click(lbl, func(tea.Mouse, bool) tea.Cmd {
a.sendInputAnswer(s, send)
return nil
}))
@@ -406,6 +407,7 @@ func readBackups(local bool, cl *sshx.Client, need []agent.FileChange) []fileBac
}
done := make(chan []fileBackup, 1)
go func() {
defer safe.Recover("ui/goalux.go")
res := make([]fileBackup, len(need))
copy(res, out)
fsys, closeFn, err := agentFS(local, cl)
@@ -649,7 +651,7 @@ func (a *App) viewBackups(b *strings.Builder, s *session, w int, key string) {
}
head := st.Warn.Render("← " + plural(len(g.backups), i18n.T("Datei geändert"), i18n.T("Dateien geändert")))
if n > 0 {
head += st.Muted.Render(" · ") + a.z.click(st.Accent.Render(key)+" "+st.Text.Render(i18n.T("zurückholen")), func(tea.Mouse, bool) tea.Cmd {
head += st.Muted.Render(" · ") + a.z.Click(st.Accent.Render(key)+" "+st.Text.Render(i18n.T("zurückholen")), func(tea.Mouse, bool) tea.Cmd {
s.panelFocus = true
return a.startUndo(s)
})
+3
View File
@@ -14,6 +14,7 @@ import (
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/harden"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
)
// Härtungs-Check (F6 h, Palette „Härtungs-Check“): nur lesend, Bewertung
@@ -72,6 +73,7 @@ func forHosts(ctx context.Context, conns []domain.Connection, par int, fn func(c
for i, c := range conns {
wg.Add(1)
go func() {
defer safe.Recover("ui/harden.go")
defer wg.Done()
select {
case sem <- struct{}{}:
@@ -193,6 +195,7 @@ func (a *App) runHardenFolder(folder string) tea.Cmd {
}
seq, ev, run := h.seq, a.events, hardenRunHost(a)
go func() {
defer safe.Recover("ui/harden.go")
defer cancel()
forHosts(ctx, conns, 4, func(ctx context.Context, i int, c domain.Connection) {
if ctx.Err() != nil {
+2
View File
@@ -18,6 +18,7 @@ import (
"github.com/db9979/sshtermy/internal/hostinfo"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/safe"
)
const (
@@ -81,6 +82,7 @@ func (a *App) liveStart(s *session) tea.Cmd {
ch := make(chan liveEvent, 8)
cl := s.client
go func() {
defer safe.Recover("ui/hostlive.go")
defer close(ch)
var p hostinfo.LiveParser
var prev *hostinfo.LiveSample
+1 -1
View File
@@ -960,7 +960,7 @@ func (a *App) viewHost(b *strings.Builder, s *session, w int) {
line = st.Text.Render(line)
}
i := i
b.WriteString(a.z.click(mark+line, func(_ tea.Mouse, double bool) tea.Cmd {
b.WriteString(a.z.Click(mark+line, func(_ tea.Mouse, double bool) tea.Cmd {
s.panelFocus, h.sel = true, i
if double {
a.showBackupDiff(s)
+1 -1
View File
@@ -296,7 +296,7 @@ func (a *App) viewImport() string {
}
}
i := i
out = a.z.click(out, func(_ tea.Mouse, double bool) tea.Cmd {
out = a.z.Click(out, func(_ tea.Mouse, double bool) tea.Cmd {
m.sel = i
m.items[i].on = !m.items[i].on
return nil
+2
View File
@@ -15,6 +15,7 @@ import (
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/inventory"
"github.com/db9979/sshtermy/internal/safe"
)
// Inventar & Änderungen (F6 i, Palette): Pakete, Benutzer, Admins, Cron,
@@ -106,6 +107,7 @@ func (a *App) runInventoryFolder(folder string) tea.Cmd {
}
seq, ev, run := v.seq, a.events, invRunHost(a)
go func() {
defer safe.Recover("ui/inventory.go")
defer cancel()
forHosts(ctx, conns, 4, func(ctx context.Context, i int, c domain.Connection) {
if ctx.Err() != nil {
+2
View File
@@ -16,6 +16,7 @@ import (
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/keyinv"
"github.com/db9979/sshtermy/internal/safe"
"github.com/db9979/sshtermy/internal/sshx"
)
@@ -213,6 +214,7 @@ func (a *App) runKeyinv(title string, conns []domain.Connection) tea.Cmd {
}
seq, ev, run := k.seq, a.events, keyinvRun(a)
go func() {
defer safe.Recover("ui/keyinv.go")
defer cancel()
forHosts(ctx, conns, 4, func(ctx context.Context, i int, c domain.Connection) {
if ctx.Err() != nil {
+3 -1
View File
@@ -9,6 +9,8 @@ import (
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/ui/clickzone"
)
// Auswahl der Aufteilung (Strg+T)
@@ -127,7 +129,7 @@ func (a *App) layoutView() string {
if i == m.sel {
box = lipgloss.NewStyle().Background(st.T.Surface).Render(box)
}
cells = append(cells, a.z.mark(box, zoneAction{block: true, click: func(tea.Mouse, bool) tea.Cmd {
cells = append(cells, a.z.Mark(box, clickzone.Action{Block: true, Click: func(tea.Mouse, bool) tea.Cmd {
a.applyLayout(i)
return nil
}}))
+1 -1
View File
@@ -450,7 +450,7 @@ func (a *App) menuView(m *modal) string {
b.WriteString(lipgloss.NewStyle().Foreground(st.T.Border).Render(strings.Repeat("─", w)) + "\n")
}
}
b.WriteString(a.z.click(line, func(tea.Mouse, bool) tea.Cmd {
b.WriteString(a.z.Click(line, func(tea.Mouse, bool) tea.Cmd {
m.sel = i
return a.menuRun()
}))
+1 -1
View File
@@ -185,7 +185,7 @@ func (a *App) llmChip() string {
txt += a.s.Header.Foreground(a.llmColor(h.level)).Render(" " + h.badgeText())
}
txt += a.s.Header.Render(" ")
return a.z.click(txt, func(tea.Mouse, bool) tea.Cmd { return a.openLLMStatus() })
return a.z.Click(txt, func(tea.Mouse, bool) tea.Cmd { return a.openLLMStatus() })
}
// llmTick plant die Hintergrundprüfung (einmal pro Sekunde aufgerufen).
+5 -3
View File
@@ -11,6 +11,8 @@ import (
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/llm"
"github.com/db9979/sshtermy/internal/ui/clickzone"
)
// KI-Einstellungen: Endpunkt testen (Strg+T) und Modell aus der Liste des
@@ -243,9 +245,9 @@ func (a *App) viewLLMExtra(w int) string {
line = a.s.Selected.Width(w - 2).Render(" " + trunc(vis[i], w-6))
}
i := i
line = a.z.mark(line, zoneAction{
click: func(tea.Mouse, bool) tea.Cmd { p.sel = i; return a.pressKey("⏎") },
wheel: func(up bool) tea.Cmd { return a.pressKey(wheelKey(up)) },
line = a.z.Mark(line, clickzone.Action{
Click: func(tea.Mouse, bool) tea.Cmd { p.sel = i; return a.pressKey("⏎") },
Wheel: func(up bool) tea.Cmd { return a.pressKey(wheelKey(up)) },
})
b.WriteString(line + "\n")
}
+3
View File
@@ -16,6 +16,7 @@ import (
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/logscan"
"github.com/db9979/sshtermy/internal/psremote"
"github.com/db9979/sshtermy/internal/safe"
)
// Ordner-Scan: Log-Blick für alle Hosts eines Ordners auf einmal, nur
@@ -142,6 +143,7 @@ func (a *App) runFolderScan(folder string) tea.Cmd {
conns[i] = h.conn
}
go func() {
defer safe.Recover("ui/logfolder.go")
defer cancel()
scanHosts(ctx, conns, hours, scan, func(i int, r *logscan.Report, err error) {
ev <- folderHostMsg{seq: seq, i: i, rep: r, err: err}
@@ -159,6 +161,7 @@ func scanHosts(ctx context.Context, conns []domain.Connection, hours int,
for i, c := range conns {
wg.Add(1)
go func() {
defer safe.Recover("ui/logfolder.go")
defer wg.Done()
select {
case sem <- struct{}{}:
+2 -2
View File
@@ -487,7 +487,7 @@ func (a *App) viewLogs() string {
st = lipgloss.NewStyle().Background(s.T.Accent).Foreground(s.T.Bg).Bold(true).Padding(0, 1)
}
f := f
chips += a.z.click(st.Render(label), func(tea.Mouse, bool) tea.Cmd { a.logs.filter = f; a.selectLog(0); return nil })
chips += a.z.Click(st.Render(label), func(tea.Mouse, bool) tea.Cmd { a.logs.filter = f; a.selectLog(0); return nil })
}
if view != "" && lipgloss.Width(chips)+lipgloss.Width(view)+3 <= leftW {
chips += strings.Repeat(" ", leftW-lipgloss.Width(chips)-lipgloss.Width(view)-2) + a.keyZone("Tab", s.Muted.Render(view))
@@ -527,7 +527,7 @@ func (a *App) viewLogs() string {
for i := start; i < len(rows) && i < start+room; i++ {
i := i
line := a.logRowLine(rows[i], i == m.sel, timeW, nameW, sessW, leftW, now)
lb.WriteString(a.z.click(line, func(_ tea.Mouse, _ bool) tea.Cmd {
lb.WriteString(a.z.Click(line, func(_ tea.Mouse, _ bool) tea.Cmd {
if a.logs.sel == i {
if rs := a.logRows(); i < len(rs) {
a.setLogOpen(rs[i], !rs[i].open)
+2 -2
View File
@@ -135,7 +135,7 @@ func (a *App) viewLogScan() string {
for i := l.top; i < min(len(vis), l.top+room); i++ {
i := i
row := a.findingRow(vis[i], cols, i == l.sel)
b.WriteString(a.z.click(row, func(_ tea.Mouse, double bool) tea.Cmd {
b.WriteString(a.z.Click(row, func(_ tea.Mouse, double bool) tea.Cmd {
l.sel = i
if double {
a.showFindingLines(vis[i])
@@ -287,7 +287,7 @@ func (a *App) findingDetail(f logscan.Finding, w int) []string {
used += cw
s := a.byID(a.lscan.sid)
cmd := c
chips = append(chips, a.z.click(chip, func(tea.Mouse, bool) tea.Cmd {
chips = append(chips, a.z.Click(chip, func(tea.Mouse, bool) tea.Cmd {
if s == nil {
return nil
}
+15 -7
View File
@@ -15,6 +15,7 @@ import (
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/i18n"
"github.com/db9979/sshtermy/internal/logscan"
"github.com/db9979/sshtermy/internal/safe"
"github.com/db9979/sshtermy/internal/sshx"
)
@@ -248,7 +249,7 @@ func (a *App) startWatch(s *session) *logStream {
st := &logStream{cancel: cancel, client: s.client}
ev := a.events
b := &watchBatcher{}
go b.run(ctx, ev)
safe.Go("ui/logwatch.go", func() { b.run(ctx, ev) })
sid := s.id
warn := a.watchLevel() == 2
end := func(err error) {
@@ -266,6 +267,7 @@ func (a *App) startWatch(s *session) *logStream {
lvl = 3
}
go func() {
defer safe.Recover("ui/logwatch.go")
since := time.Now().Add(-watchWinPoll).Unix()
for {
out, err := a.winrmRun(ctx, s, logscan.WindowsSinceScript(since, lvl))
@@ -294,6 +296,7 @@ func (a *App) startWatch(s *session) *logStream {
}
cl := s.client
go func() {
defer safe.Recover("ui/logwatch.go")
err := cl.StreamScript(ctx, logscan.UnixWatchScript(warn), func(line string) {
if e, ok := logscan.UnixWatchLine(line, time.Now()); ok {
b.add(watchItem{sid: sid, kind: logscan.KindUnix, e: e})
@@ -318,12 +321,14 @@ func (a *App) startSyslog(port int) context.CancelFunc {
a.flashErr(fmt.Sprintf(i18n.T("Syslog-Empfang auf UDP %d geht nicht: %v"), port, err))
return cancel
}
go b.run(ctx, ev)
safe.Go("ui/logwatch.go", func() { b.run(ctx, ev) })
go func() {
defer safe.Recover("ui/logwatch.go")
<-ctx.Done()
_ = pc.Close()
}()
go func() {
defer safe.Recover("ui/logwatch.go")
buf := make([]byte, 8192)
for {
n, addr, err := pc.ReadFrom(buf)
@@ -340,14 +345,17 @@ func (a *App) startSyslog(port int) context.CancelFunc {
if h, _, e := net.SplitHostPort(ip); e == nil {
ip = h
}
for _, line := range strings.Split(string(buf[:n]), "\n") {
if e, ok := logscan.SyslogPacket(line, time.Now()); ok {
b.add(watchItem{addr: ip, kind: logscan.KindNetwork, e: e})
// ein kaputtes Paket kostet nur sich selbst, nicht den Empfang
safe.Run("ui/logwatch.go syslog", func() {
for _, line := range strings.Split(string(buf[:n]), "\n") {
if e, ok := logscan.SyslogPacket(line, time.Now()); ok {
b.add(watchItem{addr: ip, kind: logscan.KindNetwork, e: e})
}
}
}
})
}
}()
go a.resolveHosts(ctx)
safe.Go("ui/logwatch.go", func() { a.resolveHosts(ctx) })
return cancel
}
+1 -1
View File
@@ -246,7 +246,7 @@ func (a *App) viewKeys() string {
if i == e.sel {
selLine = len(lines)
}
lines = append(lines, a.z.click(line, func(_ tea.Mouse, double bool) tea.Cmd {
lines = append(lines, a.z.Click(line, func(_ tea.Mouse, double bool) tea.Cmd {
e.sel = i
if double {
e.capturing = true
+9 -7
View File
@@ -23,6 +23,8 @@ import (
"github.com/db9979/sshtermy/internal/sshx"
"github.com/db9979/sshtermy/internal/store"
"github.com/db9979/sshtermy/internal/wol"
"github.com/db9979/sshtermy/internal/ui/clickzone"
)
type managerState struct {
@@ -438,7 +440,7 @@ func (a *App) viewManager() string {
info = s.OK.Render(fmt.Sprintf(i18n.T(" ✓ %d markiert"), n)) // vorn: bleibt lesbar, wenn die Zeile voll ist
}
if m.tag != "" {
info += a.z.click(s.Accent.Render(" #"+m.tag+" ×"), func(tea.Mouse, bool) tea.Cmd { m.tag = ""; return nil })
info += a.z.Click(s.Accent.Render(" #"+m.tag+" ×"), func(tea.Mouse, bool) tea.Cmd { m.tag = ""; return nil })
}
if a.mgrFiltering() {
n := 0
@@ -523,7 +525,7 @@ func (a *App) viewManager() string {
line = lipgloss.NewStyle().Foreground(s.T.Warn).Underline(true).Width(leftW - 1).Render(plain)
}
i, r := i, r
line = a.z.mark(line, zoneAction{row: i + 1, click: func(_ tea.Mouse, double bool) tea.Cmd {
line = a.z.Mark(line, clickzone.Action{Row: i + 1, Click: func(_ tea.Mouse, double bool) tea.Cmd {
m.sel = i
m.drag = &mgrDrag{from: i, over: i, dbl: double}
if double && !r.isFolder() {
@@ -531,7 +533,7 @@ func (a *App) viewManager() string {
return a.connect(r.conn)
}
return nil
}, menu: func(ms tea.Mouse) tea.Cmd {
}, Menu: func(ms tea.Mouse) tea.Cmd {
if ms.Button != tea.MouseRight {
return nil
}
@@ -549,7 +551,7 @@ func (a *App) viewManager() string {
lb.WriteString(a.mgrEmpty(leftW))
}
}
listBox := a.z.mark(lb.String(), zoneAction{block: true, wheel: func(up bool) tea.Cmd {
listBox := a.z.Mark(lb.String(), clickzone.Action{Block: true, Wheel: func(up bool) tea.Cmd {
if up {
m.sel = max(0, m.sel-1)
} else {
@@ -670,7 +672,7 @@ func (a *App) mgrConnDetails(c domain.Connection, rightW int, now time.Time) str
row(i18n.T("Startbefehl"), c.StartCmd)
}
if canWake(c) && !a.connected(c.ID) {
rb.WriteString(" " + label.Render(i18n.T("Aufwecken")) + a.z.click(s.Key.Render(i18n.T("Wake-on-LAN senden")), func(tea.Mouse, bool) tea.Cmd { return a.wake(c) }) + s.Muted.Render(" "+c.MAC) + "\n")
rb.WriteString(" " + label.Render(i18n.T("Aufwecken")) + a.z.Click(s.Key.Render(i18n.T("Wake-on-LAN senden")), func(tea.Mouse, bool) tea.Cmd { return a.wake(c) }) + s.Muted.Render(" "+c.MAC) + "\n")
}
if c.Profile != nil && !c.Profile.Empty() {
sum := c.Profile.Summary()
@@ -710,7 +712,7 @@ func (a *App) mgrConnDetails(c domain.Connection, rightW int, now time.Time) str
}
t := t
line := fmt.Sprintf(" %s %-20s %s%s", icon, trunc(t.Name, 20), s.Muted.Render(t.Spec()), auto)
rb.WriteString(a.z.click(line, func(tea.Mouse, bool) tea.Cmd { return a.openTunnelForm(t) }) + "\n")
rb.WriteString(a.z.Click(line, func(tea.Mouse, bool) tea.Cmd { return a.openTunnelForm(t) }) + "\n")
}
return rb.String()
}
@@ -1461,5 +1463,5 @@ func (a *App) syncChip() string {
if a.st.SyncConfig().Enabled() {
txt = " ↕ Sync " + ansi.Strip(a.syncStatus()) + " "
}
return a.z.click(s.Header.Foreground(s.T.Muted).Render(trunc(txt, 40)), func(tea.Mouse, bool) tea.Cmd { return a.openSync() }) + s.Header.Render(" ")
return a.z.Click(s.Header.Foreground(s.T.Muted).Render(trunc(txt, 40)), func(tea.Mouse, bool) tea.Cmd { return a.openSync() }) + s.Header.Render(" ")
}
+3 -3
View File
@@ -581,7 +581,7 @@ func (a *App) mgrDragMouse(msg tea.MouseMsg) tea.Cmd {
m := msg.Mouse()
switch msg.(type) {
case tea.MouseMotionMsg:
if r := a.z.rowAt(m.X, m.Y); r >= 0 {
if r := a.z.RowAt(m.X, m.Y); r >= 0 {
if r != d.from {
d.moved = true
}
@@ -596,7 +596,7 @@ func (a *App) mgrDragMouse(msg tea.MouseMsg) tea.Cmd {
return nil
case tea.MouseReleaseMsg:
a.mgr.drag = nil
r := a.z.rowAt(m.X, m.Y)
r := a.z.RowAt(m.X, m.Y)
rows := a.mgr.rows
if !d.moved || r == d.from {
if d.from < len(rows) && rows[d.from].isFolder() && !d.dbl {
@@ -679,7 +679,7 @@ func (a *App) viewFolderDetails(n *domain.TreeNode, w int) string {
line += " " + ansi.Truncate(a.reachText(c), rest, "…")
}
c := c
b.WriteString(a.z.click(line, func(_ tea.Mouse, double bool) tea.Cmd {
b.WriteString(a.z.Click(line, func(_ tea.Mouse, double bool) tea.Cmd {
if double {
return a.connect(c)
}
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff. Show more