Files
lan-clipboard/agent/internal/agent/agent.go
T
dbildhauerandClaude Opus 5.5 4aebac5336 feat: desktop-agent für windows, macos und linux
Go-Programm lc-agent: sendet neu kopierten Text als Clip ins Projekt
"Zwischenablage" und übernimmt eigene Clips anderer Geräte live in die
Zwischenablage. Von Passwort-Managern markierte Inhalte werden nie
gesendet; Größengrenze, Ausschlussmuster, nur die letzten 50 eigenen
Clips. Wiederholt beim Start, bis der Server erreichbar ist; beendet sich
bei widerrufenem Token mit Exit-Code 3. Build für alle Plattformen per
build.sh im Container, Autostart-Vorlagen für alle drei Systeme.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 15:11:40 +01:00

305 lines
7.6 KiB
Go

// Package agent keeps the local clipboard and the server in sync.
//
// Sending: the clipboard is polled; new text becomes a clip in the agent's project.
// Receiving: new text/code clips of the same user from other devices are written to
// the clipboard. A hash of the last seen content prevents sending received text back.
package agent
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"log"
"os"
"regexp"
"strings"
"sync"
"time"
"unicode/utf8"
"lan-clipboard/agent/internal/api"
"lan-clipboard/agent/internal/clipboard"
"lan-clipboard/agent/internal/config"
)
const (
minRetry = time.Second
maxRetry = 30 * time.Second
)
// Stands for "concealed content" so a secret staying in the clipboard is logged once
var concealedHash = sha256.Sum256([]byte("\x00concealed\x00"))
// API is the part of the server client the agent uses (faked in tests).
type API interface {
Me(ctx context.Context) (api.User, error)
Projects(ctx context.Context) ([]api.Project, error)
CreateProject(ctx context.Context, name string) (api.Project, error)
CreateClip(ctx context.Context, content string, projectID *int64) (api.Clip, error)
DeleteClip(ctx context.Context, id int64) error
Events(ctx context.Context, handle func(api.Event)) error
}
// state is persisted between runs: the ids of clips this device created, oldest first.
type state struct {
Sent []int64 `json:"sent"`
}
type Agent struct {
cfg config.Config
api API
clipboard clipboard.Clipboard
log *log.Logger
statePath string
patterns []*regexp.Regexp
mu sync.Mutex
me int64
projectID *int64
lastHash [32]byte
sent []int64
// Clips created by this device; their live events are not written back
own map[int64]bool
}
func New(cfg config.Config, client API, cb clipboard.Clipboard, logger *log.Logger, statePath string) (*Agent, error) {
patterns, err := cfg.Patterns()
if err != nil {
return nil, err
}
return &Agent{
cfg: cfg,
api: client,
clipboard: cb,
log: logger,
statePath: statePath,
patterns: patterns,
own: map[int64]bool{},
}, nil
}
// Setup identifies the user, finds or creates the project and loads the state.
// Whatever is in the clipboard at start is not sent: only later changes are.
func (a *Agent) Setup(ctx context.Context) error {
me, err := a.api.Me(ctx)
if err != nil {
return err
}
a.me = me.ID
if a.cfg.Project != "" {
id, err := a.ensureProject(ctx, a.cfg.Project)
if err != nil {
return err
}
a.projectID = &id
}
a.loadState()
if content, err := a.clipboard.Read(); err == nil {
a.lastHash = sha256.Sum256([]byte(content.Text))
}
a.log.Printf("Verbunden als %s, Richtung %s, Projekt %q", me.Username, a.cfg.Direction, a.cfg.Project)
return nil
}
func (a *Agent) ensureProject(ctx context.Context, name string) (int64, error) {
projects, err := a.api.Projects(ctx)
if err != nil {
return 0, err
}
for _, p := range projects {
// Only an own project: a shared one with the same name belongs to someone else
if p.Role == "owner" && strings.EqualFold(p.Name, name) {
return p.ID, nil
}
}
project, err := a.api.CreateProject(ctx, name)
if err != nil {
return 0, err
}
a.log.Printf("Projekt %q angelegt", name)
return project.ID, nil
}
// Run polls the clipboard and listens for live events until ctx ends or the token
// is rejected.
func (a *Agent) Run(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
errs := make(chan error, 2)
if a.cfg.Direction.Sends() {
go func() { errs <- a.pollLoop(ctx) }()
}
if a.cfg.Direction.Receives() {
go func() { errs <- a.eventLoop(ctx) }()
}
err := <-errs
if errors.Is(err, context.Canceled) {
return nil
}
return err
}
func (a *Agent) pollLoop(ctx context.Context) error {
ticker := time.NewTicker(time.Duration(a.cfg.PollMs) * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
if err := a.Tick(ctx); errors.Is(err, api.ErrUnauthorized) {
return err
}
}
}
}
func (a *Agent) eventLoop(ctx context.Context) error {
delay := minRetry
for {
started := time.Now()
err := a.api.Events(ctx, a.HandleEvent)
if ctx.Err() != nil {
return ctx.Err()
}
if errors.Is(err, api.ErrUnauthorized) {
return err
}
if time.Since(started) > time.Minute {
delay = minRetry // was connected for a while; start backing off anew
}
a.log.Printf("Live-Verbindung unterbrochen (%v), neuer Versuch in %s", err, delay)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(delay):
}
delay = min(delay*2, maxRetry)
}
}
// skipReason tells why a text is not sent, or "" if it may be sent.
func (a *Agent) skipReason(text string) string {
if strings.TrimSpace(text) == "" {
return "leer"
}
if utf8.RuneCountInString(text) > a.cfg.MaxChars {
return "zu lang"
}
for _, re := range a.patterns {
if re.MatchString(text) {
return "Ausschlussmuster"
}
}
return ""
}
// Tick checks the clipboard once and sends new text. Content is never logged.
func (a *Agent) Tick(ctx context.Context) error {
content, err := a.clipboard.Read()
if err != nil {
return nil // transient (clipboard busy); try again next tick
}
hash := sha256.Sum256([]byte(content.Text))
if content.Concealed {
hash = concealedHash // the text is unknown; remember "a secret is there" instead
}
a.mu.Lock()
if hash == a.lastHash {
a.mu.Unlock()
return nil
}
a.lastHash = hash
a.mu.Unlock()
if content.Concealed {
a.log.Print("Von einem Passwort-Manager markierten Inhalt übersprungen")
return nil
}
if reason := a.skipReason(content.Text); reason != "" {
if reason != "leer" {
a.log.Printf("Inhalt nicht gesendet: %s", reason)
}
return nil
}
clip, err := a.api.CreateClip(ctx, content.Text, a.projectID)
if err != nil {
a.log.Printf("Senden fehlgeschlagen: %v", err)
return err
}
a.log.Printf("Gesendet (%d Zeichen)", utf8.RuneCountInString(content.Text))
a.mu.Lock()
a.own[clip.ID] = true
a.sent = append(a.sent, clip.ID)
excess := max(len(a.sent)-a.cfg.Keep, 0)
old := append([]int64(nil), a.sent[:excess]...)
a.sent = a.sent[excess:]
a.mu.Unlock()
for _, id := range old {
if err := a.api.DeleteClip(ctx, id); err != nil {
a.log.Printf("Alten Clip %d nicht gelöscht: %v", id, err)
}
}
a.saveState()
return nil
}
// HandleEvent writes new text/code clips of the same user from other devices to the
// clipboard.
func (a *Agent) HandleEvent(event api.Event) {
if event.Type != "clip.created" {
return
}
var clip api.Clip
if err := json.Unmarshal(event.Data, &clip); err != nil {
return
}
if clip.Kind != "text" && clip.Kind != "code" {
return
}
hash := sha256.Sum256([]byte(clip.Content))
a.mu.Lock()
// Clips of other members of shared projects stay out of this clipboard
skip := clip.UserID != a.me || a.own[clip.ID] || hash == a.lastHash
if !skip {
a.lastHash = hash // so the next poll does not send it back
}
a.mu.Unlock()
if skip {
return
}
if err := a.clipboard.Write(clip.Content); err != nil {
a.log.Printf("Zwischenablage nicht gesetzt: %v", err)
return
}
a.log.Printf("Empfangen (%d Zeichen)", utf8.RuneCountInString(clip.Content))
}
func (a *Agent) loadState() {
data, err := os.ReadFile(a.statePath)
if err != nil {
return
}
var s state
if json.Unmarshal(data, &s) == nil {
a.sent = s.Sent
for _, id := range s.Sent {
a.own[id] = true
}
}
}
func (a *Agent) saveState() {
a.mu.Lock()
data, err := json.Marshal(state{Sent: a.sent})
a.mu.Unlock()
if err != nil {
return
}
tmp := a.statePath + ".tmp"
if err := os.WriteFile(tmp, data, 0o600); err == nil {
os.Rename(tmp, a.statePath)
}
}