diff --git a/README.de.md b/README.de.md index 41485f4..2030e05 100644 --- a/README.de.md +++ b/README.de.md @@ -29,6 +29,7 @@ sshTermy ist eine schlanke Terminal-Anwendung (TUI, eine einzige Datei, ~9 MB, k - **Wake-on-LAN**: Ein ausgeschalteter Rechner im eigenen Netz lässt sich aus dem Manager wecken (Klick auf „Wake-on-LAN senden“, Palette „aufwecken“ oder `w` im getrennten Tab). Die MAC-Adresse merkt sich sshTermy beim ersten Verbinden von selbst oder du trägst sie unter Erweitert ein. - **Platzhalter in Schnellbefehlen**: `systemctl restart {{dienst}}` fragt beim Ausführen nach dem Wert, `{{dienst:nginx}}` schlägt einen vor; der letzte Wert steht beim nächsten Mal schon da. Macht erst der eingesetzte Wert den Befehl gefährlich, fragt sshTermy nach. - **Suche über alle Tabs** (Alt+S): ein Suchbegriff, die Treffer aus dem Verlauf aller offenen Tabs in einer Liste; ⏎ springt in den Tab an genau diese Zeile. +- **Befehle als Blöcke**: Alt+Bild↑ / Alt+Bild↓ springt im Verlauf von Befehl zu Befehl, Alt+O listet die Befehle des Tabs (mit Uhrzeit, Dauer, ✓/×): ⏎ springt hin, Strg+C kopiert genau diese Ausgabe, Strg+K gibt Befehl und Ausgabe an „KI fragen“, Strg+L zeigt sie groß. - **Tabs mit der Maus ziehen**: Ein Tab lässt sich in der Tab-Leiste an eine andere Stelle ziehen. - **Fertig im Hintergrund**: Ein Befehl, der 10 s oder länger in einem verdeckten Tab lief, markiert den Tab (✓ / ×) und meldet sich mit einer Einblendung; ist das sshTermy-Fenster im Hintergrund, kommt zusätzlich eine Desktop-Benachrichtigung (Windows, macOS, Linux). Die Terminal-Glocke markiert den Tab ebenso. Beides ist in der Palette abschaltbar - **Agent-Weiterleitung** pro Verbindung (wie `ssh -A`): `git pull`, `ssh` und `scp` auf dem Server nutzen deine lokalen Keys aus ssh-agent, Pageant oder dem Windows-OpenSSH-Agent, die Keys verlassen deinen Rechner nie @@ -116,6 +117,16 @@ nicht als Beweis. Die Liste: Palette *Logwache: Meldungen* oder `w` im Log-Blick gehen zurück ans Modell statt ausgeführt zu werden. Bleibt ein von sshTermy gesendeter Befehl (Ziel, Agent, Plan, KI fragen, Begleiter, Favoriten, Vorgang über mehrere Fenster) trotzdem am `>` hängen, bricht sshTermy ihn mit Strg+C ab, meldet den Schritt als Fehlschlag und schickt erst dann den nächsten Befehl. + Im Einsatz: `?` gibt der KI mitten im Ziel eine Anweisung („nimm docker compose, nicht docker-compose“), ⇧S überspringt einen + Schritt mit Grund. Wartet ein Befehl auf eine Eingabe (`[Y/n]`, `less`/`(END)`, `--More--` am Switch, „Press any key“), zeigt + das Panel Knöpfe dafür (j / n / q / Leertaste / Strg+C); der Agent hält dort an. Bevor ein Schritt Dateien ändert (`sed -i`, + `tee`, `>`, `cp`/`mv` auf eine Datei, `rm`), sichert sshTermy sie per SFTP; am Ende holt `u` alles mit einem Befehl zurück + (neu angelegte Dateien werden gelöscht). `f` startet ein Folgeziel, das die Schritte davor kennt. Was du während des Ziels + selbst tippst, bekommt die KI als Schritt mit Ausgabe. Reißt die Verbindung ab, hält das Ziel an; nach dem Neuverbinden setzt + ⏎ es fort und die KI prüft zuerst den Stand. Jedes Ziel landet im **Zielverlauf** der Verbindung (nur auf diesem Rechner): + ↑↓ im Zielfeld, ⏎ startet es erneut, Strg+D entfernt es. Der Tab zeigt den Zustand des Ziels (◎ läuft, gelb = wartet auf + dich, grün = erreicht) und die Zahl der Schritte; wartet ein Ziel in einem verdeckten Tab auf dich, kommt eine Einblendung, + ist sshTermy im Hintergrund, eine Desktop-Benachrichtigung. - **Agent-Modus** (F2, Tab wählt den Modus): Der Agent arbeitet selbstständig bis zum Ziel. Er führt Befehle aus, sieht Ausgabe und Exit-Code, legt Skripte per SFTP in `~/.sshtermy-agent//` an und führt sie aus (erst Probelauf). Stufen: *Vorsichtig* (Standard; nur Lesendes läuft allein), *Normal* (alles außer Gefahr, sudo und Code in der Zeile wie `python -c`, `bash -c`, `eval`; als root angemeldet oder unter Windows fragt jede Änderung, weil es dort kein sudo zum Anhalten gibt), *Voll* (auch sudo). @@ -337,6 +348,7 @@ sshtermy mcp # MCP-Server für KI-Clients (stdin/stdout), siehe „ | | F7 / F8 | vorheriger / nächster Tab | | | Alt+T | alle Tabs (Liste: springen, schließen, umbenennen, duplizieren, verschieben) | | | Alt+S | in allen offenen Tabs suchen, ⏎ springt zur Trefferzeile | +| | Alt+Bild↑ / Alt+Bild↓ / Alt+O | zum vorigen / nächsten Befehl springen / Befehle des Tabs als Liste (⏎ hinspringen, Strg+C Ausgabe kopieren, Strg+K KI fragen, Strg+L lesen) | | | Alt+N / Alt+W | neuer Tab / Tab schließen (auch `+` und `×` in der Tab-Leiste, Rechtsklick auf einen Tab öffnet sein Menü, Maus darauf zeigt Ziel, Dauer und Latenz) | | | Alt+L | lokale Shell in neuem Tab (auch im Manager; Palette: `lokal`, `pwsh`, `cmd`, `wsl`, `zsh` …) | | | F9 / ⇧F1…F8 | Schnellbefehle: Liste / direkt ausführen (`{{name}}` im Befehl fragt nach einem Wert) | @@ -362,7 +374,11 @@ sshtermy mcp # MCP-Server für KI-Clients (stdin/stdout), siehe „ | | p / g / n / x | erkannte Absicht: Plan / Agent übernimmt / selbst machen / nicht mehr fragen | | | Strg+Klick / Rechtsklick | URL im Browser öffnen / Menü zu Link, IP oder Host: verbinden (direkt oder über den Server), Ping vom Server oder von hier, kopieren | | | Einfügen | mehrzeilig erst Vorschau (⏎ einfügen, o ohne letztes Enter, Esc abbrechen); Palette „Einfügeschutz aus“ | -| Ziel-Modus | ↑↓ / Strg+S / Strg+D | Runbook wählen / Ziel als Runbook speichern / Runbook löschen | +| Ziel-Modus | ↑↓ / Strg+S / Strg+D | Runbook oder früheres Ziel (Verlauf) wählen / Ziel als Runbook speichern / Runbook oder Verlaufseintrag löschen | +| | ? / ⇧S | KI anweisen (gilt ab dem nächsten Schritt) / überspringen mit Grund | +| | j / n / q / Leertaste / Strg+C | der laufende Befehl fragt nach: mit den Knöpfen antworten (Esc: selbst im Terminal) | +| | f / u | nach dem Ziel: Folgeziel / vom Ziel geänderte Dateien zurückholen (Strg+R im leeren Zielfeld) | +| | ⏎ nach Abbruch | Ziel fortsetzen, sobald die Verbindung wieder steht | | Ziel-Modus, Datei-Schritt | ⏎ / v / s | Datei auf dem Host anlegen / ansehen / überspringen; am Ende löscht `r` den Arbeitsordner | | | ⏎ / i / e / s / r / x | ausführen / nur einfügen (Dry-Run) / bearbeiten / überspringen / neu / beenden | | | Tab | Schritt für Schritt → Agent *Vorsichtig* → *Normal* → *Voll* → *Erst planen* | diff --git a/README.md b/README.md index db7ab44..4d90fc0 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ sshTermy is a lean terminal application (TUI, a single file, ~9 MB, no installer - **Wake-on-LAN**: a powered-off machine in your own network can be woken from the manager (click “Send Wake-on-LAN”, palette “wake”, or `w` in a disconnected tab). sshTermy remembers the MAC address on the first connect, or you enter it under Advanced. - **Placeholders in quick commands**: `systemctl restart {{service}}` asks for the value when run, `{{service:nginx}}` suggests one; the last value is prefilled next time. If only the inserted value makes the command dangerous, sshTermy asks first. - **Search across all tabs** (Alt+S): one search term, the hits from the scrollback of all open tabs in one list; ⏎ jumps to the tab at exactly that line. +- **Commands as blocks**: Alt+PgUp / Alt+PgDn jumps from command to command in the scrollback, Alt+O lists the commands of the tab (with time, duration, ✓/×): ⏎ jumps there, Ctrl+C copies just that output, Ctrl+K hands command and output to “Ask AI”, Ctrl+L shows it in full. - **Drag tabs with the mouse**: a tab can be dragged to another position in the tab bar. - **Finished in the background**: a command that ran 10 s or longer in a hidden tab marks the tab (✓ / ×) and shows a toast; if the sshTermy window is in the background you also get a desktop notification (Windows, macOS, Linux). The terminal bell marks the tab too. Both can be switched off in the palette - **Agent forwarding** per connection (like `ssh -A`): `git pull`, `ssh` and `scp` on the server use your local keys from ssh-agent, Pageant or the Windows OpenSSH agent, the keys never leave your computer @@ -114,6 +115,16 @@ lets them in. The AI status report treats syslog lines as hints, not as proof. T are sent back to the model instead of being run. If a command sent by sshTermy (goal, agent, plan, ask AI, companion, favorites, multi-window task) still gets stuck at `>`, sshTermy cancels it with Ctrl+C, reports it as a failed step, and only then sends the next command. + In daily use: `?` gives the AI an instruction in the middle of a goal (“use docker compose, not docker-compose”), ⇧S skips a + step with a reason. If a command waits for input (`[Y/n]`, `less`/`(END)`, `--More--` on a switch, “Press any key”), the panel + shows buttons for it (j / n / q / Space / Ctrl+C); the agent pauses there. Before a step changes files (`sed -i`, `tee`, `>`, + `cp`/`mv` onto a file, `rm`), sshTermy backs them up via SFTP; at the end `u` restores everything in one command (new files are + removed). `f` starts a follow-up goal that knows the steps before. Commands you type yourself during a goal reach the AI as + steps with their output. If the connection drops, the goal pauses; after reconnecting ⏎ continues and the AI checks the state + first. Every goal lands in the **goal history** of the connection (only on this computer): ↑↓ in the goal field, ⏎ runs it + again, Ctrl+D removes it. The tab shows the goal's state (◎ running, yellow = waiting for you, green = reached) and the + number of steps; if a goal is waiting for you in a hidden tab, a notification pops up, with sshTermy in the background a + desktop notification. - **Agent mode** (F2, Tab picks the mode): the agent works on its own until the goal is reached. It runs commands, sees their output and exit code, writes scripts via SFTP to `~/.sshtermy-agent//` and runs them (dry run first). Levels: *Careful* (default; only read-only commands run on their own), *Normal* (everything except danger, sudo and inline code such as `python -c`, `bash -c`, `eval`; signed in as root or on Windows every change asks, because there is no sudo to stop at), @@ -327,6 +338,7 @@ sshtermy mcp # MCP server for AI clients (stdin/stdout), see “sshT | | F7 / F8 | previous / next tab | | | Alt+T | all tabs (list: jump, close, rename, duplicate, move) | | | Alt+S | search in all open tabs, ⏎ jumps to the matching line | +| | Alt+PgUp / Alt+PgDn / Alt+O | jump to the previous / next command / list of the tab's commands (⏎ jump, Ctrl+C copy output, Ctrl+K ask AI, Ctrl+L read) | | | Alt+N / Alt+W | new tab / close tab (also `+` and `×` in the tab bar, right-click a tab for its menu, hover it for target, duration and latency) | | | Alt+L | local shell in a new tab (also in the manager; palette: `local`, `pwsh`, `cmd`, `wsl`, `zsh` …) | | | F9 / ⇧F1…F8 | quick commands: list / run directly (`{{name}}` in the command asks for a value) | @@ -352,7 +364,11 @@ sshtermy mcp # MCP server for AI clients (stdin/stdout), see “sshT | | p / g / n / x | spotted intent: plan / agent takes over / do it myself / don't ask again | | | Ctrl+click / right-click | open URL in the browser / menu for a link, IP or host: connect (directly or via the server), ping from the server or from here, copy | | | Paste | multi-line shows a preview first (⏎ paste, o without the last Enter, Esc cancel); palette “Paste guard off” | -| Goal mode | ↑↓ / Ctrl+S / Ctrl+D | choose runbook / save goal as runbook / delete runbook | +| Goal mode | ↑↓ / Ctrl+S / Ctrl+D | choose runbook or earlier goal (history) / save goal as runbook / delete runbook or history entry | +| | ? / ⇧S | instruct the AI (applies from the next step) / skip with a reason | +| | j / n / q / Space / Ctrl+C | the running command asks for input: answer with the buttons (Esc: answer in the terminal) | +| | f / u | after the goal: follow-up goal / restore the files the goal changed (Ctrl+R in the empty goal field) | +| | ⏎ after a drop | continue the goal once the connection is back | | Goal mode, file step | ⏎ / v / s | create the file on the host / view it / skip; at the end `r` deletes the work folder | | | ⏎ / i / e / s / r / x | run / only insert (dry run) / edit / skip / suggest again / end | | | Tab | step by step → agent *Careful* → *Normal* → *Full* → *Plan first* | diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 62bfdd3..fc5501a 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -287,6 +287,10 @@ type DoneStep struct { Output string // Ausgabe des Befehls (gekürzt) Exit *int // Exit-Code, wenn die Shell ihn meldet (OSC 133) File string // Name der angelegten Datei (dann ist Command nur eine Beschreibung) + // Manual: der Mensch hat den Befehl während des Ziels selbst getippt. + Manual bool + // Note: Grund des Menschen (z. B. beim Überspringen). + Note string } var ErrUnreadable = errors.New("Antwort des Modells nicht lesbar") @@ -311,7 +315,7 @@ func (a *Agent) NextStep(ctx context.Context, goal string, recipe []string, hist writeHist(&b, hist) } for _, x := range answers { - fmt.Fprintf(&b, "Antwort des Menschen auf deine Frage: %s\n", Redact(x)) + b.WriteString(answerLine(x, "Antwort des Menschen auf deine Frage: %s\n")) } b.WriteString("\n" + material(c)) msgs := []llm.Message{ diff --git a/internal/agent/auto.go b/internal/agent/auto.go index ada7ca2..c4c398d 100644 --- a/internal/agent/auto.go +++ b/internal/agent/auto.go @@ -92,7 +92,7 @@ func (a *Agent) AutoStep(ctx context.Context, goal string, recipe []string, hist writeHist(&b, hist) } for _, x := range answers { - fmt.Fprintf(&b, "Antwort des Menschen: %s\n", Redact(x)) + b.WriteString(answerLine(x, "Antwort des Menschen: %s\n")) } b.WriteString("\n" + material(c)) msgs := []llm.Message{ @@ -146,8 +146,19 @@ func block(s string) string { func (h DoneStep) status() string { switch { + case h.Skipped && h.Note != "": + return "vom Menschen übersprungen, Grund: " + strings.Join(strings.Fields(Redact(h.Note)), " ") case h.Skipped: return "vom Menschen übersprungen" + case h.Manual: + st := "vom Menschen selbst ausgeführt" + switch { + case h.ExitHint != "": + st += ", fehlgeschlagen: " + h.ExitHint + case h.Exit != nil: + st += fmt.Sprintf(", Exit %d", *h.Exit) + } + return st case h.File != "": return "Datei angelegt" case h.ExitHint != "": diff --git a/internal/agent/changes.go b/internal/agent/changes.go new file mode 100644 index 0000000..e4c5ef3 --- /dev/null +++ b/internal/agent/changes.go @@ -0,0 +1,311 @@ +package agent + +import ( + "path" + "strings" +) + +// Welche Dateien ändert ein Befehl? Für die Sicherung vor einem Schritt im +// Ziel-/Agent-Modus (Rückgängig). Eine Heuristik für die üblichen Wege: +// Umleitung (> / >>), tee, sed -i, cp/mv/install auf eine Datei, rm ohne -r, +// truncate. Nur absolute Pfade und ~/…, ohne Platzhalter und Variablen – +// alles andere lässt sich vorher nicht sicher bestimmen. + +// FileChange: eine Datei, die ein Befehl ändern oder löschen wird. +type FileChange struct { + Path string + Sudo bool // der Befehl läuft mit sudo (Wiederherstellen braucht es dann auch) +} + +// ChangedFiles listet die Zieldateien eines Befehls (ohne Doppelte). +func ChangedFiles(cmd string) []FileChange { + var out []FileChange + seen := map[string]bool{} + add := func(p string, sudo bool) { + p = cleanTarget(p) + if p == "" || seen[p] { + return + } + seen[p] = true + out = append(out, FileChange{Path: p, Sudo: sudo}) + } + for _, part := range splitParts(cmd) { + toks := shellTokens(part) + sudo := false + // Umleitungen gelten für den ganzen Teil + var args []string + for i := 0; i < len(toks); i++ { + t := toks[i] + switch { + case t == ">" || t == ">>" || t == "1>" || t == "1>>" || t == "&>" || t == "&>>": + if i+1 < len(toks) { + add(toks[i+1], false) // Umleitung macht die Shell des Nutzers, nicht sudo + i++ + } + continue + case strings.HasPrefix(t, ">>") && len(t) > 2: + add(t[2:], false) + continue + case strings.HasPrefix(t, ">") && len(t) > 1 && t[1] != '&' && t[1] != '(': + add(t[1:], false) + continue + case strings.HasPrefix(t, "2>") || strings.HasPrefix(t, "<"): + if (t == "2>" || t == "2>>" || t == "<" || t == "<<<") && i+1 < len(toks) { + i++ + } + continue + } + args = append(args, t) + } + // Vorspann: sudo [-u x] [-E], env VAR=…, VAR=… + for len(args) > 0 { + a := args[0] + if a == "sudo" || a == "doas" { + sudo = true + args = args[1:] + for len(args) > 0 && strings.HasPrefix(args[0], "-") { + if args[0] == "-u" || args[0] == "-g" { + args = args[1:] + } + if len(args) > 0 { + args = args[1:] + } + } + continue + } + if a == "env" || a == "nohup" || a == "command" || (strings.Contains(a, "=") && !strings.HasPrefix(a, "-") && !strings.HasPrefix(a, "/")) { + args = args[1:] + continue + } + break + } + if len(args) == 0 { + continue + } + prog := path.Base(args[0]) + rest := args[1:] + plain, opts := splitOpts(prog, rest) + switch prog { + case "tee": + for _, p := range plain { + add(p, sudo) + } + case "sed", "perl": + if !hasOpt(opts, "-i", "--in-place") { + continue + } + files := plain + if !hasOpt(opts, "-e", "--expression", "-f", "--file") && len(files) > 0 { + files = files[1:] // erstes Argument ist das Skript + } + for _, p := range files { + add(p, sudo) + } + case "cp", "mv", "install", "ln": + if prog == "ln" && !hasOpt(opts, "-f", "--force") { + continue + } + if hasOpt(opts, "-t", "--target-directory") || len(plain) < 2 { + continue + } + dst := plain[len(plain)-1] + if !strings.HasSuffix(dst, "/") { + add(dst, sudo) + } + if prog == "mv" { + for _, p := range plain[:len(plain)-1] { + add(p, sudo) // Quelle verschwindet + } + } + case "rm", "unlink", "truncate", "shred": + if prog == "rm" && hasOpt(opts, "-r", "-R", "--recursive") { + continue + } + for _, p := range plain { + add(p, sudo) + } + case "dd": + for _, a := range rest { + if strings.HasPrefix(a, "of=") { + add(a[3:], sudo) + } + } + } + } + return out +} + +// splitOpts trennt Optionen von den übrigen Argumenten. Kurze Optionen wie +// -i.bak oder -ni zählen als -i. +func splitOpts(prog string, args []string) (plain, opts []string) { + val := map[string]bool{} + switch prog { + case "sed", "perl": + val = map[string]bool{"-e": true, "-f": true, "--expression": true, "--file": true} + case "cp", "mv", "install", "ln": + val = map[string]bool{"-t": true, "-S": true, "-m": true, "-o": true, "-g": true} + case "truncate": + val = map[string]bool{"-s": true, "-r": true} + case "shred": + val = map[string]bool{"-n": true, "-s": true} + } + end := false + for i := 0; i < len(args); i++ { + a := args[i] + if end || !strings.HasPrefix(a, "-") || a == "-" { + plain = append(plain, a) + continue + } + if a == "--" { + end = true + continue + } + opts = append(opts, a) + if val[a] && i+1 < len(args) { + opts = append(opts, args[i+1]) + i++ + } + } + return plain, opts +} + +func hasOpt(opts []string, names ...string) bool { + for _, o := range opts { + for _, n := range names { + if o == n || strings.HasPrefix(o, n+"=") { + return true + } + // kurze Optionen zusammengefasst: -ni, -i.bak, -rf + if len(n) == 2 && n[0] == '-' && len(o) > 1 && o[0] == '-' && o[1] != '-' { + flags := o[1:] + if n == "-i" { // sed -i.bak: alles nach i ist die Endung + if strings.ContainsRune(flags, 'i') && !strings.ContainsAny(flags[:strings.IndexRune(flags, 'i')], "=") { + return true + } + continue + } + if strings.ContainsRune(flags, rune(n[1])) { + return true + } + } + } + } + return false +} + +// cleanTarget: nur Pfade, die sich sicher auflösen lassen. +func cleanTarget(p string) string { + p = strings.TrimSpace(p) + if p == "" || strings.ContainsAny(p, "*?[]{}$`\\") { + return "" + } + if !strings.HasPrefix(p, "/") && !strings.HasPrefix(p, "~/") { + return "" + } + for _, pre := range []string{"/dev/", "/proc/", "/sys/", "/run/"} { + if strings.HasPrefix(p, pre) { + return "" + } + } + if strings.HasSuffix(p, "/") || p == "/" || p == "~/" { + return "" + } + if strings.HasPrefix(p, "~/") { + return "~/" + strings.TrimPrefix(path.Clean("/"+p[2:]), "/") + } + return path.Clean(p) +} + +// splitParts teilt an ; && || | und Zeilenumbrüchen (außerhalb von Anführungszeichen). +func splitParts(cmd string) []string { + var parts []string + var b strings.Builder + var q rune + rs := []rune(cmd) + flush := func() { + if s := strings.TrimSpace(b.String()); s != "" { + parts = append(parts, s) + } + b.Reset() + } + for i := 0; i < len(rs); i++ { + c := rs[i] + if q != 0 { + b.WriteRune(c) + if c == q { + q = 0 + } else if c == '\\' && q == '"' && i+1 < len(rs) { + i++ + b.WriteRune(rs[i]) + } + continue + } + switch c { + case '\'', '"': + q = c + b.WriteRune(c) + case '\\': + b.WriteRune(c) + if i+1 < len(rs) { + i++ + b.WriteRune(rs[i]) + } + case ';', '\n': + flush() + case '&': + if i+1 < len(rs) && rs[i+1] == '&' { + flush() + i++ + } else if i+1 < len(rs) && rs[i+1] == '>' { + b.WriteRune(c) // &> Umleitung + } else if i > 0 && rs[i-1] == '>' { + b.WriteRune(c) // 2>&1 + } else { + flush() + } + case '|': + flush() + if i+1 < len(rs) && rs[i+1] == '|' { + i++ + } + default: + b.WriteRune(c) + } + } + flush() + return parts +} + +// shellTokens: einfache Wortzerlegung mit Anführungszeichen. Umleitungen +// stehen als eigene Wörter, wenn sie mit Leerzeichen geschrieben sind; +// „>datei“ bleibt zusammen (siehe ChangedFiles). +func shellTokens(s string) []string { + var out []string + var b strings.Builder + var q rune + has := false + for _, c := range s { + switch { + case q != 0: + if c == q { + q = 0 + } else { + b.WriteRune(c) + } + case c == '\'' || c == '"': + q, has = c, true + case c == ' ' || c == '\t': + if has || b.Len() > 0 { + out = append(out, b.String()) + b.Reset() + has = false + } + default: + b.WriteRune(c) + } + } + if has || b.Len() > 0 { + out = append(out, b.String()) + } + return out +} diff --git a/internal/agent/changes_test.go b/internal/agent/changes_test.go new file mode 100644 index 0000000..f0f4cab --- /dev/null +++ b/internal/agent/changes_test.go @@ -0,0 +1,71 @@ +package agent + +import ( + "reflect" + "testing" +) + +func TestChangedFiles(t *testing.T) { + cases := []struct { + cmd string + want []string + }{ + {`echo "x=1" | sudo tee -a /etc/app.conf`, []string{"/etc/app.conf"}}, + {`sudo sed -i 's/a/b/' /etc/nginx/nginx.conf`, []string{"/etc/nginx/nginx.conf"}}, + {`sed -i.bak -e 's/a/b/' ~/x.txt /etc/y`, []string{"~/x.txt", "/etc/y"}}, + {`sed 's/a/b/' /etc/y`, nil}, + {`echo hi > /tmp/a && cat /etc/b >> ~/c`, []string{"/tmp/a", "~/c"}}, + {`echo hi >/tmp/a 2>/dev/null`, []string{"/tmp/a"}}, + {`sudo cp ~/.sshtermy-agent/x/app.ini /etc/gitea/app.ini`, []string{"/etc/gitea/app.ini"}}, + {`sudo mv /etc/a.conf /etc/b.conf`, []string{"/etc/b.conf", "/etc/a.conf"}}, + {`rm -f /etc/nginx/sites-enabled/default`, []string{"/etc/nginx/sites-enabled/default"}}, + {`rm -rf /var/www/old`, nil}, + {`cp a.txt b.txt`, nil}, + {`cp /etc/*.conf /backup/`, nil}, + {`ls -la /etc > /dev/null`, nil}, + {`cat /etc/passwd 2>&1 | grep root`, nil}, + {`DEBIAN_FRONTEND=noninteractive sudo -E truncate -s 0 /var/log/app.log`, []string{"/var/log/app.log"}}, + {`sudo -u www-data tee /var/www/html/index.html < /tmp/x`, []string{"/var/www/html/index.html"}}, + } + for _, c := range cases { + var got []string + for _, f := range ChangedFiles(c.cmd) { + got = append(got, f.Path) + } + if !reflect.DeepEqual(got, c.want) { + t.Errorf("%s: %q, will %q", c.cmd, got, c.want) + } + } + if f := ChangedFiles(`echo x | sudo tee /etc/a`); len(f) != 1 || !f[0].Sudo { + t.Errorf("sudo tee: %+v", f) + } + if f := ChangedFiles(`sudo echo x > /etc/a`); len(f) != 1 || f[0].Sudo { + t.Errorf("Umleitung macht die Shell: %+v", f) + } +} + +func TestInputWait(t *testing.T) { + cases := map[string]InputKind{ + "Do you want to continue? [Y/n] ": InputYesNo, + "Proceed ([y]/n)? ": InputYesNo, + "Overwrite existing file? (y/n) ": InputYesNo, + "Möchten Sie fortfahren? [J/n] ": InputYesNo, + "Destination filename [startup-config]? ": InputNone, + "Proceed with reload? [confirm]": InputConfirm, + "--More--": InputPager, + " -- MORE --, next page: Space, next line: Enter": InputPager, + "(END)": InputPager, + "lines 1-23/120 19%": InputPager, + "Press any key to continue": InputAnyKey, + "user@host:~$ ": InputNone, + "": InputNone, + } + for line, want := range cases { + if got := InputWait(line, false); got != want { + t.Errorf("%q: %q, will %q", line, got, want) + } + } + if InputWait(":", true) != InputPager || InputWait(":", false) != InputNone { + t.Error("less-Doppelpunkt") + } +} diff --git a/internal/agent/inputwait.go b/internal/agent/inputwait.go new file mode 100644 index 0000000..dbd69f5 --- /dev/null +++ b/internal/agent/inputwait.go @@ -0,0 +1,72 @@ +package agent + +import ( + "regexp" + "strings" +) + +// Befehl wartet auf eine Eingabe: Rückfrage (Y/n), Pager (less, --More--) +// oder „beliebige Taste“. Der Ziel-Modus würde sonst ewig auf den Prompt +// warten. Passwortabfragen erkennt LooksLikeSecretPrompt. + +// InputKind: welche Art Eingabe erwartet wird. +type InputKind string + +const ( + InputNone InputKind = "" + InputYesNo InputKind = "yesno" // [Y/n], (yes/no), Continue? + InputPager InputKind = "pager" // less, more, --More-- am Switch + InputAnyKey InputKind = "key" // Press any key / ENTER + InputConfirm InputKind = "confirm" // [confirm] (Cisco): ⏎ = ja +) + +var ( + ynRx = regexp.MustCompile(`(?i)(\[\s*y(es)?\s*/\s*n(o)?\s*\]|\(\s*y(es)?\s*/\s*n(o)?\s*\)|\[\s*j\s*/\s*n\s*\]|\(\s*j(a)?\s*/\s*n(ein)?\s*\)|\byes/no\b|\by/n\b)\s*[?:]?\s*$`) + ynQRx = regexp.MustCompile(`(?i)\b(do you want to continue|continue|proceed|are you sure|overwrite|möchten sie fortfahren|fortfahren|wirklich)\b[^\n]{0,40}\?\s*$`) + confirmRx = regexp.MustCompile(`(?i)\[confirm\]\s*$`) + pagerRx = regexp.MustCompile(`(?i)(^\s*:\s*$|\(END\)\s*$|^\s*lines \d+-\d+(/\d+)?( \d+%)?( \(END\))?\s*$|--\s*more\s*--|-- ?more ?--|--mehr--|press space|<--- more --->|^\s*more\s*$|\bmanual page\b.*\(press h for help or q to quit\))`) + keyRx = regexp.MustCompile(`(?i)(press any key|press (enter|return)|hit (enter|return)|beliebige taste|drücken sie (die )?(eingabe|enter)|press ? to continue)[^\n]{0,30}$`) +) + +// InputWait prüft die Zeile mit dem Cursor (und bei Pagern die letzte +// Bildschirmzeile). alt = Alternativer Bildschirm (less, man). +func InputWait(cursorLine string, alt bool) InputKind { + l := strings.TrimRight(cursorLine, " \t") + if strings.TrimSpace(l) == "" { + return InputNone + } + switch { + case confirmRx.MatchString(l): + return InputConfirm + case ynRx.MatchString(l), ynQRx.MatchString(l): + return InputYesNo + case keyRx.MatchString(l): + return InputAnyKey + case pagerRx.MatchString(l): + if strings.TrimSpace(l) == ":" && !alt { + return InputNone // ein Doppelpunkt allein ist ohne Pager eher eine Eingabe + } + return InputPager + } + return InputNone +} + +// InputKeys: was die Knöpfe senden. Reihenfolge = Anzeige. +type InputButton struct { + Key, Label, Send string // Label ist deutsch, die Oberfläche übersetzt +} + +func InputKeys(k InputKind) []InputButton { + ctrlC := InputButton{"ctrl+c", "abbrechen", "\x03"} + switch k { + case InputYesNo: + return []InputButton{{"j", "ja", "y\r"}, {"n", "nein", "n\r"}, ctrlC} + case InputConfirm: + return []InputButton{{"j", "ja", "\r"}, {"n", "nein", "n"}, ctrlC} + case InputPager: + return []InputButton{{"space", "weiter", " "}, {"q", "beenden", "q"}, ctrlC} + case InputAnyKey: + return []InputButton{{"enter", "weiter", "\r"}, ctrlC} + } + return nil +} diff --git a/internal/agent/notes.go b/internal/agent/notes.go new file mode 100644 index 0000000..782c1ad --- /dev/null +++ b/internal/agent/notes.go @@ -0,0 +1,63 @@ +package agent + +import ( + "fmt" + "strings" +) + +// Was der Mensch der KI außerhalb einer Rückfrage mitgibt, steht mit in den +// Antworten (answers), ist aber markiert, damit der Prompt es richtig +// benennt: eine Anweisung (Taste ? im Ziel-Modus), ein Hinweis von sshTermy +// (z. B. Verbindung war weg) oder ein früheres Ziel (Folgeziel). +const ( + markInstruct = "\x01" + markNotice = "\x02" + markPrior = "\x03" +) + +// Instruction: Anweisung des Menschen mitten im Lauf. +func Instruction(x string) string { return markInstruct + strings.TrimSpace(x) } + +// Notice: Hinweis von sshTermy an die KI. +func Notice(x string) string { return markNotice + strings.TrimSpace(x) } + +// PriorGoal: ein früheres Ziel in derselben Sitzung (Folgeziel). +// steps = so viele der bisherigen Schritte gehören zu ihm. +func PriorGoal(goal, result string, steps int) string { + result = strings.TrimSpace(result) + if r := []rune(result); len(r) > 600 { + result = string(r[:600]) + " …" + } + return markPrior + fmt.Sprint(steps) + "\n" + strings.Join(strings.Fields(goal), " ") + "\n" + result +} + +// IsInstruction: für die Oberfläche (Zeitleiste). +func IsInstruction(x string) (string, bool) { + if strings.HasPrefix(x, markInstruct) { + return x[len(markInstruct):], true + } + return "", false +} + +// answerLine formatiert eine Antwort für den Prompt. def ist die Zeile für +// eine normale Antwort auf eine Rückfrage. +func answerLine(x, def string) string { + switch { + case strings.HasPrefix(x, markInstruct): + return fmt.Sprintf("Anweisung des Menschen (gilt ab jetzt, geht deinem bisherigen Plan vor): %s\n", Redact(x[len(markInstruct):])) + case strings.HasPrefix(x, markNotice): + return fmt.Sprintf("Hinweis von sshTermy: %s\n", Redact(x[len(markNotice):])) + case strings.HasPrefix(x, markPrior): + n, rest, _ := strings.Cut(x[len(markPrior):], "\n") + goal, res, _ := strings.Cut(rest, "\n") + s := fmt.Sprintf("Früheres Ziel in dieser Sitzung (erledigt; die bisherigen Schritte 1 bis %s gehören dazu, das aktuelle Ziel baut darauf auf): %s\n", n, Redact(goal)) + if res != "" { + s += "Ergebnis damals:\n" + block(Redact(res)) + "\n" + } + return s + } + return fmt.Sprintf(def, Redact(x)) +} + +// IsPriorGoal: Eintrag aus PriorGoal (wird beim nächsten Folgeziel mitgenommen). +func IsPriorGoal(x string) bool { return strings.HasPrefix(x, markPrior) } diff --git a/internal/agent/notes_test.go b/internal/agent/notes_test.go new file mode 100644 index 0000000..d0feb38 --- /dev/null +++ b/internal/agent/notes_test.go @@ -0,0 +1,45 @@ +package agent + +import ( + "strings" + "testing" +) + +func TestAnswerLines(t *testing.T) { + def := "Antwort des Menschen: %s\n" + if got := answerLine("Port 8080", def); got != "Antwort des Menschen: Port 8080\n" { + t.Errorf("normale Antwort: %q", got) + } + if got := answerLine(Instruction("nimm apt"), def); !strings.HasPrefix(got, "Anweisung des Menschen") || !strings.Contains(got, "nimm apt") { + t.Errorf("Anweisung: %q", got) + } + if got := answerLine(Notice("Verbindung war weg"), def); !strings.HasPrefix(got, "Hinweis von sshTermy: ") { + t.Errorf("Hinweis: %q", got) + } + p := PriorGoal("Nginx installieren", "läuft auf Port 80", 7) + if !IsPriorGoal(p) { + t.Fatal("PriorGoal nicht erkennbar") + } + if got := answerLine(p, def); !strings.Contains(got, "Schritte 1 bis 7") || !strings.Contains(got, "Nginx installieren") || !strings.Contains(got, "läuft auf Port 80") { + t.Errorf("früheres Ziel: %q", got) + } + if got := answerLine(Instruction("password=geheim123"), def); strings.Contains(got, "geheim123") { + t.Error("Anweisung wird nicht geschwärzt") + } +} + +func TestManualAndNoteStatus(t *testing.T) { + var b strings.Builder + one := 1 + writeHist(&b, []DoneStep{ + {Command: "uptime", Manual: true, Output: "up 3 days"}, + {Command: "false", Manual: true, Exit: &one}, + {Command: "systemctl restart nginx", Skipped: true, Note: "läuft schon"}, + }) + s := b.String() + for _, want := range []string{"1. uptime (vom Menschen selbst ausgeführt)", "up 3 days", "2. false (vom Menschen selbst ausgeführt, Exit 1)", "übersprungen, Grund: läuft schon"} { + if !strings.Contains(s, want) { + t.Errorf("fehlt %q in\n%s", want, s) + } + } +} diff --git a/internal/agent/plan.go b/internal/agent/plan.go index 0d882be..24d7ff2 100644 --- a/internal/agent/plan.go +++ b/internal/agent/plan.go @@ -81,7 +81,7 @@ func (a *Agent) PlanNext(ctx context.Context, goal string, hist []DoneStep, answ b.WriteString("Dein bisheriger Plan:\n" + prev.text()) } for _, x := range answers { - fmt.Fprintf(&b, "Antwort des Menschen: %s\n", Redact(x)) + b.WriteString(answerLine(x, "Antwort des Menschen: %s\n")) } if mustPlan || prev != nil { b.WriteString("Erkunde nicht weiter: antworte jetzt mit \"planfertig\".\n") diff --git a/internal/domain/model.go b/internal/domain/model.go index d6353c9..d374e99 100644 --- a/internal/domain/model.go +++ b/internal/domain/model.go @@ -891,6 +891,23 @@ type Data struct { // TeamLinks: Team-Ordner (veröffentlichen bzw. abonnieren). Rein lokal: // Pfade sind je Rechner anders, das Team-Passwort bleibt auf dem Gerät. TeamLinks []TeamLink `json:"team_links,omitempty"` + + // GoalRuns: Zielverlauf (frühere Ziele je Verbindung). Rein lokal wie + // TeamLinks: Befehle und Ergebnisse bleiben auf diesem Rechner. + GoalRuns []GoalRun `json:"goal_runs,omitempty"` +} + +// GoalRun: ein früheres Ziel im Ziel-/Agent-/Plan-Modus (Zielverlauf). +type GoalRun struct { + ID string `json:"id"` + ConnID string `json:"conn"` + Goal string `json:"goal"` + Mode string `json:"mode,omitempty"` // "" Ziel-Modus, "agent", "plan" + Steps []string `json:"steps,omitempty"` + Result string `json:"result,omitempty"` + State string `json:"state"` // "done", "stopped", "lost" + At time.Time `json:"at"` + Took int `json:"took,omitempty"` // Sekunden } // CmdUse: wie oft ein Befehl auf einer Verbindung ohne Fehler lief diff --git a/internal/i18n/en_ux1112.go b/internal/i18n/en_ux1112.go new file mode 100644 index 0000000..82b2df6 --- /dev/null +++ b/internal/i18n/en_ux1112.go @@ -0,0 +1,94 @@ +package i18n + +// Ziel-Modus im Einsatz und Befehle als Blöcke (ui/goalux.go, +// ui/goalhistory.go, ui/cmdblocks.go), 2026-11-12. +func init() { + for k, v := range enUX1112 { + en[k] = v + } +} + +var enUX1112 = map[string]string{ + " … %d weitere": " … %d more", + "Anweisung gilt ab dem nächsten Schritt": "Instruction applies from the next step", + "Aus dem Zielverlauf entfernt": "Removed from goal history", + "Ausgabe kopieren": "copy output", + "Befehl %d/%d %s %s · Alt+O Liste": "Command %d/%d %s %s · Alt+O list", + "Befehl %d/%d ist nicht mehr im Verlauf: %s": "Command %d/%d is no longer in the scrollback: %s", + "Befehl oder Ausgabe suchen": "Search command or output", + "Befehl wartet auf eine Eingabe": "Command is waiting for input", + "Befehle dieses Tabs (Ausgabe kopieren, an KI)": "Commands in this tab (copy output, ask AI)", + "Befehle in %s · %d": "Commands in %s · %d", + "Das Ziel ist angehalten und wartet auf die neue Verbindung.": "The goal is paused and waiting for the new connection.", + "Das Ziel ist angehalten. Die KI prüft zuerst den Stand, der letzte Befehl ist eventuell nicht fertig geworden.": "The goal is paused. The AI checks the state first; the last command may not have finished.", + "Datei geändert": "file changed", + "Dateien geändert": "files changed", + "Erkläre die Ausgabe dieses Befehls und sag, ob etwas nicht stimmt:\n$ %s\n%s": "Explain the output of this command and tell me if something is wrong:\n$ %s\n%s", + "Fehler im Ziel-Modus": "Error in goal mode", + "Folgeziel": "follow-up goal", + "KI anweisen": "Instruct AI", + "Kopiert: Ausgabe von ": "Copied: output of ", + "Nichts zum Zurückholen": "Nothing to restore", + "Noch keine fertigen Befehle in diesem Tab": "No finished commands in this tab yet", + "Noch nicht wieder verbunden": "Not reconnected yet", + "Oder Esc und selbst im Terminal antworten.": "Or press Esc and answer in the terminal yourself.", + "Plan wartet auf Freigabe": "Plan is waiting for approval", + "Rückfrage der KI": "Question from the AI", + "Verbindung unterbrochen": "Connection interrupted", + "Verbindung wieder da, ⏎ führt den Schritt aus": "Connection is back, ⏎ runs the step", + "Verbindung wieder da, ⏎ setzt das Ziel fort": "Connection is back, ⏎ continues the goal", + "Warum soll dieser Schritt nicht laufen? Die KI richtet sich danach.": "Why shouldn't this step run? The AI will take it into account.", + "Was soll als Nächstes passieren? Die KI kennt das Ziel davor und seine Schritte.": "What should happen next? The AI knows the previous goal and its steps.", + "Was soll die KI anders machen oder beachten? Sie schlägt danach neu vor.": "What should the AI do differently or keep in mind? It will suggest again.", + "ZULETZT": "RECENT", + "Ziel erreicht": "Goal reached", + "Ziel fortsetzen": "continue goal", + "Ziel-Modus wartet auf dich": "Goal mode is waiting for you", + "Ziel: %s · %s · %s": "Goal: %s · %s · %s", + "Zielverlauf: ": "Goal history: ", + "Zum nächsten Befehl springen": "Jump to next command", + "Zum vorigen Befehl springen": "Jump to previous command", + "Zurück zur Live-Ansicht": "Back to the live view", + "Zurückholen braucht eine Verbindung mit SFTP": "Restoring needs a connection with SFTP", + "Zurückholen hat nicht geklappt, siehe Terminal. Die Sicherungen bleiben, u versucht es erneut.": "Restoring didn't work, see the terminal. The backups are kept, u tries again.", + "Zurückholen wartet auf ⏎": "Restore is waiting for ⏎", + "Zurückholen: ": "Restore: ", + "entfernen": "remove", + "erneut": "again", + "erreicht": "reached", + "ist ein Ordner": "is a folder", + "neu angelegt": "newly created", + "nicht lesbar": "not readable", + "nächster Schritt wartet auf deine Freigabe": "next step is waiting for your approval", + "ohne Sicherung: ": "no backup: ", + "selbst im Terminal": "answer in terminal", + "stellt die geänderten Dateien (%d) wieder so her, wie sie vor dem Ziel waren": "restores the changed files (%d) to how they were before the goal", + "Strg+C": "Ctrl+C", + "z. B. der Dienst läuft schon, nicht neu starten": "e.g. the service is already running, don't restart it", + "z. B. jetzt noch HTTPS mit Let's Encrypt einrichten": "e.g. now also set up HTTPS with Let's Encrypt", + "z. B. nimm docker compose statt docker-compose": "e.g. use docker compose instead of docker-compose", + "zu groß": "too large", + "Änderungen des Ziels zurückgenommen": "Changes made by the goal were reverted", + "Änderungen zurückgenommen: ": "Changes reverted: ", + "Überspringen mit Grund": "Skip with a reason", + "→ Folgeziel nach: ": "→ Follow-up to: ", + "← Änderungen des Ziels zurückholen": "← Restore what the goal changed", + "▸ Der Befehl wartet auf eine Eingabe": "▸ The command is waiting for input", + "▪ sichert die Dateien, die der Schritt ändert …": "▪ backing up the files this step changes …", + "▲ Die Verbindung war unterbrochen": "▲ The connection was interrupted", + "▲ Verbindung unterbrochen": "▲ Connection interrupted", + "• Du hast inzwischen selbst etwas ausgeführt, r holt einen neuen Vorschlag": "• You ran something yourself in the meantime, r fetches a new suggestion", + // Hilfe (ui/help.go) + "Befehle des Tabs: Ausgabe kopieren, an KI": "Commands of the tab: copy output, ask AI", + "Alt+Bild↑ Bild↓": "Alt+PgUp PgDn", + "von Befehl zu Befehl springen": "jump from command to command", + "überspringen / mit Grund": "skip / with a reason", + "KI anweisen (gilt ab dem nächsten Schritt)": "instruct AI (applies from the next step)", + "j n q Leertaste": "j n q Space", + "Befehl fragt nach: Antwort-Knöpfe": "command asks: answer buttons", + "Folgeziel (kennt die Schritte davor)": "follow-up goal (knows the steps before)", + "Änderungen des Ziels zurückholen": "restore what the goal changed", + "⏎ nach Abbruch": "⏎ after a drop", + "Runbook oder früheres Ziel wählen": "choose runbook or earlier goal", + "Runbook / Verlaufseintrag löschen": "delete runbook / history entry", +} diff --git a/internal/store/goalruns.go b/internal/store/goalruns.go new file mode 100644 index 0000000..547e14e --- /dev/null +++ b/internal/store/goalruns.go @@ -0,0 +1,83 @@ +package store + +import ( + "sort" + + "github.com/db9979/sshtermy/internal/domain" + "github.com/db9979/sshtermy/internal/vault" +) + +// Zielverlauf: rein lokal wie Team-Ordner (persist, kein Sync, kein +// Grabstein). Je Verbindung bleiben die letzten goalRunsPer Einträge. +const goalRunsPer = 30 + +// GoalRuns: frühere Ziele einer Verbindung, neueste zuerst. +func (s *Store) GoalRuns(connID string) []domain.GoalRun { + s.mu.RLock() + defer s.mu.RUnlock() + if s.data == nil { + return nil + } + var out []domain.GoalRun + for _, r := range s.data.GoalRuns { + if r.ConnID == connID { + out = append(out, r) + } + } + sort.SliceStable(out, func(i, j int) bool { return out[i].At.After(out[j].At) }) + return out +} + +// AddGoalRun hängt ein Ziel an (ID wird vergeben) und kürzt den Verlauf. +func (s *Store) AddGoalRun(r domain.GoalRun) error { + s.Fresh() + s.mu.Lock() + if s.data == nil { + s.mu.Unlock() + return vault.ErrLocked + } + if r.ID == "" { + r.ID = "g" + newID() + } + s.data.GoalRuns = append(s.data.GoalRuns, r) + // je Verbindung nur die neuesten goalRunsPer behalten + n, drop := 0, map[int]bool{} + for i := len(s.data.GoalRuns) - 1; i >= 0; i-- { + if s.data.GoalRuns[i].ConnID == r.ConnID { + n++ + if n > goalRunsPer { + drop[i] = true + } + } + } + if len(drop) > 0 { + keep := make([]domain.GoalRun, 0, len(s.data.GoalRuns)-len(drop)) + for i, x := range s.data.GoalRuns { + if !drop[i] { + keep = append(keep, x) + } + } + s.data.GoalRuns = keep + } + s.mu.Unlock() + return s.persist() +} + +// DeleteGoalRun entfernt einen Eintrag aus dem Zielverlauf. +func (s *Store) DeleteGoalRun(id string) error { + s.Fresh() + s.mu.Lock() + if s.data == nil { + s.mu.Unlock() + return vault.ErrLocked + } + rs := s.data.GoalRuns[:0] + for _, r := range s.data.GoalRuns { + if r.ID != id { + rs = append(rs, r) + } + } + s.data.GoalRuns = rs + s.mu.Unlock() + return s.persist() +} diff --git a/internal/store/goalruns_test.go b/internal/store/goalruns_test.go new file mode 100644 index 0000000..6a97227 --- /dev/null +++ b/internal/store/goalruns_test.go @@ -0,0 +1,60 @@ +package store + +import ( + "fmt" + "testing" + "time" + + "github.com/db9979/sshtermy/internal/domain" +) + +func TestGoalRuns(t *testing.T) { + t.Setenv("SSHTERMY_HOME", t.TempDir()) + st, err := Open() + if err != nil { + t.Fatal(err) + } + if err := st.Init([]byte("correct horse"), false); err != nil { + t.Fatal(err) + } + base := time.Now() + for i := 0; i < goalRunsPer+5; i++ { + if err := st.AddGoalRun(domain.GoalRun{ConnID: "a", Goal: fmt.Sprint("ziel ", i), State: "done", At: base.Add(time.Duration(i) * time.Minute)}); err != nil { + t.Fatal(err) + } + } + if err := st.AddGoalRun(domain.GoalRun{ConnID: "b", Goal: "anderes", State: "stopped", At: base}); err != nil { + t.Fatal(err) + } + runs := st.GoalRuns("a") + if len(runs) != goalRunsPer || runs[0].Goal != fmt.Sprint("ziel ", goalRunsPer+4) || runs[len(runs)-1].Goal != "ziel 5" { + t.Fatalf("Verlauf a: %d, erster %q, letzter %q", len(runs), runs[0].Goal, runs[len(runs)-1].Goal) + } + ids := map[string]bool{} + for _, r := range runs { + if ids[r.ID] { + t.Fatalf("doppelte ID %s", r.ID) + } + ids[r.ID] = true + } + if err := st.DeleteGoalRun(runs[0].ID); err != nil { + t.Fatal(err) + } + if len(st.GoalRuns("a")) != goalRunsPer-1 || len(st.GoalRuns("b")) != 1 { + t.Error("Löschen trifft den falschen Eintrag") + } + // bleibt nach dem Neuladen (lokal gespeichert) + st2, err := Open() + if err != nil { + t.Fatal(err) + } + if err := st2.V.UnlockPassword([]byte("correct horse")); err != nil { + t.Fatal(err) + } + if err := st2.AfterUnlock(); err != nil { + t.Fatal(err) + } + if len(st2.GoalRuns("b")) != 1 { + t.Error("Zielverlauf nicht gespeichert") + } +} diff --git a/internal/ui/agentmode.go b/internal/ui/agentmode.go index 2bb7243..50afda0 100644 --- a/internal/ui/agentmode.go +++ b/internal/ui/agentmode.go @@ -205,8 +205,7 @@ func (a *App) agentExec(s *session) tea.Cmd { if g.cur.File != nil { return a.writeAgentFile(s) } - a.runProposal(s, g.cur.Command, false) - return nil + return a.execProposal(s, g.cur.Command, false) // ändert er Dateien, erst sichern (goalux.go) } // agentNext holt den nächsten Schritt, wenn keine Grenze greift. @@ -521,6 +520,10 @@ func (a *App) agentKey(s *session, key string) (tea.Cmd, bool) { case "v": a.agentView(s) return nil, true + case "f": + return a.startFollowGoal(s), true + case "u": + return a.startUndo(s), true } return nil, false } @@ -550,6 +553,10 @@ func (a *App) agentKey(s *session, key string) (tea.Cmd, bool) { if g.cur != nil { return a.agentResume(s), true } + case "S": + if g.cur != nil { + return a.goalSkipWhy(s), true + } case "s", "n": if g.cur != nil { g.steps = append(g.steps, agent.DoneStep{Command: g.cur.CommandOrFile(), Skipped: true}) diff --git a/internal/ui/agentmode_view.go b/internal/ui/agentmode_view.go index 9928de4..7e57c63 100644 --- a/internal/ui/agentmode_view.go +++ b/internal/ui/agentmode_view.go @@ -175,8 +175,9 @@ func (a *App) viewAgentDone(b *strings.Builder, s *session, w int) { if len(g.files) > 0 && !g.cleaned { keys = append(keys, [2]string{"r", i18n.T("Skripte auf dem Host löschen")}, [2]string{"v", i18n.T("Skript ansehen")}) } - keys = append(keys, [2]string{"⏎", i18n.T("neues Ziel")}) + keys = append(keys, [2]string{"f", i18n.T("Folgeziel")}, [2]string{"⏎", i18n.T("neues Ziel")}) b.WriteString(a.hintsIn(s, st.Muted, keys...)) + a.viewBackups(b, s, w, "u") } // agentPanelKeys: Fußzeile im Agent-Modus (nil = Ziel-Modus-Tasten). @@ -190,7 +191,10 @@ func (a *App) agentPanelKeys(s *session) [][2]string { if len(g.files) > 0 && !g.cleaned { k = append(k, [2]string{"r", i18n.T("aufräumen")}, [2]string{"v", i18n.T("Skript ansehen")}) } - return append(k, [2]string{"⏎", i18n.T("neues Ziel")}, [2]string{"Esc", "Terminal"}) + if len(g.backups) > 0 { + k = append(k, [2]string{"u", i18n.T("zurückholen")}) + } + return append(k, [2]string{"f", i18n.T("Folgeziel")}, [2]string{"⏎", i18n.T("neues Ziel")}, [2]string{"Esc", "Terminal"}) case !g.active: return [][2]string{{"⏎", i18n.T("Plan zeigen")}, {"Tab", i18n.T("Modus")}, {"Esc", "Terminal"}} case g.editing, g.cur != nil && g.cur.Question != "": diff --git a/internal/ui/cmdblocks.go b/internal/ui/cmdblocks.go new file mode 100644 index 0000000..6fa5985 --- /dev/null +++ b/internal/ui/cmdblocks.go @@ -0,0 +1,205 @@ +package ui + +// Befehle als Blöcke (2026-11-12): Jeder fertige Befehl im Tab wird mit +// seiner Ausgabe gemerkt (cmdlog.go, auch ohne Sitzungsprotokoll; Befehle +// mit Leerzeichen davor nicht). Alt+Bild↑/↓ springt im Verlauf von Befehl zu +// Befehl, Alt+O zeigt die Liste: ⏎ springt hin, Strg+C kopiert die Ausgabe, +// Strg+K gibt Befehl und Ausgabe an „KI fragen“, Strg+L zeigt sie groß. + +import ( + "fmt" + "strconv" + "strings" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/atotto/clipboard" + "github.com/charmbracelet/x/ansi" + + "github.com/db9979/sshtermy/internal/i18n" +) + +type cmdBlock struct { + cmd string + out string + at time.Time + dur time.Duration + failed bool + exit *int + line int // Zeile im Verlauf beim Start (verschiebt sich, wenn der Verlauf voll ist) +} + +const maxBlocks = 200 + +// promptLine: Zeile des Cursors im gesamten Verlauf. +func (s *session) promptLine() int { + if s.term == nil { + return -1 + } + _, y, _ := s.term.Cursor() + return s.term.ScrollbackLen() + y +} + +// addBlock (aus finishCommand). +func (s *session) addBlock(r *cmdRun, out string, failed bool, exit *int, dur time.Duration) { + if r == nil || r.private || strings.TrimSpace(r.cmd) == "" { + return + } + s.blocks = append(s.blocks, cmdBlock{cmd: r.cmd, out: out, at: r.at, dur: dur, failed: failed, exit: exit, line: r.line}) + if n := len(s.blocks); n > maxBlocks { + s.blocks = append(s.blocks[:0:0], s.blocks[n-maxBlocks:]...) + s.blockNav = 0 + } +} + +// locateBlock: in welcher Zeile steht der Befehl jetzt? Gesucht wird die +// Zeile mit dem Befehlstext, die der gemerkten am nächsten liegt (-1 = nicht +// mehr im Verlauf). +func (s *session) locateBlock(b cmdBlock) int { + if s.term == nil { + return -1 + } + q := b.cmd + if r := []rune(q); len(r) > 60 { + q = string(r[:60]) + } + best, bestD := -1, 1<<30 + for _, m := range s.term.Search(q, false) { + d := m.Line - b.line + if d < 0 { + d = -d + } + if d < bestD { + best, bestD = m.Line, d + } + } + return best +} + +// jumpBlock: Alt+Bild↑ (d = -1) / Alt+Bild↓ (d = +1). +func (a *App) jumpBlock(s *session, d int) { + if s.term == nil { + return + } + n := len(s.blocks) + if n == 0 { + a.flash(i18n.T("Noch keine fertigen Befehle in diesem Tab")) + return + } + cur := n // live + if s.blockNav > 0 && s.scroll == s.blockScroll { + cur = s.blockNav - 1 + } + i := cur + d + if i >= n { + s.blockNav, s.scroll = 0, 0 + a.flash(i18n.T("Zurück zur Live-Ansicht")) + return + } + if i < 0 { + i = 0 + } + a.revealBlock(s, i) +} + +func (a *App) revealBlock(s *session, i int) { + b := s.blocks[i] + ln := s.locateBlock(b) + if ln < 0 { + s.blockNav, s.blockScroll = i+1, s.scroll + a.flash(fmt.Sprintf(i18n.T("Befehl %d/%d ist nicht mehr im Verlauf: %s"), i+1, len(s.blocks), trunc(b.cmd, 40))) + return + } + sb := s.term.ScrollbackLen() + first := clamp(ln-1, 0, sb) + s.scroll, s.sbSeen = sb-first, sb + s.blockNav, s.blockScroll = i+1, s.scroll + mark := "✓" + if b.failed { + mark = "×" + } + a.flash(fmt.Sprintf(i18n.T("Befehl %d/%d %s %s · Alt+O Liste"), i+1, len(s.blocks), mark, trunc(b.cmd, 50))) +} + +// openBlocks: Alt+O, die Befehle dieses Tabs, neueste oben. +func (a *App) openBlocks(s *session) tea.Cmd { + if len(s.blocks) == 0 { + a.flash(i18n.T("Noch keine fertigen Befehle in diesem Tab")) + return nil + } + var items []pickItem + for i := len(s.blocks) - 1; i >= 0; i-- { + b := s.blocks[i] + hint := "✓" + switch { + case b.exit != nil && *b.exit != 0: + hint = fmt.Sprintf("× %d", *b.exit) + case b.failed: + hint = "×" + } + detail := b.at.Format("15:04") + if b.dur >= time.Second { + detail += " · " + fmtDur(b.dur) + } + if l := lastLine(b.out); l != "" { + detail += " · " + trunc(l, 40) + } + items = append(items, pickItem{value: strconv.Itoa(i), label: "$ " + trunc(b.cmd, max(20, a.w-50)), detail: detail, hint: hint, search: b.out}) + } + p := newPicker(fmt.Sprintf(i18n.T("Befehle in %s · %d"), trunc(s.tabName(), 24), len(s.blocks)), i18n.T("Befehl oder Ausgabe suchen"), items, "\x00", func(it pickItem) tea.Cmd { + if i, err := strconv.Atoi(it.value); err == nil && i < len(s.blocks) { + a.revealBlock(s, i) + } + return nil + }) + p.keys = [][2]string{{"⏎", i18n.T("hinspringen")}, {"Strg+C", i18n.T("Ausgabe kopieren")}, {"Strg+K", i18n.T("KI fragen")}, {"Strg+L", i18n.T("ganz lesen")}, {"Esc", i18n.T("zurück")}} + p.onKey = func(key string, it *pickItem) (tea.Cmd, bool) { + if it == nil { + return nil, false + } + i, err := strconv.Atoi(it.value) + if err != nil || i >= len(s.blocks) { + return nil, false + } + b := s.blocks[i] + switch key { + case "ctrl+c": + a.pick = nil + return a.copyBlock(b), true + case "ctrl+k": + a.pick = nil + return a.askBlock(s, b), true + case "ctrl+l": + a.pick = nil + a.readBlock(b) + return nil, true + } + return nil, false + } + return a.openPicker(p) +} + +func (a *App) copyBlock(b cmdBlock) tea.Cmd { + text := strings.TrimRight(b.out, "\n") + go func() { _ = clipboard.WriteAll(text) }() + a.flash(i18n.T("Kopiert: Ausgabe von ") + trunc(b.cmd, 40) + " (" + plural(countLines(text), i18n.T("Zeile"), i18n.T("Zeilen")) + ")") + return tea.SetClipboard(text) +} + +func (a *App) readBlock(b cmdBlock) { + w := max(20, dialog{maxW: 200}.innerMax(a.w)) + text := "$ " + b.cmd + "\n" + strings.TrimRight(b.out, "\n") + m := textModal("$ "+trunc(b.cmd, 50), strings.Split(ansi.Wrap(text, w, ""), "\n")) + m.copy = strings.TrimRight(b.out, "\n") + a.modal = m +} + +// askBlock: Befehl und Ausgabe an „KI fragen“. +func (a *App) askBlock(s *session, b cmdBlock) tea.Cmd { + out := strings.TrimRight(b.out, "\n") + if r := []rune(out); len(r) > 6000 { + out = "…\n" + string(r[len(r)-6000:]) + } + q := fmt.Sprintf(i18n.T("Erkläre die Ausgabe dieses Befehls und sag, ob etwas nicht stimmt:\n$ %s\n%s"), b.cmd, out) + return a.startAsk(s, q) +} diff --git a/internal/ui/cmdlog.go b/internal/ui/cmdlog.go index f0afb7b..cc3f35c 100644 --- a/internal/ui/cmdlog.go +++ b/internal/ui/cmdlog.go @@ -33,6 +33,7 @@ type cmdRun struct { agent bool // vom Agent-Modus ausgeführt sent bool // von sshTermy gesendet (sendLine), nicht getippt contWhy string // blieb am Fortsetzungs-Prompt „>“ hängen, Strg+C geschickt (contprompt.go) + line int // Zeile im Verlauf, in der der Befehl stand (cmdblocks.go) } // beginCommand: Enter mit einem Befehl am Prompt. @@ -43,7 +44,7 @@ func (a *App) beginCommand(s *session, typed string) { return } seq, _ := s.term.LastExit() - s.run = &cmdRun{cmd: cmd, at: time.Now(), exitSeq: seq, private: strings.HasPrefix(typed, " ")} + s.run = &cmdRun{cmd: cmd, at: time.Now(), exitSeq: seq, private: strings.HasPrefix(typed, " "), line: s.promptLine()} s.fail = nil } @@ -94,6 +95,8 @@ func (a *App) finishCommand(s *session) { if r.contWhy != "" { // am „>“ hängen geblieben, Strg+C kam von uns failed, f.Reason = true, contReason(r.contWhy) } + // Selbst getippt während eines Ziels: als eigener Schritt (goalux.go) + a.noteManualStep(s, r, out, f, failed) // Ziel-/Agent-Modus: Ausgabe und Exit-Code gehen an das Modell if g := &s.goal; g.active && len(g.steps) > 0 && strings.HasPrefix(r.cmd, g.steps[len(g.steps)-1].Command) { g.steps[len(g.steps)-1].Output, g.steps[len(g.steps)-1].Exit = sessionlog.Clip(out), f.Exit @@ -122,7 +125,8 @@ func (a *App) finishCommand(s *session) { } a.auditCommand(s, r, failed, f.Exit) a.companionAfter(s, r, f, failed) - a.vgCommandDone(s, r, out, failed, f) // Vorgang über mehrere Fenster (vorgang_run.go) + a.vgCommandDone(s, r, out, failed, f) // Vorgang über mehrere Fenster (vorgang_run.go) + s.addBlock(r, out, failed, f.Exit, end.Sub(r.at)) // Befehle als Blöcke (cmdblocks.go) if failed && !r.interrupted && !r.agent { a.cardFailed(s, f) // Befehl aus einer Antwortkarte? (cardfix.go) } diff --git a/internal/ui/goalhistory.go b/internal/ui/goalhistory.go new file mode 100644 index 0000000..f29a17a --- /dev/null +++ b/internal/ui/goalhistory.go @@ -0,0 +1,173 @@ +package ui + +// Zielverlauf je Verbindung (2026-11-12): jedes Ziel, das erreicht oder mit +// x beendet wird, landet mit seinen Befehlen im Verlauf (nur auf diesem +// Rechner, store/goalruns.go). Im Eingabebild des Ziel-Modus steht er unter +// den Runbooks; ↑↓ wählt, ⏎ startet das Ziel erneut (erreichte Ziele mit +// ihren Befehlen als Vorlage), Strg+D löscht den Eintrag. + +import ( + "errors" + "fmt" + "strings" + "time" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + + "github.com/db9979/sshtermy/internal/domain" + "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/vault" +) + +const goalHistShown = 5 + +// recordGoal schreibt das aktuelle Ziel in den Verlauf (einmal je Ziel). +func (a *App) recordGoal(s *session, state string) { + g := &s.goal + if g.recorded || strings.TrimSpace(g.goal) == "" || g.undoing { + return + } + if len(g.steps) == 0 && state != "done" { + return + } + g.recorded = true + var steps []string + for _, d := range g.steps { + if d.Skipped || d.File != "" { + continue + } + steps = append(steps, d.Command) + } + if len(steps) > 60 { + steps = steps[len(steps)-60:] + } + mode := "" + switch { + case g.approved || g.planFirst: + mode = "plan" + case g.auto: + mode = "agent" + } + took := 0 + if !g.goalAt.IsZero() { + took = int(time.Since(g.goalAt).Seconds()) + } + r := domain.GoalRun{ConnID: s.conn.ID, Goal: g.goal, Mode: mode, Steps: steps, State: state, At: time.Now(), Took: took} + if state == "done" { + r.Result = g.doneReason + if rs := []rune(r.Result); len(rs) > 1000 { + r.Result = string(rs[:1000]) + " …" + } + } + if err := a.st.AddGoalRun(r); err != nil && !errors.Is(err, vault.ErrLocked) { + a.flashErr(i18n.T("Zielverlauf: ") + err.Error()) + } +} + +// goalHist: Verlaufseinträge, wie das Eingabebild sie zeigt. +func (a *App) goalHist(s *session) []domain.GoalRun { + h := a.st.GoalRuns(s.conn.ID) + if len(h) > goalHistShown { + h = h[:goalHistShown] + } + return h +} + +// goalPickCount: Runbooks + Verlauf (gemeinsame Auswahl mit ↑↓). +func (a *App) goalPickCount(s *session) (rbs []domain.Runbook, hist []domain.GoalRun) { + return a.st.Runbooks(s.conn.ID), a.goalHist(s) +} + +// goalPickSet: Auswahl i (Runbooks zuerst, dann Verlauf) in die Eingabe. +func (a *App) goalPickSet(s *session, i int) { + g := &s.goal + rbs, hist := a.goalPickCount(s) + g.rbSel = i + switch { + case i >= 0 && i < len(rbs): + g.input.SetValue(rbs[i].Goal) + case i >= len(rbs) && i-len(rbs) < len(hist): + g.input.SetValue(hist[i-len(rbs)].Goal) + default: + g.rbSel = -1 + g.input.SetValue("") + } + g.input.CursorEnd() +} + +// startGoalRun: ein Ziel aus dem Verlauf noch einmal. +func (a *App) startGoalRun(s *session, r domain.GoalRun) tea.Cmd { + if r.State == "done" && len(r.Steps) > 0 { + rb := domain.Runbook{Goal: r.Goal, Steps: r.Steps} + cmd := a.startGoalWith(s, r.Goal, &rb) + s.goal.runbookID = "" + return cmd + } + return a.startGoal(s, r.Goal) +} + +func (a *App) deleteGoalRun(s *session, r domain.GoalRun) { + if err := a.st.DeleteGoalRun(r.ID); err != nil { + a.flashErr(err.Error()) + return + } + s.goal.rbSel = -1 + s.goal.input.SetValue("") + a.flash(i18n.T("Aus dem Zielverlauf entfernt")) +} + +func goalRunMeta(r domain.GoalRun) string { + mark := "✓" + switch r.State { + case "stopped": + mark = "×" + case "lost": + mark = "▲" + } + when := r.At.Format("02.01. 15:04") + if i18n.Lang() == "en" { + when = r.At.Format("Jan 2 15:04") + } + if time.Since(r.At) < 20*time.Hour && r.At.Day() == time.Now().Day() { + when = r.At.Format("15:04") + } + return fmt.Sprintf("%s %s · %d", mark, when, len(r.Steps)) +} + +// viewGoalHist: „ZULETZT“ unter den Runbooks im Eingabebild. +func (a *App) viewGoalHist(b *strings.Builder, s *session, w, base int) { + st := a.s + g := &s.goal + hist := a.goalHist(s) + if len(hist) == 0 { + return + } + b.WriteString("\n\n" + st.Muted.Render(i18n.T("ZULETZT")+" ") + a.hintsIn(s, st.Muted, [2]string{"↑↓", i18n.T("wählen")}, [2]string{"⏎", i18n.T("erneut")}, [2]string{"Strg+D", i18n.T("entfernen")}) + "\n") + for i, r := range hist { + meta := goalRunMeta(r) + line := "◷ " + trunc(r.Goal, max(8, w-lipgloss.Width(meta)-4)) + gap := max(1, w-lipgloss.Width(line)-lipgloss.Width(meta)) + ms := st.Muted + switch r.State { + case "done": + ms = st.OK + case "stopped", "lost": + ms = st.Warn + } + row := st.Muted.Render("◷ ") + st.Text.Render(strings.TrimPrefix(line, "◷ ")) + strings.Repeat(" ", gap) + ms.Render(meta) + idx := base + i + if idx == g.rbSel { + 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 { + s.panelFocus = true + a.goalPickSet(s, idx) + if double { + return a.startGoalRun(s, r) + } + return g.input.Focus() + }) + "\n") + } +} diff --git a/internal/ui/goalux.go b/internal/ui/goalux.go new file mode 100644 index 0000000..f0a8c47 --- /dev/null +++ b/internal/ui/goalux.go @@ -0,0 +1,779 @@ +package ui + +// Ziel-Modus im Einsatz (2026-11-12, Vorschläge 1–8 und 10): +// +// - ? gibt der KI mitten im Ziel eine Anweisung (wie im Agent-Modus), +// ⇧S überspringt einen Schritt mit Grund. +// - Wartet ein Befehl auf eine Eingabe ([Y/n], Pager, --More--, „Press any +// key“), zeigt das Panel Knöpfe dafür; der Agent hält dort an. +// - Wartet das Ziel auf dich und der Tab ist nicht zu sehen, gibt es eine +// Einblendung, im Hintergrund eine Desktop-Meldung; der Tab zeigt den +// Zustand des Ziels und die Schrittzahl. +// - f startet nach „Ziel erreicht“ ein Folgeziel, das die Schritte davor kennt. +// - Vor Schritten, die Dateien ändern, sichert sshTermy sie per SFTP; +// u holt am Ende alles zurück. +// - Zielverlauf je Verbindung im Eingabebildschirm (goalhistory.go). +// - Reißt die Verbindung ab, hält das Ziel an; nach dem Neuverbinden setzt +// ⏎ es fort. +// - Was du während des Ziels selbst tippst, bekommt die KI als Schritt mit +// Ausgabe. + +import ( + "errors" + "fmt" + "io" + "io/fs" + "strconv" + "strings" + "time" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + + "github.com/db9979/sshtermy/internal/agent" + "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/sessionlog" + "github.com/db9979/sshtermy/internal/sshx" +) + +// ---------------------------------------------------------------- 1 Anweisung + +// goalInstruct: ? im Ziel-Modus (Schritt für Schritt). Die Anweisung gilt ab +// dem nächsten Vorschlag; ein offener Vorschlag wird verworfen. +func (a *App) goalInstruct(s *session) tea.Cmd { + g := &s.goal + a.modal = inputModal(i18n.T("KI anweisen"), i18n.T("Was soll die KI anders machen oder beachten? Sie schlägt danach neu vor."), "", func(x string) tea.Cmd { + x = strings.TrimSpace(x) + if x == "" || !g.active { + return nil + } + g.answers = append(g.answers, agent.Instruction(x)) + if g.waiting || g.writing || g.backingUp { + a.flash(i18n.T("Anweisung gilt ab dem nächsten Schritt")) + return nil + } + g.cur, g.armed, g.editing = nil, false, false + return a.goalNext(s) + }) + a.modal.in.Placeholder = i18n.T("z. B. nimm docker compose statt docker-compose") + return nil +} + +// goalSkipWhy: ⇧S überspringt den Vorschlag und sagt der KI, warum. +func (a *App) goalSkipWhy(s *session) tea.Cmd { + g := &s.goal + if g.cur == nil { + return nil + } + cur := g.cur + a.modal = inputModal(i18n.T("Überspringen mit Grund"), i18n.T("Warum soll dieser Schritt nicht laufen? Die KI richtet sich danach."), "", func(x string) tea.Cmd { + if g.cur != cur { + return nil + } + g.steps = append(g.steps, agent.DoneStep{Command: cur.CommandOrFile(), Skipped: true, Note: strings.TrimSpace(x)}) + g.cur, g.armed = nil, false + if g.auto { + g.paused, g.pauseWhy, g.planOK = false, "", true + } + return a.goalNext(s) + }) + a.modal.in.Placeholder = i18n.T("z. B. der Dienst läuft schon, nicht neu starten") + return nil +} + +// ---------------------------------------------------------------- 2 Eingabe erwartet + +// inputWaitTick (aus goalTick): steht ein laufender Schritt an einer Rückfrage? +func (a *App) inputWaitTick(s *session, quiet bool) { + g := &s.goal + if !g.waiting || s.term == nil { + g.inputWait = "" + return + } + if !quiet { + g.inputWait = "" + return + } + if s.term.AtIdlePrompt() { + return + } + line := s.term.CursorLine() + if agent.LooksLikeSecretPrompt(line) { + return // Passwort: agentTick hält an, der Mensch tippt selbst + } + k := agent.InputWait(line, s.term.AltScreen()) + if k == agent.InputNone || k == g.inputWait { + return + } + g.inputWait, g.inputLine = k, strings.TrimSpace(line) + if g.auto { + a.agentPause(s, i18n.T("Befehl wartet auf eine Eingabe")) + } +} + +// inputWaitKey: Knöpfe j/n/q/Leertaste/⏎/Strg+C, solange ein Befehl fragt. +func (a *App) inputWaitKey(s *session, key string) (tea.Cmd, bool) { + g := &s.goal + if key == "y" { + key = "j" + } + for _, b := range agent.InputKeys(g.inputWait) { + if b.Key == key { + a.sendInputAnswer(s, b.Send) + return nil, true + } + } + switch key { + case "esc", "x", "?", "ctrl+s": + return nil, false + } + return nil, true // andere Tasten nicht als Ziel-Tasten deuten +} + +func (a *App) sendInputAnswer(s *session, send string) { + g := &s.goal + if s.term == nil { + return + } + s.term.SendText(send) + g.inputWait, g.inputLine = "", "" + g.waitSince = time.Now() // neue Ausgabe abwarten + if g.auto && g.paused && g.pauseWhy == i18n.T("Befehl wartet auf eine Eingabe") { + g.paused, g.pauseWhy = false, "" + } +} + +func inputKeyLabel(k string) string { + switch k { + case "space": + return i18n.T("Leertaste") + case "enter": + return "⏎" + case "ctrl+c": + return i18n.T("Strg+C") + } + return k +} + +func (a *App) inputWaitHints(s *session) [][2]string { + var out [][2]string + for _, b := range agent.InputKeys(s.goal.inputWait) { + out = append(out, [2]string{inputKeyLabel(b.Key), i18n.T(b.Label)}) + } + return append(out, [2]string{"Esc", i18n.T("selbst im Terminal")}) +} + +func (a *App) viewInputWait(b *strings.Builder, s *session, w int) { + st := a.s + g := &s.goal + b.WriteString(st.Warn.Render(i18n.T("▸ Der Befehl wartet auf eine Eingabe")) + "\n") + if g.inputLine != "" { + b.WriteString(st.Panel.Width(w).Render(wrap(st.Text.Render(g.inputLine), w-4)) + "\n") + } + var row []string + 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 { + a.sendInputAnswer(s, send) + return nil + })) + } + b.WriteString(strings.Join(row, " ") + "\n") + b.WriteString(st.Muted.Render(i18n.T("Oder Esc und selbst im Terminal antworten.")) + "\n") +} + +// ---------------------------------------------------------------- 3 + 10 Wartet auf dich + +// goalAttention: wartet das Ziel gerade auf dich? key ändert sich mit jedem +// neuen Anlass (für die Meldung), why ist der Text dazu. +func (a *App) goalAttention(s *session) (key, why string) { + g := &s.goal + switch { + case g.inputWait != "" && g.waiting: + return "in" + string(g.inputWait) + g.inputLine, i18n.T("Befehl wartet auf eine Eingabe") + case g.lost && g.active: + if s.state == stConnected { + return "lost", i18n.T("Verbindung wieder da, ⏎ setzt das Ziel fort") + } + return "", "" + case g.done && !g.active && !g.doneSeen: + return fmt.Sprintf("done%d", g.seq), i18n.T("Ziel erreicht") + case !g.active || g.busy || g.waiting || g.writing || g.backingUp || g.manualPending: + return "", "" + case g.undoing: + return "undo", i18n.T("Zurückholen wartet auf ⏎") + case g.planReview(): + return "plan", i18n.T("Plan wartet auf Freigabe") + case g.cur != nil && g.cur.Question != "": + return fmt.Sprintf("q%d", g.seq), i18n.T("Rückfrage der KI") + case g.auto && g.paused: + return "p" + g.pauseWhy + strconv.Itoa(g.seq), i18n.T("Agent angehalten: ") + g.pauseWhy + case g.auto: + return "", "" + case g.err != "": + return "e" + g.err, i18n.T("Fehler im Ziel-Modus") + case g.cur != nil: + return fmt.Sprintf("s%d", g.seq), i18n.T("nächster Schritt wartet auf deine Freigabe") + } + return "", "" +} + +// goalNotifyTick (aus goalTick): meldet einen neuen Anlass, wenn der Tab +// nicht zu sehen ist oder sshTermy im Hintergrund läuft. +func (a *App) goalNotifyTick(s *session) { + g := &s.goal + key, why := a.goalAttention(s) + if key == g.attnKey { + return + } + g.attnKey = key + if key == "" || !a.notifyOn() { + return + } + if a.sessionVisible(s) && !a.blurred { + return + } + if !a.sessionVisible(s) { + a.flash(ic("ai") + " " + s.tabName() + ": " + why) + s.flashTab(a.s.T.Warn) + } + if (a.blurred || a.lock != nil) && a.desktopNotifyOn() && time.Since(g.attnDesk) > 20*time.Second { + g.attnDesk = time.Now() + body := why + if a.lock != nil { + body = i18n.T("Ziel-Modus wartet auf dich") // gesperrt: nichts verraten + } + a.sendDesktop("sshTermy · "+s.tabName(), body) + } +} + +// goalGlyph: Zeichen im Tab für ein Ziel ("" = keins). ◎ Ziel-Modus, +// ◆ Agent, ◇ Plan; violett = läuft, gelb = wartet auf dich, grün = fertig +// (bis du den Tab ansiehst). +func (a *App) goalGlyph(x *session) string { + st := a.s + g := &x.goal + glyph := "◎" + switch { + case g.planning || g.planReview(): + glyph = "◇" + case g.auto: + glyph = "◆" + } + switch { + case g.active || g.lost: + if key, _ := a.goalAttention(x); key != "" { + return st.Warn.Render(glyph) + } + return st.AI.Render(glyph) + case g.done && !g.doneSeen: + return st.OK.Render(glyph) + } + return "" +} + +// goalTabCount: Schrittzahl hinter dem Tab-Namen, solange ein Ziel läuft. +func goalTabCount(x *session) string { + if g := &x.goal; g.active && len(g.steps) > 0 { + return " ·" + strconv.Itoa(len(g.steps)) + } + return "" +} + +// goalTip: Zeile für den Tooltip des Tabs. +func (a *App) goalTip(x *session) string { + g := &x.goal + if !g.active && !(g.done && !g.doneSeen) { + return "" + } + state := i18n.T("läuft") + if g.done && !g.active { + state = i18n.T("erreicht") + } else if _, why := a.goalAttention(x); why != "" { + state = why + } + return fmt.Sprintf(i18n.T("Ziel: %s · %s · %s"), trunc(g.goal, 30), plural(len(g.steps), i18n.T("Schritt"), i18n.T("Schritte")), state) +} + +// ---------------------------------------------------------------- 4 Folgeziel + +type goalCarry struct { + prior []agent.DoneStep + notes []string + backups []fileBackup + priorGoal string +} + +// startFollowGoal: f nach „Ziel erreicht“. +func (a *App) startFollowGoal(s *session) tea.Cmd { + g := &s.goal + if !g.done || g.goal == "" { + return nil + } + prevGoal, prevReason := g.goal, g.doneReason + prior := append(append([]agent.DoneStep(nil), g.prior...), g.steps...) + var notes []string + for _, x := range g.answers { + if agent.IsPriorGoal(x) { + notes = append(notes, x) + } + } + notes = append(notes, agent.PriorGoal(prevGoal, prevReason, len(prior))) + backups := append([]fileBackup(nil), g.backups...) + a.modal = inputModal(i18n.T("Folgeziel"), i18n.T("Was soll als Nächstes passieren? Die KI kennt das Ziel davor und seine Schritte."), "", func(x string) tea.Cmd { + x = strings.TrimSpace(x) + if x == "" { + return nil + } + return a.startGoalCarry(s, x, nil, &goalCarry{prior: prior, notes: notes, backups: backups, priorGoal: prevGoal}) + }) + a.modal.in.Placeholder = i18n.T("z. B. jetzt noch HTTPS mit Let's Encrypt einrichten") + return nil +} + +// ---------------------------------------------------------------- 5 Sicherungen + +// fileBackup: Zustand einer Datei, bevor ein Schritt des Ziels sie änderte. +type fileBackup struct { + Path string + Existed bool + Content []byte + Sudo bool + Skip string // warum es keine Sicherung gibt ("" = gesichert) +} + +func (f fileBackup) restorable() bool { return f.Skip == "" } + +const ( + maxBackups = 20 + maxBackupSize = 1 << 20 + backupTimeout = 10 * time.Second +) + +type goalBackupMsg struct { + sid, seq int + cmd string + insert bool + saved []fileBackup +} + +type goalUndoMsg struct { + sid, seq int + list []fileBackup + err error +} + +func (g *goalState) hasBackup(p string) bool { + for _, b := range g.backups { + if b.Path == p { + return true + } + } + return false +} + +// execProposal führt einen Vorschlag aus; ändert er Dateien, werden sie +// vorher gesichert (nur über SFTP auf Unix, wie die Dateien des Agenten). +func (a *App) execProposal(s *session, cmd string, insert bool) tea.Cmd { + g := &s.goal + var need []agent.FileChange + if a.agentFilesOK(s) { + for _, f := range agent.ChangedFiles(cmd) { + if g.hasBackup(f.Path) || strings.HasPrefix(f.Path, "~/"+agentDirBase+"/") || len(g.backups)+len(need) >= maxBackups { + continue + } + need = append(need, f) + } + } + if len(need) == 0 { + a.runProposal(s, cmd, insert) + return nil + } + g.backingUp = true + sid, seq := s.id, g.seq + local, cl := s.agentFSOf() + return func() tea.Msg { + return goalBackupMsg{sid, seq, cmd, insert, readBackups(local, cl, need)} + } +} + +// readBackups liest die Dateien; was nicht klappt, steht mit Grund in Skip. +func readBackups(local bool, cl *sshx.Client, need []agent.FileChange) []fileBackup { + out := make([]fileBackup, len(need)) + for i, f := range need { + out[i] = fileBackup{Path: f.Path, Sudo: f.Sudo, Skip: i18n.T("keine Antwort")} + } + done := make(chan []fileBackup, 1) + go func() { + res := make([]fileBackup, len(need)) + copy(res, out) + fsys, closeFn, err := agentFS(local, cl) + if err != nil { + for i := range res { + res[i].Skip = err.Error() + } + done <- res + return + } + defer closeFn() + for i, f := range need { + res[i] = readBackup(fsys, f) + } + done <- res + }() + select { + case r := <-done: + return r + case <-time.After(backupTimeout): + return out + } +} + +func readBackup(fsys sshx.FS, f agent.FileChange) fileBackup { + b := fileBackup{Path: f.Path, Sudo: f.Sudo} + p := f.Path + if strings.HasPrefix(p, "~/") { + p = fsys.Join(fsys.Home(), p[2:]) + } + e, err := fsys.Stat(p) + switch { + case errors.Is(err, fs.ErrNotExist): + return b // gab es noch nicht: Zurückholen löscht sie + case err != nil: + b.Skip = i18n.T("nicht lesbar") + return b + case e.IsDir: + b.Skip = i18n.T("ist ein Ordner") + return b + case e.Size > maxBackupSize: + b.Skip = i18n.T("zu groß") + return b + } + r, err := fsys.Open(p) + if err != nil { + b.Skip = i18n.T("nicht lesbar") + return b + } + defer r.Close() + data, err := io.ReadAll(io.LimitReader(r, maxBackupSize+1)) + if err != nil || len(data) > maxBackupSize { + b.Skip = i18n.T("nicht lesbar") + return b + } + b.Existed, b.Content = true, data + return b +} + +func (a *App) goalBackupDone(m goalBackupMsg) tea.Cmd { + s := a.byID(m.sid) + if s == nil || m.seq != s.goal.seq { + return nil + } + g := &s.goal + g.backingUp = false + for _, b := range m.saved { + if !g.hasBackup(b.Path) { + g.backups = append(g.backups, b) + } + } + if !g.active || s.state != stConnected { + return nil + } + a.runProposal(s, m.cmd, m.insert) + return nil +} + +// startUndo: u legt die Sicherungen in den Arbeitsordner und schlägt den +// Befehl vor, der sie zurückkopiert (bzw. neu angelegte Dateien löscht). +func (a *App) startUndo(s *session) tea.Cmd { + g := &s.goal + var list []fileBackup + for _, b := range g.backups { + if b.restorable() { + list = append(list, b) + } + } + if len(list) == 0 { + a.flash(i18n.T("Nichts zum Zurückholen")) + return nil + } + if s.state != stConnected || !a.agentFilesOK(s) { + a.flashErr(i18n.T("Zurückholen braucht eine Verbindung mit SFTP")) + return nil + } + if g.runID == "" { + g.runID = newRunID() + } + g.backingUp = true + g.seq++ + sid, seq, run := s.id, g.seq, g.runID + local, cl := s.agentFSOf() + return func() tea.Msg { + fsys, closeFn, err := agentFS(local, cl) + if err != nil { + return goalUndoMsg{sid, seq, list, err} + } + defer closeFn() + dir := fsys.Join(fsys.Home(), agentDirBase, run, "undo") + if err := fsys.Mkdir(dir); err != nil { + return goalUndoMsg{sid, seq, list, err} + } + _ = fsys.Chmod(fsys.Join(fsys.Home(), agentDirBase, run), 0o700) // Sicherungen können Geheimnisse enthalten + for i, b := range list { + if !b.Existed { + continue + } + w, err := fsys.Create(fsys.Join(dir, strconv.Itoa(i)), 0o600) + if err != nil { + return goalUndoMsg{sid, seq, list, err} + } + if _, err := w.Write(b.Content); err != nil { + _ = w.Close() + return goalUndoMsg{sid, seq, list, err} + } + if err := w.Close(); err != nil { + return goalUndoMsg{sid, seq, list, err} + } + } + return goalUndoMsg{sid, seq, list, nil} + } +} + +// undoCommand: eine Zeile, die alle Dateien zurückholt. +func undoCommand(run string, list []fileBackup) string { + var parts []string + for i, b := range list { + sudo := "" + if b.Sudo { + sudo = "sudo " + } + target := shQuote(b.Path) + if strings.HasPrefix(b.Path, "~/") { + target = "~/" + shQuote(b.Path[2:]) // ~ bleibt außerhalb der Anführungszeichen + } + if b.Existed { + parts = append(parts, fmt.Sprintf("%scp ~/%s/%s/undo/%d %s", sudo, agentDirBase, run, i, target)) + } else { + parts = append(parts, sudo+"rm -f "+target) + } + } + return strings.Join(parts, " && ") +} + +func (a *App) goalUndoDone(m goalUndoMsg) tea.Cmd { + s := a.byID(m.sid) + if s == nil || m.seq != s.goal.seq { + return nil + } + g := &s.goal + g.backingUp = false + if m.err != nil { + a.flashErr(i18n.T("Zurückholen: ") + m.err.Error()) + return nil + } + cmd := undoCommand(g.runID, m.list) + g.undoing, g.undoBack = true, g.done + g.active, g.done, g.paused, g.pauseWhy = true, false, false, "" + st := agent.ParseStepCommand(cmd, a.safetyKind(s)) + st.Command = cmd + st.Reason = fmt.Sprintf(i18n.T("stellt die geänderten Dateien (%d) wieder so her, wie sie vor dem Ziel waren"), len(m.list)) + g.cur = &agent.Step{Suggestion: st} + g.armed = false + s.panelFocus = true + return nil +} + +// undoKey: Tasten, solange der Zurückholen-Befehl wartet. +func (a *App) undoKey(s *session, key string) tea.Cmd { + g := &s.goal + switch key { + case "enter": + if g.cur == nil || g.waiting { + return nil + } + if s.state != stConnected { + a.flashErr(i18n.T("keine Verbindung: erst neu verbinden")) + return nil + } + a.runProposal(s, g.cur.Command, false) + case "x": + if g.waiting { + return nil + } + g.undoing, g.cur, g.active = false, nil, false + g.done = g.undoBack + } + return nil +} + +// undoFinished (aus goalTick): der Zurückholen-Befehl ist durch. +func (a *App) undoFinished(s *session) { + g := &s.goal + g.undoing, g.active, g.done, g.cur = false, false, true, nil + failed := false + if n := len(g.steps); n > 0 { + last := g.steps[n-1] + failed = last.ExitHint != "" || (last.Exit != nil && *last.Exit != 0) + } + if failed { + g.doneReason = i18n.T("Zurückholen hat nicht geklappt, siehe Terminal. Die Sicherungen bleiben, u versucht es erneut.") + return + } + var paths []string + keep := g.backups[:0] + for _, b := range g.backups { + if b.restorable() { + paths = append(paths, b.Path) + } else { + keep = append(keep, b) + } + } + g.backups = keep + g.doneReason = i18n.T("Änderungen zurückgenommen: ") + strings.Join(paths, ", ") + a.flashOK(i18n.T("Änderungen des Ziels zurückgenommen")) +} + +// viewBackups: geänderte Dateien unter „Ziel erreicht“ bzw. im Eingabebild. +func (a *App) viewBackups(b *strings.Builder, s *session, w int, key string) { + st := a.s + g := &s.goal + if len(g.backups) == 0 { + return + } + n := 0 + for _, x := range g.backups { + if x.restorable() { + n++ + } + } + 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 { + s.panelFocus = true + return a.startUndo(s) + }) + } + if strings.HasSuffix(b.String(), "\n") { + b.WriteString("\n") + } else { + b.WriteString("\n\n") + } + b.WriteString(head + "\n") + for i, x := range g.backups { + if i >= 5 { + b.WriteString(st.Muted.Render(fmt.Sprintf(i18n.T(" … %d weitere"), len(g.backups)-5)) + "\n") + break + } + meta := "" + switch { + case x.Skip != "": + meta = i18n.T("ohne Sicherung: ") + x.Skip + case !x.Existed: + meta = i18n.T("neu angelegt") + } + line := " " + trunc(x.Path, max(8, w-lipgloss.Width(meta)-4)) + if meta != "" { + line = st.Text.Render(line) + " " + st.Muted.Render(meta) + } else { + line = st.Text.Render(line) + } + b.WriteString(line + "\n") + } +} + +// ---------------------------------------------------------------- 7 Verbindung weg + +// connLost (aus suspend): das Ziel hält an, die laufende Anfrage verfällt. +func (g *goalState) connLost() { + if !g.active { + return + } + g.seq++ // späte Antworten der KI und Sicherungen verfallen + g.busy, g.waiting, g.writing, g.backingUp, g.manualPending = false, false, false, false, false + g.inputWait, g.inputLine = "", "" + g.lost = true + if g.auto { + g.paused, g.pauseWhy = true, i18n.T("Verbindung unterbrochen") + g.needStep = g.cur == nil + } +} + +// resumeLost: ⏎ nach dem Neuverbinden. +func (a *App) resumeLost(s *session) tea.Cmd { + g := &s.goal + if s.state != stConnected { + a.flash(i18n.T("Noch nicht wieder verbunden")) + return nil + } + g.lost = false + if g.undoing { + return nil // Zurückholen-Befehl steht noch da, ⏎ führt ihn aus + } + if g.cur != nil { // der Vorschlag steht noch; nichts lief + if g.auto { + g.pauseWhy = i18n.T("Verbindung wieder da, ⏎ führt den Schritt aus") + } + return nil + } + g.answers = append(g.answers, agent.Notice("Die Verbindung war unterbrochen und ist wieder da (neue Shell). Der letzte Befehl ist eventuell nicht fertig geworden; prüfe zuerst den Stand, bevor du weitermachst.")) + if g.auto { + g.paused, g.pauseWhy, g.needStep = false, "", false + return a.agentNext(s) + } + return a.requestStep(s) +} + +func (a *App) viewLost(b *strings.Builder, s *session, w int) { + st := a.s + if s.state == stConnected { + b.WriteString(st.Warn.Render(i18n.T("▲ Die Verbindung war unterbrochen")) + "\n" + + wrap(st.Text.Render(i18n.T("Das Ziel ist angehalten. Die KI prüft zuerst den Stand, der letzte Befehl ist eventuell nicht fertig geworden.")), w) + "\n\n" + + a.hintsIn(s, st.Muted, [2]string{"⏎", i18n.T("Ziel fortsetzen")}, [2]string{"x", i18n.T("Ziel beenden")})) + return + } + b.WriteString(st.Warn.Render(i18n.T("▲ Verbindung unterbrochen")) + "\n" + + wrap(st.Muted.Render(i18n.T("Das Ziel ist angehalten und wartet auf die neue Verbindung.")), w)) +} + +// ---------------------------------------------------------------- 8 Eigene Befehle + +// noteManualStep (aus finishCommand): Befehle, die du während des Ziels +// selbst ausführst, bekommt die KI als Schritt mit Ausgabe. +func (a *App) noteManualStep(s *session, r *cmdRun, out string, f agent.Failure, failed bool) bool { + g := &s.goal + if !g.active || g.undoing || r.sent || r.agent || r.private || g.lost { + return false + } + if n := len(g.steps); n > 0 && !g.steps[n-1].Manual && strings.HasPrefix(r.cmd, g.steps[n-1].Command) { + return false // der zuletzt vorgeschlagene (z. B. mit i eingefügt) + } + d := agent.DoneStep{Command: r.cmd, Manual: true, Output: sessionlog.Clip(out), Exit: f.Exit} + if failed && !r.interrupted { + d.ExitHint = orDefault(f.Reason, i18n.T("Fehlermeldung in der Ausgabe")) + } + g.steps = append(g.steps, d) + if g.cur != nil && !g.auto { + g.manualNew = true + } + return true +} + +// goalUXKeys: Fußzeile für die Zustände aus dieser Datei (nil = sonst). +func (a *App) goalUXKeys(s *session) [][2]string { + g := &s.goal + switch { + case g.lost && g.active: + if s.state == stConnected { + return [][2]string{{"⏎", i18n.T("Ziel fortsetzen")}, {"x", i18n.T("Ziel beenden")}, {"Esc", "Terminal"}} + } + return [][2]string{{"x", i18n.T("Ziel beenden")}, {"Esc", "Terminal"}} + case g.undoing: + return [][2]string{{"⏎", i18n.T("zurückholen")}, {"x", i18n.T("abbrechen")}, {"Esc", "Terminal"}} + case g.inputWait != "" && g.waiting: + return a.inputWaitHints(s) + case g.backingUp: + return [][2]string{{"Esc", "Terminal"}} + } + return nil +} diff --git a/internal/ui/goalux_test.go b/internal/ui/goalux_test.go new file mode 100644 index 0000000..a6ab29b --- /dev/null +++ b/internal/ui/goalux_test.go @@ -0,0 +1,389 @@ +package ui + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + + "github.com/db9979/sshtermy/internal/agent" + "github.com/db9979/sshtermy/internal/domain" +) + +// goalSession: Ziel-Modus (Schritt für Schritt) mit einem Ziel, ohne KI. +func goalSession(t *testing.T, c domain.Connection) (*App, *session, *syncBuf) { + t.Helper() + a := dangerApp(t) + if c.ID == "" { + c.ID = "c1" + } + s, out := typedSession(c, "dominik@lab:~$ ", "") + a.sessions = []*session{s} + withPanel(s, panelGoal) + a.panelOpened(s) + a.startGoal(s, "Nginx einrichten") + s.goal.busy, s.goal.err = false, "" // keine KI im Test + s.panelFocus = true + return a, s, out +} + +func toastHas(a *App, sub string) bool { + for _, t := range a.toasts { + if strings.Contains(t.text, sub) { + return true + } + } + return false +} + +func TestGoalInstructAndSkipWhy(t *testing.T) { + a, s, _ := goalSession(t, domain.Connection{GuardOff: true, Alias: "lab"}) + g := &s.goal + a.sessionMsg(stepMsg(s, cmdStep("docker-compose up -d", "unix"))) + if g.cur == nil { + t.Fatal("kein Vorschlag") + } + a.panelMsg(s, runeKey('?')) + if a.modal == nil || a.modal.onText == nil { + t.Fatal("? öffnet keine Eingabe für die Anweisung") + } + a.modal.onText("nimm docker compose") + a.modal = nil + if g.cur != nil || len(g.answers) == 0 { + t.Fatalf("Anweisung nicht übernommen: cur=%v answers=%q", g.cur, g.answers) + } + if x, ok := agent.IsInstruction(g.answers[len(g.answers)-1]); !ok || x != "nimm docker compose" { + t.Errorf("Anweisung falsch markiert: %q", g.answers) + } + // Überspringen mit Grund + g.busy, g.err = false, "" + a.sessionMsg(stepMsg(s, cmdStep("systemctl restart nginx", "unix"))) + a.panelMsg(s, runeKey('S')) + if a.modal == nil { + t.Fatal("⇧S öffnet keine Eingabe") + } + a.modal.onText("läuft schon") + a.modal = nil + last := g.steps[len(g.steps)-1] + if !last.Skipped || last.Note != "läuft schon" { + t.Errorf("Überspringen mit Grund: %+v", last) + } +} + +func TestGoalInputWait(t *testing.T) { + a, s, out := goalSession(t, domain.Connection{GuardOff: true, Alias: "lab"}) + g := &s.goal + a.sessionMsg(stepMsg(s, cmdStep("sudo apt install nginx", "unix"))) + if cmd := a.panelMsg(s, enterKey); cmd != nil { + t.Fatal("ohne SFTP darf es keine Sicherung geben") + } + if !g.waiting || !out.has("sudo apt install nginx\r") { + t.Fatalf("Schritt läuft nicht: %+v", g) + } + _, _ = s.term.Write([]byte("\r\nDo you want to continue? [Y/n] ")) + s.lastOutput = time.Now().Add(-3 * time.Second) + g.waitSince = time.Now().Add(-3 * time.Second) + a.goalTick(s) + if g.inputWait != agent.InputYesNo { + t.Fatalf("Rückfrage nicht erkannt: %q (%q)", g.inputWait, s.term.CursorLine()) + } + if k, _ := a.goalAttention(s); k == "" { + t.Error("Eingabe erwartet zählt nicht als „wartet auf dich“") + } + if !strings.Contains(a.viewPanel(s, 60, 30), "[j]") { + t.Error("Panel zeigt keine Knöpfe") + } + a.panelMsg(s, runeKey('j')) + if !out.has("y\r") || g.inputWait != "" { + t.Errorf("j schickt kein y⏎: %q", out.String()) + } +} + +func TestAgentPausesOnInputWait(t *testing.T) { + a, s, _ := agentSession(t, domain.Connection{GuardOff: true, Alias: "lab-01"}, lvlNormal) + g := &s.goal + g.planOK, g.busy = true, false + g.startWait() + _, _ = s.term.Write([]byte("\r\n--More--")) + s.lastOutput = time.Now().Add(-3 * time.Second) + g.waitSince = time.Now().Add(-3 * time.Second) + a.goalTick(s) + if g.inputWait != agent.InputPager || !g.paused { + t.Fatalf("Agent muss am Pager anhalten: wait=%q paused=%v", g.inputWait, g.paused) + } + a.panelMsg(s, tea.KeyPressMsg{Code: tea.KeySpace, Text: " "}) + if g.paused || g.inputWait != "" { + t.Errorf("Leertaste muss weiterblättern und den Agenten weiterlaufen lassen: paused=%v", g.paused) + } +} + +func TestGoalNotifyHiddenTab(t *testing.T) { + a, s, _ := goalSession(t, domain.Connection{GuardOff: true, Alias: "lab"}) + other, _ := typedSession(domain.Connection{ID: "c2", Alias: "web"}, "$ ", "") + other.id = 2 + a.sessions = []*session{s, other} + a.cur = 1 // der Ziel-Tab ist verdeckt + var sent []string + old := desktopSend + desktopSend = func(title, body string) { sent = append(sent, body) } + defer func() { desktopSend = old }() + + a.sessionMsg(stepMsg(s, agent.Step{Question: "Welcher Port?"})) + a.goalNotifyTick(s) + if !toastHas(a, "Rückfrage") { + t.Errorf("keine Einblendung für die Rückfrage: %+v", a.toasts) + } + if !strings.Contains(a.goalGlyph(s), "◎") { + t.Errorf("Tab zeigt den Zustand des Ziels nicht: %q", a.goalGlyph(s)) + } + a.blurred = true + a.sessionMsg(stepMsg(s, cmdStep("ls", "unix"))) + a.goalNotifyTick(s) + if len(sent) != 1 { + t.Errorf("im Hintergrund muss eine Desktop-Meldung kommen: %q", sent) + } + a.goalNotifyTick(s) + if len(sent) != 1 { + t.Error("derselbe Anlass darf nur einmal melden") + } +} + +func TestGoalTabCount(t *testing.T) { + _, s, _ := goalSession(t, domain.Connection{GuardOff: true, Alias: "lab"}) + if goalTabCount(s) != "" { + t.Error("ohne Schritte keine Zahl") + } + s.goal.steps = append(s.goal.steps, agent.DoneStep{Command: "ls"}, agent.DoneStep{Command: "df"}) + if got := goalTabCount(s); got != " ·2" { + t.Errorf("Schrittzahl: %q", got) + } +} + +func TestFollowGoalAndHistory(t *testing.T) { + a, s, _ := goalSession(t, domain.Connection{GuardOff: true, Alias: "lab"}) + g := &s.goal + g.steps = append(g.steps, agent.DoneStep{Command: "apt install nginx", Output: "ok"}) + a.sessionMsg(stepMsg(s, agent.Step{Done: true, Suggestion: agent.Suggestion{Reason: "Nginx läuft auf Port 80"}})) + if !g.done || g.active { + t.Fatal("Ziel nicht erreicht") + } + runs := a.st.GoalRuns("c1") + if len(runs) != 1 || runs[0].State != "done" || len(runs[0].Steps) != 1 || runs[0].Result == "" { + t.Fatalf("Zielverlauf: %+v", runs) + } + a.panelMsg(s, runeKey('f')) + if a.modal == nil { + t.Fatal("f öffnet kein Folgeziel") + } + a.modal.onText("HTTPS einrichten") + a.modal = nil + g = &s.goal + if !g.active || g.goal != "HTTPS einrichten" || len(g.prior) != 1 || g.priorGoal != "Nginx einrichten" { + t.Fatalf("Folgeziel ohne Vorgeschichte: %+v", g) + } + found := false + for _, x := range g.answers { + found = found || agent.IsPriorGoal(x) + } + if !found { + t.Error("das Ziel davor fehlt für die KI") + } + // x beendet: Verlauf hat zwei Einträge (neueste zuerst) + g.busy = false + g.steps = append(g.steps, agent.DoneStep{Command: "certbot --nginx"}) + a.panelMsg(s, runeKey('x')) + runs = a.st.GoalRuns("c1") + if len(runs) != 2 || runs[0].State != "stopped" || runs[0].Goal != "HTTPS einrichten" { + t.Fatalf("Verlauf nach x: %+v", runs) + } + // Auswahl im Eingabebild: ↓ wählt den neuesten Eintrag + a.panelMsg(s, tea.KeyPressMsg{Code: tea.KeyDown}) + if g.input.Value() != "HTTPS einrichten" { + t.Errorf("↓ übernimmt das Ziel aus dem Verlauf nicht: %q", g.input.Value()) + } + if !strings.Contains(a.viewPanel(s, 70, 40), "HTTPS einrichten") { + t.Error("Verlauf nicht zu sehen") + } + a.panelMsg(s, tea.KeyPressMsg{Code: 'd', Mod: tea.ModCtrl}) + if len(a.st.GoalRuns("c1")) != 1 { + t.Errorf("Strg+D entfernt den Eintrag nicht: sel=%d key=%q active=%v done=%v", g.rbSel, tea.KeyPressMsg{Code: 'd', Mod: tea.ModCtrl}.String(), g.active, g.done) + } +} + +func TestGoalBackupAndUndo(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + dir := t.TempDir() + conf := filepath.Join(dir, "app.conf") + if err := os.WriteFile(conf, []byte("port=80\n"), 0o644); err != nil { + t.Fatal(err) + } + fresh := filepath.Join(dir, "neu.conf") + a, s, out := goalSession(t, domain.Connection{Alias: "lokal", Protocol: domain.ProtoLocal, GuardOff: true}) + // Die Sicherung erkennt Unix-Befehle mit Unix-Pfaden (sed -i, tee, cp); + // die lokale Shell unter Windows ist PowerShell mit C:\-Pfaden. + if runtime.GOOS == "windows" || !a.agentFilesOK(s) { + t.Skip("lokale Shell hier ohne Unix-Dateien") + } + g := &s.goal + run := func(cmd string) { + t.Helper() + g.busy, g.waiting = false, false + a.sessionMsg(stepMsg(s, cmdStep(cmd, "unix"))) + c := a.panelMsg(s, enterKey) + if c == nil { + t.Fatalf("%s: keine Sicherung angestoßen", cmd) + } + if !g.backingUp { + t.Fatal("Sicherung läuft nicht") + } + a.sessionMsg(c()) + if !out.has(cmd + "\r") { + t.Fatalf("%s lief nach der Sicherung nicht", cmd) + } + } + run("sed -i 's/80/8080/' " + conf) + run("echo x | sudo tee " + fresh) + if len(g.backups) != 2 || string(g.backups[0].Content) != "port=80\n" || g.backups[1].Existed || !g.backups[1].Sudo { + t.Fatalf("Sicherungen: %+v", g.backups) + } + // derselbe Pfad wird nur einmal gesichert (Zustand vor dem Ziel) + g.busy, g.waiting = false, false + a.sessionMsg(stepMsg(s, cmdStep("sed -i 's/8080/9090/' "+conf, "unix"))) + if c := a.panelMsg(s, enterKey); c != nil { + t.Error("schon gesicherte Datei wird nochmal gesichert") + } + g.waiting = false + a.sessionMsg(stepMsg(s, agent.Step{Done: true, Suggestion: agent.Suggestion{Reason: "fertig"}})) + if !strings.Contains(a.viewPanel(s, 80, 40), "2") { + t.Error("Liste der geänderten Dateien fehlt") + } + c := a.panelMsg(s, runeKey('u')) + if c == nil { + t.Fatal("u holt nichts zurück") + } + a.sessionMsg(c()) + if !g.undoing || g.cur == nil { + t.Fatalf("Zurückholen-Befehl fehlt: %+v", g) + } + cmd := g.cur.Command + if !strings.Contains(cmd, "cp ~/.sshtermy-agent/"+g.runID+"/undo/0 '"+conf+"'") || !strings.Contains(cmd, "sudo rm -f '"+fresh+"'") { + t.Errorf("Befehl: %s", cmd) + } + saved, err := os.ReadFile(filepath.Join(home, ".sshtermy-agent", g.runID, "undo", "0")) + if err != nil || string(saved) != "port=80\n" { + t.Errorf("Sicherung nicht im Arbeitsordner: %q %v", saved, err) + } + a.panelMsg(s, enterKey) + if !out.has(cmd + "\r") { + t.Fatal("⏎ führt das Zurückholen nicht aus") + } + g.waiting = false + a.undoFinished(s) + if g.undoing || !g.done || len(g.backups) != 0 || !strings.Contains(g.doneReason, conf) { + t.Errorf("nach dem Zurückholen: %+v", g) + } + if runs := a.st.GoalRuns("c1"); len(runs) != 1 { + t.Errorf("Zurückholen darf keinen zweiten Verlaufseintrag schreiben: %d", len(runs)) + } +} + +func TestGoalConnLostResume(t *testing.T) { + a, s, _ := goalSession(t, domain.Connection{GuardOff: true, Alias: "lab"}) + g := &s.goal + a.sessionMsg(stepMsg(s, cmdStep("apt update", "unix"))) + a.panelMsg(s, enterKey) + seq := g.seq + s.state = stReconnect + g.connLost() + if !g.lost || g.waiting || g.seq == seq { + t.Fatalf("Ziel hält nicht an: %+v", g) + } + a.panelMsg(s, enterKey) + if !g.lost { + t.Error("ohne Verbindung darf ⏎ nicht fortsetzen") + } + s.state = stConnected + if k, _ := a.goalAttention(s); k != "lost" { + t.Errorf("wieder verbunden muss als „wartet auf dich“ gelten: %q", k) + } + a.panelMsg(s, enterKey) + if g.lost { + t.Fatal("⏎ setzt nicht fort") + } + last := g.answers[len(g.answers)-1] + if !strings.HasPrefix(last, "\x02") { + t.Errorf("KI erfährt nichts vom Abbruch: %q", g.answers) + } +} + +func TestGoalManualStep(t *testing.T) { + a, s, _ := goalSession(t, domain.Connection{GuardOff: true, Alias: "lab"}) + g := &s.goal + a.sessionMsg(stepMsg(s, cmdStep("systemctl status nginx", "unix"))) + a.beginCommand(s, "uptime") + _, _ = s.term.Write([]byte("uptime\r\n 10:00 up 3 days\r\ndominik@lab:~$ ")) + a.finishCommand(s) + if n := len(g.steps); n != 1 || !g.steps[0].Manual || g.steps[0].Command != "uptime" { + t.Fatalf("selbst getippter Befehl fehlt: %+v", g.steps) + } + if !g.manualNew { + t.Error("Hinweis auf neuen Vorschlag fehlt") + } + // mit i eingefügter Vorschlag ist kein eigener Schritt + a.panelMsg(s, runeKey('i')) + a.beginCommand(s, "systemctl status nginx") + a.finishCommand(s) + if len(g.steps) != 2 || g.steps[1].Manual { + t.Errorf("eingefügter Vorschlag doppelt oder als eigener gezählt: %+v", g.steps) + } +} + +func TestCmdBlocksJumpAndList(t *testing.T) { + a := dangerApp(t) + s, _ := typedSession(domain.Connection{ID: "c1", Alias: "lab"}, "$ ", "") + a.sessions = []*session{s} + for i := 0; i < 15; i++ { + cmd := "echo nummer" + string(rune('a'+i)) + a.beginCommand(s, cmd) + _, _ = s.term.Write([]byte(cmd + "\r\nzeile1\r\nzeile2\r\n$ ")) + a.finishCommand(s) + } + if len(s.blocks) != 15 { + t.Fatalf("Blöcke: %d", len(s.blocks)) + } + a.jumpBlock(s, -1) + if s.blockNav != 15 { + t.Fatalf("Alt+Bild↑ springt nicht zum letzten Befehl: %d", s.blockNav) + } + for i := 0; i < 12; i++ { + a.jumpBlock(s, -1) + } + if s.blockNav != 3 || s.scroll == 0 { + t.Fatalf("zurückblättern: nav=%d scroll=%d", s.blockNav, s.scroll) + } + ln := s.locateBlock(s.blocks[2]) + if !strings.Contains(s.term.PlainLine(ln), "echo nummerc") { + t.Errorf("falsche Zeile: %q", s.term.PlainLine(ln)) + } + if first := s.term.ScrollbackLen() - s.scroll; first != ln-1 { + t.Errorf("Befehl steht nicht oben: erste Zeile %d, Befehl %d", first, ln) + } + for i := 0; i < 13; i++ { + a.jumpBlock(s, 1) + } + if s.blockNav != 0 || s.scroll != 0 { + t.Errorf("Alt+Bild↓ am Ende muss live zeigen: nav=%d scroll=%d", s.blockNav, s.scroll) + } + a.openBlocks(s) + if a.pick == nil || len(a.pick.items) != 15 || !strings.Contains(a.pick.items[0].label, "nummero") { + t.Fatalf("Liste: %+v", a.pick) + } + if c := a.pickerKey(tea.KeyPressMsg{Code: 'c', Mod: tea.ModCtrl}); c == nil || a.pick != nil { + t.Error("Strg+C kopiert die Ausgabe nicht") + } +} diff --git a/internal/ui/help.go b/internal/ui/help.go index f091e54..24009fe 100644 --- a/internal/ui/help.go +++ b/internal/ui/help.go @@ -117,6 +117,8 @@ var helpSections = []helpSection{ {"⇧F10", "Tab in eigenes Fenster (Sitzung bleibt offen)"}, {"Strg+F", "im Verlauf suchen"}, {"Alt+S", "in allen Tabs suchen"}, + {"Alt+O", "Befehle des Tabs: Ausgabe kopieren, an KI"}, + {"Alt+Bild↑ Bild↓", "von Befehl zu Befehl springen"}, {"F6", "Host-Übersicht"}, {"Alt+E", "Log-Blick: Auffälligkeiten"}, {"F7 / F8", "Tab wechseln"}, @@ -133,15 +135,19 @@ var helpSections = []helpSection{ {"⇧⏎ / Strg+J", "neue Zeile im Ziel"}, {"i", "nur einfügen (Dry-Run)"}, {"e", "bearbeiten"}, - {"s", "überspringen"}, + {"s / ⇧S", "überspringen / mit Grund"}, + {"?", "KI anweisen (gilt ab dem nächsten Schritt)"}, {"r", "neu vorschlagen"}, {"x", "Ziel beenden"}, - {"↑ ↓", "Runbook wählen"}, + {"j n q Leertaste", "Befehl fragt nach: Antwort-Knöpfe"}, + {"f", "Folgeziel (kennt die Schritte davor)"}, + {"u", "Änderungen des Ziels zurückholen"}, + {"⏎ nach Abbruch", "Ziel fortsetzen"}, + {"↑ ↓", "Runbook oder früheres Ziel wählen"}, {"Strg+S", "als Runbook speichern"}, - {"Strg+D", "Runbook löschen"}, + {"Strg+D", "Runbook / Verlaufseintrag löschen"}, {"Tab", "Schritt für Schritt oder Agent (Stufe)"}, {"Esc", "Agent anhalten"}, - {"?", "Agent anweisen"}, {"v", "Skript des Agenten ansehen"}, {"r", "Skripte des Agenten löschen (am Ende)"}, {"c / l", "Ergebnis kopieren / ganz lesen"}, diff --git a/internal/ui/keymap.go b/internal/ui/keymap.go index bfc8762..5b31a6b 100644 --- a/internal/ui/keymap.go +++ b/internal/ui/keymap.go @@ -75,6 +75,9 @@ const ( actCompanionBar action = "companion_bar" actLogScan action = "log_scan" actVorgang action = "vorgang" + actCmdList action = "cmd_list" + actPrevCmd action = "prev_cmd" + actNextCmd action = "next_cmd" ) // Schnellbefehle ⇧F1 … ⇧F8 (manche Terminals senden dafür F13 … F20). @@ -120,6 +123,9 @@ var actionDefs = []actionDef{ {actQuick[7], "Schnellbefehl 8", "Terminal", []string{"shift+f8", "f20"}}, {actSearch, "Im Verlauf suchen", "Terminal", []string{"ctrl+f"}}, {actSearchAll, "In allen Tabs suchen", "Terminal", []string{"alt+s"}}, + {actCmdList, "Befehle dieses Tabs (Ausgabe kopieren, an KI)", "Terminal", []string{"alt+o"}}, + {actPrevCmd, "Zum vorigen Befehl springen", "Terminal", []string{"alt+pgup"}}, + {actNextCmd, "Zum nächsten Befehl springen", "Terminal", []string{"alt+pgdown"}}, {actSplit, "Ansicht teilen (Aufteilung wählen)", "Terminal", []string{"ctrl+t"}}, {actZoom, "Bereich zoomen / zurück", "Terminal", []string{"alt+z"}}, {actGrowLeft, "Trennlinie nach links", "Terminal", []string{"alt+shift+left"}}, diff --git a/internal/ui/menus1111_test.go b/internal/ui/menus1111_test.go index 5b319d1..b83ae74 100644 --- a/internal/ui/menus1111_test.go +++ b/internal/ui/menus1111_test.go @@ -40,7 +40,7 @@ func TestPaletteAreasRegrouped(t *testing.T) { } find := labels(palArea(a, "find")) - want := []string{"Im Verlauf suchen", "In allen Tabs suchen", "Fehlerzeilen im Verlauf zeigen", "Log-Blick", "Sitzungsprotokolle durchsuchen", "Ordner-Scan", "Logwache"} + want := []string{"Im Verlauf suchen", "In allen Tabs suchen", "Befehle dieses Tabs", "Fehlerzeilen im Verlauf zeigen", "Log-Blick", "Sitzungsprotokolle durchsuchen", "Ordner-Scan", "Logwache"} if len(find) < len(want) { t.Fatalf("Suchen & Logs: %v", find) } diff --git a/internal/ui/motion.go b/internal/ui/motion.go index a0661af..f82c13c 100644 --- a/internal/ui/motion.go +++ b/internal/ui/motion.go @@ -348,6 +348,9 @@ func (a *App) tabTip(x *session) string { last := x.latHist[n-1] lines = append(lines, on(st.T.Text, false).Render(i18n.T("Latenz")+" "+fmtLatency(last)+" ")+on(st.T.Accent, false).Render(sparkline(vals))) } + if t := a.goalTip(x); t != "" { + lines = append(lines, on(st.T.AI, false).Render(trunc(t, 60))) + } if n := len(x.history); n > 0 { lines = append(lines, on(st.T.Muted, false).Render("$ "+trunc(x.history[n-1], 34))) } diff --git a/internal/ui/palette.go b/internal/ui/palette.go index 16928f7..cb723e1 100644 --- a/internal/ui/palette.go +++ b/internal/ui/palette.go @@ -421,6 +421,7 @@ func (a *App) palActsFind(add palAdd, s *session, inTerm, inMgr bool) { add("find", palItem{icon: ic("search"), label: i18n.T("Im Verlauf suchen"), hint: "Strg+F", top: true, run: func() tea.Cmd { return a.openSearch(s) }}, palItem{icon: ic("search"), label: i18n.T("In allen Tabs suchen"), hint: a.keys.label(actSearchAll), keys: "suche find grep verlauf alle tabs", run: func() tea.Cmd { return a.openSearchAll() }}, + palItem{icon: ic("command"), label: i18n.T("Befehle dieses Tabs (Ausgabe kopieren, an KI)"), hint: a.keys.label(actCmdList), keys: "befehle blöcke blocks ausgabe output kopieren copy commands", run: func() tea.Cmd { return a.openBlocks(s) }}, palItem{icon: ic("errors"), label: i18n.T("Fehlerzeilen im Verlauf zeigen"), hint: i18n.T("Strg+F Strg+E"), run: func() tea.Cmd { cmd := a.openSearch(s) s.search.errors, s.search.list = true, true diff --git a/internal/ui/panels.go b/internal/ui/panels.go index 769c372..0323e65 100644 --- a/internal/ui/panels.go +++ b/internal/ui/panels.go @@ -74,6 +74,23 @@ type goalState struct { planSel, explored int planOff []bool recipeFiles []agent.FileAction + + // Bedienung im Einsatz (goalux.go) + prior []agent.DoneStep // Schritte früherer Ziele (Folgeziel, f) + priorGoal string // das Ziel davor (Anzeige) + inputWait agent.InputKind // laufender Befehl wartet auf eine Eingabe + inputLine string + lost bool // Verbindung war weg: wartet auf ⏎ zum Fortsetzen + manualNew bool // du hast nach dem Vorschlag selbst etwas ausgeführt + backups []fileBackup + backingUp bool + undoing bool // stellt gerade die Sicherungen wieder her + undoBack bool // nach Abbruch zurück zu „Ziel erreicht“ + attnKey string + attnDesk time.Time + doneSeen bool + recorded bool + goalAt time.Time } func (g *goalState) cancel() { @@ -238,6 +255,8 @@ func (a *App) sessionMsg(msg tea.Msg) (tea.Cmd, bool) { switch { case m.step.Done: g.done, g.active, g.doneReason, g.cur = true, false, m.step.Reason, nil + g.doneSeen = a.sessionVisible(s) && !a.blurred && s.panel == panelGoal + a.recordGoal(s, "done") if g.auto { a.agentFinished(s) a.flash(i18n.T("Agent: Ziel erreicht")) @@ -270,6 +289,10 @@ func (a *App) sessionMsg(msg tea.Msg) (tea.Cmd, bool) { return nil, true case agentFileMsg: return a.agentFileDone(m), true + case goalBackupMsg: + return a.goalBackupDone(m), true + case goalUndoMsg: + return a.goalUndoDone(m), true case agentCleanMsg: a.agentCleanDone(m) return nil, true @@ -355,7 +378,8 @@ func (a *App) requestStep(s *session) tea.Cmd { g.seq++ g.busy, g.cur, g.err = true, nil, "" sid, seq := s.id, g.seq - goal, hist, ans := g.goal, append([]agent.DoneStep(nil), g.steps...), append([]string(nil), g.answers...) + g.manualNew = false + goal, hist, ans := g.goal, append(append([]agent.DoneStep(nil), g.prior...), g.steps...), append([]string(nil), g.answers...) recipe := g.recipe c := a.agentContext(s, true) if g.planning { @@ -396,15 +420,22 @@ func (a *App) requestStep(s *session) tea.Cmd { // angefragt, wenn die Ausgabe ruht und wieder ein Prompt steht. func (a *App) goalTick(s *session) tea.Cmd { g := &s.goal + a.goalNotifyTick(s) // wartet das Ziel auf dich? (goalux.go) if !g.active || !g.waiting || s.term == nil { return nil } quiet := time.Since(s.lastOutput) > 1500*time.Millisecond && time.Since(g.waitSince) > time.Second + a.inputWaitTick(s, quiet) // [Y/n], Pager, „Press any key“ (goalux.go) if quiet && s.run != nil && (s.run.contWhy != "" || (s.run.sent && a.atContinuation(s))) { return nil // hängt am „>“: commandTick bricht ab, dann geht es mit dem Fehler weiter (contprompt.go) } if quiet && s.term.AtIdlePrompt() { g.waiting = false + g.inputWait = "" + if g.undoing { + a.undoFinished(s) + return nil + } if g.planning { return a.requestStep(s) } @@ -515,6 +546,28 @@ func (a *App) goalKey(s *session, msg tea.Msg) tea.Cmd { a.saveRunbook(s) return nil } + // Bedienung im Einsatz (goalux.go): Verbindung weg, Zurückholen, + // Befehl wartet auf Eingabe, Sicherung läuft + if g.lost && isKey && g.active { + switch key { + case "enter": + return a.resumeLost(s) + case "x": + default: + return nil + } + } + if g.undoing && isKey { + return a.undoKey(s, key) + } + if g.inputWait != "" && g.waiting && isKey { + if cmd, ok := a.inputWaitKey(s, key); ok { + return cmd + } + } + if g.backingUp && isKey { + return nil + } if g.planReview() && isKey { return a.planKey(s, key) } @@ -535,6 +588,10 @@ func (a *App) goalKey(s *session, msg tea.Msg) tea.Cmd { return nil case "r": return a.agentCleanup(s) + case "f": + return a.startFollowGoal(s) + case "u": + return a.startUndo(s) } if key == "enter" || key == "x" { g.done, g.rbSel, g.runbookID, g.recipe = false, -1, "", nil @@ -544,25 +601,29 @@ func (a *App) goalKey(s *session, msg tea.Msg) tea.Cmd { return nil } if !g.active { - rbs := a.st.Runbooks(s.conn.ID) + rbs, hist := a.goalPickCount(s) switch key { case "up", "down": - if len(rbs) == 0 { + n := len(rbs) + len(hist) + if n == 0 { return nil } if key == "down" { - g.rbSel = min(len(rbs)-1, g.rbSel+1) + a.goalPickSet(s, min(n-1, g.rbSel+1)) } else { - g.rbSel = max(-1, g.rbSel-1) + a.goalPickSet(s, max(-1, g.rbSel-1)) } - if g.rbSel >= 0 { - g.input.SetValue(rbs[g.rbSel].Goal) - g.input.CursorEnd() - } else { - g.input.SetValue("") + return nil + case "ctrl+r": + if len(g.backups) > 0 { + return a.startUndo(s) } return nil case "ctrl+d": + if i := g.rbSel - len(rbs); i >= 0 && i < len(hist) { + a.deleteGoalRun(s, hist[i]) + return nil + } if g.rbSel >= 0 && g.rbSel < len(rbs) { rb := rbs[g.rbSel] tr, err := a.st.DeleteRunbookTrash(rb.ID) @@ -583,6 +644,9 @@ func (a *App) goalKey(s *session, msg tea.Msg) tea.Cmd { if g.rbSel >= 0 && g.rbSel < len(rbs) && rbs[g.rbSel].Goal == text { return a.startRunbook(s, rbs[g.rbSel]) } + if i := g.rbSel - len(rbs); i >= 0 && i < len(hist) && hist[i].Goal == text { + return a.startGoalRun(s, hist[i]) + } return a.startGoal(s, text) } var cmd tea.Cmd @@ -609,7 +673,8 @@ func (a *App) goalKey(s *session, msg tea.Msg) tea.Cmd { return nil } if key == "x" && g.answer.Value() == "" { - g.active = false + a.recordGoal(s, "stopped") + g.active, g.lost = false, false return nil } var cmd tea.Cmd @@ -642,11 +707,21 @@ func (a *App) goalKey(s *session, msg tea.Msg) tea.Cmd { switch key { case "x": g.cancel() - g.active, g.busy, g.cur, g.rbSel = false, false, nil, -1 + state := "stopped" + if g.lost { + state = "lost" + } + a.recordGoal(s, state) + g.active, g.busy, g.cur, g.rbSel, g.lost = false, false, nil, -1, false + g.waiting, g.inputWait, g.manualPending = false, "", false g.input.SetValue("") return g.input.Focus() case "r": return a.requestStep(s) + case "?": + if !g.auto { + return a.goalInstruct(s) + } } if g.cur == nil || g.busy { return nil @@ -664,6 +739,8 @@ func (a *App) goalKey(s *session, msg tea.Msg) tea.Cmd { case "s": g.steps = append(g.steps, agent.DoneStep{Command: g.cur.CommandOrFile(), Skipped: true}) return a.requestStep(s) + case "S": + return a.goalSkipWhy(s) } return nil } @@ -673,12 +750,14 @@ func (a *App) goalKey(s *session, msg tea.Msg) tea.Cmd { g.armed = true // erster Druck: nur scharf schalten return nil } - a.runProposal(s, g.cur.Command, false) + return a.execProposal(s, g.cur.Command, false) // ändert er Dateien, erst sichern (goalux.go) case "i": - a.runProposal(s, g.cur.Command, true) + return a.execProposal(s, g.cur.Command, true) case "s": g.steps = append(g.steps, agent.DoneStep{Command: g.cur.Command, Skipped: true}) return a.requestStep(s) + case "S": + return a.goalSkipWhy(s) case "e": g.editing = true g.edit.SetValue(g.cur.Command) @@ -792,6 +871,9 @@ func (a *App) toggleTunnelAuto(t domain.Tunnel) { func (a *App) panelKeys(s *session) [][2]string { switch s.panel { case panelGoal: + if k := a.goalUXKeys(s); k != nil { + return k + } if k := a.planPanelKeys(s); k != nil { return k } @@ -801,7 +883,11 @@ func (a *App) panelKeys(s *session) [][2]string { g := s.goal if !g.active { if g.done { - return [][2]string{{"c", i18n.T("kopieren")}, {"l", i18n.T("ganz lesen")}, {"Strg+S", i18n.T("als Runbook merken")}, {"⏎", i18n.T("neues Ziel")}, {"Esc", "Terminal"}, {a.keys.label(actGoal), i18n.T("schließen")}} + k := [][2]string{{"c", i18n.T("kopieren")}, {"l", i18n.T("ganz lesen")}, {"Strg+S", i18n.T("als Runbook merken")}, {"f", i18n.T("Folgeziel")}} + if len(g.backups) > 0 { + k = append(k, [2]string{"u", i18n.T("zurückholen")}) + } + return append(k, [2]string{"⏎", i18n.T("neues Ziel")}, [2]string{"Esc", "Terminal"}, [2]string{a.keys.label(actGoal), i18n.T("schließen")}) } if len(a.st.Runbooks(s.conn.ID)) == 0 { return [][2]string{{"⏎", i18n.T("Ziel starten")}, {"Esc", "Terminal"}, {a.keys.label(actGoal), i18n.T("schließen")}} @@ -822,7 +908,7 @@ func (a *App) panelKeys(s *session) [][2]string { {"r", i18n.T("neu")}, {"x", i18n.T("Ziel beenden")}, {"Esc", "Terminal"}} } return [][2]string{{"⏎", i18n.T("ausführen")}, {"i", i18n.T("nur einfügen")}, {"e", i18n.T("bearbeiten")}, {"s", i18n.T("überspringen")}, - {"r", i18n.T("neu")}, {"x", i18n.T("Ziel beenden")}, {"Strg+S", "Runbook"}, {"Esc", "Terminal"}} + {"?", i18n.T("anweisen")}, {"r", i18n.T("neu")}, {"x", i18n.T("Ziel beenden")}, {"Strg+S", "Runbook"}, {"Esc", "Terminal"}} case panelAsk: q := &s.ask switch { @@ -997,8 +1083,13 @@ func (a *App) viewGoal(b *strings.Builder, s *session, w int) { }) + "\n") } } + a.viewGoalHist(b, s, w, len(a.st.Runbooks(s.conn.ID))) // Zielverlauf (goalhistory.go) + a.viewBackups(b, s, w, "Strg+R") return } + if g.priorGoal != "" { + b.WriteString(st.Muted.Render(i18n.T("→ Folgeziel nach: ")+trunc(g.priorGoal, max(8, w-20))) + "\n") + } switch { case len(g.recipe) > 0: b.WriteString(st.Badge.Foreground(st.T.AI).Render(i18n.T("▶ Runbook")) + " " + st.Muted.Render(plural(len(g.recipe), i18n.T("Schritt"), i18n.T("Schritte"))+i18n.T(" als Vorlage")) + "\n") @@ -1018,6 +1109,12 @@ func (a *App) viewGoal(b *strings.Builder, s *session, w int) { a.viewTimeline(b, s, w) // Fortschritt als Zeitleiste (timeline.go) b.WriteString("\n") switch { + case g.lost && g.active: + a.viewLost(b, s, w) + case g.inputWait != "" && g.waiting: + a.viewInputWait(b, s, w) + case g.backingUp: + b.WriteString(st.AI.Render(i18n.T("▪ sichert die Dateien, die der Schritt ändert …"))) case g.done && g.auto: markPanel(s, b.String()) // Zusammenfassung oben anfangen, Rest per Blättern a.viewAgentDone(b, s, w) @@ -1026,11 +1123,12 @@ func (a *App) viewGoal(b *strings.Builder, s *session, w int) { } case g.done: markPanel(s, b.String()) - hk := [][2]string{{"c", i18n.T("kopieren")}, {"l", i18n.T("ganz lesen")}, {"Strg+S", i18n.T("als Runbook merken")}, {"⏎", i18n.T("neues Ziel")}, {a.keys.label(actGoal), i18n.T("schließen")}} + hk := [][2]string{{"c", i18n.T("kopieren")}, {"l", i18n.T("ganz lesen")}, {"Strg+S", i18n.T("als Runbook merken")}, {"f", i18n.T("Folgeziel")}, {"⏎", i18n.T("neues Ziel")}, {a.keys.label(actGoal), i18n.T("schließen")}} if len(g.files) > 0 && !g.cleaned { hk = append(hk[:3:3], append([][2]string{{"r", i18n.T("Arbeitsordner löschen")}}, hk[3:]...)...) } b.WriteString(st.OK.Render(i18n.T("✓ Ziel erreicht")) + "\n" + wrap(st.Text.Render(g.doneReason), w) + "\n\n" + a.hintsIn(s, st.Muted, hk...)) + a.viewBackups(b, s, w, "u") if s.panelFocus && g.done { g.active = false } @@ -1065,6 +1163,9 @@ func (a *App) viewGoal(b *strings.Builder, s *session, w int) { case g.cur != nil: c := g.cur head := st.AI.Render(i18n.T("◆ Nächster Schritt")) + if g.undoing { + head = st.Warn.Render(i18n.T("← Änderungen des Ziels zurückholen")) + } box := st.Panel if len(c.Danger) > 0 { head = st.Danger.Render(i18n.T("▲ Vorsicht: ") + c.Danger[0].Reason) @@ -1085,6 +1186,9 @@ func (a *App) viewGoal(b *strings.Builder, s *session, w int) { if c.Elevated { b.WriteString(st.Warn.Render(i18n.T("↑ läuft mit erhöhten Rechten (sudo)")) + "\n") } + if g.manualNew { + b.WriteString(st.Warn.Render(i18n.T("• Du hast inzwischen selbst etwas ausgeführt, r holt einen neuen Vorschlag")) + "\n") + } if g.armed { b.WriteString("\n" + st.Danger.Render(i18n.T("Nochmal ⏎ zum Ausführen. Esc/s zum Abbrechen.")) + "\n") } @@ -1292,12 +1396,27 @@ func (a *App) startRunbook(s *session, rb domain.Runbook) tea.Cmd { } func (a *App) startGoalWith(s *session, text string, rb *domain.Runbook) tea.Cmd { + return a.startGoalCarry(s, text, rb, nil) +} + +// startGoalCarry: wie startGoalWith; carry (Folgeziel) bringt die Schritte +// und Sicherungen des Ziels davor mit (goalux.go). +func (a *App) startGoalCarry(s *session, text string, rb *domain.Runbook, carry *goalCarry) tea.Cmd { a.panelOpened(withPanel(s, panelGoal)) g := &s.goal g.cancel() + if g.active { + a.recordGoal(s, "stopped") // ein laufendes Ziel wird ersetzt + } auto, level, pf := g.auto, g.level, g.planFirst *g = goalState{input: g.input, edit: g.edit, answer: g.answer, inited: true, - goal: strings.TrimSpace(text), active: true, rbSel: -1, auto: auto, level: level, planFirst: pf} + goal: strings.TrimSpace(text), active: true, rbSel: -1, auto: auto, level: level, planFirst: pf, + goalAt: time.Now(), seq: g.seq + 1} + if carry != nil { + g.prior, g.priorGoal = carry.prior, carry.priorGoal + g.answers = append(g.answers, carry.notes...) + g.backups = carry.backups + } fromPlan := rb != nil && rb.ID == planRunbookID if rb != nil { g.recipe, g.runbookID = append([]string(nil), rb.Steps...), rb.ID diff --git a/internal/ui/reconnect.go b/internal/ui/reconnect.go index 7e28e63..b474154 100644 --- a/internal/ui/reconnect.go +++ b/internal/ui/reconnect.go @@ -305,6 +305,7 @@ func (s *session) suspend() { } s.ghost, s.chips = "", nil s.goal.cancel() + s.goal.connLost() // Ziel hält an, ⏎ setzt nach dem Neuverbinden fort (goalux.go) s.ask.cancel() if s.tunnels != nil { s.tunnels.StopAll() diff --git a/internal/ui/session.go b/internal/ui/session.go index e26101a..f3449e7 100644 --- a/internal/ui/session.go +++ b/internal/ui/session.go @@ -112,6 +112,9 @@ type session struct { // eigene Befehle und Folgebefehle history []string + blocks []cmdBlock // fertige Befehle mit Ausgabe (cmdblocks.go) + blockNav int // Sprung zwischen Befehlen: Block+1 (0 = live) + blockScroll int // s.scroll nach dem Sprung (anders = du hast selbst geblättert) chips []agent.Suggestion aiPend *aiPending // zuletzt eingefügter/ausgeführter KI-Befehl (learn.go) chipSeq int diff --git a/internal/ui/terminal.go b/internal/ui/terminal.go index f31a1f1..6435680 100644 --- a/internal/ui/terminal.go +++ b/internal/ui/terminal.go @@ -192,6 +192,18 @@ func (a *App) updateTerminal(msg tea.Msg) tea.Cmd { s.scroll, s.sel = 0, nil return nil } + if !s.panelFocus && !s.files.open && s.term != nil { + switch a.keys.which(key, actPrevCmd, actNextCmd, actCmdList) { // Befehle als Blöcke (cmdblocks.go) + case actPrevCmd: + a.jumpBlock(s, -1) + return nil + case actNextCmd: + a.jumpBlock(s, 1) + return nil + case actCmdList: + return a.openBlocks(s) + } + } s.sel, s.selecting = nil, false if !s.panelFocus && !s.files.open && !(m.Code >= tea.KeyF1 && m.Code <= tea.KeyF12) { s.scroll = 0 @@ -777,7 +789,7 @@ func (a *App) tabStrip() string { if l == 0 { return " " + strconv.Itoa(a.winNo(x)) } - return " " + strconv.Itoa(a.winNo(x)) + " " + trunc(x.tabName(), l) // Fensternummer (vorgang.go) + return " " + strconv.Itoa(a.winNo(x)) + " " + trunc(x.tabName(), l) + goalTabCount(x) // Fensternummer (vorgang.go), Schritte des Ziels } tabW := func(i, l int) int { // Streifen, Punkt, Text, Leerraum, Innenabstand, × am aktiven w := 1 + lipgloss.Width(label(i, l)) + 3 @@ -831,6 +843,9 @@ func (a *App) tabStrip() string { x := a.sessions[i] if a.sessionVisible(x) { x.unseen = false + if !a.blurred && x.goal.done { + x.goal.doneSeen = true + } } dot := a.tabDot(x, now) // Spinner, Puls bei neuer Ausgabe (motion.go) if x.detached() { @@ -839,11 +854,8 @@ func (a *App) tabStrip() string { if g := a.noticeGlyph(x); g != "" { dot = g // Befehl fertig / Glocke, solange der Tab verdeckt war } - if x.goal.auto && x.goal.active { - dot = st.AI.Render("◆") // Agent läuft - if x.goal.paused { - dot = st.Warn.Render("◆") // Agent wartet auf dich - } + if g := a.goalGlyph(x); g != "" { + dot = g // Ziel läuft / wartet auf dich / fertig (goalux.go) } ts := st.Tab if i == a.cur { diff --git a/internal/ui/testdata/golden/help-manager.de.txt b/internal/ui/testdata/golden/help-manager.de.txt index d3a3d33..031721d 100644 --- a/internal/ui/testdata/golden/help-manager.de.txt +++ b/internal/ui/testdata/golden/help-manager.de.txt @@ -1,31 +1,31 @@ >_ sshTermy vdev Idee: Dominik Bornhäußer ● KI V┌─ ? Tastenkürzel sshTermy vdev ───────────────────────────────────────────────────────────────────────────── × ─┐ │ │ - ▾│ ◆ Überall ◆ KI fragen F3 ▲ Log-Blick Alt+E │ - │ Strg+Space Befehlspalette ⏎ Frage senden ⏎ Zeilen des Musters │ - ▾│ F1 diese Hilfe ⇧⏎ / Strg+J neue Zeile 1…4 Prüfbefehl einfügen │ - │ F11 Vollbild an/aus (eige… 1…9 Befehl einfügen k KI erklärt das Muster │ -▌ │ F12 Über & Update ↑ ↓ Befehlskarte wählen b KI-Lagebericht │ -▌ │ F12 w Was ist neu a Befehl ausführen (rot… x / X ausblenden: Host / Or… │ -▌ │ F12 l Sprache: Deutsch/Engl… c Befehl kopieren n Was ist neu? (u zurüc… │ - ○│ ⇧F9 Tastenzeile erklären u nach Fehler: Fix in d… t Zeitleiste (←→, ⏎, k) │ - ○│ Strg+Q beenden (fragt bei of… z Erklärung ein-/auskla… z Zeitraum 1 h … 7 Tage │ - │ Esc / Strg+C Antwort abbrechen w Logwache: Meldungen │ - │ ≡ Verbindungs-Manager F10 hier n neue Frage (ohne Verl… s Switch: Syslog an ssh… │ - │ F10 zurück zum Terminal f Folgefrage (Verlauf g… r / c neu lesen / kopieren │ - │ ⏎ verbinden │ - │ n neue Verbindung ◇ KI-Begleiter Alt+J ≡ Sitzungsprotokolle l │ - │ e bearbeiten Alt+K Stufe: Aus/Leise/Gesp… / suchen (auch Ausgabe) │ - │ d löschen Alt+1…4 Vorschlag einfügen ⏎ / → ← auf-/zuklappen │ - │ Leertaste markieren (dann e, v,… ⏎ / a einfügen / ausführen Tab nach Zeit / nach Host │ - │ Rechtsklick Menü zu Verbindung od… m Thema stumm f Filter: heute · 7 Tag… │ - │ * alle sichtbaren marki… l Tatsache merken s Hosts sortieren │ - │ Strg+Z Löschen rückgängig (1… p / g Absicht: Plan / Agent… z KI-Zusammenfassung │ - │ Strg+T im Formular: Verbindu… r Rückblick (merken, Ru… Z alle Treffer zusammen… │ - │ / suchen (auch #tag) ? zuletzt gesendet b Änderungsbericht │ - │ o neuer Ordner (A / B v… x Export: md · txt · ca… │ - │ r Ordner bearbeiten ◆ Vorgang über mehrere Fenster d löschen │ - │ v in Ordner verschieben Alt+V a Mitschreiben an/aus │ + ▾│ ◆ Überall ◎ Ziel-Modus F2 / Suche im Verlauf Strg+F │ + │ Strg+Space Befehlspalette ⏎ Ziel starten / ausfüh… tippen suchen (Groß = genau) │ + ▾│ F1 diese Hilfe ⇧⏎ / Strg+J neue Zeile im Ziel ⏎ / ↑ nächster (älter) │ + │ F11 Vollbild an/aus (eige… i nur einfügen (Dry-Run) ⇧⏎ / ↓ zurück (neuer) │ +▌ │ F12 Über & Update e bearbeiten Strg+E nur Fehlerzeilen │ +▌ │ F12 w Was ist neu s / ⇧S überspringen / mit Gr… Tab Fehlerliste / Verlauf │ +▌ │ F12 l Sprache: Deutsch/Engl… ? KI anweisen (gilt ab … Esc schließen │ + ○│ ⇧F9 Tastenzeile erklären r neu vorschlagen │ + ○│ Strg+Q beenden (fragt bei of… x Ziel beenden ▲ Log-Blick Alt+E │ + │ j n q Leertaste Befehl fragt nach: ⏎ Zeilen des Musters │ + │ ≡ Verbindungs-Manager F10 hier An… 1…4 Prüfbefehl einfügen │ + │ F10 zurück zum Terminal f Folgeziel (kennt die … k KI erklärt das Muster │ + │ ⏎ verbinden u Änderungen des Ziels … b KI-Lagebericht │ + │ n neue Verbindung ⏎ nach Abbruch Ziel fortsetzen x / X ausblenden: Host / Or… │ + │ e bearbeiten ↑ ↓ Runbook oder früheres… n Was ist neu? (u zurüc… │ + │ d löschen Strg+S als Runbook speichern t Zeitleiste (←→, ⏎, k) │ + │ Leertaste markieren (dann e, v,… Strg+D Runbook / Verlaufsein… z Zeitraum 1 h … 7 Tage │ + │ Rechtsklick Menü zu Verbindung od… Tab Schritt für Schritt o… w Logwache: Meldungen │ + │ * alle sichtbaren marki… Esc Agent anhalten s Switch: Syslog an ssh… │ + │ Strg+Z Löschen rückgängig (1… v Skript des Agenten an… r / c neu lesen / kopieren │ + │ Strg+T im Formular: Verbindu… r Skripte des Agenten l… │ + │ / suchen (auch #tag) c / l Ergebnis kopieren / g… ≡ Sitzungsprotokolle l │ + │ o neuer Ordner (A / B v… Bild↑ Bild↓ im Panel blättern (au… / suchen (auch Ausgabe) │ + │ r Ordner bearbeiten Leertaste Plan: Schritt streich… ⏎ / → ← auf-/zuklappen │ + │ v in Ordner verschieben ? Plan: neu planen lass… Tab nach Zeit / nach Host │ │ │ │ ROT Gefährliche Befehle brauchen zweimal ⏎ bzw. Alt+N. KI-Vorschläge werden nur eingefügt, nie ausgeführt. │ │ Esc führt aus jedem Panel zurück ins Terminal. │ diff --git a/internal/ui/testdata/golden/help-manager.en.txt b/internal/ui/testdata/golden/help-manager.en.txt index be4d7c7..ce498d0 100644 --- a/internal/ui/testdata/golden/help-manager.en.txt +++ b/internal/ui/testdata/golden/help-manager.en.txt @@ -1,31 +1,31 @@ >_ sshTermy vdev Idea: Dominik Bornhäußer ● AI c┌─ ? Keyboard shortcuts sshTermy vdev ─────────────────────────────────────────────────────────────────────── × ─┐ │ │ - ▾│ ◆ Everywhere ◆ Ask AI F3 ▲ Log view Alt+E │ - │ Ctrl+Space Command palette ⏎ send question ⏎ lines of the pattern │ - ▾│ F1 this help ⇧⏎ / Ctrl+J new line 1…4 insert check command │ - │ F11 full screen on/off (o… 1…9 insert command k AI explains the patte… │ -▌ │ F12 About & update ↑ ↓ choose command card b AI status report │ -▌ │ F12 w What's new a run command (red ones… x / X hide: host / folder │ -▌ │ F12 l Language / Sprache c copy command n What's new? (u restor… │ - ○│ ⇧F9 explain key bar u after an error: put t… t Timeline (←→, ⏎, k) │ - ○│ Ctrl+Q quit (asks if connect… z collapse/expand expla… z Period 1 h … 7 days │ - │ Esc / Ctrl+C stop answer w Log watch: alerts │ - │ ≡ Connection manager F10 here n new question (fresh) s switch: send syslog t… │ - │ F10 back to the terminal f follow-up (keeps the … r / c reload / copy │ - │ ⏎ connect │ - │ n new connection ◇ AI companion Alt+J ≡ Session logs l │ - │ e edit Alt+K level: off/quiet/chat… / search (output too) │ - │ d delete Alt+1…4 insert suggestion ⏎ / → ← expand/collapse │ - │ Space mark (then e, v, d fo… ⏎ / a insert / run Tab by time / by host │ - │ Right-click menu for a connection… m mute topic f filter: today · 7 day… │ - │ * mark all visible l remember fact s sort hosts │ - │ Ctrl+Z undo delete (10 s) p / g intent: plan / agent … z AI summary │ - │ Ctrl+T in the form: test con… r recap (remember, runb… Z summarize all matches │ - │ / search (also #tag) ? last request sent b Change report │ - │ o new folder (A / B nes… x export: md · txt · ca… │ - │ r Edit folder ◆ Task across several windows Alt+V d delete │ - │ v move to folder Space / ← → choose windows / what… a recording on/off │ + ▾│ ◆ Everywhere ◎ Goal mode F2 / Search in history Ctrl+F │ + │ Ctrl+Space Command palette ⏎ start goal / run type search (capital = exa… │ + ▾│ F1 this help ⇧⏎ / Ctrl+J new line in the goal ⏎ / ↑ next (older) │ + │ F11 full screen on/off (o… i only insert (dry run) ⇧⏎ / ↓ back (newer) │ +▌ │ F12 About & update e edit Ctrl+E error lines only │ +▌ │ F12 w What's new s / ⇧S skip / with a reason Tab error list / history │ +▌ │ F12 l Language / Sprache ? instruct AI (applies … Esc close │ + ○│ ⇧F9 explain key bar r suggest again │ + ○│ Ctrl+Q quit (asks if connect… x end goal ▲ Log view Alt+E │ + │ j n q Space command asks: answer … ⏎ lines of the pattern │ + │ ≡ Connection manager F10 here f follow-up goal (knows… 1…4 insert check command │ + │ F10 back to the terminal u restore what the goal… k AI explains the patte… │ + │ ⏎ connect ⏎ after a drop continue goal b AI status report │ + │ n new connection ↑ ↓ choose runbook or ear… x / X hide: host / folder │ + │ e edit Ctrl+S save as runbook n What's new? (u restor… │ + │ d delete Ctrl+D delete runbook / hist… t Timeline (←→, ⏎, k) │ + │ Space mark (then e, v, d fo… Tab step by step or agent… z Period 1 h … 7 days │ + │ Right-click menu for a connection… Esc pause agent w Log watch: alerts │ + │ * mark all visible v view the agent's scri… s switch: send syslog t… │ + │ Ctrl+Z undo delete (10 s) r delete the agent's sc… r / c reload / copy │ + │ Ctrl+T in the form: test con… c / l copy result / read all │ + │ / search (also #tag) PgUp PgDn scroll the panel (mou… ≡ Session logs l │ + │ o new folder (A / B nes… Space plan: remove step / search (output too) │ + │ r Edit folder ? plan: re-plan ⏎ / → ← expand/collapse │ + │ v move to folder Tab by time / by host │ │ │ │ RED Dangerous commands need ⏎ twice or Alt+N. AI suggestions are only inserted, never run. │ │ Esc leads back to the terminal from every panel. │ diff --git a/internal/ui/testdata/golden/terminal-help.de.txt b/internal/ui/testdata/golden/terminal-help.de.txt index c519e43..8749d3e 100644 --- a/internal/ui/testdata/golden/terminal-help.de.txt +++ b/internal/ui/testdata/golden/terminal-help.de.txt @@ -1,31 +1,31 @@ >_ sshTermy vdev Idee: Dominik Bornhäußer ▌● 1 web-01 × + P┌─ ? Tastenkürzel sshTermy vdev ───────────────────────────────────────────────────────────────────────────── × ─┐er Li│ │ - │ ◆ Überall ◆ KI fragen F3 ▲ Log-Blick Alt+E │ -de│ Strg+Space Befehlspalette ⏎ Frage senden ⏎ Zeilen des Musters │ -● │ F1 diese Hilfe ⇧⏎ / Strg+J neue Zeile 1…4 Prüfbefehl einfügen │ - │ F11 Vollbild an/aus (eige… 1…9 Befehl einfügen k KI erklärt das Muster │ - │ F12 Über & Update ↑ ↓ Befehlskarte wählen b KI-Lagebericht │ -de│ F12 w Was ist neu a Befehl ausführen (rot… x / X ausblenden: Host / Or… │ - │ F12 l Sprache: Deutsch/Engl… c Befehl kopieren n Was ist neu? (u zurüc… │ - │ ⇧F9 Tastenzeile erklären u nach Fehler: Fix in d… t Zeitleiste (←→, ⏎, k) │ - │ Strg+Q beenden (fragt bei of… z Erklärung ein-/auskla… z Zeitraum 1 h … 7 Tage │ - │ Esc / Strg+C Antwort abbrechen w Logwache: Meldungen │ - │ ≡ Verbindungs-Manager F10 n neue Frage (ohne Verl… s Switch: Syslog an ssh… │ - │ F10 zurück zum Terminal f Folgefrage (Verlauf g… r / c neu lesen / kopieren │ - │ ⏎ verbinden │ - │ n neue Verbindung ◇ KI-Begleiter Alt+J ≡ Sitzungsprotokolle l │ - │ e bearbeiten Alt+K Stufe: Aus/Leise/Gesp… / suchen (auch Ausgabe) │ - │ d löschen Alt+1…4 Vorschlag einfügen ⏎ / → ← auf-/zuklappen │ - │ Leertaste markieren (dann e, v,… ⏎ / a einfügen / ausführen Tab nach Zeit / nach Host │ - │ Rechtsklick Menü zu Verbindung od… m Thema stumm f Filter: heute · 7 Tag… │ - │ * alle sichtbaren marki… l Tatsache merken s Hosts sortieren │ - │ Strg+Z Löschen rückgängig (1… p / g Absicht: Plan / Agent… z KI-Zusammenfassung │ - │ Strg+T im Formular: Verbindu… r Rückblick (merken, Ru… Z alle Treffer zusammen… │ - │ / suchen (auch #tag) ? zuletzt gesendet b Änderungsbericht │ - │ o neuer Ordner (A / B v… x Export: md · txt · ca… │ - │ r Ordner bearbeiten ◆ Vorgang über mehrere Fenster d löschen │ - │ v in Ordner verschieben Alt+V a Mitschreiben an/aus │ + │ ◆ Überall ◎ Ziel-Modus F2 / Suche im Verlauf Strg+F │ +de│ Strg+Space Befehlspalette ⏎ Ziel starten / ausfüh… tippen suchen (Groß = genau) │ +● │ F1 diese Hilfe ⇧⏎ / Strg+J neue Zeile im Ziel ⏎ / ↑ nächster (älter) │ + │ F11 Vollbild an/aus (eige… i nur einfügen (Dry-Run) ⇧⏎ / ↓ zurück (neuer) │ + │ F12 Über & Update e bearbeiten Strg+E nur Fehlerzeilen │ +de│ F12 w Was ist neu s / ⇧S überspringen / mit Gr… Tab Fehlerliste / Verlauf │ + │ F12 l Sprache: Deutsch/Engl… ? KI anweisen (gilt ab … Esc schließen │ + │ ⇧F9 Tastenzeile erklären r neu vorschlagen │ + │ Strg+Q beenden (fragt bei of… x Ziel beenden ▲ Log-Blick Alt+E │ + │ j n q Leertaste Befehl fragt nach: ⏎ Zeilen des Musters │ + │ ≡ Verbindungs-Manager F10 An… 1…4 Prüfbefehl einfügen │ + │ F10 zurück zum Terminal f Folgeziel (kennt die … k KI erklärt das Muster │ + │ ⏎ verbinden u Änderungen des Ziels … b KI-Lagebericht │ + │ n neue Verbindung ⏎ nach Abbruch Ziel fortsetzen x / X ausblenden: Host / Or… │ + │ e bearbeiten ↑ ↓ Runbook oder früheres… n Was ist neu? (u zurüc… │ + │ d löschen Strg+S als Runbook speichern t Zeitleiste (←→, ⏎, k) │ + │ Leertaste markieren (dann e, v,… Strg+D Runbook / Verlaufsein… z Zeitraum 1 h … 7 Tage │ + │ Rechtsklick Menü zu Verbindung od… Tab Schritt für Schritt o… w Logwache: Meldungen │ + │ * alle sichtbaren marki… Esc Agent anhalten s Switch: Syslog an ssh… │ + │ Strg+Z Löschen rückgängig (1… v Skript des Agenten an… r / c neu lesen / kopieren │ + │ Strg+T im Formular: Verbindu… r Skripte des Agenten l… │ + │ / suchen (auch #tag) c / l Ergebnis kopieren / g… ≡ Sitzungsprotokolle l │ + │ o neuer Ordner (A / B v… Bild↑ Bild↓ im Panel blättern (au… / suchen (auch Ausgabe) │ + │ r Ordner bearbeiten Leertaste Plan: Schritt streich… ⏎ / → ← auf-/zuklappen │ + │ v in Ordner verschieben ? Plan: neu planen lass… Tab nach Zeit / nach Host │ │ │ │ ROT Gefährliche Befehle brauchen zweimal ⏎ bzw. Alt+N. KI-Vorschläge werden nur eingefügt, nie ausgeführt. │ │ Esc führt aus jedem Panel zurück ins Terminal. │ diff --git a/internal/ui/testdata/golden/terminal-help.en.txt b/internal/ui/testdata/golden/terminal-help.en.txt index 53abd56..e23c95b 100644 --- a/internal/ui/testdata/golden/terminal-help.en.txt +++ b/internal/ui/testdata/golden/terminal-help.en.txt @@ -1,31 +1,31 @@ >_ sshTermy vdev Idea: Dominik Bornhäußer ▌● 1 web-01 × + P┌─ ? Keyboard shortcuts sshTermy vdev ─────────────────────────────────────────────────────────────────────── × ─┐er Li│ │ - │ ◆ Everywhere ◆ Ask AI F3 ▲ Log view Alt+E │ -de│ Ctrl+Space Command palette ⏎ send question ⏎ lines of the pattern │ -● │ F1 this help ⇧⏎ / Ctrl+J new line 1…4 insert check command │ - │ F11 full screen on/off (o… 1…9 insert command k AI explains the patte… │ - │ F12 About & update ↑ ↓ choose command card b AI status report │ -de│ F12 w What's new a run command (red ones… x / X hide: host / folder │ - │ F12 l Language / Sprache c copy command n What's new? (u restor… │ - │ ⇧F9 explain key bar u after an error: put t… t Timeline (←→, ⏎, k) │ - │ Ctrl+Q quit (asks if connect… z collapse/expand expla… z Period 1 h … 7 days │ - │ Esc / Ctrl+C stop answer w Log watch: alerts │ - │ ≡ Connection manager F10 n new question (fresh) s switch: send syslog t… │ - │ F10 back to the terminal f follow-up (keeps the … r / c reload / copy │ - │ ⏎ connect │ - │ n new connection ◇ AI companion Alt+J ≡ Session logs l │ - │ e edit Alt+K level: off/quiet/chat… / search (output too) │ - │ d delete Alt+1…4 insert suggestion ⏎ / → ← expand/collapse │ - │ Space mark (then e, v, d fo… ⏎ / a insert / run Tab by time / by host │ - │ Right-click menu for a connection… m mute topic f filter: today · 7 day… │ - │ * mark all visible l remember fact s sort hosts │ - │ Ctrl+Z undo delete (10 s) p / g intent: plan / agent … z AI summary │ - │ Ctrl+T in the form: test con… r recap (remember, runb… Z summarize all matches │ - │ / search (also #tag) ? last request sent b Change report │ - │ o new folder (A / B nes… x export: md · txt · ca… │ - │ r Edit folder ◆ Task across several windows Alt+V d delete │ - │ v move to folder Space / ← → choose windows / what… a recording on/off │ + │ ◆ Everywhere ◎ Goal mode F2 / Search in history Ctrl+F │ +de│ Ctrl+Space Command palette ⏎ start goal / run type search (capital = exa… │ +● │ F1 this help ⇧⏎ / Ctrl+J new line in the goal ⏎ / ↑ next (older) │ + │ F11 full screen on/off (o… i only insert (dry run) ⇧⏎ / ↓ back (newer) │ + │ F12 About & update e edit Ctrl+E error lines only │ +de│ F12 w What's new s / ⇧S skip / with a reason Tab error list / history │ + │ F12 l Language / Sprache ? instruct AI (applies … Esc close │ + │ ⇧F9 explain key bar r suggest again │ + │ Ctrl+Q quit (asks if connect… x end goal ▲ Log view Alt+E │ + │ j n q Space command asks: answer … ⏎ lines of the pattern │ + │ ≡ Connection manager F10 f follow-up goal (knows… 1…4 insert check command │ + │ F10 back to the terminal u restore what the goal… k AI explains the patte… │ + │ ⏎ connect ⏎ after a drop continue goal b AI status report │ + │ n new connection ↑ ↓ choose runbook or ear… x / X hide: host / folder │ + │ e edit Ctrl+S save as runbook n What's new? (u restor… │ + │ d delete Ctrl+D delete runbook / hist… t Timeline (←→, ⏎, k) │ + │ Space mark (then e, v, d fo… Tab step by step or agent… z Period 1 h … 7 days │ + │ Right-click menu for a connection… Esc pause agent w Log watch: alerts │ + │ * mark all visible v view the agent's scri… s switch: send syslog t… │ + │ Ctrl+Z undo delete (10 s) r delete the agent's sc… r / c reload / copy │ + │ Ctrl+T in the form: test con… c / l copy result / read all │ + │ / search (also #tag) PgUp PgDn scroll the panel (mou… ≡ Session logs l │ + │ o new folder (A / B nes… Space plan: remove step / search (output too) │ + │ r Edit folder ? plan: re-plan ⏎ / → ← expand/collapse │ + │ v move to folder Tab by time / by host │ │ │ │ RED Dangerous commands need ⏎ twice or Alt+N. AI suggestions are only inserted, never run. │ │ Esc leads back to the terminal from every panel. │ diff --git a/internal/ui/timeline.go b/internal/ui/timeline.go index f6633ad..a2dd8f7 100644 --- a/internal/ui/timeline.go +++ b/internal/ui/timeline.go @@ -52,6 +52,10 @@ func (a *App) viewTimeline(b *strings.Builder, s *session, w int) { switch { case d.Skipped: mark, ms = "»", st.Muted + case d.Manual && (d.ExitHint != "" || (d.Exit != nil && *d.Exit != 0)): + mark, ms = "•", st.Danger + case d.Manual: + mark, ms = "•", st.Accent // von dir selbst getippt case d.File != "" && d.ExitHint == "": mark, ms = "▪", st.AI case d.ExitHint != "" || (d.Exit != nil && *d.Exit != 0): @@ -79,6 +83,8 @@ func (a *App) viewTimeline(b *strings.Builder, s *session, w int) { } var sub string switch { + case d.Skipped && d.Note != "": + sub = st.Muted.Render("→ " + trunc(d.Note, max(4, w-4))) case d.ExitHint != "": sub = st.Danger.Render("→ " + trunc(d.ExitHint, max(4, w-4))) case d.Exit != nil && *d.Exit != 0: diff --git a/site/de/index.html b/site/de/index.html index 0484a78..89011ba 100644 --- a/site/de/index.html +++ b/site/de/index.html @@ -128,6 +128,8 @@ sudo apt update && sudo apt install sshtermy

Verbindungsmanager

Ordner, Tags, Jump-Hosts, Import aus ~/.ssh/config, PuTTY und MobaXterm.

Fehlerverzeihend

Beenden fragt bei offenen Verbindungen nach, Löschen lässt sich 10 Sekunden lang rückgängig machen, Strg+T im Formular testet die Verbindung vor dem Speichern, und fehlgeschlagene Verbindungen erklären in Klartext, was los ist (mit Taste zum Beheben, z. B. neuen Host-Key nach Neuinstallation übernehmen). Der einfache Modus blendet Profi-Funktionen aus.

Eigenes Fenster

Kein Terminal nötig: Doppelklick auf die .exe, die .app öffnen oder sshtermy -window. Schrift, Nerd-Font-Symbole und Emoji sind eingebaut, jede Taste kommt an (Alt+⏎, ⇧F-Tasten, Strg+Leertaste), Bilder erscheinen pixelgenau, abgelegte Dateien werden hochgeladen, ⇧F10 öffnet ein zweites Fenster. Startet im Vollbild (F11 schaltet um; maximiert oder „wie zuletzt“ in den Einstellungen), Schriftgröße und Fensterposition werden gemerkt. Im Terminal gestartet läuft es wie bisher im Terminal.

+

Ziel-Modus im Einsatz

? gibt der KI mitten im Ziel eine Anweisung, ⇧S überspringt einen Schritt mit Grund. Fragt ein Befehl [Y/n] oder wartet ein Pager, zeigt das Panel Antwort-Knöpfe. Dateien, die ein Schritt ändert, werden vorher gesichert, u holt alle zurück; f startet ein Folgeziel, frühere Ziele stehen im Verlauf. Nach einem Verbindungsabbruch setzt ⏎ fort, und der Tab zeigt, wenn ein Ziel auf dich wartet.

+

Befehle als Blöcke

Alt+Bild↑/Bild↓ springt im Verlauf von Befehl zu Befehl. Alt+O listet die Befehle des Tabs mit Uhrzeit, Dauer und Ergebnis: genau eine Ausgabe kopieren, an die KI geben oder groß lesen.

Echtes Terminal

xterm-256color, Truecolor, vim, htop und tmux, Scrollback, Tabs, geteilte Ansicht, Suche.

Auto-Reconnect

Reißt WLAN oder VPN ab, kommt die Sitzung von selbst zurück, mit Tunneln und tmux/screen. Nach Ruhezustand oder Netzwechsel wird jede Leitung binnen Sekunden geprüft.

Dateien (F5)

SFTP über dieselbe Verbindung: links lokal, rechts der Server. e öffnet eine Server-Datei in VS Code, Notepad++ oder TextEdit, Speichern lädt sie zurück. Beim Kopieren: Prozent, MB/s, Restzeit und Tempo-Kurve.

@@ -207,6 +209,7 @@ sudo apt update && sudo apt install sshtermy Alt+0Nach einem Fehler: Ursache und Fix F2Ziel-Modus (Agent) F2 → v / s / rZiel-Modus, Datei-Schritt: Datei ansehen / überspringen; am Ende Arbeitsordner löschen (⏎ legt die Datei an) + F2 → ? / ⇧S / f / uZiel-Modus: KI anweisen / mit Grund überspringen / Folgeziel / vom Ziel geänderte Dateien zurückholen; ↑↓ im leeren Zielfeld wählt ein früheres Ziel; fragt ein Befehl nach: j n q Leertaste F2 → c / lAgent fertig: Ergebnis kopieren / ganz lesen; Bild↑/Bild↓ oder Mausrad blättern im Panel; mit der Maus ziehen markiert und kopiert Text im Panel (Ziel, Schritte, Ausgaben, Fehler) F3KI fragen, mit Terminal-Kontext; Esc bricht die Antwort ab, n neue Frage, f Folgefrage, u Fix übernehmen, wenn ein Kartenbefehl fehlschlug Alt+K / Alt+JKI-Begleiter: Stufe (aus, leise, gesprächig, Coach) / Begleiter-Leiste @@ -220,6 +223,7 @@ sudo apt update && sudo apt install sshtermy Alt+Z / Alt+IBereich zoomen / in alle Bereiche tippen Strg+FIm Verlauf suchen Alt+SIn allen offenen Tabs suchen + Alt+Bild↑ / Bild↓ / Alt+OZum vorigen / nächsten Befehl springen; Befehle des Tabs als Liste (Ausgabe kopieren, KI fragen) Leertaste / *Manager: Verbindung markieren / alle sichtbaren; dann e, v, d für alle Manager → RechtsklickMenü zu Verbindung oder Ordner: verbinden, bearbeiten, verschieben, Tunnel, SSH-Key, Wake-on-LAN, löschen F6 → cContainer: Docker, Podman, Kubernetes (Shell, Logs, KI) diff --git a/site/handout/sshtermy-kurzreferenz-de.pdf b/site/handout/sshtermy-kurzreferenz-de.pdf index d162642..30d9000 100644 Binary files a/site/handout/sshtermy-kurzreferenz-de.pdf and b/site/handout/sshtermy-kurzreferenz-de.pdf differ diff --git a/site/handout/sshtermy-quickref-en.pdf b/site/handout/sshtermy-quickref-en.pdf index 17629a2..88fdbf6 100644 Binary files a/site/handout/sshtermy-quickref-en.pdf and b/site/handout/sshtermy-quickref-en.pdf differ diff --git a/site/index.html b/site/index.html index dc269de..793fe48 100644 --- a/site/index.html +++ b/site/index.html @@ -128,6 +128,8 @@ sudo apt update && sudo apt install sshtermy

Connection manager

Folders, tags, jump hosts, import from ~/.ssh/config, PuTTY and MobaXterm.

Forgiving

Quitting asks while connections are open, deleting offers undo for 10 s, Ctrl+T in the form tests the connection before saving, and failed connections explain in plain language what's wrong (with a key to fix it, e.g. accept a new host key after a reinstall). Simple mode hides the pro features.

Own window

No terminal needed: double-click the .exe, open the .app or run sshtermy -window. Font, Nerd Font symbols and emoji are built in, every key arrives (Alt+⏎, ⇧F-keys, Ctrl+Space), images show pixel-perfect, dropped files are uploaded, ⇧F10 opens a second window. Starts in full screen (F11 toggles; maximized or “as last time” in the settings), font size and window position are remembered. From a terminal it runs in the terminal as before.

+

Goal mode in daily use

? gives the AI an instruction mid-goal, ⇧S skips a step with a reason. When a command asks [Y/n] or a pager waits, the panel shows answer buttons. Files a step changes are backed up first, u restores them all; f starts a follow-up goal, earlier goals are in the history. After a connection drop ⏎ continues, and the tab shows when a goal is waiting for you.

+

Commands as blocks

Alt+PgUp/PgDn jumps from command to command in the scrollback. Alt+O lists the tab's commands with time, duration and result: copy exactly one output, hand it to the AI or read it in full.

Real terminal

xterm-256color, truecolor, vim, htop and tmux, scrollback, tabs, split view, search.

Auto-reconnect

When Wi-Fi or VPN drops, the session comes back by itself, with tunnels and tmux/screen. After sleep or a network change every line is checked within seconds.

Files (F5)

SFTP over the same connection: local on the left, server on the right. e opens a server file in VS Code, Notepad++ or TextEdit, saving uploads it back. While copying: percent, MB/s, time left and a speed curve.

@@ -206,6 +208,7 @@ sudo apt update && sudo apt install sshtermy F1Help F2Goal mode (agent) F2 → v / s / rGoal mode, file step: view the file / skip it; at the end delete the work folder (⏎ creates the file) + F2 → ? / ⇧S / f / uGoal mode: instruct the AI / skip with a reason / follow-up goal / restore the files the goal changed; ↑↓ in the empty goal field picks an earlier goal; if a command asks for input: j n q Space F2 → c / lAgent finished: copy the result / read it in full; PgUp/PgDn or the mouse wheel scroll the panel; drag with the mouse to select and copy text in the panel (goal, steps, output, errors) F3Ask AI with terminal context; Esc stops the answer, n new question, f follow-up, u use the fix after a failed card command Alt+K / Alt+JAI companion: level (off, quiet, chatty, coach) / companion sidebar @@ -219,6 +222,7 @@ sudo apt update && sudo apt install sshtermy Alt+Z / Alt+IZoom a pane / type into all panes Ctrl+FSearch the scrollback Alt+SSearch in all open tabs + Alt+PgUp / PgDn / Alt+OJump to the previous / next command; list of the tab's commands (copy output, ask AI) Space / *Manager: mark a connection / all visible; then e, v, d for all Manager → right-clickMenu for a connection or folder: connect, edit, move, tunnel, SSH key, Wake-on-LAN, delete F6 → cContainers: Docker, Podman, Kubernetes (shell, logs, AI) diff --git a/tools/handout/content.mjs b/tools/handout/content.mjs index 451aa2a..d1bd6d4 100644 --- a/tools/handout/content.mjs +++ b/tools/handout/content.mjs @@ -63,6 +63,7 @@ export const de = { ['Alt+T', 'Tab-Liste: ⏎ springen, 1…9 direkt'], ['Strg+R / D', '(Liste) umbenennen / duplizieren'], ['Alt+S', 'in allen Tabs suchen'], + ['Alt+O', 'Befehle des Tabs · Alt+Bild↑↓ springt'], ['⇧↑ / ⇧↓', '(Liste) Tab verschieben'], ['_Rechtsklick_', 'Tab-Menü · Mittelklick schließt'], ]}, @@ -97,10 +98,11 @@ export const de = { ['⏎', 'Ziel starten / Schritt ausführen'], ['i', 'nur einfügen (Dry-Run)'], ['e / s / r', 'ändern / auslassen / neu'], + ['? / ⇧S', 'KI anweisen / auslassen mit Grund'], ['x', 'Ziel beenden'], - ['↑ / ↓', 'Runbook wählen'], - ['Strg+S', 'als Runbook speichern'], - ['Strg+D', 'Runbook löschen'], + ['f / u', 'Folgeziel / Änderungen zurückholen'], + ['↑ / ↓', 'Runbook oder früheres Ziel'], + ['Strg+S / D', 'als Runbook speichern / löschen'], ['Tab', 'Modus: Schritt → Agent → Erst planen'], ]}, { t: 'Agent-Modus', ic: '◆', key: 'F2 → Tab', ai: true, rows: [ @@ -241,6 +243,7 @@ export const en = { ['Alt+T', 'tab list: ⏎ jump, 1…9 direct'], ['Ctrl+R / D', '(list) rename / duplicate'], ['Alt+S', 'search in all tabs'], + ['Alt+O', 'tab commands · Alt+PgUp/Dn jumps'], ['⇧↑ / ⇧↓', '(list) move the tab'], ['_right-click_', 'tab menu · middle click closes'], ]}, @@ -275,10 +278,11 @@ export const en = { ['⏎', 'start goal / run step'], ['i', 'only insert (dry run)'], ['e / s / r', 'edit / skip / suggest again'], + ['? / ⇧S', 'instruct the AI / skip with a reason'], ['x', 'end the goal'], - ['↑ / ↓', 'choose a runbook'], - ['Ctrl+S', 'save as runbook'], - ['Ctrl+D', 'delete runbook'], + ['f / u', 'follow-up goal / restore changes'], + ['↑ / ↓', 'runbook or earlier goal'], + ['Ctrl+S / D', 'save as runbook / delete'], ['⇧⏎ / Ctrl+J', 'new line in the goal'], ['Tab', 'mode: step by step → agent → plan first'], ]}, diff --git a/tools/handout/keys.sha256 b/tools/handout/keys.sha256 index abdc110..09fad74 100644 --- a/tools/handout/keys.sha256 +++ b/tools/handout/keys.sha256 @@ -1 +1 @@ -ecf92ef193056eb1360d0b1623d8a8f48a8aa51f27a8c0bacb03a831ee8e98fc +789a1c6ea5290bea17bb135956832ed8a137edfa8c159f48e58bc0ed447e6a02