package action import ( "context" "fmt" "github.com/egoist/mygo" ) func init() { Register("show_notification", func() Action { return ¬ificationAction{} }) } // notificationAction 显示系统桌面通知。 type notificationAction struct{} func (a *notificationAction) ID() string { return "show_notification" } func (a *notificationAction) Name() string { return "显示通知" } func (a *notificationAction) Schema() ActionSchema { return ActionSchema{Params: []ParamSpec{ {Name: "title", Label: "标题", Type: "string", Required: true}, {Name: "text", Label: "内容", Type: "string", Required: true}, }} } func (a *notificationAction) Validate(params map[string]any) error { if GetString(params, "title") == "" { return fmt.Errorf("show_notification: missing param \"title\"") } if GetString(params, "text") == "" { return fmt.Errorf("show_notification: missing param \"text\"") } return nil } func (a *notificationAction) Execute(ctx context.Context, params map[string]any) error { if !NotificationsAllowed(ctx) { logger.Debug("show_notification suppressed by notify switch", "action", a.ID()) return nil } if err := notifyDesktop(GetString(params, "title"), GetString(params, "text")); err != nil { return fmt.Errorf("show_notification: %w", err) } return nil } // notifyDesktop 通过 mygo 通知后端显示一条桌面通知。 // mygo 通知后端要求应用已启动:测试环境或启动早期调用时返回错误而不是 panic。 func notifyDesktop(title, body string) (err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("notification backend unavailable: %v", r) } }() if !mygo.NotificationsSupported() { return fmt.Errorf("当前环境不支持桌面通知") } return mygo.NewNotification(mygo.NotificationOptions{Title: title, Body: body}).Show() }