PasteFerry (隔空贴): clipboard and file sync across macOS, Windows and Linux. Direct-first, end-to-end encrypted. Optional official access: no server to host. Independent self-hosting remains available.
Dart airdrop-alternativeclipboardclipboard-sharingclipboard-synccopy-pastecross-platformend-to-end-encryptionfile-syncfile-transferfluttergolanglinuxmacosnat-traversalp2pself-hostedtailscaleuniversal-clipboardwebrtcwindows
feat(core): add large file receive notifications and feedback
baiyuzed461fcc8eace
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 74a5026..3fef0c3 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -118,7 +118,7 @@ jobs:- name: 安装构建依赖run: |sudo apt-get update -q- sudo apt-get install -y -q clang cmake ninja-build pkg-config libgtk-3-dev xvfb xclip+ sudo apt-get install -y -q clang cmake ninja-build pkg-config libgtk-3-dev xvfb xclip dbus-x11# flutter-action 不提供 Linux ARM64 的 Flutter,两种架构都直接取 stable 分支- name: 安装 Flutterrun: |@@ -126,7 +126,7 @@ jobs:echo "$RUNNER_TEMP/flutter/bin" >> "$GITHUB_PATH"- run: flutter --version# X11 剪贴板的测试在虚拟显示器里跑,xclip 扮演别的程序- - run: go vet ./... && xvfb-run -a go test ./...+ - run: go vet ./... && dbus-run-session -- xvfb-run -a go test ./...working-directory: client-core- run: xvfb-run -a go test -v -count=1 -run Linux ./internal/clipboard/working-directory: client-corediff --git a/client-core/cmd/pasteferryd/main.go b/client-core/cmd/pasteferryd/main.goindex d6e4e2d..d11cc69 100644--- a/client-core/cmd/pasteferryd/main.go+++ b/client-core/cmd/pasteferryd/main.go@@ -24,6 +24,7 @@ import ("github.com/baiyuze/pasteferry/client-core/internal/config""github.com/baiyuze/pasteferry/client-core/internal/gc""github.com/baiyuze/pasteferry/client-core/internal/identity"+ "github.com/baiyuze/pasteferry/client-core/internal/notifications""github.com/baiyuze/pasteferry/client-core/internal/peers""github.com/baiyuze/pasteferry/client-core/internal/rpc""github.com/baiyuze/pasteferry/client-core/internal/store"@@ -45,14 +46,22 @@ func main() {runtime.LockOSThread()var (- dataDir = flag.String("data-dir", "", "数据目录(默认为系统标准位置)")- verbose = flag.Bool("v", false, "输出调试日志")- probe = flag.Bool("probe-clipboard", false,+ notificationAction = flag.String("notification-action", "", "Handle a desktop notification action and exit")+ dataDir = flag.String("data-dir", "", "数据目录(默认为系统标准位置)")+ verbose = flag.Bool("v", false, "输出调试日志")+ probe = flag.Bool("probe-clipboard", false,"诊断用:在主线程直接读一次剪贴板并打印结果后退出")supervise = flag.Bool("supervise", false,"守护模式:拉起后台服务,异常退出时自动重启(Windows、Linux 开机自启用)"))flag.Parse()+ if *notificationAction != "" {+ if err := activateNotification(*notificationAction); err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+ return+ }if *dataDir == "" {if p, err := config.DefaultPaths(); err == nil {@@ -171,6 +180,9 @@ func run(dataDir string) error {return err}defer db.Close()+ if err := db.RecoverReceives(); err != nil {+ return err+ }blobs, err := cache.New(paths.Cache)if err != nil {@@ -213,6 +225,19 @@ func run(dataDir string) error {// ── 设备配对与信令(引擎稍后注入)──var engine *syncengine.Engine+ notifier := notifications.New(ctx, notifications.Options{+ Enabled: dataDir == "", Loop: loop, Language: func() string { return loadCfg().Language },+ Fetch: func(ctx context.Context, id string) error { return engine.Fetch(ctx, id) },+ Apply: func(ctx context.Context, id string) error { return engine.ApplyToClipboard(ctx, id) },+ Record: func(id string) (*pb.ClipRecord, error) {+ clip, err := db.GetClip(id)+ if err != nil {+ return nil, err+ }+ return rpc.ClipToProto(clip), nil+ },+ })+ defer notifier.Close()// 状态快照要由 gRPC 服务组装,而它晚于 peerMgr 创建,这里先记下"状态变了",// 等服务就绪后统一推送。容量 1 让连续的变化合并成一次刷新。@@ -276,6 +301,21 @@ func run(dataDir string) error {}return ids},+ OnReceive: func(ev syncengine.ReceiveEvent) {+ switch ev.Stage {+ case syncengine.ReceivePending:+ notifier.Pending(ev.Record)+ case syncengine.ReceiveStarted:+ notifier.Started(ev.Record)+ case syncengine.ReceiveCompleted:+ notifier.Completed(ev.Record, ev.Clipboard)+ case syncengine.ReceiveFailed:+ notifier.Failed(ev.Record)+ }+ },+ OnClipboardResult: func(result *pb.ClipboardWriteResult) {+ hub.Publish(&pb.Event{Payload: &pb.Event_ClipboardWritten{ClipboardWritten: result}})+ },OnRecord: func(r *pb.ClipRecord) {hub.Publish(rpc.EventClipAdded(r))},@@ -290,6 +330,8 @@ func run(dataDir string) error {go engine.HandleClipboardChange(ctx, snap)})+ defer engine.Close()+go peerMgr.Run(ctx)go watcher.Run(ctx)@@ -388,6 +430,9 @@ func run(dataDir string) error {defer cancel()return watcher.OpenPermissionSettings(ctx)},+ NotificationStatus: notifier.Status,+ RequestNotifications: notifier.Request,+ ActivateNotification: notifier.Activate,}, hub, token)// 信令连接与在线对端数的变化推给 UI。Subscribe 只在建立订阅时推一次状态,diff --git a/client-core/cmd/pasteferryd/notification_action.go b/client-core/cmd/pasteferryd/notification_action.gonew file mode 100644index 0000000..c45b1eb--- /dev/null+++ b/client-core/cmd/pasteferryd/notification_action.go@@ -0,0 +1,51 @@+package main++import (+ "context"+ "fmt"+ "net"+ "net/url"+ "time"++ "github.com/baiyuze/pasteferry/client-core/internal/config"+ "github.com/baiyuze/pasteferry/client-core/internal/notifications"+ "github.com/baiyuze/pasteferry/client-core/internal/rpc"+ pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"+ "google.golang.org/grpc"+ "google.golang.org/grpc/credentials/insecure"+ "google.golang.org/grpc/metadata"+)++// A Windows protocol activation is a client of the existing daemon, never a+// second clipboard owner or supervisor. The endpoint token stays off the URI.+func activateNotification(raw string) error {+ u, err := url.Parse(raw)+ if err != nil || u.Scheme != "pasteferry-notify" || u.Host != "action" {+ return fmt.Errorf("invalid notification URI")+ }+ verb, id := u.Query().Get("action"), u.Query().Get("clip")+ if verb == "open" {+ return notifications.OpenUI()+ }+ if (verb != "receive" && verb != "apply") || id == "" {+ return fmt.Errorf("invalid notification action")+ }+ paths, err := config.DefaultPaths()+ if err != nil {+ return err+ }+ ep, err := rpc.ReadEndpoint(paths.Endpoint)+ if err != nil {+ return err+ }+ conn, err := grpc.NewClient(net.JoinHostPort("127.0.0.1", fmt.Sprint(ep.Port)), grpc.WithTransportCredentials(insecure.NewCredentials()))+ if err != nil {+ return err+ }+ defer conn.Close()+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()+ ctx = metadata.AppendToOutgoingContext(ctx, "x-pasteferry-token", ep.Token)+ _, err = pb.NewDaemonServiceClient(conn).ActivateNotification(ctx, &pb.NotificationAction{ClipId: id, Action: verb})+ return err+}diff --git a/client-core/go.mod b/client-core/go.modindex 2cb7989..3f0baa7 100644--- a/client-core/go.mod+++ b/client-core/go.mod@@ -6,6 +6,7 @@ require modernc.org/sqlite v1.59.0require (github.com/dustin/go-humanize v1.0.1 // indirect+ github.com/godbus/dbus/v5 v5.2.2 // indirectgithub.com/google/uuid v1.6.0 // indirectgithub.com/mattn/go-isatty v0.0.24 // indirectgithub.com/ncruces/go-strftime v1.0.0 // indirect@@ -44,6 +45,7 @@ replace github.com/baiyuze/pasteferry/proto => ../protorequire (github.com/baiyuze/pasteferry/server v0.0.0+ github.com/godbus/dbus/v5 v5.2.2github.com/jezek/xgb v1.3.1github.com/klauspost/compress v1.20.0github.com/pion/ice/v4 v4.4.2diff --git a/client-core/go.sum b/client-core/go.sumindex 9df31be..09434c4 100644--- a/client-core/go.sum+++ b/client-core/go.sum@@ -2,6 +2,8 @@ github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUgithub.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=+github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=+github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=diff --git a/client-core/internal/cache/cache.go b/client-core/internal/cache/cache.goindex 0417d09..c6ca6c2 100644--- a/client-core/internal/cache/cache.go+++ b/client-core/internal/cache/cache.go@@ -9,6 +9,7 @@ import ("os""path/filepath""strings"+ "sync")// Cache 是缓存目录的封装。@@ -16,7 +17,9 @@ import (// 每条记录占一个子目录,目录名即 clip id 派生的短标识。// 用目录而非单文件,是因为一次复制可能包含多个文件或整个文件夹。type Cache struct {- root string+ root string+ mu sync.Mutex+ active map[string]int}func New(root string) (*Cache, error) {@@ -28,6 +31,49 @@ func New(root string) (*Cache, error) {func (c *Cache) Root() string { return c.root }+// LeaseDir protects an in-progress unpacker from orphan collection. The lease+// is released only after the record references the completed cache, or the+// failed unpacker has stopped writing.+func (c *Cache) LeaseDir(id string) (rel, abs string, release func(), err error) {+ c.mu.Lock()+ defer c.mu.Unlock()+ rel, abs, err = c.Dir(id)+ if err != nil {+ return "", "", nil, err+ }+ if c.active == nil {+ c.active = make(map[string]int)+ }+ c.active[rel]+++ var once sync.Once+ return rel, abs, func() {+ once.Do(func() {+ c.mu.Lock()+ defer c.mu.Unlock()+ c.active[rel]--+ if c.active[rel] == 0 {+ delete(c.active, rel)+ }+ })+ }, nil+}++// RemoveOrphan rechecks the database while holding the lease lock. The+// collector's earlier reference snapshot may predate a completed download.+func (c *Cache) RemoveOrphan(rel string, referenced func(string) (bool, error)) (bool, error) {+ c.mu.Lock()+ defer c.mu.Unlock()+ if c.active[rel] > 0 {+ return false, nil+ }+ used, err := referenced(rel)+ if err != nil || used {+ return false, err+ }+ err = c.Remove(rel)+ return err == nil, err+}+// Dir 返回某条记录的缓存目录(相对路径),必要时创建。func (c *Cache) Dir(clipID string) (rel, abs string, err error) {rel = safeName(clipID)diff --git a/client-core/internal/cache/lease_test.go b/client-core/internal/cache/lease_test.gonew file mode 100644index 0000000..ade3439--- /dev/null+++ b/client-core/internal/cache/lease_test.go@@ -0,0 +1,27 @@+package cache++import "testing"++func TestReceivingCacheSurvivesCollectionAndReferenceSnapshotRace(t *testing.T) {+ c, err := New(t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ rel, _, release, err := c.LeaseDir("receiving")+ if err != nil {+ t.Fatal(err)+ }+ unreferenced := func(string) (bool, error) { return false, nil }+ if removed, err := c.RemoveOrphan(rel, unreferenced); err != nil || removed {+ t.Fatal("removed a live receive", removed, err)+ }+ release()+ // The collector's original snapshot had no reference. A just-completed+ // transfer committed one before releasing its lease; recheck it.+ if removed, err := c.RemoveOrphan(rel, func(string) (bool, error) { return true, nil }); err != nil || removed {+ t.Fatal("removed a completed receive", removed, err)+ }+ if removed, err := c.RemoveOrphan(rel, unreferenced); err != nil || !removed {+ t.Fatal("orphan not collected", removed, err)+ }+}diff --git a/client-core/internal/clipboard/clipboard.go b/client-core/internal/clipboard/clipboard.goindex 3f1f9fd..d6b368c 100644--- a/client-core/internal/clipboard/clipboard.go+++ b/client-core/internal/clipboard/clipboard.go@@ -172,6 +172,9 @@ func (l *MainLoop) Call(ctx context.Context, fn func()) error {done := make(chan struct{})wrapped := func() {defer close(done)+ if ctx.Err() != nil {+ return+ }fn()}select {@@ -181,7 +184,7 @@ func (l *MainLoop) Call(ctx context.Context, fn func()) error {}select {case <-done:- return nil+ return ctx.Err()case <-ctx.Done():return ctx.Err()}diff --git a/client-core/internal/clipboard/watcher.go b/client-core/internal/clipboard/watcher.goindex 19ae686..50eaa17 100644--- a/client-core/internal/clipboard/watcher.go+++ b/client-core/internal/clipboard/watcher.go@@ -155,15 +155,41 @@ func (w *Watcher) Read(ctx context.Context) (Content, error) {// Write 在主线程写入剪贴板,并记下由此产生的 changeCount,// 使下一轮轮询不会把它误判为用户的新复制。func (w *Watcher) Write(ctx context.Context, content Content) error {- return w.loop.Call(ctx, func() {+ _, err := w.write(ctx, content, nil)+ return err+}++// Revision reads metadata only. A failed read must never authorize a later write.+func (w *Watcher) Revision(ctx context.Context) (int64, error) {+ snap, err := CallResult(ctx, w.loop, w.cb.Peek)+ return snap.ChangeCount, err+}++// WriteIfUnchanged checks and writes in the same main-loop task, including+// changes made by other remote transfers and copies of sensitive content.+func (w *Watcher) WriteIfUnchanged(ctx context.Context, content Content, revision int64) (bool, error) {+ return w.write(ctx, content, &revision)+}++func (w *Watcher) write(ctx context.Context, content Content, revision *int64) (bool, error) {+ return CallResult(ctx, w.loop, func() (bool, error) {+ if revision != nil {+ snap, err := w.cb.Peek()+ if err != nil {+ return false, err+ }+ if snap.ChangeCount != *revision {+ return false, nil+ }+ }if err := w.cb.Write(content); err != nil {- w.log.Warn("写入剪贴板失败", "err", err)- return+ return false, err}if snap, err := w.cb.Peek(); err == nil {w.selfWrites[snap.ChangeCount] = struct{}{}w.lastChange = snap.ChangeCount}+ return true, nil})}diff --git a/client-core/internal/clipboard/watcher_test.go b/client-core/internal/clipboard/watcher_test.gonew file mode 100644index 0000000..8cdf815--- /dev/null+++ b/client-core/internal/clipboard/watcher_test.go@@ -0,0 +1,67 @@+package clipboard++import (+ "context"+ "errors"+ "testing"+)++type testClipboard struct {+ revision int64+ writeErr, peekErr error+ writes int+}++func (c *testClipboard) Peek() (Snapshot, error) { return Snapshot{ChangeCount: c.revision}, c.peekErr }+func (*testClipboard) Read() (Content, error) { return Content{}, nil }+func (c *testClipboard) Write(Content) error {+ if c.writeErr != nil {+ return c.writeErr+ }+ c.writes+++ c.revision+++ return nil+}+func (*testClipboard) Permission() Permission { return PermissionNotApplicable }+func (*testClipboard) OpenPermissionSettings() error { return nil }++func TestWatcherConditionalWriteAndErrors(t *testing.T) {+ loop := NewMainLoop()+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ // Fake clipboard: execute the actual main-loop tasks without touching an OS+ // clipboard or requiring an interactive desktop on CI.+ done := make(chan struct{})+ go func() {+ defer close(done)+ for {+ select {+ case fn := <-loop.tasks:+ fn()+ case <-ctx.Done():+ return+ }+ }+ }()+ t.Cleanup(func() { cancel(); <-done })+ cb := &testClipboard{revision: 7}+ w := NewWatcher(WatcherOptions{Clipboard: cb, MainLoop: loop})+ if ok, err := w.WriteIfUnchanged(ctx, Content{}, 6); err != nil || ok {+ t.Fatalf("changed clipboard: %v %v", ok, err)+ }+ if cb.writes != 0 {+ t.Fatal("overwrote a newer clipboard")+ }+ if ok, err := w.WriteIfUnchanged(ctx, Content{}, 7); err != nil || !ok {+ t.Fatalf("unchanged clipboard: %v %v", ok, err)+ }+ writeErr := errors.New("clipboard locked")+ cb.writeErr = writeErr+ if err := w.Write(ctx, Content{}); !errors.Is(err, writeErr) {+ t.Fatalf("write error swallowed: %v", err)+ }+ cb.peekErr = errors.New("metadata unavailable")+ if ok, err := w.WriteIfUnchanged(ctx, Content{}, 8); err == nil || ok {+ t.Fatalf("failed probe authorized a write: %v %v", ok, err)+ }+}diff --git a/client-core/internal/gc/gc.go b/client-core/internal/gc/gc.goindex d417224..fbb8a87 100644--- a/client-core/internal/gc/gc.go+++ b/client-core/internal/gc/gc.go@@ -135,7 +135,7 @@ func (c *Collector) Collect() Result {c.log.Warn("扫描孤儿缓存失败", "err", err)} else {for _, o := range orphans {- if err := c.cache.Remove(o); err == nil {+ if removed, err := c.cache.RemoveOrphan(o, c.store.CacheReferenced); err == nil && removed {res.OrphansRemoved++}}diff --git a/client-core/internal/notifications/catalog.json b/client-core/internal/notifications/catalog.jsonnew file mode 100644index 0000000..a5af680--- /dev/null+++ b/client-core/internal/notifications/catalog.json@@ -0,0 +1,92 @@+{+ "en": {+ "notifyPendingTitle": "Receive to paste",+ "notifyPendingBody": "{device} · {name} · {size}\nReceive this item before pasting. You can also receive it from History.",+ "notifyReceivingTitle": "Receiving…",+ "notifyReceivingBody": "{name}\nSee History for progress.",+ "notifyReadyTitle": "Ready to paste",+ "notifyReadyBody": "{name}\nReceived and placed on the clipboard.",+ "notifyReceivedTitle": "Received",+ "notifyReceivedBody": "{name}\nYour clipboard was kept. Use Copy to clipboard when ready; this is also available in History.",+ "notifyFailedTitle": "Could not receive",+ "notifyFailedBody": "{name}\n{error}\nTry again from this notification or History.",+ "notifyClipboardFailedTitle": "Received; clipboard was not updated",+ "notifyClipboardFailedBody": "{name}\n{error}\nUse Copy to clipboard to try again, here or in History.",+ "navHistory": "History",+ "retry": "Try again",+ "fetch": "Receive",+ "putOnClipboard": "Copy to clipboard"+ },+ "zh-Hans": {+ "notifyPendingTitle": "接收后即可粘贴",+ "notifyPendingBody": "{device} · {name} · {size}\n尚未接收,暂不可粘贴。也可从复制记录接收。",+ "notifyReceivingTitle": "正在接收…",+ "notifyReceivingBody": "{name}\n可在复制记录查看接收进度。",+ "notifyReadyTitle": "已就绪,可以粘贴",+ "notifyReadyBody": "{name}\n已接收并放入剪贴板。",+ "notifyReceivedTitle": "已接收",+ "notifyReceivedBody": "{name}\n已保留当前剪贴板,点击放入剪贴板后可粘贴,也可从复制记录操作。",+ "notifyFailedTitle": "接收失败",+ "notifyFailedBody": "{name}\n{error}\n可从此通知或复制记录重试。",+ "notifyClipboardFailedTitle": "已接收,但未能写入剪贴板",+ "notifyClipboardFailedBody": "{name}\n{error}\n可从此通知或复制记录重新放入剪贴板。",+ "navHistory": "复制记录",+ "retry": "重试",+ "fetch": "接收",+ "putOnClipboard": "放入剪贴板"+ },+ "ja": {+ "notifyPendingTitle": "受信するとペーストできます",+ "notifyPendingBody": "{device} · {name} · {size}\nペーストする前に受信してください。履歴からも受信できます。",+ "notifyReceivingTitle": "受信中…",+ "notifyReceivingBody": "{name}\n進捗は履歴で確認できます。",+ "notifyReadyTitle": "ペーストできます",+ "notifyReadyBody": "{name}\n受信してクリップボードに入れました。",+ "notifyReceivedTitle": "受信しました",+ "notifyReceivedBody": "{name}\n現在のクリップボードは保持しました。クリップボードに入れる操作は履歴からもできます。",+ "notifyFailedTitle": "受信できませんでした",+ "notifyFailedBody": "{name}\n{error}\nこの通知または履歴から再試行できます。",+ "notifyClipboardFailedTitle": "受信済みですがクリップボードを更新できませんでした",+ "notifyClipboardFailedBody": "{name}\n{error}\nこの通知または履歴からクリップボードに入れて再試行できます。",+ "navHistory": "履歴",+ "retry": "再試行",+ "fetch": "受信",+ "putOnClipboard": "クリップボードに入れる"+ },+ "zh-Hant-TW": {+ "notifyPendingTitle": "接收後即可貼上",+ "notifyPendingBody": "{device} · {name} · {size}\n尚未接收,暫不可貼上。也可從複製記錄接收。",+ "notifyReceivingTitle": "正在接收…",+ "notifyReceivingBody": "{name}\n可在複製記錄查看接收進度。",+ "notifyReadyTitle": "已就緒,可以貼上",+ "notifyReadyBody": "{name}\n已接收並放入剪貼簿。",+ "notifyReceivedTitle": "已接收",+ "notifyReceivedBody": "{name}\n已保留目前剪貼簿,點選放入剪貼簿後即可貼上,也可從複製記錄操作。",+ "notifyFailedTitle": "接收失敗",+ "notifyFailedBody": "{name}\n{error}\n可從此通知或複製記錄重試。",+ "notifyClipboardFailedTitle": "已接收,但無法寫入剪貼簿",+ "notifyClipboardFailedBody": "{name}\n{error}\n可從此通知或複製記錄重新放入剪貼簿。",+ "navHistory": "複製記錄",+ "retry": "重試",+ "fetch": "接收",+ "putOnClipboard": "放入剪貼簿"+ },+ "zh-Hant-HK": {+ "notifyPendingTitle": "接收後即可貼上",+ "notifyPendingBody": "{device} · {name} · {size}\n尚未接收,暫不可貼上。亦可從複製記錄接收。",+ "notifyReceivingTitle": "正在接收…",+ "notifyReceivingBody": "{name}\n可在複製記錄查看接收進度。",+ "notifyReadyTitle": "已就緒,可以貼上",+ "notifyReadyBody": "{name}\n已接收並放入剪貼簿。",+ "notifyReceivedTitle": "已接收",+ "notifyReceivedBody": "{name}\n已保留目前剪貼簿,按放入剪貼簿後即可貼上,亦可從複製記錄操作。",+ "notifyFailedTitle": "接收失敗",+ "notifyFailedBody": "{name}\n{error}\n可從此通知或複製記錄重試。",+ "notifyClipboardFailedTitle": "已接收,但無法寫入剪貼簿",+ "notifyClipboardFailedBody": "{name}\n{error}\n可從此通知或複製記錄重新放入剪貼簿。",+ "navHistory": "複製記錄",+ "retry": "重試",+ "fetch": "接收",+ "putOnClipboard": "放入剪貼簿"+ }+}diff --git a/client-core/internal/notifications/darwin.go b/client-core/internal/notifications/darwin.gonew file mode 100644index 0000000..a048e2c--- /dev/null+++ b/client-core/internal/notifications/darwin.go@@ -0,0 +1,103 @@+//go:build darwin++package notifications++/*+#cgo CFLAGS: -x objective-c -fobjc-arc+#cgo LDFLAGS: -framework Cocoa -framework UserNotifications+#include <stdlib.h>+int pf_notify_init(void);+int pf_notify_permission(int request);+int pf_notify_show(const char *id, const char *title, const char *body, const char *action, const char *label);+char *pf_notify_language(void);+*/+import "C"++import (+ "context"+ "errors"+ "github.com/baiyuze/pasteferry/client-core/internal/clipboard"+ pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"+ "sync"+ "unsafe"+)++var macAction struct {+ sync.RWMutex+ callback func(string, string)+}++//export goNotificationAction+func goNotificationAction(id, action *C.char) {+ clipID, verb := C.GoString(id), C.GoString(action)+ macAction.RLock()+ callback := macAction.callback+ macAction.RUnlock()+ if callback != nil {+ callback(clipID, verb)+ }+}++type macBackend struct{ loop *clipboard.MainLoop }++func newBackend(loop *clipboard.MainLoop, action func(string, string)) (Backend, error) {+ // New is called on the daemon's locked main thread after InitPlatform.+ if C.pf_notify_init() == 0 {+ return nil, errors.New("notifications require the packaged daemon app")+ }+ macAction.Lock()+ macAction.callback = action+ macAction.Unlock()+ return &macBackend{loop}, nil+}+func (b *macBackend) permission(ctx context.Context, request bool) (*pb.NotificationStatus, error) {+ value := C.int(0)+ if request {+ value = 1+ }+ state, err := clipboard.CallResult(ctx, b.loop, func() (int, error) { return int(C.pf_notify_permission(value)), nil })+ permission := "unavailable"+ switch state {+ case 0:+ permission = "not_requested"+ case 1:+ permission = "denied"+ case 2, 3, 4:+ permission = "allowed"+ }+ return &pb.NotificationStatus{Supported: true, ActionsSupported: true, Permission: permission}, err+}+func (b *macBackend) Status(ctx context.Context) (*pb.NotificationStatus, error) {+ return b.permission(ctx, false)+}+func (b *macBackend) Request(ctx context.Context) (*pb.NotificationStatus, error) {+ return b.permission(ctx, true)+}+func (b *macBackend) Show(ctx context.Context, n Message) error {+ status, err := b.Status(ctx)+ if err != nil || status.Permission != "allowed" {+ return err+ }+ _, err = clipboard.CallResult(ctx, b.loop, func() (bool, error) {+ values := []string{n.ID, n.Title, n.Body, n.Action, n.ActionLabel}+ cs := make([]*C.char, len(values))+ for i, value := range values {+ cs[i] = C.CString(value)+ defer C.free(unsafe.Pointer(cs[i]))+ }+ if C.pf_notify_show(cs[0], cs[1], cs[2], cs[3], cs[4]) == 0 {+ return false, errors.New("notification delivery failed")+ }+ return true, nil+ })+ return err+}+func (*macBackend) Close() { macAction.Lock(); macAction.callback = nil; macAction.Unlock() }+func systemLanguage() string {+ value := C.pf_notify_language()+ if value == nil {+ return "en"+ }+ defer C.free(unsafe.Pointer(value))+ return C.GoString(value)+}diff --git a/client-core/internal/notifications/darwin.m b/client-core/internal/notifications/darwin.mnew file mode 100644index 0000000..8d29188--- /dev/null+++ b/client-core/internal/notifications/darwin.m@@ -0,0 +1,89 @@+//go:build darwin++#import <Cocoa/Cocoa.h>+#import <UserNotifications/UserNotifications.h>+#include <stdlib.h>+#include <string.h>+extern void goNotificationAction(char *, char *);++static BOOL spin(dispatch_semaphore_t sem) {+ NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:8];+ while (dispatch_semaphore_wait(sem, DISPATCH_TIME_NOW) != 0) {+ if (deadline.timeIntervalSinceNow < 0) return NO;+ @autoreleasepool {+ [NSRunLoop.currentRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];+ }+ }+ return YES;+}++@interface PFNotificationDelegate : NSObject <UNUserNotificationCenterDelegate>+@end+@implementation PFNotificationDelegate+- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {+ completionHandler(UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionList);+}+- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {+ NSString *verb = response.actionIdentifier;+ if ([verb isEqualToString:UNNotificationDefaultActionIdentifier]) verb = @"open";+ if (![verb isEqualToString:UNNotificationDismissActionIdentifier]) {+ goNotificationAction((char *)response.notification.request.identifier.UTF8String, (char *)verb.UTF8String);+ }+ completionHandler();+}+@end++static PFNotificationDelegate *delegate;+int pf_notify_init(void) {+ @autoreleasepool {+ if (NSBundle.mainBundle.bundleIdentifier.length == 0) return 0;+ delegate = [PFNotificationDelegate new];+ UNUserNotificationCenter.currentNotificationCenter.delegate = delegate;+ // Delivered notifications from an earlier daemon instance cannot retain+ // the state of a transfer. History remains the durable source of truth.+ [UNUserNotificationCenter.currentNotificationCenter removeAllDeliveredNotifications];+ return 1;+ }+}+int pf_notify_permission(int request) {+ @autoreleasepool {+ UNUserNotificationCenter *center = UNUserNotificationCenter.currentNotificationCenter;+ __block NSInteger status = -1;+ dispatch_semaphore_t sem = dispatch_semaphore_create(0);+ [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) { status = settings.authorizationStatus; dispatch_semaphore_signal(sem); }];+ if (!spin(sem)) return -1;+ if (request && status == UNAuthorizationStatusNotDetermined) {+ sem = dispatch_semaphore_create(0);+ [center requestAuthorizationWithOptions:UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError *error) { status = granted ? UNAuthorizationStatusAuthorized : UNAuthorizationStatusDenied; dispatch_semaphore_signal(sem); }];+ if (!spin(sem)) return -1;+ } else if (request && status != UNAuthorizationStatusNotDetermined) {+ [NSWorkspace.sharedWorkspace openURL:[NSURL URLWithString:@"x-apple.systempreferences:com.apple.Notifications-Settings.extension?id=com.pasteferry.daemon"]];+ }+ return (int)status;+ }+}+int pf_notify_show(const char *id, const char *title, const char *body, const char *action, const char *label) {+ @autoreleasepool {+ UNUserNotificationCenter *center = UNUserNotificationCenter.currentNotificationCenter;+ NSString *identifier = @(id), *verb = @(action);+ // Keep all categories registered: notifications for different records may+ // remain in Notification Center at the same time.+ UNNotificationAction *button = [UNNotificationAction actionWithIdentifier:verb title:@(label) options:UNNotificationActionOptionNone];+ UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:verb actions:@[button] intentIdentifiers:@[] options:UNNotificationCategoryOptionNone];+ dispatch_semaphore_t sem = dispatch_semaphore_create(0);+ [center getNotificationCategoriesWithCompletionHandler:^(NSSet<UNNotificationCategory *> *categories) {+ NSMutableSet *updated = [categories mutableCopy];+ for (UNNotificationCategory *old in categories) if ([old.identifier isEqualToString:verb]) [updated removeObject:old];+ [updated addObject:category]; [center setNotificationCategories:updated]; dispatch_semaphore_signal(sem);+ }];+ if (!spin(sem)) return 0;+ UNMutableNotificationContent *content = [UNMutableNotificationContent new];+ content.title = @(title); content.body = @(body); content.categoryIdentifier = verb;+ [center removeDeliveredNotificationsWithIdentifiers:@[identifier]];+ __block BOOL ok = NO;+ sem = dispatch_semaphore_create(0);+ [center addNotificationRequest:[UNNotificationRequest requestWithIdentifier:identifier content:content trigger:nil] withCompletionHandler:^(NSError *error) { ok = error == nil; dispatch_semaphore_signal(sem); }];+ return spin(sem) && ok;+ }+}+char *pf_notify_language(void) { @autoreleasepool { return strdup((NSLocale.preferredLanguages.firstObject ?: @"en").UTF8String); } }diff --git a/client-core/internal/notifications/linux.go b/client-core/internal/notifications/linux.gonew file mode 100644index 0000000..d0ea864--- /dev/null+++ b/client-core/internal/notifications/linux.go@@ -0,0 +1,121 @@+//go:build linux++package notifications++import (+ "context"+ "os"+ "strings"+ "sync"++ "github.com/baiyuze/pasteferry/client-core/internal/clipboard"+ pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"+ "github.com/godbus/dbus/v5"+)++const desktopNotifications = "org.freedesktop.Notifications"+const desktopNotificationPath = dbus.ObjectPath("/org/freedesktop/Notifications")++type linuxBackend struct {+ bus *dbus.Conn+ mu sync.Mutex+ ids map[string]uint32+ records map[uint32]string+ action func(string, string)+ signals chan *dbus.Signal+ done chan struct{}+}++func newBackend(_ *clipboard.MainLoop, action func(string, string)) (Backend, error) {+ bus, err := dbus.ConnectSessionBus()+ if err != nil {+ return nil, err+ }+ b := &linuxBackend{bus: bus, ids: make(map[string]uint32), records: make(map[uint32]string), action: action, signals: make(chan *dbus.Signal, 32), done: make(chan struct{})}+ if err := bus.AddMatchSignal(dbus.WithMatchObjectPath(desktopNotificationPath), dbus.WithMatchInterface(desktopNotifications)); err != nil {+ bus.Close()+ return nil, err+ }+ bus.Signal(b.signals)+ go func() {+ for {+ select {+ case <-b.done:+ return+ case signal := <-b.signals:+ if signal == nil || signal.Name != desktopNotifications+".ActionInvoked" || len(signal.Body) != 2 {+ continue+ }+ id, ok := signal.Body[0].(uint32)+ if !ok {+ continue+ }+ verb, ok := signal.Body[1].(string)+ if !ok {+ continue+ }+ b.mu.Lock()+ record := b.records[id]+ b.mu.Unlock()+ if record != "" {+ if verb == "default" {+ verb = "open"+ }+ b.action(record, verb)+ }+ }+ }+ }()+ return b, nil+}+func (b *linuxBackend) Status(ctx context.Context) (*pb.NotificationStatus, error) {+ var capabilities []string+ err := b.bus.Object(desktopNotifications, desktopNotificationPath).CallWithContext(ctx, desktopNotifications+".GetCapabilities", 0).Store(&capabilities)+ if err != nil {+ return &pb.NotificationStatus{Permission: "unavailable"}, nil+ }+ status := &pb.NotificationStatus{Supported: true, Permission: "unknown"}+ for _, capability := range capabilities {+ if capability == "actions" {+ status.ActionsSupported = true+ }+ }+ return status, nil // Linux has no portable per-app permission/DND query.+}+func (b *linuxBackend) Request(ctx context.Context) (*pb.NotificationStatus, error) {+ return b.Status(ctx)+}+func (b *linuxBackend) Show(ctx context.Context, n Message) error {+ status, err := b.Status(ctx)+ if err != nil || !status.Supported {+ return err+ }+ actions := []string{}+ if status.ActionsSupported {+ actions = []string{"default", "", n.Action, n.ActionLabel}+ }+ b.mu.Lock()+ defer b.mu.Unlock()+ var id uint32+ err = b.bus.Object(desktopNotifications, desktopNotificationPath).CallWithContext(ctx, desktopNotifications+".Notify", 0,+ "PasteFerry", b.ids[n.ID], "com.pasteferry.app", n.Title, escapeMarkup(n.Body), actions,+ map[string]dbus.Variant{"desktop-entry": dbus.MakeVariant("com.pasteferry.app"), "suppress-sound": dbus.MakeVariant(true)}, int32(-1)).Store(&id)+ if err == nil {+ delete(b.records, b.ids[n.ID])+ b.ids[n.ID] = id+ b.records[id] = n.ID+ }+ return err+}+func (b *linuxBackend) Close() { close(b.done); b.bus.RemoveSignal(b.signals); b.bus.Close() }+func systemLanguage() string {+ for _, key := range []string{"LC_ALL", "LC_MESSAGES", "LANG"} {+ if value := os.Getenv(key); value != "" {+ return strings.ReplaceAll(strings.Split(value, ".")[0], "_", "-")+ }+ }+ return "en"+}+func escapeMarkup(value string) string {+ return strings.NewReplacer("&", "&", "<", "<", ">", ">").Replace(value)+}diff --git a/client-core/internal/notifications/linux_test.go b/client-core/internal/notifications/linux_test.gonew file mode 100644index 0000000..1f7374d--- /dev/null+++ b/client-core/internal/notifications/linux_test.go@@ -0,0 +1,124 @@+//go:build linux++package notifications++import (+ "context"+ "os"+ "strings"+ "testing"+ "time"++ "github.com/godbus/dbus/v5"+)++type desktopNotice struct {+ replaces uint32+ body string+ actions []string+}+type desktopFixture struct{ calls chan desktopNotice }++func (*desktopFixture) GetCapabilities() ([]string, *dbus.Error) {+ return []string{"actions", "body-markup"}, nil+}+func (s *desktopFixture) Notify(_ string, replaces uint32, _ string, _ string, body string, actions []string, _ map[string]dbus.Variant, _ int32) (uint32, *dbus.Error) {+ s.calls <- desktopNotice{replaces, body, actions}+ return 17, nil+}++func TestLinuxDesktopNotificationActionsAndReplacement(t *testing.T) {+ if os.Getenv("DBUS_SESSION_BUS_ADDRESS") == "" {+ t.Skip("run under dbus-run-session for native D-Bus coverage")+ }+ bus, err := dbus.ConnectSessionBus()+ if err != nil {+ t.Fatal(err)+ }+ defer bus.Close()+ reply, err := bus.RequestName(desktopNotifications, dbus.NameFlagDoNotQueue)+ if err != nil || reply != dbus.RequestNameReplyPrimaryOwner {+ t.Skip("a real desktop notification service owns this session; use dbus-run-session")+ }+ fixture := &desktopFixture{calls: make(chan desktopNotice, 4)}+ if err := bus.Export(fixture, desktopNotificationPath, desktopNotifications); err != nil {+ t.Fatal(err)+ }+ actions := make(chan string, 1)+ b, err := newBackend(nil, func(id, action string) { actions <- id + ":" + action })+ if err != nil {+ t.Fatal(err)+ }+ defer b.Close()+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)+ defer cancel()+ status, err := b.Status(ctx)+ if err != nil || !status.Supported || !status.ActionsSupported {+ t.Fatal(status, err)+ }+ n := Message{ID: "clip", Title: "Receive to paste", Body: `<b>file & name</b>`, Action: "receive", ActionLabel: "Receive"}+ if err := b.Show(ctx, n); err != nil {+ t.Fatal(err)+ }+ first := <-fixture.calls+ if first.replaces != 0 || len(first.actions) != 4 || strings.Contains(first.body, "<b>") {+ t.Fatal(first)+ }+ if err := bus.Emit(desktopNotificationPath, desktopNotifications+".ActionInvoked", uint32(17), "receive"); err != nil {+ t.Fatal(err)+ }+ select {+ case got := <-actions:+ if got != "clip:receive" {+ t.Fatal(got)+ }+ case <-ctx.Done():+ t.Fatal("desktop action not delivered")+ }+ if err := b.Show(ctx, n); err != nil {+ t.Fatal(err)+ }+ if next := <-fixture.calls; next.replaces != 17 {+ t.Fatal("notification was not replaced", next)+ }+}++func TestLinuxDesktopNotificationSmoke(t *testing.T) {+ if os.Getenv("PASTEFERRY_DESKTOP_SMOKE") != "1" {+ t.Skip("requires an interactive Linux desktop")+ }+ actions := make(chan string, 4)+ b, err := newBackend(nil, func(id, action string) { actions <- id + ":" + action })+ if err != nil {+ t.Fatal(err)+ }+ defer b.Close()+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()+ status, err := b.Status(ctx)+ if err != nil || !status.Supported {+ t.Fatal(status, err)+ }+ t.Logf("native notification status: %v", status)+ if err := b.Show(ctx, Message{ID: "desktop-smoke", Title: "PasteFerry test: Receive to paste", Body: "Office PC · archive.zip · 80 MB\nReceive before pasting. History also offers Receive.", Action: "receive", ActionLabel: "Receive"}); err != nil {+ t.Fatal(err)+ }+ t.Log("waiting for the desktop Receive action")+ select {+ case action := <-actions:+ if action != "desktop-smoke:receive" {+ t.Fatal(action)+ }+ case <-ctx.Done():+ t.Fatal("native notification action was not clicked")+ }+ if err := b.Show(ctx, Message{ID: "desktop-smoke", Title: "PasteFerry test: Ready to paste", Body: "Native Receive action delivered successfully.", Action: "open", ActionLabel: "History"}); err != nil {+ t.Fatal(err)+ }+ time.Sleep(5 * time.Second)+ if linux, ok := b.(*linuxBackend); ok {+ for _, id := range linux.ids {+ _ = linux.bus.Object(desktopNotifications, desktopNotificationPath).CallWithContext(ctx, desktopNotifications+".CloseNotification", 0, id).Err+ }+ }+}diff --git a/client-core/internal/notifications/notifications.go b/client-core/internal/notifications/notifications.gonew file mode 100644index 0000000..6b9f93a--- /dev/null+++ b/client-core/internal/notifications/notifications.go@@ -0,0 +1,253 @@+// Package notifications owns desktop notifications in the background process.+// It never starts a GUI merely to deliver a notification.+package notifications++import (+ "context"+ _ "embed"+ "encoding/json"+ "fmt"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "sync"+ "time"++ "github.com/baiyuze/pasteferry/client-core/internal/clipboard"+ pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"+)++type Message struct {+ ID, Title, Body, Action, ActionLabel string+}++type Backend interface {+ Status(context.Context) (*pb.NotificationStatus, error)+ Request(context.Context) (*pb.NotificationStatus, error)+ Show(context.Context, Message) error+ Close()+}++type Options struct {+ Enabled bool+ Loop *clipboard.MainLoop+ Language func() string+ Fetch, Apply func(context.Context, string) error+ Record func(string) (*pb.ClipRecord, error)+}++type Manager struct {+ backend Backend+ opts Options+ ctx context.Context+ cancel context.CancelFunc+ mu sync.Mutex+ pending map[string]Message+ wake chan struct{}+ done chan struct{}+}++func New(ctx context.Context, opts Options) *Manager {+ ctx, cancel := context.WithCancel(ctx)+ m := &Manager{opts: opts, ctx: ctx, cancel: cancel, pending: make(map[string]Message), wake: make(chan struct{}, 1), done: make(chan struct{})}+ m.backend = unavailable{}+ if opts.Enabled {+ backend, err := newBackend(opts.Loop, func(id, action string) {+ go func() {+ if err := m.Activate(ctx, id, action); err != nil {+ slog.Warn("通知操作失败", "err", err)+ }+ }()+ })+ if err != nil {+ slog.Warn("系统通知不可用", "err", err)+ } else {+ m.backend = backend+ }+ }+ go m.run()+ return m+}++func (m *Manager) Close() { m.cancel(); <-m.done; m.backend.Close() }+func (m *Manager) Status(ctx context.Context) (*pb.NotificationStatus, error) {+ return m.backend.Status(ctx)+}+func (m *Manager) Request(ctx context.Context) (*pb.NotificationStatus, error) {+ return m.backend.Request(ctx)+}++func (m *Manager) run() {+ defer close(m.done)+ for {+ select {+ case <-m.ctx.Done():+ return+ case <-m.wake:+ m.mu.Lock()+ batch := m.pending+ m.pending = make(map[string]Message)+ m.mu.Unlock()+ for _, notice := range batch {+ ctx, cancel := context.WithTimeout(m.ctx, 10*time.Second)+ if err := m.backend.Show(ctx, notice); err != nil {+ slog.Debug("发送系统通知失败", "err", err)+ }+ cancel()+ }+ }+ }+}++func (m *Manager) show(r *pb.ClipRecord, title, body, action, actionLabel string, failure string) {+ lang := ""+ if m.opts.Language != nil {+ lang = m.opts.Language()+ }+ if lang == "" {+ lang = systemLanguage()+ }+ name := r.GetTextPreview()+ if len(r.GetItems()) > 0 {+ name = r.Items[0].Name+ if len(r.Items) > 1 {+ name += fmt.Sprintf(" (+%d)", len(r.Items)-1)+ }+ }+ if len([]rune(name)) > 120 {+ name = string([]rune(name)[:117]) + "…"+ }+ replace := strings.NewReplacer("{name}", name, "{device}", r.GetOriginDeviceName(), "{size}", humanSize(r.GetTotalSize()), "{error}", failure)+ notice := Message{ID: r.Id, Title: translate(lang, title), Body: replace.Replace(translate(lang, body)), Action: action, ActionLabel: translate(lang, actionLabel)}+ m.mu.Lock()+ m.pending[r.Id] = notice+ m.mu.Unlock()+ select {+ case m.wake <- struct{}{}:+ default:+ }+}++func (m *Manager) Pending(r *pb.ClipRecord) {+ m.show(r, "notifyPendingTitle", "notifyPendingBody", "receive", "fetch", "")+}+func (m *Manager) Started(r *pb.ClipRecord) {+ m.show(r, "notifyReceivingTitle", "notifyReceivingBody", "open", "navHistory", "")+}+func (m *Manager) Failed(r *pb.ClipRecord) {+ m.show(r, "notifyFailedTitle", "notifyFailedBody", "receive", "retry", r.Error)+}+func (m *Manager) Completed(r *pb.ClipRecord, result *pb.ClipboardWriteResult) {+ switch result.GetOutcome() {+ case pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_APPLIED:+ m.show(r, "notifyReadyTitle", "notifyReadyBody", "open", "navHistory", "")+ case pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_FAILED:+ m.show(r, "notifyClipboardFailedTitle", "notifyClipboardFailedBody", "apply", "putOnClipboard", result.Error)+ default:+ m.show(r, "notifyReceivedTitle", "notifyReceivedBody", "apply", "putOnClipboard", "")+ }+}++func (m *Manager) Activate(ctx context.Context, id, action string) error {+ if action == "open" {+ return OpenUI()+ }+ r, err := m.opts.Record(id)+ if err != nil {+ return err+ }+ if r.Outgoing {+ return fmt.Errorf("notification does not refer to a received item")+ }+ switch action {+ case "receive":+ if r.Status == pb.ClipStatus_CLIP_STATUS_READY {+ m.Completed(r, &pb.ClipboardWriteResult{Outcome: pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_PRESERVED})+ return nil+ }+ return m.opts.Fetch(ctx, id)+ case "apply":+ result := &pb.ClipboardWriteResult{ClipId: id, Outcome: pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_APPLIED}+ if err := m.opts.Apply(ctx, id); err != nil {+ result.Outcome = pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_FAILED+ result.Error = err.Error()+ }+ m.Completed(r, result)+ return nil+ default:+ return fmt.Errorf("unknown notification action")+ }+}++// OpenUI resolves the sibling installed/portable UI, never a PATH executable.+func OpenUI() error {+ exe, err := os.Executable()+ if err != nil {+ return err+ }+ var cmd *exec.Cmd+ switch runtime.GOOS {+ case "darwin":+ app := filepath.Clean(filepath.Join(filepath.Dir(exe), "../../../../.."))+ if filepath.Ext(app) != ".app" {+ return fmt.Errorf("UI app bundle not found")+ }+ cmd = exec.Command("/usr/bin/open", app)+ case "windows":+ cmd = exec.Command(filepath.Join(filepath.Dir(exe), "PasteFerry.exe"))+ default:+ cmd = exec.Command(filepath.Join(filepath.Dir(exe), "pasteferry"))+ }+ if err := cmd.Start(); err != nil {+ return err+ }+ go cmd.Wait()+ return nil+}++type unavailable struct{}++func (unavailable) Status(context.Context) (*pb.NotificationStatus, error) {+ return &pb.NotificationStatus{Permission: "unavailable"}, nil+}+func (u unavailable) Request(ctx context.Context) (*pb.NotificationStatus, error) {+ return u.Status(ctx)+}+func (unavailable) Show(context.Context, Message) error { return nil }+func (unavailable) Close() {}++//go:embed catalog.json+var catalogJSON []byte+var catalog = func() map[string]map[string]string {+ var c map[string]map[string]string+ _ = json.Unmarshal(catalogJSON, &c)+ return c+}()++func translate(lang, key string) string {+ switch {+ case strings.HasPrefix(lang, "zh-Hant-HK") || strings.HasPrefix(lang, "zh-HK"):+ lang = "zh-Hant-HK"+ case strings.HasPrefix(lang, "zh-Hant") || strings.HasPrefix(lang, "zh-TW"):+ lang = "zh-Hant-TW"+ case strings.HasPrefix(lang, "zh"):+ lang = "zh-Hans"+ case strings.HasPrefix(lang, "ja"):+ lang = "ja"+ default:+ lang = "en"+ }+ if value := catalog[lang][key]; value != "" {+ return value+ }+ return catalog["en"][key]+}+func humanSize(n int64) string {+ if n >= 1<<30 {+ return fmt.Sprintf("%.1f GB", float64(n)/(1<<30))+ }+ return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))+}diff --git a/client-core/internal/notifications/notifications_test.go b/client-core/internal/notifications/notifications_test.gonew file mode 100644index 0000000..c6f353c--- /dev/null+++ b/client-core/internal/notifications/notifications_test.go@@ -0,0 +1,111 @@+package notifications++import (+ "context"+ "encoding/xml"+ "errors"+ "strings"+ "testing"+ "time"++ pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"+)++type fakeBackend struct{ messages chan Message }++func (*fakeBackend) Status(context.Context) (*pb.NotificationStatus, error) {+ return &pb.NotificationStatus{Supported: true, ActionsSupported: true, Permission: "allowed"}, nil+}+func (b *fakeBackend) Request(ctx context.Context) (*pb.NotificationStatus, error) {+ return b.Status(ctx)+}+func (b *fakeBackend) Show(_ context.Context, n Message) error { b.messages <- n; return nil }+func (*fakeBackend) Close() {}++func nextMessage(t *testing.T, b *fakeBackend) Message {+ t.Helper()+ select {+ case n := <-b.messages:+ return n+ case <-time.After(time.Second):+ t.Fatal("notification not delivered")+ return Message{}+ }+}++func TestNotificationActionsAndClipboardOutcomes(t *testing.T) {+ r := &pb.ClipRecord{Id: "clip", OriginDeviceName: "Office PC", Items: []*pb.ClipItem{{Name: "file.zip"}}, TotalSize: 80 << 20}+ var receives, applies int+ m := New(context.Background(), Options{Language: func() string { return "en" }, Record: func(string) (*pb.ClipRecord, error) { return r, nil },+ Fetch: func(context.Context, string) error { receives++; return nil }, Apply: func(context.Context, string) error { applies++; return errors.New("clipboard busy") }})+ b := &fakeBackend{messages: make(chan Message, 16)}+ m.backend = b+ t.Cleanup(m.Close)+ m.Pending(r)+ n := nextMessage(t, b)+ if n.Action != "receive" || !strings.Contains(n.Body, "80.0 MB") || !strings.Contains(n.Body, "Office PC") {+ t.Fatal(n)+ }+ if err := m.Activate(context.Background(), r.Id, "receive"); err != nil || receives != 1 {+ t.Fatalf("receive: %d %v", receives, err)+ }+ r.Status = pb.ClipStatus_CLIP_STATUS_READY+ if err := m.Activate(context.Background(), r.Id, "receive"); err != nil {+ t.Fatal(err)+ }+ n = nextMessage(t, b)+ if n.Action != "apply" || receives != 1 || applies != 0 {+ t.Fatal("stale receive toast overwrote clipboard", n)+ }+ if err := m.Activate(context.Background(), r.Id, "apply"); err != nil {+ t.Fatal(err)+ }+ n = nextMessage(t, b)+ if n.Action != "apply" || strings.Contains(n.Title, "Ready to paste") || !strings.Contains(n.Body, "clipboard busy") {+ t.Fatal("write failure reported as paste-ready", n)+ }+ m.Completed(r, &pb.ClipboardWriteResult{Outcome: pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_APPLIED})+ n = nextMessage(t, b)+ if n.Title != "Ready to paste" {+ t.Fatal(n)+ }+ if err := m.Activate(context.Background(), r.Id, "unknown"); err == nil {+ t.Fatal("unknown action accepted")+ }+}++func TestNativeCatalogHasEveryLocaleAndPlaceholder(t *testing.T) {+ for _, lang := range []string{"en", "zh-Hans", "ja", "zh-Hant-TW", "zh-Hant-HK"} {+ for key := range catalog["en"] {+ if catalog[lang][key] == "" {+ t.Fatalf("missing %s/%s", lang, key)+ }+ }+ for _, key := range []string{"notifyPendingBody", "notifyReceivingBody", "notifyReadyBody", "notifyReceivedBody", "notifyFailedBody", "notifyClipboardFailedBody"} {+ text := strings.NewReplacer("{device}", "PC", "{name}", "file.bin", "{size}", "80 MB", "{error}", "offline").Replace(translate(lang, key))+ if strings.ContainsAny(text, "{}") || strings.Contains(text, `\n`) {+ t.Fatalf("unexpanded %s/%s: %q", lang, key, text)+ }+ }+ }+}++func TestWindowsToastEscapesFilenamesAndKeepsFullActionIdentity(t *testing.T) {+ n := Message{ID: "full-id/with spaces?&", Title: `<receive & paste>`, Body: `a"b & <file>`, Action: "receive", ActionLabel: `Receive "file"`}+ markup := toastXML(n)+ var parsed struct {+ Launch string `xml:"launch,attr"`+ Actions []struct {+ Arguments string `xml:"arguments,attr"`+ } `xml:"actions>action"`+ }+ if err := xml.Unmarshal([]byte(markup), &parsed); err != nil {+ t.Fatal(err)+ }+ if parsed.Launch != actionURI(n.ID, "open") || len(parsed.Actions) != 1 || parsed.Actions[0].Arguments != actionURI(n.ID, "receive") {+ t.Fatal(markup)+ }+ if len(notificationTag(n.ID)) > 16 || notificationTag(n.ID) == notificationTag("other") {+ t.Fatal("invalid toast identity")+ }+}diff --git a/client-core/internal/notifications/other.go b/client-core/internal/notifications/other.gonew file mode 100644index 0000000..f4ce09b--- /dev/null+++ b/client-core/internal/notifications/other.go@@ -0,0 +1,10 @@+//go:build !darwin && !windows && !linux++package notifications++import "github.com/baiyuze/pasteferry/client-core/internal/clipboard"++func newBackend(*clipboard.MainLoop, func(string, string)) (Backend, error) {+ return unavailable{}, nil+}+func systemLanguage() string { return "en" }diff --git a/client-core/internal/notifications/tag.go b/client-core/internal/notifications/tag.gonew file mode 100644index 0000000..effb149--- /dev/null+++ b/client-core/internal/notifications/tag.go@@ -0,0 +1,11 @@+package notifications++import (+ "crypto/sha256"+ "encoding/hex"+)++func notificationTag(id string) string {+ digest := sha256.Sum256([]byte(id))+ return hex.EncodeToString(digest[:8])+}diff --git a/client-core/internal/notifications/windows.go b/client-core/internal/notifications/windows.gonew file mode 100644index 0000000..da548df--- /dev/null+++ b/client-core/internal/notifications/windows.go@@ -0,0 +1,108 @@+//go:build windows++package notifications++import (+ "bytes"+ "context"+ "encoding/base64"+ "encoding/binary"+ "fmt"+ "os"+ "os/exec"+ "syscall"+ "unicode/utf16"+ "unsafe"++ "github.com/baiyuze/pasteferry/client-core/internal/clipboard"+ pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"+ "golang.org/x/sys/windows"+ "golang.org/x/sys/windows/registry"+)++const windowsAppID = "PasteFerry.Desktop"++type windowsBackend struct{ appID string }++func newBackend(_ *clipboard.MainLoop, _ func(string, string)) (Backend, error) {+ exe, err := os.Executable()+ if err != nil {+ return nil, err+ }+ // Per-user registration works for the portable distribution too. Actions+ // launch a short-lived client; it authenticates to the existing daemon.+ entries := []struct{ path, name, value string }{+ {`Software\Classes\` + protocolName, "", "PasteFerry notification action"},+ {`Software\Classes\` + protocolName, "URL Protocol", ""},+ {`Software\Classes\` + protocolName + `\shell\open\command`, "", `"` + exe + `" -notification-action "%1"`},+ {`Software\Classes\AppUserModelId\` + windowsAppID, "DisplayName", "PasteFerry"},+ }+ for _, entry := range entries {+ key, _, err := registry.CreateKey(registry.CURRENT_USER, entry.path, registry.SET_VALUE)+ if err != nil {+ return nil, err+ }+ err = key.SetStringValue(entry.name, entry.value)+ key.Close()+ if err != nil {+ return nil, err+ }+ }+ return windowsBackend{appID: windowsAppID}, nil+}++func (b windowsBackend) Status(ctx context.Context) (*pb.NotificationStatus, error) {+ output, err := powershell(ctx, toastPrelude+`$n=[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('`+b.appID+`'); try{$setting=$n.get_Setting(); if($null -eq $setting){'unknown'}else{$setting.ToString()}}catch{'unknown'}`)+ if err != nil {+ return &pb.NotificationStatus{Permission: "unavailable"}, nil+ }+ permission := "unknown"+ switch string(bytes.TrimSpace(output)) {+ case "Enabled":+ permission = "allowed"+ case "DisabledForApplication", "DisabledForUser", "DisabledByGroupPolicy", "DisabledByManifest":+ permission = "denied"+ }+ return &pb.NotificationStatus{Supported: true, ActionsSupported: true, Permission: permission}, nil+}+func (b windowsBackend) Request(ctx context.Context) (*pb.NotificationStatus, error) {+ cmd := exec.Command("explorer.exe", "ms-settings:notifications")+ _ = cmd.Start()+ if cmd.Process != nil {+ go cmd.Wait()+ }+ return b.Status(ctx)+}++const toastPrelude = `$ErrorActionPreference='Stop'; [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType=WindowsRuntime] > $null; [Windows.UI.Notifications.ToastNotification, Windows.UI.Notifications, ContentType=WindowsRuntime] > $null; [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType=WindowsRuntime] > $null; `++func (b windowsBackend) Show(ctx context.Context, n Message) error {+ encoded := base64.StdEncoding.EncodeToString([]byte(toastXML(n)))+ // All dynamic XML is data, never PowerShell source.+ script := toastPrelude + `$xml=New-Object Windows.Data.Xml.Dom.XmlDocument; $xml.LoadXml([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('` + encoded + `'))); $toast=[Windows.UI.Notifications.ToastNotification]::new($xml); $toast.Tag='` + notificationTag(n.ID) + `'; $toast.Group='receive'; [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('` + b.appID + `').Show($toast)`+ _, err := powershell(ctx, script)+ return err+}+func (windowsBackend) Close() {}+func powershell(ctx context.Context, script string) ([]byte, error) {+ var buf bytes.Buffer+ for _, value := range utf16.Encode([]rune(script)) {+ _ = binary.Write(&buf, binary.LittleEndian, value)+ }+ cmd := exec.CommandContext(ctx, "powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", base64.StdEncoding.EncodeToString(buf.Bytes()))+ cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}+ output, err := cmd.CombinedOutput()+ if err != nil {+ return nil, fmt.Errorf("Windows notification: %w", err)+ }+ return output, nil+}+func systemLanguage() string {+ var name [85]uint16+ proc := windows.NewLazySystemDLL("kernel32.dll").NewProc("GetUserDefaultLocaleName")+ count, _, _ := proc.Call(uintptr(unsafe.Pointer(&name[0])), uintptr(len(name)))+ if count == 0 {+ return "en"+ }+ return windows.UTF16ToString(name[:])+}diff --git a/client-core/internal/notifications/windows_test.go b/client-core/internal/notifications/windows_test.gonew file mode 100644index 0000000..b828ab8--- /dev/null+++ b/client-core/internal/notifications/windows_test.go@@ -0,0 +1,65 @@+//go:build windows++package notifications++import (+ "context"+ "encoding/base64"+ "golang.org/x/sys/windows/registry"+ "os"+ "strings"+ "testing"+ "time"+)++func TestWindowsNativeToastXML(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ markup := base64.StdEncoding.EncodeToString([]byte(toastXML(Message{ID: "test", Title: "Receive", Body: `<file & name>`, Action: "receive", ActionLabel: "Receive"})))+ output, err := powershell(ctx, toastPrelude+`$xml=New-Object Windows.Data.Xml.Dom.XmlDocument; $xml.LoadXml([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('`+markup+`'))); [Windows.UI.Notifications.ToastNotification]::new($xml).Content.GetXml()`)+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(string(output), "pasteferry-notify:") {+ t.Fatalf("native toast lost its activation URI: %s", output)+ }+}++func TestWindowsDesktopNotificationSmoke(t *testing.T) {+ if os.Getenv("PASTEFERRY_DESKTOP_SMOKE") != "1" {+ t.Skip("requires an interactive Windows desktop")+ }+ const appID = "PasteFerry.Validation.LargeFile"+ keyPath := `Software\Classes\AppUserModelId\` + appID+ key, _, err := registry.CreateKey(registry.CURRENT_USER, keyPath, registry.SET_VALUE)+ if err != nil {+ t.Fatal(err)+ }+ if err := key.SetStringValue("DisplayName", "PasteFerry validation"); err != nil {+ t.Fatal(err)+ }+ key.Close()+ defer registry.DeleteKey(registry.CURRENT_USER, keyPath)+ b := windowsBackend{appID: appID}+ ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)+ defer cancel()+ status, err := b.Status(ctx)+ if err != nil || !status.Supported {+ t.Fatalf("native status: %v %v", status, err)+ }+ t.Logf("native notification status: %v", status)+ for _, n := range []Message{+ {ID: "desktop-smoke", Title: "PasteFerry test: Receive to paste", Body: "Office PC · archive.zip · 80 MB\nReceive this item before pasting.", Action: "receive", ActionLabel: "Receive"},+ {ID: "desktop-smoke", Title: "PasteFerry test: Ready to paste", Body: "archive.zip\nReceived and placed on the clipboard.", Action: "open", ActionLabel: "History"},+ } {+ if err := b.Show(ctx, n); err != nil {+ t.Fatal(err)+ }+ t.Log(n.Title)+ time.Sleep(8 * time.Second)+ }+ _, err = powershell(ctx, toastPrelude+`[Windows.UI.Notifications.ToastNotificationManager]::History.Clear('`+appID+`')`)+ if err != nil {+ t.Fatal(err)+ }+}diff --git a/client-core/internal/notifications/windows_toast.go b/client-core/internal/notifications/windows_toast.gonew file mode 100644index 0000000..8154f31--- /dev/null+++ b/client-core/internal/notifications/windows_toast.go@@ -0,0 +1,20 @@+package notifications++import (+ "bytes"+ "encoding/xml"+ "net/url"+)++const protocolName = "pasteferry-notify"++func actionURI(id, action string) string {+ return protocolName + "://action?" + url.Values{"clip": {id}, "action": {action}}.Encode()+}++// Windows toast tags are at most 16 characters; the full record ID remains in+// every activation URI, so an old toast can never accept a different file.+func toastXML(n Message) string {+ escape := func(s string) string { var b bytes.Buffer; _ = xml.EscapeText(&b, []byte(s)); return b.String() }+ return `<toast activationType="protocol" launch="` + escape(actionURI(n.ID, "open")) + `"><visual><binding template="ToastGeneric"><text>` + escape(n.Title) + `</text><text>` + escape(n.Body) + `</text></binding></visual><actions><action activationType="protocol" content="` + escape(n.ActionLabel) + `" arguments="` + escape(actionURI(n.ID, n.Action)) + `"/></actions><audio silent="true"/></toast>`+}diff --git a/client-core/internal/rpc/convert.go b/client-core/internal/rpc/convert.goindex 23b1c00..56a0c47 100644--- a/client-core/internal/rpc/convert.go+++ b/client-core/internal/rpc/convert.go@@ -110,3 +110,6 @@ func permissionToProto(p clipboard.Permission) pb.ClipboardPermission {return pb.ClipboardPermission_CLIPBOARD_PERMISSION_UNSPECIFIED}}++// ClipToProto exposes the same record projection to desktop notifications.+func ClipToProto(c store.Clip) *pb.ClipRecord { return clipToProto(c) }diff --git a/client-core/internal/rpc/server.go b/client-core/internal/rpc/server.goindex 003c7a4..f53d117 100644--- a/client-core/internal/rpc/server.go+++ b/client-core/internal/rpc/server.go@@ -73,6 +73,33 @@ type Deps struct {// OpenLocalNetworkSettings 让系统放行局域网访问(macOS 打开设置面板,Windows 放行防火墙)OpenLocalNetworkSettings func() errorCacheBytesUsed func() int64+ NotificationStatus func(context.Context) (*pb.NotificationStatus, error)+ RequestNotifications func(context.Context) (*pb.NotificationStatus, error)+ ActivateNotification func(context.Context, string, string) error+}++func (s *Server) GetNotificationStatus(ctx context.Context, _ *pb.Empty) (*pb.NotificationStatus, error) {+ if s.deps.NotificationStatus == nil {+ return &pb.NotificationStatus{Permission: "unavailable"}, nil+ }+ return s.deps.NotificationStatus(ctx)+}++func (s *Server) RequestNotificationPermission(ctx context.Context, _ *pb.Empty) (*pb.NotificationStatus, error) {+ if s.deps.RequestNotifications == nil {+ return &pb.NotificationStatus{Permission: "unavailable"}, nil+ }+ return s.deps.RequestNotifications(ctx)+}++func (s *Server) ActivateNotification(ctx context.Context, req *pb.NotificationAction) (*pb.Empty, error) {+ if s.deps.ActivateNotification == nil {+ return nil, status.Error(codes.Unimplemented, "Notifications unavailable")+ }+ if err := s.deps.ActivateNotification(ctx, req.GetClipId(), req.GetAction()); err != nil {+ return nil, status.Error(codes.FailedPrecondition, err.Error())+ }+ return &pb.Empty{}, nil}type Server struct {diff --git a/client-core/internal/store/recover_test.go b/client-core/internal/store/recover_test.gonew file mode 100644index 0000000..ba3ae30--- /dev/null+++ b/client-core/internal/store/recover_test.go@@ -0,0 +1,32 @@+package store++import (+ "path/filepath"+ "testing"+)++func TestRecoverReceivesOnlyChangesInterruptedIncomingTransfers(t *testing.T) {+ s, err := Open(filepath.Join(t.TempDir(), "test.db"))+ if err != nil {+ t.Fatal(err)+ }+ defer s.Close()+ for _, clip := range []Clip{+ {ID: "interrupted", Status: StatusFetching},+ {ID: "ready", Status: StatusReady, CachePath: "downloaded"},+ {ID: "outgoing", Status: StatusFetching, Outgoing: true},+ } {+ if err := s.PutClip(clip); err != nil {+ t.Fatal(err)+ }+ }+ if err := s.RecoverReceives(); err != nil {+ t.Fatal(err)+ }+ for id, want := range map[string]Status{"interrupted": StatusFailed, "ready": StatusReady, "outgoing": StatusFetching} {+ got, err := s.GetClip(id)+ if err != nil || got.Status != want {+ t.Fatalf("%s: %v %v", id, got.Status, err)+ }+ }+}diff --git a/client-core/internal/store/store.go b/client-core/internal/store/store.goindex 1fffbfd..67cbe78 100644--- a/client-core/internal/store/store.go+++ b/client-core/internal/store/store.go@@ -399,6 +399,19 @@ func (s *Store) SetClipStatus(id string, st Status, errMsg string) error {return err}+// RecoverReceives runs once before the daemon accepts connections. There are+// no live streams after a restart; show a retry action instead of a stale spinner.+func (s *Store) RecoverReceives() error {+ _, err := s.db.Exec(`UPDATE clips SET status=?, error=? WHERE status=? AND outgoing=0`, StatusFailed, "接收已中断,请重试", StatusFetching)+ return err+}++func (s *Store) CacheReferenced(rel string) (bool, error) {+ var used bool+ err := s.db.QueryRow(`SELECT EXISTS(SELECT 1 FROM clips WHERE cache_path=?)`, rel).Scan(&used)+ return used, err+}+func (s *Store) SetClipCache(id, cachePath string, totalSize int64) error {_, err := s.db.Exec(`UPDATE clips SET cache_path=?, total_size=?, status=?, error='' WHERE id=?`,diff --git a/client-core/internal/sync/engine.go b/client-core/internal/sync/engine.goindex fc7180c..0e46ecc 100644--- a/client-core/internal/sync/engine.go+++ b/client-core/internal/sync/engine.go@@ -70,12 +70,17 @@ type Engine struct {pairedPeers func() []string// 事件回传给界面- onRecord func(*pb.ClipRecord)- onProgress func(*pb.TransferProgress)+ onRecord func(*pb.ClipRecord)+ onProgress func(*pb.TransferProgress)+ onReceive func(ReceiveEvent)+ onClipboardResult func(*pb.ClipboardWriteResult)+ receiveStartTimeout time.Duration+ offerMu sync.Mutexmu sync.Mutex// 正在接收中的流:stream_id -> 接收器incoming map[string]*receiver+ receives map[string]*receiveAttempt// 对端补发来的内容,收完后不写进剪贴板:clip_id 集合,见 PeerReadyquiet map[string]bool@@ -98,9 +103,12 @@ type Options struct {Send func(deviceID string, msg *pb.PeerMessage) errorOpenStream func(deviceID, label string) (*webrtc.DataChannel, error)// PairedPeers 返回所有已配对设备,不论在线与否:连不上的记进待补发- PairedPeers func() []string- OnRecord func(*pb.ClipRecord)- OnProgress func(*pb.TransferProgress)+ PairedPeers func() []string+ OnRecord func(*pb.ClipRecord)+ OnProgress func(*pb.TransferProgress)+ OnReceive func(ReceiveEvent)+ OnClipboardResult func(*pb.ClipboardWriteResult)+ ReceiveStartTimeout time.Duration}func New(opts Options) *Engine {@@ -109,21 +117,25 @@ func New(opts Options) *Engine {log = slog.Default()}return &Engine{- log: log,- store: opts.Store,- cache: opts.Cache,- watcher: opts.Watcher,- deviceID: opts.DeviceID,- deviceName: opts.DeviceName,- loadConfig: opts.LoadConfig,- send: opts.Send,- openStream: opts.OpenStream,- pairedPeers: opts.PairedPeers,- onRecord: opts.OnRecord,- onProgress: opts.OnProgress,- incoming: make(map[string]*receiver),- quiet: make(map[string]bool),- lastProgress: make(map[string]time.Time),+ log: log,+ store: opts.Store,+ cache: opts.Cache,+ watcher: opts.Watcher,+ deviceID: opts.DeviceID,+ deviceName: opts.DeviceName,+ loadConfig: opts.LoadConfig,+ send: opts.Send,+ openStream: opts.OpenStream,+ pairedPeers: opts.PairedPeers,+ onRecord: opts.OnRecord,+ onProgress: opts.OnProgress,+ onReceive: opts.OnReceive,+ onClipboardResult: opts.OnClipboardResult,+ receiveStartTimeout: opts.ReceiveStartTimeout,+ receives: make(map[string]*receiveAttempt),+ incoming: make(map[string]*receiver),+ quiet: make(map[string]bool),+ lastProgress: make(map[string]time.Time),}}@@ -315,6 +327,19 @@ func (e *Engine) HandlePeerMessage(ctx context.Context, from string, msg *pb.Pee}func (e *Engine) handleOffer(ctx context.Context, from string, offer *pb.ClipOffer) {+ e.offerMu.Lock()+ defer e.offerMu.Unlock()+ if existing, err := e.store.GetClip(offer.GetClipId()); err == nil {+ // Offers are replayed after reconnect. Never erase a cache or an active+ // manual request, and never turn an old record into a new notification.+ if existing.OriginDeviceID != from || existing.Outgoing {+ return+ }+ if offer.GetWillPush() && existing.Status != store.StatusReady && existing.Status != store.StatusFetching {+ e.startAutomaticReceive(existing, offer.GetBacklog())+ }+ return+ }// Older clients can still announce UU placeholders. Ignore an all-placeholder// offer before it reaches history or the local clipboard. Mixed offers are// kept intact because their subsequent archive contains real user files too.@@ -372,12 +397,14 @@ func (e *Engine) handleOffer(ctx context.Context, from string, offer *pb.ClipOffreturn}backlog := offer.GetBacklog()- if backlog && clip.Status == store.StatusFetching {- e.mu.Lock()- e.quiet[clip.ID] = true- e.mu.Unlock()+ if clip.Status == store.StatusFetching {+ e.startAutomaticReceive(clip, backlog)+ } else {+ e.emitRecord(clip)+ }+ if clip.Status == store.StatusRemoteOnly && !backlog {+ e.receiveEvent(clip, ReceivePending, nil)}- e.emitRecord(clip)e.log.Info("收到对端剪贴板内容","clip", clip.ID, "kind", clip.Kind, "status", clip.Status, "from", from, "补发", backlog)@@ -402,11 +429,7 @@ func (e *Engine) handleFetch(ctx context.Context, from, clipID string) {}func (e *Engine) handleReject(r *pb.FetchReject) {- e.log.Warn("对端拒绝了拉取请求", "clip", r.GetClipId(), "原因", r.GetReason())- _ = e.store.SetClipStatus(r.GetClipId(), store.StatusFailed, r.GetReason())- if clip, err := e.store.GetClip(r.GetClipId()); err == nil {- e.emitRecord(clip)- }+ e.failReceive(r.GetClipId(), nil, errors.New(r.GetReason()))}func (e *Engine) reject(to, clipID, reason string) {@@ -542,56 +565,60 @@ func packRaw(w io.Writer, path string) error {// receiver 承接一条进行中的数据流。type receiver struct {- clipID string- streamID string- from string- total int64- received int64- pipeW *io.PipeWriter- done chan error- start time.Time+ clipID string+ streamID string+ from string+ total int64+ received int64+ pipeW *io.PipeWriter+ done chan error+ start time.Time+ attempt *receiveAttempt+ closeStream func()+ bound bool}func (e *Engine) handleHeader(from string, h *pb.TransferHeader) {- // A rejected/ignored offer must not allocate a receiver or write files. This- // also handles a legacy sender that pushes immediately after its offer.- if _, err := e.store.GetClip(h.GetClipId()); err != nil {+ clip, err := e.store.GetClip(h.GetClipId())+ if err != nil || clip.Outgoing || clip.OriginDeviceID != from || clip.Status != store.StatusFetching {+ return+ }+ e.mu.Lock()+ a := e.receives[clip.ID]+ if a == nil || a.streamID != "" {+ e.mu.Unlock()return}- rel, abs, err := e.cache.Dir(h.GetClipId())+ a.streamID = h.GetStreamId()+ // A fresh directory per stream prevents an old failed unpacker from+ // racing a retry or leaving removed files in the retried archive.+ rel, abs, release, err := e.cache.LeaseDir(clip.ID + "-" + newID())if err != nil {- e.log.Warn("准备缓存目录失败", "err", err)+ e.mu.Unlock()+ e.failReceive(clip.ID, a, err)return}-pr, pw := io.Pipe()- r := &receiver{- clipID: h.GetClipId(),- streamID: h.GetStreamId(),- from: from,- total: h.GetTotalBytes(),- pipeW: pw,- done: make(chan error, 1),- start: time.Now(),+ r := &receiver{clipID: clip.ID, streamID: h.GetStreamId(), from: from,+ total: h.GetTotalBytes(), pipeW: pw, done: make(chan error, 1), start: time.Now(), attempt: a}+ if e.incoming == nil {+ e.incoming = make(map[string]*receiver)}-- e.mu.Lock()- e.incoming[h.GetStreamId()] = r+ e.incoming[r.streamID] = re.mu.Unlock()-- _ = e.store.SetClipStatus(h.GetClipId(), store.StatusFetching, "")-- // 边收边解包:不等整条流收完就开始落盘,大文件才不会先堆在内存里go func() {+ defer release()+ defer pr.Close()tops, err := pack.Unpack(pr, abs)if err != nil {- pr.CloseWithError(err)- e.log.Warn("解包失败", "clip", r.clipID, "err", err)- _ = e.store.SetClipStatus(r.clipID, store.StatusFailed, err.Error())+ e.failReceive(r.clipID, a, err)+ _ = e.cache.Remove(rel)r.done <- errreturn}- e.finishReceive(r, rel, tops)+ if !e.finishReceive(r, rel, tops) {+ _ = e.cache.Remove(rel)+ }r.done <- nil}()}@@ -626,76 +653,94 @@ func (e *Engine) HandlePeerStream(from, label string, stream *p2p.Stream) {}func (e *Engine) bindStream(r *receiver, stream *p2p.Stream) {- e.log.Debug("已绑定数据流", "stream", r.streamID, "clip", r.clipID,- "state", stream.ReadyState())-- idle := time.AfterFunc(streamIdleTimeout, func() {- r.pipeW.CloseWithError(errors.New("传输超时中断"))+ e.mu.Lock()+ if e.receives[r.clipID] != r.attempt || r.bound {+ e.mu.Unlock()stream.Close()- })-- // Stream 的队列保证顺序与完整性,这里只管按序搬进管道。- // 队列在对端关闭数据流时关闭,循环随之退出并收尾。+ return+ }+ r.bound = true+ r.closeStream = func() { stream.Close() }+ r.attempt.timer.Reset(streamIdleTimeout)+ e.mu.Unlock()go func() {- defer idle.Stop()defer r.pipeW.Close()-+ var received int64for chunk := range stream.Chunks() {- idle.Reset(streamIdleTimeout)if _, err := r.pipeW.Write(chunk); err != nil {stream.Close()return}- r.received += int64(len(chunk))- e.emitProgress(r.clipID, r.received, r.total, r.start)+ received += int64(len(chunk))+ e.mu.Lock()+ if e.receives[r.clipID] != r.attempt {+ e.mu.Unlock()+ stream.Close()+ return+ }+ r.received = received+ r.attempt.timer.Reset(streamIdleTimeout)+ e.mu.Unlock()+ e.emitProgress(r.clipID, received, r.total, r.start)}}()}-func (e *Engine) finishReceive(r *receiver, cacheRel string, tops []string) {+func (e *Engine) finishReceive(r *receiver, cacheRel string, tops []string) bool {e.mu.Lock()- delete(e.incoming, r.streamID)+ a := r.attempt+ if a == nil {+ a = e.receives[r.clipID]+ } // also used by the preview integration test+ if a == nil || e.receives[r.clipID] != a {+ e.mu.Unlock()+ return false+ }+ if err := e.store.SetClipCache(r.clipID, cacheRel, max64(r.total, r.received)); err != nil {+ e.mu.Unlock()+ e.failReceive(r.clipID, a, err)+ return false+ }quiet := e.quiet[r.clipID]- delete(e.quiet, r.clipID)+ e.retireReceiveLocked(r.clipID, a)e.mu.Unlock()e.forgetProgress(r.clipID)-- var size int64- for _, p := range tops {- if info, err := os.Stat(p); err == nil {- size += info.Size()- }- }- if err := e.store.SetClipCache(r.clipID, cacheRel, max64(size, r.received)); err != nil {- e.log.Warn("更新缓存记录失败", "err", err)- }-clip, err := e.store.GetClip(r.clipID)if err != nil {- return+ return false}e.emitRecord(clip)- e.log.Info("内容接收完成",- "clip", r.clipID, "from", r.from, "收到字节", r.received,- "条目", len(tops), "耗时", time.Since(r.start).Round(time.Millisecond))-+ result := &pb.ClipboardWriteResult{ClipId: clip.ID, Outcome: pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_PRESERVED}if e.loadConfig().AutoApplyToClipboard && !quiet {ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)defer cancel()- if err := e.applyToClipboard(ctx, clip); err != nil {- e.log.Warn("写入剪贴板失败", "err", err)+ if a.manual {+ if a.revision != nil {+ result = e.writeClipboard(ctx, clip, a.revision)+ }+ } else {+ result = e.writeClipboard(ctx, clip, nil)+ }+ }+ if !a.preview {+ e.clipboardResult(result)+ if a.manual {+ e.receiveEvent(clip, ReceiveCompleted, result)}}+ return true}func (e *Engine) handleDone(d *pb.TransferDone) {if d.GetOk() {return}- e.log.Warn("对端报告传输失败", "clip", d.GetClipId(), "err", d.GetError())- _ = e.store.SetClipStatus(d.GetClipId(), store.StatusFailed, d.GetError())- if clip, err := e.store.GetClip(d.GetClipId()); err == nil {- e.emitRecord(clip)+ e.mu.Lock()+ a := e.receives[d.GetClipId()]+ matches := a != nil && a.streamID == d.GetStreamId()+ e.mu.Unlock()+ if matches {+ e.failReceive(d.GetClipId(), a, errors.New(d.GetError()))}}@@ -711,41 +756,29 @@ func (e *Engine) FetchForPreview(ctx context.Context, clipID string) error {return e.fetch(ctx, clipID, true)}-func (e *Engine) fetch(ctx context.Context, clipID string, preserveClipboard bool) error {+// ApplyToClipboard 把某条已就绪的记录写入本机剪贴板。+func (e *Engine) ApplyToClipboard(ctx context.Context, clipID string) error {clip, err := e.store.GetClip(clipID)if err != nil {return err}- if clip.Outgoing {- return errors.New("这是本机复制的内容,无需拉取")- }- if preserveClipboard {- e.mu.Lock()- e.quiet[clipID] = true- e.mu.Unlock()- }- if err := e.send(clip.OriginDeviceID, &pb.PeerMessage{- Payload: &pb.PeerMessage_Fetch{Fetch: &pb.PeerFetch{ClipId: clipID}},- }); err != nil {- return fmt.Errorf("源设备当前不可达: %w", err)- }- _ = e.store.SetClipStatus(clipID, store.StatusFetching, "")- if c, err := e.store.GetClip(clipID); err == nil {- e.emitRecord(c)+ result := e.writeClipboard(ctx, clip, nil)+ e.clipboardResult(result)+ if result.Outcome == pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_FAILED {+ return errors.New(result.Error)}return nil}-// ApplyToClipboard 把某条已就绪的记录写入本机剪贴板。-func (e *Engine) ApplyToClipboard(ctx context.Context, clipID string) error {- clip, err := e.store.GetClip(clipID)- if err != nil {- return err+func (e *Engine) applyToClipboard(ctx context.Context, clip store.Clip) error {+ result := e.writeClipboard(ctx, clip, nil)+ if result.Outcome == pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_FAILED {+ return errors.New(result.Error)}- return e.applyToClipboard(ctx, clip)+ return nil}-func (e *Engine) applyToClipboard(ctx context.Context, clip store.Clip) error {+func (e *Engine) clipboardContent(clip store.Clip) (clipboard.Content, error) {var content clipboard.Contentswitch clip.Kind {@@ -758,7 +791,7 @@ func (e *Engine) applyToClipboard(ctx context.Context, clip store.Clip) error {case store.KindImage, store.KindFile:paths, err := e.localPaths(clip)if err != nil {- return err+ return content, err}if clip.Kind == store.KindImage && len(paths) == 1 {data, err := os.ReadFile(paths[0])@@ -769,10 +802,10 @@ func (e *Engine) applyToClipboard(ctx context.Context, clip store.Clip) error {}content = clipboard.Content{Kind: clipboard.KindFile, Files: paths}default:- return fmt.Errorf("不支持写入剪贴板的类型: %v", clip.Kind)+ return content, fmt.Errorf("不支持写入剪贴板的类型: %v", clip.Kind)}- return e.watcher.Write(ctx, content)+ return content, nil}// ImagePreview 解析一条记录里第 index 张图片在本机的位置,不拉取文件、不写剪贴板。@@ -844,16 +877,19 @@ func (e *Engine) localPaths(clip store.Clip) ([]string, error) {// ─────────────────────── 辅助 ───────────────────────func (e *Engine) emitRecord(clip store.Clip) {- if e.onRecord == nil {- return+ if e.onRecord != nil {+ e.onRecord(recordProto(clip))}+}++func recordProto(clip store.Clip) *pb.ClipRecord {items := make([]*pb.ClipItem, 0, len(clip.Items))for _, it := range clip.Items {items = append(items, &pb.ClipItem{Name: it.Name, Size: it.Size, IsDir: it.IsDir, ContentType: it.ContentType,})}- e.onRecord(&pb.ClipRecord{+ return &pb.ClipRecord{Id: clip.ID,Kind: pb.ClipKind(clip.Kind),Status: pb.ClipStatus(clip.Status),@@ -867,7 +903,7 @@ func (e *Engine) emitRecord(clip store.Clip) {ExpiresAtUnix: clip.ExpiresAt.Unix(),Error: clip.Error,ImageCount: imagepreview.ImageCount(clip),- })+ }}// progressInterval 是同一次传输两次进度上报之间的最小间隔。diff --git a/client-core/internal/sync/receive.go b/client-core/internal/sync/receive.gonew file mode 100644index 0000000..c229610--- /dev/null+++ b/client-core/internal/sync/receive.go@@ -0,0 +1,206 @@+package sync++import (+ "context"+ "errors"+ "fmt"+ "time"++ "github.com/baiyuze/pasteferry/client-core/internal/store"+ pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"+)++type ReceiveStage int++const (+ ReceivePending ReceiveStage = iota+ ReceiveStarted+ ReceiveCompleted+ ReceiveFailed+)++// ReceiveEvent is live intent, unlike a replayable history record. Preview+// downloads and reconnect backlogs must not produce actionable notifications.+type ReceiveEvent struct {+ Stage ReceiveStage+ Record *pb.ClipRecord+ Clipboard *pb.ClipboardWriteResult+}++type receiveAttempt struct {+ manual, preview bool+ revision *int64+ streamID string+ timer *time.Timer+}++func (e *Engine) receiveEvent(clip store.Clip, stage ReceiveStage, result *pb.ClipboardWriteResult) {+ if e.onReceive != nil {+ e.onReceive(ReceiveEvent{stage, recordProto(clip), result})+ }+}++// All receiveAttempt fields and timers are protected by e.mu.+func (e *Engine) newReceiveLocked(id string, manual, preview bool) *receiveAttempt {+ if e.receives == nil {+ e.receives = make(map[string]*receiveAttempt)+ }+ a := &receiveAttempt{manual: manual, preview: preview}+ e.receives[id] = a+ d := e.receiveStartTimeout+ if d <= 0 {+ d = 30 * time.Second+ }+ a.timer = time.AfterFunc(d, func() { e.failReceive(id, a, errors.New("接收超时,请确认源设备在线后重试")) })+ return a+}++func (e *Engine) startAutomaticReceive(clip store.Clip, quiet bool) {+ e.mu.Lock()+ if e.receives[clip.ID] == nil {+ e.newReceiveLocked(clip.ID, false, false)+ }+ if quiet {+ if e.quiet == nil {+ e.quiet = make(map[string]bool)+ }+ e.quiet[clip.ID] = true+ }+ _ = e.store.SetClipStatus(clip.ID, store.StatusFetching, "")+ clip.Status = store.StatusFetching+ e.mu.Unlock()+ e.emitRecord(clip)+}++func (e *Engine) fetch(ctx context.Context, clipID string, preview bool) error {+ e.mu.Lock()+ clip, err := e.store.GetClip(clipID)+ if err != nil {+ e.mu.Unlock()+ return err+ }+ if clip.Outgoing {+ e.mu.Unlock()+ return errors.New("这是本机复制的内容,无需接收")+ }+ if clip.Status == store.StatusReady || e.receives[clipID] != nil {+ e.mu.Unlock()+ return nil+ }+ // Also recovers FETCHING records left behind by a previous daemon process.+ a := e.newReceiveLocked(clipID, true, preview)+ if preview {+ if e.quiet == nil {+ e.quiet = make(map[string]bool)+ }+ e.quiet[clipID] = true+ }+ e.mu.Unlock()+ if !preview && e.watcher != nil {+ if revision, readErr := e.watcher.Revision(ctx); readErr == nil {+ e.mu.Lock()+ a.revision = &revision+ e.mu.Unlock()+ }+ }+ e.mu.Lock()+ if e.receives[clipID] != a {+ e.mu.Unlock()+ return errors.New("接收请求已超时,请重试")+ }+ err = e.store.SetClipStatus(clipID, store.StatusFetching, "")+ e.mu.Unlock()+ if err != nil {+ e.failReceive(clipID, a, err)+ return err+ }+ clip.Status, clip.Error = store.StatusFetching, ""+ e.emitRecord(clip)+ if !preview {+ e.receiveEvent(clip, ReceiveStarted, nil)+ }+ if err := e.send(clip.OriginDeviceID, &pb.PeerMessage{+ Payload: &pb.PeerMessage_Fetch{Fetch: &pb.PeerFetch{ClipId: clipID}},+ }); err != nil {+ wrapped := fmt.Errorf("源设备当前不可达: %w", err)+ e.failReceive(clipID, a, wrapped)+ return wrapped+ }+ return nil+}++func (e *Engine) retireReceiveLocked(id string, a *receiveAttempt) {+ a.timer.Stop()+ delete(e.receives, id)+ delete(e.incoming, a.streamID)+ delete(e.quiet, id)+}++func (e *Engine) failReceive(id string, expected *receiveAttempt, failure error) {+ e.mu.Lock()+ a := e.receives[id]+ if a == nil || (expected != nil && expected != a) {+ e.mu.Unlock()+ return+ }+ r := e.incoming[a.streamID]+ _ = e.store.SetClipStatus(id, store.StatusFailed, failure.Error())+ e.retireReceiveLocked(id, a)+ e.mu.Unlock()+ if r != nil {+ r.pipeW.CloseWithError(failure)+ if r.closeStream != nil {+ r.closeStream()+ }+ }+ e.forgetProgress(id)+ if clip, err := e.store.GetClip(id); err == nil {+ e.emitRecord(clip)+ if a.manual && !a.preview {+ e.receiveEvent(clip, ReceiveFailed, nil)+ }+ }+}++func (e *Engine) writeClipboard(ctx context.Context, clip store.Clip, revision *int64) *pb.ClipboardWriteResult {+ result := &pb.ClipboardWriteResult{ClipId: clip.ID, Outcome: pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_FAILED}+ content, err := e.clipboardContent(clip)+ if err == nil {+ if e.watcher == nil {+ err = errors.New("剪贴板服务不可用")+ } else if revision != nil {+ var applied bool+ applied, err = e.watcher.WriteIfUnchanged(ctx, content, *revision)+ if err == nil && !applied {+ result.Outcome = pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_PRESERVED+ return result+ }+ } else {+ err = e.watcher.Write(ctx, content)+ }+ }+ if err != nil {+ result.Error = err.Error()+ } else {+ result.Outcome = pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_APPLIED+ }+ return result+}++func (e *Engine) clipboardResult(result *pb.ClipboardWriteResult) {+ if e.onClipboardResult != nil {+ e.onClipboardResult(result)+ }+}++// Close cancels watchdogs before the store is closed on shutdown.+func (e *Engine) Close() {+ e.mu.Lock()+ defer e.mu.Unlock()+ for id, a := range e.receives {+ if r := e.incoming[a.streamID]; r != nil {+ r.pipeW.CloseWithError(context.Canceled)+ }+ e.retireReceiveLocked(id, a)+ }+}diff --git a/client-core/internal/sync/receive_test.go b/client-core/internal/sync/receive_test.gonew file mode 100644index 0000000..3eb1615--- /dev/null+++ b/client-core/internal/sync/receive_test.go@@ -0,0 +1,284 @@+package sync++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "runtime"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/baiyuze/pasteferry/client-core/internal/cache"+ "github.com/baiyuze/pasteferry/client-core/internal/clipboard"+ "github.com/baiyuze/pasteferry/client-core/internal/config"+ "github.com/baiyuze/pasteferry/client-core/internal/pack"+ "github.com/baiyuze/pasteferry/client-core/internal/store"+ pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"+)++type receiveClipboard struct {+ mu sync.Mutex+ revision int64+ writes int+ failure error+}++func (c *receiveClipboard) Peek() (clipboard.Snapshot, error) {+ c.mu.Lock()+ defer c.mu.Unlock()+ return clipboard.Snapshot{ChangeCount: c.revision}, nil+}+func (*receiveClipboard) Read() (clipboard.Content, error) { return clipboard.Content{}, nil }+func (c *receiveClipboard) Write(clipboard.Content) error {+ c.mu.Lock()+ defer c.mu.Unlock()+ if c.failure != nil {+ return c.failure+ }+ c.writes+++ c.revision+++ return nil+}+func (*receiveClipboard) Permission() clipboard.Permission { return clipboard.PermissionNotApplicable }+func (*receiveClipboard) OpenPermissionSettings() error { return nil }++func receiveFixture(t *testing.T, cb *receiveClipboard, cfg config.Config, timeout time.Duration) (*Engine, chan ReceiveEvent) {+ t.Helper()+ db, err := store.Open(filepath.Join(t.TempDir(), "test.db"))+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { db.Close() })+ blobs, err := cache.New(t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ loop := clipboard.NewMainLoop()+ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan struct{})+ go func() { runtime.LockOSThread(); defer runtime.UnlockOSThread(); defer close(done); loop.Run(ctx) }()+ t.Cleanup(func() { cancel(); <-done })+ events := make(chan ReceiveEvent, 32)+ e := New(Options{Store: db, Cache: blobs, Watcher: clipboard.NewWatcher(clipboard.WatcherOptions{Clipboard: cb, MainLoop: loop}),+ LoadConfig: func() config.Config { return cfg }, Send: func(string, *pb.PeerMessage) error { return nil },+ ReceiveStartTimeout: timeout, OnReceive: func(event ReceiveEvent) { events <- event },+ })+ t.Cleanup(e.Close)+ return e, events+}++func offerLarge(e *Engine, id string, backlog bool) {+ e.handleOffer(context.Background(), "peer", &pb.ClipOffer{ClipId: id, Kind: pb.ClipKind_CLIP_KIND_FILE,+ TotalSize: (50 << 20) + 1, CreatedAtUnix: time.Now().Unix(), Items: []*pb.ClipItem{{Name: "large.bin"}}, Backlog: backlog})+}++func waitReceive(t *testing.T, events <-chan ReceiveEvent, stage ReceiveStage) ReceiveEvent {+ t.Helper()+ timer := time.NewTimer(3 * time.Second)+ defer timer.Stop()+ for {+ select {+ case event := <-events:+ if event.Stage == stage {+ return event+ }+ case <-timer.C:+ t.Fatalf("no stage %v", stage)+ return ReceiveEvent{}+ }+ }+}++func TestReceiveNotifiesOnlyNewLiveOffers(t *testing.T) {+ e, events := receiveFixture(t, &receiveClipboard{}, config.Default(), 0)+ offerLarge(e, "live", false)+ offerLarge(e, "live", false)+ offerLarge(e, "late", true)+ offerLarge(e, "late", false)+ if event := waitReceive(t, events, ReceivePending); event.Record.Id != "live" {+ t.Fatal(event)+ }+ select {+ case event := <-events:+ t.Fatalf("duplicate/backlog notification: %v", event)+ default:+ }+ // A sender replays an offer after it has been downloaded. Keep its cache.+ if err := e.store.SetClipCache("live", "cached", 123); err != nil {+ t.Fatal(err)+ }+ offerLarge(e, "live", false)+ clip, _ := e.store.GetClip("live")+ if clip.CachePath != "cached" || clip.Status != store.StatusReady {+ t.Fatal("replay erased ready record")+ }+}++func TestReceiveDeduplicatesAndTimesOutBeforeHeader(t *testing.T) {+ e, events := receiveFixture(t, &receiveClipboard{}, config.Default(), time.Second)+ offerLarge(e, "clip", false)+ var sends atomic.Int32+ e.send = func(string, *pb.PeerMessage) error { sends.Add(1); return nil }+ var group sync.WaitGroup+ for range 20 {+ group.Go(func() {+ if err := e.Fetch(context.Background(), "clip"); err != nil {+ t.Error(err)+ }+ })+ }+ group.Wait()+ if sends.Load() != 1 {+ t.Fatalf("sent %d fetches", sends.Load())+ }+ waitReceive(t, events, ReceiveFailed)+ clip, _ := e.store.GetClip("clip")+ if clip.Status != store.StatusFailed {+ t.Fatal(clip.Status)+ }+ if err := e.Fetch(context.Background(), "clip"); err != nil {+ t.Fatal(err)+ }+ if sends.Load() != 2 {+ t.Fatal("retry did not send")+ }+}++func TestImmediateRejectionAndOfflineFailure(t *testing.T) {+ for _, rejected := range []bool{false, true} {+ t.Run(map[bool]string{false: "offline", true: "rejected"}[rejected], func(t *testing.T) {+ e, events := receiveFixture(t, &receiveClipboard{}, config.Default(), 0)+ offerLarge(e, "clip", false)+ e.send = func(string, *pb.PeerMessage) error {+ if rejected {+ e.handleReject(&pb.FetchReject{ClipId: "clip", Reason: "source missing"})+ return nil+ }+ return errors.New("offline")+ }+ _ = e.Fetch(context.Background(), "clip")+ waitReceive(t, events, ReceiveFailed)+ clip, _ := e.store.GetClip("clip")+ if clip.Status != store.StatusFailed {+ t.Fatal("fast failure overwritten by fetching")+ }+ })+ }+}++func TestReceiveCompletionProtectsClipboardAndRetainsDownload(t *testing.T) {+ for _, scenario := range []string{"unchanged", "new-copy", "write-error", "auto-off", "preview"} {+ t.Run(scenario, func(t *testing.T) {+ cb := &receiveClipboard{revision: 10}+ cfg := config.Default()+ if scenario == "auto-off" {+ cfg.AutoApplyToClipboard = false+ }+ e, events := receiveFixture(t, cb, cfg, 0)+ offerLarge(e, "clip", false)+ if err := e.fetch(context.Background(), "clip", scenario == "preview"); err != nil {+ t.Fatal(err)+ }+ cb.mu.Lock()+ if scenario == "new-copy" {+ cb.revision+++ }+ if scenario == "write-error" {+ cb.failure = errors.New("locked")+ }+ cb.mu.Unlock()+ rel, dir, err := e.cache.Dir("clip")+ if err != nil {+ t.Fatal(err)+ }+ path := filepath.Join(dir, "large.bin")+ if err := os.WriteFile(path, []byte("downloaded"), 0600); err != nil {+ t.Fatal(err)+ }+ if !e.finishReceive(&receiver{clipID: "clip", total: 10}, rel, []string{path}) {+ t.Fatal("receive rejected")+ }+ clip, _ := e.store.GetClip("clip")+ if clip.Status != store.StatusReady || clip.CachePath == "" {+ t.Fatal("download was not retained")+ }+ cb.mu.Lock()+ writes := cb.writes+ cb.mu.Unlock()+ if scenario == "preview" {+ if writes != 0 {+ t.Fatal("preview wrote clipboard")+ }+ return+ }+ event := waitReceive(t, events, ReceiveCompleted)+ want := pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_PRESERVED+ if scenario == "unchanged" {+ want = pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_APPLIED+ if writes != 1 {+ t.Fatal(writes)+ }+ } else if writes != 0 {+ t.Fatal("overwrote clipboard")+ }+ if scenario == "write-error" {+ want = pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_FAILED+ }+ if event.Clipboard.Outcome != want {+ t.Fatalf("outcome %v, want %v", event.Clipboard.Outcome, want)+ }+ })+ }+}++func TestUnpackFailurePublishesTerminalStateAndRetryUsesFreshCache(t *testing.T) {+ e, events := receiveFixture(t, &receiveClipboard{}, config.Default(), 0)+ offerLarge(e, "clip", false)+ if err := e.FetchForPreview(context.Background(), "clip"); err != nil {+ t.Fatal(err)+ }+ e.handleHeader("peer", &pb.TransferHeader{ClipId: "clip", StreamId: "broken"})+ e.mu.Lock()+ r := e.incoming["broken"]+ e.mu.Unlock()+ _, _ = r.pipeW.Write([]byte("invalid zstd stream"))+ r.pipeW.Close()+ select {+ case <-r.done:+ case <-time.After(time.Second):+ t.Fatal("unpacker hung")+ }+ clip, _ := e.store.GetClip("clip")+ if clip.Status != store.StatusFailed {+ t.Fatal(clip.Status)+ }+ e.mu.Lock()+ quiet := e.quiet["clip"]+ e.mu.Unlock()+ if quiet {+ t.Fatal("preview state leaked")+ }+ if err := e.Fetch(context.Background(), "clip"); err != nil {+ t.Fatal(err)+ }+ e.handleHeader("peer", &pb.TransferHeader{ClipId: "clip", StreamId: "retry"})+ e.mu.Lock()+ r = e.incoming["retry"]+ e.mu.Unlock()+ path := filepath.Join(t.TempDir(), "large.bin")+ if err := os.WriteFile(path, []byte("whole file"), 0600); err != nil {+ t.Fatal(err)+ }+ if err := pack.Pack(r.pipeW, []string{path}); err != nil {+ t.Fatal(err)+ }+ r.pipeW.Close()+ waitReceive(t, events, ReceiveCompleted)+ entries, err := e.cache.Entries(func() string { c, _ := e.store.GetClip("clip"); return c.CachePath }())+ if err != nil || len(entries) != 1 {+ t.Fatalf("cache: %v %v", entries, err)+ }+}diff --git a/proto/gen/pasteferry/v1/daemon.pb.go b/proto/gen/pasteferry/v1/daemon.pb.goindex d971bc6..c33370d 100644--- a/proto/gen/pasteferry/v1/daemon.pb.go+++ b/proto/gen/pasteferry/v1/daemon.pb.go@@ -251,6 +251,58 @@ func (ClipboardPermission) EnumDescriptor() ([]byte, []int) {return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{3}}+type ClipboardWriteOutcome int32++const (+ ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_UNSPECIFIED ClipboardWriteOutcome = 0+ ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_APPLIED ClipboardWriteOutcome = 1+ ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_PRESERVED ClipboardWriteOutcome = 2+ ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_FAILED ClipboardWriteOutcome = 3+)++// Enum value maps for ClipboardWriteOutcome.+var (+ ClipboardWriteOutcome_name = map[int32]string{+ 0: "CLIPBOARD_WRITE_OUTCOME_UNSPECIFIED",+ 1: "CLIPBOARD_WRITE_OUTCOME_APPLIED",+ 2: "CLIPBOARD_WRITE_OUTCOME_PRESERVED",+ 3: "CLIPBOARD_WRITE_OUTCOME_FAILED",+ }+ ClipboardWriteOutcome_value = map[string]int32{+ "CLIPBOARD_WRITE_OUTCOME_UNSPECIFIED": 0,+ "CLIPBOARD_WRITE_OUTCOME_APPLIED": 1,+ "CLIPBOARD_WRITE_OUTCOME_PRESERVED": 2,+ "CLIPBOARD_WRITE_OUTCOME_FAILED": 3,+ }+)++func (x ClipboardWriteOutcome) Enum() *ClipboardWriteOutcome {+ p := new(ClipboardWriteOutcome)+ *p = x+ return p+}++func (x ClipboardWriteOutcome) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (ClipboardWriteOutcome) Descriptor() protoreflect.EnumDescriptor {+ return file_pasteferry_v1_daemon_proto_enumTypes[4].Descriptor()+}++func (ClipboardWriteOutcome) Type() protoreflect.EnumType {+ return &file_pasteferry_v1_daemon_proto_enumTypes[4]+}++func (x ClipboardWriteOutcome) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use ClipboardWriteOutcome.Descriptor instead.+func (ClipboardWriteOutcome) EnumDescriptor() ([]byte, []int) {+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{4}+}+type Empty struct {state protoimpl.MessageState `protogen:"open.v1"`unknownFields protoimpl.UnknownFields@@ -724,6 +776,7 @@ type Event struct {// *Event_DeviceChanged// *Event_PermissionChanged// *Event_StatusChanged+ // *Event_ClipboardWrittenPayload isEvent_Payload `protobuf_oneof:"payload"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache@@ -829,6 +882,15 @@ func (x *Event) GetStatusChanged() *Status {return nil}+func (x *Event) GetClipboardWritten() *ClipboardWriteResult {+ if x != nil {+ if x, ok := x.Payload.(*Event_ClipboardWritten); ok {+ return x.ClipboardWritten+ }+ }+ return nil+}+type isEvent_Payload interface {isEvent_Payload()}@@ -861,6 +923,10 @@ type Event_StatusChanged struct {StatusChanged *Status `protobuf:"bytes,7,opt,name=status_changed,json=statusChanged,proto3,oneof"`}+type Event_ClipboardWritten struct {+ ClipboardWritten *ClipboardWriteResult `protobuf:"bytes,8,opt,name=clipboard_written,json=clipboardWritten,proto3,oneof"`+}+func (*Event_ClipAdded) isEvent_Payload() {}func (*Event_ClipUpdated) isEvent_Payload() {}@@ -875,6 +941,182 @@ func (*Event_PermissionChanged) isEvent_Payload() {}func (*Event_StatusChanged) isEvent_Payload() {}+func (*Event_ClipboardWritten) isEvent_Payload() {}++type NotificationStatus struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Supported bool `protobuf:"varint,1,opt,name=supported,proto3" json:"supported,omitempty"`+ ActionsSupported bool `protobuf:"varint,2,opt,name=actions_supported,json=actionsSupported,proto3" json:"actions_supported,omitempty"`+ // unknown, not_requested, allowed, denied, unavailable+ Permission string `protobuf:"bytes,3,opt,name=permission,proto3" json:"permission,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *NotificationStatus) Reset() {+ *x = NotificationStatus{}+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[7]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *NotificationStatus) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*NotificationStatus) ProtoMessage() {}++func (x *NotificationStatus) ProtoReflect() protoreflect.Message {+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[7]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use NotificationStatus.ProtoReflect.Descriptor instead.+func (*NotificationStatus) Descriptor() ([]byte, []int) {+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{7}+}++func (x *NotificationStatus) GetSupported() bool {+ if x != nil {+ return x.Supported+ }+ return false+}++func (x *NotificationStatus) GetActionsSupported() bool {+ if x != nil {+ return x.ActionsSupported+ }+ return false+}++func (x *NotificationStatus) GetPermission() string {+ if x != nil {+ return x.Permission+ }+ return ""+}++type NotificationAction struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ ClipId string `protobuf:"bytes,1,opt,name=clip_id,json=clipId,proto3" json:"clip_id,omitempty"`+ Action string `protobuf:"bytes,2,opt,name=action,proto3" json:"action,omitempty"` // receive, apply, open+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *NotificationAction) Reset() {+ *x = NotificationAction{}+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[8]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *NotificationAction) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*NotificationAction) ProtoMessage() {}++func (x *NotificationAction) ProtoReflect() protoreflect.Message {+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[8]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use NotificationAction.ProtoReflect.Descriptor instead.+func (*NotificationAction) Descriptor() ([]byte, []int) {+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{8}+}++func (x *NotificationAction) GetClipId() string {+ if x != nil {+ return x.ClipId+ }+ return ""+}++func (x *NotificationAction) GetAction() string {+ if x != nil {+ return x.Action+ }+ return ""+}++// READY still means downloaded, not necessarily the current system clipboard.+type ClipboardWriteResult struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ ClipId string `protobuf:"bytes,1,opt,name=clip_id,json=clipId,proto3" json:"clip_id,omitempty"`+ Outcome ClipboardWriteOutcome `protobuf:"varint,2,opt,name=outcome,proto3,enum=pasteferry.v1.ClipboardWriteOutcome" json:"outcome,omitempty"`+ Error string `protobuf:"bytes,3,opt,name=error,proto3" json:"error,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ClipboardWriteResult) Reset() {+ *x = ClipboardWriteResult{}+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[9]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ClipboardWriteResult) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ClipboardWriteResult) ProtoMessage() {}++func (x *ClipboardWriteResult) ProtoReflect() protoreflect.Message {+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[9]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ClipboardWriteResult.ProtoReflect.Descriptor instead.+func (*ClipboardWriteResult) Descriptor() ([]byte, []int) {+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{9}+}++func (x *ClipboardWriteResult) GetClipId() string {+ if x != nil {+ return x.ClipId+ }+ return ""+}++func (x *ClipboardWriteResult) GetOutcome() ClipboardWriteOutcome {+ if x != nil {+ return x.Outcome+ }+ return ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_UNSPECIFIED+}++func (x *ClipboardWriteResult) GetError() string {+ if x != nil {+ return x.Error+ }+ return ""+}+type ListHistoryRequest struct {state protoimpl.MessageState `protogen:"open.v1"`Limit int32 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"`@@ -889,7 +1131,7 @@ type ListHistoryRequest struct {func (x *ListHistoryRequest) Reset() {*x = ListHistoryRequest{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[7]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[10]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -901,7 +1143,7 @@ func (x *ListHistoryRequest) String() string {func (*ListHistoryRequest) ProtoMessage() {}func (x *ListHistoryRequest) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[7]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[10]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -914,7 +1156,7 @@ func (x *ListHistoryRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use ListHistoryRequest.ProtoReflect.Descriptor instead.func (*ListHistoryRequest) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{7}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{10}}func (x *ListHistoryRequest) GetLimit() int32 {@@ -956,7 +1198,7 @@ type ListHistoryResponse struct {func (x *ListHistoryResponse) Reset() {*x = ListHistoryResponse{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[8]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[11]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -968,7 +1210,7 @@ func (x *ListHistoryResponse) String() string {func (*ListHistoryResponse) ProtoMessage() {}func (x *ListHistoryResponse) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[8]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[11]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -981,7 +1223,7 @@ func (x *ListHistoryResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use ListHistoryResponse.ProtoReflect.Descriptor instead.func (*ListHistoryResponse) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{8}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{11}}func (x *ListHistoryResponse) GetRecords() []*ClipRecord {@@ -1008,7 +1250,7 @@ type DeleteHistoryRequest struct {func (x *DeleteHistoryRequest) Reset() {*x = DeleteHistoryRequest{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[9]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[12]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1020,7 +1262,7 @@ func (x *DeleteHistoryRequest) String() string {func (*DeleteHistoryRequest) ProtoMessage() {}func (x *DeleteHistoryRequest) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[9]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[12]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1033,7 +1275,7 @@ func (x *DeleteHistoryRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use DeleteHistoryRequest.ProtoReflect.Descriptor instead.func (*DeleteHistoryRequest) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{9}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{12}}func (x *DeleteHistoryRequest) GetIds() []string {@@ -1060,7 +1302,7 @@ type FetchRequest struct {func (x *FetchRequest) Reset() {*x = FetchRequest{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[10]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[13]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1072,7 +1314,7 @@ func (x *FetchRequest) String() string {func (*FetchRequest) ProtoMessage() {}func (x *FetchRequest) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[10]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[13]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1085,7 +1327,7 @@ func (x *FetchRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use FetchRequest.ProtoReflect.Descriptor instead.func (*FetchRequest) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{10}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{13}}func (x *FetchRequest) GetClipId() string {@@ -1111,7 +1353,7 @@ type ApplyToClipboardRequest struct {func (x *ApplyToClipboardRequest) Reset() {*x = ApplyToClipboardRequest{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[11]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[14]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1123,7 +1365,7 @@ func (x *ApplyToClipboardRequest) String() string {func (*ApplyToClipboardRequest) ProtoMessage() {}func (x *ApplyToClipboardRequest) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[11]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[14]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1136,7 +1378,7 @@ func (x *ApplyToClipboardRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use ApplyToClipboardRequest.ProtoReflect.Descriptor instead.func (*ApplyToClipboardRequest) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{11}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{14}}func (x *ApplyToClipboardRequest) GetClipId() string {@@ -1156,7 +1398,7 @@ type ListDevicesResponse struct {func (x *ListDevicesResponse) Reset() {*x = ListDevicesResponse{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[12]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[15]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1168,7 +1410,7 @@ func (x *ListDevicesResponse) String() string {func (*ListDevicesResponse) ProtoMessage() {}func (x *ListDevicesResponse) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[12]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[15]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1181,7 +1423,7 @@ func (x *ListDevicesResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use ListDevicesResponse.ProtoReflect.Descriptor instead.func (*ListDevicesResponse) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{12}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{15}}func (x *ListDevicesResponse) GetSelf() *Device {@@ -1211,7 +1453,7 @@ type CreatePairingCodeResponse struct {func (x *CreatePairingCodeResponse) Reset() {*x = CreatePairingCodeResponse{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[13]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[16]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1223,7 +1465,7 @@ func (x *CreatePairingCodeResponse) String() string {func (*CreatePairingCodeResponse) ProtoMessage() {}func (x *CreatePairingCodeResponse) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[13]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[16]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1236,7 +1478,7 @@ func (x *CreatePairingCodeResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use CreatePairingCodeResponse.ProtoReflect.Descriptor instead.func (*CreatePairingCodeResponse) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{13}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{16}}func (x *CreatePairingCodeResponse) GetCode() string {@@ -1273,7 +1515,7 @@ type RedeemPairingCodeRequest struct {func (x *RedeemPairingCodeRequest) Reset() {*x = RedeemPairingCodeRequest{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[14]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[17]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1285,7 +1527,7 @@ func (x *RedeemPairingCodeRequest) String() string {func (*RedeemPairingCodeRequest) ProtoMessage() {}func (x *RedeemPairingCodeRequest) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[14]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[17]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1298,7 +1540,7 @@ func (x *RedeemPairingCodeRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use RedeemPairingCodeRequest.ProtoReflect.Descriptor instead.func (*RedeemPairingCodeRequest) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{14}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{17}}func (x *RedeemPairingCodeRequest) GetCode() string {@@ -1326,7 +1568,7 @@ type RedeemPairingCodeResponse struct {func (x *RedeemPairingCodeResponse) Reset() {*x = RedeemPairingCodeResponse{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[15]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[18]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1338,7 +1580,7 @@ func (x *RedeemPairingCodeResponse) String() string {func (*RedeemPairingCodeResponse) ProtoMessage() {}func (x *RedeemPairingCodeResponse) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[15]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[18]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1351,7 +1593,7 @@ func (x *RedeemPairingCodeResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use RedeemPairingCodeResponse.ProtoReflect.Descriptor instead.func (*RedeemPairingCodeResponse) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{15}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{18}}func (x *RedeemPairingCodeResponse) GetPeer() *Device {@@ -1378,7 +1620,7 @@ type ConfirmPairingRequest struct {func (x *ConfirmPairingRequest) Reset() {*x = ConfirmPairingRequest{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[16]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[19]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1390,7 +1632,7 @@ func (x *ConfirmPairingRequest) String() string {func (*ConfirmPairingRequest) ProtoMessage() {}func (x *ConfirmPairingRequest) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[16]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[19]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1403,7 +1645,7 @@ func (x *ConfirmPairingRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use ConfirmPairingRequest.ProtoReflect.Descriptor instead.func (*ConfirmPairingRequest) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{16}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{19}}func (x *ConfirmPairingRequest) GetPairingSession() string {@@ -1433,7 +1675,7 @@ type NearbyDevice struct {func (x *NearbyDevice) Reset() {*x = NearbyDevice{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[17]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[20]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1445,7 +1687,7 @@ func (x *NearbyDevice) String() string {func (*NearbyDevice) ProtoMessage() {}func (x *NearbyDevice) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[17]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[20]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1458,7 +1700,7 @@ func (x *NearbyDevice) ProtoReflect() protoreflect.Message {// Deprecated: Use NearbyDevice.ProtoReflect.Descriptor instead.func (*NearbyDevice) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{17}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{20}}func (x *NearbyDevice) GetId() string {@@ -1498,7 +1740,7 @@ type NearbyDevices struct {func (x *NearbyDevices) Reset() {*x = NearbyDevices{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[18]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[21]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1510,7 +1752,7 @@ func (x *NearbyDevices) String() string {func (*NearbyDevices) ProtoMessage() {}func (x *NearbyDevices) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[18]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[21]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1523,7 +1765,7 @@ func (x *NearbyDevices) ProtoReflect() protoreflect.Message {// Deprecated: Use NearbyDevices.ProtoReflect.Descriptor instead.func (*NearbyDevices) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{18}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{21}}func (x *NearbyDevices) GetDevices() []*NearbyDevice {@@ -1542,7 +1784,7 @@ type PairNearbyRequest struct {func (x *PairNearbyRequest) Reset() {*x = PairNearbyRequest{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[19]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[22]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1554,7 +1796,7 @@ func (x *PairNearbyRequest) String() string {func (*PairNearbyRequest) ProtoMessage() {}func (x *PairNearbyRequest) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[19]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[22]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1567,7 +1809,7 @@ func (x *PairNearbyRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use PairNearbyRequest.ProtoReflect.Descriptor instead.func (*PairNearbyRequest) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{19}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{22}}func (x *PairNearbyRequest) GetId() string {@@ -1586,7 +1828,7 @@ type UnpairRequest struct {func (x *UnpairRequest) Reset() {*x = UnpairRequest{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[20]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[23]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1598,7 +1840,7 @@ func (x *UnpairRequest) String() string {func (*UnpairRequest) ProtoMessage() {}func (x *UnpairRequest) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[20]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[23]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1611,7 +1853,7 @@ func (x *UnpairRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use UnpairRequest.ProtoReflect.Descriptor instead.func (*UnpairRequest) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{20}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{23}}func (x *UnpairRequest) GetDeviceId() string {@@ -1631,7 +1873,7 @@ type SetDeviceAddressRequest struct {func (x *SetDeviceAddressRequest) Reset() {*x = SetDeviceAddressRequest{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[21]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[24]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1643,7 +1885,7 @@ func (x *SetDeviceAddressRequest) String() string {func (*SetDeviceAddressRequest) ProtoMessage() {}func (x *SetDeviceAddressRequest) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[21]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[24]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1656,7 +1898,7 @@ func (x *SetDeviceAddressRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use SetDeviceAddressRequest.ProtoReflect.Descriptor instead.func (*SetDeviceAddressRequest) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{21}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{24}}func (x *SetDeviceAddressRequest) GetDeviceId() string {@@ -1703,7 +1945,7 @@ type Config struct {func (x *Config) Reset() {*x = Config{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[22]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[25]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1715,7 +1957,7 @@ func (x *Config) String() string {func (*Config) ProtoMessage() {}func (x *Config) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[22]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[25]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1728,7 +1970,7 @@ func (x *Config) ProtoReflect() protoreflect.Message {// Deprecated: Use Config.ProtoReflect.Descriptor instead.func (*Config) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{22}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{25}}func (x *Config) GetAutoSyncThresholdBytes() int64 {@@ -1844,7 +2086,7 @@ type NetworkInfo struct {func (x *NetworkInfo) Reset() {*x = NetworkInfo{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[23]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[26]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1856,7 +2098,7 @@ func (x *NetworkInfo) String() string {func (*NetworkInfo) ProtoMessage() {}func (x *NetworkInfo) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[23]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[26]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1869,7 +2111,7 @@ func (x *NetworkInfo) ProtoReflect() protoreflect.Message {// Deprecated: Use NetworkInfo.ProtoReflect.Descriptor instead.func (*NetworkInfo) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{23}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{26}}func (x *NetworkInfo) GetLocalPort() int32 {@@ -1929,7 +2171,7 @@ type LanInfo struct {func (x *LanInfo) Reset() {*x = LanInfo{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[24]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[27]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1941,7 +2183,7 @@ func (x *LanInfo) String() string {func (*LanInfo) ProtoMessage() {}func (x *LanInfo) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[24]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[27]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -1954,7 +2196,7 @@ func (x *LanInfo) ProtoReflect() protoreflect.Message {// Deprecated: Use LanInfo.ProtoReflect.Descriptor instead.func (*LanInfo) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{24}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{27}}func (x *LanInfo) GetEnabled() bool {@@ -2013,7 +2255,7 @@ type LanPeer struct {func (x *LanPeer) Reset() {*x = LanPeer{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[25]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[28]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2025,7 +2267,7 @@ func (x *LanPeer) String() string {func (*LanPeer) ProtoMessage() {}func (x *LanPeer) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[25]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[28]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2038,7 +2280,7 @@ func (x *LanPeer) ProtoReflect() protoreflect.Message {// Deprecated: Use LanPeer.ProtoReflect.Descriptor instead.func (*LanPeer) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{25}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{28}}func (x *LanPeer) GetDeviceId() string {@@ -2095,7 +2337,7 @@ type NetworkEgress struct {func (x *NetworkEgress) Reset() {*x = NetworkEgress{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[26]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[29]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2107,7 +2349,7 @@ func (x *NetworkEgress) String() string {func (*NetworkEgress) ProtoMessage() {}func (x *NetworkEgress) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[26]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[29]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2120,7 +2362,7 @@ func (x *NetworkEgress) ProtoReflect() protoreflect.Message {// Deprecated: Use NetworkEgress.ProtoReflect.Descriptor instead.func (*NetworkEgress) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{26}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{29}}func (x *NetworkEgress) GetAddress() string {@@ -2173,7 +2415,7 @@ type Status struct {func (x *Status) Reset() {*x = Status{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[27]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[30]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2185,7 +2427,7 @@ func (x *Status) String() string {func (*Status) ProtoMessage() {}func (x *Status) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[27]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[30]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2198,7 +2440,7 @@ func (x *Status) ProtoReflect() protoreflect.Message {// Deprecated: Use Status.ProtoReflect.Descriptor instead.func (*Status) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{27}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{30}}func (x *Status) GetDeviceId() string {@@ -2288,7 +2530,7 @@ type ExportDiagnosticsRequest struct {func (x *ExportDiagnosticsRequest) Reset() {*x = ExportDiagnosticsRequest{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[28]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[31]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2300,7 +2542,7 @@ func (x *ExportDiagnosticsRequest) String() string {func (*ExportDiagnosticsRequest) ProtoMessage() {}func (x *ExportDiagnosticsRequest) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[28]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[31]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2313,7 +2555,7 @@ func (x *ExportDiagnosticsRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use ExportDiagnosticsRequest.ProtoReflect.Descriptor instead.func (*ExportDiagnosticsRequest) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{28}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{31}}func (x *ExportDiagnosticsRequest) GetLogLines() int32 {@@ -2339,7 +2581,7 @@ type Diagnostics struct {func (x *Diagnostics) Reset() {*x = Diagnostics{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[29]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[32]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2351,7 +2593,7 @@ func (x *Diagnostics) String() string {func (*Diagnostics) ProtoMessage() {}func (x *Diagnostics) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[29]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[32]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2364,7 +2606,7 @@ func (x *Diagnostics) ProtoReflect() protoreflect.Message {// Deprecated: Use Diagnostics.ProtoReflect.Descriptor instead.func (*Diagnostics) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{29}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{32}}func (x *Diagnostics) GetReport() string {@@ -2383,7 +2625,7 @@ type SetVerboseLogRequest struct {func (x *SetVerboseLogRequest) Reset() {*x = SetVerboseLogRequest{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[30]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[33]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2395,7 +2637,7 @@ func (x *SetVerboseLogRequest) String() string {func (*SetVerboseLogRequest) ProtoMessage() {}func (x *SetVerboseLogRequest) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[30]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[33]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2408,7 +2650,7 @@ func (x *SetVerboseLogRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use SetVerboseLogRequest.ProtoReflect.Descriptor instead.func (*SetVerboseLogRequest) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{30}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{33}}func (x *SetVerboseLogRequest) GetMinutes() int32 {@@ -2428,7 +2670,7 @@ type GetImagePreviewRequest struct {func (x *GetImagePreviewRequest) Reset() {*x = GetImagePreviewRequest{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[31]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[34]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2440,7 +2682,7 @@ func (x *GetImagePreviewRequest) String() string {func (*GetImagePreviewRequest) ProtoMessage() {}func (x *GetImagePreviewRequest) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[31]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[34]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2453,7 +2695,7 @@ func (x *GetImagePreviewRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use GetImagePreviewRequest.ProtoReflect.Descriptor instead.func (*GetImagePreviewRequest) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{31}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{34}}func (x *GetImagePreviewRequest) GetClipId() string {@@ -2481,7 +2723,7 @@ type GetImagePreviewResponse struct {func (x *GetImagePreviewResponse) Reset() {*x = GetImagePreviewResponse{}- mi := &file_pasteferry_v1_daemon_proto_msgTypes[32]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[35]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2493,7 +2735,7 @@ func (x *GetImagePreviewResponse) String() string {func (*GetImagePreviewResponse) ProtoMessage() {}func (x *GetImagePreviewResponse) ProtoReflect() protoreflect.Message {- mi := &file_pasteferry_v1_daemon_proto_msgTypes[32]+ mi := &file_pasteferry_v1_daemon_proto_msgTypes[35]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2506,7 +2748,7 @@ func (x *GetImagePreviewResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use GetImagePreviewResponse.ProtoReflect.Descriptor instead.func (*GetImagePreviewResponse) Descriptor() ([]byte, []int) {- return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{32}+ return file_pasteferry_v1_daemon_proto_rawDescGZIP(), []int{35}}func (x *GetImagePreviewResponse) GetPath() string {@@ -2577,7 +2819,7 @@ const file_pasteferry_v1_daemon_proto_rawDesc = "" +"connection\x124\n" +"\x16public_key_fingerprint\x18\x06 \x01(\tR\x14publicKeyFingerprint\x12$\n" +"\x0epaired_at_unix\x18\a \x01(\x03R\fpairedAtUnix\x12'\n" +- "\x0fpairing_session\x18\b \x01(\tR\x0epairingSession\"\xc7\x03\n" ++ "\x0fpairing_session\x18\b \x01(\tR\x0epairingSession\"\x9b\x04\n" +"\x05Event\x12:\n" +"\n" +"clip_added\x18\x01 \x01(\v2\x19.pasteferry.v1.ClipRecordH\x00R\tclipAdded\x12>\n" +@@ -2586,8 +2828,22 @@ const file_pasteferry_v1_daemon_proto_rawDesc = "" +"\bprogress\x18\x04 \x01(\v2\x1f.pasteferry.v1.TransferProgressH\x00R\bprogress\x12>\n" +"\x0edevice_changed\x18\x05 \x01(\v2\x15.pasteferry.v1.DeviceH\x00R\rdeviceChanged\x12S\n" +"\x12permission_changed\x18\x06 \x01(\x0e2\".pasteferry.v1.ClipboardPermissionH\x00R\x11permissionChanged\x12>\n" +- "\x0estatus_changed\x18\a \x01(\v2\x15.pasteferry.v1.StatusH\x00R\rstatusChangedB\t\n" +- "\apayload\"\x9b\x01\n" ++ "\x0estatus_changed\x18\a \x01(\v2\x15.pasteferry.v1.StatusH\x00R\rstatusChanged\x12R\n" ++ "\x11clipboard_written\x18\b \x01(\v2#.pasteferry.v1.ClipboardWriteResultH\x00R\x10clipboardWrittenB\t\n" ++ "\apayload\"\x7f\n" ++ "\x12NotificationStatus\x12\x1c\n" ++ "\tsupported\x18\x01 \x01(\bR\tsupported\x12+\n" ++ "\x11actions_supported\x18\x02 \x01(\bR\x10actionsSupported\x12\x1e\n" ++ "\n" ++ "permission\x18\x03 \x01(\tR\n" ++ "permission\"E\n" ++ "\x12NotificationAction\x12\x17\n" ++ "\aclip_id\x18\x01 \x01(\tR\x06clipId\x12\x16\n" ++ "\x06action\x18\x02 \x01(\tR\x06action\"\x85\x01\n" ++ "\x14ClipboardWriteResult\x12\x17\n" ++ "\aclip_id\x18\x01 \x01(\tR\x06clipId\x12>\n" ++ "\aoutcome\x18\x02 \x01(\x0e2$.pasteferry.v1.ClipboardWriteOutcomeR\aoutcome\x12\x14\n" ++ "\x05error\x18\x03 \x01(\tR\x05error\"\x9b\x01\n" +"\x12ListHistoryRequest\x12\x14\n" +"\x05limit\x18\x01 \x01(\x05R\x05limit\x12\x1f\n" +"\vbefore_unix\x18\x02 \x01(\x03R\n" +@@ -2740,7 +2996,12 @@ const file_pasteferry_v1_daemon_proto_rawDesc = "" +"\x1cCLIPBOARD_PERMISSION_DEFAULT\x10\x02\x12\x1c\n" +"\x18CLIPBOARD_PERMISSION_ASK\x10\x03\x12%\n" +"!CLIPBOARD_PERMISSION_ALWAYS_ALLOW\x10\x04\x12$\n" +- " CLIPBOARD_PERMISSION_ALWAYS_DENY\x10\x052\x9a\r\n" ++ " CLIPBOARD_PERMISSION_ALWAYS_DENY\x10\x05*\xb0\x01\n" ++ "\x15ClipboardWriteOutcome\x12'\n" ++ "#CLIPBOARD_WRITE_OUTCOME_UNSPECIFIED\x10\x00\x12#\n" ++ "\x1fCLIPBOARD_WRITE_OUTCOME_APPLIED\x10\x01\x12%\n" ++ "!CLIPBOARD_WRITE_OUTCOME_PRESERVED\x10\x02\x12\"\n" ++ "\x1eCLIPBOARD_WRITE_OUTCOME_FAILED\x10\x032\x97\x0f\n" +"\rDaemonService\x12D\n" +"\tSubscribe\x12\x1f.pasteferry.v1.SubscribeRequest\x1a\x14.pasteferry.v1.Event0\x01\x12T\n" +"\vListHistory\x12!.pasteferry.v1.ListHistoryRequest\x1a\".pasteferry.v1.ListHistoryResponse\x12J\n" +@@ -2761,7 +3022,10 @@ const file_pasteferry_v1_daemon_proto_rawDesc = "" +"\fUpdateConfig\x12\x15.pasteferry.v1.Config\x1a\x15.pasteferry.v1.Config\x128\n" +"\tGetStatus\x12\x14.pasteferry.v1.Empty\x1a\x15.pasteferry.v1.Status\x12H\n" +"\x1aRequestClipboardPermission\x12\x14.pasteferry.v1.Empty\x1a\x14.pasteferry.v1.Empty\x12K\n" +- "\x1dRequestLocalNetworkPermission\x12\x14.pasteferry.v1.Empty\x1a\x14.pasteferry.v1.Empty\x12>\n" ++ "\x1dRequestLocalNetworkPermission\x12\x14.pasteferry.v1.Empty\x1a\x14.pasteferry.v1.Empty\x12P\n" ++ "\x15GetNotificationStatus\x12\x14.pasteferry.v1.Empty\x1a!.pasteferry.v1.NotificationStatus\x12X\n" ++ "\x1dRequestNotificationPermission\x12\x14.pasteferry.v1.Empty\x1a!.pasteferry.v1.NotificationStatus\x12O\n" ++ "\x14ActivateNotification\x12!.pasteferry.v1.NotificationAction\x1a\x14.pasteferry.v1.Empty\x12>\n" +"\n" +"GetNetwork\x12\x14.pasteferry.v1.Empty\x1a\x1a.pasteferry.v1.NetworkInfo\x12X\n" +"\x11ExportDiagnostics\x12'.pasteferry.v1.ExportDiagnosticsRequest\x1a\x1a.pasteferry.v1.Diagnostics\x12K\n" +@@ -2779,117 +3043,129 @@ func file_pasteferry_v1_daemon_proto_rawDescGZIP() []byte {return file_pasteferry_v1_daemon_proto_rawDescData}-var file_pasteferry_v1_daemon_proto_enumTypes = make([]protoimpl.EnumInfo, 4)-var file_pasteferry_v1_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 33)+var file_pasteferry_v1_daemon_proto_enumTypes = make([]protoimpl.EnumInfo, 5)+var file_pasteferry_v1_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 36)var file_pasteferry_v1_daemon_proto_goTypes = []any{(ClipKind)(0), // 0: pasteferry.v1.ClipKind(ClipStatus)(0), // 1: pasteferry.v1.ClipStatus(ConnectionKind)(0), // 2: pasteferry.v1.ConnectionKind(ClipboardPermission)(0), // 3: pasteferry.v1.ClipboardPermission- (*Empty)(nil), // 4: pasteferry.v1.Empty- (*ClipItem)(nil), // 5: pasteferry.v1.ClipItem- (*ClipRecord)(nil), // 6: pasteferry.v1.ClipRecord- (*SubscribeRequest)(nil), // 7: pasteferry.v1.SubscribeRequest- (*TransferProgress)(nil), // 8: pasteferry.v1.TransferProgress- (*Device)(nil), // 9: pasteferry.v1.Device- (*Event)(nil), // 10: pasteferry.v1.Event- (*ListHistoryRequest)(nil), // 11: pasteferry.v1.ListHistoryRequest- (*ListHistoryResponse)(nil), // 12: pasteferry.v1.ListHistoryResponse- (*DeleteHistoryRequest)(nil), // 13: pasteferry.v1.DeleteHistoryRequest- (*FetchRequest)(nil), // 14: pasteferry.v1.FetchRequest- (*ApplyToClipboardRequest)(nil), // 15: pasteferry.v1.ApplyToClipboardRequest- (*ListDevicesResponse)(nil), // 16: pasteferry.v1.ListDevicesResponse- (*CreatePairingCodeResponse)(nil), // 17: pasteferry.v1.CreatePairingCodeResponse- (*RedeemPairingCodeRequest)(nil), // 18: pasteferry.v1.RedeemPairingCodeRequest- (*RedeemPairingCodeResponse)(nil), // 19: pasteferry.v1.RedeemPairingCodeResponse- (*ConfirmPairingRequest)(nil), // 20: pasteferry.v1.ConfirmPairingRequest- (*NearbyDevice)(nil), // 21: pasteferry.v1.NearbyDevice- (*NearbyDevices)(nil), // 22: pasteferry.v1.NearbyDevices- (*PairNearbyRequest)(nil), // 23: pasteferry.v1.PairNearbyRequest- (*UnpairRequest)(nil), // 24: pasteferry.v1.UnpairRequest- (*SetDeviceAddressRequest)(nil), // 25: pasteferry.v1.SetDeviceAddressRequest- (*Config)(nil), // 26: pasteferry.v1.Config- (*NetworkInfo)(nil), // 27: pasteferry.v1.NetworkInfo- (*LanInfo)(nil), // 28: pasteferry.v1.LanInfo- (*LanPeer)(nil), // 29: pasteferry.v1.LanPeer- (*NetworkEgress)(nil), // 30: pasteferry.v1.NetworkEgress- (*Status)(nil), // 31: pasteferry.v1.Status- (*ExportDiagnosticsRequest)(nil), // 32: pasteferry.v1.ExportDiagnosticsRequest- (*Diagnostics)(nil), // 33: pasteferry.v1.Diagnostics- (*SetVerboseLogRequest)(nil), // 34: pasteferry.v1.SetVerboseLogRequest- (*GetImagePreviewRequest)(nil), // 35: pasteferry.v1.GetImagePreviewRequest- (*GetImagePreviewResponse)(nil), // 36: pasteferry.v1.GetImagePreviewResponse+ (ClipboardWriteOutcome)(0), // 4: pasteferry.v1.ClipboardWriteOutcome+ (*Empty)(nil), // 5: pasteferry.v1.Empty+ (*ClipItem)(nil), // 6: pasteferry.v1.ClipItem+ (*ClipRecord)(nil), // 7: pasteferry.v1.ClipRecord+ (*SubscribeRequest)(nil), // 8: pasteferry.v1.SubscribeRequest+ (*TransferProgress)(nil), // 9: pasteferry.v1.TransferProgress+ (*Device)(nil), // 10: pasteferry.v1.Device+ (*Event)(nil), // 11: pasteferry.v1.Event+ (*NotificationStatus)(nil), // 12: pasteferry.v1.NotificationStatus+ (*NotificationAction)(nil), // 13: pasteferry.v1.NotificationAction+ (*ClipboardWriteResult)(nil), // 14: pasteferry.v1.ClipboardWriteResult+ (*ListHistoryRequest)(nil), // 15: pasteferry.v1.ListHistoryRequest+ (*ListHistoryResponse)(nil), // 16: pasteferry.v1.ListHistoryResponse+ (*DeleteHistoryRequest)(nil), // 17: pasteferry.v1.DeleteHistoryRequest+ (*FetchRequest)(nil), // 18: pasteferry.v1.FetchRequest+ (*ApplyToClipboardRequest)(nil), // 19: pasteferry.v1.ApplyToClipboardRequest+ (*ListDevicesResponse)(nil), // 20: pasteferry.v1.ListDevicesResponse+ (*CreatePairingCodeResponse)(nil), // 21: pasteferry.v1.CreatePairingCodeResponse+ (*RedeemPairingCodeRequest)(nil), // 22: pasteferry.v1.RedeemPairingCodeRequest+ (*RedeemPairingCodeResponse)(nil), // 23: pasteferry.v1.RedeemPairingCodeResponse+ (*ConfirmPairingRequest)(nil), // 24: pasteferry.v1.ConfirmPairingRequest+ (*NearbyDevice)(nil), // 25: pasteferry.v1.NearbyDevice+ (*NearbyDevices)(nil), // 26: pasteferry.v1.NearbyDevices+ (*PairNearbyRequest)(nil), // 27: pasteferry.v1.PairNearbyRequest+ (*UnpairRequest)(nil), // 28: pasteferry.v1.UnpairRequest+ (*SetDeviceAddressRequest)(nil), // 29: pasteferry.v1.SetDeviceAddressRequest+ (*Config)(nil), // 30: pasteferry.v1.Config+ (*NetworkInfo)(nil), // 31: pasteferry.v1.NetworkInfo+ (*LanInfo)(nil), // 32: pasteferry.v1.LanInfo+ (*LanPeer)(nil), // 33: pasteferry.v1.LanPeer+ (*NetworkEgress)(nil), // 34: pasteferry.v1.NetworkEgress+ (*Status)(nil), // 35: pasteferry.v1.Status+ (*ExportDiagnosticsRequest)(nil), // 36: pasteferry.v1.ExportDiagnosticsRequest+ (*Diagnostics)(nil), // 37: pasteferry.v1.Diagnostics+ (*SetVerboseLogRequest)(nil), // 38: pasteferry.v1.SetVerboseLogRequest+ (*GetImagePreviewRequest)(nil), // 39: pasteferry.v1.GetImagePreviewRequest+ (*GetImagePreviewResponse)(nil), // 40: pasteferry.v1.GetImagePreviewResponse}var file_pasteferry_v1_daemon_proto_depIdxs = []int32{0, // 0: pasteferry.v1.ClipRecord.kind:type_name -> pasteferry.v1.ClipKind1, // 1: pasteferry.v1.ClipRecord.status:type_name -> pasteferry.v1.ClipStatus- 5, // 2: pasteferry.v1.ClipRecord.items:type_name -> pasteferry.v1.ClipItem+ 6, // 2: pasteferry.v1.ClipRecord.items:type_name -> pasteferry.v1.ClipItem2, // 3: pasteferry.v1.Device.connection:type_name -> pasteferry.v1.ConnectionKind- 6, // 4: pasteferry.v1.Event.clip_added:type_name -> pasteferry.v1.ClipRecord- 6, // 5: pasteferry.v1.Event.clip_updated:type_name -> pasteferry.v1.ClipRecord- 8, // 6: pasteferry.v1.Event.progress:type_name -> pasteferry.v1.TransferProgress- 9, // 7: pasteferry.v1.Event.device_changed:type_name -> pasteferry.v1.Device+ 7, // 4: pasteferry.v1.Event.clip_added:type_name -> pasteferry.v1.ClipRecord+ 7, // 5: pasteferry.v1.Event.clip_updated:type_name -> pasteferry.v1.ClipRecord+ 9, // 6: pasteferry.v1.Event.progress:type_name -> pasteferry.v1.TransferProgress+ 10, // 7: pasteferry.v1.Event.device_changed:type_name -> pasteferry.v1.Device3, // 8: pasteferry.v1.Event.permission_changed:type_name -> pasteferry.v1.ClipboardPermission- 31, // 9: pasteferry.v1.Event.status_changed:type_name -> pasteferry.v1.Status- 0, // 10: pasteferry.v1.ListHistoryRequest.kind_filter:type_name -> pasteferry.v1.ClipKind- 6, // 11: pasteferry.v1.ListHistoryResponse.records:type_name -> pasteferry.v1.ClipRecord- 9, // 12: pasteferry.v1.ListDevicesResponse.self:type_name -> pasteferry.v1.Device- 9, // 13: pasteferry.v1.ListDevicesResponse.peers:type_name -> pasteferry.v1.Device- 9, // 14: pasteferry.v1.RedeemPairingCodeResponse.peer:type_name -> pasteferry.v1.Device- 21, // 15: pasteferry.v1.NearbyDevices.devices:type_name -> pasteferry.v1.NearbyDevice- 30, // 16: pasteferry.v1.NetworkInfo.egresses:type_name -> pasteferry.v1.NetworkEgress- 28, // 17: pasteferry.v1.NetworkInfo.lan:type_name -> pasteferry.v1.LanInfo- 29, // 18: pasteferry.v1.LanInfo.peers:type_name -> pasteferry.v1.LanPeer- 3, // 19: pasteferry.v1.Status.clipboard_permission:type_name -> pasteferry.v1.ClipboardPermission- 7, // 20: pasteferry.v1.DaemonService.Subscribe:input_type -> pasteferry.v1.SubscribeRequest- 11, // 21: pasteferry.v1.DaemonService.ListHistory:input_type -> pasteferry.v1.ListHistoryRequest- 13, // 22: pasteferry.v1.DaemonService.DeleteHistory:input_type -> pasteferry.v1.DeleteHistoryRequest- 14, // 23: pasteferry.v1.DaemonService.Fetch:input_type -> pasteferry.v1.FetchRequest- 15, // 24: pasteferry.v1.DaemonService.ApplyToClipboard:input_type -> pasteferry.v1.ApplyToClipboardRequest- 35, // 25: pasteferry.v1.DaemonService.GetImagePreview:input_type -> pasteferry.v1.GetImagePreviewRequest- 4, // 26: pasteferry.v1.DaemonService.ListDevices:input_type -> pasteferry.v1.Empty- 4, // 27: pasteferry.v1.DaemonService.CreatePairingCode:input_type -> pasteferry.v1.Empty- 18, // 28: pasteferry.v1.DaemonService.RedeemPairingCode:input_type -> pasteferry.v1.RedeemPairingCodeRequest- 20, // 29: pasteferry.v1.DaemonService.ConfirmPairing:input_type -> pasteferry.v1.ConfirmPairingRequest- 24, // 30: pasteferry.v1.DaemonService.Unpair:input_type -> pasteferry.v1.UnpairRequest- 25, // 31: pasteferry.v1.DaemonService.SetDeviceAddress:input_type -> pasteferry.v1.SetDeviceAddressRequest- 4, // 32: pasteferry.v1.DaemonService.WatchNearby:input_type -> pasteferry.v1.Empty- 23, // 33: pasteferry.v1.DaemonService.PairNearby:input_type -> pasteferry.v1.PairNearbyRequest- 4, // 34: pasteferry.v1.DaemonService.GetConfig:input_type -> pasteferry.v1.Empty- 26, // 35: pasteferry.v1.DaemonService.UpdateConfig:input_type -> pasteferry.v1.Config- 4, // 36: pasteferry.v1.DaemonService.GetStatus:input_type -> pasteferry.v1.Empty- 4, // 37: pasteferry.v1.DaemonService.RequestClipboardPermission:input_type -> pasteferry.v1.Empty- 4, // 38: pasteferry.v1.DaemonService.RequestLocalNetworkPermission:input_type -> pasteferry.v1.Empty- 4, // 39: pasteferry.v1.DaemonService.GetNetwork:input_type -> pasteferry.v1.Empty- 32, // 40: pasteferry.v1.DaemonService.ExportDiagnostics:input_type -> pasteferry.v1.ExportDiagnosticsRequest- 34, // 41: pasteferry.v1.DaemonService.SetVerboseLog:input_type -> pasteferry.v1.SetVerboseLogRequest- 10, // 42: pasteferry.v1.DaemonService.Subscribe:output_type -> pasteferry.v1.Event- 12, // 43: pasteferry.v1.DaemonService.ListHistory:output_type -> pasteferry.v1.ListHistoryResponse- 4, // 44: pasteferry.v1.DaemonService.DeleteHistory:output_type -> pasteferry.v1.Empty- 4, // 45: pasteferry.v1.DaemonService.Fetch:output_type -> pasteferry.v1.Empty- 4, // 46: pasteferry.v1.DaemonService.ApplyToClipboard:output_type -> pasteferry.v1.Empty- 36, // 47: pasteferry.v1.DaemonService.GetImagePreview:output_type -> pasteferry.v1.GetImagePreviewResponse- 16, // 48: pasteferry.v1.DaemonService.ListDevices:output_type -> pasteferry.v1.ListDevicesResponse- 17, // 49: pasteferry.v1.DaemonService.CreatePairingCode:output_type -> pasteferry.v1.CreatePairingCodeResponse- 19, // 50: pasteferry.v1.DaemonService.RedeemPairingCode:output_type -> pasteferry.v1.RedeemPairingCodeResponse- 4, // 51: pasteferry.v1.DaemonService.ConfirmPairing:output_type -> pasteferry.v1.Empty- 4, // 52: pasteferry.v1.DaemonService.Unpair:output_type -> pasteferry.v1.Empty- 4, // 53: pasteferry.v1.DaemonService.SetDeviceAddress:output_type -> pasteferry.v1.Empty- 22, // 54: pasteferry.v1.DaemonService.WatchNearby:output_type -> pasteferry.v1.NearbyDevices- 19, // 55: pasteferry.v1.DaemonService.PairNearby:output_type -> pasteferry.v1.RedeemPairingCodeResponse- 26, // 56: pasteferry.v1.DaemonService.GetConfig:output_type -> pasteferry.v1.Config- 26, // 57: pasteferry.v1.DaemonService.UpdateConfig:output_type -> pasteferry.v1.Config- 31, // 58: pasteferry.v1.DaemonService.GetStatus:output_type -> pasteferry.v1.Status- 4, // 59: pasteferry.v1.DaemonService.RequestClipboardPermission:output_type -> pasteferry.v1.Empty- 4, // 60: pasteferry.v1.DaemonService.RequestLocalNetworkPermission:output_type -> pasteferry.v1.Empty- 27, // 61: pasteferry.v1.DaemonService.GetNetwork:output_type -> pasteferry.v1.NetworkInfo- 33, // 62: pasteferry.v1.DaemonService.ExportDiagnostics:output_type -> pasteferry.v1.Diagnostics- 31, // 63: pasteferry.v1.DaemonService.SetVerboseLog:output_type -> pasteferry.v1.Status- 42, // [42:64] is the sub-list for method output_type- 20, // [20:42] is the sub-list for method input_type- 20, // [20:20] is the sub-list for extension type_name- 20, // [20:20] is the sub-list for extension extendee- 0, // [0:20] is the sub-list for field type_name+ 35, // 9: pasteferry.v1.Event.status_changed:type_name -> pasteferry.v1.Status+ 14, // 10: pasteferry.v1.Event.clipboard_written:type_name -> pasteferry.v1.ClipboardWriteResult+ 4, // 11: pasteferry.v1.ClipboardWriteResult.outcome:type_name -> pasteferry.v1.ClipboardWriteOutcome+ 0, // 12: pasteferry.v1.ListHistoryRequest.kind_filter:type_name -> pasteferry.v1.ClipKind+ 7, // 13: pasteferry.v1.ListHistoryResponse.records:type_name -> pasteferry.v1.ClipRecord+ 10, // 14: pasteferry.v1.ListDevicesResponse.self:type_name -> pasteferry.v1.Device+ 10, // 15: pasteferry.v1.ListDevicesResponse.peers:type_name -> pasteferry.v1.Device+ 10, // 16: pasteferry.v1.RedeemPairingCodeResponse.peer:type_name -> pasteferry.v1.Device+ 25, // 17: pasteferry.v1.NearbyDevices.devices:type_name -> pasteferry.v1.NearbyDevice+ 34, // 18: pasteferry.v1.NetworkInfo.egresses:type_name -> pasteferry.v1.NetworkEgress+ 32, // 19: pasteferry.v1.NetworkInfo.lan:type_name -> pasteferry.v1.LanInfo+ 33, // 20: pasteferry.v1.LanInfo.peers:type_name -> pasteferry.v1.LanPeer+ 3, // 21: pasteferry.v1.Status.clipboard_permission:type_name -> pasteferry.v1.ClipboardPermission+ 8, // 22: pasteferry.v1.DaemonService.Subscribe:input_type -> pasteferry.v1.SubscribeRequest+ 15, // 23: pasteferry.v1.DaemonService.ListHistory:input_type -> pasteferry.v1.ListHistoryRequest+ 17, // 24: pasteferry.v1.DaemonService.DeleteHistory:input_type -> pasteferry.v1.DeleteHistoryRequest+ 18, // 25: pasteferry.v1.DaemonService.Fetch:input_type -> pasteferry.v1.FetchRequest+ 19, // 26: pasteferry.v1.DaemonService.ApplyToClipboard:input_type -> pasteferry.v1.ApplyToClipboardRequest+ 39, // 27: pasteferry.v1.DaemonService.GetImagePreview:input_type -> pasteferry.v1.GetImagePreviewRequest+ 5, // 28: pasteferry.v1.DaemonService.ListDevices:input_type -> pasteferry.v1.Empty+ 5, // 29: pasteferry.v1.DaemonService.CreatePairingCode:input_type -> pasteferry.v1.Empty+ 22, // 30: pasteferry.v1.DaemonService.RedeemPairingCode:input_type -> pasteferry.v1.RedeemPairingCodeRequest+ 24, // 31: pasteferry.v1.DaemonService.ConfirmPairing:input_type -> pasteferry.v1.ConfirmPairingRequest+ 28, // 32: pasteferry.v1.DaemonService.Unpair:input_type -> pasteferry.v1.UnpairRequest+ 29, // 33: pasteferry.v1.DaemonService.SetDeviceAddress:input_type -> pasteferry.v1.SetDeviceAddressRequest+ 5, // 34: pasteferry.v1.DaemonService.WatchNearby:input_type -> pasteferry.v1.Empty+ 27, // 35: pasteferry.v1.DaemonService.PairNearby:input_type -> pasteferry.v1.PairNearbyRequest+ 5, // 36: pasteferry.v1.DaemonService.GetConfig:input_type -> pasteferry.v1.Empty+ 30, // 37: pasteferry.v1.DaemonService.UpdateConfig:input_type -> pasteferry.v1.Config+ 5, // 38: pasteferry.v1.DaemonService.GetStatus:input_type -> pasteferry.v1.Empty+ 5, // 39: pasteferry.v1.DaemonService.RequestClipboardPermission:input_type -> pasteferry.v1.Empty+ 5, // 40: pasteferry.v1.DaemonService.RequestLocalNetworkPermission:input_type -> pasteferry.v1.Empty+ 5, // 41: pasteferry.v1.DaemonService.GetNotificationStatus:input_type -> pasteferry.v1.Empty+ 5, // 42: pasteferry.v1.DaemonService.RequestNotificationPermission:input_type -> pasteferry.v1.Empty+ 13, // 43: pasteferry.v1.DaemonService.ActivateNotification:input_type -> pasteferry.v1.NotificationAction+ 5, // 44: pasteferry.v1.DaemonService.GetNetwork:input_type -> pasteferry.v1.Empty+ 36, // 45: pasteferry.v1.DaemonService.ExportDiagnostics:input_type -> pasteferry.v1.ExportDiagnosticsRequest+ 38, // 46: pasteferry.v1.DaemonService.SetVerboseLog:input_type -> pasteferry.v1.SetVerboseLogRequest+ 11, // 47: pasteferry.v1.DaemonService.Subscribe:output_type -> pasteferry.v1.Event+ 16, // 48: pasteferry.v1.DaemonService.ListHistory:output_type -> pasteferry.v1.ListHistoryResponse+ 5, // 49: pasteferry.v1.DaemonService.DeleteHistory:output_type -> pasteferry.v1.Empty+ 5, // 50: pasteferry.v1.DaemonService.Fetch:output_type -> pasteferry.v1.Empty+ 5, // 51: pasteferry.v1.DaemonService.ApplyToClipboard:output_type -> pasteferry.v1.Empty+ 40, // 52: pasteferry.v1.DaemonService.GetImagePreview:output_type -> pasteferry.v1.GetImagePreviewResponse+ 20, // 53: pasteferry.v1.DaemonService.ListDevices:output_type -> pasteferry.v1.ListDevicesResponse+ 21, // 54: pasteferry.v1.DaemonService.CreatePairingCode:output_type -> pasteferry.v1.CreatePairingCodeResponse+ 23, // 55: pasteferry.v1.DaemonService.RedeemPairingCode:output_type -> pasteferry.v1.RedeemPairingCodeResponse+ 5, // 56: pasteferry.v1.DaemonService.ConfirmPairing:output_type -> pasteferry.v1.Empty+ 5, // 57: pasteferry.v1.DaemonService.Unpair:output_type -> pasteferry.v1.Empty+ 5, // 58: pasteferry.v1.DaemonService.SetDeviceAddress:output_type -> pasteferry.v1.Empty+ 26, // 59: pasteferry.v1.DaemonService.WatchNearby:output_type -> pasteferry.v1.NearbyDevices+ 23, // 60: pasteferry.v1.DaemonService.PairNearby:output_type -> pasteferry.v1.RedeemPairingCodeResponse+ 30, // 61: pasteferry.v1.DaemonService.GetConfig:output_type -> pasteferry.v1.Config+ 30, // 62: pasteferry.v1.DaemonService.UpdateConfig:output_type -> pasteferry.v1.Config+ 35, // 63: pasteferry.v1.DaemonService.GetStatus:output_type -> pasteferry.v1.Status+ 5, // 64: pasteferry.v1.DaemonService.RequestClipboardPermission:output_type -> pasteferry.v1.Empty+ 5, // 65: pasteferry.v1.DaemonService.RequestLocalNetworkPermission:output_type -> pasteferry.v1.Empty+ 12, // 66: pasteferry.v1.DaemonService.GetNotificationStatus:output_type -> pasteferry.v1.NotificationStatus+ 12, // 67: pasteferry.v1.DaemonService.RequestNotificationPermission:output_type -> pasteferry.v1.NotificationStatus+ 5, // 68: pasteferry.v1.DaemonService.ActivateNotification:output_type -> pasteferry.v1.Empty+ 31, // 69: pasteferry.v1.DaemonService.GetNetwork:output_type -> pasteferry.v1.NetworkInfo+ 37, // 70: pasteferry.v1.DaemonService.ExportDiagnostics:output_type -> pasteferry.v1.Diagnostics+ 35, // 71: pasteferry.v1.DaemonService.SetVerboseLog:output_type -> pasteferry.v1.Status+ 47, // [47:72] is the sub-list for method output_type+ 22, // [22:47] is the sub-list for method input_type+ 22, // [22:22] is the sub-list for extension type_name+ 22, // [22:22] is the sub-list for extension extendee+ 0, // [0:22] is the sub-list for field type_name}func init() { file_pasteferry_v1_daemon_proto_init() }@@ -2905,14 +3181,15 @@ func file_pasteferry_v1_daemon_proto_init() {(*Event_DeviceChanged)(nil),(*Event_PermissionChanged)(nil),(*Event_StatusChanged)(nil),+ (*Event_ClipboardWritten)(nil),}type x struct{}out := protoimpl.TypeBuilder{File: protoimpl.DescBuilder{GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_pasteferry_v1_daemon_proto_rawDesc), len(file_pasteferry_v1_daemon_proto_rawDesc)),- NumEnums: 4,- NumMessages: 33,+ NumEnums: 5,+ NumMessages: 36,NumExtensions: 0,NumServices: 1,},diff --git a/proto/gen/pasteferry/v1/daemon_grpc.pb.go b/proto/gen/pasteferry/v1/daemon_grpc.pb.goindex 07fa0a1..58a1f7b 100644--- a/proto/gen/pasteferry/v1/daemon_grpc.pb.go+++ b/proto/gen/pasteferry/v1/daemon_grpc.pb.go@@ -43,6 +43,9 @@ const (DaemonService_GetStatus_FullMethodName = "/pasteferry.v1.DaemonService/GetStatus"DaemonService_RequestClipboardPermission_FullMethodName = "/pasteferry.v1.DaemonService/RequestClipboardPermission"DaemonService_RequestLocalNetworkPermission_FullMethodName = "/pasteferry.v1.DaemonService/RequestLocalNetworkPermission"+ DaemonService_GetNotificationStatus_FullMethodName = "/pasteferry.v1.DaemonService/GetNotificationStatus"+ DaemonService_RequestNotificationPermission_FullMethodName = "/pasteferry.v1.DaemonService/RequestNotificationPermission"+ DaemonService_ActivateNotification_FullMethodName = "/pasteferry.v1.DaemonService/ActivateNotification"DaemonService_GetNetwork_FullMethodName = "/pasteferry.v1.DaemonService/GetNetwork"DaemonService_ExportDiagnostics_FullMethodName = "/pasteferry.v1.DaemonService/ExportDiagnostics"DaemonService_SetVerboseLog_FullMethodName = "/pasteferry.v1.DaemonService/SetVerboseLog"@@ -83,6 +86,10 @@ type DaemonServiceClient interface {// 让系统放行局域网访问:macOS 打开「本地网络」设置面板;// Windows 申请管理员权限,在防火墙里放行后台服务。其他平台返回 UNIMPLEMENTED。RequestLocalNetworkPermission(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error)+ // These belong to the background service, which also notifies with the UI closed.+ GetNotificationStatus(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*NotificationStatus, error)+ RequestNotificationPermission(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*NotificationStatus, error)+ ActivateNotification(ctx context.Context, in *NotificationAction, opts ...grpc.CallOption) (*Empty, error)// 网络出口与打洞诊断:本机有几个出口、各自的公网地址,见 pasteferry-cli natGetNetwork(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*NetworkInfo, error)// 反馈问题用的诊断报告:版本、系统、设置、设备与网络状态、最近的日志。@@ -308,6 +315,36 @@ func (c *daemonServiceClient) RequestLocalNetworkPermission(ctx context.Context,return out, nil}+func (c *daemonServiceClient) GetNotificationStatus(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*NotificationStatus, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(NotificationStatus)+ err := c.cc.Invoke(ctx, DaemonService_GetNotificationStatus_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *daemonServiceClient) RequestNotificationPermission(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*NotificationStatus, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(NotificationStatus)+ err := c.cc.Invoke(ctx, DaemonService_RequestNotificationPermission_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *daemonServiceClient) ActivateNotification(ctx context.Context, in *NotificationAction, opts ...grpc.CallOption) (*Empty, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Empty)+ err := c.cc.Invoke(ctx, DaemonService_ActivateNotification_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}+func (c *daemonServiceClient) GetNetwork(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*NetworkInfo, error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)out := new(NetworkInfo)@@ -373,6 +410,10 @@ type DaemonServiceServer interface {// 让系统放行局域网访问:macOS 打开「本地网络」设置面板;// Windows 申请管理员权限,在防火墙里放行后台服务。其他平台返回 UNIMPLEMENTED。RequestLocalNetworkPermission(context.Context, *Empty) (*Empty, error)+ // These belong to the background service, which also notifies with the UI closed.+ GetNotificationStatus(context.Context, *Empty) (*NotificationStatus, error)+ RequestNotificationPermission(context.Context, *Empty) (*NotificationStatus, error)+ ActivateNotification(context.Context, *NotificationAction) (*Empty, error)// 网络出口与打洞诊断:本机有几个出口、各自的公网地址,见 pasteferry-cli natGetNetwork(context.Context, *Empty) (*NetworkInfo, error)// 反馈问题用的诊断报告:版本、系统、设置、设备与网络状态、最近的日志。@@ -447,6 +488,15 @@ func (UnimplementedDaemonServiceServer) RequestClipboardPermission(context.Contefunc (UnimplementedDaemonServiceServer) RequestLocalNetworkPermission(context.Context, *Empty) (*Empty, error) {return nil, status.Error(codes.Unimplemented, "method RequestLocalNetworkPermission not implemented")}+func (UnimplementedDaemonServiceServer) GetNotificationStatus(context.Context, *Empty) (*NotificationStatus, error) {+ return nil, status.Error(codes.Unimplemented, "method GetNotificationStatus not implemented")+}+func (UnimplementedDaemonServiceServer) RequestNotificationPermission(context.Context, *Empty) (*NotificationStatus, error) {+ return nil, status.Error(codes.Unimplemented, "method RequestNotificationPermission not implemented")+}+func (UnimplementedDaemonServiceServer) ActivateNotification(context.Context, *NotificationAction) (*Empty, error) {+ return nil, status.Error(codes.Unimplemented, "method ActivateNotification not implemented")+}func (UnimplementedDaemonServiceServer) GetNetwork(context.Context, *Empty) (*NetworkInfo, error) {return nil, status.Error(codes.Unimplemented, "method GetNetwork not implemented")}@@ -805,6 +855,60 @@ func _DaemonService_RequestLocalNetworkPermission_Handler(srv interface{}, ctx creturn interceptor(ctx, in, info, handler)}+func _DaemonService_GetNotificationStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(Empty)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).GetNotificationStatus(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_GetNotificationStatus_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).GetNotificationStatus(ctx, req.(*Empty))+ }+ return interceptor(ctx, in, info, handler)+}++func _DaemonService_RequestNotificationPermission_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(Empty)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).RequestNotificationPermission(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_RequestNotificationPermission_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).RequestNotificationPermission(ctx, req.(*Empty))+ }+ return interceptor(ctx, in, info, handler)+}++func _DaemonService_ActivateNotification_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(NotificationAction)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).ActivateNotification(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_ActivateNotification_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).ActivateNotification(ctx, req.(*NotificationAction))+ }+ return interceptor(ctx, in, info, handler)+}+func _DaemonService_GetNetwork_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {in := new(Empty)if err := dec(in); err != nil {@@ -934,6 +1038,18 @@ var DaemonService_ServiceDesc = grpc.ServiceDesc{MethodName: "RequestLocalNetworkPermission",Handler: _DaemonService_RequestLocalNetworkPermission_Handler,},+ {+ MethodName: "GetNotificationStatus",+ Handler: _DaemonService_GetNotificationStatus_Handler,+ },+ {+ MethodName: "RequestNotificationPermission",+ Handler: _DaemonService_RequestNotificationPermission_Handler,+ },+ {+ MethodName: "ActivateNotification",+ Handler: _DaemonService_ActivateNotification_Handler,+ },{MethodName: "GetNetwork",Handler: _DaemonService_GetNetwork_Handler,diff --git a/proto/pasteferry/v1/daemon.proto b/proto/pasteferry/v1/daemon.protoindex dab9c31..6ba4115 100644--- a/proto/pasteferry/v1/daemon.proto+++ b/proto/pasteferry/v1/daemon.proto@@ -47,6 +47,11 @@ service DaemonService {// Windows 申请管理员权限,在防火墙里放行后台服务。其他平台返回 UNIMPLEMENTED。rpc RequestLocalNetworkPermission(Empty) returns (Empty);+ // These belong to the background service, which also notifies with the UI closed.+ rpc GetNotificationStatus(Empty) returns (NotificationStatus);+ rpc RequestNotificationPermission(Empty) returns (NotificationStatus);+ rpc ActivateNotification(NotificationAction) returns (Empty);+// 网络出口与打洞诊断:本机有几个出口、各自的公网地址,见 pasteferry-cli natrpc GetNetwork(Empty) returns (NetworkInfo);@@ -163,9 +168,36 @@ message Event {Device device_changed = 5;ClipboardPermission permission_changed = 6;Status status_changed = 7;+ ClipboardWriteResult clipboard_written = 8;}}+message NotificationStatus {+ bool supported = 1;+ bool actions_supported = 2;+ // unknown, not_requested, allowed, denied, unavailable+ string permission = 3;+}++message NotificationAction {+ string clip_id = 1;+ string action = 2; // receive, apply, open+}++enum ClipboardWriteOutcome {+ CLIPBOARD_WRITE_OUTCOME_UNSPECIFIED = 0;+ CLIPBOARD_WRITE_OUTCOME_APPLIED = 1;+ CLIPBOARD_WRITE_OUTCOME_PRESERVED = 2;+ CLIPBOARD_WRITE_OUTCOME_FAILED = 3;+}++// READY still means downloaded, not necessarily the current system clipboard.+message ClipboardWriteResult {+ string clip_id = 1;+ ClipboardWriteOutcome outcome = 2;+ string error = 3;+}+// ─────────────────────────── 查询与操作 ───────────────────────────message ListHistoryRequest {diff --git a/scripts/build-windows.ps1 b/scripts/build-windows.ps1index 39c2e8b..4bf7b4b 100644--- a/scripts/build-windows.ps1+++ b/scripts/build-windows.ps1@@ -1,86 +1,87 @@-# 在 Windows 上构建 PasteFerry,产物放在 dist\windows\:-#-# PasteFerry\ 可以直接运行的目录:界面、后台服务、命令行工具-# PasteFerry-Setup.exe 安装程序(需要 Inno Setup 6)-# PasteFerry-windows-x64.zip 便携版-#-# powershell -ExecutionPolicy Bypass -File scripts\build-windows.ps1 [-Version 1.3.2]-#-# 需要 Go、Flutter 与 Visual Studio(「使用 C++ 的桌面开发」)。-# 后台服务是纯 Go,也可以在 Mac 上交叉编译;界面只能在 Windows 上构建。--param([string]$Version)--$ErrorActionPreference = 'Stop'-$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path-Set-Location $root--# 版本号与 Mac 版共用 scripts/build.sh 里的那一个-if (-not $Version) {- $m = Select-String -Path scripts\build.sh -Pattern 'VERSION=\$\{VERSION:-([0-9.]+)\}'- $Version = $m.Matches[0].Groups[1].Value-}--$out = Join-Path $root 'dist\windows'-$app = Join-Path $out 'PasteFerry'-if (Test-Path $out) { Remove-Item -Recurse -Force $out }-New-Item -ItemType Directory -Force $app | Out-Null--function Invoke-Checked([scriptblock]$cmd, [string]$what) {- & $cmd- if ($LASTEXITCODE -ne 0) { throw "$what 失败(退出码 $LASTEXITCODE)" }-}--Write-Host "▶ 构建后台服务与命令行工具($Version)"-$env:CGO_ENABLED = '0'; $env:GOOS = 'windows'; $env:GOARCH = 'amd64'-Push-Location client-core-try {- # -H=windowsgui:后台服务没有控制台窗口,开机自启时不会闪一下黑框- Invoke-Checked { go build -trimpath -ldflags "-s -w -H=windowsgui -X main.version=$Version" -o "$app\pasteferryd.exe" ./cmd/pasteferryd } 'go build pasteferryd'- Invoke-Checked { go build -trimpath -ldflags '-s -w' -o "$app\pasteferry-cli.exe" ./cmd/pasteferry-cli } 'go build pasteferry-cli'-} finally {- Pop-Location- Remove-Item Env:CGO_ENABLED, Env:GOOS, Env:GOARCH-}--Write-Host '▶ 构建图形界面'-Push-Location ui-try {- Invoke-Checked { flutter build windows --release --build-name $Version "--dart-define=APP_VERSION=$Version" } 'flutter build windows'-} finally {- Pop-Location-}-Copy-Item -Recurse -Force 'ui\build\windows\x64\runner\Release\*' $app--# 界面程序依赖 VC++ 运行库(msvcp140 等三个 DLL),Windows 不一定自带,缺了就打不开。-# 按微软的「应用本地部署」放在 exe 旁边:不用装系统级的运行库,也就不需要管理员权限-Write-Host '▶ 附带 VC++ 运行库'-$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"-$vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath-$crt = Get-ChildItem "$vs\VC\Redist\MSVC\*\x64\Microsoft.VC*.CRT" -Directory -ErrorAction SilentlyContinue |- Where-Object { $_.Parent.Parent.Name -as [version] } |- Sort-Object { $_.Parent.Parent.Name -as [version] } -Descending | Select-Object -First 1-if (-not $crt) { throw "在 $vs 里没有找到 VC++ 运行库(VC\Redist\MSVC\<版本>\x64\Microsoft.VC*.CRT)" }-foreach ($dll in 'msvcp140.dll', 'vcruntime140.dll', 'vcruntime140_1.dll') {- Copy-Item (Join-Path $crt.FullName $dll) $app-}-Write-Host " $($crt.FullName)"--Write-Host '▶ 打包'-Compress-Archive -Path $app -DestinationPath (Join-Path $out 'PasteFerry-windows-x64.zip')--$iscc = Get-Command iscc.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source-if (-not $iscc) {- $iscc = @(- "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe",- "$env:ProgramFiles\Inno Setup 6\ISCC.exe",- "$env:LOCALAPPDATA\Programs\Inno Setup 6\ISCC.exe"- ) | Where-Object { Test-Path $_ } | Select-Object -First 1-}-if ($iscc) {- Invoke-Checked { & $iscc /Qp "/DAppVersion=$Version" "/DSourceDir=$app" "/DOutputDir=$out" tools\installer\pasteferry.iss } 'Inno Setup'-} else {- Write-Warning '没有找到 Inno Setup 6,跳过安装程序,只出便携版 zip'-}--Get-ChildItem $out -File | ForEach-Object { Write-Host " ✓ $($_.Name) $([math]::Round($_.Length / 1MB, 1)) MB" }+# 在 Windows 上构建 PasteFerry,产物放在 dist\windows\:+#+# PasteFerry\ 可以直接运行的目录:界面、后台服务、命令行工具+# PasteFerry-Setup.exe 安装程序(需要 Inno Setup 6)+# PasteFerry-windows-x64.zip 便携版+#+# powershell -ExecutionPolicy Bypass -File scripts\build-windows.ps1 [-Version 1.3.2]+#+# 需要 Go、Flutter 与 Visual Studio(「使用 C++ 的桌面开发」)。+# 后台服务是纯 Go,也可以在 Mac 上交叉编译;界面只能在 Windows 上构建。++param([string]$Version)++$ErrorActionPreference = 'Stop'+$AppBuild = if ($env:APP_BUILD) { $env:APP_BUILD } else { git -C $PSScriptRoot rev-parse --short=8 HEAD }+$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path+Set-Location $root++# 版本号与 Mac 版共用 scripts/build.sh 里的那一个+if (-not $Version) {+ $m = Select-String -Path scripts\build.sh -Pattern 'VERSION=\$\{VERSION:-([0-9.]+)\}'+ $Version = $m.Matches[0].Groups[1].Value+}++$out = Join-Path $root 'dist\windows'+$app = Join-Path $out 'PasteFerry'+if (Test-Path $out) { Remove-Item -Recurse -Force $out }+New-Item -ItemType Directory -Force $app | Out-Null++function Invoke-Checked([scriptblock]$cmd, [string]$what) {+ & $cmd+ if ($LASTEXITCODE -ne 0) { throw "$what 失败(退出码 $LASTEXITCODE)" }+}++Write-Host "▶ 构建后台服务与命令行工具($Version)"+$env:CGO_ENABLED = '0'; $env:GOOS = 'windows'; $env:GOARCH = 'amd64'+Push-Location client-core+try {+ # -H=windowsgui:后台服务没有控制台窗口,开机自启时不会闪一下黑框+ Invoke-Checked { go build -trimpath -ldflags "-s -w -H=windowsgui -X main.version=$Version" -o "$app\pasteferryd.exe" ./cmd/pasteferryd } 'go build pasteferryd'+ Invoke-Checked { go build -trimpath -ldflags '-s -w' -o "$app\pasteferry-cli.exe" ./cmd/pasteferry-cli } 'go build pasteferry-cli'+} finally {+ Pop-Location+ Remove-Item Env:CGO_ENABLED, Env:GOOS, Env:GOARCH+}++Write-Host '▶ 构建图形界面'+Push-Location ui+try {+ Invoke-Checked { flutter build windows --release --build-name $Version "--dart-define=APP_VERSION=$Version" "--dart-define=APP_BUILD=$AppBuild" } 'flutter build windows'+} finally {+ Pop-Location+}+Copy-Item -Recurse -Force 'ui\build\windows\x64\runner\Release\*' $app++# 界面程序依赖 VC++ 运行库(msvcp140 等三个 DLL),Windows 不一定自带,缺了就打不开。+# 按微软的「应用本地部署」放在 exe 旁边:不用装系统级的运行库,也就不需要管理员权限+Write-Host '▶ 附带 VC++ 运行库'+$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"+$vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath+$crt = Get-ChildItem "$vs\VC\Redist\MSVC\*\x64\Microsoft.VC*.CRT" -Directory -ErrorAction SilentlyContinue |+ Where-Object { $_.Parent.Parent.Name -as [version] } |+ Sort-Object { $_.Parent.Parent.Name -as [version] } -Descending | Select-Object -First 1+if (-not $crt) { throw "在 $vs 里没有找到 VC++ 运行库(VC\Redist\MSVC\<版本>\x64\Microsoft.VC*.CRT)" }+foreach ($dll in 'msvcp140.dll', 'vcruntime140.dll', 'vcruntime140_1.dll') {+ Copy-Item (Join-Path $crt.FullName $dll) $app+}+Write-Host " $($crt.FullName)"++Write-Host '▶ 打包'+Compress-Archive -Path $app -DestinationPath (Join-Path $out 'PasteFerry-windows-x64.zip')++$iscc = Get-Command iscc.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source+if (-not $iscc) {+ $iscc = @(+ "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe",+ "$env:ProgramFiles\Inno Setup 6\ISCC.exe",+ "$env:LOCALAPPDATA\Programs\Inno Setup 6\ISCC.exe"+ ) | Where-Object { Test-Path $_ } | Select-Object -First 1+}+if ($iscc) {+ Invoke-Checked { & $iscc /Qp "/DAppVersion=$Version" "/DSourceDir=$app" "/DOutputDir=$out" tools\installer\pasteferry.iss } 'Inno Setup'+} else {+ Write-Warning '没有找到 Inno Setup 6,跳过安装程序,只出便携版 zip'+}++Get-ChildItem $out -File | ForEach-Object { Write-Host " ✓ $($_.Name) $([math]::Round($_.Length / 1MB, 1)) MB" }diff --git a/scripts/build.sh b/scripts/build.shindex efcfc2b..d970782 100755--- a/scripts/build.sh+++ b/scripts/build.sh@@ -15,6 +15,7 @@ cd "$(dirname "$0")/.."DIST=distVERSION=${VERSION:-2.0.0}+APP_BUILD=${APP_BUILD:-$(git rev-parse --short=8 HEAD)}rm -rf "$DIST" && mkdir -p "$DIST"# 支持的最低 macOS 版本,与界面工程的 MACOSX_DEPLOYMENT_TARGET、后台服务的 LSMinimumSystemVersion 一致。@@ -97,7 +98,8 @@ echo " ✓ $APP"echo "▶ 构建图形界面"(cd ui && flutter build macos --release \- --build-name "$VERSION" --dart-define=APP_VERSION="$VERSION" 2>&1 | tail -1)+ --build-name "$VERSION" --dart-define=APP_VERSION="$VERSION" \+ --dart-define=APP_BUILD="$APP_BUILD" 2>&1 | tail -1)UI="$DIST/PasteFerry.app"cp -R ui/build/macos/Build/Products/Release/PasteFerry.app "$UI"diff --git a/scripts/package-linux.sh b/scripts/package-linux.shindex c70eb00..4c36298 100755--- a/scripts/package-linux.sh+++ b/scripts/package-linux.sh@@ -17,6 +17,7 @@ set -euo pipefailcd "$(dirname "$0")/.."VERSION=${VERSION:-$(sed -n 's/^VERSION=\${VERSION:-\(.*\)}$/\1/p' scripts/build.sh)}+APP_BUILD=${APP_BUILD:-$(git rev-parse --short=8 HEAD)}case "$(uname -m)" inx86_64) ARCH=amd64 FLUTTER_ARCH=x64 ;;aarch64 | arm64) ARCH=arm64 FLUTTER_ARCH=arm64 ;;@@ -37,7 +38,8 @@ echo "▶ 后台服务与命令行($VERSION,$ARCH)"(cd client-core && CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" -o "../$APP/pasteferry-cli" ./cmd/pasteferry-cli)echo "▶ 界面"-(cd ui && flutter build linux --release --build-name "$VERSION" --dart-define=APP_VERSION="$VERSION")+(cd ui && flutter build linux --release --build-name "$VERSION" --dart-define=APP_VERSION="$VERSION" \+ --dart-define=APP_BUILD="$APP_BUILD")cp -R "ui/build/linux/$FLUTTER_ARCH/release/bundle/." "$APP/"# ── tar.gz:解压即用 ──diff --git a/tools/installer/pasteferry.iss b/tools/installer/pasteferry.issindex 8218362..af8c80e 100644--- a/tools/installer/pasteferry.iss+++ b/tools/installer/pasteferry.iss@@ -71,6 +71,8 @@ Name: "{autodesktop}\PasteFerry"; Filename: "{app}\PasteFerry.exe"; 卸载时删掉开机自启项与窗口位置记录。ValueType: none 表示安装时不写,只在卸载时删Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueName: "PasteFerry"; ValueType: none; Flags: uninsdeletevalueRoot: HKCU; Subkey: "Software\PasteFerry"; ValueType: none; Flags: uninsdeletekey+Root: HKCU; Subkey: "Software\Classes\pasteferry-notify"; ValueType: none; Flags: uninsdeletekey+Root: HKCU; Subkey: "Software\Classes\AppUserModelId\PasteFerry.Desktop"; ValueType: none; Flags: uninsdeletekey[Run]; 升级前停掉了后台服务;之前启用过后台同步的话,装完立刻重新拉起,不必等用户打开界面diff --git a/ui/lib/app_state.dart b/ui/lib/app_state.dartindex c61940b..5f5a12d 100644--- a/ui/lib/app_state.dart+++ b/ui/lib/app_state.dart@@ -41,6 +41,10 @@ class AppState extends ChangeNotifier {/// 正在传输的记录的进度(0–1),只在界面上展示,传完即移除。final Map<String, double> _progress = {};+ final Map<String, ClipboardWriteResult> _clipboardResults = {};+ NotificationStatus? _notificationStatus;+ NotificationStatus? get notificationStatus => _notificationStatus;+ ClipboardWriteResult? clipboardResultOf(String id) => _clipboardResults[id];/// 复制记录的搜索:搜索词,以及后台服务返回的结果(还没出结果时为 null)。/// 界面只加载最新的 200 条,更早的记录只有后台服务能搜到,所以不在界面里筛选。@@ -127,6 +131,7 @@ class AppState extends ChangeNotifier {_status = results[2] as Status;await _loadDevices();+ await refreshNotificationStatus();_events = conn.client.subscribe(SubscribeRequest()).listen(_onEvent,@@ -287,8 +292,12 @@ class AppState extends ChangeNotifier {case Event_Payload.clipRemoved:_records.removeWhere((r) => r.id == ev.clipRemoved);+ _clipboardResults.remove(ev.clipRemoved);_searchResults?.removeWhere((r) => r.id == ev.clipRemoved);+ case Event_Payload.clipboardWritten:+ _clipboardResults[ev.clipboardWritten.clipId] = ev.clipboardWritten;+case Event_Payload.deviceChanged:_onDeviceChanged(ev.deviceChanged);@@ -305,6 +314,7 @@ class AppState extends ChangeNotifier {}void _upsert(ClipRecord r) {+ if (r.status == ClipStatus.CLIP_STATUS_FETCHING) _clipboardResults.remove(r.id);final i = _records.indexWhere((x) => x.id == r.id);if (i >= 0) {_records[i] = r;@@ -518,6 +528,25 @@ class AppState extends ChangeNotifier {return true;}+ Future<void> refreshNotificationStatus() async {+ final conn = _conn;+ if (conn == null) return;+ try {+ final status = await conn.client.getNotificationStatus(Empty(),+ options: CallOptions(timeout: const Duration(seconds: 12)));+ if (_conn == conn) _notificationStatus = status;+ } on GrpcError {+ if (_conn == conn) _notificationStatus = NotificationStatus(permission: 'unavailable');+ }+ if (_conn == conn) notifyListeners();+ }++ Future<void> requestNotifications() async {+ _notificationStatus = await _client.requestNotificationPermission(Empty(),+ options: CallOptions(timeout: const Duration(seconds: 20)));+ notifyListeners();+ }+Future<void> fetch(String clipId) =>_client.fetch(FetchRequest(clipId: clipId));diff --git a/ui/lib/background_service.dart b/ui/lib/background_service.dartindex 4988e79..0be306b 100644--- a/ui/lib/background_service.dart+++ b/ui/lib/background_service.dart@@ -7,6 +7,7 @@ import 'i18n.dart';/// 构建时注入的版本号(build.sh 传 --dart-define=APP_VERSION)。/// 用来判断后台服务是不是跟界面同一个版本。const appVersion = String.fromEnvironment('APP_VERSION', defaultValue: 'dev');+const appBuild = String.fromEnvironment('APP_BUILD');/// 后台服务的安装状态。enum ServiceState {diff --git a/ui/lib/gen/pasteferry/v1/daemon.pb.dart b/ui/lib/gen/pasteferry/v1/daemon.pb.dartindex 81a8f04..97c358f 100644--- a/ui/lib/gen/pasteferry/v1/daemon.pb.dart+++ b/ui/lib/gen/pasteferry/v1/daemon.pb.dart@@ -652,6 +652,7 @@ enum Event_Payload {deviceChanged,permissionChanged,statusChanged,+ clipboardWritten,notSet}@@ -664,6 +665,7 @@ class Event extends $pb.GeneratedMessage {Device? deviceChanged,ClipboardPermission? permissionChanged,Status? statusChanged,+ ClipboardWriteResult? clipboardWritten,}) {final result = Event._();if (clipAdded != null) result.clipAdded = clipAdded;@@ -673,6 +675,7 @@ class Event extends $pb.GeneratedMessage {if (deviceChanged != null) result.deviceChanged = deviceChanged;if (permissionChanged != null) result.permissionChanged = permissionChanged;if (statusChanged != null) result.statusChanged = statusChanged;+ if (clipboardWritten != null) result.clipboardWritten = clipboardWritten;return result;}@@ -693,13 +696,14 @@ class Event extends $pb.GeneratedMessage {5: Event_Payload.deviceChanged,6: Event_Payload.permissionChanged,7: Event_Payload.statusChanged,+ 8: Event_Payload.clipboardWritten,0: Event_Payload.notSet};static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Event',package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),createEmptyInstance: Event.$_createMessage)- ..oo(0, [1, 2, 3, 4, 5, 6, 7])+ ..oo(0, [1, 2, 3, 4, 5, 6, 7, 8])..aOM<ClipRecord>(1, _omitFieldNames ? '' : 'clipAdded',subBuilder: ClipRecord.$_createMessage)..aOM<ClipRecord>(2, _omitFieldNames ? '' : 'clipUpdated',@@ -713,6 +717,8 @@ class Event extends $pb.GeneratedMessage {enumValues: ClipboardPermission.values)..aOM<Status>(7, _omitFieldNames ? '' : 'statusChanged',subBuilder: Status.$_createMessage)+ ..aOM<ClipboardWriteResult>(8, _omitFieldNames ? '' : 'clipboardWritten',+ subBuilder: ClipboardWriteResult.$_createMessage)..hasRequiredFields = false;@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')@@ -742,6 +748,7 @@ class Event extends $pb.GeneratedMessage {@$pb.TagNumber(5)@$pb.TagNumber(6)@$pb.TagNumber(7)+ @$pb.TagNumber(8)Event_Payload whichPayload() => _Event_PayloadByTag[$_whichOneof(0)]!;@$pb.TagNumber(1)@$pb.TagNumber(2)@@ -750,6 +757,7 @@ class Event extends $pb.GeneratedMessage {@$pb.TagNumber(5)@$pb.TagNumber(6)@$pb.TagNumber(7)+ @$pb.TagNumber(8)void clearPayload() => $_clearField($_whichOneof(0));@$pb.TagNumber(1)@@ -824,6 +832,252 @@ class Event extends $pb.GeneratedMessage {void clearStatusChanged() => $_clearField(7);@$pb.TagNumber(7)Status ensureStatusChanged() => $_ensure(6);++ @$pb.TagNumber(8)+ ClipboardWriteResult get clipboardWritten => $_getN(7);+ @$pb.TagNumber(8)+ set clipboardWritten(ClipboardWriteResult value) => $_setField(8, value);+ @$pb.TagNumber(8)+ $core.bool hasClipboardWritten() => $_has(7);+ @$pb.TagNumber(8)+ void clearClipboardWritten() => $_clearField(8);+ @$pb.TagNumber(8)+ ClipboardWriteResult ensureClipboardWritten() => $_ensure(7);+}++class NotificationStatus extends $pb.GeneratedMessage {+ factory NotificationStatus({+ $core.bool? supported,+ $core.bool? actionsSupported,+ $core.String? permission,+ }) {+ final result = NotificationStatus._();+ if (supported != null) result.supported = supported;+ if (actionsSupported != null) result.actionsSupported = actionsSupported;+ if (permission != null) result.permission = permission;+ return result;+ }++ NotificationStatus._();++ factory NotificationStatus.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ NotificationStatus()..mergeFromBuffer(data, registry);+ factory NotificationStatus.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ NotificationStatus()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'NotificationStatus',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),+ createEmptyInstance: NotificationStatus.$_createMessage)+ ..aOB(1, _omitFieldNames ? '' : 'supported')+ ..aOB(2, _omitFieldNames ? '' : 'actionsSupported')+ ..aOS(3, _omitFieldNames ? '' : 'permission')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ NotificationStatus clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ NotificationStatus copyWith(void Function(NotificationStatus) updates) =>+ super.copyWith((message) => updates(message as NotificationStatus))+ as NotificationStatus;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use NotificationStatus() / NotificationStatus.new instead')+ static NotificationStatus create() => NotificationStatus._();+ static $pb.GeneratedMessage $_createMessage() => NotificationStatus._();+ @$core.override+ NotificationStatus createEmptyInstance() => NotificationStatus._();+ @$core.pragma('dart2js:noInline')+ static NotificationStatus getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<NotificationStatus>(+ NotificationStatus.$_createMessage);+ static NotificationStatus? _defaultInstance;++ @$pb.TagNumber(1)+ $core.bool get supported => $_getBF(0);+ @$pb.TagNumber(1)+ set supported($core.bool value) => $_setBool(0, value);+ @$pb.TagNumber(1)+ $core.bool hasSupported() => $_has(0);+ @$pb.TagNumber(1)+ void clearSupported() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.bool get actionsSupported => $_getBF(1);+ @$pb.TagNumber(2)+ set actionsSupported($core.bool value) => $_setBool(1, value);+ @$pb.TagNumber(2)+ $core.bool hasActionsSupported() => $_has(1);+ @$pb.TagNumber(2)+ void clearActionsSupported() => $_clearField(2);++ /// unknown, not_requested, allowed, denied, unavailable+ @$pb.TagNumber(3)+ $core.String get permission => $_getSZ(2);+ @$pb.TagNumber(3)+ set permission($core.String value) => $_setString(2, value);+ @$pb.TagNumber(3)+ $core.bool hasPermission() => $_has(2);+ @$pb.TagNumber(3)+ void clearPermission() => $_clearField(3);+}++class NotificationAction extends $pb.GeneratedMessage {+ factory NotificationAction({+ $core.String? clipId,+ $core.String? action,+ }) {+ final result = NotificationAction._();+ if (clipId != null) result.clipId = clipId;+ if (action != null) result.action = action;+ return result;+ }++ NotificationAction._();++ factory NotificationAction.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ NotificationAction()..mergeFromBuffer(data, registry);+ factory NotificationAction.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ NotificationAction()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'NotificationAction',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),+ createEmptyInstance: NotificationAction.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'clipId')+ ..aOS(2, _omitFieldNames ? '' : 'action')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ NotificationAction clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ NotificationAction copyWith(void Function(NotificationAction) updates) =>+ super.copyWith((message) => updates(message as NotificationAction))+ as NotificationAction;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use NotificationAction() / NotificationAction.new instead')+ static NotificationAction create() => NotificationAction._();+ static $pb.GeneratedMessage $_createMessage() => NotificationAction._();+ @$core.override+ NotificationAction createEmptyInstance() => NotificationAction._();+ @$core.pragma('dart2js:noInline')+ static NotificationAction getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<NotificationAction>(+ NotificationAction.$_createMessage);+ static NotificationAction? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get clipId => $_getSZ(0);+ @$pb.TagNumber(1)+ set clipId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasClipId() => $_has(0);+ @$pb.TagNumber(1)+ void clearClipId() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get action => $_getSZ(1);+ @$pb.TagNumber(2)+ set action($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasAction() => $_has(1);+ @$pb.TagNumber(2)+ void clearAction() => $_clearField(2);+}++/// READY still means downloaded, not necessarily the current system clipboard.+class ClipboardWriteResult extends $pb.GeneratedMessage {+ factory ClipboardWriteResult({+ $core.String? clipId,+ ClipboardWriteOutcome? outcome,+ $core.String? error,+ }) {+ final result = ClipboardWriteResult._();+ if (clipId != null) result.clipId = clipId;+ if (outcome != null) result.outcome = outcome;+ if (error != null) result.error = error;+ return result;+ }++ ClipboardWriteResult._();++ factory ClipboardWriteResult.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ClipboardWriteResult()..mergeFromBuffer(data, registry);+ factory ClipboardWriteResult.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ClipboardWriteResult()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'ClipboardWriteResult',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),+ createEmptyInstance: ClipboardWriteResult.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'clipId')+ ..aE<ClipboardWriteOutcome>(2, _omitFieldNames ? '' : 'outcome',+ enumValues: ClipboardWriteOutcome.values)+ ..aOS(3, _omitFieldNames ? '' : 'error')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ClipboardWriteResult clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ClipboardWriteResult copyWith(void Function(ClipboardWriteResult) updates) =>+ super.copyWith((message) => updates(message as ClipboardWriteResult))+ as ClipboardWriteResult;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated(+ 'Use ClipboardWriteResult() / ClipboardWriteResult.new instead')+ static ClipboardWriteResult create() => ClipboardWriteResult._();+ static $pb.GeneratedMessage $_createMessage() => ClipboardWriteResult._();+ @$core.override+ ClipboardWriteResult createEmptyInstance() => ClipboardWriteResult._();+ @$core.pragma('dart2js:noInline')+ static ClipboardWriteResult getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<ClipboardWriteResult>(+ ClipboardWriteResult.$_createMessage);+ static ClipboardWriteResult? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get clipId => $_getSZ(0);+ @$pb.TagNumber(1)+ set clipId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasClipId() => $_has(0);+ @$pb.TagNumber(1)+ void clearClipId() => $_clearField(1);++ @$pb.TagNumber(2)+ ClipboardWriteOutcome get outcome => $_getN(1);+ @$pb.TagNumber(2)+ set outcome(ClipboardWriteOutcome value) => $_setField(2, value);+ @$pb.TagNumber(2)+ $core.bool hasOutcome() => $_has(1);+ @$pb.TagNumber(2)+ void clearOutcome() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.String get error => $_getSZ(2);+ @$pb.TagNumber(3)+ set error($core.String value) => $_setString(2, value);+ @$pb.TagNumber(3)+ $core.bool hasError() => $_has(2);+ @$pb.TagNumber(3)+ void clearError() => $_clearField(3);}class ListHistoryRequest extends $pb.GeneratedMessage {diff --git a/ui/lib/gen/pasteferry/v1/daemon.pbenum.dart b/ui/lib/gen/pasteferry/v1/daemon.pbenum.dartindex 0850fcc..af9ec99 100644--- a/ui/lib/gen/pasteferry/v1/daemon.pbenum.dart+++ b/ui/lib/gen/pasteferry/v1/daemon.pbenum.dart@@ -137,5 +137,35 @@ class ClipboardPermission extends $pb.ProtobufEnum {const ClipboardPermission._(super.value, super.name);}+class ClipboardWriteOutcome extends $pb.ProtobufEnum {+ static const ClipboardWriteOutcome CLIPBOARD_WRITE_OUTCOME_UNSPECIFIED =+ ClipboardWriteOutcome._(+ 0, _omitEnumNames ? '' : 'CLIPBOARD_WRITE_OUTCOME_UNSPECIFIED');+ static const ClipboardWriteOutcome CLIPBOARD_WRITE_OUTCOME_APPLIED =+ ClipboardWriteOutcome._(+ 1, _omitEnumNames ? '' : 'CLIPBOARD_WRITE_OUTCOME_APPLIED');+ static const ClipboardWriteOutcome CLIPBOARD_WRITE_OUTCOME_PRESERVED =+ ClipboardWriteOutcome._(+ 2, _omitEnumNames ? '' : 'CLIPBOARD_WRITE_OUTCOME_PRESERVED');+ static const ClipboardWriteOutcome CLIPBOARD_WRITE_OUTCOME_FAILED =+ ClipboardWriteOutcome._(+ 3, _omitEnumNames ? '' : 'CLIPBOARD_WRITE_OUTCOME_FAILED');++ static const $core.List<ClipboardWriteOutcome> values =+ <ClipboardWriteOutcome>[+ CLIPBOARD_WRITE_OUTCOME_UNSPECIFIED,+ CLIPBOARD_WRITE_OUTCOME_APPLIED,+ CLIPBOARD_WRITE_OUTCOME_PRESERVED,+ CLIPBOARD_WRITE_OUTCOME_FAILED,+ ];++ static final $core.List<ClipboardWriteOutcome?> _byValue =+ $pb.ProtobufEnum.$_initByValueList(values, 3);+ static ClipboardWriteOutcome? valueOf($core.int value) =>+ value < 0 || value >= _byValue.length ? null : _byValue[value];++ const ClipboardWriteOutcome._(super.value, super.name);+}+const $core.bool _omitEnumNames =$core.bool.fromEnvironment('protobuf.omit_enum_names');diff --git a/ui/lib/gen/pasteferry/v1/daemon.pbgrpc.dart b/ui/lib/gen/pasteferry/v1/daemon.pbgrpc.dartindex af5d032..7f0f219 100644--- a/ui/lib/gen/pasteferry/v1/daemon.pbgrpc.dart+++ b/ui/lib/gen/pasteferry/v1/daemon.pbgrpc.dart@@ -183,6 +183,29 @@ class DaemonServiceClient extends $grpc.Client {options: options);}+ /// These belong to the background service, which also notifies with the UI closed.+ $grpc.ResponseFuture<$0.NotificationStatus> getNotificationStatus(+ $0.Empty request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$getNotificationStatus, request, options: options);+ }++ $grpc.ResponseFuture<$0.NotificationStatus> requestNotificationPermission(+ $0.Empty request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$requestNotificationPermission, request,+ options: options);+ }++ $grpc.ResponseFuture<$0.Empty> activateNotification(+ $0.NotificationAction request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$activateNotification, request, options: options);+ }+/// 网络出口与打洞诊断:本机有几个出口、各自的公网地址,见 pasteferry-cli nat$grpc.ResponseFuture<$0.NetworkInfo> getNetwork($0.Empty request, {@@ -298,6 +321,21 @@ class DaemonServiceClient extends $grpc.Client {'/pasteferry.v1.DaemonService/RequestLocalNetworkPermission',($0.Empty value) => value.writeToBuffer(),$0.Empty.fromBuffer);+ static final _$getNotificationStatus =+ $grpc.ClientMethod<$0.Empty, $0.NotificationStatus>(+ '/pasteferry.v1.DaemonService/GetNotificationStatus',+ ($0.Empty value) => value.writeToBuffer(),+ $0.NotificationStatus.fromBuffer);+ static final _$requestNotificationPermission =+ $grpc.ClientMethod<$0.Empty, $0.NotificationStatus>(+ '/pasteferry.v1.DaemonService/RequestNotificationPermission',+ ($0.Empty value) => value.writeToBuffer(),+ $0.NotificationStatus.fromBuffer);+ static final _$activateNotification =+ $grpc.ClientMethod<$0.NotificationAction, $0.Empty>(+ '/pasteferry.v1.DaemonService/ActivateNotification',+ ($0.NotificationAction value) => value.writeToBuffer(),+ $0.Empty.fromBuffer);static final _$getNetwork = $grpc.ClientMethod<$0.Empty, $0.NetworkInfo>('/pasteferry.v1.DaemonService/GetNetwork',($0.Empty value) => value.writeToBuffer(),@@ -464,6 +502,28 @@ abstract class DaemonServiceBase extends $grpc.Service {false,($core.List<$core.int> value) => $0.Empty.fromBuffer(value),($0.Empty value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.Empty, $0.NotificationStatus>(+ 'GetNotificationStatus',+ getNotificationStatus_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.Empty.fromBuffer(value),+ ($0.NotificationStatus value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.Empty, $0.NotificationStatus>(+ 'RequestNotificationPermission',+ requestNotificationPermission_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.Empty.fromBuffer(value),+ ($0.NotificationStatus value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.NotificationAction, $0.Empty>(+ 'ActivateNotification',+ activateNotification_Pre,+ false,+ false,+ ($core.List<$core.int> value) =>+ $0.NotificationAction.fromBuffer(value),+ ($0.Empty value) => value.writeToBuffer()));$addMethod($grpc.ServiceMethod<$0.Empty, $0.NetworkInfo>('GetNetwork',getNetwork_Pre,@@ -642,6 +702,30 @@ abstract class DaemonServiceBase extends $grpc.Service {$async.Future<$0.Empty> requestLocalNetworkPermission($grpc.ServiceCall call, $0.Empty request);+ $async.Future<$0.NotificationStatus> getNotificationStatus_Pre(+ $grpc.ServiceCall $call, $async.Future<$0.Empty> $request) async {+ return getNotificationStatus($call, await $request);+ }++ $async.Future<$0.NotificationStatus> getNotificationStatus(+ $grpc.ServiceCall call, $0.Empty request);++ $async.Future<$0.NotificationStatus> requestNotificationPermission_Pre(+ $grpc.ServiceCall $call, $async.Future<$0.Empty> $request) async {+ return requestNotificationPermission($call, await $request);+ }++ $async.Future<$0.NotificationStatus> requestNotificationPermission(+ $grpc.ServiceCall call, $0.Empty request);++ $async.Future<$0.Empty> activateNotification_Pre($grpc.ServiceCall $call,+ $async.Future<$0.NotificationAction> $request) async {+ return activateNotification($call, await $request);+ }++ $async.Future<$0.Empty> activateNotification(+ $grpc.ServiceCall call, $0.NotificationAction request);+$async.Future<$0.NetworkInfo> getNetwork_Pre($grpc.ServiceCall $call, $async.Future<$0.Empty> $request) async {return getNetwork($call, await $request);diff --git a/ui/lib/gen/pasteferry/v1/daemon.pbjson.dart b/ui/lib/gen/pasteferry/v1/daemon.pbjson.dartindex 85d84c1..f762140 100644--- a/ui/lib/gen/pasteferry/v1/daemon.pbjson.dart+++ b/ui/lib/gen/pasteferry/v1/daemon.pbjson.dart@@ -91,6 +91,24 @@ final $typed_data.Uint8List clipboardPermissionDescriptor = $convert.base64Decod'ohQ0xJUEJPQVJEX1BFUk1JU1NJT05fQUxXQVlTX0FMTE9XEAQSJAogQ0xJUEJPQVJEX1BFUk1J''U1NJT05fQUxXQVlTX0RFTlkQBQ==');+@$core.Deprecated('Use clipboardWriteOutcomeDescriptor instead')+const ClipboardWriteOutcome$json = {+ '1': 'ClipboardWriteOutcome',+ '2': [+ {'1': 'CLIPBOARD_WRITE_OUTCOME_UNSPECIFIED', '2': 0},+ {'1': 'CLIPBOARD_WRITE_OUTCOME_APPLIED', '2': 1},+ {'1': 'CLIPBOARD_WRITE_OUTCOME_PRESERVED', '2': 2},+ {'1': 'CLIPBOARD_WRITE_OUTCOME_FAILED', '2': 3},+ ],+};++/// Descriptor for `ClipboardWriteOutcome`. Decode as a `google.protobuf.EnumDescriptorProto`.+final $typed_data.Uint8List clipboardWriteOutcomeDescriptor = $convert.base64Decode(+ 'ChVDbGlwYm9hcmRXcml0ZU91dGNvbWUSJwojQ0xJUEJPQVJEX1dSSVRFX09VVENPTUVfVU5TUE'+ 'VDSUZJRUQQABIjCh9DTElQQk9BUkRfV1JJVEVfT1VUQ09NRV9BUFBMSUVEEAESJQohQ0xJUEJP'+ 'QVJEX1dSSVRFX09VVENPTUVfUFJFU0VSVkVEEAISIgoeQ0xJUEJPQVJEX1dSSVRFX09VVENPTU'+ 'VfRkFJTEVEEAM=');+@$core.Deprecated('Use emptyDescriptor instead')const Empty$json = {'1': 'Empty',@@ -300,6 +318,15 @@ const Event$json = {'9': 0,'10': 'statusChanged'},+ {+ '1': 'clipboard_written',+ '3': 8,+ '4': 1,+ '5': 11,+ '6': '.pasteferry.v1.ClipboardWriteResult',+ '9': 0,+ '10': 'clipboardWritten'+ },],'8': [{'1': 'payload'},@@ -316,7 +343,67 @@ final $typed_data.Uint8List eventDescriptor = $convert.base64Decode('VIAFINZGV2aWNlQ2hhbmdlZBJTChJwZXJtaXNzaW9uX2NoYW5nZWQYBiABKA4yIi5wYXN0ZWZl''cnJ5LnYxLkNsaXBib2FyZFBlcm1pc3Npb25IAFIRcGVybWlzc2lvbkNoYW5nZWQSPgoOc3RhdH''VzX2NoYW5nZWQYByABKAsyFS5wYXN0ZWZlcnJ5LnYxLlN0YXR1c0gAUg1zdGF0dXNDaGFuZ2Vk'- 'QgkKB3BheWxvYWQ=');+ 'ElIKEWNsaXBib2FyZF93cml0dGVuGAggASgLMiMucGFzdGVmZXJyeS52MS5DbGlwYm9hcmRXcm'+ 'l0ZVJlc3VsdEgAUhBjbGlwYm9hcmRXcml0dGVuQgkKB3BheWxvYWQ=');++@$core.Deprecated('Use notificationStatusDescriptor instead')+const NotificationStatus$json = {+ '1': 'NotificationStatus',+ '2': [+ {'1': 'supported', '3': 1, '4': 1, '5': 8, '10': 'supported'},+ {+ '1': 'actions_supported',+ '3': 2,+ '4': 1,+ '5': 8,+ '10': 'actionsSupported'+ },+ {'1': 'permission', '3': 3, '4': 1, '5': 9, '10': 'permission'},+ ],+};++/// Descriptor for `NotificationStatus`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List notificationStatusDescriptor = $convert.base64Decode(+ 'ChJOb3RpZmljYXRpb25TdGF0dXMSHAoJc3VwcG9ydGVkGAEgASgIUglzdXBwb3J0ZWQSKwoRYW'+ 'N0aW9uc19zdXBwb3J0ZWQYAiABKAhSEGFjdGlvbnNTdXBwb3J0ZWQSHgoKcGVybWlzc2lvbhgD'+ 'IAEoCVIKcGVybWlzc2lvbg==');++@$core.Deprecated('Use notificationActionDescriptor instead')+const NotificationAction$json = {+ '1': 'NotificationAction',+ '2': [+ {'1': 'clip_id', '3': 1, '4': 1, '5': 9, '10': 'clipId'},+ {'1': 'action', '3': 2, '4': 1, '5': 9, '10': 'action'},+ ],+};++/// Descriptor for `NotificationAction`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List notificationActionDescriptor = $convert.base64Decode(+ 'ChJOb3RpZmljYXRpb25BY3Rpb24SFwoHY2xpcF9pZBgBIAEoCVIGY2xpcElkEhYKBmFjdGlvbh'+ 'gCIAEoCVIGYWN0aW9u');++@$core.Deprecated('Use clipboardWriteResultDescriptor instead')+const ClipboardWriteResult$json = {+ '1': 'ClipboardWriteResult',+ '2': [+ {'1': 'clip_id', '3': 1, '4': 1, '5': 9, '10': 'clipId'},+ {+ '1': 'outcome',+ '3': 2,+ '4': 1,+ '5': 14,+ '6': '.pasteferry.v1.ClipboardWriteOutcome',+ '10': 'outcome'+ },+ {'1': 'error', '3': 3, '4': 1, '5': 9, '10': 'error'},+ ],+};++/// Descriptor for `ClipboardWriteResult`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List clipboardWriteResultDescriptor = $convert.base64Decode(+ 'ChRDbGlwYm9hcmRXcml0ZVJlc3VsdBIXCgdjbGlwX2lkGAEgASgJUgZjbGlwSWQSPgoHb3V0Y2'+ '9tZRgCIAEoDjIkLnBhc3RlZmVycnkudjEuQ2xpcGJvYXJkV3JpdGVPdXRjb21lUgdvdXRjb21l'+ 'EhQKBWVycm9yGAMgASgJUgVlcnJvcg==');@$core.Deprecated('Use listHistoryRequestDescriptor instead')const ListHistoryRequest$json = {diff --git a/ui/lib/l10n/app_en.arb b/ui/lib/l10n/app_en.arbindex 22c4a63..dbae803 100644--- a/ui/lib/l10n/app_en.arb+++ b/ui/lib/l10n/app_en.arb@@ -1,5 +1,97 @@{"@@locale": "en",+ "buildDetails": "UI {uiVersion} · Service {serviceVersion} · Build {build}",+ "@buildDetails": {+ "placeholders": {+ "uiVersion": {+ "type": "String"+ },+ "serviceVersion": {+ "type": "String"+ },+ "build": {+ "type": "String"+ }+ }+ },+ "notReceived": "Not received — receive before pasting",+ "receivedPreserved": "Received; use Copy to clipboard when ready",+ "clipboardWriteFailed": "Received, but the clipboard could not be updated",+ "receivingStatus": "Receiving…",+ "largeFileNotifications": "Large file reminders",+ "notificationsAllowed": "Notifications are enabled. Progress is shown in History.",+ "notificationsNotRequested": "Enable notifications so large files do not wait silently. You can always receive them from History.",+ "notificationsDenied": "Notifications are blocked in system settings. Receive pending items from History.",+ "notificationsUnknown": "Your desktop controls notification delivery and Do Not Disturb. Receive items from History if no reminder appears.",+ "notificationsUnavailable": "System notifications are unavailable. Receive large files from History.",+ "enableNotifications": "Enable reminders",+ "notificationSettings": "Notification settings",+ "notifyPendingTitle": "Receive to paste",+ "notifyPendingBody": "{device} · {name} · {size}\nReceive this item before pasting. You can also receive it from History.",+ "@notifyPendingBody": {+ "placeholders": {+ "device": {+ "type": "String"+ },+ "name": {+ "type": "String"+ },+ "size": {+ "type": "String"+ }+ }+ },+ "notifyReceivingTitle": "Receiving…",+ "notifyReceivingBody": "{name}\nSee History for progress.",+ "@notifyReceivingBody": {+ "placeholders": {+ "name": {+ "type": "String"+ }+ }+ },+ "notifyReadyTitle": "Ready to paste",+ "notifyReadyBody": "{name}\nReceived and placed on the clipboard.",+ "@notifyReadyBody": {+ "placeholders": {+ "name": {+ "type": "String"+ }+ }+ },+ "notifyReceivedTitle": "Received",+ "notifyReceivedBody": "{name}\nYour clipboard was kept. Use Copy to clipboard when ready; this is also available in History.",+ "@notifyReceivedBody": {+ "placeholders": {+ "name": {+ "type": "String"+ }+ }+ },+ "notifyFailedTitle": "Could not receive",+ "notifyFailedBody": "{name}\n{error}\nTry again from this notification or History.",+ "@notifyFailedBody": {+ "placeholders": {+ "name": {+ "type": "String"+ },+ "error": {+ "type": "String"+ }+ }+ },+ "notifyClipboardFailedTitle": "Received; clipboard was not updated",+ "notifyClipboardFailedBody": "{name}\n{error}\nUse Copy to clipboard to try again, here or in History.",+ "@notifyClipboardFailedBody": {+ "placeholders": {+ "name": {+ "type": "String"+ },+ "error": {+ "type": "String"+ }+ }+ },"appName": "PasteFerry","navHistory": "History","navDevices": "Devices",@@ -180,8 +272,8 @@"permDeniedBody": "What you copy on this Mac won't be synced. In System Settings, set PasteFerry Daemon to Allow.","permAskBody": "Otherwise macOS asks every time. In System Settings, set PasteFerry Daemon to Allow.","openSystemSettings": "Open System Settings",- "fetch": "Pull to this device",- "fetchStarted": "Pulling…",+ "fetch": "Receive",+ "fetchStarted": "Receiving… See History for progress","transferFailed": "Transfer failed","expired": "Expired","putOnClipboard": "Copy to clipboard",@@ -418,9 +510,9 @@"language": "Language","languageSystem": "System","sync": "Sync",- "syncFootnote": "Items under the limit are pushed to your other devices as you copy. Larger ones sync as a record; pull them from History when you need them, so big files don't waste bandwidth or disk space.",+ "syncFootnote": "Items under the limit are pushed to your other devices as you copy. Larger ones sync as a record; receive them from History when you need them, so big files don't waste bandwidth or disk space.","autoSyncLimit": "Auto-sync limit",- "autoSyncLimitDesc": "Larger files are pulled by hand",+ "autoSyncLimitDesc": "Larger files must be received before pasting","autoApply": "Put received items on the clipboard","autoApplyDesc": "When off, put them on the clipboard from History yourself","whatToSync": "What to sync",diff --git a/ui/lib/l10n/app_ja.arb b/ui/lib/l10n/app_ja.arbindex c551ee4..2e76c44 100644--- a/ui/lib/l10n/app_ja.arb+++ b/ui/lib/l10n/app_ja.arb@@ -1,5 +1,30 @@{"@@locale": "ja",+ "buildDetails": "UI {uiVersion} · サービス {serviceVersion} · ビルド {build}",+ "notReceived": "未受信 — ペーストする前に受信してください",+ "receivedPreserved": "受信済み。クリップボードに入れるとペーストできます",+ "clipboardWriteFailed": "受信済みですが、クリップボードを更新できませんでした",+ "receivingStatus": "受信中…",+ "largeFileNotifications": "大きなファイルの受信通知",+ "notificationsAllowed": "通知は有効です。受信の進捗は履歴で確認できます。",+ "notificationsNotRequested": "大きなファイルの受信待ちを通知します。履歴からいつでも受信できます。",+ "notificationsDenied": "システム設定で通知が無効です。受信待ちの項目は履歴から受信できます。",+ "notificationsUnknown": "通知とおやすみモードはデスクトップで管理されます。通知がない場合は履歴から受信できます。",+ "notificationsUnavailable": "システム通知を利用できません。大きなファイルは履歴から受信してください。",+ "enableNotifications": "通知を有効にする",+ "notificationSettings": "通知設定",+ "notifyPendingTitle": "受信するとペーストできます",+ "notifyPendingBody": "{device} · {name} · {size}\nペーストする前に受信してください。履歴からも受信できます。",+ "notifyReceivingTitle": "受信中…",+ "notifyReceivingBody": "{name}\n進捗は履歴で確認できます。",+ "notifyReadyTitle": "ペーストできます",+ "notifyReadyBody": "{name}\n受信してクリップボードに入れました。",+ "notifyReceivedTitle": "受信しました",+ "notifyReceivedBody": "{name}\n現在のクリップボードは保持しました。クリップボードに入れる操作は履歴からもできます。",+ "notifyFailedTitle": "受信できませんでした",+ "notifyFailedBody": "{name}\n{error}\nこの通知または履歴から再試行できます。",+ "notifyClipboardFailedTitle": "受信済みですがクリップボードを更新できませんでした",+ "notifyClipboardFailedBody": "{name}\n{error}\nこの通知または履歴からクリップボードに入れて再試行できます。","appName": "PasteFerry","navHistory": "履歴","navDevices": "デバイス",@@ -62,8 +87,8 @@"permDeniedBody": "この Mac でコピーした内容は同期されません。システム設定で PasteFerry Daemon を「許可」にしてください。","permAskBody": "許可しないと macOS が毎回確認します。システム設定で PasteFerry Daemon を「許可」にしてください。","openSystemSettings": "システム設定を開く",- "fetch": "このデバイスに取り込む",- "fetchStarted": "取り込みを開始しました",+ "fetch": "受信",+ "fetchStarted": "受信中…進捗は履歴で確認できます","transferFailed": "転送に失敗しました","expired": "期限切れ","putOnClipboard": "クリップボードに入れる",diff --git a/ui/lib/l10n/app_localizations.dart b/ui/lib/l10n/app_localizations.dartindex d455c85..faa01bd 100644--- a/ui/lib/l10n/app_localizations.dart+++ b/ui/lib/l10n/app_localizations.dart@@ -110,6 +110,156 @@ abstract class AppLocalizations {),];+ /// No description provided for @buildDetails.+ ///+ /// In en, this message translates to:+ /// **'UI {uiVersion} · Service {serviceVersion} · Build {build}'**+ String buildDetails(String uiVersion, String serviceVersion, String build);++ /// No description provided for @notReceived.+ ///+ /// In en, this message translates to:+ /// **'Not received — receive before pasting'**+ String get notReceived;++ /// No description provided for @receivedPreserved.+ ///+ /// In en, this message translates to:+ /// **'Received; use Copy to clipboard when ready'**+ String get receivedPreserved;++ /// No description provided for @clipboardWriteFailed.+ ///+ /// In en, this message translates to:+ /// **'Received, but the clipboard could not be updated'**+ String get clipboardWriteFailed;++ /// No description provided for @receivingStatus.+ ///+ /// In en, this message translates to:+ /// **'Receiving…'**+ String get receivingStatus;++ /// No description provided for @largeFileNotifications.+ ///+ /// In en, this message translates to:+ /// **'Large file reminders'**+ String get largeFileNotifications;++ /// No description provided for @notificationsAllowed.+ ///+ /// In en, this message translates to:+ /// **'Notifications are enabled. Progress is shown in History.'**+ String get notificationsAllowed;++ /// No description provided for @notificationsNotRequested.+ ///+ /// In en, this message translates to:+ /// **'Enable notifications so large files do not wait silently. You can always receive them from History.'**+ String get notificationsNotRequested;++ /// No description provided for @notificationsDenied.+ ///+ /// In en, this message translates to:+ /// **'Notifications are blocked in system settings. Receive pending items from History.'**+ String get notificationsDenied;++ /// No description provided for @notificationsUnknown.+ ///+ /// In en, this message translates to:+ /// **'Your desktop controls notification delivery and Do Not Disturb. Receive items from History if no reminder appears.'**+ String get notificationsUnknown;++ /// No description provided for @notificationsUnavailable.+ ///+ /// In en, this message translates to:+ /// **'System notifications are unavailable. Receive large files from History.'**+ String get notificationsUnavailable;++ /// No description provided for @enableNotifications.+ ///+ /// In en, this message translates to:+ /// **'Enable reminders'**+ String get enableNotifications;++ /// No description provided for @notificationSettings.+ ///+ /// In en, this message translates to:+ /// **'Notification settings'**+ String get notificationSettings;++ /// No description provided for @notifyPendingTitle.+ ///+ /// In en, this message translates to:+ /// **'Receive to paste'**+ String get notifyPendingTitle;++ /// No description provided for @notifyPendingBody.+ ///+ /// In en, this message translates to:+ /// **'{device} · {name} · {size}\nReceive this item before pasting. You can also receive it from History.'**+ String notifyPendingBody(String device, String name, String size);++ /// No description provided for @notifyReceivingTitle.+ ///+ /// In en, this message translates to:+ /// **'Receiving…'**+ String get notifyReceivingTitle;++ /// No description provided for @notifyReceivingBody.+ ///+ /// In en, this message translates to:+ /// **'{name}\nSee History for progress.'**+ String notifyReceivingBody(String name);++ /// No description provided for @notifyReadyTitle.+ ///+ /// In en, this message translates to:+ /// **'Ready to paste'**+ String get notifyReadyTitle;++ /// No description provided for @notifyReadyBody.+ ///+ /// In en, this message translates to:+ /// **'{name}\nReceived and placed on the clipboard.'**+ String notifyReadyBody(String name);++ /// No description provided for @notifyReceivedTitle.+ ///+ /// In en, this message translates to:+ /// **'Received'**+ String get notifyReceivedTitle;++ /// No description provided for @notifyReceivedBody.+ ///+ /// In en, this message translates to:+ /// **'{name}\nYour clipboard was kept. Use Copy to clipboard when ready; this is also available in History.'**+ String notifyReceivedBody(String name);++ /// No description provided for @notifyFailedTitle.+ ///+ /// In en, this message translates to:+ /// **'Could not receive'**+ String get notifyFailedTitle;++ /// No description provided for @notifyFailedBody.+ ///+ /// In en, this message translates to:+ /// **'{name}\n{error}\nTry again from this notification or History.'**+ String notifyFailedBody(String name, String error);++ /// No description provided for @notifyClipboardFailedTitle.+ ///+ /// In en, this message translates to:+ /// **'Received; clipboard was not updated'**+ String get notifyClipboardFailedTitle;++ /// No description provided for @notifyClipboardFailedBody.+ ///+ /// In en, this message translates to:+ /// **'{name}\n{error}\nUse Copy to clipboard to try again, here or in History.'**+ String notifyClipboardFailedBody(String name, String error);+/// No description provided for @appName.////// In en, this message translates to:@@ -485,13 +635,13 @@ abstract class AppLocalizations {/// No description provided for @fetch.////// In en, this message translates to:- /// **'Pull to this device'**+ /// **'Receive'**String get fetch;/// No description provided for @fetchStarted.////// In en, this message translates to:- /// **'Pulling…'**+ /// **'Receiving… See History for progress'**String get fetchStarted;/// No description provided for @transferFailed.@@ -1229,7 +1379,7 @@ abstract class AppLocalizations {/// No description provided for @syncFootnote.////// In en, this message translates to:- /// **'Items under the limit are pushed to your other devices as you copy. Larger ones sync as a record; pull them from History when you need them, so big files don\'t waste bandwidth or disk space.'**+ /// **'Items under the limit are pushed to your other devices as you copy. Larger ones sync as a record; receive them from History when you need them, so big files don\'t waste bandwidth or disk space.'**String get syncFootnote;/// No description provided for @autoSyncLimit.@@ -1241,7 +1391,7 @@ abstract class AppLocalizations {/// No description provided for @autoSyncLimitDesc.////// In en, this message translates to:- /// **'Larger files are pulled by hand'**+ /// **'Larger files must be received before pasting'**String get autoSyncLimitDesc;/// No description provided for @autoApply.diff --git a/ui/lib/l10n/app_localizations_en.dart b/ui/lib/l10n/app_localizations_en.dartindex 22536a2..cca2ca5 100644--- a/ui/lib/l10n/app_localizations_en.dart+++ b/ui/lib/l10n/app_localizations_en.dart@@ -8,6 +8,102 @@ import 'app_localizations.dart';class AppLocalizationsEn extends AppLocalizations {AppLocalizationsEn([String locale = 'en']) : super(locale);+ @override+ String buildDetails(String uiVersion, String serviceVersion, String build) {+ return 'UI $uiVersion · Service $serviceVersion · Build $build';+ }++ @override+ String get notReceived => 'Not received — receive before pasting';++ @override+ String get receivedPreserved => 'Received; use Copy to clipboard when ready';++ @override+ String get clipboardWriteFailed =>+ 'Received, but the clipboard could not be updated';++ @override+ String get receivingStatus => 'Receiving…';++ @override+ String get largeFileNotifications => 'Large file reminders';++ @override+ String get notificationsAllowed =>+ 'Notifications are enabled. Progress is shown in History.';++ @override+ String get notificationsNotRequested =>+ 'Enable notifications so large files do not wait silently. You can always receive them from History.';++ @override+ String get notificationsDenied =>+ 'Notifications are blocked in system settings. Receive pending items from History.';++ @override+ String get notificationsUnknown =>+ 'Your desktop controls notification delivery and Do Not Disturb. Receive items from History if no reminder appears.';++ @override+ String get notificationsUnavailable =>+ 'System notifications are unavailable. Receive large files from History.';++ @override+ String get enableNotifications => 'Enable reminders';++ @override+ String get notificationSettings => 'Notification settings';++ @override+ String get notifyPendingTitle => 'Receive to paste';++ @override+ String notifyPendingBody(String device, String name, String size) {+ return '$device · $name · $size\nReceive this item before pasting. You can also receive it from History.';+ }++ @override+ String get notifyReceivingTitle => 'Receiving…';++ @override+ String notifyReceivingBody(String name) {+ return '$name\nSee History for progress.';+ }++ @override+ String get notifyReadyTitle => 'Ready to paste';++ @override+ String notifyReadyBody(String name) {+ return '$name\nReceived and placed on the clipboard.';+ }++ @override+ String get notifyReceivedTitle => 'Received';++ @override+ String notifyReceivedBody(String name) {+ return '$name\nYour clipboard was kept. Use Copy to clipboard when ready; this is also available in History.';+ }++ @override+ String get notifyFailedTitle => 'Could not receive';++ @override+ String notifyFailedBody(String name, String error) {+ return '$name\n$error\nTry again from this notification or History.';+ }++ @override+ String get notifyClipboardFailedTitle =>+ 'Received; clipboard was not updated';++ @override+ String notifyClipboardFailedBody(String name, String error) {+ return '$name\n$error\nUse Copy to clipboard to try again, here or in History.';+ }+@overrideString get appName => 'PasteFerry';@@ -282,10 +378,10 @@ class AppLocalizationsEn extends AppLocalizations {String get openSystemSettings => 'Open System Settings';@override- String get fetch => 'Pull to this device';+ String get fetch => 'Receive';@override- String get fetchStarted => 'Pulling…';+ String get fetchStarted => 'Receiving… See History for progress';@overrideString get transferFailed => 'Transfer failed';@@ -719,13 +815,14 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get syncFootnote =>- 'Items under the limit are pushed to your other devices as you copy. Larger ones sync as a record; pull them from History when you need them, so big files don\'t waste bandwidth or disk space.';+ 'Items under the limit are pushed to your other devices as you copy. Larger ones sync as a record; receive them from History when you need them, so big files don\'t waste bandwidth or disk space.';@overrideString get autoSyncLimit => 'Auto-sync limit';@override- String get autoSyncLimitDesc => 'Larger files are pulled by hand';+ String get autoSyncLimitDesc =>+ 'Larger files must be received before pasting';@overrideString get autoApply => 'Put received items on the clipboard';diff --git a/ui/lib/l10n/app_localizations_ja.dart b/ui/lib/l10n/app_localizations_ja.dartindex ca3db42..daa9413 100644--- a/ui/lib/l10n/app_localizations_ja.dart+++ b/ui/lib/l10n/app_localizations_ja.dart@@ -8,6 +8,96 @@ import 'app_localizations.dart';class AppLocalizationsJa extends AppLocalizations {AppLocalizationsJa([String locale = 'ja']) : super(locale);+ @override+ String buildDetails(String uiVersion, String serviceVersion, String build) {+ return 'UI $uiVersion · サービス $serviceVersion · ビルド $build';+ }++ @override+ String get notReceived => '未受信 — ペーストする前に受信してください';++ @override+ String get receivedPreserved => '受信済み。クリップボードに入れるとペーストできます';++ @override+ String get clipboardWriteFailed => '受信済みですが、クリップボードを更新できませんでした';++ @override+ String get receivingStatus => '受信中…';++ @override+ String get largeFileNotifications => '大きなファイルの受信通知';++ @override+ String get notificationsAllowed => '通知は有効です。受信の進捗は履歴で確認できます。';++ @override+ String get notificationsNotRequested => '大きなファイルの受信待ちを通知します。履歴からいつでも受信できます。';++ @override+ String get notificationsDenied => 'システム設定で通知が無効です。受信待ちの項目は履歴から受信できます。';++ @override+ String get notificationsUnknown =>+ '通知とおやすみモードはデスクトップで管理されます。通知がない場合は履歴から受信できます。';++ @override+ String get notificationsUnavailable => 'システム通知を利用できません。大きなファイルは履歴から受信してください。';++ @override+ String get enableNotifications => '通知を有効にする';++ @override+ String get notificationSettings => '通知設定';++ @override+ String get notifyPendingTitle => '受信するとペーストできます';++ @override+ String notifyPendingBody(String device, String name, String size) {+ return '$device · $name · $size\nペーストする前に受信してください。履歴からも受信できます。';+ }++ @override+ String get notifyReceivingTitle => '受信中…';++ @override+ String notifyReceivingBody(String name) {+ return '$name\n進捗は履歴で確認できます。';+ }++ @override+ String get notifyReadyTitle => 'ペーストできます';++ @override+ String notifyReadyBody(String name) {+ return '$name\n受信してクリップボードに入れました。';+ }++ @override+ String get notifyReceivedTitle => '受信しました';++ @override+ String notifyReceivedBody(String name) {+ return '$name\n現在のクリップボードは保持しました。クリップボードに入れる操作は履歴からもできます。';+ }++ @override+ String get notifyFailedTitle => '受信できませんでした';++ @override+ String notifyFailedBody(String name, String error) {+ return '$name\n$error\nこの通知または履歴から再試行できます。';+ }++ @override+ String get notifyClipboardFailedTitle => '受信済みですがクリップボードを更新できませんでした';++ @override+ String notifyClipboardFailedBody(String name, String error) {+ return '$name\n$error\nこの通知または履歴からクリップボードに入れて再試行できます。';+ }+@overrideString get appName => 'PasteFerry';@@ -229,10 +319,10 @@ class AppLocalizationsJa extends AppLocalizations {String get openSystemSettings => 'システム設定を開く';@override- String get fetch => 'このデバイスに取り込む';+ String get fetch => '受信';@override- String get fetchStarted => '取り込みを開始しました';+ String get fetchStarted => '受信中…進捗は履歴で確認できます';@overrideString get transferFailed => '転送に失敗しました';diff --git a/ui/lib/l10n/app_localizations_zh.dart b/ui/lib/l10n/app_localizations_zh.dartindex 6c1e6e1..bb2bead 100644--- a/ui/lib/l10n/app_localizations_zh.dart+++ b/ui/lib/l10n/app_localizations_zh.dart@@ -8,6 +8,95 @@ import 'app_localizations.dart';class AppLocalizationsZh extends AppLocalizations {AppLocalizationsZh([String locale = 'zh']) : super(locale);+ @override+ String buildDetails(String uiVersion, String serviceVersion, String build) {+ return '界面 $uiVersion · 后台 $serviceVersion · 构建 $build';+ }++ @override+ String get notReceived => '尚未接收,暂不可粘贴';++ @override+ String get receivedPreserved => '已接收,点击放入剪贴板后可粘贴';++ @override+ String get clipboardWriteFailed => '已接收,但未能写入剪贴板';++ @override+ String get receivingStatus => '正在接收…';++ @override+ String get largeFileNotifications => '大文件接收提醒';++ @override+ String get notificationsAllowed => '已允许系统通知,接收进度在复制记录中查看。';++ @override+ String get notificationsNotRequested => '开启系统通知,避免大文件等待接收时没有提示;也可随时从复制记录接收。';++ @override+ String get notificationsDenied => '系统通知已关闭,请在系统设置中开启;待接收内容仍可从复制记录接收。';++ @override+ String get notificationsUnknown => '通知显示和勿扰由系统控制;未看到提醒时,可在复制记录中接收。';++ @override+ String get notificationsUnavailable => '系统通知暂不可用,请从复制记录接收大文件。';++ @override+ String get enableNotifications => '开启提醒';++ @override+ String get notificationSettings => '通知设置';++ @override+ String get notifyPendingTitle => '接收后即可粘贴';++ @override+ String notifyPendingBody(String device, String name, String size) {+ return '$device · $name · $size\n尚未接收,暂不可粘贴。也可从复制记录接收。';+ }++ @override+ String get notifyReceivingTitle => '正在接收…';++ @override+ String notifyReceivingBody(String name) {+ return '$name\n可在复制记录查看接收进度。';+ }++ @override+ String get notifyReadyTitle => '已就绪,可以粘贴';++ @override+ String notifyReadyBody(String name) {+ return '$name\n已接收并放入剪贴板。';+ }++ @override+ String get notifyReceivedTitle => '已接收';++ @override+ String notifyReceivedBody(String name) {+ return '$name\n已保留当前剪贴板,点击放入剪贴板后可粘贴,也可从复制记录操作。';+ }++ @override+ String get notifyFailedTitle => '接收失败';++ @override+ String notifyFailedBody(String name, String error) {+ return '$name\n$error\n可从此通知或复制记录重试。';+ }++ @override+ String get notifyClipboardFailedTitle => '已接收,但未能写入剪贴板';++ @override+ String notifyClipboardFailedBody(String name, String error) {+ return '$name\n$error\n可从此通知或复制记录重新放入剪贴板。';+ }+@overrideString get appName => '隔空贴';@@ -229,10 +318,10 @@ class AppLocalizationsZh extends AppLocalizations {String get openSystemSettings => '打开系统设置';@override- String get fetch => '拉取到本机';+ String get fetch => '接收';@override- String get fetchStarted => '开始拉取';+ String get fetchStarted => '正在接收,可在复制记录查看进度';@overrideString get transferFailed => '传输失败';@@ -638,13 +727,13 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get syncFootnote =>- '小于阈值的内容在复制时直接推送到其他设备;超过阈值的只同步一条记录,需要时在「复制记录」里点「拉取到本机」,避免大文件无谓地占用带宽和磁盘。';+ '小于阈值的内容在复制时直接推送到其他设备;超过阈值的只同步一条记录,需要时在「复制记录」里点「接收」,避免大文件无谓地占用带宽和磁盘。';@overrideString get autoSyncLimit => '自动同步上限';@override- String get autoSyncLimitDesc => '超过这个大小的文件改为手动拉取';+ String get autoSyncLimitDesc => '超过这个大小的文件改为手动接收';@overrideString get autoApply => '收到后直接写入剪贴板';@@ -860,6 +949,95 @@ class AppLocalizationsZh extends AppLocalizations {class AppLocalizationsZhHantHk extends AppLocalizationsZh {AppLocalizationsZhHantHk() : super('zh_Hant_HK');+ @override+ String buildDetails(String uiVersion, String serviceVersion, String build) {+ return '介面 $uiVersion · 背景服務 $serviceVersion · 版本識別 $build';+ }++ @override+ String get notReceived => '尚未接收,暫不可貼上';++ @override+ String get receivedPreserved => '已接收,按放入剪貼簿後即可貼上';++ @override+ String get clipboardWriteFailed => '已接收,但無法寫入剪貼簿';++ @override+ String get receivingStatus => '正在接收…';++ @override+ String get largeFileNotifications => '大檔案接收提醒';++ @override+ String get notificationsAllowed => '已允許系統通知,接收進度可在複製記錄中查看。';++ @override+ String get notificationsNotRequested => '開啟系統通知,避免大檔案等待接收時沒有提示;亦可隨時從複製記錄接收。';++ @override+ String get notificationsDenied => '系統通知已關閉,請在系統設定中開啟;待接收內容仍可從複製記錄接收。';++ @override+ String get notificationsUnknown => '通知顯示和勿擾由系統控制;未看到提示時,可在複製記錄中接收。';++ @override+ String get notificationsUnavailable => '系統通知暫時無法使用,請從複製記錄接收大檔案。';++ @override+ String get enableNotifications => '開啟提醒';++ @override+ String get notificationSettings => '通知設定';++ @override+ String get notifyPendingTitle => '接收後即可貼上';++ @override+ String notifyPendingBody(String device, String name, String size) {+ return '$device · $name · $size\n尚未接收,暫不可貼上。亦可從複製記錄接收。';+ }++ @override+ String get notifyReceivingTitle => '正在接收…';++ @override+ String notifyReceivingBody(String name) {+ return '$name\n可在複製記錄查看接收進度。';+ }++ @override+ String get notifyReadyTitle => '已就緒,可以貼上';++ @override+ String notifyReadyBody(String name) {+ return '$name\n已接收並放入剪貼簿。';+ }++ @override+ String get notifyReceivedTitle => '已接收';++ @override+ String notifyReceivedBody(String name) {+ return '$name\n已保留目前剪貼簿,按放入剪貼簿後即可貼上,亦可從複製記錄操作。';+ }++ @override+ String get notifyFailedTitle => '接收失敗';++ @override+ String notifyFailedBody(String name, String error) {+ return '$name\n$error\n可從此通知或複製記錄重試。';+ }++ @override+ String get notifyClipboardFailedTitle => '已接收,但無法寫入剪貼簿';++ @override+ String notifyClipboardFailedBody(String name, String error) {+ return '$name\n$error\n可從此通知或複製記錄重新放入剪貼簿。';+ }+@overrideString get appName => '隔空貼';@@ -1081,10 +1259,10 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh {String get openSystemSettings => '開啟系統設定';@override- String get fetch => '拉取到本機';+ String get fetch => '接收';@override- String get fetchStarted => '開始拉取';+ String get fetchStarted => '正在接收,可在複製記錄查看進度';@overrideString get transferFailed => '傳輸失敗';@@ -1490,13 +1668,13 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh {@overrideString get syncFootnote =>- '小於上限的內容在複製時直接推送到其他裝置;超過上限的只同步一條記錄,需要時在「複製記錄」裏按「拉取到本機」,避免大檔案無謂地佔用頻寬和磁碟空間。';+ '小於上限的內容在複製時直接推送到其他裝置;超過上限的只同步一條記錄,需要時在「複製記錄」裏按「接收」,避免大檔案無謂地佔用頻寬和磁碟空間。';@overrideString get autoSyncLimit => '自動同步上限';@override- String get autoSyncLimitDesc => '超過這個大小的檔案改為手動拉取';+ String get autoSyncLimitDesc => '超過這個大小的檔案改為手動接收';@overrideString get autoApply => '收到後直接寫入剪貼簿';@@ -1712,6 +1890,95 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh {class AppLocalizationsZhHantTw extends AppLocalizationsZh {AppLocalizationsZhHantTw() : super('zh_Hant_TW');+ @override+ String buildDetails(String uiVersion, String serviceVersion, String build) {+ return '介面 $uiVersion · 背景服務 $serviceVersion · 建置 $build';+ }++ @override+ String get notReceived => '尚未接收,暫不可貼上';++ @override+ String get receivedPreserved => '已接收,點選放入剪貼簿後即可貼上';++ @override+ String get clipboardWriteFailed => '已接收,但無法寫入剪貼簿';++ @override+ String get receivingStatus => '正在接收…';++ @override+ String get largeFileNotifications => '大檔案接收提醒';++ @override+ String get notificationsAllowed => '已允許系統通知,接收進度可在複製記錄中查看。';++ @override+ String get notificationsNotRequested => '開啟系統通知,避免大檔案等待接收時沒有提醒;也可隨時從複製記錄接收。';++ @override+ String get notificationsDenied => '系統通知已關閉,請在系統設定中開啟;待接收內容仍可從複製記錄接收。';++ @override+ String get notificationsUnknown => '通知顯示和勿擾由系統控制;未看到提醒時,可在複製記錄中接收。';++ @override+ String get notificationsUnavailable => '系統通知暫時無法使用,請從複製記錄接收大檔案。';++ @override+ String get enableNotifications => '開啟提醒';++ @override+ String get notificationSettings => '通知設定';++ @override+ String get notifyPendingTitle => '接收後即可貼上';++ @override+ String notifyPendingBody(String device, String name, String size) {+ return '$device · $name · $size\n尚未接收,暫不可貼上。也可從複製記錄接收。';+ }++ @override+ String get notifyReceivingTitle => '正在接收…';++ @override+ String notifyReceivingBody(String name) {+ return '$name\n可在複製記錄查看接收進度。';+ }++ @override+ String get notifyReadyTitle => '已就緒,可以貼上';++ @override+ String notifyReadyBody(String name) {+ return '$name\n已接收並放入剪貼簿。';+ }++ @override+ String get notifyReceivedTitle => '已接收';++ @override+ String notifyReceivedBody(String name) {+ return '$name\n已保留目前剪貼簿,點選放入剪貼簿後即可貼上,也可從複製記錄操作。';+ }++ @override+ String get notifyFailedTitle => '接收失敗';++ @override+ String notifyFailedBody(String name, String error) {+ return '$name\n$error\n可從此通知或複製記錄重試。';+ }++ @override+ String get notifyClipboardFailedTitle => '已接收,但無法寫入剪貼簿';++ @override+ String notifyClipboardFailedBody(String name, String error) {+ return '$name\n$error\n可從此通知或複製記錄重新放入剪貼簿。';+ }+@overrideString get appName => '隔空貼';@@ -1933,10 +2200,10 @@ class AppLocalizationsZhHantTw extends AppLocalizationsZh {String get openSystemSettings => '打開系統設定';@override- String get fetch => '拉取到本機';+ String get fetch => '接收';@override- String get fetchStarted => '開始拉取';+ String get fetchStarted => '正在接收,可在複製記錄查看進度';@overrideString get transferFailed => '傳輸失敗';@@ -2342,13 +2609,13 @@ class AppLocalizationsZhHantTw extends AppLocalizationsZh {@overrideString get syncFootnote =>- '小於上限的內容在複製時直接推送到其他裝置;超過上限的只同步一筆記錄,需要時在「複製記錄」裡點「拉取到本機」,避免大檔案白白佔用頻寬和磁碟空間。';+ '小於上限的內容在複製時直接推送到其他裝置;超過上限的只同步一筆記錄,需要時在「複製記錄」裡點「接收」,避免大檔案白白佔用頻寬和磁碟空間。';@overrideString get autoSyncLimit => '自動同步上限';@override- String get autoSyncLimitDesc => '超過這個大小的檔案改為手動拉取';+ String get autoSyncLimitDesc => '超過這個大小的檔案改為手動接收';@overrideString get autoApply => '收到後直接寫入剪貼簿';diff --git a/ui/lib/l10n/app_zh.arb b/ui/lib/l10n/app_zh.arbindex 5990ff6..627d878 100644--- a/ui/lib/l10n/app_zh.arb+++ b/ui/lib/l10n/app_zh.arb@@ -1,5 +1,30 @@{"@@locale": "zh",+ "buildDetails": "界面 {uiVersion} · 后台 {serviceVersion} · 构建 {build}",+ "notReceived": "尚未接收,暂不可粘贴",+ "receivedPreserved": "已接收,点击放入剪贴板后可粘贴",+ "clipboardWriteFailed": "已接收,但未能写入剪贴板",+ "receivingStatus": "正在接收…",+ "largeFileNotifications": "大文件接收提醒",+ "notificationsAllowed": "已允许系统通知,接收进度在复制记录中查看。",+ "notificationsNotRequested": "开启系统通知,避免大文件等待接收时没有提示;也可随时从复制记录接收。",+ "notificationsDenied": "系统通知已关闭,请在系统设置中开启;待接收内容仍可从复制记录接收。",+ "notificationsUnknown": "通知显示和勿扰由系统控制;未看到提醒时,可在复制记录中接收。",+ "notificationsUnavailable": "系统通知暂不可用,请从复制记录接收大文件。",+ "enableNotifications": "开启提醒",+ "notificationSettings": "通知设置",+ "notifyPendingTitle": "接收后即可粘贴",+ "notifyPendingBody": "{device} · {name} · {size}\n尚未接收,暂不可粘贴。也可从复制记录接收。",+ "notifyReceivingTitle": "正在接收…",+ "notifyReceivingBody": "{name}\n可在复制记录查看接收进度。",+ "notifyReadyTitle": "已就绪,可以粘贴",+ "notifyReadyBody": "{name}\n已接收并放入剪贴板。",+ "notifyReceivedTitle": "已接收",+ "notifyReceivedBody": "{name}\n已保留当前剪贴板,点击放入剪贴板后可粘贴,也可从复制记录操作。",+ "notifyFailedTitle": "接收失败",+ "notifyFailedBody": "{name}\n{error}\n可从此通知或复制记录重试。",+ "notifyClipboardFailedTitle": "已接收,但未能写入剪贴板",+ "notifyClipboardFailedBody": "{name}\n{error}\n可从此通知或复制记录重新放入剪贴板。","appName": "隔空贴","navHistory": "复制记录","navDevices": "设备",@@ -62,8 +87,8 @@"permDeniedBody": "在这台 Mac 上复制的内容不会同步出去。到系统设置里把 PasteFerry Daemon 改为「允许」。","permAskBody": "否则 macOS 每次都会弹窗询问。到系统设置里把 PasteFerry Daemon 改为「允许」。","openSystemSettings": "打开系统设置",- "fetch": "拉取到本机",- "fetchStarted": "开始拉取",+ "fetch": "接收",+ "fetchStarted": "正在接收,可在复制记录查看进度","transferFailed": "传输失败","expired": "已过期","putOnClipboard": "放入剪贴板",@@ -186,9 +211,9 @@"language": "语言","languageSystem": "跟随系统","sync": "同步",- "syncFootnote": "小于阈值的内容在复制时直接推送到其他设备;超过阈值的只同步一条记录,需要时在「复制记录」里点「拉取到本机」,避免大文件无谓地占用带宽和磁盘。",+ "syncFootnote": "小于阈值的内容在复制时直接推送到其他设备;超过阈值的只同步一条记录,需要时在「复制记录」里点「接收」,避免大文件无谓地占用带宽和磁盘。","autoSyncLimit": "自动同步上限",- "autoSyncLimitDesc": "超过这个大小的文件改为手动拉取",+ "autoSyncLimitDesc": "超过这个大小的文件改为手动接收","autoApply": "收到后直接写入剪贴板","autoApplyDesc": "关闭后,需要在「复制记录」里手动放入剪贴板","whatToSync": "同步哪些内容",diff --git a/ui/lib/l10n/app_zh_Hant_HK.arb b/ui/lib/l10n/app_zh_Hant_HK.arbindex 2eb8f82..82a7f5c 100644--- a/ui/lib/l10n/app_zh_Hant_HK.arb+++ b/ui/lib/l10n/app_zh_Hant_HK.arb@@ -1,5 +1,30 @@{"@@locale": "zh_Hant_HK",+ "buildDetails": "介面 {uiVersion} · 背景服務 {serviceVersion} · 版本識別 {build}",+ "notReceived": "尚未接收,暫不可貼上",+ "receivedPreserved": "已接收,按放入剪貼簿後即可貼上",+ "clipboardWriteFailed": "已接收,但無法寫入剪貼簿",+ "receivingStatus": "正在接收…",+ "largeFileNotifications": "大檔案接收提醒",+ "notificationsAllowed": "已允許系統通知,接收進度可在複製記錄中查看。",+ "notificationsNotRequested": "開啟系統通知,避免大檔案等待接收時沒有提示;亦可隨時從複製記錄接收。",+ "notificationsDenied": "系統通知已關閉,請在系統設定中開啟;待接收內容仍可從複製記錄接收。",+ "notificationsUnknown": "通知顯示和勿擾由系統控制;未看到提示時,可在複製記錄中接收。",+ "notificationsUnavailable": "系統通知暫時無法使用,請從複製記錄接收大檔案。",+ "enableNotifications": "開啟提醒",+ "notificationSettings": "通知設定",+ "notifyPendingTitle": "接收後即可貼上",+ "notifyPendingBody": "{device} · {name} · {size}\n尚未接收,暫不可貼上。亦可從複製記錄接收。",+ "notifyReceivingTitle": "正在接收…",+ "notifyReceivingBody": "{name}\n可在複製記錄查看接收進度。",+ "notifyReadyTitle": "已就緒,可以貼上",+ "notifyReadyBody": "{name}\n已接收並放入剪貼簿。",+ "notifyReceivedTitle": "已接收",+ "notifyReceivedBody": "{name}\n已保留目前剪貼簿,按放入剪貼簿後即可貼上,亦可從複製記錄操作。",+ "notifyFailedTitle": "接收失敗",+ "notifyFailedBody": "{name}\n{error}\n可從此通知或複製記錄重試。",+ "notifyClipboardFailedTitle": "已接收,但無法寫入剪貼簿",+ "notifyClipboardFailedBody": "{name}\n{error}\n可從此通知或複製記錄重新放入剪貼簿。","appName": "隔空貼","navHistory": "複製記錄","navDevices": "裝置",@@ -62,8 +87,8 @@"permDeniedBody": "在這部 Mac 上複製的內容不會同步出去。請到系統設定裏把 PasteFerry Daemon 改為「允許」。","permAskBody": "否則 macOS 每次都會彈出視窗詢問。請到系統設定裏把 PasteFerry Daemon 改為「允許」。","openSystemSettings": "開啟系統設定",- "fetch": "拉取到本機",- "fetchStarted": "開始拉取",+ "fetch": "接收",+ "fetchStarted": "正在接收,可在複製記錄查看進度","transferFailed": "傳輸失敗","expired": "已過期","putOnClipboard": "放入剪貼簿",@@ -186,9 +211,9 @@"language": "語言","languageSystem": "跟隨系統","sync": "同步",- "syncFootnote": "小於上限的內容在複製時直接推送到其他裝置;超過上限的只同步一條記錄,需要時在「複製記錄」裏按「拉取到本機」,避免大檔案無謂地佔用頻寬和磁碟空間。",+ "syncFootnote": "小於上限的內容在複製時直接推送到其他裝置;超過上限的只同步一條記錄,需要時在「複製記錄」裏按「接收」,避免大檔案無謂地佔用頻寬和磁碟空間。","autoSyncLimit": "自動同步上限",- "autoSyncLimitDesc": "超過這個大小的檔案改為手動拉取",+ "autoSyncLimitDesc": "超過這個大小的檔案改為手動接收","autoApply": "收到後直接寫入剪貼簿","autoApplyDesc": "關閉後,需要在「複製記錄」裏手動放入剪貼簿","whatToSync": "同步哪些內容",diff --git a/ui/lib/l10n/app_zh_Hant_TW.arb b/ui/lib/l10n/app_zh_Hant_TW.arbindex 81c38e2..265d4b8 100644--- a/ui/lib/l10n/app_zh_Hant_TW.arb+++ b/ui/lib/l10n/app_zh_Hant_TW.arb@@ -1,5 +1,30 @@{"@@locale": "zh_Hant_TW",+ "buildDetails": "介面 {uiVersion} · 背景服務 {serviceVersion} · 建置 {build}",+ "notReceived": "尚未接收,暫不可貼上",+ "receivedPreserved": "已接收,點選放入剪貼簿後即可貼上",+ "clipboardWriteFailed": "已接收,但無法寫入剪貼簿",+ "receivingStatus": "正在接收…",+ "largeFileNotifications": "大檔案接收提醒",+ "notificationsAllowed": "已允許系統通知,接收進度可在複製記錄中查看。",+ "notificationsNotRequested": "開啟系統通知,避免大檔案等待接收時沒有提醒;也可隨時從複製記錄接收。",+ "notificationsDenied": "系統通知已關閉,請在系統設定中開啟;待接收內容仍可從複製記錄接收。",+ "notificationsUnknown": "通知顯示和勿擾由系統控制;未看到提醒時,可在複製記錄中接收。",+ "notificationsUnavailable": "系統通知暫時無法使用,請從複製記錄接收大檔案。",+ "enableNotifications": "開啟提醒",+ "notificationSettings": "通知設定",+ "notifyPendingTitle": "接收後即可貼上",+ "notifyPendingBody": "{device} · {name} · {size}\n尚未接收,暫不可貼上。也可從複製記錄接收。",+ "notifyReceivingTitle": "正在接收…",+ "notifyReceivingBody": "{name}\n可在複製記錄查看接收進度。",+ "notifyReadyTitle": "已就緒,可以貼上",+ "notifyReadyBody": "{name}\n已接收並放入剪貼簿。",+ "notifyReceivedTitle": "已接收",+ "notifyReceivedBody": "{name}\n已保留目前剪貼簿,點選放入剪貼簿後即可貼上,也可從複製記錄操作。",+ "notifyFailedTitle": "接收失敗",+ "notifyFailedBody": "{name}\n{error}\n可從此通知或複製記錄重試。",+ "notifyClipboardFailedTitle": "已接收,但無法寫入剪貼簿",+ "notifyClipboardFailedBody": "{name}\n{error}\n可從此通知或複製記錄重新放入剪貼簿。","appName": "隔空貼","navHistory": "複製記錄","navDevices": "裝置",@@ -62,8 +87,8 @@"permDeniedBody": "在這台 Mac 上複製的內容不會同步出去。請到系統設定裡把 PasteFerry Daemon 改為「允許」。","permAskBody": "否則 macOS 每次都會跳出視窗詢問。請到系統設定裡把 PasteFerry Daemon 改為「允許」。","openSystemSettings": "打開系統設定",- "fetch": "拉取到本機",- "fetchStarted": "開始拉取",+ "fetch": "接收",+ "fetchStarted": "正在接收,可在複製記錄查看進度","transferFailed": "傳輸失敗","expired": "已過期","putOnClipboard": "放入剪貼簿",@@ -186,9 +211,9 @@"language": "語言","languageSystem": "跟隨系統","sync": "同步",- "syncFootnote": "小於上限的內容在複製時直接推送到其他裝置;超過上限的只同步一筆記錄,需要時在「複製記錄」裡點「拉取到本機」,避免大檔案白白佔用頻寬和磁碟空間。",+ "syncFootnote": "小於上限的內容在複製時直接推送到其他裝置;超過上限的只同步一筆記錄,需要時在「複製記錄」裡點「接收」,避免大檔案白白佔用頻寬和磁碟空間。","autoSyncLimit": "自動同步上限",- "autoSyncLimitDesc": "超過這個大小的檔案改為手動拉取",+ "autoSyncLimitDesc": "超過這個大小的檔案改為手動接收","autoApply": "收到後直接寫入剪貼簿","autoApplyDesc": "關閉後,需要在「複製記錄」裡手動放入剪貼簿","whatToSync": "同步哪些內容",diff --git a/ui/lib/pages/history_page.dart b/ui/lib/pages/history_page.dartindex 92ea4c3..0e9c52b 100644--- a/ui/lib/pages/history_page.dart+++ b/ui/lib/pages/history_page.dart@@ -256,6 +256,17 @@ class _RecordRowState extends State<_RecordRow> {final p = context.palette;// 剪贴板里的图片、以及复制的图片文件,点一下这一行就能预览,不另放按钮final previewable = r.imageCount > 0;+ final outcome = AppScope.of(context).clipboardResultOf(r.id);+ final detail = switch (r.status) {+ ClipStatus.CLIP_STATUS_REMOTE_ONLY => context.l10n.notReceived,+ ClipStatus.CLIP_STATUS_FETCHING => context.l10n.receivingStatus,+ ClipStatus.CLIP_STATUS_FAILED => r.error.isEmpty ? context.l10n.transferFailed : r.error,+ _ => switch (outcome?.outcome) {+ ClipboardWriteOutcome.CLIPBOARD_WRITE_OUTCOME_PRESERVED => context.l10n.receivedPreserved,+ ClipboardWriteOutcome.CLIPBOARD_WRITE_OUTCOME_FAILED => context.l10n.clipboardWriteFailed,+ _ => null,+ },+ };return MouseRegion(cursor: previewable ? SystemMouseCursors.click : MouseCursor.defer,@@ -303,6 +314,16 @@ class _RecordRowState extends State<_RecordRow> {maxLines: 1,overflow: TextOverflow.ellipsis,),+ if (detail != null) ...[+ const SizedBox(height: 2),+ Tooltip(+ message: outcome?.error.isNotEmpty == true ? outcome!.error : detail,+ child: Text(detail, maxLines: 2, overflow: TextOverflow.ellipsis,+ style: context.text.bodySmall?.copyWith(color:+ r.status == ClipStatus.CLIP_STATUS_FAILED || outcome?.outcome == ClipboardWriteOutcome.CLIPBOARD_WRITE_OUTCOME_FAILED+ ? p.danger : p.textDim)),+ ),+ ],],),),@@ -344,7 +365,10 @@ class _RecordRowState extends State<_RecordRow> {case ClipStatus.CLIP_STATUS_FAILED:return Tooltip(message: r.error.isEmpty ? l.transferFailed : r.error,- child: Text(l.transferFailed, style: context.text.bodySmall?.copyWith(color: p.danger)),+ child: OutlinedButton(+ onPressed: () => _run(() => AppScope.read(context).fetch(r.id), l.fetchStarted),+ child: Text(l.retry),+ ),);case ClipStatus.CLIP_STATUS_EXPIRED:return Text(l.expired, style: context.text.bodySmall?.copyWith(color: p.textFaint));@@ -352,7 +376,8 @@ class _RecordRowState extends State<_RecordRow> {// 悬停时才显示「放入剪贴板」与删除,静态时列表保持干净。// 不悬停时它们只是看不见,位置照样留着:鼠标移上来时标题不会被挤短一截Widget hoverOnly(Widget child) => Visibility(- visible: _hovered,+ visible: _hovered || (AppScope.of(context).clipboardResultOf(r.id)?.outcome != null &&+ AppScope.of(context).clipboardResultOf(r.id)?.outcome != ClipboardWriteOutcome.CLIPBOARD_WRITE_OUTCOME_APPLIED),maintainSize: true,maintainAnimation: true,maintainState: true,diff --git a/ui/lib/pages/settings_page.dart b/ui/lib/pages/settings_page.dartindex 8989342..86ee4e7 100644--- a/ui/lib/pages/settings_page.dart+++ b/ui/lib/pages/settings_page.dart@@ -5,6 +5,7 @@ import 'package:fixnum/fixnum.dart';import 'package:flutter/material.dart';import '../app_state.dart';+import '../background_service.dart';import '../gen/pasteferry/v1/daemon.pb.dart';import '../i18n.dart';import '../main.dart';@@ -21,7 +22,14 @@ class SettingsPage extends StatefulWidget {State<SettingsPage> createState() => _SettingsPageState();}-class _SettingsPageState extends State<SettingsPage> {+class _SettingsPageState extends State<SettingsPage> with WidgetsBindingObserver {+ @override+ void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); }++ @override+ void didChangeAppLifecycleState(AppLifecycleState state) {+ if (state == AppLifecycleState.resumed && mounted) AppScope.read(context).refreshNotificationStatus();+ }final _serverController = TextEditingController();final _nameController = TextEditingController();bool _serverDirty = false;@@ -31,6 +39,7 @@ class _SettingsPageState extends State<SettingsPage> {@overridevoid dispose() {+ WidgetsBinding.instance.removeObserver(this);_serverController.dispose();_nameController.dispose();super.dispose();@@ -205,6 +214,27 @@ class _SettingsPageState extends State<SettingsPage> {onChanged: (v) => _update(state, cfg..autoSyncThresholdBytes = Int64(v)),),),+ SettingRow(+ title: l.largeFileNotifications,+ description: switch (state.notificationStatus?.permission) {+ 'allowed' => l.notificationsAllowed,+ 'not_requested' => l.notificationsNotRequested,+ 'denied' => l.notificationsDenied,+ 'unknown' => l.notificationsUnknown,+ _ => l.notificationsUnavailable,+ },+ child: state.notificationStatus?.supported == true &&+ !(Platform.isLinux && state.notificationStatus?.permission == 'unknown')+ ? TextButton(+ onPressed: () async {+ try { await state.requestNotifications(); }+ catch (e) { if (context.mounted) showToast(context, AppState.describeError(e), error: true); }+ },+ child: Text(state.notificationStatus?.permission == 'not_requested'+ ? l.enableNotifications : l.notificationSettings),+ )+ : TextButton(onPressed: state.refreshNotificationStatus, child: Text(l.retry)),+ ),SettingRow(title: l.autoApply,description: l.autoApplyDesc,@@ -298,7 +328,9 @@ class _SettingsPageState extends State<SettingsPage> {child: GroupBox(children: [SettingRow(title: '${l.appName} ${state.status?.version ?? ''}',- description: l.aboutDesc,+ description: appBuild.isEmpty+ ? l.aboutDesc+ : '${l.aboutDesc}\n${l.buildDetails(appVersion, state.status?.version ?? '…', appBuild)}',child: Row(mainAxisSize: MainAxisSize.min,children: [diff --git a/ui/test/large_file_receive_test.dart b/ui/test/large_file_receive_test.dartnew file mode 100644index 0000000..a54c5f5--- /dev/null+++ b/ui/test/large_file_receive_test.dart@@ -0,0 +1,54 @@+import 'package:fixnum/fixnum.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:pasteferry_ui/app_state.dart';+import 'package:pasteferry_ui/gen/pasteferry/v1/daemon.pb.dart';+import 'package:pasteferry_ui/main.dart';++class _ReceiveState extends AppState {+ final received = <String>[];+ @override+ Future<void> fetch(String id) async { received.add(id); }+}++_ReceiveState _seed(ClipStatus status, {String language = 'en'}) => _ReceiveState()+ ..debugSeed(status: Status(), config: Config(language: language), self: Device(id: 'self'), records: [+ ClipRecord(id: 'large', kind: ClipKind.CLIP_KIND_FILE, status: status,+ items: [ClipItem(name: 'archive.zip')], totalSize: Int64(80 << 20), originDeviceName: 'Office PC',+ error: status == ClipStatus.CLIP_STATUS_FAILED ? 'Source is offline' : ''),+ ]);++void main() {+ testWidgets('pending item explains why paste is unavailable and offers receive', (tester) async {+ final state = _seed(ClipStatus.CLIP_STATUS_REMOTE_ONLY);+ await tester.pumpWidget(PasteFerryApp(state: state));+ expect(find.text('Not received — receive before pasting'), findsOneWidget);+ await tester.tap(find.widgetWithText(OutlinedButton, 'Receive'));+ await tester.pump();+ expect(state.received, ['large']);+ });++ testWidgets('failed receive keeps the reason and a retry action', (tester) async {+ final state = _seed(ClipStatus.CLIP_STATUS_FAILED);+ await tester.pumpWidget(PasteFerryApp(state: state));+ expect(find.text('Source is offline'), findsOneWidget);+ await tester.tap(find.widgetWithText(OutlinedButton, 'Try again'));+ await tester.pump();+ expect(state.received, ['large']);+ });++ testWidgets('downloaded item preserves clipboard result and exposes apply without hover', (tester) async {+ final state = _seed(ClipStatus.CLIP_STATUS_READY);+ await tester.pumpWidget(PasteFerryApp(state: state));+ state.debugEvent(Event(clipboardWritten: ClipboardWriteResult(clipId: 'large',+ outcome: ClipboardWriteOutcome.CLIPBOARD_WRITE_OUTCOME_PRESERVED)));+ await tester.pump();+ expect(find.text('Received; use Copy to clipboard when ready'), findsOneWidget);+ expect(find.widgetWithText(TextButton, 'Copy to clipboard').hitTestable(), findsOneWidget);+ state.debugEvent(Event(clipboardWritten: ClipboardWriteResult(clipId: 'large',+ outcome: ClipboardWriteOutcome.CLIPBOARD_WRITE_OUTCOME_FAILED, error: 'Clipboard is busy')));+ await tester.pump();+ expect(find.text('Received, but the clipboard could not be updated'), findsOneWidget);+ expect(state.records.single.status, ClipStatus.CLIP_STATUS_READY);+ });+}diff --git a/ui/tool/l10n/strings.py b/ui/tool/l10n/strings.pyindex 636544d..8e2e6b3 100644--- a/ui/tool/l10n/strings.py+++ b/ui/tool/l10n/strings.py@@ -14,6 +14,32 @@ import refrom pathlib import PathS = [+ ('buildDetails', 'UI {uiVersion} · Service {serviceVersion} · Build {build}', '界面 {uiVersion} · 后台 {serviceVersion} · 构建 {build}', 'UI {uiVersion} · サービス {serviceVersion} · ビルド {build}', '介面 {uiVersion} · 背景服務 {serviceVersion} · 建置 {build}', '介面 {uiVersion} · 背景服務 {serviceVersion} · 版本識別 {build}'),+ ('notReceived', 'Not received — receive before pasting', '尚未接收,暂不可粘贴', '未受信 — ペーストする前に受信してください', '尚未接收,暫不可貼上', '尚未接收,暫不可貼上'),+ ('receivedPreserved', 'Received; use Copy to clipboard when ready', '已接收,点击放入剪贴板后可粘贴', '受信済み。クリップボードに入れるとペーストできます', '已接收,點選放入剪貼簿後即可貼上', '已接收,按放入剪貼簿後即可貼上'),+ ('clipboardWriteFailed', 'Received, but the clipboard could not be updated', '已接收,但未能写入剪贴板', '受信済みですが、クリップボードを更新できませんでした', '已接收,但無法寫入剪貼簿', '已接收,但無法寫入剪貼簿'),+ ('receivingStatus', 'Receiving…', '正在接收…', '受信中…', '正在接收…', '正在接收…'),+ ('largeFileNotifications', 'Large file reminders', '大文件接收提醒', '大きなファイルの受信通知', '大檔案接收提醒', '大檔案接收提醒'),+ ('notificationsAllowed', 'Notifications are enabled. Progress is shown in History.', '已允许系统通知,接收进度在复制记录中查看。', '通知は有効です。受信の進捗は履歴で確認できます。', '已允許系統通知,接收進度可在複製記錄中查看。', '已允許系統通知,接收進度可在複製記錄中查看。'),+ ('notificationsNotRequested', 'Enable notifications so large files do not wait silently. You can always receive them from History.', '开启系统通知,避免大文件等待接收时没有提示;也可随时从复制记录接收。', '大きなファイルの受信待ちを通知します。履歴からいつでも受信できます。', '開啟系統通知,避免大檔案等待接收時沒有提醒;也可隨時從複製記錄接收。', '開啟系統通知,避免大檔案等待接收時沒有提示;亦可隨時從複製記錄接收。'),+ ('notificationsDenied', 'Notifications are blocked in system settings. Receive pending items from History.', '系统通知已关闭,请在系统设置中开启;待接收内容仍可从复制记录接收。', 'システム設定で通知が無効です。受信待ちの項目は履歴から受信できます。', '系統通知已關閉,請在系統設定中開啟;待接收內容仍可從複製記錄接收。', '系統通知已關閉,請在系統設定中開啟;待接收內容仍可從複製記錄接收。'),+ ('notificationsUnknown', 'Your desktop controls notification delivery and Do Not Disturb. Receive items from History if no reminder appears.', '通知显示和勿扰由系统控制;未看到提醒时,可在复制记录中接收。', '通知とおやすみモードはデスクトップで管理されます。通知がない場合は履歴から受信できます。', '通知顯示和勿擾由系統控制;未看到提醒時,可在複製記錄中接收。', '通知顯示和勿擾由系統控制;未看到提示時,可在複製記錄中接收。'),+ ('notificationsUnavailable', 'System notifications are unavailable. Receive large files from History.', '系统通知暂不可用,请从复制记录接收大文件。', 'システム通知を利用できません。大きなファイルは履歴から受信してください。', '系統通知暫時無法使用,請從複製記錄接收大檔案。', '系統通知暫時無法使用,請從複製記錄接收大檔案。'),+ ('enableNotifications', 'Enable reminders', '开启提醒', '通知を有効にする', '開啟提醒', '開啟提醒'),+ ('notificationSettings', 'Notification settings', '通知设置', '通知設定', '通知設定', '通知設定'),+ ('notifyPendingTitle', 'Receive to paste', '接收后即可粘贴', '受信するとペーストできます', '接收後即可貼上', '接收後即可貼上'),+ ('notifyPendingBody', '{device} · {name} · {size}\nReceive this item before pasting. You can also receive it from History.', '{device} · {name} · {size}\n尚未接收,暂不可粘贴。也可从复制记录接收。', '{device} · {name} · {size}\nペーストする前に受信してください。履歴からも受信できます。', '{device} · {name} · {size}\n尚未接收,暫不可貼上。也可從複製記錄接收。', '{device} · {name} · {size}\n尚未接收,暫不可貼上。亦可從複製記錄接收。'),+ ('notifyReceivingTitle', 'Receiving…', '正在接收…', '受信中…', '正在接收…', '正在接收…'),+ ('notifyReceivingBody', '{name}\nSee History for progress.', '{name}\n可在复制记录查看接收进度。', '{name}\n進捗は履歴で確認できます。', '{name}\n可在複製記錄查看接收進度。', '{name}\n可在複製記錄查看接收進度。'),+ ('notifyReadyTitle', 'Ready to paste', '已就绪,可以粘贴', 'ペーストできます', '已就緒,可以貼上', '已就緒,可以貼上'),+ ('notifyReadyBody', '{name}\nReceived and placed on the clipboard.', '{name}\n已接收并放入剪贴板。', '{name}\n受信してクリップボードに入れました。', '{name}\n已接收並放入剪貼簿。', '{name}\n已接收並放入剪貼簿。'),+ ('notifyReceivedTitle', 'Received', '已接收', '受信しました', '已接收', '已接收'),+ ('notifyReceivedBody', '{name}\nYour clipboard was kept. Use Copy to clipboard when ready; this is also available in History.', '{name}\n已保留当前剪贴板,点击放入剪贴板后可粘贴,也可从复制记录操作。', '{name}\n現在のクリップボードは保持しました。クリップボードに入れる操作は履歴からもできます。', '{name}\n已保留目前剪貼簿,點選放入剪貼簿後即可貼上,也可從複製記錄操作。', '{name}\n已保留目前剪貼簿,按放入剪貼簿後即可貼上,亦可從複製記錄操作。'),+ ('notifyFailedTitle', 'Could not receive', '接收失败', '受信できませんでした', '接收失敗', '接收失敗'),+ ('notifyFailedBody', '{name}\n{error}\nTry again from this notification or History.', '{name}\n{error}\n可从此通知或复制记录重试。', '{name}\n{error}\nこの通知または履歴から再試行できます。', '{name}\n{error}\n可從此通知或複製記錄重試。', '{name}\n{error}\n可從此通知或複製記錄重試。'),+ ('notifyClipboardFailedTitle', 'Received; clipboard was not updated', '已接收,但未能写入剪贴板', '受信済みですがクリップボードを更新できませんでした', '已接收,但無法寫入剪貼簿', '已接收,但無法寫入剪貼簿'),+ ('notifyClipboardFailedBody', '{name}\n{error}\nUse Copy to clipboard to try again, here or in History.', '{name}\n{error}\n可从此通知或复制记录重新放入剪贴板。', '{name}\n{error}\nこの通知または履歴からクリップボードに入れて再試行できます。', '{name}\n{error}\n可從此通知或複製記錄重新放入剪貼簿。', '{name}\n{error}\n可從此通知或複製記錄重新放入剪貼簿。'),+# ── 侧边栏与连接状态 ──# 产品名:中文界面叫隔空贴,其他语言叫 PasteFerry。窗口标题、可执行文件等系统里看得到的名字一律用 PasteFerry("appName", "PasteFerry", "隔空贴", "PasteFerry", "隔空貼", "隔空貼"),@@ -87,8 +113,8 @@ S = [("permDeniedBody", "What you copy on this Mac won't be synced. In System Settings, set PasteFerry Daemon to Allow.", "在这台 Mac 上复制的内容不会同步出去。到系统设置里把 PasteFerry Daemon 改为「允许」。", "この Mac でコピーした内容は同期されません。システム設定で PasteFerry Daemon を「許可」にしてください。", "在這台 Mac 上複製的內容不會同步出去。請到系統設定裡把 PasteFerry Daemon 改為「允許」。", "在這部 Mac 上複製的內容不會同步出去。請到系統設定裏把 PasteFerry Daemon 改為「允許」。"),("permAskBody", "Otherwise macOS asks every time. In System Settings, set PasteFerry Daemon to Allow.", "否则 macOS 每次都会弹窗询问。到系统设置里把 PasteFerry Daemon 改为「允许」。", "許可しないと macOS が毎回確認します。システム設定で PasteFerry Daemon を「許可」にしてください。", "否則 macOS 每次都會跳出視窗詢問。請到系統設定裡把 PasteFerry Daemon 改為「允許」。", "否則 macOS 每次都會彈出視窗詢問。請到系統設定裏把 PasteFerry Daemon 改為「允許」。"),("openSystemSettings", "Open System Settings", "打开系统设置", "システム設定を開く", "打開系統設定", "開啟系統設定"),- ("fetch", "Pull to this device", "拉取到本机", "このデバイスに取り込む", "拉取到本機", "拉取到本機"),- ("fetchStarted", "Pulling…", "开始拉取", "取り込みを開始しました", "開始拉取", "開始拉取"),+ ("fetch", "Receive", "接收", "受信", "接收", "接收"),+ ("fetchStarted", "Receiving… See History for progress", "正在接收,可在复制记录查看进度", "受信中…進捗は履歴で確認できます", "正在接收,可在複製記錄查看進度", "正在接收,可在複製記錄查看進度"),("transferFailed", "Transfer failed", "传输失败", "転送に失敗しました", "傳輸失敗", "傳輸失敗"),("expired", "Expired", "已过期", "期限切れ", "已過期", "已過期"),("putOnClipboard", "Copy to clipboard", "放入剪贴板", "クリップボードに入れる", "放入剪貼簿", "放入剪貼簿"),@@ -223,9 +249,9 @@ S = [("language", "Language", "语言", "言語", "語言", "語言"),("languageSystem", "System", "跟随系统", "システムに合わせる", "跟隨系統", "跟隨系統"),("sync", "Sync", "同步", "同期", "同步", "同步"),- ("syncFootnote", "Items under the limit are pushed to your other devices as you copy. Larger ones sync as a record; pull them from History when you need them, so big files don't waste bandwidth or disk space.", "小于阈值的内容在复制时直接推送到其他设备;超过阈值的只同步一条记录,需要时在「复制记录」里点「拉取到本机」,避免大文件无谓地占用带宽和磁盘。", "上限より小さい内容はコピーした時点で他のデバイスに送られます。大きいものは記録だけを同期し、必要なときに「履歴」から取り込むので、帯域やディスクを無駄に使いません。", "小於上限的內容在複製時直接推送到其他裝置;超過上限的只同步一筆記錄,需要時在「複製記錄」裡點「拉取到本機」,避免大檔案白白佔用頻寬和磁碟空間。", "小於上限的內容在複製時直接推送到其他裝置;超過上限的只同步一條記錄,需要時在「複製記錄」裏按「拉取到本機」,避免大檔案無謂地佔用頻寬和磁碟空間。"),+ ("syncFootnote", "Items under the limit are pushed to your other devices as you copy. Larger ones sync as a record; receive them from History when you need them, so big files don't waste bandwidth or disk space.", "小于阈值的内容在复制时直接推送到其他设备;超过阈值的只同步一条记录,需要时在「复制记录」里点「接收」,避免大文件无谓地占用带宽和磁盘。", "上限より小さい内容はコピーした時点で他のデバイスに送られます。大きいものは記録だけを同期し、必要なときに「履歴」から取り込むので、帯域やディスクを無駄に使いません。", "小於上限的內容在複製時直接推送到其他裝置;超過上限的只同步一筆記錄,需要時在「複製記錄」裡點「接收」,避免大檔案白白佔用頻寬和磁碟空間。", "小於上限的內容在複製時直接推送到其他裝置;超過上限的只同步一條記錄,需要時在「複製記錄」裏按「接收」,避免大檔案無謂地佔用頻寬和磁碟空間。"),("autoSyncLimit", "Auto-sync limit", "自动同步上限", "自動同期の上限", "自動同步上限", "自動同步上限"),- ("autoSyncLimitDesc", "Larger files are pulled by hand", "超过这个大小的文件改为手动拉取", "これより大きいファイルは手動で取り込みます", "超過這個大小的檔案改為手動拉取", "超過這個大小的檔案改為手動拉取"),+ ("autoSyncLimitDesc", "Larger files must be received before pasting", "超过这个大小的文件改为手动接收", "これより大きいファイルは手動で取り込みます", "超過這個大小的檔案改為手動接收", "超過這個大小的檔案改為手動接收"),("autoApply", "Put received items on the clipboard", "收到后直接写入剪贴板", "受け取った内容をクリップボードに入れる", "收到後直接寫入剪貼簿", "收到後直接寫入剪貼簿"),("autoApplyDesc", "When off, put them on the clipboard from History yourself", "关闭后,需要在「复制记录」里手动放入剪贴板", "オフの場合は「履歴」から手動でクリップボードに入れます", "關閉後,需要在「複製記錄」裡手動放入剪貼簿", "關閉後,需要在「複製記錄」裏手動放入剪貼簿"),("whatToSync", "What to sync", "同步哪些内容", "同期する内容", "同步哪些內容", "同步哪些內容"),@@ -339,6 +365,10 @@ def main() -> None:data[row[0]] = row[index](out / f"app_{locale}.arb").write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")(out / "app_en.arb").write_text(json.dumps(en, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")+ native = {lang: {row[0]: row[index] for row in S if row[0].startswith("notify") or row[0] in {"fetch", "putOnClipboard", "navHistory", "retry"}}+ for lang, index in (("en", 1), ("zh-Hans", 2), ("ja", 3), ("zh-Hant-TW", 4), ("zh-Hant-HK", 5))}+ native_path = Path(__file__).resolve().parents[3] / "client-core/internal/notifications/catalog.json"+ native_path.write_text(json.dumps(native, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")print(f"✓ {len(S)} 条,写入 {out}")