From f3e89067efad98177190e7df33ccf31c6d26c29f Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 22:01:43 +0800 Subject: [PATCH 1/7] =?UTF-8?q?fix(desktop):=20=E6=97=A5=E5=BF=97=E5=86=99?= =?UTF-8?q?=E5=85=A5=E5=99=A8=E6=98=BE=E7=A4=BA=E8=A2=AB=E6=8B=92=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E3=80=81=E6=8C=89=20Core=20=E5=94=A4=E9=86=92?= =?UTF-8?q?=E5=86=99=E5=85=A5=E5=B9=B6=E8=AE=B0=E5=BD=95=E7=9B=AE=E5=BD=95?= =?UTF-8?q?=E5=9B=9E=E9=80=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 被 Core 拒绝的事件按事件 ID 和错误码记录(最近 20 种),日志窗口状态栏和 collection-status.txt 显示数量与最近一条;不再算作写入失败。 - 整批编码失败的事件计入 dropped,由下一次写入的 log.dropped 报告;批内的 log.dropped 丢失时转交下一次报告,不重复计数。 - 去掉 500ms 轮询:Core 记录事实时通过 lithe_core_install_log_waker 回调安排一次 100ms 合并写入;详细诊断到期由写入器的一次性定时器关闭 Core 的 DEBUG 开关; 关闭时先移除回调再做最后一次写入。只有应用主进程的日志调用 ObserveCoreFacts。 - 自定义日志目录不可用、回退到默认目录时记录 app.logging.redirect_failed;读不出 logging.json 时记录 app.settings.decode_failed;推送 DEBUG 开关失败记录一次 app.logging.diagnostics_failed。 - 日志窗口不再把所有失败记成 app.logging.diagnostics_failed:用户操作失败记 app.notification.operation_failed,窗口自己的读取和保存失败记 app.background.operation_failed,都带 operation。 - ErrorFields 移到 core.LogErrorFields,供各处共用。 --- desktop/cmd/lithe/main.go | 2 + desktop/internal/core/log_waker.go | 68 ++++ desktop/internal/core/logging.go | 39 +++ desktop/internal/i18n/en.go | 3 + desktop/internal/i18n/messages.go | 3 + desktop/internal/i18n/shared.generated.go | 2 + desktop/internal/i18n/zh.go | 3 + desktop/internal/logstore/collect.go | 16 +- desktop/internal/logstore/collect_test.go | 2 +- desktop/internal/logstore/query.go | 15 +- desktop/internal/logstore/store.go | 251 ++++++++++++--- desktop/internal/logstore/writer_test.go | 363 ++++++++++++++++++++++ desktop/internal/logwindow/export.go | 4 +- desktop/internal/logwindow/export_test.go | 43 ++- desktop/internal/logwindow/model.go | 111 ++++--- desktop/internal/logwindow/window.go | 9 +- desktop/internal/workbench/commit.go | 3 +- desktop/internal/workbench/documents.go | 5 +- desktop/internal/workbench/settings.go | 5 +- desktop/internal/workbench/terminal.go | 3 +- desktop/internal/workbench/updates.go | 5 +- shared/i18n/locales/en-US.json | 1 + shared/i18n/locales/zh-CN.json | 1 + shared/i18n/messages.json | 12 + 24 files changed, 859 insertions(+), 110 deletions(-) create mode 100644 desktop/internal/core/log_waker.go create mode 100644 desktop/internal/logstore/writer_test.go diff --git a/desktop/cmd/lithe/main.go b/desktop/cmd/lithe/main.go index 47b936e95c..823155ad96 100644 --- a/desktop/cmd/lithe/main.go +++ b/desktop/cmd/lithe/main.go @@ -44,6 +44,8 @@ func main() { if err != nil { fmt.Fprintln(os.Stderr, "lithe: log:", err) } else { + // Core holds one waker for the process; this client's log is the one that drains it. + logs.ObserveCoreFacts() options.Logs = logs } err = workbench.New(options).Run() diff --git a/desktop/internal/core/log_waker.go b/desktop/internal/core/log_waker.go new file mode 100644 index 0000000000..7b1867228d --- /dev/null +++ b/desktop/internal/core/log_waker.go @@ -0,0 +1,68 @@ +package core + +/* +#include +#include "lithe_core.h" + +extern void goLitheLogWake(uintptr_t identity); + +static void lithe_go_log_wake(void *context) { + goLitheLogWake((uintptr_t)context); +} + +static void lithe_go_install_log_waker(uintptr_t identity) { + lithe_core_install_log_waker(lithe_go_log_wake, (void *)identity); +} + +static int32_t lithe_go_remove_log_waker(uintptr_t identity) { + return lithe_core_remove_log_waker((void *)identity); +} +*/ +import "C" + +import ( + "sync" + "sync/atomic" +) + +// C only receives integer identities; the registry owns the Go callbacks until Core has +// removed the waker and no longer calls it. +var logWakers sync.Map +var logWakerID atomic.Uint64 + +// WatchCoreEvents asks the kernel to call wake when it queues a fact for the host's writer +// while the previous drain has not been followed by a wake yet, and at once when facts are +// already queued. wake runs on a kernel thread while the kernel holds its waker lock: it must +// only schedule a drain and never call into the kernel. A later watch replaces this one. stop +// removes the waker; once it returns wake is not running and is never called again, and +// calling stop again does nothing. +func (c *Client) WatchCoreEvents(wake func()) (stop func()) { + var id uintptr + for { + id = uintptr(logWakerID.Add(1)) + if id != 0 { + if _, loaded := logWakers.LoadOrStore(id, wake); !loaded { + break + } + } + } + C.lithe_go_install_log_waker(C.uintptr_t(id)) + var once sync.Once + return func() { + once.Do(func() { + C.lithe_go_remove_log_waker(C.uintptr_t(id)) + logWakers.Delete(id) + }) + } +} + +//export goLitheLogWake +func goLitheLogWake(identity C.uintptr_t) { + value, ok := logWakers.Load(uintptr(identity)) + if !ok { + return + } + // A Go panic must never unwind through Rust; a lost wake only delays the next drain. + defer func() { _ = recover() }() + value.(func())() +} diff --git a/desktop/internal/core/logging.go b/desktop/internal/core/logging.go index 8c240634fa..b932657112 100644 --- a/desktop/internal/core/logging.go +++ b/desktop/internal/core/logging.go @@ -2,7 +2,11 @@ package core import ( "context" + "errors" "fmt" + "strings" + "syscall" + "unicode/utf8" ) // LogLevel is the severity of a log record, in the kernel's canonical disk spelling. @@ -31,6 +35,38 @@ func (e *LogError) Error() string { return fmt.Sprintf("log error %d: %s", e.Code, e.Reason) } +// LogErrorFields encodes an error the way the event catalog asks for an error field: a bounded +// message without control characters, a code and the domain the code belongs to. The message +// is still redacted by the kernel before it reaches the disk. +func LogErrorFields(err error) map[string]any { + message := strings.Map(func(r rune) rune { + if r < 0x20 || r == 0x7f || (r >= 0x80 && r < 0xa0) { + return ' ' + } + return r + }, err.Error()) + if len(message) > 1024 { + cut := 1024 + for cut > 0 && !utf8.RuneStart(message[cut]) { + cut-- + } + message = message[:cut] + } + code, domain := any("unknown"), "go" + var logErr *LogError + var coreErr *Error + var errno syscall.Errno + switch { + case errors.As(err, &logErr): + code, domain = logErr.Code, "lithe.logging" + case errors.As(err, &coreErr): + code, domain = string(coreErr.Code), "lithe.core" + case errors.As(err, &errno): + code, domain = int(errno), "posix" + } + return map[string]any{"error": message, "error_code": code, "error_domain": domain} +} + // logResult is how the logging commands that can fail in their own domain answer: either the // result or a LogError, inside a successful kernel response. type logResult[T any] struct { @@ -122,6 +158,9 @@ type EncodedLog struct { Line string `json:"line"` // Error explains why the item was rejected; nil on success. Error *LogError `json:"error"` + // Index is the position of the input event a rejected result belongs to. Deduplication + // merges events, so the position of a result does not name its input; nil on success. + Index *int `json:"index,omitempty"` } // EncodedLogBatch is the encoder's answer, one entry per input in order. diff --git a/desktop/internal/i18n/en.go b/desktop/internal/i18n/en.go index ffb0191edf..e4dc99f842 100644 --- a/desktop/internal/i18n/en.go +++ b/desktop/internal/i18n/en.go @@ -458,6 +458,9 @@ var english = Messages{ WriteFailures: func(count int) string { return SharedFormat(English, "desktop.logs.writeFailures", map[string]string{"count": strconv.Itoa(count)}) }, + Rejected: func(count int, event string, code int) string { + return SharedFormat(English, "desktop.logs.rejected", map[string]string{"count": strconv.Itoa(count), "event": event, "code": strconv.Itoa(code)}) + }, Time: Shared(English, "logs.window.time"), Level: Shared(English, "logs.window.level"), Channel: Shared(English, "logs.window.channel"), diff --git a/desktop/internal/i18n/messages.go b/desktop/internal/i18n/messages.go index e61efe06c0..ae7c489b0f 100644 --- a/desktop/internal/i18n/messages.go +++ b/desktop/internal/i18n/messages.go @@ -738,6 +738,9 @@ type LogMessages struct { VisibleCount func(visible, total, line string) string Dropped func(count int) string WriteFailures func(count int) string + // Rejected counts the events the kernel refused and names the latest one; event and code + // are diagnostic identifiers and stay untranslated. + Rejected func(count int, event string, code int) string // The table's column titles, folded runs and context menu. Time string diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 9639d92db9..73274e64b5 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -874,6 +874,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.logs.newLogs": "↓ {count} new logs, jump to latest", "desktop.logs.operation": "Op {op} · {count} records · {duration}", "desktop.logs.paused": "Paused", + "desktop.logs.rejected": "rejected {count} (latest: {event} {code})", "desktop.logs.repeated": "Repeated {count} times · last {last}", "desktop.logs.revealInFinder": "Reveal in Finder", "desktop.logs.savedTo": "Saved to {path}", @@ -3461,6 +3462,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.logs.newLogs": "↓ {count} 条新日志,回到最新", "desktop.logs.operation": "操作 {op} · {count} 条 · 共 {duration}", "desktop.logs.paused": "已暂停", + "desktop.logs.rejected": "被拒绝 {count}(最近:{event} {code})", "desktop.logs.repeated": "重复 {count} 次 · 末次 {last}", "desktop.logs.revealInFinder": "在 Finder 中显示", "desktop.logs.savedTo": "已保存到 {path}", diff --git a/desktop/internal/i18n/zh.go b/desktop/internal/i18n/zh.go index eecab626c7..2e0a65d35d 100644 --- a/desktop/internal/i18n/zh.go +++ b/desktop/internal/i18n/zh.go @@ -458,6 +458,9 @@ var chinese = Messages{ WriteFailures: func(count int) string { return SharedFormat(Chinese, "desktop.logs.writeFailures", map[string]string{"count": strconv.Itoa(count)}) }, + Rejected: func(count int, event string, code int) string { + return SharedFormat(Chinese, "desktop.logs.rejected", map[string]string{"count": strconv.Itoa(count), "event": event, "code": strconv.Itoa(code)}) + }, Time: Shared(Chinese, "logs.window.time"), Level: Shared(Chinese, "logs.window.level"), Channel: Shared(Chinese, "logs.window.channel"), diff --git a/desktop/internal/logstore/collect.go b/desktop/internal/logstore/collect.go index 14c735ec66..dd5d5e23eb 100644 --- a/desktop/internal/logstore/collect.go +++ b/desktop/internal/logstore/collect.go @@ -141,9 +141,19 @@ func (s *Store) Collect(ctx context.Context, q ExportQuery) (Export, error) { } truncated := plan.Truncated || short || result.Truncated || result.SkippedInvalidLines > 0 dropped, failures := s.Stats() - status := fmt.Sprintf("truncated=%t dropped_events=%d write_failures=%d skipped_invalid_lines=%d\n", - truncated, dropped, failures, result.SkippedInvalidLines) - files = append(files, ExportFile{RelativePath: "collection-status.txt", Data: []byte(status)}) + rejected, rejections := s.Rejections() + var status strings.Builder + fmt.Fprintf(&status, "truncated=%t dropped_events=%d write_failures=%d rejected_events=%d skipped_invalid_lines=%d\n", + truncated, dropped, failures, rejected, result.SkippedInvalidLines) + // The newest reasons come first; an event id is code the application declares, never data. + for _, rejection := range slices.Backward(rejections) { + event := rejection.Event + if event == "" { + event = "unknown" + } + fmt.Fprintf(&status, "rejected event=%s code=%d count=%d\n", event, rejection.Code, rejection.Count) + } + files = append(files, ExportFile{RelativePath: "collection-status.txt", Data: []byte(status.String())}) return Export{ Files: files, Truncated: truncated, diff --git a/desktop/internal/logstore/collect_test.go b/desktop/internal/logstore/collect_test.go index c3a81fdf57..91fb974feb 100644 --- a/desktop/internal/logstore/collect_test.go +++ b/desktop/internal/logstore/collect_test.go @@ -51,7 +51,7 @@ func TestCollectGroupsTheRecordsByFile(t *testing.T) { t.Fatalf("log file holds the wrong records: %q", text) } if status.RelativePath != "collection-status.txt" || - string(status.Data) != "truncated=false dropped_events=0 write_failures=0 skipped_invalid_lines=0\n" { + string(status.Data) != "truncated=false dropped_events=0 write_failures=0 rejected_events=0 skipped_invalid_lines=0\n" { t.Fatalf("status file = %q: %q", status.RelativePath, status.Data) } } diff --git a/desktop/internal/logstore/query.go b/desktop/internal/logstore/query.go index ea85399300..df16b21211 100644 --- a/desktop/internal/logstore/query.go +++ b/desktop/internal/logstore/query.go @@ -51,8 +51,11 @@ type Collection struct { CurrentSessionPath string // Dropped and WriteFailures are the totals reported by Stats. Dropped, WriteFailures int - DiagnosticCategory string - DiagnosticRemaining time.Duration + // Rejected and Rejections are what Rejections reports. + Rejected int + Rejections []Rejection + DiagnosticCategory string + DiagnosticRemaining time.Duration } // LiveSummary is the histogram of the records the window currently holds, plus the writer's @@ -60,6 +63,8 @@ type Collection struct { type LiveSummary struct { Histogram *core.LogHistogram Dropped, WriteFailures int + Rejected int + Rejections []Rejection DiagnosticCategory string DiagnosticRemaining time.Duration } @@ -123,6 +128,7 @@ func (s *Store) QueryWindow(ctx context.Context, q Query) (Collection, error) { return Collection{}, err } dropped, failures := s.Stats() + rejected, rejections := s.Rejections() category, remaining, _ := s.Diagnostics() return Collection{ Result: result, @@ -130,6 +136,8 @@ func (s *Store) QueryWindow(ctx context.Context, q Query) (Collection, error) { CurrentSessionPath: session, Dropped: dropped, WriteFailures: failures, + Rejected: rejected, + Rejections: rejections, DiagnosticCategory: category, DiagnosticRemaining: remaining, }, nil @@ -181,11 +189,14 @@ func (s *Store) LiveSummary(ctx context.Context, records []core.LogRecord) (Live return LiveSummary{}, err } dropped, failures := s.Stats() + rejected, rejections := s.Rejections() category, remaining, _ := s.Diagnostics() return LiveSummary{ Histogram: result.Histogram, Dropped: dropped, WriteFailures: failures, + Rejected: rejected, + Rejections: rejections, DiagnosticCategory: category, DiagnosticRemaining: remaining, }, nil diff --git a/desktop/internal/logstore/store.go b/desktop/internal/logstore/store.go index 4643607acc..7ec938756a 100644 --- a/desktop/internal/logstore/store.go +++ b/desktop/internal/logstore/store.go @@ -21,6 +21,7 @@ import ( "fmt" "io/fs" "maps" + "math" "os" "path" "path/filepath" @@ -43,10 +44,9 @@ const ( defaultReserved = 2000 // batchSize is the most events one encoder call takes. batchSize = 256 - // coalesceDelay lets a burst of events share one drain. + // coalesceDelay lets a burst of events share one drain. The kernel's own facts arrive the + // same way: its waker schedules one drain, so an idle writer never polls. coalesceDelay = 100 * time.Millisecond - // kernelTick is how often the writer drains the kernel's own facts when the host is idle. - kernelTick = 500 * time.Millisecond // maintenanceInterval is how often retention runs; the first run is the startup cleanup. maintenanceInterval = time.Minute // defaultFileLimit rotates a channel file before it grows past this size. @@ -71,6 +71,10 @@ const ( controlLimit = 4 // controlTimeout bounds how long one control operation may take. controlTimeout = 10 * time.Second + // rejectionLimit is how many distinct (event, code) rejections the writer remembers. + rejectionLimit = 20 + // droppedEvent reports how many events never reached the disk. + droppedEvent = "log.dropped" // windowLimit and windowBuckets shape the log window's queries. windowLimit = 10000 windowBuckets = 90 @@ -111,6 +115,20 @@ type Kernel interface { PlanLogRetention(ctx context.Context, request core.LogRetentionRequest) (core.LogRetentionPlan, error) DrainCoreEvents(ctx context.Context) (core.CoreEvents, error) ConfigureCoreEvents(ctx context.Context, debug bool, roots []string) error + // WatchCoreEvents installs the kernel's single, process-wide waker; see ObserveCoreFacts. + WatchCoreEvents(wake func()) (stop func()) +} + +// Rejection counts the events the kernel refused to encode for one reason. A rejected event is +// a bug in the code that emitted it: an id the catalog does not declare, a level that differs +// from the catalog's, or fields of the wrong shape. +type Rejection struct { + // Event is the id the caller emitted; empty when the kernel did not say which input it was. + Event string + // Code is the logging v2 error code, for example -32055 for an invalid field. + Code int + // Count is how many times this pair was rejected since the process started. + Count int } // Options configures Open. @@ -128,10 +146,12 @@ type Options struct { // Now is the clock; nil means time.Now. Now func() time.Time - // The fields below shrink the limits so tests reach them with a handful of events. - capacity int - reserved int - fileLimit int + // The fields below shrink the limits so tests reach them with a handful of events, or the + // diagnostics window so a test sees it expire. + capacity int + reserved int + fileLimit int + diagnosticWindow time.Duration } // directorySetting is the content of logging.json. @@ -190,6 +210,8 @@ type Store struct { capacity int reserved int fileLimit int64 + // window is how long detailed diagnostics stay on, diagnosticWindow outside tests. + window time.Duration // mu guards the ingress state and the fields the writer publishes to other goroutines. // Only the writer goroutine changes directory and sessionPath, so the writer itself may @@ -201,11 +223,15 @@ type Store struct { dropped int unreportedDropped int failures int + rejected int + rejections []Rejection diagnosticUntil time.Time stopped bool controls int directory string sessionPath string + // unwatch removes the kernel's waker; nil while the store does not observe the kernel. + unwatch func() wake chan struct{} // work was queued; arm the coalescing timer full chan struct{} // a whole batch is waiting; drain now @@ -232,12 +258,16 @@ type Store struct { recent []Batch recentBytes int replays []replay + // expiry ends detailed diagnostics at expiryAt even when nothing else drains. + expiry *time.Timer + expiryC <-chan time.Time + expiryAt time.Time } // Open starts a store. It creates and probes the log directory, derives the session's path // from the kernel, starts the writer and queues the app.session.started event. A custom -// directory that cannot be used falls back to the default one; Open fails only when no -// directory works. +// directory that cannot be used falls back to the default one and the fallback is logged as +// app.logging.redirect_failed; Open fails only when no directory works. func Open(opts Options) (*Store, error) { if opts.Kernel == nil { return nil, errors.New("logstore: a kernel is required") @@ -257,8 +287,9 @@ func Open(opts Options) (*Store, error) { defaultDir, defaultErr = DefaultDir() } chosen := opts.Dir + var settingErr error if chosen == "" { - chosen = loadDirectory(opts.Settings) + chosen, settingErr = loadDirectory(opts.Settings) } if chosen == "" { if defaultErr != nil { @@ -284,6 +315,10 @@ func Open(opts Options) (*Store, error) { if opts.fileLimit > 0 { fileLimit = int64(opts.fileLimit) } + window := diagnosticWindow + if opts.diagnosticWindow > 0 { + window = opts.diagnosticWindow + } s := &Store{ kernel: opts.Kernel, @@ -297,6 +332,7 @@ func Open(opts Options) (*Store, error) { capacity: capacity, reserved: reserved, fileLimit: fileLimit, + window: window, wake: make(chan struct{}, 1), full: make(chan struct{}, 1), jobs: make(chan func()), @@ -307,9 +343,10 @@ func Open(opts Options) (*Store, error) { headers: make(map[string]string), handles: make(map[string]*openLog), } - if err := s.switchDirectory(chosen); err != nil { + redirectErr := s.switchDirectory(chosen) + if redirectErr != nil { if defaultDir == "" || chosen == defaultDir { - return nil, err + return nil, redirectErr } if fallbackErr := s.switchDirectory(defaultDir); fallbackErr != nil { return nil, fallbackErr @@ -322,9 +359,42 @@ func Open(opts Options) (*Store, error) { go s.run() s.Emit(core.LevelInfo, "app.session.started", "", nil) + if settingErr != nil { + fields := core.LogErrorFields(settingErr) + fields["stage"] = "log_directory" + s.Emit(core.LevelWarn, "app.settings.decode_failed", "", fields) + } + if redirectErr != nil { + s.redirected(chosen, redirectErr) + } return s, nil } +// redirected records that logging left dir for the default directory. It is emitted only after +// the default directory took over, so the record has somewhere to go and a failing directory +// can never make the writer log about itself in a loop. +func (s *Store) redirected(dir string, err error) { + fields := core.LogErrorFields(err) + fields["directory"] = dir + s.Emit(core.LevelWarn, "app.logging.redirect_failed", "", fields) +} + +// ObserveCoreFacts asks the kernel to wake the writer whenever it records a fact for the host, +// so those facts reach the disk within coalesceDelay even while the host itself is idle. The +// kernel keeps a single waker per process, so only the application's one store may observe; +// a store that does not observe drains the kernel's facts together with its own events. Close +// removes the waker before the final drain. +func (s *Store) ObserveCoreFacts() { + s.mu.Lock() + defer s.mu.Unlock() + if s.stopped || s.unwatch != nil { + return + } + // The kernel calls wake while holding its waker lock: it may only signal the writer, and + // signal neither blocks nor takes s.mu. + s.unwatch = s.kernel.WatchCoreEvents(func() { signal(s.wake) }) +} + // newSessionID returns a random version 4 UUID in lowercase, the form the kernel's session // naming expects. func newSessionID() (string, error) { @@ -337,16 +407,20 @@ func newSessionID() (string, error) { return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]), nil } -// loadDirectory reads the user's saved log directory; an unreadable setting means none. -func loadDirectory(settings *store.Store) string { +// loadDirectory reads the user's saved log directory. An unreadable setting means none, and +// its error is returned so Open can record why the default directory is used. +func loadDirectory(settings *store.Store) (string, error) { if settings == nil { - return "" + return "", nil } var saved directorySetting - if _, err := settings.Load(settingsName, &saved); err != nil || !filepath.IsAbs(saved.Directory) { - return "" + if _, err := settings.Load(settingsName, &saved); err != nil { + return "", err } - return saved.Directory + if !filepath.IsAbs(saved.Directory) { + return "", nil + } + return saved.Directory, nil } // formatTime renders an instant the way the kernel takes it. @@ -369,6 +443,52 @@ func (s *Store) fail() { s.mu.Unlock() } +// lose counts the events of a batch the kernel could not encode at all, so they reach neither +// the disk nor the live window. They are reported like queue overflow, by the log.dropped of a +// later drain. A log.dropped in the lost batch is not an event of its own: the loss it carried +// is reported again instead of being counted twice. +func (s *Store) lose(batch []core.LogEvent) { + s.mu.Lock() + defer s.mu.Unlock() + for _, event := range batch { + if event.Event == droppedEvent { + if count, ok := event.Fields["count"].(uint64); ok { + s.unreportedDropped = saturatingAdd(s.unreportedDropped, count) + continue + } + } + s.dropped++ + s.unreportedDropped++ + } +} + +// saturatingAdd adds a carried loss count without overflowing the counter. +func saturatingAdd(total int, count uint64) int { + if count > uint64(math.MaxInt-total) { + return math.MaxInt + } + return total + int(count) +} + +// reject remembers one event the kernel refused. The list keeps the most recently seen +// distinct (event, code) pairs, so a single faulty call site cannot hide the others. +func (s *Store) reject(event string, code int) { + s.mu.Lock() + defer s.mu.Unlock() + s.rejected++ + for i, known := range s.rejections { + if known.Event == event && known.Code == code { + known.Count++ + s.rejections = append(slices.Delete(s.rejections, i, i+1), known) + return + } + } + if len(s.rejections) >= rejectionLimit { + s.rejections = slices.Delete(s.rejections, 0, 1) + } + s.rejections = append(s.rejections, Rejection{Event: event, Code: code, Count: 1}) +} + // signal wakes the writer without ever blocking the caller. func signal(ch chan struct{}) { select { @@ -445,14 +565,22 @@ func (s *Store) SessionPath() string { return s.sessionPath } -// Stats reports how many events were dropped from a full queue and how many writes or -// maintenance steps failed since the process started. +// Stats reports how many events were dropped, from a full queue or with a batch the kernel +// could not encode, and how many writes or maintenance steps failed since the process started. func (s *Store) Stats() (dropped, writeFailures int) { s.mu.Lock() defer s.mu.Unlock() return s.dropped, s.failures } +// Rejections reports how many events the kernel refused since the process started and the most +// recent distinct reasons, oldest first. +func (s *Store) Rejections() (total int, recent []Rejection) { + s.mu.Lock() + defer s.mu.Unlock() + return s.rejected, slices.Clone(s.rejections) +} + // UsedBytes is the size of every log file in the directory, after writing what is queued. It is // zero when the directory cannot be read. func (s *Store) UsedBytes() int64 { @@ -496,14 +624,14 @@ func (s *Store) diagnosticsLocked(at time.Time) (string, time.Duration, bool) { } // ConfigureDiagnostics turns detailed diagnostics on or off. Turning them on lasts -// diagnosticWindow and then expires by itself; both the kernel's and the host's DEBUG events -// follow the same switch. +// diagnosticWindow and then expires by itself, on a one-shot timer of the writer; both the +// kernel's and the host's DEBUG events follow the same switch. func (s *Store) ConfigureDiagnostics(enabled bool) { err := s.do(context.Background(), func(ctx context.Context) error { at := s.now() s.mu.Lock() if enabled { - s.diagnosticUntil = at.Add(diagnosticWindow) + s.diagnosticUntil = at.Add(s.window) } else { s.diagnosticUntil = time.Time{} } @@ -512,7 +640,7 @@ func (s *Store) ConfigureDiagnostics(enabled bool) { return nil }) if err != nil && !errors.Is(err, ErrClosed) { - // The switch could not reach the writer: fail closed, and let the next tick tell the + // The switch could not reach the writer: fail closed, and let the next drain tell the // kernel. s.mu.Lock() s.failures++ @@ -649,8 +777,7 @@ func (s *Store) do(ctx context.Context, fn func(context.Context) error) error { // run is the writer goroutine's loop. It is the only code that touches the open files. func (s *Store) run() { defer close(s.done) - ticker := time.NewTicker(kernelTick) - defer ticker.Stop() + defer s.stopExpiry() var coalesce *time.Timer var coalesceC <-chan time.Time @@ -675,8 +802,10 @@ func (s *Store) run() { case <-coalesceC: coalesce, coalesceC = nil, nil s.drainSafely() - case <-ticker.C: - // Also drains the kernel's own facts and expires diagnostics when the host is idle. + case <-s.expiryC: + // Detailed diagnostics ran out while nothing else drained: the drain tells the + // kernel, whose DEBUG gate would otherwise stay open. + s.expiry, s.expiryC, s.expiryAt = nil, nil, time.Time{} disarm() s.drainSafely() case job := <-s.jobs: @@ -689,9 +818,18 @@ func (s *Store) run() { } } -// shutdown runs the final drain, which also switches the kernel's DEBUG gate off because the -// store is stopped, then releases every resource. +// shutdown removes the kernel's waker, runs the final drain, which also switches the kernel's +// DEBUG gate off because the store is stopped, then releases every resource. The waker goes +// first so nothing can signal a store that is going away; the final drain still takes every +// fact the kernel recorded until then. func (s *Store) shutdown() { + s.mu.Lock() + unwatch := s.unwatch + s.unwatch = nil + s.mu.Unlock() + if unwatch != nil { + unwatch() + } s.drainSafely() s.closeHandles() s.subsMu.Lock() @@ -710,20 +848,45 @@ func (s *Store) drainSafely() { } // syncGate pushes the DEBUG gate to the kernel when it differs from what the kernel was last -// told. A failed push is not retried until the wanted state changes, so a broken kernel cannot -// make every drain fail again. +// told, and keeps the expiry timer on the current deadline. A failed push is logged once and +// not retried until the wanted state changes, so a broken kernel cannot make every drain fail +// again. func (s *Store) syncGate(ctx context.Context) { at := s.now() s.mu.Lock() - _, _, on := s.diagnosticsLocked(at) + _, remaining, on := s.diagnosticsLocked(at) + until := s.diagnosticUntil s.mu.Unlock() + if on { + s.armExpiry(until, remaining) + } else { + s.stopExpiry() + } if s.gateKnown && s.gateOn == on { return } s.gateKnown, s.gateOn = true, on if err := s.kernel.ConfigureCoreEvents(ctx, on, nil); err != nil { s.fail() + s.Emit(core.LevelWarn, "app.logging.diagnostics_failed", "", core.LogErrorFields(err)) + } +} + +// armExpiry points the one-shot expiry timer at until, which is remaining away. +func (s *Store) armExpiry(until time.Time, remaining time.Duration) { + if s.expiry != nil && s.expiryAt.Equal(until) { + return } + s.stopExpiry() + s.expiry = time.NewTimer(remaining) + s.expiryC, s.expiryAt = s.expiry.C, until +} + +func (s *Store) stopExpiry() { + if s.expiry != nil { + s.expiry.Stop() + } + s.expiry, s.expiryC, s.expiryAt = nil, nil, time.Time{} } // diagnosticsOn reports whether DEBUG events are admitted right now. @@ -818,7 +981,7 @@ func (s *Store) drain(ctx context.Context) error { Ts: formatTime(s.now()), Level: core.LevelWarn, Seq: s.sequence, - Event: "log.dropped", + Event: droppedEvent, Msg: "Dropped events", Fields: map[string]any{"count": count}, Channel: "app", @@ -837,7 +1000,8 @@ func (s *Store) drain(ctx context.Context) error { } // persist encodes one batch and appends the resulting lines. The caller keeps ownership of -// batch and may reuse it afterwards. +// batch and may reuse it afterwards. A batch the kernel cannot encode at all is lost and counted +// as dropped; an event it refuses is remembered as a rejection. func (s *Store) persist(ctx context.Context, batch []core.LogEvent) { encoded, err := s.kernel.EncodeLogBatch(ctx, core.LogBatch{ Events: batch, @@ -846,7 +1010,7 @@ func (s *Store) persist(ctx context.Context, batch []core.LogEvent) { Previous: s.previous, }) if err != nil { - s.fail() + s.lose(batch) return } // The next call hands the last input back so the kernel can fold consecutive duplicates @@ -856,7 +1020,15 @@ func (s *Store) persist(ctx context.Context, batch []core.LogEvent) { published := make([]Batch, 0, len(encoded.Results)) for _, result := range encoded.Results { - if result.Error != nil || result.Line == "" || result.Channel == "" { + if result.Error != nil { + event := "" + if result.Index != nil && *result.Index >= 0 && *result.Index < len(batch) { + event = batch[*result.Index].Event + } + s.reject(event, result.Error.Code) + continue + } + if result.Line == "" || result.Channel == "" { s.fail() continue } @@ -886,17 +1058,20 @@ func (s *Store) persist(ctx context.Context, batch []core.LogEvent) { // retry fails too, so the failure can be diagnosed from the window; it is dropped only when // there is no other directory to try. func (s *Store) write(ctx context.Context, entry Batch) bool { - if err := s.appendEntry(ctx, entry); err == nil { + appendErr := s.appendEntry(ctx, entry) + if appendErr == nil { return true } s.fail() if s.defaultDir == "" || s.directory == s.defaultDir { return false } + failed := s.directory if err := s.switchDirectory(s.defaultDir); err != nil { s.fail() return false } + s.redirected(failed, appendErr) if err := s.appendEntry(ctx, entry); err != nil { s.fail() } diff --git a/desktop/internal/logstore/writer_test.go b/desktop/internal/logstore/writer_test.go new file mode 100644 index 0000000000..017fa289b4 --- /dev/null +++ b/desktop/internal/logstore/writer_test.go @@ -0,0 +1,363 @@ +package logstore + +import ( + "context" + "errors" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +// wakingKernel stands in for the kernel's fact queue: record queues a fact and calls the waker +// the store installed, the way the kernel does when one of its own facts is recorded. +type wakingKernel struct { + Kernel + mu sync.Mutex + wake func() + installs int + removals int + facts []core.CoreEvent +} + +func (k *wakingKernel) WatchCoreEvents(wake func()) func() { + k.mu.Lock() + defer k.mu.Unlock() + k.wake = wake + k.installs++ + return func() { + k.mu.Lock() + defer k.mu.Unlock() + k.wake = nil + k.removals++ + } +} + +func (k *wakingKernel) record(fact core.CoreEvent) { + k.mu.Lock() + k.facts = append(k.facts, fact) + wake := k.wake + k.mu.Unlock() + if wake != nil { + wake() + } +} + +func (k *wakingKernel) DrainCoreEvents(ctx context.Context) (core.CoreEvents, error) { + k.mu.Lock() + facts := k.facts + k.facts = nil + k.mu.Unlock() + drained, err := k.Kernel.DrainCoreEvents(ctx) + drained.Events = append(facts, drained.Events...) + return drained, err +} + +func (k *wakingKernel) counts() (installs, removals int, installed bool) { + k.mu.Lock() + defer k.mu.Unlock() + return k.installs, k.removals, k.wake != nil +} + +// awaitLine subscribes to the store and returns a function that waits until a written line +// contains want. +func awaitLine(t *testing.T, s *Store, want string) func() { + t.Helper() + seen := make(chan struct{}) + var once sync.Once + cancel := s.Subscribe(func(batch []Batch) { + for _, entry := range batch { + if strings.Contains(entry.Line, want) { + once.Do(func() { close(seen) }) + } + } + }) + t.Cleanup(cancel) + return func() { + t.Helper() + select { + case <-seen: + case <-time.After(waitLimit): + t.Fatalf("no line containing %q was written", want) + } + } +} + +func TestCoreFactsReachTheDiskWithoutHostEvents(t *testing.T) { + kernel := &wakingKernel{Kernel: core.NewClient()} + s, _, _ := openStore(t, func(o *Options) { o.Kernel = kernel }) + s.ObserveCoreFacts() + // The kernel keeps one waker per process; observing again must not replace it. + s.ObserveCoreFacts() + if installs, _, installed := kernel.counts(); installs != 1 || !installed { + t.Fatalf("waker installs = %d, installed %v, want one installed waker", installs, installed) + } + flush(t, s) + + // Nothing but the kernel's waker schedules the drain that writes this fact. + written := awaitLine(t, s, "app.workspace.scratch_cleanup_failed") + kernel.record(core.CoreEvent{ + Level: core.LevelWarn, + Event: "app.workspace.scratch_cleanup_failed", + Channel: "app", + Fields: core.LogErrorFields(errors.New("scratch directory busy")), + }) + written() + + s.Close() + if _, removals, installed := kernel.counts(); removals != 1 || installed { + t.Fatalf("waker removals = %d, installed %v after Close, want it removed once", removals, installed) + } + // A closed store never installs the waker again. + s.ObserveCoreFacts() + if installs, _, _ := kernel.counts(); installs != 1 { + t.Fatalf("waker installs = %d after Close, want 1", installs) + } +} + +func TestRejectedEventsAreNamedWithTheirCode(t *testing.T) { + s, _, _ := openStore(t, nil) + flush(t, s) + + s.Emit(core.LevelInfo, "app.test.never_declared", "", nil) + s.Emit(core.LevelError, "app.action.performed", "", map[string]any{"action": "wrong_level", "surface": "button"}) + s.Emit(core.LevelInfo, "app.action.performed", "", map[string]any{"action": "extra", "surface": "button", "extra": "x"}) + s.Emit(core.LevelInfo, "app.action.performed", "", map[string]any{"action": "extra_again", "surface": "button", "extra": "y"}) + action(s, "accepted") + flush(t, s) + + total, recent := s.Rejections() + if total != 4 { + t.Fatalf("rejected = %d, want 4 (recent %+v)", total, recent) + } + unknown, ok := find(recent, "app.test.never_declared") + if !ok || unknown.Code != -32053 || unknown.Count != 1 { + t.Fatalf("unknown event rejection = %+v, found %v; recent %+v", unknown, ok, recent) + } + // The two rejections of app.action.performed differ by code, and the repeated one counts. + var level, field Rejection + for _, rejection := range recent { + if rejection.Event != "app.action.performed" { + continue + } + switch rejection.Code { + case -32057: + level = rejection + case -32056: + field = rejection + } + } + if level.Count != 1 || field.Count != 2 { + t.Fatalf("app.action.performed rejections: level %+v, field %+v; recent %+v", level, field, recent) + } + // A refused event is a bug of its caller, not a failed write. + if dropped, failures := s.Stats(); dropped != 0 || failures != 0 { + t.Fatalf("dropped = %d, write failures = %d, want 0 and 0", dropped, failures) + } + records := window(t, s, Query{Session: "current"}).Records + if got := fieldValues(records, "app.action.performed", "action"); !slices.Equal(got, []string{"accepted"}) { + t.Fatalf("written actions = %v, want only the accepted one", got) + } + + // The window and the export see the same rejections. + collection, err := s.QueryWindow(context.Background(), Query{Session: "current"}) + if err != nil { + t.Fatalf("QueryWindow: %v", err) + } + if collection.Rejected != 4 || len(collection.Rejections) != len(recent) { + t.Fatalf("collection rejections = %d %+v, want 4 %+v", collection.Rejected, collection.Rejections, recent) + } +} + +func find(rejections []Rejection, event string) (Rejection, bool) { + for _, rejection := range rejections { + if rejection.Event == event { + return rejection, true + } + } + return Rejection{}, false +} + +func TestRejectionListKeepsTheLatestDistinctReasons(t *testing.T) { + s, _, _ := openStore(t, nil) + for i := range rejectionLimit + 5 { + s.reject("app.test."+strconv.Itoa(i), -32055) + } + // Seeing the oldest kept reason again moves it to the end instead of adding a copy. + s.reject("app.test.5", -32055) + total, recent := s.Rejections() + if total != rejectionLimit+6 || len(recent) != rejectionLimit { + t.Fatalf("total = %d, kept = %d, want %d and %d", total, len(recent), rejectionLimit+6, rejectionLimit) + } + if recent[0].Event != "app.test.6" || recent[len(recent)-1].Event != "app.test.5" || recent[len(recent)-1].Count != 2 { + t.Fatalf("kept rejections = %+v", recent) + } +} + +// failingEncoder fails every EncodeLogBatch call while armed, the way a kernel that cannot +// decode the request answers. +type failingEncoder struct { + Kernel + armed atomic.Bool +} + +func (f *failingEncoder) EncodeLogBatch(ctx context.Context, batch core.LogBatch) (core.EncodedLogBatch, error) { + if f.armed.Load() { + return core.EncodedLogBatch{}, errors.New("encoder unavailable") + } + return f.Kernel.EncodeLogBatch(ctx, batch) +} + +func TestUnencodableBatchIsCountedAsDropped(t *testing.T) { + encoder := &failingEncoder{Kernel: core.NewClient()} + s, _, _ := openStore(t, func(o *Options) { o.Kernel = encoder }) + flush(t, s) + + encoder.armed.Store(true) + for _, name := range []string{"lost_1", "lost_2", "lost_3"} { + action(s, name) + } + flush(t, s) + if dropped, failures := s.Stats(); dropped != 3 || failures != 0 { + t.Fatalf("dropped = %d, write failures = %d, want 3 and 0", dropped, failures) + } + // The report of the loss is lost too while the encoder fails; it is carried, not counted + // as one more lost event. + flush(t, s) + if dropped, _ := s.Stats(); dropped != 3 { + t.Fatalf("dropped = %d after a lost report, want 3", dropped) + } + + encoder.armed.Store(false) + flush(t, s) + records := window(t, s, Query{Session: "current"}).Records + if got := fieldValues(records, "log.dropped", "count"); !slices.Equal(got, []string{"3"}) { + t.Fatalf("log.dropped counts = %v, want [3]", got) + } + if got := fieldValues(records, "app.action.performed", "action"); len(got) != 0 { + t.Fatalf("lost actions were written: %v", got) + } +} + +// gateKernel reports every DEBUG gate the store pushes to the kernel on a channel. +type gateKernel struct { + Kernel + gates chan bool +} + +func (g *gateKernel) ConfigureCoreEvents(ctx context.Context, debug bool, roots []string) error { + select { + case g.gates <- debug: + default: + } + return g.Kernel.ConfigureCoreEvents(ctx, debug, roots) +} + +func TestDiagnosticsExpireWithoutHostEvents(t *testing.T) { + kernel := &gateKernel{Kernel: core.NewClient(), gates: make(chan bool, 64)} + s, clock, _ := openStore(t, func(o *Options) { + o.Kernel = kernel + o.diagnosticWindow = 20 * time.Millisecond + }) + flush(t, s) + // The first drain told the kernel the gate is closed; only what follows matters. + for len(kernel.gates) > 0 { + <-kernel.gates + } + + s.ConfigureDiagnostics(true) + // Past the window on the store's clock; only the writer's expiry timer can now notice. + clock.Advance(time.Minute) + opened := false + deadline := time.After(waitLimit) + for { + select { + case on := <-kernel.gates: + if on { + opened = true + continue + } + if !opened { + t.Fatal("the kernel gate closed before it was opened") + } + if _, _, on := s.Diagnostics(); on { + t.Fatal("diagnostics are on after the kernel gate closed") + } + return + case <-deadline: + t.Fatal("the kernel's DEBUG gate stayed open after the window expired") + } + } +} + +// refusingKernel fails the DEBUG gate push. +type refusingKernel struct{ Kernel } + +func (refusingKernel) ConfigureCoreEvents(context.Context, bool, []string) error { + return errors.New("gate unavailable") +} + +func TestFailedGatePushIsLoggedOnce(t *testing.T) { + s, _, _ := openStore(t, func(o *Options) { o.Kernel = refusingKernel{Kernel: core.NewClient()} }) + flush(t, s) + flush(t, s) + records := window(t, s, Query{Session: "current"}).Records + if counts := eventCounts(records); counts["app.logging.diagnostics_failed"] != 1 { + t.Fatalf("event counts = %v, want one app.logging.diagnostics_failed", counts) + } +} + +func TestFailedDirectoryFallsBackAndIsLogged(t *testing.T) { + s, _, first := openStore(t, nil) + flush(t, s) + second := filepath.Join(t.TempDir(), "logs") + if err := s.ChangeDirectory(second); err != nil { + t.Fatalf("ChangeDirectory: %v", err) + } + // The chosen directory disappears before anything is written there. + if err := os.RemoveAll(second); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(second, nil, 0o600); err != nil { + t.Fatal(err) + } + action(s, "after_the_loss") + flush(t, s) + + if s.Directory() != first { + t.Fatalf("Directory = %q, want the default %q", s.Directory(), first) + } + records := window(t, s, Query{Session: "current"}).Records + // The kernel redacts the directory; one record names the failed one, with its error. + if got := fieldValues(records, "app.logging.redirect_failed", "directory"); len(got) != 1 || got[0] == "" { + t.Fatalf("redirect_failed directories = %v, want one", got) + } + if got := fieldValues(records, "app.logging.redirect_failed", "error_domain"); len(got) != 1 || got[0] == "" { + t.Fatalf("redirect_failed error domains = %v, want one", got) + } + if got := fieldValues(records, "app.action.performed", "action"); !slices.Contains(got, "after_the_loss") { + t.Fatalf("the event that hit the failed directory was not retried: %v", got) + } +} + +func TestUnreadableDirectorySettingIsReported(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, settingsName), []byte("{not json"), 0o600); err != nil { + t.Fatal(err) + } + directory, err := loadDirectory(store.At(dir)) + if directory != "" || err == nil { + t.Fatalf("loadDirectory = %q, %v, want no directory and an error", directory, err) + } + if directory, err := loadDirectory(nil); directory != "" || err != nil { + t.Fatalf("loadDirectory(nil) = %q, %v", directory, err) + } +} diff --git a/desktop/internal/logwindow/export.go b/desktop/internal/logwindow/export.go index a9162ad484..a24a1f49e2 100644 --- a/desktop/internal/logwindow/export.go +++ b/desktop/internal/logwindow/export.go @@ -500,7 +500,7 @@ func (m *Model) revealExport() { // The file manager can take a while to answer, so the window thread does not wait. m.spawn(func() { if err := m.opts.Reveal(destination); err != nil { - m.post(func() { m.report(err) }) + m.post(func() { m.report(opRevealExport, err) }) } }) } @@ -512,7 +512,7 @@ func (m *Model) exportFailure(stage string, err error) { } func (m *Model) emitExportFailure(stage string, err error) { - fields := ErrorFields(err) + fields := core.LogErrorFields(err) fields["stage"] = stage m.opts.Source.Emit(core.LevelError, exportFailedEvent, "", fields) } diff --git a/desktop/internal/logwindow/export_test.go b/desktop/internal/logwindow/export_test.go index 2fd5c48393..2528a4c896 100644 --- a/desktop/internal/logwindow/export_test.go +++ b/desktop/internal/logwindow/export_test.go @@ -151,7 +151,7 @@ func newExportFixture(t testing.TB) *exportFixture { source: &exportSource{dir: logs, export: logstore.Export{ Files: []logstore.ExportFile{ {RelativePath: exportLogPath, Data: []byte("{\"event\":\"app.session.started\"}\n")}, - {RelativePath: "collection-status.txt", Data: []byte("truncated=false dropped_events=0 write_failures=0 skipped_invalid_lines=0\n")}, + {RelativePath: "collection-status.txt", Data: []byte("truncated=false dropped_events=0 write_failures=0 rejected_events=0 skipped_invalid_lines=0\n")}, }, Directory: logs, EstimatedBytes: 4096, @@ -528,3 +528,44 @@ func TestBundlePathStaysInsideTheFolder(t *testing.T) { } } } + +// TestFailuresAreLoggedByWhoStartedThem checks that a failure the user caused is an operation +// failure and one of the window's own reads a background failure, each naming its operation. +func TestFailuresAreLoggedByWhoStartedThem(t *testing.T) { + fx := newExportFixture(t) + fx.model.opts.Clipboard = func(string) error { return errors.New("pasteboard busy") } + fx.model.copyText("record") + fx.model.queryFailed(fx.model.generation, errors.New("index unreadable")) + // A cancelled read is the window's own doing and is not a failure. + fx.model.queryFailed(fx.model.generation, context.Canceled) + + events := fx.source.emittedEvents() + if len(events) != 2 { + t.Fatalf("emitted %+v, want two failures", events) + } + if e := events[0]; e.event != operationFailed || e.level != core.LevelError || e.fields["operation"] != opCopy || e.fields["error"] != "pasteboard busy" { + t.Fatalf("copy failure = %+v", e) + } + if e := events[1]; e.event != backgroundFailed || e.level != core.LevelWarn || e.fields["operation"] != opQuery { + t.Fatalf("query failure = %+v", e) + } + if !fx.model.failed { + t.Fatal("the error line is not shown") + } +} + +// TestStatusNamesTheLatestRejection checks that the status bar keeps the newest refused event. +func TestStatusNamesTheLatestRejection(t *testing.T) { + fx := newExportFixture(t) + fx.model.setRejections(3, []logstore.Rejection{ + {Event: "app.old.failed", Code: -32055, Count: 1}, + {Event: "app.new.failed", Code: -32056, Count: 2}, + }) + if fx.model.rejected != 3 || fx.model.latestRejection.Event != "app.new.failed" || fx.model.latestRejection.Code != -32056 { + t.Fatalf("rejected = %d, latest = %+v", fx.model.rejected, fx.model.latestRejection) + } + fx.model.setRejections(0, nil) + if fx.model.rejected != 0 || fx.model.latestRejection != (logstore.Rejection{}) { + t.Fatalf("after clearing: rejected = %d, latest = %+v", fx.model.rejected, fx.model.latestRejection) + } +} diff --git a/desktop/internal/logwindow/model.go b/desktop/internal/logwindow/model.go index abd337100e..84209cb2ad 100644 --- a/desktop/internal/logwindow/model.go +++ b/desktop/internal/logwindow/model.go @@ -25,7 +25,6 @@ import ( "strings" "sync" "sync/atomic" - "syscall" "time" "unicode/utf8" @@ -78,8 +77,27 @@ const ( prefsFile = "log-window.json" // defaultDebounce is how long typing in the filter waits before it queries. defaultDebounce = 150 * time.Millisecond - // diagnosticsFailed is the event the window records when it cannot read the logs. - diagnosticsFailed = "app.logging.diagnostics_failed" + // operationFailed records an operation the user started in the window that failed; + // backgroundFailed records work the window runs on its own that failed. + operationFailed = "app.notification.operation_failed" + backgroundFailed = "app.background.operation_failed" +) + +// The operation field of operationFailed and backgroundFailed, one per kind of work. +const ( + opPreferencesSave = "logs_preferences_save" + opQuery = "logs_query" + opLive = "logs_live" + opTrace = "logs_trace" + opDetail = "logs_detail" + opFilterCompose = "logs_filter_compose" + opCopy = "logs_copy" + opRevealDirectory = "logs_reveal_directory" + opRevealExport = "logs_reveal_export" + opRevealRecord = "logs_reveal_record" + opChangeDirectory = "logs_change_directory" + opRestoreDirectory = "logs_restore_directory" + opClear = "logs_clear" ) // Sessions the session menu offers, in its order. @@ -309,6 +327,8 @@ type Model struct { directory, currentSessionPath string defaultDirectory string dropped, writeFailures int + rejected int + latestRejection logstore.Rejection diagnosticRemaining time.Duration diagnosticCategory string diagnosticSince time.Time @@ -505,7 +525,7 @@ func (m *Model) persist() { return } if err := m.opts.Store.Save(prefsFile, m.prefs); err != nil { - m.report(err) + m.reportBackground(opPreferencesSave, err) } } @@ -605,7 +625,7 @@ func (m *Model) queryFailed(token int, err error) { return } m.queryPending = false - m.report(err) + m.reportBackground(opQuery, err) } // applyCollection replaces the records with the answer to a query. @@ -615,6 +635,7 @@ func (m *Model) applyCollection(q logstore.Query, c logstore.Collection) { m.directory = c.Directory m.currentSessionPath = c.CurrentSessionPath m.dropped, m.writeFailures = c.Dropped, c.WriteFailures + m.setRejections(c.Rejected, c.Rejections) m.setDiagnostics(c.DiagnosticCategory, c.DiagnosticRemaining) m.latestSequences = maps.Clone(c.Result.SessionSequences) if m.latestSequences == nil { @@ -774,7 +795,7 @@ func (m *Model) liveError(revision int, err error) { m.unsubscribe() m.unsubscribe = nil } - m.report(err) + m.reportBackground(opLive, err) } // liveKey identifies a live record against one read back from disk, whose path differs. @@ -848,6 +869,7 @@ func (m *Model) append(result core.LogQueryResult, summary *logstore.LiveSummary if summary != nil { m.histogram = summary.Histogram m.dropped, m.writeFailures = summary.Dropped, summary.WriteFailures + m.setRejections(summary.Rejected, summary.Rejections) m.setDiagnostics(summary.DiagnosticCategory, summary.DiagnosticRemaining) } if result.FoldMinimumRun > 0 { @@ -1004,7 +1026,7 @@ func (m *Model) selectIDs(ids map[string]bool) { return } if err != nil { - m.report(err) + m.reportBackground(opTrace, err) return } m.trace = &collection.Result @@ -1062,7 +1084,7 @@ func (m *Model) scheduleDetail(id, line string) { return } if err != nil { - m.report(err) + m.reportBackground(opDetail, err) return } m.detailText = text @@ -1240,7 +1262,7 @@ func (m *Model) compose(term core.LogFilterTerm) { composed, err := m.opts.Kernel.ComposeLogFilter(m.ctx, expression, term) m.post(func() { if err != nil { - m.report(err) + m.report(opFilterCompose, err) return } m.replaceExpression(composed) @@ -1267,7 +1289,7 @@ func (m *Model) copyFormatted(records []core.LogRecord, format string) { text, err := m.opts.Kernel.FormatLogRecords(m.ctx, lines, format, environment) m.post(func() { if err != nil { - m.report(err) + m.report(opCopy, err) return } m.copyText(text) @@ -1281,7 +1303,7 @@ func (m *Model) copyText(text string) { return } if err := m.opts.Clipboard(text); err != nil { - m.report(err) + m.report(opCopy, err) } } @@ -1379,7 +1401,7 @@ func (m *Model) revealDirectory() { return } if err := m.opts.Reveal(m.directory); err != nil { - m.report(err) + m.report(opRevealDirectory, err) } } @@ -1398,7 +1420,7 @@ func (m *Model) chooseDirectory() { m.post(func() { m.busy = false if err != nil { - m.report(err) + m.report(opChangeDirectory, err) return } if dir != "" { @@ -1424,7 +1446,7 @@ func (m *Model) restoreDirectory() { m.post(func() { m.busy = false if err != nil { - m.report(err) + m.report(opRestoreDirectory, err) return } m.refresh(false) @@ -1443,7 +1465,7 @@ func (m *Model) clearLogs() { m.post(func() { m.busy = false if err != nil { - m.report(err) + m.report(opClear, err) } m.usedBytes = 0 m.refresh(false) @@ -1451,42 +1473,33 @@ func (m *Model) clearLogs() { }) } -// report records a failure to read the logs and shows the error line. -func (m *Model) report(err error) { +// setRejections keeps the writer's count of refused events and the latest refusal, which the +// status bar names so a faulty call site is visible without opening an export. +func (m *Model) setRejections(total int, recent []logstore.Rejection) { + m.rejected = total + m.latestRejection = logstore.Rejection{} + if len(recent) > 0 { + m.latestRejection = recent[len(recent)-1] + } +} + +// report records an operation the user started that failed, and shows the error line. +func (m *Model) report(operation string, err error) { + m.fail(core.LevelError, operationFailed, operation, err) +} + +// reportBackground records work the window runs on its own, reading or formatting the logs +// or saving its preferences, that failed, and shows the error line. +func (m *Model) reportBackground(operation string, err error) { + m.fail(core.LevelWarn, backgroundFailed, operation, err) +} + +func (m *Model) fail(level core.LogLevel, event, operation string, err error) { if err == nil || errors.Is(err, context.Canceled) { return } - m.opts.Source.Emit(core.LevelWarn, diagnosticsFailed, "", ErrorFields(err)) + fields := core.LogErrorFields(err) + fields["operation"] = operation + m.opts.Source.Emit(level, event, "", fields) m.failed = true } - -// ErrorFields encodes an error the way the event catalog asks: a bounded message without -// control characters, a code and the domain the code belongs to. -func ErrorFields(err error) map[string]any { - message := strings.Map(func(r rune) rune { - if r < 0x20 || r == 0x7f || (r >= 0x80 && r < 0xa0) { - return ' ' - } - return r - }, err.Error()) - if len(message) > 1024 { - cut := 1024 - for cut > 0 && !utf8.RuneStart(message[cut]) { - cut-- - } - message = message[:cut] - } - code, domain := any("unknown"), "go" - var logErr *core.LogError - var coreErr *core.Error - var errno syscall.Errno - switch { - case errors.As(err, &logErr): - code, domain = logErr.Code, "lithe.logging" - case errors.As(err, &coreErr): - code, domain = string(coreErr.Code), "lithe.core" - case errors.As(err, &errno): - code, domain = int(errno), "posix" - } - return map[string]any{"error": message, "error_code": code, "error_domain": domain} -} diff --git a/desktop/internal/logwindow/window.go b/desktop/internal/logwindow/window.go index dd17145054..30e6db43b8 100644 --- a/desktop/internal/logwindow/window.go +++ b/desktop/internal/logwindow/window.go @@ -499,6 +499,13 @@ func (w *window) status(c ui.C) { ui.Spacer(c) w.mono(c, w.text.Logs.Dropped(m.discarded+m.dropped), 11.5, w.pal.white) w.mono(c, w.text.Logs.WriteFailures(m.writeFailures), 11.5, w.pal.white) + if m.rejected > 0 { + event := m.latestRejection.Event + if event == "" { + event = "—" + } + w.mono(c, w.text.Logs.Rejected(m.rejected, event, m.latestRejection.Code), 11.5, w.pal.white) + } w.mono(c, "v2 · UTF-8 · NDJSON", 11.5, w.pal.white) }) } @@ -657,7 +664,7 @@ func (w *window) revealRecord() { relative = w.model.currentSessionPath + "/" + relative } if err := w.model.opts.Reveal(filepath.Join(w.model.directory, filepath.FromSlash(relative))); err != nil { - w.model.report(err) + w.model.report(opRevealRecord, err) } } diff --git a/desktop/internal/workbench/commit.go b/desktop/internal/workbench/commit.go index 1cb4c9e719..ab08b03bea 100644 --- a/desktop/internal/workbench/commit.go +++ b/desktop/internal/workbench/commit.go @@ -9,7 +9,6 @@ import ( "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" - "github.com/1lck/Lithe-IDEA/desktop/internal/logwindow" "github.com/vivaui/viva/text" "github.com/vivaui/viva/ui" ) @@ -440,7 +439,7 @@ func (a *App) gitOperationFailed(operation string, err error) { // operationFailedFields are the fields of app.notification.operation_failed. func operationFailedFields(operation string, err error) map[string]any { - fields := logwindow.ErrorFields(err) + fields := core.LogErrorFields(err) fields["operation"] = operation return fields } diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index 3e4b2ddf8b..8bd60c79f7 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -17,7 +17,6 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/editor/syntax" "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" - "github.com/1lck/Lithe-IDEA/desktop/internal/logwindow" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/winpath" "github.com/vivaui/viva/gfx" @@ -395,7 +394,7 @@ func readDocument(path string) ([]byte, error) { // documentOpenFields are the fields of editor.document.open_failed: the error, and the // catalog's token for why the file was not opened. func documentOpenFields(err error) map[string]any { - fields := logwindow.ErrorFields(documentLogError(err)) + fields := core.LogErrorFields(documentLogError(err)) fields["reason"] = documentOpenReason(err) return fields } @@ -783,7 +782,7 @@ func (a *App) saveFailed(id, revision int, name string, err error) { // documentSaveFields are the fields of editor.document.save_failed for document id, whose // text was at revision when it was written. func documentSaveFields(id, revision int, err error) map[string]any { - fields := logwindow.ErrorFields(documentLogError(err)) + fields := core.LogErrorFields(documentLogError(err)) fields["document"] = strconv.Itoa(id) fields["revision"] = revision fields["stage"] = documentSaveStage diff --git a/desktop/internal/workbench/settings.go b/desktop/internal/workbench/settings.go index 1a48cc2ed7..fcc5030d29 100644 --- a/desktop/internal/workbench/settings.go +++ b/desktop/internal/workbench/settings.go @@ -11,7 +11,6 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/fontprefs" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/localshell" - "github.com/1lck/Lithe-IDEA/desktop/internal/logwindow" "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" "github.com/1lck/Lithe-IDEA/desktop/internal/processledger" @@ -56,7 +55,7 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { return marketplace.Snapshot{}, err } a.post(func(a *App) { - fields := logwindow.ErrorFields(err) + fields := core.LogErrorFields(err) fields["operation"] = "plugin_settings_catalog" a.emit(core.LevelError, "app.notification.operation_failed", fields) }) @@ -81,7 +80,7 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { }, MarketplaceError: func(err error) { a.post(func(a *App) { - fields := logwindow.ErrorFields(err) + fields := core.LogErrorFields(err) fields["operation"] = "plugin_marketplace" a.emit(core.LevelError, "app.notification.operation_failed", fields) }) diff --git a/desktop/internal/workbench/terminal.go b/desktop/internal/workbench/terminal.go index 24279f1d76..69f8697440 100644 --- a/desktop/internal/workbench/terminal.go +++ b/desktop/internal/workbench/terminal.go @@ -2,7 +2,6 @@ package workbench import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" - "github.com/1lck/Lithe-IDEA/desktop/internal/logwindow" "github.com/1lck/Lithe-IDEA/desktop/internal/nativeterm" "github.com/1lck/Lithe-IDEA/desktop/internal/termview" "github.com/vivaui/viva/gfx" @@ -31,7 +30,7 @@ func (a *App) terminalFailed(f termview.Failure) { } fields := map[string]any{} if f.Err != nil { - fields = logwindow.ErrorFields(f.Err) + fields = core.LogErrorFields(f.Err) } if f.Stage != "" { fields["stage"] = f.Stage diff --git a/desktop/internal/workbench/updates.go b/desktop/internal/workbench/updates.go index c148f2989b..cd684f2c28 100644 --- a/desktop/internal/workbench/updates.go +++ b/desktop/internal/workbench/updates.go @@ -13,7 +13,6 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/buildinfo" "github.com/1lck/Lithe-IDEA/desktop/internal/core" - "github.com/1lck/Lithe-IDEA/desktop/internal/logwindow" "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" appupdate "github.com/vivaui/viva/update" ) @@ -470,14 +469,14 @@ func (a *App) deleteUpdatePayload(payload string) { return } if err := removeUpdateDir(payload); err != nil { - a.emit(core.LevelWarn, deltaCleanupFailedEvent, logwindow.ErrorFields(err)) + a.emit(core.LevelWarn, deltaCleanupFailedEvent, core.LogErrorFields(err)) } } // deltaFellBack logs the step of a delta update that failed and skips the patch to version // from then on, so the next download is the full archive. It runs on any goroutine. func (a *App) deltaFellBack(stage, version string, err error) { - fields := logwindow.ErrorFields(err) + fields := core.LogErrorFields(err) fields["stage"] = stage a.emit(core.LevelWarn, deltaFallbackEvent, fields) a.updates.mu.Lock() diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index 8303a9f4fb..ac1ba1d781 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -1185,6 +1185,7 @@ "desktop.logs.newLogs": "↓ {count} new logs, jump to latest", "desktop.logs.operation": "Op {op} · {count} records · {duration}", "desktop.logs.paused": "Paused", + "desktop.logs.rejected": "rejected {count} (latest: {event} {code})", "desktop.logs.repeated": "Repeated {count} times · last {last}", "desktop.logs.revealInFinder": "Reveal in Finder", "desktop.logs.savedTo": "Saved to {path}", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index fd2af06237..90feb88898 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -1185,6 +1185,7 @@ "desktop.logs.newLogs": "↓ {count} 条新日志,回到最新", "desktop.logs.operation": "操作 {op} · {count} 条 · 共 {duration}", "desktop.logs.paused": "已暂停", + "desktop.logs.rejected": "被拒绝 {count}(最近:{event} {code})", "desktop.logs.repeated": "重复 {count} 次 · 末次 {last}", "desktop.logs.revealInFinder": "在 Finder 中显示", "desktop.logs.savedTo": "已保存到 {path}", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 9b5120e313..1278babbfe 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -11991,6 +11991,18 @@ "desktop" ] }, + { + "id": "desktop.logs.rejected", + "description": "Desktop log window status bar: how many events the kernel refused to log, with the event id and logging error code of the latest refusal. The event id and code are diagnostic identifiers, not translated.", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "integer", + "event": "string", + "code": "integer" + } + }, { "id": "desktop.logs.repeated", "description": "Desktop log window: Repeated", From f0eaeb1c5d3bdcdc1b8a98daa627238ca697012b Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 22:56:20 +0800 Subject: [PATCH 2/7] =?UTF-8?q?fix(desktop):=20=E5=88=87=E6=8D=A2=20Core?= =?UTF-8?q?=20=E6=A3=80=E5=87=BA=E6=97=B6=E9=87=8D=E6=96=B0=E7=BC=96?= =?UTF-8?q?=E8=AF=91=E5=B7=A5=E4=BD=9C=E5=8C=BA=E6=88=90=E5=91=98=EF=BC=8C?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E6=9A=82=E5=AD=98=E5=8F=A6=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E6=A3=80=E5=87=BA=E7=9A=84=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 固定检出和 LITHE_CORE_RUST_DIR 共用 Cargo 编译目录,而 cargo 按成员在工作区内的相对路径 计算哈希,两个检出把 lithe-diagnostics 等成员编译到同一组文件、同一份指纹,只按修改时间判 新旧。切回原检出时 identity.txt 写着 pinned,链接的却是 override 的事件目录。 构建脚本按 target 和 profile 记录上次编译工作区成员的检出,换了检出先 cargo clean --workspace,registry 依赖仍走缓存;无变化的运行不清理。同步更新 ci-builds.md 和 worktree-resources.json 的说明。 --- docs/ci-builds.md | 7 ++++++- scripts/desktop/build-desktop-core.sh | 15 +++++++++++++++ scripts/resources/worktree-resources.json | 2 +- 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/docs/ci-builds.md b/docs/ci-builds.md index 995414e27a..86744fb142 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -475,7 +475,12 @@ Viva 桌面端(`desktop/`,Go)的构建状态位于 `.artifacts/desktop/` 默认从构建脚本中固定的 Lithe-core-rust 提交检出;联调尚未合入的 core 改动时,设置 `LITHE_CORE_RUST_DIR=/path/to/Lithe-core-rust` 改用本地检出(脚本只读取它,不修改该检出)。 `desktop-go.sh` 每次运行前都调用构建脚本重新暂存,固定提交变了或本地检出改了都不会继续链接旧库; -没有变化时 git 和 cargo 都判定为最新,这一步约一秒。`LITHE_DESKTOP_CORE_PROFILE=release` 选择暂存的 profile。 +没有变化时 git 和 cargo 都判定为最新,这一步约一秒。固定检出和 `LITHE_CORE_RUST_DIR` 共用同一个 Cargo 编译目录, +而 cargo 按成员在工作区内的相对路径计算哈希,不看检出所在位置:两个检出把每个工作区成员(例如事件目录所在的 +`lithe-diagnostics`)编译到同一组文件、同一份指纹,新旧只按修改时间判断,切回原检出时会把另一个检出的代码当作 +本检出暂存。构建脚本因此按 target 和 profile 在编译目录里记录上次编译工作区成员的检出 +(`lithe-core-built-from--.txt`),换了检出就先 `cargo clean --workspace`,只重新编译工作区成员, +registry 依赖仍然命中缓存。`LITHE_DESKTOP_CORE_PROFILE=release` 选择暂存的 profile。 `identity.txt` 记录 core 提交、`core-worktree`(clean/dirty)、`core-source`(pinned/override)、rustc 版本、 target、profile 和 macOS deployment target,但它只描述本工作树最近一次构建:override 构建包含未提交的 core 改动, 提交号无法复现;二进制又随本工作树的 `desktop/` 源码变化。因此它不是可以授权跨工作树复制的封存身份, diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 2bcc433ea4..9fb33d38c2 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -182,6 +182,21 @@ if [[ ! -s "$NATIVE_LIBS_FILE" ]]; then cargo clean --manifest-path "$MANIFEST_NATIVE" -p lithe-core \ "${PROFILE_ARGS[@]+"${PROFILE_ARGS[@]}"}" >&2 fi +# The pinned checkout and a LITHE_CORE_RUST_DIR override share this target directory, and Cargo +# hashes a workspace member by its path inside the workspace, not by where the checkout is: both +# checkouts build every member, such as the event catalog in lithe-diagnostics, to the same +# files with the same fingerprint. Freshness is judged by modification times, so after the other +# checkout overwrote them, the files still look up to date and the staged library would carry +# the other checkout's code under this checkout's identity. The checkout that built the members +# last is recorded per target and profile; a different one cleans the workspace members, which +# are then built from it, while registry dependencies stay cached. +BUILT_FROM_FILE="$CARGO_TARGET_DIR_BASH/lithe-core-built-from-$RUST_TARGET-$PROFILE.txt" +if [[ "$(cat "$BUILT_FROM_FILE" 2>/dev/null || true)" != "$CORE_DIR" ]]; then + cargo clean --manifest-path "$MANIFEST_NATIVE" --workspace \ + "${PROFILE_ARGS[@]+"${PROFILE_ARGS[@]}"}" >&2 + mkdir -p "$CARGO_TARGET_DIR_BASH" + printf '%s\n' "$CORE_DIR" > "$BUILT_FROM_FILE" +fi cargo rustc --manifest-path "$MANIFEST_NATIVE" -p lithe-core --lib --crate-type staticlib \ "${PROFILE_ARGS[@]+"${PROFILE_ARGS[@]}"}" \ -- --print "native-static-libs=$NATIVE_LIBS_FILE_NATIVE" >&2 diff --git a/scripts/resources/worktree-resources.json b/scripts/resources/worktree-resources.json index 340d9d8c97..7cc9078e9c 100644 --- a/scripts/resources/worktree-resources.json +++ b/scripts/resources/worktree-resources.json @@ -64,7 +64,7 @@ ".artifacts/desktop/lithe-core-rust/source/.artifacts/rust-core-checks/", "/lithe core-cache-*/" ], - "identity": "The Core source checkout is pinned by build-desktop-core.sh, while Cargo target output and staged libraries depend on source revision, target, profile, compiler, environment and native linker inputs. Windows GNU builds set WINAPI_NO_BUNDLED_LIBRARIES=1 and record winapi-import-libraries=mingw-system, using the installed MinGW system import libraries. The current staged identity is not a sealed reusable-resource manifest.", + "identity": "The Core source checkout is pinned by build-desktop-core.sh, while Cargo target output and staged libraries depend on source revision, target, profile, compiler, environment and native linker inputs. Cargo hashes workspace members by their path inside the workspace, so the pin and a LITHE_CORE_RUST_DIR override build them to the same files; the target directory records, per target and profile, the checkout that last built them (lithe-core-built-from--.txt), and switching checkouts cleans the workspace members instead of staging the other checkout's code. Windows GNU builds set WINAPI_NO_BUNDLED_LIBRARIES=1 and record winapi-import-libraries=mingw-system, using the installed MinGW system import libraries. The current staged identity is not a sealed reusable-resource manifest.", "reason": "Never copy or share these mutable build outputs or the checkout through worktree reuse. Each worktree builds or validates its own Core artifacts. They are build-time resources outside an installed application and do not modify a signed bundle or Sparkle baseline. Restored Core comment verification and its pinned lexer helper use the caller Cargo target, or a checkout-local .artifacts/rust-core-checks fallback; Rustdoc, helper binaries and build state remain excluded at every reuse stage. The native cgo cache regression owns one temporary fixture checkout and static archive, removes it after bounded compiler processes terminate, and never reuses it across worktrees. The Go cache identity includes staged Core/header/native-linker bytes and selected Windows import archives; this action hash is not a reusable-resource seal." }, { From 0513b7ca4a3b58f2db8b54288c916d4db8455680 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 22:56:29 +0800 Subject: [PATCH 3/7] =?UTF-8?q?fix(desktop):=20=E6=97=A5=E5=BF=97=E8=B0=83?= =?UTF-8?q?=E7=94=A8=E6=8C=89=E7=9C=9F=E5=AE=9E=E5=86=85=E6=A0=B8=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E6=A0=A1=E9=AA=8C=EF=BC=8C=E6=93=8D=E4=BD=9C=E6=9D=A5?= =?UTF-8?q?=E6=BA=90=E6=94=B9=E4=B8=BA=E5=B0=81=E9=97=AD=E5=B8=B8=E9=87=8F?= =?UTF-8?q?=E9=9B=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 internal/core 的站点测试:从源码读出每个生产日志调用的级别、事件 id 和字段,交给当前 链接的内核按目录编码,拼错的 id、与目录不同的级别、缺少或多出的字段都在测试里失败,而不是 运行时被写入器拒绝。用户操作的 surface 改为 actionSurface 常量,测试要求常量集合与目录描述 完全一致、每个调用解析出的 surface 都在集合内,并禁止把字符串转换成该类型。 按入口修正 surface:右键菜单、拖放、工具栏、按钮分别记录;Find Action 与快捷键运行同一命令时 由命令自己带上来源(runFrom),打开设置、项目、查找等不再一律记成 menu;构建、运行、调试的 共享启动路径不再直接 emit,由按钮、菜单和插件请求各自记录。草稿恢复改记 editor.recovery.applied,后台失败、启动残留处理、VCS 提供者跳过等改用目录中声明的事件。 --- .../contractfixture/contractfixture.go | 13 +- desktop/internal/core/log_sites_test.go | 1009 +++++++++++++++++ desktop/internal/termview/session.go | 2 +- desktop/internal/termview/view.go | 1 + desktop/internal/workbench/app.go | 40 +- desktop/internal/workbench/branch.go | 6 +- desktop/internal/workbench/branch_view.go | 13 +- desktop/internal/workbench/browser_preview.go | 4 +- desktop/internal/workbench/build.go | 4 - desktop/internal/workbench/build_menus.go | 20 +- desktop/internal/workbench/build_tests.go | 4 +- desktop/internal/workbench/build_tree_view.go | 6 +- desktop/internal/workbench/chrome_view.go | 10 +- desktop/internal/workbench/clone.go | 2 +- desktop/internal/workbench/commands.go | 65 +- desktop/internal/workbench/commit.go | 24 +- desktop/internal/workbench/commit_view.go | 4 +- desktop/internal/workbench/compact_menu.go | 2 +- desktop/internal/workbench/debug.go | 3 +- desktop/internal/workbench/debug_gutter.go | 2 +- desktop/internal/workbench/debug_menus.go | 30 +- desktop/internal/workbench/debug_start.go | 4 +- desktop/internal/workbench/debug_view.go | 15 +- desktop/internal/workbench/debug_watch.go | 2 +- desktop/internal/workbench/difftab.go | 10 +- desktop/internal/workbench/difftab_test.go | 4 +- .../workbench/directory_exclusions.go | 6 +- .../workbench/editor_essentials_test.go | 4 +- desktop/internal/workbench/editor_find.go | 4 +- desktop/internal/workbench/editor_menu.go | 8 +- desktop/internal/workbench/editor_recovery.go | 2 +- desktop/internal/workbench/filetree_batch.go | 2 +- desktop/internal/workbench/filetree_dnd.go | 8 +- .../internal/workbench/filetree_duplicate.go | 2 +- .../internal/workbench/filetree_git_menu.go | 2 +- desktop/internal/workbench/filetree_menu.go | 31 +- desktop/internal/workbench/filetree_open.go | 2 +- desktop/internal/workbench/git_exclude.go | 2 +- desktop/internal/workbench/git_gutter.go | 7 +- desktop/internal/workbench/git_history.go | 6 +- desktop/internal/workbench/git_rebase.go | 2 +- desktop/internal/workbench/gitconsole.go | 2 +- desktop/internal/workbench/github_create.go | 2 +- desktop/internal/workbench/gitlinehistory.go | 4 +- .../internal/workbench/gitlog_popover_view.go | 9 +- desktop/internal/workbench/gitlog_ref_menu.go | 8 +- desktop/internal/workbench/gitlog_view.go | 4 +- desktop/internal/workbench/gitreview.go | 2 +- .../internal/workbench/gitreview_actions.go | 12 +- desktop/internal/workbench/gitreview_test.go | 6 +- desktop/internal/workbench/gitreview_tools.go | 11 +- .../workbench/gitreview_tools_view.go | 2 +- desktop/internal/workbench/gitsync.go | 32 +- desktop/internal/workbench/gitsync_test.go | 8 +- .../internal/workbench/gitworktree_test.go | 2 +- .../internal/workbench/gitworktree_view.go | 6 +- desktop/internal/workbench/html_preview.go | 2 +- .../internal/workbench/ide_api_dispatch.go | 1 + desktop/internal/workbench/ide_api_run.go | 1 + desktop/internal/workbench/legacy_import.go | 8 +- .../internal/workbench/legacy_import_test.go | 8 +- desktop/internal/workbench/local_history.go | 1 - desktop/internal/workbench/lsp_status_test.go | 4 +- desktop/internal/workbench/new_project.go | 2 +- .../internal/workbench/outputlinks_view.go | 4 +- desktop/internal/workbench/plugins.go | 4 +- desktop/internal/workbench/pluginsemantics.go | 39 +- desktop/internal/workbench/root.go | 5 +- desktop/internal/workbench/runconfig.go | 1 - desktop/internal/workbench/runconfig_view.go | 19 +- .../workbench/search_everywhere_view.go | 4 +- desktop/internal/workbench/settings.go | 14 +- .../workbench/settings_plugin_actions.go | 2 +- desktop/internal/workbench/shell_view.go | 2 +- desktop/internal/workbench/startup_sweep.go | 27 +- desktop/internal/workbench/tab_menu.go | 10 +- desktop/internal/workbench/terminal_drop.go | 4 +- desktop/internal/workbench/terminal_menu.go | 12 +- desktop/internal/workbench/tests.go | 2 +- desktop/internal/workbench/title_run.go | 4 +- desktop/internal/workbench/vcs.go | 2 +- desktop/internal/workbench/viewer.go | 1 - desktop/internal/workbench/welcome_drop.go | 2 +- desktop/internal/workbench/welcome_view.go | 8 +- 84 files changed, 1414 insertions(+), 276 deletions(-) create mode 100644 desktop/internal/core/log_sites_test.go diff --git a/desktop/internal/contractfixture/contractfixture.go b/desktop/internal/contractfixture/contractfixture.go index f11ce2559d..9bbea5dbe4 100644 --- a/desktop/internal/contractfixture/contractfixture.go +++ b/desktop/internal/contractfixture/contractfixture.go @@ -1,6 +1,7 @@ // Package contractfixture locates the contract files that tests read. The plugin contract -// (shared/plugins/contract/v1/) and the application fixtures (rust/fixtures/) each have a single -// source in the Lithe-core-rust checkout this client links, and this repository keeps no copy. +// (shared/plugins/contract/v1/), the application fixtures (rust/fixtures/) and the log event +// catalog (rust/logging/events/) each have a single source in the Lithe-core-rust checkout this +// client links, and this repository keeps no copy. // scripts/desktop/desktop-go.sh exports LITHE_PLUGIN_CONTRACT_DIR and LITHE_CORE_FIXTURE_DIR for // the same checkout it builds: the pinned clone, or LITHE_CORE_RUST_DIR when that is set. package contractfixture @@ -32,6 +33,14 @@ func CoreFixture(rel string) string { return join(CoreFixtureEnvironmentVariable, rel) } +// CoreEventCatalog returns the directory of the kernel's log event catalog, rust/logging/events, +// which sits beside rust/fixtures in the same checkout. Tests read the declared field types from +// it; whether an event is accepted is still the kernel's answer, not the test's. It panics when +// the variable is unset, for the same reason as Path. +func CoreEventCatalog() string { + return join(CoreFixtureEnvironmentVariable, "../logging/events") +} + func join(variable, rel string) string { dir := os.Getenv(variable) if dir == "" { diff --git a/desktop/internal/core/log_sites_test.go b/desktop/internal/core/log_sites_test.go new file mode 100644 index 0000000000..2de4029e84 --- /dev/null +++ b/desktop/internal/core/log_sites_test.go @@ -0,0 +1,1009 @@ +package core + +import ( + "context" + "encoding/json" + "go/ast" + "go/parser" + "go/token" + "io/fs" + "os" + "path/filepath" + "slices" + "sort" + "strconv" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" +) + +// TestEveryLoggedEventIsAcceptedByTheKernel reads every production call that reaches a log +// store's Emit, works out from the source the level, event id and field keys it writes, and +// asks the kernel this client links to encode one such event per call. A misspelled id, a +// level other than the catalog's, a missing required field or a key the catalog does not know +// fails here, instead of being a record the writer drops at run time. +func TestEveryLoggedEventIsAcceptedByTheKernel(t *testing.T) { + scan := scanLogSources(t, filepath.Join("..", "..")) + catalog := readLogCatalog(t) + forwarded := forwardedLogEvents(t, scan) + + var sites []logSite + used := map[string]bool{} + for _, site := range scan.sites() { + if site.problem == "" { + sites = append(sites, site) + continue + } + cases, ok := forwarded[site.origin] + if !ok { + t.Errorf("%s: %s; log a constant event, or list what %s forwards in forwardedLogEvents", + strings.Join(site.where, " → "), site.problem, site.origin) + continue + } + if !used[site.origin] { + used[site.origin] = true + for _, c := range cases { + c.where = site.where + sites = append(sites, c) + } + } + } + for origin := range forwarded { + if !used[origin] { + t.Errorf("forwardedLogEvents lists %s, which no longer logs an event chosen at run time", origin) + } + } + + seen := map[string]bool{} + for _, site := range sites { + seen[site.event] = true + } + // The scan must keep finding the calls it was written against, or a change to how the + // client logs would make this test pass by checking nothing. + for _, event := range []string{"app.session.started", "app.action.performed", "app.notification.operation_failed", "app.background.operation_failed"} { + if !seen[event] { + t.Errorf("the scan found no call that logs %s", event) + } + } + checkActionSurfaces(t, scan, sites) + + c := NewClient() + const batchSize = 64 + for start := 0; start < len(sites); start += batchSize { + chunk := sites[start:min(start+batchSize, len(sites))] + events := make([]LogEvent, len(chunk)) + for i, site := range chunk { + fields := map[string]any{} + for key, bound := range site.fields { + fields[key] = catalog.value(site.event, key, bound) + } + events[i] = LogEvent{Ts: "2026-11-14T09:30:00.000Z", Level: site.level, Seq: uint64(start + i + 1), Event: site.event, Fields: fields} + } + batch, err := c.EncodeLogBatch(context.Background(), LogBatch{Events: events, ValidateCatalog: true}) + if err != nil { + t.Fatalf("EncodeLogBatch: %v", err) + } + if len(batch.Results) != len(events) { + t.Fatalf("EncodeLogBatch answered %d results for %d events", len(batch.Results), len(events)) + } + for i, result := range batch.Results { + if result.Error == nil { + continue + } + site := chunk[i] + keys := make([]string, 0, len(site.fields)) + for key := range site.fields { + keys = append(keys, key) + } + sort.Strings(keys) + t.Errorf("%s: the kernel rejects %s %s with fields %v: %s (%d)", strings.Join(site.where, " → "), + site.level, site.event, keys, logRejection(result.Error.Code), result.Error.Code) + } + } + t.Logf("checked %d logging calls against the kernel's catalog", len(sites)) +} + +// forwardedLogEvents lists, for each function that logs an event chosen at run time, every +// event its callers hand it. Functions are named as their directory and name; the ids come from +// the constants the senders use, so a renamed constant fails to resolve here. +func forwardedLogEvents(t *testing.T, scan *logScan) map[string][]logSite { + errorKeys := func(more ...string) map[string]*logBound { + fields := logErrorKeys("error") + for _, key := range more { + fields[key] = nil + } + return fields + } + return map[string][]logSite{ + // termview.Failure carries the event of a terminal failure to the workbench, which + // logs a failed start as a warning and anything else at debug level. + "internal/workbench.terminalFailed": { + {level: LevelWarn, event: scan.constant(t, "internal/termview", "eventStartFailed"), fields: errorKeys("stage")}, + {level: LevelDebug, event: scan.constant(t, "internal/termview", "eventInputFailed"), fields: errorKeys("stage")}, + }, + } +} + +// actionEvent is the event a user action is recorded as; its surface field is a closed set. +const actionEvent = "app.action.performed" + +// checkActionSurfaces holds the surface of every recorded user action to the closed set the +// catalog lists for it. The kernel only checks that a surface is a token, so a made-up one +// would be accepted and then split the action counts of a surface in two. +// +// The workbench's actionSurface constants must be exactly that set, and every surface a call +// shows in the source must be one of them. A surface read from a parameter no caller in the +// source supplies, such as an action handed around as a func(actionSurface), is typed +// actionSurface and so is one of the constants; converting a string to the type is the only +// way past that, and fails here. +func checkActionSurfaces(t *testing.T, scan *logScan, sites []logSite) { + t.Helper() + allowed := readActionSurfaces(t) + pkg := scan.packages["internal/workbench"] + if pkg == nil { + t.Fatal("no package internal/workbench") + } + declared := map[string]bool{} + for _, file := range pkg.files { + for _, decl := range file.Decls { + gen, ok := decl.(*ast.GenDecl) + if !ok || gen.Tok != token.CONST { + continue + } + for _, spec := range gen.Specs { + values := spec.(*ast.ValueSpec) + if typ, ok := values.Type.(*ast.Ident); !ok || typ.Name != "actionSurface" { + continue + } + for _, name := range values.Names { + text, ok := (&logFrame{scan: scan, pkg: pkg, busy: map[string]bool{}}).identText(name.Name) + switch { + case !ok: + t.Errorf("%s: actionSurface %s is not a string constant", scan.position(name), name.Name) + case !allowed[text]: + t.Errorf("%s: actionSurface %s is %q, which the catalog does not list for %s", scan.position(name), name.Name, text, actionEvent) + default: + declared[text] = true + } + } + } + } + } + for surface := range allowed { + if !declared[surface] { + t.Errorf("the catalog lists surface %q for %s, but no actionSurface constant has it", surface, actionEvent) + } + } + for _, p := range scan.packages { + for _, file := range p.files { + ast.Inspect(file, func(n ast.Node) bool { + if call, ok := n.(*ast.CallExpr); ok { + if fun, ok := call.Fun.(*ast.Ident); ok && fun.Name == "actionSurface" { + t.Errorf("%s: converts a value to actionSurface; pass one of its constants", scan.position(call)) + } + } + return true + }) + } + } + checked := 0 + for _, site := range sites { + if site.event != actionEvent { + continue + } + bound := site.fields["surface"] + if bound == nil { + t.Errorf("%s: logs %s without a surface the source shows", strings.Join(site.where, " → "), actionEvent) + continue + } + text, ok := bound.frame.text(bound.expr) + if !ok { + continue + } + checked++ + if !allowed[text] { + t.Errorf("%s: records surface %q, which the catalog does not list for %s", strings.Join(site.where, " → "), text, actionEvent) + } + } + if checked == 0 { + t.Errorf("no call to %s showed its surface; the check would pass by checking nothing", actionEvent) + } + t.Logf("checked the surface of %d user actions", checked) +} + +// readActionSurfaces reads the surfaces the catalog lists in the description of the surface +// field of app.action.performed, written as "…: menu, shortcut, … or drag_drop". +func readActionSurfaces(t *testing.T) map[string]bool { + t.Helper() + paths, err := filepath.Glob(filepath.Join(contractfixture.CoreEventCatalog(), "*.json")) + if err != nil { + t.Fatal(err) + } + for _, path := range paths { + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var file struct { + Events []struct { + ID string `json:"id"` + Fields map[string]struct { + Description string `json:"description"` + } `json:"fields"` + } `json:"events"` + } + if err := json.Unmarshal(data, &file); err != nil { + t.Fatalf("%s: %v", path, err) + } + for _, event := range file.Events { + if event.ID != actionEvent { + continue + } + _, list, ok := strings.Cut(event.Fields["surface"].Description, ": ") + if !ok { + t.Fatalf("%s: the surface field of %s does not list its values after a colon", path, actionEvent) + } + allowed := map[string]bool{} + for _, part := range strings.Split(list, ", ") { + for _, surface := range strings.Split(part, " or ") { + allowed[strings.TrimSpace(surface)] = true + } + } + return allowed + } + } + t.Fatalf("the catalog has no event %s", actionEvent) + return nil +} + +// logRejection names a logging v2 rejection code. +func logRejection(code int) string { + switch code { + case -32053: + return "unknown event" + case -32054: + return "missing field" + case -32055: + return "invalid field" + case -32056: + return "unknown field" + case -32057: + return "level differs from the catalog" + case -32059: + return "event owned by the kernel" + } + return "rejected" +} + +// logCatalog maps each event id to its encoded field keys and their catalog types: a duration +// is written as _ms, and an error as , _code and _domain. +type logCatalog map[string]map[string]string + +func readLogCatalog(t *testing.T) logCatalog { + t.Helper() + dir := contractfixture.CoreEventCatalog() + paths, err := filepath.Glob(filepath.Join(dir, "*.json")) + if err != nil || len(paths) == 0 { + t.Fatalf("no event catalog in %s: %v", dir, err) + } + catalog := logCatalog{} + for _, path := range paths { + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var file struct { + Events []struct { + ID string `json:"id"` + Fields map[string]struct { + Type string `json:"type"` + } `json:"fields"` + } `json:"events"` + } + if err := json.Unmarshal(data, &file); err != nil { + t.Fatalf("%s: %v", path, err) + } + for _, event := range file.Events { + keys := map[string]string{} + for name, field := range event.Fields { + switch field.Type { + case "duration": + keys[name+"_ms"] = field.Type + case "error": + keys[name], keys[name+"_code"], keys[name+"_domain"] = field.Type, "token", "token" + default: + keys[name] = field.Type + } + } + catalog[event.ID] = keys + } + } + return catalog +} + +// value is what the event carries under key: the constant the source writes when it shows one, +// otherwise a valid value of the catalog type, so the kernel judges the keys and the constants +// rather than made-up values. A key the catalog does not declare gets a string the kernel then +// rejects as unknown. +func (c logCatalog) value(event, key string, bound *logBound) any { + kind, ok := c[event][key] + if !ok { + return "probe" + } + switch kind { + case "int": + return int64(1) + case "bool": + return true + case "duration", "bytes": + return uint64(1) + } + if bound != nil { + if text, ok := bound.frame.text(bound.expr); ok && text != "" { + return text + } + } + switch kind { + case "id": + return "probe-1" + case "version": + return "1.0.0" + case "path": + return "/probe/path" + case "token": + return "probe" + } + return "probe failure" +} + +// logScan is the client's production Go source, parsed for the calls that reach a log store. +type logScan struct { + fset *token.FileSet + root string + packages map[string]*logPackage + // sinks are the client functions that pass some of their parameters on to a log store. + sinks map[*ast.FuncDecl]*logSink +} + +// logPackage is one directory of production files. +type logPackage struct { + dir string + files []*ast.File + consts map[string]ast.Expr + funcs map[string][]*ast.FuncDecl +} + +// logSink is a client function whose parameters decide the level, the event, the field keys +// or a field constant of what it logs. calls are the calls in it that read those parameters; +// the function's callers supply them. +type logSink struct { + pkg *logPackage + decl *ast.FuncDecl + calls []*ast.CallExpr +} + +// logSite is one event a call writes. +type logSite struct { + // where is the call chain from the function that chose the event down to the store. + where []string + // origin names that function as its directory and name. + origin string + level LogLevel + event string + // fields maps each key to the expression of its value, nil when the source builds it. + fields map[string]*logBound + // problem says why the source does not show the event; empty when it does. + problem string +} + +// logBound is an expression and the call frame it is read in. +type logBound struct { + expr ast.Expr + frame *logFrame +} + +// logFrame is one function being read, with the arguments its caller passed. +type logFrame struct { + scan *logScan + pkg *logPackage + decl *ast.FuncDecl + args map[string]logBound + depth int + busy map[string]bool + // parent is the frame of the caller; nil for the function that chose the event. + parent *logFrame + // hits collects the parameters read while no caller supplies them, when finding sinks. + hits map[string]bool +} + +func scanLogSources(t *testing.T, root string) *logScan { + t.Helper() + s := &logScan{fset: token.NewFileSet(), root: root, packages: map[string]*logPackage{}, sinks: map[*ast.FuncDecl]*logSink{}} + for _, top := range []string{"cmd", "internal"} { + err := filepath.WalkDir(filepath.Join(root, top), func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if d.Name() == "testdata" { + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + file, err := parser.ParseFile(s.fset, path, nil, parser.SkipObjectResolution) + if err != nil { + return err + } + rel, err := filepath.Rel(root, filepath.Dir(path)) + if err != nil { + return err + } + dir := filepath.ToSlash(rel) + pkg := s.packages[dir] + if pkg == nil { + pkg = &logPackage{dir: dir, consts: map[string]ast.Expr{}, funcs: map[string][]*ast.FuncDecl{}} + s.packages[dir] = pkg + } + pkg.files = append(pkg.files, file) + for _, decl := range file.Decls { + switch decl := decl.(type) { + case *ast.GenDecl: + if decl.Tok != token.CONST { + continue + } + for _, spec := range decl.Specs { + values := spec.(*ast.ValueSpec) + for i, name := range values.Names { + if i < len(values.Values) { + pkg.consts[name.Name] = values.Values[i] + } + } + } + case *ast.FuncDecl: + if decl.Body != nil { + pkg.funcs[decl.Name.Name] = append(pkg.funcs[decl.Name.Name], decl) + } + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + return s +} + +// constant is the string value of a package-level constant. +func (s *logScan) constant(t *testing.T, dir, name string) string { + t.Helper() + pkg := s.packages[dir] + if pkg == nil { + t.Fatalf("no package %s", dir) + } + text, ok := (&logFrame{scan: s, pkg: pkg, busy: map[string]bool{}}).identText(name) + if !ok { + t.Fatalf("%s has no string constant %s", dir, name) + } + return text +} + +func (s *logScan) position(node ast.Node) string { + p := s.fset.Position(node.Pos()) + rel, err := filepath.Rel(s.root, p.Filename) + if err != nil { + rel = p.Filename + } + return filepath.ToSlash(rel) + ":" + strconv.Itoa(p.Line) +} + +// sites reads every call that logs, from the functions that choose what they log. +func (s *logScan) sites() []logSite { + s.findSinks() + dirs := make([]string, 0, len(s.packages)) + for dir := range s.packages { + dirs = append(dirs, dir) + } + sort.Strings(dirs) + var out []logSite + for _, dir := range dirs { + pkg := s.packages[dir] + for _, file := range pkg.files { + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + sink := s.sinks[fn] + // A function that is only ever called is read through its callers, which + // supply the values; one that is also passed around is read on its own too. + alone := sink == nil || s.escapes(pkg, fn) + top := &logFrame{scan: s, pkg: pkg, decl: fn, busy: map[string]bool{}} + for _, call := range s.calls(pkg, fn) { + if !alone && slices.Contains(sink.calls, call) { + continue + } + for _, site := range top.sites(call, nil) { + site.origin = pkg.dir + "." + fn.Name.Name + out = append(out, site) + } + } + } + } + } + return out +} + +// findSinks marks, until nothing changes, every function with a call that logs whose level, +// event, field keys or field constants come from the function's own parameters: reading the +// call without a caller then reads one of them. +func (s *logScan) findSinks() { + for changed := true; changed; { + changed = false + for _, pkg := range s.packages { + for _, decls := range pkg.funcs { + for _, fn := range decls { + for _, call := range s.calls(pkg, fn) { + if sink := s.sinks[fn]; sink != nil && slices.Contains(sink.calls, call) { + continue + } + probe := &logFrame{scan: s, pkg: pkg, decl: fn, busy: map[string]bool{}, hits: map[string]bool{}} + for _, site := range probe.sites(call, nil) { + for _, bound := range site.fields { + if bound != nil { + bound.frame.text(bound.expr) + } + } + } + if len(probe.hits) == 0 { + continue + } + sink := s.sinks[fn] + if sink == nil { + sink = &logSink{pkg: pkg, decl: fn} + s.sinks[fn] = sink + } + sink.calls = append(sink.calls, call) + changed = true + } + } + } + } + } +} + +// calls lists the calls in fn that log, directly or through a sink. +func (s *logScan) calls(pkg *logPackage, fn *ast.FuncDecl) []*ast.CallExpr { + var out []*ast.CallExpr + ast.Inspect(fn.Body, func(n ast.Node) bool { + if call, ok := n.(*ast.CallExpr); ok { + if _, ok := s.sinkCall(pkg, call); ok { + out = append(out, call) + } + } + return true + }) + return out +} + +// sinkCall returns the sinks call reaches; it reports a store's Emit(level, event, op, fields) +// as a call that logs with no sinks. +func (s *logScan) sinkCall(pkg *logPackage, call *ast.CallExpr) ([]*logSink, bool) { + name, method := "", false + switch fun := call.Fun.(type) { + case *ast.SelectorExpr: + if fun.Sel.Name == "Emit" && len(call.Args) == 4 { + return nil, true + } + name, method = fun.Sel.Name, true + case *ast.Ident: + name = fun.Name + default: + return nil, false + } + var targets []*logSink + for _, decl := range pkg.funcs[name] { + sink := s.sinks[decl] + if sink == nil || (decl.Recv != nil) != method || len(paramNames(decl)) != len(call.Args) { + continue + } + targets = append(targets, sink) + } + return targets, len(targets) > 0 +} + +// escapes reports whether fn is never called by name, or is also used as a value, such as a +// callback handed to another component; its callers then cannot be read from the source. +func (s *logScan) escapes(pkg *logPackage, fn *ast.FuncDecl) bool { + name, method := fn.Name.Name, fn.Recv != nil + calls, values := 0, 0 + for _, file := range pkg.files { + skip := map[ast.Node]bool{} + ast.Inspect(file, func(n ast.Node) bool { + switch n := n.(type) { + case *ast.FuncDecl: + skip[n.Name] = true + case *ast.CallExpr: + skip[n.Fun] = true + if sel, ok := n.Fun.(*ast.SelectorExpr); ok { + skip[sel.Sel] = true + if method && sel.Sel.Name == name { + calls++ + } + } else if id, ok := n.Fun.(*ast.Ident); ok && !method && id.Name == name { + calls++ + } + case *ast.SelectorExpr: + skip[n.Sel] = true + if method && n.Sel.Name == name && !skip[n] { + values++ + } + case *ast.Ident: + if !method && n.Name == name && !skip[n] { + values++ + } + } + return true + }) + } + return calls == 0 || values > 0 +} + +func paramNames(decl *ast.FuncDecl) []string { + var names []string + for _, field := range decl.Type.Params.List { + if len(field.Names) == 0 { + names = append(names, "_") + } + for _, name := range field.Names { + names = append(names, name.Name) + } + } + return names +} + +// logWrite is one assignment to a local variable. +type logWrite struct { + // value is the assigned expression; nil when the source cannot say (a multi-value or + // range assignment, or an operator assignment). + value ast.Expr + // key is set for name[key] = value. + key ast.Expr + // source is what an assignment without a value reads from. + source ast.Expr + // zero marks var name T with no value. + zero bool + // merged marks maps.Copy(name, value). + merged bool +} + +func writes(body *ast.BlockStmt, name string) []logWrite { + var out []logWrite + is := func(e ast.Expr) bool { + id, ok := e.(*ast.Ident) + return ok && id.Name == name + } + ast.Inspect(body, func(n ast.Node) bool { + switch n := n.(type) { + case *ast.AssignStmt: + paired := len(n.Lhs) == len(n.Rhs) && (n.Tok == token.DEFINE || n.Tok == token.ASSIGN) + for i, lhs := range n.Lhs { + w := logWrite{source: n.Rhs[min(i, len(n.Rhs)-1)]} + if paired { + w = logWrite{value: n.Rhs[i]} + } + if is(lhs) { + out = append(out, w) + } + if ix, ok := lhs.(*ast.IndexExpr); ok && is(ix.X) { + w.key = ix.Index + out = append(out, w) + } + } + case *ast.ValueSpec: + for i, id := range n.Names { + switch { + case id.Name != name: + case len(n.Values) == 0: + out = append(out, logWrite{zero: true}) + case len(n.Values) == len(n.Names): + out = append(out, logWrite{value: n.Values[i]}) + default: + out = append(out, logWrite{source: n.Values[0]}) + } + } + case *ast.RangeStmt: + if (n.Key != nil && is(n.Key)) || (n.Value != nil && is(n.Value)) { + out = append(out, logWrite{source: n.X}) + } + case *ast.CallExpr: + if sel, ok := n.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "Copy" && len(n.Args) == 2 && is(n.Args[0]) { + if pkg, ok := sel.X.(*ast.Ident); ok && pkg.Name == "maps" { + out = append(out, logWrite{value: n.Args[1], merged: true}) + } + } + } + return true + }) + return out +} + +// sites reads the events call writes in frame f. +func (f *logFrame) sites(call *ast.CallExpr, where []string) []logSite { + where = append(slices.Clone(where), f.scan.position(call)) + if f.depth > 12 { + return []logSite{{where: where, problem: "the call chain is too deep to follow"}} + } + targets, _ := f.scan.sinkCall(f.pkg, call) + if len(targets) == 0 { + site := logSite{where: where} + level, levelOK := f.text(call.Args[0]) + event, eventOK := f.text(call.Args[1]) + fields, fieldsOK := f.fields(call.Args[3]) + switch { + case !levelOK: + site.problem = "the level is not a constant" + case !eventOK: + site.problem = "the event id is not a constant" + case !fieldsOK: + site.problem = "the field keys cannot be read from the source" + } + site.level, site.event, site.fields = LogLevel(level), event, fields + return []logSite{site} + } + var out []logSite + for _, target := range targets { + // A function that reaches itself again logs through the calls already read at its + // first entry. + if f.active(target.decl) { + continue + } + inner := f.enter(target.pkg, target.decl, call.Args) + for _, c := range target.calls { + out = append(out, inner.sites(c, where)...) + } + } + return out +} + +func (f *logFrame) enter(pkg *logPackage, decl *ast.FuncDecl, args []ast.Expr) *logFrame { + bound := map[string]logBound{} + for i, name := range paramNames(decl) { + if name != "_" && i < len(args) { + bound[name] = logBound{expr: args[i], frame: f} + } + } + return &logFrame{scan: f.scan, pkg: pkg, decl: decl, args: bound, depth: f.depth + 1, busy: map[string]bool{}, parent: f} +} + +// active reports whether decl is being read in f or one of its callers. +func (f *logFrame) active(decl *ast.FuncDecl) bool { + for frame := f; frame != nil; frame = frame.parent { + if frame.decl == decl { + return true + } + } + return false +} + +func (f *logFrame) bind(expr ast.Expr) *logBound { + if expr == nil { + return nil + } + return &logBound{expr: expr, frame: f} +} + +// hit records that the frame read a parameter no caller supplies. +func (f *logFrame) hit(name string) { + if f.hits != nil { + f.hits[name] = true + } +} + +func (f *logFrame) isParam(name string) bool { + return f.decl != nil && slices.Contains(paramNames(f.decl), name) +} + +// logLevelNames are the severity constants of this package, as other packages name them. +var logLevelNames = map[string]LogLevel{"LevelDebug": LevelDebug, "LevelInfo": LevelInfo, "LevelWarn": LevelWarn, "LevelError": LevelError} + +// text is the string value of expr, when the source shows a single one. +func (f *logFrame) text(expr ast.Expr) (string, bool) { + switch e := ast.Unparen(expr).(type) { + case *ast.BasicLit: + if e.Kind == token.STRING { + text, err := strconv.Unquote(e.Value) + return text, err == nil + } + case *ast.BinaryExpr: + if e.Op == token.ADD { + left, leftOK := f.text(e.X) + right, rightOK := f.text(e.Y) + return left + right, leftOK && rightOK + } + case *ast.SelectorExpr: + if pkg, ok := e.X.(*ast.Ident); ok && pkg.Name == "core" { + if level, ok := logLevelNames[e.Sel.Name]; ok { + return string(level), true + } + } + case *ast.Ident: + return f.identText(e.Name) + case *ast.CallExpr: + // string(x) of a string-typed constant is that constant. + if fun, ok := e.Fun.(*ast.Ident); ok && fun.Name == "string" && len(e.Args) == 1 { + return f.text(e.Args[0]) + } + } + return "", false +} + +func (f *logFrame) identText(name string) (string, bool) { + if bound, ok := f.args[name]; ok { + return bound.frame.text(bound.expr) + } + if f.decl != nil { + if f.isParam(name) { + f.hit(name) + return "", false + } + if f.busy[name] { + return "", false + } + if ws := writes(f.decl.Body, name); len(ws) > 0 { + f.busy[name] = true + defer delete(f.busy, name) + var value string + for i, w := range ws { + if w.value == nil || w.key != nil || w.merged { + return "", false + } + text, ok := f.text(w.value) + if !ok || (i > 0 && text != value) { + return "", false + } + value = text + } + return value, true + } + } + if c, ok := f.pkg.consts[name]; ok { + return (&logFrame{scan: f.scan, pkg: f.pkg, busy: map[string]bool{}}).text(c) + } + return "", false +} + +// logErrorKeys are the keys LogErrorFields writes for an error field called name. +func logErrorKeys(name string) map[string]*logBound { + return map[string]*logBound{name: nil, name + "_code": nil, name + "_domain": nil} +} + +// fields returns the keys of the map expr builds, each with the expression of its value when +// the source shows one. Keys set on different branches are all included. +func (f *logFrame) fields(expr ast.Expr) (map[string]*logBound, bool) { + if f.depth > 12 { + return nil, false + } + switch e := ast.Unparen(expr).(type) { + case *ast.Ident: + if e.Name == "nil" { + return map[string]*logBound{}, true + } + if bound, ok := f.args[e.Name]; ok { + return bound.frame.fields(bound.expr) + } + if f.isParam(e.Name) { + f.hit(e.Name) + return nil, false + } + if f.decl == nil || f.busy[e.Name] { + return nil, false + } + ws := writes(f.decl.Body, e.Name) + if len(ws) == 0 { + return nil, false + } + f.busy[e.Name] = true + defer delete(f.busy, e.Name) + out := map[string]*logBound{} + for _, w := range ws { + switch { + case w.zero: + case w.key != nil: + key, ok := f.text(w.key) + if !ok { + return nil, false + } + out[key] = f.bind(w.value) + case w.value != nil: + more, ok := f.fields(w.value) + if !ok { + return nil, false + } + for key, value := range more { + out[key] = value + } + default: + return nil, false + } + } + return out, true + case *ast.CompositeLit: + out := map[string]*logBound{} + for _, elt := range e.Elts { + kv, ok := elt.(*ast.KeyValueExpr) + if !ok { + return nil, false + } + key, ok := f.text(kv.Key) + if !ok { + return nil, false + } + out[key] = f.bind(kv.Value) + } + return out, true + case *ast.CallExpr: + return f.callFields(e) + } + return nil, false +} + +// callFields reads the map a call returns: LogErrorFields, maps.Clone, or a function of the +// same package whose returns show their keys. +func (f *logFrame) callFields(call *ast.CallExpr) (map[string]*logBound, bool) { + name, method := "", false + switch fun := call.Fun.(type) { + case *ast.SelectorExpr: + if pkg, ok := fun.X.(*ast.Ident); ok { + switch { + case pkg.Name == "core" && fun.Sel.Name == "LogErrorFields": + return logErrorKeys("error"), true + case pkg.Name == "maps" && fun.Sel.Name == "Clone" && len(call.Args) == 1: + return f.fields(call.Args[0]) + } + } + name, method = fun.Sel.Name, true + case *ast.Ident: + name = fun.Name + default: + return nil, false + } + out := map[string]*logBound{} + found := false + for _, decl := range f.pkg.funcs[name] { + if (decl.Recv != nil) != method || len(paramNames(decl)) != len(call.Args) { + continue + } + found = true + inner := f.enter(f.pkg, decl, call.Args) + var failed bool + ast.Inspect(decl.Body, func(n ast.Node) bool { + switch n := n.(type) { + case *ast.FuncLit: + return false + case *ast.ReturnStmt: + if len(n.Results) == 0 { + failed = true + return false + } + more, ok := inner.fields(n.Results[0]) + if !ok { + failed = true + return false + } + for key, value := range more { + out[key] = value + } + } + return true + }) + if failed { + return nil, false + } + } + return out, found +} diff --git a/desktop/internal/termview/session.go b/desktop/internal/termview/session.go index 71cc4ac1fe..686e02f3d1 100644 --- a/desktop/internal/termview/session.go +++ b/desktop/internal/termview/session.go @@ -34,7 +34,7 @@ func (v *View) start() { v.ended = true v.say(sgrFail, v.cfg.Messages.StartFailed(err.Error())) v.say(sgrMuted, v.cfg.Messages.RestartHint) - v.failed(Failure{Event: eventStartFailed, Warn: true, Err: err}) + v.failed(Failure{Event: eventStartFailed, Stage: stageSpawn, Warn: true, Err: err}) v.exited(nil) return } diff --git a/desktop/internal/termview/view.go b/desktop/internal/termview/view.go index d900ff2ab6..a8b80b4529 100644 --- a/desktop/internal/termview/view.go +++ b/desktop/internal/termview/view.go @@ -120,6 +120,7 @@ type Failure struct { const ( eventStartFailed = "terminal.session.start_failed" eventInputFailed = "terminal.input.failed" + stageSpawn = "spawn" stageSend = "send" ) diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 031fd3f7e5..1e79464765 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -904,17 +904,41 @@ func (a *App) emit(level core.LogLevel, event string, fields map[string]any) { } } -// Surfaces a user action can be started from, written as the catalog's tokens. +// actionSurface is the part of the window a user action was started from. The set is closed: +// it is the list the catalog gives for the surface field of app.action.performed, and the +// test that checks every logging call against the kernel rejects a value outside it. +type actionSurface string + +// The surfaces, written as the catalog's tokens. Each one is typed, so performed cannot be +// handed a bare string. const ( - surfaceButton = "button" - surfaceMenu = "menu" - surfaceShortcut = "shortcut" + // surfaceMenu is a menu bar menu, the compact menu, or a drop-down opened from a menu + // button. + surfaceMenu actionSurface = "menu" + // surfaceShortcut is a key binding. + surfaceShortcut actionSurface = "shortcut" + // surfacePalette is a command picked in Search Everywhere. + surfacePalette actionSurface = "palette" + // surfaceToolbar is a control on the title bar. + surfaceToolbar actionSurface = "toolbar" + // surfaceButton is a control clicked in a panel, tool window, sheet or dialog: a button, a + // link, a list row or a gutter mark. + surfaceButton actionSurface = "button" + // surfaceContextMenu is a menu opened with a secondary click or from a "more" button on + // an item. + surfaceContextMenu actionSurface = "context_menu" + // surfaceNotification is a button on a notification. + surfaceNotification actionSurface = "notification" + // surfacePlugin is a plugin backend asking the host to do the action. + surfacePlugin actionSurface = "plugin" + // surfaceDragDrop is a drop of a dragged file, tab or tree item. + surfaceDragDrop actionSurface = "drag_drop" ) // performed logs that the user started the action with the stable id from surface, as the // macOS client does; the id is never a localized title. -func (a *App) performed(action, surface string) { - a.emit(core.LevelInfo, "app.action.performed", map[string]any{"action": action, "surface": surface}) +func (a *App) performed(action string, surface actionSurface) { + a.emit(core.LevelInfo, "app.action.performed", map[string]any{"action": action, "surface": string(surface)}) } // titleBarHeight is the height of the title bar on both screens; the system's window @@ -1034,7 +1058,7 @@ func (a *App) activate(index int) { a.titleDebug(a.project) case it.id == itemTitleSearch: if a.project != nil { - a.performed("workspace.searchEverywhere.open", surfaceButton) + a.performed("workspace.searchEverywhere.open", surfaceToolbar) a.openEverywhere(a.project) } case it.id == itemCaret: @@ -1107,7 +1131,7 @@ func (a *App) reduceRecent(entries []core.RecentProject, action core.RecentActio // chooseProject asks for a project folder and opens it; surface is where the user asked. // The system dialog runs off the window thread so the window keeps painting behind it. -func (a *App) chooseProject(surface string) { +func (a *App) chooseProject(surface actionSurface) { title := a.text.Welcome.OpenDialogTitle a.background(nil, 0, func(context.Context) func(*App) { path, err := app.OpenDirectory(app.OpenDirectoryOptions{Title: title}) diff --git a/desktop/internal/workbench/branch.go b/desktop/internal/workbench/branch.go index cd11fbe855..4dc56f8a18 100644 --- a/desktop/internal/workbench/branch.go +++ b/desktop/internal/workbench/branch.go @@ -226,14 +226,14 @@ func (a *App) runBranchWrite(p *project, operation string, failed func(reason st } // checkoutBranch checks out r, after asking the kernel whether local changes stand in the -// way. A branch that is already checked out only says so. -func (a *App) checkoutBranch(p *project, r core.GitReference) { +// way. A branch that is already checked out only says so. surface is where the user asked. +func (a *App) checkoutBranch(p *project, r core.GitReference, surface actionSurface) { a.leaveBranches() if r.Kind == "local" && r.IsCurrent { a.notifyInfo(a.text.Branch.AlreadyOn(r.ShortName)) return } - a.performed("git.checkout", surfaceMenu) + a.performed("git.checkout", surface) b := &a.branch b.busy = true kernel, root := a.kernel, a.branchRoot(p) diff --git a/desktop/internal/workbench/branch_view.go b/desktop/internal/workbench/branch_view.go index e2d21cd1b0..728ae32399 100644 --- a/desktop/internal/workbench/branch_view.go +++ b/desktop/internal/workbench/branch_view.go @@ -144,7 +144,7 @@ func (a *App) drawBranchActions(c ui.C, p *project, current core.GitReference, q if a.drawBranchAction(c, "fetch", icons.Download, g.Fetch, busy) { c.After(func() { a.closeBranches() - a.fetchAllAt(p, root) + a.fetchAllAt(p, root, surfaceButton) }) } } @@ -153,7 +153,7 @@ func (a *App) drawBranchActions(c ui.C, p *project, current core.GitReference, q if a.drawBranchAction(c, "update", icons.ArrowDownLeft, g.UpdateBranch, busy || !onBranch) { c.After(func() { a.closeBranches() - a.updateCurrentBranchAt(p, root, current.ShortName) + a.updateCurrentBranchAt(p, root, current.ShortName, surfaceButton) }) } } @@ -161,6 +161,7 @@ func (a *App) drawBranchActions(c ui.C, p *project, current core.GitReference, q shown++ if a.drawBranchAction(c, "commit", icons.GitCommitHorizontal, commit, false) { c.After(func() { + a.performed("git.showChanges", surfaceButton) a.closeBranches() a.layout.commitTab = commitTabChanges a.showChanges() @@ -172,7 +173,7 @@ func (a *App) drawBranchActions(c ui.C, p *project, current core.GitReference, q if a.drawBranchAction(c, "push", icons.ArrowUp, push, busy || !onBranch) { c.After(func() { a.closeBranches() - a.openPushOf(p, root, core.GitReference{}) + a.openPushOf(p, root, core.GitReference{}, surfaceButton) }) } } @@ -453,7 +454,7 @@ func (a *App) drawBranchRowMenu(c ui.C, menu *ui.MenuItems, p *project, r core.G if !current { menu.Separator() if menu.Item(t.Checkout).Disabled(busy).Clicked() { - c.After(func() { a.checkoutBranch(p, r) }) + c.After(func() { a.checkoutBranch(p, r, surfaceMenu) }) } } if r.Kind == "local" { @@ -462,13 +463,13 @@ func (a *App) drawBranchRowMenu(c ui.C, menu *ui.MenuItems, p *project, r core.G if menu.Item(i18n.Shared(lang, "git.log.updateBranch")).Disabled(busy || !current && r.UpstreamShortName == "").Clicked() { c.After(func() { a.closeBranches() - a.updateBranchAt(p, root, r) + a.updateBranchAt(p, root, r, surfaceMenu) }) } if menu.Item(i18n.Shared(lang, "git.contextMenu.push")).Disabled(busy).Clicked() { c.After(func() { a.closeBranches() - a.openPushOf(p, root, r) + a.openPushOf(p, root, r, surfaceMenu) }) } if menu.Item(t.Rename).Disabled(busy).Clicked() { diff --git a/desktop/internal/workbench/browser_preview.go b/desktop/internal/workbench/browser_preview.go index 7822bcb8f3..799491ed23 100644 --- a/desktop/internal/workbench/browser_preview.go +++ b/desktop/internal/workbench/browser_preview.go @@ -25,7 +25,7 @@ func browserPreviewable(d *document) bool { // openInBrowser saves d when it has changes and opens the file in the default web browser. The // system is asked off the window thread: on macOS the handoff waits for open to report. -func (a *App) openInBrowser(p *project, d *document) { +func (a *App) openInBrowser(p *project, d *document, surface actionSurface) { if !browserPreviewable(d) { return } @@ -39,7 +39,7 @@ func (a *App) openInBrowser(p *project, d *document) { a.notifyError(i18n.SharedFormat(a.language(), "desktop.editorMenu.openInBrowserFailed", map[string]string{"reason": err.Error()})) return } - a.performed("editor.openInBrowser", surfaceMenu) + a.performed("editor.openInBrowser", surface) } }) } diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index 51e1c6f573..cfcc780c83 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -904,7 +904,6 @@ func (a *App) runBuildTask(p *project, projectID, targetID, taskID string, userA return nil, refuseBuild(refusalInvalid, "this task requires user arguments") } } - a.emit(core.LevelInfo, "app.action.performed", map[string]any{"action": "build.runTask", "surface": "build"}) captured := *instance kernel := a.kernel messages := a.text.Build @@ -1144,7 +1143,6 @@ func (a *App) runBuildEntry(p *project, entryID string) { } captured := *instance messages := a.text.Build - a.emit(core.LevelInfo, "app.action.performed", map[string]any{"action": "build.runEntry", "surface": "build"}) op := a.beginBuildOperation(p, "run", entry.Name, "", restartWithInstance(instance.ID, func(a *App, p *project) { a.runBuildEntry(p, entryID) })) @@ -1222,7 +1220,6 @@ func (a *App) debugProviderTarget(p *project, index int, projectID, targetID, ru Project: &core.BuildSelection{Name: project.Name, Path: project.Path, Properties: project.Properties}, Target: &core.BuildSelection{Name: target.Name, Path: target.Path, Tags: target.Tags, Properties: target.Properties}, } - a.emit(core.LevelInfo, "app.action.performed", map[string]any{"action": "build.debugTarget", "surface": "build"}) p.debug.preparing = true fail := func(err error) func(*App) { return func(a *App) { @@ -1351,7 +1348,6 @@ func (a *App) runBuildTargetWith(p *project, op *buildOperation, instance *build captured := *instance kernel := a.kernel messages := a.text.Build - a.emit(core.LevelInfo, "app.action.performed", map[string]any{"action": "build.runTarget", "surface": "build"}) a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { prepare, release := op.bind(ctx) defer release() diff --git a/desktop/internal/workbench/build_menus.go b/desktop/internal/workbench/build_menus.go index c85d227e3f..093f07801a 100644 --- a/desktop/internal/workbench/build_menus.go +++ b/desktop/internal/workbench/build_menus.go @@ -26,7 +26,7 @@ func (a *App) buildRowMenu(c ui.C, row ui.Box, p *project, instance *buildInstan case buildRowTask: if menu.Item(i18n.Shared(lang, "desktop.runConfig.run")).Disabled(b.operation != nil).Clicked() { c.After(func() { - a.performed("build.task.run", surfaceMenu) + a.performed("build.task.run", surfaceContextMenu) a.chooseBuildInstance(p, spec.instance) b.taskID = spec.id a.runSelectedBuildTask(p) @@ -41,7 +41,7 @@ func (a *App) buildRowMenu(c ui.C, row ui.Box, p *project, instance *buildInstan runID := run.ID if menu.Item(a.text.Build.RunTarget(run.Name)).Disabled(b.operation != nil || instance.modelLoading).Clicked() { c.After(func() { - a.performed("build.target.run", surfaceMenu) + a.performed("build.target.run", surfaceContextMenu) a.chooseBuildInstance(p, spec.instance) b.projectID, b.targetID = spec.project, spec.id a.runBuildTarget(p, spec.id, runID) @@ -52,7 +52,7 @@ func (a *App) buildRowMenu(c ui.C, row ui.Box, p *project, instance *buildInstan // plugin: the provider prepares the native debug program and that adapter starts it. if run.DebugAdapter != "" && menu.Item(i18n.Shared(lang, "desktop.build.debugTarget")).Disabled(b.operation != nil || instance.modelLoading || p.debug.preparing).Clicked() { c.After(func() { - a.performed("build.target.debug", surfaceMenu) + a.performed("build.target.debug", surfaceContextMenu) a.chooseBuildInstance(p, spec.instance) b.projectID, b.targetID = spec.project, spec.id a.debugBuildTarget(p, spec.id, runID) @@ -63,7 +63,7 @@ func (a *App) buildRowMenu(c ui.C, row ui.Box, p *project, instance *buildInstan entryID := entry.ID if menu.Item(a.text.Build.RunTarget(entry.Name)).Disabled(b.operation != nil || instance.modelLoading).Clicked() { c.After(func() { - a.performed("build.target.run", surfaceMenu) + a.performed("build.target.run", surfaceContextMenu) a.chooseBuildInstance(p, spec.instance) b.projectID, b.targetID = spec.project, spec.id a.runBuildEntry(p, entryID) @@ -74,7 +74,7 @@ func (a *App) buildRowMenu(c ui.C, row ui.Box, p *project, instance *buildInstan if buildTargetTestable(instance, *spec.target) { if menu.Item(i18n.Shared(lang, "native.runTests")).Disabled(p.tests.running || instance.modelLoading).Clicked() { c.After(func() { - a.performed("build.target.test", surfaceMenu) + a.performed("build.target.test", surfaceContextMenu) a.chooseBuildInstance(p, spec.instance) b.projectID, b.targetID = spec.project, spec.id a.runBuildTargetTests(p, instance, spec.id) @@ -85,7 +85,7 @@ func (a *App) buildRowMenu(c ui.C, row ui.Box, p *project, instance *buildInstan if buildTestDeclares(instance, "project") { if menu.Item(i18n.Shared(lang, "native.runTests")).Disabled(p.tests.running || instance.modelLoading).Clicked() { c.After(func() { - a.performed("build.project.test", surfaceMenu) + a.performed("build.project.test", surfaceContextMenu) a.chooseBuildInstance(p, spec.instance) a.runBuildProjectTests(p, instance, spec.id) }) @@ -95,7 +95,7 @@ func (a *App) buildRowMenu(c ui.C, row ui.Box, p *project, instance *buildInstan label := i18n.SharedFormat(lang, "native.open", map[string]string{"arg1": filepath.Base(path)}) if menu.Item(label).Clicked() { c.After(func() { - a.performed("build.project.openBuildFile", surfaceMenu) + a.performed("build.project.openBuildFile", surfaceContextMenu) a.openFile(p, path) }) } @@ -103,7 +103,7 @@ func (a *App) buildRowMenu(c ui.C, row ui.Box, p *project, instance *buildInstan index := spec.instance if menu.Item(i18n.Shared(lang, "native.reload")).Disabled(instance.modelLoading || b.operation != nil).Clicked() { c.After(func() { - a.performed("build.model.reload", surfaceMenu) + a.performed("build.model.reload", surfaceContextMenu) a.reloadBuildModel(p, index) }) } @@ -120,7 +120,7 @@ func (a *App) buildDependencyMenu(c ui.C, row ui.Box, p *project, instance *buil deps := a.dependenciesOf(p, instance, projectID) if menu.Item(i18n.Shared(lang, "native.reload")).Disabled(deps.loading).Clicked() { c.After(func() { - a.performed("build.dependencies.reload", surfaceMenu) + a.performed("build.dependencies.reload", surfaceContextMenu) a.loadBuildDependencies(p, instance, projectID, deps, true) }) } @@ -128,7 +128,7 @@ func (a *App) buildDependencyMenu(c ui.C, row ui.Box, p *project, instance *buil label := i18n.SharedFormat(lang, "native.open", map[string]string{"arg1": filepath.Base(path)}) if menu.Item(label).Clicked() { c.After(func() { - a.performed("build.dependencies.openBuildFile", surfaceMenu) + a.performed("build.dependencies.openBuildFile", surfaceContextMenu) a.openFile(p, path) }) } diff --git a/desktop/internal/workbench/build_tests.go b/desktop/internal/workbench/build_tests.go index daf42b843a..4c33f44378 100644 --- a/desktop/internal/workbench/build_tests.go +++ b/desktop/internal/workbench/build_tests.go @@ -372,7 +372,7 @@ func (a *App) buildTestRow(row ui.ListRow, p *project, instance *buildInstance, menu.WidthRange(180, 280) if menu.Item(label).Disabled(p.tests.running).Clicked() { c.After(func() { - a.performed("build.tests.runCase", surfaceMenu) + a.performed("build.tests.runCase", surfaceContextMenu) a.runDiscoveredTest(p, instance, test) }) } @@ -393,7 +393,7 @@ func (a *App) buildTestsMenuItems(c ui.C, menu *ui.MenuItems, p *project, instan tests := p.discoveredTestsView(instance) if menu.Item(i18n.Shared(a.language(), "native.refreshDiscoveredTests")).Disabled(tests.loading).Clicked() { c.After(func() { - a.performed("build.tests.refresh", surfaceMenu) + a.performed("build.tests.refresh", surfaceContextMenu) a.discoverBuildTests(p, instance, true) }) } diff --git a/desktop/internal/workbench/build_tree_view.go b/desktop/internal/workbench/build_tree_view.go index 20215840c5..43d922bec5 100644 --- a/desktop/internal/workbench/build_tree_view.go +++ b/desktop/internal/workbench/build_tree_view.go @@ -306,13 +306,13 @@ func (a *App) buildGroupRow(row ui.ListRow, p *project, instance *buildInstance, menu.WidthRange(180, 280) if menu.Item(i18n.Shared(language, "native.reload")).Disabled(instance.modelLoading || b.operation != nil).Clicked() { c.After(func() { - a.performed("build.model.reload", surfaceMenu) + a.performed("build.model.reload", surfaceContextMenu) a.reloadBuildModel(p, index) }) } if options && menu.Item(i18n.Shared(language, "desktop.build.options")).Clicked() { c.After(func() { - a.performed("build.options.open", surfaceMenu) + a.performed("build.options.open", surfaceContextMenu) a.chooseBuildInstance(p, index) a.openBuildOptions(p, p.selectedBuildInstance()) }) @@ -404,7 +404,7 @@ func (a *App) buildNoteRow(row ui.ListRow, p *project, instance *buildInstance, menu.WidthRange(180, 280) if menu.Item(i18n.Shared(a.language(), "native.reload")).Disabled(instance.modelLoading || p.build.operation != nil).Clicked() { c.After(func() { - a.performed("build.model.reload", surfaceMenu) + a.performed("build.model.reload", surfaceContextMenu) a.reloadBuildModel(p, index) }) } diff --git a/desktop/internal/workbench/chrome_view.go b/desktop/internal/workbench/chrome_view.go index ca312c2509..8a4881c5a2 100644 --- a/desktop/internal/workbench/chrome_view.go +++ b/desktop/internal/workbench/chrome_view.go @@ -791,14 +791,14 @@ func (a *App) stripeButtonMenu(c ui.C, i int, at zone) func(*ui.MenuItems) { label := a.chrome.catalog[i].label(a.text) if menu.Item(i18n.SharedFormat(language, "native.hideToolWindow", map[string]string{"arg1": label})).Clicked() { c.After(func() { - a.performed("workbench.toolWindow.hide", surfaceMenu) + a.performed("workbench.toolWindow.hide", surfaceContextMenu) a.reduceChrome(core.SetChromeOpen(id, false)) }) } } if menu.Item(i18n.Shared(language, "native.hideEntry")).Clicked() { c.After(func() { - a.performed("workbench.toolWindow.hideEntry", surfaceMenu) + a.performed("workbench.toolWindow.hideEntry", surfaceContextMenu) a.hideEntry(i) }) } @@ -811,7 +811,7 @@ func (a *App) stripeButtonMenu(c ui.C, i int, at zone) func(*ui.MenuItems) { target := zoneNames[z] if sub.Item(stripeZoneMoveText(language, z)).Clicked() { c.After(func() { - a.performed("workbench.toolWindow.move", surfaceMenu) + a.performed("workbench.toolWindow.move", surfaceContextMenu) a.reduceChrome(core.MoveChrome(id, target, "")) }) } @@ -828,7 +828,7 @@ func (a *App) stripeButtonMenu(c ui.C, i int, at zone) func(*ui.MenuItems) { if menu.Item(i18n.Shared(language, "native.moveEarlier")).Disabled(position == 0).Clicked() { before := a.chrome.catalog[items[max(position-1, 0)]].id c.After(func() { - a.performed("workbench.toolWindow.moveEarlier", surfaceMenu) + a.performed("workbench.toolWindow.moveEarlier", surfaceContextMenu) a.reduceChrome(core.MoveChrome(id, zoneNames[at], before)) }) } @@ -838,7 +838,7 @@ func (a *App) stripeButtonMenu(c ui.C, i int, at zone) func(*ui.MenuItems) { before = a.chrome.catalog[items[position+2]].id } c.After(func() { - a.performed("workbench.toolWindow.moveLater", surfaceMenu) + a.performed("workbench.toolWindow.moveLater", surfaceContextMenu) a.reduceChrome(core.MoveChrome(id, zoneNames[at], before)) }) } diff --git a/desktop/internal/workbench/clone.go b/desktop/internal/workbench/clone.go index a37b819fe5..eec6019180 100644 --- a/desktop/internal/workbench/clone.go +++ b/desktop/internal/workbench/clone.go @@ -23,7 +23,7 @@ type cloneState struct { err string } -func (a *App) openClone(surface string) { +func (a *App) openClone(surface actionSurface) { c := &a.clone if c.open { return diff --git a/desktop/internal/workbench/commands.go b/desktop/internal/workbench/commands.go index ea85a46476..8ac8b4e054 100644 --- a/desktop/internal/workbench/commands.go +++ b/desktop/internal/workbench/commands.go @@ -32,7 +32,28 @@ type command struct { shortcut string // enabled is false for an action that cannot run now; it is listed greyed. enabled bool - run func() + // run is the action. startCommand records it as command. before running it. + run func() + // runFrom, set instead of run, is an action that records the user action itself, such as + // opening Settings: it is handed the surface the command was started from, so the action + // is recorded once, under its own id and with the right surface. + runFrom func(actionSurface) +} + +// runnable reports whether the command is listed enabled and has an action. +func (c command) runnable() bool { + return c.enabled && (c.run != nil || c.runFrom != nil) +} + +// startCommand runs c, started from surface, and records it once: a command with runFrom +// records itself, every other one is recorded as command.. +func (a *App) startCommand(c command, surface actionSurface) { + if c.runFrom != nil { + c.runFrom(surface) + return + } + a.performed("command."+c.id, surface) + c.run() } // commands lists the actions available in the current window. @@ -44,11 +65,15 @@ func (a *App) commands() []command { add := func(id, group, title, _ string, enabled bool, run func()) { list = append(list, command{id: id, group: group, title: title, shortcut: keys.Label(id), enabled: enabled, run: run}) } + // addFrom adds a command whose action records itself with the surface it is handed. + addFrom := func(id, group, title string, enabled bool, run func(actionSurface)) { + list = append(list, command{id: id, group: group, title: title, shortcut: keys.Label(id), enabled: enabled, runFrom: run}) + } - add("settings.open", t.GroupApp, t.Settings, "", true, func() { a.openSettings(surfaceMenu) }) - add("plugins.open", t.GroupApp, t.Plugins, "", true, func() { a.openPluginSettings(surfaceMenu) }) + addFrom("settings.open", t.GroupApp, t.Settings, true, a.openSettings) + addFrom("plugins.open", t.GroupApp, t.Plugins, true, a.openPluginSettings) add("logs.open", t.GroupApp, t.Logs, "", true, a.openLogs) - add("legacy.import", t.GroupApp, t.ImportLegacy, "", true, a.readLegacyImport) + addFrom("legacy.import", t.GroupApp, t.ImportLegacy, true, a.readLegacyImport) add("theme.system", t.GroupView, t.ThemeSystem, "", a.settings.Theme != themeSystem, func() { a.setTheme(themeSystem) }) add("theme.light", t.GroupView, t.ThemeLight, "", a.settings.Theme != themeLight, func() { a.setTheme(themeLight) }) add("theme.dark", t.GroupView, t.ThemeDark, "", a.settings.Theme != themeDark, func() { a.setTheme(themeDark) }) @@ -61,9 +86,9 @@ func (a *App) commands() []command { add("language.zh", t.GroupView, t.LanguageChinese, "", a.settings.Language != "zh-Hans", func() { a.setLanguage("zh-Hans") }) add("editor.vimMode", t.GroupEditor, t.ToggleVim, "", true, func() { a.setVimMode(!a.settings.VimMode) }) - add("project.open", t.GroupProject, t.OpenProject, "", true, func() { a.chooseProject(surfaceMenu) }) - add("project.new", t.GroupProject, t.NewProject, "", true, func() { a.openNewProject(surfaceMenu) }) - add("project.clone", t.GroupProject, t.Clone, "", true, func() { a.openClone(surfaceMenu) }) + addFrom("project.open", t.GroupProject, t.OpenProject, true, a.chooseProject) + addFrom("project.new", t.GroupProject, t.NewProject, true, a.openNewProject) + addFrom("project.clone", t.GroupProject, t.Clone, true, a.openClone) if p == nil { return sortCommands(list) } @@ -101,12 +126,12 @@ func (a *App) commands() []command { } } if d := p.selectedDocument(p.docs.group); browserPreviewable(d) { - add("editor.openInBrowser", t.GroupEditor, i18n.Shared(a.language(), "desktop.editorMenu.openInBrowser"), "", true, func() { a.openInBrowser(p, d) }) + addFrom("editor.openInBrowser", t.GroupEditor, i18n.Shared(a.language(), "desktop.editorMenu.openInBrowser"), true, func(surface actionSurface) { a.openInBrowser(p, d, surface) }) } // Code folding of the selected document. if d := p.selectedDocument(p.docs.group); d != nil { - add("editor.find", t.GroupEditor, i18n.Shared(a.language(), "desktop.editorFind.find"), "", true, func() { a.openEditorFind(false) }) - add("editor.replace", t.GroupEditor, i18n.Shared(a.language(), "desktop.editorFind.replace"), "", !d.virtual, func() { a.openEditorFind(true) }) + addFrom("editor.find", t.GroupEditor, i18n.Shared(a.language(), "desktop.editorFind.find"), true, func(surface actionSurface) { a.openEditorFind(false, surface) }) + addFrom("editor.replace", t.GroupEditor, i18n.Shared(a.language(), "desktop.editorFind.replace"), !d.virtual, func(surface actionSurface) { a.openEditorFind(true, surface) }) add("editor.fold", t.GroupEditor, t.Fold, "", true, func() { a.foldCommand(d, func(v *editorview.View) { v.FoldAtCaret() }) }) add("editor.unfold", t.GroupEditor, t.Unfold, "", true, func() { a.foldCommand(d, func(v *editorview.View) { v.UnfoldAtCaret() }) }) add("editor.foldAll", t.GroupEditor, t.FoldAll, "", true, func() { a.foldCommand(d, (*editorview.View).FoldAll) }) @@ -168,12 +193,12 @@ func (a *App) commands() []command { add("search.files", t.GroupSearch, t.FindInFiles, "", true, func() { a.openFindInFiles(p, false) }) add("search.replace", t.GroupSearch, t.ReplaceInFiles, "", true, func() { a.openFindInFiles(p, true) }) - add("git.commit", t.GroupGit, t.Commit, "", true, func() { a.startCommit(p, false, surfaceMenu) }) - add("git.commitPush", t.GroupGit, t.CommitAndPush, "", true, func() { a.startCommit(p, true, surfaceMenu) }) + addFrom("git.commit", t.GroupGit, t.Commit, true, func(surface actionSurface) { a.startCommit(p, false, surface) }) + addFrom("git.commitPush", t.GroupGit, t.CommitAndPush, true, func(surface actionSurface) { a.startCommit(p, true, surface) }) add("git.branches", t.GroupGit, t.Branches, "", true, a.openBranches) add("git.pull", t.GroupGit, a.text.Sync.Pull.MenuItem, "", p.git.isRepository(), func() { a.openPullDialog(p) }) if d := p.selectedDocument(p.docs.group); d != nil && !d.virtual { - add("git.lineHistory", t.GroupGit, i18n.Shared(a.language(), "desktop.editorMenu.lineHistory"), "", p.git.isRepository(), func() { a.startLineHistory(p, d) }) + addFrom("git.lineHistory", t.GroupGit, i18n.Shared(a.language(), "desktop.editorMenu.lineHistory"), p.git.isRepository(), func(surface actionSurface) { a.startLineHistory(p, d, surface) }) } add("git.console", t.GroupGit, t.GitConsole, "", true, func() { a.showGitConsole("") }) @@ -221,9 +246,10 @@ func matchCommands(list []command, query string) []command { return out } -// runCommand closes Search Everywhere and runs one action. -func (a *App) runCommand(c command) { - if !c.enabled || c.run == nil { +// runCommand closes Search Everywhere and runs one action, started from surface: the Find +// Action list or the compact menu. +func (a *App) runCommand(c command, surface actionSurface) { + if !c.runnable() { return } if p := a.project; p != nil { @@ -231,8 +257,7 @@ func (a *App) runCommand(c command) { } else { a.everywhereView.open = false } - a.performed("command."+c.id, surfaceMenu) - c.run() + a.startCommand(c, surface) } // openFindAction opens Search Everywhere on its Actions tab. @@ -283,7 +308,7 @@ func (a *App) everywhereActions(c ui.C) { } if run >= 0 { command := matches[run] - c.After(func() { a.runCommand(command) }) + c.After(func() { a.runCommand(command, surfacePalette) }) } } @@ -292,7 +317,7 @@ func (a *App) runSelectedAction() { v := &a.everywhereView matches := matchCommands(a.commands(), v.actionQuery()) if v.actionSelected >= 0 && v.actionSelected < len(matches) { - a.runCommand(matches[v.actionSelected]) + a.runCommand(matches[v.actionSelected], surfacePalette) } } diff --git a/desktop/internal/workbench/commit.go b/desktop/internal/workbench/commit.go index ab08b03bea..80bda79b53 100644 --- a/desktop/internal/workbench/commit.go +++ b/desktop/internal/workbench/commit.go @@ -224,12 +224,12 @@ func (c *commitState) retryable() bool { // startCommit plans a commit of the project's staged changes and runs it, through the review // when the plan or a push asks for one. surface is where the user asked. -func (a *App) startCommit(p *project, push bool, surface string) { +func (a *App) startCommit(p *project, push bool, surface actionSurface) { a.startCommitIn(p, p.projectCommit(), push, surface) } // startCommitIn is startCommit in the checkout of t. -func (a *App) startCommitIn(p *project, t commitTarget, push bool, surface string) { +func (a *App) startCommitIn(p *project, t commitTarget, push bool, surface actionSurface) { c := t.state if c.busy || c.review != nil { return @@ -432,6 +432,20 @@ const ( operationFailedLevel = core.LevelError ) +// The log event of a failure no notification reports, such as cleanup after the work is done, +// and the level the kernel's event catalog declares for it. It has the same fields as +// app.notification.operation_failed. +const ( + backgroundFailedEvent = "app.background.operation_failed" + backgroundFailedLevel = core.LevelWarn +) + +// backgroundFailed logs a failure of work the window runs on its own and does not tell the +// user about. +func (a *App) backgroundFailed(operation string, err error) { + a.emit(backgroundFailedLevel, backgroundFailedEvent, operationFailedFields(operation, err)) +} + // gitOperationFailed logs a Git operation that failed. func (a *App) gitOperationFailed(operation string, err error) { a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields(operation, err)) @@ -485,7 +499,7 @@ func allStaged(changes []core.GitChange) bool { // stageAll stages every change of the active ChangeList, or unstages every staged one when // everything is staged already, as the checkbox of the change list does. While only the // default list exists that is every change of the repository. -func (a *App) stageAll(p *project, surface string) { +func (a *App) stageAll(p *project, surface actionSurface) { if p.commit.busy || !p.listsReady() { return } @@ -508,7 +522,7 @@ func (a *App) stageAll(p *project, surface string) { // stageChanges stages every one of changes, or unstages them all when they are all staged, // as the checkbox of a ChangeList section does. -func (a *App) stageChanges(p *project, changes []core.GitChange, surface string) { +func (a *App) stageChanges(p *project, changes []core.GitChange, surface actionSurface) { if p.commit.busy || !p.listsReady() { return } @@ -533,7 +547,7 @@ func (a *App) stageChanges(p *project, changes []core.GitChange, surface string) } // unstageAll unstages every staged change. -func (a *App) unstageAll(p *project, surface string) { +func (a *App) unstageAll(p *project, surface actionSurface) { if p.commit.busy { return } diff --git a/desktop/internal/workbench/commit_view.go b/desktop/internal/workbench/commit_view.go index 8ad3b6eb90..ae19cec2c4 100644 --- a/desktop/internal/workbench/commit_view.go +++ b/desktop/internal/workbench/commit_view.go @@ -71,7 +71,7 @@ func (a *App) drawCommitToolbar(c ui.C, p *project) { } if a.gitIconButton(c, i18n.Shared(lang, "git.previewFirstChange"), icons.Eye, false, !review || len(changes) == 0) { first := changes[0] - c.After(func() { a.openChange(p, first) }) + c.After(func() { a.openChange(p, first, surfaceButton) }) } ui.Spacer(c) if branch := p.git.branch(); branch != "" { @@ -143,7 +143,7 @@ func (a *App) drawCommitChange(c ui.C, p *project, change core.GitChange) { c.After(func() { a.stageChange(p, change) }) } if opened { - c.After(func() { a.openChange(p, change) }) + c.After(func() { a.openChange(p, change, surfaceButton) }) } } diff --git a/desktop/internal/workbench/compact_menu.go b/desktop/internal/workbench/compact_menu.go index f64c29bc45..370a708ad2 100644 --- a/desktop/internal/workbench/compact_menu.go +++ b/desktop/internal/workbench/compact_menu.go @@ -87,7 +87,7 @@ func (a *App) compactMenu(c ui.C, anchor ui.Box) { } if item.Clicked() { run := cmd - c.After(func() { a.runCommand(run) }) + c.After(func() { a.runCommand(run, surfaceMenu) }) a.title.menuOpen = false } } diff --git a/desktop/internal/workbench/debug.go b/desktop/internal/workbench/debug.go index 2bd4aae38c..6828f3d358 100644 --- a/desktop/internal/workbench/debug.go +++ b/desktop/internal/workbench/debug.go @@ -698,7 +698,6 @@ func (a *App) toggleBreakpoint(p *project) { return } caretLine, _ := doc.view.Caret() - a.emit(core.LevelInfo, "app.action.performed", map[string]any{"action": "debug.toggleBreakpoint", "surface": "debug"}) a.toggleBreakpointAt(p, doc.path, int64(caretLine+1)) } @@ -881,7 +880,7 @@ func (a *App) releaseDebugSession(p *project, session *debugSession) { return func(a *App) { a.releaseChildSessions(p, children, destroyed) if cleanupErr != nil { - a.emit(core.LevelWarn, operationFailedEvent, operationFailedFields("debug", cleanupErr)) + a.backgroundFailed("debug_cleanup", cleanupErr) } } }) diff --git a/desktop/internal/workbench/debug_gutter.go b/desktop/internal/workbench/debug_gutter.go index d8f5c27953..d1508493c1 100644 --- a/desktop/internal/workbench/debug_gutter.go +++ b/desktop/internal/workbench/debug_gutter.go @@ -37,7 +37,7 @@ func (a *App) applyDebugGutter(p *project, d *document) { if g.click == nil { path := d.path g.click = func(line int) { - a.performed("debug.gutter.toggleBreakpoint", "editor") + a.performed("debug.gutter.toggleBreakpoint", surfaceButton) a.toggleBreakpointAt(p, path, int64(line+1)) } } diff --git a/desktop/internal/workbench/debug_menus.go b/desktop/internal/workbench/debug_menus.go index 68fa4b7193..19a7603fbb 100644 --- a/desktop/internal/workbench/debug_menus.go +++ b/desktop/internal/workbench/debug_menus.go @@ -33,7 +33,7 @@ type debugVarMenu struct { // copyDebugText puts one value the debugger shows on the clipboard. func (a *App) copyDebugText(action, text string) { - a.performed(action, surfaceMenu) + a.performed(action, surfaceContextMenu) _ = app.SetClipboardText(text) } @@ -58,7 +58,7 @@ func (a *App) debugThreadItems(c ui.C, menu *ui.MenuItems, p *project) { } if menu.Item(label).Disabled(!enabled).Clicked() { c.After(func() { - a.performed("debug.thread."+command, surfaceMenu) + a.performed("debug.thread."+command, surfaceContextMenu) a.executeDebugThread(p, id) }) } @@ -106,7 +106,7 @@ func (a *App) debugFrameMenu(c ui.C, row ui.Box, p *project, index int) { // showFrameDisassembly makes the frame at index current and shows the Disassembly section, // which loads the code around that frame's instruction pointer. func (a *App) showFrameDisassembly(p *project, index int) { - a.performed("debug.frame.showDisassembly", surfaceMenu) + a.performed("debug.frame.showDisassembly", surfaceContextMenu) if index != p.debug.vars.frame { a.selectDebugFrame(p, index) } @@ -127,7 +127,7 @@ func (a *App) debugInstructionMenu(c ui.C, row ui.Box, p *project, instruction c } if menu.Item(label).Clicked() { c.After(func() { - a.performed("debug.instruction.toggleBreakpoint", surfaceMenu) + a.performed("debug.instruction.toggleBreakpoint", surfaceContextMenu) a.toggleInstructionBreakpoint(p, address) }) } @@ -136,7 +136,7 @@ func (a *App) debugInstructionMenu(c ui.C, row ui.Box, p *project, instruction c if d.capabilities != nil && d.capabilities.SupportsReadMemoryRequest && menu.Item(i18n.Shared(lang, "debugger.disassembly.readMemoryAtAddress")).Disabled(d.state != "paused" || d.memory.loading).Clicked() { c.After(func() { - a.performed("debug.instruction.readMemory", surfaceMenu) + a.performed("debug.instruction.readMemory", surfaceContextMenu) a.readDebugMemoryAt(p, address) }) } @@ -181,7 +181,7 @@ func (a *App) debugVariableMenu(c ui.C, p *project) { edits := canEditDebugVariable(d, node) if edits && menu.Item(i18n.Shared(lang, "native.setValue")).Clicked() { c.After(func() { - a.performed("debug.variable.setValue", surfaceMenu) + a.performed("debug.variable.setValue", surfaceContextMenu) v.json, v.selected = false, node }) } @@ -189,7 +189,7 @@ func (a *App) debugVariableMenu(c ui.C, p *project) { menu.Item(i18n.Shared(lang, "native.breakOnFieldAccess")).Clicked() { name, parent := node.name, node.parentRef c.After(func() { - a.performed("debug.variable.breakOnAccess", surfaceMenu) + a.performed("debug.variable.breakOnAccess", surfaceContextMenu) a.requestDataBreakpoint(p, name, parent) }) } @@ -215,7 +215,7 @@ func (a *App) debugVariableMenu(c ui.C, p *project) { menu.Separator() if menu.Item(i18n.Shared(lang, "native.addToWatches")).Disabled(d.state != "paused").Clicked() { c.After(func() { - a.performed("debug.variable.addWatch", surfaceMenu) + a.performed("debug.variable.addWatch", surfaceContextMenu) d.watch.input = watched a.addDebugWatch(p) }) @@ -236,13 +236,13 @@ func (a *App) debugWatchMenu(c ui.C, row ui.Box, p *project, index int) { menu.WidthRange(160, 240) if menu.Item(i18n.Shared(lang, "native.refreshWatches")).Clicked() { c.After(func() { - a.performed("debug.watch.refresh", surfaceMenu) + a.performed("debug.watch.refresh", surfaceContextMenu) a.refreshDebugWatches(p) }) } if menu.Item(i18n.Shared(lang, "native.editWatch")).Clicked() { c.After(func() { - a.performed("debug.watch.edit", surfaceMenu) + a.performed("debug.watch.edit", surfaceContextMenu) w.beginEdit(index) }) } @@ -256,7 +256,7 @@ func (a *App) debugWatchMenu(c ui.C, row ui.Box, p *project, index int) { menu.Separator() if menu.Item(t.RemoveWatch).Clicked() { c.After(func() { - a.performed("debug.watch.remove", surfaceMenu) + a.performed("debug.watch.remove", surfaceContextMenu) a.removeDebugWatch(p, index) }) } @@ -278,26 +278,26 @@ func (a *App) debugBreakpointMenu(c ui.C, row ui.Box, p *project, path string, l } if menu.Item(toggle).Clicked() { c.After(func() { - a.performed(action, surfaceMenu) + a.performed(action, surfaceContextMenu) a.setBreakpointEnabled(p, path, line, disabled) }) } if menu.Item(i18n.Shared(lang, "git.jumpToSource")).Clicked() { c.After(func() { - a.performed("debug.breakpoint.jumpToSource", surfaceMenu) + a.performed("debug.breakpoint.jumpToSource", surfaceContextMenu) a.openFileAtPosition(p, path, int(max(line-1, 0)), 0) }) } menu.Separator() if menu.Item(i18n.Shared(lang, "debugger.removeBreakpoint")).Clicked() { c.After(func() { - a.performed("debug.breakpoint.remove", surfaceMenu) + a.performed("debug.breakpoint.remove", surfaceContextMenu) a.removeBreakpoint(p, path, line) }) } if menu.Item(i18n.Shared(lang, "native.removeAll")).Clicked() { c.After(func() { - a.performed("debug.breakpoint.removeAll", surfaceMenu) + a.performed("debug.breakpoint.removeAll", surfaceContextMenu) a.removeAllBreakpoints(p) }) } diff --git a/desktop/internal/workbench/debug_start.go b/desktop/internal/workbench/debug_start.go index da3c57cdde..5f33238512 100644 --- a/desktop/internal/workbench/debug_start.go +++ b/desktop/internal/workbench/debug_start.go @@ -238,6 +238,7 @@ func (a *App) attachDebugForRun(ctx context.Context, request pluginservice.RunDe if configurationType != request.ConfigurationType { continue } + a.performed("debug.start", surfacePlugin) a.beginDebug(p, debugStart{ adapter: adapter, request: "attach", confirmed: true, target: &core.DebugTargetFacts{Kind: "connection", Host: request.Host, Port: request.Port}, @@ -297,6 +298,7 @@ func (a *App) launchDebugForRun(ctx context.Context, request pluginservice.RunDe if environment == nil { environment = map[string]string{} } + a.performed("debug.start", surfacePlugin) a.beginDebug(p, debugStart{ adapter: adapter, request: "launch", ended: ended, launchTarget: &core.DebugTargetFacts{ @@ -349,6 +351,7 @@ func (a *App) startDebugForBackend(ctx context.Context, request pluginservice.De if adapter.PluginID+"/"+adapter.Declaration.ID != request.AdapterID { continue } + a.performed("debug.start", surfacePlugin) a.beginDebug(p, debugStart{adapter: adapter, request: request.Request, confirmed: true, configuration: request.Configuration}) if p.debug.activeSession() == nil { result <- outcome{err: errors.New("the debug session could not start")} @@ -480,7 +483,6 @@ func (a *App) beginDebug(p *project, start debugStart) { // Instruction addresses are valid for one run of one process: the set is not replayed. p.debug.instructionBreakpoints = nil p.debug.hideFiltered = hideFiltered - a.emit(core.LevelInfo, "app.action.performed", map[string]any{"action": "debug.start", "surface": "debug"}) a.background(p, 0, func(_ context.Context) func(*App) { session.operationMu.Lock() diff --git a/desktop/internal/workbench/debug_view.go b/desktop/internal/workbench/debug_view.go index aa4c5ae3c5..6e21af9558 100644 --- a/desktop/internal/workbench/debug_view.go +++ b/desktop/internal/workbench/debug_view.go @@ -77,7 +77,10 @@ func (a *App) debugToolbar(c ui.C, p *project) { } if session == nil { if _, clicked := a.toolIconButton(c.Part("start"), t.Start, icons.Bug, false, len(d.adapters) == 0 || d.preparing); clicked { - c.After(func() { a.startDebug(p) }) + c.After(func() { + a.performed("debug.start", surfaceButton) + a.startDebug(p) + }) } } else if _, clicked := a.toolIconButton(c.Part("stop"), t.Stop, icons.Square, false, false); clicked { c.After(func() { a.stopDebugByUser(p) }) @@ -251,7 +254,10 @@ func (a *App) debugRemotePrompt(c ui.C, p *project) { *open = false } if ui.Button(c, t.RemoteAttach).Clicked() { - c.After(func() { a.confirmRemoteDebug(p) }) + c.After(func() { + a.performed("debug.remote.attach", surfaceButton) + a.confirmRemoteDebug(p) + }) } }) if closed || !*open { @@ -317,7 +323,10 @@ func (a *App) debugBreakpoints(c ui.C, p *project) { ui.Text(c, i18n.Shared(a.language(), "native.lineBreakpoints")).Color(a.colors.Text).Weight(gfx.WeightMedium).Shrink(0) ui.Spacer(c) if ui.Button(c, t.ToggleBreakpoint).Outline().Clicked() { - c.After(func() { a.toggleBreakpoint(p) }) + c.After(func() { + a.performed("debug.toggleBreakpoint", surfaceButton) + a.toggleBreakpoint(p) + }) } }) rows := debugBreakpointList(d) diff --git a/desktop/internal/workbench/debug_watch.go b/desktop/internal/workbench/debug_watch.go index c80ce0916f..cd2f2c3091 100644 --- a/desktop/internal/workbench/debug_watch.go +++ b/desktop/internal/workbench/debug_watch.go @@ -351,7 +351,7 @@ func (a *App) debugWatchView(c ui.C, p *project) { if row.DoubleClicked() { i := index c.After(func() { - a.performed("debug.watch.edit", "debug") + a.performed("debug.watch.edit", surfaceButton) w.beginEdit(i) }) } diff --git a/desktop/internal/workbench/difftab.go b/desktop/internal/workbench/difftab.go index 757e4061a5..8af988a609 100644 --- a/desktop/internal/workbench/difftab.go +++ b/desktop/internal/workbench/difftab.go @@ -247,16 +247,16 @@ func (t *diffTab) untracked() bool { // openDiff opens the Diff tab of a change of the project's repository and reads it in the // background. -func (a *App) openDiff(p *project, change core.GitChange) *diffTab { - return a.openDiffIn(p, p.git.repositoryRoot(p.root), change) +func (a *App) openDiff(p *project, change core.GitChange, surface actionSurface) *diffTab { + return a.openDiffIn(p, p.git.repositoryRoot(p.root), change, surface) } // openDiffIn opens the Diff tab of a change of the checkout at root. The tab steps through the -// checkout's other changes. -func (a *App) openDiffIn(p *project, root string, change core.GitChange) *diffTab { +// checkout's other changes. surface is where the user asked. +func (a *App) openDiffIn(p *project, root string, change core.GitChange, surface actionSurface) *diffTab { t := a.showDiff(p, root, "", change, a.changeSiblings(p, root), diffOrigin{}) if t != nil { - a.performed("git.diff.open", surfaceMenu) + a.performed("git.diff.open", surface) } return t } diff --git a/desktop/internal/workbench/difftab_test.go b/desktop/internal/workbench/difftab_test.go index 8a01a6d070..fb16f61bce 100644 --- a/desktop/internal/workbench/difftab_test.go +++ b/desktop/internal/workbench/difftab_test.go @@ -17,7 +17,7 @@ import ( // what it reads. func openDiffTab(t *testing.T, h *harness, p *project, path string) *diffTab { t.Helper() - d := h.app.openDiff(p, changeOf(t, p, path)) + d := h.app.openDiff(p, changeOf(t, p, path), surfaceButton) if d == nil { t.Fatalf("no Diff tab opened for %s", path) } @@ -174,7 +174,7 @@ func TestDiffTabIsAnEditorTab(t *testing.T) { if h.app.focus != (focusTarget{diff: d.id}) { t.Fatalf("focus %+v, want the Diff tab", h.app.focus) } - if again := h.app.openDiff(p, changeOf(t, p, "changed.txt")); again != d || len(p.diffs.list) != 1 { + if again := h.app.openDiff(p, changeOf(t, p, "changed.txt"), surfaceButton); again != d || len(p.diffs.list) != 1 { t.Fatalf("opening the change again made another tab: %d tabs", len(p.diffs.list)) } h.await("the diff read again", func() bool { return !d.loading }) diff --git a/desktop/internal/workbench/directory_exclusions.go b/desktop/internal/workbench/directory_exclusions.go index 6d8b14bf25..bd17f6005d 100644 --- a/desktop/internal/workbench/directory_exclusions.go +++ b/desktop/internal/workbench/directory_exclusions.go @@ -142,9 +142,9 @@ func (a *App) excludeFromSearch(p *project, rel string, cancel bool) { return } if cancel { - a.performed("workspace.tree.cancelExclusion", surfaceMenu) + a.performed("workspace.tree.cancelExclusion", surfaceContextMenu) } else { - a.performed("workspace.tree.excludeFromSearch", surfaceMenu) + a.performed("workspace.tree.excludeFromSearch", surfaceContextMenu) } a.changeIndexingRules(p, func(ctx context.Context, rules json.RawMessage) (bool, json.RawMessage, error) { if cancel { @@ -159,7 +159,7 @@ func (a *App) setGitIgnoreIndexing(p *project, on bool) { if !p.indexing.loaded || p.indexing.gitIgnore == on { return } - a.performed("workspace.indexing.gitIgnore", surfaceMenu) + a.performed("workspace.indexing.gitIgnore", surfaceContextMenu) a.changeIndexingRules(p, func(context.Context, json.RawMessage) (bool, json.RawMessage, error) { return true, p.indexing.rules, nil }, on) diff --git a/desktop/internal/workbench/editor_essentials_test.go b/desktop/internal/workbench/editor_essentials_test.go index ee7f68e3ba..bcbb672dfd 100644 --- a/desktop/internal/workbench/editor_essentials_test.go +++ b/desktop/internal/workbench/editor_essentials_test.go @@ -49,7 +49,7 @@ func TestEditorEssentialsFindReplaceNativeFlow(t *testing.T) { if start != 11 || end != 16 { t.Fatalf("next match %d..%d", start, end) } - h.app.openEditorFind(true) + h.app.openEditorFind(true, surfaceButton) d.find.replacement.SetText("omega") h.settleChain() h.clickNamed(h.shared("desktop.editorFind.replaceAll")) @@ -240,7 +240,7 @@ func TestEditorEssentialsSelectionScopeFollowsBulkReplacement(t *testing.T) { h, p, d := essentialsDocument(t, "one one one") d.view.SetSelection(0, 7) d.find.debounce = -1 - h.app.openEditorFind(true) + h.app.openEditorFind(true, surfaceButton) d.find.selection = true d.find.query.SetText("one") d.find.replacement.SetText("a") diff --git a/desktop/internal/workbench/editor_find.go b/desktop/internal/workbench/editor_find.go index aa889611aa..135a19de50 100644 --- a/desktop/internal/workbench/editor_find.go +++ b/desktop/internal/workbench/editor_find.go @@ -45,7 +45,7 @@ type editorFindKernel interface { FindEditorText(context.Context, []byte, core.EditorFindRequest) (core.EditorFindResult, error) } -func (a *App) openEditorFind(replace bool) { +func (a *App) openEditorFind(replace bool, surface actionSurface) { p := a.project if p == nil { return @@ -66,7 +66,7 @@ func (a *App) openEditorFind(replace bool) { } f.open, f.replace, f.focus = true, replace, true f.computed = false - a.performed("editor.find.open", surfaceShortcut) + a.performed("editor.find.open", surface) a.invalidator.Invalidate() } diff --git a/desktop/internal/workbench/editor_menu.go b/desktop/internal/workbench/editor_menu.go index 39c3d15a59..e952b8b440 100644 --- a/desktop/internal/workbench/editor_menu.go +++ b/desktop/internal/workbench/editor_menu.go @@ -19,10 +19,10 @@ func (a *App) editorMenuItems(c ui.C, p *project, d *document) func(*ui.MenuItem a.editorActionMenuItems(c, p, d, menu) readOnly := d.view.ReadOnly() if menu.Item(a.text.Commands.Find).Clicked() { - c.After(func() { a.selectDocument(p, d.id); a.openEditorFind(false) }) + c.After(func() { a.selectDocument(p, d.id); a.openEditorFind(false, surfaceContextMenu) }) } if menu.Item(a.text.Commands.Replace).Disabled(readOnly).Clicked() { - c.After(func() { a.selectDocument(p, d.id); a.openEditorFind(true) }) + c.After(func() { a.selectDocument(p, d.id); a.openEditorFind(true, surfaceContextMenu) }) } menu.Separator() if menu.Item(i18n.Shared(language, "desktop.editorMenu.goToDefinition")).Keys(primary, "b").Clicked() { @@ -45,7 +45,7 @@ func (a *App) editorMenuItems(c ui.C, p *project, d *document) func(*ui.MenuItem } if browserPreviewable(d) { if menu.Item(i18n.Shared(language, "desktop.editorMenu.openInBrowser")).Clicked() { - c.After(func() { a.openInBrowser(p, d) }) + c.After(func() { a.openInBrowser(p, d, surfaceContextMenu) }) } } menu.Separator() @@ -66,7 +66,7 @@ func (a *App) editorMenuItems(c ui.C, p *project, d *document) func(*ui.MenuItem } menu.Separator() if p.git.isRepository() && menu.Item(i18n.Shared(language, "desktop.editorMenu.lineHistory")).Clicked() { - c.After(func() { a.startLineHistory(p, d) }) + c.After(func() { a.startLineHistory(p, d, surfaceContextMenu) }) } if menu.Item(i18n.Shared(language, "desktop.editorMenu.goToLine")).Clicked() { c.After(func() { a.openNavigation(p) }) diff --git a/desktop/internal/workbench/editor_recovery.go b/desktop/internal/workbench/editor_recovery.go index 78a6523013..2b03a4a371 100644 --- a/desktop/internal/workbench/editor_recovery.go +++ b/desktop/internal/workbench/editor_recovery.go @@ -209,7 +209,7 @@ func (a *App) applyRecoveredDocument(p *project, d *document, restored recovered if restored.conflict { message = i18n.Shared(a.language(), "desktop.drafts.conflict") } - a.performed("editor.recovery.restored", surfaceMenu) + a.emit(core.LevelInfo, "editor.recovery.applied", map[string]any{"conflict": restored.conflict}) a.notifyInfo(message) } func (a *App) restoreCheckpoints(p *project) { diff --git a/desktop/internal/workbench/filetree_batch.go b/desktop/internal/workbench/filetree_batch.go index 945a8640d9..52accb8793 100644 --- a/desktop/internal/workbench/filetree_batch.go +++ b/desktop/internal/workbench/filetree_batch.go @@ -193,7 +193,7 @@ func (a *App) finishRemoval(p *project, parents []string, performed string, fail if failed > 0 && reason != nil { a.notifyError(failure(a.language(), treeErrorReason(reason))) } - a.performed(performed, surfaceMenu) + a.performed(performed, surfaceButton) for _, dir := range parents { a.listTree(p, dir) } diff --git a/desktop/internal/workbench/filetree_dnd.go b/desktop/internal/workbench/filetree_dnd.go index c8d925b134..1416b2a61d 100644 --- a/desktop/internal/workbench/filetree_dnd.go +++ b/desktop/internal/workbench/filetree_dnd.go @@ -67,7 +67,7 @@ func (a *App) treeDragDrop(source, target gfx.ID) { if !ok || !ok2 || !dst.dir { return } - a.performed("workspace.file.dragMove", surfaceMenu) + a.performed("workspace.file.dragMove", surfaceDragDrop) a.moveTreeItem(p, src.path, dst.path) } @@ -101,12 +101,12 @@ func (a *App) moveTreeItem(p *project, rel, dir string) { // treeCut and treeCopy put the item of n on the tree clipboard. func (a *App) treeCut(p *project, n *treeNode) { p.tree.clip = treeClipboard{paths: []string{n.path}, cut: true} - a.performed("workspace.file.cut", surfaceMenu) + a.performed("workspace.file.cut", surfaceContextMenu) } func (a *App) treeCopy(p *project, n *treeNode) { p.tree.clip = treeClipboard{paths: []string{n.path}} - a.performed("workspace.file.copy", surfaceMenu) + a.performed("workspace.file.copy", surfaceContextMenu) } // treeClipboardHas reports that there is something to paste. @@ -155,7 +155,7 @@ func (a *App) treePaste(p *project, n *treeNode) { if failed != nil { a.notifyError(i18n.SharedFormat(language, "desktop.files.pasteFailed", map[string]string{"reason": treeErrorReason(failed)})) } - a.performed("workspace.file.paste", surfaceMenu) + a.performed("workspace.file.paste", surfaceContextMenu) a.listTree(p, dir) for _, rel := range clip.paths { a.listTree(p, path.Dir(rel)) diff --git a/desktop/internal/workbench/filetree_duplicate.go b/desktop/internal/workbench/filetree_duplicate.go index 59647e4e2c..fe1faf7c5b 100644 --- a/desktop/internal/workbench/filetree_duplicate.go +++ b/desktop/internal/workbench/filetree_duplicate.go @@ -48,7 +48,7 @@ func (a *App) duplicateTreeItem(p *project, n *treeNode) { a.notifyError(i18n.SharedFormat(language, "desktop.files.duplicateFailed", map[string]string{"reason": treeErrorReason(err)})) return } - a.performed("workspace.file.duplicate", surfaceMenu) + a.performed("workspace.file.duplicate", surfaceContextMenu) rel, _ := filepath.Rel(p.root, dir) a.listTree(p, path.Clean(filepath.ToSlash(rel))) a.loadGit(p) diff --git a/desktop/internal/workbench/filetree_git_menu.go b/desktop/internal/workbench/filetree_git_menu.go index b637b187e2..45150fd211 100644 --- a/desktop/internal/workbench/filetree_git_menu.go +++ b/desktop/internal/workbench/filetree_git_menu.go @@ -68,7 +68,7 @@ func (a *App) treeCompareMenu(c ui.C, p *project, sub *ui.MenuItems, n *treeNode // showFileHistory shows the Git tool window's Log tab narrowed to the commits that changed the file // at rel, which is project-relative. func (a *App) showFileHistory(p *project, rel string) { - a.performed("git.showFileHistory", surfaceMenu) + a.performed("git.showFileHistory", surfaceContextMenu) a.layout.gitTab = gitTabLog if !a.chrome.isOpen(catalogIndex[itemGit]) { a.reduceChrome(core.SetChromeOpen(itemGit, true)) diff --git a/desktop/internal/workbench/filetree_menu.go b/desktop/internal/workbench/filetree_menu.go index a8956390a5..d01ef74235 100644 --- a/desktop/internal/workbench/filetree_menu.go +++ b/desktop/internal/workbench/filetree_menu.go @@ -74,7 +74,7 @@ func (a *App) projectTreeMenu(c ui.C, p *project, n *treeNode, target ui.Box) { if !n.dir { if menu.Item(i18n.Shared(language, "desktop.files.open")).Clicked() { c.After(func() { - a.performed("workspace.tree.open", surfaceMenu) + a.performed("workspace.tree.open", surfaceContextMenu) a.activateTreeNode(p, n) }) } @@ -91,10 +91,7 @@ func (a *App) projectTreeMenu(c ui.C, p *project, n *treeNode, target ui.Box) { } opened = true if menu.Item(i18n.Shared(language, "desktop.files.showDiff")).Clicked() { - c.After(func() { - a.performed("git.diff.open", surfaceMenu) - a.openDiff(p, change) - }) + c.After(func() { a.openDiff(p, change, surfaceContextMenu) }) } if change.CanToggleStaging { stage := !change.Staged || change.Worktree @@ -104,13 +101,13 @@ func (a *App) projectTreeMenu(c ui.C, p *project, n *treeNode, target ui.Box) { } if menu.Item(item).Clicked() { c.After(func() { - a.performed("git.contextMenu.stage", surfaceMenu) + a.performed("git.contextMenu.stage", surfaceContextMenu) a.stageChange(p, change) }) } if stage && menu.Item(i18n.Shared(language, "desktop.files.stageAndCommit")).Clicked() { c.After(func() { - a.performed("git.contextMenu.stageAndCommit", surfaceMenu) + a.performed("git.contextMenu.stageAndCommit", surfaceContextMenu) a.stageChangeAndShowCommit(p, change) }) } @@ -122,7 +119,7 @@ func (a *App) projectTreeMenu(c ui.C, p *project, n *treeNode, target ui.Box) { if _, ok := a.kernel.(localHistoryKernel); ok && menu.Item(i18n.Shared(language, "desktop.history.show")).Clicked() { file := filepath.Join(p.root, filepath.FromSlash(n.path)) c.After(func() { - a.performed("localHistory.show", surfaceMenu) + a.performed("localHistory.show", surfaceContextMenu) a.openLocalHistory(p, file) }) } @@ -134,13 +131,13 @@ func (a *App) projectTreeMenu(c ui.C, p *project, n *treeNode, target ui.Box) { // Find in Files searches the whole project from any row, as the IDE's entry does. if menu.Item(i18n.Shared(language, "native.findInFiles")).Clicked() { c.After(func() { - a.performed("workspace.search.open", surfaceMenu) + a.performed("workspace.search.open", surfaceContextMenu) a.openFindInFiles(p, false) }) } if menu.Item(i18n.Shared(language, "desktop.command.replaceInFiles")).Clicked() { c.After(func() { - a.performed("workspace.replace.open", surfaceMenu) + a.performed("workspace.replace.open", surfaceContextMenu) a.openFindInFiles(p, true) }) } @@ -161,7 +158,7 @@ func (a *App) projectTreeMenu(c ui.C, p *project, n *treeNode, target ui.Box) { if n.dir { if p.git.isRepository() && menu.Item(i18n.Shared(language, "desktop.files.showRepositoryChanges")).Clicked() { c.After(func() { - a.performed("git.contextMenu.showRepositoryChanges", surfaceMenu) + a.performed("git.contextMenu.showRepositoryChanges", surfaceContextMenu) a.showRepositoryChangesOf(p, filepath.Join(p.root, filepath.FromSlash(n.path))) }) } @@ -201,14 +198,14 @@ func (a *App) projectTreeMenu(c ui.C, p *project, n *treeNode, target ui.Box) { a.copyPathMenu(c, menu, full, !root, "workspace.tree") if menu.Item(revealLabel(language)).Clicked() { c.After(func() { - a.performed("workspace.tree.reveal", surfaceMenu) + a.performed("workspace.tree.reveal", surfaceContextMenu) a.revealPath(full) }) } menu.Separator() if menu.Item(i18n.Shared(language, "desktop.files.refresh")).Clicked() { c.After(func() { - a.performed("workspace.tree.refresh", surfaceMenu) + a.performed("workspace.tree.refresh", surfaceContextMenu) a.refreshProjectTree(p) }) } @@ -240,7 +237,7 @@ func (a *App) copyPathMenu(c ui.C, menu *ui.MenuItems, full string, relative boo if sub.Item(i18n.Shared(language, "native.copyPath")).Clicked() { c.After(func() { if surface != "" { - a.performed(surface+".copyPath", surfaceMenu) + a.performed(surface+".copyPath", surfaceContextMenu) } a.copyTreePath(full, false) }) @@ -248,7 +245,7 @@ func (a *App) copyPathMenu(c ui.C, menu *ui.MenuItems, full string, relative boo if relative && sub.Item(i18n.Shared(language, "native.copyRelativePath")).Clicked() { c.After(func() { if surface != "" { - a.performed(surface+".copyRelativePath", surfaceMenu) + a.performed(surface+".copyRelativePath", surfaceContextMenu) } a.copyTreePath(full, true) }) @@ -377,7 +374,7 @@ func (a *App) createTreeItem(p *project) { created := pr.kind == treePromptNewFile parent := pr.node.path pr.open, pr.kind, pr.node, pr.err, pr.name = false, treePromptNone, nil, "", "" - a.performed("workspace.file.create", surfaceMenu) + a.performed("workspace.file.create", surfaceButton) a.listTree(p, parent) if created { a.openFile(p, full) @@ -421,7 +418,7 @@ func (a *App) renameTreeItem(p *project) { return } a.renamedLocalHistory(p, oldFull, newFull, before) - a.performed("workspace.file.rename", surfaceMenu) + a.performed("workspace.file.rename", surfaceButton) a.moveOpenDocuments(p, oldFull, newFull) a.listTree(p, path.Dir(oldRel)) a.loadGit(p) diff --git a/desktop/internal/workbench/filetree_open.go b/desktop/internal/workbench/filetree_open.go index cd8f5be88d..cfa6a8cf9d 100644 --- a/desktop/internal/workbench/filetree_open.go +++ b/desktop/internal/workbench/filetree_open.go @@ -27,7 +27,7 @@ func (a *App) openSelectedTreeFile(p *project) { // nothing; a failure is shown to the user. func (a *App) openTreeFileWith(file string) { lang := a.language() - a.performed("workspace.tree.openWith", surfaceMenu) + a.performed("workspace.tree.openWith", surfaceContextMenu) paths, err := app.OpenFiles(app.OpenFileOptions{Title: i18n.Shared(lang, "desktop.files.openWithTitle")}) if errors.Is(err, app.ErrCanceled) || (err == nil && len(paths) == 0) { return diff --git a/desktop/internal/workbench/git_exclude.go b/desktop/internal/workbench/git_exclude.go index 9399ae5f75..fcbabb6156 100644 --- a/desktop/internal/workbench/git_exclude.go +++ b/desktop/internal/workbench/git_exclude.go @@ -43,7 +43,7 @@ func (a *App) excludeLocally(p *project, change core.GitChange) { if !ok { return } - a.performed("git.excludeLocally", surfaceMenu) + a.performed("git.excludeLocally", surfaceContextMenu) root := p.git.repositoryRoot(p.root) pattern := excludeLocallyPattern(change.Path) a.background(p, gitTimeout, func(ctx context.Context) func(*App) { diff --git a/desktop/internal/workbench/git_gutter.go b/desktop/internal/workbench/git_gutter.go index 0f3218db48..b58bd9bb80 100644 --- a/desktop/internal/workbench/git_gutter.go +++ b/desktop/internal/workbench/git_gutter.go @@ -265,14 +265,15 @@ func (a *App) stageGitGutter(p *project, d *document, h gitHunk) { // revertGitGutter opens the Diff of the file, where its blocks are rolled back under the // existing confirmation. The marker does not roll back on its own: a rollback discards work. -func (a *App) revertGitGutter(p *project, d *document) { +// surface is where the user asked. +func (a *App) revertGitGutter(p *project, d *document, surface actionSurface) { root := p.git.repositoryRoot(p.root) rel, ok := gitRelativePath(root, d.path) if !ok { return } d.gutter.peekOpen, d.gutter.peek = false, nil - a.openDiff(p, core.GitChange{Path: rel, Status: "M", Worktree: true}) + a.openDiff(p, core.GitChange{Path: rel, Status: "M", Worktree: true}, surface) } // gitGutterPeek declares the popover of a clicked marker: the text it replaced, and the stage and @@ -308,7 +309,7 @@ func (a *App) gitGutterPeek(c ui.C, p *project, d *document, anchor ui.Box) { c.After(func() { a.stageGitGutter(p, d, h) }) } if ui.Button(c.Key("revert"), i18n.Shared(a.language(), "desktop.git.gutter.revert")).Outline().Clicked() { - c.After(func() { a.revertGitGutter(p, d) }) + c.After(func() { a.revertGitGutter(p, d, surfaceButton) }) } }) }) diff --git a/desktop/internal/workbench/git_history.go b/desktop/internal/workbench/git_history.go index a6783864e6..44bdf4a186 100644 --- a/desktop/internal/workbench/git_history.go +++ b/desktop/internal/workbench/git_history.go @@ -180,9 +180,9 @@ func (a *App) historyHints(p *project, revisions []string) (core.HistoryActionCa // line. label names the menu item, for the notice of a failure. func (a *App) copyRevisions(revisions []string, short bool, label string) { if short { - a.performed("git.log.copyShortHash", surfaceMenu) + a.performed("git.log.copyShortHash", surfaceContextMenu) } else { - a.performed("git.log.copyCommitHash", surfaceMenu) + a.performed("git.log.copyCommitHash", surfaceContextMenu) } hashes := make([]string, len(revisions)) for i, revision := range revisions { @@ -206,7 +206,7 @@ func (a *App) beginTagAt(p *project, revision string) { // beginHistoryRewrite opens the dialog of the rewrite operation of revisions and reads its preview. func (a *App) beginHistoryRewrite(p *project, operation string, revisions []string) { a.reviewHistoryRewrite(p, operation, revisions, p.logRepositoryRoot()) - a.performed("git.history."+operation, surfaceMenu) + a.performed("git.history."+operation, surfaceContextMenu) } // reviewHistoryRewrite opens the rewrite dialog of operation on revisions in root and reads its diff --git a/desktop/internal/workbench/git_rebase.go b/desktop/internal/workbench/git_rebase.go index 7f071f5edc..a685d11729 100644 --- a/desktop/internal/workbench/git_rebase.go +++ b/desktop/internal/workbench/git_rebase.go @@ -97,7 +97,7 @@ func (a *App) beginRebaseFromHere(p *project, base, subject string) { root := p.logRepositoryRoot() *r = rebaseState{open: true, gen: gen, busy: true, base: base, subject: subject, session: r.session, root: root} kernel := a.kernel.(rebaseKernel) - a.performed("git.rebase.fromHere", surfaceMenu) + a.performed("git.rebase.fromHere", surfaceContextMenu) a.background(p, gitTimeout, func(ctx context.Context) func(*App) { preview, err := kernel.GitRebasePreview(ctx, root, base) return func(a *App) { diff --git a/desktop/internal/workbench/gitconsole.go b/desktop/internal/workbench/gitconsole.go index f7835dc1ff..dff0330de9 100644 --- a/desktop/internal/workbench/gitconsole.go +++ b/desktop/internal/workbench/gitconsole.go @@ -882,7 +882,7 @@ func (a *App) copyConsoleAll() { // copyConsoleRecord puts value, which a record's context menu action named action made, on // the clipboard. func (a *App) copyConsoleRecord(action, value string) { - a.performed("git.console."+action, surfaceMenu) + a.performed("git.console."+action, surfaceContextMenu) a.copyConsoleText(value) } diff --git a/desktop/internal/workbench/github_create.go b/desktop/internal/workbench/github_create.go index 1c9d2a0807..42d3e8270a 100644 --- a/desktop/internal/workbench/github_create.go +++ b/desktop/internal/workbench/github_create.go @@ -62,7 +62,7 @@ func (a *App) openCreatePullRequest(p *project) { cr.busy = false return } - a.performed("github.createPullRequest.open", surfaceMenu) + a.performed("github.createPullRequest.open", surfaceButton) root := p.git.repositoryRoot(p.root) a.background(p, githubReadTimeout, func(ctx context.Context) func(*App) { url, err := kernel.GitRemoteURL(ctx, root, "origin") diff --git a/desktop/internal/workbench/gitlinehistory.go b/desktop/internal/workbench/gitlinehistory.go index ff79442802..f28b1a0c84 100644 --- a/desktop/internal/workbench/gitlinehistory.go +++ b/desktop/internal/workbench/gitlinehistory.go @@ -54,7 +54,7 @@ func lineHistoryRange(d *document) (start, end int) { // startLineHistory traces the lines the editor asks about in d against the repository of the // project and opens the dialog with the answer. -func (a *App) startLineHistory(p *project, d *document) { +func (a *App) startLineHistory(p *project, d *document, surface actionSurface) { kernel, ok := a.kernel.(lineHistoryKernel) if !ok { return @@ -66,7 +66,7 @@ func (a *App) startLineHistory(p *project, d *document) { a.notify(i18n.Shared(a.language(), "desktop.lineHistory.outsideRepository")) return } - a.performed("git.lineHistory", surfaceMenu) + a.performed("git.lineHistory", surface) start, end := lineHistoryRange(d) content, _ := d.view.Text() h.gen++ diff --git a/desktop/internal/workbench/gitlog_popover_view.go b/desktop/internal/workbench/gitlog_popover_view.go index 6a15cdcfec..bde2dc973e 100644 --- a/desktop/internal/workbench/gitlog_popover_view.go +++ b/desktop/internal/workbench/gitlog_popover_view.go @@ -70,13 +70,13 @@ func (a *App) drawLogMenu(c ui.C, p *project, button ui.Box) { open := true ui.Menu(c, button, &open, func(menu *ui.MenuItems) { if menu.Item(g.FetchAll).Disabled(l.sync.busy).Clicked() { - c.After(func() { a.fetchAll(p) }) + c.After(func() { a.fetchAll(p, surfaceMenu) }) } if menu.Item(g.FetchOptions).Disabled(l.sync.busy).Clicked() { c.After(func() { a.openFetchOptions(p) }) } if menu.Item(g.UpdateBranch).Disabled(l.current == "" || l.sync.busy).Clicked() { - c.After(func() { a.updateCurrentBranch(p) }) + c.After(func() { a.updateCurrentBranch(p, surfaceMenu) }) } if menu.Item(a.text.Sync.Pull.MenuItem).Disabled(l.sync.busy).Clicked() { c.After(func() { a.openPullDialog(p) }) @@ -89,7 +89,10 @@ func (a *App) drawLogMenu(c ui.C, p *project, button ui.Box) { } menu.Separator() if menu.Item(g.ShowChanges).Clicked() { - c.After(a.showChanges) + c.After(func() { + a.performed("git.showChanges", surfaceMenu) + a.showChanges() + }) } }) if !open { diff --git a/desktop/internal/workbench/gitlog_ref_menu.go b/desktop/internal/workbench/gitlog_ref_menu.go index 7a0246959f..ee6ee1d9de 100644 --- a/desktop/internal/workbench/gitlog_ref_menu.go +++ b/desktop/internal/workbench/gitlog_ref_menu.go @@ -124,7 +124,7 @@ func (a *App) drawLogRefMenuItems(c ui.C, menu *ui.MenuItems, p *project, r core if menu.Item(t.Checkout).Disabled(busy).Clicked() { c.After(func() { a.adoptLogBranches(p) - a.checkoutBranch(p, r) + a.checkoutBranch(p, r, surfaceContextMenu) }) } if r.Kind != "tag" { @@ -142,10 +142,10 @@ func (a *App) drawLogRefMenuItems(c ui.C, menu *ui.MenuItems, p *project, r core menu.Separator() // Any other local branch fast-forwards from its upstream in place, as in IDEA. if menu.Item(i18n.Shared(lang, "git.log.updateBranch")).Disabled(busy || !current && r.UpstreamShortName == "").Clicked() { - c.After(func() { a.updateBranchAt(p, root, r) }) + c.After(func() { a.updateBranchAt(p, root, r, surfaceContextMenu) }) } if menu.Item(i18n.Shared(lang, "git.contextMenu.push")).Disabled(busy).Clicked() { - c.After(func() { a.openPushOf(p, root, r) }) + c.After(func() { a.openPushOf(p, root, r, surfaceContextMenu) }) } if menu.Item(t.Rename).Disabled(busy).Clicked() { c.After(func() { @@ -228,7 +228,7 @@ func (a *App) setLogUpstream(p *project, branch core.GitReference, upstream *cor return } a.adoptLogBranches(p) - a.performed("git.log.trackingBranch", surfaceMenu) + a.performed("git.log.trackingBranch", surfaceContextMenu) lang := a.language() a.runBranchWrite(p, "git_set_upstream", func(reason string) string { diff --git a/desktop/internal/workbench/gitlog_view.go b/desktop/internal/workbench/gitlog_view.go index 693407db42..d099dd65a1 100644 --- a/desktop/internal/workbench/gitlog_view.go +++ b/desktop/internal/workbench/gitlog_view.go @@ -114,7 +114,7 @@ func (a *App) drawLogStripe(c ui.C, p *project) { }) } if a.gitIconButton(c, g.UpdateBranch, icons.ArrowDownLeft, false, !updatable || l.sync.busy) { - c.After(func() { a.updateBranch(p, target) }) + c.After(func() { a.updateBranch(p, target, surfaceButton) }) } if a.gitIconButton(c, g.DeleteBranch, icons.Trash2, false, !deletable) { c.After(func() { @@ -129,7 +129,7 @@ func (a *App) drawLogStripe(c ui.C, p *project) { a.logView.focus = logRefSearchID } if a.gitIconButton(c, g.Fetch, icons.CloudDownload, false, l.sync.busy) { - c.After(func() { a.fetchAll(p) }) + c.After(func() { a.fetchAll(p, surfaceButton) }) } if a.gitIconButton(c, g.LocateBranch, icons.Locate, false, !hasSelected && l.current == "") { short := l.current diff --git a/desktop/internal/workbench/gitreview.go b/desktop/internal/workbench/gitreview.go index 413a99ef76..1a74f62418 100644 --- a/desktop/internal/workbench/gitreview.go +++ b/desktop/internal/workbench/gitreview.go @@ -111,7 +111,7 @@ func (a *App) openBlame(p *project, relative string) { *b = blameState{open: true, loading: true, gen: b.gen + 1, path: relative, list: b.list} gen, root := b.gen, p.git.repositoryRoot(p.root) disk := filepath.Join(root, filepath.FromSlash(relative)) - a.performed("git.blame.open", surfaceMenu) + a.performed("git.blame.open", surfaceContextMenu) a.background(p, reviewTimeout, func(ctx context.Context) func(*App) { lines, err := kernel.GitBlame(ctx, root, relative) var text []string diff --git a/desktop/internal/workbench/gitreview_actions.go b/desktop/internal/workbench/gitreview_actions.go index 17da7a70e8..5058ac8c2b 100644 --- a/desktop/internal/workbench/gitreview_actions.go +++ b/desktop/internal/workbench/gitreview_actions.go @@ -10,13 +10,13 @@ import ( ) // openChange opens what a double click on a change of the Commit window shows: the Diff of a -// file, or the listing of a summarized untracked directory. -func (a *App) openChange(p *project, change core.GitChange) { +// file, or the listing of a summarized untracked directory. surface is where the user asked. +func (a *App) openChange(p *project, change core.GitChange, surface actionSurface) { if strings.HasSuffix(change.Path, "/") { a.openUntracked(p, change.Path) return } - a.openDiff(p, change) + a.openDiff(p, change, surface) } // changeMenuItems are the Git actions of one change of the Commit window. They apply to the @@ -38,7 +38,7 @@ func (a *App) changeMenuItems(c ui.C, p *project, change core.GitChange) func(*u deleted := strings.ContainsRune(change.Status, 'D') if !folder && !deleted && menu.Item(i18n.Shared(lang, "desktop.files.open")).Clicked() { c.After(func() { - a.performed("git.change.open", surfaceMenu) + a.performed("git.change.open", surfaceContextMenu) a.openFile(p, full) }) } @@ -47,7 +47,7 @@ func (a *App) changeMenuItems(c ui.C, p *project, change core.GitChange) func(*u c.After(func() { a.openUntracked(p, change.Path) }) } } else if menu.Item(i18n.Shared(lang, "git.showDiff")).Clicked() { - c.After(func() { a.openDiff(p, change) }) + c.After(func() { a.openDiff(p, change, surfaceContextMenu) }) } tracked := !change.Untracked && change.Status != "??" && !strings.HasSuffix(change.Status, "A") && !strings.HasPrefix(change.Status, "A") if !folder && tracked && menu.Item(i18n.Shared(lang, "git.blame.annotate")).Clicked() { @@ -83,7 +83,7 @@ func (a *App) changeMenuItems(c ui.C, p *project, change core.GitChange) func(*u menu.Separator() if !deleted && menu.Item(revealLabel(lang)).Clicked() { c.After(func() { - a.performed("git.change.reveal", surfaceMenu) + a.performed("git.change.reveal", surfaceContextMenu) a.revealPath(full) }) } diff --git a/desktop/internal/workbench/gitreview_test.go b/desktop/internal/workbench/gitreview_test.go index f0c77aa721..68660e1342 100644 --- a/desktop/internal/workbench/gitreview_test.go +++ b/desktop/internal/workbench/gitreview_test.go @@ -81,7 +81,7 @@ func TestPushDialogReviewsAndPushes(t *testing.T) { h := newHarness(t, &gitKernel{Client: core.NewClient()}) p := h.openCommit(dir) - h.app.openPush(p) + h.app.openPush(p, surfaceButton) h.settle() s := &p.review.push if s.err != "" || !s.hasPrev || len(s.preview.Commits) != 1 || !s.canPush() { @@ -106,7 +106,7 @@ func TestPushDialogWithoutRemoteReportsIt(t *testing.T) { dir := newTestRepository(t) h := newHarness(t, &gitKernel{Client: core.NewClient()}) p := h.openCommit(dir) - h.app.openPush(p) + h.app.openPush(p, surfaceButton) h.settle() s := &p.review.push if s.err == "" || s.canPush() { @@ -150,7 +150,7 @@ func TestUntrackedDirectoryListingStagesAFile(t *testing.T) { if summary.UntrackedFileCount < 100 { t.Fatalf("summary = %+v, want a summarized directory", summary) } - h.app.openChange(p, summary) + h.app.openChange(p, summary, surfaceButton) h.settle() u := &p.review.untracked if u.err != "" || len(u.changes) == 0 { diff --git a/desktop/internal/workbench/gitreview_tools.go b/desktop/internal/workbench/gitreview_tools.go index 799d6b33aa..82679c40b4 100644 --- a/desktop/internal/workbench/gitreview_tools.go +++ b/desktop/internal/workbench/gitreview_tools.go @@ -38,17 +38,20 @@ type pushState struct { } // openPush opens the Push dialog on the branch checked out in the repository the log walks. -func (a *App) openPush(p *project) { a.openPushOf(p, p.logRepositoryRoot(), core.GitReference{}) } +func (a *App) openPush(p *project, surface actionSurface) { + a.openPushOf(p, p.logRepositoryRoot(), core.GitReference{}, surface) +} // openPushOf opens the Push dialog on the local branch of the repository at root, the -// checked-out one when branch is empty, and reads Core's preview. -func (a *App) openPushOf(p *project, root string, branch core.GitReference) { +// checked-out one when branch is empty, and reads Core's preview. surface is where the user +// asked. +func (a *App) openPushOf(p *project, root string, branch core.GitReference, surface actionSurface) { if _, ok := a.reviewKernel(); !ok || !p.git.isRepository() { return } s := &p.review.push *s = pushState{open: true, gen: s.gen + 1, root: root, branch: branch} - a.performed("git.push.open", surfaceMenu) + a.performed("git.push.open", surface) a.loadPush(p) } diff --git a/desktop/internal/workbench/gitreview_tools_view.go b/desktop/internal/workbench/gitreview_tools_view.go index 236b4accfa..0cb19434a2 100644 --- a/desktop/internal/workbench/gitreview_tools_view.go +++ b/desktop/internal/workbench/gitreview_tools_view.go @@ -28,7 +28,7 @@ func (a *App) drawGitReviewMenu(c ui.C, p *project) { ui.Menu(c, button, &r.open, func(menu *ui.MenuItems) { menu.WidthRange(240, 320) if menu.Item(i18n.Shared(a.language(), "git.contextMenu.push")).Clicked() { - c.After(func() { a.openPush(p) }) + c.After(func() { a.openPush(p, surfaceMenu) }) } if menu.Item(i18n.Shared(a.language(), "git.saved.stashes")).Clicked() { c.After(a.showStashes) diff --git a/desktop/internal/workbench/gitsync.go b/desktop/internal/workbench/gitsync.go index c1a186098d..db4e8e240b 100644 --- a/desktop/internal/workbench/gitsync.go +++ b/desktop/internal/workbench/gitsync.go @@ -206,11 +206,14 @@ func (a *App) cancelSync(p *project) { } // fetchAll fetches every remote of the repository the log walks with Core's default options. -func (a *App) fetchAll(p *project) { a.fetchAllAt(p, p.logRepositoryRoot()) } +func (a *App) fetchAll(p *project, surface actionSurface) { + a.fetchAllAt(p, p.logRepositoryRoot(), surface) +} // fetchAllAt fetches every remote of the repository at root with Core's default options. -func (a *App) fetchAllAt(p *project, root string) { - a.performed("git.fetch", surfaceMenu) +// surface is where the user asked. +func (a *App) fetchAllAt(p *project, root string, surface actionSurface) { + a.performed("git.fetch", surface) a.runSyncAt(p, root, "git_fetch", a.text.Sync.Fetching(), a.text.Sync.FetchFailed, func(ctx context.Context, kernel Kernel, root string) (func(*App), error) { return func(a *App) { a.notifySuccess(a.text.Sync.Fetched) }, kernel.GitFetch(ctx, root, nil) @@ -291,18 +294,18 @@ func (a *App) submitFetchOptions(p *project) { // updateCurrentBranch fetches, then brings the branch checked out in the repository the log // walks up to its upstream, see updateCurrentBranchAt. -func (a *App) updateCurrentBranch(p *project) { - a.updateCurrentBranchAt(p, p.logRepositoryRoot(), p.log.current) +func (a *App) updateCurrentBranch(p *project, surface actionSurface) { + a.updateCurrentBranchAt(p, p.logRepositoryRoot(), p.log.current, surface) } // updateCurrentBranchAt fetches, then brings branch, the one checked out in the repository at // root, up to its upstream. A branch that has diverged asks how to combine, unless Git's -// configuration already says. -func (a *App) updateCurrentBranchAt(p *project, root, branch string) { +// configuration already says. surface is where the user asked. +func (a *App) updateCurrentBranchAt(p *project, root, branch string, surface actionSurface) { if branch == "" { return } - a.performed("git.updateBranch", surfaceMenu) + a.performed("git.updateBranch", surface) t := a.text.Sync a.runSyncAt(p, root, "git_update_branch", t.Updating(branch), t.UpdateFailed, func(ctx context.Context, kernel Kernel, root string) (func(*App), error) { @@ -339,20 +342,20 @@ type branchUpdateKernel interface { // updateBranch brings the local branch r of the repository the log walks up to its upstream, // see updateBranchAt; any other reference updates the checked out branch. -func (a *App) updateBranch(p *project, r core.GitReference) { +func (a *App) updateBranch(p *project, r core.GitReference, surface actionSurface) { if r.Kind != "local" { - a.updateCurrentBranch(p) + a.updateCurrentBranch(p, surface) return } - a.updateBranchAt(p, p.logRepositoryRoot(), r) + a.updateBranchAt(p, p.logRepositoryRoot(), r, surface) } // updateBranchAt brings the local branch r of the repository at root up to its upstream: the // checked out one the way updateCurrentBranchAt does, any other by fetching and // fast-forwarding it without touching HEAD. -func (a *App) updateBranchAt(p *project, root string, r core.GitReference) { +func (a *App) updateBranchAt(p *project, root string, r core.GitReference, surface actionSurface) { if r.IsCurrent { - a.updateCurrentBranchAt(p, root, r.ShortName) + a.updateCurrentBranchAt(p, root, r.ShortName, surface) return } updater, ok := a.kernel.(branchUpdateKernel) @@ -364,7 +367,7 @@ func (a *App) updateBranchAt(p *project, root string, r core.GitReference) { a.notifyInfo(a.text.Sync.NoUpstream(branch)) return } - a.performed("git.updateBranch", surfaceButton) + a.performed("git.updateBranch", surface) t := a.text.Sync a.runSyncAt(p, root, "git_update_branch", t.Updating(branch), t.UpdateFailed, func(ctx context.Context, kernel Kernel, root string) (func(*App), error) { @@ -397,7 +400,6 @@ func (a *App) resolveDiverged(p *project, strategy core.GitPullStrategy) { // showChanges opens the Commit tool window, which lists the working tree changes. func (a *App) showChanges() { - a.performed("git.showChanges", surfaceMenu) if !a.chrome.isOpen(catalogIndex[itemCommit]) { a.reduceChrome(core.SetChromeOpen(itemCommit, true)) } diff --git a/desktop/internal/workbench/gitsync_test.go b/desktop/internal/workbench/gitsync_test.go index bfaa8b005a..aed73d5548 100644 --- a/desktop/internal/workbench/gitsync_test.go +++ b/desktop/internal/workbench/gitsync_test.go @@ -51,7 +51,7 @@ func publishCommit(t *testing.T, clone, name string) { func TestLogFetchAllRefreshesTheReferences(t *testing.T) { h, p, dir, other := syncFixture(t) publishCommit(t, other, "fetched.txt") - h.app.fetchAll(p) + h.app.fetchAll(p, surfaceButton) if !p.log.sync.busy { t.Fatal("no operation is shown while the fetch runs") } @@ -97,7 +97,7 @@ func TestLogFetchOptionsFetchOneRemoteAndReportAFailure(t *testing.T) { func TestLogUpdateBranchFastForwardsAndAsksWhenDiverged(t *testing.T) { h, p, dir, other := syncFixture(t) - h.app.updateCurrentBranch(p) + h.app.updateCurrentBranch(p, surfaceButton) h.settle() h.settle() if want := h.app.text.Sync.UpToDate("main"); h.app.notice != want { @@ -105,7 +105,7 @@ func TestLogUpdateBranchFastForwardsAndAsksWhenDiverged(t *testing.T) { } publishCommit(t, other, "one.txt") - h.app.updateCurrentBranch(p) + h.app.updateCurrentBranch(p, surfaceButton) h.settle() h.settle() if want := h.app.text.Sync.Updated("main"); h.app.notice != want { @@ -121,7 +121,7 @@ func TestLogUpdateBranchFastForwardsAndAsksWhenDiverged(t *testing.T) { } gitRun(t, dir, "add", "mine.txt") gitRun(t, dir, "commit", "-m", "mine") - h.app.updateCurrentBranch(p) + h.app.updateCurrentBranch(p, surfaceButton) h.settle() h.settle() s := &p.log.sync diff --git a/desktop/internal/workbench/gitworktree_test.go b/desktop/internal/workbench/gitworktree_test.go index b0042fee22..a515b89821 100644 --- a/desktop/internal/workbench/gitworktree_test.go +++ b/desktop/internal/workbench/gitworktree_test.go @@ -431,7 +431,7 @@ func TestWorktreeChangesShowTheDiffAndRollBackInTheirCheckout(t *testing.T) { changes := h.awaitWorktreeChanges("the linked checkout's changes", linked, func(c []core.GitChange) bool { return len(c) == 2 }) // draft.txt exists only in the linked checkout, so its diff can only be read there. - d := h.app.openDiffIn(p, linked, changeAt(t, changes, "draft.txt")) + d := h.app.openDiffIn(p, linked, changeAt(t, changes, "draft.txt"), surfaceButton) if d == nil { t.Fatal("no Diff tab opened for the linked checkout's change") } diff --git a/desktop/internal/workbench/gitworktree_view.go b/desktop/internal/workbench/gitworktree_view.go index f109aac52f..fbbb57d6bb 100644 --- a/desktop/internal/workbench/gitworktree_view.go +++ b/desktop/internal/workbench/gitworktree_view.go @@ -201,7 +201,7 @@ func (a *App) worktreeRowMenu(row ui.ListRow, p *project, w core.GitWorktree) { item := func(label string, disabled bool, action string, run func()) { if menu.Item(label).Disabled(disabled).Clicked() { c.After(func() { - a.performed(action, surfaceMenu) + a.performed(action, surfaceContextMenu) run() }) } @@ -491,7 +491,7 @@ func (a *App) drawWorktreeChange(c ui.C, p *project, root string, busy bool, cha c.After(func() { a.stageWorktreeChange(p, root, change) }) } if opened && !strings.HasSuffix(change.Path, "/") { - c.After(func() { a.openDiffIn(p, root, change) }) + c.After(func() { a.openDiffIn(p, root, change, surfaceButton) }) } } @@ -503,7 +503,7 @@ func (a *App) worktreeChangeMenuItems(c ui.C, p *project, root string, change co _, review := a.reviewKernel() folder := strings.HasSuffix(change.Path, "/") if review && !folder && menu.Item(i18n.Shared(a.language(), "git.showDiff")).Clicked() { - c.After(func() { a.openDiffIn(p, root, change) }) + c.After(func() { a.openDiffIn(p, root, change, surfaceContextMenu) }) } if menu.Item(a.text.Worktrees.CopyPath).Clicked() { c.After(func() { diff --git a/desktop/internal/workbench/html_preview.go b/desktop/internal/workbench/html_preview.go index d9152319fb..39deaad2d8 100644 --- a/desktop/internal/workbench/html_preview.go +++ b/desktop/internal/workbench/html_preview.go @@ -160,7 +160,7 @@ func (a *App) htmlActions(c ui.C, p *project, d *document, s *htmlPreviewState, } } if a.viewerIconButton(c.Part("browser"), i18n.Shared(language, "desktop.editorMenu.openInBrowser"), icons.ExternalLink) { - c.After(func() { a.openInBrowser(p, d) }) + c.After(func() { a.openInBrowser(p, d, surfaceButton) }) } } diff --git a/desktop/internal/workbench/ide_api_dispatch.go b/desktop/internal/workbench/ide_api_dispatch.go index fdbfa08c1e..5862fbfb2a 100644 --- a/desktop/internal/workbench/ide_api_dispatch.go +++ b/desktop/internal/workbench/ide_api_dispatch.go @@ -591,6 +591,7 @@ func (a *App) ideAPIBuildExecute(p *project, args ideAPIBuildExecuteArguments) ( // Make the requested instance the Build window's selection so the shared run path // prepares that plugin's model and tool, not whatever the window selected before. a.selectBuildInstance(p, index) + a.performed("build.task.run", surfacePlugin) operation, err := a.runBuildTask(p, args.ProjectID, args.TargetID, taskID, args.UserArguments) if err != nil { return nil, ideAPIRefusal(err) diff --git a/desktop/internal/workbench/ide_api_run.go b/desktop/internal/workbench/ide_api_run.go index a739f97e51..bff64e243d 100644 --- a/desktop/internal/workbench/ide_api_run.go +++ b/desktop/internal/workbench/ide_api_run.go @@ -24,6 +24,7 @@ func ideAPIRunList(p *project) any { // ideAPIRunStart starts a run configuration through the Run window and returns the execution // it reserved. A refused start reserves nothing and is answered with the refusal's code. func (a *App) ideAPIRunStart(p *project, configurationID string) (*ideAPIOperation, any) { + a.performed("run.configuration.run", surfacePlugin) operation, err := a.startRunConfiguration(p, configurationID) if err != nil { return nil, ideAPIRefusal(err) diff --git a/desktop/internal/workbench/legacy_import.go b/desktop/internal/workbench/legacy_import.go index 6a21bb9794..b60e05922b 100644 --- a/desktop/internal/workbench/legacy_import.go +++ b/desktop/internal/workbench/legacy_import.go @@ -64,19 +64,19 @@ type legacyImportItem struct { // disabled while the earlier preferences are read. func (a *App) legacyImportMenuItem(c ui.C, menu *ui.MenuItems) { if menu.Item(i18n.Shared(a.language(), "desktop.legacyImport.menu")).Disabled(a.legacyImport.reading).Clicked() { - c.After(a.readLegacyImport) + c.After(func() { a.readLegacyImport(surfaceMenu) }) } } // readLegacyImport reads what the earlier client stored, off the window thread, and opens -// the dialog that lists it. -func (a *App) readLegacyImport() { +// the dialog that lists it. surface is where the user started the import. +func (a *App) readLegacyImport(surface actionSurface) { s := &a.legacyImport if s.reading || s.open { return } s.reading = true - a.performed("settings.import_legacy", surfaceMenu) + a.performed("settings.import_legacy", surface) read := s.read if read == nil { read = legacyimport.Read diff --git a/desktop/internal/workbench/legacy_import_test.go b/desktop/internal/workbench/legacy_import_test.go index 7952fbcd07..8e83e614e2 100644 --- a/desktop/internal/workbench/legacy_import_test.go +++ b/desktop/internal/workbench/legacy_import_test.go @@ -38,7 +38,7 @@ func TestLegacyImportAppliesTheChosenSettings(t *testing.T) { recent := filepath.Join(t.TempDir(), "earlier") h.app.legacyImport.read = func(context.Context) (legacyimport.Found, error) { return earlierLithe(recent), nil } s := &h.app.legacyImport - h.app.post((*App).readLegacyImport) + h.app.post(func(a *App) { a.readLegacyImport(surfaceMenu) }) awaitStateWithin(t, h, 10*time.Second, "the import dialog", func() bool { return s.open }) h.settle() language := h.app.language() @@ -94,7 +94,7 @@ func TestLegacyImportWithoutAnEarlierClient(t *testing.T) { h.app.legacyImport.read = func(context.Context) (legacyimport.Found, error) { return legacyimport.Found{}, legacyimport.ErrNotFound } - h.app.post((*App).readLegacyImport) + h.app.post(func(a *App) { a.readLegacyImport(surfaceMenu) }) want := i18n.Shared(h.app.language(), "desktop.legacyImport.none") awaitStateWithin(t, h, 10*time.Second, "the notice", func() bool { return h.app.notice == want }) if h.app.legacyImport.open || h.app.legacyImport.reading { @@ -130,7 +130,7 @@ func TestLegacyImportListsMissingPlugins(t *testing.T) { }}, nil } s := &h.app.legacyImport - h.app.post((*App).readLegacyImport) + h.app.post(func(a *App) { a.readLegacyImport(surfaceMenu) }) awaitStateWithin(t, h, 10*time.Second, "the import dialog", func() bool { return s.open }) h.settle() if !h.shows("Database Tools") || h.shows("Java Support") || len(s.items) != 0 { @@ -143,7 +143,7 @@ func TestLegacyImportListsMissingPlugins(t *testing.T) { // Once every earlier plugin is installed, nothing is left to import. h.app.post(func(a *App) { a.legacyImport.open = false }) h.app.pluginState.Store(&map[string]settingswindow.PluginState{"dev.example.java": {Installed: true}, "dev.example.db": {Installed: true}}) - h.app.post((*App).readLegacyImport) + h.app.post(func(a *App) { a.readLegacyImport(surfaceMenu) }) want := i18n.Shared(h.app.language(), "desktop.legacyImport.none") awaitStateWithin(t, h, 10*time.Second, "the notice", func() bool { return h.app.notice == want }) if s.open { diff --git a/desktop/internal/workbench/local_history.go b/desktop/internal/workbench/local_history.go index 8d7c6dacd5..58a4e486ec 100644 --- a/desktop/internal/workbench/local_history.go +++ b/desktop/internal/workbench/local_history.go @@ -203,7 +203,6 @@ func (a *App) openLocalHistory(p *project, path string) { } } }) - a.performed("localHistory.open", surfaceMenu) } // selectLocalHistory selects one snapshot and reads its text for the preview. diff --git a/desktop/internal/workbench/lsp_status_test.go b/desktop/internal/workbench/lsp_status_test.go index d1dbcab8a9..e9fc6d43f4 100644 --- a/desktop/internal/workbench/lsp_status_test.go +++ b/desktop/internal/workbench/lsp_status_test.go @@ -158,8 +158,8 @@ func TestLSPLogTabSplitsOffAndCloses(t *testing.T) { // runCommand runs the catalog's command id, reporting whether it was listed and enabled. func runCommand(a *App, id string) bool { for _, cmd := range a.commands() { - if cmd.id == id && cmd.enabled { - cmd.run() + if cmd.id == id && cmd.runnable() { + a.startCommand(cmd, surfaceShortcut) return true } } diff --git a/desktop/internal/workbench/new_project.go b/desktop/internal/workbench/new_project.go index 3f436919a7..e5f4268d33 100644 --- a/desktop/internal/workbench/new_project.go +++ b/desktop/internal/workbench/new_project.go @@ -133,7 +133,7 @@ type searchRequest struct { candidates []core.RankCandidate } -func (a *App) openNewProject(surface string) { +func (a *App) openNewProject(surface actionSurface) { n := &a.newProject if n.open { return diff --git a/desktop/internal/workbench/outputlinks_view.go b/desktop/internal/workbench/outputlinks_view.go index d5b5d2d872..6a246787f5 100644 --- a/desktop/internal/workbench/outputlinks_view.go +++ b/desktop/internal/workbench/outputlinks_view.go @@ -28,14 +28,14 @@ func (a *App) outputLineMenu(c ui.C, text string, line bool, m *outputMenu) func menu.WidthRange(180, 260) if menu.Item(i18n.Shared(lang, "menu.copy")).Disabled(!line).Clicked() { c.After(func() { - a.performed("output.copyLine", surfaceMenu) + a.performed("output.copyLine", surfaceContextMenu) _ = app.SetClipboardText(text) }) } if menu.Item(i18n.Shared(lang, "git.console.copyOutput")).Clicked() { all := m.all() c.After(func() { - a.performed("output.copyAll", surfaceMenu) + a.performed("output.copyAll", surfaceContextMenu) _ = app.SetClipboardText(all) }) } diff --git a/desktop/internal/workbench/plugins.go b/desktop/internal/workbench/plugins.go index 2da830dc1f..1ed4fc4639 100644 --- a/desktop/internal/workbench/plugins.go +++ b/desktop/internal/workbench/plugins.go @@ -79,7 +79,7 @@ func (a *App) installPlugin(plugin core.MarketplacePlugin, feedback settingswind a.pluginDownloads = marketplace.NewArchiveSession(nil) } downloads := a.pluginDownloads - a.performed("plugin.install", "marketplace") + a.performed("plugin.install.marketplace", surfaceButton) a.preparePluginInstall(feedback, func(ctx context.Context) (plugininstall.Plan, error) { archive, err := downloads.Download(ctx, availability, feedback.Progress) if err != nil { @@ -119,7 +119,7 @@ func (a *App) closePluginDownloads() { // installPluginFromFile submits a local package to the same review. func (a *App) installPluginFromFile(path string, feedback settingswindow.PluginInstallFeedback) { - a.performed("plugin.install", "disk") + a.performed("plugin.install.disk", surfaceButton) a.preparePluginInstall(feedback, func(ctx context.Context) (plugininstall.Plan, error) { return a.plugins.Installer.Prepare(ctx, plugininstall.Request{ ArchivePath: path, diff --git a/desktop/internal/workbench/pluginsemantics.go b/desktop/internal/workbench/pluginsemantics.go index 84e5e3d3f3..fac8be11ff 100644 --- a/desktop/internal/workbench/pluginsemantics.go +++ b/desktop/internal/workbench/pluginsemantics.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "path/filepath" + "regexp" "runtime" "strconv" "strings" @@ -1665,19 +1666,43 @@ func (a *App) removePending(pending *semanticPending) bool { return false } -// logSemanticError records Core's stable error code without copying server -// internals into the user's log. +// logSemanticError records that the language server failed a request, with the error's stable +// code and never its message, which can quote the user's code. The code is the JSON-RPC +// number or the plugin's token; anything else is recorded as unknown. Formatting and rename +// tell the user (semanticOperationFailed), so they are notification failures; the other +// requests fail quietly and are background failures. func (a *App) logSemanticError(kind semanticKind, raw json.RawMessage) { var failure struct { - Code string `json:"code"` + Code json.RawMessage `json:"code"` } - fields := map[string]any{"operation": "plugin_semantics", "request": string(kind)} - if err := json.Unmarshal(raw, &failure); err == nil && failure.Code != "" { - fields["code"] = failure.Code + code := any("unknown") + if json.Unmarshal(raw, &failure) == nil { + var number int64 + var token string + switch { + case json.Unmarshal(failure.Code, &number) == nil: + code = number + case json.Unmarshal(failure.Code, &token) == nil && logToken.MatchString(token): + code = token + } + } + fields := map[string]any{ + "operation": "plugin_semantics." + string(kind), + "error": "the language server failed the " + kind.method() + " request", + "error_code": code, + "error_domain": "lsp", + } + switch kind { + case pluginSemanticFormatting, pluginSemanticRangeFormatting, pluginSemanticRename: + a.emit(operationFailedLevel, operationFailedEvent, fields) + default: + a.emit(backgroundFailedLevel, backgroundFailedEvent, fields) } - a.emit(operationFailedLevel, operationFailedEvent, fields) } +// logToken is the catalog's token type: what a token field accepts. +var logToken = regexp.MustCompile(`^[A-Za-z0-9._:/$-]{1,64}$`) + func truncateHover(contents string) string { if len(contents) <= maxHoverBytes { return contents diff --git a/desktop/internal/workbench/root.go b/desktop/internal/workbench/root.go index 0e0bca6874..22923f0ebf 100644 --- a/desktop/internal/workbench/root.go +++ b/desktop/internal/workbench/root.go @@ -281,9 +281,8 @@ func (a *App) runShortcut(id string, view *editorview.View, term *terminal) { } for _, command := range a.commands() { if command.id == id { - if command.enabled && command.run != nil { - a.performed("command."+id, surfaceShortcut) - command.run() + if command.runnable() { + a.startCommand(command, surfaceShortcut) } return } diff --git a/desktop/internal/workbench/runconfig.go b/desktop/internal/workbench/runconfig.go index 9e41f2f69b..9104984ef9 100644 --- a/desktop/internal/workbench/runconfig.go +++ b/desktop/internal/workbench/runconfig.go @@ -175,7 +175,6 @@ func (a *App) startRunConfiguration(p *project, id string) (*buildOperation, err a.notifyError(a.text.Build.TargetMissing) return nil, refuseBuild(refusalNotReady, a.text.Build.TargetMissing) } - a.emit(core.LevelInfo, "app.action.performed", map[string]any{"action": "run.configuration", "surface": "build"}) op := a.beginBuildOperation(p, "run", configuration.Name, id, func(a *App, p *project) { a.runConfiguration(p, id) }) diff --git a/desktop/internal/workbench/runconfig_view.go b/desktop/internal/workbench/runconfig_view.go index 3dee09c338..5f477d94ec 100644 --- a/desktop/internal/workbench/runconfig_view.go +++ b/desktop/internal/workbench/runconfig_view.go @@ -100,7 +100,10 @@ func (a *App) drawRunConfigRows(c ui.C, p *project, title string) { key := b.groups[row.group].key c.After(func() { s.toggleRunConfigGroup(key) }) } else if configuration := s.list[row.configuration]; p.build.operation == nil && p.runConfigurationReady(configuration) { - c.After(func() { a.runConfiguration(p, configuration.ID) }) + c.After(func() { + a.performed("run.configuration.run", surfaceButton) + a.runConfiguration(p, configuration.ID) + }) } } } @@ -148,7 +151,10 @@ func (a *App) drawRunConfigRow(p *project, row ui.ListRow, selected bool) { } disabled := p.build.operation != nil || !p.runConfigurationReady(configuration) if a.gitIconButton(c.Part("run"), i18n.Shared(language, "desktop.runConfig.run"), icons.Play, false, disabled) { - c.After(func() { a.runConfiguration(p, configuration.ID) }) + c.After(func() { + a.performed("run.configuration.run", surfaceButton) + a.runConfiguration(p, configuration.ID) + }) } }) } @@ -192,12 +198,15 @@ func (a *App) runConfigMenu(c ui.C, row ui.Box, p *project, configuration core.R c.After(func() { a.stopBuildOperation(p) }) } } else if menu.Item(i18n.Shared(language, "desktop.runConfig.run")).Disabled(p.build.operation != nil || !p.runConfigurationReady(configuration)).Clicked() { - c.After(func() { a.runConfiguration(p, id) }) + c.After(func() { + a.performed("run.configuration.run", surfaceContextMenu) + a.runConfiguration(p, id) + }) } menu.Separator() if menu.Item(i18n.Shared(language, "native.editConfiguration")).Clicked() { c.After(func() { - a.performed("run.configuration.edit", surfaceMenu) + a.performed("run.configuration.edit", surfaceContextMenu) a.openRunConfigEditor(p, id) }) } @@ -207,7 +216,7 @@ func (a *App) runConfigMenu(c ui.C, row ui.Box, p *project, configuration core.R } if menu.Item(pin).Clicked() { c.After(func() { - a.performed(action, surfaceMenu) + a.performed(action, surfaceContextMenu) a.toggleRunConfigPin(p, id) }) } diff --git a/desktop/internal/workbench/search_everywhere_view.go b/desktop/internal/workbench/search_everywhere_view.go index 143f6176f1..f002a0b268 100644 --- a/desktop/internal/workbench/search_everywhere_view.go +++ b/desktop/internal/workbench/search_everywhere_view.go @@ -427,7 +427,7 @@ func (a *App) searchResultMenu(c ui.C, target ui.Box, p *project, result core.Wo ui.ContextMenu(c, target, func(menu *ui.MenuItems) { if menu.Item(i18n.Shared(language, "desktop.files.open")).Clicked() { c.After(func() { - a.performed(surface+".openResult", surfaceMenu) + a.performed(surface+".openResult", surfaceContextMenu) if leave != nil { leave() } @@ -436,7 +436,7 @@ func (a *App) searchResultMenu(c ui.C, target ui.Box, p *project, result core.Wo } if menu.Item(revealLabel(language)).Clicked() { c.After(func() { - a.performed(surface+".reveal", surfaceMenu) + a.performed(surface+".reveal", surfaceContextMenu) a.revealPath(full) }) } diff --git a/desktop/internal/workbench/settings.go b/desktop/internal/workbench/settings.go index fcc5030d29..d8a87c0e75 100644 --- a/desktop/internal/workbench/settings.go +++ b/desktop/internal/workbench/settings.go @@ -339,28 +339,28 @@ func (a *App) invalidateSettingsWindow() { // The window is opened from a queued task because the toolkit only opens a window from a // window thread, which the task runs on. The settings in force are read there, at the // moment the window opens, so a window that has to be made starts from the latest ones. -func (a *App) openSettings(surface string) { +func (a *App) openSettings(surface actionSurface) { a.openSettingsPage(surface, settingsHome) } // openPluginSettings shows the settings window on its plugin page. -func (a *App) openPluginSettings(surface string) { +func (a *App) openPluginSettings(surface actionSurface) { a.openSettingsPage(surface, settingsPlugins) } // openPluginSettingsSearch shows the plugin page with the marketplace search set to query. -func (a *App) openPluginSettingsSearch(surface, query string) { +func (a *App) openPluginSettingsSearch(surface actionSurface, query string) { a.openSettingsPageWith(surface, settingsPlugins, query) } // openTerminalSettings shows the settings window on its Terminal page, where the shell new // terminals run is picked. -func (a *App) openTerminalSettings(surface string) { +func (a *App) openTerminalSettings(surface actionSurface) { a.openSettingsPage(surface, settingsTerminal) } // openKeymapSettings shows the settings window on its Keymap page. -func (a *App) openKeymapSettings(surface string) { +func (a *App) openKeymapSettings(surface actionSurface) { a.openSettingsPage(surface, settingsKeymap) } @@ -379,12 +379,12 @@ const ( settingsKeymap ) -func (a *App) openSettingsPage(surface string, page settingsPage) { +func (a *App) openSettingsPage(surface actionSurface, page settingsPage) { a.openSettingsPageWith(surface, page, "") } // openSettingsPageWith is openSettingsPage with the marketplace search text the plugin page starts with. -func (a *App) openSettingsPageWith(surface string, page settingsPage, query string) { +func (a *App) openSettingsPageWith(surface actionSurface, page settingsPage, query string) { a.performed("settings.open", surface) // Users can enter Plugins from any settings page. Publish native installed // state when the window opens, including its general-settings entry point. diff --git a/desktop/internal/workbench/settings_plugin_actions.go b/desktop/internal/workbench/settings_plugin_actions.go index 26f2cd4576..0620b9132f 100644 --- a/desktop/internal/workbench/settings_plugin_actions.go +++ b/desktop/internal/workbench/settings_plugin_actions.go @@ -49,7 +49,7 @@ func (s pluginSettingsSources) actionWorkspaceCheck(editor pluginservice.Setting // unavailable action starts a process or publishes a settings draft. func (s pluginSettingsSources) Action(ctx context.Context, editor pluginservice.SettingsEditor, id string, confirmed bool) (result pluginservice.SettingsActionResult, err error) { defer func() { (settingsToolchains{app: s.app}).recordFailure("plugin_settings_action", err) }() - s.app.emit(core.LevelInfo, "app.action.performed", map[string]any{"action": "plugin.settingsAction", "surface": "settings"}) + s.app.performed("plugin.settingsAction", surfaceButton) check := s.actionWorkspaceCheck(editor) result.Plan, err = s.app.plugins.PlanSettingsEditorAction(ctx, editor, id, confirmed, check) if err != nil { diff --git a/desktop/internal/workbench/shell_view.go b/desktop/internal/workbench/shell_view.go index 1fad90153e..cc00e9a03d 100644 --- a/desktop/internal/workbench/shell_view.go +++ b/desktop/internal/workbench/shell_view.go @@ -142,7 +142,7 @@ func (a *App) shellPanel(c ui.C, s slot, index int, hidden *slot) ui.Box { menu.WidthRange(180, 280) if menu.Item(i18n.SharedFormat(a.language(), "native.hideToolWindow", map[string]string{"arg1": title})).Clicked() { c.After(func() { - a.performed("workbench.toolWindow.hide", surfaceMenu) + a.performed("workbench.toolWindow.hide", surfaceContextMenu) a.hidePanel(s) }) } diff --git a/desktop/internal/workbench/startup_sweep.go b/desktop/internal/workbench/startup_sweep.go index 4f0e879968..89a2036947 100644 --- a/desktop/internal/workbench/startup_sweep.go +++ b/desktop/internal/workbench/startup_sweep.go @@ -113,17 +113,23 @@ func (a *App) planStartupSweep() { kept = append(kept, leftovers[i]) } } - a.settleLeftovers(ended, kept, grace, "policy") + a.settleLeftovers(ended, kept, grace, leftoversByPolicy) question.open = len(question.leftovers) > 0 a.startupSweep = question } }) } +// What decided the leftovers, as app.startup.leftovers_resolved records it: Core's process +// lifecycle policy, or the user's answer to the start-up question. +const ( + leftoversByPolicy = "policy" + leftoversByDialog = "dialog" +) + // settleLeftovers forgets ended and kept off the window thread, ending the ones in ended with -// grace to stop before they are killed. surface says what decided them: Core's policy or the -// user's answer. -func (a *App) settleLeftovers(ended, kept []processledger.Record, grace time.Duration, surface string) { +// grace to stop before they are killed. decidedBy is leftoversByPolicy or leftoversByDialog. +func (a *App) settleLeftovers(ended, kept []processledger.Record, grace time.Duration, decidedBy string) { service := a.plugins if service == nil || len(ended)+len(kept) == 0 { return @@ -137,7 +143,7 @@ func (a *App) settleLeftovers(ended, kept []processledger.Record, grace time.Dur a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("startup_sweep", err)) return } - a.emit(core.LevelInfo, "app.action.performed", map[string]any{"action": "startupSweep", "surface": surface, "ended": count, "kept": len(kept)}) + a.emit(core.LevelInfo, "app.startup.leftovers_resolved", map[string]any{"decided_by": decidedBy, "ended": count, "kept": len(kept)}) } }) } @@ -178,14 +184,19 @@ func (a *App) drawStartupSweep(c ui.C) { // forgotten. The question closes at once; the ending itself is bounded. A settlement that // cannot be had ends nothing and leaves the leftovers recorded, so the next start asks again. func (a *App) settleStartupSweep(end bool) { + if end { + a.performed("startupSweep.end", surfaceButton) + } else { + a.performed("startupSweep.keep", surfaceButton) + } question := a.startupSweep a.startupSweep = startupSweepState{} if question.decisions == nil { // Core made no plan, so there is nothing to settle the answer with. if end { - a.settleLeftovers(question.leftovers, nil, question.grace, "dialog") + a.settleLeftovers(question.leftovers, nil, question.grace, leftoversByDialog) } else { - a.settleLeftovers(nil, question.leftovers, question.grace, "dialog") + a.settleLeftovers(nil, question.leftovers, question.grace, leftoversByDialog) } return } @@ -217,7 +228,7 @@ func (a *App) settleStartupSweep(end bool) { } return picked } - a.settleLeftovers(pick(settlement.Terminate), pick(settlement.Keep), question.grace, "dialog") + a.settleLeftovers(pick(settlement.Terminate), pick(settlement.Keep), question.grace, leftoversByDialog) } }) } diff --git a/desktop/internal/workbench/tab_menu.go b/desktop/internal/workbench/tab_menu.go index 3998eb4743..f75ffca54c 100644 --- a/desktop/internal/workbench/tab_menu.go +++ b/desktop/internal/workbench/tab_menu.go @@ -32,7 +32,7 @@ func (a *App) tabMenuItems(c ui.C, group string, t shownTab, tabs []shownTab) fu } } c.After(func() { - a.performed(action, surfaceMenu) + a.performed(action, surfaceContextMenu) a.closeMembers(p, members) }) } @@ -78,20 +78,20 @@ func (a *App) tabMenuItems(c ui.C, group string, t shownTab, tabs []shownTab) fu a.copyPathMenu(c, menu, path, true, "editor.tabs") if menu.Item(revealLabel(language)).Clicked() { c.After(func() { - a.performed("editor.tabs.reveal", surfaceMenu) + a.performed("editor.tabs.reveal", surfaceContextMenu) a.revealPath(path) }) } _, inside := projectRelative(p.root, path) if _, ok := a.kernel.(localHistoryKernel); ok && inside && menu.Item(i18n.Shared(language, "desktop.history.show")).Clicked() { c.After(func() { - a.performed("localHistory.show", surfaceMenu) + a.performed("localHistory.show", surfaceContextMenu) a.openLocalHistory(p, path) }) } if inside && menu.Item(i18n.Shared(language, "desktop.tab.selectInProject")).Clicked() { c.After(func() { - a.performed("editor.tabs.selectInProject", surfaceMenu) + a.performed("editor.tabs.selectInProject", surfaceContextMenu) a.selectDocument(p, d.id) a.reduceChrome(core.SetChromeOpen(itemProject, true)) a.revealActiveFile(p) @@ -131,7 +131,7 @@ func (a *App) setTabPinned(p *project, group string, d *document, pinned bool) { if pinned { action = "editor.tabs.pin" } - a.performed(action, surfaceMenu) + a.performed(action, surfaceContextMenu) member := documentMember(d.id) if !a.reduceTerminals(p, p.terms.bench, core.PinEditor(group, member, pinned)) { return diff --git a/desktop/internal/workbench/terminal_drop.go b/desktop/internal/workbench/terminal_drop.go index 82e4e2ab37..e296022cff 100644 --- a/desktop/internal/workbench/terminal_drop.go +++ b/desktop/internal/workbench/terminal_drop.go @@ -39,7 +39,7 @@ func (a *App) terminalTreeDrop(source, target gfx.ID) { if !ok || t == nil { return } - a.performed("terminal.dropPath", surfaceMenu) + a.performed("terminal.dropPath", surfaceDragDrop) a.pasteTerminalPaths(t, []string{filepath.Join(p.root, filepath.FromSlash(ref.path))}) } @@ -55,7 +55,7 @@ func (a *App) terminalFileDrop(event gfx.FileDropEvent) (gfx.EventResult, bool) return gfx.EventResult{Handled: true}, true case gfx.FileDropDrop: if len(event.Paths) > 0 { - a.performed("terminal.dropPath", surfaceMenu) + a.performed("terminal.dropPath", surfaceDragDrop) a.pasteTerminalPaths(t, event.Paths) return gfx.EventResult{Handled: true, Repaint: true}, true } diff --git a/desktop/internal/workbench/terminal_menu.go b/desktop/internal/workbench/terminal_menu.go index bb2074f982..7310db35d1 100644 --- a/desktop/internal/workbench/terminal_menu.go +++ b/desktop/internal/workbench/terminal_menu.go @@ -20,33 +20,33 @@ func (a *App) terminalMenu(c ui.C, name string, box ui.Box, t *terminal) { if menu.Item(i18n.Shared(lang, "menu.copy")).Disabled(!t.view.HasSelection()).Clicked() { text := t.view.SelectionText() c.After(func() { - a.performed("terminal.copy", surfaceMenu) + a.performed("terminal.copy", surfaceContextMenu) _ = app.SetClipboardText(text) }) } if menu.Item(i18n.Shared(lang, "menu.paste")).Clicked() { c.After(func() { - a.performed("terminal.paste", surfaceMenu) + a.performed("terminal.paste", surfaceContextMenu) t.view.PasteClipboard() a.focusTerminal(t.id) }) } if menu.Item(i18n.Shared(lang, "menu.selectAll")).Clicked() { c.After(func() { - a.performed("terminal.selectAll", surfaceMenu) + a.performed("terminal.selectAll", surfaceContextMenu) t.view.SelectAll() }) } menu.Separator() if menu.Item(i18n.Shared(lang, "ui.clear")).Clicked() { c.After(func() { - a.performed("terminal.clear", surfaceMenu) + a.performed("terminal.clear", surfaceContextMenu) t.view.Clear() }) } if t.view.Ended() && menu.Item(i18n.Shared(lang, "native.restart")).Clicked() { c.After(func() { - a.performed("terminal.restart", surfaceMenu) + a.performed("terminal.restart", surfaceContextMenu) t.view.Restart() }) } @@ -54,7 +54,7 @@ func (a *App) terminalMenu(c ui.C, name string, box ui.Box, t *terminal) { if menu.Item(i18n.Shared(lang, "terminal.contextClose")).Clicked() { id := t.id c.After(func() { - a.performed("terminal.close", surfaceMenu) + a.performed("terminal.close", surfaceContextMenu) a.requestCloseTerminal(p, id) }) } diff --git a/desktop/internal/workbench/tests.go b/desktop/internal/workbench/tests.go index c137f62762..13b2a87077 100644 --- a/desktop/internal/workbench/tests.go +++ b/desktop/internal/workbench/tests.go @@ -216,7 +216,7 @@ func (a *App) startTests(p *project, selection testSelection) { p.tests.last = &last captured := *instance startedMillis := time.Now().UnixMilli() - a.emit(core.LevelInfo, "app.action.performed", map[string]any{"action": "tests.run", "surface": "tests", "scope": selection.scope()}) + a.performed("tests.run."+selection.scope(), surfaceButton) a.background(p, testRequestTimeout, func(ctx context.Context) func(*App) { return a.executeTestRun(ctx, p, captured, selection, generation, startedMillis) }) diff --git a/desktop/internal/workbench/title_run.go b/desktop/internal/workbench/title_run.go index b7ad9e64f8..dcb1b20e45 100644 --- a/desktop/internal/workbench/title_run.go +++ b/desktop/internal/workbench/title_run.go @@ -121,7 +121,7 @@ func (a *App) titleRun(p *project) { if p == nil { return } - a.performed("title.run", surfaceButton) + a.performed("title.run", surfaceToolbar) a.openToolWindow(itemRun) a.titleStart(p, titleActionRun) } @@ -132,7 +132,7 @@ func (a *App) titleDebug(p *project) { if p == nil { return } - a.performed("title.debug", surfaceButton) + a.performed("title.debug", surfaceToolbar) a.openToolWindow(itemDebug) a.titleStart(p, titleActionDebug) } diff --git a/desktop/internal/workbench/vcs.go b/desktop/internal/workbench/vcs.go index 326958d0ce..04b94a34e5 100644 --- a/desktop/internal/workbench/vcs.go +++ b/desktop/internal/workbench/vcs.go @@ -547,7 +547,7 @@ func (a *App) detectVcsRoots(p *project) { } s.detection, s.manifests = detection, plugins for _, conflict := range detection.Conflicts { - a.emit(core.LevelWarn, "app.vcs.provider_conflict", map[string]any{"plugin": conflict.PluginID, "vcs": conflict.Vcs, "by": conflict.By}) + a.emit(core.LevelWarn, "vcs.provider.skipped", map[string]any{"plugin": conflict.PluginID, "vcs": conflict.Vcs, "selected": conflict.By}) } if len(detection.UnusedMappings) > 0 { a.dropVcsMappings(root, detection.UnusedMappings) diff --git a/desktop/internal/workbench/viewer.go b/desktop/internal/workbench/viewer.go index 91baed54b5..1f513b3187 100644 --- a/desktop/internal/workbench/viewer.go +++ b/desktop/internal/workbench/viewer.go @@ -160,7 +160,6 @@ func (a *App) openViewer(p *project, path string, kind viewerKind) { p.viewers.list = append(p.viewers.list, t) p.docs.group = group a.focus = focusTarget{} - a.performed("editor.viewer.open", surfaceMenu) // The file is read off the window's thread, which a slow disk would hold up. a.background(p, 0, func(ctx context.Context) func(*App) { info, err := os.Stat(path) diff --git a/desktop/internal/workbench/welcome_drop.go b/desktop/internal/workbench/welcome_drop.go index 59f59455c3..233ce25455 100644 --- a/desktop/internal/workbench/welcome_drop.go +++ b/desktop/internal/workbench/welcome_drop.go @@ -33,7 +33,7 @@ func (a *App) welcomeFileDrop(event gfx.FileDropEvent) gfx.EventResult { a.notifyInfo(a.text.Welcome.DropFolderOnly) return gfx.EventResult{Handled: true, Repaint: true} } - a.performed("workspace.drop.open", surfaceMenu) + a.performed("workspace.drop.open", surfaceDragDrop) a.openProject(folder) return gfx.EventResult{Handled: true, Repaint: true} } diff --git a/desktop/internal/workbench/welcome_view.go b/desktop/internal/workbench/welcome_view.go index 36a85ed830..798f4335b8 100644 --- a/desktop/internal/workbench/welcome_view.go +++ b/desktop/internal/workbench/welcome_view.go @@ -251,7 +251,7 @@ func (a *App) welcomeMenuItems(c ui.C, path string) func(*ui.MenuItems) { if !a.missing[path] { if menu.Item(a.text.Welcome.MenuOpen).Clicked() { c.After(func() { - a.performed("workspace.recent.open", surfaceMenu) + a.performed("workspace.recent.open", surfaceContextMenu) a.openProject(path) }) } @@ -272,13 +272,13 @@ func (a *App) welcomeMenuItems(c ui.C, path string) func(*ui.MenuItems) { } if menu.Item(pinLabel).Clicked() { c.After(func() { - a.performed("workspace.recent.pin", surfaceMenu) + a.performed("workspace.recent.pin", surfaceContextMenu) a.reduceRecent(a.recent, core.TogglePinnedRecent(path), true) }) } if menu.Item(a.text.Welcome.MenuRemove).Clicked() { c.After(func() { - a.performed("workspace.recent.remove", surfaceMenu) + a.performed("workspace.recent.remove", surfaceContextMenu) a.reduceRecent(a.recent, core.RemoveRecent(path), true) }) } @@ -287,7 +287,7 @@ func (a *App) welcomeMenuItems(c ui.C, path string) func(*ui.MenuItems) { // revealRecent shows a recent project in the system's file browser. func (a *App) revealRecent(path string) { - a.performed("workspace.recent.reveal", surfaceMenu) + a.performed("workspace.recent.reveal", surfaceContextMenu) a.background(nil, 0, func(context.Context) func(*App) { err := app.RevealPath(path) return func(a *App) { From 6d0a9ca9e0423072278d42dc3723b82861100306 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 01:17:49 +0800 Subject: [PATCH 4/7] =?UTF-8?q?fix(desktop):=20=E6=97=A5=E5=BF=97=E6=8C=89?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E4=B8=B2=E8=81=94=EF=BC=8C=E8=A1=A5=E9=BD=90?= =?UTF-8?q?=E6=8F=92=E4=BB=B6=E6=97=A5=E5=BF=97=E6=8E=A5=E7=BA=BF=E5=92=8C?= =?UTF-8?q?=E5=AE=BF=E4=B8=BB=E4=BB=A3=E8=AE=B0=E7=9A=84=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 操作链(#1927 第 1–4 项): - 每个用户动作分配一个 op(action-N),后台工作通过 a.background 继承 origin, Core 请求带 origin(source、trigger、operation),宿主记录和失败提示都带同一个 op。 - 失败提示带“查看日志”按钮,按 op 打开日志窗口并过滤到这次动作的记录。 - 补齐缺失的失败记录;app.notification.operation_failed 只用于用户动作失败, 后台失败改记 app.background.operation_failed,被取代的模型加载记为 plugin_model_superseded。 插件日志(#1927 第 5–9 项): - 插件 ${logDir} 改为会话内的 PluginFilesPath,不再推导安装目录。 - 插件后端的 lithe/log 引擎事实转发给 Core;按设置开关 lsp.setDetailedDiagnostics,诊断详情不再只停在宿主内存。 - languageServer/start 启动前失败由宿主代记,之后通过 startupOperation 交给 Core。 宿主代记的声明式贡献(diagnostics.recordPluginOperation): - debugAdapter/start:stdio 和 hosted 适配器从解析到应答 initialize 的结果, 按 resolve/launch/timeout/exit/initialize 记录;用户停止和 Core 拒绝不记录; 写入超时记为 timeout,stdio 适配器停止读取输入记为 exit。 - lithe/build/model、lithe/build/dependencies:命令式来源按 plan/resolve/launch/exit/decode/timeout 记录;provider 请求由插件 SDK 自己记录; 项目关闭取消的加载不记录。 - Core 拒绝记录时改记 app.background.operation_failed(plugin_operation_record)。 测试用真实 Core 和复制的测试二进制端到端验证各阶段,录制内核放到 plugin_operation_record_test.go 供调试和构建测试共用。 --- desktop/internal/core/client.go | 3 + desktop/internal/core/log_sites_test.go | 8 +- desktop/internal/core/origin.go | 71 +++++ desktop/internal/core/origin_test.go | 82 +++++ desktop/internal/core/plugin_operation.go | 189 ++++++++++++ .../internal/core/plugin_operation_test.go | 211 +++++++++++++ desktop/internal/core/plugin_session.go | 14 + desktop/internal/i18n/shared.generated.go | 4 + desktop/internal/logstore/store.go | 69 +++++ desktop/internal/logstore/store_test.go | 102 ++++++ desktop/internal/logwindow/model.go | 16 + desktop/internal/logwindow/operation_test.go | 68 ++++ desktop/internal/logwindow/window.go | 17 + .../internal/pluginbackend/log_facts_test.go | 117 +++++++ .../internal/pluginbackend/pluginbackend.go | 58 +++- .../pluginbackend/pluginbackend_test.go | 52 ++++ desktop/internal/pluginbackend/trace.go | 123 ++++++++ desktop/internal/pluginbackend/trace_test.go | 162 ++++++++++ desktop/internal/pluginservice/backendhost.go | 19 +- .../internal/pluginservice/backendlaunch.go | 7 +- desktop/internal/pluginservice/backends.go | 21 +- desktop/internal/pluginservice/operations.go | 28 ++ .../internal/pluginservice/operations_test.go | 154 +++++++++ .../internal/pluginservice/pluginservice.go | 10 + .../pluginservice/pluginservice_test.go | 13 +- desktop/internal/workbench/aicommit.go | 5 +- desktop/internal/workbench/app.go | 183 +++++++++-- desktop/internal/workbench/branch.go | 6 +- desktop/internal/workbench/browser_preview.go | 2 +- desktop/internal/workbench/build.go | 85 +++-- .../workbench/build_command_record_test.go | 280 +++++++++++++++++ .../internal/workbench/build_dependencies.go | 40 ++- desktop/internal/workbench/build_tests.go | 5 +- desktop/internal/workbench/catalog.go | 8 +- desktop/internal/workbench/changelists.go | 6 +- .../internal/workbench/changelists_select.go | 1 + desktop/internal/workbench/clone.go | 16 +- desktop/internal/workbench/commands.go | 1 + desktop/internal/workbench/commit.go | 84 ++++- .../internal/workbench/completion_merge.go | 4 +- .../internal/workbench/credentials_import.go | 2 +- desktop/internal/workbench/debug.go | 28 +- .../internal/workbench/debug_adapter_start.go | 99 ++++++ .../workbench/debug_adapter_start_test.go | 288 +++++++++++++++++ .../internal/workbench/debug_breakpoints.go | 2 + desktop/internal/workbench/debug_child.go | 2 +- desktop/internal/workbench/debug_launch.go | 26 +- desktop/internal/workbench/debug_relocate.go | 2 +- desktop/internal/workbench/debug_start.go | 56 +++- desktop/internal/workbench/debug_tcp_test.go | 9 +- desktop/internal/workbench/debug_transport.go | 9 +- .../workbench/diagnostics_watch_test.go | 104 +++++++ desktop/internal/workbench/diff_find.go | 2 +- desktop/internal/workbench/difftab.go | 4 +- .../workbench/directory_exclusions.go | 9 +- desktop/internal/workbench/document_links.go | 2 +- .../workbench/document_observation.go | 2 +- desktop/internal/workbench/documents.go | 4 +- desktop/internal/workbench/editor_actions.go | 12 +- desktop/internal/workbench/editor_find.go | 2 +- .../internal/workbench/editor_preferences.go | 4 +- desktop/internal/workbench/editor_recovery.go | 6 +- desktop/internal/workbench/editor_session.go | 6 +- desktop/internal/workbench/encoding.go | 8 +- desktop/internal/workbench/filetree.go | 10 +- .../internal/workbench/filetree_actions.go | 3 +- desktop/internal/workbench/filetree_batch.go | 3 +- desktop/internal/workbench/filetree_dnd.go | 7 +- .../internal/workbench/filetree_duplicate.go | 1 + desktop/internal/workbench/filetree_menu.go | 7 +- desktop/internal/workbench/filetree_open.go | 1 + desktop/internal/workbench/filetree_rows.go | 6 +- desktop/internal/workbench/filetree_test.go | 4 +- desktop/internal/workbench/filetree_watch.go | 11 +- desktop/internal/workbench/folding.go | 2 +- desktop/internal/workbench/git.go | 1 + .../internal/workbench/git_blame_inline.go | 4 +- desktop/internal/workbench/git_exclude.go | 2 +- desktop/internal/workbench/git_gutter.go | 2 +- desktop/internal/workbench/git_history.go | 17 +- desktop/internal/workbench/git_observation.go | 4 +- desktop/internal/workbench/git_rebase.go | 6 +- desktop/internal/workbench/gitcompare.go | 2 +- desktop/internal/workbench/gitconsole.go | 1 + desktop/internal/workbench/github_account.go | 6 +- desktop/internal/workbench/github_create.go | 4 +- desktop/internal/workbench/github_prs.go | 5 +- desktop/internal/workbench/gitlinehistory.go | 2 +- desktop/internal/workbench/gitlog.go | 1 + desktop/internal/workbench/gitlog_ref_menu.go | 3 +- desktop/internal/workbench/gitreview.go | 6 +- desktop/internal/workbench/gitreview_tools.go | 4 +- desktop/internal/workbench/gitsync.go | 4 +- desktop/internal/workbench/gitworktree.go | 17 +- desktop/internal/workbench/html_preview.go | 2 +- desktop/internal/workbench/inlineedit.go | 6 +- desktop/internal/workbench/legacy_import.go | 6 +- desktop/internal/workbench/lineedit.go | 2 +- desktop/internal/workbench/local_history.go | 5 +- .../workbench/local_history_settings.go | 13 +- desktop/internal/workbench/logevents_test.go | 21 +- .../internal/workbench/markdown_preview.go | 4 +- desktop/internal/workbench/markdown_web.go | 2 +- desktop/internal/workbench/memory_monitor.go | 4 +- desktop/internal/workbench/navigation.go | 4 +- .../internal/workbench/navigation_history.go | 9 +- desktop/internal/workbench/network.go | 3 +- desktop/internal/workbench/new_project.go | 12 +- .../internal/workbench/new_project_view.go | 8 +- desktop/internal/workbench/notifications.go | 59 +++- .../internal/workbench/notifications_test.go | 77 +++++ desktop/internal/workbench/operation.go | 97 ++++++ desktop/internal/workbench/operation_test.go | 292 ++++++++++++++++++ desktop/internal/workbench/outline.go | 4 +- desktop/internal/workbench/output_style.go | 5 +- desktop/internal/workbench/outputlinks.go | 21 +- desktop/internal/workbench/plugin_displace.go | 4 +- .../workbench/plugin_log_directory_test.go | 70 +++++ desktop/internal/workbench/plugin_native.go | 4 +- .../internal/workbench/plugin_native_state.go | 6 +- .../workbench/plugin_operation_record_test.go | 75 +++++ desktop/internal/workbench/pluginbackends.go | 10 +- desktop/internal/workbench/plugincontent.go | 2 +- .../internal/workbench/plugindiagnostics.go | 4 +- desktop/internal/workbench/pluginedits.go | 17 +- desktop/internal/workbench/pluginpages.go | 6 +- desktop/internal/workbench/pluginrename.go | 5 +- desktop/internal/workbench/plugins.go | 59 ++-- desktop/internal/workbench/plugins_test.go | 6 +- desktop/internal/workbench/pluginsemantics.go | 62 ++-- .../workbench/pluginsemantics_hover.go | 2 +- desktop/internal/workbench/pluginsync.go | 2 +- desktop/internal/workbench/plugintools.go | 3 +- desktop/internal/workbench/preview_pages.go | 4 +- desktop/internal/workbench/problems.go | 2 +- desktop/internal/workbench/process_exit.go | 6 +- .../workbench/project_open_destination.go | 1 + desktop/internal/workbench/recent_branch.go | 2 +- desktop/internal/workbench/recent_files.go | 2 +- desktop/internal/workbench/root.go | 3 +- desktop/internal/workbench/runconfig.go | 1 + .../internal/workbench/runconfig_browser.go | 4 +- desktop/internal/workbench/runs.go | 2 +- desktop/internal/workbench/search.go | 28 +- .../internal/workbench/search_everywhere.go | 12 +- .../workbench/search_everywhere_gesture.go | 2 +- .../workbench/search_everywhere_lsp.go | 4 +- desktop/internal/workbench/search_replace.go | 1 + desktop/internal/workbench/semantic_tokens.go | 4 +- desktop/internal/workbench/settings.go | 31 +- .../internal/workbench/settings_ide_api.go | 2 +- .../workbench/settings_plugin_actions.go | 10 +- .../workbench/settings_plugin_effects.go | 2 +- .../workbench/settings_plugin_restart.go | 2 +- .../internal/workbench/settings_plugins.go | 20 +- .../internal/workbench/settings_toolchains.go | 10 +- desktop/internal/workbench/shelf.go | 8 +- desktop/internal/workbench/startup_sweep.go | 6 +- desktop/internal/workbench/startup_test.go | 2 +- desktop/internal/workbench/stash.go | 6 +- desktop/internal/workbench/status_items.go | 1 + desktop/internal/workbench/tabdrag.go | 3 +- desktop/internal/workbench/tasks.go | 12 +- .../internal/workbench/terminal_commands.go | 1 + desktop/internal/workbench/terminal_find.go | 3 +- desktop/internal/workbench/terminals.go | 3 +- desktop/internal/workbench/tests.go | 6 +- desktop/internal/workbench/title_run.go | 6 +- desktop/internal/workbench/updates.go | 43 ++- desktop/internal/workbench/vcs.go | 28 +- desktop/internal/workbench/viewer.go | 2 +- desktop/internal/workbench/viewer_image.go | 1 + desktop/internal/workbench/welcome_view.go | 2 +- desktop/internal/workbench/window_sessions.go | 4 +- .../workbench/workbench_background.go | 8 +- desktop/internal/workbench/worktree_window.go | 1 + shared/i18n/locales/en-US.json | 2 + shared/i18n/locales/zh-CN.json | 2 + shared/i18n/messages.json | 14 + 179 files changed, 3996 insertions(+), 494 deletions(-) create mode 100644 desktop/internal/core/origin.go create mode 100644 desktop/internal/core/origin_test.go create mode 100644 desktop/internal/core/plugin_operation.go create mode 100644 desktop/internal/core/plugin_operation_test.go create mode 100644 desktop/internal/logwindow/operation_test.go create mode 100644 desktop/internal/pluginbackend/log_facts_test.go create mode 100644 desktop/internal/pluginbackend/trace.go create mode 100644 desktop/internal/pluginbackend/trace_test.go create mode 100644 desktop/internal/pluginservice/operations.go create mode 100644 desktop/internal/pluginservice/operations_test.go create mode 100644 desktop/internal/workbench/build_command_record_test.go create mode 100644 desktop/internal/workbench/debug_adapter_start.go create mode 100644 desktop/internal/workbench/debug_adapter_start_test.go create mode 100644 desktop/internal/workbench/diagnostics_watch_test.go create mode 100644 desktop/internal/workbench/operation.go create mode 100644 desktop/internal/workbench/operation_test.go create mode 100644 desktop/internal/workbench/plugin_log_directory_test.go create mode 100644 desktop/internal/workbench/plugin_operation_record_test.go diff --git a/desktop/internal/core/client.go b/desktop/internal/core/client.go index 41e7438521..af1a5895d8 100644 --- a/desktop/internal/core/client.go +++ b/desktop/internal/core/client.go @@ -32,6 +32,8 @@ type requestEnvelope struct { Payload any `json:"payload"` // GitExecution is the request's Git policy, nil for Core's defaults. GitExecution *gitExecution `json:"gitExecution,omitempty"` + // Origin is the user action the request belongs to, nil for none (see Origin). + Origin *requestOrigin `json:"origin,omitempty"` } // gitExecution is the part of a request's Git policy the client sets (GitExecutionOptions in @@ -105,6 +107,7 @@ func (c *Client) execute(ctx context.Context, command string, payload, result an Command: command, Payload: payload, GitExecution: gitExecutionOf(ctx, command), + Origin: requestOriginOf(ctx), }) if err != nil { return nil, &Error{ diff --git a/desktop/internal/core/log_sites_test.go b/desktop/internal/core/log_sites_test.go index 2de4029e84..62481e122b 100644 --- a/desktop/internal/core/log_sites_test.go +++ b/desktop/internal/core/log_sites_test.go @@ -61,7 +61,8 @@ func TestEveryLoggedEventIsAcceptedByTheKernel(t *testing.T) { } // The scan must keep finding the calls it was written against, or a change to how the // client logs would make this test pass by checking nothing. - for _, event := range []string{"app.session.started", "app.action.performed", "app.notification.operation_failed", "app.background.operation_failed"} { + for _, event := range []string{"app.session.started", "app.action.performed", "app.notification.operation_failed", + "app.notification.operation_rejected", "app.background.operation_failed", "app.settings.decode_failed"} { if !seen[event] { t.Errorf("the scan found no call that logs %s", event) } @@ -122,6 +123,11 @@ func forwardedLogEvents(t *testing.T, scan *logScan) map[string][]logSite { {level: LevelWarn, event: scan.constant(t, "internal/termview", "eventStartFailed"), fields: errorKeys("stage")}, {level: LevelDebug, event: scan.constant(t, "internal/termview", "eventInputFailed"), fields: errorKeys("stage")}, }, + // recordEngineFact relays the facts Core attaches to plugin session events. Core picks + // them from its own catalog and checks them there before they leave it, so the client + // chooses none of them and has nothing to list; copying Core's choice here would only + // drift from it. + "internal/workbench.recordEngineFact": nil, } } diff --git a/desktop/internal/core/origin.go b/desktop/internal/core/origin.go new file mode 100644 index 0000000000..d52295fede --- /dev/null +++ b/desktop/internal/core/origin.go @@ -0,0 +1,71 @@ +package core + +import ( + "context" + "fmt" + "sync/atomic" +) + +// Origin is the user action a request belongs to. The client reports it with every request a +// context carrying it sends (RequestOrigin in the Rust protocol), and Core records the request +// under the action's operation, so the host's records of the action and Core's records of the +// requests it caused share one op. It is diagnostics only: Core never changes what a request +// does because of it, and drops a value of the wrong shape instead of failing the request. +type Origin struct { + // Operation correlates the records of the action; NewOperation makes one. Empty means the + // request belongs to no action. + Operation string + // Trigger is the stable id of the action, such as command.git.commit; Core keeps it when it + // is a catalog token: letters, digits and ._:/-$, at most 64 bytes. + Trigger string +} + +type originKey struct{} + +// WithOrigin returns a context whose requests belong to origin. An origin without an operation +// leaves ctx as it is. +func WithOrigin(ctx context.Context, origin Origin) context.Context { + if origin.Operation == "" { + return ctx + } + return context.WithValue(ctx, originKey{}, origin) +} + +// OriginOf is the action the requests of ctx belong to; the zero Origin for none. +func OriginOf(ctx context.Context) Origin { + origin, _ := ctx.Value(originKey{}).(Origin) + return origin +} + +var nextOperation atomic.Uint64 + +// NewOperation returns an operation id unique in the process, of the shape Core accepts for an +// op: letters, digits and ._:/@+-, at most 128 bytes. +func NewOperation() string { + return fmt.Sprintf("action-%d", nextOperation.Add(1)) +} + +// requestOrigin is the origin of one request on the wire (RequestOrigin in the Rust protocol). +type requestOrigin struct { + // Source is "user" for a request of an action and "background" for an automatic refresh. + // Core decodes it as an enum, so it never carries another value. + Source string `json:"source,omitempty"` + Trigger string `json:"trigger,omitempty"` + Operation string `json:"operation,omitempty"` +} + +// requestOriginOf is the origin a request of ctx reports, nil when there is nothing to report. +// An automatic refresh is background even when an action started it: Core keeps the internal +// queries of a background request silent, as the refresh asks. +func requestOriginOf(ctx context.Context) *requestOrigin { + origin := OriginOf(ctx) + refresh, _ := ctx.Value(gitRefreshKey{}).(bool) + switch { + case origin.Operation == "" && !refresh: + return nil + case refresh: + return &requestOrigin{Source: "background", Trigger: origin.Trigger, Operation: origin.Operation} + default: + return &requestOrigin{Source: "user", Trigger: origin.Trigger, Operation: origin.Operation} + } +} diff --git a/desktop/internal/core/origin_test.go b/desktop/internal/core/origin_test.go new file mode 100644 index 0000000000..d112b196be --- /dev/null +++ b/desktop/internal/core/origin_test.go @@ -0,0 +1,82 @@ +package core + +import ( + "context" + "encoding/json" + "testing" +) + +// TestRequestOriginReportsTheActionAndItsSource checks what each kind of context reports: nothing +// without an action, the action as a user request, and an automatic refresh as background even +// when an action started it. +func TestRequestOriginReportsTheActionAndItsSource(t *testing.T) { + ctx := context.Background() + action := Origin{Operation: "action-7", Trigger: "command.git.commit"} + cases := []struct { + name string + ctx context.Context + want string + }{ + {"no action", ctx, `null`}, + {"an origin without an operation", WithOrigin(ctx, Origin{Trigger: "command.git.commit"}), `null`}, + {"an action", WithOrigin(ctx, action), `{"source":"user","trigger":"command.git.commit","operation":"action-7"}`}, + {"a refresh", AutomaticRefresh(ctx), `{"source":"background"}`}, + {"a refresh an action started", AutomaticRefresh(WithOrigin(ctx, action)), `{"source":"background","trigger":"command.git.commit","operation":"action-7"}`}, + } + for _, c := range cases { + encoded, err := json.Marshal(requestOriginOf(c.ctx)) + if err != nil { + t.Fatalf("%s: %v", c.name, err) + } + if string(encoded) != c.want { + t.Errorf("%s: origin = %s, want %s", c.name, encoded, c.want) + } + } + if got := OriginOf(WithOrigin(ctx, action)); got != action { + t.Errorf("OriginOf = %+v, want %+v", got, action) + } +} + +// TestCoreRecordsTheRequestsOfAnActionUnderItsOp sends failing requests with the real kernel and +// reads back the terminal facts Core recorded for them: each carries the action's op, trigger +// and source, so the host's records of an action and Core's records of its requests share an op. +func TestCoreRecordsTheRequestsOfAnActionUnderItsOp(t *testing.T) { + c := NewClient() + ctx := context.Background() + if err := c.ConfigureCoreEvents(ctx, false, nil); err != nil { + t.Fatalf("ConfigureCoreEvents: %v", err) + } + if _, err := c.DrainCoreEvents(ctx); err != nil { + t.Fatalf("DrainCoreEvents: %v", err) + } + user, refresh := NewOperation(), NewOperation() + if user == refresh { + t.Fatalf("NewOperation returned %q twice", user) + } + const command = "test.noSuchCommand" + if err := c.Execute(WithOrigin(ctx, Origin{Operation: user, Trigger: "test.origin"}), command, nil, nil); err == nil { + t.Fatalf("%s succeeded", command) + } + if err := c.Execute(AutomaticRefresh(WithOrigin(ctx, Origin{Operation: refresh, Trigger: "test.refresh"})), command, nil, nil); err == nil { + t.Fatalf("%s succeeded", command) + } + drained, err := c.DrainCoreEvents(ctx) + if err != nil { + t.Fatalf("DrainCoreEvents: %v", err) + } + found := map[string]CoreEvent{} + for _, event := range drained.Events { + if event.Event == "app.core.request.failed" && (event.Op == user || event.Op == refresh) { + found[event.Op] = event + } + } + for op, want := range map[string][2]string{user: {"user", "test.origin"}, refresh: {"background", "test.refresh"}} { + event, ok := found[op] + if !ok { + t.Fatalf("no app.core.request.failed under op %s in %+v", op, drained.Events) + } + if event.Level != LevelWarn || event.Fields["method"] != command || event.Fields["source"] != want[0] || event.Fields["trigger"] != want[1] { + t.Errorf("op %s: %+v, want a WARN of %s with source %s and trigger %s", op, event, command, want[0], want[1]) + } + } +} diff --git a/desktop/internal/core/plugin_operation.go b/desktop/internal/core/plugin_operation.go new file mode 100644 index 0000000000..2eb65f5c33 --- /dev/null +++ b/desktop/internal/core/plugin_operation.go @@ -0,0 +1,189 @@ +package core + +import ( + "context" + "errors" + "sync/atomic" + "time" +) + +// PluginOperationName is one row of Core's table of declarative plugin contributions: work a +// plugin declares in its manifest that the host or a Core engine runs, so no plugin process can +// report it through lithe/log. The set is closed; Core refuses any other token. +type PluginOperationName string + +// The contributions the host runs, written as Core's tokens. A command contribution reuses the +// SDK method name, so a declarative plugin logs the same work the way an SDK-backed one does. +const ( + // OperationLanguageServerStart is a languageServers[] start, from resolving the launch to + // the initialize result. The host records what fails before it hands the start to Core. + OperationLanguageServerStart PluginOperationName = "languageServer/start" + // OperationDebugAdapterStart is a debugAdapters[] start, up to the adapter being reachable. + OperationDebugAdapterStart PluginOperationName = "debugAdapter/start" + // OperationBuildModel is one model load of a buildSystems[].model command source. + OperationBuildModel PluginOperationName = "lithe/build/model" + // OperationBuildDependencies is one dependency tree load of a command source. + OperationBuildDependencies PluginOperationName = "lithe/build/dependencies" +) + +// PluginStage is where an attempt failed. Core turns it into a code through the contribution's +// lifecycle, and refuses a stage the lifecycle cannot reach: a process start has no plan or +// decode stage, and a command run has no initialize stage. +type PluginStage string + +// The stages, written as Core's tokens. +const ( + // StagePlan: the declared command plan could not be prepared. + StagePlan PluginStage = "plan" + // StageResolve: the declared executable or launch input could not be resolved. + StageResolve PluginStage = "resolve" + // StageLaunch: the resolved process could not be started. + StageLaunch PluginStage = "launch" + // StageInitialize: the protocol handshake failed after the process started. + StageInitialize PluginStage = "initialize" + // StageTimeout: the attempt ran past its deadline. + StageTimeout PluginStage = "timeout" + // StageExit: the process exited before it was ready, or a command exited nonzero. + StageExit PluginStage = "exit" + // StageDecode: the command output was not a valid document for the contract. + StageDecode PluginStage = "decode" +) + +// PluginOperation is the payload of diagnostics.recordPluginOperation: one terminal result of a +// declarative contribution the host ran. It carries no plugin output, path or error text. +type PluginOperation struct { + PluginID string `json:"pluginId"` + Operation PluginOperationName `json:"operation"` + // Outcome is "finished" or "failed". + Outcome string `json:"outcome"` + // Stage is set exactly when the attempt failed; Core refuses it on a finished one. + Stage PluginStage `json:"stage,omitempty"` + // DurationMs is the attempt's monotonic duration. + DurationMs int64 `json:"durationMs"` + // OperationID is the op that correlates the attempt's other records. An absent one is + // left out, since Core refuses an explicit null. + OperationID string `json:"operationId,omitempty"` +} + +// StartupOperation hands a language-server start the host began to Core, which then records +// its single result. It is the startupOperation of lsp.startServer. +type StartupOperation struct { + PluginID string `json:"pluginId"` + OperationID string `json:"operationId"` + // ElapsedMs is the time the host spent on the attempt before the handoff; Core adds its own. + ElapsedMs int64 `json:"elapsedMs"` +} + +// PluginAttempt times one attempt of a declarative contribution and makes sure it yields one +// result at most: the host's own, or Core's after a handoff. It is safe from any goroutine. +type PluginAttempt struct { + pluginID string + operation PluginOperationName + operationID string + started time.Time + // ended is set by the first result or handoff; every later one is ignored. + ended atomic.Bool + // handedOff tells that Core owns the result. + handedOff atomic.Bool +} + +// StartPluginAttempt starts timing an attempt of plugin's operation. operationID is the op of +// the action the attempt runs for; an empty one, or one outside the grammar Core accepts for an +// operation ID, gets a fresh op, since a handoff needs one. +func StartPluginAttempt(pluginID string, operation PluginOperationName, operationID string) *PluginAttempt { + if !validAttemptID(operationID) { + operationID = NewOperation() + } + return &PluginAttempt{pluginID: pluginID, operation: operation, operationID: operationID, started: time.Now()} +} + +// OperationID is the op the attempt's result is recorded under. +func (a *PluginAttempt) OperationID() string { + if a == nil { + return "" + } + return a.operationID +} + +// HandOff gives the attempt to Core and returns the startupOperation that does so. Nothing the +// host reports afterwards is recorded. It returns nil for a nil attempt or one already ended. +func (a *PluginAttempt) HandOff() *StartupOperation { + if a == nil || !a.ended.CompareAndSwap(false, true) { + return nil + } + a.handedOff.Store(true) + return &StartupOperation{PluginID: a.pluginID, OperationID: a.operationID, ElapsedMs: a.elapsed()} +} + +// HandedOff reports whether Core owns the attempt's result. +func (a *PluginAttempt) HandedOff() bool { + return a != nil && a.handedOff.Load() +} + +// Ended returns the result of an attempt that stopped with err, failing at stage, and whether +// it may be recorded. A nil err finishes the attempt. The attempt yields nothing when it was +// already ended or handed off, and when the user cancelled it: Core never records a +// cancellation. A deadline that ended it is a timeout, whatever stage it was at. +func (a *PluginAttempt) Ended(ctx context.Context, stage PluginStage, err error) (PluginOperation, bool) { + if a == nil { + return PluginOperation{}, false + } + if err != nil && (errors.Is(err, context.Canceled) || errors.Is(ctx.Err(), context.Canceled)) { + return PluginOperation{}, false + } + if !a.ended.CompareAndSwap(false, true) { + return PluginOperation{}, false + } + result := PluginOperation{ + PluginID: a.pluginID, + Operation: a.operation, + Outcome: "finished", + DurationMs: a.elapsed(), + OperationID: a.operationID, + } + if err == nil { + return result, true + } + if errors.Is(err, context.DeadlineExceeded) || errors.Is(ctx.Err(), context.DeadlineExceeded) { + stage = StageTimeout + } + result.Outcome, result.Stage = "failed", stage + return result, true +} + +// Abandon ends the attempt without a result, for one the user stopped or a newer one replaced. +func (a *PluginAttempt) Abandon() { + if a != nil { + a.ended.Store(true) + } +} + +func (a *PluginAttempt) elapsed() int64 { + return time.Since(a.started).Milliseconds() +} + +// validAttemptID reports whether Core takes id as an operation ID: it must be in the SDK +// operationId grammar (1-128 ASCII letters, digits and ._:/-$) and also a bare record identity +// (letters, digits and ._:/@+-), so only letters, digits and ._:/- are left. +func validAttemptID(id string) bool { + if id == "" || len(id) > 128 { + return false + } + for i := 0; i < len(id); i++ { + switch b := id[i]; { + case 'a' <= b && b <= 'z', 'A' <= b && b <= 'Z', '0' <= b && b <= '9': + case b == '.' || b == '_' || b == ':' || b == '/' || b == '-': + default: + return false + } + } + return true +} + +// RecordPluginOperation records one terminal result of a declarative plugin contribution the +// host ran. Core puts it on the plugin's plugins//host channel as plugins.operation.finished +// or plugins.operation.failed, next to what SDK-backed plugins report. +func (c *Client) RecordPluginOperation(ctx context.Context, operation PluginOperation) error { + _, err := executeLog[struct{}](ctx, c, "diagnostics.recordPluginOperation", operation) + return err +} diff --git a/desktop/internal/core/plugin_operation_test.go b/desktop/internal/core/plugin_operation_test.go new file mode 100644 index 0000000000..e338440672 --- /dev/null +++ b/desktop/internal/core/plugin_operation_test.go @@ -0,0 +1,211 @@ +package core + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" +) + +// TestPluginOperationWireShape checks the payload Core's strict ingress takes: a finished +// result names no stage, and an absent operation ID is left out rather than sent as null. +func TestPluginOperationWireShape(t *testing.T) { + for _, tc := range []struct { + operation PluginOperation + want string + }{ + { + PluginOperation{PluginID: "io.example.go", Operation: OperationBuildModel, Outcome: "finished", DurationMs: 12, OperationID: "action-3"}, + `{"pluginId":"io.example.go","operation":"lithe/build/model","outcome":"finished","durationMs":12,"operationId":"action-3"}`, + }, + { + PluginOperation{PluginID: "io.example.go", Operation: OperationDebugAdapterStart, Outcome: "failed", Stage: StageLaunch}, + `{"pluginId":"io.example.go","operation":"debugAdapter/start","outcome":"failed","stage":"launch","durationMs":0}`, + }, + } { + got, err := json.Marshal(tc.operation) + if err != nil { + t.Fatal(err) + } + if string(got) != tc.want { + t.Fatalf("payload = %s, want %s", got, tc.want) + } + } + handoff, err := json.Marshal(PluginBackendStart{StartupOperation: &StartupOperation{PluginID: "p", OperationID: "action-1", ElapsedMs: 4}}) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(handoff), `"startupOperation":{"pluginId":"p","operationId":"action-1","elapsedMs":4}`) { + t.Fatalf("lsp.startServer carries the handoff as %s", handoff) + } + plain, err := json.Marshal(PluginBackendStart{}) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(plain), "startupOperation") { + t.Fatalf("a start without an attempt still names one: %s", plain) + } +} + +// TestPluginAttemptYieldsOneResult checks that an attempt yields one result at most, whoever +// ends it first, that a handoff leaves the host nothing to record, that a cancellation is +// never a result, and that a deadline is a timeout whatever stage it stopped. +func TestPluginAttemptYieldsOneResult(t *testing.T) { + ctx := context.Background() + + attempt := StartPluginAttempt("p", OperationBuildModel, "action-9") + finished, ok := attempt.Ended(ctx, StageExit, nil) + if !ok || finished.Outcome != "finished" || finished.Stage != "" || finished.OperationID != "action-9" || finished.PluginID != "p" || finished.Operation != OperationBuildModel { + t.Fatalf("finished attempt = %+v, %v", finished, ok) + } + if again, ok := attempt.Ended(ctx, StageExit, errors.New("late")); ok { + t.Fatalf("an ended attempt yielded a second result %+v", again) + } + if attempt.HandOff() != nil { + t.Fatal("an ended attempt was handed to Core") + } + + failed, ok := StartPluginAttempt("p", OperationBuildModel, "action-9").Ended(ctx, StageDecode, errors.New("bad output")) + if !ok || failed.Outcome != "failed" || failed.Stage != StageDecode { + t.Fatalf("failed attempt = %+v, %v", failed, ok) + } + + timed, ok := StartPluginAttempt("p", OperationBuildModel, "action-9").Ended(ctx, StageExit, context.DeadlineExceeded) + if !ok || timed.Stage != StageTimeout { + t.Fatalf("an attempt past its deadline = %+v, %v, want a timeout", timed, ok) + } + expired, stop := context.WithTimeout(ctx, 0) + defer stop() + <-expired.Done() + if timed, ok := StartPluginAttempt("p", OperationBuildModel, "action-9").Ended(expired, StageExit, errors.New("signal: killed")); !ok || timed.Stage != StageTimeout { + t.Fatalf("an attempt whose context expired = %+v, %v, want a timeout", timed, ok) + } + + cancelled := StartPluginAttempt("p", OperationBuildModel, "action-9") + if result, ok := cancelled.Ended(ctx, StageExit, context.Canceled); ok { + t.Fatalf("a cancellation was recorded as %+v", result) + } + stopped, cancel := context.WithCancel(ctx) + cancel() + if result, ok := StartPluginAttempt("p", OperationBuildModel, "action-9").Ended(stopped, StageExit, errors.New("signal: killed")); ok { + t.Fatalf("an attempt the user stopped was recorded as %+v", result) + } + // A cancellation leaves the attempt open, so the result of the work that went on anyway + // is still the attempt's one result. + if _, ok := cancelled.Ended(ctx, StageExit, nil); !ok { + t.Fatal("a cancelled report used up the attempt") + } + + abandoned := StartPluginAttempt("p", OperationBuildModel, "action-9") + abandoned.Abandon() + if result, ok := abandoned.Ended(ctx, StageExit, nil); ok { + t.Fatalf("an abandoned attempt was recorded as %+v", result) + } + + handed := StartPluginAttempt("p", OperationLanguageServerStart, "action-9") + handoff := handed.HandOff() + if handoff == nil || handoff.PluginID != "p" || handoff.OperationID != "action-9" || handoff.ElapsedMs < 0 || !handed.HandedOff() { + t.Fatalf("handoff = %+v", handoff) + } + if handed.HandOff() != nil { + t.Fatal("an attempt was handed to Core twice") + } + if result, ok := handed.Ended(ctx, StageResolve, errors.New("refused")); ok { + t.Fatalf("the host recorded %+v for an attempt Core owns", result) + } + + var none *PluginAttempt + if none.HandOff() != nil || none.HandedOff() || none.OperationID() != "" { + t.Fatal("a nil attempt is not inert") + } + if _, ok := none.Ended(ctx, StageExit, nil); ok { + t.Fatal("a nil attempt yielded a result") + } + none.Abandon() +} + +// TestPluginAttemptKeepsOnlyOperationIDsCoreTakes checks that an op Core would refuse as an +// operation ID is replaced by a fresh one, since a handoff and a correlated result need one. +func TestPluginAttemptKeepsOnlyOperationIDsCoreTakes(t *testing.T) { + for _, kept := range []string{"action-12", "a.b_c:d/e-f", strings.Repeat("a", 128)} { + if got := StartPluginAttempt("p", OperationBuildModel, kept).OperationID(); got != kept { + t.Fatalf("op %q became %q", kept, got) + } + } + for _, replaced := range []string{"", "with space", "dollar$", "at@sign", "plus+", strings.Repeat("a", 129), "é"} { + got := StartPluginAttempt("p", OperationBuildModel, replaced).OperationID() + if got == replaced || !strings.HasPrefix(got, "action-") { + t.Fatalf("op %q was kept as %q, want a fresh one", replaced, got) + } + } +} + +// TestCoreTakesEveryResultTheHostRecords sends the real kernel every result the host can +// record, for each contribution and each stage its lifecycle reaches, and reads back the facts: +// each lands on the plugin's host channel under its op with the stage's code. A stage the +// lifecycle cannot reach is refused, so the host's stage choices are checked against Core's +// own table rather than a copy of it. +func TestCoreTakesEveryResultTheHostRecords(t *testing.T) { + c := NewClient() + ctx := context.Background() + if _, err := c.DrainCoreEvents(ctx); err != nil { + t.Fatalf("DrainCoreEvents: %v", err) + } + processStart := map[PluginStage]string{ + StageResolve: "host.executableUnavailable", StageLaunch: "host.launchFailed", StageInitialize: "host.initializeFailed", + StageTimeout: "host.timedOut", StageExit: "host.exitedEarly", + } + commandRun := map[PluginStage]string{ + StagePlan: "host.planFailed", StageResolve: "host.executableUnavailable", StageLaunch: "host.launchFailed", + StageTimeout: "host.timedOut", StageExit: "host.commandFailed", StageDecode: "host.outputInvalid", + } + contributions := map[PluginOperationName]map[PluginStage]string{ + OperationLanguageServerStart: processStart, OperationDebugAdapterStart: processStart, + OperationBuildModel: commandRun, OperationBuildDependencies: commandRun, + } + allStages := []PluginStage{StagePlan, StageResolve, StageLaunch, StageInitialize, StageTimeout, StageExit, StageDecode} + want := map[string]string{} // op -> code, "" for finished + for operation, codes := range contributions { + finished := NewOperation() + if err := c.RecordPluginOperation(ctx, PluginOperation{PluginID: "io.example.go", Operation: operation, Outcome: "finished", DurationMs: 1, OperationID: finished}); err != nil { + t.Fatalf("%s finished: %v", operation, err) + } + want[finished] = "" + for _, stage := range allStages { + op := NewOperation() + err := c.RecordPluginOperation(ctx, PluginOperation{PluginID: "io.example.go", Operation: operation, Outcome: "failed", Stage: stage, DurationMs: 1, OperationID: op}) + code, reachable := codes[stage] + var refused *LogError + switch { + case reachable && err != nil: + t.Fatalf("%s failed at %s: %v", operation, stage, err) + case reachable: + want[op] = code + case !errors.As(err, &refused) || refused.Code != -32064: + t.Fatalf("%s at unreachable stage %s answered %v, want -32064", operation, stage, err) + } + } + } + drained, err := c.DrainCoreEvents(ctx) + if err != nil { + t.Fatalf("DrainCoreEvents: %v", err) + } + for _, event := range drained.Events { + code, ok := want[event.Op] + if !ok { + continue + } + delete(want, event.Op) + wantEvent := "plugins.operation.failed" + if code == "" { + wantEvent = "plugins.operation.finished" + } + if event.Event != wantEvent || event.Channel != "plugins/io.example.go/host" || (code != "" && event.Fields["code"] != code) { + t.Errorf("op %s: %+v, want %s on plugins/io.example.go/host with code %q", event.Op, event, wantEvent, code) + } + } + if len(want) != 0 { + t.Fatalf("Core recorded no fact for %d results: %v", len(want), want) + } +} diff --git a/desktop/internal/core/plugin_session.go b/desktop/internal/core/plugin_session.go index 910840425a..cb2d7065ab 100644 --- a/desktop/internal/core/plugin_session.go +++ b/desktop/internal/core/plugin_session.go @@ -29,6 +29,9 @@ type PluginBackendStart struct { InitializeTimeoutMilliseconds int `json:"initializeTimeoutMilliseconds,omitempty"` RequestTimeoutMilliseconds int `json:"requestTimeoutMilliseconds,omitempty"` ShutdownTimeoutMilliseconds int `json:"shutdownTimeoutMilliseconds,omitempty"` + // StartupOperation hands a declarative language-server start to Core, which records its + // one result from here on. Core takes it only for the language-server role. + StartupOperation *StartupOperation `json:"startupOperation,omitempty"` } // PluginHostOptions are what the host declares about the services it grants one session. @@ -443,6 +446,17 @@ func (c *Client) StopPluginBackend(ctx context.Context, session string) error { }{session}, nil) } +// SetDetailedDiagnostics turns the upstream trace of one running session on or off: Core sends +// the server $/setTrace verbose or off, and only a session with it on reports trace summaries. +// Before the startup handshake ends Core keeps the value and sends it after initialized. A +// session that is no longer running is refused with invalid_request. +func (c *Client) SetDetailedDiagnostics(ctx context.Context, session string, enabled bool) error { + return c.Execute(ctx, "lsp.setDetailedDiagnostics", struct { + SessionID string `json:"sessionId"` + Enabled bool `json:"enabled"` + }{session, enabled}, nil) +} + // DestroyPluginBackend disposes a terminal session. It must not race stop. func (c *Client) DestroyPluginBackend(ctx context.Context, session string) error { return c.Execute(ctx, "lsp.destroyServer", struct { diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 73274e64b5..1fc68855e6 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -477,6 +477,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.files.copyFailed": "Could not copy the path: {reason}", "desktop.files.create": "Create", "desktop.files.createFailed": "Could not create the item: {reason}", + "desktop.files.crossBoundaryMove": "Moving or renaming between WSL distributions, or between a distribution and a local folder, is not supported", "desktop.files.cut": "Cut", "desktop.files.delete": "Delete…", "desktop.files.deleteFailed": "Could not delete the item: {reason}", @@ -1035,6 +1036,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.notifications.repeated": "{message} ({count})", "desktop.notifications.title": "Notifications", "desktop.notifications.unread": "Notifications, {count} unread", + "desktop.notifications.viewLogs": "View Logs", "desktop.outline.empty": "No symbols in this file.", "desktop.outline.failed": "Could not get the structure of this file.", "desktop.outline.filter": "Filter symbols", @@ -3065,6 +3067,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.files.copyFailed": "无法复制路径:{reason}", "desktop.files.create": "创建", "desktop.files.createFailed": "无法创建条目:{reason}", + "desktop.files.crossBoundaryMove": "不支持在不同 WSL 发行版之间、或在发行版与本地文件夹之间移动或重命名", "desktop.files.cut": "剪切", "desktop.files.delete": "删除…", "desktop.files.deleteFailed": "无法删除条目:{reason}", @@ -3623,6 +3626,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.notifications.repeated": "{message}({count})", "desktop.notifications.title": "通知", "desktop.notifications.unread": "通知,{count} 条未读", + "desktop.notifications.viewLogs": "查看日志", "desktop.outline.empty": "此文件没有符号。", "desktop.outline.failed": "无法获取此文件的结构。", "desktop.outline.filter": "筛选符号", diff --git a/desktop/internal/logstore/store.go b/desktop/internal/logstore/store.go index 7ec938756a..f321058d75 100644 --- a/desktop/internal/logstore/store.go +++ b/desktop/internal/logstore/store.go @@ -243,6 +243,12 @@ type Store struct { subsMu sync.Mutex subscribers map[*subscriber]struct{} + // watchMu orders the detailed-diagnostics watchers against the gate changes they are told + // about, so a watcher that joins while the gate changes still ends on the current value. + watchMu sync.Mutex + watchers map[*func(on bool)]struct{} + watchedOn bool + // Everything below is owned by the writer goroutine (and by Open before it starts). sequence uint64 previous *core.LogEvent @@ -565,6 +571,37 @@ func (s *Store) SessionPath() string { return s.sessionPath } +// PluginFilesDirectory creates and returns this session's private file directory of a plugin, +// sessions//plugins//files below Directory. The kernel derives it from the +// plugin's host channel and refuses an id that is not a plugin identity. A plugin process +// receives it as ${logDir}, so what the plugin writes there is a file of this session: the +// retention plan's plugin file budget covers it and Clear Logs removes it. The directory is +// made 0700 and no symbolic link on the way is followed. A process started before the log +// directory changed keeps writing where it was told; the old directory keeps its files. +func (s *Store) PluginFilesDirectory(ctx context.Context, pluginID string) (string, error) { + resolved, err := s.kernel.ResolveLogChannel(ctx, "plugins/"+pluginID+"/host", 0, nil) + if err != nil { + return "", err + } + if resolved.PluginFilesPath == "" { + return "", errUnsafePath + } + s.mu.Lock() + root, session := s.directory, s.sessionPath + s.mu.Unlock() + if root == "" || session == "" { + return "", errNoDirectory + } + target, err := safePath(root, session+"/"+strings.TrimSuffix(resolved.PluginFilesPath, "/")) + if err != nil { + return "", err + } + if err := os.MkdirAll(target, 0o700); err != nil { + return "", err + } + return target, nil +} + // Stats reports how many events were dropped, from a full queue or with a batch the kernel // could not encode, and how many writes or maintenance steps failed since the process started. func (s *Store) Stats() (dropped, writeFailures int) { @@ -866,12 +903,44 @@ func (s *Store) syncGate(ctx context.Context) { return } s.gateKnown, s.gateOn = true, on + s.tellWatchers(on) if err := s.kernel.ConfigureCoreEvents(ctx, on, nil); err != nil { s.fail() s.Emit(core.LevelWarn, "app.logging.diagnostics_failed", "", core.LogErrorFields(err)) } } +// WatchDiagnostics tells watch whether detailed diagnostics are on, at once, and again every +// time they turn on or off, including when they expire and when the store stops, until the +// returned function is called. The later calls run on the writer goroutine, so watch must +// return quickly and must not call the store. +func (s *Store) WatchDiagnostics(watch func(on bool)) (stop func()) { + key := &watch + s.watchMu.Lock() + if s.watchers == nil { + s.watchers = map[*func(on bool)]struct{}{} + } + s.watchers[key] = struct{}{} + watch(s.watchedOn) + s.watchMu.Unlock() + return func() { + s.watchMu.Lock() + delete(s.watchers, key) + s.watchMu.Unlock() + } +} + +// tellWatchers hands a change of the DEBUG gate to the diagnostics watchers. It runs on the +// writer goroutine. +func (s *Store) tellWatchers(on bool) { + s.watchMu.Lock() + defer s.watchMu.Unlock() + s.watchedOn = on + for watch := range s.watchers { + (*watch)(on) + } +} + // armExpiry points the one-shot expiry timer at until, which is remaining away. func (s *Store) armExpiry(until time.Time, remaining time.Duration) { if s.expiry != nil && s.expiryAt.Equal(until) { diff --git a/desktop/internal/logstore/store_test.go b/desktop/internal/logstore/store_test.go index 455cb8648f..12c1093bc6 100644 --- a/desktop/internal/logstore/store_test.go +++ b/desktop/internal/logstore/store_test.go @@ -589,6 +589,57 @@ func TestDiagnosticsGateDebugEventsAndExpire(t *testing.T) { } } +// TestDiagnosticsWatchersFollowTheGate checks that a watcher learns the current state as it +// joins and then every change of the switch, including expiry and the store stopping, that a +// repeated choice is not told again, and that a watcher that left is not told any more. +func TestDiagnosticsWatchersFollowTheGate(t *testing.T) { + s, clock, _ := openStore(t, nil) + var mu sync.Mutex + var seen, late []bool + record := func(into *[]bool) func(bool) { + return func(on bool) { + mu.Lock() + *into = append(*into, on) + mu.Unlock() + } + } + told := func(from *[]bool) []bool { + mu.Lock() + defer mu.Unlock() + return slices.Clone(*from) + } + + stop := s.WatchDiagnostics(record(&seen)) + if got := told(&seen); !slices.Equal(got, []bool{false}) { + t.Fatalf("a watcher joining while diagnostics are off was told %v, want [false]", got) + } + s.ConfigureDiagnostics(true) + s.ConfigureDiagnostics(true) + if got := told(&seen); !slices.Equal(got, []bool{false, true}) { + t.Fatalf("turning diagnostics on twice told %v, want one true", got) + } + stopLate := s.WatchDiagnostics(record(&late)) + if got := told(&late); !slices.Equal(got, []bool{true}) { + t.Fatalf("a watcher joining while diagnostics are on was told %v, want [true]", got) + } + stopLate() + + clock.Advance(16 * time.Minute) + flush(t, s) + if got := told(&seen); !slices.Equal(got, []bool{false, true, false}) { + t.Fatalf("the window expiring told %v, want a final false", got) + } + s.ConfigureDiagnostics(true) + s.Close() + if got := told(&seen); !slices.Equal(got, []bool{false, true, false, true, false}) { + t.Fatalf("closing the store with diagnostics on told %v, want a final false", got) + } + if got := told(&late); !slices.Equal(got, []bool{true}) { + t.Fatalf("a watcher that left was told %v after leaving", got) + } + stop() +} + func TestStartupRetentionRemovesExpiredSessionsOnly(t *testing.T) { dir := t.TempDir() const stale, recent = "2026-09-01T00-00-00_deadbeef", "2026-11-01T00-00-00_cafebabe" @@ -646,6 +697,57 @@ func TestClearLogsRemovesFilesAndWritingContinues(t *testing.T) { } } +// A plugin's ${logDir} is a directory of the current session, so the retention plan counts +// what the plugin writes there and Clear Logs removes it. +func TestPluginFilesDirectoryIsASessionDirectory(t *testing.T) { + s, _, dir := openStore(t, nil) + ctx := context.Background() + got, err := s.PluginFilesDirectory(ctx, "io.example.plugin") + if err != nil { + t.Fatalf("PluginFilesDirectory: %v", err) + } + want := filepath.Join(dir, filepath.FromSlash(s.SessionPath()), "plugins", "io.example.plugin", "files") + if got != want { + t.Fatalf("PluginFilesDirectory = %q, want %q", got, want) + } + info, err := os.Stat(got) + if err != nil || !info.IsDir() { + t.Fatalf("the directory was not made: %v", err) + } + if runtime.GOOS != "windows" && info.Mode().Perm() != 0o700 { + t.Fatalf("the directory has mode %v, want 0700", info.Mode().Perm()) + } + plugin := filepath.Join(got, "server.log") + if err := os.WriteFile(plugin, []byte("plugin output\n"), 0o600); err != nil { + t.Fatal(err) + } + if files, err := inventory(dir); err != nil || !slices.ContainsFunc(files, func(f diskFile) bool { return f.path == plugin }) { + t.Fatalf("the inventory does not list the plugin's file: %v", err) + } + if err := s.ClearLogs(); err != nil { + t.Fatalf("ClearLogs: %v", err) + } + if _, err := os.Lstat(plugin); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("Clear Logs left the plugin's file: %v", err) + } + if again, err := s.PluginFilesDirectory(ctx, "io.example.plugin"); err != nil || again != got { + t.Fatalf("PluginFilesDirectory after clearing = %q, %v", again, err) + } + + if _, err := s.PluginFilesDirectory(ctx, "../escape"); err == nil { + t.Fatal("an id that is not a plugin identity was given a directory") + } + if runtime.GOOS != "windows" { + plugins := filepath.Join(dir, filepath.FromSlash(s.SessionPath()), "plugins") + if err := os.Symlink(t.TempDir(), filepath.Join(plugins, "io.example.linked")); err != nil { + t.Fatal(err) + } + if _, err := s.PluginFilesDirectory(ctx, "io.example.linked"); !errors.Is(err, errUnsafePath) { + t.Fatalf("PluginFilesDirectory through a symbolic link = %v, want errUnsafePath", err) + } + } +} + func TestCloseWritesWhatIsQueuedAndIsFinal(t *testing.T) { s, _, dir := openStore(t, nil) action(s, "last_words") diff --git a/desktop/internal/logwindow/model.go b/desktop/internal/logwindow/model.go index 84209cb2ad..a361307118 100644 --- a/desktop/internal/logwindow/model.go +++ b/desktop/internal/logwindow/model.go @@ -1270,6 +1270,22 @@ func (m *Model) compose(term core.LogFilterTerm) { }) } +// showOperation narrows the table to every record of one operation of this session, which a +// notice's View Logs asks for: the current session, no time limit, every channel and level, +// and an expression of only the op term, which the kernel writes. The filter field shows the +// term, so clearing it shows everything again. +func (m *Model) showOperation(op string) { + m.follows = false + m.changeQuery(func(q *windowQuery) { + q.Session = sessionCurrent + q.Since, q.Until = "", "" + q.ChannelPrefixes = []string{} + q.Levels = slices.Clone(allLevels) + q.Expression = "" + }) + m.compose(core.LogFilterTerm{Kind: "op", Value: op}) +} + // copyFormatted formats records in format, json or markdown, and puts the text on the // clipboard. Copies carry the description of the client; the details pane does not. func (m *Model) copyFormatted(records []core.LogRecord, format string) { diff --git a/desktop/internal/logwindow/operation_test.go b/desktop/internal/logwindow/operation_test.go new file mode 100644 index 0000000000..4788ea2b52 --- /dev/null +++ b/desktop/internal/logwindow/operation_test.go @@ -0,0 +1,68 @@ +package logwindow + +import ( + "context" + "slices" + "sync" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// termKernel writes a composed term the way the kernel does for an empty expression and +// records what it was asked to compose. +type termKernel struct { + *exportKernel + + mu sync.Mutex + asked []string +} + +func (k *termKernel) ComposeLogFilter(_ context.Context, expression string, term core.LogFilterTerm) (string, error) { + k.mu.Lock() + defer k.mu.Unlock() + k.asked = append(k.asked, expression) + return term.Kind + ":" + term.Value, nil +} + +func TestShowOperationNarrowsToTheOperationOfThisSession(t *testing.T) { + fixture := newExportFixture(t) + kernel := &termKernel{exportKernel: fixture.kernel} + m := fixture.model + m.opts.Kernel = kernel + m.prefs.Query.Session = sessionPrevious + m.prefs.Query.Since, m.prefs.Query.Until = formatInstant(1), formatInstant(2) + m.prefs.Query.ChannelPrefixes = []string{"git"} + m.prefs.Query.Levels = []core.LogLevel{core.LevelError} + m.prefs.Query.Expression = "level:error" + m.follows = true + + m.showOperation("action-7") + settle(t, m) + + q := m.prefs.Query + if q.Session != sessionCurrent || q.Since != "" || q.Until != "" { + t.Fatalf("session %q, range %q..%q; want the current session without a limit", q.Session, q.Since, q.Until) + } + if len(q.ChannelPrefixes) != 0 { + t.Fatalf("channels %v; want every channel", q.ChannelPrefixes) + } + if !slices.Equal(q.Levels, allLevels) { + t.Fatalf("levels %v; want %v", q.Levels, allLevels) + } + if q.Expression != "op:action-7" { + t.Fatalf("expression %q; want the op term alone", q.Expression) + } + kernel.mu.Lock() + asked := slices.Clone(kernel.asked) + kernel.mu.Unlock() + if !slices.Equal(asked, []string{""}) { + t.Fatalf("composed into %q; want the term composed into an empty expression", asked) + } + if m.follows { + t.Fatal("the table still follows new records after narrowing to an operation") + } + if m.expressionRevision == 0 { + t.Fatal("the filter field was not told the expression changed") + } +} diff --git a/desktop/internal/logwindow/window.go b/desktop/internal/logwindow/window.go index 30e6db43b8..dac35afef7 100644 --- a/desktop/internal/logwindow/window.go +++ b/desktop/internal/logwindow/window.go @@ -125,6 +125,23 @@ func (c *Controller) Open(application *app.Application) error { return nil } +// OpenOperation opens the window as Open does and narrows it to the records of one operation +// of this session. Like Open, it must run on a window thread of application; the window +// applies the filter on its own thread. +func (c *Controller) OpenOperation(application *app.Application, op string) error { + if err := c.Open(application); err != nil { + return err + } + c.mu.Lock() + current := c.current + c.mu.Unlock() + if current != nil && current.model != nil { + model := current.model + model.post(func() { model.showOperation(op) }) + } + return nil +} + // Close closes the open window, if any. It is safe from any goroutine. func (c *Controller) Close() { c.mu.Lock() diff --git a/desktop/internal/pluginbackend/log_facts_test.go b/desktop/internal/pluginbackend/log_facts_test.go new file mode 100644 index 0000000000..70e22c22bf --- /dev/null +++ b/desktop/internal/pluginbackend/log_facts_test.go @@ -0,0 +1,117 @@ +package pluginbackend + +import ( + "context" + "encoding/json" + "errors" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// loggedFact is one fact the runner handed to its sink. +type loggedFact struct { + level core.LogLevel + event string + fields map[string]any +} + +// factRecorder collects the facts a runner forwards; the runner calls it on the goroutine +// that serves or stops the session, which is the test's own here. +type factRecorder struct{ facts []loggedFact } + +func (r *factRecorder) record(level core.LogLevel, event string, fields map[string]any) { + r.facts = append(r.facts, loggedFact{level: level, event: event, fields: fields}) +} + +// TestServeForwardsEveryLogFactOnce checks that Serve hands each catalog fact Core attached +// to a runtime event to the sink exactly once, whatever the event's type, the exit included; +// that an event without a fact, or whose fact Core could not prepare, forwards nothing; and +// that numbers reach the sink as written rather than rounded through float64. +func TestServeForwardsEveryLogFactOnce(t *testing.T) { + kernel := &fakeKernel{events: [][]core.BackendEvent{{ + {Type: "log", Event: "lsp.stderr.received", Level: "DEBUG", Fields: json.RawMessage(`{"text":"warming up","bytes":9007199254740993}`)}, + {Type: "log", Message: "a line Core kept only for the v1 log"}, + {Type: "stateChanged", State: "running", Event: "lsp.session.updated", Level: "INFO"}, + {Type: "log", Level: "WARN", Fields: json.RawMessage(`{"text":"no id"}`)}, + {Type: "log", Event: "lsp.message.logged", Level: "INFO", Fields: json.RawMessage(`not json`)}, + }, { + {Type: EventExit, Event: "lsp.session.failed", Level: "ERROR", Fields: json.RawMessage(`{"stage":"exit"}`)}, + }}} + facts := &factRecorder{} + runner := New(kernel, echoServices(t)) + runner.SetLogFacts(facts.record) + if err := runner.Serve(context.Background(), Session{ID: "session-1"}, nil); err != nil { + t.Fatalf("serve: %v", err) + } + + want := []loggedFact{ + {level: core.LevelDebug, event: "lsp.stderr.received", fields: map[string]any{"text": "warming up", "bytes": json.Number("9007199254740993")}}, + {level: core.LevelInfo, event: "lsp.session.updated", fields: map[string]any{}}, + {level: core.LevelError, event: "lsp.session.failed", fields: map[string]any{"stage": "exit"}}, + } + if len(facts.facts) != len(want) { + t.Fatalf("forwarded %d facts, want %d: %+v", len(facts.facts), len(want), facts.facts) + } + for i, got := range facts.facts { + if got.level != want[i].level || got.event != want[i].event || !sameFields(got.fields, want[i].fields) { + t.Fatalf("fact %d = %+v, want %+v", i, got, want[i]) + } + } +} + +// TestStopForwardsTheLastFactsItWaitsThrough checks that the lifecycle facts a session +// reports while Stop waits for Core to let go of it reach the sink, instead of being read +// and dropped because nothing serves the session any more. +func TestStopForwardsTheLastFactsItWaitsThrough(t *testing.T) { + kernel := &stoppingKernel{fakeKernel: fakeKernel{events: [][]core.BackendEvent{{ + {Type: "stateChanged", State: "stopped", Event: "lsp.session.updated", Level: "INFO", Fields: json.RawMessage(`{"state":"stopped"}`)}, + }}}, refusals: 1} + facts := &factRecorder{} + runner := New(kernel, nil) + runner.SetLogFacts(facts.record) + if err := runner.Stop(context.Background(), Session{ID: "session-1"}); err != nil { + t.Fatalf("stop: %v", err) + } + if len(facts.facts) != 1 || facts.facts[0].event != "lsp.session.updated" || facts.facts[0].fields["state"] != "stopped" { + t.Fatalf("Stop forwarded %+v, want the stopped session's update once", facts.facts) + } +} + +// TestRunnerWithoutLogSinkDropsFacts checks that a runner nobody gave a sink still serves +// its session. +func TestRunnerWithoutLogSinkDropsFacts(t *testing.T) { + kernel := &fakeKernel{events: [][]core.BackendEvent{{ + {Type: EventExit, Event: "lsp.session.failed", Level: "ERROR", Fields: json.RawMessage(`{"stage":"exit"}`)}, + }}} + if err := New(kernel, echoServices(t)).Serve(context.Background(), Session{ID: "session-1"}, nil); err != nil { + t.Fatalf("serve: %v", err) + } +} + +// stoppingKernel refuses the first destroys, as Core does while a session is still +// shutting down. +type stoppingKernel struct { + fakeKernel + refusals int +} + +func (k *stoppingKernel) DestroyPluginBackend(ctx context.Context, session string) error { + if k.refusals > 0 { + k.refusals-- + return errors.New("session is still stopping") + } + return k.fakeKernel.DestroyPluginBackend(ctx, session) +} + +func sameFields(got, want map[string]any) bool { + if len(got) != len(want) { + return false + } + for key, value := range want { + if got[key] != value { + return false + } + } + return true +} diff --git a/desktop/internal/pluginbackend/pluginbackend.go b/desktop/internal/pluginbackend/pluginbackend.go index 50fa5a01c7..6332edc7e9 100644 --- a/desktop/internal/pluginbackend/pluginbackend.go +++ b/desktop/internal/pluginbackend/pluginbackend.go @@ -12,6 +12,7 @@ package pluginbackend import ( + "bytes" "context" "encoding/json" "errors" @@ -67,6 +68,7 @@ type Kernel interface { WaitBackendEvents(ctx context.Context, session string, timeoutMilliseconds int) ([]core.BackendEvent, error) StopPluginBackend(ctx context.Context, session string) error DestroyPluginBackend(ctx context.Context, session string) error + SetDetailedDiagnostics(ctx context.Context, session string, enabled bool) error RespondPluginHostRequest(ctx context.Context, session, requestID string, result json.RawMessage, failure *core.PluginHostFailure) error RequestPluginSemantics(ctx context.Context, request core.PluginSemanticRequest) (string, error) RequestPluginBuild(ctx context.Context, request core.PluginBuildProviderRequest) (string, error) @@ -128,6 +130,10 @@ type StartRequest struct { // instrumented binary raises it so scheduler load cannot masquerade as a // provider failure. InitializeTimeoutMilliseconds int + // Attempt is the languageServer/start attempt of a language-server start. The runner hands + // it to Core with the start itself, so the host records only what fails before that and + // Core records the rest. It is nil for every other role. + Attempt *core.PluginAttempt } // Session is one running plugin backend. @@ -161,6 +167,41 @@ type Runner struct { // initializeTimeout is the startup-handshake deadline applied to a request // that does not carry its own. Zero keeps Core's default. initializeTimeout time.Duration + // logFacts receives the catalog facts Core attaches to runtime events. Nil + // drops them. + logFacts LogFacts + // trace is the detailed-diagnostics switch of the sessions this runner started. + trace traceSwitch +} + +// LogFacts receives one catalog fact Core attached to a session's runtime event: +// the catalog level, the event id and the fields Core already validated and +// redacted. The writer derives the channel from them exactly as Core did. It runs +// on the goroutine that read the event, so it must queue the fact, not write it. +type LogFacts func(level core.LogLevel, event string, fields map[string]any) + +// SetLogFacts installs the sink of the facts on runtime events. It must be called +// before the first Start. +func (r *Runner) SetLogFacts(sink LogFacts) { r.logFacts = sink } + +// forwardLog hands the catalog fact event carries to the sink, once. Core puts a +// fact on any event type, the exit event included, and leaves the identity off a +// fact that failed its own catalog check, so only an event with an id and a +// level is a fact. Numbers are kept as written, so a large integer is not +// rounded on its way to the writer. +func (r *Runner) forwardLog(event core.BackendEvent) { + if r.logFacts == nil || event.Event == "" || event.Level == "" { + return + } + fields := map[string]any{} + if len(event.Fields) != 0 { + decoder := json.NewDecoder(bytes.NewReader(event.Fields)) + decoder.UseNumber() + if decoder.Decode(&fields) != nil { + return + } + } + r.logFacts(core.LogLevel(event.Level), event.Event, fields) } // SetInitializeTimeout sets the startup-handshake deadline of every backend @@ -351,6 +392,9 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro } var started core.PluginBackendStarted if request.LanguageID != "" { + // From here Core owns the attempt: it records the launch, the early exit, the + // initialize failure, the deadline or the finish. + start.StartupOperation = request.Attempt.HandOff() started, err = r.kernel.StartPluginLanguageServer(ctx, start) } else { started, err = r.kernel.StartPluginBackend(ctx, start) @@ -370,6 +414,7 @@ func (r *Runner) Start(ctx context.Context, request StartRequest) (Session, erro if started.ProcessID != nil { session.ProcessID = *started.ProcessID } + r.trackTrace(session.ID) return session, nil } @@ -398,6 +443,7 @@ func (r *Runner) Stop(ctx context.Context, session Session) error { if session.ID == "" { return ErrNoSession } + r.untrackTrace(session.ID) stopErr := r.kernel.StopPluginBackend(ctx, session.ID) // Core keeps the session until its shutdown reaches a terminal state, so a // destroy immediately after stop is normally refused. Wait for queued @@ -408,9 +454,15 @@ func (r *Runner) Stop(ctx context.Context, session Session) error { if destroyErr == nil || ctx.Err() != nil { break } - if _, waitErr := r.kernel.WaitBackendEvents(ctx, session.ID, 250); waitErr != nil { + events, waitErr := r.kernel.WaitBackendEvents(ctx, session.ID, 250) + if waitErr != nil { break } + // The session's last lifecycle facts arrive here when nothing serves it + // any more. + for _, event := range events { + r.forwardLog(event) + } } return errors.Join(stopErr, destroyErr) } @@ -449,6 +501,9 @@ func (r *Runner) Serve(ctx context.Context, session Session, observe EventObserv // pending requests, and cancelled when the backend cancels it. answers := newAnswerGroup(ctx) defer answers.wait() + // Once nothing serves the session it has ended or is being stopped: a trace switch + // would only be refused. + defer r.untrackTrace(session.ID) for { if err := ctx.Err(); err != nil { return err @@ -464,6 +519,7 @@ func (r *Runner) Serve(ctx context.Context, session Session, observe EventObserv return err } for _, event := range events { + r.forwardLog(event) switch event.Type { case EventExit: return nil diff --git a/desktop/internal/pluginbackend/pluginbackend_test.go b/desktop/internal/pluginbackend/pluginbackend_test.go index d7e47838f3..ba44430432 100644 --- a/desktop/internal/pluginbackend/pluginbackend_test.go +++ b/desktop/internal/pluginbackend/pluginbackend_test.go @@ -26,6 +26,8 @@ type fakeKernel struct { startErr error started_ core.PluginBackendStart events [][]core.BackendEvent + traces chan traceCall + traceRefused map[string]error answeredMu sync.Mutex answered []answeredRequest stopErr error @@ -98,6 +100,18 @@ func (k *fakeKernel) DestroyPluginBackend(context.Context, string) error { return k.destroyErr } +// SetDetailedDiagnostics records each switch on traces when a test watches them, and refuses +// the sessions in traceRefused. +func (k *fakeKernel) SetDetailedDiagnostics(_ context.Context, session string, enabled bool) error { + if k.traces != nil { + k.traces <- traceCall{session: session, enabled: enabled} + } + if err, ok := k.traceRefused[session]; ok { + return err + } + return nil +} + func (k *fakeKernel) RespondPluginHostRequest(_ context.Context, session, requestID string, result json.RawMessage, failure *core.PluginHostFailure) error { k.answeredMu.Lock() defer k.answeredMu.Unlock() @@ -519,6 +533,44 @@ func TestStartUsesLanguageServerPlanAndRole(t *testing.T) { } } +// A language-server start hands its attempt to Core with the start itself, so Core records +// the result; a plugin backend reports its own operations and hands nothing over, and a start +// that fails before Core is asked keeps the attempt for the host to record. +func TestStartHandsTheLanguageServerAttemptToCore(t *testing.T) { + root := backendPackage(t) + kernel := &fakeKernel{plan: packagedPlan(), started: core.PluginBackendStarted{SessionID: "session-1"}} + request := startRequest(root) + request.LanguageID = "java" + request.Attempt = core.StartPluginAttempt("example", core.OperationLanguageServerStart, "action-5") + if _, err := New(kernel, echoServices(t)).Start(context.Background(), request); err != nil { + t.Fatalf("start: %v", err) + } + handoff := kernel.started_.StartupOperation + if handoff == nil || handoff.PluginID != "example" || handoff.OperationID != "action-5" || !request.Attempt.HandedOff() { + t.Fatalf("the language-server start carried %+v", handoff) + } + + backend := startRequest(root) + backend.Attempt = core.StartPluginAttempt("example", core.OperationLanguageServerStart, "action-6") + if _, err := New(kernel, echoServices(t)).Start(context.Background(), backend); err != nil { + t.Fatalf("backend start: %v", err) + } + if kernel.started_.StartupOperation != nil || backend.Attempt.HandedOff() { + t.Fatalf("a plugin backend start handed off %+v", kernel.started_.StartupOperation) + } + + refused := &fakeKernel{planErr: errors.New("refused")} + early := startRequest(root) + early.LanguageID = "java" + early.Attempt = core.StartPluginAttempt("example", core.OperationLanguageServerStart, "action-7") + if _, err := New(refused, echoServices(t)).Start(context.Background(), early); err == nil { + t.Fatal("a refused plan started") + } + if early.Attempt.HandedOff() { + t.Fatal("a start that never reached Core handed its attempt over") + } +} + func TestLanguageServerStartPreservesCoreWorkspaceConfiguration(t *testing.T) { // Read a real wire-shaped plan so the test also catches a missing bridge field. var plan core.PluginBackendPlan diff --git a/desktop/internal/pluginbackend/trace.go b/desktop/internal/pluginbackend/trace.go new file mode 100644 index 0000000000..e4375fd806 --- /dev/null +++ b/desktop/internal/pluginbackend/trace.go @@ -0,0 +1,123 @@ +package pluginbackend + +import ( + "context" + "sync" +) + +// traceSwitch keeps the upstream trace of every session a runner started on the value the host +// last chose, as Core's logging README asks: detailed diagnostics reach the sessions already +// running and every session started while they are on, and turning them off, by hand or when +// they expire, reaches the same sessions. +type traceSwitch struct { + // mu guards everything below except send. + mu sync.Mutex + // sessions are the sessions started and not yet stopped or ended. + sessions map[string]bool + // enabled is the value the host chose last; generation counts its changes. + enabled bool + generation uint64 + // reported is the generation whose failure was already reported: a broken session or + // kernel reports one failure per choice, not one per session or per attempt. + reported uint64 + failed func(error) + // send orders the switches the sessions receive, so the last one each gets is the value + // read last, whichever goroutine sends it. + send sync.Mutex +} + +// SetDetailedDiagnostics turns the upstream trace of every running session this runner started, +// and of every one it starts from now on, on or off. It returns at once: the sessions are told +// on a goroutine of their own, so a caller on the log writer's goroutine is never held up by a +// session. Asking for the value already chosen does nothing. +func (r *Runner) SetDetailedDiagnostics(enabled bool) { + t := &r.trace + t.mu.Lock() + if t.enabled == enabled { + t.mu.Unlock() + return + } + t.enabled = enabled + t.generation++ + idle := len(t.sessions) == 0 + t.mu.Unlock() + if !idle { + go r.sendTraces() + } +} + +// SetTraceFailed installs the report of a trace switch a running session refused. It is told +// once per choice; a session that ended in the meantime is not a failure. It must be called +// before the first Start. +func (r *Runner) SetTraceFailed(report func(error)) { + r.trace.mu.Lock() + r.trace.failed = report + r.trace.mu.Unlock() +} + +// sendTraces tells every tracked session the value chosen last. +func (r *Runner) sendTraces() { + t := &r.trace + t.send.Lock() + defer t.send.Unlock() + t.mu.Lock() + enabled, generation := t.enabled, t.generation + sessions := make([]string, 0, len(t.sessions)) + for id := range t.sessions { + sessions = append(sessions, id) + } + t.mu.Unlock() + for _, id := range sessions { + r.sendTrace(id, enabled, generation) + } +} + +// trackTrace starts following a session that just started, and switches its trace on when +// detailed diagnostics are on. Core keeps the value until the handshake ends, so this does not +// wait for the session to be ready. +func (r *Runner) trackTrace(id string) { + t := &r.trace + t.send.Lock() + defer t.send.Unlock() + t.mu.Lock() + if t.sessions == nil { + t.sessions = map[string]bool{} + } + t.sessions[id] = true + enabled, generation := t.enabled, t.generation + t.mu.Unlock() + if enabled { + r.sendTrace(id, true, generation) + } +} + +// untrackTrace stops following a session that is stopping or ended; Core refuses the switch +// for it from then on. +func (r *Runner) untrackTrace(id string) { + r.trace.mu.Lock() + delete(r.trace.sessions, id) + r.trace.mu.Unlock() +} + +// sendTrace tells one session. A refusal from a session that is no longer tracked is the +// session ending while it was told, which Core reports as invalid_request like any request to +// an ended session; any other refusal is reported once for the choice. +func (r *Runner) sendTrace(id string, enabled bool, generation uint64) { + err := r.kernel.SetDetailedDiagnostics(context.Background(), id, enabled) + if err == nil { + return + } + t := &r.trace + t.mu.Lock() + report := t.failed + if !t.sessions[id] || t.reported == generation { + report = nil + } + if report != nil { + t.reported = generation + } + t.mu.Unlock() + if report != nil { + report(err) + } +} diff --git a/desktop/internal/pluginbackend/trace_test.go b/desktop/internal/pluginbackend/trace_test.go new file mode 100644 index 0000000000..e06643cb2f --- /dev/null +++ b/desktop/internal/pluginbackend/trace_test.go @@ -0,0 +1,162 @@ +package pluginbackend + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// traceCall is one trace switch a session received. +type traceCall struct { + session string + enabled bool +} + +// traceWait bounds how long a test waits for a switch the runner sends on its own goroutine. +const traceWait = 10 * time.Second + +func nextTrace(t *testing.T, calls <-chan traceCall) traceCall { + t.Helper() + select { + case call := <-calls: + return call + case <-time.After(traceWait): + t.Fatal("no trace switch reached a session") + return traceCall{} + } +} + +// settled waits until the runner has finished telling its sessions, so a test can then check +// that nothing more was sent. +func settled(r *Runner) { + r.trace.send.Lock() + defer r.trace.send.Unlock() +} + +// TestDetailedDiagnosticsReachRunningAndNewSessions checks that turning detailed diagnostics +// on switches the trace of the sessions already running, that a session started while they are +// on is switched on as it starts, that choosing the same value again sends nothing, and that a +// session that was stopped or has ended is not told any more. +func TestDetailedDiagnosticsReachRunningAndNewSessions(t *testing.T) { + root := backendPackage(t) + kernel := &fakeKernel{plan: packagedPlan(), started: core.PluginBackendStarted{SessionID: "session-1"}, traces: make(chan traceCall, 8)} + runner := New(kernel, echoServices(t)) + + first, err := runner.Start(context.Background(), startRequest(root)) + if err != nil { + t.Fatalf("start: %v", err) + } + if len(kernel.traces) != 0 { + t.Fatalf("a session started with diagnostics off was sent %+v", <-kernel.traces) + } + + runner.SetDetailedDiagnostics(true) + if got := nextTrace(t, kernel.traces); got != (traceCall{session: "session-1", enabled: true}) { + t.Fatalf("the running session got %+v, want its trace switched on", got) + } + settled(runner) + + kernel.started = core.PluginBackendStarted{SessionID: "session-2"} + second, err := runner.Start(context.Background(), startRequest(root)) + if err != nil { + t.Fatalf("start: %v", err) + } + if len(kernel.traces) != 1 { + t.Fatalf("a session started with diagnostics on got %d switches, want one as it starts", len(kernel.traces)) + } + if got := <-kernel.traces; got != (traceCall{session: "session-2", enabled: true}) { + t.Fatalf("the new session got %+v, want its trace switched on", got) + } + + runner.SetDetailedDiagnostics(true) + settled(runner) + if len(kernel.traces) != 0 { + t.Fatalf("choosing the same value again sent %+v", <-kernel.traces) + } + + if err := runner.Stop(context.Background(), first); err != nil { + t.Fatalf("stop: %v", err) + } + runner.SetDetailedDiagnostics(false) + if got := nextTrace(t, kernel.traces); got != (traceCall{session: "session-2", enabled: false}) { + t.Fatalf("turning diagnostics off sent %+v, want only the running session switched off", got) + } + settled(runner) + if len(kernel.traces) != 0 { + t.Fatalf("a stopped session was still told: %+v", <-kernel.traces) + } + + kernel.events = [][]core.BackendEvent{{{Type: EventExit}}} + if err := runner.Serve(context.Background(), second, nil); err != nil { + t.Fatalf("serve: %v", err) + } + runner.SetDetailedDiagnostics(true) + settled(runner) + if len(kernel.traces) != 0 { + t.Fatalf("a session that ended was still told: %+v", <-kernel.traces) + } +} + +// TestTraceRefusalIsReportedOncePerChoice checks that sessions refusing a switch report one +// failure for that choice, not one per session, that the next choice may report again, and +// that a session ending while it was told is not a failure. +func TestTraceRefusalIsReportedOncePerChoice(t *testing.T) { + refused := errors.New("lithe core: lsp.setDetailedDiagnostics: refused (unknown)") + kernel := &endingKernel{fakeKernel: fakeKernel{traces: make(chan traceCall, 8), traceRefused: map[string]error{"a": refused, "b": refused}}} + runner := New(kernel, nil) + kernel.runner = runner + reports := make(chan error, 8) + runner.SetTraceFailed(func(err error) { reports <- err }) + runner.trackTrace("a") + runner.trackTrace("b") + + runner.SetDetailedDiagnostics(true) + nextTrace(t, kernel.traces) + nextTrace(t, kernel.traces) + settled(runner) + if len(reports) != 1 { + t.Fatalf("two refusals of one choice reported %d failures, want one", len(reports)) + } + if err := <-reports; !errors.Is(err, refused) { + t.Fatalf("reported %v, want the session's refusal", err) + } + + runner.SetDetailedDiagnostics(false) + nextTrace(t, kernel.traces) + nextTrace(t, kernel.traces) + settled(runner) + if len(reports) != 1 { + t.Fatalf("the next choice reported %d failures, want one again", len(reports)) + } + <-reports + + runner.untrackTrace("a") + runner.untrackTrace("b") + kernel.ending = "c" + kernel.traceRefused["c"] = refused + runner.trackTrace("c") + runner.SetDetailedDiagnostics(true) + nextTrace(t, kernel.traces) + settled(runner) + if len(reports) != 0 { + t.Fatalf("a session that ended while it was told reported %v", <-reports) + } +} + +// endingKernel ends the session named ending while it is being told, the way a session that +// exits at that moment is refused by Core. +type endingKernel struct { + fakeKernel + runner *Runner + ending string +} + +func (k *endingKernel) SetDetailedDiagnostics(ctx context.Context, session string, enabled bool) error { + if session == k.ending { + k.runner.untrackTrace(session) + } + return k.fakeKernel.SetDetailedDiagnostics(ctx, session, enabled) +} diff --git a/desktop/internal/pluginservice/backendhost.go b/desktop/internal/pluginservice/backendhost.go index a81fe48393..ed08b276a8 100644 --- a/desktop/internal/pluginservice/backendhost.go +++ b/desktop/internal/pluginservice/backendhost.go @@ -179,7 +179,7 @@ func (h *BackendHost) start(ctx context.Context, pluginID string) (*BackendSessi if err != nil { return nil, err } - directories := s.backendDirectories(entry.Installed.ID, entry.Installed.Version) + directories := s.backendDirectories(ctx, entry.Installed.ID, entry.Installed.Version) if err := directories.create(); err != nil { return nil, err } @@ -606,14 +606,23 @@ func (d pluginDirectories) create() error { // never inside one: an installed package is read-only for the host, and a // version directory that changed would no longer match the digest the user // approved. The plugin root is the platform's plugin storage, not the app bundle. -func (s *Service) backendDirectories(pluginID, version string) pluginDirectories { - base := filepath.Join(s.Root, pluginStateDirectory, pluginID) +// The log directory is the log session's, which the log store has already created. +func (s *Service) backendDirectories(ctx context.Context, pluginID, version string) pluginDirectories { return pluginDirectories{ - state: filepath.Join(base, version), - log: filepath.Join(base, "logs"), + state: filepath.Join(s.Root, pluginStateDirectory, pluginID, version), + log: s.logDirectory(ctx, pluginID), } } +// logDirectory is the ${logDir} of a process started for pluginID, or empty when the window +// has no local log store. +func (s *Service) logDirectory(ctx context.Context, pluginID string) string { + if s.LogDirectory == nil { + return "" + } + return s.LogDirectory(ctx, pluginID) +} + // fileURI is the file URL of an absolute native path. func fileURI(path string) string { slashed := filepath.ToSlash(path) diff --git a/desktop/internal/pluginservice/backendlaunch.go b/desktop/internal/pluginservice/backendlaunch.go index 49fbad6174..e6e839f65c 100644 --- a/desktop/internal/pluginservice/backendlaunch.go +++ b/desktop/internal/pluginservice/backendlaunch.go @@ -23,8 +23,9 @@ type backendLaunch struct { // the command line through its launch function, and Core checks the answer and // returns the plan the host starts like any other. // -// Every writable location is the platform's plugin storage or a scratch directory -// under the system temporary directory. Nothing is derived from the installed +// Every writable location is the platform's plugin storage, the log session's +// plugin directory start already carries, or a scratch directory under the +// system temporary directory. Nothing is derived from the installed // package or the application bundle, which stay read-only so the next // differential update still matches what the user installed. func (s *Service) resolveBackendLaunch(ctx context.Context, pluginID, version string, manifest json.RawMessage, languageID string, workspace WorkspaceContext, start pluginbackend.StartRequest) (backendLaunch, error) { @@ -39,7 +40,7 @@ func (s *Service) resolveBackendLaunch(ctx context.Context, pluginID, version st directories := pluginDirectories{ state: start.StateDirectory, workspaceState: filepath.Join(base, "servers", languageID, "workspaces", WorkspaceKey(workspace.Path)), - log: filepath.Join(base, "logs"), + log: start.LogDirectory, temporary: temporary, } fail := func(err error) (backendLaunch, error) { diff --git a/desktop/internal/pluginservice/backends.go b/desktop/internal/pluginservice/backends.go index f4323245a4..1106c4f9a6 100644 --- a/desktop/internal/pluginservice/backends.go +++ b/desktop/internal/pluginservice/backends.go @@ -62,9 +62,17 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag if !ok { return nil, err } + // The start is one attempt of the plugin's languageServers declaration. What fails before + // the runner hands it to Core is the host's to record, as a launch it could not resolve; + // Core records everything after the handoff. + attempt := core.StartPluginAttempt(entry.Installed.ID, core.OperationLanguageServerStart, core.OriginOf(ctx).Operation) + fail := func(cause error) (*LanguageSession, error) { + s.EndAttempt(ctx, attempt, core.StageResolve, cause) + return nil, errors.Join(err, cause) + } manifest, readErr := readBounded(filepath.Join(entry.Installed.Path, pluginpkg.ManifestFile), MaxManifestBytes) if readErr != nil { - return nil, errors.Join(err, readErr) + return fail(readErr) } var workspaceContext WorkspaceContext if request.WorkingDirectory != "" && s.Contexts != nil { @@ -74,14 +82,14 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag } settings, settingsErr := s.Settings.Load(ctx, manifest, request.WorkingDirectory) if settingsErr != nil { - return nil, errors.Join(err, settingsErr) + return fail(settingsErr) } // State lives beside the installed versions, never inside one: an installed // package is read-only for the host, and a version directory that changed // would no longer match the digest the user approved. stateDirectory := filepath.Join(s.Root, pluginStateDirectory, entry.Installed.ID, entry.Installed.Version) if stateErr := os.MkdirAll(stateDirectory, 0o700); stateErr != nil { - return nil, errors.Join(err, stateErr) + return fail(stateErr) } start := pluginbackend.StartRequest{ Manifest: manifest, @@ -89,7 +97,9 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag PluginID: entry.Installed.ID, ProviderID: entry.Installed.ID + "/language-server", LanguageID: languageID, + Attempt: attempt, StateDirectory: stateDirectory, + LogDirectory: s.logDirectory(ctx, entry.Installed.ID), Architecture: request.Architecture, Settings: settings.State.Settings, ProjectSettings: settings.State.ProjectSettings, @@ -100,17 +110,16 @@ func (s *Service) StartLanguageServer(ctx context.Context, entries []pluginmanag if declaresBackendLaunch(manifest, languageID) { resolved, resolveErr := s.resolveBackendLaunch(ctx, entry.Installed.ID, entry.Installed.Version, manifest, languageID, workspaceContext, start) if resolveErr != nil { - return nil, errors.Join(err, resolveErr) + return fail(resolveErr) } start.Plan = resolved.plan - start.LogDirectory = resolved.directories.log start.WorkspaceStateDirectory = resolved.directories.workspaceState temporary = resolved.directories.temporary } started, startErr := s.Backend.Start(ctx, start) if startErr != nil { removeTemporary(temporary) - return nil, errors.Join(err, startErr) + return fail(startErr) } session := &LanguageSession{ PluginID: entry.Installed.ID, diff --git a/desktop/internal/pluginservice/operations.go b/desktop/internal/pluginservice/operations.go new file mode 100644 index 0000000000..2128dcacba --- /dev/null +++ b/desktop/internal/pluginservice/operations.go @@ -0,0 +1,28 @@ +package pluginservice + +import ( + "context" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// RecordOperation records the result of a declarative contribution the host ran, such as a +// build command or a debug adapter start, on the plugin's own log channel. A result Core +// refuses goes to RecordFailed; the caller has nothing more to do about it. +func (s *Service) RecordOperation(ctx context.Context, operation core.PluginOperation) { + if s == nil || s.kernel == nil { + return + } + if err := s.kernel.RecordPluginOperation(ctx, operation); err != nil && s.RecordFailed != nil { + s.RecordFailed(ctx, err) + } +} + +// EndAttempt records an attempt that stopped with err at stage, unless it is not the host's to +// record: Core owns a handed-off attempt, and a cancelled one is never recorded. Recording does +// not use ctx, since the attempt may have ended because ctx did. +func (s *Service) EndAttempt(ctx context.Context, attempt *core.PluginAttempt, stage core.PluginStage, err error) { + if result, ok := attempt.Ended(ctx, stage, err); ok { + s.RecordOperation(context.WithoutCancel(ctx), result) + } +} diff --git a/desktop/internal/pluginservice/operations_test.go b/desktop/internal/pluginservice/operations_test.go new file mode 100644 index 0000000000..4c21ffeab4 --- /dev/null +++ b/desktop/internal/pluginservice/operations_test.go @@ -0,0 +1,154 @@ +package pluginservice + +import ( + "context" + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginmanager" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +// languageServerEntry is an enabled package that declares a go language server and ships the +// program its plan starts. The fake kernels never run it, but the runner verifies it exists. +func languageServerEntry(t *testing.T) pluginmanager.Entry { + t.Helper() + entry := serverPackage(t, "1.0.0", true, "go") + program := filepath.Join(entry.Installed.Path, "bin", "server") + if err := os.MkdirAll(filepath.Dir(program), 0o700); err != nil { + t.Fatal(err) + } + image := []byte("binary") + if runtime.GOOS == "windows" { + // The Windows adapter checks for a native image even when the process is fake. + current, err := os.Executable() + if err != nil { + t.Fatal(err) + } + if image, err = os.ReadFile(current); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(program, image, 0o755); err != nil { + t.Fatal(err) + } + return entry +} + +// packagedServerPlan starts the package's own program. +func packagedServerPlan() core.PluginBackendPlan { + var plan core.PluginBackendPlan + plan.Launch.Kind = pluginhost.LaunchPackaged + plan.Launch.Path = "bin/server" + return plan +} + +// TestLanguageServerStartRecordsWhatFailsBeforeCoreTakesIt checks that a language-server start +// is recorded by the host only up to the handoff: a failure before it is a launch the host +// could not resolve, or a timeout at a deadline, under the action's op; a start handed to Core +// carries the attempt and records nothing here, whatever Core answers; a cancelled start +// records nothing; and a result Core refuses is reported, not lost. +func TestLanguageServerStartRecordsWhatFailsBeforeCoreTakesIt(t *testing.T) { + refused := errors.New("lithe core: plan refused") + cases := []struct { + name string + prepare func(*fakeKernel) + cancel bool + origin string + wantStage core.PluginStage + wantStart bool + }{ + {name: "plan refused", prepare: func(k *fakeKernel) { k.planErr = refused }, origin: "action-41", wantStage: core.StageResolve}, + {name: "deadline before the handoff", prepare: func(k *fakeKernel) { k.planErr = context.DeadlineExceeded }, origin: "action-41", wantStage: core.StageTimeout}, + {name: "cancelled", prepare: func(k *fakeKernel) { k.planErr = context.Canceled }, cancel: true, origin: "action-41"}, + {name: "handed off", prepare: func(k *fakeKernel) { + k.plan, k.started = packagedServerPlan(), core.PluginBackendStarted{SessionID: "ls-1"} + }, origin: "action-41", wantStart: true}, + {name: "refused by core after the handoff", prepare: func(k *fakeKernel) { + k.plan, k.startErr = packagedServerPlan(), errors.New("lithe core: lsp.startServer: refused") + }, origin: "action-41", wantStart: true}, + {name: "handed off without an action", prepare: func(k *fakeKernel) { + k.plan, k.started = packagedServerPlan(), core.PluginBackendStarted{SessionID: "ls-1"} + }, wantStart: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + kernel := &fakeKernel{} + tc.prepare(kernel) + service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) + if err != nil { + t.Fatal(err) + } + ctx := core.WithOrigin(context.Background(), core.Origin{Operation: tc.origin, Trigger: "command.test"}) + if tc.cancel { + var cancel context.CancelFunc + ctx, cancel = context.WithCancel(ctx) + cancel() + } + session, _ := service.StartLanguageServer(ctx, []pluginmanager.Entry{languageServerEntry(t)}, "go", BackendRequest{Architecture: core.PluginArchitecture()}) + if session != nil { + t.Cleanup(func() { service.unregisterLanguageSession(session) }) + } + + if !tc.wantStart { + if len(kernel.languageStarts) != 0 { + t.Fatalf("a start that failed before the handoff reached Core: %+v", kernel.languageStarts) + } + } else { + if len(kernel.languageStarts) != 1 { + t.Fatalf("Core was asked to start %d servers, want one", len(kernel.languageStarts)) + } + handoff := kernel.languageStarts[0].StartupOperation + if handoff == nil || handoff.PluginID != "example" || handoff.ElapsedMs < 0 { + t.Fatalf("the start did not hand the attempt to Core: %+v", handoff) + } + if tc.origin != "" && handoff.OperationID != tc.origin { + t.Fatalf("the handoff is under %q, want the action's op %q", handoff.OperationID, tc.origin) + } + if tc.origin == "" && !strings.HasPrefix(handoff.OperationID, "action-") { + t.Fatalf("a start without an action handed off op %q, want a fresh one", handoff.OperationID) + } + } + + switch { + case tc.wantStage == "": + if len(kernel.operations) != 0 { + t.Fatalf("the host recorded %+v for a start that is not its to record", kernel.operations) + } + case len(kernel.operations) != 1: + t.Fatalf("the host recorded %d results, want one: %+v", len(kernel.operations), kernel.operations) + default: + got := kernel.operations[0] + want := core.PluginOperation{ + PluginID: "example", Operation: core.OperationLanguageServerStart, Outcome: "failed", + Stage: tc.wantStage, DurationMs: got.DurationMs, OperationID: tc.origin, + } + if got != want || got.DurationMs < 0 { + t.Fatalf("recorded %+v, want %+v", got, want) + } + } + }) + } + + t.Run("refused result", func(t *testing.T) { + kernel := &fakeKernel{planErr: refused, recordErr: errors.New("log error -32064: Invalid host plugin operation")} + service, err := Open(kernel, store.At(t.TempDir()), t.TempDir()) + if err != nil { + t.Fatal(err) + } + var reported []error + service.RecordFailed = func(_ context.Context, err error) { reported = append(reported, err) } + if _, err := service.StartLanguageServer(context.Background(), []pluginmanager.Entry{languageServerEntry(t)}, "go", BackendRequest{}); !errors.Is(err, refused) { + t.Fatalf("start = %v, want the plan's refusal", err) + } + if len(reported) != 1 || !errors.Is(reported[0], kernel.recordErr) { + t.Fatalf("a refused result was reported %v, want once", reported) + } + }) +} diff --git a/desktop/internal/pluginservice/pluginservice.go b/desktop/internal/pluginservice/pluginservice.go index d087f15340..e9b8ee110a 100644 --- a/desktop/internal/pluginservice/pluginservice.go +++ b/desktop/internal/pluginservice/pluginservice.go @@ -57,6 +57,7 @@ type Kernel interface { DecodeDebugBackendConfiguration(ctx context.Context, manifest json.RawMessage, params json.RawMessage) (core.DebugBackendStart, error) DecodeOutputLinkResolution(ctx context.Context, reply json.RawMessage) (*core.OutputLocation, error) DecodePluginLanguageServerLaunch(ctx context.Context, manifest json.RawMessage, languageID string, directories core.PluginBackendDirectories, answer json.RawMessage) (core.PluginBackendPlan, error) + RecordPluginOperation(ctx context.Context, operation core.PluginOperation) error } // Service is the assembled plugin stack. @@ -106,6 +107,15 @@ type Service struct { // LanguageTool resolves an optional installation for a backend-resolved // language server. A nil installation means the tool is unavailable. LanguageTool func(context.Context, string, string) (*core.ToolchainSelection, error) + // LogDirectory gives the ${logDir} of a process started for a plugin: the current log + // session's plugins//files directory, created by the window's log store. An empty + // answer, or a nil LogDirectory, means there is no local log store; the process then gets + // no logDirectory and a launch that names ${logDir} is refused, as the contract says. + LogDirectory func(ctx context.Context, pluginID string) string + // RecordFailed reports that Core refused or could not queue the result of a declarative + // contribution the host ran. A nil RecordFailed drops the error: the result is diagnostics, + // and the attempt it describes already went its own way. + RecordFailed func(ctx context.Context, err error) // kernel reads what only Core can validate, such as a plugin's grammar. kernel Kernel // lsMu guards the running plugin-owned language servers backends reach. diff --git a/desktop/internal/pluginservice/pluginservice_test.go b/desktop/internal/pluginservice/pluginservice_test.go index 93ddc903fe..e7d2547a49 100644 --- a/desktop/internal/pluginservice/pluginservice_test.go +++ b/desktop/internal/pluginservice/pluginservice_test.go @@ -35,6 +35,9 @@ type fakeKernel struct { synced []string documentVersion int64 semanticRequests []core.PluginSemanticRequest + languageStarts []core.PluginBackendStart + operations []core.PluginOperation + recordErr error } func (k *fakeKernel) ValidatePluginManifest(_ context.Context, manifest json.RawMessage, _ map[string][]int) (json.RawMessage, error) { @@ -69,10 +72,16 @@ func (k *fakeKernel) StartPluginBackend(context.Context, core.PluginBackendStart return k.started, k.startErr } -func (k *fakeKernel) StartPluginLanguageServer(context.Context, core.PluginBackendStart) (core.PluginBackendStarted, error) { +func (k *fakeKernel) StartPluginLanguageServer(_ context.Context, request core.PluginBackendStart) (core.PluginBackendStarted, error) { + k.languageStarts = append(k.languageStarts, request) return k.started, k.startErr } +func (k *fakeKernel) RecordPluginOperation(_ context.Context, operation core.PluginOperation) error { + k.operations = append(k.operations, operation) + return k.recordErr +} + func (k *fakeKernel) WaitBackendEvents(context.Context, string, int) ([]core.BackendEvent, error) { if len(k.events) == 0 { return nil, nil @@ -86,6 +95,8 @@ func (k *fakeKernel) StopPluginBackend(context.Context, string) error { return k func (k *fakeKernel) DestroyPluginBackend(context.Context, string) error { return k.destroyErr } +func (k *fakeKernel) SetDetailedDiagnostics(context.Context, string, bool) error { return nil } + func (k *fakeKernel) RespondPluginHostRequest(context.Context, string, string, json.RawMessage, *core.PluginHostFailure) error { return k.hostResponseErr } diff --git a/desktop/internal/workbench/aicommit.go b/desktop/internal/workbench/aicommit.go index ebee092c73..3800d341e1 100644 --- a/desktop/internal/workbench/aicommit.go +++ b/desktop/internal/workbench/aicommit.go @@ -96,7 +96,7 @@ func (a *App) finishCommitGeneration(p *project, message, token string, reposito return } a.notifyError(a.aiCommitFailure(err)) - a.gitOperationFailed("ai_commit_generation", err) + a.operationFailed("ai_commit_generation", err) return } message = strings.TrimSpace(message) @@ -153,8 +153,11 @@ func (a *App) confirmGeneratedMessage(p *project, replace bool) { return func(a *App) { switch { case err != nil: + a.operationFailed("ai_commit_confirm", err) a.notifyError(a.aiCommitFailure(err)) case !current: + // The staged changes moved on since the message was generated. + a.operationRejected("ai_commit_confirm", "stale") a.notifyError(a.aiCommitFailure(ai.ErrStale)) case c.message() != typed: // The user kept typing: the draft is theirs, not ours. diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 1e79464765..90b6047b76 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -244,6 +244,19 @@ type LogSink interface { Emit(level core.LogLevel, event, op string, fields map[string]any) } +// pluginFileSink is the part of the client's log that gives a plugin process the directory +// it writes its own files to. *logstore.Store implements it; a sink without it gives none. +type pluginFileSink interface { + PluginFilesDirectory(ctx context.Context, pluginID string) (string, error) +} + +// diagnosticsWatchSink is the part of the client's log that tells when detailed diagnostics +// turn on and off, so the upstream trace of plugin sessions follows the same switch. +// *logstore.Store implements it; with a sink without it the trace stays off. +type diagnosticsWatchSink interface { + WatchDiagnostics(watch func(on bool)) (stop func()) +} + // logsShortcut opens the log window, as on macOS. const logsShortcut = "⇧⌘L" @@ -654,6 +667,14 @@ type App struct { // when the window was made without a log. logSink LogSink logs *logwindow.Controller + // unwatchDiagnostics stops the detailed-diagnostics switch reaching this workbench's plugin + // sessions; it is nil when nothing watches it. + unwatchDiagnostics func() + // logWindowOpen replaces how the log window opens, for tests, which have no application. + logWindowOpen func(op string) error + // op is the user action the window thread is running (operation.go); only the window + // thread reads or sets it. + op operation // version is Options.Version. version string // shared is what the log window reads from its own thread: the language and the look @@ -694,7 +715,10 @@ func New(options Options) *App { listShells: localshell.InstalledShells, } a.gitConsole = core.NewGitConsole(a.gitConsoleChanged) - if _, err := a.store.Load(settingsFile, &a.settings); err != nil { + // The settings are read before the log sink is in place; a failure is recorded below, once + // it is. + _, settingsErr := a.store.Load(settingsFile, &a.settings) + if settingsErr != nil { a.settings = settings{} } a.settings.Keymap = shortcuts.Normalize(a.settings.Keymap) @@ -750,6 +774,9 @@ func New(options Options) *App { // Processes started from now on are recorded in the preferences' ledger (startup_sweep.go). processledger.Activate(a.store.Dir()) } + if settingsErr != nil { + a.storedStateFailed("settings", settingsErr) + } a.openPlugins(options) a.settingsWindow = a.newSettingsWindow() a.loadRecent() @@ -774,7 +801,7 @@ func (a *App) openPlugins(options Options) { if root == "" { resolved, err := pluginpkg.DefaultRoot() if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_root", err)) + a.operationFailed("plugin_root", err) return } root = resolved @@ -785,16 +812,21 @@ func (a *App) openPlugins(options Options) { } service, err := open(options.PluginKernel, a.store, root) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_open", err)) + a.operationFailed("plugin_open", err) return } a.plugins = service service.Backend.SetInitializeTimeout(options.PluginInitializeTimeout) service.Backend.SetToolResolver(a.resolveBackendTool) service.Backend.SetToolEntryResolver(a.resolveBackendToolEntry) + service.Backend.SetLogFacts(a.recordEngineFact) + service.Backend.SetTraceFailed(a.traceFailed) + a.watchDiagnostics() service.LanguageTool = a.resolveLanguageTool + service.LogDirectory = a.pluginLogDirectory + service.RecordFailed = a.pluginOperationRecordFailed if err := service.AttachWorkbench(pluginWorkbench{app: a}); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_host_services", err)) + a.operationFailed("plugin_host_services", err) } a.wirePluginRuns() } @@ -836,10 +868,11 @@ func (a *App) Run() error { }) for _, session := range a.sessions.everyOne() { session.unsubscribeSettings() + session.stopWatchingDiagnostics() session.closeProject() session.wait() if session.pluginDownloads != nil { - session.recordPluginInstallCleanup(session.pluginDownloads.Close()) + session.recordPluginInstallCleanup(context.Background(), session.pluginDownloads.Close()) } if session.plugins != nil && session.plugins.Runs != nil { // Runs of the closed project are already stopped; this ends any the @@ -879,31 +912,123 @@ func (a *App) closed() { a.stopUpdates() } -// openLogs shows the log window. The window is opened from the queue drained in OnWake, -// not from the paint or the event that asked for it, because opening a window while this -// one is painting is not allowed. -func (a *App) openLogs() { +// openLogs shows the log window. +func (a *App) openLogs() { a.showLogs("") } + +// showLogs shows the log window, narrowed to the records of op when op is not empty. The +// window is opened from the queue drained in OnWake, not from the paint or the event that +// asked for it, because opening a window while this one is painting is not allowed. +func (a *App) showLogs(op string) { if a.logs == nil { + // The client runs without a log writer, so there is nowhere to record this: a failure + // of the writer itself is never written through the writer. a.notifyError(a.text.Title.LogsUnavailable) return } a.post(func(a *App) { - if a.application == nil { - return - } - if err := a.logs.Open(a.application); err != nil { + if err := a.openLogWindow(op); err != nil { + a.operationFailed("log_window_open", err) a.notifyError(a.text.Errors.LogsFailed(err.Error())) } }) } -// emit writes one of the window's own events to the client's log, when there is one. +// openLogWindow opens the log window in the application, on the records of op when op is not +// empty. It runs on the window thread. +func (a *App) openLogWindow(op string) error { + if a.logWindowOpen != nil { + return a.logWindowOpen(op) + } + if a.application == nil { + return nil + } + if op == "" { + return a.logs.Open(a.application) + } + return a.logs.OpenOperation(a.application, op) +} + +// emit writes one of the window's own events to the client's log, when there is one, under the +// user action in progress. It reads the window thread's state: a goroutine records with emitIn. func (a *App) emit(level core.LogLevel, event string, fields map[string]any) { + a.emitAs(a.op.id, level, event, fields) +} + +// emitIn writes one of the window's own events from any goroutine, under the user action ctx +// belongs to (core.OriginOf), for work that runs off the window thread. +func (a *App) emitIn(ctx context.Context, level core.LogLevel, event string, fields map[string]any) { + a.emitAs(core.OriginOf(ctx).Operation, level, event, fields) +} + +// emitAs writes one event under op; empty op means the event belongs to no action. +func (a *App) emitAs(op string, level core.LogLevel, event string, fields map[string]any) { if a.logSink != nil { - a.logSink.Emit(level, event, "", fields) + a.logSink.Emit(level, event, op, fields) + } +} + +// recordEngineFact writes a catalog fact Core attached to a plugin session's runtime event: +// a language server's stderr line or logMessage, a provider's lifecycle, a session's exit. +// Core chose the event and already checked and redacted its fields against the catalog, so +// the window adds nothing; the writer checks it again on the way out. Engine facts belong to +// no user action. It is safe from any goroutine. +func (a *App) recordEngineFact(level core.LogLevel, event string, fields map[string]any) { + a.emitAs("", level, event, fields) +} + +// traceFailed records that Core refused to switch the upstream trace of a plugin session the +// way detailed diagnostics were last turned. The runner reports one refusal per choice, so a +// broken kernel cannot flood the log. It is safe from any goroutine. +func (a *App) traceFailed(err error) { + a.emitAs("", core.LevelWarn, "app.logging.diagnostics_failed", core.LogErrorFields(err)) +} + +// watchDiagnostics makes the upstream trace of this workbench's plugin sessions follow the +// detailed-diagnostics switch of the client's log: the sessions running when it turns, and +// those started while it is on, as Core's logging contract asks. Without a log that tells +// the switch, or without plugins, the trace stays off. +func (a *App) watchDiagnostics() { + a.stopWatchingDiagnostics() + sink, ok := a.logSink.(diagnosticsWatchSink) + if !ok || a.plugins == nil { + return + } + a.unwatchDiagnostics = sink.WatchDiagnostics(a.plugins.Backend.SetDetailedDiagnostics) +} + +// stopWatchingDiagnostics stops the plugin sessions of this workbench following the +// detailed-diagnostics switch; it runs once the workbench is done with them. +func (a *App) stopWatchingDiagnostics() { + if a.unwatchDiagnostics != nil { + a.unwatchDiagnostics() + a.unwatchDiagnostics = nil } } +// pluginLogDirectory is the ${logDir} of a process started for pluginID: this log session's +// plugins//files directory, whose files retention and Clear Logs treat like the +// session's own. It is empty when the client runs without a log store, and when the +// directory cannot be made, which is recorded; the process then starts without one. It is +// safe from any goroutine. +func (a *App) pluginLogDirectory(ctx context.Context, pluginID string) string { + sink, ok := a.logSink.(pluginFileSink) + if !ok { + return "" + } + directory, err := sink.PluginFilesDirectory(ctx, pluginID) + if err != nil { + a.backgroundFailedIn(ctx, "plugin_log_directory", documentLogError(err)) + return "" + } + return directory +} + +// pluginOperationRecordFailed records that Core refused, or could not queue, the result of a +// declarative plugin contribution the window ran. It is safe from any goroutine. +func (a *App) pluginOperationRecordFailed(ctx context.Context, err error) { + a.backgroundFailedIn(ctx, "plugin_operation_record", err) +} + // actionSurface is the part of the window a user action was started from. The set is closed: // it is the list the catalog gives for the surface field of app.action.performed, and the // test that checks every logging call against the kernel rejects a value outside it. @@ -936,11 +1061,23 @@ const ( ) // performed logs that the user started the action with the stable id from surface, as the -// macOS client does; the id is never a localized title. +// macOS client does; the id is never a localized title. It starts the action's operation +// (operation.go): what the action records and the Core requests it sends share its op. func (a *App) performed(action string, surface actionSurface) { + a.op = operation{id: core.NewOperation(), trigger: action} a.emit(core.LevelInfo, "app.action.performed", map[string]any{"action": action, "surface": string(surface)}) } +// performedIn logs an action the user started in a window other than this one, such as the +// settings window, from the goroutine that runs it. It never touches the window thread's +// operation: the action's operation travels in the returned context, under which the work +// records its events (emitIn) and sends its Core requests. +func (a *App) performedIn(ctx context.Context, action string, surface actionSurface) context.Context { + id := core.NewOperation() + a.emitAs(id, core.LevelInfo, "app.action.performed", map[string]any{"action": action, "surface": string(surface)}) + return core.WithOrigin(ctx, core.Origin{Operation: id, Trigger: action}) +} + // titleBarHeight is the height of the title bar on both screens; the system's window // buttons sit in it. const titleBarHeight = 40 @@ -993,7 +1130,7 @@ func (a *App) saveSettings() { a.settings.WorkbenchBackground = a.savedBackgroundState() a.updates.store(&a.settings) if err := a.store.Save(settingsFile, a.settings); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("settings_save", documentLogError(err))) + a.operationFailed("settings_save", documentLogError(err)) a.notifyError(a.text.Errors.SaveFailed(err.Error())) } } @@ -1095,6 +1232,7 @@ func (a *App) hidePanel(s slot) { func (a *App) loadRecent() { var entries []core.RecentProject if _, err := a.store.Load(recentFile, &entries); err != nil { + a.storedStateFailed("recent_projects", err) a.notifyError(a.text.Errors.Core(err.Error())) entries = nil } @@ -1104,17 +1242,17 @@ func (a *App) loadRecent() { // reduceRecent sends one change of the recent project list to the kernel and keeps // the result, saving it when save is set. func (a *App) reduceRecent(entries []core.RecentProject, action core.RecentAction, save bool) { - ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) defer cancel() result, err := a.kernel.ReduceRecentProjects(ctx, entries, action, 0) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_recent_reduce", documentLogError(err))) + a.operationFailed("workspace_recent_reduce", documentLogError(err)) a.notifyError(a.text.Errors.Core(err.Error())) return } if save { if err := a.store.Save(recentFile, result.Entries); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_recent_save", documentLogError(err))) + a.operationFailed("workspace_recent_save", documentLogError(err)) a.notifyError(a.text.Errors.SaveFailed(err.Error())) return } @@ -1139,6 +1277,7 @@ func (a *App) chooseProject(surface actionSurface) { switch { case errors.Is(err, app.ErrCanceled): case err != nil: + a.operationFailed("project_open_dialog", err) a.notifyError(a.text.Errors.OpenFailed(err.Error())) default: a.performed("workspace.open", surface) @@ -1153,7 +1292,7 @@ func (a *App) chooseProject(surface actionSurface) { func (a *App) openProjectHere(path string) { root, err := filepath.Abs(wslpath.ToNative(path)) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_open", documentLogError(err))) + a.operationFailed("workspace_open", documentLogError(err)) a.notifyError(a.text.Errors.OpenFailed(err.Error())) return } @@ -1161,7 +1300,7 @@ func (a *App) openProjectHere(path string) { if err == nil { err = errors.New("not a directory") } - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_open", documentLogError(err))) + a.operationFailed("workspace_open", documentLogError(err)) a.notifyError(a.text.Errors.FolderMissing(root)) return } diff --git a/desktop/internal/workbench/branch.go b/desktop/internal/workbench/branch.go index 4dc56f8a18..e740568689 100644 --- a/desktop/internal/workbench/branch.go +++ b/desktop/internal/workbench/branch.go @@ -209,7 +209,7 @@ func (a *App) runBranchWrite(p *project, operation string, failed func(reason st b.busy = false if err != nil { a.notifyError(failed(err.Error())) - a.gitOperationFailed(operation, err) + a.operationFailed(operation, err) return } // The project's status describes its own repository only. @@ -244,7 +244,7 @@ func (a *App) checkoutBranch(p *project, r core.GitReference, surface actionSurf b.busy = false if err != nil { a.notifyError(a.text.Branch.CheckoutFailed(err.Error())) - a.gitOperationFailed("git_checkout", err) + a.operationFailed("git_checkout", err) return } if len(blocking) > 0 { @@ -338,7 +338,7 @@ func (a *App) previewBranchName(p *project, raw string, require bool) core.Branc if err != nil { // The kernel could not clean the name; the typed text stands, and the submit tells // the user what Git says. - a.gitOperationFailed("git_branch_name_preview", err) + a.backgroundFailed("git_branch_name_preview", err) return core.BranchNamePreview{TypingCleanedName: raw, CleanedName: strings.TrimSpace(raw)} } return preview diff --git a/desktop/internal/workbench/browser_preview.go b/desktop/internal/workbench/browser_preview.go index 799491ed23..b2da76442e 100644 --- a/desktop/internal/workbench/browser_preview.go +++ b/desktop/internal/workbench/browser_preview.go @@ -35,7 +35,7 @@ func (a *App) openInBrowser(p *project, d *document, surface actionSurface) { err := app.OpenPathInBrowser(path) return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_open_in_browser", documentLogError(err))) + a.operationFailed("editor_open_in_browser", documentLogError(err)) a.notifyError(i18n.SharedFormat(a.language(), "desktop.editorMenu.openInBrowserFailed", map[string]string{"reason": err.Error()})) return } diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index cfcc780c83..db23c265a2 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -237,8 +237,9 @@ type buildRuntime struct { // provider is the running provider of instance, started when there is none. The process starts // outside the lock, so detaching on the window thread never waits for a start; a start that lost -// to another one or to a detach is stopped again. -func (r *buildRuntime) provider(ctx context.Context, runner *pluginbackend.Runner, pluginRoot, root, rootURI string, instance buildInstance, settings core.PluginSettingsState) (*buildprovider.Client, error) { +// to another one or to a detach is stopped again. logDirectory gives the process's ${logDir}, and +// is asked only when a process starts. +func (r *buildRuntime) provider(ctx context.Context, runner *pluginbackend.Runner, pluginRoot, root, rootURI string, instance buildInstance, settings core.PluginSettingsState, logDirectory func(context.Context, string) string) (*buildprovider.Client, error) { key := instance.PluginID + "\x00" + instance.BuildSystemID errClosing := buildprovider.ErrClosed r.mu.Lock() @@ -255,9 +256,8 @@ func (r *buildRuntime) provider(ctx context.Context, runner *pluginbackend.Runne return nil, err } workspaceState := filepath.Join(state, "workspace") - logDirectory := filepath.Join(state, "log") temporaryDirectory := filepath.Join(state, "tmp") - for _, directory := range []string{workspaceState, logDirectory, temporaryDirectory} { + for _, directory := range []string{workspaceState, temporaryDirectory} { if err := os.MkdirAll(directory, 0o700); err != nil { return nil, err } @@ -271,7 +271,7 @@ func (r *buildRuntime) provider(ctx context.Context, runner *pluginbackend.Runne Role: "build", StateDirectory: state, WorkspaceStateDirectory: workspaceState, - LogDirectory: logDirectory, + LogDirectory: logDirectory(ctx, instance.PluginID), TemporaryDirectory: temporaryDirectory, Architecture: core.PluginArchitecture(), Settings: settings.Settings, @@ -352,7 +352,7 @@ func (a *App) buildProvider(ctx context.Context, p *project, instance buildInsta if err != nil { return nil, err } - client, err = p.buildSessions.provider(ctx, a.plugins.Backend, a.plugins.Root, p.root, rootURI, instance, settings.State) + client, err = p.buildSessions.provider(ctx, a.plugins.Backend, a.plugins.Root, p.root, rootURI, instance, settings.State, a.pluginLogDirectory) var shared *pluginbackend.SharedProviderError if !errors.As(err, &shared) { return client, err @@ -400,7 +400,7 @@ func (a *App) sharedBuildProvider(ctx context.Context, p *project, instance buil return nil, errors.New("no enabled plugin serves the shared provider language") } if session.Warnings != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_server_selection", session.Warnings)) + a.emitIn(ctx, backgroundFailedLevel, backgroundFailedEvent, operationFailedFields("plugin_server_selection", session.Warnings)) } server := &pluginServer{session: session, project: p, done: make(chan struct{})} serveCtx, serveCancel := context.WithCancel(context.Background()) @@ -487,7 +487,7 @@ func (a *App) loadBuildSystems(p *project) { kernel := a.kernel // The team and local option documents are read here, on the window thread, and resolved and detected // with the instances below; a document that cannot be read fails the detection instead of emptying it. - docs, docsErr := a.readBuildOptionDocuments(context.Background(), p.root) + docs, docsErr := a.readBuildOptionDocuments(a.operationContext(context.Background()), p.root) a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { entries, err := a.plugins.Manager.Installed() if err != nil { @@ -621,15 +621,22 @@ func (a *App) reloadBuildModel(p *project, index int) { // commandModel runs a command-sourced model plan and decodes its output. The // output file, when the plan uses one, is host-allocated under the plugin's -// writable state and removed after decoding. +// writable state and removed after decoding. No plugin process runs the command, so the +// host records the load as the plugin's lithe/build/model operation, at the stage +// buildCommandStage describes. func (a *App) commandModel(ctx context.Context, p *project, instance buildInstance, kernel Kernel, messages i18n.BuildMessages) (core.BuildModel, error) { + attempt := core.StartPluginAttempt(instance.PluginID, core.OperationBuildModel, core.OriginOf(ctx).Operation) + fail := func(stage core.PluginStage, err error) (core.BuildModel, error) { + a.plugins.EndAttempt(ctx, attempt, stage, err) + return core.BuildModel{}, err + } state := buildStateDirectory(a.plugins.Root, p.root, instance) if err := os.MkdirAll(state, 0o700); err != nil { - return core.BuildModel{}, err + return fail(core.StagePlan, err) } file, createErr := os.CreateTemp(state, "model-*.json") if createErr != nil { - return core.BuildModel{}, createErr + return fail(core.StagePlan, createErr) } outputFile := file.Name() _ = file.Close() @@ -647,14 +654,14 @@ func (a *App) commandModel(ctx context.Context, p *project, instance buildInstan OutputFile: outputFile, }) if err != nil { - return core.BuildModel{}, err + return fail(core.StagePlan, err) } if plan.Provider != nil { - return core.BuildModel{}, errors.New("the build system answered with a provider model") + return fail(core.StagePlan, errors.New("the build system answered with a provider model")) } execution, err := a.resolveBuildExecutable(ctx, p, instance, messages) if err != nil { - return core.BuildModel{}, err + return fail(core.StageResolve, err) } workingDirectory := filepath.Join(p.root, filepath.FromSlash(plan.WorkingDirectory)) output, runErr := captureBuildProcess(ctx, execution.Executable, plan.Arguments, workingDirectory, applyToolchainSelection(plan.Environment, execution.selection())) @@ -666,11 +673,39 @@ func (a *App) commandModel(ctx context.Context, p *project, instance buildInstan } model, decodeErr := kernel.DecodeBuildModel(ctx, instance.Manifest, instance.BuildSystemID, request) if decodeErr != nil { - return core.BuildModel{}, errors.Join(runErr, decodeErr) + return fail(buildCommandStage(runErr), errors.Join(runErr, decodeErr)) } + a.plugins.EndAttempt(ctx, attempt, buildCommandStage(runErr), runErr) return model, runErr } +// buildCommandStage is the stage at which a build command source that ran ends, given how its +// process ended: one that did not start is a launch failure, and one that failed is an exit, +// which also explains output that does not decode. Only a command that succeeded can end at +// decode, when its output is not a valid document. +// +// Preparing the plan and its output file is the plan stage and finding the build tool is the +// resolve stage; a deadline is a timeout at any stage, and a load the project's close cancels +// records nothing. A provider request is the plugin's own to log, so it is never recorded here. +func buildCommandStage(runErr error) core.PluginStage { + var launch *buildLaunchError + switch { + case errors.As(runErr, &launch): + return core.StageLaunch + case runErr != nil: + return core.StageExit + default: + return core.StageDecode + } +} + +// buildLaunchError is a build command whose process did not start, as opposed to one that ran +// and failed. Its text is the start's own. +type buildLaunchError struct{ cause error } + +func (e *buildLaunchError) Error() string { return e.cause.Error() } +func (e *buildLaunchError) Unwrap() error { return e.cause } + func (a *App) providerModel(ctx context.Context, p *project, instance buildInstance, kernel Kernel, refresh bool) (core.BuildModel, error) { // The host resolves the build tool the provider runs with, so the provider never searches // for it; an explicit tool setting that does not exist fails here, as it does for commands. @@ -730,7 +765,7 @@ func (a *App) finishBuildModel(p *project, id string, model core.BuildModel, err instance.modelReloadPending = false instance.modelLoaded = false if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_model_superseded", err)) + a.backgroundFailed("plugin_model_superseded", err) } if index == p.build.selected || p.runConfigs.wanted { a.loadBuildModel(p, index) @@ -879,6 +914,7 @@ func (a *App) runBuildTask(p *project, projectID, targetID, taskID string, userA if projectID != "" { project, ok := buildProjectByID(instance.Model, projectID) if !ok { + a.operationRejected("build_task", "project_missing") a.notifyError(a.text.Build.ProjectMissing) return nil, refuseBuild(refusalNotFound, "unknown build project") } @@ -887,6 +923,7 @@ func (a *App) runBuildTask(p *project, projectID, targetID, taskID string, userA if targetID != "" { target, ok := buildTargetByID(instance.Model, targetID) if !ok { + a.operationRejected("build_task", "target_missing") a.notifyError(a.text.Build.TargetMissing) return nil, refuseBuild(refusalNotFound, "unknown build target") } @@ -1085,7 +1122,7 @@ func captureBuildProcess(ctx context.Context, executable string, arguments []str outputMu.Unlock() }) if err != nil { - return "", err + return "", &buildLaunchError{cause: err} } waitErr := process.Wait() outputMu.Lock() @@ -1133,6 +1170,7 @@ func (a *App) runBuildEntry(p *project, entryID string) { } } if entry == nil { + a.operationRejected("build_run_entry", "target_missing") a.notifyError(a.text.Build.TargetMissing) return } @@ -1165,6 +1203,7 @@ func (a *App) runBuildTarget(p *project, targetID, runID string) { } target, ok := buildTargetByID(instance.Model, targetID) if !ok { + a.operationRejected("build_run_target", "target_missing") a.notifyError(a.text.Build.TargetMissing) return } @@ -1191,17 +1230,19 @@ func (a *App) debugProviderTarget(p *project, index int, projectID, targetID, ru instance := &p.build.instances[index] run, ok := buildRunDeclaration(instance.System, runID) if !ok || run.DebugAdapter == "" { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("build_debug_prepare", errors.New("the run declares no debug adapter"))) + a.operationFailed("build_debug_prepare", errors.New("the run declares no debug adapter")) a.notifyError(i18n.Shared(a.language(), "desktop.build.noDebugAdapter")) return } project, ok := buildProjectByID(instance.Model, projectID) if !ok { + a.operationRejected("build_debug_target", "project_missing") a.notifyError(a.text.Build.ProjectMissing) return } target, ok := buildTargetByID(instance.Model, targetID) if !ok { + a.operationRejected("build_debug_target", "target_missing") a.notifyError(a.text.Build.TargetMissing) return } @@ -1224,7 +1265,7 @@ func (a *App) debugProviderTarget(p *project, index int, projectID, targetID, ru fail := func(err error) func(*App) { return func(a *App) { p.debug.preparing = false - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("build_debug_prepare", err)) + a.operationFailed("build_debug_prepare", err) a.notifyError(err.Error()) } } @@ -1276,7 +1317,7 @@ func (a *App) debugProviderTarget(p *project, index int, projectID, targetID, ru func (a *App) redebugProviderTarget(p *project, reference core.RunProviderReference, projectID, targetID, runID string) { index := p.buildInstanceIndex(reference) if index < 0 { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("debug_rerun", errors.New("the debugged build instance is no longer detected"))) + a.operationFailed("debug_rerun", errors.New("the debugged build instance is no longer detected")) a.notifyError(a.text.Build.TargetMissing) return } @@ -1322,7 +1363,7 @@ func (a *App) startProviderDebug(p *project, pluginID string, preparation core.B }) return } - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("build_debug_start", errors.New("the plugin does not install the adapter its run names"))) + a.operationFailed("build_debug_start", errors.New("the plugin does not install the adapter its run names")) a.notifyError(i18n.Shared(a.language(), "desktop.build.noDebugAdapter")) }) } @@ -1585,7 +1626,7 @@ func (a *App) finishBuildError(p *project, op *buildOperation, err error) { failure = err.Error() } if a.endBuildOperation(p, op, "failed", nil, failure, err.Error()) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("build", err)) + a.operationFailed("build", err) } } diff --git a/desktop/internal/workbench/build_command_record_test.go b/desktop/internal/workbench/build_command_record_test.go new file mode 100644 index 0000000000..1fe1d5ee78 --- /dev/null +++ b/desktop/internal/workbench/build_command_record_test.go @@ -0,0 +1,280 @@ +package workbench + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +const buildCommandPluginID = "dev.lithe.test.build-command" + +// buildCommandManifest declares one build system whose model and dependencies are commands of +// the fixture-build tool, which is the copied test binary running TestBuildCommandRunner. +const buildCommandManifest = `{ + "schemaVersion": 0, + "id": "dev.lithe.test.build-command", + "displayName": "Build Command Fixture", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": {"buildSystems": 0}, + "vendor": {"id": "dev.lithe.test", "displayName": "Test", "signatureRequirement": "publisherPackage"}, + "permissions": ["process.build"], + "activationEvents": ["onBuildSystem:fixture"], + "languages": [], + "buildSystems": [{ + "id": "fixture", + "displayName": "Fixture", + "detection": {"markers": ["build.fixture"]}, + "invocation": {"executables": [{"kind": "command", "command": "fixture-build"}]}, + "model": { + "source": "command", + "arguments": ["-test.run=^TestBuildCommandRunner$"], + "decoder": "litheBuildModel", + "executesProjectCode": false, + "mayUseNetwork": false + }, + "dependencies": { + "source": "command", + "scopes": ["workspace"], + "arguments": ["-test.run=^TestBuildCommandRunner$"], + "decoder": "litheDependencies", + "executesProjectCode": false, + "mayUseNetwork": false + } + }] +}` + +// buildCommandMarker names the file in the command's working directory that tells the runner +// what to do: print a model or a tree, exit with a failure, print what is no document, or hang. +const buildCommandMarker = "build-command.marker" + +// TestBuildCommandRunner is the fixture build tool. It prints nothing of the testing package +// and exits by itself, since the host reads its whole output. +func TestBuildCommandRunner(t *testing.T) { + mode, err := os.ReadFile(buildCommandMarker) + if err != nil { + t.Skip("not the build command fixture workspace") + } + switch string(mode) { + case "model": + fmt.Print(`{"format":"litheBuildModel","version":0,"projects":[{"name":"fixture"}]}`) + case "dependencies": + fmt.Print(`{"format":"litheDependencies","version":0,"dependencies":[{"name":"fixture-dependency","children":[]}]}`) + case "fail": + os.Exit(3) + case "hang": + // The host kills the tool when the load's deadline passes; this only outlives it. + time.Sleep(pluginOperationWait) + default: + fmt.Print("not a document") + } + os.Exit(0) +} + +// buildCommandHarness opens an empty project in a window whose plugin kernel hands the test +// every recorded result, with a private plugin root for the build state. +func buildCommandHarness(t *testing.T) (*harness, *recordingPluginKernel, *project) { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, settingsFile), []byte(`{"theme":"dark"}`), 0o600); err != nil { + t.Fatal(err) + } + plugins := newRecordingPluginKernel() + h := newHarnessWithOptions(t, Options{ + Kernel: &testKernel{Client: core.NewClient()}, + PluginKernel: plugins, + PluginRoot: t.TempDir(), + Store: store.At(dir), + Languages: []string{"zh-Hans"}, + }) + h.open(t.TempDir()) + return h, plugins, h.app.project +} + +// installBuildTool puts the fixture build tool first on PATH and returns the PATH without it. +func installBuildTool(t *testing.T) string { + t.Helper() + bin := t.TempDir() + name := "fixture-build" + if runtime.GOOS == "windows" { + name += ".exe" + } + copyTestBinary(t, filepath.Join(bin, name)) + without := os.Getenv("PATH") + t.Setenv("PATH", bin+string(os.PathListSeparator)+without) + return without +} + +func writeBuildCommandMarker(t *testing.T, root, mode string) { + t.Helper() + if err := os.WriteFile(filepath.Join(root, buildCommandMarker), []byte(mode), 0o600); err != nil { + t.Fatal(err) + } +} + +// buildCommandInstance is the fixture's instance at root; provider makes it a system that +// declares a provider, whose plan may still answer with a command. +func buildCommandInstance(root string, provider bool) buildInstance { + return buildInstance{ + BuildInstance: core.BuildInstance{ID: "fixture@" + root, PluginID: buildCommandPluginID, BuildSystemID: "fixture", Root: root, ModelSource: "command"}, + PluginID: buildCommandPluginID, + Version: "1.0.0", + Manifest: json.RawMessage(buildCommandManifest), + System: pluginservice.BuildSystemDeclaration{Provider: provider}, + } +} + +// buildLoadContext is the context of a load the action op runs, bounded by timeout. +func buildLoadContext(t *testing.T, op string, timeout time.Duration) context.Context { + t.Helper() + ctx, cancel := context.WithTimeout(core.WithOrigin(context.Background(), core.Origin{Operation: op}), timeout) + t.Cleanup(cancel) + return ctx +} + +func failedBuildCommand(operation core.PluginOperationName, op string, stage core.PluginStage) core.PluginOperation { + return core.PluginOperation{PluginID: buildCommandPluginID, Operation: operation, Outcome: "failed", Stage: stage, OperationID: op} +} + +func TestBuildCommandModelLoadIsRecordedAtTheStageItEnded(t *testing.T) { + h, plugins, p := buildCommandHarness(t) + withoutTool := installBuildTool(t) + for _, tc := range []struct { + name string + mode string + root string + noTool bool + want core.PluginOperation + }{ + {name: "the model decodes", mode: "model", root: ".", want: core.PluginOperation{PluginID: buildCommandPluginID, Operation: core.OperationBuildModel, Outcome: "finished", OperationID: "action-41"}}, + {name: "the command fails", mode: "fail", root: ".", want: failedBuildCommand(core.OperationBuildModel, "action-41", core.StageExit)}, + {name: "the output is no model", mode: "garbage", root: ".", want: failedBuildCommand(core.OperationBuildModel, "action-41", core.StageDecode)}, + {name: "the command cannot start", mode: "model", root: "absent", want: failedBuildCommand(core.OperationBuildModel, "action-41", core.StageLaunch)}, + {name: "no build tool is found", mode: "model", root: ".", noTool: true, want: failedBuildCommand(core.OperationBuildModel, "action-41", core.StageResolve)}, + } { + t.Run(tc.name, func(t *testing.T) { + writeBuildCommandMarker(t, p.root, tc.mode) + if tc.noTool { + t.Setenv("PATH", withoutTool) + } + model, err := h.app.commandModel(buildLoadContext(t, "action-41", pluginOperationWait), p, buildCommandInstance(tc.root, false), h.app.kernel, h.app.text.Build) + if (err == nil) != (tc.want.Outcome == "finished") { + t.Fatalf("load error = %v, want outcome %s", err, tc.want.Outcome) + } + if err == nil && len(model.Projects) != 1 { + t.Fatalf("model = %+v, want the fixture project", model) + } + wantPluginOperation(t, plugins.next(t, tc.name), tc.want) + plugins.none(t) + }) + } +} + +func TestBuildCommandModelLoadPastItsDeadlineIsRecordedAsATimeout(t *testing.T) { + h, plugins, p := buildCommandHarness(t) + installBuildTool(t) + writeBuildCommandMarker(t, p.root, "hang") + _, err := h.app.commandModel(buildLoadContext(t, "action-42", 500*time.Millisecond), p, buildCommandInstance(".", false), h.app.kernel, h.app.text.Build) + if err == nil { + t.Fatal("a load past its deadline succeeded") + } + wantPluginOperation(t, plugins.next(t, "the hung model command"), failedBuildCommand(core.OperationBuildModel, "action-42", core.StageTimeout)) + plugins.none(t) +} + +func TestBuildCommandLoadTheProjectCancelsIsNotRecorded(t *testing.T) { + h, plugins, p := buildCommandHarness(t) + installBuildTool(t) + writeBuildCommandMarker(t, p.root, "model") + ctx, cancel := context.WithCancel(core.WithOrigin(context.Background(), core.Origin{Operation: "action-43"})) + cancel() + if _, err := h.app.commandModel(ctx, p, buildCommandInstance(".", false), h.app.kernel, h.app.text.Build); err == nil { + t.Fatal("a cancelled model load succeeded") + } + kernel := h.app.kernel.(buildDependencyKernel) + if _, err := h.app.buildDependencyTree(ctx, p, buildCommandInstance(".", false), kernel, nil, false); err == nil { + t.Fatal("a cancelled dependency load succeeded") + } + plugins.none(t) +} + +func TestBuildCommandDependencyLoadIsRecordedAtTheStageItEnded(t *testing.T) { + h, plugins, p := buildCommandHarness(t) + withoutTool := installBuildTool(t) + kernel, ok := h.app.kernel.(buildDependencyKernel) + if !ok { + t.Fatal("the test kernel does not load dependencies") + } + for _, tc := range []struct { + name string + mode string + provider bool + noTool bool + want core.PluginOperation + }{ + {name: "the tree decodes", mode: "dependencies", want: core.PluginOperation{PluginID: buildCommandPluginID, Operation: core.OperationBuildDependencies, Outcome: "finished", OperationID: "action-51"}}, + {name: "a provider system's command plan decodes", mode: "dependencies", provider: true, want: core.PluginOperation{PluginID: buildCommandPluginID, Operation: core.OperationBuildDependencies, Outcome: "finished", OperationID: "action-51"}}, + {name: "the command fails", mode: "fail", want: failedBuildCommand(core.OperationBuildDependencies, "action-51", core.StageExit)}, + {name: "the output is no tree", mode: "garbage", want: failedBuildCommand(core.OperationBuildDependencies, "action-51", core.StageDecode)}, + {name: "no build tool is found", mode: "dependencies", noTool: true, want: failedBuildCommand(core.OperationBuildDependencies, "action-51", core.StageResolve)}, + } { + t.Run(tc.name, func(t *testing.T) { + writeBuildCommandMarker(t, p.root, tc.mode) + if tc.noTool { + t.Setenv("PATH", withoutTool) + } + tree, err := h.app.buildDependencyTree(buildLoadContext(t, "action-51", pluginOperationWait), p, buildCommandInstance(".", tc.provider), kernel, nil, false) + if (err == nil) != (tc.want.Outcome == "finished") { + t.Fatalf("load error = %v, want outcome %s", err, tc.want.Outcome) + } + if err == nil && len(tree.Dependencies) != 1 { + t.Fatalf("tree = %+v, want the fixture dependency", tree) + } + wantPluginOperation(t, plugins.next(t, tc.name), tc.want) + plugins.none(t) + }) + } +} + +// A provider system that fails before its plan names a command never ran a command, and what +// its provider does is the plugin's own to log. +func TestBuildProviderSystemFailingBeforeItsPlanIsNotRecorded(t *testing.T) { + h, plugins, p := buildCommandHarness(t) + kernel := h.app.kernel.(buildDependencyKernel) + ctx := buildLoadContext(t, "action-52", pluginOperationWait) + if _, err := h.app.buildDependencyTree(ctx, p, buildCommandInstance(".", true), kernel, nil, false); err == nil { + t.Fatal("a provider system without its build tool loaded a tree") + } + plugins.none(t) +} + +func TestBuildCommandStage(t *testing.T) { + launch := &buildLaunchError{cause: errors.New("buildprocess: start fixture-build: no such directory")} + for _, tc := range []struct { + name string + runErr error + want core.PluginStage + }{ + {name: "the process did not start", runErr: launch, want: core.StageLaunch}, + {name: "a joined start failure", runErr: errors.Join(launch, errors.New("decode")), want: core.StageLaunch}, + {name: "the process failed", runErr: errors.New("exit status 3"), want: core.StageExit}, + {name: "the process succeeded", want: core.StageDecode}, + } { + if got := buildCommandStage(tc.runErr); got != tc.want { + t.Errorf("%s: stage = %q, want %q", tc.name, got, tc.want) + } + } + if launch.Error() != launch.cause.Error() || !errors.Is(launch, launch.cause) { + t.Fatalf("a start failure changed its text or cause: %q", launch.Error()) + } +} diff --git a/desktop/internal/workbench/build_dependencies.go b/desktop/internal/workbench/build_dependencies.go index 02bddbebce..e4d4991707 100644 --- a/desktop/internal/workbench/build_dependencies.go +++ b/desktop/internal/workbench/build_dependencies.go @@ -122,7 +122,7 @@ func (a *App) loadBuildDependencies(p *project, instance *buildInstance, project } deps.loading = false if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("build_dependencies", err)) + a.operationFailed("build_dependencies", err) deps.failed = err.Error() return } @@ -131,11 +131,23 @@ func (a *App) loadBuildDependencies(p *project, instance *buildInstance, project }) } -// buildDependencyTree plans, runs and decodes one dependency request. +// buildDependencyTree plans, runs and decodes one dependency request. A command plan has no +// plugin process to log it, so the host records it as the plugin's lithe/build/dependencies +// operation, at the stages buildCommandStage describes; a provider request is the plugin's own +// to log, and so is a provider system's failure before its plan says it is a command. func (a *App) buildDependencyTree(ctx context.Context, p *project, instance buildInstance, kernel buildDependencyKernel, selection *core.BuildSelection, refresh bool) (core.BuildDependencyTree, error) { + attempt := core.StartPluginAttempt(instance.PluginID, core.OperationBuildDependencies, core.OriginOf(ctx).Operation) + defer attempt.Abandon() + fail := func(stage core.PluginStage, err error) (core.BuildDependencyTree, error) { + a.plugins.EndAttempt(ctx, attempt, stage, err) + return core.BuildDependencyTree{}, err + } execution, err := a.resolveBuildExecutable(ctx, p, instance, a.text.Build) if err != nil { - return core.BuildDependencyTree{}, err + if instance.System.Provider { + return core.BuildDependencyTree{}, err + } + return fail(core.StageResolve, err) } // The package directory expands ${pluginDir} in a dependency command. request := core.BuildPlanRequest{Root: instance.Root, Options: instance.Options, PluginDirectory: instance.PackageDirectory, WorkspaceRoot: p.root, Project: selection} @@ -153,7 +165,7 @@ func (a *App) buildDependencyTree(ctx context.Context, p *project, instance buil return core.BuildDependencyTree{}, err } if plan.Provider == nil { - return a.commandDependencies(ctx, p, instance, kernel, plan, execution, decode, "") + return a.commandDependencies(ctx, p, instance, kernel, attempt, plan, execution, decode, "") } client, err := a.buildProvider(ctx, p, instance) if err != nil { @@ -173,11 +185,11 @@ func (a *App) buildDependencyTree(ctx context.Context, p *project, instance buil // A command may write its tree to a file the host allocates in the plugin's state. state := buildStateDirectory(a.plugins.Root, p.root, instance) if err := os.MkdirAll(state, 0o700); err != nil { - return core.BuildDependencyTree{}, err + return fail(core.StagePlan, err) } file, err := os.CreateTemp(state, "dependencies-*.json") if err != nil { - return core.BuildDependencyTree{}, err + return fail(core.StagePlan, err) } outputFile := file.Name() _ = file.Close() @@ -186,16 +198,17 @@ func (a *App) buildDependencyTree(ctx context.Context, p *project, instance buil request.OutputFile = outputFile plan, err := kernel.PlanBuildDependencies(ctx, instance.Manifest, instance.BuildSystemID, request) if err != nil { - return core.BuildDependencyTree{}, err + return fail(core.StagePlan, err) } if plan.Provider != nil { - return core.BuildDependencyTree{}, errors.New("the build system answered with a provider request") + return fail(core.StagePlan, errors.New("the build system answered with a provider request")) } - return a.commandDependencies(ctx, p, instance, kernel, plan, execution, decode, outputFile) + return a.commandDependencies(ctx, p, instance, kernel, attempt, plan, execution, decode, outputFile) } -// commandDependencies runs a command plan and decodes what it printed or wrote. -func (a *App) commandDependencies(ctx context.Context, p *project, instance buildInstance, kernel buildDependencyKernel, plan core.BuildPlan, execution buildExecution, decode core.BuildDecodeDependenciesRequest, outputFile string) (core.BuildDependencyTree, error) { +// commandDependencies runs a command plan and decodes what it printed or wrote, and ends the +// command's attempt with the result. +func (a *App) commandDependencies(ctx context.Context, p *project, instance buildInstance, kernel buildDependencyKernel, attempt *core.PluginAttempt, plan core.BuildPlan, execution buildExecution, decode core.BuildDecodeDependenciesRequest, outputFile string) (core.BuildDependencyTree, error) { workingDirectory := filepath.Join(p.root, filepath.FromSlash(plan.WorkingDirectory)) output, runErr := captureBuildProcess(ctx, execution.Executable, plan.Arguments, workingDirectory, applyToolchainSelection(plan.Environment, execution.selection())) if plan.Output == "outputFile" && outputFile != "" { @@ -205,8 +218,11 @@ func (a *App) commandDependencies(ctx context.Context, p *project, instance buil } tree, err := kernel.DecodeBuildDependencies(ctx, instance.Manifest, instance.BuildSystemID, decode) if err != nil { - return core.BuildDependencyTree{}, errors.Join(runErr, err) + err = errors.Join(runErr, err) + a.plugins.EndAttempt(ctx, attempt, buildCommandStage(runErr), err) + return core.BuildDependencyTree{}, err } + a.plugins.EndAttempt(ctx, attempt, buildCommandStage(runErr), runErr) return tree, runErr } diff --git a/desktop/internal/workbench/build_tests.go b/desktop/internal/workbench/build_tests.go index 4c33f44378..4ac0cb0a74 100644 --- a/desktop/internal/workbench/build_tests.go +++ b/desktop/internal/workbench/build_tests.go @@ -121,6 +121,7 @@ func buildProjectSelection(project core.BuildProject) *core.BuildSelection { func (a *App) runBuildProjectTests(p *project, instance *buildInstance, projectID string) { project, ok := buildProjectByID(instance.Model, projectID) if !ok { + a.operationRejected("build_tests", "project_missing") a.notifyError(a.text.Build.ProjectMissing) return } @@ -136,11 +137,13 @@ func (a *App) runBuildProjectTests(p *project, instance *buildInstance, projectI func (a *App) runBuildTargetTests(p *project, instance *buildInstance, targetID string) { target, ok := buildTargetByID(instance.Model, targetID) if !ok { + a.operationRejected("build_tests", "target_missing") a.notifyError(a.text.Build.TargetMissing) return } project, ok := buildProjectByID(instance.Model, target.ProjectID) if !ok { + a.operationRejected("build_tests", "project_missing") a.notifyError(a.text.Build.ProjectMissing) return } @@ -197,7 +200,7 @@ func (a *App) discoverBuildTests(p *project, instance *buildInstance, refresh bo } tests.loading = false if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("build_test_discovery", err)) + a.operationFailed("build_test_discovery", err) tests.failed = err.Error() return } diff --git a/desktop/internal/workbench/catalog.go b/desktop/internal/workbench/catalog.go index eadd3b8ffc..e5c2b9bd09 100644 --- a/desktop/internal/workbench/catalog.go +++ b/desktop/internal/workbench/catalog.go @@ -532,6 +532,7 @@ func (a *App) loadChrome() { var saved core.ChromeLayout found, err := a.store.Load(layoutFile, &saved) if err != nil { + a.storedStateFailed("chrome_layout", err) a.notifyError(a.text.Errors.Core(err.Error())) saved, found = core.ChromeLayout{}, false } @@ -542,10 +543,11 @@ func (a *App) loadChrome() { if !found { action = core.ResetChrome() } - ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) defer cancel() layout, _, err := a.kernel.ReduceChromeLayout(ctx, a.chrome.coreItems, saved, action) if err != nil { + a.operationFailed("chrome_layout_load", err) a.notifyError(a.text.Errors.Core(err.Error())) return } @@ -555,10 +557,11 @@ func (a *App) loadChrome() { // reduceChrome sends one layout action to the kernel, shows the result and saves it // when it changed. A failure leaves the arrangement as it was and is reported. func (a *App) reduceChrome(action core.ChromeAction) { - ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) defer cancel() layout, changed, err := a.kernel.ReduceChromeLayout(ctx, a.chrome.coreItems, a.chrome.layout, action) if err != nil { + a.operationFailed("chrome_layout_reduce", err) a.notifyError(a.text.Errors.Core(err.Error())) return } @@ -576,6 +579,7 @@ func (a *App) reduceChrome(action core.ChromeAction) { } saved := a.chrome.withAbsent(layout) if err := a.store.Save(layoutFile, saved); err != nil { + a.operationFailed("chrome_layout_save", documentLogError(err)) a.notifyError(a.text.Errors.SaveFailed(err.Error())) return } diff --git a/desktop/internal/workbench/changelists.go b/desktop/internal/workbench/changelists.go index 791ed6f032..b8a1fd838f 100644 --- a/desktop/internal/workbench/changelists.go +++ b/desktop/internal/workbench/changelists.go @@ -307,7 +307,7 @@ func (a *App) applyChangeLists(p *project, root string, statusGen int, job chang if err != nil { if job.action == nil { l.failed, l.members, l.scope = err, nil, nil - a.gitOperationFailed("git_changelists", err) + a.operationFailed("git_changelists", err) } return } @@ -444,7 +444,7 @@ func (a *App) changeListAction(p *project, operation string, action core.ChangeL // changeListFailed tells the user that a list action failed and logs it. func (a *App) changeListFailed(err error) { a.notifyError(a.text.Commit.Failed(err.Error())) - a.gitOperationFailed("git_changelists", err) + a.operationFailed("git_changelists", err) } // activateChangeList makes the list id the one stage all and commit take. @@ -504,7 +504,7 @@ func (a *App) submitChangeListName(p *project) { l.nameError = i18n.Shared(a.language(), "git.changelists.invalidName") default: l.nameError = err.Error() - a.gitOperationFailed("git_changelists", err) + a.operationFailed("git_changelists", err) } } if l.dialog == changeListRename { diff --git a/desktop/internal/workbench/changelists_select.go b/desktop/internal/workbench/changelists_select.go index b13268f6c8..677301c782 100644 --- a/desktop/internal/workbench/changelists_select.go +++ b/desktop/internal/workbench/changelists_select.go @@ -52,6 +52,7 @@ func (a *App) clickChangeRow(p *project, change core.GitChange, mods gfx.Modifie defer cancel() result, err := a.kernel.ReduceRowSelection(ctx, rows, selection, action) if err != nil { + a.operationFailed("changes_selection", err) a.notifyError(a.text.Errors.Core(err.Error())) return } diff --git a/desktop/internal/workbench/clone.go b/desktop/internal/workbench/clone.go index eec6019180..9a07c73f57 100644 --- a/desktop/internal/workbench/clone.go +++ b/desktop/internal/workbench/clone.go @@ -34,7 +34,7 @@ func (a *App) openClone(surface actionSurface) { c.name.SetText("") home, err := os.UserHomeDir() if err != nil { - a.gitOperationFailed("clone_home_directory", documentLogError(err)) + a.backgroundFailed("clone_home_directory", documentLogError(err)) } c.parent.SetText(home) a.performed("workspace.clone", surface) @@ -74,7 +74,7 @@ func (a *App) chooseCloneParent() { c := &a.clone if !c.open || c.generation != generation || c.busy { if err != nil && !errors.Is(err, app.ErrCanceled) { - a.gitOperationFailed("clone_choose_directory", documentLogError(err)) + a.operationFailed("clone_choose_directory", documentLogError(err)) } // log-exempt: 用户取消:关闭对话框后不再应用目录选择结果。 return @@ -84,7 +84,7 @@ func (a *App) chooseCloneParent() { return } if err != nil { - a.gitOperationFailed("clone_choose_directory", documentLogError(err)) + a.operationFailed("clone_choose_directory", documentLogError(err)) c.err = err.Error() return } @@ -111,13 +111,13 @@ func (a *App) submitClone() { parent, source := c.parent.Text(), c.source.Text() destination, valid := cloneDestination(parent, c.name.Text()) if !valid { - a.gitOperationFailed("git_clone_destination", errors.New("invalid clone destination")) + a.operationFailed("git_clone_destination", errors.New("invalid clone destination")) c.err = i18n.Shared(a.language(), "desktop.clone.invalidName") return } c.busy, c.cancelling, c.err = true, false, "" generation := c.generation - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), 30*time.Minute) c.cancel = cancel kernel := a.kernel a.background(nil, 0, func(context.Context) func(*App) { @@ -127,7 +127,7 @@ func (a *App) submitClone() { c := &a.clone if !c.open || c.generation != generation { if err != nil && !errors.Is(err, context.Canceled) { - a.gitOperationFailed("git_clone", errors.New("clone operation failed after closing")) + a.operationFailed("git_clone", errors.New("clone operation failed after closing")) } // log-exempt: 用户取消:关闭对话框后不再应用克隆结果。 return @@ -136,7 +136,7 @@ func (a *App) submitClone() { c.busy = false if c.cancelling || errors.Is(err, context.Canceled) { if err != nil && !errors.Is(err, context.Canceled) { - a.gitOperationFailed("git_clone", errors.New("clone operation failed during cancellation")) + a.operationFailed("git_clone", errors.New("clone operation failed during cancellation")) } // log-exempt: 用户取消:克隆已结束,任何部分目录留给用户处理。 a.closeClone() @@ -145,7 +145,7 @@ func (a *App) submitClone() { if err != nil { // Git's stderr can contain credentials or repository URLs. Neither // the on-screen message nor the log may reproduce those bytes. - a.gitOperationFailed("git_clone", errors.New("clone operation failed")) + a.operationFailed("git_clone", errors.New("clone operation failed")) c.err = i18n.Shared(a.language(), "desktop.clone.failed") return } diff --git a/desktop/internal/workbench/commands.go b/desktop/internal/workbench/commands.go index 8ac8b4e054..0bc5f15566 100644 --- a/desktop/internal/workbench/commands.go +++ b/desktop/internal/workbench/commands.go @@ -79,6 +79,7 @@ func (a *App) commands() []command { add("theme.dark", t.GroupView, t.ThemeDark, "", a.settings.Theme != themeDark, func() { a.setTheme(themeDark) }) add("window.fullscreen", t.GroupView, a.text.Keymap.ToggleFullscreen, "", a.window != nil, func() { if err := a.window.SetFullscreen(!a.window.Fullscreen()); err != nil { + a.operationFailed("window_fullscreen", err) a.notifyError(a.text.Keymap.FullscreenFailed(err.Error())) } }) diff --git a/desktop/internal/workbench/commit.go b/desktop/internal/workbench/commit.go index 80bda79b53..c85a8b2b09 100644 --- a/desktop/internal/workbench/commit.go +++ b/desktop/internal/workbench/commit.go @@ -382,7 +382,7 @@ func (a *App) commitFinished(c *commitState, session core.WorkspaceCommitSession a.notifySuccess(a.text.Commit.Done) default: a.notify(a.text.Commit.NeedsAttention) - a.gitOperationFailed("git_commit", incompleteRun(session)) + a.operationFailed("git_commit", incompleteRun(session)) } if session.Succeeded { c.resetMessage() @@ -422,42 +422,96 @@ func (a *App) commitFailed(err error) { } else { a.notifyError(a.text.Commit.Failed(err.Error())) } - a.gitOperationFailed("git_commit", err) + a.operationFailed("git_commit", err) } -// The log event of a Git operation that failed, and the level the kernel's event catalog -// declares for it. +// The log event of a failure that leaves the user without what they asked for, or without a +// feature they rely on, and the level the kernel's event catalog declares for it. The window +// shows the failure: a notice, an error in the dialog or panel, or a failed state. const ( operationFailedEvent = "app.notification.operation_failed" operationFailedLevel = core.LevelError ) -// The log event of a failure no notification reports, such as cleanup after the work is done, -// and the level the kernel's event catalog declares for it. It has the same fields as -// app.notification.operation_failed. +// The log event of a failure of work the window runs on its own and falls back from: a stale +// or superseded answer, a decoration or preview it skips, cleanup after the work is done. It +// has the same fields as app.notification.operation_failed. const ( backgroundFailedEvent = "app.background.operation_failed" backgroundFailedLevel = core.LevelWarn ) -// backgroundFailed logs a failure of work the window runs on its own and does not tell the -// user about. +// operationFailed logs, on the window thread, an operation the user asked for or a feature +// they rely on that did not complete. Off the window thread, operationFailedIn logs it. +func (a *App) operationFailed(operation string, err error) { + a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields(operation, err)) +} + +// operationFailedIn logs the same failure from any goroutine, under the user action ctx +// belongs to: the settings window and other workers that never touch the window thread's +// state use it. +func (a *App) operationFailedIn(ctx context.Context, operation string, err error) { + a.emitIn(ctx, operationFailedLevel, operationFailedEvent, operationFailedFields(operation, err)) +} + +// backgroundFailed logs, on the window thread, a failure of work the window runs on its own +// and falls back from. func (a *App) backgroundFailed(operation string, err error) { a.emit(backgroundFailedLevel, backgroundFailedEvent, operationFailedFields(operation, err)) } -// gitOperationFailed logs a Git operation that failed. -func (a *App) gitOperationFailed(operation string, err error) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields(operation, err)) +// backgroundFailedIn logs the same failure from any goroutine, under the user action ctx +// belongs to. +func (a *App) backgroundFailedIn(ctx context.Context, operation string, err error) { + a.emitIn(ctx, backgroundFailedLevel, backgroundFailedEvent, operationFailedFields(operation, err)) } -// operationFailedFields are the fields of app.notification.operation_failed. +// operationFailedFields are the fields of app.notification.operation_failed and +// app.background.operation_failed. func operationFailedFields(operation string, err error) map[string]any { fields := core.LogErrorFields(err) fields["operation"] = operation return fields } +// The log event of an operation the window refused before it ran, telling the user why: what +// it acts on is gone from the model or the file system, the answer it waited for is stale, or +// the action is not supported there. reason is a fixed token, never the notice or user input. +const ( + operationRejectedEvent = "app.notification.operation_rejected" + operationRejectedLevel = core.LevelWarn +) + +// operationRejected logs, on the window thread, an operation the window refused. +func (a *App) operationRejected(operation, reason string) { + a.emit(operationRejectedLevel, operationRejectedEvent, operationRejectedFields(operation, reason)) +} + +// operationRejectedIn logs the same refusal from any goroutine, under the user action ctx +// belongs to. +func (a *App) operationRejectedIn(ctx context.Context, operation, reason string) { + a.emitIn(ctx, operationRejectedLevel, operationRejectedEvent, operationRejectedFields(operation, reason)) +} + +// operationRejectedFields are the fields of app.notification.operation_rejected. +func operationRejectedFields(operation, reason string) map[string]any { + return map[string]any{"operation": operation, "reason": reason} +} + +// storedStateFailed logs, on the window thread, saved settings or window state that could not +// be read, which the window replaced with its defaults. stage names what was replaced. The +// error loses its path: the store's files are under the platform's application data folder. +func (a *App) storedStateFailed(stage string, err error) { + a.emit(core.LevelWarn, "app.settings.decode_failed", storedStateFields(stage, err)) +} + +// storedStateFields are the fields of app.settings.decode_failed. +func storedStateFields(stage string, err error) map[string]any { + fields := core.LogErrorFields(documentLogError(err)) + fields["stage"] = stage + return fields +} + // stageChange stages or unstages one change, as a click on its checkbox asks: a change with // nothing staged is staged, one that is partly staged gets the rest, and one that is fully // staged is unstaged. @@ -598,11 +652,11 @@ func (a *App) stagingDone(p *project, stage bool, err error) { func (a *App) stagingFailed(stage bool, err error) { if stage { a.notifyError(a.text.Commit.StageFailed(err.Error())) - a.gitOperationFailed("git_stage", err) + a.operationFailed("git_stage", err) return } a.notifyError(a.text.Commit.UnstageFailed(err.Error())) - a.gitOperationFailed("git_unstage", err) + a.operationFailed("git_unstage", err) } // refreshChanges reads the project's status again. diff --git a/desktop/internal/workbench/completion_merge.go b/desktop/internal/workbench/completion_merge.go index 7ae4d6821f..a50fb83eed 100644 --- a/desktop/internal/workbench/completion_merge.go +++ b/desktop/internal/workbench/completion_merge.go @@ -89,7 +89,7 @@ func (a *App) settleMergeSide(join *completionMergeJoin, server bool, items []co result, err := merger.MergeCompletions(ctx, lists) return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_semantics", err)) + a.backgroundFailed("plugin_semantics", err) a.finishMergedCompletion(join, concatCompletionSources(sources), anyIncomplete) return } @@ -172,7 +172,7 @@ func (a *App) settleServerCompletion(pending *semanticPending, event core.Backen } items, incomplete, err := core.PluginSemanticCompletions(event) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_semantics", err)) + a.backgroundFailed("plugin_semantics", err) a.settleMergeSide(pending.join, true, nil, false) return } diff --git a/desktop/internal/workbench/credentials_import.go b/desktop/internal/workbench/credentials_import.go index 00251f72e2..2cec03fc15 100644 --- a/desktop/internal/workbench/credentials_import.go +++ b/desktop/internal/workbench/credentials_import.go @@ -74,7 +74,7 @@ func (a *App) importLegacyCredentials() { lang := a.language() switch { case err != nil: - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("credentials_import_legacy", err)) + a.operationFailed("credentials_import_legacy", err) a.notifyError(i18n.SharedFormat(lang, "desktop.credentials.importLegacyFailed", map[string]string{"error": err.Error()})) case result == credentials.ImportResult{}: a.notifyInfo(i18n.Shared(lang, "desktop.credentials.importLegacyNone")) diff --git a/desktop/internal/workbench/debug.go b/desktop/internal/workbench/debug.go index 6828f3d358..eb9239d245 100644 --- a/desktop/internal/workbench/debug.go +++ b/desktop/internal/workbench/debug.go @@ -288,6 +288,11 @@ type debugSession struct { generation uint64 // adapter is the declaration the session runs, so a child session starts on the same adapter. adapter debugAdapter + // adapterStart is this session's start of its adapter, recorded on the plugin's channel + // once it has a result (see recordDebugStart). reached is set once the adapter can be + // talked to: its process runs, or its socket connected. + adapterStart *core.PluginAttempt + reached atomic.Bool // parent is the session whose adapter asked for this one through startDebugging; // startRequestID is that reverse request, answered once with this session's outcome. parent *debugSession @@ -331,12 +336,23 @@ func (s *debugSession) writeFrames(frames []string) error { return fmt.Errorf("debug frame: %w", err) } if _, err := transport.Write(data); err != nil { + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return &debugWriteTimedOut{cause: err} + } return err } } return nil } +// debugWriteTimedOut is a write the adapter did not take within the session's write deadline. +// Its text is the write's own; it also is a context.DeadlineExceeded, so the adapter start +// it ends is a timeout. +type debugWriteTimedOut struct{ cause error } + +func (e *debugWriteTimedOut) Error() string { return e.cause.Error() } +func (e *debugWriteTimedOut) Unwrap() []error { return []error{e.cause, context.DeadlineExceeded} } + // recordFailure keeps the reason Core failed the stream so the termination that // follows it can show that reason. func (s *debugSession) recordFailure(err error) { @@ -491,11 +507,16 @@ func (a *App) receiveDebug(p *project, session *debugSession, chunk []byte) { if session.stopped.Load() || p.ctx.Err() != nil { return } + // Bytes Core cannot read before initialize was answered fail the handshake. + a.recordDebugStart(session.ctx, session, core.StageInitialize, err) a.post(func(a *App) { a.finishDebugError(p, session, err) }) return } + a.debugAdapterAnswered(session, update.State) if err := session.writeFrames(update.OutboundFrames); err != nil && !session.stopped.Load() { - a.post(func(a *App) { a.finishDebugError(p, session, err) }) + if finish := a.debugWriteFailed(p, session, err); finish != nil { + a.post(finish) + } return } a.postDebugUpdate(p, session, update) @@ -825,6 +846,9 @@ func (a *App) releaseDebugSession(p *project, session *debugSession) { p.debug.removeSession(child) } session.stopped.Store(true) + // A start still without a result when its session is taken apart was stopped, or + // failed for a reason that is not the adapter's: it records nothing. + session.adapterStart.Abandon() session.cancel() drain := session.drainOnStop.Load() && session.hosted != nil if !drain { @@ -955,7 +979,7 @@ func (a *App) finishDebugError(p *project, session *debugSession, err error) { if errors.As(err, &settingsError) { message = i18n.Shared(a.language(), "desktop.debug.settingsUnreadable") } - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("debug", err)) + a.operationFailed("debug", err) a.endDebugSession(p, session) p.debug.failure = message if p.debug.activeSession() != nil { diff --git a/desktop/internal/workbench/debug_adapter_start.go b/desktop/internal/workbench/debug_adapter_start.go new file mode 100644 index 0000000000..fac986b618 --- /dev/null +++ b/desktop/internal/workbench/debug_adapter_start.go @@ -0,0 +1,99 @@ +package workbench + +import ( + "context" + "errors" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// A debug adapter is a declarative contribution: no plugin process reports its start, so the +// host records each one as a debugAdapter/start operation on the plugin's channel, under the +// debug session ID. The start runs from launch resolution until the adapter answers initialize: +// +// - resolve: the adapter's settings, plan, program or state directories cannot be resolved; +// - launch: the adapter is not reached, meaning its process does not run or its language +// server's socket does not connect; +// - timeout: the hosted adapter's discovery deadline, the initialize window, or a write's +// deadline ran out; +// - exit: a reached adapter's process or stream ended, or a stdio adapter stopped reading +// its input, before it answered initialize; +// - initialize: any other failure of a reached adapter before it answered initialize, a +// refused initialize included; +// - finished: the adapter answered initialize. +// +// A start the user stops, or one Core refuses (the debug session itself, a breakpoint), records +// nothing: the session's release abandons a start that has no result yet. + +// errDebugAdapterExited stands for an adapter whose process or stream ended before it answered +// initialize. The exit is the failure whatever its status, so it is never a nil error. +var errDebugAdapterExited = errors.New("debug adapter exited before initialize") + +// errDebugInitializeRefused stands for an adapter that answered initialize with a failure. +var errDebugInitializeRefused = errors.New("debug adapter refused initialize") + +// recordDebugStart records the session's adapter start once it has a result, ending at stage +// with err (nil for finished). The first result wins and later ones do nothing. ctx is the +// start's: a cancelled ctx is a stop, which records nothing and leaves the start open. It +// calls Core, so it never runs on the window thread. +func (a *App) recordDebugStart(ctx context.Context, session *debugSession, stage core.PluginStage, err error) { + a.plugins.EndAttempt(ctx, session.adapterStart, stage, err) +} + +// debugAdapterAnswered ends the adapter start once Core has read the adapter's answer to +// initialize: the session leaves initializing for a state that runs, or for one that ended. +func (a *App) debugAdapterAnswered(session *debugSession, state string) { + switch state { + case "", "idle", "initializing": + case "failed", "terminating", "terminated": + a.recordDebugStart(session.ctx, session, core.StageInitialize, errDebugInitializeRefused) + default: + a.recordDebugStart(session.ctx, session, "", nil) + } +} + +// debugWriteFailed ends a session that could not write to its adapter, or returns nil when +// the write failed only because the hosted stream no longer runs: the user stopped it, or Core +// failed it, and that failure's own report and termination end the start and the session with +// its reason. Before the adapter answered initialize, any other failed write also ends its +// start (a write past the deadline is a timeout): +// +// - a stdio adapter's input refuses a write only once the adapter stopped reading it, so +// the adapter left, as its process exit says too, whichever of the two comes first; +// - a hosted adapter's queue refuses one over its budget before its socket connected, +// which is a launch that did not reach it, or after, when the adapter takes no handshake. +func (a *App) debugWriteFailed(p *project, session *debugSession, err error) func(*App) { + if errors.Is(err, errDebugTransportNotRunning) { + return nil + } + stage := debugWriteFailureStage(session.process.Load() != nil, session.reached.Load()) + a.recordDebugStart(session.ctx, session, stage, err) + return func(a *App) { a.finishDebugError(p, session, err) } +} + +// debugWriteFailureStage is the stage a failed write ends the adapter start at, for a stdio +// adapter whose process runs, or a hosted one whose socket connected or not. +func debugWriteFailureStage(stdio, reached bool) core.PluginStage { + switch { + case stdio: + return core.StageExit + case reached: + return core.StageInitialize + default: + return core.StageLaunch + } +} + +// hostedFailureStage is the stage at which Core's failure of a hosted adapter's stream ends +// its start: its startup deadline is a timeout; any other failure is a launch until the socket +// connected and an initialize failure after. +func hostedFailureStage(reached bool, reason string) core.PluginStage { + switch { + case reason == "startupTimedOut": + return core.StageTimeout + case !reached: + return core.StageLaunch + default: + return core.StageInitialize + } +} diff --git a/desktop/internal/workbench/debug_adapter_start_test.go b/desktop/internal/workbench/debug_adapter_start_test.go new file mode 100644 index 0000000000..5ce614b286 --- /dev/null +++ b/desktop/internal/workbench/debug_adapter_start_test.go @@ -0,0 +1,288 @@ +package workbench + +import ( + "context" + "errors" + "net" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +const ( + debugFixturePluginID = "dev.lithe.test.debug-adapter" + debugHostedPluginID = "dev.lithe.test.debug-hosted" +) + +// wantDebugStart checks a recorded adapter start of session against outcome and stage. +func wantDebugStart(t *testing.T, got core.PluginOperation, pluginID string, session *debugSession, outcome string, stage core.PluginStage) { + t.Helper() + wantPluginOperation(t, got, core.PluginOperation{PluginID: pluginID, Operation: core.OperationDebugAdapterStart, Outcome: outcome, Stage: stage, OperationID: session.id}) +} + +// awaitDebugSessionDone waits until nothing of session can still record: its startup returned +// and, when it started a process, the process's watcher did. +func awaitDebugSessionDone(t *testing.T, session *debugSession) { + t.Helper() + select { + case <-session.startupDone: + case <-time.After(debugAdapterExitWait): + t.Fatal("the debug startup did not finish before the deadline") + } + if session.process.Load() == nil { + return + } + select { + case <-session.exitObserved: + case <-time.After(debugAdapterExitWait): + t.Fatal("the adapter process was not observed to exit before the deadline") + } +} + +func writeDebugMarker(t *testing.T, root, mode string) { + t.Helper() + if err := os.WriteFile(filepath.Join(root, "debug.marker"), []byte(mode), 0o600); err != nil { + t.Fatal(err) + } +} + +func TestDebugAdapterStartIsRecordedWhenTheAdapterAnswersInitialize(t *testing.T) { + plugins := newRecordingPluginKernel() + h := debugPluginHarnessOn(t, debugFixturePluginID, debugFixtureManifest, true, plugins) + root := t.TempDir() + writeDebugMarker(t, root, "debug") + p := openDebugPanel(t, h, root) + h.app.startDebug(p) + session := p.debug.activeSession() + awaitStateWithin(t, h, debugAdapterExitWait, "the paused session", func() bool { + if p.debug.failure != "" { + t.Fatalf("debug start failed: %s", p.debug.failure) + } + return p.debug.state == "paused" + }) + wantDebugStart(t, plugins.next(t, "the adapter start"), debugFixturePluginID, session, "finished", "") + + // The session's later work and its stop are not the start: nothing more is recorded. + h.app.stopDebug(p) + awaitStateWithin(t, h, debugAdapterExitWait, "the stopped session", func() bool { return p.debug.activeSession() == nil }) + awaitDebugSessionDone(t, session) + plugins.none(t) +} + +func TestDebugAdapterThatExitsBeforeInitializeIsRecordedAsAnExit(t *testing.T) { + plugins := newRecordingPluginKernel() + h := debugPluginHarnessOn(t, debugFixturePluginID, debugFixtureManifest, true, plugins) + root := t.TempDir() + writeDebugMarker(t, root, "exit") + p := openDebugPanel(t, h, root) + h.app.startDebug(p) + session := p.debug.activeSession() + awaitStateWithin(t, h, debugAdapterExitWait, "adapter exit to release session", func() bool { return p.debug.activeSession() == nil }) + // The exit is recorded once, whether the process watcher or the refused initialize write + // sees it first. + wantDebugStart(t, plugins.next(t, "the adapter exit"), debugFixturePluginID, session, "failed", core.StageExit) + awaitDebugSessionDone(t, session) + plugins.none(t) +} + +func TestDebugAdapterWhoseProgramIsMissingIsRecordedAsUnresolved(t *testing.T) { + plugins := newRecordingPluginKernel() + manifest := strings.Replace(debugFixtureManifest, `"path": "adapter"`, `"path": "absent-adapter"`, 1) + h := debugPluginHarnessOn(t, debugFixturePluginID, manifest, true, plugins) + root := t.TempDir() + writeDebugMarker(t, root, "debug") + p := openDebugPanel(t, h, root) + h.app.startDebug(p) + session := p.debug.activeSession() + awaitStateWithin(t, h, debugAdapterExitWait, "the failed start", func() bool { return p.debug.failure != "" }) + wantDebugStart(t, plugins.next(t, "the unresolved adapter"), debugFixturePluginID, session, "failed", core.StageResolve) + awaitDebugSessionDone(t, session) + plugins.none(t) +} + +func TestDebugAdapterStartTheUserStopsIsNotRecorded(t *testing.T) { + plugins := newRecordingPluginKernel() + h := debugPluginHarnessOn(t, debugFixturePluginID, debugFixtureManifest, true, plugins) + root := t.TempDir() + writeDebugMarker(t, root, "debug") + p := openDebugPanel(t, h, root) + // The adapter runs but is sent nothing while Core creates the session, so Stop comes before + // the adapter can answer. + gate := &delayedDebugCreate{Kernel: h.app.kernel, entered: make(chan struct{}), release: make(chan struct{}), destroyed: make(chan string, 4)} + h.app.kernel = gate + var once sync.Once + release := func() { once.Do(func() { close(gate.release) }) } + t.Cleanup(release) + h.app.startDebug(p) + session := p.debug.activeSession() + select { + case <-gate.entered: + case <-time.After(debugAdapterExitWait): + t.Fatal("the session create did not start") + } + h.app.stopDebug(p) + release() + awaitStateWithin(t, h, debugAdapterExitWait, "the stopped session", func() bool { return p.debug.activeSession() == nil }) + awaitDebugSessionDone(t, session) + plugins.none(t) +} + +func TestDebugHostedAdapterStartIsRecordedWhenItAnswersInitialize(t *testing.T) { + plugins := newRecordingPluginKernel() + h := debugPluginHarnessOn(t, debugHostedPluginID, debugHostedManifest, false, plugins) + root, _ := fixtureWorkspace(t) + server := serveHostedAdapter(t, root, false) + h.app.debugHostedPort = func(context.Context, *project, debugAdapter) (int, error) { return server.port(), nil } + p := openHostedPanel(t, h, root) + h.app.startDebug(p) + session := p.debug.activeSession() + awaitStateWithin(t, h, debugAdapterExitWait, "the paused hosted session", func() bool { + if p.debug.failure != "" { + t.Fatalf("debug start failed: %s", p.debug.failure) + } + return p.debug.state == "paused" + }) + wantDebugStart(t, plugins.next(t, "the hosted adapter start"), debugHostedPluginID, session, "finished", "") + h.app.stopDebug(p) + awaitStateWithin(t, h, debugAdapterExitWait, "the stopped session", func() bool { return p.debug.activeSession() == nil }) + awaitDebugSessionDone(t, session) + plugins.none(t) +} + +func TestDebugHostedAdapterThatCannotBeReachedIsRecordedAsALaunchFailure(t *testing.T) { + for name, port := range map[string]func(t *testing.T) func(context.Context, *project, debugAdapter) (int, error){ + "the endpoint command fails": func(*testing.T) func(context.Context, *project, debugAdapter) (int, error) { + return func(context.Context, *project, debugAdapter) (int, error) { + return 0, errors.New("the server has no debug command") + } + }, + "nothing listens on the port": func(t *testing.T) func(context.Context, *project, debugAdapter) (int, error) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + closed := listener.Addr().(*net.TCPAddr).Port + _ = listener.Close() + return func(context.Context, *project, debugAdapter) (int, error) { return closed, nil } + }, + } { + t.Run(name, func(t *testing.T) { + plugins := newRecordingPluginKernel() + h := debugPluginHarnessOn(t, debugHostedPluginID, debugHostedManifest, false, plugins) + root, _ := fixtureWorkspace(t) + h.app.debugHostedPort = port(t) + p := openHostedPanel(t, h, root) + h.app.startDebug(p) + session := p.debug.activeSession() + awaitStateWithin(t, h, debugAdapterExitWait, "the failure", func() bool { return p.debug.failure != "" }) + wantDebugStart(t, plugins.next(t, "the unreached adapter"), debugHostedPluginID, session, "failed", core.StageLaunch) + awaitDebugSessionDone(t, session) + plugins.none(t) + }) + } +} + +func TestDebugHostedAdapterThatNeverAnswersIsRecordedAsATimeout(t *testing.T) { + plugins := newRecordingPluginKernel() + h := debugPluginHarnessOn(t, debugHostedPluginID, debugHostedManifest, false, plugins) + root, _ := fixtureWorkspace(t) + server := serveHostedAdapter(t, root, true) + h.app.debugHostedPort = func(context.Context, *project, debugAdapter) (int, error) { return server.port(), nil } + h.app.debugInitializeWindow = 300 * time.Millisecond + p := openHostedPanel(t, h, root) + h.app.startDebug(p) + session := p.debug.activeSession() + awaitStateWithin(t, h, debugAdapterExitWait, "the timeout", func() bool { return p.debug.failure != "" }) + wantDebugStart(t, plugins.next(t, "the silent adapter"), debugHostedPluginID, session, "failed", core.StageTimeout) + awaitDebugSessionDone(t, session) + plugins.none(t) +} + +// The adapter's first answer Core read decides the start: a state that runs finishes it, one +// that ended fails it at initialize, and one still initializing leaves it open. A later answer +// changes nothing, and a stop records nothing. +func TestDebugAdapterAnswerEndsTheStartByItsState(t *testing.T) { + plugins := newRecordingPluginKernel() + h := debugPluginHarnessOn(t, debugFixturePluginID, debugFixtureManifest, true, plugins) + for _, c := range []struct { + state string + outcome string + stage core.PluginStage + }{ + {state: ""}, {state: "idle"}, {state: "initializing"}, + {state: "ready", outcome: "finished"}, {state: "launching", outcome: "finished"}, + {state: "running", outcome: "finished"}, {state: "paused", outcome: "finished"}, + {state: "failed", outcome: "failed", stage: core.StageInitialize}, + {state: "terminating", outcome: "failed", stage: core.StageInitialize}, + {state: "terminated", outcome: "failed", stage: core.StageInitialize}, + } { + id := "desktop-debug-answer-" + c.state + session := &debugSession{id: id, ctx: context.Background(), adapterStart: core.StartPluginAttempt(debugFixturePluginID, core.OperationDebugAdapterStart, id)} + h.app.debugAdapterAnswered(session, c.state) + if c.outcome == "" { + plugins.none(t) + continue + } + wantDebugStart(t, plugins.next(t, "state "+c.state), debugFixturePluginID, session, c.outcome, c.stage) + h.app.debugAdapterAnswered(session, "failed") + plugins.none(t) + } + + stopped, cancel := context.WithCancel(context.Background()) + cancel() + session := &debugSession{id: "desktop-debug-stopped", ctx: stopped, adapterStart: core.StartPluginAttempt(debugFixturePluginID, core.OperationDebugAdapterStart, "desktop-debug-stopped")} + h.app.debugAdapterAnswered(session, "failed") + h.app.recordDebugStart(stopped, session, core.StageExit, errDebugAdapterExited) + plugins.none(t) + + // A write past the session's write deadline is a timeout, whatever stage it was at. + session = &debugSession{id: "desktop-debug-write", ctx: context.Background(), adapterStart: core.StartPluginAttempt(debugFixturePluginID, core.OperationDebugAdapterStart, "desktop-debug-write")} + h.app.recordDebugStart(session.ctx, session, core.StageExit, &debugWriteTimedOut{cause: os.ErrClosed}) + wantDebugStart(t, plugins.next(t, "the timed-out write"), debugFixturePluginID, session, "failed", core.StageTimeout) + + // A write the hosted stream refused because it no longer runs leaves the start and the + // session to that stream's own failure, which carries the reason. + session = &debugSession{id: "desktop-debug-stream", ctx: context.Background(), adapterStart: core.StartPluginAttempt(debugHostedPluginID, core.OperationDebugAdapterStart, "desktop-debug-stream")} + if finish := h.app.debugWriteFailed(nil, session, errDebugTransportNotRunning); finish != nil { + t.Fatal("a write to a stream that no longer runs ended the session itself") + } + plugins.none(t) +} + +func TestDebugAdapterFailureStages(t *testing.T) { + for _, c := range []struct { + reached bool + reason string + want core.PluginStage + }{ + {reason: "startupTimedOut", want: core.StageTimeout}, + {reached: true, reason: "startupTimedOut", want: core.StageTimeout}, + {reason: "connectFailed", want: core.StageLaunch}, + {reached: true, reason: "readFailed", want: core.StageInitialize}, + } { + if got := hostedFailureStage(c.reached, c.reason); got != c.want { + t.Errorf("hostedFailureStage(%v, %q) = %q, want %q", c.reached, c.reason, got, c.want) + } + } + for _, c := range []struct { + stdio, reached bool + want core.PluginStage + }{ + {stdio: true, reached: true, want: core.StageExit}, + {reached: true, want: core.StageInitialize}, + {want: core.StageLaunch}, + } { + if got := debugWriteFailureStage(c.stdio, c.reached); got != c.want { + t.Errorf("debugWriteFailureStage(%v, %v) = %q, want %q", c.stdio, c.reached, got, c.want) + } + } + timedOut := &debugWriteTimedOut{cause: os.ErrClosed} + if !errors.Is(timedOut, context.DeadlineExceeded) || !errors.Is(timedOut, os.ErrClosed) || timedOut.Error() != os.ErrClosed.Error() { + t.Fatalf("debugWriteTimedOut = %v, want the write's text that is also a deadline", timedOut) + } +} diff --git a/desktop/internal/workbench/debug_breakpoints.go b/desktop/internal/workbench/debug_breakpoints.go index dec9295402..436b073e7b 100644 --- a/desktop/internal/workbench/debug_breakpoints.go +++ b/desktop/internal/workbench/debug_breakpoints.go @@ -295,6 +295,8 @@ func (a *App) requestDataBreakpoint(p *project, name string, variablesReference return a.kernel.DebugDataBreakpointInfo(ctx, session.id, operationID, name, variablesReference) }, debugOperationHandlers{done: func(a *App, result core.DebugOperationResult) { if result.Kind != "dataBreakpointInfo" || result.DataID == "" { + // The adapter has no data breakpoint for the variable. + a.operationRejected("debug_data_breakpoint", "data_unavailable") a.notifyError(a.text.Debug.Breakpoint.DataUnavailable) return } diff --git a/desktop/internal/workbench/debug_child.go b/desktop/internal/workbench/debug_child.go index fc4945702b..27cd76c989 100644 --- a/desktop/internal/workbench/debug_child.go +++ b/desktop/internal/workbench/debug_child.go @@ -77,7 +77,7 @@ func (a *App) failChildDebug(p *project, child *debugSession, err error) { if a.project != p || !p.debug.hasSession(child) { return } - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("debug", err)) + a.operationFailed("debug", err) a.endDebugSession(p, child) p.debug.failure = message if p.debug.activeSession() != nil { diff --git a/desktop/internal/workbench/debug_launch.go b/desktop/internal/workbench/debug_launch.go index 8fea61b7fe..879f63e1cf 100644 --- a/desktop/internal/workbench/debug_launch.go +++ b/desktop/internal/workbench/debug_launch.go @@ -23,6 +23,16 @@ type debugSettingsError struct{ cause error } func (e *debugSettingsError) Error() string { return e.cause.Error() } func (e *debugSettingsError) Unwrap() error { return e.cause } +// debugAdapterUnresolved marks a preparation failure of the adapter's own launch, as opposed +// to the debuggee's: its settings, plan, program or state directories could not be resolved. +// Only these end the plugin's adapter start. The text is the cause's. +type debugAdapterUnresolved struct{ cause error } + +func (e *debugAdapterUnresolved) Error() string { return e.cause.Error() } +func (e *debugAdapterUnresolved) Unwrap() error { return e.cause } + +func adapterUnresolved(err error) error { return &debugAdapterUnresolved{cause: err} } + // preparedDebugLaunch contains only Core's plan and verified native executable paths. type preparedDebugLaunch struct { Executable string @@ -120,13 +130,13 @@ func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDir hosted := adapter.Declaration.Transport == "tcpLanguageServer" settings, err := a.loadPluginPreferenceSources(ctx, adapter.Manifest, root) if err != nil { - return preparedDebugLaunch{}, &debugSettingsError{cause: err} + return preparedDebugLaunch{}, adapterUnresolved(&debugSettingsError{cause: err}) } directories := core.PluginBackendDirectories{ PluginDirectory: adapter.Directory, StateDirectory: stateDirectory, WorkspaceStateDirectory: filepath.Join(stateDirectory, "workspace"), - LogDirectory: filepath.Join(stateDirectory, "log"), + LogDirectory: a.pluginLogDirectory(ctx, adapter.PluginID), TemporaryDirectory: filepath.Join(stateDirectory, "tmp"), Architecture: core.PluginArchitecture(), Settings: settings.State.Settings, @@ -134,7 +144,7 @@ func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDir } plan, err := a.kernel.PlanPluginDebugAdapter(ctx, adapter.Manifest, adapter.Declaration.ID, directories) if err != nil { - return preparedDebugLaunch{}, err + return preparedDebugLaunch{}, adapterUnresolved(err) } var executable string processArguments := plan.Arguments @@ -144,10 +154,10 @@ func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDir if !hosted { executable, processArguments, environment, err = a.resolveAdapterProcess(ctx, adapter, plan, root, stateDirectory) if err != nil { - return preparedDebugLaunch{}, err + return preparedDebugLaunch{}, adapterUnresolved(err) } if executable == "" { - return preparedDebugLaunch{}, errors.New(unavailable) + return preparedDebugLaunch{}, adapterUnresolved(errors.New(unavailable)) } } target := core.DebugTargetFacts{Kind: "file", Path: targetPath, WorkingDirectory: root, Arguments: []string{}, Environment: map[string]string{}} @@ -215,16 +225,16 @@ func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDir for _, directory := range plan.RequiredDirectories { relative, err := filepath.Rel(stateDirectory, directory) if err != nil { - return preparedDebugLaunch{}, err + return preparedDebugLaunch{}, adapterUnresolved(err) } if relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) || filepath.IsAbs(relative) { - return preparedDebugLaunch{}, errors.New(unavailable) + return preparedDebugLaunch{}, adapterUnresolved(errors.New(unavailable)) } if err := ctx.Err(); err != nil { return preparedDebugLaunch{}, err } if err := os.MkdirAll(directory, 0o700); err != nil { - return preparedDebugLaunch{}, err + return preparedDebugLaunch{}, adapterUnresolved(err) } } prepared := preparedDebugLaunch{ diff --git a/desktop/internal/workbench/debug_relocate.go b/desktop/internal/workbench/debug_relocate.go index 65096c880f..f1cd83a10d 100644 --- a/desktop/internal/workbench/debug_relocate.go +++ b/desktop/internal/workbench/debug_relocate.go @@ -37,7 +37,7 @@ func (a *App) relocateDocumentBreakpoints(p *project, d *document, edit editorvi }, sourceBreakpoints(lines)) cancel() if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("debug_relocate", err)) + a.backgroundFailed("debug_relocate", err) return } next := make([]debugBreakpoint, 0, len(moved)) diff --git a/desktop/internal/workbench/debug_start.go b/desktop/internal/workbench/debug_start.go index 5f33238512..3207e55c85 100644 --- a/desktop/internal/workbench/debug_start.go +++ b/desktop/internal/workbench/debug_start.go @@ -432,8 +432,9 @@ func (a *App) beginDebug(p *project, start debugStart) { breakpoints[path] = append([]debugBreakpoint(nil), lines...) } ctx, cancel := context.WithCancel(p.ctx) + id := fmt.Sprintf("desktop-debug-%d", debugSessionSequence.Add(1)) session := &debugSession{ - id: fmt.Sprintf("desktop-debug-%d", debugSessionSequence.Add(1)), + id: id, adapterID: adapter.Declaration.AdapterID, project: p, cancel: cancel, @@ -446,6 +447,9 @@ func (a *App) beginDebug(p *project, start debugStart) { adapter: adapter, parent: start.parent, startRequestID: start.startRequestID, + // The debug session ID is the start's operation ID, so its result sits with the + // session's own debug records. + adapterStart: core.StartPluginAttempt(adapter.PluginID, core.OperationDebugAdapterStart, id), } // A session started while the breakpoints are muted starts muted. session.muted.Store(p.debug.muted) @@ -464,7 +468,7 @@ func (a *App) beginDebug(p *project, start debugStart) { p.debug.state = "failed" p.debug.failure = err.Error() } - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("debug", err)) + a.operationFailed("debug", err) return } stdinReader = reader @@ -497,16 +501,27 @@ func (a *App) beginDebug(p *project, start debugStart) { return nil } if err := os.MkdirAll(stateRoot, 0o700); err != nil { + a.recordDebugStart(ctx, session, core.StageResolve, err) return func(a *App) { a.finishDebugError(p, session, err) } } stateDirectory, err := os.MkdirTemp(stateRoot, "desktop-debug-") if err != nil { + a.recordDebugStart(ctx, session, core.StageResolve, err) return func(a *App) { a.finishDebugError(p, session, err) } } // Assigned only by startup; cleanup reads it after startupDone closes. session.stateDirectory = stateDirectory preparationContext, cancelPreparation := context.WithTimeout(ctx, debugOperationTimeout) prepared, err := a.prepareDebugLaunch(preparationContext, start, session.stateDirectory, p.root, targetPath, generation, targetUnavailable) + if err != nil { + // Only the adapter's own launch is the plugin's start; a debuggee that cannot be + // found or a remote endpoint waiting for the user is not. The preparation's + // context says whether its deadline stopped it, so it is read before release. + var unresolved *debugAdapterUnresolved + if errors.As(err, &unresolved) || errors.Is(preparationContext.Err(), context.DeadlineExceeded) { + a.recordDebugStart(preparationContext, session, core.StageResolve, err) + } + } cancelPreparation() if err != nil { return func(a *App) { a.finishDebugError(p, session, err) } @@ -518,9 +533,11 @@ func (a *App) beginDebug(p *project, start debugStart) { } if hosted { if err := a.openHostedTransport(p, session, adapter, messages); err != nil { + a.recordDebugStart(ctx, session, core.StageLaunch, err) return func(a *App) { a.finishDebugError(p, session, err) } } } else if err := a.startAdapterProcess(ctx, p, session, prepared, stdinReader); err != nil { + a.recordDebugStart(ctx, session, core.StageLaunch, err) return func(a *App) { a.finishDebugError(p, session, err) } } update, err := a.kernel.CreateDebugSession(ctx, core.DebugCreateSessionRequest{ @@ -551,7 +568,7 @@ func (a *App) beginDebug(p *project, start debugStart) { } a.watchDebugInitialize(p, session, window) if err := session.writeFrames(update.OutboundFrames); err != nil { - return func(a *App) { a.finishDebugError(p, session, err) } + return a.debugWriteFailed(p, session, err) } a.postDebugUpdate(p, session, update) // Muting comes before the first breakpoint set, so a muted session never stops on @@ -562,7 +579,7 @@ func (a *App) beginDebug(p *project, start debugStart) { return func(a *App) { a.finishDebugError(p, session, err) } } if err := session.writeFrames(update.OutboundFrames); err != nil { - return func(a *App) { a.finishDebugError(p, session, err) } + return a.debugWriteFailed(p, session, err) } a.postDebugUpdate(p, session, update) } @@ -572,7 +589,7 @@ func (a *App) beginDebug(p *project, start debugStart) { return func(a *App) { a.finishDebugError(p, session, err) } } if err := session.writeFrames(update.OutboundFrames); err != nil { - return func(a *App) { a.finishDebugError(p, session, err) } + return a.debugWriteFailed(p, session, err) } a.postDebugUpdate(p, session, update) } @@ -582,7 +599,7 @@ func (a *App) beginDebug(p *project, start debugStart) { return func(a *App) { a.finishDebugError(p, session, err) } } if err := session.writeFrames(update.OutboundFrames); err != nil { - return func(a *App) { a.finishDebugError(p, session, err) } + return a.debugWriteFailed(p, session, err) } a.postDebugUpdate(p, session, update) } @@ -592,7 +609,7 @@ func (a *App) beginDebug(p *project, start debugStart) { return func(a *App) { a.finishDebugError(p, session, err) } } if err := session.writeFrames(update.OutboundFrames); err != nil { - return func(a *App) { a.finishDebugError(p, session, err) } + return a.debugWriteFailed(p, session, err) } a.postDebugUpdate(p, session, update) } @@ -601,7 +618,7 @@ func (a *App) beginDebug(p *project, start debugStart) { return func(a *App) { a.finishDebugError(p, session, err) } } if err := session.writeFrames(update.OutboundFrames); err != nil { - return func(a *App) { a.finishDebugError(p, session, err) } + return a.debugWriteFailed(p, session, err) } a.postDebugUpdate(p, session, update) return nil @@ -613,6 +630,9 @@ func (a *App) beginDebug(p *project, start debugStart) { // deadline); the host only runs the clock. func (a *App) watchDebugInitialize(p *project, session *debugSession, window time.Duration) { timer := time.AfterFunc(window, func() { + // The window is the start's deadline: an adapter start that has no result by now + // timed out. A start that already ended keeps its result. + a.recordDebugStart(session.ctx, session, core.StageTimeout, context.DeadlineExceeded) a.post(func(a *App) { if a.project != p || !p.debug.hasSession(session) { return @@ -651,10 +671,14 @@ func (a *App) startAdapterProcess(ctx context.Context, p *project, session *debu return err } session.process.Store(process) + session.reached.Store(true) // Observe native exit even when the adapter cannot send a DAP terminated event. go func() { defer close(session.exitObserved) err := process.Wait() + // An exit before initialize was answered ends the start, whatever its status. It is + // read before the session's context ends, which would make it a stop by the user. + a.recordDebugStart(session.ctx, session, core.StageExit, errDebugAdapterExited) session.cancel() session.closeTransport() a.debugStreamEnded(p, session, err) @@ -710,15 +734,25 @@ func (a *App) openHostedTransport(p *project, session *debugSession, adapter deb return debugLoopback, port, err } hooks := debugTransportHooks{ - Discover: discover, - Deliver: func(data []byte) { a.receiveDebug(p, session, data) }, + Discover: discover, + Connected: func() { session.reached.Store(true) }, + Deliver: func(data []byte) { a.receiveDebug(p, session, data) }, Failure: func(reason, message string) { - session.recordFailure(debugTransportFailureText(messages, reason, message)) + failure := debugTransportFailureText(messages, reason, message) + session.recordFailure(failure) + a.recordDebugStart(session.ctx, session, hostedFailureStage(session.reached.Load(), reason), failure) }, Terminated: func(exitCode int) { if session.stopped.Load() { return } + // A failure already ended the start; a clean close of a reached socket before + // initialize was answered is the adapter leaving. + stage := core.StageExit + if !session.reached.Load() { + stage = core.StageLaunch + } + a.recordDebugStart(session.ctx, session, stage, errDebugAdapterExited) if exitCode == 0 { a.debugStreamEnded(p, session, nil) return diff --git a/desktop/internal/workbench/debug_tcp_test.go b/desktop/internal/workbench/debug_tcp_test.go index 4c1fbe3e42..b03119cb5b 100644 --- a/desktop/internal/workbench/debug_tcp_test.go +++ b/desktop/internal/workbench/debug_tcp_test.go @@ -13,6 +13,7 @@ import ( "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginstate" "github.com/1lck/Lithe-IDEA/desktop/internal/store" ) @@ -74,6 +75,12 @@ const debugAttachManifest = `{ // debugPluginHarness installs one fixture plugin (and the copied test binary when // it has a stdio process) and opens a window over it. func debugPluginHarness(t *testing.T, id, manifest string, withBinary bool) *harness { + t.Helper() + return debugPluginHarnessOn(t, id, manifest, withBinary, &testKernel{Client: core.NewClient()}) +} + +// debugPluginHarnessOn is debugPluginHarness whose plugin service runs on plugins. +func debugPluginHarnessOn(t *testing.T, id, manifest string, withBinary bool, plugins pluginservice.Kernel) *harness { t.Helper() dir := t.TempDir() if err := os.WriteFile(filepath.Join(dir, settingsFile), []byte(`{"theme":"dark"}`), 0o600); err != nil { @@ -101,7 +108,7 @@ func debugPluginHarness(t *testing.T, id, manifest string, withBinary bool) *har } return newHarnessWithOptions(t, Options{ Kernel: &testKernel{Client: core.NewClient()}, - PluginKernel: &testKernel{Client: core.NewClient()}, + PluginKernel: plugins, PluginRoot: pluginRoot, Store: preferences, Languages: []string{"zh-Hans"}, diff --git a/desktop/internal/workbench/debug_transport.go b/desktop/internal/workbench/debug_transport.go index 24a26428f6..d6b4935e51 100644 --- a/desktop/internal/workbench/debug_transport.go +++ b/desktop/internal/workbench/debug_transport.go @@ -33,6 +33,9 @@ type debugTransportHooks struct { Discover func(ctx context.Context) (host string, port int, err error) // Dial opens the socket; nil dials TCP. Dial func(ctx context.Context, host string, port int) (net.Conn, error) + // Connected, when set, runs once Core took the socket as ready, before anything is read + // from it. + Connected func() // Deliver receives bytes the adapter sent, in order. Deliver func(data []byte) // Failure reports why Core failed the stream; Message is only set for the @@ -318,9 +321,13 @@ func (t *debugTransport) connect(wait context.Context, generation uint64, host s } t.conn = conn t.mu.Unlock() - if _, err := t.apply(core.DebugTransportEvent{Type: "connectionReady", Generation: &generation}, nil, nil); err != nil { + step, err := t.apply(core.DebugTransportEvent{Type: "connectionReady", Generation: &generation}, nil, nil) + if err != nil { return } + if step.Phase == "ready" && t.hooks.Connected != nil { + t.hooks.Connected() + } t.read(generation, conn) } diff --git a/desktop/internal/workbench/diagnostics_watch_test.go b/desktop/internal/workbench/diagnostics_watch_test.go new file mode 100644 index 0000000000..a0f18573c3 --- /dev/null +++ b/desktop/internal/workbench/diagnostics_watch_test.go @@ -0,0 +1,104 @@ +package workbench + +import ( + "errors" + "os" + "path/filepath" + "sync" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/logstore" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +// The window finds the detailed-diagnostics switch by a type assertion on its log sink, which +// would silently leave every plugin session's trace off if the store stopped implementing it. +var _ diagnosticsWatchSink = (*logstore.Store)(nil) + +// diagnosticsWatchLog is a log sink that counts who watches its diagnostics switch. +type diagnosticsWatchLog struct { + opRecordingLog + watchMu sync.Mutex + watching int +} + +func (l *diagnosticsWatchLog) WatchDiagnostics(watch func(on bool)) func() { + l.watchMu.Lock() + l.watching++ + l.watchMu.Unlock() + watch(false) + var once sync.Once + return func() { + once.Do(func() { + l.watchMu.Lock() + l.watching-- + l.watchMu.Unlock() + }) + } +} + +func (l *diagnosticsWatchLog) watchers() int { + l.watchMu.Lock() + defer l.watchMu.Unlock() + return l.watching +} + +// TestPluginSessionsFollowTheDiagnosticsSwitch checks that a workbench with plugins watches the +// log's diagnostics switch once, even when it is wired again, that it stops watching when it is +// done with its sessions, that a window without plugins or without such a log watches nothing, +// and that a refused trace switch is recorded as a diagnostics failure under no action. +func TestPluginSessionsFollowTheDiagnosticsSwitch(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, settingsFile), []byte(`{"theme":"dark"}`), 0o600); err != nil { + t.Fatal(err) + } + h := newHarnessWithOptions(t, Options{ + Kernel: &testKernel{Client: core.NewClient()}, + PluginKernel: &testKernel{Client: core.NewClient()}, + PluginRoot: t.TempDir(), + Store: store.At(dir), + Languages: []string{"en"}, + }) + a := h.app + if a.plugins == nil { + t.Fatal("the workbench opened without plugins") + } + t.Cleanup(func() { + a.stopWatchingDiagnostics() + a.logSink = nil + }) + + log := &diagnosticsWatchLog{} + a.logSink = log + a.watchDiagnostics() + a.watchDiagnostics() + if got := log.watchers(); got != 1 { + t.Fatalf("wiring the switch twice left %d watchers, want one", got) + } + a.stopWatchingDiagnostics() + a.stopWatchingDiagnostics() + if got := log.watchers(); got != 0 { + t.Fatalf("a workbench done with its sessions still has %d watchers", got) + } + + a.logSink = &opRecordingLog{} + a.watchDiagnostics() + if a.unwatchDiagnostics != nil { + t.Fatal("a log without a diagnostics switch was watched") + } + + a.logSink = log + service := a.plugins + a.plugins = nil + a.watchDiagnostics() + a.plugins = service + if got := log.watchers(); got != 0 { + t.Fatalf("a workbench without plugins watches the switch %d times", got) + } + + a.traceFailed(errors.New("lithe core: lsp.setDetailedDiagnostics: refused (unknown)")) + if got := log.ops("app.logging.diagnostics_failed"); len(got) != 1 || got[0] != "" { + t.Fatalf("a refused trace switch was recorded under %q, want once under no action", got) + } +} diff --git a/desktop/internal/workbench/diff_find.go b/desktop/internal/workbench/diff_find.go index 9b913a51ae..37b0faec05 100644 --- a/desktop/internal/workbench/diff_find.go +++ b/desktop/internal/workbench/diff_find.go @@ -132,7 +132,7 @@ func (a *App) applyDiffFind(t *diffTab, gen uint64, found []diffMatch, truncated } if err != nil { if !errors.Is(err, context.Canceled) { - a.gitOperationFailed("diff_find", err) + a.operationFailed("diff_find", err) } return } diff --git a/desktop/internal/workbench/difftab.go b/desktop/internal/workbench/difftab.go index 8af988a609..d8c99a98aa 100644 --- a/desktop/internal/workbench/difftab.go +++ b/desktop/internal/workbench/difftab.go @@ -500,7 +500,7 @@ func (a *App) loadDiff(p *project, t *diffTab) { t.loading = false if err != nil { t.err = i18n.SharedFormat(a.language(), "git.diff.getFileDiffFailed", map[string]string{"file": change.Path, "error": reviewReason(err)}) - a.gitOperationFailed("git_diff", err) + a.operationFailed("git_diff", err) return } a.readDiff(t, file, plan) @@ -920,5 +920,5 @@ func (a *App) diffBlockRefused(t *diffTab, err error) { default: t.note = i18n.Shared(a.language(), "git.diff.stageFailed") } - a.gitOperationFailed("git_diff_block", err) + a.operationFailed("git_diff_block", err) } diff --git a/desktop/internal/workbench/directory_exclusions.go b/desktop/internal/workbench/directory_exclusions.go index bd17f6005d..3f95fc56fb 100644 --- a/desktop/internal/workbench/directory_exclusions.go +++ b/desktop/internal/workbench/directory_exclusions.go @@ -87,7 +87,7 @@ func (a *App) installIndexing(p *project, refresh bool) { return } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_indexing", err)) + a.operationFailed("workspace_indexing", err) a.notifyError(i18n.Shared(a.language(), "indexing.configureFailed")) return } @@ -111,11 +111,12 @@ func (a *App) releaseIndexing(p *project) { } ix.generation++ root, owner, revision := p.root, ix.owner, ix.status.Revision + parent := a.operationContext(context.Background()) go func() { - ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + ctx, cancel := context.WithTimeout(parent, kernelCallTimeout) defer cancel() if _, err := kernel.ReleaseIndexing(ctx, root, owner, revision); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_indexing_release", err)) + a.emitIn(ctx, backgroundFailedLevel, backgroundFailedEvent, operationFailedFields("workspace_indexing_release", err)) } }() } @@ -181,7 +182,7 @@ func (a *App) changeIndexingRules(p *project, reduce func(context.Context, json. return func(a *App) { if err != nil { a.notifyError(i18n.SharedFormat(a.language(), "desktop.files.excludeFailed", map[string]string{"reason": reviewReason(err)})) - a.gitOperationFailed("workspace_exclude", err) + a.operationFailed("workspace_exclude", err) return } if !changed { diff --git a/desktop/internal/workbench/document_links.go b/desktop/internal/workbench/document_links.go index b91d45ff84..8f4fe3a018 100644 --- a/desktop/internal/workbench/document_links.go +++ b/desktop/internal/workbench/document_links.go @@ -183,7 +183,7 @@ func (a *App) applyServerDocumentLinks(pending *semanticPending, event core.Back } links, err := core.PluginServerDocumentLinks(event) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("server_document_links", err)) + a.backgroundFailed("server_document_links", err) return } converted := make([]pluginservice.EditorLink, 0, len(links)) diff --git a/desktop/internal/workbench/document_observation.go b/desktop/internal/workbench/document_observation.go index 8fbbcb9481..afc43cf9ea 100644 --- a/desktop/internal/workbench/document_observation.go +++ b/desktop/internal/workbench/document_observation.go @@ -320,7 +320,7 @@ func (a *App) applyDocumentCheck(p *project, d *document, baseline rope.Rope, co d.conflictGeneration++ if !d.conflicted { d.conflicted = true - a.emit(core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "document_external_change", "reason": "disk_conflict"}) + a.operationRejected("document_external_change", "disk_conflict") } default: d.checkFailed = true diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index 8bd60c79f7..62d67c03a1 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -859,7 +859,7 @@ func (a *App) saveProjectPass(p *project, verified map[int]int, done func(bool)) plan, err := a.kernel.PlanDocumentSaveBatch(ctx, documents) cancel() if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("document_save_batch", err)) + a.operationFailed("document_save_batch", err) a.notifyError(a.text.Errors.Core(err.Error())) done(false) return @@ -884,7 +884,7 @@ func (a *App) saveProjectPass(p *project, verified map[int]int, done func(bool)) decision, err := a.kernel.ReduceDocumentSaveBatch(ctx, plan.Members, nil, documents) cancel() if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("document_save_batch", err)) + a.operationFailed("document_save_batch", err) a.notifyError(a.text.Errors.Core(err.Error())) done(false) return diff --git a/desktop/internal/workbench/editor_actions.go b/desktop/internal/workbench/editor_actions.go index dd97f97d5a..93d07b9363 100644 --- a/desktop/internal/workbench/editor_actions.go +++ b/desktop/internal/workbench/editor_actions.go @@ -95,7 +95,7 @@ func (a *App) presentEditorActions(p *project, snapshot editorActionSnapshot, ac return } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_actions", err)) + a.backgroundFailed("editor_actions", err) } d.actions = actions a.annotateEditorActions(d) @@ -306,7 +306,7 @@ func (a *App) runEditorAction(p *project, d *document, action pluginservice.Edit return func(a *App) { if err != nil { a.notifyError(i18n.Shared(a.language(), "desktop.editorActions.failed")) - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_action", err)) + a.operationFailed("editor_action", err) return } if len(locations) == 0 { @@ -347,6 +347,9 @@ func (a *App) revealEditorLocations(p *project, d *document, root string, locati func (a *App) revealEditorLocation(p *project, root string, location pluginservice.EditorLocation) { parsed, err := url.Parse(location.URI) if err != nil { + // The plugin named a location that is not a URI; the error would repeat it, so only the + // refusal is recorded. + a.operationRejected("editor_action_reveal", "invalid_uri") a.notifyError(i18n.Shared(a.language(), "desktop.editorActions.failed")) return } @@ -358,7 +361,10 @@ func (a *App) revealEditorLocation(p *project, root string, location pluginservi uri, line, column := location.URI, location.StartLine, location.StartCharacter a.background(p, 30*time.Second, func(ctx context.Context) func(*App) { if err := a.plugins.OpenContentURI(ctx, root, uri, line, column); err != nil { - return func(a *App) { a.notifyError(i18n.Shared(a.language(), "desktop.editorActions.failed")) } + return func(a *App) { + a.operationFailed("editor_action_reveal", err) + a.notifyError(i18n.Shared(a.language(), "desktop.editorActions.failed")) + } } return nil }) diff --git a/desktop/internal/workbench/editor_find.go b/desktop/internal/workbench/editor_find.go index 135a19de50..58ea7b8521 100644 --- a/desktop/internal/workbench/editor_find.go +++ b/desktop/internal/workbench/editor_find.go @@ -191,7 +191,7 @@ func (a *App) applyEditorFind(p *project, d *document, before rope.Rope, gen uin code = failure.Details } if code != f.failure { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_find", err)) + a.operationFailed("editor_find", err) } f.failure = code return diff --git a/desktop/internal/workbench/editor_preferences.go b/desktop/internal/workbench/editor_preferences.go index a84cba91d2..93bc77ea4d 100644 --- a/desktop/internal/workbench/editor_preferences.go +++ b/desktop/internal/workbench/editor_preferences.go @@ -13,13 +13,13 @@ func (a *App) loadEditorEssentials() { client := core.NewClient() prefs, err := client.ResolveEditorPreferences(ctx, a.settings.EditorPreferences) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_preferences", err)) + a.backgroundFailed("editor_preferences", err) } else { a.editorPreferences = prefs } schemes, err := client.ReduceKeymapSchemes(ctx, core.KeymapSchemeRequest{State: a.settings.KeymapSchemes, Current: a.settings.Keymap}) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("keymap_schemes", err)) + a.backgroundFailed("keymap_schemes", err) } else { a.settings.KeymapSchemes = schemes.State a.settings.Keymap = shortcuts.Overrides(schemes.Bindings) diff --git a/desktop/internal/workbench/editor_recovery.go b/desktop/internal/workbench/editor_recovery.go index 2b03a4a371..f02c325122 100644 --- a/desktop/internal/workbench/editor_recovery.go +++ b/desktop/internal/workbench/editor_recovery.go @@ -35,11 +35,11 @@ type recoveryWriter struct { } func (a *App) initRecovery() { - ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) defer cancel() limits, err := core.NewClient().DecideEditorRecovery(ctx, core.EditorRecoveryRequest{}) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_recovery", err)) + a.operationFailed("editor_recovery", err) return } a.recovery = &recoveryWriter{pending: map[string]checkpoint{}, store: draftstore.New(a.store.Dir(), limits), limit: limits.MaxDocuments} @@ -141,7 +141,7 @@ func (a *App) enqueueCheckpoint(job checkpoint) { }) } func (a *App) recoveryFailed(err error) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_recovery", documentLogError(err))) + a.operationFailed("editor_recovery", documentLogError(err)) a.notifyError(i18n.Shared(a.language(), "desktop.drafts.failed")) } diff --git a/desktop/internal/workbench/editor_session.go b/desktop/internal/workbench/editor_session.go index 7c54e00c55..d192c3b495 100644 --- a/desktop/internal/workbench/editor_session.go +++ b/desktop/internal/workbench/editor_session.go @@ -80,7 +80,7 @@ type editorRestoreItem struct { func (a *App) saveEditorSession(p *project) { all := map[string]savedEditorSession{} if _, err := a.store.Load(editorSessionFile, &all); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_session_load", documentLogError(err))) + a.backgroundFailed("editor_session_load", documentLogError(err)) all = map[string]savedEditorSession{} } if session, ok := captureEditorSession(p); ok { @@ -100,7 +100,7 @@ func (a *App) saveEditorSession(p *project) { } } if err := a.store.Save(editorSessionFile, all); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_session_save", documentLogError(err))) + a.backgroundFailed("editor_session_save", documentLogError(err)) } } @@ -175,7 +175,7 @@ func (a *App) restoreEditorSession(p *project) { all := map[string]savedEditorSession{} if found, err := a.store.Load(editorSessionFile, &all); err != nil || !found { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_session_load", documentLogError(err))) + a.backgroundFailed("editor_session_load", documentLogError(err)) } return } diff --git a/desktop/internal/workbench/encoding.go b/desktop/internal/workbench/encoding.go index 99a776d73d..7e942b2c44 100644 --- a/desktop/internal/workbench/encoding.go +++ b/desktop/internal/workbench/encoding.go @@ -94,6 +94,10 @@ func readDocumentEncoded(ctx context.Context, kernel editorKernel, path string) return documentRead{text: []byte(decoded.Text), encoding: decoded.Encoding, hasBOM: decoded.HasBOM, disk: raw}, nil } +// errLossyDecode is the failure logged when a file reopened in an encoding that cannot decode +// all of it: the window shows replacement characters for the bytes it lost. +var errLossyDecode = errors.New("the file has bytes the chosen encoding cannot decode") + // readDocumentAs reads the file at path decoded as encoding, which is the reopen path: a wrong // choice shows replacement characters and Lossy says so. func readDocumentAs(ctx context.Context, kernel editorKernel, path, encoding string) (documentRead, bool, error) { @@ -181,7 +185,7 @@ func (a *App) reopenWithEncoding(p *project, d *document, encoding string) { } return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_encoding_reopen", err)) + a.operationFailed("editor_encoding_reopen", err) a.notifyError(i18n.Shared(a.language(), "desktop.encoding.reopenFailed")) return } @@ -195,6 +199,8 @@ func (a *App) reopenWithEncoding(p *project, d *document, encoding string) { d.savedRevision = d.view.Revision() a.clearDocumentConflict(d) if lossy { + // The file reopened, but not all of it: what the encoding cannot decode is lost. + a.operationFailed("editor_encoding_reopen", errLossyDecode) a.notifyError(i18n.Shared(a.language(), "desktop.encoding.reopenLossy")) } } diff --git a/desktop/internal/workbench/filetree.go b/desktop/internal/workbench/filetree.go index 63b1d2670f..04fe4720e7 100644 --- a/desktop/internal/workbench/filetree.go +++ b/desktop/internal/workbench/filetree.go @@ -259,7 +259,13 @@ func (a *App) pumpTreeListings(p *project) { n.loading = false if err != nil { if !loggedFailure { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("project_tree_list", err)) + // A root that cannot be listed leaves the project without a tree; a + // folder that cannot be listed just closes again. + if _, root := batch[t.root.path]; root { + a.operationFailed("project_tree_list", err) + } else { + a.backgroundFailed("project_tree_list", err) + } loggedFailure = true t.failureReported = true } @@ -278,7 +284,7 @@ func (a *App) pumpTreeListings(p *project) { } } else { if n == t.root { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("project_tree_list", errors.New("workspace root unavailable"))) + a.operationFailed("project_tree_list", errors.New("workspace root unavailable")) t.failed = i18n.Shared(a.language(), "desktop.project.rootUnavailable") } else { // log-exempt: 目标已消失:目录可能已被外部删除或隐藏。 diff --git a/desktop/internal/workbench/filetree_actions.go b/desktop/internal/workbench/filetree_actions.go index e776bb8540..2e64c69455 100644 --- a/desktop/internal/workbench/filetree_actions.go +++ b/desktop/internal/workbench/filetree_actions.go @@ -3,7 +3,6 @@ package workbench import ( "strings" - "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" "github.com/vivaui/viva/ui" @@ -161,7 +160,7 @@ func childTreePath(parent, name string) string { // giveUpTreeReveal ends locating a file the tree cannot show, for reason. func (a *App) giveUpTreeReveal(p *project, reason string) { - a.emit(core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "project_tree_reveal", "reason": reason}) + a.operationRejected("project_tree_reveal", reason) p.tree.reveal, p.tree.revealAsked = "", nil } diff --git a/desktop/internal/workbench/filetree_batch.go b/desktop/internal/workbench/filetree_batch.go index 52accb8793..9a67a75872 100644 --- a/desktop/internal/workbench/filetree_batch.go +++ b/desktop/internal/workbench/filetree_batch.go @@ -190,10 +190,11 @@ func treeParents(paths []string) []string { // still ran; failure words it. func (a *App) finishRemoval(p *project, parents []string, performed string, failed int, reason error, failure func(i18n.Language, string) string) { p.tree.marked, p.tree.anchor, p.tree.targets = nil, "", nil + a.performed(performed, surfaceButton) if failed > 0 && reason != nil { + a.operationFailed("project_tree_remove", documentLogError(reason)) a.notifyError(failure(a.language(), treeErrorReason(reason))) } - a.performed(performed, surfaceButton) for _, dir := range parents { a.listTree(p, dir) } diff --git a/desktop/internal/workbench/filetree_dnd.go b/desktop/internal/workbench/filetree_dnd.go index 1416b2a61d..3ee5251de0 100644 --- a/desktop/internal/workbench/filetree_dnd.go +++ b/desktop/internal/workbench/filetree_dnd.go @@ -82,12 +82,14 @@ func (a *App) moveTreeItem(p *project, rel, dir string) { return } if err := wslpath.CheckMove(oldFull, newFull); err != nil { - a.notifyError(err.Error()) + a.operationRejected("project_tree_move", "cross_wsl_boundary") + a.notifyError(i18n.Shared(language, "desktop.files.crossBoundaryMove")) return } docs := a.documentsUnder(p, oldFull) a.saveDocumentsThen(p, docs, func() { if err := os.Rename(oldFull, newFull); err != nil { + a.operationFailed("project_tree_move", documentLogError(err)) a.notifyError(i18n.SharedFormat(language, "desktop.files.moveFailed", map[string]string{"reason": treeErrorReason(err)})) return } @@ -152,10 +154,11 @@ func (a *App) treePaste(p *project, n *treeNode) { if clip.cut { p.tree.clip = treeClipboard{} } + a.performed("workspace.file.paste", surfaceContextMenu) if failed != nil { + a.operationFailed("project_tree_paste", documentLogError(failed)) a.notifyError(i18n.SharedFormat(language, "desktop.files.pasteFailed", map[string]string{"reason": treeErrorReason(failed)})) } - a.performed("workspace.file.paste", surfaceContextMenu) a.listTree(p, dir) for _, rel := range clip.paths { a.listTree(p, path.Dir(rel)) diff --git a/desktop/internal/workbench/filetree_duplicate.go b/desktop/internal/workbench/filetree_duplicate.go index fe1faf7c5b..9157c59ae7 100644 --- a/desktop/internal/workbench/filetree_duplicate.go +++ b/desktop/internal/workbench/filetree_duplicate.go @@ -45,6 +45,7 @@ func (a *App) duplicateTreeItem(p *project, n *treeNode) { } } if err := copyTreeEntry(source, target); err != nil { + a.operationFailed("project_tree_duplicate", documentLogError(err)) a.notifyError(i18n.SharedFormat(language, "desktop.files.duplicateFailed", map[string]string{"reason": treeErrorReason(err)})) return } diff --git a/desktop/internal/workbench/filetree_menu.go b/desktop/internal/workbench/filetree_menu.go index d01ef74235..ddb9864bc8 100644 --- a/desktop/internal/workbench/filetree_menu.go +++ b/desktop/internal/workbench/filetree_menu.go @@ -223,6 +223,7 @@ func revealLabel(language i18n.Language) string { // revealPath shows full in the platform's file manager and says why when it cannot. func (a *App) revealPath(full string) { if err := treeRevealPath(full); err != nil { + a.operationFailed("project_tree_reveal", documentLogError(err)) a.notifyError(i18n.SharedFormat(a.language(), "desktop.files.revealFailed", map[string]string{"reason": treeErrorReason(err)})) } } @@ -264,6 +265,7 @@ func (a *App) copyTreePath(full string, relative bool) { } } if err := treeCopyText(text); err != nil { + a.operationFailed("clipboard_copy", err) a.notifyError(i18n.SharedFormat(a.language(), "desktop.files.copyFailed", map[string]string{"reason": treeErrorReason(err)})) } } @@ -368,6 +370,7 @@ func (a *App) createTreeItem(p *project) { err = os.Mkdir(full, 0o755) } if err != nil { + a.operationFailed("project_tree_create", documentLogError(err)) a.notifyError(i18n.SharedFormat(language, "desktop.files.createFailed", map[string]string{"reason": treeErrorReason(err)})) return } @@ -410,10 +413,12 @@ func (a *App) renameTreeItem(p *project) { a.saveDocumentsThen(p, docs, func() { before := readForLocalHistory(oldFull) if err := wslpath.CheckMove(oldFull, newFull); err != nil { - a.notifyError(err.Error()) + a.operationRejected("project_tree_rename", "cross_wsl_boundary") + a.notifyError(i18n.Shared(language, "desktop.files.crossBoundaryMove")) return } if err := os.Rename(oldFull, newFull); err != nil { + a.operationFailed("project_tree_rename", documentLogError(err)) a.notifyError(i18n.SharedFormat(language, "desktop.files.renameFailed", map[string]string{"reason": treeErrorReason(err)})) return } diff --git a/desktop/internal/workbench/filetree_open.go b/desktop/internal/workbench/filetree_open.go index cfa6a8cf9d..7e39bca996 100644 --- a/desktop/internal/workbench/filetree_open.go +++ b/desktop/internal/workbench/filetree_open.go @@ -36,6 +36,7 @@ func (a *App) openTreeFileWith(file string) { err = app.OpenWith(paths[0], filepath.Clean(file)) } if err != nil { + a.operationFailed("project_tree_open_with", documentLogError(err)) a.notifyError(i18n.SharedFormat(lang, "desktop.files.openWithFailed", map[string]string{"reason": treeErrorReason(err)})) } } diff --git a/desktop/internal/workbench/filetree_rows.go b/desktop/internal/workbench/filetree_rows.go index bf4af04d6f..4f693da1d5 100644 --- a/desktop/internal/workbench/filetree_rows.go +++ b/desktop/internal/workbench/filetree_rows.go @@ -36,10 +36,11 @@ func (a *App) refreshTreeRows(p *project, top *string) bool { } } walk(t.root) - ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) defer cancel() result, err := a.kernel.ProjectTreeRows(ctx, core.ProjectTreeQuery{Nodes: nodes, Selection: t.selection(), Top: top}) if err != nil { + a.operationFailed("project_tree_rows", err) a.notifyError(a.text.Errors.Core(err.Error())) return false } @@ -77,10 +78,11 @@ func (a *App) reduceTreeSelection(p *project, action core.RowAction) bool { for i, n := range t.rows { rows[i] = n.path } - ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) defer cancel() result, err := a.kernel.ReduceRowSelection(ctx, rows, t.selection(), action) if err != nil { + a.operationFailed("project_tree_selection", err) a.notifyError(a.text.Errors.Core(err.Error())) return false } diff --git a/desktop/internal/workbench/filetree_test.go b/desktop/internal/workbench/filetree_test.go index 0f86e5ae2f..aaf134ff19 100644 --- a/desktop/internal/workbench/filetree_test.go +++ b/desktop/internal/workbench/filetree_test.go @@ -85,7 +85,9 @@ func TestProjectTreeBatchFailureLogsOnce(t *testing.T) { awaitDocumentState(t, h, func() bool { return !p.tree.reading && !p.tree.find("a").loading && !p.tree.find("b").loading }) logger.mu.Lock() defer logger.mu.Unlock() - if len(logger.events) != 1 || logger.events[0].Event != operationFailedEvent || logger.events[0].Fields["operation"] != "project_tree_list" { + // Folders that cannot be listed just close again, which the window shows by no notice: the + // failure is background work, recorded once for the batch. + if len(logger.events) != 1 || logger.events[0].Event != backgroundFailedEvent || logger.events[0].Fields["operation"] != "project_tree_list" { t.Fatalf("batch failure logs = %+v", logger.events) } } diff --git a/desktop/internal/workbench/filetree_watch.go b/desktop/internal/workbench/filetree_watch.go index 5ad95f2eb6..61105cf854 100644 --- a/desktop/internal/workbench/filetree_watch.go +++ b/desktop/internal/workbench/filetree_watch.go @@ -8,7 +8,6 @@ import ( "runtime" "strings" - "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/vivaui/viva/app" ) @@ -95,7 +94,7 @@ func treeUsesRecursiveWatch() bool { return runtime.GOOS == "darwin" || runtime. func (a *App) applyTreeRecursiveWatch(p *project, ready, available bool, err error, changes app.DirectoryChanges) { if ready && err != nil { if p.search.watchAttached || p.everywhere.watchAttached { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("project_tree_watch", err)) + a.backgroundFailed("project_tree_watch", err) } else { a.treeWatchFailed(err) } @@ -112,7 +111,7 @@ func (a *App) applyTreeRecursiveWatch(p *project, ready, available bool, err err if len(p.tree.eventPending)+len(changes.Names) > searchEventLimit { p.tree.eventEpoch++ p.tree.eventPending = nil - a.emit(core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "project_tree_watch", "reason": "event_limit_exceeded"}) + a.backgroundFailed("project_tree_watch", errWatchEventLimit) a.resyncTreeListings(p) return } @@ -136,7 +135,7 @@ func (a *App) filterTreeEvents(p *project) { return func(a *App) { t.eventFiltering = false if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("project_tree_filter_changes", err)) + a.backgroundFailed("project_tree_filter_changes", err) if t.recursiveWatch { a.resyncTreeListings(p) } @@ -235,7 +234,7 @@ func (a *App) detachTreeRecursiveWatch(p *project) { } func (a *App) treeWatchFailed(err error) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("project_tree_watch", err)) + a.operationFailed("project_tree_watch", err) a.notifyError(i18n.Shared(a.language(), "desktop.project.watchUnavailable")) } @@ -252,7 +251,7 @@ func (a *App) drainTreeWatch(p *project, path string, slot *documentWatch) { changes := watch.Changes(nil) changed = changed || changes.Resync || len(changes.Names) != 0 if changes.Resync { - a.emit(core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "project_tree_watch", "reason": "watch_events_lost"}) + a.backgroundFailed("project_tree_watch", errWatchEventsLost) slot.close() delete(p.tree.watches, path) if n := p.tree.find(path); n != nil { diff --git a/desktop/internal/workbench/folding.go b/desktop/internal/workbench/folding.go index 394789ab01..93f1f51898 100644 --- a/desktop/internal/workbench/folding.go +++ b/desktop/internal/workbench/folding.go @@ -125,7 +125,7 @@ func (a *App) applyFoldRanges(pending *semanticPending, event core.BackendEvent, } if failed || err != nil { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_folding_ranges", err)) + a.backgroundFailed("plugin_folding_ranges", err) } a.foldFromIndent(p, d, pending.revision) return diff --git a/desktop/internal/workbench/git.go b/desktop/internal/workbench/git.go index aaa4e4e7a2..f73714e14e 100644 --- a/desktop/internal/workbench/git.go +++ b/desktop/internal/workbench/git.go @@ -33,6 +33,7 @@ func (a *App) loadGit(p *project) { return func(a *App) { a.setGit(p, gitState{loaded: true, status: status, err: err}) if err != nil { + a.operationFailed("git_status", err) a.notifyError(a.text.Git.Failed(err.Error())) return } diff --git a/desktop/internal/workbench/git_blame_inline.go b/desktop/internal/workbench/git_blame_inline.go index f455e8a79b..1879cd228e 100644 --- a/desktop/internal/workbench/git_blame_inline.go +++ b/desktop/internal/workbench/git_blame_inline.go @@ -78,7 +78,7 @@ func (a *App) refreshInlineBlame(p *project, d *document) { return } if err != nil { - a.gitOperationFailed("git_blame_inline", err) + a.backgroundFailed("git_blame_inline", err) return } d.blame.lines = lines @@ -187,7 +187,7 @@ func (a *App) blameSubject(p *project, hash string) (string, bool) { return func(a *App) { delete(cache.pending, hash) if err != nil { - a.gitOperationFailed("git_blame_subject", err) + a.backgroundFailed("git_blame_subject", err) return } if cache.subjects == nil || len(cache.subjects) >= blameSubjectLimit { diff --git a/desktop/internal/workbench/git_exclude.go b/desktop/internal/workbench/git_exclude.go index fcbabb6156..76ae61a874 100644 --- a/desktop/internal/workbench/git_exclude.go +++ b/desktop/internal/workbench/git_exclude.go @@ -57,7 +57,7 @@ func (a *App) excludeLocally(p *project, change core.GitChange) { return func(a *App) { if err != nil { a.notifyError(i18n.SharedFormat(a.language(), "desktop.git.excludeFailed", map[string]string{"reason": reviewReason(err)})) - a.gitOperationFailed("git_exclude", err) + a.operationFailed("git_exclude", err) } a.loadGit(p) } diff --git a/desktop/internal/workbench/git_gutter.go b/desktop/internal/workbench/git_gutter.go index b58bd9bb80..25b72a8a69 100644 --- a/desktop/internal/workbench/git_gutter.go +++ b/desktop/internal/workbench/git_gutter.go @@ -193,7 +193,7 @@ func (a *App) refreshGitGutter(p *project, d *document) { return } if err != nil { - a.gitOperationFailed("git_gutter", err) + a.backgroundFailed("git_gutter", err) return } d.gutter.hunks = hunks diff --git a/desktop/internal/workbench/git_history.go b/desktop/internal/workbench/git_history.go index 44bdf4a186..5d03b616f5 100644 --- a/desktop/internal/workbench/git_history.go +++ b/desktop/internal/workbench/git_history.go @@ -2,6 +2,7 @@ package workbench import ( "context" + "errors" "strconv" "strings" @@ -192,6 +193,7 @@ func (a *App) copyRevisions(revisions []string, short bool, label string) { } } if err := app.SetClipboardText(strings.Join(hashes, "\n")); err != nil { + a.operationFailed("clipboard_copy", err) a.notifyError(i18n.SharedFormat(a.language(), "git.log.copyFailed", map[string]string{"label": label})) } } @@ -234,7 +236,7 @@ func (a *App) reviewHistoryRewrite(p *project, operation string, revisions []str r.busy, r.loaded = false, true if err != nil { r.err = reviewReason(err) - a.gitOperationFailed("git_history_preview", err) + a.operationFailed("git_history_preview", err) return } r.preview = preview @@ -312,6 +314,8 @@ func (a *App) runHistoryRewrite(p *project) { r.open = false } if result != nil && result.WorktreeRefresh == "failed" { + // The history was rewritten; only the worktree did not follow it. + a.operationFailed("git_history_rewrite_refresh", errors.New("the rewrite succeeded but the worktree refresh failed")) a.notifyError(i18n.Shared(lang, "git.historyReview.refreshFailed")) } else { a.notifySuccess(i18n.Shared(lang, "git.historyReview.completed")) @@ -324,7 +328,7 @@ func (a *App) runHistoryRewrite(p *project) { } else { a.notifyError(historyRecoveryNotice(lang, result)) } - a.gitOperationFailed("git_history_write", err) + a.operationFailed("git_history_write", err) default: // Nothing changed; the preview is spent and has to be read again. if current && r.open { @@ -332,7 +336,7 @@ func (a *App) runHistoryRewrite(p *project) { } else { a.notifyError(i18n.SharedFormat(lang, "git.operationError", map[string]string{"error": reviewReason(err)})) } - a.gitOperationFailed("git_history_write", err) + a.operationFailed("git_history_write", err) return } a.afterHistoryWrite(p, root) @@ -370,6 +374,7 @@ func (a *App) copyRecoveryReference(p *project) { a.performed("git.history.copyRecovery", surfaceButton) lang := a.language() if err := app.SetClipboardText(result.RecoveryReference); err != nil { + a.operationFailed("clipboard_copy", err) a.notifyError(i18n.Shared(lang, "git.historyReview.copyFailed")) return } @@ -419,7 +424,7 @@ func (a *App) runCherryPick(p *project) { return case err != nil: a.notifyError(i18n.SharedFormat(lang, "git.operationError", map[string]string{"error": reviewReason(err)})) - a.gitOperationFailed("git_"+operation, err) + a.operationFailed("git_"+operation, err) case operation == gitOperationRevert: a.notifySuccess(i18n.SharedFormat(lang, "desktop.gitHistory.reverted", map[string]string{"hash": shortHash(revision)})) default: @@ -465,7 +470,7 @@ func (a *App) runHistoryReset(p *project) { lang := a.language() if err != nil { a.notifyError(i18n.SharedFormat(lang, "git.operationError", map[string]string{"error": reviewReason(err)})) - a.gitOperationFailed("git_reset", err) + a.operationFailed("git_reset", err) } else { a.notifySuccess(i18n.SharedFormat(lang, "desktop.gitHistory.resetDone", map[string]string{"hash": shortHash(reset.revision)})) } @@ -535,7 +540,7 @@ func (a *App) controlGitOperation(p *project, control string) { p.gitHistory.busy = false if err != nil { a.notifyError(i18n.SharedFormat(a.language(), "git.operationError", map[string]string{"error": reviewReason(err)})) - a.gitOperationFailed("git_"+control, err) + a.operationFailed("git_"+control, err) } a.afterHistoryWrite(p, root) } diff --git a/desktop/internal/workbench/git_observation.go b/desktop/internal/workbench/git_observation.go index 381b9bdea6..acfa0f5e41 100644 --- a/desktop/internal/workbench/git_observation.go +++ b/desktop/internal/workbench/git_observation.go @@ -76,7 +76,7 @@ func (a *App) startGitObservation(p *project) { return } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("git_metadata_watch", documentLogError(err))) + a.backgroundFailed("git_metadata_watch", documentLogError(err)) return } if !found { @@ -133,7 +133,7 @@ func (a *App) drainGitWatch(p *project, dir string, slot *documentWatch) { // The watch was installed after the last status: one rescan covers the gap. p.observe.full = true if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("git_metadata_watch", documentLogError(err))) + a.backgroundFailed("git_metadata_watch", documentLogError(err)) } } if watch != nil { diff --git a/desktop/internal/workbench/git_rebase.go b/desktop/internal/workbench/git_rebase.go index a685d11729..7c45cf466c 100644 --- a/desktop/internal/workbench/git_rebase.go +++ b/desktop/internal/workbench/git_rebase.go @@ -108,7 +108,7 @@ func (a *App) beginRebaseFromHere(p *project, base, subject string) { r.busy = false if err != nil { r.err = reviewReason(err) - a.gitOperationFailed("git_rebase_preview", err) + a.operationFailed("git_rebase_preview", err) return } r.preview = preview @@ -166,7 +166,7 @@ func (a *App) startRebase(p *project) { r.busy = false if err != nil { r.err = reviewReason(err) - a.gitOperationFailed("git_rebase_start", err) + a.operationFailed("git_rebase_start", err) return } r.open = false @@ -204,7 +204,7 @@ func (a *App) controlRebaseWith(p *project, action, message string) { r.busy = false if err != nil { a.notifyError(i18n.SharedFormat(a.language(), "desktop.rebase.controlFailed", map[string]string{"reason": reviewReason(err)})) - a.gitOperationFailed("git_rebase_control", err) + a.operationFailed("git_rebase_control", err) a.loadRebaseSession(p) return } diff --git a/desktop/internal/workbench/gitcompare.go b/desktop/internal/workbench/gitcompare.go index a709698ef7..0fa6ad3ef4 100644 --- a/desktop/internal/workbench/gitcompare.go +++ b/desktop/internal/workbench/gitcompare.go @@ -57,7 +57,7 @@ func (a *App) compareReferencesAt(p *project, root string, base core.GitReferenc } else { a.notifyError(i18n.SharedFormat(lang, "git.diff.compareRefsFailed", map[string]string{"base": base.ShortName, "target": target.ShortName, "error": reviewReason(err)})) } - a.gitOperationFailed("git_comparison", err) + a.operationFailed("git_comparison", err) return } if len(files) == 0 { diff --git a/desktop/internal/workbench/gitconsole.go b/desktop/internal/workbench/gitconsole.go index dff0330de9..4b907feb18 100644 --- a/desktop/internal/workbench/gitconsole.go +++ b/desktop/internal/workbench/gitconsole.go @@ -891,6 +891,7 @@ func (a *App) copyConsoleRecord(action, value string) { // symbol. func (a *App) copyConsoleText(value string) { if err := app.SetClipboardText(strings.ReplaceAll(value, "\x00", "\u2400")); err != nil { + a.operationFailed("clipboard_copy", err) a.notifyError(a.text.Errors.Core(err.Error())) } } diff --git a/desktop/internal/workbench/github_account.go b/desktop/internal/workbench/github_account.go index fa2877d334..810cc1429c 100644 --- a/desktop/internal/workbench/github_account.go +++ b/desktop/internal/workbench/github_account.go @@ -134,12 +134,13 @@ func (a *App) startGitHubSignIn() { if g.cancel != nil { g.cancel() } - ctx, cancel := context.WithCancel(context.Background()) + // The sign-in's requests run under its own context, which carries the action. + a.performed("github.signIn", surfaceButton) + ctx, cancel := context.WithCancel(a.operationContext(context.Background())) g.gen++ gen := g.gen g.cancel, g.phase, g.err, g.code = cancel, githubStarting, "", githubapi.DeviceCode{} g.mu.Unlock() - a.performed("github.signIn", surfaceButton) started := time.Now() a.background(nil, 0, func(context.Context) func(*App) { startCtx, stop := context.WithTimeout(ctx, githubAccountTimeout) @@ -233,6 +234,7 @@ func (a *App) signOutGitHub() { err := credentials.Default().Delete(ctx, githubCredentialPlugin, githubCredentialKey) return func(a *App) { if err != nil { + a.operationFailed("github_sign_out", err) a.notifyError(i18n.SharedFormat(a.language(), "desktop.github.signOutFailed", map[string]string{"reason": err.Error()})) } } diff --git a/desktop/internal/workbench/github_create.go b/desktop/internal/workbench/github_create.go index 42d3e8270a..f2c76a33e5 100644 --- a/desktop/internal/workbench/github_create.go +++ b/desktop/internal/workbench/github_create.go @@ -263,7 +263,7 @@ func (a *App) finishPullRequestDraft(title, description string, err error) func( return } cr.err = aiPullRequestFailure(a.language(), err) - a.gitOperationFailed("ai_pull_request_description", err) + a.operationFailed("ai_pull_request_description", err) return } cr.title.SetText(strings.TrimSpace(title)) @@ -318,7 +318,7 @@ func (a *App) publishCreateBranch(p *project) { } else { cr.err = githubFailure(language, err) } - a.gitOperationFailed("git_publish_branch", err) + a.operationFailed("git_publish_branch", err) return } cr.blocked = creationBlockedReason(language, facts) diff --git a/desktop/internal/workbench/github_prs.go b/desktop/internal/workbench/github_prs.go index 0befc70347..48af07cc5c 100644 --- a/desktop/internal/workbench/github_prs.go +++ b/desktop/internal/workbench/github_prs.go @@ -227,7 +227,7 @@ func (a *App) loadPullRequests(p *project) { if err != nil { pr.err = githubFailure(a.language(), err) pr.items = nil - a.gitOperationFailed("github_pull_requests", err) + a.operationFailed("github_pull_requests", err) return } pr.items = items @@ -301,6 +301,7 @@ func (a *App) openPullRequestInBrowser(url string) { } a.performed("github.pullRequest.openBrowser", surfaceButton) if err := app.OpenURL(url); err != nil { + a.operationFailed("open_url", err) a.notifyError(i18n.SharedFormat(a.language(), "desktop.github.openFailed", map[string]string{"reason": err.Error()})) } } @@ -358,7 +359,7 @@ func (a *App) checkoutPullRequest(p *project) { pr.preview = nil if err != nil { pr.detailErr = githubFailure(a.language(), err) - a.gitOperationFailed("github_pull_request_checkout", err) + a.operationFailed("github_pull_request_checkout", err) return } pr.checkoutOK = true diff --git a/desktop/internal/workbench/gitlinehistory.go b/desktop/internal/workbench/gitlinehistory.go index f28b1a0c84..7e7f0d0142 100644 --- a/desktop/internal/workbench/gitlinehistory.go +++ b/desktop/internal/workbench/gitlinehistory.go @@ -83,7 +83,7 @@ func (a *App) startLineHistory(p *project, d *document, surface actionSurface) { h.busy = false if err != nil { h.err = reviewReason(err) - a.gitOperationFailed("git_line_history", err) + a.operationFailed("git_line_history", err) return } h.history = history diff --git a/desktop/internal/workbench/gitlog.go b/desktop/internal/workbench/gitlog.go index 2ab6242cc7..5da58a251e 100644 --- a/desktop/internal/workbench/gitlog.go +++ b/desktop/internal/workbench/gitlog.go @@ -453,6 +453,7 @@ func (a *App) reproject(p *project, delay time.Duration) { l.pathFiles = files } if err != nil { + a.operationFailed("git_log_project", err) a.notifyError(a.text.Git.Failed(err.Error())) return } diff --git a/desktop/internal/workbench/gitlog_ref_menu.go b/desktop/internal/workbench/gitlog_ref_menu.go index ee6ee1d9de..c104c3ddde 100644 --- a/desktop/internal/workbench/gitlog_ref_menu.go +++ b/desktop/internal/workbench/gitlog_ref_menu.go @@ -175,6 +175,7 @@ func (a *App) drawLogRefMenuItems(c ui.C, menu *ui.MenuItems, p *project, r core if menu.Item(i18n.Shared(lang, "git.log.copyBranchName")).Clicked() { c.After(func() { if err := app.SetClipboardText(r.ShortName); err != nil { + a.operationFailed("clipboard_copy", err) a.notifyError(i18n.SharedFormat(a.language(), "git.log.copyFailed", map[string]string{"label": r.ShortName})) } }) @@ -298,7 +299,7 @@ func (a *App) runRefIntegration(p *project) { return case err != nil: a.notifyError(i18n.SharedFormat(lang, "git.operationError", map[string]string{"error": reviewReason(err)})) - a.gitOperationFailed("git_"+in.operation, err) + a.operationFailed("git_"+in.operation, err) case in.operation == refMerge: a.notifySuccess(i18n.SharedFormat(lang, "desktop.refs.merged", map[string]string{"branch": name})) case in.operation == refRebase: diff --git a/desktop/internal/workbench/gitreview.go b/desktop/internal/workbench/gitreview.go index 1a74f62418..b6356fb710 100644 --- a/desktop/internal/workbench/gitreview.go +++ b/desktop/internal/workbench/gitreview.go @@ -83,7 +83,7 @@ func reviewReason(err error) string { // reviewFailed words a failed review operation for the user and logs it. func (a *App) reviewFailed(operation string, err error) { a.notifyError(i18n.SharedFormat(a.language(), "desktop.gitReview.operationFailed", map[string]string{"reason": reviewReason(err)})) - a.gitOperationFailed(operation, err) + a.operationFailed(operation, err) } // --- Blame --- @@ -126,7 +126,7 @@ func (a *App) openBlame(p *project, relative string) { b.loading = false if err != nil { b.err = i18n.SharedFormat(a.language(), "desktop.gitReview.blameFailed", map[string]string{"reason": reviewReason(err)}) - a.gitOperationFailed("git_blame", err) + a.operationFailed("git_blame", err) return } b.lines, b.text = lines, text @@ -194,7 +194,7 @@ func (a *App) loadUntracked(p *project) { u.loading = false if err != nil { u.err = reviewReason(err) - a.gitOperationFailed("git_untracked_directory", err) + a.operationFailed("git_untracked_directory", err) return } u.err, u.changes = "", changes diff --git a/desktop/internal/workbench/gitreview_tools.go b/desktop/internal/workbench/gitreview_tools.go index 82679c40b4..5c4deb8d01 100644 --- a/desktop/internal/workbench/gitreview_tools.go +++ b/desktop/internal/workbench/gitreview_tools.go @@ -84,7 +84,7 @@ func (a *App) loadPush(p *project) { s.loading = false if err != nil { s.err, s.hasPrev = i18n.Shared(a.language(), "git.pushDialog.previewFailed")+" "+reviewReason(err), false - a.gitOperationFailed("git_push_preview", err) + a.operationFailed("git_push_preview", err) return } s.preview, s.hasPrev = preview, true @@ -191,7 +191,7 @@ func (a *App) loadTools(p *project) { t.loading, t.repositories = false, repos if err != nil { t.err = reviewReason(err) - a.gitOperationFailed("git_repositories", err) + a.operationFailed("git_repositories", err) return } t.err = "" diff --git a/desktop/internal/workbench/gitsync.go b/desktop/internal/workbench/gitsync.go index db4e8e240b..8f6e161ec3 100644 --- a/desktop/internal/workbench/gitsync.go +++ b/desktop/internal/workbench/gitsync.go @@ -180,10 +180,10 @@ func (a *App) runSyncAt(p *project, root, operation, label string, failed func(r a.notifyInfo(a.text.Sync.Cancelled) case core.IsAuthenticationFailure(err): a.notifyError(a.text.Sync.AuthFailed(syncReason(err))) - a.gitOperationFailed(operation, err) + a.operationFailed(operation, err) default: a.notifyError(failed(syncReason(err))) - a.gitOperationFailed(operation, err) + a.operationFailed(operation, err) } } }) diff --git a/desktop/internal/workbench/gitworktree.go b/desktop/internal/workbench/gitworktree.go index 9378f0ffda..7edd3c9c77 100644 --- a/desktop/internal/workbench/gitworktree.go +++ b/desktop/internal/workbench/gitworktree.go @@ -365,7 +365,7 @@ func (a *App) loadWorktrees(p *project) { w.loading, w.loaded, w.err = false, true, err if err != nil { w.list = nil - a.gitOperationFailed("git_worktrees", err) + a.operationFailed("git_worktrees", err) return } w.list = list @@ -647,7 +647,7 @@ func (a *App) readWorktreeHistory(p *project, cursor string) { } else { h.failed = true } - a.gitOperationFailed("git_worktree_history", err) + a.operationFailed("git_worktree_history", err) return } h.loaded = true @@ -656,7 +656,7 @@ func (a *App) readWorktreeHistory(p *project, cursor string) { h.remotes, h.current, h.graph = remotes, current, graph if graphErr != nil { // The commits still show, without their lanes. - a.gitOperationFailed("git_worktree_graph", graphErr) + a.backgroundFailed("git_worktree_graph", graphErr) } } }) @@ -700,7 +700,7 @@ func (a *App) runWorktreeWrite(p *project, operation string, removing bool, } w.dialog = worktreeDialogNone a.notifyError(worktreeFailureText(&a.text.Worktrees, removing, err)) - a.gitOperationFailed(operation, err) + a.operationFailed(operation, err) if worktreeErrorCode(err) == core.CodeGitWorktreeNotRegistered { a.loadWorktrees(p) } @@ -787,7 +787,7 @@ func (a *App) revealWorktree(path string) { err := app.RevealPath(path) return func(a *App) { if err != nil { - a.gitOperationFailed("git_worktree_reveal", err) + a.operationFailed("git_worktree_reveal", err) a.notifyError(a.text.Worktrees.Failed(err.Error())) } } @@ -798,6 +798,7 @@ func (a *App) revealWorktree(path string) { func (a *App) copyWorktreePath(path string) { a.performed("git.worktree.copyPath", surfaceButton) if err := app.SetClipboardText(path); err != nil { + a.operationFailed("clipboard_copy", err) a.notifyError(a.text.Worktrees.Failed(err.Error())) } } @@ -840,7 +841,7 @@ func (a *App) beginCreateWorktree(p *project) { } cr.refs, cr.refsErr, cr.refsLoaded = refs, err, true if err != nil { - a.gitOperationFailed("git_worktree_references", err) + a.operationFailed("git_worktree_references", err) } a.syncWorktreeCreation(p) } @@ -863,7 +864,7 @@ func (a *App) syncWorktreeCreation(p *project) { func (a *App) previewWorktreeCreation(p *project, require bool) bool { w := &p.worktrees cr := &w.create - ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) defer cancel() result, err := a.kernel.GitWorktreeCreationPreview(ctx, core.GitWorktreeCreationInput{ Root: p.git.repositoryRoot(p.root), Mode: cr.mode, Kind: cr.kind, Reference: cr.reference, @@ -872,7 +873,7 @@ func (a *App) previewWorktreeCreation(p *project, require bool) bool { References: cr.refs.References, CheckedOutBranches: checkedOutBranches(w.list), }) if err != nil { - a.gitOperationFailed("git_worktree_creation_preview", err) + a.operationFailed("git_worktree_creation_preview", err) cr.result.Ready = false cr.key = cr.inputs(w.gen) return false diff --git a/desktop/internal/workbench/html_preview.go b/desktop/internal/workbench/html_preview.go index 39deaad2d8..17a6d260b0 100644 --- a/desktop/internal/workbench/html_preview.go +++ b/desktop/internal/workbench/html_preview.go @@ -180,7 +180,7 @@ func (a *App) askHTMLSite(p *project, d *document, s *htmlPreviewState) { } if err != nil { s.failed = true - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("html_preview_site", err)) + a.operationFailed("html_preview_site", err) return } s.site = &site diff --git a/desktop/internal/workbench/inlineedit.go b/desktop/internal/workbench/inlineedit.go index 85290fa06b..96a933aa07 100644 --- a/desktop/internal/workbench/inlineedit.go +++ b/desktop/internal/workbench/inlineedit.go @@ -112,7 +112,7 @@ func (a *App) runInlineEdit(p *project) { case errors.Is(err, context.Canceled): case err != nil: s.failure = a.inlineEditFailure(err) - a.gitOperationFailed("ai_inline_edit", err) + a.operationFailed("ai_inline_edit", err) default: s.hasResult, s.result = true, edited s.diff = lineDiff(s.selected, edited) @@ -162,6 +162,8 @@ func (a *App) acceptInlineEdit(p *project) { view := s.doc.view text, _ := view.Text() if view.Revision() != s.revision && (s.end > len(text) || string(text[s.start:s.end]) != s.selected) || view.IsComposing() { + // The document changed under the suggestion since it was made. + a.operationRejected("inline_edit_accept", "stale") a.notifyError(t.Stale) a.closeInlineEdit() return @@ -169,7 +171,7 @@ func (a *App) acceptInlineEdit(p *project) { a.performed("ai.inlineEdit.accept", surfaceButton) if err := view.ApplyEdits([]editorview.TextEdit{{Range: editorview.Range{Start: s.start, End: s.end}, Text: s.result}}); err != nil { a.notifyError(t.Failed(err.Error())) - a.gitOperationFailed("ai_inline_edit", err) + a.operationFailed("ai_inline_edit", err) } a.closeInlineEdit() } diff --git a/desktop/internal/workbench/legacy_import.go b/desktop/internal/workbench/legacy_import.go index b60e05922b..07be58c9a0 100644 --- a/desktop/internal/workbench/legacy_import.go +++ b/desktop/internal/workbench/legacy_import.go @@ -96,7 +96,7 @@ func (a *App) showLegacyImport(found legacyimport.Found, err error) { a.notifyInfo(i18n.Shared(language, "desktop.legacyImport.none")) return case err != nil: - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("settings_import_legacy_read", err)) + a.operationFailed("settings_import_legacy_read", err) a.notifyError(i18n.SharedFormat(language, "desktop.legacyImport.readFailed", map[string]string{"error": err.Error()})) return } @@ -315,7 +315,7 @@ func (a *App) applyLegacyImport() { a.saveSettings() language := a.language() if err := a.verifySettingsSaved(); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("settings_import_legacy_apply", err)) + a.operationFailed("settings_import_legacy_apply", err) a.notifyError(i18n.SharedFormat(language, "desktop.legacyImport.failed", map[string]string{"error": err.Error()})) return } @@ -328,7 +328,7 @@ func (a *App) applyLegacyImport() { before := len(a.recent) a.reduceRecent(entries, core.NormalizeRecent(), true) if err := a.verifyRecentSaved(); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("settings_import_legacy_recent", err)) + a.operationFailed("settings_import_legacy_recent", err) a.notifyError(i18n.SharedFormat(language, "desktop.legacyImport.failed", map[string]string{"error": err.Error()})) return } diff --git a/desktop/internal/workbench/lineedit.go b/desktop/internal/workbench/lineedit.go index 6a6bc3fd70..8fcca9619e 100644 --- a/desktop/internal/workbench/lineedit.go +++ b/desktop/internal/workbench/lineedit.go @@ -140,7 +140,7 @@ func (a *App) runLineOperation(p *project, d *document, op core.LineEditOperatio } func (a *App) lineEditFailed(err error) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_line_edit", err)) + a.operationFailed("editor_line_edit", err) a.notifyError(i18n.Shared(a.language(), "desktop.editor.lineEditFailed")) } diff --git a/desktop/internal/workbench/local_history.go b/desktop/internal/workbench/local_history.go index 58a4e486ec..c98ea9fd57 100644 --- a/desktop/internal/workbench/local_history.go +++ b/desktop/internal/workbench/local_history.go @@ -102,7 +102,7 @@ func (a *App) localHistoryJob(p *project, work func(ctx context.Context, kernel err := work(ctx, kernel, root, storage, policy) return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("local_history_record", err)) + a.backgroundFailed("local_history_record", err) } } }) @@ -254,6 +254,7 @@ func (a *App) restoreLocalHistory(p *project) { data, _ := d.view.Text() a.recordLocalHistory(p, path, "restore", historyTexts{before: append([]byte(nil), data...)}) if err := d.view.ApplyEdits([]editorview.TextEdit{{Range: editorview.Range{Start: 0, End: len(data)}, Text: text}}); err != nil { + a.operationFailed("local_history_restore", err) a.notifyError(a.text.History.Failed(err.Error())) return } @@ -393,7 +394,7 @@ func (a *App) compareLocalHistory(p *project, previous bool) { h.busy = false } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("local_history_compare", err)) + a.operationFailed("local_history_compare", err) if same { h.failure = a.text.History.Failed(err.Error()) } diff --git a/desktop/internal/workbench/local_history_settings.go b/desktop/internal/workbench/local_history_settings.go index 25cba043f8..6ae13e4edc 100644 --- a/desktop/internal/workbench/local_history_settings.go +++ b/desktop/internal/workbench/local_history_settings.go @@ -52,7 +52,7 @@ func (s localHistorySettings) Preview(ctx context.Context, rules core.HistoryIgn // log-exempt: 随输入实时重算的校验提示:测试路径越出项目时 Core 拒绝请求,卡片随键入提示,不是系统失败。 var refused *core.Error if !errors.As(err, &refused) || refused.Code != core.CodeInvalidRequest { - s.logFailure("local_history_preview", err) + s.logFailure(ctx, "local_history_preview", err) } return preview, err } @@ -65,7 +65,7 @@ func (s localHistorySettings) Usage(ctx context.Context, limitMegabytes int) (co } limit := settingswindow.LocalHistorySettings{LimitMegabytes: limitMegabytes}.Policy().StorageLimitBytes usage, err := s.kernel.LocalHistoryUsage(ctx, storage, limit) - s.logFailure("local_history_usage", err) + s.logFailure(ctx, "local_history_usage", err) return usage, true, err } @@ -76,16 +76,17 @@ func (s localHistorySettings) Clear(ctx context.Context) error { return nil } err := s.kernel.ClearHistory(ctx, storage) - s.logFailure("local_history_clear", err) + s.logFailure(ctx, "local_history_clear", err) return err } // logFailure records a failed local history request. The settings window gave up on it when -// its context ended, which is not a failure. -func (s localHistorySettings) logFailure(operation string, err error) { +// its context ended, which is not a failure. It runs on the settings worker, so it logs under +// the user action ctx carries. +func (s localHistorySettings) logFailure(ctx context.Context, operation string, err error) { // log-exempt: 用户取消:设置窗口关闭或放弃了这次请求。 if err == nil || errors.Is(err, context.Canceled) { return } - s.app.emit(operationFailedLevel, operationFailedEvent, operationFailedFields(operation, err)) + s.app.operationFailedIn(ctx, operation, err) } diff --git a/desktop/internal/workbench/logevents_test.go b/desktop/internal/workbench/logevents_test.go index fa317dcfe0..13540fd5f1 100644 --- a/desktop/internal/workbench/logevents_test.go +++ b/desktop/internal/workbench/logevents_test.go @@ -38,6 +38,11 @@ func TestLogEventsMatchCatalog(t *testing.T) { {core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "document_external_change", "reason": "disk_conflict"}}, {documentFailedLevel, documentEventSaveFailed, documentSaveFields(12, 41, failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("project_tree_list", failure)}, + {backgroundFailedLevel, backgroundFailedEvent, operationFailedFields("project_tree_list", failure)}, + {core.LevelWarn, "app.settings.decode_failed", storedStateFields("settings", failure)}, + {core.LevelWarn, "app.settings.decode_failed", storedStateFields("recent_projects", &fs.PathError{Op: "open", Path: "recent.json", Err: fs.ErrPermission})}, + {operationRejectedLevel, operationRejectedEvent, operationRejectedFields("project_tree_move", "cross_wsl_boundary")}, + {operationFailedLevel, operationFailedEvent, operationFailedFields("editor_encoding_reopen", errLossyDecode)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("git_branch_name_preview", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("git_commit", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("settings_save", failure)}, @@ -53,14 +58,14 @@ func TestLogEventsMatchCatalog(t *testing.T) { {operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_search_watch", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("project_tree_watch", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("project_tree_filter_changes", failure)}, - {core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "project_tree_watch", "reason": "watch_events_lost"}}, - {core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "project_tree_watch", "reason": "event_limit_exceeded"}}, + {backgroundFailedLevel, backgroundFailedEvent, operationFailedFields("project_tree_watch", errWatchEventsLost)}, + {backgroundFailedLevel, backgroundFailedEvent, operationFailedFields("project_tree_watch", errWatchEventLimit)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_search_everywhere", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_search_everywhere_page", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_search_everywhere_watch", failure)}, - {core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "workspace_search", "reason": "invalid_result_path"}}, - {core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "workspace_search_incremental_update", "reason": "watch_events_lost"}}, - {core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "workspace_search_incremental_update", "reason": "event_limit_exceeded"}}, + {operationRejectedLevel, operationRejectedEvent, operationRejectedFields("workspace_search", "invalid_result_path")}, + {backgroundFailedLevel, backgroundFailedEvent, operationFailedFields("workspace_search_incremental_update", errWatchEventsLost)}, + {backgroundFailedLevel, backgroundFailedEvent, operationFailedFields("workspace_search_incremental_update", errWatchEventLimit)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("workbench_background", documentLogError(errors.New("image: unknown format")))}, {operationFailedLevel, operationFailedEvent, operationFailedFields("workbench_background_save", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("workbench_background_remove", failure)}, @@ -79,9 +84,9 @@ func TestLogEventsMatchCatalog(t *testing.T) { {operationFailedLevel, operationFailedEvent, operationFailedFields("keymap_schemes", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_settings_surface", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_settings_load", failure)}, - {core.LevelWarn, pluginSettingsLoadRejectedEvent, pluginSettingsLoadRejected("localization_unreadable")}, - {core.LevelWarn, pluginSettingsLoadRejectedEvent, pluginSettingsLoadRejected("invalid_localization")}, - {core.LevelWarn, pluginSettingsLoadRejectedEvent, pluginSettingsLoadRejected("invalid_stored_values")}, + {operationRejectedLevel, operationRejectedEvent, operationRejectedFields("plugin_settings_load", "localization_unreadable")}, + {operationRejectedLevel, operationRejectedEvent, operationRejectedFields("plugin_settings_load", "invalid_localization")}, + {operationRejectedLevel, operationRejectedEvent, operationRejectedFields("plugin_settings_load", "invalid_stored_values")}, {core.LevelInfo, "app.action.performed", map[string]any{"action": "settings.openLink", "surface": surfaceButton}}, } events := make([]core.LogEvent, len(cases)) diff --git a/desktop/internal/workbench/markdown_preview.go b/desktop/internal/workbench/markdown_preview.go index cf09550926..b9edcdd758 100644 --- a/desktop/internal/workbench/markdown_preview.go +++ b/desktop/internal/workbench/markdown_preview.go @@ -605,7 +605,7 @@ func (a *App) followDocumentLink(p *project, path, destination string, anchor fu target, err := kernel.ResolveMarkdownReference(ctx, path, root, destination, core.MarkdownLink) if err != nil { return func(a *App) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("preview_link", err)) + a.operationFailed("preview_link", err) } } if target.Kind == "file" { @@ -617,7 +617,7 @@ func (a *App) followDocumentLink(p *project, path, destination string, anchor fu switch target.Kind { case "external": if err := openURL(target.URL); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("preview_link", err)) + a.operationFailed("preview_link", err) } case "anchor": if anchor != nil { diff --git a/desktop/internal/workbench/markdown_web.go b/desktop/internal/workbench/markdown_web.go index 53014fdf6e..c5ac27f82d 100644 --- a/desktop/internal/workbench/markdown_web.go +++ b/desktop/internal/workbench/markdown_web.go @@ -169,7 +169,7 @@ func (a *App) renderMarkdownWeb(p *project, d *document, s *markdownPreviewState w.rendering, w.rendered = -1, revision if err != nil { // The page keeps the last HTML; the next change renders again. - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("markdown_render", err)) + a.backgroundFailed("markdown_render", err) return } w.html = html diff --git a/desktop/internal/workbench/memory_monitor.go b/desktop/internal/workbench/memory_monitor.go index 3a65f7309b..a3a209f015 100644 --- a/desktop/internal/workbench/memory_monitor.go +++ b/desktop/internal/workbench/memory_monitor.go @@ -149,7 +149,7 @@ func (a *App) readMemoryNames() { names := memoryNamesOf(installedPluginFacts(entries, nil)) return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("memory_plugin_names", err)) + a.backgroundFailed("memory_plugin_names", err) } a.memory.names = names a.memory.sampledAt = time.Time{} @@ -208,7 +208,7 @@ func (a *App) memorySampled(summary core.MemorySummary, err error) { m.sampling = false if err != nil { if !m.failed { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("memory_sample", err)) + a.backgroundFailed("memory_sample", err) } m.failed = true return diff --git a/desktop/internal/workbench/navigation.go b/desktop/internal/workbench/navigation.go index e46243d31f..3381898480 100644 --- a/desktop/internal/workbench/navigation.go +++ b/desktop/internal/workbench/navigation.go @@ -108,14 +108,14 @@ func (a *App) syncNavigation(p *project) { v := &a.navigation if !v.open || v.project != p || v.generation != gen || v.input.Text() != value { if err != nil && !errors.Is(err, context.Canceled) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_parse_navigation", err)) + a.backgroundFailed("editor_parse_navigation", err) } // log-exempt: 用户取消:旧输入的结果已被替换或对话框已关闭。 return } v.cancel = nil if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_parse_navigation", err)) + a.operationFailed("editor_parse_navigation", err) return } v.target = target diff --git a/desktop/internal/workbench/navigation_history.go b/desktop/internal/workbench/navigation_history.go index 6001ea75ac..c22ff73722 100644 --- a/desktop/internal/workbench/navigation_history.go +++ b/desktop/internal/workbench/navigation_history.go @@ -55,12 +55,12 @@ func (a *App) recordNavigationJump(p *project, path string, line, column int) { return } s := a.navigationHistoryOf(p) - ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) defer cancel() destination := core.NavigationLocation{Document: path, Line: line, Column: column} next, _, err := kernel.ReduceNavigationHistory(ctx, s.history, core.NavigationHistoryRecord(departure, &destination)) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_navigation_history", err)) + a.backgroundFailed("editor_navigation_history", err) return } s.history = next @@ -81,11 +81,11 @@ func (a *App) stepNavigation(p *project, forward bool) { if forward { event = core.NavigationHistoryForward(current) } - ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) defer cancel() next, destination, err := kernel.ReduceNavigationHistory(ctx, s.history, event) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_navigation_history", err)) + a.operationFailed("editor_navigation_history", err) return } if destination == nil { @@ -94,6 +94,7 @@ func (a *App) stepNavigation(p *project, forward bool) { } // A destination that no longer exists keeps the history as it was, so the entry is not lost. if _, err := os.Stat(destination.Document); err != nil { + a.operationRejected("editor_navigation_history", "destination_unavailable") a.notifyError(i18n.Shared(a.language(), "desktop.navigation.historyUnavailable")) return } diff --git a/desktop/internal/workbench/network.go b/desktop/internal/workbench/network.go index 2ab0ce213d..46b560828a 100644 --- a/desktop/internal/workbench/network.go +++ b/desktop/internal/workbench/network.go @@ -51,7 +51,7 @@ func (a *App) applyNetwork() { policy, err := kernel.ProxyPolicy(ctx, networkProxyRequest(stored, password)) if err != nil { a.post(func(a *App) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("network_proxy_policy", err)) + a.backgroundFailed("network_proxy_policy", err) }) return } @@ -92,6 +92,7 @@ func (a *App) setNetwork(next settingswindow.NetworkSettings, password *string) } a.post(func(a *App) { if err != nil { + a.operationFailed("network_credentials_save", err) a.notifyError(a.text.Errors.SaveFailed(err.Error())) } a.applyNetwork() diff --git a/desktop/internal/workbench/new_project.go b/desktop/internal/workbench/new_project.go index e5f4268d33..519d56d871 100644 --- a/desktop/internal/workbench/new_project.go +++ b/desktop/internal/workbench/new_project.go @@ -208,7 +208,7 @@ func (a *App) chooseNewProjectParent() { return } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("new_project_choose_directory", documentLogError(err))) + a.operationFailed("new_project_choose_directory", documentLogError(err)) if n.open && n.generation == generation { n.err = i18n.Shared(a.language(), "desktop.newProject.chooseFailed") } @@ -539,7 +539,7 @@ func (a *App) submitNewProject() { if parent == "~" || strings.HasPrefix(parent, "~/") || strings.HasPrefix(parent, "~\\") { home, err := os.UserHomeDir() if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("new_project_home", documentLogError(err))) + a.operationFailed("new_project_home", documentLogError(err)) n.err = i18n.Shared(a.language(), "desktop.newProject.invalidLocation") return } @@ -553,7 +553,7 @@ func (a *App) submitNewProject() { n.busy, n.cancelling, n.err = true, false, "" n.progress = nil generation := n.generation - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), 30*time.Second) n.cancel = cancel kernel := a.kernel a.background(nil, 0, func(context.Context) func(*App) { @@ -567,7 +567,7 @@ func (a *App) submitNewProject() { func (a *App) finishNewProject(generation uint64, result newProjectResult) { n := &a.newProject if result.err != nil && !errors.Is(result.err, context.Canceled) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("new_project_create", documentLogError(result.err))) + a.operationFailed("new_project_create", documentLogError(result.err)) } if !n.open || n.generation != generation { // log-exempt: 用户取消:窗口已关闭,保留可能已创建的目录。 @@ -624,7 +624,7 @@ func (a *App) submitGenerator(parent string) { progress := &runProgress{} n.progress = progress generation := n.generation - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(a.operationContext(context.Background())) n.cancel = cancel kernel := a.kernel a.background(nil, 0, func(context.Context) func(*App) { @@ -660,7 +660,7 @@ func (a *App) submitGenerator(parent string) { func (a *App) finishGenerator(generation uint64, result projectgen.Result) { n := &a.newProject if result.Failure != nil && !errors.Is(result.Failure, context.Canceled) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("new_project_generate", documentLogError(result.Failure.Err))) + a.operationFailed("new_project_generate", documentLogError(result.Failure.Err)) } if !n.open || n.generation != generation { // log-exempt: 用户取消:窗口已关闭,保留可能已创建的目录。 diff --git a/desktop/internal/workbench/new_project_view.go b/desktop/internal/workbench/new_project_view.go index da81dcf21d..2cb120e1ef 100644 --- a/desktop/internal/workbench/new_project_view.go +++ b/desktop/internal/workbench/new_project_view.go @@ -54,7 +54,7 @@ func (a *App) collectNewProject(c ui.C) { n.catalogFx.declare(c, revision, struct{}{}) if result, err, ok := n.catalogFx.take(); ok { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("new_project_catalog", documentLogError(err))) + a.operationFailed("new_project_catalog", documentLogError(err)) } if result.plugins != nil { n.applyCatalog(a, result) @@ -82,7 +82,7 @@ func (a *App) collectNewProject(c ui.C) { n.toolsFx.declare(c, form.key+"#"+revision, ids) if tools, err, ok := n.toolsFx.take(); ok { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("new_project_tools", documentLogError(err))) + a.operationFailed("new_project_tools", documentLogError(err)) } form.setTools(tools, err != nil) } @@ -96,7 +96,7 @@ func (a *App) collectNewProject(c ui.C) { n.formFx.declare(c, key, formRequest{manifest: form.plugin.Manifest, generatorID: form.entry.Generator.ID, input: input}) if result, err, ok := n.formFx.take(); ok { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("new_project_form", documentLogError(err))) + a.operationFailed("new_project_form", documentLogError(err)) } else { form.apply(result) form.formKey = key @@ -126,7 +126,7 @@ func (a *App) collectNewProjectSearch(c ui.C) { n.searchFx.declare(c, key, searchRequest{query: query, candidates: candidates}) if indices, err, ok := n.searchFx.take(); ok { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("new_project_search", documentLogError(err))) + a.operationFailed("new_project_search", documentLogError(err)) n.visible = nil return } diff --git a/desktop/internal/workbench/notifications.go b/desktop/internal/workbench/notifications.go index 59fd3be384..b1432488c4 100644 --- a/desktop/internal/workbench/notifications.go +++ b/desktop/internal/workbench/notifications.go @@ -33,6 +33,10 @@ type notification struct { unread bool // toast is the toast that shows it, which may have gone by itself already. toast ui.ToastID + // op is the user action the failure was last reported under, empty when it never came + // during one. The toast and the history offer View Logs for it, which opens the log window + // on that action's records. + op string } // notificationCenter is the history, newest first, and whether its panel is open. @@ -82,7 +86,8 @@ func (a *App) notificationColor(kind ui.ToastKind) gfx.Color { // notifyKind shows message as a toast of kind and records it. The same message of the same // kind again is not a second entry: its entry counts it, moves to the top, is unread again -// and its toast shows the count, replacing the toast it had. +// and its toast shows the count, replacing the toast it had. A failure reported during a user +// action refers to the action's records: its toast has a View Logs button. func (a *App) notifyKind(message string, kind ui.ToastKind) { a.notice = message center := &a.notifications @@ -101,11 +106,47 @@ func (a *App) notifyKind(message string, kind ui.ToastKind) { entry.count++ entry.at = a.now() entry.unread = !center.open + if kind == ui.ToastError && a.op.id != "" { + entry.op = a.op.id + } center.list = append([]*notification{entry}, center.list...) if len(center.list) > notificationHistoryLimit { center.list = center.list[:notificationHistoryLimit] } - entry.toast = a.overlay.toaster.Show(a.notificationText(entry), "", kind) + action := "" + if a.viewsLogs(entry) { + action = i18n.Shared(a.language(), "desktop.notifications.viewLogs") + } + entry.toast = a.overlay.toaster.ShowAction(a.notificationText(entry), "", kind, action) +} + +// viewsLogs says the notice offers View Logs: it refers to an action's records and there is a +// log window to show them in. +func (a *App) viewsLogs(entry *notification) bool { + return entry.op != "" && a.logs != nil +} + +// notificationActed opens the records of the notice whose toast's View Logs this paint +// delivered a press on. Call it after ui.Toasts. +func (a *App) notificationActed(c ui.C) { + id, ok := a.overlay.toaster.Acted() + if !ok { + return + } + for _, entry := range a.notifications.list { + if entry.toast == id && entry.op != "" { + op := entry.op + c.After(func() { a.viewNotificationLogs(op) }) + return + } + } +} + +// viewNotificationLogs is View Logs on a notice: the log window on the records of op, the +// action the notice reported a failure of. +func (a *App) viewNotificationLogs(op string) { + a.performed("logs.openOperation", surfaceNotification) + a.showLogs(op) } // notificationText is a notice's words, with how often it came when that is more than once. @@ -203,12 +244,20 @@ func (a *App) notificationPanel(c ui.C, anchor ui.Box) { } } -// notificationEntry declares a notice of the history: its words, when it came last and how often. +// notificationEntry declares a notice of the history: its words, when it came last and how +// often, and View Logs when it refers to an action's records. func (a *App) notificationEntry(k ui.C, entry *notification) { + language := a.language() ui.Wrap(k, entry.text).FontSize(a.theme.Metrics.FontSizeS) meta := entry.at.Format("15:04:05") if entry.count > 1 { - meta = i18n.SharedFormat(a.language(), "desktop.notifications.meta", map[string]string{"time": meta, "count": strconv.Itoa(entry.count)}) + meta = i18n.SharedFormat(language, "desktop.notifications.meta", map[string]string{"time": meta, "count": strconv.Itoa(entry.count)}) } - ui.Text(k, meta).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + ui.Row(k).FillWidth().Items(ui.Center).Gap(8).Children(func() { + ui.Text(k, meta).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Grow(1).Ellipsis() + if a.viewsLogs(entry) && ui.Button(k.Part("logs"), i18n.Shared(language, "desktop.notifications.viewLogs")).Ghost().Small().Clicked() { + op := entry.op + k.After(func() { a.viewNotificationLogs(op) }) + } + }) } diff --git a/desktop/internal/workbench/notifications_test.go b/desktop/internal/workbench/notifications_test.go index 2883cd5abd..6c63222f0b 100644 --- a/desktop/internal/workbench/notifications_test.go +++ b/desktop/internal/workbench/notifications_test.go @@ -6,6 +6,8 @@ import ( "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/logwindow" "github.com/vivaui/viva/ui" ) @@ -69,6 +71,81 @@ func TestNotificationBellOpensReadsAndClearsTheHistory(t *testing.T) { } } +// pageControls counts the controls named name that the pages declared. +func (h *harness) pageControls(name string) int { + count := 0 + for _, hit := range h.driver.Snapshot().Hits { + if hit.Label == name && !hit.IsLabel && !hit.Backdrop && !hit.ID.IsZero() { + count++ + } + } + return count +} + +// A failure reported during a user action refers to the action's records: its toast and its +// history entry offer View Logs, which opens the log window on them as an action of its own. +// A failure outside an action and a notice of another kind offer none. +func TestFailureNoticeOpensTheLogsOfTheActionThatFailed(t *testing.T) { + h := newHarnessWithLanguages(t, &testKernel{Client: core.NewClient()}, []string{"en-US"}) + h.open(t.TempDir()) + logger := &opRecordingLog{} + h.app.logSink = logger + h.app.logs = logwindow.NewController(logwindow.WindowOptions{}) + var opened []string + h.app.logWindowOpen = func(op string) error { + opened = append(opened, op) + return nil + } + viewLogs := i18n.Shared(h.app.language(), "desktop.notifications.viewLogs") + + h.app.performed("test.build", surfaceButton) + failed := h.app.op.id + h.app.notifyError("Build failed") + h.app.notifySuccess("Build cached") + h.app.endOperation() + h.app.notifyError("Index broken") + h.app.invalidator.Invalidate() + h.settle() + + ops := map[string]string{} + for _, entry := range h.app.notifications.list { + ops[entry.text] = entry.op + } + if ops["Build failed"] != failed || ops["Build cached"] != "" || ops["Index broken"] != "" { + t.Fatalf("the notices refer to %v; only the failure during action %q should", ops, failed) + } + if n := h.pageControls(viewLogs); n != 1 { + t.Fatalf("%d toasts offer %s, want only the failure's", n, viewLogs) + } + + h.clickNamed(viewLogs) + h.settle() + if len(opened) != 1 || opened[0] != failed { + t.Fatalf("the toast opened the logs of %q, want %q", opened, failed) + } + viewed := logger.ops("app.action.performed") + if len(viewed) != 2 || viewed[1] == "" || viewed[1] == failed { + t.Fatalf("View Logs was recorded under %q; want an action of its own after %q", viewed, failed) + } + + // The history offers the same once the toasts have gone. + for _, entry := range h.app.notifications.list { + h.app.overlay.toaster.Close(entry.toast) + } + h.app.invalidator.Invalidate() + h.settle() + h.clickNamed("Notifications, 3 unread") + h.settle() + if n := h.pageControls(viewLogs); n != 1 { + t.Fatalf("%d history entries offer %s, want only the failure's", n, viewLogs) + } + h.clickNamed(viewLogs) + h.settle() + if len(opened) != 2 || opened[1] != failed { + t.Fatalf("the history opened the logs of %q, want %q", opened, failed) + } +} + // The history keeps the newest notices up to its limit. func TestNotificationHistoryKeepsTheNewest(t *testing.T) { h := newHarnessWithLanguages(t, &testKernel{Client: core.NewClient()}, []string{"en-US"}) diff --git a/desktop/internal/workbench/operation.go b/desktop/internal/workbench/operation.go new file mode 100644 index 0000000000..bbc51ed065 --- /dev/null +++ b/desktop/internal/workbench/operation.go @@ -0,0 +1,97 @@ +package workbench + +import ( + "context" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" +) + +// A user action is one operation from the click to the last thing it causes. performed starts +// it on the window thread and it lasts until the window callback it was started in returns +// (operating). Meanwhile every record the window writes carries its op, background work started +// for it carries it in its context, so Core records the requests the work sends under the same +// op (core.Origin), and the work's result is applied under it again, so a failure the result +// reports is found under the action that caused it. + +// operation is the user action the window thread is running; the zero value is none. +type operation struct { + // id is the op of the action's records and the operation of its Core requests. + id string + // trigger is the stable id of the action, the trigger of its Core requests. + trigger string +} + +// origin is what the action's Core requests report. +func (o operation) origin() core.Origin { + return core.Origin{Operation: o.id, Trigger: o.trigger} +} + +// operationContext is parent carrying the user action in progress, for work the window thread +// starts for it on another goroutine; parent itself when no action is in progress. +func (a *App) operationContext(parent context.Context) context.Context { + return core.WithOrigin(parent, a.op.origin()) +} + +// within runs apply on the window thread under the action op, then restores the action that was +// in progress: the result of an action's work belongs to the action. +func (a *App) within(op operation, apply func(*App)) { + previous := a.op + a.op = op + defer func() { a.op = previous }() + apply(a) +} + +// operating makes the window callbacks of config end the user action they start: an action +// started in a callback does not leak into the next one, such as a paint or a refresh that +// follows a click. +func (a *App) operating(config app.Config) app.Config { + config.OnPointer = operatingOn(a, config.OnPointer) + config.OnKey = operatingOn(a, config.OnKey) + config.OnShortcut = operatingOn(a, config.OnShortcut) + config.OnModifierTap = operatingOn(a, config.OnModifierTap) + config.OnScroll = operatingOn(a, config.OnScroll) + config.OnFileDrop = operatingOn(a, config.OnFileDrop) + if focusLost := config.OnFocusLost; focusLost != nil { + config.OnFocusLost = func() gfx.EventResult { + defer a.endOperation() + return focusLost() + } + } + if wake := config.OnWake; wake != nil { + config.OnWake = func() { + defer a.endOperation() + wake() + } + } + if paint := config.Paint; paint != nil { + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + defer a.endOperation() + paint(canvas, size) + } + } + if closeRequest := config.OnCloseRequest; closeRequest != nil { + config.OnCloseRequest = func(allow func()) { + defer a.endOperation() + closeRequest(allow) + } + } + return config +} + +// operatingOn is handle ending the user action it starts; nil stays nil. +func operatingOn[E any](a *App, handle func(E) gfx.EventResult) func(E) gfx.EventResult { + if handle == nil { + return nil + } + return func(event E) gfx.EventResult { + defer a.endOperation() + return handle(event) + } +} + +// endOperation ends the user action in progress. +func (a *App) endOperation() { + a.op = operation{} +} diff --git a/desktop/internal/workbench/operation_test.go b/desktop/internal/workbench/operation_test.go new file mode 100644 index 0000000000..06bdc2ae03 --- /dev/null +++ b/desktop/internal/workbench/operation_test.go @@ -0,0 +1,292 @@ +package workbench + +import ( + "context" + "fmt" + "go/ast" + "go/parser" + "go/token" + "path/filepath" + "sort" + "strings" + "sync" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/logwindow" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" +) + +// opRecordingLog keeps each record with the op it was written under. +type opRecordingLog struct { + logwindow.Source + mu sync.Mutex + records []opRecord +} + +type opRecord struct{ event, op string } + +func (l *opRecordingLog) Emit(level core.LogLevel, event, op string, fields map[string]any) { + l.mu.Lock() + defer l.mu.Unlock() + l.records = append(l.records, opRecord{event: event, op: op}) +} + +// ops is the op of each record of event, in the order they were written. +func (l *opRecordingLog) ops(event string) []string { + l.mu.Lock() + defer l.mu.Unlock() + var ops []string + for _, record := range l.records { + if record.event == event { + ops = append(ops, record.op) + } + } + return ops +} + +// TestUserActionCarriesItsOpToItsWorkAndResult starts an action in a window callback that +// starts background work, and checks that the action's record, the work's record, the context +// the work sends Core requests with and the result applied on the window thread share the op, +// and that the op ends with the callback and with the result. +func TestUserActionCarriesItsOpToItsWorkAndResult(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + a := h.app + logger := &opRecordingLog{} + a.logSink = logger + var origin core.Origin + var opDuringResult operation + config := a.operating(app.Config{OnKey: func(gfx.KeyEvent) gfx.EventResult { + a.performed("test.action", surfaceShortcut) + a.background(nil, 0, func(ctx context.Context) func(*App) { + origin = core.OriginOf(ctx) + a.emitIn(ctx, core.LevelInfo, "test.work", nil) + return func(a *App) { + opDuringResult = a.op + a.emit(core.LevelInfo, "test.result", nil) + } + }) + return gfx.EventResult{} + }}) + config.OnKey(gfx.KeyEvent{}) + if a.op != (operation{}) { + t.Fatalf("the action %+v outlived the callback that started it", a.op) + } + a.emit(core.LevelInfo, "test.after", nil) + h.settle() + + performed := logger.ops("app.action.performed") + if len(performed) != 1 || performed[0] == "" { + t.Fatalf("app.action.performed ops = %q, want one op", performed) + } + op := performed[0] + if got := logger.ops("test.work"); len(got) != 1 || got[0] != op { + t.Errorf("the work's record ops = %q, want %q", got, op) + } + if got := logger.ops("test.result"); len(got) != 1 || got[0] != op { + t.Errorf("the result's record ops = %q, want %q", got, op) + } + if got := logger.ops("test.after"); len(got) != 1 || got[0] != "" { + t.Errorf("a record after the callback has ops %q, want none", got) + } + if want := (core.Origin{Operation: op, Trigger: "test.action"}); origin != want { + t.Errorf("the work's requests report %+v, want %+v", origin, want) + } + if opDuringResult.id != op { + t.Errorf("the result ran under %+v, want op %q", opDuringResult, op) + } + if a.op != (operation{}) { + t.Errorf("the action %+v outlived its result", a.op) + } +} + +// TestBackgroundWorkWithoutAnActionHasNoOp checks that work started outside an action sends +// requests that belong to no action and applies its result under none. +func TestBackgroundWorkWithoutAnActionHasNoOp(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + a := h.app + logger := &opRecordingLog{} + a.logSink = logger + var origin core.Origin + a.background(nil, 0, func(ctx context.Context) func(*App) { + origin = core.OriginOf(ctx) + return func(a *App) { a.emit(core.LevelInfo, "test.result", nil) } + }) + h.settle() + if origin != (core.Origin{}) { + t.Errorf("work outside an action reports %+v", origin) + } + if got := logger.ops("test.result"); len(got) != 1 || got[0] != "" { + t.Errorf("the result's record ops = %q, want none", got) + } +} + +// operationAccessors are the App methods that read or set a.op, which only the window thread +// may do. +var operationAccessors = []string{"emit", "performed", "operationContext", "within", "endOperation"} + +// TestOperationIsOnlyUsedOnTheWindowThread finds the App methods that can run off the window +// thread and fails when one of them reads or sets the action in progress: a go statement's +// function, the work given to background and every App method they call run off it, except the +// functions they hand back to the window thread (func(*App) results and the functions given to +// windowRunners). Such code records with emitIn and the work's context instead. +func TestOperationIsOnlyUsedOnTheWindowThread(t *testing.T) { + paths, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + fset := token.NewFileSet() + // calls is, for each App method, the App methods its window-thread part calls. + calls := map[string]map[string][]token.Pos{} + // offThread is where each App method is called off the window thread directly. + offThread := map[string][]token.Pos{} + for _, path := range paths { + if strings.HasSuffix(path, "_test.go") { + continue + } + file, err := parser.ParseFile(fset, path, nil, 0) + if err != nil { + t.Fatal(err) + } + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + mine := map[string][]token.Pos{} + if isAppMethod(fn) { + calls[fn.Name.Name] = mine + } + var walk func(node ast.Node, off, record bool) + walk = func(node ast.Node, off, record bool) { + ast.Inspect(node, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.GoStmt: + if lit, ok := x.Call.Fun.(*ast.FuncLit); ok { + walk(lit.Body, true, false) + for _, arg := range x.Call.Args { + walk(arg, off, record) + } + return false + } + if sel, ok := x.Call.Fun.(*ast.SelectorExpr); ok && isReceiver(sel.X) { + offThread[sel.Sel.Name] = append(offThread[sel.Sel.Name], x.Pos()) + } + case *ast.FuncLit: + if isApply(x) { + // An apply function runs on the window thread whoever made it. + walk(x.Body, false, false) + return false + } + case *ast.CallExpr: + sel, ok := x.Fun.(*ast.SelectorExpr) + if !ok { + return true + } + if windowRunners[sel.Sel.Name] && isReceiver(sel.X) { + for _, arg := range x.Args { + if lit, ok := arg.(*ast.FuncLit); ok { + walk(lit.Body, false, false) + } else { + walk(arg, off, record) + } + } + return false + } + if sel.Sel.Name == "background" && len(x.Args) == 3 { + if lit, ok := x.Args[2].(*ast.FuncLit); ok { + walk(x.Args[0], off, record) + walk(lit.Body, true, false) + return false + } + } + if !isReceiver(sel.X) { + return true + } + if off { + offThread[sel.Sel.Name] = append(offThread[sel.Sel.Name], x.Pos()) + } else if record { + mine[sel.Sel.Name] = append(mine[sel.Sel.Name], x.Pos()) + } + } + return true + }) + } + walk(fn.Body, false, true) + } + } + // An App method called off the window thread runs its window-thread part off it too. + why := map[string]string{} + var queue []string + for name, where := range offThread { + if _, ok := calls[name]; ok { + why[name] = "called off the window thread at " + fset.Position(where[0]).String() + queue = append(queue, name) + } + } + for len(queue) > 0 { + name := queue[0] + queue = queue[1:] + for callee := range calls[name] { + if _, ok := calls[callee]; !ok { + continue + } + if _, seen := why[callee]; seen { + continue + } + why[callee] = "called by " + name + queue = append(queue, callee) + } + } + var found []string + for _, accessor := range operationAccessors { + for _, pos := range offThread[accessor] { + found = append(found, fmt.Sprintf("%s: %s off the window thread", fset.Position(pos), accessor)) + } + for name, reason := range why { + for _, pos := range calls[name][accessor] { + found = append(found, fmt.Sprintf("%s: %s calls %s and is %s", fset.Position(pos), name, accessor, reason)) + } + } + } + sort.Strings(found) + for _, line := range found { + t.Error(line) + } +} + +// windowRunners are the App methods that run the functions they are given on the window thread. +var windowRunners = map[string]bool{"post": true, "ideAPIOnProject": true, "ideAPIOnProjectLater": true, "ideAPIAwaitLaunch": true} + +func isAppMethod(fn *ast.FuncDecl) bool { + if fn.Recv == nil || len(fn.Recv.List) != 1 { + return false + } + star, ok := fn.Recv.List[0].Type.(*ast.StarExpr) + if !ok { + return false + } + id, ok := star.X.(*ast.Ident) + return ok && id.Name == "App" +} + +// isApply reports whether lit is a func(*App), which the window thread runs. +func isApply(lit *ast.FuncLit) bool { + params := lit.Type.Params.List + if len(params) != 1 { + return false + } + star, ok := params[0].Type.(*ast.StarExpr) + if !ok { + return false + } + id, ok := star.X.(*ast.Ident) + return ok && id.Name == "App" +} + +// isReceiver reports whether x is the workbench, which the package always names a. +func isReceiver(x ast.Expr) bool { + id, ok := x.(*ast.Ident) + return ok && id.Name == "a" +} diff --git a/desktop/internal/workbench/outline.go b/desktop/internal/workbench/outline.go index cc37159c24..594d04ff1c 100644 --- a/desktop/internal/workbench/outline.go +++ b/desktop/internal/workbench/outline.go @@ -233,7 +233,7 @@ func (a *App) applyMarkdownOutline(request *outlineMarkdownRequest, symbols []co } s.outlining = nil if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("markdown_outline", err)) + a.backgroundFailed("markdown_outline", err) s.failed = true return } @@ -266,7 +266,7 @@ func (a *App) applyOutline(pending *semanticPending, event core.BackendEvent, fa } symbols, err := core.PluginDocumentSymbols(event) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_document_symbols", err)) + a.backgroundFailed("plugin_document_symbols", err) s.failed = true return } diff --git a/desktop/internal/workbench/output_style.go b/desktop/internal/workbench/output_style.go index 359081851f..b2ddb13c66 100644 --- a/desktop/internal/workbench/output_style.go +++ b/desktop/internal/workbench/output_style.go @@ -217,9 +217,10 @@ func (b *outputBuffer) all() string { } // reportOutputStyleFailure logs that Core could not decode a console's escapes; that console -// shows the rest of its output as it came. Each decoder reports its failure once; nil is none. +// shows the rest of its output as it came, so the colors are what is lost, not the output. Each +// decoder reports its failure once; nil is none. func (a *App) reportOutputStyleFailure(failure error) { if failure != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("output_style", failure)) + a.backgroundFailed("output_style", failure) } } diff --git a/desktop/internal/workbench/outputlinks.go b/desktop/internal/workbench/outputlinks.go index 32f8845fa0..69ffaf469c 100644 --- a/desktop/internal/workbench/outputlinks.go +++ b/desktop/internal/workbench/outputlinks.go @@ -96,7 +96,7 @@ func (a *App) finishOutputLinkSources(p *project, sources []core.OutputLinkSourc p.links.loaded = true p.links.sources = sources if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("output_links", err)) + a.backgroundFailed("output_links", err) } } @@ -160,7 +160,7 @@ func (a *App) flushOutputLinks(p *project) { l.links[key] = links } if failure != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("output_links", failure)) + a.backgroundFailed("output_links", failure) } } }) @@ -178,7 +178,10 @@ func (a *App) openOutputLink(p *project, link core.OutputLink) { a.background(p, outputLinkTimeout, func(ctx context.Context) func(*App) { path := firstExistingFile(location.Paths) if path == "" { - return func(a *App) { a.notifyError(messages.LinkMissing) } + return func(a *App) { + a.operationRejected("output_link_open", "target_missing") + a.notifyError(messages.LinkMissing) + } } return func(a *App) { a.openFileAtPosition(p, path, zeroBased(location.Line), zeroBased(location.Column)) } }) @@ -188,16 +191,22 @@ func (a *App) openOutputLink(p *project, link core.OutputLink) { location, err := a.plugins.ResolveOutputLink(ctx, pluginID, function, json.RawMessage(groups), p.root) if err != nil { return func(a *App) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("output_link_resolve", err)) + a.operationFailed("output_link_resolve", err) a.notifyError(messages.LinkUnresolved) } } if location == nil { - return func(a *App) { a.notifyError(messages.LinkUnresolved) } + return func(a *App) { + a.operationRejected("output_link_open", "unresolved") + a.notifyError(messages.LinkUnresolved) + } } path := firstExistingFile([]string{location.Path}) if path == "" { - return func(a *App) { a.notifyError(messages.LinkMissing) } + return func(a *App) { + a.operationRejected("output_link_open", "target_missing") + a.notifyError(messages.LinkMissing) + } } return func(a *App) { a.openFileAtPosition(p, path, zeroBased(location.Line), zeroBased(location.Column)) } }) diff --git a/desktop/internal/workbench/plugin_displace.go b/desktop/internal/workbench/plugin_displace.go index d2887d78b9..f5463e2d7e 100644 --- a/desktop/internal/workbench/plugin_displace.go +++ b/desktop/internal/workbench/plugin_displace.go @@ -56,7 +56,7 @@ func (a *App) stopDisplaced(d displacement) { return } if d.err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_list", d.err)) + a.backgroundFailed("plugin_list", d.err) } p := a.project for _, item := range d.displaced { @@ -66,7 +66,7 @@ func (a *App) stopDisplaced(d displacement) { err := a.plugins.StopDisplaced(ctx, id, server) return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_displace", err)) + a.backgroundFailed("plugin_displace", err) } if a.project != p || p == nil { return diff --git a/desktop/internal/workbench/plugin_log_directory_test.go b/desktop/internal/workbench/plugin_log_directory_test.go new file mode 100644 index 0000000000..d58005eb47 --- /dev/null +++ b/desktop/internal/workbench/plugin_log_directory_test.go @@ -0,0 +1,70 @@ +package workbench + +import ( + "context" + "errors" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/logstore" +) + +// The window asks its log sink for a plugin's ${logDir} by a type assertion, which would +// silently give every plugin process no log directory if the store stopped implementing it. +var _ pluginFileSink = (*logstore.Store)(nil) + +// pluginFilesLog is a log sink that also gives plugin file directories. +type pluginFilesLog struct { + opRecordingLog + directory string + err error + asked []string +} + +func (l *pluginFilesLog) PluginFilesDirectory(_ context.Context, pluginID string) (string, error) { + l.mu.Lock() + defer l.mu.Unlock() + l.asked = append(l.asked, pluginID) + return l.directory, l.err +} + +// TestPluginLogDirectoryComesFromTheLogStore checks that a plugin process's ${logDir} is the +// directory the log store gives for the plugin, that a store that cannot make it leaves the +// process without one and records the failure as background work under the action, and that +// a window without a log store gives none. +func TestPluginLogDirectoryComesFromTheLogStore(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + a := h.app + t.Cleanup(func() { a.logSink = nil }) + ctx := core.WithOrigin(context.Background(), core.Origin{Operation: "op-1", Trigger: "test.action"}) + + log := &pluginFilesLog{directory: "/logs/sessions/s/plugins/io.example.plugin/files"} + a.logSink = log + if got := a.pluginLogDirectory(ctx, "io.example.plugin"); got != log.directory { + t.Fatalf("pluginLogDirectory = %q, want %q", got, log.directory) + } + if len(log.asked) != 1 || log.asked[0] != "io.example.plugin" { + t.Fatalf("the store was asked for %q, want the plugin's own directory", log.asked) + } + if got := log.ops(backgroundFailedEvent); len(got) != 0 { + t.Fatalf("a directory the store made recorded a failure under %q", got) + } + + failing := &pluginFilesLog{err: errors.New("disk full")} + a.logSink = failing + if got := a.pluginLogDirectory(ctx, "io.example.plugin"); got != "" { + t.Fatalf("pluginLogDirectory = %q after the store failed, want none", got) + } + if got := failing.ops(backgroundFailedEvent); len(got) != 1 || got[0] != "op-1" { + t.Fatalf("the failure was recorded under %q, want once under op-1", got) + } + + a.logSink = &opRecordingLog{} + if got := a.pluginLogDirectory(ctx, "io.example.plugin"); got != "" { + t.Fatalf("pluginLogDirectory = %q from a sink that gives no plugin directories", got) + } + a.logSink = nil + if got := a.pluginLogDirectory(ctx, "io.example.plugin"); got != "" { + t.Fatalf("pluginLogDirectory = %q without a log store", got) + } +} diff --git a/desktop/internal/workbench/plugin_native.go b/desktop/internal/workbench/plugin_native.go index 4dac3248fb..6a43b648d4 100644 --- a/desktop/internal/workbench/plugin_native.go +++ b/desktop/internal/workbench/plugin_native.go @@ -676,7 +676,7 @@ func (a *App) runNativeAction(p *project, tool *pluginservice.ToolWindow, state return func(a *App) { state.busy = false if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_native_action", err)) + a.operationFailed("plugin_native_action", err) a.notifyError(i18n.Shared(a.language(), "desktop.nativePanel.failed")) return } @@ -723,7 +723,7 @@ func (a *App) loadNativeSource(p *project, tool *pluginservice.ToolWindow, state state.sourceBusy = false state.sourceLoaded = true if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_native_source", err)) + a.operationFailed("plugin_native_source", err) state.nodes = nil state.sourceFailure = i18n.Shared(a.language(), "desktop.nativePanel.sourceFailed") return diff --git a/desktop/internal/workbench/plugin_native_state.go b/desktop/internal/workbench/plugin_native_state.go index 1a10963e6f..e39a6b070d 100644 --- a/desktop/internal/workbench/plugin_native_state.go +++ b/desktop/internal/workbench/plugin_native_state.go @@ -37,7 +37,7 @@ type savedNativeProject struct { func (a *App) restoreNativePanels(p *project) { all := map[string]savedNativeProject{} if found, err := a.store.Load(nativePanelsFile, &all); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_native_state_load", documentLogError(err))) + a.backgroundFailed("plugin_native_state_load", documentLogError(err)) return } else if !found { return @@ -52,7 +52,7 @@ func (a *App) restoreNativePanels(p *project) { func (a *App) saveNativePanels(p *project) { all := map[string]savedNativeProject{} if _, err := a.store.Load(nativePanelsFile, &all); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_native_state_load", documentLogError(err))) + a.backgroundFailed("plugin_native_state_load", documentLogError(err)) all = map[string]savedNativeProject{} } panels := map[string]savedNativePanel{} @@ -83,7 +83,7 @@ func (a *App) saveNativePanels(p *project) { } } if err := a.store.Save(nativePanelsFile, all); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_native_state_save", documentLogError(err))) + a.backgroundFailed("plugin_native_state_save", documentLogError(err)) } } diff --git a/desktop/internal/workbench/plugin_operation_record_test.go b/desktop/internal/workbench/plugin_operation_record_test.go new file mode 100644 index 0000000000..f3c2508813 --- /dev/null +++ b/desktop/internal/workbench/plugin_operation_record_test.go @@ -0,0 +1,75 @@ +package workbench + +import ( + "context" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" +) + +// pluginOperationWait bounds the wait for a recorded result. The paths that record run real +// processes and real Core requests, so it is generous; a result that arrives returns at once. +const pluginOperationWait = 30 * time.Second + +// recordedPluginOperation is one result the host sent Core, with Core's answer. +type recordedPluginOperation struct { + operation core.PluginOperation + err error +} + +// recordingPluginKernel is the real plugin kernel that also hands each recorded result to the +// test, so a test sees what the host recorded and that Core took it. +type recordingPluginKernel struct { + pluginservice.Kernel + recorded chan recordedPluginOperation +} + +func newRecordingPluginKernel() *recordingPluginKernel { + return &recordingPluginKernel{Kernel: &testKernel{Client: core.NewClient()}, recorded: make(chan recordedPluginOperation, 16)} +} + +func (k *recordingPluginKernel) RecordPluginOperation(ctx context.Context, operation core.PluginOperation) error { + err := k.Kernel.RecordPluginOperation(ctx, operation) + k.recorded <- recordedPluginOperation{operation: operation, err: err} + return err +} + +// next is the next recorded result, which Core must have taken. +func (k *recordingPluginKernel) next(t *testing.T, what string) core.PluginOperation { + t.Helper() + select { + case recorded := <-k.recorded: + if recorded.err != nil { + t.Fatalf("Core refused %+v: %v", recorded.operation, recorded.err) + } + return recorded.operation + case <-time.After(pluginOperationWait): + t.Fatalf("no result was recorded for %s", what) + } + return core.PluginOperation{} +} + +// none fails when anything was recorded. A caller first waits for every path that could record. +func (k *recordingPluginKernel) none(t *testing.T) { + t.Helper() + select { + case recorded := <-k.recorded: + t.Fatalf("recorded %+v, want nothing", recorded.operation) + default: + } +} + +// wantPluginOperation checks a recorded result against the rest of want, after checking that +// its duration is a monotonic one, which no test can predict. +func wantPluginOperation(t *testing.T, got, want core.PluginOperation) { + t.Helper() + if got.DurationMs < 0 { + t.Fatalf("duration = %d, want a monotonic duration", got.DurationMs) + } + got.DurationMs = 0 + if got != want { + t.Fatalf("recorded %+v, want %+v", got, want) + } +} diff --git a/desktop/internal/workbench/pluginbackends.go b/desktop/internal/workbench/pluginbackends.go index 2c81be1718..a23a06d6b6 100644 --- a/desktop/internal/workbench/pluginbackends.go +++ b/desktop/internal/workbench/pluginbackends.go @@ -181,14 +181,14 @@ func (a *App) finishPluginServerStart(p *project, languageID string, session *pl delete(a.pluginServerStarting, languageID) a.pluginServerMu.Unlock() if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_server_start", err)) + a.operationFailed("plugin_server_start", err) return } if session == nil { return } if session.Warnings != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_server_selection", session.Warnings)) + a.backgroundFailed("plugin_server_selection", session.Warnings) } if a.plugins == nil { a.stopPluginSession(session) @@ -277,7 +277,7 @@ func (a *App) servePluginServer(server *pluginServer, ctx context.Context) { } if serveErr := a.plugins.ServeLanguageSession(ctx, server.session, observe); serveErr != nil && ctx.Err() == nil { a.post(func(a *App) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_server", serveErr)) + a.operationFailed("plugin_server", serveErr) }) } // A server that exits on its own, crashes, or ends after a stop must not @@ -371,7 +371,7 @@ func (a *App) activatePluginWorkspace(root string) { } return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_backend_start", err)) + a.operationFailed("plugin_backend_start", err) } } }) @@ -434,7 +434,7 @@ func (a *App) stopPluginSession(session *pluginservice.LanguageSession) { err := a.plugins.StopLanguageServer(ctx, session) return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_server_stop", err)) + a.backgroundFailed("plugin_server_stop", err) } } }) diff --git a/desktop/internal/workbench/plugincontent.go b/desktop/internal/workbench/plugincontent.go index 105ec24e5e..931823384c 100644 --- a/desktop/internal/workbench/plugincontent.go +++ b/desktop/internal/workbench/plugincontent.go @@ -94,7 +94,7 @@ func (a *App) openContentTarget(p *project, uri string, line, column int) { if err == nil || errors.Is(err, context.Canceled) { return } - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_content", err)) + a.operationFailed("plugin_content", err) a.notifyError(i18n.SharedFormat(a.language(), "desktop.pluginHost.contentFailed", map[string]string{"uri": uri})) } }) diff --git a/desktop/internal/workbench/plugindiagnostics.go b/desktop/internal/workbench/plugindiagnostics.go index cf6b3cc61e..d671a9ee49 100644 --- a/desktop/internal/workbench/plugindiagnostics.go +++ b/desktop/internal/workbench/plugindiagnostics.go @@ -68,7 +68,7 @@ func (a *App) applyPluginDiagnostics(pluginID string, event core.PluginDiagnosti records := pluginservice.DiagnosticsFromEvent(event, resolve) set := a.pluginDiagnosticSet(pluginID) if err := set.Replace(fileKey, records); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_diagnostics", err)) + a.backgroundFailed("plugin_diagnostics", err) return } a.refreshDocumentMarkers(fileKey) @@ -218,7 +218,7 @@ func (a *App) pluginDocumentResolver() pluginservice.Resolver { if err != nil { // log-exempt: 用户取消:关闭工作区后迟到的诊断不再需要归属。 if !errors.Is(err, context.Canceled) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_diagnostic_identity", err)) + a.backgroundFailed("plugin_diagnostic_identity", err) } identity = nil } diff --git a/desktop/internal/workbench/pluginedits.go b/desktop/internal/workbench/pluginedits.go index 9f7765c7a1..02f6b97225 100644 --- a/desktop/internal/workbench/pluginedits.go +++ b/desktop/internal/workbench/pluginedits.go @@ -134,12 +134,13 @@ func (a *App) startPluginFormattingAtSelection(p *project, d *document) { // semanticOperationFailed tells the user a document-changing request failed; // the stable error code is already in the log. func (a *App) semanticOperationFailed(kind semanticKind) { - switch kind { - case pluginSemanticFormatting, pluginSemanticRangeFormatting, pluginSemanticRename: - a.notifyError(i18n.Shared(a.language(), "desktop.semantics.operationFailed")) - if kind == pluginSemanticRename { - a.renameAborted() - } + if !kind.toldToUser() { + return + } + // The callers record the failure (plugin_semantics); this only tells the user. + a.notifyError(i18n.Shared(a.language(), "desktop.semantics.operationFailed")) + if kind == pluginSemanticRename { + a.renameAborted() } } @@ -150,7 +151,7 @@ func (a *App) applySemanticFormatting(pending *semanticPending, event core.Backe } edits, err := core.PluginSemanticTextEdits(event) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_format", err)) + a.operationFailed("plugin_format", err) a.notifyError(i18n.Shared(a.language(), "desktop.semantics.formatFailed")) return } @@ -178,7 +179,7 @@ func (a *App) applyEditsToDocument(p *project, d *document, edits []core.PluginT return func(a *App) { current, document := a.currentSemanticDocument(documentID) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields(operation, err)) + a.operationFailed(operation, err) a.notifyError(i18n.Shared(a.language(), "desktop.semantics.formatFailed")) return } diff --git a/desktop/internal/workbench/pluginpages.go b/desktop/internal/workbench/pluginpages.go index aa19037838..12d1435dbc 100644 --- a/desktop/internal/workbench/pluginpages.go +++ b/desktop/internal/workbench/pluginpages.go @@ -95,7 +95,7 @@ func (a *App) pluginPage(it item, p *project) *pluginPage { a.pluginPages[it.id] = page if err := a.openPluginPage(page); err != nil { page.failure = err.Error() - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_web_open", err)) + a.operationFailed("plugin_web_open", err) } return page } @@ -106,7 +106,7 @@ func (a *App) openPluginPage(page *pluginPage) error { return errors.ErrUnsupported } host := &pluginPageHost{a: a, plugins: a.plugins, tool: page.tool, project: page.project, language: a.language()} - ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) defer cancel() opened, err := pluginweb.Open(ctx, pluginweb.Config{ Kernel: kernel, @@ -119,7 +119,7 @@ func (a *App) openPluginPage(page *pluginPage) error { Post: func(fn func()) { a.post(func(*App) { fn() }) }, Log: func(stage string, err error) { a.post(func(a *App) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_web_"+stage, err)) + a.backgroundFailed("plugin_web_"+stage, err) }) }, }) diff --git a/desktop/internal/workbench/pluginrename.go b/desktop/internal/workbench/pluginrename.go index ff14a0a8c3..59f3569633 100644 --- a/desktop/internal/workbench/pluginrename.go +++ b/desktop/internal/workbench/pluginrename.go @@ -170,7 +170,7 @@ func (a *App) applySemanticRename(pending *semanticPending, event core.BackendEv changes, err := core.PluginSemanticWorkspaceChanges(event) a.closePluginRename() if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_rename", err)) + a.operationFailed("plugin_rename", err) a.notifyError(i18n.Shared(a.language(), "desktop.semantics.operationFailed")) return } @@ -213,7 +213,7 @@ func (a *App) applyWorkspaceChanges(p *project, changes map[string][]core.Plugin if errors.Is(err, errRenameRejected) { a.notifyError(i18n.Shared(a.language(), "desktop.semantics.renameRejected")) } else { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_rename", err)) + a.operationFailed("plugin_rename", err) a.notifyError(i18n.Shared(a.language(), "desktop.semantics.renameFailed")) } return @@ -226,6 +226,7 @@ func (a *App) applyWorkspaceChanges(p *project, changes map[string][]core.Plugin } } if stale > 0 { + a.operationFailed("plugin_rename_apply", fmt.Errorf("%d of %d open documents changed before the rename reached them", stale, len(updates))) a.notifyError(i18n.Shared(a.language(), "desktop.semantics.renamePartial")) return } diff --git a/desktop/internal/workbench/plugins.go b/desktop/internal/workbench/plugins.go index 1ed4fc4639..7043a876c7 100644 --- a/desktop/internal/workbench/plugins.go +++ b/desktop/internal/workbench/plugins.go @@ -14,7 +14,6 @@ import ( "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" - "github.com/1lck/Lithe-IDEA/desktop/internal/logwindow" "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" "github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginmanager" @@ -45,7 +44,7 @@ func (a *App) refreshPluginState() { return func(a *App) { a.pluginFacts.Store(&facts) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_list", err)) + a.backgroundFailed("plugin_list", err) if entries == nil { return } @@ -86,7 +85,7 @@ func (a *App) installPlugin(plugin core.MarketplacePlugin, feedback settingswind return plugininstall.Plan{}, err } defer func() { - a.recordPluginInstallCleanup(archive.Discard()) + a.recordPluginInstallCleanup(ctx, archive.Discard()) }() if feedback.Preparing != nil { feedback.Preparing() @@ -100,7 +99,7 @@ func (a *App) installPlugin(plugin core.MarketplacePlugin, feedback settingswind ExpectedVersion: availability.Version, }) if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) { - a.recordPluginInstallCleanup(downloads.Forget(archive)) + a.recordPluginInstallCleanup(ctx, downloads.Forget(archive)) } return plan, err }) @@ -110,8 +109,8 @@ func (a *App) closePluginDownloads() { downloads := a.pluginDownloads a.pluginDownloads = nil if downloads != nil { - a.background(nil, 0, func(context.Context) func(*App) { - a.recordPluginInstallCleanup(downloads.Close()) + a.background(nil, 0, func(ctx context.Context) func(*App) { + a.recordPluginInstallCleanup(ctx, downloads.Close()) return nil }) } @@ -131,7 +130,7 @@ func (a *App) installPluginFromFile(path string, feedback settingswindow.PluginI func (a *App) preparePluginInstall(feedback settingswindow.PluginInstallFeedback, prepare func(context.Context) (plugininstall.Plan, error)) { if a.plugins == nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_install", errors.New("plugin service unavailable"))) + a.operationFailed("plugin_install", errors.New("plugin service unavailable")) if feedback.Failure != nil { feedback.Failure(errors.New("plugin service unavailable")) } @@ -140,8 +139,11 @@ func (a *App) preparePluginInstall(feedback settingswindow.PluginInstallFeedback } // Register the worker on the workbench thread so application shutdown waits // for cancelled downloads and unapproved packages to be cleaned up. - a.background(nil, 0, func(context.Context) func(*App) { - ctx, cancel := context.WithTimeout(feedback.Context, pluginDownloadTimeout) + a.background(nil, 0, func(work context.Context) func(*App) { + // The review window's context ends the install; the install still belongs to the + // action that started it, so its records and Core requests carry its op. + origin := core.OriginOf(work) + ctx, cancel := context.WithTimeout(core.WithOrigin(feedback.Context, origin), pluginDownloadTimeout) plan, err := prepare(ctx) cancel() if err != nil { @@ -150,7 +152,7 @@ func (a *App) preparePluginInstall(feedback settingswindow.PluginInstallFeedback if cancelled && errors.Is(err, context.Canceled) { return nil } - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_install", err)) + a.operationFailedIn(work, "plugin_install", err) if !cancelled { if feedback.Failure != nil { feedback.Failure(err) @@ -162,20 +164,22 @@ func (a *App) preparePluginInstall(feedback settingswindow.PluginInstallFeedback // The worker holds staging until the originating window accepts the // verified package; a cancelled window discards it before installation. if !feedback.Review(plan.Version, plan.Review, plan.Decision.Reuse) { - a.recordPluginInstallCleanup(a.plugins.Installer.Discard(plan)) + a.recordPluginInstallCleanup(work, a.plugins.Installer.Discard(plan)) return nil } - commitCtx, cancelCommit := context.WithTimeout(context.Background(), pluginInstallTimeout) + commitCtx, cancelCommit := context.WithTimeout(core.WithOrigin(context.Background(), origin), pluginInstallTimeout) defer cancelCommit() return a.commitPluginInstall(commitCtx, plan, feedback) }) } -func (a *App) recordPluginInstallCleanup(err error) { +// recordPluginInstallCleanup records a download or staging package the install could not +// remove, under the action ctx belongs to. It is safe from any goroutine. +func (a *App) recordPluginInstallCleanup(ctx context.Context, err error) { if err != nil { - fields := logwindow.ErrorFields(err) + fields := core.LogErrorFields(err) fields["stage"] = "plugin_install_cleanup" - a.emit(core.LevelWarn, "app.storage.maintenance_failed", fields) + a.emitIn(ctx, core.LevelWarn, "app.storage.maintenance_failed", fields) } } @@ -194,12 +198,12 @@ func (a *App) commitPluginInstall(ctx context.Context, plan plugininstall.Plan, displaced = a.describeDisplacement(ctx, plan.ID, outcome.Displaced) } if err != nil && approval == nil { - a.recordPluginInstallCleanup(a.plugins.Installer.Discard(plan)) + a.recordPluginInstallCleanup(ctx, a.plugins.Installer.Discard(plan)) } return func(a *App) { installed := err == nil if enableErr != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_enable", enableErr)) + a.operationFailed("plugin_enable", enableErr) } if err != nil { if approval != nil { @@ -207,9 +211,9 @@ func (a *App) commitPluginInstall(ctx context.Context, plan plugininstall.Plan, // The package is on disk; only its approval record failed, so the // user is not told the installation failed. The next installation // of the same version asks again. - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_approval", err)) + a.operationFailed("plugin_approval", err) } else { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_commit", err)) + a.operationFailed("plugin_commit", err) } } if installed && plan.ID != "" { @@ -253,7 +257,7 @@ func (a *App) setPluginEnabled(id string, enabled bool) { } return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_enable", err)) + a.operationFailed("plugin_enable", err) } if enabled { // An enable clears the tombstone a disable left for an in-flight start. @@ -287,7 +291,7 @@ func (a *App) uninstallPlugin(id string) { err := a.plugins.Uninstall(ctx, id, nil, stop) return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_uninstall", err)) + a.operationFailed("plugin_uninstall", err) } for _, tab := range a.everyTab() { if err == nil { @@ -313,7 +317,7 @@ func (a *App) reloadPluginLanguages() { entries, err := a.plugins.Manager.Installed() if err != nil { return func(a *App) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_languages", err)) + a.backgroundFailed("plugin_languages", err) } } languages, loadErr := a.plugins.LoadLanguages(ctx, entries) @@ -322,24 +326,23 @@ func (a *App) reloadPluginLanguages() { vcsPlugins, vcsErr := a.plugins.VcsPlugins(ctx, entries) return func(a *App) { if commandsErr != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_tool_commands", commandsErr)) + a.backgroundFailed("plugin_tool_commands", commandsErr) } a.pluginCommands = commands shortcuts.SetPluginActions(pluginCommandActions(commands)) if loadErr != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_languages", loadErr)) + a.backgroundFailed("plugin_languages", loadErr) } if windowsErr != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_tool_windows", windowsErr)) + a.backgroundFailed("plugin_tool_windows", windowsErr) } if vcsErr != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_vcs_providers", vcsErr)) + a.backgroundFailed("plugin_vcs_providers", vcsErr) } a.setPluginTools(windows, vcsWindows(vcsPlugins)) failed, _ := a.syntaxRegistry().SetPluginLanguages(languages) if len(failed) > 0 { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_languages", - fmt.Errorf("%d plugin languages were rejected", len(failed)))) + a.backgroundFailed("plugin_languages", fmt.Errorf("%d plugin languages were rejected", len(failed))) } } }) diff --git a/desktop/internal/workbench/plugins_test.go b/desktop/internal/workbench/plugins_test.go index 3ac7c36b3a..815fbcd425 100644 --- a/desktop/internal/workbench/plugins_test.go +++ b/desktop/internal/workbench/plugins_test.go @@ -335,7 +335,7 @@ func TestUninstallStopsProviderSessionsBeforeDeletingFiles(t *testing.T) { }) } else if err == nil { started, err = runtime.session(ctx, h.app.plugins.Backend, h.app.plugins.Root, root, uri, - vcsWindow{PluginID: id, Version: "1.0.0", Directory: directory, Manifest: json.RawMessage(manifest), Vcs: "fakevcs"}, core.PluginSettingsState{}) + vcsWindow{PluginID: id, Version: "1.0.0", Directory: directory, Manifest: json.RawMessage(manifest), Vcs: "fakevcs"}, core.PluginSettingsState{}, h.app.pluginLogDirectory) } return func(*App) { if err != nil { @@ -378,7 +378,7 @@ func TestUninstallStopsProviderSessionsBeforeDeletingFiles(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() _, err := p.vcs.runtime().session(ctx, h.app.plugins.Backend, h.app.plugins.Root, root, "", - vcsWindow{PluginID: id, Version: "1.0.0"}, core.PluginSettingsState{}) + vcsWindow{PluginID: id, Version: "1.0.0"}, core.PluginSettingsState{}, h.app.pluginLogDirectory) if !errors.Is(err, buildprovider.ErrClosed) { t.Fatalf("catalog refresh reopened a removed plugin: %v", err) } @@ -495,7 +495,7 @@ func TestEnableReopensVcsAfterCatalogRefresh(t *testing.T) { uri, err := h.app.kernel.PluginDocumentURI(ctx, root, "auto") if err == nil { _, err = sessions.session(ctx, h.app.plugins.Backend, h.app.plugins.Root, root, uri, - vcsWindow{PluginID: id, Version: "1.0.0", Directory: filepath.Join(h.app.plugins.Root, id, "1.0.0"), Manifest: json.RawMessage(vcsFixtureManifest), Vcs: "fakevcs"}, core.PluginSettingsState{}) + vcsWindow{PluginID: id, Version: "1.0.0", Directory: filepath.Join(h.app.plugins.Root, id, "1.0.0"), Manifest: json.RawMessage(vcsFixtureManifest), Vcs: "fakevcs"}, core.PluginSettingsState{}, h.app.pluginLogDirectory) } return func(*App) { if err != nil { diff --git a/desktop/internal/workbench/pluginsemantics.go b/desktop/internal/workbench/pluginsemantics.go index fac8be11ff..4bfcf35195 100644 --- a/desktop/internal/workbench/pluginsemantics.go +++ b/desktop/internal/workbench/pluginsemantics.go @@ -138,8 +138,10 @@ type semanticPending struct { // fromPointer marks a hover started by pointer movement; its anchor is the // row under the pointer rather than the caret cell. fromPointer bool - anchor gfx.Rect - operation string + // automatic marks a completion the editor asked for while the user typed. + automatic bool + anchor gfx.Rect + operation string // join is set on the language-server side of an explicit completion that also asks a // plugin completion provider; the answer feeds the join instead of opening the popup. join *completionMergeJoin @@ -637,7 +639,7 @@ func (a *App) startProviderHover(p *project, d *document, line, column int, anch return } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_provider", err)) + a.backgroundFailed("plugin_provider", err) return } if contents == "" { @@ -692,6 +694,7 @@ func (a *App) requestPluginCompletion(p *project, d *document, line, column int, position := core.PluginDocumentPosition{Line: line, UTF16Column: column} a.cancelSemanticKind(pluginSemanticCompletion) pending := a.newSemanticPending(pluginSemanticCompletion, p, d, server, line, column, true, false) + pending.automatic = automatic if join := a.newCompletionMergeJoin(p, d, line, column, automatic); join != nil { pending.join = join a.startProviderCompletionFor(p, d, line, column, join) @@ -847,8 +850,13 @@ func (a *App) newSemanticPending(kind semanticKind, p *project, d *document, ser } } +// submitSemantic sends one request to the language server. A request the user asked for is an +// action of its own; a hover under the moving pointer and a completion while typing are the +// editor's, and stay part of whatever action is current. func (a *App) submitSemantic(pending *semanticPending, request core.PluginSemanticRequest) { - a.performed("editor.semantics."+string(pending.kind), surfaceShortcut) + if !pending.fromPointer && !pending.automatic { + a.performed("editor.semantics."+string(pending.kind), surfaceShortcut) + } a.background(pending.project, semanticStartTimeout, func(ctx context.Context) func(*App) { operation, err := a.plugins.RequestLanguageSession(ctx, pending.server.session, request) return func(a *App) { a.semanticRequestStarted(pending, operation, err, ctx.Err()) } @@ -872,7 +880,14 @@ func (a *App) semanticRequestStarted(pending *semanticPending, operation string, if errors.Is(err, context.Canceled) || errors.Is(ctxErr, context.Canceled) { return } - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_semantics", err)) + // A request the server never received fails like one it refused: formatting and rename + // tell the user, the others go without. + if pending.kind.toldToUser() { + a.operationFailed("plugin_semantics", err) + a.semanticOperationFailed(pending.kind) + } else { + a.backgroundFailed("plugin_semantics", err) + } } } @@ -941,7 +956,7 @@ func (a *App) applySemanticDefinition(pending *semanticPending, event core.Backe } locations, err := core.PluginSemanticLocations(event) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_semantics", err)) + a.backgroundFailed("plugin_semantics", err) return } if pending.usages { @@ -984,7 +999,7 @@ func (a *App) gestureOnDeclaration(d *document, line, column int, targets []core position := core.PluginDocumentPosition{Line: line, UTF16Column: column} usages, err := kernel.DeclarationOrUsages(ctx, d.sync.uri, position, targets) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_declaration_or_usages", err)) + a.backgroundFailed("editor_declaration_or_usages", err) return false } return usages @@ -1016,7 +1031,7 @@ func (a *App) mergeProviderDefinitions(p *project, d *document, pending *semanti return } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_provider", err)) + a.backgroundFailed("plugin_provider", err) merged = server } a.presentDefinitionOrUsages(p, d, line, column, requireCaret, a.usableDefinitionTargets(merged, maxDefinitionTargets), len(merged), revision) @@ -1033,6 +1048,7 @@ func (a *App) presentDefinitionTargets(p *project, d *document, kind semanticKin case answered > 0: // Every target is outside the file system (a class in a jar): // say so instead of looking like an empty answer. + a.operationRejected("plugin_navigation", "target_outside_file_system") a.notifyError(i18n.Shared(a.language(), "desktop.semantics.targetUnavailable")) case references: a.notifyInfo(i18n.Shared(a.language(), "desktop.semantics.noReferences")) @@ -1081,7 +1097,7 @@ func (a *App) startProviderDefinition(p *project, d *document, line, column int) return } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_provider", err)) + a.backgroundFailed("plugin_provider", err) return } targets := a.usableDefinitionTargets(locations, maxDefinitionTargets) @@ -1098,7 +1114,7 @@ func (a *App) applySemanticHover(pending *semanticPending, event core.BackendEve } hover, err := core.PluginSemanticHoverFromEvent(event) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_semantics", err)) + a.backgroundFailed("plugin_semantics", err) return } if hover == nil || hover.Contents == "" { @@ -1120,7 +1136,7 @@ func (a *App) applySemanticCompletion(pending *semanticPending, event core.Backe } items, incomplete, err := core.PluginSemanticCompletions(event) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_semantics", err)) + a.backgroundFailed("plugin_semantics", err) return } if len(items) > maxCompletionItems { @@ -1163,7 +1179,7 @@ func (a *App) startProviderCompletionFor(p *project, d *document, line, column i return } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_provider", err)) + a.backgroundFailed("plugin_provider", err) a.settleMergeSide(join, false, nil, false) return } @@ -1282,7 +1298,7 @@ func (a *App) acceptPluginCompletion(index int) { return func(a *App) { current, document := a.currentSemanticDocument(documentID) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_completion_apply", err)) + a.operationFailed("plugin_completion_apply", err) a.notifyError(i18n.Shared(a.language(), "desktop.semantics.completionFailed")) return } @@ -1668,9 +1684,7 @@ func (a *App) removePending(pending *semanticPending) bool { // logSemanticError records that the language server failed a request, with the error's stable // code and never its message, which can quote the user's code. The code is the JSON-RPC -// number or the plugin's token; anything else is recorded as unknown. Formatting and rename -// tell the user (semanticOperationFailed), so they are notification failures; the other -// requests fail quietly and are background failures. +// number or the plugin's token; anything else is recorded as unknown. func (a *App) logSemanticError(kind semanticKind, raw json.RawMessage) { var failure struct { Code json.RawMessage `json:"code"` @@ -1692,14 +1706,24 @@ func (a *App) logSemanticError(kind semanticKind, raw json.RawMessage) { "error_code": code, "error_domain": "lsp", } - switch kind { - case pluginSemanticFormatting, pluginSemanticRangeFormatting, pluginSemanticRename: + if kind.toldToUser() { a.emit(operationFailedLevel, operationFailedEvent, fields) - default: + } else { a.emit(backgroundFailedLevel, backgroundFailedEvent, fields) } } +// toldToUser says a failed request of this kind is told to the user (semanticOperationFailed), +// so it is a notification failure. The other requests fail quietly: the editor goes without the +// hover, completion or location, and the failure is a background one. +func (k semanticKind) toldToUser() bool { + switch k { + case pluginSemanticFormatting, pluginSemanticRangeFormatting, pluginSemanticRename: + return true + } + return false +} + // logToken is the catalog's token type: what a token field accepts. var logToken = regexp.MustCompile(`^[A-Za-z0-9._:/$-]{1,64}$`) diff --git a/desktop/internal/workbench/pluginsemantics_hover.go b/desktop/internal/workbench/pluginsemantics_hover.go index 38bd9b4462..0f076dc64c 100644 --- a/desktop/internal/workbench/pluginsemantics_hover.go +++ b/desktop/internal/workbench/pluginsemantics_hover.go @@ -486,7 +486,7 @@ func (a *App) followHoverLink(destination string) { err = openURL(target.URL) } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_semantics", err)) + a.operationFailed("plugin_semantics", err) return } a.closeSemanticHover() diff --git a/desktop/internal/workbench/pluginsync.go b/desktop/internal/workbench/pluginsync.go index 5bc4c502d1..1eeebbb8c1 100644 --- a/desktop/internal/workbench/pluginsync.go +++ b/desktop/internal/workbench/pluginsync.go @@ -244,7 +244,7 @@ func (a *App) reportDocumentSyncFailure(event string, ctxErr, err error) { if errors.Is(err, context.Canceled) || errors.Is(ctxErr, context.Canceled) { return } - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields(event, err)) + a.backgroundFailed(event, err) } // openDocumentsForPlugin opens every document of languageID in a newly started diff --git a/desktop/internal/workbench/plugintools.go b/desktop/internal/workbench/plugintools.go index 017681284a..10173e9d7c 100644 --- a/desktop/internal/workbench/plugintools.go +++ b/desktop/internal/workbench/plugintools.go @@ -149,10 +149,11 @@ func (a *App) setPluginTools(windows []pluginservice.ToolWindow, vcs []vcsWindow a.drag = dragState{} a.chrome.setItems(items) a.closeStalePluginPages() - ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) defer cancel() layout, _, err := a.kernel.ReduceChromeLayout(ctx, a.chrome.coreItems, restated, core.NormalizeChrome()) if err != nil { + a.operationFailed("chrome_layout_reduce", err) a.notifyError(a.text.Errors.Core(err.Error())) layout = a.chrome.layout } diff --git a/desktop/internal/workbench/preview_pages.go b/desktop/internal/workbench/preview_pages.go index 71585a3844..3ab458b124 100644 --- a/desktop/internal/workbench/preview_pages.go +++ b/desktop/internal/workbench/preview_pages.go @@ -103,7 +103,7 @@ func (a *App) openPreviewPage(config webpreview.Config, alive func() bool) *prev config.Host = &a.web config.Log = func(stage string, err error) { a.post(func(a *App) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("web_preview_"+stage, err)) + a.backgroundFailed("web_preview_"+stage, err) }) } open := a.previews.open @@ -117,7 +117,7 @@ func (a *App) openPreviewPage(config webpreview.Config, alive func() bool) *prev } else { a.previews.failed = true } - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("web_preview_open", err)) + a.operationFailed("web_preview_open", err) return nil } entry := &previewPage{view: view, shown: a.previews.frame, alive: alive} diff --git a/desktop/internal/workbench/problems.go b/desktop/internal/workbench/problems.go index a622e1a394..38c351b5b1 100644 --- a/desktop/internal/workbench/problems.go +++ b/desktop/internal/workbench/problems.go @@ -160,7 +160,7 @@ func (a *App) applyProblemsQuery(p *project, generation uint64, diagnostics []co v.loaded = true v.queried = generation if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_problems_query", err)) + a.operationFailed("plugin_problems_query", err) v.failure = err v.diagnostics, v.result, v.starts, v.rows = nil, core.ProblemsResult{}, nil, 0 a.invalidator.Invalidate() diff --git a/desktop/internal/workbench/process_exit.go b/desktop/internal/workbench/process_exit.go index 862783be7a..66384b2fc6 100644 --- a/desktop/internal/workbench/process_exit.go +++ b/desktop/internal/workbench/process_exit.go @@ -154,7 +154,7 @@ func (a *App) confirmProcessExit(p *project, lifecycleContext string, proceed fu } return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("process_exit_plan", err)) + a.backgroundFailed("process_exit_plan", err) proceed() return } @@ -201,7 +201,7 @@ func (a *App) requestCloseTerminal(p *project, id int) { names, err := a.confirmationNames(ctx, exitContextCloseTerminal, settings, terminalRecords(terminals)) return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("terminal_close_plan", err)) + a.backgroundFailed("terminal_close_plan", err) } if err != nil || len(names) == 0 { a.closeTerminal(p, id) @@ -256,7 +256,7 @@ func (a *App) refreshStopGrace() { return } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("process_stop_grace", err)) + a.backgroundFailed("process_stop_grace", err) return } buildprocess.SetStopGrace(time.Duration(plan.GracefulStopMilliseconds) * time.Millisecond) diff --git a/desktop/internal/workbench/project_open_destination.go b/desktop/internal/workbench/project_open_destination.go index 5718b13a45..affd5ffde6 100644 --- a/desktop/internal/workbench/project_open_destination.go +++ b/desktop/internal/workbench/project_open_destination.go @@ -101,6 +101,7 @@ func (a *App) askProjectOpenDestination(path string) { // own project. func (a *App) openProjectInNewWindow(path string) { if err := launchClient(path); err != nil { + a.operationFailed("project_open_new_window", documentLogError(err)) a.notifyError(i18n.SharedFormat(a.language(), "desktop.projectOpen.newWindowFailed", map[string]string{"reason": treeErrorReason(err)})) } } diff --git a/desktop/internal/workbench/recent_branch.go b/desktop/internal/workbench/recent_branch.go index 18b56b1557..0419324da9 100644 --- a/desktop/internal/workbench/recent_branch.go +++ b/desktop/internal/workbench/recent_branch.go @@ -54,7 +54,7 @@ func (a *App) collectWelcomeBranches(c ui.C) { if read, err, ok := w.branchesFx.take(); ok && err == nil { w.branches = read.branches for _, failure := range read.failures { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_recent_branch", documentLogError(failure))) + a.backgroundFailed("workspace_recent_branch", documentLogError(failure)) } } } diff --git a/desktop/internal/workbench/recent_files.go b/desktop/internal/workbench/recent_files.go index 254f1d6b85..777340333f 100644 --- a/desktop/internal/workbench/recent_files.go +++ b/desktop/internal/workbench/recent_files.go @@ -60,7 +60,7 @@ func (a *App) markRecentlyEdited(p *project, d *document) { } } func (a *App) recentFailed(err error) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_recent", documentLogError(err))) + a.operationFailed("editor_recent", documentLogError(err)) a.notifyError(i18n.Shared(a.language(), "desktop.recentFiles.failed")) } func (a *App) openRecentFiles(edited bool) { diff --git a/desktop/internal/workbench/root.go b/desktop/internal/workbench/root.go index 22923f0ebf..91118e2acc 100644 --- a/desktop/internal/workbench/root.go +++ b/desktop/internal/workbench/root.go @@ -108,7 +108,7 @@ func (a *App) sessionConfig() app.Config { paint(canvas, size) a.endPaint() } - return config + return a.operating(config) } // beginPaint settles the look of the paint about to be declared and forgets what the last @@ -150,6 +150,7 @@ func (a *App) page(c ui.C) { a.noteEditorFocus(c.Canvas().Focused()) a.overlays(c) ui.Toasts(c, &a.overlay.toaster) + a.notificationActed(c) }) } diff --git a/desktop/internal/workbench/runconfig.go b/desktop/internal/workbench/runconfig.go index 9104984ef9..20b3f51bf6 100644 --- a/desktop/internal/workbench/runconfig.go +++ b/desktop/internal/workbench/runconfig.go @@ -172,6 +172,7 @@ func (a *App) startRunConfiguration(p *project, id string) (*buildOperation, err } index := p.buildInstanceIndex(reference) if index < 0 || !p.build.instances[index].modelLoaded { + a.operationRejected("run_configuration", "target_missing") a.notifyError(a.text.Build.TargetMissing) return nil, refuseBuild(refusalNotReady, a.text.Build.TargetMissing) } diff --git a/desktop/internal/workbench/runconfig_browser.go b/desktop/internal/workbench/runconfig_browser.go index 8b7740f34d..808a4ba0d9 100644 --- a/desktop/internal/workbench/runconfig_browser.go +++ b/desktop/internal/workbench/runconfig_browser.go @@ -249,7 +249,7 @@ func (a *App) loadRunConfigPins(p *project) { } all := map[string][]string{} if _, err := a.store.Load(runConfigPinsFile, &all); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("run_configuration_pins_load", documentLogError(err))) + a.operationFailed("run_configuration_pins_load", documentLogError(err)) a.notifyError(i18n.SharedFormat(a.language(), "desktop.runConfig.loadFailed", map[string]string{"reason": err.Error()})) return } @@ -272,7 +272,7 @@ func (a *App) toggleRunConfigPin(p *project, id string) { pins[id] = true } if err := a.storeRunConfigPins(p.root, pins); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("run_configuration_pins_save", documentLogError(err))) + a.operationFailed("run_configuration_pins_save", documentLogError(err)) a.notifyError(i18n.SharedFormat(a.language(), "desktop.runConfig.saveFailed", map[string]string{"reason": err.Error()})) return } diff --git a/desktop/internal/workbench/runs.go b/desktop/internal/workbench/runs.go index d6116ec44c..e06339f049 100644 --- a/desktop/internal/workbench/runs.go +++ b/desktop/internal/workbench/runs.go @@ -395,7 +395,7 @@ func (a *App) rerunRun(p *project, entry *runEntry) { a.background(p, runRerunTimeout, func(ctx context.Context) func(*App) { if err := runs.Rerun(ctx, rerun); err != nil { return func(a *App) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("run_rerun", err)) + a.operationFailed("run_rerun", err) } } return nil diff --git a/desktop/internal/workbench/search.go b/desktop/internal/workbench/search.go index 48fca928e0..735d084e80 100644 --- a/desktop/internal/workbench/search.go +++ b/desktop/internal/workbench/search.go @@ -29,6 +29,16 @@ const ( searchUpdateLimit = 512 ) +// The two ways a directory watch stops keeping the project tree or a search index up to date +// change by change: the watcher fell behind and dropped events, or more changes arrived than +// searchEventLimit lets the window apply one by one. Either way the window rebuilds from a +// fresh listing without telling the user, so the log records it as background work it fell +// back from (backgroundFailed). +var ( + errWatchEventsLost = errors.New("directory watch lost events") + errWatchEventLimit = errors.New("directory watch changes exceeded the incremental update limit") +) + type searchQuery struct { text, mask string matchCase, wholeWords, regex bool @@ -127,7 +137,7 @@ func (a *App) drainProjectSearchWatch(p *project, slot *documentWatch) { if ready { s.watchReady, s.watchAvailable, s.fullResync = true, watch != nil, true if err != nil && s.watchAttached { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_search_watch", err)) + a.operationFailed("workspace_search_watch", err) a.notifyError(i18n.Shared(a.language(), "desktop.search.watchUnavailable")) } } @@ -140,7 +150,7 @@ func (a *App) drainProjectSearchWatch(p *project, slot *documentWatch) { if !s.watchAttached && !p.everywhere.watchAttached && p.tree.recursiveWatch { operation = "project_tree_watch" } - a.emit(core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": operation, "reason": "watch_events_lost"}) + a.backgroundFailed(operation, errWatchEventsLost) // The root may have been replaced, so install a fresh watch before // rebuilding. The new watch covers changes during the rebuild. slot.close() @@ -151,7 +161,7 @@ func (a *App) drainProjectSearchWatch(p *project, slot *documentWatch) { changed = true } else if len(events.Names) > 0 { if len(s.pending)+len(events.Names) > searchEventLimit { - a.emit(core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "workspace_search_incremental_update", "reason": "event_limit_exceeded"}) + a.backgroundFailed("workspace_search_incremental_update", errWatchEventLimit) s.pending = nil s.fullResync = true } else if !s.fullResync { @@ -204,7 +214,7 @@ func (a *App) updateProjectSearch(p *project, query searchQuery) { if !wasAttached && s.watchReady && !s.watchAvailable && s.watch != nil { _, _, err := s.watch.state() if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_search_watch", err)) + a.operationFailed("workspace_search_watch", err) } a.notifyError(i18n.Shared(a.language(), "desktop.search.watchUnavailable")) } @@ -313,7 +323,7 @@ func (a *App) releaseProjectSearch(p *project) { err = kernel.InvalidateWorkspaceSearch(ctx, root) } if err != nil && !errors.Is(err, context.Canceled) && sink != nil { - sink.Emit(operationFailedLevel, operationFailedEvent, "", operationFailedFields("workspace_search_cleanup", err)) + sink.Emit(backgroundFailedLevel, backgroundFailedEvent, "", operationFailedFields("workspace_search_cleanup", err)) } return nil }) @@ -327,7 +337,7 @@ func (a *App) finishProjectSearch(p *project, generation uint64, matches []core. } if generation != s.generation { if err != nil && !errors.Is(err, context.Canceled) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_search", err)) + a.backgroundFailed("workspace_search", err) } if s.watchReady && strings.TrimSpace(s.want.text) != "" { a.runProjectSearch(p) @@ -340,7 +350,7 @@ func (a *App) finishProjectSearch(p *project, generation uint64, matches []core. return } s.failed = true - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_search", err)) + a.operationFailed("workspace_search", err) return } s.matches = matches @@ -350,13 +360,13 @@ func (a *App) openSearchResult(p *project, result core.WorkspaceSearchMatch) { // Defend the adapter boundary even though Core returns workspace-relative paths. relative := filepath.FromSlash(result.Path) if relative == "" || filepath.IsAbs(relative) { - a.emit(core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "workspace_search", "reason": "invalid_result_path"}) + a.operationRejected("workspace_search", "invalid_result_path") return } path := filepath.Join(p.root, relative) rel, err := filepath.Rel(p.root, path) if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { - a.emit(core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "workspace_search", "reason": "invalid_result_path"}) + a.operationRejected("workspace_search", "invalid_result_path") return } if result.Line != nil && len(result.ContentMatchRanges) > 0 { diff --git a/desktop/internal/workbench/search_everywhere.go b/desktop/internal/workbench/search_everywhere.go index fc194cdceb..209e360816 100644 --- a/desktop/internal/workbench/search_everywhere.go +++ b/desktop/internal/workbench/search_everywhere.go @@ -244,7 +244,7 @@ func (a *App) startEverywhereWatch(p *project) { if !s.watchAvailable { _, _, err := p.search.watch.state() if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_search_everywhere_watch", err)) + a.operationFailed("workspace_search_everywhere_watch", err) } a.notifyError(i18n.Shared(a.language(), "desktop.everywhere.watchUnavailable")) } @@ -261,7 +261,7 @@ func (a *App) applyEverywhereWatch(p *project, ready, available bool, err error, if ready { s.watchReady, s.watchAvailable, s.fullResync = true, available, true if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_search_everywhere_watch", err)) + a.operationFailed("workspace_search_everywhere_watch", err) a.notifyError(i18n.Shared(a.language(), "desktop.everywhere.watchUnavailable")) } } @@ -272,7 +272,7 @@ func (a *App) applyEverywhereWatch(p *project, ready, available bool, err error, changed = true } else if len(events.Names) > 0 { if len(s.pending)+len(events.Names) > searchEventLimit { - a.emit(core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "workspace_search_incremental_update", "reason": "event_limit_exceeded"}) + a.backgroundFailed("workspace_search_incremental_update", errWatchEventLimit) s.pending, s.fullResync = nil, true } else if !s.fullResync { s.pending = append(s.pending, events.Names...) @@ -357,7 +357,7 @@ func (a *App) finishEverywhere(p *project, generation uint64, next bool, page co } if generation != s.generation { if err != nil && !errors.Is(err, context.Canceled) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_search_everywhere", err)) + a.backgroundFailed("workspace_search_everywhere", err) } if s.watchReady && a.everywhereView.open && strings.TrimSpace(s.query) != "" { a.runEverywhere(p, false) @@ -371,7 +371,7 @@ func (a *App) finishEverywhere(p *project, generation uint64, next bool, page co if err != nil { if !errors.Is(err, context.Canceled) { s.failed = true - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_search_everywhere", err)) + a.operationFailed("workspace_search_everywhere", err) } return } @@ -404,7 +404,7 @@ func (a *App) finishEverywhere(p *project, generation uint64, next bool, page co } } if page.NextCursor != nil && ((s.cursor != nil && *page.NextCursor == *s.cursor) || len(s.matches) == before) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_search_everywhere_page", errors.New("search page did not advance"))) + a.operationFailed("workspace_search_everywhere_page", errors.New("search page did not advance")) s.failed, s.cursor = true, nil return } diff --git a/desktop/internal/workbench/search_everywhere_gesture.go b/desktop/internal/workbench/search_everywhere_gesture.go index 265554670d..9d6acd74c6 100644 --- a/desktop/internal/workbench/search_everywhere_gesture.go +++ b/desktop/internal/workbench/search_everywhere_gesture.go @@ -46,7 +46,7 @@ func (a *App) onModifierTap(event gfx.ModifierTapEvent) gfx.EventResult { if err != nil { // There is no second implementation of the rule; the gesture just does not fire. v.gesture = nil - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("keymap_modifier_gesture", err)) + a.backgroundFailed("keymap_modifier_gesture", err) return gfx.EventResult{} } v.gesture = state diff --git a/desktop/internal/workbench/search_everywhere_lsp.go b/desktop/internal/workbench/search_everywhere_lsp.go index 52073a548c..0b59c0b9f4 100644 --- a/desktop/internal/workbench/search_everywhere_lsp.go +++ b/desktop/internal/workbench/search_everywhere_lsp.go @@ -170,7 +170,7 @@ func (a *App) applyWorkspaceSymbols(pending *semanticPending, event core.Backend } symbols, err := core.PluginWorkspaceSymbols(event) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_symbols", err)) + a.backgroundFailed("workspace_symbols", err) return } if st.itemKeys == nil { @@ -214,7 +214,7 @@ func (a *App) applyWorkspaceSymbols(pending *semanticPending, event core.Backend return } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_symbols_rank", err)) + a.backgroundFailed("workspace_symbols_rank", err) return } st.ranked = everywhereRankedMatches(p, items, order) diff --git a/desktop/internal/workbench/search_replace.go b/desktop/internal/workbench/search_replace.go index 197f8cf960..3852a9e67a 100644 --- a/desktop/internal/workbench/search_replace.go +++ b/desktop/internal/workbench/search_replace.go @@ -242,6 +242,7 @@ func (a *App) reportProjectReplace(outcomes []replaceOutcome) { if errors.Is(reason, documentio.ErrConflict) { message = t.ReplaceConflict } + a.operationFailed("project_replace", documentLogError(reason)) a.notifyError(t.ReplacePartlyFailed(strconv.Itoa(changed), strconv.Itoa(failed), message)) return } diff --git a/desktop/internal/workbench/semantic_tokens.go b/desktop/internal/workbench/semantic_tokens.go index c2f871b590..05ea097dc0 100644 --- a/desktop/internal/workbench/semantic_tokens.go +++ b/desktop/internal/workbench/semantic_tokens.go @@ -136,7 +136,7 @@ func (a *App) requestProviderTokens(p *project, d *document, revision int) { return } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_semantic_tokens", err)) + a.backgroundFailed("plugin_semantic_tokens", err) return } legend := syntax.NewSemanticLegend(tokens.Types, tokens.Modifiers) @@ -171,7 +171,7 @@ func (a *App) applySemanticTokens(pending *semanticPending, event core.BackendEv } tokens, err := core.PluginSemanticTokens(event) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_semantic_tokens", err)) + a.backgroundFailed("plugin_semantic_tokens", err) return } view := d.view diff --git a/desktop/internal/workbench/settings.go b/desktop/internal/workbench/settings.go index d8a87c0e75..3c8cea3e05 100644 --- a/desktop/internal/workbench/settings.go +++ b/desktop/internal/workbench/settings.go @@ -34,8 +34,11 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { PluginInstallsClosed: func() { a.post(func(a *App) { a.closePluginDownloads() }) }, - GitHub: a.githubSettings(), - SettingsError: func(operation string, err error) { (settingsToolchains{app: a}).recordFailure(operation, err) }, + GitHub: a.githubSettings(), + // The settings window reports from its own jobs, which run no action of this window. + SettingsError: func(operation string, err error) { + (settingsToolchains{app: a}).recordFailure(context.Background(), operation, err) + }, SettingsNavigation: navigation, SettingsPages: func(ctx context.Context) ([]core.SettingsPage, error) { if a.plugins == nil { @@ -54,11 +57,7 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { if plugins == nil { return marketplace.Snapshot{}, err } - a.post(func(a *App) { - fields := core.LogErrorFields(err) - fields["operation"] = "plugin_settings_catalog" - a.emit(core.LevelError, "app.notification.operation_failed", fields) - }) + a.operationFailedIn(ctx, "plugin_settings_catalog", err) } return marketplace.Snapshot{Index: core.MarketplaceIndex{Plugins: plugins}}, nil }, @@ -78,19 +77,14 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { } return service.Fetch(ctx, marketplace.OfficialIndexURL, core.MarketplaceOfficial, runtime.GOOS+"-"+arch, pluginhost.Declared().Clone()) }, + // The plugin page reports from the settings window's own jobs. They run no action of + // this window, so the events are written straight from that goroutine, under no + // operation, rather than posted to the window thread under whatever it was doing. MarketplaceError: func(err error) { - a.post(func(a *App) { - fields := core.LogErrorFields(err) - fields["operation"] = "plugin_marketplace" - a.emit(core.LevelError, "app.notification.operation_failed", fields) - }) + a.operationFailedIn(context.Background(), "plugin_marketplace", err) }, MarketplaceRejected: func(_ int) { - a.post(func(a *App) { - a.emit(core.LevelWarn, "app.notification.operation_rejected", map[string]any{ - "operation": "plugin_marketplace", "reason": "invalid_index_entries", - }) - }) + a.operationRejectedIn(context.Background(), "plugin_marketplace", "invalid_index_entries") }, MarketplaceResized: func(width float32) { a.post(func(a *App) { a.setMarketplaceWidth(width) }) @@ -437,6 +431,7 @@ func (a *App) openSettingsPageWith(surface actionSurface, page settingsPage, que err = a.settingsWindow.Open(a.application, current) } if err != nil { + a.operationFailed("settings_open", err) a.notifyError(a.text.Errors.SettingsFailed(err.Error())) } }) @@ -446,7 +441,7 @@ func (a *App) openSettingsPageWith(surface actionSurface, page settingsPage, que // browser. When the system cannot, the window says so and the log records why. func (a *App) openSettingsLink(address string) { if err := openURL(address); err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("settings_open_link", err)) + a.operationFailed("settings_open_link", err) a.notifyError(i18n.SharedFormat(a.language(), "desktop.terminal.openLinkFailed", map[string]string{"reason": err.Error()})) return } diff --git a/desktop/internal/workbench/settings_ide_api.go b/desktop/internal/workbench/settings_ide_api.go index 371470cc5a..b2d335e349 100644 --- a/desktop/internal/workbench/settings_ide_api.go +++ b/desktop/internal/workbench/settings_ide_api.go @@ -35,7 +35,7 @@ func (a *App) ideAPISetProject(p *project) { if p != nil { all := map[string]ideAPIGrants{} if _, err := a.store.Load(ideAPIGrantsFile, &all); err != nil { - a.gitOperationFailed("ide_api_grants", err) + a.backgroundFailed("ide_api_grants", err) } grants = all[p.root] } diff --git a/desktop/internal/workbench/settings_plugin_actions.go b/desktop/internal/workbench/settings_plugin_actions.go index 0620b9132f..f2b94f6359 100644 --- a/desktop/internal/workbench/settings_plugin_actions.go +++ b/desktop/internal/workbench/settings_plugin_actions.go @@ -48,8 +48,10 @@ func (s pluginSettingsSources) actionWorkspaceCheck(editor pluginservice.Setting // Action runs on the settings worker. Neither confirmation planning nor an // unavailable action starts a process or publishes a settings draft. func (s pluginSettingsSources) Action(ctx context.Context, editor pluginservice.SettingsEditor, id string, confirmed bool) (result pluginservice.SettingsActionResult, err error) { - defer func() { (settingsToolchains{app: s.app}).recordFailure("plugin_settings_action", err) }() - s.app.performed("plugin.settingsAction", surfaceButton) + // The click is the action; its operation travels in ctx, since the settings worker must not + // touch the window thread's operation. + ctx = s.app.performedIn(ctx, "plugin.settingsAction", surfaceButton) + defer func() { (settingsToolchains{app: s.app}).recordFailure(ctx, "plugin_settings_action", err) }() check := s.actionWorkspaceCheck(editor) result.Plan, err = s.app.plugins.PlanSettingsEditorAction(ctx, editor, id, confirmed, check) if err != nil { @@ -57,7 +59,7 @@ func (s pluginSettingsSources) Action(ctx context.Context, editor pluginservice. } if result.Plan.Kind != "invoke" { if result.Plan.Kind == "unavailable" { - s.app.emit(core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "plugin_settings_action", "reason": result.Plan.Reason}) + s.app.operationRejectedIn(ctx, "plugin_settings_action", result.Plan.Reason) } return result, nil } @@ -128,7 +130,7 @@ func (s pluginSettingsSources) Action(ctx context.Context, editor pluginservice. } if live.Kind != "invoke" { result.Plan = live - s.app.emit(core.LevelWarn, "app.notification.operation_rejected", map[string]any{"operation": "plugin_settings_action", "reason": live.Reason}) + s.app.operationRejectedIn(ctx, "plugin_settings_action", live.Reason) return result, nil } if err := ctx.Err(); err != nil { diff --git a/desktop/internal/workbench/settings_plugin_effects.go b/desktop/internal/workbench/settings_plugin_effects.go index 42ce98b928..d49607be98 100644 --- a/desktop/internal/workbench/settings_plugin_effects.go +++ b/desktop/internal/workbench/settings_plugin_effects.go @@ -69,7 +69,7 @@ func (a *App) applyLivePluginSettings(p *project, id, version string) { } return func(a *App) { if err != nil && server.settingsRevision.Load() == revision && a.isCurrentPluginServer(id, server) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_settings_immediate", err)) + a.backgroundFailed("plugin_settings_immediate", err) a.pluginSettingsRestart.Store(id, true) if a.settingsWindow != nil { a.settingsWindow.Invalidate() diff --git a/desktop/internal/workbench/settings_plugin_restart.go b/desktop/internal/workbench/settings_plugin_restart.go index 351ae45dc7..2272c9b55d 100644 --- a/desktop/internal/workbench/settings_plugin_restart.go +++ b/desktop/internal/workbench/settings_plugin_restart.go @@ -65,7 +65,7 @@ func (a *App) restartSettingsPlugin(id, version, scope, workspace string) { // Cleanup belongs to the detached native session, not to the project // context. Record failures even when its UI continuation was revoked. if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("plugin_settings_restart", err)) + a.operationFailedIn(ctx, "plugin_settings_restart", err) } return func(a *App) { a.pluginServerMu.Lock() diff --git a/desktop/internal/workbench/settings_plugins.go b/desktop/internal/workbench/settings_plugins.go index fab434af68..f03aa084a9 100644 --- a/desktop/internal/workbench/settings_plugins.go +++ b/desktop/internal/workbench/settings_plugins.go @@ -17,7 +17,7 @@ import ( type pluginSettingsSources struct{ app *App } func (s pluginSettingsSources) Load(ctx context.Context, id string, language i18n.Language) (editor pluginservice.SettingsEditor, err error) { - defer func() { (settingsToolchains{app: s.app}).recordFailure("plugin_settings_load", err) }() + defer func() { (settingsToolchains{app: s.app}).recordFailure(ctx, "plugin_settings_load", err) }() root := "" if current := s.app.toolchainRoot.Load(); current != nil { root = *current @@ -27,10 +27,10 @@ func (s pluginSettingsSources) Load(ctx context.Context, id string, language i18 // A skipped translation falls back to the next candidate or to manifest // text; the page still loads, so this is a degraded read, not a failure. if len(editor.Snapshot.LocalizationReadFailures()) > 0 { - s.app.emit(core.LevelWarn, pluginSettingsLoadRejectedEvent, pluginSettingsLoadRejected("localization_unreadable")) + s.app.operationRejectedIn(ctx, "plugin_settings_load", "localization_unreadable") } if localization := editor.Snapshot.State.Localization; localization != nil && len(localization.Rejected) > 0 { - s.app.emit(core.LevelWarn, pluginSettingsLoadRejectedEvent, pluginSettingsLoadRejected("invalid_localization")) + s.app.operationRejectedIn(ctx, "plugin_settings_load", "invalid_localization") } invalid := false for _, value := range editor.Snapshot.State.Editors.Global { @@ -40,24 +40,14 @@ func (s pluginSettingsSources) Load(ctx context.Context, id string, language i18 invalid = invalid || value.InvalidStored } if invalid { - s.app.emit(core.LevelWarn, pluginSettingsLoadRejectedEvent, pluginSettingsLoadRejected("invalid_stored_values")) + s.app.operationRejectedIn(ctx, "plugin_settings_load", "invalid_stored_values") } } return editor, err } -// pluginSettingsLoadRejectedEvent logs a plugin settings read that loaded but refused part of -// what it read: a stored value or a translation file of the package. -const pluginSettingsLoadRejectedEvent = "app.notification.operation_rejected" - -// pluginSettingsLoadRejected are the fields of that event; reason is localization_unreadable, -// invalid_localization or invalid_stored_values. -func pluginSettingsLoadRejected(reason string) map[string]any { - return map[string]any{"operation": "plugin_settings_load", "reason": reason} -} - func (s pluginSettingsSources) Save(ctx context.Context, editor pluginservice.SettingsEditor, scope string, edits []core.PluginSettingEdit) (result pluginsettings.SaveResult, err error) { - defer func() { (settingsToolchains{app: s.app}).recordFailure("plugin_settings_save", err) }() + defer func() { (settingsToolchains{app: s.app}).recordFailure(ctx, "plugin_settings_save", err) }() check := func() error { if scope != "project" { return nil diff --git a/desktop/internal/workbench/settings_toolchains.go b/desktop/internal/workbench/settings_toolchains.go index e1630a07e8..819cf35c3b 100644 --- a/desktop/internal/workbench/settings_toolchains.go +++ b/desktop/internal/workbench/settings_toolchains.go @@ -17,7 +17,7 @@ type settingsToolchains struct { // Load reads toolchains for the open project. No project means an empty // snapshot, which the page shows as "open a project". func (s settingsToolchains) Load(ctx context.Context) (snapshot toolchain.Snapshot, err error) { - defer func() { s.recordFailure("toolchain_settings_load", err) }() + defer func() { s.recordFailure(ctx, "toolchain_settings_load", err) }() root := s.app.toolchainRoot.Load() if root == nil || *root == "" { return toolchain.Snapshot{}, nil @@ -36,7 +36,7 @@ func (s settingsToolchains) loadAt(ctx context.Context, root string) (toolchain. // Save applies all draft changes in one Core edit, against the exact // bytes the snapshot was read from, then re-reads the effective values. func (s settingsToolchains) Save(ctx context.Context, snapshot toolchain.Snapshot, edits []toolchain.Edit) (updated toolchain.Snapshot, err error) { - defer func() { s.recordFailure("toolchain_settings_save", err) }() + defer func() { s.recordFailure(ctx, "toolchain_settings_save", err) }() root := s.app.toolchainRoot.Load() if root == nil || *root == "" || snapshot.Root == "" { return snapshot, toolchain.ErrPinConflict @@ -56,10 +56,12 @@ func (s settingsToolchains) Save(ctx context.Context, snapshot toolchain.Snapsho return updated, nil } -func (s settingsToolchains) recordFailure(operation string, err error) { +// recordFailure logs a failed settings request from the settings worker that ran it, under the +// user action ctx carries; it never reads the window thread's operation. +func (s settingsToolchains) recordFailure(ctx context.Context, operation string, err error) { // log-exempt: 用户取消:设置窗口关闭或取消操作不是失败。 if err == nil || errors.Is(err, context.Canceled) { return } - s.app.emit(operationFailedLevel, operationFailedEvent, operationFailedFields(operation, err)) + s.app.operationFailedIn(ctx, operation, err) } diff --git a/desktop/internal/workbench/shelf.go b/desktop/internal/workbench/shelf.go index 967eb7088f..999609a94d 100644 --- a/desktop/internal/workbench/shelf.go +++ b/desktop/internal/workbench/shelf.go @@ -239,11 +239,11 @@ func (a *App) loadShelves(p *project) { } s.loading, s.loaded = false, true if skipped != nil { - a.gitOperationFailed("git_shelf_read", skipped) + a.backgroundFailed("git_shelf_read", skipped) } if err != nil { s.err = err.Error() - a.gitOperationFailed("git_shelf_list", err) + a.operationFailed("git_shelf_list", err) return } s.err, s.list = "", list @@ -299,7 +299,7 @@ func (a *App) selectShelf(p *project, id string) { s.filesLoading = false if err != nil { s.filesErr = i18n.Shared(a.language(), "native.couldNotLoadSavedChanges") + ": " + reviewReason(err) - a.gitOperationFailed("git_shelf_diff", err) + a.operationFailed("git_shelf_diff", err) return } for i, kind := range kinds { @@ -395,7 +395,7 @@ func (a *App) shelfWrite(p *project, operation string, checkout bool, write func a.loadShelves(p) if err != nil { s.writeErr = a.shelfReason(err) - a.gitOperationFailed(operation, err) + a.operationFailed(operation, err) } } }) diff --git a/desktop/internal/workbench/startup_sweep.go b/desktop/internal/workbench/startup_sweep.go index 89a2036947..a9f2f808f8 100644 --- a/desktop/internal/workbench/startup_sweep.go +++ b/desktop/internal/workbench/startup_sweep.go @@ -95,7 +95,7 @@ func (a *App) planStartupSweep() { } return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("startup_sweep_plan", err)) + a.backgroundFailed("startup_sweep_plan", err) a.startupSweep = startupSweepState{open: true, leftovers: leftovers, settings: settings, grace: buildprocess.StopGrace()} return } @@ -140,7 +140,7 @@ func (a *App) settleLeftovers(ended, kept []processledger.Record, grace time.Dur err := errors.Join(keepErr, endErr) return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("startup_sweep", err)) + a.operationFailed("startup_sweep", err) return } a.emit(core.LevelInfo, "app.startup.leftovers_resolved", map[string]any{"decided_by": decidedBy, "ended": count, "kept": len(kept)}) @@ -216,7 +216,7 @@ func (a *App) settleStartupSweep(end bool) { settlement, err := a.kernel.SettleProcessLifecycle(ctx, question.settings, decisions, answers, false) return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("startup_sweep_settle", err)) + a.operationFailed("startup_sweep_settle", err) return } pick := func(ids []string) []processledger.Record { diff --git a/desktop/internal/workbench/startup_test.go b/desktop/internal/workbench/startup_test.go index 75a6cf088c..d844fcc1d6 100644 --- a/desktop/internal/workbench/startup_test.go +++ b/desktop/internal/workbench/startup_test.go @@ -119,7 +119,7 @@ func TestPluginSettingsLoadLogsSkippedAndRefusedTranslations(t *testing.T) { var reasons []string for _, event := range log.events { if event.Fields["operation"] == "plugin_settings_load" { - if event.Level != core.LevelWarn || event.Event != pluginSettingsLoadRejectedEvent { + if event.Level != operationRejectedLevel || event.Event != operationRejectedEvent { t.Fatalf("plugin settings load logged %s %s %v", event.Level, event.Event, event.Fields) } reasons = append(reasons, event.Fields["reason"].(string)) diff --git a/desktop/internal/workbench/stash.go b/desktop/internal/workbench/stash.go index 2347f5fbf1..78ec2c0cbd 100644 --- a/desktop/internal/workbench/stash.go +++ b/desktop/internal/workbench/stash.go @@ -108,7 +108,7 @@ func (a *App) loadStashes(p *project) { s.loading, s.loaded = false, true if err != nil { s.err = reviewReason(err) - a.gitOperationFailed("git_stash_list", err) + a.operationFailed("git_stash_list", err) return } s.err, s.list = "", list @@ -150,7 +150,7 @@ func (a *App) selectStash(p *project, oid string) { s.filesLoading = false if err != nil { s.filesErr = i18n.SharedFormat(a.language(), "git.diff.getStashDiffFailed", map[string]string{"stash": stash.Reference, "error": reviewReason(err)}) - a.gitOperationFailed("git_stash_diff", err) + a.operationFailed("git_stash_diff", err) return } s.files = files @@ -201,7 +201,7 @@ func (a *App) stashWrite(p *project, operation string, write func(ctx context.Co a.reloadDiffs(p, root) if err != nil { s.writeErr = reviewReason(err) - a.gitOperationFailed(operation, err) + a.operationFailed(operation, err) } } }) diff --git a/desktop/internal/workbench/status_items.go b/desktop/internal/workbench/status_items.go index 847267df42..6ead604cb9 100644 --- a/desktop/internal/workbench/status_items.go +++ b/desktop/internal/workbench/status_items.go @@ -47,6 +47,7 @@ func (a *App) toggleLineEnding(d *document) { return } if err := d.view.ApplyEdits([]editorview.TextEdit{{Range: editorview.Range{Start: 0, End: len(text)}, Text: next}}); err != nil { + a.operationFailed("line_ending_toggle", err) a.notifyError(a.text.Errors.OpenFailed(err.Error())) } } diff --git a/desktop/internal/workbench/tabdrag.go b/desktop/internal/workbench/tabdrag.go index 4be1baa8fe..548b0f26f4 100644 --- a/desktop/internal/workbench/tabdrag.go +++ b/desktop/internal/workbench/tabdrag.go @@ -51,13 +51,14 @@ func (a *App) tabDropRules(member string) *core.EditorDropRules { if p == nil { return nil } - ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) defer cancel() rules, err := a.kernel.EditorDropTargets(ctx, core.EditorDropQuery{ State: p.terms.bench, Layout: layoutShape(p.terms.layout), Member: member, Docked: dockedGroups, Dockable: dockable(member), }) if err != nil { + a.operationFailed("editor_tab_drop", err) a.notifyError(a.text.Errors.Core(err.Error())) return nil } diff --git a/desktop/internal/workbench/tasks.go b/desktop/internal/workbench/tasks.go index 99d8baada9..a42cd9dec9 100644 --- a/desktop/internal/workbench/tasks.go +++ b/desktop/internal/workbench/tasks.go @@ -49,12 +49,15 @@ func (a *App) wakeForEarlyResults() { // project's shell produced. It is the window's OnWake, which runs before every repaint a // wake asks for, so output reaches the screen without a timer. func (a *App) drain() { + // The window drains every workbench directly, not through the callback operating wraps. + defer a.endOperation() a.tasks.mu.Lock() pending := a.tasks.pending a.tasks.pending = nil a.tasks.mu.Unlock() + // Each result runs as a turn of its own: an action one of them starts ends with it. for _, apply := range pending { - apply(a) + a.within(operation{}, apply) } a.drainSettings() a.pumpTerminal() @@ -66,12 +69,15 @@ func (a *App) drain() { // replaced is dropped. timeout bounds the work; zero leaves it unbounded, for work the // user ends, such as a folder dialog. // -// work returns nil when there is nothing to apply. +// work returns nil when there is nothing to apply. Work started during a user action belongs to +// it (operation.go): its context carries the action, and its result is applied under it. func (a *App) background(p *project, timeout time.Duration, work func(ctx context.Context) func(*App)) { parent := context.Background() if p != nil { parent = p.ctx } + op := a.op + parent = a.operationContext(parent) ctx, cancel := parent, context.CancelFunc(func() {}) if timeout > 0 { ctx, cancel = context.WithTimeout(parent, timeout) @@ -88,7 +94,7 @@ func (a *App) background(p *project, timeout time.Duration, work func(ctx contex if p != nil && a.project != p { return } - apply(a) + a.within(op, apply) }) }() } diff --git a/desktop/internal/workbench/terminal_commands.go b/desktop/internal/workbench/terminal_commands.go index 8183ae24a4..d3e270e6a5 100644 --- a/desktop/internal/workbench/terminal_commands.go +++ b/desktop/internal/workbench/terminal_commands.go @@ -43,6 +43,7 @@ func (a *App) sendTerminalCommand(t *terminal, command string) bool { } line, path, err := writeCommandScript(kind, command) if err != nil { + a.operationFailed("terminal_command_script", documentLogError(err)) a.notifyError(err.Error()) return false } diff --git a/desktop/internal/workbench/terminal_find.go b/desktop/internal/workbench/terminal_find.go index a8dd0ec565..7dc6b3e760 100644 --- a/desktop/internal/workbench/terminal_find.go +++ b/desktop/internal/workbench/terminal_find.go @@ -104,10 +104,11 @@ func (a *App) openTerminalLink(target string) { return } a.post(func(a *App) { + a.performed("terminal.link.open", surfaceButton) if err := openURL(target); err != nil { + a.operationFailed("open_url", err) a.notifyError(a.text.Terminal.OpenLinkFailed(err.Error())) } - a.performed("terminal.link.open", surfaceButton) }) } diff --git a/desktop/internal/workbench/terminals.go b/desktop/internal/workbench/terminals.go index 9fe554398d..c493a4b037 100644 --- a/desktop/internal/workbench/terminals.go +++ b/desktop/internal/workbench/terminals.go @@ -316,11 +316,12 @@ func (a *App) reduceTerminals(p *project, state core.EditorWorkbench, action cor // reduceEditorLayout is reduceTerminals with what the kernel answered. func (a *App) reduceEditorLayout(p *project, state core.EditorWorkbench, action core.EditorAction) (core.EditorLayoutResult, bool) { - ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) defer cancel() set := &p.terms result, err := a.kernel.ReduceEditorLayout(ctx, state, layoutShape(set.layout), action) if err != nil { + a.operationFailed("editor_layout_reduce", err) a.notifyError(a.text.Errors.Core(err.Error())) return result, false } diff --git a/desktop/internal/workbench/tests.go b/desktop/internal/workbench/tests.go index 13b2a87077..d746e3406c 100644 --- a/desktop/internal/workbench/tests.go +++ b/desktop/internal/workbench/tests.go @@ -430,7 +430,7 @@ func (a *App) finishTestRun(p *project, generation uint64, selection testSelecti if a.project != p || p.tests.generation != generation { return } - verdict, err := a.kernel.ResolveBuildTestOutcome(context.Background(), termination, selection.scopeProject(), selection.suite, selection.caseName, &results.Summary) + verdict, err := a.kernel.ResolveBuildTestOutcome(a.operationContext(context.Background()), termination, selection.scopeProject(), selection.suite, selection.caseName, &results.Summary) if err != nil { a.finishTestError(p, generation, err) return @@ -452,7 +452,7 @@ func (a *App) finishTestInterrupted(p *project, generation uint64, selection tes if a.project != p || p.tests.generation != generation { return } - verdict, err := a.kernel.ResolveBuildTestOutcome(context.Background(), termination, selection.scopeProject(), selection.suite, selection.caseName, nil) + verdict, err := a.kernel.ResolveBuildTestOutcome(a.operationContext(context.Background()), termination, selection.scopeProject(), selection.suite, selection.caseName, nil) if err != nil { a.finishTestError(p, generation, err) return @@ -488,7 +488,7 @@ func (a *App) finishTestError(p *project, generation uint64, err error) { } p.tests.failed = a.text.Tests.ResultsUnavailable(err.Error()) p.tests.status = a.text.Tests.ResultsUnavailable(err.Error()) - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("tests", err)) + a.operationFailed("tests", err) } // stopTests stops the process and asks the provider to cancel. The terminal diff --git a/desktop/internal/workbench/title_run.go b/desktop/internal/workbench/title_run.go index dcb1b20e45..ca639ce001 100644 --- a/desktop/internal/workbench/title_run.go +++ b/desktop/internal/workbench/title_run.go @@ -188,7 +188,7 @@ func (a *App) decideTitleAction(p *project, action titleAction, trigger string) cancel() p.runConfigs.pending = titleActionNone if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("title_run", err)) + a.operationFailed("title_run", err) a.notifyError(err.Error()) return } @@ -203,11 +203,11 @@ func (a *App) decideTitleAction(p *project, action titleAction, trigger string) case "unsupported": a.notifyInfo(i18n.SharedFormat(a.language(), "desktop.title.configurationNotStartable", map[string]string{"name": configuration.Name})) case "targetMissing": - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("title_run", errors.New("the configuration's build instance was not detected"))) + a.operationFailed("title_run", errors.New("the configuration's build instance was not detected")) a.notifyError(a.text.Build.TargetMissing) case "modelFailed": failure := p.build.instances[index].modelError - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("title_run", errors.New(failure))) + a.operationFailed("title_run", errors.New(failure)) a.notifyError(failure) case "run": if _, err := a.startRunConfiguration(p, configuration.ID); errors.Is(err, errBuildBusy) { diff --git a/desktop/internal/workbench/updates.go b/desktop/internal/workbench/updates.go index cd684f2c28..bf50350a06 100644 --- a/desktop/internal/workbench/updates.go +++ b/desktop/internal/workbench/updates.go @@ -343,8 +343,10 @@ func (a *App) checkForUpdates(asked bool) { s.Failure = "" } }) + // A check the user asked for carries the action; an automatic one carries none. + parent := a.operationContext(context.Background()) go func() { - ctx, cancel := context.WithTimeout(context.Background(), updateCheckTimeout) + ctx, cancel := context.WithTimeout(parent, updateCheckTimeout) defer cancel() feed, err := source.Check(ctx) var asset appupdate.Asset @@ -361,7 +363,12 @@ func (a *App) checkForUpdates(asked bool) { func (a *App) updateChecked(asked bool, feed *appupdate.Feed, asset appupdate.Asset, err error) { u := a.updates if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("update_check", err)) + // A check the user asked for shows its failure; a scheduled one tries again later. + if asked { + a.operationFailed("update_check", err) + } else { + a.backgroundFailed("update_check", err) + } a.changeUpdate(func(s *settingswindow.UpdateStatus) { s.Checking = false if asked { @@ -455,30 +462,32 @@ func (a *App) removeUpdatePayload(payload string) { if payload == "" { return } - a.background(nil, 0, func(context.Context) func(*App) { - a.deleteUpdatePayload(payload) + a.background(nil, 0, func(ctx context.Context) func(*App) { + a.deleteUpdatePayload(ctx, payload) return nil }) } // deleteUpdatePayload deletes an application a patch rebuilt in the system's temporary -// directory, on the calling goroutine, which is not the window thread. A deletion that fails -// leaves a copy the system cleans up later, so it is logged and nothing else. -func (a *App) deleteUpdatePayload(payload string) { +// directory, on the calling goroutine, which is not the window thread; ctx is the work's +// context, whose action the record belongs to. A deletion that fails leaves a copy the system +// cleans up later, so it is logged and nothing else. +func (a *App) deleteUpdatePayload(ctx context.Context, payload string) { if payload == "" { return } if err := removeUpdateDir(payload); err != nil { - a.emit(core.LevelWarn, deltaCleanupFailedEvent, core.LogErrorFields(err)) + a.emitIn(ctx, core.LevelWarn, deltaCleanupFailedEvent, core.LogErrorFields(err)) } } // deltaFellBack logs the step of a delta update that failed and skips the patch to version -// from then on, so the next download is the full archive. It runs on any goroutine. -func (a *App) deltaFellBack(stage, version string, err error) { +// from then on, so the next download is the full archive. It runs on any goroutine; ctx +// carries the action the record belongs to. +func (a *App) deltaFellBack(ctx context.Context, stage, version string, err error) { fields := core.LogErrorFields(err) fields["stage"] = stage - a.emit(core.LevelWarn, deltaFallbackEvent, fields) + a.emitIn(ctx, core.LevelWarn, deltaFallbackEvent, fields) a.updates.mu.Lock() a.updates.noDelta = version a.updates.mu.Unlock() @@ -507,7 +516,7 @@ func (a *App) downloadUpdate() { return } dir := filepath.Join(cache, "Lithe", "Updates", feed.Latest.Version) - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(a.operationContext(context.Background())) u.mu.Lock() u.cancel = cancel u.mu.Unlock() @@ -549,7 +558,7 @@ func (a *App) fetchDelta(ctx context.Context, source updateSource, version strin return "", ctxErr } if err != nil { - a.deltaFellBack(deltaStageDownload, version, err) + a.deltaFellBack(ctx, deltaStageDownload, version, err) return "", err } // Applying reads every file of the installed application and cannot be interrupted, so @@ -561,11 +570,11 @@ func (a *App) fetchDelta(ctx context.Context, source updateSource, version strin if ctxErr := ctx.Err(); ctxErr != nil { // The window closed or the download was cancelled while the patch applied: nothing // will install the copy. - a.deleteUpdatePayload(payload) + a.deleteUpdatePayload(ctx, payload) return "", ctxErr } if err != nil { - a.deltaFellBack(deltaStageApply, version, err) + a.deltaFellBack(ctx, deltaStageApply, version, err) return "", err } return payload, nil @@ -669,7 +678,7 @@ func (a *App) installUpdate() { } return } - a.deltaFellBack(deltaStageInstall, feed.Latest.Version, err) + a.deltaFellBack(a.operationContext(context.Background()), deltaStageInstall, feed.Latest.Version, err) a.changeUpdate(func(s *settingswindow.UpdateStatus) { s.Installing, s.Ready = false, false }) a.downloadUpdate() } @@ -686,5 +695,5 @@ func (a *App) updateFailed(err error) { s.Downloading, s.Applying, s.FellBack, s.Installing, s.Checking, s.Progress = false, false, false, false, false, 0 s.Failure = err.Error() }) - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("update", err)) + a.operationFailed("update", err) } diff --git a/desktop/internal/workbench/vcs.go b/desktop/internal/workbench/vcs.go index 04b94a34e5..a5494d9af1 100644 --- a/desktop/internal/workbench/vcs.go +++ b/desktop/internal/workbench/vcs.go @@ -370,8 +370,9 @@ func (r *vcsRuntime) live(key string) *buildprovider.Client { // session is the running session of window, started when there is none. A session that did not // negotiate the window's provider is stopped and refused, as the contract asks. The process starts // outside the lock, so detaching on the window thread never waits for a start; a start that lost -// to another one or to detaching is stopped again. -func (r *vcsRuntime) session(ctx context.Context, runner *pluginbackend.Runner, pluginRoot, root, rootURI string, window vcsWindow, settings core.PluginSettingsState) (client *buildprovider.Client, err error) { +// to another one or to detaching is stopped again. logDirectory gives the process's ${logDir}, and +// is asked only when a process starts. +func (r *vcsRuntime) session(ctx context.Context, runner *pluginbackend.Runner, pluginRoot, root, rootURI string, window vcsWindow, settings core.PluginSettingsState, logDirectory func(context.Context, string) string) (client *buildprovider.Client, err error) { ctx, finish, err := r.launches.begin(ctx, window.PluginID) if err != nil { return nil, err @@ -389,9 +390,8 @@ func (r *vcsRuntime) session(ctx context.Context, runner *pluginbackend.Runner, } state := filepath.Join(pluginRoot, ".state", window.PluginID, window.Version, "vcs", workspaceDigest(root)) workspaceState := filepath.Join(state, "workspace") - logDirectory := filepath.Join(state, "log") temporaryDirectory := filepath.Join(state, "tmp") - for _, directory := range []string{state, workspaceState, logDirectory, temporaryDirectory} { + for _, directory := range []string{state, workspaceState, temporaryDirectory} { if err := os.MkdirAll(directory, 0o700); err != nil { return nil, err } @@ -405,7 +405,7 @@ func (r *vcsRuntime) session(ctx context.Context, runner *pluginbackend.Runner, Role: "vcs", StateDirectory: state, WorkspaceStateDirectory: workspaceState, - LogDirectory: logDirectory, + LogDirectory: logDirectory(ctx, window.PluginID), TemporaryDirectory: temporaryDirectory, Architecture: core.PluginArchitecture(), Settings: settings.Settings, @@ -527,7 +527,7 @@ func (a *App) detectVcsRoots(p *project) { } mappings, err := a.loadVcsMappings(p.root) if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("vcs_root_mappings_load", documentLogError(err))) + a.operationFailed("vcs_root_mappings_load", documentLogError(err)) a.notifyError(i18n.SharedFormat(a.language(), "desktop.project.readFailed", map[string]string{"reason": err.Error()})) } s.generation++ @@ -542,7 +542,7 @@ func (a *App) detectVcsRoots(p *project) { s.detecting, s.detected = false, true if err != nil { s.failure = a.vcsFailureText(err) - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("vcs_detect_roots", documentLogError(err))) + a.operationFailed("vcs_detect_roots", documentLogError(err)) return } s.detection, s.manifests = detection, plugins @@ -596,7 +596,7 @@ func (a *App) mapVcsRoot(p *project, id, vcs string) { err = a.storeVcsMappings(p.root, append(mappings, core.VcsMapping{ID: id, Vcs: vcs})) } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("vcs_root_mappings_save", documentLogError(err))) + a.operationFailed("vcs_root_mappings_save", documentLogError(err)) a.notifyError(i18n.SharedFormat(a.language(), "desktop.runConfig.saveFailed", map[string]string{"reason": err.Error()})) return } @@ -611,7 +611,7 @@ func (a *App) dropVcsMappings(root string, unused []core.VcsMapping) { err = a.storeVcsMappings(root, mappings) } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("vcs_root_mappings_save", documentLogError(err))) + a.backgroundFailed("vcs_root_mappings_save", documentLogError(err)) } } @@ -654,7 +654,7 @@ func (a *App) runVcs(ctx context.Context, p *project, sessions *vcsRuntime, call if err != nil { return nil, nil, err } - if client, err = sessions.session(ctx, a.plugins.Backend, a.plugins.Root, p.root, rootURI, call.window, settings.State); err != nil { + if client, err = sessions.session(ctx, a.plugins.Backend, a.plugins.Root, p.root, rootURI, call.window, settings.State, a.pluginLogDirectory); err != nil { return nil, nil, err } } @@ -786,7 +786,7 @@ func (a *App) refreshVcsStatus(p *project, t vcsTarget) { } if err != nil { t.state.failure = a.vcsFailureText(err) - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("vcs_status", documentLogError(err))) + a.operationFailed("vcs_status", documentLogError(err)) return } t.state.status = &status @@ -834,7 +834,7 @@ func (a *App) loadVcsHistory(p *project, t vcsTarget, more bool) { } if err != nil { t.state.historyFailure = a.vcsFailureText(err) - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("vcs_history", documentLogError(err))) + a.operationFailed("vcs_history", documentLogError(err)) return } if !more { @@ -870,7 +870,7 @@ func (a *App) runVcsChange(p *project, t vcsTarget, action, operation string, ar } if err != nil { t.view.failure = a.vcsFailureText(err) - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("vcs_"+operation, documentLogError(err))) + a.operationFailed("vcs_"+operation, documentLogError(err)) } else { t.view.notice = done(a, decoded) } @@ -985,7 +985,7 @@ func (a *App) showVcsDiff(p *project, t vcsTarget, change core.VcsChange) { t.view.capabilities = capabilities } if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("vcs_diff", documentLogError(err))) + a.operationFailed("vcs_diff", documentLogError(err)) a.notifyError(a.vcsFailureText(err)) return } diff --git a/desktop/internal/workbench/viewer.go b/desktop/internal/workbench/viewer.go index 1f513b3187..94d1a6aefe 100644 --- a/desktop/internal/workbench/viewer.go +++ b/desktop/internal/workbench/viewer.go @@ -202,7 +202,7 @@ func (a *App) viewerCanvas(p *project, t *viewerTab) *imageCanvas { } if err != nil { n.state = canvasFailed - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("viewer_decode", err)) + a.operationFailed("viewer_decode", err) return } n.bitmap, n.state = bitmap, canvasReady diff --git a/desktop/internal/workbench/viewer_image.go b/desktop/internal/workbench/viewer_image.go index 634ab1930c..fe45e3ada0 100644 --- a/desktop/internal/workbench/viewer_image.go +++ b/desktop/internal/workbench/viewer_image.go @@ -118,6 +118,7 @@ func (a *App) viewerToolbar(c ui.C, bar viewerBar) { path := bar.path c.After(func() { if err := app.OpenPath(path); err != nil { + a.operationFailed("open_externally", documentLogError(err)) a.notifyError(i18n.SharedFormat(language, "desktop.viewer.openFailed", map[string]string{"reason": err.Error()})) } }) diff --git a/desktop/internal/workbench/welcome_view.go b/desktop/internal/workbench/welcome_view.go index 798f4335b8..865e4b2626 100644 --- a/desktop/internal/workbench/welcome_view.go +++ b/desktop/internal/workbench/welcome_view.go @@ -292,7 +292,7 @@ func (a *App) revealRecent(path string) { err := app.RevealPath(path) return func(a *App) { if err != nil { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_reveal_recent", documentLogError(err))) + a.operationFailed("workspace_reveal_recent", documentLogError(err)) a.notifyError(a.text.Errors.OpenFailed(err.Error())) } } diff --git a/desktop/internal/workbench/window_sessions.go b/desktop/internal/workbench/window_sessions.go index ad69c0fe71..7496d9fb0d 100644 --- a/desktop/internal/workbench/window_sessions.go +++ b/desktop/internal/workbench/window_sessions.go @@ -271,6 +271,7 @@ func (s *windowSessions) leave(a *App) { s.activate(s.list[min(at, len(s.list)-1)]) } a.unsubscribeSettings() + a.stopWatchingDiagnostics() a.closeClone() a.closeNewProject() a.settingsWindow.Close() @@ -372,7 +373,8 @@ func (a *App) projectTab(c ui.C, tab *App, i, size int) { c.After(func() { a.performed("workspace.tab.close", surfaceButton) a.sessions.activate(tab) - tab.closeProject() + // The tab closes as part of the action, whichever workbench shows the bar. + tab.within(a.op, (*App).closeProject) }) case chip.Clicked(): c.After(func() { diff --git a/desktop/internal/workbench/workbench_background.go b/desktop/internal/workbench/workbench_background.go index 05054655b0..dfc6c27cfd 100644 --- a/desktop/internal/workbench/workbench_background.go +++ b/desktop/internal/workbench/workbench_background.go @@ -238,7 +238,7 @@ func (a *App) restoredBackground(serial uint64, pix []byte, width, height int, e b.set, b.name = false, "" default: b.mu.Unlock() - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workbench_background", documentLogError(err))) + a.operationFailed("workbench_background", documentLogError(err)) a.notifyError(backgroundFailureText(a.language(), err)) a.dropBackground(err) return @@ -337,7 +337,7 @@ func checkBackgroundHeader(data []byte) error { // backgroundChoiceFailed tells why the chosen file cannot be used; the background is left as // it was. func (a *App) backgroundChoiceFailed(err error) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workbench_background", documentLogError(err))) + a.operationFailed("workbench_background", documentLogError(err)) a.notifyError(backgroundFailureText(a.language(), err)) } @@ -373,7 +373,7 @@ func (a *App) backgroundCopied(serial uint64, chosen chosenBackground, err error if err != nil { set, decoded := b.set, b.pix != nil b.mu.Unlock() - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workbench_background_save", documentLogError(err))) + a.operationFailed("workbench_background_save", documentLogError(err)) a.notifyError(a.text.Errors.SaveFailed(err.Error())) switch { case !set: @@ -422,7 +422,7 @@ func (a *App) deleteBackgroundCopy(serial uint64) { return nil } return func(a *App) { - a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("workbench_background_remove", documentLogError(err))) + a.backgroundFailed("workbench_background_remove", documentLogError(err)) } }) } diff --git a/desktop/internal/workbench/worktree_window.go b/desktop/internal/workbench/worktree_window.go index b3babaa2d4..7985124ec4 100644 --- a/desktop/internal/workbench/worktree_window.go +++ b/desktop/internal/workbench/worktree_window.go @@ -10,6 +10,7 @@ import ( func (a *App) openWorktreeInNewWindow(path string) { a.performed("git.worktree.openNewWindow", surfaceButton) if err := launchClient(path); err != nil { + a.operationFailed("worktree_open_new_window", documentLogError(err)) a.notifyError(i18n.SharedFormat(a.language(), "desktop.worktree.openNewWindowFailed", map[string]string{"reason": treeErrorReason(err)})) } } diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index ac1ba1d781..2d868944c1 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -1265,6 +1265,7 @@ "desktop.notifications.repeated": "{message} ({count})", "desktop.notifications.title": "Notifications", "desktop.notifications.unread": "Notifications, {count} unread", + "desktop.notifications.viewLogs": "View Logs", "desktop.outline.empty": "No symbols in this file.", "desktop.outline.loading": "Loading structure...", "desktop.outline.noFile": "Open a file to see its structure.", @@ -10612,6 +10613,7 @@ "desktop.files.copy": "Copy", "desktop.files.paste": "Paste", "desktop.files.moveFailed": "Could not move the item: {reason}", + "desktop.files.crossBoundaryMove": "Moving or renaming between WSL distributions, or between a distribution and a local folder, is not supported", "desktop.files.pasteFailed": "Could not paste the item: {reason}", "desktop.github.settingsTitle": "GitHub Account", "desktop.github.settingsHelp": "Sign in to list, check out and review pull requests of this repository.", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 90feb88898..1ad40c2661 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -1265,6 +1265,7 @@ "desktop.notifications.repeated": "{message}({count})", "desktop.notifications.title": "通知", "desktop.notifications.unread": "通知,{count} 条未读", + "desktop.notifications.viewLogs": "查看日志", "desktop.outline.empty": "此文件没有符号。", "desktop.outline.loading": "正在加载结构…", "desktop.outline.noFile": "打开文件后可查看其结构。", @@ -10612,6 +10613,7 @@ "desktop.files.copy": "复制", "desktop.files.paste": "粘贴", "desktop.files.moveFailed": "无法移动该项目:{reason}", + "desktop.files.crossBoundaryMove": "不支持在不同 WSL 发行版之间、或在发行版与本地文件夹之间移动或重命名", "desktop.files.pasteFailed": "无法粘贴该项目:{reason}", "desktop.github.settingsTitle": "GitHub 账号", "desktop.github.settingsHelp": "登录后可以查看、检出和评审本仓库的 Pull Request。", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 1278babbfe..3854717852 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -9396,6 +9396,13 @@ "reason": "string" } }, + { + "id": "desktop.files.crossBoundaryMove", + "description": "Notice when a move or rename would cross between WSL distributions or between a distribution and a local folder", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.files.moveToTrash", "description": "Delete dialog: the default button, which moves the items to the system trash", @@ -13064,6 +13071,13 @@ "count": "string" } }, + { + "id": "desktop.notifications.viewLogs", + "description": "Button on a failure notice, in its toast and in the notification history, that opens the log window on the records of the action that failed", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.outline.empty", "description": "Structure tool window text when the file has no symbols", From 7730ce6a3e257298c17f4a47a251c81082fc77aa Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 01:57:36 +0800 Subject: [PATCH 5/7] =?UTF-8?q?docs(develop-lithe):=20=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E6=8E=A5=E5=85=A5=E6=94=B9=E5=86=99=E4=B8=BA=20Viva=20?= =?UTF-8?q?=E6=A1=8C=E9=9D=A2=E7=AB=AF=EF=BC=9B=E4=BF=AE=E5=A4=8D=E7=A9=BA?= =?UTF-8?q?=E7=BC=96=E8=BE=91=E5=8C=BA=E6=8F=90=E7=A4=BA=E7=9A=84=E7=95=8C?= =?UTF-8?q?=E9=9D=A2=E6=96=87=E6=A1=88=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - references/logging.md 整体改写为 Go/Viva 桌面端的记录规则、入口和校验 - SKILL.md 规则 7 与显式处理失败改为 Go 写法 - build-desktop-core.sh 固定到 Core #46 分支提交并说明合入后迁移 - 补齐 log-exempt 标记,webpreview 去掉 slog - 空编辑区快捷键提示改为结构体表,避免 i18n 检查把命令 ID 误判为界面文案 --- .agents/skills/develop-lithe/SKILL.md | 4 +- .../develop-lithe/references/logging.md | 297 +++++++++--------- desktop/internal/webpreview/webpreview.go | 6 +- desktop/internal/workbench/app.go | 4 +- desktop/internal/workbench/filetree.go | 2 +- desktop/internal/workbench/plugincontent.go | 2 +- desktop/internal/workbench/pluginsemantics.go | 2 +- desktop/internal/workbench/recent_files.go | 2 +- .../workbench/settings_publication.go | 2 +- desktop/internal/workbench/shell_view.go | 18 +- desktop/internal/workbench/updates.go | 2 +- .../workbench/workbench_background.go | 4 +- scripts/desktop/build-desktop-core.sh | 10 +- 13 files changed, 185 insertions(+), 170 deletions(-) diff --git a/.agents/skills/develop-lithe/SKILL.md b/.agents/skills/develop-lithe/SKILL.md index ad31eefefb..b2d253f22b 100644 --- a/.agents/skills/develop-lithe/SKILL.md +++ b/.agents/skills/develop-lithe/SKILL.md @@ -32,7 +32,7 @@ description: 在 Lithe 仓库进行实现、重构、缺陷修复、审查、调 4. **难以理解的配置和功能必须用 ⓘ 解释。**(第五节“用 ⓘ 解释”) 5. **用户可修改的配置不得只显示“自动”**,必须显示为“自动(实际生效值)”。(第五节“显示实际生效值”) 6. **发现无用代码或可重构之处,提交 `refactor` Issue**,不在当前 PR 中顺手处理。(第九节) -7. **警告、错误和被丢弃的失败必须走日志。** 显示给用户的警告和错误、功能降级、回退、自动恢复、重试耗尽和被丢弃的错误,都必须在处理边界记录一条目录事件;只有封闭清单里的例外可以不记录,并且必须写 `// log-exempt: <类别>:<原因>`。日志用法门禁没有存量额度,任何违规都直接失败;新增的 `logSink` 参数必须在每个生产构造处传入真实 sink。([日志接入](references/logging.md)) +7. **警告、错误和被丢弃的失败必须走日志。** 显示给用户的警告和错误、功能降级、回退、自动恢复、重试耗尽和被丢弃的错误,都必须在处理边界记录一条目录事件;只有封闭清单里的例外可以不记录,并且必须写 `// log-exempt: <类别>:<原因>`。事件只用 Core 目录里声明的,事件 ID、级别和字段键写成常量,由目录测试校验;新增的记录回调必须在每个生产构造处接上真实实现。([日志接入](references/logging.md)) 8. **插件的内容只在插件仓库,宿主对具体插件零依赖。** 插件的代码、测试(包括端到端测试)、功能矩阵、界面文案翻译和构建资源说明只在该插件的仓库维护;本仓库和 Core 仓库的代码、测试、CI、功能矩阵和 i18n 词条不得依赖或收录任何具体插件。(第三节“插件归属与宿主零依赖”) ## 二、开始前:按任务读取资料 @@ -400,7 +400,7 @@ macOS app bundle 和 Windows 安装目录是发行基线。Sparkle 增量更新 ### 显式处理失败 -- 不得静默吞掉错误。在有足够上下文的层返回、转换或记录错误;丢弃错误的写法(`try?`、只有 `return`/`break`/`continue` 的 `catch`、`.ok();`、`let _ =`)必须记录目录事件,或属于[日志接入](references/logging.md)第二节的例外并写豁免标记。 +- 不得静默吞掉错误。在有足够上下文的层返回、转换或记录错误;丢弃错误的写法(Go 的 `_ =`、只有 `return`/`continue`/`break` 的 `if err != nil`;Rust Core 的 `.ok();`、`let _ =`)必须记录目录事件,或属于[日志接入](references/logging.md)第二节的例外并写豁免标记。 - 跨 Rust、Swift、TypeScript、Tauri 或进程边界时,保留稳定的契约错误分类。 - 面向用户的失败信息必须告诉用户可以怎么做,不得泄漏凭据、环境变量内容或不必要的内部细节。 - 注释解释不明显的约束和取舍,不复述代码的执行过程。 diff --git a/.agents/skills/develop-lithe/references/logging.md b/.agents/skills/develop-lithe/references/logging.md index d2ca1ea166..bddf7462d9 100644 --- a/.agents/skills/develop-lithe/references/logging.md +++ b/.agents/skills/develop-lithe/references/logging.md @@ -3,14 +3,10 @@ 新增、迁移或审查日志事件、写入器、诊断采集、界面警告、用户操作入口,以及任何丢弃错误的代码时遵守本页。通用规则见 [Lithe 开发规范](../SKILL.md);路径均相对于仓库根目录。 -事件声明、字段编码、限额和 Core 事件队列以固定修订的 [Lithe-core-rust 日志目录说明](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/0ffd327b4329261e393b08ed76fbd134b4dd17e9/shared/logging/README.md) 为规则来源。本页规定什么必须记录、怎样设计一条日志、执行轨迹怎样接入,以及豁免和审查动作,不另列一套会漂移的语法或参数表。 - -> Viva 迁移状态:本仓库已移除旧 `shared/logging/`、Swift/Tauri 实现和 `scripts/logging/`; -> 事件目录现在位于固定 Core 仓库,Viva 经 `desktop/internal/core/logging.go` 和 -> `desktop/internal/logstore/` 接线。下文旧客户端与旧脚本名称保留为历史约束,不能直接 -> 作为当前命令或验收证据;等价生成及使用门禁未恢复前,相关检查必须标为未完成, -> 不得静默跳过。恢复 Viva 类型生成与使用门禁跟踪 -> [#1802](https://github.com/1lck/Lithe-IDEA/issues/1802)。日志事实、隐私、失败处理和目录一致性的要求不变。 +事件声明、通道模板、字段编码、限额、Core 事件队列和 Core 执行轨迹的规则来源是 Rust Core 的 +`rust/logging/README.md`,以 `scripts/desktop/build-desktop-core.sh` 的 `PINNED_CORE_REVISION` 固定的修订为准; +本地读 `scripts/desktop/desktop-go.sh` 链接的 Core 检出(`LITHE_CORE_RUST_DIR`)里的同一文件。本页规定桌面端 +(`desktop/`,Go)什么必须记录、怎样设计一条日志、执行轨迹怎样接入,以及豁免和审查动作;不另列一套会漂移的语法或参数表。 判断一次失败是否要记录,只问一个问题:**这次失败有没有丢掉数据、能力或清理结果。** 丢了就记录;什么也没丢、只是目标本来就不在了,就属于第二节的例外。 @@ -18,128 +14,129 @@ ## 一、必须记录的情形 -下表中的情形必须记录一条目录事件。失败类情形在处理边界记录;处理边界是决定重试、降级、回退、放弃或告知用户的那一层,不是抛出错误的最底层。 +下表中的情形必须记录一条目录事件。失败类情形在处理边界记录;处理边界是决定重试、降级、回退、放弃或告知用户的那一层,不是返回错误的最底层。 | 情形 | 级别 | 要求 | | --- | --- | --- | -| 用户从菜单、快捷键、命令面板、工具栏、按钮、右键菜单、通知动作或插件动作发起操作 | INFO | 最外层入口用 `UserActionTrace` 记录一次 `app.action.performed`,它的 op 贯穿后续的 Core 请求和外部进程(第七节)。 | -| 每个 Core 请求、Core 启动的每个外部进程 | 用户来源成功为 INFO,其余成功或取消为 DEBUG,失败为 WARN | Core 在请求分发处和进程执行点各记录一条终态(第七节);宿主和领域代码不再为同一请求或进程另记一条。 | -| 操作最终失败,用户的请求没有完成 | ERROR | 在拥有处理决定的边界记录一次;成对操作由 span 的 fail 记录。失败的全部事实已经在同一 op 的 Core 失败轨迹里时,不另记,界面提示引用那条轨迹(第七节)。 | -| 显示给用户的错误:横幅、弹窗、通知、行内错误、状态栏错误 | ERROR 或 WARN(按处理结果) | 与提示出自同一边界、同一 op;提示文案走 i18n,事件消息是英文事实,两者分开维护。提示的事实已在同一 op 的 Core 失败轨迹里时,提示引用那条轨迹。 | -| 显示给用户的警告 | WARN | 同上。只有界面提示、没有日志的警告不得合入。 | -| 功能降级、回退到备用路径、使用缓存或默认值代替失败的读取 | WARN | 记录降级原因的结构化分类和降级后的状态。 | -| 失败后自动恢复,或重试后成功 | WARN | 记录尝试次数和最终结果;不要逐次记录每一次重试。 | +| 用户从菜单、快捷键、命令面板、标题栏、按钮、右键菜单、通知、插件动作或拖放发起操作 | INFO | 最外层入口调用 `performed` 记录一次 `app.action.performed`,它开始的 op 贯穿后续的宿主记录、Core 请求和外部进程(第七节)。 | +| 每个 Core 请求、Core 启动的每个 Git 进程 | 用户来源成功为 INFO,其余成功或取消为 DEBUG,失败为 WARN | Core 在请求分发处和进程执行点各记录一条终态(第七节);宿主不为同一请求或进程另记一条。 | +| 用户请求的操作或用户依赖的功能没有完成 | ERROR | 在拥有处理决定的边界用 `operationFailed` 记录一次 `app.notification.operation_failed`,与提示出自同一 op。 | +| 宿主在执行前拒绝了用户的操作并告知原因(对象已不在、结果已过期、不支持) | WARN | `operationRejected` 记录 `app.notification.operation_rejected`,`reason` 是固定 token。 | +| 窗口自己运行的后台工作失败,宿主降级、回退或使用缓存与默认值继续 | WARN | `backgroundFailed` 记录 `app.background.operation_failed`;不得用 `operationFailed` 把后台降级记成 ERROR。 | +| 显示给用户的错误和警告:通知、弹窗、行内错误、状态栏错误 | 按处理结果 ERROR 或 WARN | 与提示出自同一边界、同一 op。提示文案走 i18n,事件消息是目录里的英文事实,两者分开维护。只有界面提示、没有日志的警告和错误不得合入。 | +| 失败后自动恢复,或重试后成功 | WARN | 记录尝试次数和最终结果;不逐次记录每一次重试。 | | 重试耗尽后放弃 | 用户受影响时 ERROR,否则 WARN | 一条终态,带尝试次数和最后一次错误。 | | 清理、关闭、终止失败,留下了残留(文件、目录、仍在运行的进程、未释放的远端资源) | WARN | 记录阶段和稳定错误类别。超时后仍未退出的进程可能成为孤儿进程,必须记录。 | -| 丢弃错误的写法(`try?`、只有 `return`/`break`/`continue` 的 `catch`、`.ok();`、`let _ =`) | 按上面各行判断 | 记录事件,或者属于第二节的例外并写豁免标记。 | -| 上游组件报告的警告和错误(LSP `window/logMessage`、插件宿主消息、子进程 stderr) | 按上游严重度映射 | 进入该组件已有的通道,不另建自由文本通道。 | +| 丢弃错误的写法(`_ =`、`_, _ =`、只有 `return`/`continue`/`break` 的 `if err != nil`、只检查不使用的错误) | 按上面各行判断 | 记录事件,或者属于第二节的例外并写豁免标记。 | +| 上游组件报告的警告和错误(LSP `window/logMessage`、语言服务器 stderr、插件会话事件) | 按上游严重度映射 | 由 Core 映射为目录事实,宿主按 7.8 转发,不另建自由文本通道。 | | 生命周期里程碑和有排障价值的操作终态 | INFO | 只记里程碑和终态,不记每个内部步骤。 | -“用户受影响”按处理后的结果判断:内部重试后成功记 WARN,最终没有完成用户请求记 ERROR。不得把上游的 ERROR 标签机械地升级成产品 ERROR,也不得用 INFO 掩盖真正的失败。Core 轨迹的失败固定为 WARN,原因见第七节。 +“用户受影响”按处理后的结果判断:内部重试后成功记 WARN,最终没有完成用户请求记 ERROR。不得把上游的 ERROR 标签机械地升级成产品 ERROR,也不得用 INFO 掩盖真正的失败。Core 轨迹的失败固定为 WARN,原因见 7.6。 -日志写入器自身的失败(写盘、轮转、句柄关闭、队列溢出)不能经过它自己记录。写入器把这类失败计入自身的失败和丢弃计数,导出诊断包时写进 `collection-status.txt`;不得为此另开 NSLog、stderr 或第二个写入器。 +日志写入器自身的失败(写盘、轮转、句柄关闭、队列溢出)不能经过它自己记录。写入器把这类失败计入 `Stats()` 的丢弃和写入失败计数,导出诊断包时写进 `collection-status.txt`;不得为此另开 stderr、`log`/`slog` 或第二个写入器。 ## 二、不记录的例外 只有以下四类可以不记录。例外是封闭清单,不得自行扩充;需要新类别时先修改本页并说明理由。 -1. **用户取消。** `CancellationError`、`CocoaError(.userCancelled)` 等由用户或调用方主动取消的结果不是失败。取消之后的清理如果失败,清理失败仍然按第一节判断。Core 轨迹把取消记成带 `cancelled` 的成功终态,不记成失败。 +1. **用户取消。** `context.Canceled`、`app.ErrCanceled`(原生选择器被关闭)等由用户或调用方主动取消的结果不是失败;关闭项目、关闭窗口、新输入取代旧请求结束的 context 也属于取消。`context.DeadlineExceeded` 是超时,不是取消,必须记录。取消之后的清理如果失败,清理失败仍然按第一节判断。Core 轨迹把取消记成带 `cancelled` 的成功终态,不记成失败。 2. **预期的缺失。** 目标本来就不在,调用方按“没有”处理,并且这正是正常路径。包括两种情况: - - 探测可选的文件、配置、缓存或功能时目标不存在。 - - 收尾时操作的对象已经不在:对端已经断开、子进程已经退出、连接已经关闭、要删除的文件已经不存在。典型错误类别是 `NotConnected`、`BrokenPipe`、`ConnectionReset`、`ConnectionAborted`、`UnexpectedEof`、`NotFound`,以及对已退出进程的 kill。 + - 探测可选的文件、配置、缓存或功能时目标不存在(`fs.ErrNotExist`、`os.ErrNotExist`)。 + - 收尾时操作的对象已经不在:对端已经断开、子进程已经退出、连接已经关闭、要删除的文件已经不存在。典型错误是 `io.EOF`、`net.ErrClosed`、`os.ErrProcessDone`、`syscall.EPIPE`、`syscall.ECONNRESET`、`fs.ErrNotExist`。 只有这些类别属于缺失。权限不足、格式损坏、读到一半失败、超时后对象仍然存在,都不属于缺失,必须记录。 3. **随输入实时重算的校验提示。** 表单里随键入即时更新、不阻断已经发生的操作、不反映系统状态的提示(例如“名称不能为空”)。提交后真正失败的操作仍然必须记录。 -4. **同一次失败已经记录过。** 下层处理边界、同一操作的 span fail、同一 op 的 Core 请求或进程轨迹,或同一代码路径上导致这次收尾的那次失败已经记录过。不得再记录一次,见第六节。 +4. **同一次失败已经记录过。** 下层处理边界、同一 op 的 Core 请求或进程轨迹,或同一代码路径上导致这次收尾的那次失败已经记录过。不得再记录一次,见第六节。 -按错误类别判断例外时,在一个辅助函数里集中过滤:只放过上面列出的类别,其余类别照常记录。不要在每个调用点复制一份 match,也不要因为“收尾失败通常无害”把整个调用点豁免掉。拿不到错误类别、确实无法区分正常收尾和异常时,才整体豁免,并在原因里写明为什么无法区分。 +按错误类别判断例外时,用 `errors.Is` 在一个辅助函数里集中过滤:只放过上面列出的类别,其余类别照常记录。不要在每个调用点复制一份判断,也不要因为“收尾失败通常无害”把整个调用点豁免掉。拿不到错误类别、确实无法区分正常收尾和异常时,才整体豁免,并在原因里写明为什么无法区分。 -门禁会标记的写法属于以上例外时,在同一行或紧邻的上一行写豁免标记,标记写明例外类别和具体原因: +属于以上例外时,在同一行或紧邻的上一行写豁免标记,类别必须逐字取上面四类的名称,后面写具体原因: -```swift -// log-exempt: 预期的缺失:可选的项目级 .editorconfig 不存在时使用默认值 -let override = try? fileStorage.read(projectRoot.appending(path: ".editorconfig")) +```go +// log-exempt: 预期的缺失:缺失的配置文件是未覆盖的空来源。 +if errors.Is(err, fs.ErrNotExist) { + return nil, nil +} ``` -```rust -// log-exempt: 预期的缺失:对端已经断开,连接无需再关闭 -let _ = stream.shutdown(Shutdown::Both); +```go +// log-exempt: 用户取消:关闭原生文件选择器不修改草稿。 +if errors.Is(err, app.ErrCanceled) { + return +} ``` -原因要写清楚是什么已经不在了或者为什么不是失败。“不重要”“忽略”“暂时”“旧代码”不是原因。豁免标记只用于丢弃错误的规则,不能豁免 NSLog、stderr、`print` 等绕过统一入口的写法,那类永久例外写进 allowlist(第十节)。 +原因要写清楚是什么已经不在了或者为什么不是失败。“不重要”“忽略”“暂时”“旧代码”不是原因。豁免标记只用于丢弃错误;绕过写入器的输出没有豁免方式(第十节)。 ## 三、如何设计一条日志 按以下顺序设计,每一步的答案都要能写进事件声明或代码审查说明。 1. **先写下读者的问题。** 维护者拿到用户附在 Issue 里的诊断包时,要靠这条日志回答什么问题?例如“Git fetch 为什么失败、失败在哪个远程、用了多久”。回答不了具体问题的日志不要加。先查第七节的执行轨迹是否已经回答了这个问题;已经回答的不要再加。 -2. **确定事实和终态。** 一条事件描述一个已经发生的事实,事件 ID 的结果词用过去时(`fetch_failed`、`index_degraded`)。成对操作用 span,只产生一条带耗时的终态。 -3. **确定 owner 和通道。** owner 是拥有这次操作结果的模块;通道由目录模板和已校验的身份决定(`lsp/{server}`、`vcs/{provider}`、`plugins/{plugin}/host`),不按显示名称、路径或用户输入分通道。 +2. **确定事实和终态。** 一条事件描述一个已经发生的事实,事件 ID 的结果词用过去时(`start_failed`、`operation_failed`)。一个操作只产生一条终态。 +3. **确定 owner 和通道。** owner 是拥有这次操作结果的模块;通道由目录模板和已校验的身份决定(`lsp/{server}`、`vcs/{provider}`、`plugins/{plugin}/host`),不按显示名称、路径或用户输入分通道。宿主不传通道,Core 按模板推导。 4. **按处理后的影响选级别。** 用第一节的表,不按“看起来严重”选级别。 -5. **选最窄的字段类型。** 计数、耗时、体积用数值;阶段和结果用受控 token;失败用 `error` 保留稳定 code 和 domain。不把结构化信息拼进消息(第八节)。 -6. **用 op 串起同一操作。** 用户入口由 `UserActionTrace` 生成 op,Core 请求和外部进程沿用它;其他有实际操作上下文的事件传同一个 `operationID`。用户在日志窗口里选中一行,能看到同一 op 的全部记录及相对耗时;每层重新生成编号会切断这条链。 -7. **控制频率。** 循环、逐按键、逐帧、逐连接路径不用 INFO 逐项记录;需要时用 DEBUG 或在发送侧有界汇总,并按目录声明 rate。高频 Core 方法列入 `is_hot`(第七节)。 -8. **在日志窗口里验证。** 触发一次真实场景,在日志窗口(⌘⇧L)中按通道和事件过滤能找到这条记录,字段齐全、没有敏感内容,同一 op 的调用链完整。界面提示带“查看日志”时,点击能定位到这条记录。 +5. **选最窄的字段类型。** 计数、耗时、体积用数值;阶段和结果用受控 token;失败用 `core.LogErrorFields(err)` 保留稳定 code 和 domain。不把结构化信息拼进消息(第八节)。 +6. **用 op 串起同一操作。** 用户入口由 `performed` 生成 op,宿主记录、Core 请求和外部进程沿用它。用户在日志窗口里按 op 过滤,能看到同一操作的全部记录及相对耗时;每层重新生成编号会切断这条链。 +7. **控制频率。** 循环、逐按键、逐帧、逐连接路径不用 INFO 逐项记录;需要时用 DEBUG 或在发送侧有界汇总,并按目录声明 rate。高频 Core 方法列入 `is_hot`(7.3)。 +8. **在日志窗口里验证。** 触发一次真实场景,在日志窗口(⇧⌘L)中按通道和事件过滤能找到这条记录,字段齐全、没有敏感内容,同一 op 的调用链完整。错误通知带“查看日志”时,点击能打开这个 op 的记录。 反例与正例: | 反例 | 问题 | 正例 | | --- | --- | --- | -| `catch { return nil }` | 失败被吞掉,诊断包里没有任何痕迹 | 在处理边界记录 `*.load_failed`(WARN,带 `error`),再返回降级值 | -| 横幅显示“同步失败”,没有日志 | 用户报告问题时无从排查 | 横幅的“查看日志”引用同一 op 的 `vcs.git.command.failed`;宿主有降级、放弃等额外事实时,再在同一边界记录自己的终态 | -| 消息 `"fetch origin failed: \(error)"` | 结构化信息拼进消息,未经字段脱敏 | 消息模板 `Fetch failed`,字段 `remote`(token)、`error`(error)、`duration` | -| 适配器、服务和视图各记录一次同一个失败 | 一次失败出现三次,计数失真 | 适配器返回结构化错误,服务决定降级时记录一次 | -| Swift 在调用 Core 前后各记一条“开始执行 git fetch”“git fetch 失败” | 与 Core 的进程轨迹重复,且拿不到真实的 argv、退出码和 stderr | 不写;Core 在执行点记录 `vcs.git.command.*`,宿主只引用 | -| 重试循环里每次失败都记 WARN | 噪声淹没真正的终态 | 一条终态带 `attempts` 和最后一次 `error` | -| 关闭连接、终止子进程、取消请求时,所有失败一律记 WARN | 正常关闭每天都会触发,日志窗口被假警告刷满,真正的残留反而看不见 | 辅助函数按错误类别过滤:对象已经不在的类别写豁免,权限不足、超时后仍在运行等类别记录 | -| 新增 `logSink: (any LogSink)? = nil` 参数,生产构造不传 | 代码看似记录了,生产环境里事件全部丢失 | 组合根把真实 sink 一路传到构造处,测试替身才使用 `nil` | -| 按钮回调里用 `Task.detached` 或 `DispatchQueue.main.async` 执行动作 | 丢掉用户操作上下文,Core 请求没有 `trigger` 和 op,看不出是哪个按钮触发的 | 用 `UserActionContext.detached` 或 `UserActionContext.mainAsync` | - -## 四、只使用目录生成的事件 +| `if err != nil { return nil }` | 失败被吞掉,诊断包里没有任何痕迹 | 在处理边界用 `backgroundFailed` 或领域事件记录,再返回降级值 | +| 通知显示“同步失败”,没有日志 | 用户报告问题时无从排查 | 同一边界、同一 op 记录 `operationFailed`;通知的“查看日志”打开这个 op,Core 的请求和 Git 进程轨迹一起出现 | +| `fmt.Sprintf("fetch %s failed: %v", remote, err)` 作为字段或消息 | 结构化信息拼进文本,未经字段脱敏 | 事件 ID 和消息来自目录,字段 `remote`(token)、`core.LogErrorFields(err)`、`_ms` | +| `event := "app." + kind + ".failed"` 再传给 `emit` | 事件 ID 不是常量,目录测试读不出它,拼错的 ID 只在运行时被拒绝 | 每个分支写常量事件 ID;确实由上游在运行时选择事件的转发函数列入 `forwardedLogEvents`(第十节) | +| 适配器、服务和视图各记录一次同一个失败 | 一次失败出现三次,计数失真 | 下层返回带类别的错误,决定降级或告知用户的那一层记录一次 | +| 宿主在调用 Core 前后各记一条“开始执行 git fetch”“git fetch 失败” | 与 Core 的进程轨迹重复,且拿不到真实的 argv、退出码和 stderr | 不写;Core 在执行点记录 `vcs.git.command.*`,宿主只记自己掌握的结果 | +| 重试循环里每次失败都记 WARN | 噪声淹没真正的终态 | 一条终态带 `attempts` 和最后一次错误 | +| 关闭连接、终止子进程、取消请求时,所有失败一律记 WARN | 正常关闭每天都会触发,真正的残留反而看不见 | 辅助函数按错误类别过滤:对象已经不在的类别写豁免,权限不足、超时后仍在运行等类别记录 | +| 用户操作里直接 `go func() { … }()` 调 Core | 新 goroutine 不带操作上下文,Core 请求没有 `trigger` 和 op,结果也不在原操作下应用 | 用 `a.background(p, timeout, work)`;必须自己起 goroutine 时传 `a.operationContext(ctx)`,结果经 `a.post` 回窗口线程并由 `within` 恢复 op | +| 后台降级用 `operationFailed` | 把用户没有请求的工作记成 ERROR,用户可见失败的计数失真 | 用 `backgroundFailed` | + +## 四、只使用目录里的事件 1. 先调查真实调用和消费者,确定 owner、通道身份与需要保留的事实;没有实际来源不预造事件。 -2. 新增事件先修改固定 Core 修订中的 `rust/logging/events/.json`,按共享 README 声明稳定 ID、通道模板、英文消息、级别和字段含义。字段说明必须解释本事件中的来源、语义和单位,不能用按类型的通用短语凑说明。 -3. 旧 `scripts/logging/generate-log-events.mjs` 已移除;修改事件目录前须恢复等价生成与校验入口,审查 Rust 静态目录及 Viva 消费者。不得手改生成的目录以绕过声明。 -4. 调用生成的事件类型与 span,把类型化输入交给统一日志入口;Rust 使用生成目录和共享边界。Viva 的等价类型生成及门禁尚待恢复,不能把旧 Swift 生成类型当作 Go 已接入。不得手写事件 ID、自由消息或字段字典来规避目录声明,不得自行实现序列化或脱敏。 +2. 新增或修改事件在 Rust Core 仓库修改 `rust/logging/events/.json`,按 Core README 声明稳定 ID、通道模板、英文消息、级别和字段含义。字段说明必须解释本事件中的来源、语义和单位,不能用按类型的通用短语凑说明。 +3. 在 Core 仓库根运行 `node scripts/logging/generate-log-events.mjs` 重新生成 `catalog_generated.rs`,并用 `--check` 确认生成物一致;不得手改生成物。Core 改动合入后,把 `PINNED_CORE_REVISION` 升到包含它的 main commit,桌面端调用点与固定的目录同一个 PR 生效。 +4. 桌面端调用时,事件 ID、级别和字段键必须是常量或在源码里可读出的值,由目录测试逐条交给链接的 Core 校验(第十节)。Go 还没有按目录生成的事件类型,恢复跟踪 [#1802](https://github.com/1lck/Lithe-IDEA/issues/1802)。不得手写第二份目录、自由消息或私有序列化与脱敏。 5. 不再有调用点的事件,从目录声明中删除并重新生成,不保留空事件。 -生成事件是尚未脱敏的内存输入。落盘必须经过 Core 的目录字段校验、共享脱敏和编码;只通过类型检查或通用编码器不能证明隐私安全。日志路径由平台可写存储适配器提供,不从 bundle、插件安装目录或 Windows 安装目录推导。 +宿主传入的事件是尚未脱敏的内存输入。落盘必须经过写入器调用的 `diagnostics.encodeLogBatch`(`validateCatalog: true`)完成目录校验、共享脱敏和编码;只通过 Go 的类型检查或 JSON 编码不能证明隐私安全。日志目录由平台可写存储提供,不从 app bundle、插件安装目录或 Windows 安装目录推导。 -## 五、sink 注入 +## 五、写入器与记录入口 -每个进程只有一个日志写入器。macOS 的写入器由组合根创建,Rust 侧的记录最终都交给这个写入器。各层通过以下途径拿到入口: +每个进程只有一个日志写入器 `desktop/internal/logstore.Store`。`cmd/lithe/main.go` 用 `logstore.Open` 创建它,调用 `ObserveCoreFacts` 安装 Core 唤醒回调,再经 `workbench.DesktopOptions.Logs` 交给窗口;退出时 `Close` 排空并写完队列。写入器打不开时客户端照常启动,没有日志窗口,“查看日志”只提示日志不可用。 -| 位置 | 获取方式 | +| 位置 | 记录方式 | | --- | --- | -| macOS 服务、适配器、平台实现 | 构造参数,由 `MacServiceContainer` 或上层构造者传入 | -| macOS 应用服务集合 | `AppServices.logSink` | -| macOS 功能模块 | 激活时的 `ModuleContext.logSink` | -| SwiftUI 视图 | 环境值 `applicationLogSink` | -| 没有服务容器的用户操作入口(AppKit 菜单、通知动作) | `UserActionTrace.applicationSink`,启动时安装一次;测试传入自己的 sink | -| Swift 侧的 Rust Core 桥接 | `RustCoreBridge.coreLogSink` | -| Rust Core 的请求处理 | 请求事件流携带的目录事件 | -| Rust Core 的执行轨迹和没有请求上下文的代码(析构、后台清理) | `lithe_diagnostics::core_events` 进程级有界队列;宿主在写入批次、flush 和退出时排空,Core 唤醒回调再安排一次排空 | -| 链接进 Core 的辅助 crate(git-host、ide-host、lithe-remote 客户端) | 本 crate 的 `failure_log` 模块;sink 由 Core 的 `runtime::helper_failures::install()` 注入 | +| 窗口线程上的工作台代码 | `a.emit(level, event, fields)`,op 取当前用户操作 `a.op` | +| 其他 goroutine 上为某个操作工作的代码(设置窗口、后台任务) | `a.emitIn(ctx, …)`,op 取 `core.OriginOf(ctx).Operation` | +| 已知 op 的代码 | `a.emitAs(op, …)`;op 为空表示不属于任何操作 | +| 用户可见失败、拒绝、后台降级 | `operationFailed`/`operationFailedIn`、`operationRejected`/`operationRejectedIn`、`backgroundFailed`/`backgroundFailedIn` | +| 不持有写入器的包(`webpreview`、`pluginweb`、`termview`、`pluginservice`) | 把失败交给工作台提供的回调(`Log func(stage string, err error)`、`Failed func(Failure)`、`RecordFailed`),由工作台在处理边界记录;包自己不写日志、不回退到 stderr | +| 日志窗口自己的失败(导出等) | `logwindow.Source.Emit`,即同一个写入器 | +| Core 引擎随插件会话事件带来的目录事实 | `recordEngineFact`(7.8) | +| Core 请求处理、执行轨迹和没有请求上下文的 Core 代码 | Core 的进程级有界事件队列;写入器在每次写入批次、flush 和关闭时排空,唤醒回调再安排一次排空(7.7) | +| 链接进 Core 的辅助 crate | 本 crate 的 `failure_log` 模块,sink 由 Core 的 `runtime::helper_failures::install()` 注入;规则见 Core README | 规则: -- 给类型新增 `logSink` 参数时,同一次改动必须把真实 sink 传到每个生产构造处,包括默认参数里隐式构造的下层对象。`= nil` 默认值只为测试替身保留;生产路径依赖默认值等于没有记录。 -- 不得新增全局可变日志单例,不得在下层自行创建写入器。辅助 crate 的 `failure_log` 和 `UserActionTrace.applicationSink` 是仅有的进程级入口:前者只保存 Core 注入的函数指针,后者只引用组合根创建的写入器,都不写文件。 -- 辅助 crate 不依赖 Core(依赖方向相反,会形成循环),只通过 `failure_log` 交出事件 ID 和标量字段;事件仍在共享目录中以 `lithe-core` 为 owner 声明,由 Core 校验、脱敏后入队。 -- sink 尚未注入时,辅助 crate 只累加未注入计数,不回退到 stderr 或其他输出。新增会调用辅助 crate 的 Core 入口(FFI 函数、独立进程入口)时,必须在入口处调用 `helper_failures::install()`,否则这条路径上的事件全部丢失。 -- sink 注入前就可能失败的 macOS 代码(启动早期的设置解码、配置迁移)有界缓存类型化事件,注入后一次性补发;不得另建自由字符串通道,也不得无界缓存。 -- `LogScope` 携带同一操作的 op 和可信身份,目录决定通道。路径传 URL,错误传 Error,不先拼成字符串。 - -macOS 的日志窗口和诊断包只读取 v2 会话文件;v1 文件只进入保留清单,按 30 天自然过期。Rust 的 v1 API 和旧命令继续供 Windows 使用,不得改变其输出。 +- 不得新增全局可变日志单例,不得在下层自行创建写入器,不得用 `log`、`slog`、`fmt.Fprint(os.Stderr, …)` 或 `println` 输出诊断。 +- 新增构造参数、回调或接口字段用于记录失败时,同一次改动把真实实现接到每个生产构造处。`nil` 只能出现在测试里;生产路径留空等于没有记录。 +- 写入器同时实现 `logwindow.Source`:日志窗口和诊断包只读取 v2 会话文件,没有 v1 缓冲。 +- 被目录拒绝的事件不会落盘:写入器按事件和错误码计入 `Rejections()`,日志窗口显示被拒事件,诊断包的 `collection-status.txt` 写出 `rejected event=… code=… count=…`。出现被拒事件就是调用点和目录不一致,必须修调用点或目录。 ## 六、一个操作、一条终态、一个错误处理边界 -- 成对操作使用生成的 span,由一个调用方拥有。成功调用一次 finish,失败调用一次 fail,生成一条带耗时的终态;不要再手工补“结束”记录。begin 总会产生一条 DEBUG 级别的 started,是否落盘由写入端按级别和详细诊断通道过滤。 -- 不复制 span 来产生多份生命周期,不用墙钟差值计算耗时。跨异步边界保留同一个操作所有者和单调计时上下文。 -- 有实际操作上下文时传 `operationID`,持久化层用 `op` 关联跨模块证据。不得把 op 重新声明为普通字段,不得用用户内容作为操作编号。 -- 错误只在处理它的边界记录一次。下层把错误和稳定分类返回;上层决定恢复、降级或告知用户时记录。不得“记录后再抛出”;span 的 fail 已经记录该操作失败时,不再额外写相同错误。 +- 一个操作只有一条终态。不要在开始时记一条、结束时再记一条;需要耗时时在目录里给终态声明 `duration` 字段,宿主传磁盘键 `_ms`,用单调时钟(`time.Since`)计算,不用墙钟差值。 +- 目录里的 span 事件(`app.shell.environment`、`editor.sync.freeze`、`run.process.execution`)在 Go 里还没有 span 辅助,桌面端不得手工拼 begin/finish 两条记录来模拟 span;采用方式由单独的 Issue 决定。 +- 有实际操作上下文时用同一个 op,持久化层用 `op` 关联跨模块证据。不得把 op 重新声明为普通字段,不得用用户内容作为操作编号。 +- 错误只在处理它的边界记录一次。下层把错误和稳定分类返回;上层决定恢复、降级或告知用户时记录。不得“记录后再返回”。 - 一次失败引发的后续收尾失败,属于第二节第 4 类,不再单独记录。 -- Core 请求和外部进程的终态由 Core 记录,不属于任何宿主调用方。宿主只决定界面提示是否引用它,以及是否需要为自己掌握的额外事实记录一条终态(第七节)。 +- Core 请求和外部进程的终态由 Core 记录,不属于任何宿主调用方。宿主只为自己掌握的结果记录终态(7.6)。 ## 七、执行轨迹:用户操作、Core 请求与外部进程 @@ -147,125 +144,129 @@ macOS 的日志窗口和诊断包只读取 v2 会话文件;v1 文件只进入 | 层 | 事件 | 由谁记录 | 级别 | | --- | --- | --- | --- | -| 用户操作 | `app.action.performed`(通道 `app`) | 最外层 UI 入口的 `UserActionTrace` | INFO | -| Core 请求 | `app.core.request.finished` / `.traced` / `.failed`(通道 `app/core`) | Core 请求分发处 `rust/crates/core/src/runtime/dispatcher.rs`,实现在 `diagnostics/request_trace.rs` | 用户来源的成功或取消为 `finished`(INFO);后台或未知来源的成功或取消为 `traced`(DEBUG);失败为 `failed`(WARN) | +| 用户操作 | `app.action.performed`(通道 `app`) | 最外层 UI 入口的 `performed` 或 `performedIn` | INFO | +| Core 请求 | `app.core.request.finished` / `.traced` / `.failed`(通道 `app/core`) | Core 请求分发处 `rust/crates/core/src/runtime/dispatcher.rs`,实现在 `rust/crates/core/src/runtime/request_trace.rs` | 用户来源的成功或取消为 `finished`(INFO);后台或未知来源的成功或取消为 `traced`(DEBUG);失败为 `failed`(WARN) | | 外部进程 | `vcs.git.command.finished` / `.traced` / `.failed`(通道 `vcs/git`) | Core 的 Git 进程执行点 `rust/crates/git/src/command_trace.rs`,本地和远程工作区都经过这里 | 来源为用户的可见命令(定义见 7.4),成功或取消为 `finished`(INFO);其余成功或取消为 `traced`(DEBUG);失败为 `failed`(WARN) | ### 7.1 用户操作入口 -- 每个用户入口在最外层调用 `UserActionTrace.run(_:surface:sink:_:)`;SwiftUI 控件直接调用模型方法时用 `UserActionTrace.action(_:surface:_:)` 包装回调。它记录一条 `app.action.performed`,并把 `UserAction`(id、surface、op、开始时间)绑定到 `UserActionContext.current`,供后续请求继承。 -- 嵌套调用既不记录也不重新绑定,外层 id 生效。因此在共用的模型方法上再包一层是安全的,但入口必须包在最外层:例如 `GitFeatureModel.withGitOperation` 为每个 Git 操作生成 `vcs.git.<方法名>`,菜单或按钮先包了自己的 id 时以菜单或按钮为准。 -- id 是稳定的 catalog token:1 到 64 字节,字符为 ASCII 字母数字和 `._:/-$`,不合规时记为 `invalid`。不得使用本地化标题、文件名、分支名或任何用户内容。命名按 `<领域>.<对象>.<动作>`,例如 `workspace.remote.test`、`run.panel.stop`、`build.task.run`;主菜单用固定 id(`open-project`、`show-logs`);右键和下拉菜单用 `menu:`,标题来自用户内容的菜单项记在所属子菜单的 id 下,菜单项声明了 `actionID` 时用它;插件动作用 `plugin:/`;通知动作用通知声明的动作 id。 -- surface 取 `UserActionSurface` 的值:`menu`、`shortcut`、`palette`、`toolbar`、`button`、`context_menu`、`notification`、`plugin`,按用户实际点击的位置选。 -- 只记录用户主动发起的入口。定时刷新、文件监听、窗口恢复等自动行为不调用 `UserActionTrace`,它们的 Core 请求按后台来源记录。 +- 每个用户入口在最外层调用 `a.performed(action, surface)`(`desktop/internal/workbench/app.go`)。它生成新的 op(`core.NewOperation()`),记录一条 `app.action.performed { action, surface }`,并把操作设为窗口线程的当前操作 `a.op`。窗口回调返回时 `operating` 结束这次操作,它不会漏进下一次绘制或刷新。 +- `performed` 会覆盖当前操作,没有嵌套保护:入口只调用一次,共用的模型方法里不再调用。命令统一在 `startCommand` 记录 `command.<命令 id>`,命令的实现不再另记。 +- 在窗口线程之外由用户发起的操作(例如设置窗口)用 `ctx = a.performedIn(ctx, action, surface)`:它不碰窗口线程的 `a.op`,op 放进返回的 context,后续用 `emitIn(ctx, …)` 记录,用这个 ctx 发 Core 请求。 +- action 是稳定的 catalog token:1 到 64 字节,字符为 ASCII 字母数字和 `._:/-$`。不得使用本地化标题、文件名、分支名或任何用户内容。命名按 `<领域>.<对象>.<动作>`,例如 `build.task.run`、`debug.breakpoint.remove`、`logs.openOperation`。 +- surface 只能取 `actionSurface` 常量:`surfaceMenu`、`surfaceShortcut`、`surfacePalette`、`surfaceToolbar`、`surfaceButton`、`surfaceContextMenu`、`surfaceNotification`、`surfacePlugin`、`surfaceDragDrop`,按用户实际操作的位置选。新增 surface 先在 Core 目录的 `surface` 字段加 token。 +- 只记录用户主动发起的入口。定时刷新、文件监听、窗口恢复等自动行为不调用 `performed`,它们的 Core 请求按后台来源记录。 ### 7.2 跨越异步边界 -- `Task {}` 继承 `UserActionContext.current`;`Task.detached` 和 GCD 不继承。为用户操作服务的分离任务用 `UserActionContext.detached`,需要等菜单或弹窗收起后再执行的主线程工作用 `UserActionContext.mainAsync`。不得把 `UserAction` 存进属性留到以后使用。 -- 桥接层用 `RustCoreBridge.RequestOrigin.resolve` 给每个请求附上可选的 `origin`:Git 执行来源是后台时记 `source: background`;当前操作开始不到 60 秒时记 `source: user`、`trigger` 和 `operation`;超过 60 秒只保留 `trigger` 和 `operation`,不再声称是用户工作(例如运行会话后续的长期请求);没有当前操作时沿用已知的 Git 执行来源。 -- Core 在请求开始时把 op 和来源放进线程局部上下文,同一请求里启动的 Git 进程自动继承。op 依次取 `origin.operation`、请求的 `operationId`、请求 `id`。在其他线程上结束的轨迹(例如流式历史)必须在离开请求线程前用 `request_trace::current()` 取快照。 +- `a.background(p, timeout, work)`(`tasks.go`)是为操作启动后台工作的唯一方式:work 的 context 携带当前操作(`operationContext`),返回的结果函数回到窗口线程后由 `within` 在原操作下应用,结果里的失败因此记在引起它的操作下。p 不为空时 context 随项目关闭结束,项目关闭或替换后到达的结果被丢弃。 +- 必须自己管理 goroutine 时(流式读取、长期会话),在离开窗口线程前用 `a.operationContext(ctx)` 取上下文,goroutine 里用 `emitIn(ctx, …)` 记录,结果经 `a.post` 回窗口线程。不得把 `a.op` 存进字段留到以后使用,也不得在 goroutine 里读 `a.op`。 +- 桌面客户端为每个 Core 请求附上可选的 `origin`(`desktop/internal/core/origin.go` 的 `requestOriginOf`):ctx 不带操作且不是自动刷新时不附带;`core.AutomaticRefresh(ctx)` 标记的 Git 自动刷新记 `source: "background"`,即使由操作触发也一样,Core 因此不把它的内部查询记成用户工作;其余带操作的请求记 `source: "user"`、`trigger` 和 `operation`。 +- Core 在请求开始时把 op 和来源放进线程局部上下文,同一请求里启动的 Git 进程自动继承。op 依次取 `origin.operation`、请求的 `operationId`、请求 `id`。 ### 7.3 Core 请求轨迹 -- 每个 Core 请求在分发处记录一条终态,覆盖所有宿主、工作区、插件和按钮背后的调用。领域代码不得为“请求开始”“请求完成”另加日志。 -- 字段:`method`;请求载荷里的 `operation` 选择器(如 `git.write` 的 `fetch`);`source`;`trigger`;`path` 取载荷中第一个绝对路径的 `root`、`workspaceRoot`、`repositoryRoot`、`projectRoot`、`rootPath`、`directory` 或 `path`;`remote`;`duration`;取消时 `cancelled`,失败时 `error`(code 与 domain 为 `core`)。不记录载荷的其他内容。 -- 按键、每帧、轮询和监听批次触发的方法列入 `request_trace::is_hot`,不记录。新增这类方法时必须在同一次改动里加入列表。`diagnostics.*` 和 `core.ping` 永远不记录:日志系统不得记录自己的排空、查询和编码调用。 +- 每个 Core 请求在分发处记录一条终态,覆盖所有宿主、工作区、插件和按钮背后的调用。宿主和领域代码不得为“请求开始”“请求完成”另加日志。 +- 记录的字段、`path` 的取法和不记录载荷其他内容的规则以 Core README“执行轨迹事件”一节为准。 +- 按键、每帧、轮询和监听批次触发的方法列入 `request_trace::is_hot`,不记录。新增这类 Core 方法时必须在同一个 Core 改动里加入列表。`diagnostics.*` 和 `core.ping` 永远不记录:日志系统不得记录自己的排空、查询和编码调用。 ### 7.4 外部进程轨迹 -- Core 启动的每个 Git 进程在执行点记录一条终态,字段为 `command`、`arguments`、`repository`、`source`、`remote`、`exit_code`、`duration`,失败或非零退出时带 `stderr`,取消时带 `cancelled`,失败时带 `error`。 -- 可见命令指经 `execute_git` 执行、作为 invocation 返回给宿主并显示在 Git 控制台的命令;内部读取指 Core 经 `capture_git` 执行、自己解析输出的命令。即使在用户操作中,内部读取的成功或取消也只记 `traced`。 -- argv 只能经过 `command_trace::format_arguments` 进入日志:`-m`、`--message`、`-m…`、`--message=…` 的值换成 ``;`-c` 后键名含凭据或个人身份标记(`credential`、`token`、`password`、`user.`、`author.` 等)的值换成 ``;URL 中的用户信息和共享脱敏规则覆盖的路径与令牌被改写;结果超过 1 KiB 时在末尾截断并以 `…` 标记。不得在其他地方格式化 argv。 -- stderr 只保留进程最后 16 KiB 输出中的最后 8 个非空行,逐行脱敏后用 ` | ` 连接,超过 1 KiB 时丢弃最早的内容并以 `…` 标记。stdout、stdin 和进程环境永远不记录。 -- 结果分类:Core 返回取消错误为取消;返回其他错误为失败;退出码 0 为成功;退出码按文档表示“回答”而不是错误的(`exit_is_answer`,如 `git config --get` 的 1、`git diff --quiet` 的 1)为成功;来源不是用户的内部读取,非零退出视为成功,由调用方判断含义,调用方据此返回错误时由请求轨迹记录失败;其余为失败。Core 开始依赖某个命令的另一个文档化退出码时,在同一次改动里给 `exit_is_answer` 加一行。 +- Core 启动的每个 Git 进程在执行点记录一条终态。可见命令指作为 invocation 返回给宿主、显示在 Git 控制台的命令;内部读取指 Core 自己解析输出的命令,即使在用户操作中,内部读取的成功或取消也只记 `traced`。 +- argv 只能经过 `command_trace::format_arguments` 进入日志,stderr 只保留脱敏后的末尾几行,stdout、stdin 和进程环境永远不记录;具体的脱敏、截断和行数规则以 Core README 为准。 +- 退出码按文档表示“回答”而不是错误的(`exit_is_answer`,如 `git config --get` 的 1)为成功。Core 开始依赖某个命令的另一个文档化退出码时,在同一次改动里给 `exit_is_answer` 加一行。 - 将来为其他外部进程增加轨迹时,沿用同一模型:在执行点记录唯一终态,argv 只经过一个集中的脱敏格式化函数,stderr 只保留脱敏后的末尾几行。 -### 7.5 失败级别与宿主边界 +### 7.5 插件声明式贡献的代记 -- Core 轨迹的失败固定为 WARN:Core 不知道宿主会重试、降级还是放弃,ERROR 留给知道结果的那一层。 -- 宿主要告知用户的失败,如果事实已经全部在同一 op 的 Core 失败轨迹里,提示的“查看日志”引用这条轨迹,宿主不再记录。Git 的引用规则:有进程以非零状态退出时引用通道 `vcs/git` 的 `vcs.git.command.failed`;没有这样的进程而请求失败(参数校验、仓库不可用)时引用通道 `app/core` 的 `app.core.request.failed`;进程全部以 0 退出、只是操作结果报告失败时,Core 没有失败轨迹,不返回引用,由调用方记录自己的终态。op 都取 `GitExecutionContext.traceOperationID`。实现见 `GitService.failureReference`。 -- 宿主只在掌握 Core 没有的事实时才记录自己的终态:降级到哪条路径、重试了几次后放弃、留下了什么残留。最终没有完成用户请求时这条终态为 ERROR。 +插件声明、由宿主启动的贡献(`languageServer/start`、`debugAdapter/start`、`lithe/build/model`、`lithe/build/dependencies`),启动结果由宿主代插件记录,规则见 Core 的 `rust/contracts/rust-core-api.md`。桌面端的做法固定为: -正例与反例: +- 开始时 `attempt := core.StartPluginAttempt(pluginID, operation, core.OriginOf(ctx).Operation)`,结果记在操作的 op 下;没有合法 op 时自动生成一个。 +- 结束时调 `pluginservice.Service.EndAttempt(ctx, attempt, stage, err)`,stage 取 `plan`、`resolve`、`launch`、`initialize`、`timeout`、`exit`、`decode` 中失败所在的阶段;`err == nil` 记为完成。一次尝试最多产生一条结果,用户取消不记录,截止时间到达记为 `timeout`。 +- 语言服务器交给 Core 启动时,用 `attempt.HandOff()` 生成 `lsp.startServer` 的 `startupOperation`,之后的结果由 Core 记录,宿主不再记录。 +- Core 拒绝这条代记时,宿主用 `backgroundFailedIn(ctx, "plugin_operation_record", err)` 记录。插件经 provider 请求自己完成的操作由插件自己记录,宿主不代记。 -```swift -// 正例:GitService 把同一 op 的 Core 失败轨迹放进结果,提示直接引用它 -LogRecordReference(channel: "vcs/git", event: VcsGitCommandFailed.id, op: execution.traceOperationID) -pendingNotificationReference = result.logReference +### 7.6 失败级别与宿主边界 -// 反例:为同一次失败另声明一个宿主事件,再记一次 ERROR -sink.emit(GitFetchNoticeFailed(remote: remote, error: error, operationID: op)) -``` +- Core 轨迹的失败固定为 WARN:Core 不知道宿主会重试、降级还是放弃,ERROR 留给知道结果的那一层。 +- 宿主的 ERROR(`app.notification.operation_failed`)记录的是宿主自己的结果:用户的哪个操作没有完成。它和 Core 的失败轨迹共用 op,因此不重复 argv、退出码、stderr 这些 Core 已经记下的事实;`operation` 字段写宿主的操作 token,错误字段来自 `core.LogErrorFields(err)`。 +- 宿主只在掌握 Core 没有的事实时才多记:降级到哪条路径、重试了几次后放弃、留下了什么残留。 + +### 7.7 DEBUG 门、唤醒与详细诊断 -### 7.6 DEBUG 门与排空 +- Core 在入队前丢弃宿主没有开启的 DEBUG 事实。写入器只在详细诊断状态变化时调用 `diagnostics.configureCoreEvents { debug, roots }`;调用失败时记录一次 `app.logging.diagnostics_failed`,状态再次变化后才重试。只在宿主侧过滤会让后台 DEBUG 占满 Core 的有界队列,之后的 WARN 和 ERROR 会因此丢失。 +- Core 代码构造字段前先调用 `core_events::accepts(level, root)`,被拒绝的事实只花一次分支判断。 +- 只有应用写入器调用 `ObserveCoreFacts` 安装 Core 唤醒回调。回调只唤醒写入器,写入器合并 100 毫秒内的唤醒做一次排空;关闭时先移除回调再做最后一次排空。不得为 Core 队列增加空闲轮询定时器,也不得在响应里再加待取标记。 +- 同一个详细诊断开关经 `WatchDiagnostics` 驱动插件会话的 `lsp.setDetailedDiagnostics`:正在运行的会话和开启期间新启动的会话都跟随,15 分钟后自动关闭。拒绝切换的会话每次选择只记录一次 `app.logging.diagnostics_failed`(`traceFailed`),不论有几个会话拒绝;期间已经结束的会话不算失败。 -- Core 在入队前丢弃宿主没有开启的 DEBUG 事实:宿主通过 `diagnostics.configureCoreEvents { debug, roots }` 告诉 Core 详细诊断是否开启、开启哪些通道根,默认关闭。`MacLogStore` 在详细诊断状态变化时调用它。只在宿主侧过滤会让后台 DEBUG 占满 256 条的 Core 队列;队列满时新事实只计入丢弃数,之后的 WARN 和 ERROR 会因此丢失。 -- 构造字段前先调用 `core_events::accepts(level, root)`,被拒绝的事实只花一次分支判断。 -- 只有应用写入器调用 `MacLogStore.observeCoreFacts()` 安装 Core 唤醒回调。记录事实或增加丢弃数后,Core 在两次排空之间最多回调一次;回调只安排 100 毫秒后的单次排空,不在回调里直接排空。结束会话先移除回调再做最后一次排空。不得为 Core 队列增加空闲轮询定时器,也不得在响应信封里再加待取标记。 +### 7.8 引擎事实与插件日志目录 + +- Core 在插件会话的运行时事件上附带的目录事实(`event`、`catalogLevel`、`fields`:语言服务器的 stderr 行和 logMessage、provider 生命周期、会话退出和停止),在按事件类型分支之前由 `recordEngineFact` 原样转发一次,不属于任何用户操作。Core 已经按目录校验和脱敏,宿主不增删字段。 +- 插件进程自己的日志文件写在 `PluginFilesDirectory(ctx, pluginID)` 给出的目录:写入器在本次会话目录下创建 0700 的插件目录,逐段拒绝 `.`、`..`、符号链接和特殊文件。本地语言服务器和后端启动时把它作为 `request.logDirectory` 传给 Core,插件以 `${logDir}` 引用;目录不可用时宿主记录 `app.background.operation_failed` 并省略它,远程请求不传。 ## 八、字段选择与隐私 -选择能表达事实的最窄类型,不把结构化信息拼进 message 或自由文本: +选择能表达事实的最窄类型,不把结构化信息拼进消息或自由文本。宿主传入的是磁盘键和 JSON 值,单位与编码以 Core README 为准: | 信息 | 选择原则 | | --- | --- | -| 计数、开关、耗时、体积 | 使用 int、bool、duration、bytes,单位与编码依共享 README。 | +| 计数、开关、耗时、体积 | 整数、布尔值;耗时用 `_ms` 的整数毫秒,体积用字节数。 | | 身份、阶段、版本 | 身份用 id;受控短词用 token;版本用 version。id 必须来自已验证的真实身份,字符合法不等于来源可信。 | -| 文件位置 | 使用 path,由共享边界脱敏,不自己拼用户绝对路径。 | -| 失败 | 使用 error,保留稳定 code/domain 等结构化类别,不传未清理的整段错误转储。 | +| 文件位置 | 传原始路径,由 Core 按目录脱敏,不自己拼或改写用户绝对路径。 | +| 失败 | 用 `core.LogErrorFields(err)` 得到 `error`、`error_code`、`error_domain`,不传未清理的整段错误转储。 | | 无法结构化的上游诊断和外部进程命令行 | 仅在必须保留 stderr 行、LSP logMessage 等上游原文,或经第七节集中格式化函数脱敏的 argv 时使用 text,并在声明中写 reason 说明结构化字段为什么不能代替;“方便调试”不是理由。 | -不得记录源码、编辑缓冲区、文件内容、提交说明正文、环境变量值、进程的 stdout 与 stdin、凭据、终端历史或协议正文,也不得把它们塞进 text、error、token、路径或消息模板绕过。外部进程只通过第七节的集中格式化函数记录 argv,只记录脱敏后的 stderr 末尾几行。处理凭据的代码路径记录失败时,只记阶段和错误类别,并用测试证明凭据不会出现在事件字段里。 +不得记录源码、编辑缓冲区、文件内容、提交说明正文、环境变量值、进程的 stdout 与 stdin、凭据、终端历史或协议正文,也不得把它们塞进 text、error、token、路径或消息绕过。处理凭据的代码路径记录失败时,只记阶段和错误类别,并用测试证明凭据不会出现在事件字段里。 每个动态通道段必须能追溯到已校验的插件、provider、server 或内部连接 ID,不得使用主机名、显示名称、项目路径和任意用户输入。 ## 九、界面提示与日志的对应 -- 每个显示给用户的警告和错误都对应一条事件:第一节的宿主事件,或者同一 op 的 Core 失败轨迹。提示和事件共用同一个 op。 -- 提示需要“查看日志”时,携带日志记录引用(通道、事件,有 op 时带 op),打开日志窗口并定位到这条记录。打开日志窗口只走统一的打开请求,不为某个插件或 provider 写专门分支。 -- 插件发给宿主的消息和警告由宿主记入 `plugins/{plugin}/host` 通道,再按插件声明显示;插件不能绕过宿主写日志文件。 +- 每个显示给用户的警告和错误都对应一条事件,出自同一边界、同一 op。 +- 用户操作期间显示的错误通知记下当前 op,带“查看日志”按钮;点击记录 `logs.openOperation`(`surfaceNotification`),日志窗口打开并按这个 op 过滤,同一操作的宿主记录、Core 请求和 Git 进程轨迹一起出现。打开日志窗口只走 `showLogs(op)`,不为某个插件或 provider 写专门分支。 +- 插件发给宿主的消息和警告由宿主记入 `plugins/{plugin}/host` 通道,再按插件声明显示;插件不能绕过宿主写应用日志。 - 日志消息、事件名、通道、字段、级别名和过滤语法不翻译;提示文案、按钮和日志窗口自身的界面文字走共享 i18n。 ## 十、门禁与豁免 -`node scripts/logging/verify-log-usage.mjs` 扫描 macOS、Rust Core 和链接进 Core 的辅助 crate 的生产代码。扫描的目录和排除范围以共享 README 为准;被排除的目录必须在 README 中写明原因和后续计划。门禁没有存量额度:引入门禁时的全部存量已经迁移完毕,任何违规都直接失败。规则分两类: +桌面端现有的自动门禁是目录测试 `TestEveryLoggedEventIsAcceptedByTheKernel`(`desktop/internal/core/log_sites_test.go`): -| 类别 | 规则 | 合法的例外方式 | -| --- | --- | --- | -| 绕过统一入口 | Swift 的 `NSLog`、stderr 写入、`os_log`/`Logger`、字符串 `record(level:)`、`print`/`debugPrint`;Rust 的 `eprintln!`、`println!`、`dbg!` | 只能写进 `scripts/logging/log-usage-allowlist.json`,给出具体的协议或架构理由和精确计数 | -| 丢弃错误 | Swift 语句级 `try?`、只有 `return`/`break`/`continue` 的 `catch`;Rust 语句级 `.ok();`、`let _ =` | 记录事件;属于第二节例外时写 `// log-exempt: <类别>:<原因>`。这类规则不能进 allowlist | +- 它扫描生产代码里所有最终到达写入器 `Emit` 的调用。级别、事件 ID 和字段键必须是常量或在源码里可读出的值,否则测试失败(“the level is not a constant”“the event id is not a constant”“the field keys cannot be read from the source”“the call chain is too deep to follow”)。 +- 每个调用点按读出的事件、级别和字段键构造一条事件,交给链接的 Core 用 `diagnostics.encodeLogBatch`(`validateCatalog: true`)校验;目录里不存在的事件、级别不符或字段不符都会失败。 +- `surface` 只能取 `actionSurface` 常量,并且必须在目录的 token 列表里(`checkActionSurfaces`)。 +- 在运行时选择事件的转发函数必须列入 `forwardedLogEvents`,并写明它会转发哪些事件;不再转发的条目也会让测试失败。 -- allowlist 的计数必须等于实际出现次数。少于实际失败;多于实际同样失败,必须同步调低,防止空出来的名额被新写法占用。 -- 不得利用别名、包装函数或动态调用逃避门禁,也不得为了通过门禁放宽扫描范围或规则。 -- 迁移机器读取的性能标记等协议输出时,同步修改它的消费者,不得直接删除协议输出。 -- 门禁无法静态识别以下问题,由第二、五、七、九节和审查清单保证:界面提示没有对应日志、生产构造没有传入 sink、收尾失败没有按错误类别区分、用户入口没有 `UserActionTrace`、异步跳转丢失操作上下文。 +目录测试只保证调用点与目录一致。它识别不了以下问题,由审查保证,等价的用法门禁恢复跟踪 [#1802](https://github.com/1lck/Lithe-IDEA/issues/1802): -## 十一、验证 +- 绕过写入器的输出(`log`、`slog`、`fmt.Fprint(os.Stderr, …)`、`println`)。唯一的例外是 `cmd/lithe/main.go`:写入器打不开时和启动失败退出前写 stderr,这两处此时没有写入器可用。 +- 丢弃的错误没有记录也没有豁免标记,豁免标记的类别不属于第二节的四类。 +- 界面提示没有对应日志、用户入口没有 `performed`、异步跳转丢失操作上下文、收尾失败没有按错误类别区分。 -旧日志生成、使用扫描和对应测试脚本已从本仓库移除,恢复等价门禁后才能将其记为通过。 -修改目录、生成器或门禁本身时,还须运行直接受影响的 Core、辅助 crate 和 Viva 宿主测试; -当前 Go 桥接和存储测试不能代替缺失的目录生成及使用扫描。只读核验不能改写生成物。 +不得利用包装函数、动态拼接或反射逃避目录测试,也不得为了通过测试放宽扫描范围或规则。 -修改执行轨迹时运行对应测试:Core 请求轨迹在 `rust/crates/core/src/tests/core_request_traces.rs`,Git 进程轨迹、argv 脱敏和 `exit_is_answer` 在 `rust/crates/git/src/command_trace.rs` 的测试模块,宿主侧的入口与来源解析在 `macos/Tests/LitheTests/UserActionTraceTests.swift` 和 `macos/Tests/LitheTests/CoreRequestTraceTests.swift`。 - -按错误类别过滤的辅助函数必须有测试:对象已经不在的类别(例如 `NotConnected`、`BrokenPipe`)不发事件,意外类别(例如 `PermissionDenied`)发事件。 +## 十一、验证 -新增或修改用户可见的警告和错误、用户入口时,按第三节第 8 步在真实应用的日志窗口里确认记录存在、字段正确、同一 op 的链条完整、“查看日志”能定位;无法在本机验证时在 PR 说明中写明。 +- 修改桌面端的日志调用:从 `desktop/` 运行 `../scripts/desktop/desktop-go.sh test ./internal/core -run TestEveryLoggedEventIsAcceptedByTheKernel`,以及改动所在包的测试。 +- 修改 Core 的目录、编码或执行轨迹:在 Core 仓库运行 `node scripts/logging/generate-log-events.mjs --check` 和受影响 crate 的测试;执行轨迹的测试在 `rust/crates/core/src/tests/core_request_traces.rs` 和 `rust/crates/git/src/command_trace.rs` 的测试模块。再用 `LITHE_CORE_RUST_DIR` 指向这份 Core 检出运行桌面端的目录测试,确认桌面端调用点仍被接受。 +- 修改写入器:运行 `desktop/internal/logstore` 和 `desktop/internal/logwindow` 的测试,包括 `-race`。 +- 按错误类别过滤的辅助函数必须有测试:对象已经不在的类别(例如 `net.ErrClosed`、`syscall.EPIPE`)不发事件,意外类别(例如权限不足)发事件。 +- 新增或修改用户可见的警告和错误、用户入口时,按第三节第 8 步在真实应用的日志窗口里确认记录存在、字段正确、同一 op 的链条完整、“查看日志”能打开这个 op;无法在本机验证时在 PR 说明中写明。 ## 十二、审查清单 -- 第一节的每种情形都有事件:界面警告和错误、降级、回退、自动恢复、重试耗尽、留下残留的清理失败、丢弃的错误。没有只出现在界面上的警告。 -- 新增的用户入口在最外层用 `UserActionTrace`,id 是稳定 token 而不是本地化标题或用户内容,surface 与实际位置一致;异步跳转用 `UserActionContext.detached` 或 `UserActionContext.mainAsync`。 +- 第一节的每种情形都有事件:界面警告和错误、拒绝、降级、回退、自动恢复、重试耗尽、留下残留的清理失败、丢弃的错误。没有只出现在界面上的警告。 +- 用户可见失败用 `operationFailed`,后台降级用 `backgroundFailed`,执行前拒绝用 `operationRejected`,级别没有混用。 +- 新增的用户入口在最外层调用一次 `performed`,action 是稳定 token 而不是本地化标题或用户内容,surface 是与实际位置一致的 `actionSurface` 常量;窗口线程之外的入口用 `performedIn`。 +- 为操作启动的后台工作经 `background` 或 `operationContext` 携带操作,goroutine 里用 `emitIn`,没有裸 `go func()` 丢掉 op,也没有在 goroutine 里读 `a.op`。 - 没有为 Core 请求或 Git 进程另写开始、完成或失败日志;新增的高频 Core 方法已列入 `is_hot`;Core 新依赖的文档化退出码已加入 `exit_is_answer`。 -- 宿主提示的事实都在 Core 轨迹里时,提示引用 Core 轨迹而不是重复记录;宿主自己的终态只描述 Core 没有的事实。 -- 豁免标记属于第二节的四类之一,写明类别和具体原因;绕过统一入口的例外只在 allowlist 里,计数精确。 -- 收尾类失败按错误类别过滤:对象已经不在的类别豁免,其余类别记录;没有因为“通常无害”整体豁免,也没有把正常关闭记成 WARN。 +- 插件声明式贡献的启动经 `StartPluginAttempt`/`EndAttempt` 代记,阶段正确,交给 Core 的启动用了 `HandOff`。 +- 豁免标记属于第二节的四类之一,类别名逐字一致并写明具体原因;收尾类失败按错误类别过滤,`context.DeadlineExceeded` 没有被当成取消。 - 事件有真实来源和 owner,级别按处理后的用户影响选择;高频路径没有 INFO 逐项输出。 -- 声明先于调用,使用生成类型;没有手写 ID、消息、字段字典、第二套写入器或直接打印;没有残留无调用点的事件。 -- 新增的 `logSink` 参数在每个生产构造处都传入真实 sink;`nil` 只出现在测试替身中。新增的 Core 入口如果会调用辅助 crate,已经调用 `helper_failures::install()`。 -- 同一操作只有一个 span 所有者和一条终态;错误只在处理边界记录一次,op 贯穿调用链。 -- 动态段来源可信并经过校验;字段类型最窄,description 具体,text 的 reason 说明不可替代性;argv 只经过集中格式化函数;没有禁止记录的内容。 -- 生成物检查和用法门禁通过,门禁零违规。 +- 事件先在 Core 目录声明,`PINNED_CORE_REVISION` 指向包含它的修订;事件 ID、级别、字段键是常量;没有第二套写入器、`log`/`slog` 或直接打印;没有残留无调用点的事件。 +- 新增的记录回调或接口字段在每个生产构造处都接上真实实现;`nil` 只出现在测试中。 +- 同一操作只有一条终态;错误只在处理边界记录一次,op 贯穿调用链。 +- 动态段来源可信并经过校验;字段类型最窄,错误用 `core.LogErrorFields`,没有用 `fmt.Sprintf` 拼出的消息或字段;没有禁止记录的内容。 +- 目录测试通过,日志窗口里没有被拒事件。 - 写入、查询、保留和导出保持有界,文件位于平台可写存储;Core 队列没有新增轮询。 当前决策见 `.agents/notes/implemented/architecture/2026-11-03-structured-logging-channels.md`。 diff --git a/desktop/internal/webpreview/webpreview.go b/desktop/internal/webpreview/webpreview.go index 2d0059190f..ce048202c0 100644 --- a/desktop/internal/webpreview/webpreview.go +++ b/desktop/internal/webpreview/webpreview.go @@ -25,7 +25,6 @@ import ( "encoding/json" "errors" "io/fs" - "log/slog" "net/url" "path" "path/filepath" @@ -143,7 +142,8 @@ type Config struct { // Request answers what a request of the site page serves, from its decoded path from the // root (core.Client.ResolveHTMLPreviewRequest); nil serves the file alone. Request func(ctx context.Context, path string) (core.HTMLPreviewResource, error) - // Log reports a failure of the page's resources; nil logs to slog. + // Log reports a failure of the page's resources to the client's log. Only tests leave it + // nil, and then a failure is not recorded: the page never writes logs of its own. Log func(stage string, err error) } @@ -403,9 +403,7 @@ func LoadResource(ctx context.Context, resolved core.MarkdownReference, remote * func (p *Page) log(stage string, err error) { if p.config.Log != nil { p.config.Log(stage, err) - return } - slog.Warn("web preview resource failed", "page", p.config.Page, "stage", stage, "error", err) } // decodeReference is the src a resource route carries. diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 90b6047b76..365ec063e1 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -1060,8 +1060,8 @@ const ( surfaceDragDrop actionSurface = "drag_drop" ) -// performed logs that the user started the action with the stable id from surface, as the -// macOS client does; the id is never a localized title. It starts the action's operation +// performed logs that the user started the action with the stable id from surface; the id is +// never a localized title. It starts the action's operation // (operation.go): what the action records and the Core requests it sends share its op. func (a *App) performed(action string, surface actionSurface) { a.op = operation{id: core.NewOperation(), trigger: action} diff --git a/desktop/internal/workbench/filetree.go b/desktop/internal/workbench/filetree.go index 04fe4720e7..75e8d1e24e 100644 --- a/desktop/internal/workbench/filetree.go +++ b/desktop/internal/workbench/filetree.go @@ -287,7 +287,7 @@ func (a *App) pumpTreeListings(p *project) { a.operationFailed("project_tree_list", errors.New("workspace root unavailable")) t.failed = i18n.Shared(a.language(), "desktop.project.rootUnavailable") } else { - // log-exempt: 目标已消失:目录可能已被外部删除或隐藏。 + // log-exempt: 预期的缺失:Core 的列表里没有这个目录,它已被外部删除或隐藏。 n.expanded, t.rowsDirty = false, true } } diff --git a/desktop/internal/workbench/plugincontent.go b/desktop/internal/workbench/plugincontent.go index 931823384c..e67ea1cd81 100644 --- a/desktop/internal/workbench/plugincontent.go +++ b/desktop/internal/workbench/plugincontent.go @@ -90,7 +90,7 @@ func (a *App) openContentTarget(p *project, uri string, line, column int) { if a.contentOpen == request { a.contentOpen = nil } - // log-exempt: user cancellation: an abandoned navigation opens no tab. + // log-exempt: 用户取消:放弃的导航不打开标签页。 if err == nil || errors.Is(err, context.Canceled) { return } diff --git a/desktop/internal/workbench/pluginsemantics.go b/desktop/internal/workbench/pluginsemantics.go index 4bfcf35195..59180779e7 100644 --- a/desktop/internal/workbench/pluginsemantics.go +++ b/desktop/internal/workbench/pluginsemantics.go @@ -1657,7 +1657,7 @@ func (a *App) cancelSemanticOperation(pending *semanticPending, operation string } session := pending.server.session a.background(pending.project, semanticCancelTimeout, func(ctx context.Context) func(*App) { - // log-exempt: 取消:过期结果已被 generation 丢弃,取消失败不影响界面状态。 + // log-exempt: 预期的缺失:取消只在会话已经结束时失败;过期结果已由 generation 丢弃。 _ = a.plugins.CancelLanguageOperation(ctx, session, operation) return nil }) diff --git a/desktop/internal/workbench/recent_files.go b/desktop/internal/workbench/recent_files.go index 777340333f..5a9ebed27e 100644 --- a/desktop/internal/workbench/recent_files.go +++ b/desktop/internal/workbench/recent_files.go @@ -133,7 +133,7 @@ func (a *App) enqueueRecent(request recentRequest) { recentFilesIO.Unlock() a.post(func(a *App) { if err != nil { - // log-exempt: 生命周期清理:关闭项目取消所属的历史读取,结果不再投递。 + // log-exempt: 用户取消:关闭项目取消了所属的历史读取,结果不再投递。 if !errors.Is(err, context.Canceled) { a.recentFailed(err) } diff --git a/desktop/internal/workbench/settings_publication.go b/desktop/internal/workbench/settings_publication.go index 8e383c97ff..7da6926310 100644 --- a/desktop/internal/workbench/settings_publication.go +++ b/desktop/internal/workbench/settings_publication.go @@ -89,7 +89,7 @@ func (a *App) publishSettings(editor pluginservice.SettingsEditor, scope string, case sub.notices <- notice: target.invalidator.Invalidate() case <-sub.done: - // log-exempt: 生命周期清理:接收窗口已经关闭,不再持有运行时或设置视图。 + // log-exempt: 预期的缺失:接收窗口已经关闭,不再需要这条刷新通知。 case <-ctx.Done(): failures = append(failures, ctx.Err()) } diff --git a/desktop/internal/workbench/shell_view.go b/desktop/internal/workbench/shell_view.go index cc00e9a03d..e047ad1d63 100644 --- a/desktop/internal/workbench/shell_view.go +++ b/desktop/internal/workbench/shell_view.go @@ -316,18 +316,28 @@ func (a *App) editorArea(c ui.C) { if a.editorGroups(c) { return } - hints := [...]struct{ label, keys string }{ - {a.text.Editor.SearchEverywhere, shortcuts.DoubleShiftLabel() + " " + a.settings.Keymap.Label("search.everywhere")}, - {a.text.Editor.FindInFiles, a.settings.Keymap.Label("search.files")}, + hints := [...]struct { + label string + // gesture is a gesture the keymap does not bind, shown before the command's bindings. + gesture string + // command is the keymap command whose bindings are shown. + command string + }{ + {a.text.Editor.SearchEverywhere, shortcuts.DoubleShiftLabel(), "search.everywhere"}, + {a.text.Editor.FindInFiles, "", "search.files"}, } editor := ui.Column(c).Fill().Clip().Center().Pad(shellContentPad).Background(a.colors.Editor).Radius(workbenchPanelRadius).Children(func() { ui.Column(c).FillWidth().MaxWidth(shellHintWidth).Children(func() { // Labels end and shortcuts start at one line down the middle, so the two read as // columns however long the words are. for _, hint := range hints { + keys := a.settings.Keymap.Label(hint.command) + if hint.gesture != "" { + keys = hint.gesture + " " + keys + } ui.Row(c).Height(rowHeight).Items(ui.Center).Gap(12).Children(func() { ui.Text(c, hint.label).Color(a.colors.Subtle).TextEnd().Ellipsis().FillWidth() - ui.Text(c, hint.keys).Color(a.colors.Text).FillWidth() + ui.Text(c, keys).Color(a.colors.Text).FillWidth() }) } }) diff --git a/desktop/internal/workbench/updates.go b/desktop/internal/workbench/updates.go index bf50350a06..3cc38d4d3d 100644 --- a/desktop/internal/workbench/updates.go +++ b/desktop/internal/workbench/updates.go @@ -610,7 +610,7 @@ func (a *App) updateDownloaded(feed *appupdate.Feed, artifact, payload string, e a.removeUpdatePayload(stale) switch { case errors.Is(err, context.Canceled): - // log-exempt: 用户取消下载或窗口关闭,不是失败。 + // log-exempt: 用户取消:用户取消下载或关闭窗口,不是失败。 a.changeUpdate(func(s *settingswindow.UpdateStatus) { s.Downloading, s.Applying, s.FellBack, s.Progress = false, false, false, 0 }) diff --git a/desktop/internal/workbench/workbench_background.go b/desktop/internal/workbench/workbench_background.go index dfc6c27cfd..7e0c9dc225 100644 --- a/desktop/internal/workbench/workbench_background.go +++ b/desktop/internal/workbench/workbench_background.go @@ -234,7 +234,7 @@ func (a *App) restoredBackground(serial uint64, pix []byte, width, height int, e b.pix, b.width, b.height = pix, width, height b.id = 1<<62 | backgroundImages.Add(1) case errors.Is(err, fs.ErrNotExist): - // log-exempt: 数据目录里没有副本,按未选择背景处理,不打扰用户。 + // log-exempt: 预期的缺失:数据目录里没有背景图副本,按未选择背景处理。 b.set, b.name = false, "" default: b.mu.Unlock() @@ -281,7 +281,7 @@ func (a *App) chooseBackground() { a.background(nil, 0, func(context.Context) func(*App) { paths, err := choose(options) if errors.Is(err, app.ErrCanceled) || err == nil && len(paths) == 0 { - // log-exempt: 用户取消了选择,背景保持不变。 + // log-exempt: 用户取消:关闭选择器或没有选文件,背景保持不变。 return nil } if err != nil { diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 9fb33d38c2..f7eefff709 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -28,7 +28,13 @@ native_path() { } PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" -# Lithe-core-rust #45, squash-merged into main: processMemory.summarize also sums the memory the +# Lithe-core-rust #46 (feat/logging-viva-adoption, not merged yet): the logging event catalog +# declares the events the desktop records (terminal.session.start_failed, vcs.provider.skipped, +# app.background.operation_failed, app.startup.leftovers_resolved, editor.recovery.applied and the +# drag_drop surface) and drops the 90 events only the macOS client used; a failure of +# diagnostics.encodeLogBatch carries the index of the refused input. Once #46 is merged, this pin +# moves to the main commit. It is on top of #45, squash-merged into main: processMemory.summarize +# also sums the memory the # system compressed or swapped out, graphics memory, and the processor and graphics use between # two tables, which the host sends back as a baseline. It is on top of #44, squash-merged into # main: outputStyle.decode turns console output with ANSI escapes into plain lines and styled @@ -90,7 +96,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="40711b146dc387fa6148ad2d0a4b758fc8e89909" +PINNED_CORE_REVISION="6f2d1853a3c1fa9101b57a79d1298bd081484440" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in From e601916b4605687604e9261a48f070ed46a62b69 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 02:04:16 +0800 Subject: [PATCH 6/7] =?UTF-8?q?docs(matrix):=20=E8=AF=8A=E6=96=AD=E4=B8=8E?= =?UTF-8?q?=E6=97=A5=E5=BF=97=E6=9D=A1=E7=9B=AE=E8=AE=B0=E5=BD=95=20Viva?= =?UTF-8?q?=20=E6=A1=8C=E9=9D=A2=E7=AB=AF=E7=9A=84=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E6=8E=A5=E5=85=A5=E7=8E=B0=E7=8A=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit diagnostics-export 的证据补上唤醒回调、origin、插件代记、引擎事实转发、操作串联和目录校验测试, 说明改为 #1927 之后的实现;整机与 Windows 实机验收仍为 pending。 --- .../features/diagnostics-export.json | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/shared/platform-feature-matrix/features/diagnostics-export.json b/shared/platform-feature-matrix/features/diagnostics-export.json index bb6999d2b1..1046a0dd49 100644 --- a/shared/platform-feature-matrix/features/diagnostics-export.json +++ b/shared/platform-feature-matrix/features/diagnostics-export.json @@ -8,8 +8,15 @@ "verificationStatus": "pending", "evidence": [ "desktop/internal/logwindow/export.go", + "desktop/internal/logwindow/model.go", "desktop/internal/logstore/collect.go", - "desktop/internal/logstore/store.go" + "desktop/internal/logstore/store.go", + "desktop/internal/core/log_waker.go", + "desktop/internal/core/origin.go", + "desktop/internal/core/plugin_operation.go", + "desktop/internal/core/log_sites_test.go", + "desktop/internal/pluginbackend/trace.go", + "desktop/internal/workbench/operation.go" ] }, "windows": { @@ -17,8 +24,15 @@ "verificationStatus": "pending", "evidence": [ "desktop/internal/logwindow/export.go", + "desktop/internal/logwindow/model.go", "desktop/internal/logstore/collect.go", - "desktop/internal/logstore/store.go" + "desktop/internal/logstore/store.go", + "desktop/internal/core/log_waker.go", + "desktop/internal/core/origin.go", + "desktop/internal/core/plugin_operation.go", + "desktop/internal/core/log_sites_test.go", + "desktop/internal/pluginbackend/trace.go", + "desktop/internal/workbench/operation.go" ] }, "owner": "Diagnostics", @@ -79,5 +93,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva:日志窗口导出(logwindow/export.go)使用暂存目录,logstore.ExportQuery 支持按会话、级别、时间与表达式筛选,store.go 负责保留预算;未确认 15 分钟诊断到期、过载不阻塞、凭据脱敏和 macOS v1 日志排除的专门实现。" + "notes": "Viva:日志窗口导出(logwindow/export.go)使用暂存目录,logstore.ExportQuery 支持按会话、级别、时间与表达式筛选,store.go 负责保留预算。#1927 起:写入器在 Core 记录事实时经唤醒回调(core/log_waker.go)合并排空,不再空闲轮询;详细诊断由一次性定时器 15 分钟到期,同时切换 Core 的 DEBUG 门和语言服务器的 lsp.setDetailedDiagnostics;被 Core 拒绝的事件按事件 ID 和错误码显示在日志窗口状态栏与 collection-status.txt,整批编码失败计入 log.dropped。用户动作分配 op,经 origin 带进 Core 请求(core/origin.go、workbench/operation.go),失败提示的“查看日志”按 op 过滤日志窗口。插件后端的引擎日志事实转发进会话日志(pluginbackend/trace.go);调试适配器启动和构建命令来源由宿主经 diagnostics.recordPluginOperation 代记(core/plugin_operation.go);插件 ${logDir} 改为会话内的插件文件目录。core/log_sites_test.go 把每个生产日志调用交给链接的内核按目录校验。未确认过载不阻塞和凭据脱敏的专门实现;macOS 整机窗口与 Windows 实机验收仍 pending。" } From 69768e57082ae13c73ccca5897814545439a9a30 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 02:14:34 +0800 Subject: [PATCH 7/7] =?UTF-8?q?build(desktop):=20Core=20=E5=9B=BA=E5=AE=9A?= =?UTF-8?q?=E5=88=B0=20main=20=E4=B8=8A=20#46=20=E7=9A=84=E5=90=88?= =?UTF-8?q?=E5=85=A5=E6=8F=90=E4=BA=A4=20e811068?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/desktop/build-desktop-core.sh | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index f7eefff709..dc0a334377 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -28,12 +28,12 @@ native_path() { } PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" -# Lithe-core-rust #46 (feat/logging-viva-adoption, not merged yet): the logging event catalog -# declares the events the desktop records (terminal.session.start_failed, vcs.provider.skipped, +# Lithe-core-rust #46, squash-merged into main: the logging event catalog declares the events the +# desktop records (terminal.session.start_failed, vcs.provider.skipped, # app.background.operation_failed, app.startup.leftovers_resolved, editor.recovery.applied and the # drag_drop surface) and drops the 90 events only the macOS client used; a failure of -# diagnostics.encodeLogBatch carries the index of the refused input. Once #46 is merged, this pin -# moves to the main commit. It is on top of #45, squash-merged into main: processMemory.summarize +# diagnostics.encodeLogBatch carries the index of the refused input. It is on top of #45, +# squash-merged into main: processMemory.summarize # also sums the memory the # system compressed or swapped out, graphics memory, and the processor and graphics use between # two tables, which the host sends back as a baseline. It is on top of #44, squash-merged into @@ -96,7 +96,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="6f2d1853a3c1fa9101b57a79d1298bd081484440" +PINNED_CORE_REVISION="e81106827b3f0e5c8178742b6ef61a7a8a225f57" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in