From 290f9e6aa44e7b8bb6ee7e34c8d1020e89173da8 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 07:46:35 +0800 Subject: [PATCH 01/11] =?UTF-8?q?fix(desktop):=20=E5=81=9C=E6=AD=A2?= =?UTF-8?q?=E7=AD=89=E5=BE=85=E6=97=B6=E9=97=B4=E7=9A=84=E8=A7=84=E5=88=99?= =?UTF-8?q?=E6=94=B9=E8=AF=BB=20Core=20=E7=9A=84=20gracefulStopRule?= =?UTF-8?q?=EF=BC=8C=E5=88=A0=E9=99=A4=E4=B8=89=E6=AC=A1=E6=8E=A2=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #1830 --- desktop/internal/core/process_lifecycle.go | 15 +++++- desktop/internal/workbench/process_exit.go | 47 +++---------------- .../internal/workbench/process_exit_test.go | 12 ++++- 3 files changed, 30 insertions(+), 44 deletions(-) diff --git a/desktop/internal/core/process_lifecycle.go b/desktop/internal/core/process_lifecycle.go index 2327c57e50..c915ba0118 100644 --- a/desktop/internal/core/process_lifecycle.go +++ b/desktop/internal/core/process_lifecycle.go @@ -32,13 +32,24 @@ type ProcessDecision struct { Reason string `json:"reason"` } -// ProcessPlan is Core's exit plan: one decision per record in request order and -// how long an ordinary process gets to stop gracefully. +// ProcessPlan is Core's exit plan: one decision per record in request order, +// how long an ordinary process gets to stop gracefully, and the rule that time +// follows. type ProcessPlan struct { GracefulStopMilliseconds int `json:"gracefulStopMilliseconds"` + GracefulStopRule GracefulStopRule `json:"gracefulStopRule"` Decisions []ProcessDecision `json:"decisions"` } +// GracefulStopRule is Core's rule for the gracefulStopSeconds setting, in +// seconds: the time settings without one get, and the limits a stored time is +// kept within. +type GracefulStopRule struct { + DefaultSeconds int `json:"defaultSeconds"` + MinSeconds int `json:"minSeconds"` + MaxSeconds int `json:"maxSeconds"` +} + // ResolveProcessLifecycle decides how each record ends in one context (quit, // closeTerminalTab, agentDisconnect, crashRecovery, startupSweep, finalSweep // or closeWorkspace). settings is the user's lifecycle settings document; nil diff --git a/desktop/internal/workbench/process_exit.go b/desktop/internal/workbench/process_exit.go index 4c8f918f33..862783be7a 100644 --- a/desktop/internal/workbench/process_exit.go +++ b/desktop/internal/workbench/process_exit.go @@ -3,7 +3,6 @@ package workbench import ( "context" "encoding/json" - "math" "strconv" "strings" "time" @@ -238,27 +237,20 @@ func (a *App) setProcessTermination(value settingswindow.ProcessTermination) { // hands it to the processes Lithe stops (buildprocess.SetStopGrace). Until Core answers, // processes keep the time they had: at start-up that is none, so one stopped before the // answer is killed at once. An answer for settings that changed since is dropped, because the -// refresh of the newer ones is on its way. The first refresh also reads Core's rule for the -// stop time, which the Process Termination page shows. +// refresh of the newer ones is on its way. The answer also carries Core's rule for the stop +// time, which the Process Termination page shows. func (a *App) refreshStopGrace() { if a.kernel == nil { return } a.stopGraceRequest++ request, settings := a.stopGraceRequest, terminationSettings(a.settings.ProcessTermination) - readRule := a.stopTime.Load() == nil a.background(nil, debugOperationTimeout, func(ctx context.Context) func(*App) { - grace, err := resolveStopTime(ctx, a.kernel, settings) - var rule *settingswindow.StopTime - if err == nil && readRule { - var read settingswindow.StopTime - if read, err = stopTimeRule(ctx, a.kernel); err == nil { - rule = &read - } - } + plan, err := a.kernel.ResolveProcessLifecycle(ctx, exitContextQuit, settings, nil) return func(a *App) { - if rule != nil { - a.stopTime.Store(rule) + if err == nil { + rule := plan.GracefulStopRule + a.stopTime.Store(&settingswindow.StopTime{Default: rule.DefaultSeconds, Min: rule.MinSeconds, Max: rule.MaxSeconds}) } if request != a.stopGraceRequest { return @@ -267,7 +259,7 @@ func (a *App) refreshStopGrace() { a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("process_stop_grace", err)) return } - buildprocess.SetStopGrace(grace) + buildprocess.SetStopGrace(time.Duration(plan.GracefulStopMilliseconds) * time.Millisecond) if a.settingsWindow != nil { a.settingsWindow.Invalidate() } @@ -275,31 +267,6 @@ func (a *App) refreshStopGrace() { }) } -// resolveStopTime is the stop time Core gives settings. -func resolveStopTime(ctx context.Context, kernel processExitKernel, settings json.RawMessage) (time.Duration, error) { - plan, err := kernel.ResolveProcessLifecycle(ctx, exitContextQuit, settings, nil) - if err != nil { - return 0, err - } - return time.Duration(plan.GracefulStopMilliseconds) * time.Millisecond, nil -} - -// stopTimeRule reads Core's rule for the stop time: the time it gives no stored time, the -// smallest stored time and the largest. Core does not publish its limits, so they are the -// times it resolves for the smallest and the largest number a setting can hold; #1830 has Core -// publish them instead. -func stopTimeRule(ctx context.Context, kernel processExitKernel) (settingswindow.StopTime, error) { - var seconds [3]int - for i, stored := range []*uint32{nil, new(uint32), new(uint32(math.MaxUint32))} { - grace, err := resolveStopTime(ctx, kernel, terminationSettings(settingswindow.ProcessTermination{GracefulStopSeconds: stored})) - if err != nil { - return settingswindow.StopTime{}, err - } - seconds[i] = int(grace / time.Second) - } - return settingswindow.StopTime{Default: seconds[0], Min: seconds[1], Max: seconds[2]}, nil -} - // stopTimeOption is how the Process Termination page reads Core's rule for the stop time once // refreshStopGrace has read it; it is safe from any thread. It is nil where a stopped program // is ended at once (buildprocess.StopsGracefully), so the page leaves the stop time out. diff --git a/desktop/internal/workbench/process_exit_test.go b/desktop/internal/workbench/process_exit_test.go index cad124241e..2e23052f03 100644 --- a/desktop/internal/workbench/process_exit_test.go +++ b/desktop/internal/workbench/process_exit_test.go @@ -1,6 +1,7 @@ package workbench import ( + "context" "runtime" "strings" "testing" @@ -208,8 +209,15 @@ func TestStopTimeFollowsCoreAndTheSetting(t *testing.T) { // Run calls this when the window opens; the harness never runs the application. h.app.refreshStopGrace() awaitStateWithin(t, h, 20*time.Second, "Core's stop time rule", func() bool { return h.app.stopTime.Load() != nil }) - if rule := *h.app.stopTime.Load(); rule != (settingswindow.StopTime{Default: 5, Min: 1, Max: 60}) { - t.Fatalf("the rule is %+v", rule) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + plan, err := core.NewClient().ResolveProcessLifecycle(ctx, exitContextQuit, nil, nil) + if err != nil { + t.Fatal(err) + } + want := plan.GracefulStopRule + if rule := *h.app.stopTime.Load(); rule != (settingswindow.StopTime{Default: want.DefaultSeconds, Min: want.MinSeconds, Max: want.MaxSeconds}) { + t.Fatalf("the rule is %+v, Core gives %+v", rule, want) } for _, step := range []struct { stored *uint32 From f8a253710d54ffc704454efcb0554c9969748f1c Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 07:55:57 +0800 Subject: [PATCH 02/11] =?UTF-8?q?fix(desktop):=20=E4=BB=A3=E7=90=86?= =?UTF-8?q?=E6=8E=92=E9=99=A4=E9=A1=B9=E7=94=B1=20Core=20=E8=A7=A3?= =?UTF-8?q?=E6=9E=90=EF=BC=8C=E6=B5=8B=E8=AF=95=E8=BF=9E=E6=8E=A5=E6=8F=90?= =?UTF-8?q?=E7=A4=BA=E8=A2=AB=E5=BF=BD=E7=95=A5=E7=9A=84=E6=9D=A1=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit network.proxyPolicy 返回 exclusionRules 和 invalidExclusions;netproxy 删掉 自己解析排除项的 Excluded,改为 Bypasses 只做契约规定的比较,并回放 Core 的 network/proxy-bypass-v1.json。设置页测试连接的结果后面列出 Core 无法识别、 不会生效的排除项。 Closes #1829 --- desktop/internal/core/network.go | 30 +++++++---- desktop/internal/i18n/shared.generated.go | 2 + desktop/internal/netproxy/netproxy.go | 45 ++++++++++------- desktop/internal/netproxy/netproxy_test.go | 50 ++++++++++++++++++- .../internal/settingswindow/network_view.go | 24 +++++++-- .../settingswindow/network_view_test.go | 8 ++- desktop/internal/workbench/network.go | 2 +- .../internal/workbench/network_check_test.go | 11 ++++ shared/i18n/locales/en-US.json | 1 + shared/i18n/locales/zh-CN.json | 1 + shared/i18n/messages.json | 10 ++++ 11 files changed, 148 insertions(+), 36 deletions(-) diff --git a/desktop/internal/core/network.go b/desktop/internal/core/network.go index 3d30d081b4..3572a791fe 100644 --- a/desktop/internal/core/network.go +++ b/desktop/internal/core/network.go @@ -29,16 +29,28 @@ type NetworkProxyRequest struct { // NetworkProxyPolicy is the policy the network stack applies: Policy "system", // "direct" or "custom". Credentials are present only for a custom policy whose // password belongs to its endpoint. Configured is false when a custom server was -// incomplete and the policy fell back to the system's. +// incomplete and the policy fell back to the system's. ExclusionRules is what Core +// read the exclusions as; InvalidExclusions are the entries it could not read, which +// send no host direct. type NetworkProxyPolicy struct { - Policy string `json:"policy"` - ProxyType string `json:"proxyType"` - Host string `json:"host"` - Port int `json:"port"` - Username string `json:"username"` - Password string `json:"password"` - Exclusions []string `json:"exclusions"` - Configured bool `json:"configured"` + Policy string `json:"policy"` + ProxyType string `json:"proxyType"` + Host string `json:"host"` + Port int `json:"port"` + Username string `json:"username"` + Password string `json:"password"` + Exclusions []string `json:"exclusions"` + ExclusionRules []NetworkProxyExclusionRule `json:"exclusionRules"` + InvalidExclusions []string `json:"invalidExclusions"` + Configured bool `json:"configured"` +} + +// NetworkProxyExclusionRule is one exclusion entry as Core read it. Kind is "host", +// "suffix", "ip", "cidr" or "local"; Value is the lowercase host or domain, the +// canonical address or block, or empty for "local". +type NetworkProxyExclusionRule struct { + Kind string `json:"kind"` + Value string `json:"value"` } // ProxyPolicy has Core normalize stored proxy settings (network.proxyPolicy). diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 1ff2700f8c..8b2fb3ea12 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1233,6 +1233,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.settings.network.exclusions": "No proxy for", "desktop.settings.network.exclusionsHelp": "Comma-separated hosts, domain suffixes (*.example.com), IP addresses, CIDR blocks, or for names without a dot.", "desktop.settings.network.host": "Host", + "desktop.settings.network.ignoredExclusions": "These exclusions have none of the supported forms and are ignored: {entries}", "desktop.settings.network.invalidPort": "The port must be a number from 1 to 65535.", "desktop.settings.network.mode": "Connection", "desktop.settings.network.password": "Password", @@ -3666,6 +3667,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.settings.network.exclusions": "不使用代理的地址", "desktop.settings.network.exclusionsHelp": "用逗号分隔:主机名、域名后缀(*.example.com)、IP 地址、CIDR 网段,或用 表示不含点的主机名。", "desktop.settings.network.host": "主机", + "desktop.settings.network.ignoredExclusions": "以下排除项不是支持的格式,已忽略:{entries}", "desktop.settings.network.invalidPort": "端口必须是 1 到 65535 之间的数字。", "desktop.settings.network.mode": "连接方式", "desktop.settings.network.password": "密码", diff --git a/desktop/internal/netproxy/netproxy.go b/desktop/internal/netproxy/netproxy.go index ea26260709..635ee07db1 100644 --- a/desktop/internal/netproxy/netproxy.go +++ b/desktop/internal/netproxy/netproxy.go @@ -13,6 +13,7 @@ import ( "errors" "net" "net/http" + "net/netip" "net/url" "strconv" "strings" @@ -63,7 +64,7 @@ func proxyFor(policy *core.NetworkProxyPolicy, request *http.Request) (*url.URL, if policy.Policy == "direct" || request.URL == nil { return nil, nil } - if Excluded(request.URL.Hostname(), policy.Exclusions) { + if Bypasses(request.URL.Hostname(), policy.ExclusionRules) { return nil, nil } return proxyURL(*policy), nil @@ -120,34 +121,40 @@ func proxyURL(policy core.NetworkProxyPolicy) *url.URL { return out } -// Excluded reports whether host is reached directly under exclusions: an entry is an -// exact host, a domain suffix written ".example.com" or "*.example.com", an IP -// address, a CIDR block, or "" for names without a dot. -func Excluded(host string, exclusions []string) bool { +// Bypasses reports whether host, a request URL's host name or address, goes direct under +// rules. Core reads what each exclusion entry means (network.proxyPolicy); this is only the +// comparison its contract states, replayed against rust/fixtures/network/proxy-bypass-v1.json: +// the host lowercase and without a trailing dot; "host" equal; "suffix" the domain or a host +// ending in "." and the domain; "ip" an equal address and "cidr" an address inside the block, +// both of the same family, an IPv6 zone not compared; "local" a name without a dot. +func Bypasses(host string, rules []core.NetworkProxyExclusionRule) bool { host = strings.ToLower(strings.TrimSuffix(host, ".")) if host == "" { return false } - ip := net.ParseIP(host) - for _, entry := range exclusions { - entry = strings.ToLower(strings.TrimSpace(entry)) - switch { - case entry == "": - case entry == "": - if ip == nil && !strings.Contains(host, ".") { + address, err := netip.ParseAddr(host) + isAddress := err == nil + address = address.WithZone("") + for _, rule := range rules { + switch rule.Kind { + case "host": + if host == rule.Value { return true } - case strings.Contains(entry, "/"): - if _, block, err := net.ParseCIDR(entry); err == nil && ip != nil && block.Contains(ip) { + case "suffix": + if host == rule.Value || strings.HasSuffix(host, "."+rule.Value) { return true } - case strings.HasPrefix(entry, "*."), strings.HasPrefix(entry, "."): - suffix := strings.TrimPrefix(entry, "*") - if strings.HasSuffix(host, suffix) || host == suffix[1:] { + case "ip": + if value, err := netip.ParseAddr(rule.Value); err == nil && isAddress && address == value { return true } - default: - if host == entry { + case "cidr": + if block, err := netip.ParsePrefix(rule.Value); err == nil && isAddress && block.Contains(address) { + return true + } + case "local": + if !isAddress && !strings.Contains(host, ".") { return true } } diff --git a/desktop/internal/netproxy/netproxy_test.go b/desktop/internal/netproxy/netproxy_test.go index c3ba001f29..a530954f22 100644 --- a/desktop/internal/netproxy/netproxy_test.go +++ b/desktop/internal/netproxy/netproxy_test.go @@ -3,15 +3,19 @@ package netproxy import ( "context" "encoding/base64" + "encoding/json" "net" "net/http" "net/http/httptest" + "os" + "reflect" "strconv" "strings" "sync" "testing" "time" + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" "github.com/1lck/Lithe-IDEA/desktop/internal/core" ) @@ -96,7 +100,7 @@ func TestCheckGoesDirectToAnExcludedHostAndReportsTheCause(t *testing.T) { direct := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) t.Cleanup(direct.Close) policy := proxy.policy(t) - policy.Exclusions = []string{"127.0.0.1"} + policy.ExclusionRules = []core.NetworkProxyExclusionRule{{Kind: "ip", Value: "127.0.0.1"}} if status, _, err := Check(checkContext(t), policy, direct.URL); err != nil || status != http.StatusOK { t.Fatalf("the excluded host = %d, %v", status, err) @@ -111,3 +115,47 @@ func TestCheckGoesDirectToAnExcludedHostAndReportsTheCause(t *testing.T) { t.Fatalf("a closed proxy = %v, want the cause without the request", err) } } + +// TestBypassesReplaysTheCoreFixture checks that the exclusion rules Core reads from each case's +// entries are the ones the fixture lists, and that Bypasses sends exactly the fixture's hosts +// direct under them. +func TestBypassesReplaysTheCoreFixture(t *testing.T) { + raw, err := os.ReadFile(contractfixture.CoreFixture("network/proxy-bypass-v1.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Cases []struct { + Name string `json:"name"` + Exclusions []string `json:"exclusions"` + ExclusionRules []core.NetworkProxyExclusionRule `json:"exclusionRules"` + InvalidExclusions []string `json:"invalidExclusions"` + Hosts map[string]bool `json:"hosts"` + } `json:"cases"` + } + if err := json.Unmarshal(raw, &fixture); err != nil { + t.Fatal(err) + } + if len(fixture.Cases) == 0 { + t.Fatal("the fixture has no cases") + } + client := core.NewClient() + for _, c := range fixture.Cases { + policy, err := client.ProxyPolicy(checkContext(t), core.NetworkProxyRequest{ + Mode: "custom", ProxyType: "http", Host: "proxy.example", Port: 8080, Exclusions: c.Exclusions, + }) + if err != nil { + t.Fatalf("%s: %v", c.Name, err) + } + if !reflect.DeepEqual(policy.ExclusionRules, c.ExclusionRules) || + !reflect.DeepEqual(append([]string{}, policy.InvalidExclusions...), c.InvalidExclusions) { + t.Fatalf("%s: Core read %+v and %q, want %+v and %q", c.Name, + policy.ExclusionRules, policy.InvalidExclusions, c.ExclusionRules, c.InvalidExclusions) + } + for host, want := range c.Hosts { + if got := Bypasses(host, policy.ExclusionRules); got != want { + t.Errorf("%s: Bypasses(%q) = %v, want %v", c.Name, host, got, want) + } + } + } +} diff --git a/desktop/internal/settingswindow/network_view.go b/desktop/internal/settingswindow/network_view.go index 31b53fee84..016e6a9649 100644 --- a/desktop/internal/settingswindow/network_view.go +++ b/desktop/internal/settingswindow/network_view.go @@ -37,11 +37,14 @@ var ( // NetworkCheck is the outcome of the Network page's connection check. Incomplete says the // draft names no complete custom server, so nothing was sent. Otherwise Err says why no // answer came, or Status is the HTTP status of the answer, which came after Elapsed. +// IgnoredExclusions are the draft's exclusion entries Core could not read, which send no +// host direct. type NetworkCheck struct { - Incomplete bool - Status int - Elapsed time.Duration - Err error + Incomplete bool + Status int + Elapsed time.Duration + Err error + IgnoredExclusions []string } // networkCheckTimeout bounds a connection check, Core's reading of the draft included. @@ -299,8 +302,19 @@ func (w *window) checkNetwork() { } // networkCheckText says what a check found, and whether the server carried the request: any -// answer from 200 to 399 does, since a redirect also came through it. +// answer from 200 to 399 does, since a redirect also came through it. Exclusion entries Core +// ignored follow the result. func networkCheckText(language i18n.Language, outcome NetworkCheck) (string, bool) { + text, succeeded := networkCheckResult(language, outcome) + if len(outcome.IgnoredExclusions) > 0 { + text += " " + i18n.SharedFormat(language, "desktop.settings.network.ignoredExclusions", + map[string]string{"entries": strings.Join(outcome.IgnoredExclusions, ", ")}) + } + return text, succeeded +} + +// networkCheckResult says what the request of a check found. +func networkCheckResult(language i18n.Language, outcome NetworkCheck) (string, bool) { switch { case outcome.Incomplete: return i18n.Shared(language, "settings.network.enterAddressAndPort"), false diff --git a/desktop/internal/settingswindow/network_view_test.go b/desktop/internal/settingswindow/network_view_test.go index f76226129a..24f1dd27ae 100644 --- a/desktop/internal/settingswindow/network_view_test.go +++ b/desktop/internal/settingswindow/network_view_test.go @@ -12,7 +12,8 @@ import ( // TestNetworkPageChecksTheDraftAndSaysWhatItFound walks the Network page's connection check: // it sends the unsaved draft off the window thread and says so while it runs, then shows the -// time an answer took, the status of an answer that is not one, or why none came. A draft +// time an answer took, the status of an answer that is not one, or why none came, followed by +// the exclusion entries Core ignored. A draft // without a server is answered at once without a request, Revert forgets the outcome, and only // a custom server offers the check. func TestNetworkPageChecksTheDraftAndSaysWhatItFound(t *testing.T) { @@ -70,6 +71,11 @@ func TestNetworkPageChecksTheDraftAndSaysWhatItFound(t *testing.T) { d.click(text("settings.network.testConnection")) d.until("the proxy's status", func() bool { return d.text(format("settings.network.proxyAnsweredWithHTTP", "407")) }) + set(NetworkCheck{Status: 204, Elapsed: 42 * time.Millisecond, IgnoredExclusions: []string{"*", "a..b"}}) + d.click(text("settings.network.testConnection")) + ignored := succeeded + " " + i18n.SharedFormat(i18n.English, "desktop.settings.network.ignoredExclusions", map[string]string{"entries": "*, a..b"}) + d.until("the ignored exclusions", func() bool { return d.text(ignored) }) + set(NetworkCheck{Err: errors.New("connection refused")}) d.click(text("settings.network.testConnection")) d.until("the cause", func() bool { return d.text(text("settings.network.checkFailed") + " connection refused") }) diff --git a/desktop/internal/workbench/network.go b/desktop/internal/workbench/network.go index 26aecd82cf..2ab0ce213d 100644 --- a/desktop/internal/workbench/network.go +++ b/desktop/internal/workbench/network.go @@ -175,5 +175,5 @@ func checkNetwork(ctx context.Context, kernel networkKernel, secrets secretReade return settingswindow.NetworkCheck{Incomplete: true} } status, elapsed, err := netproxy.Check(ctx, policy, target) - return settingswindow.NetworkCheck{Status: status, Elapsed: elapsed, Err: err} + return settingswindow.NetworkCheck{Status: status, Elapsed: elapsed, Err: err, IgnoredExclusions: policy.InvalidExclusions} } diff --git a/desktop/internal/workbench/network_check_test.go b/desktop/internal/workbench/network_check_test.go index b5489118b6..9f5b652e2a 100644 --- a/desktop/internal/workbench/network_check_test.go +++ b/desktop/internal/workbench/network_check_test.go @@ -6,6 +6,7 @@ import ( "net" "net/http" "net/http/httptest" + "reflect" "strconv" "sync" "testing" @@ -29,6 +30,7 @@ func (s savedSecret) Get(_ context.Context, namespace, key string) (string, bool // check against Core's reading of the draft: a typed password goes with the draft, the saved // one only while the draft still names the endpoint it was saved for, a cleared one not at all // (the account still goes, with an empty password), and a draft without a server sends nothing. +// Exclusion entries Core cannot read are reported with the outcome. func TestNetworkCheckSendsTheDraftsAccountOnlyToItsEndpoint(t *testing.T) { var mu sync.Mutex var auth []string @@ -70,6 +72,15 @@ func TestNetworkCheckSendsTheDraftsAccountOnlyToItsEndpoint(t *testing.T) { typed := "typed" check("a typed password", draft, "", &typed, basic("typed")) + withInvalid := draft + withInvalid.Exclusions = []string{"*", "intranet"} + invalidCtx, invalidCancel := context.WithTimeout(context.Background(), 10*time.Second) + outcome := checkNetwork(invalidCtx, kernel, savedSecret(""), "http://lithe-check.invalid/", withInvalid, &typed) + invalidCancel() + if outcome.Status != http.StatusNoContent || !reflect.DeepEqual(outcome.IgnoredExclusions, []string{"*"}) { + t.Fatalf("a draft with an unsupported exclusion = %+v, want the request sent and the entry reported", outcome) + } + saved := draft saved.HasPassword = true saved.PasswordIdentity = &core.NetworkProxyIdentity{ProxyType: "http", Host: host, Port: port, Username: "ada"} diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index e3ede51385..57fcabe630 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -10908,6 +10908,7 @@ "desktop.settings.network.revert": "Revert", "desktop.settings.network.apply": "Apply", "desktop.settings.network.invalidPort": "The port must be a number from 1 to 65535.", + "desktop.settings.network.ignoredExclusions": "These exclusions have none of the supported forms and are ignored: {entries}", "desktop.settings.localHistory.help": "Local history keeps versions of a project's files as you save and edit them, in Lithe's own data folder. Ignore rules only keep files out of local history; the project tree still shows them.", "desktop.settings.localHistory.wildcardHelp": "One pattern per line, matched against the path inside the project, for example `*.log` or `**/generated/`.", "desktop.settings.localHistory.builtIns": "Built-in rules, which also apply: {patterns}. Add a line such as `!**/target/` to record one of these folders again.", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 88120f4d23..df178f6251 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -10908,6 +10908,7 @@ "desktop.settings.network.revert": "还原", "desktop.settings.network.apply": "应用", "desktop.settings.network.invalidPort": "端口必须是 1 到 65535 之间的数字。", + "desktop.settings.network.ignoredExclusions": "以下排除项不是支持的格式,已忽略:{entries}", "desktop.settings.localHistory.help": "本地历史在你保存和编辑项目文件时保留各个版本,存放在 Lithe 自己的数据目录中。忽略规则只让文件不进入本地历史,项目树仍然显示它们。", "desktop.settings.localHistory.wildcardHelp": "每行一条规则,按项目内的路径匹配,例如 `*.log` 或 `**/generated/`。", "desktop.settings.localHistory.builtIns": "同时生效的内置规则:{patterns}。添加一行例如 `!**/target/`,可以重新记录其中的某个目录。", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 850465acea..630b65077e 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -14919,6 +14919,16 @@ "desktop" ] }, + { + "id": "desktop.settings.network.ignoredExclusions", + "description": "Network settings page: connection check result, followed by the exclusion entries that have none of the supported forms", + "platforms": [ + "desktop" + ], + "parameters": { + "entries": "string" + } + }, { "id": "desktop.settings.network.invalidPort", "description": "Network settings page", From 66436fb04f9847428f1a670372e1f18b5da15fb7 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 08:04:42 +0800 Subject: [PATCH 03/11] fix(desktop): group changed files of commits, stashes and shelves through Core The Log tab's commit files, the Stash tab and the Shelf tab grouped files by folder with path.Dir and strings.Compare, so v0.1.12 sorted before v0.1.4 and the top folder was ".". They now ask Core's git.changedFileGroups once when a list loads, in the background task that reads it, and test whether a folder holds the selected file from Core's grouping instead of path.Dir. The top folder is "". stashCommitFiles is gone with the old grouping. Closes #1814 --- desktop/internal/core/gitlog.go | 30 ++++++++++ desktop/internal/workbench/app.go | 1 + desktop/internal/workbench/gitlog.go | 56 ++++++++++++------- .../internal/workbench/gitlog_details_view.go | 4 +- .../internal/workbench/gitlog_files_test.go | 37 ++++++------ desktop/internal/workbench/gitreview.go | 1 + desktop/internal/workbench/saved_files.go | 35 +++++++++--- desktop/internal/workbench/shelf.go | 8 ++- desktop/internal/workbench/stash.go | 15 ++--- 9 files changed, 131 insertions(+), 56 deletions(-) diff --git a/desktop/internal/core/gitlog.go b/desktop/internal/core/gitlog.go index 0761997a0b..b4b17d4b9c 100644 --- a/desktop/internal/core/gitlog.go +++ b/desktop/internal/core/gitlog.go @@ -319,6 +319,36 @@ func (c *Client) GitReferenceTree(ctx context.Context, names []string, prioritiz return nonNil(response.Nodes), nil } +// GitChangedFolder is one folder of changed files (git.changedFileGroups): Path from the top +// of the repository, "" for the top itself, and Files, indices into the grouped paths of the +// files directly in it, in name order. +type GitChangedFolder struct { + Path string `json:"path"` + Files []int `json:"files"` +} + +type changedFileGroupsRequest struct { + Paths []string `json:"paths"` +} + +type changedFileGroupsResponse struct { + Folders []GitChangedFolder `json:"folders"` +} + +// GitChangedFileGroups groups repository-relative paths by folder, folders and files in the +// project tree's natural order. It runs no process. +func (c *Client) GitChangedFileGroups(ctx context.Context, paths []string) ([]GitChangedFolder, error) { + request := changedFileGroupsRequest{Paths: nonNil(paths)} + var response changedFileGroupsResponse + if err := c.Execute(ctx, "git.changedFileGroups", request, &response); err != nil { + return nil, err + } + for i := range response.Folders { + response.Folders[i].Files = nonNil(response.Folders[i].Files) + } + return nonNil(response.Folders), nil +} + // HistoryDateEntry is one commit a date filter is asked about. type HistoryDateEntry struct { ID string `json:"id"` diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index a64e9bba72..5d16128834 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -125,6 +125,7 @@ type Kernel interface { GitCommit(ctx context.Context, root, commit string) (core.GitCommitDetail, error) GitGraph(ctx context.Context, request core.GraphRequest) (core.Graph, error) GitReferenceTree(ctx context.Context, names []string, prioritized map[string]bool) ([]core.ReferenceTreeNode, error) + GitChangedFileGroups(ctx context.Context, paths []string) ([]core.GitChangedFolder, error) GitHistoryDates(ctx context.Context, entries []core.HistoryDateEntry, after, before *int64) ([]string, error) ReduceEditorWorkbench(ctx context.Context, state core.EditorWorkbench, action core.EditorAction) (core.EditorWorkbench, []string, error) GitStage(ctx context.Context, root string, paths []string) error diff --git a/desktop/internal/workbench/gitlog.go b/desktop/internal/workbench/gitlog.go index f2b3480c9e..2ab6242cc7 100644 --- a/desktop/internal/workbench/gitlog.go +++ b/desktop/internal/workbench/gitlog.go @@ -2,7 +2,6 @@ package workbench import ( "context" - "path" "slices" "strings" "time" @@ -608,6 +607,10 @@ func (a *App) selectCommit(p *project, hash string) { ctx, cancel := untilStopped(ctx, stop) defer cancel() files, err := kernel.GitCommitFiles(ctx, root, hash) + var folders []logFolder + if err == nil { + folders, err = groupLogFiles(ctx, kernel, commitFilePaths(files)) + } if ctx.Err() != nil { return nil } @@ -619,7 +622,7 @@ func (a *App) selectCommit(p *project, hash string) { if err != nil { l.filesState = logFilesFailed } else { - l.files, l.folders, l.filesState = files, groupLogFiles(files), logFilesReady + l.files, l.folders, l.filesState = files, folders, logFilesReady } if detailErr == nil { l.detail = &detail @@ -644,30 +647,45 @@ func untilStopped(ctx context.Context, stop <-chan struct{}) (context.Context, c return ctx, cancel } -// logFolder is one folder of the selected commit's changed files: its path from the top of -// the repository, "." for the top itself, and the indices into the files of the ones in it, in -// the order Git listed them. +// logFolder is one folder of a list of changed files as Core grouped it +// (git.changedFileGroups): its path from the top of the repository, "" for the top itself, and +// the indices into the files of the ones directly in it, in name order. type logFolder struct { dir string files []int } -// groupLogFiles groups files by their folder, the folders sorted by path. -func groupLogFiles(files []core.GitCommitFile) []logFolder { - at := map[string]int{} - var folders []logFolder +// changedFileGrouper is the kernel as the lists of changed files group their files. +type changedFileGrouper interface { + GitChangedFileGroups(ctx context.Context, paths []string) ([]core.GitChangedFolder, error) +} + +// groupLogFiles has Core group the files at paths by folder, folders and files in the project +// tree's natural order. A list is grouped once, when it loads. +func groupLogFiles(ctx context.Context, kernel changedFileGrouper, paths []string) ([]logFolder, error) { + groups, err := kernel.GitChangedFileGroups(ctx, paths) + if err != nil { + return nil, err + } + folders := make([]logFolder, len(groups)) + for i, group := range groups { + folders[i] = logFolder{dir: group.Path, files: group.Files} + } + return folders, nil +} + +// holds says the folder lists the file at file, pathOf naming the file at an index. +func (f logFolder) holds(file string, pathOf func(int) string) bool { + return slices.ContainsFunc(f.files, func(i int) bool { return pathOf(i) == file }) +} + +// commitFilePaths are the paths of a commit's changed files. +func commitFilePaths(files []core.GitCommitFile) []string { + paths := make([]string, len(files)) for i, file := range files { - dir := path.Dir(file.Path) - j, ok := at[dir] - if !ok { - j = len(folders) - at[dir] = j - folders = append(folders, logFolder{dir: dir}) - } - folders[j].files = append(folders[j].files, i) + paths[i] = file.Path } - slices.SortFunc(folders, func(a, b logFolder) int { return strings.Compare(a.dir, b.dir) }) - return folders + return paths } // locateReference selects the newest loaded commit that the reference with short name diff --git a/desktop/internal/workbench/gitlog_details_view.go b/desktop/internal/workbench/gitlog_details_view.go index 4f7795277e..a99dc8cc66 100644 --- a/desktop/internal/workbench/gitlog_details_view.go +++ b/desktop/internal/workbench/gitlog_details_view.go @@ -138,7 +138,7 @@ func (a *App) collectLogFiles(p *project) { v.fileRows, v.fileSelected = v.fileRows[:0], -1 for g, folder := range l.folders { depth := 0 - if folder.dir != "." { + if folder.dir != "" { open := !l.closedFolders[folder.dir] if v.folder == folder.dir { v.fileSelected = len(v.fileRows) @@ -306,7 +306,7 @@ func (a *App) toggleLogFolder(p *project, g int) { l.closedFolders = map[string]bool{} } l.closedFolders[dir] = true - if v.file != "" && path.Dir(v.file) == dir { + if v.file != "" && l.folders[g].holds(v.file, func(i int) string { return l.files[i].Path }) { v.file, v.folder = "", dir } } diff --git a/desktop/internal/workbench/gitlog_files_test.go b/desktop/internal/workbench/gitlog_files_test.go index c4bcefd5ec..cb139f4f00 100644 --- a/desktop/internal/workbench/gitlog_files_test.go +++ b/desktop/internal/workbench/gitlog_files_test.go @@ -5,6 +5,7 @@ import ( "os" "path" "path/filepath" + "reflect" "strings" "testing" "time" @@ -156,22 +157,26 @@ func TestLogChangedFilesFoldersCollapse(t *testing.T) { } } -func TestGroupLogFilesSortsFoldersAndKeepsGitOrder(t *testing.T) { - files := []core.GitCommitFile{{Path: "b/x.go"}, {Path: "a.go"}, {Path: "b/c/y.go"}, {Path: "b/a.go"}} - got := groupLogFiles(files) - want := []logFolder{{dir: ".", files: []int{1}}, {dir: "b", files: []int{0, 3}}, {dir: "b/c", files: []int{2}}} - if len(got) != len(want) { - t.Fatalf("folders %+v", got) - } - for i := range want { - if got[i].dir != want[i].dir || len(got[i].files) != len(want[i].files) { - t.Fatalf("folder %d is %+v, want %+v", i, got[i], want[i]) - } - for j := range want[i].files { - if got[i].files[j] != want[i].files[j] { - t.Fatalf("folder %d is %+v, want %+v", i, got[i], want[i]) - } - } +// The changed-file lists group through Core: the top first, as "", then each folder before +// its subfolders, folders and files in the project tree's natural order. +func TestGroupLogFilesUsesCoreNaturalOrder(t *testing.T) { + paths := []string{"b/x.go", "a.go", "b/c/y.go", "b/a.go", "v0.1.12/n", "v0.1.4/n", "file10.go", "file2.go"} + got, err := groupLogFiles(context.Background(), core.NewClient(), paths) + if err != nil { + t.Fatal(err) + } + want := []logFolder{ + {dir: "", files: []int{1, 7, 6}}, + {dir: "b", files: []int{3, 0}}, + {dir: "b/c", files: []int{2}}, + {dir: "v0.1.4", files: []int{5}}, + {dir: "v0.1.12", files: []int{4}}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("folders %+v, want %+v", got, want) + } + if !got[1].holds("b/a.go", func(i int) string { return paths[i] }) || got[1].holds("b/c/y.go", func(i int) string { return paths[i] }) { + t.Fatalf("folder b holds %v", got[1].files) } } diff --git a/desktop/internal/workbench/gitreview.go b/desktop/internal/workbench/gitreview.go index dcd1b465bd..413a99ef76 100644 --- a/desktop/internal/workbench/gitreview.go +++ b/desktop/internal/workbench/gitreview.go @@ -53,6 +53,7 @@ type gitReviewKernel interface { GitPushPreviewOf(ctx context.Context, root string, branch core.GitReference, tags core.GitPushTags, target core.PushTargetChoice) (core.GitPushPreview, error) GitPush(ctx context.Context, root string, preview core.GitPushPreview, tags core.GitPushTags, target core.PushTargetChoice, force bool) error DiscoverWorkspaceRepositories(ctx context.Context, root string) ([]core.WorkspaceRepository, error) + changedFileGrouper } // reviewKernel is the window's kernel as the review dialogs use it. diff --git a/desktop/internal/workbench/saved_files.go b/desktop/internal/workbench/saved_files.go index b497f90763..87256f6656 100644 --- a/desktop/internal/workbench/saved_files.go +++ b/desktop/internal/workbench/saved_files.go @@ -1,6 +1,7 @@ package workbench import ( + "context" "path" "github.com/1lck/Lithe-IDEA/desktop/internal/core" @@ -52,9 +53,29 @@ type savedFileRow struct { depth int } -// newSavedLayer is a layer of files, grouped by folder. -func newSavedLayer(label string, files []core.GitDiffFile) savedLayer { - return savedLayer{label: label, files: files, folders: groupLogFiles(stashCommitFiles(files))} +// newSavedLayer is a layer of files, grouped by folder through kernel. +func newSavedLayer(ctx context.Context, kernel changedFileGrouper, label string, files []core.GitDiffFile) (savedLayer, error) { + paths := make([]string, len(files)) + for i, file := range files { + paths[i] = file.Path + } + folders, err := groupLogFiles(ctx, kernel, paths) + return savedLayer{label: label, files: files, folders: folders}, err +} + +// holds says the folder g of the layer lists the file at file. +func (layer savedLayer) holds(g int, file string) bool { + return layer.folders[g].holds(file, func(i int) string { return layer.files[i].Path }) +} + +// atTop says the layer lists the file at file at the top of the repository. +func (layer savedLayer) atTop(file string) bool { + for g, folder := range layer.folders { + if folder.dir == "" { + return layer.holds(g, file) + } + } + return false } // reset forgets the files, the folders the user closed and the selected file. @@ -95,7 +116,7 @@ func (f *savedFiles) collect() { } for g, folder := range layer.folders { depth := indent - if folder.dir != "." { + if folder.dir != "" { f.rows = append(f.rows, savedFileRow{key: base + 1 + g, layer: l, folder: g, file: -1, depth: indent}) if f.closed[savedPath{l, folder.dir}] { continue @@ -125,7 +146,7 @@ func (f *savedFiles) toggleFolder(l, g int) { f.closed = map[savedPath]bool{} } f.closed[folder] = true - if f.file.path != "" && f.file.layer == l && path.Dir(f.file.path) == folder.path { + if f.file.path != "" && f.file.layer == l && f.layers[l].holds(g, f.file.path) { f.file = savedPath{} } } @@ -139,12 +160,12 @@ func (f *savedFiles) openFolders(open bool) { f.closed = map[savedPath]bool{} for l, layer := range f.layers { for _, folder := range layer.folders { - if folder.dir != "." { + if folder.dir != "" { f.closed[savedPath{l, folder.dir}] = true } } } - if f.file.path != "" && path.Dir(f.file.path) != "." { + if f.file.path != "" && !f.layers[f.file.layer].atTop(f.file.path) { f.file = savedPath{} } } diff --git a/desktop/internal/workbench/shelf.go b/desktop/internal/workbench/shelf.go index 23275824bd..967eb7088f 100644 --- a/desktop/internal/workbench/shelf.go +++ b/desktop/internal/workbench/shelf.go @@ -40,6 +40,7 @@ type shelfKernel interface { GitShelfClean(ctx context.Context, root, layer string, snapshot core.GitShelfSnapshot) error GitShelfRestore(ctx context.Context, root, layer string, snapshot core.GitShelfSnapshot) error GitParsePatch(ctx context.Context, root, patch string) ([]core.GitDiffFile, error) + changedFileGrouper } // shelfFormat is the version of the shelf files this client reads and writes; a file of @@ -286,6 +287,10 @@ func (a *App) selectShelf(p *project, id string) { } kinds, files = append(kinds, layer.kind), append(files, parsed) } + layers := make([]savedLayer, len(files)) + for i := 0; err == nil && i < len(files); i++ { + layers[i], err = newSavedLayer(ctx, kernel, "", files[i]) + } return func(a *App) { s := &p.shelf if s.filesGen != gen || s.selected != id { @@ -297,9 +302,8 @@ func (a *App) selectShelf(p *project, id string) { a.gitOperationFailed("git_shelf_diff", err) return } - layers := make([]savedLayer, len(kinds)) for i, kind := range kinds { - layers[i] = newSavedLayer(a.shelfLayerLabel(kind), files[i]) + layers[i].label = a.shelfLayerLabel(kind) } s.layers = kinds s.tree.reset(layers...) diff --git a/desktop/internal/workbench/stash.go b/desktop/internal/workbench/stash.go index d79140986e..2347f5fbf1 100644 --- a/desktop/internal/workbench/stash.go +++ b/desktop/internal/workbench/stash.go @@ -138,6 +138,10 @@ func (a *App) selectStash(p *project, oid string) { gen, root := s.filesGen, p.git.repositoryRoot(p.root) a.background(p, reviewTimeout, func(ctx context.Context) func(*App) { files, err := kernel.GitStashDiff(ctx, root, stash) + var layer savedLayer + if err == nil { + layer, err = newSavedLayer(ctx, kernel, "", files) + } return func(a *App) { s := &p.stash if s.filesGen != gen || s.selected != oid { @@ -150,7 +154,7 @@ func (a *App) selectStash(p *project, oid string) { return } s.files = files - s.tree.reset(newSavedLayer("", files)) + s.tree.reset(layer) } }) } @@ -165,15 +169,6 @@ func stashDate(stash core.GitStash) string { return t.Local().Format(logDateFormat) } -// stashCommitFiles are a stash's files as the Log tab's grouping takes a commit's. -func stashCommitFiles(files []core.GitDiffFile) []core.GitCommitFile { - out := make([]core.GitCommitFile, len(files)) - for i, f := range files { - out[i] = core.GitCommitFile{Path: f.Path, Status: f.Status} - } - return out -} - // openStashFile opens the Diff tab of the file at path the selected stash saved. func (a *App) openStashFile(p *project, file string) { s := &p.stash From 0a495ddf5b44bd7aef1209ec66e82589dd090e33 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 08:24:34 +0800 Subject: [PATCH 04/11] fix(desktop): worktree states, blocked writes and the creation dialog follow Core The Worktrees tab shows the states and blocked-write reasons Core derives, counts every checkout's changes with one countChanges listing, and the new worktree dialog takes its choices, branch name, destination and readiness from git.worktreeCreationPreview instead of rules of its own. Closes #1817 --- desktop/internal/core/gitworktree.go | 122 +++++- desktop/internal/workbench/app.go | 2 + desktop/internal/workbench/gitworktree.go | 374 ++++++++---------- .../internal/workbench/gitworktree_test.go | 108 +++-- .../internal/workbench/gitworktree_view.go | 49 ++- 5 files changed, 374 insertions(+), 281 deletions(-) diff --git a/desktop/internal/core/gitworktree.go b/desktop/internal/core/gitworktree.go index 6d6a08479f..6a37170aaa 100644 --- a/desktop/internal/core/gitworktree.go +++ b/desktop/internal/core/gitworktree.go @@ -25,23 +25,139 @@ type GitWorktree struct { IsPrunable bool `json:"isPrunable"` // PruneReason is Git's explanation of why the registration can be pruned. PruneReason string `json:"pruneReason"` + // Status is the one state the worktree's row shows, one of the GitWorktreeStatus values. + // It is GitWorktreeModified only in a listing that counted the changes. + Status string `json:"status"` + // Changes is the number of local changes of the checkout, nil when they were not counted + // or could not be read. + Changes *int `json:"changes"` + // Actions says which writes Core accepts for the worktree. + Actions GitWorktreeActions `json:"actions"` } -// GitWorktrees returns the worktrees registered with the repository at root, in Git's order. +// The states of GitWorktree.Status, the first that holds of a worktree. +const ( + // GitWorktreeMissing is a registration whose checkout is gone. + GitWorktreeMissing = "missing" + // GitWorktreeLocked is a locked worktree. + GitWorktreeLocked = "locked" + // GitWorktreeModified is a checkout with counted local changes. + GitWorktreeModified = "modified" + // GitWorktreeCurrent is the worktree the listing was made from. + GitWorktreeCurrent = "current" + // GitWorktreeAvailable is any other worktree. + GitWorktreeAvailable = "available" +) + +// GitWorktreeActions are the writes a worktree's menu and details offer. +type GitWorktreeActions struct { + // Remove is GitRemoveWorktree's. + Remove GitWorktreeAction `json:"remove"` + // Lock is GitLockWorktree's and GitUnlockWorktree's. + Lock GitWorktreeAction `json:"lock"` +} + +// GitWorktreeAction says whether Core accepts one write to a worktree. +type GitWorktreeAction struct { + Allowed bool `json:"allowed"` + // Reason names the refusal, empty when the write is allowed: CodeGitWorktreePrimary, + // CodeGitWorktreeCurrent and CodeGitWorktreeLocked are the codes the write itself returns, + // and GitWorktreeBlockedMissing is a checkout that is gone, which is pruned instead. + Reason ErrorCode `json:"reason"` +} + +// GitWorktreeBlockedMissing is the GitWorktreeAction.Reason of a checkout that is gone. It is +// not an error code: Core leaves such a write to Git. +const GitWorktreeBlockedMissing ErrorCode = "git_worktree_missing" + +// GitWorktrees returns the worktrees registered with the repository at root, in Git's order, +// without reading their checkouts. // // GitWorktrees starts git and blocks; call it from a background goroutine. func (c *Client) GitWorktrees(ctx context.Context, root string) ([]GitWorktree, error) { + return c.gitWorktrees(ctx, root, false) +} + +// GitWorktreesWithChanges is GitWorktrees with the local changes of every checkout counted, +// which sets each worktree's Changes and lets its Status be GitWorktreeModified. +// +// GitWorktreesWithChanges starts git once per checkout and blocks; call it from a background +// goroutine. +func (c *Client) GitWorktreesWithChanges(ctx context.Context, root string) ([]GitWorktree, error) { + return c.gitWorktrees(ctx, root, true) +} + +func (c *Client) gitWorktrees(ctx context.Context, root string, countChanges bool) ([]GitWorktree, error) { var response struct { Worktrees []GitWorktree `json:"worktrees"` } if err := c.Execute(ctx, "git.worktrees", struct { - Root string `json:"root"` - }{root}, &response); err != nil { + Root string `json:"root"` + CountChanges bool `json:"countChanges,omitempty"` + }{root, countChanges}, &response); err != nil { return nil, err } return response.Worktrees, nil } +// GitWorktreeCreationInput is what the dialog that creates a worktree holds, for +// GitWorktreeCreationPreview. +type GitWorktreeCreationInput struct { + // Root is the repository the worktree is created from. + Root string `json:"root"` + // Mode is one of GitWorktreeNewBranch, GitWorktreeExistingBranch and GitWorktreeDetached. + Mode string `json:"mode"` + // Kind is the kind of reference listed, "local", "remote" or "tag"; an existing-branch + // worktree lists local branches whatever it is. + Kind string `json:"kind"` + // Reference is the FullName of the held reference, empty for none. + Reference string `json:"reference"` + // Name is the new branch as typed; RequireName makes an empty one an error, as a submit + // does. + Name string `json:"name"` + RequireName bool `json:"requireName"` + // Revision is the revision as typed. + Revision string `json:"revision"` + // Destination is the destination as typed, and LastSuggestion the suggestion it last + // followed, empty at first. + Destination string `json:"destination"` + LastSuggestion string `json:"lastSuggestion"` + // References are the repository's references, as GitReferences reads them. + References []GitReference `json:"references"` + // CheckedOutBranches are the Branch of every registered worktree. + CheckedOutBranches []string `json:"checkedOutBranches"` +} + +// GitWorktreeCreationPreview is what the dialog shows for a GitWorktreeCreationInput. +type GitWorktreeCreationPreview struct { + // Choices are indices into the input's References the dialog lists, in their order. + Choices []int `json:"choices"` + // Reference is the FullName of the reference the dialog holds now, nil without choices. + Reference *string `json:"reference"` + // Branch is the cleaned and checked new branch name, nil outside GitWorktreeNewBranch. + Branch *BranchNamePreview `json:"branch"` + // SuggestedDestination is the next input's LastSuggestion. + SuggestedDestination string `json:"suggestedDestination"` + // Destination is what the destination field holds: the suggestion until the user edited + // it, then what they typed. + Destination string `json:"destination"` + DestinationIsAbsolute bool `json:"destinationIsAbsolute"` + // Ready says the dialog can create the worktree. + Ready bool `json:"ready"` +} + +// GitWorktreeCreationPreview derives the choices, the branch name, the destination and the +// readiness of the dialog that creates a worktree. It does not start git. +func (c *Client) GitWorktreeCreationPreview(ctx context.Context, input GitWorktreeCreationInput) (GitWorktreeCreationPreview, error) { + input.References = nonNil(input.References) + input.CheckedOutBranches = nonNil(input.CheckedOutBranches) + var preview GitWorktreeCreationPreview + if err := c.Execute(ctx, "git.worktreeCreationPreview", input, &preview); err != nil { + return GitWorktreeCreationPreview{}, err + } + return preview, nil +} + // How a created worktree gets its checkout, for GitWorktreeCreation.Mode. const ( // GitWorktreeNewBranch creates a branch for the worktree. diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 5d16128834..22b4670b69 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -158,6 +158,8 @@ type Kernel interface { GitDeleteTag(ctx context.Context, root, name string) error GitBranchNamePreview(ctx context.Context, request core.BranchNameRequest) (core.BranchNamePreview, error) GitWorktrees(ctx context.Context, root string) ([]core.GitWorktree, error) + GitWorktreesWithChanges(ctx context.Context, root string) ([]core.GitWorktree, error) + GitWorktreeCreationPreview(ctx context.Context, input core.GitWorktreeCreationInput) (core.GitWorktreeCreationPreview, error) GitCreateWorktree(ctx context.Context, root string, creation core.GitWorktreeCreation) error GitRemoveWorktree(ctx context.Context, root, path string, force bool) error GitLockWorktree(ctx context.Context, root, path string) error diff --git a/desktop/internal/workbench/gitworktree.go b/desktop/internal/workbench/gitworktree.go index 716e05f619..9378f0ffda 100644 --- a/desktop/internal/workbench/gitworktree.go +++ b/desktop/internal/workbench/gitworktree.go @@ -4,9 +4,7 @@ import ( "context" "errors" "path/filepath" - "slices" "strings" - "unicode" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" @@ -30,11 +28,6 @@ const ( // worktreeLoadMoreMargin is how near the end of the history the list is scrolled when the // next page is read. worktreeLoadMoreMargin = 200 - // worktreeLeafFallback is the last part of a suggested destination when the dialog's - // inputs name nothing. - worktreeLeafFallback = "worktree" - // worktreeRevisionLeaf is how many characters of a typed revision name a destination. - worktreeRevisionLeaf = 9 ) // worktreeDialog is the dialog of the Worktrees tab that is open over the window. @@ -63,18 +56,6 @@ const ( // worktreeTabs are the details' tabs in the order they are shown. var worktreeTabs = []worktreeTab{worktreeTabOverview, worktreeTabChanges, worktreeTabHistory} -// worktreeStatus is the one state a worktree's row shows, the most pressing of what is true of -// it: a missing checkout, then a lock, local changes, being the open one, and otherwise none. -type worktreeStatus uint8 - -const ( - worktreeAvailable worktreeStatus = iota - worktreeCurrent - worktreeModified - worktreeLocked - worktreeMissing -) - // The modes a worktree can be created in, in the order the dialog offers them. var worktreeModes = []string{core.GitWorktreeNewBranch, core.GitWorktreeExistingBranch, core.GitWorktreeDetached} @@ -132,17 +113,38 @@ type worktreeCreation struct { // reference is the FullName of the chosen reference, empty for none. reference string name ui.Field - // typed is the name the preview was made for, so it is made again only when the name - // changes. - typed string - preview core.BranchNamePreview - revision ui.Field - // destination is the path of the new checkout. It follows the suggestion the inputs make - // for as long as it holds the last suggestion, that is until the user edits it. + revision ui.Field + // destination is the path of the new checkout. Core keeps it on the suggestion the inputs + // make for as long as it holds the last one, suggested, that is until the user edits it. destination ui.Field suggested string - noCheckout bool - after worktreeAfterCreate + // result is Core's preview of the inputs: the references to choose from, the cleaned and + // checked branch name, the destination and whether the worktree can be created. key is the + // inputs it was made for, so it is made again only when they change. + result core.GitWorktreeCreationPreview + key worktreeCreationKey + noCheckout bool + after worktreeAfterCreate +} + +// worktreeCreationKey is what a creation preview is made from: the dialog's inputs, whether +// the references were read, and the reading of the list that tells which branches are +// checked out. +type worktreeCreationKey struct { + mode, kind, reference string + name, revision, destination string + refsLoaded bool + listGen int +} + +// inputs is the key of a preview of the dialog's inputs as they stand; gen is the reading of +// the worktree list. +func (cr *worktreeCreation) inputs(gen int) worktreeCreationKey { + return worktreeCreationKey{ + mode: cr.mode, kind: cr.kind, reference: cr.reference, + name: cr.name.Text(), revision: cr.revision.Text(), destination: cr.destination.Text(), + refsLoaded: cr.refsLoaded, listGen: gen, + } } // worktreeState is a project's Worktrees tab: the registered worktrees, their changes and the @@ -153,10 +155,13 @@ type worktreeState struct { // gen counts the readings of the list, so the answer of one that was overtaken is dropped. gen int list []core.GitWorktree - // counts are the numbers of local changes of the worktrees by path; a worktree whose - // status could not be read has none. + // counts are the numbers of local changes of the worktrees by path, and statuses the + // states Core derived with them; a worktree whose status could not be read has neither. + // countGen tells the answer of a count that a later one overtook. counts map[string]int + statuses map[string]string countsKnown bool + countGen int selected string changes map[string]*worktreeChanges // commits are the commits of the linked worktrees by path, each with its own message, @@ -237,65 +242,64 @@ func worktreeName(w core.GitWorktree) string { return filepath.Base(w.Path) } -// worktreeStatusOf is the state w's row shows; changes is its number of local changes, zero -// while unknown. -func worktreeStatusOf(w core.GitWorktree, changes int) worktreeStatus { - switch { - case w.IsPrunable: - return worktreeMissing - case w.IsLocked: - return worktreeLocked - case changes > 0: - return worktreeModified - case w.IsCurrent: - return worktreeCurrent +// statusOf is the state w's row shows, which Core derives: with its counted local changes once +// they are, from its registration alone before. +func (ws *worktreeState) statusOf(w core.GitWorktree) string { + if status, ok := ws.statuses[w.Path]; ok { + return status } - return worktreeAvailable + return w.Status } -// worktreeRemoveBlocked is why w cannot be removed, empty when it can. -func worktreeRemoveBlocked(t *i18n.WorktreeMessages, w core.GitWorktree) string { - switch { - case w.IsPrimary: - return t.RemovePrimary - case w.IsCurrent: +// worktreeReasonText words why Core refuses or blocks a worktree write, empty for a code that +// is not such a reason. removing says the write is a removal, whose refusal of the primary +// worktree and of a missing checkout reads differently from a lock's. +func worktreeReasonText(t *i18n.WorktreeMessages, removing bool, code core.ErrorCode) string { + switch code { + case core.CodeGitWorktreePrimary: + if removing { + return t.RemovePrimary + } + return t.LockPrimary + case core.CodeGitWorktreeCurrent: return t.RemoveCurrent - case w.IsPrunable: - return t.RemovePrunable - case w.IsLocked: + case core.CodeGitWorktreeLocked: return t.RemoveLocked + case core.GitWorktreeBlockedMissing: + if removing { + return t.RemovePrunable + } + return t.LockPrunable } return "" } -// worktreeLockBlocked is why the lock of w cannot be changed, empty when it can. +// worktreeRemoveBlocked is why w cannot be removed, as Core gave it, empty when it can. +func worktreeRemoveBlocked(t *i18n.WorktreeMessages, w core.GitWorktree) string { + if w.Actions.Remove.Allowed { + return "" + } + return worktreeReasonText(t, true, w.Actions.Remove.Reason) +} + +// worktreeLockBlocked is why the lock of w cannot be changed, as Core gave it, empty when it +// can. func worktreeLockBlocked(t *i18n.WorktreeMessages, w core.GitWorktree) string { - switch { - case w.IsPrimary: - return t.LockPrimary - case w.IsPrunable: - return t.LockPrunable + if w.Actions.Lock.Allowed { + return "" } - return "" + return worktreeReasonText(t, false, w.Actions.Lock.Reason) } // worktreeFailureText words the failure of a worktree write for the user. Core names each // refusal with its own code, so the words come from the code, never from the message; a // failure without one of those codes is shown with what Git or Core said. removing says the -// write was a removal, whose refusal of the primary worktree reads differently from a lock's. +// write was a removal. func worktreeFailureText(t *i18n.WorktreeMessages, removing bool, err error) string { var e *core.Error if errors.As(err, &e) { - switch e.Code { - case core.CodeGitWorktreePrimary: - if removing { - return t.RemovePrimary - } - return t.LockPrimary - case core.CodeGitWorktreeCurrent: - return t.RemoveCurrent - case core.CodeGitWorktreeLocked: - return t.RemoveLocked + if text := worktreeReasonText(t, removing, e.Code); text != "" { + return text } if e.Message != "" { return t.Failed(e.Message) @@ -313,49 +317,6 @@ func worktreeErrorCode(err error) core.ErrorCode { return "" } -// worktreeLeaf is the last part of a suggested destination made from source: its last -// "/"-separated segment with every character that is not a letter, a digit, "-" or "_" -// replaced by "-", or worktreeLeafFallback when nothing is left. -func worktreeLeaf(source string) string { - if i := strings.LastIndexByte(source, '/'); i >= 0 { - source = source[i+1:] - } - var b strings.Builder - for _, r := range source { - if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '-' || r == '_' { - b.WriteRune(r) - } else { - b.WriteByte('-') - } - } - if b.Len() == 0 { - return worktreeLeafFallback - } - return b.String() -} - -// worktreeDestination suggests where a worktree named from source is checked out: beside the -// repository at root, named after it and the leaf of source. -func worktreeDestination(root, source string) string { - return filepath.Join(filepath.Dir(root), filepath.Base(root)+"-"+worktreeLeaf(source)) -} - -// suggestionSource is what the creation dialog names its suggested destination after: the new -// branch, the start of a typed revision, or the chosen reference. -func (cr *worktreeCreation) suggestionSource() string { - revision := strings.TrimSpace(cr.revision.Text()) - switch { - case cr.mode == core.GitWorktreeNewBranch && cr.preview.CleanedName != "": - return cr.preview.CleanedName - case cr.mode == core.GitWorktreeDetached && revision != "": - return revision[:min(len(revision), worktreeRevisionLeaf)] - } - if r, ok := cr.chosenReference(); ok { - return r.ShortName - } - return "" -} - // chosenReference is the loaded reference the dialog chose. func (cr *worktreeCreation) chosenReference() (core.GitReference, bool) { if cr.reference == "" { @@ -373,42 +334,16 @@ func (cr *worktreeCreation) chosenReference() (core.GitReference, bool) { // it offers them. var worktreeReferenceKinds = []string{"local", "remote", "tag"} -// referenceChoices are the references of the dialog's kind it can start from; an -// existing-branch worktree can only check out a local branch no worktree has checked out. -func (cr *worktreeCreation) referenceChoices(worktrees []core.GitWorktree) []core.GitReference { - kind := cr.kind - if cr.mode == core.GitWorktreeExistingBranch { - kind = "local" - } - var choices []core.GitReference - for _, r := range cr.refs.References { - if r.Kind != kind { - continue +// checkedOutBranches are the full names of the branches the worktrees in list have checked +// out, which an existing-branch worktree cannot check out again. +func checkedOutBranches(list []core.GitWorktree) []string { + branches := make([]string, 0, len(list)) + for _, w := range list { + if w.Branch != "" { + branches = append(branches, w.Branch) } - if cr.mode == core.GitWorktreeExistingBranch && - slices.ContainsFunc(worktrees, func(w core.GitWorktree) bool { return w.Branch == r.FullName }) { - continue - } - choices = append(choices, r) } - return choices -} - -// ready reports whether the dialog can create the worktree. -func (cr *worktreeCreation) ready() bool { - if !filepath.IsAbs(strings.TrimSpace(cr.destination.Text())) { - return false - } - _, hasReference := cr.chosenReference() - switch cr.mode { - case core.GitWorktreeNewBranch: - return hasReference && cr.preview.Error == nil && cr.preview.CleanedName != "" - case core.GitWorktreeExistingBranch: - return hasReference - case core.GitWorktreeDetached: - return hasReference || strings.TrimSpace(cr.revision.Text()) != "" - } - return false + return branches } // loadWorktrees reads the worktrees of p's repository again, then the number of local changes @@ -450,34 +385,36 @@ func (a *App) loadWorktrees(p *project) { // A write may have changed every checkout, so what was read of them is read again. w.changes = nil a.dropWorktreeHistory(p) + w.countsKnown = false a.countWorktreeChanges(p, gen) } }) } -// countWorktreeChanges reads the number of local changes of every worktree that has a -// checkout, in one task. gen is the reading of the list the counts belong to. +// countWorktreeChanges has Core count the local changes of every worktree that has a +// checkout and derive the states that follow from them, in one listing. gen is the reading of +// the list the counts belong to; the counts known before stay on show until the answer. func (a *App) countWorktreeChanges(p *project, gen int) { w := &p.worktrees - w.countsKnown = false - paths := make([]string, 0, len(w.list)) - for _, worktree := range w.list { - if !worktree.IsPrunable && !worktree.IsBare { - paths = append(paths, worktree.Path) - } - } - kernel := a.kernel + w.countGen++ + countGen := w.countGen + kernel, root := a.kernel, p.git.repositoryRoot(p.root) a.background(p, gitTimeout, func(ctx context.Context) func(*App) { - counts := make(map[string]int, len(paths)) - for _, path := range paths { - if status, err := kernel.GitStatus(core.AutomaticRefresh(ctx), path); err == nil { - counts[path] = len(status.Changes) - } - } + counted, err := kernel.GitWorktreesWithChanges(core.AutomaticRefresh(ctx), root) return func(a *App) { - if w := &p.worktrees; w.gen == gen { - w.counts, w.countsKnown = counts, true + w := &p.worktrees + if w.gen != gen || w.countGen != countGen { + return + } + counts, statuses := make(map[string]int, len(counted)), make(map[string]string, len(counted)) + if err == nil { + for _, worktree := range counted { + if worktree.Changes != nil { + counts[worktree.Path], statuses[worktree.Path] = *worktree.Changes, worktree.Status + } + } } + w.counts, w.statuses, w.countsKnown = counts, statuses, true } }) } @@ -513,11 +450,15 @@ func (a *App) loadWorktreeChanges(p *project, path string) { return } entry.loading, entry.err, entry.changes = false, err, status.Changes - if err == nil { - if p.worktrees.counts == nil { - p.worktrees.counts = map[string]int{} + w := &p.worktrees + if known, ok := w.counts[path]; err == nil && (!ok || known != len(status.Changes)) { + if w.counts == nil { + w.counts = map[string]int{} } - p.worktrees.counts[path] = len(status.Changes) + // The count shows at once; the state that follows from it is Core's to derive + // again. + w.counts[path] = len(status.Changes) + a.countWorktreeChanges(p, w.gen) } } }) @@ -887,7 +828,7 @@ func (a *App) beginCreateWorktree(p *project) { cr.name.SetText("") cr.revision.SetText("") cr.destination.SetText("") - cr.typed, cr.preview, cr.suggested, cr.noCheckout, cr.after = "", core.BranchNamePreview{}, "", false, worktreeStay + cr.suggested, cr.result, cr.key, cr.noCheckout, cr.after = "", core.GitWorktreeCreationPreview{}, worktreeCreationKey{}, false, worktreeStay w.dialog = worktreeDialogCreate kernel, root := a.kernel, p.git.repositoryRoot(p.root) a.background(p, gitTimeout, func(ctx context.Context) func(*App) { @@ -906,62 +847,59 @@ func (a *App) beginCreateWorktree(p *project) { }) } -// syncWorktreeCreation keeps the dialog's derived values in step with its inputs: the -// reference stays one the mode can use, the branch name is cleaned and checked as the user -// types, and the destination follows the suggestion until the user edits it. +// syncWorktreeCreation keeps the dialog's derived values in step with its inputs, asking Core +// again whenever they changed: the reference stays one the mode can use, the branch name is +// cleaned and checked as the user types, and the destination follows the suggestion until the +// user edits it. func (a *App) syncWorktreeCreation(p *project) { - cr := &p.worktrees.create - if cr.refsLoaded { - choices := cr.referenceChoices(p.worktrees.list) - if !slices.ContainsFunc(choices, func(r core.GitReference) bool { return r.FullName == cr.reference }) { - cr.reference = "" - for _, r := range choices { - if r.Kind == "local" && r.IsCurrent { - cr.reference = r.FullName - } - } - if cr.reference == "" && len(choices) > 0 { - cr.reference = choices[0].FullName - } - } - } - if text := cr.name.Text(); text != cr.typed { - cr.preview = a.previewWorktreeBranch(p, text, false) - if cr.preview.TypingCleanedName != text { - cr.name.SetText(cr.preview.TypingCleanedName) - } - cr.typed = cr.name.Text() - } - destination := cr.destination.Text() - if destination == cr.suggested { - suggestion := worktreeDestination(p.git.repositoryRoot(p.root), cr.suggestionSource()) - if suggestion != destination { - cr.destination.SetText(suggestion) - } - cr.suggested = suggestion + if cr := &p.worktrees.create; cr.inputs(p.worktrees.gen) != cr.key { + a.previewWorktreeCreation(p, false) } } -// previewWorktreeBranch asks Core to clean and check the name of the branch a new worktree -// creates; require makes an empty name an error, as a submit does. -func (a *App) previewWorktreeBranch(p *project, raw string, require bool) core.BranchNamePreview { +// previewWorktreeCreation has Core derive the dialog's values from its inputs and applies +// them; require makes an empty branch name an error, as a submit does. It reports whether Core +// answered; without an answer the dialog cannot create the worktree. +func (a *App) previewWorktreeCreation(p *project, require bool) bool { + w := &p.worktrees + cr := &w.create ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) defer cancel() - preview, err := a.kernel.GitBranchNamePreview(ctx, core.BranchNameRequest{ - RawName: raw, RequireName: require, References: p.worktrees.create.refs.References}) + result, err := a.kernel.GitWorktreeCreationPreview(ctx, core.GitWorktreeCreationInput{ + Root: p.git.repositoryRoot(p.root), Mode: cr.mode, Kind: cr.kind, Reference: cr.reference, + Name: cr.name.Text(), RequireName: require, Revision: cr.revision.Text(), + Destination: cr.destination.Text(), LastSuggestion: cr.suggested, + References: cr.refs.References, CheckedOutBranches: checkedOutBranches(w.list), + }) 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) - return core.BranchNamePreview{TypingCleanedName: raw, CleanedName: strings.TrimSpace(raw)} + a.gitOperationFailed("git_worktree_creation_preview", err) + cr.result.Ready = false + cr.key = cr.inputs(w.gen) + return false } - return preview + cr.result = result + if cr.refsLoaded { + cr.reference = "" + if result.Reference != nil { + cr.reference = *result.Reference + } + } + if b := result.Branch; b != nil && b.TypingCleanedName != cr.name.Text() { + cr.name.SetText(b.TypingCleanedName) + } + if result.Destination != cr.destination.Text() { + cr.destination.SetText(result.Destination) + } + cr.suggested = result.SuggestedDestination + cr.key = cr.inputs(w.gen) + return true } -// submitCreateWorktree creates the worktree the dialog describes. +// submitCreateWorktree creates the worktree the dialog describes, once Core confirms, with the +// branch name required, that it can be created. func (a *App) submitCreateWorktree(p *project) { cr := &p.worktrees.create - if p.worktrees.busy || !cr.ready() { + if p.worktrees.busy || !cr.result.Ready || !a.previewWorktreeCreation(p, true) || !cr.result.Ready { return } creation := core.GitWorktreeCreation{ @@ -970,12 +908,8 @@ func (a *App) submitCreateWorktree(p *project) { NoCheckout: cr.noCheckout, } name := filepath.Base(creation.Destination) - if cr.mode == core.GitWorktreeNewBranch { - cr.preview = a.previewWorktreeBranch(p, cr.name.Text(), true) - if cr.preview.Error != nil { - return - } - creation.Name, name = cr.preview.CleanedName, cr.preview.CleanedName + if b := cr.result.Branch; cr.mode == core.GitWorktreeNewBranch && b != nil { + creation.Name, name = b.CleanedName, b.CleanedName } if r, ok := cr.chosenReference(); ok { creation.Reference = &r diff --git a/desktop/internal/workbench/gitworktree_test.go b/desktop/internal/workbench/gitworktree_test.go index 0104313fe6..b0042fee22 100644 --- a/desktop/internal/workbench/gitworktree_test.go +++ b/desktop/internal/workbench/gitworktree_test.go @@ -1,11 +1,13 @@ package workbench import ( + "context" "errors" "os" "path/filepath" - "slices" + "strings" "testing" + "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" @@ -118,6 +120,13 @@ func TestWorktreesListThePrimaryAndTheLinkedCheckouts(t *testing.T) { if w.counts[current.Path] == 0 { t.Fatalf("counts = %v, want the primary worktree's modified file counted", w.counts) } + // Core derives the states: the primary worktree's change outranks its being the open one. + if got := w.statusOf(current); got != core.GitWorktreeModified { + t.Fatalf("the primary worktree's state = %q, want modified", got) + } + if other, _ := w.find(linked); w.statusOf(other) != core.GitWorktreeAvailable { + t.Fatalf("the linked worktree's state = %q, want available", w.statusOf(other)) + } } func TestWorktreesRemoveACleanLinkedCheckout(t *testing.T) { @@ -210,7 +219,11 @@ func TestWorktreesCreateANewBranchBesideTheRepository(t *testing.T) { w.create.name.SetText("topic/new thing") h.app.invalidator.Invalidate() h.settle() - want := worktreeDestination(p.git.repositoryRoot(p.root), w.create.preview.CleanedName) + root := p.git.repositoryRoot(p.root) + want := w.create.result.SuggestedDestination + if filepath.Dir(want) != filepath.Dir(root) || !strings.HasPrefix(filepath.Base(want), filepath.Base(root)+"-") { + t.Fatalf("suggestion = %q, want a checkout beside %q named after it", want, root) + } if got := w.create.destination.Text(); got != want { t.Fatalf("destination = %q, want the suggestion %q", got, want) } @@ -219,27 +232,40 @@ func TestWorktreesCreateANewBranchBesideTheRepository(t *testing.T) { h.clickNamed(text.Create) h.awaitWorktreeWrite("the creation", w, func() bool { return len(w.list) == 2 }) created, ok := w.find(w.selected) - if !ok || created.IsPrimary || created.Branch != "refs/heads/"+w.create.preview.CleanedName { + if !ok || created.IsPrimary || created.Branch != "refs/heads/"+w.create.result.Branch.CleanedName { t.Fatalf("selected %+v, want the new worktree on its new branch", created) } } -func TestWorktreeDestinationNamesTheLeafBesideTheRepository(t *testing.T) { - root := filepath.Join(string(filepath.Separator), "work", "app") - for _, tc := range []struct{ source, leaf string }{ - {"feature/login", "login"}, - {"fix bug#12", "fix-bug-12"}, - {"版本", "版本"}, - {"", worktreeLeafFallback}, - {"refs/heads/", worktreeLeafFallback}, - } { - if got := worktreeLeaf(tc.source); got != tc.leaf { - t.Errorf("worktreeLeaf(%q) = %q, want %q", tc.source, got, tc.leaf) - } +// The creation preview is Core's: the client sends the dialog's inputs and gets the +// suggestion, which the destination follows until the user edits it. +func TestWorktreeCreationPreviewFollowsTheSuggestionUntilEdited(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + client := core.NewClient() + root := filepath.Join(t.TempDir(), "app") + input := core.GitWorktreeCreationInput{ + Root: root, Mode: core.GitWorktreeNewBranch, Kind: "local", Name: "feature/login", + References: []core.GitReference{{FullName: "refs/heads/main", ShortName: "main", Kind: "local", IsCurrent: true}}, + } + got, err := client.GitWorktreeCreationPreview(ctx, input) + if err != nil { + t.Fatal(err) } - want := filepath.Join(string(filepath.Separator), "work", "app-login") - if got := worktreeDestination(root, "feature/login"); got != want { - t.Fatalf("worktreeDestination() = %q, want %q", got, want) + want := filepath.Join(filepath.Dir(root), "app-login") + if got.SuggestedDestination != want || got.Destination != want || !got.DestinationIsAbsolute || !got.Ready { + t.Fatalf("preview = %+v, want the ready suggestion %q", got, want) + } + if got.Reference == nil || *got.Reference != "refs/heads/main" || got.Branch == nil || got.Branch.CleanedName != "feature/login" { + t.Fatalf("preview = %+v, want the current branch held and the name kept", got) + } + edited := filepath.Join(t.TempDir(), "elsewhere") + input.Name, input.Destination, input.LastSuggestion = "feature/other", edited, want + if got, err = client.GitWorktreeCreationPreview(ctx, input); err != nil { + t.Fatal(err) + } + if got.Destination != edited || got.SuggestedDestination != filepath.Join(filepath.Dir(root), "app-other") { + t.Fatalf("preview = %+v, want the edited destination kept beside a new suggestion", got) } } @@ -254,6 +280,8 @@ func TestWorktreeFailureTextFollowsTheCode(t *testing.T) { {core.CodeGitWorktreePrimary, false, text.LockPrimary}, {core.CodeGitWorktreeCurrent, true, text.RemoveCurrent}, {core.CodeGitWorktreeLocked, true, text.RemoveLocked}, + {core.GitWorktreeBlockedMissing, true, text.RemovePrunable}, + {core.GitWorktreeBlockedMissing, false, text.LockPrunable}, {core.CodeProcessFailed, true, text.Failed("fatal: refused")}, } { err := &core.Error{Code: tc.code, Message: "fatal: refused"} @@ -266,26 +294,30 @@ func TestWorktreeFailureTextFollowsTheCode(t *testing.T) { } } -func TestWorktreeStatusPutsTheMostPressingFirst(t *testing.T) { - all := core.GitWorktree{IsPrunable: true, IsLocked: true, IsCurrent: true} - steps := []worktreeStatus{worktreeMissing, worktreeLocked, worktreeModified, worktreeCurrent, worktreeAvailable} - var got []worktreeStatus - changes := 3 - for range steps { - got = append(got, worktreeStatusOf(all, changes)) - switch { - case all.IsPrunable: - all.IsPrunable = false - case all.IsLocked: - all.IsLocked = false - case changes > 0: - changes = 0 - default: - all.IsCurrent = false - } - } - if !slices.Equal(got, steps) { - t.Fatalf("statuses = %v, want %v", got, steps) +// A row shows the state Core derived from the registration until the changes are counted, +// then the one Core derived with them; the blocked writes are named by the reasons Core gave. +func TestWorktreeRowFollowsCoreStatesAndReasons(t *testing.T) { + text := i18n.For(i18n.English).Worktrees + w := core.GitWorktree{ + Path: "/work/app-feature", Status: core.GitWorktreeAvailable, + Actions: core.GitWorktreeActions{ + Remove: core.GitWorktreeAction{Reason: core.GitWorktreeBlockedMissing}, + Lock: core.GitWorktreeAction{Allowed: true}, + }, + } + var ws worktreeState + if got := ws.statusOf(w); got != core.GitWorktreeAvailable { + t.Fatalf("uncounted state = %q, want the registration's", got) + } + ws.statuses = map[string]string{w.Path: core.GitWorktreeModified} + if got := ws.statusOf(w); got != core.GitWorktreeModified { + t.Fatalf("counted state = %q, want modified", got) + } + if got := worktreeRemoveBlocked(&text, w); got != text.RemovePrunable { + t.Errorf("removal blocked by %q, want %q", got, text.RemovePrunable) + } + if got := worktreeLockBlocked(&text, w); got != "" { + t.Errorf("lock blocked by %q, want none", got) } } diff --git a/desktop/internal/workbench/gitworktree_view.go b/desktop/internal/workbench/gitworktree_view.go index 8ee0c25738..7e5db1802f 100644 --- a/desktop/internal/workbench/gitworktree_view.go +++ b/desktop/internal/workbench/gitworktree_view.go @@ -168,7 +168,7 @@ func (a *App) drawWorktreeRow(p *project, shown []core.GitWorktree, row ui.ListR } else { item = item.Hover(ui.Look{}.Background(a.colors.Hover)) } - status := worktreeStatusOf(w, p.worktrees.counts[w.Path]) + status := p.worktrees.statusOf(w) item.Children(func() { icon := icons.GitBranch if w.IsLocked { @@ -233,32 +233,32 @@ func (a *App) worktreeBranchText(w core.GitWorktree) string { return t.Detached } -// worktreeStatusText is the label of a worktree's state. -func (a *App) worktreeStatusText(s worktreeStatus) string { +// worktreeStatusText is the label of a worktree's state as Core names it. +func (a *App) worktreeStatusText(status string) string { t := &a.text.Worktrees - switch s { - case worktreeMissing: + switch status { + case core.GitWorktreeMissing: return t.PathMissing - case worktreeLocked: + case core.GitWorktreeLocked: return t.Locked - case worktreeModified: + case core.GitWorktreeModified: return t.Modified - case worktreeCurrent: + case core.GitWorktreeCurrent: return t.Current } return t.Available } -// worktreeStatusColor is the color of a worktree's state. -func (a *App) worktreeStatusColor(s worktreeStatus) gfx.Color { - switch s { - case worktreeMissing: +// worktreeStatusColor is the color of a worktree's state as Core names it. +func (a *App) worktreeStatusColor(status string) gfx.Color { + switch status { + case core.GitWorktreeMissing: return a.theme.Danger - case worktreeLocked: + case core.GitWorktreeLocked: return a.colors.Warning - case worktreeModified: + case core.GitWorktreeModified: return a.colors.Accent - case worktreeCurrent: + case core.GitWorktreeCurrent: return a.colors.Success } return a.colors.Subtle @@ -305,7 +305,7 @@ func (a *App) drawWorktreeDetails(c ui.C, p *project) ui.Box { // state and what can be done with it. func (a *App) drawWorktreeOverview(c ui.C, p *project, w core.GitWorktree) { ws, t := &p.worktrees, &a.text.Worktrees - status := worktreeStatusOf(w, ws.counts[w.Path]) + status := ws.statusOf(w) ui.Scroll(c).Grow(1).FillWidth().Pad(shellContentPad).Gap(12).Children(func() { a.worktreeCard(c, t.BasicInformation, func() { a.worktreeField(c, t.Path, w.Path) @@ -732,9 +732,18 @@ func (a *App) drawWorktreeCreateDialog(c ui.C, p *project) { a.syncWorktreeCreation(p) w, t := &p.worktrees, &a.text.Worktrees cr := &w.create - ready := !w.busy && cr.ready() - problem := a.branchNameErrorText(cr.preview.Error) - choices := cr.referenceChoices(w.list) + ready := !w.busy && cr.result.Ready + problem := "" + if cr.result.Branch != nil { + problem = a.branchNameErrorText(cr.result.Branch.Error) + } + // Core names the choices by their places in the references the dialog read. + choices := make([]core.GitReference, 0, len(cr.result.Choices)) + for _, i := range cr.result.Choices { + if i >= 0 && i < len(cr.refs.References) { + choices = append(choices, cr.refs.References[i]) + } + } names := make([]string, len(choices)) for i, r := range choices { names[i] = r.FullName @@ -795,7 +804,7 @@ func (a *App) drawWorktreeCreateDialog(c ui.C, p *project) { ui.Paragraph(c, t.DetachedHint, 3).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) } submitted = ui.TextField(c, &cr.destination, t.Destination, t.Destination).FillWidth().Submitted() || submitted - if !filepath.IsAbs(strings.TrimSpace(cr.destination.Text())) { + if !cr.result.DestinationIsAbsolute { ui.Paragraph(c, t.DestinationAbsolute, 3).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) } ui.Checkbox(c, &cr.noCheckout, t.NoCheckout).Disabled(w.busy) From cff3cd72fa7e3fd853a3b145d6627cf483556a7c Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 08:28:51 +0800 Subject: [PATCH 05/11] =?UTF-8?q?fix(desktop):=20Diff=20=E6=9F=A5=E6=89=BE?= =?UTF-8?q?=E6=94=B9=E7=94=A8=20Core=20editor.find?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Diff 页签的查找栏不再自己用 Go 转小写匹配(遇到小写后字节变长的字符就退回区分大小写), 改为在后台对两侧编辑器的快照逐个调用 Core 的 editor.find,与编辑器查找栏同一套规则: Unicode 大小写折叠、匹配上限 10000 处(计数显示 n+)。新查询或关闭查找栏会取消进行中的 查找;两侧文本在查找期间变化时丢弃结果并重新查找;匹配会在两侧编辑器里高亮。 Closes #1847 --- desktop/internal/workbench/diff_find.go | 189 +++++++++++++++------ desktop/internal/workbench/difftab_test.go | 23 +-- desktop/internal/workbench/difftab_view.go | 2 +- 3 files changed, 149 insertions(+), 65 deletions(-) diff --git a/desktop/internal/workbench/diff_find.go b/desktop/internal/workbench/diff_find.go index a30d16e31f..9b913a51ae 100644 --- a/desktop/internal/workbench/diff_find.go +++ b/desktop/internal/workbench/diff_find.go @@ -1,10 +1,14 @@ package workbench import ( + "context" + "errors" "runtime" "strconv" "strings" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" @@ -12,11 +16,13 @@ import ( "github.com/vivaui/viva/ui" ) -// This file is the find bar of the Diff tab (matrix id git-diff-review): it searches the text the -// two side editors show, without case where the case folds to the same length, and moves from -// one match to the next by selecting it in its editor, which reveals it. The toolbar opens the bar -// (difftab_view.go). Ignoring whitespace is a read option of the diff (difftab_whitespace.go), and -// the word ranges come with Core's diff (difftab_view.go). +// This file is the find bar of the Diff tab (matrix id git-diff-review): it has Core search the +// text the two side editors show, without case, and moves from one match to the next by +// selecting it in its editor, which reveals it. Matching is Core's editor.find, the rule the +// editors' find bar uses, run on a worker over each side's immutable snapshot; the bar keeps the +// query, the matches of the snapshots they were found in and the current one. The toolbar opens +// the bar (difftab_view.go). Ignoring whitespace is a read option of the diff +// (difftab_whitespace.go), and the word ranges come with Core's diff (difftab_view.go). // diffMatch is one occurrence of the query: the editor it is in and its byte range there. type diffMatch struct { @@ -28,66 +34,134 @@ type diffMatch struct { type diffFind struct { open bool field ui.Field - // query is the text the matches were computed for; computed says they were. - query string - computed bool - matches []diffMatch - current int + // query and snapshots are what the matches were asked for: the typed text and the text of + // each searched editor, in the order of views; computed says they were asked for. + query string + views []*editorview.View + snapshots []rope.Rope + computed bool + // pending is set while Core searches; gen tells its answer from a later search's, and + // cancel gives it up. + pending bool + gen uint64 + cancel context.CancelFunc + matches []diffMatch + // truncated says Core stopped at its bound of matches in a side. + truncated bool + current int } -// diffFindMatches finds every case-insensitive occurrence of query in the text of views. -func diffFindMatches(query string, views ...*editorview.View) []diffMatch { - if query == "" { - return nil - } - needle := strings.ToLower(query) - var out []diffMatch - for _, v := range views { - if v == nil { - continue - } - raw, _ := v.Text() - haystack := string(raw) - folded := strings.ToLower(haystack) - if len(folded) != len(haystack) { - folded = haystack - needle = query +// diffFindViews are the editors of t the bar searches, in the order their matches come. +func (t *diffTab) diffFindViews() []*editorview.View { + var views []*editorview.View + if t.before != nil { + views = append(views, t.before.view) + } + if t.after != nil { + views = append(views, t.after.view) + } + return views +} + +// diffFindCurrent reports whether the matches were asked for query in the texts views show now. +func (f *diffFind) diffFindCurrent(query string, views []*editorview.View) bool { + if !f.computed || query != f.query || len(views) != len(f.views) { + return false + } + for i, v := range views { + if v != f.views[i] || !v.TextSnapshot().Same(f.snapshots[i]) { + return false } - for at := 0; ; { - i := strings.Index(folded[at:], needle) - if i < 0 { + } + return true +} + +// refreshDiffFind has Core search the sides again when the typed query or the text they show +// changed. The search runs on a worker over the sides' snapshots; a newer one or closing the +// bar gives it up, and an answer for text the sides no longer show is dropped and asked again. +func (a *App) refreshDiffFind(p *project, t *diffTab) { + f := &t.find + query, views := f.field.Text(), t.diffFindViews() + if f.diffFindCurrent(query, views) { + return + } + f.stopDiffFind() + f.query, f.views, f.computed = query, views, true + f.snapshots = make([]rope.Rope, len(views)) + for i, v := range views { + f.snapshots[i] = v.TextSnapshot() + } + f.matches, f.truncated, f.current = nil, false, 0 + kernel, ok := a.kernel.(editorFindKernel) + if query == "" || len(views) == 0 || !ok { + return + } + ctx, cancel := context.WithTimeout(p.ctx, kernelCallTimeout) + f.cancel, f.pending = cancel, true + gen, snapshots := f.gen, f.snapshots + a.background(p, kernelCallTimeout, func(context.Context) func(*App) { + defer cancel() + var found []diffMatch + truncated := false + var err error + for i, v := range views { + var result core.EditorFindResult + if result, err = kernel.FindEditorText(ctx, snapshots[i].Bytes(), core.EditorFindRequest{Query: query}); err != nil { break } - start := at + i - out = append(out, diffMatch{view: v, start: start, end: start + len(needle)}) - at = start + max(len(needle), 1) + for _, m := range result.Matches { + found = append(found, diffMatch{view: v, start: m.Start, end: m.End}) + } + truncated = truncated || result.Truncated } - } - return out + return func(a *App) { a.applyDiffFind(t, gen, found, truncated, err) } + }) } -// refreshDiffFind recomputes the matches when the typed query changed and selects the current one. -func (a *App) refreshDiffFind(t *diffTab) { - q := t.find.field.Text() - if t.find.computed && q == t.find.query { +// applyDiffFind shows the matches of the search gen when it is still the bar's own, marking +// them in their editors and selecting the first. +func (a *App) applyDiffFind(t *diffTab, gen uint64, found []diffMatch, truncated bool, err error) { + f := &t.find + if !f.open || f.gen != gen { return } - t.find.query, t.find.computed = q, true - t.find.current = 0 - t.find.matches = nil - if t.before != nil || t.after != nil { - var views []*editorview.View - if t.before != nil { - views = append(views, t.before.view) + f.pending, f.cancel = false, nil + if !f.diffFindCurrent(f.field.Text(), t.diffFindViews()) { + f.computed = false // the sides changed under the search; the next draw asks again + return + } + if err != nil { + if !errors.Is(err, context.Canceled) { + a.gitOperationFailed("diff_find", err) } - if t.after != nil { - views = append(views, t.after.view) + return + } + f.matches, f.truncated = found, truncated + for _, v := range f.views { + var ranges []editorview.Range + for _, m := range found { + if m.view == v { + ranges = append(ranges, editorview.Range{Start: m.start, End: m.end}) + } } - t.find.matches = diffFindMatches(q, views...) + v.SetSearchMatches(ranges) } a.selectDiffMatch(t) } +// stopDiffFind gives up the search under way and the marks of the last one. +func (f *diffFind) stopDiffFind() { + f.gen++ + if f.cancel != nil { + f.cancel() + f.cancel = nil + } + f.pending = false + for _, v := range f.views { + v.ClearSearchMatches() + } +} + // selectDiffMatch selects the current match in its editor, so that the editor reveals it. func (a *App) selectDiffMatch(t *diffTab) { if t.find.current < 0 || t.find.current >= len(t.find.matches) { @@ -107,15 +181,16 @@ func (a *App) stepDiffFind(t *diffTab, by int) { a.selectDiffMatch(t) } -// closeDiffFind closes the bar and forgets its matches. +// closeDiffFind closes the bar and forgets its matches, giving up a search under way. func (t *diffTab) closeDiffFind() { - t.find = diffFind{} + t.find.stopDiffFind() + t.find = diffFind{gen: t.find.gen} } // diffFindBar declares the find bar over the Diff tab: the query field, how many matches there // are and which one is current, and the previous, next and close buttons. -func (a *App) diffFindBar(c ui.C, t *diffTab) { - a.refreshDiffFind(t) +func (a *App) diffFindBar(c ui.C, p *project, t *diffTab) { + a.refreshDiffFind(p, t) n := len(t.find.matches) lang := a.language() ui.Row(c).FillWidth().Height(logToolbarHeight).Shrink(0).Items(ui.Center).Gap(4).PadX(6).Children(func() { @@ -123,8 +198,14 @@ func (a *App) diffFindBar(c ui.C, t *diffTab) { c.After(func() { a.stepDiffFind(t, 1) }) } count := "0/0" - if n > 0 { + switch { + case t.find.pending: + count = i18n.Shared(lang, "desktop.editorFind.loading") + case n > 0: count = strconv.Itoa(t.find.current+1) + "/" + strconv.Itoa(n) + if t.find.truncated { + count += "+" // Core stopped at its bound of matches in a side + } } ui.Text(c, count).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Shrink(0) if a.gitIconButton(c, i18n.Shared(lang, "desktop.diffFind.previous"), icons.ArrowUp, false, n == 0) { diff --git a/desktop/internal/workbench/difftab_test.go b/desktop/internal/workbench/difftab_test.go index 98400f1544..4101483a28 100644 --- a/desktop/internal/workbench/difftab_test.go +++ b/desktop/internal/workbench/difftab_test.go @@ -339,7 +339,7 @@ func TestDiffTabSidesScrollInStep(t *testing.T) { func TestDiffTabFindsIgnoresWhitespaceAndEditsTheWorkingCopy(t *testing.T) { dir := newTestRepository(t) commitLongFile(t, dir, numberedLines(20), func(lines []string) []string { - lines[2], lines[10] = " line 3", "line eleven" + lines[2], lines[10] = " line 3", "line eleven Ⱥ" return lines }) h := newHarness(t, &gitKernel{Client: core.NewClient()}) @@ -355,16 +355,19 @@ func TestDiffTabFindsIgnoresWhitespaceAndEditsTheWorkingCopy(t *testing.T) { h.app.setDiffMode(p, d, true, false) h.settle() d.find.open = true - d.find.field.SetText("ELEVEN") - h.app.refreshDiffFind(d) - if m := d.find.matches; len(m) != 1 || m[0].view != d.after.view { - t.Fatalf("the find bar found %+v for ELEVEN, want the new side's line", m) - } - d.find.field.SetText("line 11") - h.app.refreshDiffFind(d) - if m := d.find.matches; len(m) != 1 || m[0].view != d.before.view { - t.Fatalf("the find bar found %+v for line 11, want the old side's line", m) + find := func(query string, want *editorview.View) { + t.Helper() + d.find.field.SetText(query) + h.app.refreshDiffFind(p, d) + h.await("the matches of "+query, func() bool { return !d.find.pending }) + if m := d.find.matches; len(m) != 1 || m[0].view != want { + t.Fatalf("the find bar found %+v for %q, want one match in %p", m, query, want) + } } + find("ELEVEN", d.after.view) + find("line 11", d.before.view) + // Ⱥ lowercases to ⱥ, which takes a byte more; Core folds case on the text as it is. + find("ⱥ", d.after.view) h.app.stepDiffFind(d, 1) if d.find.current != 0 { t.Fatalf("stepping past the only match went to %d", d.find.current) diff --git a/desktop/internal/workbench/difftab_view.go b/desktop/internal/workbench/difftab_view.go index 9de9c2b197..a7198b58fb 100644 --- a/desktop/internal/workbench/difftab_view.go +++ b/desktop/internal/workbench/difftab_view.go @@ -55,7 +55,7 @@ func (a *App) diffView(c ui.C, p *project, t *diffTab) { a.diffToolbar(c, p, t) ui.Divider(c) if t.find.open && t.file != nil { - a.diffFindBar(c, t) + a.diffFindBar(c, p, t) } a.diffSides(c, t) ui.Divider(c) From 34beb24b0b75e1194b50eaeb4524cafe99414e01 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 08:38:09 +0800 Subject: [PATCH 06/11] =?UTF-8?q?refactor(desktop):=20=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=E5=90=AF=E7=94=A8=E8=A7=84=E5=88=99=E5=92=8C=E7=94=9F=E5=91=BD?= =?UTF-8?q?=E5=91=A8=E6=9C=9F=E6=AD=A5=E9=AA=A4=E6=94=B9=E7=94=B1=20Core?= =?UTF-8?q?=20=E5=86=B3=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 core.PlanPluginLifecycle,调用 plugins.installed.lifecycle: Core 按插件回答启用状态,并为确认安装、启用、禁用、卸载给出有序步骤 - pluginstate 只保存用户选择,去掉 Enabled、EnableUnlessChosen - pluginmanager.Manager.Apply 按步骤执行删版本、删批准记录、忘记选择、 删状态目录和停止插件程序,未安装插件报 ErrUnknownPlugin - pluginservice 的 Uninstall、Disable 改走 Apply,停止程序由调用方传入 - 更新安装即启用、卸载清理状态的 Agent Note Closes #1842 --- ...tall-enables-and-uninstall-cleans-state.md | 18 +- desktop/internal/core/plugin_lifecycle.go | 118 +++++++++++ .../internal/pluginmanager/pluginmanager.go | 192 ++++++++++-------- .../pluginmanager/pluginmanager_test.go | 82 ++++++-- desktop/internal/pluginservice/lifecycle.go | 25 +-- .../internal/pluginservice/lifecycle_test.go | 8 +- .../internal/pluginservice/pluginservice.go | 3 +- .../pluginservice/pluginservice_test.go | 4 + desktop/internal/pluginstate/pluginstate.go | 56 +---- .../internal/pluginstate/pluginstate_test.go | 91 +++------ 10 files changed, 359 insertions(+), 238 deletions(-) create mode 100644 desktop/internal/core/plugin_lifecycle.go diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-viva-plugin-install-enables-and-uninstall-cleans-state.md b/.agents/notes/implemented/bug-fix/2026-11-13-viva-plugin-install-enables-and-uninstall-cleans-state.md index 949d0a0028..d0dea8e209 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-13-viva-plugin-install-enables-and-uninstall-cleans-state.md +++ b/.agents/notes/implemented/bug-fix/2026-11-13-viva-plugin-install-enables-and-uninstall-cleans-state.md @@ -18,9 +18,13 @@ Viva 客户端从插件市场装好插件后,插件默认是禁用的,用户 ## 决策 -- **确认安装即启用**:`pluginstate.Store.EnableUnlessChosen` 在同一把锁里检查并写入:没有记录才写 `enabled: true`,有记录(无论启用还是禁用)都保留。`pluginmanager.Manager.EnableInstalled` 先确认插件已安装,再调用它。工作台在 `confirmPluginInstall` 提交成功后(包括只是批准记录写入失败的 `ApprovalError`)调用一次。卸载时 `Forget` 清除选择,所以“卸载后重装”又会启用。 -- **卸载顺序**:`pluginservice.Service.Uninstall(ctx, id, server)` 先摘除并停止后端、停止语言服务器(`Runner.Stop` 等到 Core 销毁会话才返回,进程此时已经退出),再调用 `Manager.Uninstall`。工作台在窗口线程先用 `detachPluginServer` 把语言服务器移出登记表(不再接收请求、不会被重新启动),再把会话交给后台的 `Service.Uninstall`。 -- **禁用顺序**:`Service.Disable` 先记录禁用,再停止语言服务器和后端,这样停止期间没有路径会把插件重新拉起来。 +启用规则和每个动作的步骤顺序由 Core 命令 `plugins.installed.lifecycle` 决定(实现在 Core 的 `rust/crates/plugin-lifecycle`,规则表和用例在 `rust/fixtures/plugins/installed-lifecycle.json`)。客户端只保存用户的选择、插件包和批准记录,把它们的身份交给 Core,再按 Core 返回的步骤逐条执行文件和进程操作。这样 Windows、macOS 和以后换的界面外壳共用同一套规则,不会各自再写一份。 + +- **谁是“启用”**:Core 按“插件”而不是“版本”回答启用状态,没有用户选择就是禁用。`pluginstate` 只读写选择(`SetEnabled`、`Forget`、`List`),不再自己判断启用;`pluginmanager.Manager.Installed` 用 Core 的回答。 +- **确认安装即启用**:确认安装时,没有选择 Core 才返回“记录启用”这一步,有选择(无论启用还是禁用)就没有步骤。工作台在 `confirmPluginInstall` 提交成功后(包括只是批准记录写入失败的 `ApprovalError`)调用一次 `Manager.EnableInstalled`。卸载时 Core 返回“忘掉选择”,所以“卸载后重装”又会启用。 +- **卸载顺序**:Core 返回的步骤依次是:停止插件程序 → 删除每个已安装版本(删成功才删它的批准记录)→ 忘掉选择 → 删除状态目录。`pluginmanager.Manager.Apply` 按顺序执行并汇总每个失败,“停止插件程序”由调用方传入:`pluginservice.Service.Uninstall(ctx, id, server)` 传的是先摘除并停止后端、再停止语言服务器(`Runner.Stop` 等到 Core 销毁会话才返回,进程此时已经退出)。工作台在窗口线程先用 `detachPluginServer` 把语言服务器移出登记表(不再接收请求、不会被重新启动),再把会话交给后台的 `Service.Uninstall`。 +- **禁用顺序**:Core 先返回“记录禁用”,再返回“停止插件程序”,这样停止期间没有路径会把插件重新拉起来。 +- **未安装的插件**:对没有安装版本的插件启用、禁用或卸载,Core 返回拒绝 `plugin.lifecycle.notInstalled`,`Manager` 报 `ErrUnknownPlugin`,不写任何选择,避免以后安装时被悄悄启用。 - **状态目录**:`pluginpkg.StateDirectory` 是 `.state` 的唯一定义(`pluginservice` 的 `pluginStateDirectory` 引用它)。`pluginpkg.RemoveState` 和卸载包一样,先把 `.state/<插件 ID>` 改名进 `.trash`,再递归删除,删除失败也不会把半份状态留在下次安装会读取的位置;它只处理目录,不跟随符号链接。`.state/host-secret` 和其他插件的目录不动。插件设置保存在应用偏好目录,不在 `.state` 里,所以卸载不会丢用户设置。 ## 考虑过的备选方案 @@ -35,12 +39,12 @@ Viva 客户端从插件市场装好插件后,插件默认是禁用的,用户 - 用户从商店装好带语言服务器的插件,打开对应文件即可使用。 - 卸载会删除插件的全部运行时状态,包括较大的源码副本和索引;重装后需要重新生成,首次跳转进 JDK 会再解压一次。 - 卸载时要等进程停止(有界:语言服务器最长按 `pluginInstallTimeout`,后端按 `backendStopTimeout`),再删文件,卸载完成会稍晚出现在界面上。 -- 构建 Provider、VCS Provider 和调试适配器进程仍没有在删包前停止,已建单 #1843。工作台三处写死 `".state"` 的路径拼接已建单 #1841。启用规则和卸载顺序仍在 Go 平台层,迁入 Core 已建单 #1842。 +- 构建 Provider、VCS Provider 和调试适配器进程仍没有在删包前停止,已建单 #1843。工作台三处写死 `".state"` 的路径拼接已建单 #1841。启用规则和步骤顺序已按 #1842 迁入 Core。 ## 验证 -- `scripts/desktop/desktop-go.sh test ./internal/pluginstate ./internal/pluginmanager ./internal/pluginpkg ./internal/pluginservice ./internal/workbench -count=1`: - - `TestEnableUnlessChosenRecordsOnlyAFirstChoice`:没有记录时启用,有明确禁用时不改。 +- `scripts/desktop/desktop-go.sh test ./internal/core ./internal/pluginstate ./internal/pluginmanager ./internal/pluginpkg ./internal/pluginservice ./internal/workbench -count=1`: + - Core 仓库 `cargo test -p lithe-core --lib installed_lifecycle`:逐条跑 `installed-lifecycle.json` 的用例,覆盖首次确认安装、禁用后更新保持禁用、卸载的步骤顺序、未安装插件的拒绝和非法请求。 - `TestEnableInstalledKeepsAnExplicitChoice`:首次安装启用、禁用后升级保持禁用、未安装报 `ErrUnknownPlugin`、卸载后重装又启用。 - `TestUninstallRemovesThePluginState`:删除本插件的 `.state/<插件 ID>`(含版本目录和 `pages/workspaces`),保留其他插件和 `host-secret`。 - `TestUninstallStopsTheBackendBeforeRemovingThePlugin`、`TestDisableStopsTheBackend`:后端在删包前停止、禁用先记录后停止、其他插件后端不受影响。 @@ -49,4 +53,4 @@ Viva 客户端从插件市场装好插件后,插件默认是禁用的,用户 ## 适用范围 -Viva 客户端(`desktop/`)的插件安装、启用、禁用和卸载:`desktop/internal/pluginstate/`、`desktop/internal/pluginmanager/`、`desktop/internal/pluginpkg/install.go`、`desktop/internal/pluginservice/lifecycle.go`、`desktop/internal/workbench/plugins.go`。旧 Swift/Tauri 客户端的规则以各自原 Note 为准。 +Viva 客户端(`desktop/`)的插件安装、启用、禁用和卸载:Core 的 `plugins.installed.lifecycle`、`desktop/internal/core/plugin_lifecycle.go`、`desktop/internal/pluginstate/`、`desktop/internal/pluginmanager/`、`desktop/internal/pluginpkg/install.go`、`desktop/internal/pluginservice/lifecycle.go`、`desktop/internal/workbench/plugins.go`。旧 Swift/Tauri 客户端的规则以各自原 Note 为准。 diff --git a/desktop/internal/core/plugin_lifecycle.go b/desktop/internal/core/plugin_lifecycle.go new file mode 100644 index 0000000000..1f28d5ce27 --- /dev/null +++ b/desktop/internal/core/plugin_lifecycle.go @@ -0,0 +1,118 @@ +package core + +import "context" + +// PluginLifecycleAction is what the user does to an installed plugin. +type PluginLifecycleAction string + +// The actions plugins.installed.lifecycle plans. +const ( + // PluginConfirmInstall is the user confirming the installation of a version now on disk. + PluginConfirmInstall PluginLifecycleAction = "confirmInstall" + // PluginEnable is the user turning the plugin on. + PluginEnable PluginLifecycleAction = "enable" + // PluginDisable is the user turning the plugin off. + PluginDisable PluginLifecycleAction = "disable" + // PluginUninstall is the user removing the plugin. + PluginUninstall PluginLifecycleAction = "uninstall" +) + +// PluginNotInstalled is the rejection of an action on a plugin that has no installed version. +const PluginNotInstalled = "plugin.lifecycle.notInstalled" + +// The kinds of PluginLifecycleStep, all on the action's plugin. +const ( + // PluginRecordChoice records the user's choice, Enabled. + PluginRecordChoice = "recordChoice" + // PluginForgetChoice drops the user's choice. + PluginForgetChoice = "forgetChoice" + // PluginStopPrograms stops the language server and the backend, returning once they ended + // or gave up. + PluginStopPrograms = "stopPrograms" + // PluginRemoveVersion removes installed version Version, then forgets its approval; the + // approval stays when the version could not be removed. + PluginRemoveVersion = "removeVersion" + // PluginRemoveState removes the state directory the plugin's programs wrote. + PluginRemoveState = "removeState" +) + +// PluginInstalledVersion is one installed plugin version, by identity only. +type PluginInstalledVersion struct { + PluginID string `json:"pluginID"` + Version string `json:"version"` +} + +// PluginEnablement is one plugin and whether it is enabled: a choice the user made, or a +// plugin's enablement as Core reports it. +type PluginEnablement struct { + PluginID string `json:"pluginID"` + Enabled bool `json:"enabled"` +} + +// PluginLifecycleRequest is every installed version and every choice the user made, and the +// action, if any, on one plugin. +type PluginLifecycleRequest struct { + Installed []PluginInstalledVersion + Choices []PluginEnablement + // Action is empty when only enablement is asked for. + Action PluginLifecycleAction + PluginID string +} + +// PluginLifecycleStep is one thing the host does on the action's plugin. +type PluginLifecycleStep struct { + Kind string `json:"kind"` + Enabled bool `json:"enabled,omitempty"` + Version string `json:"version,omitempty"` +} + +// PluginLifecycle is Core's answer: every installed plugin with its enablement once the steps +// ran, whether they change the plugin's choice, and the steps in order. Rejection is set, and +// there are no steps, when the action does not apply. +type PluginLifecycle struct { + Plugins []PluginEnablement `json:"plugins"` + Changed bool `json:"changed"` + Steps []PluginLifecycleStep `json:"steps"` + Rejection string `json:"rejection,omitempty"` +} + +// PlanPluginLifecycle has Core report installed plugins' enablement and plan request's action +// (plugins.installed.lifecycle). The host keeps the packages, approvals, choices and programs +// and carries the steps out in order, reporting every failure. +func (c *Client) PlanPluginLifecycle(ctx context.Context, request PluginLifecycleRequest) (PluginLifecycle, error) { + const command = "plugins.installed.lifecycle" + type action struct { + Kind PluginLifecycleAction `json:"kind"` + PluginID string `json:"pluginID"` + } + payload := struct { + Installed []PluginInstalledVersion `json:"installed"` + Choices []PluginEnablement `json:"choices"` + Action *action `json:"action,omitempty"` + }{Installed: request.Installed, Choices: request.Choices} + if payload.Installed == nil { + payload.Installed = []PluginInstalledVersion{} + } + if payload.Choices == nil { + payload.Choices = []PluginEnablement{} + } + if request.Action != "" { + payload.Action = &action{Kind: request.Action, PluginID: request.PluginID} + } + var result PluginLifecycle + if err := c.Execute(ctx, command, payload, &result); err != nil { + return PluginLifecycle{}, err + } + for _, step := range result.Steps { + switch step.Kind { + case PluginRecordChoice, PluginForgetChoice, PluginStopPrograms, PluginRemoveState: + case PluginRemoveVersion: + if step.Version == "" { + return PluginLifecycle{}, newParseError(command, "a removeVersion step has no version", "") + } + default: + return PluginLifecycle{}, newParseError(command, "unknown lifecycle step", step.Kind) + } + } + return result, nil +} diff --git a/desktop/internal/pluginmanager/pluginmanager.go b/desktop/internal/pluginmanager/pluginmanager.go index 5e68c93e8f..77b4c083f7 100644 --- a/desktop/internal/pluginmanager/pluginmanager.go +++ b/desktop/internal/pluginmanager/pluginmanager.go @@ -2,17 +2,20 @@ // plugins. // // It owns no policy of its own: extracting and installing belongs to pluginpkg, -// approving to plugintrust, enablement to pluginstate. What it adds is the -// lifecycle that spans them, which is where the mistakes live — forgetting an -// approval when the package is removed, keeping a user's enablement choice while -// another version of the same plugin is still installed, and dropping it when the -// last one goes. +// approving to plugintrust, storing enablement choices to pluginstate, and the +// lifecycle that spans them to Core (plugins.installed.lifecycle) — which plugin +// is enabled, what confirming an install, enabling, disabling and uninstalling +// do, and in which order. The manager hands Core the installed versions and the +// choices, and carries out the steps it gets back. package pluginmanager import ( + "context" "errors" "fmt" + "time" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginstate" "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" @@ -21,123 +24,155 @@ import ( // ErrUnknownPlugin reports a plugin that has no installed version. var ErrUnknownPlugin = errors.New("plugin is not installed") +// planTimeout bounds one Core plan asked for without a caller's context. Core answers from +// the identities it is given, without reading a file. +const planTimeout = 5 * time.Second + +// Kernel is the Core the manager asks for the lifecycle rules. +type Kernel interface { + PlanPluginLifecycle(context.Context, core.PluginLifecycleRequest) (core.PluginLifecycle, error) +} + // Entry is one installed plugin version and whether its plugin is enabled. type Entry struct { // Installed is the package on disk. Installed pluginpkg.Installed - // Enabled is the user's choice for this plugin, not for this version. + // Enabled is the plugin's enablement, not this version's. Enabled bool } // Manager ties the installed packages to their approval records and enablement // choices. type Manager struct { + kernel Kernel root string approvals *plugintrust.Store state *pluginstate.Store } // New returns a manager for the plugin root root. -func New(root string, approvals *plugintrust.Store, state *pluginstate.Store) *Manager { - return &Manager{root: root, approvals: approvals, state: state} +func New(kernel Kernel, root string, approvals *plugintrust.Store, state *pluginstate.Store) *Manager { + return &Manager{kernel: kernel, root: root, approvals: approvals, state: state} } // Installed reports every installed version with its plugin's enablement. func (m *Manager) Installed() ([]Entry, error) { - installed, err := pluginpkg.List(m.root) + ctx, cancel := context.WithTimeout(context.Background(), planTimeout) + defer cancel() + installed, plan, err := m.plan(ctx, "", "") if err != nil { return nil, err } + enabled := make(map[string]bool, len(plan.Plugins)) + for _, plugin := range plan.Plugins { + enabled[plugin.PluginID] = plugin.Enabled + } entries := make([]Entry, 0, len(installed)) for _, packageEntry := range installed { - enabled, err := m.state.Enabled(packageEntry.ID) - if err != nil { - return nil, err - } - entries = append(entries, Entry{Installed: packageEntry, Enabled: enabled}) + entries = append(entries, Entry{Installed: packageEntry, Enabled: enabled[packageEntry.ID]}) } return entries, nil } -// Uninstall removes every installed version of a plugin, drops their approvals, -// the enablement choice and the plugin's state directory, so a later -// installation starts as a first one. -// -// Every version goes: installing does not remove an earlier one, and the plugin -// page shows one row per plugin, so leaving an older version behind would keep the -// plugin installed after the user removed it. +// Apply carries out action on plugin id as Core plans it, and reports whether it +// changed the user's choice for the plugin. stop stops what the plugin runs and +// returns once it ended; nil means the caller runs nothing of the plugin. // -// The packages are removed before anything else, so a failure to clean up a record -// never leaves a half-removed package that still looks installed. Such a failure is -// returned and the caller should log it; the next installation of an affected -// version asks the user again. -func (m *Manager) Uninstall(id string) error { - installed, err := pluginpkg.List(m.root) +// Steps run in Core's order and a failed one does not stop the rest, so a failure +// to clean up one record never leaves a half-removed package that still looks +// installed; every failure is returned for the caller to log. An approval is only +// forgotten once its version is gone, so the next installation of a version that +// could not be removed asks the user again. +func (m *Manager) Apply(ctx context.Context, action core.PluginLifecycleAction, id string, stop func() error) (bool, error) { + _, plan, err := m.plan(ctx, action, id) if err != nil { - return err + return false, err } - var versions []string - for _, entry := range installed { - if entry.ID == id { - versions = append(versions, entry.Version) - } + if plan.Rejection == core.PluginNotInstalled { + return false, fmt.Errorf("%w: %s", ErrUnknownPlugin, id) } - if len(versions) == 0 { - return fmt.Errorf("%w: %s", ErrUnknownPlugin, id) + if plan.Rejection != "" { + return false, fmt.Errorf("the plugin lifecycle of %s was refused: %s", id, plan.Rejection) } var failures []error - for _, version := range versions { - if err := pluginpkg.Uninstall(m.root, id, version); err != nil { - failures = append(failures, err) - continue + for _, step := range plan.Steps { + switch step.Kind { + case core.PluginRecordChoice: + if err := m.state.SetEnabled(id, step.Enabled); err != nil { + failures = append(failures, fmt.Errorf("record the enablement of %s: %w", id, err)) + } + case core.PluginForgetChoice: + if err := m.state.Forget(id); err != nil { + failures = append(failures, fmt.Errorf("forget the enablement of %s: %w", id, err)) + } + case core.PluginStopPrograms: + if stop != nil { + if err := stop(); err != nil { + failures = append(failures, err) + } + } + case core.PluginRemoveVersion: + if err := pluginpkg.Uninstall(m.root, id, step.Version); err != nil { + failures = append(failures, err) + continue + } + if err := m.approvals.Forget(id, step.Version); err != nil { + failures = append(failures, fmt.Errorf("forget the approval of %s %s: %w", id, step.Version, err)) + } + case core.PluginRemoveState: + if err := pluginpkg.RemoveState(m.root, id); err != nil { + failures = append(failures, fmt.Errorf("remove the state of %s: %w", id, err)) + } } - if err := m.approvals.Forget(id, version); err != nil { - failures = append(failures, fmt.Errorf("forget the approval of %s %s: %w", id, version, err)) - } - } - if err := m.state.Forget(id); err != nil { - failures = append(failures, fmt.Errorf("forget the enablement of %s: %w", id, err)) } - // What the plugin's programs wrote goes with it: an uninstalled plugin - // leaves nothing behind, and a later installation starts clean. The - // caller stops those programs first, or they could write it again. - if err := pluginpkg.RemoveState(m.root, id); err != nil { - failures = append(failures, fmt.Errorf("remove the state of %s: %w", id, err)) - } - return errors.Join(failures...) + return plan.Changed, errors.Join(failures...) } -// SetEnabled records an enablement choice for a plugin that has an installed -// version. Enabling a plugin that is not installed would silently enable it the -// moment a later installation lands. +// SetEnabled records the user turning an installed plugin on or off. It stops +// nothing; pluginservice.Service.Disable also stops what a disabled plugin runs. func (m *Manager) SetEnabled(id string, enabled bool) error { - installed, err := pluginpkg.List(m.root) - if err != nil { - return err - } - if !installsID(installed, id) { - return fmt.Errorf("%w: %s", ErrUnknownPlugin, id) + action := core.PluginDisable + if enabled { + action = core.PluginEnable } - return m.state.SetEnabled(id, enabled) + ctx, cancel := context.WithTimeout(context.Background(), planTimeout) + defer cancel() + _, err := m.Apply(ctx, action, id, nil) + return err } -// EnableInstalled enables a plugin the user just confirmed installing, unless -// the user already chose to enable or disable it, and reports whether it -// changed the choice. The plugin must be installed. +// EnableInstalled records that the user confirmed installing plugin id, which +// enables it unless the user already chose to enable or disable it, and reports +// whether it changed the choice. func (m *Manager) EnableInstalled(id string) (bool, error) { + ctx, cancel := context.WithTimeout(context.Background(), planTimeout) + defer cancel() + return m.Apply(ctx, core.PluginConfirmInstall, id, nil) +} + +// plan lists the installed versions and the choices and asks Core for the plan of +// action on plugin id; an empty action only asks for enablement. +func (m *Manager) plan(ctx context.Context, action core.PluginLifecycleAction, id string) ([]pluginpkg.Installed, core.PluginLifecycle, error) { installed, err := pluginpkg.List(m.root) if err != nil { - return false, err + return nil, core.PluginLifecycle{}, err } - if !installsID(installed, id) { - return false, fmt.Errorf("%w: %s", ErrUnknownPlugin, id) + choices, err := m.state.List() + if err != nil { + return nil, core.PluginLifecycle{}, err } - return m.state.EnableUnlessChosen(id) -} - -// Enabled reports whether a plugin is enabled. -func (m *Manager) Enabled(id string) (bool, error) { - return m.state.Enabled(id) + request := core.PluginLifecycleRequest{Action: action, PluginID: id} + for _, entry := range installed { + request.Installed = append(request.Installed, core.PluginInstalledVersion{PluginID: entry.ID, Version: entry.Version}) + } + for _, choice := range choices { + request.Choices = append(request.Choices, core.PluginEnablement{PluginID: choice.PluginID, Enabled: choice.Enabled}) + } + plan, err := m.kernel.PlanPluginLifecycle(ctx, request) + if err != nil { + return nil, core.PluginLifecycle{}, fmt.Errorf("plan the plugin lifecycle: %w", err) + } + return installed, plan, nil } // Approval reports what the user approved when this version was installed: where @@ -146,12 +181,3 @@ func (m *Manager) Enabled(id string) (bool, error) { func (m *Manager) Approval(id, version string) (plugintrust.Record, bool, error) { return m.approvals.Record(id, version) } - -func installsID(installed []pluginpkg.Installed, id string) bool { - for _, entry := range installed { - if entry.ID == id { - return true - } - } - return false -} diff --git a/desktop/internal/pluginmanager/pluginmanager_test.go b/desktop/internal/pluginmanager/pluginmanager_test.go index 317129d7b5..13a5b19918 100644 --- a/desktop/internal/pluginmanager/pluginmanager_test.go +++ b/desktop/internal/pluginmanager/pluginmanager_test.go @@ -1,11 +1,13 @@ package pluginmanager import ( + "context" "errors" "os" "path/filepath" "testing" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginstate" "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" @@ -18,7 +20,43 @@ func newManager(t *testing.T) (*Manager, *plugintrust.Store, *pluginstate.Store, approvals := plugintrust.New(store.At(t.TempDir())) state := pluginstate.New(store.At(t.TempDir())) root := t.TempDir() - return New(root, approvals, state), approvals, state, root + return New(core.NewClient(), root, approvals, state), approvals, state, root +} + +// uninstall removes plugin id; nothing of it runs in these tests. +func uninstall(manager *Manager, id string) error { + _, err := manager.Apply(context.Background(), core.PluginUninstall, id, nil) + return err +} + +// enabled reports whether plugin id is installed and enabled. +func enabled(t *testing.T, manager *Manager, id string) bool { + t.Helper() + entries, err := manager.Installed() + if err != nil { + t.Fatalf("installed: %v", err) + } + for _, entry := range entries { + if entry.Installed.ID == id { + return entry.Enabled + } + } + return false +} + +// recorded reports whether the user's choice for plugin id is stored. +func recorded(t *testing.T, state *pluginstate.Store, id string) bool { + t.Helper() + entries, err := state.List() + if err != nil { + t.Fatalf("list: %v", err) + } + for _, entry := range entries { + if entry.PluginID == id { + return true + } + } + return false } // install puts one plugin version into the root. @@ -87,7 +125,7 @@ func TestUninstallRemovesPackageAndApproval(t *testing.T) { manager, approvals, _, root := newManager(t) install(t, root, "example", "1.0.0") approve(t, approvals, "example", "1.0.0") - if err := manager.Uninstall("example"); err != nil { + if err := uninstall(manager, "example"); err != nil { t.Fatalf("uninstall: %v", err) } if _, err := os.Stat(filepath.Join(root, "example")); !errors.Is(err, os.ErrNotExist) { @@ -104,12 +142,11 @@ func TestUninstallForgetsEnablement(t *testing.T) { if err := manager.SetEnabled("example", true); err != nil { t.Fatal(err) } - if err := manager.Uninstall("example"); err != nil { + if err := uninstall(manager, "example"); err != nil { t.Fatalf("uninstall: %v", err) } - enabled, err := state.Enabled("example") - if err != nil || enabled { - t.Fatalf("enabled = %v, err = %v", enabled, err) + if recorded(t, state, "example") { + t.Fatal("the enablement choice survived the uninstall") } } @@ -119,7 +156,7 @@ func TestUninstallRemovesEveryVersion(t *testing.T) { install(t, root, "example", "1.1.0") approve(t, approvals, "example", "1.0.0") approve(t, approvals, "example", "1.1.0") - if err := manager.Uninstall("example"); err != nil { + if err := uninstall(manager, "example"); err != nil { t.Fatalf("uninstall: %v", err) } // Installing leaves the earlier version on disk, and the plugin page shows one @@ -136,7 +173,7 @@ func TestUninstallRemovesEveryVersion(t *testing.T) { func TestUninstallRefusesAnUnknownPlugin(t *testing.T) { manager, _, _, _ := newManager(t) - if err := manager.Uninstall("example"); !errors.Is(err, ErrUnknownPlugin) { + if err := uninstall(manager, "example"); !errors.Is(err, ErrUnknownPlugin) { t.Fatalf("err = %v", err) } } @@ -148,22 +185,23 @@ func TestSetEnabledRefusesUnknownPlugin(t *testing.T) { } } -func TestSetEnabledAndEnabledRoundTrip(t *testing.T) { +func TestSetEnabledAndInstalledRoundTrip(t *testing.T) { manager, _, _, root := newManager(t) install(t, root, "example", "1.0.0") + if enabled(t, manager, "example") { + t.Fatal("a plugin without a choice is enabled") + } if err := manager.SetEnabled("example", true); err != nil { t.Fatalf("set enabled: %v", err) } - enabled, err := manager.Enabled("example") - if err != nil || !enabled { - t.Fatalf("enabled = %v, err = %v", enabled, err) + if !enabled(t, manager, "example") { + t.Fatal("the enabled plugin is reported disabled") } if err := manager.SetEnabled("example", false); err != nil { t.Fatalf("set disabled: %v", err) } - enabled, err = manager.Enabled("example") - if err != nil || enabled { - t.Fatalf("enabled = %v, err = %v", enabled, err) + if enabled(t, manager, "example") { + t.Fatal("the disabled plugin is reported enabled") } } @@ -189,7 +227,7 @@ func TestUninstallRemovesThePluginState(t *testing.T) { t.Fatal(err) } } - if err := manager.Uninstall("example"); err != nil { + if err := uninstall(manager, "example"); err != nil { t.Fatalf("uninstall: %v", err) } if _, err := os.Stat(filepath.Join(stateRoot, "example")); !errors.Is(err, os.ErrNotExist) { @@ -205,7 +243,7 @@ func TestUninstallRemovesThePluginState(t *testing.T) { // Confirming an installation enables a plugin the user made no choice for, and // keeps a choice the user made, such as disabling it before an update. func TestEnableInstalledKeepsAnExplicitChoice(t *testing.T) { - manager, _, state, root := newManager(t) + manager, _, _, root := newManager(t) install(t, root, "fresh", "1.0.0") install(t, root, "disabled", "1.0.0") if err := manager.SetEnabled("disabled", false); err != nil { @@ -219,19 +257,19 @@ func TestEnableInstalledKeepsAnExplicitChoice(t *testing.T) { if _, err := manager.EnableInstalled(c.id); err != nil { t.Fatalf("enable %s: %v", c.id, err) } - if enabled, err := state.Enabled(c.id); err != nil || enabled != c.want { - t.Fatalf("%s: enabled = %v, err = %v, want %v", c.id, enabled, err, c.want) + if got := enabled(t, manager, c.id); got != c.want { + t.Fatalf("%s: enabled = %v, want %v", c.id, got, c.want) } } if _, err := manager.EnableInstalled("absent"); !errors.Is(err, ErrUnknownPlugin) { t.Fatalf("enabling a plugin that is not installed: %v", err) } // After an uninstall the choice is forgotten, so installing again enables it. - if err := manager.Uninstall("disabled"); err != nil { + if err := uninstall(manager, "disabled"); err != nil { t.Fatal(err) } install(t, root, "disabled", "1.1.0") - if enabled, err := manager.EnableInstalled("disabled"); err != nil || !enabled { - t.Fatalf("reinstall after uninstall: enabled = %v, err = %v", enabled, err) + if changed, err := manager.EnableInstalled("disabled"); err != nil || !changed { + t.Fatalf("reinstall after uninstall: changed = %v, err = %v", changed, err) } } diff --git a/desktop/internal/pluginservice/lifecycle.go b/desktop/internal/pluginservice/lifecycle.go index 53774598b7..98670c2d84 100644 --- a/desktop/internal/pluginservice/lifecycle.go +++ b/desktop/internal/pluginservice/lifecycle.go @@ -2,29 +2,30 @@ package pluginservice import ( "context" - "errors" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" ) -// Uninstall stops what plugin id runs and then removes it. server is the -// plugin's language server session, which the window tracks, or nil; the -// plugin's backend is the host's. Removing it takes every installed version, -// its approvals, the enablement choice and its state directory -// (pluginmanager.Manager.Uninstall). +// Uninstall stops what plugin id runs and then removes it, in the order Core +// plans (pluginmanager.Manager.Apply): every installed version, its approvals, +// the enablement choice and its state directory. server is the plugin's +// language server session, which the window tracks, or nil; the plugin's +// backend is the host's. // // The programs stop first, and Uninstall waits for them (bounded): one still // running could write its state again after the removal, and Windows cannot // move the directory of a program that runs. func (s *Service) Uninstall(ctx context.Context, id string, server *LanguageSession) error { - stopped := s.stopPlugin(ctx, id, server) - return errors.Join(stopped, s.Manager.Uninstall(id)) + _, err := s.Manager.Apply(ctx, core.PluginUninstall, id, func() error { return s.stopPlugin(ctx, id, server) }) + return err } // Disable records that the user turned plugin id off and stops what it runs, -// as Uninstall does, so a disabled plugin keeps no process. The choice is -// recorded first, so nothing starts the plugin again while it stops. +// as Uninstall does, so a disabled plugin keeps no process. Core plans the +// choice before the stop, so nothing starts the plugin again while it stops. func (s *Service) Disable(ctx context.Context, id string, server *LanguageSession) error { - recorded := s.Manager.SetEnabled(id, false) - return errors.Join(recorded, s.stopPlugin(ctx, id, server)) + _, err := s.Manager.Apply(ctx, core.PluginDisable, id, func() error { return s.stopPlugin(ctx, id, server) }) + return err } // stopPlugin stops a plugin's language server session and its backend, and diff --git a/desktop/internal/pluginservice/lifecycle_test.go b/desktop/internal/pluginservice/lifecycle_test.go index 11cf5b5fc6..9a24381944 100644 --- a/desktop/internal/pluginservice/lifecycle_test.go +++ b/desktop/internal/pluginservice/lifecycle_test.go @@ -90,11 +90,15 @@ func TestDisableStopsTheBackend(t *testing.T) { stopped, enabledWhenStopped := false, true runningBackend(service, "example", func() { stopped = true - enabled, err := service.Manager.Enabled("example") + entries, err := service.Manager.Installed() if err != nil { t.Error(err) } - enabledWhenStopped = enabled + for _, entry := range entries { + if entry.Installed.ID == "example" { + enabledWhenStopped = entry.Enabled + } + } }) if err := service.Disable(context.Background(), "example", nil); err != nil { t.Fatal(err) diff --git a/desktop/internal/pluginservice/pluginservice.go b/desktop/internal/pluginservice/pluginservice.go index 5f8bca0bc5..d087f15340 100644 --- a/desktop/internal/pluginservice/pluginservice.go +++ b/desktop/internal/pluginservice/pluginservice.go @@ -44,6 +44,7 @@ type Kernel interface { ReadInstalledPluginSettingsState(context.Context, json.RawMessage, string, string) (core.PluginSettingsState, error) ValidatePluginNativeData(ctx context.Context, declaration, data json.RawMessage) (json.RawMessage, error) SelectInstalledPluginVersions(context.Context, []core.InstalledPluginFact, bool) (core.InstalledPluginSelection, error) + pluginmanager.Kernel ExpandPluginWorkspaceConfiguration(context.Context, json.RawMessage, string, map[string]json.RawMessage, map[string]json.RawMessage) (json.RawMessage, error) UpdatePluginWorkspaceConfiguration(context.Context, string, json.RawMessage) (bool, error) ReviewMarketplaceInstall(ctx context.Context, manifest json.RawMessage, expectedID, expectedVersion string, approvedPrograms []json.RawMessage, hostCapabilities map[string][]int) (core.MarketplaceReview, error) @@ -157,7 +158,7 @@ func open(kernel Kernel, preferences *store.Store, root string, first bool) (*Se service := &Service{ startupLeftovers: leftovers, Root: root, - Manager: pluginmanager.New(root, approvals, state), + Manager: pluginmanager.New(kernel, root, approvals, state), Installer: plugininstall.New(kernel, NewReviewer(kernel), approvals, pluginhost.Declared()), Backend: pluginbackend.New(kernel, hostServices), Settings: pluginsettings.New(kernel, preferences.Dir()), diff --git a/desktop/internal/pluginservice/pluginservice_test.go b/desktop/internal/pluginservice/pluginservice_test.go index 3cc5d7bc95..79f5d2f7e0 100644 --- a/desktop/internal/pluginservice/pluginservice_test.go +++ b/desktop/internal/pluginservice/pluginservice_test.go @@ -423,6 +423,10 @@ func (k *fakeKernel) UpdatePluginWorkspaceConfiguration(context.Context, string, return false, nil } +func (k *fakeKernel) PlanPluginLifecycle(ctx context.Context, request core.PluginLifecycleRequest) (core.PluginLifecycle, error) { + return core.NewClient().PlanPluginLifecycle(ctx, request) +} + func (k *fakeKernel) SelectInstalledPluginVersions(ctx context.Context, entries []core.InstalledPluginFact, includeDisabled bool) (core.InstalledPluginSelection, error) { return core.NewClient().SelectInstalledPluginVersions(ctx, entries, includeDisabled) } diff --git a/desktop/internal/pluginstate/pluginstate.go b/desktop/internal/pluginstate/pluginstate.go index 6b98268cc1..e9cff27d9a 100644 --- a/desktop/internal/pluginstate/pluginstate.go +++ b/desktop/internal/pluginstate/pluginstate.go @@ -1,13 +1,8 @@ -// Package pluginstate keeps which installed plugins the user enabled. +// Package pluginstate keeps the enablement choices the user made, one per plugin. // -// Enablement is per plugin, not per version: installing a new version must not -// silently turn a plugin back on, and uninstalling one version must not reset a -// choice the user made for another. -// -// A plugin with no record is disabled. Confirming an installation is the user -// saying they want the plugin, so it records the plugin as enabled unless the -// user already made a choice for it (EnableUnlessChosen): a plugin the user -// disabled stays disabled when a new version is installed. +// It only stores them. What a plugin without a choice is, when a choice is recorded +// or dropped, and in which order with the plugin's other records, is Core's +// (plugins.installed.lifecycle); pluginmanager asks Core and carries out its steps. package pluginstate import ( @@ -48,25 +43,6 @@ func New(preferences *store.Store) *Store { return &Store{preferences: preferences} } -// Enabled reports whether a plugin is enabled. A plugin with no record is -// disabled. -func (s *Store) Enabled(id string) (bool, error) { - s.mu.Lock() - defer s.mu.Unlock() - if err := checkID(id); err != nil { - return false, err - } - contents, err := s.load() - if err != nil { - return false, err - } - entry, ok := contents.Plugins[id] - if !ok { - return false, nil - } - return entry.Enabled, nil -} - // SetEnabled records an explicit choice for a plugin. func (s *Store) SetEnabled(id string, enabled bool) error { s.mu.Lock() @@ -82,28 +58,8 @@ func (s *Store) SetEnabled(id string, enabled bool) error { return s.save(contents) } -// EnableUnlessChosen records the plugin as enabled when the user has made no -// choice for it, and reports whether it did. An explicit choice is kept. -func (s *Store) EnableUnlessChosen(id string) (bool, error) { - s.mu.Lock() - defer s.mu.Unlock() - if err := checkID(id); err != nil { - return false, err - } - contents, err := s.load() - if err != nil { - return false, err - } - if _, chosen := contents.Plugins[id]; chosen { - return false, nil - } - contents.Plugins[id] = Entry{PluginID: id, Enabled: true} - return true, s.save(contents) -} - -// Forget drops a choice, so a later installation starts from no choice again -// and is enabled when the user confirms it. It is called when the last -// installed version of a plugin is removed. +// Forget drops the choice for a plugin. Dropping one that was never recorded is +// not an error. func (s *Store) Forget(id string) error { s.mu.Lock() defer s.mu.Unlock() diff --git a/desktop/internal/pluginstate/pluginstate_test.go b/desktop/internal/pluginstate/pluginstate_test.go index 12f1502ebd..cc86b50cd6 100644 --- a/desktop/internal/pluginstate/pluginstate_test.go +++ b/desktop/internal/pluginstate/pluginstate_test.go @@ -7,54 +7,44 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/store" ) -func TestEnabledDefaultsToDisabled(t *testing.T) { - state := New(store.At(t.TempDir())) - enabled, err := state.Enabled("example") +// choices reports the stored choices by plugin ID. +func choices(t *testing.T, state *Store) map[string]bool { + t.Helper() + entries, err := state.List() if err != nil { - t.Fatalf("enabled: %v", err) + t.Fatalf("list: %v", err) } - if enabled { - t.Fatal("a plugin with no record was enabled") + found := make(map[string]bool, len(entries)) + for _, entry := range entries { + found[entry.PluginID] = entry.Enabled + } + return found +} + +func TestNoChoiceIsStoredAtFirst(t *testing.T) { + if found := choices(t, New(store.At(t.TempDir()))); len(found) != 0 { + t.Fatalf("a new store holds %v", found) } } func TestSetEnabledRoundTrips(t *testing.T) { - state := New(store.At(t.TempDir())) + dir := t.TempDir() + state := New(store.At(dir)) if err := state.SetEnabled("example", true); err != nil { t.Fatalf("set enabled: %v", err) } - enabled, err := state.Enabled("example") - if err != nil || !enabled { - t.Fatalf("enabled = %v, err = %v", enabled, err) + if enabled, ok := choices(t, New(store.At(dir)))["example"]; !ok || !enabled { + t.Fatalf("enabled = %v, recorded = %v", enabled, ok) } if err := state.SetEnabled("example", false); err != nil { t.Fatalf("set disabled: %v", err) } - enabled, err = state.Enabled("example") - if err != nil || enabled { - t.Fatalf("enabled = %v, err = %v", enabled, err) - } -} - -func TestForgetReturnsToDisabled(t *testing.T) { - state := New(store.At(t.TempDir())) - if err := state.SetEnabled("example", true); err != nil { - t.Fatal(err) - } - if err := state.Forget("example"); err != nil { - t.Fatalf("forget: %v", err) - } - enabled, err := state.Enabled("example") - if err != nil || enabled { - t.Fatalf("enabled = %v, err = %v", enabled, err) - } - // Forgetting a plugin that was never recorded is not an error. - if err := state.Forget("absent"); err != nil { - t.Fatalf("forget absent: %v", err) + if enabled, ok := choices(t, state)["example"]; !ok || enabled { + t.Fatalf("enabled = %v, recorded = %v", enabled, ok) } } -func TestForgetKeepsOtherPlugins(t *testing.T) { +func TestForgetDropsOnlyThatChoice(t *testing.T) { state := New(store.At(t.TempDir())) if err := state.SetEnabled("first", true); err != nil { t.Fatal(err) @@ -63,11 +53,15 @@ func TestForgetKeepsOtherPlugins(t *testing.T) { t.Fatal(err) } if err := state.Forget("first"); err != nil { - t.Fatal(err) + t.Fatalf("forget: %v", err) } - enabled, err := state.Enabled("second") - if err != nil || !enabled { - t.Fatalf("enabled = %v, err = %v", enabled, err) + found := choices(t, state) + if _, ok := found["first"]; ok || !found["second"] { + t.Fatalf("choices after forgetting first = %v", found) + } + // Forgetting a plugin that was never recorded is not an error. + if err := state.Forget("absent"); err != nil { + t.Fatalf("forget absent: %v", err) } } @@ -98,9 +92,6 @@ func TestListIsSorted(t *testing.T) { func TestRefusesEmptyID(t *testing.T) { state := New(store.At(t.TempDir())) - if _, err := state.Enabled(""); !errors.Is(err, ErrInvalidPlugin) { - t.Fatalf("err = %v", err) - } if err := state.SetEnabled("", true); !errors.Is(err, ErrInvalidPlugin) { t.Fatalf("err = %v", err) } @@ -108,25 +99,3 @@ func TestRefusesEmptyID(t *testing.T) { t.Fatalf("err = %v", err) } } - -func TestEnableUnlessChosenRecordsOnlyAFirstChoice(t *testing.T) { - state := New(store.At(t.TempDir())) - if changed, err := state.EnableUnlessChosen("fresh"); err != nil || !changed { - t.Fatalf("fresh: changed = %v, err = %v", changed, err) - } - if enabled, err := state.Enabled("fresh"); err != nil || !enabled { - t.Fatalf("fresh: enabled = %v, err = %v", enabled, err) - } - if err := state.SetEnabled("chosen", false); err != nil { - t.Fatal(err) - } - if changed, err := state.EnableUnlessChosen("chosen"); err != nil || changed { - t.Fatalf("chosen: changed = %v, err = %v", changed, err) - } - if enabled, err := state.Enabled("chosen"); err != nil || enabled { - t.Fatalf("an explicit disable was overridden: enabled = %v, err = %v", enabled, err) - } - if _, err := state.EnableUnlessChosen(""); !errors.Is(err, ErrInvalidPlugin) { - t.Fatalf("empty ID: %v", err) - } -} From 9eae9a892512d9ca8badffc03d27db3fc25a2660 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 09:07:32 +0800 Subject: [PATCH 07/11] =?UTF-8?q?fix(desktop):=20=E7=BC=96=E8=BE=91?= =?UTF-8?q?=E5=88=86=E7=BB=84=E7=9A=84=E6=89=93=E5=BC=80=E3=80=81=E6=8B=96?= =?UTF-8?q?=E6=94=BE=E4=B8=8E=E7=A9=BA=E7=BB=84=E7=A7=BB=E9=99=A4=E6=94=B9?= =?UTF-8?q?=E7=94=B1=20Core=20editor.groupLayout=20=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 core.ReduceEditorLayout(editor.groupLayout.reduce):分组与布局树一起归约, 打开页签、拖放页签(合并、拆分、空编辑区)、移除空组都由 Core 返回新状态、新布局、 被移除的组和页签所在组;拖到已关闭的页签或已消失的组时返回 stale,不会变成别的移动 - 新增 core.EditorDropTargets(editor.groupLayout.dropTargets):拖动开始时取一次 每个组可接受的位置,宿主只按画出的区域命中测试 - 工作台删掉自写的 moveTab、moveIntoNewGroup、splitTab、placeInEmptyEditor、 splitLeaf、removeLeaf 和 dropRestoredGroup;adoptLayout 按 split 编号复用分隔条比例 - 会话恢复只创建布局里有的组,结束时用 RemoveEmptyEditorGroups 去掉空组 - 更新编辑分组拆分与停靠的 Agent Note Closes #1806 --- .../2026-10-12-editor-tab-split-docking.md | 17 +- desktop/internal/core/editor_layout.go | 282 ++++++++++++++++++ desktop/internal/core/editor_layout_test.go | 200 +++++++++++++ desktop/internal/core/workbench.go | 59 ++-- desktop/internal/core/workbench_test.go | 8 +- desktop/internal/workbench/app.go | 3 +- desktop/internal/workbench/difftab.go | 22 -- desktop/internal/workbench/difftab_test.go | 4 +- desktop/internal/workbench/documents.go | 44 ++- .../internal/workbench/documents_tabless.go | 17 +- desktop/internal/workbench/editor_session.go | 38 ++- desktop/internal/workbench/editor_view.go | 4 +- desktop/internal/workbench/editorgroups.go | 169 +++++------ .../internal/workbench/editorgroups_test.go | 247 ++++++++------- desktop/internal/workbench/tab_menu.go | 4 +- desktop/internal/workbench/tabdrag.go | 39 ++- desktop/internal/workbench/tabstrip.go | 4 +- desktop/internal/workbench/terminals.go | 170 ++++------- 18 files changed, 866 insertions(+), 465 deletions(-) create mode 100644 desktop/internal/core/editor_layout.go create mode 100644 desktop/internal/core/editor_layout_test.go diff --git a/.agents/notes/implemented/architecture/2026-10-12-editor-tab-split-docking.md b/.agents/notes/implemented/architecture/2026-10-12-editor-tab-split-docking.md index c77efe38e5..43d831de39 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-editor-tab-split-docking.md +++ b/.agents/notes/implemented/architecture/2026-10-12-editor-tab-split-docking.md @@ -2,7 +2,7 @@ 状态:已实现 -> Viva 迁移状态:本文记录旧 macOS 客户端的分组、终端和 Diff 行为,不代表 Viva 已全部实现。Viva 已有部分文本与终端分组展示;跨类型拖放、Diff 会话、焦点及生命周期需按下述要求逐项核验,原版像素对照和 Windows 实机验收仍未完成。Go 宿主现有分组状态转换下沉 Core 的债务已登记 [#1806](https://github.com/1lck/Lithe-IDEA/issues/1806)。 +> Viva 迁移状态:本文记录旧 macOS 客户端的分组、终端和 Diff 行为,不代表 Viva 已全部实现。Viva 已有部分文本与终端分组展示;跨类型拖放、Diff 会话、焦点及生命周期需按下述要求逐项核验,原版像素对照和 Windows 实机验收仍未完成。Viva 的分组与布局规则已由 Core 计算([#1806](https://github.com/1lck/Lithe-IDEA/issues/1806)),见下文“Viva 宿主只画布局,规则在 Core”。 ## 先说结论 @@ -32,6 +32,20 @@ LSP 日志是普通编辑器标签(`EditorTabItem.languageLogs`),不登记 文件通过功能模型直接打开时,日志标签也必须让出活动选择;工作区重置会移除日志标签并停止它的查询。 与数据库 PR #17 集成后,数据库标签继续使用其共享工作区和查询状态,统一保留在同一个编辑分组,只允许组内重排;不能直接开放跨组移动,否则两个分组会显示同一数据库上下文。数据库工具窗口及 Services 工具窗口仍支持停靠分组。 +### Viva 宿主只画布局,规则在 Core + +Viva 桌面端(Go 宿主)不自己决定标签能放到哪里、放下后分组怎么变。 +这些规则在 Core 的 `lithe-editor-layout` crate,宿主通过两条命令使用: + +- `editor.groupLayout.dropTargets`:拖动开始时问一次,Core 回答每个分组的标签栏能否插入(join)、正文边缘能否拆分(split)、正文中间能否追加(append),以及空编辑区能否接收。宿主只拿这份答案和上一帧画出的位置做命中测试,算出插入序号、拆分方向和预览区域。 +- `editor.groupLayout.reduce`:打开标签、放下拖动的标签、移除空分组时调用。Core 同时改分组状态和布局树:拆分时插入新分组,最后一个标签离开后删掉空分组,兄弟分组占满空出的位置。过期的落点(标签已关闭、分组已消失)被拒绝,不会变成另一种移动。 + +宿主保留的只有 Core 不需要知道的东西:每个拆分节点的分隔条比例,按 Core 返回的节点编号复用原节点,所以分隔条比例和 Viva 持有的指针在其他分组变化时不丢。 +停靠在 Terminal 工具窗口里的分组作为 `docked` 传给 Core,只有终端标签(`dockable`)能拖进去,它永远不拆分,最后一个终端离开后保留。 + +正确做法:拖放、打开位置、空分组的规则改在 Core,桌面端只改命中几何和绘制。 +不要这样做:在 `desktop/internal/workbench` 里重新写 `splitLeaf`、`removeLeaf` 这类布局树算法,或按标签种类加“能不能放”的分支。 + ### 终端标签使用独立的 AppKit 拖放 终端标签不能继续使用 SwiftUI `.onDrag`。Monaco 所在的 `WKWebView` 会消费拖放目标,祖先视图的 `.onDrop` 收不到终端 payload;带文本兜底的 `NSItemProvider` 还会把 “Terminal” 当文本插入编辑器。 @@ -118,6 +132,7 @@ Windows 的既有分栏实现不受此次 macOS 呈现改动影响,完整两 - `./scripts/desktop/verify/verify-runtime-bundle-immutability.sh` - `./scripts/platform-feature-matrix/verify-platform-feature-matrix.sh` - `./scripts/agent-notes/verify-agent-notes.sh` +- Viva:`desktop/internal/core` 的 `TestReduceEditorLayout`、`TestEditorDropTargets` 对真实 Core 检查打开、拆分、合并、拒绝和落点规则;`desktop/internal/workbench` 的 `TestDropAt*`、`TestAdoptLayout*` 检查命中几何与节点复用,`TestTerminalTabDragJoinsAndSplitsEditorGroupsThroughThePage`、`TestFileTabDragSplitsTheEditorThroughThePage` 经页面拖放走完整流程。 - 原生事件检查右侧、底部半区、释放提交、Esc 取消、重排、关闭与焦点;实机预览另检查真实字体资源、代码输入、灰色浮动标签及分隔器调整。 - 终端标签拖放:聚焦测试覆盖外部插入/边缘分屏、私有 pasteboard 与拖拽状态、工具窗终端拖入编辑器不重建进程;真实窗口录屏确认工具窗→底边分屏→右侧分屏→工具窗往返中 PTY 未重建。 - `TerminalPlacementFeatureModelTests.toolTerminalDropOverlayLeavesTheTabBarAvailable` 在两种面板高度挂载真实工具窗视图,检查正文覆盖层不命中标签栏;`EditorTabOrderFeatureModelTests.editorGroupDropPreviewPublishesOnlyChangedTargets` 检查相同落点、目标切换和重复清空的发布次数。实机拖放仍需检查拖回已有标签前后的位置,组件命中验证不代替系统拖放验收。 diff --git a/desktop/internal/core/editor_layout.go b/desktop/internal/core/editor_layout.go new file mode 100644 index 0000000000..74bc80a35a --- /dev/null +++ b/desktop/internal/core/editor_layout.go @@ -0,0 +1,282 @@ +package core + +import ( + "context" + "encoding/json" + "errors" +) + +// EditorLayout is the shape of the tree that divides the editor area among its tab groups: a +// leaf shows Group, and a split lays First and Second side by side (Row) or one over the other. +// Node is the host's number for a split, unique in the tree; the host keeps what its widgets +// need for each split, such as the splitter's ratio, under that number. +type EditorLayout struct { + Group string + Node int + Row bool + First, Second *EditorLayout +} + +// UnmarshalJSON decodes a leaf {group} or a split {node, row, first, second}. +func (l *EditorLayout) UnmarshalJSON(data []byte) error { + var wire struct { + Group string `json:"group"` + Node int `json:"node"` + Row bool `json:"row"` + First *EditorLayout `json:"first"` + Second *EditorLayout `json:"second"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return err + } + if wire.Group == "" && (wire.First == nil || wire.Second == nil) { + return errors.New("core: an editor layout split lacks a child") + } + *l = EditorLayout{Group: wire.Group, Node: wire.Node, Row: wire.Row, First: wire.First, Second: wire.Second} + return nil +} + +// MarshalJSON encodes a leaf as {group} and a split as {node, row, first, second}; Core +// rejects any other field. +func (l EditorLayout) MarshalJSON() ([]byte, error) { + if l.Group != "" { + return json.Marshal(struct { + Group string `json:"group"` + }{l.Group}) + } + if l.First == nil || l.Second == nil { + return nil, errors.New("core: an editor layout split lacks a child") + } + return json.Marshal(struct { + Node int `json:"node"` + Row bool `json:"row"` + First *EditorLayout `json:"first"` + Second *EditorLayout `json:"second"` + }{l.Node, l.Row, l.First, l.Second}) +} + +// EditorEdge is a side of a group, where a dropped tab splits it. +type EditorEdge string + +// The sides of a group. +const ( + EditorEdgeLeft EditorEdge = "left" + EditorEdgeRight EditorEdge = "right" + EditorEdgeTop EditorEdge = "top" + EditorEdgeBottom EditorEdge = "bottom" +) + +// EditorDropPlace is where a dragged tab is released. Build it with JoinEditorGroup, +// SplitEditorGroup or EmptyEditorArea. +type EditorDropPlace struct { + kind string + group string + index int + edge EditorEdge +} + +// JoinEditorGroup puts the tab into group as its tab at index, counted among the group's tabs +// without the dragged one. +func JoinEditorGroup(group string, index int) EditorDropPlace { + return EditorDropPlace{kind: "join", group: group, index: index} +} + +// SplitEditorGroup puts the tab into a new group on side edge of group. +func SplitEditorGroup(group string, edge EditorEdge) EditorDropPlace { + return EditorDropPlace{kind: "split", group: group, edge: edge} +} + +// EmptyEditorArea puts the tab into the first group of an editor area that has none. +func EmptyEditorArea() EditorDropPlace { return EditorDropPlace{kind: "empty"} } + +// MarshalJSON encodes the place as the exact object of its kind. +func (p EditorDropPlace) MarshalJSON() ([]byte, error) { + switch p.kind { + case "join": + return json.Marshal(struct { + Kind string `json:"kind"` + Group string `json:"group"` + Index int `json:"index"` + }{p.kind, p.group, p.index}) + case "split": + return json.Marshal(struct { + Kind string `json:"kind"` + Group string `json:"group"` + Edge EditorEdge `json:"edge"` + }{p.kind, p.group, p.edge}) + case "empty": + return json.Marshal(struct { + Kind string `json:"kind"` + }{p.kind}) + } + return nil, errors.New("core: zero EditorDropPlace; build one with JoinEditorGroup, SplitEditorGroup or EmptyEditorArea") +} + +// EditorDrop is the release of a dragged tab. +type EditorDrop struct { + Member string + Target EditorDropPlace + // Docked are the groups docked in a tool window: never split, kept when their last tab + // leaves, and joined only by a Dockable tab. + Docked []string + Dockable bool + // NewGroup and NewNode are the group ID and split number the host offers for a group the + // drop makes; the result's Group says whether it was made. + NewGroup string + NewNode int +} + +// OpenEditorTab opens member and shows it: in preferred while the layout shows it, else in the +// first group of the layout, else in group newGroup, made as the whole layout. +func OpenEditorTab(member, preferred, newGroup string) EditorAction { + return EditorAction{kind: editorOpenTab, member: member, group: preferred, drop: EditorDrop{NewGroup: newGroup}} +} + +// DropEditorTab releases a dragged tab on a place EditorDropTargets offered. A place that no +// longer fits the groups is rejected (EditorDropStale), never turned into a different move. +func DropEditorTab(drop EditorDrop) EditorAction { + return EditorAction{kind: editorDropTab, drop: drop} +} + +// RemoveEmptyEditorGroups removes the named groups that have no tab, and their leaves. +func RemoveEmptyEditorGroups(groups []string) EditorAction { + return EditorAction{kind: editorRemoveEmpty, unplaced: groups} +} + +// The rejections of DropEditorTab. +const ( + // EditorDropStale is a drop whose member or place no longer fits the groups, as when a tab + // closed or a group went away while the tab was dragged. + EditorDropStale = "editor.groupLayout.stale" + // EditorDropRefused is a drop on a place the drop rules refuse. + EditorDropRefused = "editor.groupLayout.refused" +) + +type editorOpenTabWire struct { + Kind editorKind `json:"kind"` + Member string `json:"member"` + PreferredGroup *string `json:"preferredGroup,omitempty"` + NewGroup string `json:"newGroup"` +} + +type editorRemoveEmptyWire struct { + Kind editorKind `json:"kind"` + Groups []string `json:"groups"` +} + +func (d EditorDrop) marshal() ([]byte, error) { + wire := struct { + Kind editorKind `json:"kind"` + Member string `json:"member"` + Target EditorDropPlace `json:"target"` + Docked []string `json:"docked"` + Dockable bool `json:"dockable"` + NewGroup *string `json:"newGroup,omitempty"` + NewNode *int `json:"newNode,omitempty"` + }{Kind: editorDropTab, Member: d.Member, Target: d.Target, Docked: nonNil(d.Docked), Dockable: d.Dockable, NewGroup: optional(d.NewGroup)} + if d.NewNode > 0 { + wire.NewNode = &d.NewNode + } + return json.Marshal(wire) +} + +// EditorLayoutResult is the outcome of one editor.groupLayout.reduce. +type EditorLayoutResult struct { + State EditorWorkbench `json:"state"` + // Layout is nil when the editor area shows no group. + Layout *EditorLayout `json:"layout"` + // Removed is the groups that left the state, in their previous order. + Removed []string `json:"removedGroupIds"` + // Group is the group the tab is in after OpenEditorTab or DropEditorTab. + Group string `json:"group"` + // Rejection says why a drop did not apply; State and Layout are then as sent. + Rejection string `json:"rejection"` +} + +// ReduceEditorLayout applies action to the groups and the layout together +// (editor.groupLayout.reduce): any workbench action, after which a leaf whose group left the +// state leaves the layout and its sibling takes the room, or OpenEditorTab, DropEditorTab and +// RemoveEmptyEditorGroups. The layout first loses the leaves of groups state does not have. +// +// The call only computes over its arguments and is fast enough for an event handler. +func (c *Client) ReduceEditorLayout(ctx context.Context, state EditorWorkbench, layout *EditorLayout, action EditorAction) (EditorLayoutResult, error) { + payload := struct { + State EditorWorkbench `json:"state"` + Layout *EditorLayout `json:"layout"` + Action EditorAction `json:"action"` + }{state, layout, action} + var result EditorLayoutResult + if err := c.Execute(ctx, "editor.groupLayout.reduce", payload, &result); err != nil { + return EditorLayoutResult{}, err + } + result.State.Groups = nonNil(result.State.Groups) + for i := range result.State.Groups { + g := &result.State.Groups[i] + g.Members, g.MRU, g.Pinned = nonNil(g.Members), nonNil(g.MRU), nonNil(g.Pinned) + } + result.Removed = nonNil(result.Removed) + return result, nil +} + +// EditorDropQuery is a drag that starts: the groups, the layout and the dragged tab. +type EditorDropQuery struct { + State EditorWorkbench + Layout *EditorLayout + Member string + Docked []string + Dockable bool +} + +// EditorPlaceRules says which places of one group accept the dragged tab. +type EditorPlaceRules struct { + // Join is the strip of tabs: the tab joins at the place it is dropped. + Join bool `json:"join"` + // Split is the edges of the body: the tab splits the group on that side. + Split bool `json:"split"` + // Append is the middle of the body: the tab joins at the end. + Append bool `json:"append"` +} + +// EditorGroupDropRules is the rules of one group. +type EditorGroupDropRules struct { + Group string `json:"group"` + EditorPlaceRules +} + +// EditorDropRules is where a dragged tab may land, for as long as the drag lasts. +type EditorDropRules struct { + // Groups is every group of the state, in its order. + Groups []EditorGroupDropRules `json:"groups"` + // Empty says the editor area has no group and the tab may open its first one. + Empty bool `json:"empty"` +} + +// For is the rules of group; a group Core did not see accepts nothing. +func (r *EditorDropRules) For(group string) EditorPlaceRules { + if r == nil { + return EditorPlaceRules{} + } + for _, g := range r.Groups { + if g.Group == group { + return g.EditorPlaceRules + } + } + return EditorPlaceRules{} +} + +// EditorDropTargets has Core say, once per drag, which places of each group accept the +// dragged tab (editor.groupLayout.dropTargets). The host hit-tests against what it painted. +func (c *Client) EditorDropTargets(ctx context.Context, query EditorDropQuery) (EditorDropRules, error) { + payload := struct { + State EditorWorkbench `json:"state"` + Layout *EditorLayout `json:"layout"` + Member string `json:"member"` + Docked []string `json:"docked"` + Dockable bool `json:"dockable"` + }{query.State, query.Layout, query.Member, nonNil(query.Docked), query.Dockable} + var rules EditorDropRules + if err := c.Execute(ctx, "editor.groupLayout.dropTargets", payload, &rules); err != nil { + return EditorDropRules{}, err + } + return rules, nil +} diff --git a/desktop/internal/core/editor_layout_test.go b/desktop/internal/core/editor_layout_test.go new file mode 100644 index 0000000000..c856cf245b --- /dev/null +++ b/desktop/internal/core/editor_layout_test.go @@ -0,0 +1,200 @@ +package core + +import ( + "encoding/json" + "slices" + "testing" +) + +// leafGroups are the groups of a layout, first to last. +func leafGroups(l *EditorLayout) []string { + if l == nil { + return nil + } + if l.Group != "" { + return []string{l.Group} + } + return append(leafGroups(l.First), leafGroups(l.Second)...) +} + +func TestReduceEditorLayout(t *testing.T) { + client := NewClient() + ctx := testContext(t) + reduce := func(t *testing.T, state EditorWorkbench, layout *EditorLayout, action EditorAction) EditorLayoutResult { + t.Helper() + result, err := client.ReduceEditorLayout(ctx, state, layout, action) + if err != nil { + t.Fatalf("ReduceEditorLayout() error: %v", err) + } + return result + } + docked := []string{"tool"} + twoTerminals := EditorWorkbench{Groups: []EditorGroup{ + {ID: "tool", Members: []string{"terminal:1", "terminal:2"}, Selected: "terminal:1"}, + {ID: "editor:1", Members: []string{"document:1"}, Selected: "document:1"}, + }} + one := &EditorLayout{Group: "editor:1"} + + t.Run("openTab makes the first group of an empty editor", func(t *testing.T) { + result := reduce(t, EditorWorkbench{}, nil, OpenEditorTab("document:1", "", "editor:1")) + if result.Group != "editor:1" || !slices.Equal(leafGroups(result.Layout), []string{"editor:1"}) { + t.Fatalf("result = %+v, want document:1 in a new editor:1 that fills the layout", result) + } + if g := result.State.Group("editor:1"); g == nil || g.Selected != "document:1" { + t.Fatalf("editor:1 = %+v, want document:1 selected", g) + } + }) + + t.Run("openTab prefers a group the layout shows", func(t *testing.T) { + state := twoTerminals + state.Groups = append(slices.Clone(state.Groups), EditorGroup{ID: "editor:2", Members: []string{"document:2"}}) + layout := &EditorLayout{Node: 1, Row: true, First: &EditorLayout{Group: "editor:1"}, Second: &EditorLayout{Group: "editor:2"}} + if got := reduce(t, state, layout, OpenEditorTab("document:3", "editor:2", "editor:3")).Group; got != "editor:2" { + t.Errorf("preferred editor:2: group = %q", got) + } + if got := reduce(t, state, layout, OpenEditorTab("document:3", "editor:9", "editor:3")).Group; got != "editor:1" { + t.Errorf("missing preference: group = %q, want the first group", got) + } + }) + + t.Run("a terminal splits the editor and the docked group stays", func(t *testing.T) { + result := reduce(t, twoTerminals, one, DropEditorTab(EditorDrop{ + Member: "terminal:1", Target: SplitEditorGroup("editor:1", EditorEdgeLeft), + Docked: docked, Dockable: true, NewGroup: "editor:2", NewNode: 4, + })) + if result.Rejection != "" || result.Group != "editor:2" { + t.Fatalf("result = %+v, want the terminal in editor:2", result) + } + l := result.Layout + if l == nil || l.Node != 4 || !l.Row || !slices.Equal(leafGroups(l), []string{"editor:2", "editor:1"}) { + t.Fatalf("layout = %+v, want split 4 with editor:2 left of editor:1", l) + } + if g := result.State.Group("tool"); g == nil || !slices.Equal(g.Members, []string{"terminal:2"}) { + t.Fatalf("tool = %+v, want terminal:2 left", g) + } + }) + + t.Run("the last tab of a split leaves it and the sibling takes the room", func(t *testing.T) { + state := twoTerminals + state.Groups = append(slices.Clone(state.Groups), EditorGroup{ID: "editor:2", Members: []string{"document:2"}, Selected: "document:2"}) + layout := &EditorLayout{Node: 1, First: &EditorLayout{Group: "editor:1"}, Second: &EditorLayout{Group: "editor:2"}} + result := reduce(t, state, layout, DropEditorTab(EditorDrop{ + Member: "document:2", Target: JoinEditorGroup("editor:1", 0), Docked: docked, + })) + if !slices.Equal(result.Removed, []string{"editor:2"}) || !slices.Equal(leafGroups(result.Layout), []string{"editor:1"}) { + t.Fatalf("result = %+v, want editor:2 gone from the state and the layout", result) + } + }) + + t.Run("a file cannot join the docked group", func(t *testing.T) { + result := reduce(t, twoTerminals, one, DropEditorTab(EditorDrop{ + Member: "document:1", Target: JoinEditorGroup("tool", 0), Docked: docked, + })) + if result.Rejection != EditorDropRefused { + t.Fatalf("rejection = %q, want %q", result.Rejection, EditorDropRefused) + } + }) + + t.Run("a drop of a closed tab is stale", func(t *testing.T) { + result := reduce(t, twoTerminals, one, DropEditorTab(EditorDrop{ + Member: "terminal:9", Target: JoinEditorGroup("editor:1", 0), Docked: docked, Dockable: true, + })) + if result.Rejection != EditorDropStale { + t.Fatalf("rejection = %q, want %q", result.Rejection, EditorDropStale) + } + }) + + t.Run("removeEmptyGroups drops only the named empty groups", func(t *testing.T) { + state := twoTerminals + state.Groups = append(slices.Clone(state.Groups), EditorGroup{ID: "editor:2"}, EditorGroup{ID: "editor:3"}) + layout := &EditorLayout{Node: 1, First: &EditorLayout{Group: "editor:1"}, Second: &EditorLayout{Group: "editor:2"}} + result := reduce(t, state, layout, RemoveEmptyEditorGroups([]string{"editor:1", "editor:2"})) + if !slices.Equal(result.Removed, []string{"editor:2"}) || result.State.Group("editor:3") == nil { + t.Fatalf("result = %+v, want only editor:2 removed", result) + } + if !slices.Equal(leafGroups(result.Layout), []string{"editor:1"}) { + t.Fatalf("layout = %+v, want editor:1 alone", result.Layout) + } + }) +} + +func TestEditorDropTargets(t *testing.T) { + client := NewClient() + ctx := testContext(t) + state := EditorWorkbench{Groups: []EditorGroup{ + {ID: "tool", Members: []string{"terminal:1", "terminal:2"}}, + {ID: "editor:1", Members: []string{"document:1"}}, + }} + layout := &EditorLayout{Group: "editor:1"} + query := func(member string, dockable bool) EditorDropRules { + t.Helper() + rules, err := client.EditorDropTargets(ctx, EditorDropQuery{State: state, Layout: layout, Member: member, Docked: []string{"tool"}, Dockable: dockable}) + if err != nil { + t.Fatalf("EditorDropTargets() error: %v", err) + } + return rules + } + terminal := query("terminal:1", true) + if got := terminal.For("tool"); got != (EditorPlaceRules{Join: true}) { + t.Errorf("terminal over tool = %+v, want join only", got) + } + if got := terminal.For("editor:1"); got != (EditorPlaceRules{Join: true, Split: true, Append: true}) { + t.Errorf("terminal over editor:1 = %+v, want every place", got) + } + file := query("document:1", false) + if got := file.For("tool"); got != (EditorPlaceRules{}) { + t.Errorf("file over tool = %+v, want nothing", got) + } + if got := file.For("editor:1"); got != (EditorPlaceRules{}) { + t.Errorf("only tab over its group = %+v, want nothing", got) + } + if file.Empty || terminal.For("missing") != (EditorPlaceRules{}) { + t.Errorf("empty = %v, unknown group = %+v; want false and nothing", file.Empty, terminal.For("missing")) + } + var none *EditorDropRules + if none.For("tool") != (EditorPlaceRules{}) { + t.Error("nil rules accepted a place") + } +} + +func TestEditorLayoutEncoding(t *testing.T) { + layout := &EditorLayout{Node: 2, Row: true, First: &EditorLayout{Group: "a"}, Second: &EditorLayout{Group: "b"}} + got, err := json.Marshal(layout) + if err != nil { + t.Fatal(err) + } + if want := `{"node":2,"row":true,"first":{"group":"a"},"second":{"group":"b"}}`; string(got) != want { + t.Errorf("layout = %s, want %s", got, want) + } + var back EditorLayout + if err := json.Unmarshal(got, &back); err != nil || !slices.Equal(leafGroups(&back), []string{"a", "b"}) || back.Node != 2 || !back.Row { + t.Errorf("decoded %+v, %v; want the same layout", back, err) + } + if err := json.Unmarshal([]byte(`{"node":1,"first":{"group":"a"}}`), &back); err == nil { + t.Error("a split with one child decoded") + } + if _, err := json.Marshal(EditorLayout{Node: 1}); err == nil { + t.Error("a split with no children encoded") + } + if _, err := json.Marshal(EditorDropPlace{}); err == nil { + t.Error("zero EditorDropPlace encoded") + } + cases := []struct { + action EditorAction + want string + }{ + {OpenEditorTab("m", "", "g"), `{"kind":"openTab","member":"m","newGroup":"g"}`}, + {DropEditorTab(EditorDrop{Member: "m", Target: EmptyEditorArea(), NewGroup: "g"}), `{"kind":"dropTab","member":"m","target":{"kind":"empty"},"docked":[],"dockable":false,"newGroup":"g"}`}, + {DropEditorTab(EditorDrop{Member: "m", Target: SplitEditorGroup("a", EditorEdgeTop), Docked: []string{"t"}, NewGroup: "g", NewNode: 3}), `{"kind":"dropTab","member":"m","target":{"kind":"split","group":"a","edge":"top"},"docked":["t"],"dockable":false,"newGroup":"g","newNode":3}`}, + {RemoveEmptyEditorGroups(nil), `{"kind":"removeEmptyGroups","groups":[]}`}, + } + for _, c := range cases { + got, err := json.Marshal(c.action) + if err != nil { + t.Fatalf("Marshal(%+v) error: %v", c.action, err) + } + if string(got) != c.want { + t.Errorf("Marshal = %s, want %s", got, c.want) + } + } +} diff --git a/desktop/internal/core/workbench.go b/desktop/internal/core/workbench.go index 1cd2c8f983..1756a9bca3 100644 --- a/desktop/internal/core/workbench.go +++ b/desktop/internal/core/workbench.go @@ -1,7 +1,6 @@ package core import ( - "context" "encoding/json" "errors" "slices" @@ -119,11 +118,16 @@ const ( editorMerge editorKind = "mergeGroup" editorPin editorKind = "setPinned" editorPinAll editorKind = "setPinnedEverywhere" + // The transitions only editor.groupLayout.reduce has (editor_layout.go). + editorOpenTab editorKind = "openTab" + editorDropTab editorKind = "dropTab" + editorRemoveEmpty editorKind = "removeEmptyGroups" ) -// EditorAction is one transition of an EditorWorkbench. Build it with NormalizeEditor, -// OpenEditor, CloseEditor, ActivateEditor, MoveEditor, ReorderEditor or MergeEditorGroups; the -// zero value is not a valid action and cannot be encoded. +// EditorAction is one transition of an EditorWorkbench and its layout. Build it with +// NormalizeEditor, OpenEditor, CloseEditor, ActivateEditor, MoveEditor, ReorderEditor, +// MergeEditorGroups, PinEditor, PinEditorEverywhere, OpenEditorTab, DropEditorTab or +// RemoveEmptyEditorGroups; the zero value is not a valid action and cannot be encoded. type EditorAction struct { kind editorKind group string @@ -131,8 +135,11 @@ type EditorAction struct { activate bool empty EmptyGroups fallback SelectionFallback + // unplaced is the members NormalizeEditor places, and the groups RemoveEmptyEditorGroups + // names. unplaced []string move EditorMove + drop EditorDrop from, to int } @@ -301,42 +308,12 @@ func (a EditorAction) MarshalJSON() ([]byte, error) { return json.Marshal(editorPinWire{Kind: a.kind, Group: a.group, Member: a.member, Pinned: a.activate}) case editorMerge: return json.Marshal(editorMergeWire{Kind: a.kind, From: a.group, Into: a.member, ActivateSelected: a.activate}) + case editorOpenTab: + return json.Marshal(editorOpenTabWire{Kind: a.kind, Member: a.member, PreferredGroup: optional(a.group), NewGroup: a.drop.NewGroup}) + case editorDropTab: + return a.drop.marshal() + case editorRemoveEmpty: + return json.Marshal(editorRemoveEmptyWire{Kind: a.kind, Groups: nonNil(a.unplaced)}) } - return nil, errors.New("core: zero EditorAction; build one with NormalizeEditor, OpenEditor, CloseEditor, ActivateEditor, MoveEditor, ReorderEditor, PinEditor or MergeEditorGroups") -} - -// editorWorkbenchRequest is the payload of editor.workbenchState.reduce. The kernel rejects -// unknown fields. -type editorWorkbenchRequest struct { - State EditorWorkbench `json:"state"` - Action EditorAction `json:"action"` -} - -// editorWorkbenchResponse is the data of editor.workbenchState.reduce. -type editorWorkbenchResponse struct { - State EditorWorkbench `json:"state"` - Removed []string `json:"removedGroupIds"` -} - -// ReduceEditorWorkbench applies action to state and returns the new state with the identifiers -// of the groups that left it, in their old order. The host keeps only what a gesture needs while -// it runs and sends one action when it ends. -// -// Groups the action does not touch come back unchanged, and an action that names a group the -// state does not have changes nothing. A new group is made by the host: it adds an empty group -// to the state and moves a member into it. -// -// The call only computes over its arguments and is fast enough for an event handler. -func (c *Client) ReduceEditorWorkbench(ctx context.Context, state EditorWorkbench, action EditorAction) (EditorWorkbench, []string, error) { - var response editorWorkbenchResponse - if err := c.Execute(ctx, "editor.workbenchState.reduce", editorWorkbenchRequest{State: state, Action: action}, &response); err != nil { - return EditorWorkbench{}, nil, err - } - state = response.State - state.Groups = nonNil(state.Groups) - for i := range state.Groups { - g := &state.Groups[i] - g.Members, g.MRU, g.Pinned = nonNil(g.Members), nonNil(g.MRU), nonNil(g.Pinned) - } - return state, nonNil(response.Removed), nil + return nil, errors.New("core: zero EditorAction; build one with NormalizeEditor, OpenEditor, CloseEditor, ActivateEditor, MoveEditor, ReorderEditor, MergeEditorGroups, PinEditor, PinEditorEverywhere, OpenEditorTab, DropEditorTab or RemoveEmptyEditorGroups") } diff --git a/desktop/internal/core/workbench_test.go b/desktop/internal/core/workbench_test.go index 3a5c5ac8bf..90b55dda1a 100644 --- a/desktop/internal/core/workbench_test.go +++ b/desktop/internal/core/workbench_test.go @@ -6,17 +6,17 @@ import ( "testing" ) -func TestReduceEditorWorkbench(t *testing.T) { +func TestReduceEditorWorkbenchActions(t *testing.T) { client := NewClient() ctx := testContext(t) reduce := func(t *testing.T, state EditorWorkbench, action EditorAction) (EditorWorkbench, []string) { t.Helper() - next, removed, err := client.ReduceEditorWorkbench(ctx, state, action) + result, err := client.ReduceEditorLayout(ctx, state, nil, action) if err != nil { - t.Fatalf("ReduceEditorWorkbench() error: %v", err) + t.Fatalf("ReduceEditorLayout() error: %v", err) } - return next, removed + return result.State, result.Removed } tool := EditorWorkbench{Groups: []EditorGroup{{ID: "tool"}}} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 22b4670b69..1558c48568 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -127,7 +127,8 @@ type Kernel interface { GitReferenceTree(ctx context.Context, names []string, prioritized map[string]bool) ([]core.ReferenceTreeNode, error) GitChangedFileGroups(ctx context.Context, paths []string) ([]core.GitChangedFolder, error) GitHistoryDates(ctx context.Context, entries []core.HistoryDateEntry, after, before *int64) ([]string, error) - ReduceEditorWorkbench(ctx context.Context, state core.EditorWorkbench, action core.EditorAction) (core.EditorWorkbench, []string, error) + ReduceEditorLayout(ctx context.Context, state core.EditorWorkbench, layout *core.EditorLayout, action core.EditorAction) (core.EditorLayoutResult, error) + EditorDropTargets(ctx context.Context, query core.EditorDropQuery) (core.EditorDropRules, error) GitStage(ctx context.Context, root string, paths []string) error GitClone(ctx context.Context, root, source, destination string) error CheckProjectName(context.Context, string) (core.ProjectNameProblem, error) diff --git a/desktop/internal/workbench/difftab.go b/desktop/internal/workbench/difftab.go index 9dfb024f71..757e4061a5 100644 --- a/desktop/internal/workbench/difftab.go +++ b/desktop/internal/workbench/difftab.go @@ -342,28 +342,6 @@ func (a *App) showDiff(p *project, root, commit string, change core.GitChange, f return t } -// placeEditorMember opens member, a Diff tab's, a viewer tab's or the LSP Logs tab's, in the -// group a file opens in, made first when the editor has no group. It returns that group and -// whether the kernel accepted the member. -func (a *App) placeEditorMember(p *project, member string) (string, bool) { - set := &p.terms - state := set.bench - group, added := a.documentGroup(p), "" - if group == "" { - added = editorGroupID(set.nextGroup + 1) - state.Groups = append(slices.Clone(state.Groups), core.EditorGroup{ID: added}) - group = added - } - if !a.reduceTerminals(p, state, core.OpenEditor(group, member, true)) { - return "", false - } - if added != "" { - set.nextGroup++ - set.layout = newLeaf(added) - } - return group, true -} - // show makes the tab show change of its checkout or commit, forgetting what it read before. // Another file gets editors of its own, made for its language and scrolled to its top. func (t *diffTab) show(change core.GitChange) { diff --git a/desktop/internal/workbench/difftab_test.go b/desktop/internal/workbench/difftab_test.go index 4101483a28..8a01a6d070 100644 --- a/desktop/internal/workbench/difftab_test.go +++ b/desktop/internal/workbench/difftab_test.go @@ -180,9 +180,7 @@ func TestDiffTabIsAnEditorTab(t *testing.T) { h.await("the diff read again", func() bool { return !d.loading }) first := g.ID - if !h.app.splitTab(p, member, first, edgeRight) { - t.Fatal("the Diff tab did not split off") - } + h.app.dropTab(member, dropTarget{kind: dropSplit, group: first, edge: edgeRight}) h.settle() g = p.terms.bench.GroupOf(member) if g == nil || g.ID == first || editorGroups(p) != 2 { diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index 0a56436e47..b772d1cd30 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -164,7 +164,7 @@ type documentLocation struct { column int columnSet bool // group is the editor group the file opens in when it is still there; "" opens it - // where files open (documentGroup). A restored session sets it (editor_session.go). + // where files open (placeEditorMember). A restored session sets it (editor_session.go). group string } @@ -304,7 +304,8 @@ func (a *App) openFile(p *project, path string) { a.notifyError(a.text.Editor.OpenFailed(name, a.documentReason(err))) return } - if g := location.group; g != "" && p.terms.layout.contains(g) && p.terms.bench.Group(g) != nil { + if g := location.group; g != "" { + // The kernel opens the file there only while the layout shows the group. p.docs.group = g } a.placeDocument(p, path, name, content, grammar, languageID) @@ -478,23 +479,12 @@ func (a *App) placeDocumentAs(p *project, path, name string, content editorview. a.selectDocument(p, d.id) return } - set := &p.terms - state := set.bench - group, added := a.documentGroup(p), "" - if group == "" { - added = editorGroupID(set.nextGroup + 1) - state.Groups = append(slices.Clone(state.Groups), core.EditorGroup{ID: added}) - group = added - } id := p.docs.next + 1 - if !a.reduceTerminals(p, state, core.OpenEditor(group, documentMember(id), true)) { + group, ok := a.placeEditorMember(p, documentMember(id)) + if !ok { return } p.docs.next = id - if added != "" { - set.nextGroup++ - set.layout = newLeaf(added) - } d := &document{id: id, path: path, name: name, languageID: languageID, virtual: virtual} d.view = editorview.New(editorview.Config{ Label: name, @@ -531,21 +521,21 @@ func (a *App) placeDocumentAs(p *project, path, name string, content editorview. } } -// documentGroup is the editor group a file opens in: the one a document was last shown in, -// while it is still there, or else the first group of the editor; "" when it has none. -func (a *App) documentGroup(p *project) string { +// placeEditorMember opens member, a file's, a Diff tab's, a viewer tab's or the LSP Logs tab's, +// in the group a file opens in, and shows it. The kernel picks the group: the one a file was +// last shown in while the layout shows it, else the first group of the layout, else a group it +// makes as the whole layout. It returns that group and whether the kernel accepted the member. +func (a *App) placeEditorMember(p *project, member string) (string, bool) { set := &p.terms - if g := p.docs.group; g != "" && set.layout.contains(g) && set.bench.Group(g) != nil { - return g - } - n := set.layout - for n != nil && !n.leaf() { - n = n.first + added := editorGroupID(set.nextGroup + 1) + result, ok := a.reduceEditorLayout(p, set.bench, core.OpenEditorTab(member, p.docs.group, added)) + if !ok { + return "", false } - if n == nil { - return "" + if result.Group == added { + set.nextGroup++ } - return n.group + return result.Group, true } // selectDocument shows document id in its group and gives it the keyboard. diff --git a/desktop/internal/workbench/documents_tabless.go b/desktop/internal/workbench/documents_tabless.go index 69ef662518..51cc006acf 100644 --- a/desktop/internal/workbench/documents_tabless.go +++ b/desktop/internal/workbench/documents_tabless.go @@ -3,9 +3,7 @@ package workbench import ( "context" "path/filepath" - "slices" - "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/editor/syntax" "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" ) @@ -100,21 +98,10 @@ func (a *App) newTablessDocument(p *project, id int, path, name string, content // attachDocumentTab gives the tabless document d a tab in the editor, in the group a new file would // open in, and reports whether the tab was made. func (a *App) attachDocumentTab(p *project, d *document) bool { - set := &p.terms - state := set.bench - group, added := a.documentGroup(p), "" - if group == "" { - added = editorGroupID(set.nextGroup + 1) - state.Groups = append(slices.Clone(state.Groups), core.EditorGroup{ID: added}) - group = added - } - if !a.reduceTerminals(p, state, core.OpenEditor(group, documentMember(d.id), true)) { + group, ok := a.placeEditorMember(p, documentMember(d.id)) + if !ok { return false } - if added != "" { - set.nextGroup++ - set.layout = newLeaf(added) - } d.tabless = false p.docs.group = group a.documentInput(p, d) diff --git a/desktop/internal/workbench/editor_session.go b/desktop/internal/workbench/editor_session.go index 219d03856b..7c54e00c55 100644 --- a/desktop/internal/workbench/editor_session.go +++ b/desktop/internal/workbench/editor_session.go @@ -188,8 +188,7 @@ func (a *App) restoreEditorSession(p *project) { ids := map[string]string{} if set.layout == nil { // The saved groups are made empty, laid out as they were; the files then join them. - state := set.bench - state.Groups = slices.Clone(state.Groups) + var made []string for _, g := range session.Groups { if _, dup := ids[g.ID]; dup { continue @@ -197,22 +196,28 @@ func (a *App) restoreEditorSession(p *project) { set.nextGroup++ id := editorGroupID(set.nextGroup) ids[g.ID] = id - r.groups = append(r.groups, id) - state.Groups = append(state.Groups, core.EditorGroup{ID: id}) + made = append(made, id) } layout := restoredSplit(set, session.Layout, ids) if layout == nil { return } - set.bench = state - set.layout = layout - // A group the layout left out is not kept. + // A group the layout left out is not made. + state := set.bench + state.Groups = slices.Clone(state.Groups) + for _, id := range made { + if layout.contains(id) { + r.groups = append(r.groups, id) + state.Groups = append(state.Groups, core.EditorGroup{ID: id}) + } + } for saved, id := range ids { if !layout.contains(id) { delete(ids, saved) - a.dropRestoredGroup(p, id) } } + set.bench = state + set.layout = layout } for _, g := range session.Groups { group := ids[g.ID] @@ -314,17 +319,17 @@ func (a *App) finishEditorRestore(p *project, r *editorRestore) { } for _, id := range r.groups { g := p.terms.bench.Group(id) - if g == nil { - continue - } - if len(g.Members) == 0 { - a.dropRestoredGroup(p, id) + if g == nil || len(g.Members) == 0 { continue } if d := p.docs.byPath(r.selected[id]); d != nil && slices.Contains(g.Members, documentMember(d.id)) { a.reduceTerminals(p, p.terms.bench, core.ActivateEditor(id, documentMember(d.id))) } } + if len(r.groups) > 0 { + // The kernel removes the groups no file reached, with their leaves. + a.reduceTerminals(p, p.terms.bench, core.RemoveEmptyEditorGroups(r.groups)) + } focused := r.focused if p.terms.bench.Group(focused) == nil { focused = firstEditorGroup(p.terms.layout) @@ -335,10 +340,3 @@ func (a *App) finishEditorRestore(p *project, r *editorRestore) { } } } - -// dropRestoredGroup removes a group made for the session that no file reached. -func (a *App) dropRestoredGroup(p *project, id string) { - set := &p.terms - set.bench.Groups = slices.DeleteFunc(slices.Clone(set.bench.Groups), func(g core.EditorGroup) bool { return g.ID == id }) - set.layout = removeLeaf(set.layout, id) -} diff --git a/desktop/internal/workbench/editor_view.go b/desktop/internal/workbench/editor_view.go index e6cd142cbe..e55c833215 100644 --- a/desktop/internal/workbench/editor_view.go +++ b/desktop/internal/workbench/editor_view.go @@ -64,7 +64,7 @@ func (a *App) editorNode(c ui.C, n *splitNode) ui.Box { // the switch of a Markdown file's view. func (a *App) editorGroup(c ui.C, id string) ui.Box { u := &a.term - place := newGroupPlace(id, false) + place := newGroupPlace(id) u.groups = append(u.groups, place) p := a.project doc := p.selectedDocument(id) @@ -319,7 +319,7 @@ func (a *App) terminalInput(t *terminal) { // a dragged tab can join the group. func (a *App) terminalTabs(c ui.C) { u := &a.term - place := newGroupPlace(toolGroup, true) + place := newGroupPlace(toolGroup) u.tool, u.toolDrawn = place, true ui.Row(c).Grow(1).Shrink(1).MinWidth(0).Height(panelHeaderHeight).Items(ui.Center).Gap(chromeGap).Clip().Draw(place.stripHook).Children(func() { a.tabBar(c, place, tabsScroll, func() { diff --git a/desktop/internal/workbench/editorgroups.go b/desktop/internal/workbench/editorgroups.go index 6f312c727a..41561aeada 100644 --- a/desktop/internal/workbench/editorgroups.go +++ b/desktop/internal/workbench/editorgroups.go @@ -1,6 +1,7 @@ package workbench import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -21,24 +22,17 @@ const ( tabMarkInset = 4 ) -// edge is a side of a group, which is where a dropped tab splits it. -type edge uint8 +// edge is a side of a group, which is where a dropped tab splits it; edgeNone is no side. +type edge = core.EditorEdge const ( - edgeNone edge = iota - edgeLeft - edgeRight - edgeTop - edgeBottom + edgeNone edge = "" + edgeLeft = core.EditorEdgeLeft + edgeRight = core.EditorEdgeRight + edgeTop = core.EditorEdgeTop + edgeBottom = core.EditorEdgeBottom ) -// sideBySide says the edge splits the group into a left half and a right half; the top and -// bottom edges split it into an upper and a lower one. -func (e edge) sideBySide() bool { return e == edgeLeft || e == edgeRight } - -// leading says the new group goes before the old one: to its left or above it. -func (e edge) leading() bool { return e == edgeLeft || e == edgeTop } - // splitNode is a node of the tree that divides the editor area among its groups. A leaf // shows one group; a container lays out two children side by side or one over the other // with a splitter between them, and the children may be containers in turn. @@ -79,55 +73,54 @@ func (n *splitNode) contains(group string) bool { return n.first.contains(group) || n.second.contains(group) } -// splitLeaf returns root with the leaf that shows target replaced by a container that -// holds it and a new leaf for added, on the side e names: a leading edge puts the new group -// first. The container is given id and starts divided in half. The tree is edited in -// place, so the splitters of the nodes that stay keep their state; a root that does not -// show target is returned as it is. -func splitLeaf(root *splitNode, target, added string, e edge, id int) *splitNode { +// layoutShape is the shape of the tree the kernel reduces: groups by name and containers by id. +func layoutShape(n *splitNode) *core.EditorLayout { switch { - case root == nil: + case n == nil: return nil - case root.leaf(): - if root.group != target { - return root - } - fresh := newLeaf(added) - parent := &splitNode{id: id, row: e.sideBySide(), state: ui.SplitterState{Ratio: 0.5}} - if e.leading() { - parent.first, parent.second = fresh, root - } else { - parent.first, parent.second = root, fresh - } - return parent + case n.leaf(): + return &core.EditorLayout{Group: n.group} } - root.first = splitLeaf(root.first, target, added, e, id) - root.second = splitLeaf(root.second, target, added, e, id) - return root + return &core.EditorLayout{Node: n.id, Row: n.row, First: layoutShape(n.first), Second: layoutShape(n.second)} } -// removeLeaf returns root without the leaf that shows group. The container that held it is -// replaced by its other child, which then takes the whole room, as a split closes when its -// last tab leaves. Removing the only leaf leaves no tree. -func removeLeaf(root *splitNode, group string) *splitNode { - switch { - case root == nil: - return nil - case root.leaf(): - if root.group == group { - return nil +// adoptLayout is the tree of shape, the kernel's answer, built from the nodes of old: a container +// whose id old has is that node, so its splitter keeps its state and the pointer Viva holds, and +// a leaf whose group old shows is that leaf. A container the kernel made starts divided in half. +func adoptLayout(old *splitNode, shape *core.EditorLayout) *splitNode { + containers, leaves := map[int]*splitNode{}, map[string]*splitNode{} + var index func(*splitNode) + index = func(n *splitNode) { + switch { + case n == nil: + case n.leaf(): + leaves[n.group] = n + default: + containers[n.id] = n + index(n.first) + index(n.second) } - return root } - root.first = removeLeaf(root.first, group) - root.second = removeLeaf(root.second, group) - switch { - case root.first == nil: - return root.second - case root.second == nil: - return root.first + index(old) + var build func(*core.EditorLayout) *splitNode + build = func(s *core.EditorLayout) *splitNode { + switch { + case s == nil: + return nil + case s.Group != "": + if n := leaves[s.Group]; n != nil { + return n + } + return newLeaf(s.Group) + } + n := containers[s.Node] + if n == nil { + n = &splitNode{id: s.Node, state: ui.SplitterState{Ratio: 0.5}} + } + n.row, n.first, n.second = s.Row, build(s.First), build(s.Second) + return n } - return root + return build(shape) } // tabSlot is where the chip of one tab, a terminal's or a file's, was laid out. member is @@ -140,24 +133,11 @@ type tabSlot struct { // dropPlace is one tab group as the last frame laid it out: where its strip of tabs and its // body are, and where each tab is. It is what a drag is aimed against. type dropPlace struct { - group string - // tool says the place is the Terminal tool window, which a terminal's tab can join but - // not split and a file's tab cannot join. - tool bool + group string strip, body gfx.Rect tabs []tabSlot } -// has says the dragged tab is one of the tabs of the place. -func (p dropPlace) has(dragged string) bool { - for _, t := range p.tabs { - if t.member == dragged { - return true - } - } - return false -} - // others are the tabs of the place except the dragged one. The dragged tab is not counted, // so moving it by less than its own width does not make it jump. func (p dropPlace) others(dragged string) []tabSlot { @@ -170,10 +150,6 @@ func (p dropPlace) others(dragged string) []tabSlot { return others } -// solo says the dragged tab is the only tab of the place, so there is nothing to reorder it -// against and dropping it anywhere in the place would change nothing. -func (p dropPlace) solo(dragged string) bool { return len(p.tabs) == 1 && p.has(dragged) } - // dropKind is what dropping a tab would do. type dropKind uint8 @@ -204,44 +180,57 @@ type dropTarget struct { hasLine bool } +// place is the target as the kernel's drop place, and false for dropNone. +func (t dropTarget) place() (core.EditorDropPlace, bool) { + switch t.kind { + case dropJoin: + return core.JoinEditorGroup(t.group, t.index), true + case dropSplit: + return core.SplitEditorGroup(t.group, t.edge), true + case dropEmpty: + return core.EmptyEditorArea(), true + } + return core.EditorDropPlace{}, false +} + // dropAt finds where releasing the tab dragged at (x, y), the group member dragged, would -// put it. +// put it, among the places rules accepts; the kernel said once, as the drag started, which +// places of each group take the tab (core.EditorDropTargets), and nil rules accept nothing. // // In a group's strip the tab joins the group at the place among the tabs the pointer is // at. Over a group's body, near an edge, the tab splits the group on that side; anywhere -// else in the body it joins the group at the end. The Terminal tool window never splits, -// and takes only terminals. A place whose only tab is the dragged one accepts nothing, and -// neither does the middle of the dragged tab's own group. Over an editor with no group the -// tab opens the first one. -func dropAt(places []dropPlace, empty gfx.Rect, dragged string, x, y float32) dropTarget { - _, terminal := memberTerminal(dragged) +// else in the body it joins the group at the end. A place the rules refuse is no place, and +// so is the editor with no group unless the rules let the tab open the first one. +func dropAt(places []dropPlace, rules *core.EditorDropRules, empty gfx.Rect, dragged string, x, y float32) dropTarget { + if rules == nil { + return dropTarget{} + } for _, p := range places { inStrip, inBody := pointInRect(p.strip, x, y), pointInRect(p.body, x, y) if !inStrip && !inBody { continue } - if p.solo(dragged) || (p.tool && !terminal) { - return dropTarget{} - } + r := rules.For(p.group) others := p.others(dragged) - if inStrip { + switch { + case inStrip && r.Join: index := insertionIndex(others, x, y) return dropTarget{ kind: dropJoin, group: p.group, index: index, preview: p.strip, line: insertionMark(p.strip, others, index, y), hasLine: true, } + case inStrip: + return dropTarget{} } - if !p.tool { - if e := splitEdgeAt(p.body, x, y); e != edgeNone { - return dropTarget{kind: dropSplit, group: p.group, edge: e, preview: edgePreview(p.body, e)} - } + if e := splitEdgeAt(p.body, x, y); r.Split && e != edgeNone { + return dropTarget{kind: dropSplit, group: p.group, edge: e, preview: edgePreview(p.body, e)} } - if p.has(dragged) { + if !r.Append { return dropTarget{} } return dropTarget{kind: dropJoin, group: p.group, index: len(others), preview: unionRect(p.strip, p.body)} } - if pointInRect(empty, x, y) { + if rules.Empty && pointInRect(empty, x, y) { return dropTarget{kind: dropEmpty, preview: empty} } return dropTarget{} diff --git a/desktop/internal/workbench/editorgroups_test.go b/desktop/internal/workbench/editorgroups_test.go index 5702d3b6ab..2a19845ca3 100644 --- a/desktop/internal/workbench/editorgroups_test.go +++ b/desktop/internal/workbench/editorgroups_test.go @@ -1,10 +1,13 @@ package workbench import ( + "context" "os" "path/filepath" + "reflect" "slices" "testing" + "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/vivaui/viva/gfx" @@ -23,97 +26,79 @@ func leaves(n *splitNode) []string { return append(leaves(n.first), leaves(n.second)...) } -// threeWay is the tree "a | (b over c)": a container with id 1 that holds a and a container -// with id 2. +// threeWayShape is the layout "a | (b over c)": split 1 side by side holds a and split 2, +// which holds b over c. +func threeWayShape() *core.EditorLayout { + return &core.EditorLayout{Node: 1, Row: true, First: &core.EditorLayout{Group: "a"}, Second: &core.EditorLayout{ + Node: 2, First: &core.EditorLayout{Group: "b"}, Second: &core.EditorLayout{Group: "c"}, + }} +} + +// threeWay is the tree of threeWayShape, as the kernel's first answer makes it. func threeWay(t *testing.T) *splitNode { t.Helper() - root := splitLeaf(newLeaf("a"), "a", "b", edgeRight, 1) - root = splitLeaf(root, "b", "c", edgeBottom, 2) + root := adoptLayout(nil, threeWayShape()) if got := leaves(root); !slices.Equal(got, []string{"a", "b", "c"}) { t.Fatalf("leaves = %v, want [a b c]", got) } - if root.second.leaf() || root.second.id != 2 || root.second.row { - t.Fatalf("second child = %+v, want the column with id 2", root.second) + if root.id != 1 || !root.row || root.second.leaf() || root.second.id != 2 || root.second.row { + t.Fatalf("tree = %+v, want row 1 holding the column 2", root) } return root } -func TestSplitLeafPutsTheNewGroupOnTheNamedSide(t *testing.T) { - cases := []struct { - edge edge - row bool - want []string - }{ - {edgeRight, true, []string{"a", "b"}}, - {edgeLeft, true, []string{"b", "a"}}, - {edgeBottom, false, []string{"a", "b"}}, - {edgeTop, false, []string{"b", "a"}}, +func TestLayoutShapeIsWhatTheTreeShows(t *testing.T) { + if layoutShape(nil) != nil { + t.Errorf("no tree has a shape") } - for _, c := range cases { - got := splitLeaf(newLeaf("a"), "a", "b", c.edge, 7) - if got.leaf() || got.id != 7 || got.row != c.row || got.state.Ratio != 0.5 { - t.Errorf("edge %d: container = %+v, want id 7, row %v, ratio 0.5", c.edge, got, c.row) - } - if order := leaves(got); !slices.Equal(order, c.want) { - t.Errorf("edge %d: leaves = %v, want %v", c.edge, order, c.want) - } + if got, want := layoutShape(threeWay(t)), threeWayShape(); !reflect.DeepEqual(got, want) { + t.Errorf("layoutShape = %+v, want %+v", got, want) } } -func TestSplitLeafEditsInPlaceAndIgnoresUnknownTargets(t *testing.T) { +func TestAdoptLayoutKeepsTheNodesThatStay(t *testing.T) { root := threeWay(t) + if root.state.Ratio != 0.5 || root.second.state.Ratio != 0.5 { + t.Errorf("ratios = %v, %v, want new splits divided in half", root.state.Ratio, root.second.state.Ratio) + } + root.state.Ratio = 0.3 first, inner := root.first, root.second - // A target the tree does not show changes nothing. - if got := splitLeaf(root, "zzz", "d", edgeLeft, 3); got != root || !slices.Equal(leaves(got), []string{"a", "b", "c"}) { - t.Errorf("splitting an unknown group changed the tree: %v", leaves(got)) - } - // Splitting a leaf deep in the tree keeps every node that stays, so their splitters keep - // their state. - got := splitLeaf(root, "c", "d", edgeRight, 3) - if got != root || root.first != first || root.second != inner { - t.Errorf("splitting a leaf replaced a node that stays") + // The kernel split c with d on its right as split 3: every node that stays is the same, + // so the splitters keep their state, and the new split starts in half. + shape := threeWayShape() + shape.Second.Second = &core.EditorLayout{Node: 3, Row: true, First: &core.EditorLayout{Group: "c"}, Second: &core.EditorLayout{Group: "d"}} + got := adoptLayout(root, shape) + if got != root || root.first != first || root.second != inner || root.state.Ratio != 0.3 { + t.Errorf("adopting a split replaced a node that stays") } if order := leaves(got); !slices.Equal(order, []string{"a", "b", "c", "d"}) { t.Errorf("leaves = %v, want [a b c d]", order) } - if splitLeaf(nil, "a", "b", edgeLeft, 1) != nil { - t.Errorf("splitting no tree made one") + if split := inner.second; split.id != 3 || !split.row || split.state.Ratio != 0.5 { + t.Errorf("new split = %+v, want split 3 side by side, in half", split) } } -func TestRemoveLeafLetsTheSiblingTakeTheRoom(t *testing.T) { - // Removing c leaves the column's other child, b, in its place. +func TestAdoptLayoutLetsTheSiblingTakeTheRoom(t *testing.T) { + // Without a, the column is the whole tree. root := threeWay(t) - if got := removeLeaf(root, "c"); got != root || !root.second.leaf() || root.second.group != "b" { - t.Errorf("after removing c: leaves = %v, second = %+v", leaves(got), root.second) - } - - // Removing a leaves the column as the whole tree. - root = threeWay(t) inner := root.second - if got := removeLeaf(root, "a"); got != inner || !slices.Equal(leaves(got), []string{"b", "c"}) { - t.Errorf("after removing a: leaves = %v", leaves(got)) - } - - // Removing b leaves c beside a. - root = threeWay(t) - if got := removeLeaf(root, "b"); got != root || !slices.Equal(leaves(got), []string{"a", "c"}) || !root.second.leaf() { - t.Errorf("after removing b: leaves = %v", leaves(got)) + shape := threeWayShape().Second + if got := adoptLayout(root, shape); got != inner || !slices.Equal(leaves(got), []string{"b", "c"}) { + t.Errorf("after a left: leaves = %v", leaves(got)) } - - // A group the tree does not show changes nothing. + // Without b, c stands beside a in the same row. root = threeWay(t) - if got := removeLeaf(root, "zzz"); got != root || !slices.Equal(leaves(got), []string{"a", "b", "c"}) { - t.Errorf("removing an unknown group changed the tree: %v", leaves(got)) - } - - // The only leaf leaves no tree, and no tree stays none. - if got := removeLeaf(newLeaf("a"), "a"); got != nil { - t.Errorf("removing the only leaf left %+v", got) + c := root.second.second + shape = threeWayShape() + shape.Second = shape.Second.Second + if got := adoptLayout(root, shape); got != root || root.second != c || !slices.Equal(leaves(got), []string{"a", "c"}) { + t.Errorf("after b left: leaves = %v", leaves(got)) } - if removeLeaf(nil, "a") != nil { - t.Errorf("removing from no tree made one") + // No layout is no tree. + if adoptLayout(threeWay(t), nil) != nil { + t.Errorf("an empty layout kept a tree") } } @@ -158,24 +143,24 @@ func TestSplitEdgeAt(t *testing.T) { } for _, c := range cases { if got := splitEdgeAt(body, c.x, c.y); got != c.want { - t.Errorf("%s: splitEdgeAt(%v, %v) = %d, want %d", c.name, c.x, c.y, got, c.want) + t.Errorf("%s: splitEdgeAt(%v, %v) = %q, want %q", c.name, c.x, c.y, got, c.want) } } // A tie goes to the first of left, right, top and bottom. square := gfx.Rect{Width: 100, Height: 100} if got := splitEdgeAt(square, 10, 10); got != edgeLeft { - t.Errorf("tie of left and top = %d, want left", got) + t.Errorf("tie of left and top = %q, want left", got) } if got := splitEdgeAt(square, 90, 10); got != edgeRight { - t.Errorf("tie of right and top = %d, want right", got) + t.Errorf("tie of right and top = %q, want right", got) } // A body with no area has no edge. if got := splitEdgeAt(gfx.Rect{}, 0, 0); got != edgeNone { - t.Errorf("empty body = %d, want none", got) + t.Errorf("empty body = %q, want none", got) } if got := splitEdgeAt(gfx.Rect{Width: 100}, 1, 0); got != edgeNone { - t.Errorf("body with no height = %d, want none", got) + t.Errorf("body with no height = %q, want none", got) } } @@ -193,7 +178,7 @@ func TestEdgePreviewIsTheHalfOnThatSide(t *testing.T) { } for _, c := range cases { if got := edgePreview(body, c.edge); got != c.want { - t.Errorf("edgePreview(edge %d) = %v, want %v", c.edge, got, c.want) + t.Errorf("edgePreview(edge %q) = %v, want %v", c.edge, got, c.want) } } } @@ -327,24 +312,48 @@ func TestUnionRectAndPointInRect(t *testing.T) { } } -func TestDropPlaceHelpers(t *testing.T) { +func TestDropPlaceOthers(t *testing.T) { p := dropPlace{tabs: []tabSlot{{member: terminalMember(1)}, {member: terminalMember(2)}}} - if !p.has(terminalMember(1)) || p.has(terminalMember(3)) { - t.Errorf("has: 1 = %v, 3 = %v, want true and false", p.has(terminalMember(1)), p.has(terminalMember(3))) - } if got := p.others(terminalMember(1)); len(got) != 1 || got[0].member != terminalMember(2) { t.Errorf("others(1) = %v, want only the tab of 2", got) } if got := p.others(terminalMember(3)); len(got) != 2 { t.Errorf("others(3) has %d tabs, want 2", len(got)) } - if p.solo(terminalMember(1)) { - t.Errorf("a place with two tabs is not solo") +} + +// dropRules has the kernel say where member may land: the groups are the places, each with +// its tabs, and then extra, which are open but not laid out; the layout shows the editor's +// places side by side, and the tool window is docked. +func dropRules(t *testing.T, places []dropPlace, member string, extra ...core.EditorGroup) *core.EditorDropRules { + t.Helper() + var state core.EditorWorkbench + var layout *core.EditorLayout + for i, p := range places { + g := core.EditorGroup{ID: p.group} + for _, tab := range p.tabs { + g.Members = append(g.Members, tab.member) + } + state.Groups = append(state.Groups, g) + if p.group == toolGroup { + continue + } + if leaf := (&core.EditorLayout{Group: p.group}); layout == nil { + layout = leaf + } else { + layout = &core.EditorLayout{Node: i, Row: true, First: layout, Second: leaf} + } } - one := dropPlace{tabs: []tabSlot{{member: terminalMember(5)}}} - if !one.solo(terminalMember(5)) || one.solo(terminalMember(6)) { - t.Errorf("solo: 5 = %v, 6 = %v, want true and false", one.solo(terminalMember(5)), one.solo(terminalMember(6))) + state.Groups = append(state.Groups, extra...) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + rules, err := core.NewClient().EditorDropTargets(ctx, core.EditorDropQuery{ + State: state, Layout: layout, Member: member, Docked: dockedGroups, Dockable: dockable(member), + }) + if err != nil { + t.Fatalf("EditorDropTargets() error: %v", err) } + return &rules } // dragFixture is the Terminal tool window at the bottom left, with the tabs of terminals 1 @@ -353,7 +362,7 @@ func TestDropPlaceHelpers(t *testing.T) { func dragFixture() []dropPlace { return []dropPlace{ { - group: toolGroup, tool: true, + group: toolGroup, strip: gfx.Rect{X: 0, Y: 600, Width: 400, Height: 32}, body: gfx.Rect{X: 0, Y: 632, Width: 400, Height: 200}, tabs: []tabSlot{ @@ -377,24 +386,24 @@ func TestDropAtStrips(t *testing.T) { places := dragFixture() // A tab from the tool window dropped at the right end of the editor's strip joins it last. - got := dropAt(places, gfx.Rect{}, terminalMember(1), 900, 10) + got := dropAt(places, dropRules(t, places, terminalMember(1)), gfx.Rect{}, terminalMember(1), 900, 10) if got.kind != dropJoin || got.group != "editor:1" || got.index != 2 || !got.hasLine || got.preview != places[1].strip { t.Errorf("end of the editor strip = %+v, want a join at index 2 with a line", got) } // Dropped before the middle of the first tab it goes first, and the line stands in front // of that tab. - got = dropAt(places, gfx.Rect{}, terminalMember(1), 430, 10) + got = dropAt(places, dropRules(t, places, terminalMember(1)), gfx.Rect{}, terminalMember(1), 430, 10) if got.kind != dropJoin || got.index != 0 || got.line != (gfx.Rect{X: 401, Y: 4, Width: 2, Height: 24}) { t.Errorf("front of the editor strip = %+v, want a join at index 0 with its line at 401", got) } // A tab of the editor's own group dropped in its strip reorders it: the dragged tab is // not counted, so the only other tab, 4, is before the pointer. - got = dropAt(places, gfx.Rect{}, terminalMember(3), 900, 10) + got = dropAt(places, dropRules(t, places, terminalMember(3)), gfx.Rect{}, terminalMember(3), 900, 10) if got.kind != dropJoin || got.group != "editor:1" || got.index != 1 || got.line != (gfx.Rect{X: 609, Y: 4, Width: 2, Height: 24}) { t.Errorf("own strip = %+v, want a join at index 1 with its line at 609", got) } // And a tab from the editor dropped in the tool window's strip joins that. - got = dropAt(places, gfx.Rect{}, terminalMember(3), 300, 610) + got = dropAt(places, dropRules(t, places, terminalMember(3)), gfx.Rect{}, terminalMember(3), 300, 610) if got.kind != dropJoin || got.group != toolGroup || got.index != 2 { t.Errorf("tool strip = %+v, want a join of the tool window at index 2", got) } @@ -405,33 +414,33 @@ func TestDropAtBodies(t *testing.T) { body := places[1].body // The middle of a group's body joins it at the end and tints the whole group. - got := dropAt(places, gfx.Rect{}, terminalMember(1), 700, 300) + got := dropAt(places, dropRules(t, places, terminalMember(1)), gfx.Rect{}, terminalMember(1), 700, 300) if got.kind != dropJoin || got.group != "editor:1" || got.index != 2 || got.hasLine || got.preview != (gfx.Rect{X: 400, Y: 0, Width: 600, Height: 600}) { t.Errorf("middle of the editor body = %+v, want a join at the end over the whole group", got) } // Near an edge of the body the tab splits the group, and the preview is that half. - got = dropAt(places, gfx.Rect{}, terminalMember(1), 990, 300) + got = dropAt(places, dropRules(t, places, terminalMember(1)), gfx.Rect{}, terminalMember(1), 990, 300) if got.kind != dropSplit || got.group != "editor:1" || got.edge != edgeRight || got.preview != edgePreview(body, edgeRight) { t.Errorf("right of the editor body = %+v, want a split on the right", got) } // A group with other tabs can be split by its own tab. - got = dropAt(places, gfx.Rect{}, terminalMember(3), 410, 300) + got = dropAt(places, dropRules(t, places, terminalMember(3)), gfx.Rect{}, terminalMember(3), 410, 300) if got.kind != dropSplit || got.group != "editor:1" || got.edge != edgeLeft { t.Errorf("left of its own body = %+v, want a split on the left", got) } // But the middle of its own group is nowhere to go. - if got = dropAt(places, gfx.Rect{}, terminalMember(3), 700, 300); got.kind != dropNone { + if got = dropAt(places, dropRules(t, places, terminalMember(3)), gfx.Rect{}, terminalMember(3), 700, 300); got.kind != dropNone { t.Errorf("middle of its own body = %+v, want no place", got) } // The Terminal tool window is never split: near its edge the tab joins it. - got = dropAt(places, gfx.Rect{}, terminalMember(3), 5, 700) + got = dropAt(places, dropRules(t, places, terminalMember(3)), gfx.Rect{}, terminalMember(3), 5, 700) if got.kind != dropJoin || got.group != toolGroup || got.index != 2 || got.preview != (gfx.Rect{X: 0, Y: 600, Width: 400, Height: 232}) { t.Errorf("edge of the tool body = %+v, want a join, not a split", got) } // A tool window tab dropped on its own body is nowhere to go either. - if got = dropAt(places, gfx.Rect{}, terminalMember(1), 5, 700); got.kind != dropNone { + if got = dropAt(places, dropRules(t, places, terminalMember(1)), gfx.Rect{}, terminalMember(1), 5, 700); got.kind != dropNone { t.Errorf("own tool body = %+v, want no place", got) } } @@ -443,36 +452,45 @@ func TestDropAtSoloPlaceAcceptsNothing(t *testing.T) { body: gfx.Rect{X: 0, Y: 32, Width: 300, Height: 200}, tabs: []tabSlot{{member: terminalMember(5), rect: gfx.Rect{X: 4, Y: 4, Width: 100, Height: 24}}}, }} + // Terminal 6 is open in the tool window, which this page does not lay out. + elsewhere := core.EditorGroup{ID: toolGroup, Members: []string{terminalMember(6)}} for _, at := range [][2]float32{{10, 10}, {100, 100}, {2, 100}} { - if got := dropAt(places, gfx.Rect{}, terminalMember(5), at[0], at[1]); got.kind != dropNone { + if got := dropAt(places, dropRules(t, places, terminalMember(5)), gfx.Rect{}, terminalMember(5), at[0], at[1]); got.kind != dropNone { t.Errorf("solo place at %v = %+v, want no place", at, got) } } // Another terminal can still be dropped into it. - if got := dropAt(places, gfx.Rect{}, terminalMember(6), 10, 10); got.kind != dropJoin || got.index != 0 { + if got := dropAt(places, dropRules(t, places, terminalMember(6), elsewhere), gfx.Rect{}, terminalMember(6), 10, 10); got.kind != dropJoin || got.index != 0 { t.Errorf("strip of the solo place for another terminal = %+v, want a join at 0", got) } - if got := dropAt(places, gfx.Rect{}, terminalMember(6), 100, 100); got.kind != dropJoin || got.index != 1 { + if got := dropAt(places, dropRules(t, places, terminalMember(6), elsewhere), gfx.Rect{}, terminalMember(6), 100, 100); got.kind != dropJoin || got.index != 1 { t.Errorf("body of the solo place for another terminal = %+v, want a join at 1", got) } } func TestDropAtEmptyEditorAndOutside(t *testing.T) { empty := gfx.Rect{X: 0, Y: 32, Width: 1000, Height: 568} - got := dropAt(nil, empty, terminalMember(1), 500, 300) + // Terminal 1 is in the tool window and the editor shows no group. + docked := dropRules(t, nil, terminalMember(1), core.EditorGroup{ID: toolGroup, Members: []string{terminalMember(1)}}) + got := dropAt(nil, docked, empty, terminalMember(1), 500, 300) if got.kind != dropEmpty || got.preview != empty { t.Errorf("empty editor = %+v, want dropEmpty over the editor", got) } - if got = dropAt(nil, empty, terminalMember(1), 500, 10); got.kind != dropNone { + if got = dropAt(nil, docked, empty, terminalMember(1), 500, 10); got.kind != dropNone { t.Errorf("above the empty editor = %+v, want no place", got) } - if got = dropAt(nil, gfx.Rect{}, terminalMember(1), 0, 0); got.kind != dropNone { + if got = dropAt(nil, docked, gfx.Rect{}, terminalMember(1), 0, 0); got.kind != dropNone { t.Errorf("no editor box = %+v, want no place", got) } - // Between the tool window and the editor is no place. - if got = dropAt(dragFixture(), gfx.Rect{}, terminalMember(1), 200, 300); got.kind != dropNone { + // An editor that shows a group has no empty area to drop on. + places := dragFixture() + if got = dropAt(places, dropRules(t, places, terminalMember(1)), empty, terminalMember(1), 200, 300); got.kind != dropNone { t.Errorf("gap = %+v, want no place", got) } + // Without the kernel's rules nothing accepts the tab. + if got = dropAt(places, nil, gfx.Rect{}, terminalMember(1), 900, 10); got.kind != dropNone { + t.Errorf("no rules = %+v, want no place", got) + } } func TestMemberAndGroupNames(t *testing.T) { @@ -542,11 +560,13 @@ func TestTabDragLocateStaysInsideTheWindow(t *testing.T) { a.term.tool, a.term.groups = groupsOf(dragFixture()) viewport := gfx.Size{Width: 1000, Height: 840} - if got := a.tabDragLocate(terminalMember(1), 900, 10, viewport); got.kind != dropJoin || got.group != "editor:1" { + rules := dropRules(t, dragFixture(), terminalMember(1)) + + if got := a.tabDragLocate(terminalMember(1), rules, 900, 10, viewport); got.kind != dropJoin || got.group != "editor:1" { t.Errorf("inside the window = %+v, want a join of editor:1", got) } for _, at := range [][2]float32{{-1, 10}, {900, -1}, {1000, 10}, {900, 840}} { - if got := a.tabDragLocate(terminalMember(1), at[0], at[1], viewport); got.kind != dropNone { + if got := a.tabDragLocate(terminalMember(1), rules, at[0], at[1], viewport); got.kind != dropNone { t.Errorf("outside the window at %v = %+v, want no place", at, got) } } @@ -558,12 +578,12 @@ func groupsOf(places []dropPlace) (*groupPlace, []*groupPlace) { var tool *groupPlace var groups []*groupPlace for _, p := range places { - g := newGroupPlace(p.group, p.tool) + g := newGroupPlace(p.group) g.strip, g.body = p.strip, p.body for _, t := range p.tabs { g.chips = append(g.chips, tabSlotDecl{member: t.member, rect: t.rect}) } - if p.tool { + if p.group == toolGroup { tool = g } else { groups = append(groups, g) @@ -573,8 +593,8 @@ func groupsOf(places []dropPlace) (*groupPlace, []*groupPlace) { } func TestGroupPlaceReportsWhatTheLastPaintLaidOut(t *testing.T) { - g := newGroupPlace("editor:1", false) - if p := g.place(); p.group != "editor:1" || p.tool || p.strip != (gfx.Rect{}) || p.body != (gfx.Rect{}) || len(p.tabs) != 0 { + g := newGroupPlace("editor:1") + if p := g.place(); p.group != "editor:1" || p.strip != (gfx.Rect{}) || p.body != (gfx.Rect{}) || len(p.tabs) != 0 { t.Errorf("place of a group nothing was laid out for = %+v, want only its name", p) } g.stripHook(&ui.DrawContext{Rect: gfx.Rect{X: 1, Y: 2, Width: 3, Height: 4}}) @@ -584,15 +604,12 @@ func TestGroupPlaceReportsWhatTheLastPaintLaidOut(t *testing.T) { if p.strip.Width != 3 || len(p.tabs) != 1 || p.tabs[0].member != terminalMember(5) || p.tabs[0].rect.X != 9 { t.Errorf("place = %+v, want the strip and the tab the hooks were given", p) } - if got := newGroupPlace(toolGroup, true).place(); !got.tool { - t.Errorf("place of the tool window = %+v, want tool", got) - } } func TestTerminalUIPlacesTheToolWindowFirst(t *testing.T) { u := terminalUI{ - tool: newGroupPlace(toolGroup, true), - groups: []*groupPlace{newGroupPlace("editor:1", false), newGroupPlace("editor:2", false)}, + tool: newGroupPlace(toolGroup), + groups: []*groupPlace{newGroupPlace("editor:1"), newGroupPlace("editor:2")}, } ids := func() []string { var ids []string @@ -613,8 +630,8 @@ func TestTerminalUIPlacesTheToolWindowFirst(t *testing.T) { func TestBeginTerminalFrameKeepsTheGesture(t *testing.T) { a := &App{} u := &a.term - u.tool, u.toolDrawn, u.emptyDrawn = newGroupPlace(toolGroup, true), true, true - u.groups = append(u.groups, newGroupPlace("editor:1", false), newGroupPlace("editor:2", false)) + u.tool, u.toolDrawn, u.emptyDrawn = newGroupPlace(toolGroup), true, true + u.groups = append(u.groups, newGroupPlace("editor:1"), newGroupPlace("editor:2")) u.tabIDs = append(u.tabIDs, tabID{member: terminalMember(1)}) u.drag = tabDrag{active: true, member: terminalMember(2)} @@ -636,24 +653,24 @@ func TestDropAtFileTab(t *testing.T) { file := documentMember(7) // In its own strip the file is not counted, so the two terminals are before the pointer. - if got := dropAt(places, gfx.Rect{}, file, 900, 10); got.kind != dropJoin || got.group != "editor:1" || got.index != 2 { + if got := dropAt(places, dropRules(t, places, file), gfx.Rect{}, file, 900, 10); got.kind != dropJoin || got.group != "editor:1" || got.index != 2 { t.Errorf("own strip = %+v, want a join at index 2", got) } // Before the middle of the first tab it goes first, in front of the terminals. - if got := dropAt(places, gfx.Rect{}, file, 430, 10); got.kind != dropJoin || got.index != 0 { + if got := dropAt(places, dropRules(t, places, file), gfx.Rect{}, file, 430, 10); got.kind != dropJoin || got.index != 0 { t.Errorf("front of its strip = %+v, want a join at index 0", got) } // Near an edge of its group's body it splits the group. - if got := dropAt(places, gfx.Rect{}, file, 410, 300); got.kind != dropSplit || got.edge != edgeLeft { + if got := dropAt(places, dropRules(t, places, file), gfx.Rect{}, file, 410, 300); got.kind != dropSplit || got.edge != edgeLeft { t.Errorf("left edge = %+v, want a split on the left", got) } // A terminal of the group counts the file's tab among the others. - if got := dropAt(places, gfx.Rect{}, terminalMember(3), 990, 10); got.kind != dropJoin || got.index != 2 { + if got := dropAt(places, dropRules(t, places, terminalMember(3)), gfx.Rect{}, terminalMember(3), 990, 10); got.kind != dropJoin || got.index != 2 { t.Errorf("terminal at the end of a mixed strip = %+v, want a join at index 2", got) } // The Terminal tool window's strip and body take no file. for _, at := range [][2]float32{{300, 610}, {200, 700}} { - if got := dropAt(places, gfx.Rect{}, file, at[0], at[1]); got.kind != dropNone { + if got := dropAt(places, dropRules(t, places, file), gfx.Rect{}, file, at[0], at[1]); got.kind != dropNone { t.Errorf("file over the tool window at %v = %+v, want no place", at, got) } } diff --git a/desktop/internal/workbench/tab_menu.go b/desktop/internal/workbench/tab_menu.go index 258fd6c92c..76a40fa18e 100644 --- a/desktop/internal/workbench/tab_menu.go +++ b/desktop/internal/workbench/tab_menu.go @@ -153,5 +153,7 @@ func (a *App) setTabPinned(p *project, group string, d *document, pinned bool) { front++ } } - a.moveTab(p, member, group, front) + a.reduceTerminals(p, p.terms.bench, core.DropEditorTab(core.EditorDrop{ + Member: member, Target: core.JoinEditorGroup(group, front), Docked: dockedGroups, Dockable: dockable(member), + })) } diff --git a/desktop/internal/workbench/tabdrag.go b/desktop/internal/workbench/tabdrag.go index 5493b18c90..e11ea719ed 100644 --- a/desktop/internal/workbench/tabdrag.go +++ b/desktop/internal/workbench/tabdrag.go @@ -1,6 +1,9 @@ package workbench import ( + "context" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/fileicons" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" "github.com/vivaui/viva/gfx" @@ -19,6 +22,9 @@ type tabDrag struct { viewport gfx.Size // target is where the tab would land if it were dropped now. target dropTarget + // rules is where the kernel lets the tab land, asked once as the drag starts; nil when + // the kernel could not say, and then the tab lands nowhere. + rules *core.EditorDropRules } // tabAccept is the tab target's accept callback: it follows the pointer of the drag of a @@ -29,12 +35,35 @@ func (a *App) tabAccept(source, _ gfx.ID) bool { return false } d := &a.term.drag + if !d.active || d.member != member { + d.rules = a.tabDropRules(member) + } point := a.dnd.tab.At() d.active, d.member, d.x, d.y, d.viewport = true, member, point.X, point.Y, a.viewport() - d.target = a.tabDragLocate(member, point.X, point.Y, d.viewport) + d.target = a.tabDragLocate(member, d.rules, point.X, point.Y, d.viewport) return d.target.kind != dropNone } +// tabDropRules asks the kernel where the tab of group member may land in the project's +// groups; nil, with the reason on the notice banner, when it cannot say. +func (a *App) tabDropRules(member string) *core.EditorDropRules { + p := a.project + if p == nil { + return nil + } + ctx, cancel := context.WithTimeout(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.notifyError(a.text.Errors.Core(err.Error())) + return nil + } + return &rules +} + // tabDrop does what dropping the dragged tab where tabAccept last aimed it asks for. func (a *App) tabDrop(_, _ gfx.ID) { d := a.term.drag @@ -45,13 +74,13 @@ func (a *App) tabDrop(_, _ gfx.ID) { } // tabDragLocate finds where dropping the tab of group member at (x, y) would put it, from -// where the last frame laid the groups out. Outside the window there is no place. viewport -// is the window's size. -func (a *App) tabDragLocate(member string, x, y float32, viewport gfx.Size) dropTarget { +// where the last frame laid the groups out and the places rules accepts. Outside the window +// there is no place. viewport is the window's size. +func (a *App) tabDragLocate(member string, rules *core.EditorDropRules, x, y float32, viewport gfx.Size) dropTarget { if x < 0 || y < 0 || x >= viewport.Width || y >= viewport.Height { return dropTarget{} } - return dropAt(a.term.places(), a.term.emptyRect, member, x, y) + return dropAt(a.term.places(), rules, a.term.emptyRect, member, x, y) } // paintTabDrag paints the gesture on top of the frame, in the manner of paintDrag: the area diff --git a/desktop/internal/workbench/tabstrip.go b/desktop/internal/workbench/tabstrip.go index 9eb85a2be5..56d1ec3b10 100644 --- a/desktop/internal/workbench/tabstrip.go +++ b/desktop/internal/workbench/tabstrip.go @@ -303,7 +303,7 @@ func (a *App) tabBar(c ui.C, place *groupPlace, layout tabLayout, buttons func() ui.Row(c).Height(panelHeaderHeight).Shrink(1).MinWidth(0).Items(ui.Center).Gap(chromeGap).Grow(1).Children(func() { view := ui.Row(c).FillHeight().Items(ui.Center).Shrink(1).MinWidth(0).Clip() - if !place.tool { + if place.id != toolGroup { view.Grow(1) } else { // The tool window's tabs keep their width and give way before the buttons do. @@ -514,7 +514,7 @@ func (a *App) closeTab(t shownTab) { // tabMenuMaxHeight. func (a *App) hiddenTabsButton(c ui.C, place *groupPlace, s *tabStrip, tabs []shownTab, current string) { icon := icons.ChevronDown - if place.tool { + if place.id == toolGroup { icon = icons.Ellipsis } button, clicked := a.toolIconButton(c.Part("more"), a.text.Editor.HiddenTabs, icon, s.menu, false) diff --git a/desktop/internal/workbench/terminals.go b/desktop/internal/workbench/terminals.go index 0857d56a5c..9fe554398d 100644 --- a/desktop/internal/workbench/terminals.go +++ b/desktop/internal/workbench/terminals.go @@ -151,17 +151,15 @@ type tabSlotDecl struct { // The rectangles are written by draw hooks as the paint goes, so between paints they are // those of the last complete one. type groupPlace struct { - id string - // tool says the group is the Terminal tool window. - tool bool + id string strip, body gfx.Rect chips []tabSlotDecl stripHook func(*ui.DrawContext) bodyHook func(*ui.DrawContext) } -func newGroupPlace(id string, tool bool) *groupPlace { - g := &groupPlace{id: id, tool: tool} +func newGroupPlace(id string) *groupPlace { + g := &groupPlace{id: id} g.stripHook = func(d *ui.DrawContext) { g.strip = d.Rect } g.bodyHook = func(d *ui.DrawContext) { g.body = d.Rect } return g @@ -174,7 +172,7 @@ func (g *groupPlace) chipHook(i int) func(*ui.DrawContext) { // place is where the group was laid out, for a drag to aim at. func (g *groupPlace) place() dropPlace { - p := dropPlace{group: g.id, tool: g.tool, strip: g.strip, body: g.body, tabs: make([]tabSlot, 0, len(g.chips))} + p := dropPlace{group: g.id, strip: g.strip, body: g.body, tabs: make([]tabSlot, 0, len(g.chips))} for _, t := range g.chips { p.tabs = append(p.tabs, tabSlot{member: t.member, rect: t.rect}) } @@ -306,24 +304,42 @@ func (a *App) endTerminalFrame() { // is what a person who just picked, opened or moved a terminal expects to type into. func (a *App) focusTerminal(id int) { a.focus = focusTarget{term: id} } -// reduceTerminals applies action to state through the kernel and, if the kernel accepts -// it, makes the result the project's tab groups. A group the kernel removed leaves the split -// layout with it, so the layout never shows a group that does not exist. It reports whether -// the state changed; on an error nothing is changed and the notice banner says why. +// reduceTerminals applies action to state and the split layout through the kernel and, if the +// kernel accepts it, makes the result the project's tab groups and layout. A group the kernel +// removed leaves the layout with it, so the layout never shows a group that does not exist. It +// reports whether the state changed; on an error nothing is changed and the notice banner says +// why, and a rejected drop changes nothing either. func (a *App) reduceTerminals(p *project, state core.EditorWorkbench, action core.EditorAction) bool { + _, ok := a.reduceEditorLayout(p, state, action) + return ok +} + +// 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) defer cancel() - next, removed, err := a.kernel.ReduceEditorWorkbench(ctx, state, action) + set := &p.terms + result, err := a.kernel.ReduceEditorLayout(ctx, state, layoutShape(set.layout), action) if err != nil { a.notifyError(a.text.Errors.Core(err.Error())) - return false + return result, false } - set := &p.terms - set.bench = next - for _, group := range removed { - set.layout = removeLeaf(set.layout, group) + if result.Rejection != "" { + return result, false } - return true + set.bench = result.State + set.layout = adoptLayout(set.layout, result.Layout) + return result, true +} + +// dockedGroups are the groups docked in a tool window: the Terminal tool window's, which only a +// terminal's tab joins and which is never split. +var dockedGroups = []string{toolGroup} + +// dockable says the tab of member may join a group docked in a tool window. +func dockable(member string) bool { + _, ok := memberTerminal(member) + return ok } // newTerminal opens a terminal at the end of the Terminal tool window's tabs and shows it, @@ -458,26 +474,35 @@ func (a *App) selectTerminal(p *project, id int) { } // dropTab does what dropping the tab of group member on target asks for, and shows the -// terminal, the file, the diff, the viewer or the LSP Logs tab with the keyboard if it was done: a tab dropped on a strip or -// on the middle of a group joins it, one dropped near the edge of a group splits it, and one -// dropped on an empty editor opens the first group. A target that is no place does nothing. +// terminal, the file, the diff, the viewer or the LSP Logs tab with the keyboard if it was +// done. The kernel carries the drop out over the groups and the layout: a tab dropped on a +// strip or on the middle of a group joins it, one dropped near the edge of a group splits it, +// and one dropped on an empty editor opens the first group. A target that is no place, or one +// the kernel rejects because the groups changed under the drag, does nothing. func (a *App) dropTab(member string, target dropTarget) { p := a.project if p == nil { return } - done := false - switch target.kind { - case dropJoin: - done = a.moveTab(p, member, target.group, target.index) - case dropSplit: - done = a.splitTab(p, member, target.group, target.edge) - case dropEmpty: - done = a.placeInEmptyEditor(p, member) + place, ok := target.place() + if !ok { + return } - if !done { + set := &p.terms + added, node := editorGroupID(set.nextGroup+1), set.nextNode+1 + result, ok := a.reduceEditorLayout(p, set.bench, core.DropEditorTab(core.EditorDrop{ + Member: member, Target: place, Docked: dockedGroups, Dockable: dockable(member), + NewGroup: added, NewNode: node, + })) + if !ok { return } + if result.Group == added { + set.nextGroup++ + } + if target.kind == dropSplit { + set.nextNode = node + } if id, ok := memberTerminal(member); ok { a.focusTerminal(id) } else if id, ok := memberDocument(member); ok { @@ -491,93 +516,6 @@ func (a *App) dropTab(member string, target dropTarget) { } } -// moveTab puts group member into group as the tab at index, counted among the group's tabs -// without it, and shows it there. Inside its own group that reorders the tabs. It reports -// whether the kernel accepted the move. -func (a *App) moveTab(p *project, member, group string, index int) bool { - set := &p.terms - src, dest := set.bench.GroupOf(member), set.bench.Group(group) - if src == nil || dest == nil { - return false - } - if src.ID == group { - at := slices.Index(src.Members, member) - index = min(max(index, 0), len(src.Members)-1) - if at >= 0 && at != index && !a.reduceTerminals(p, set.bench, core.ReorderEditor(group, at, index)) { - return false - } - return a.reduceTerminals(p, set.bench, core.ActivateEditor(group, member)) - } - before := "" - if index = max(index, 0); index < len(dest.Members) { - before = dest.Members[index] - } - return a.reduceTerminals(p, set.bench, core.MoveEditor(core.EditorMove{ - Member: member, From: src.ID, To: group, Before: before, Activate: true, - Empty: emptyPolicy(src.ID), Fallback: core.SelectAdjacent, - })) -} - -// moveIntoNewGroup moves group member into a group of the editor area that it makes, and -// returns the new group's name. The caller gives the group its place in the layout. The -// group it left goes if that leaves it empty, which the layout follows. -func (a *App) moveIntoNewGroup(p *project, member string) (string, bool) { - set := &p.terms - src := set.bench.GroupOf(member) - if src == nil { - return "", false - } - from := src.ID - added := editorGroupID(set.nextGroup + 1) - state := set.bench - state.Groups = append(slices.Clone(state.Groups), core.EditorGroup{ID: added}) - if !a.reduceTerminals(p, state, core.MoveEditor(core.EditorMove{ - Member: member, From: from, To: added, Activate: true, - Empty: emptyPolicy(from), Fallback: core.SelectAdjacent, - })) { - return "", false - } - set.nextGroup++ - return added, true -} - -// splitTab moves group member into a new group beside the group target, on the side e -// names. Whether it can is checked before anything changes, so the layout never gets a -// group the state does not have: target must be in the layout, and a group's only tab -// cannot split off its own group, since nothing would be left to split from. -func (a *App) splitTab(p *project, member, target string, e edge) bool { - set := &p.terms - src := set.bench.GroupOf(member) - if src == nil || e == edgeNone || !set.layout.contains(target) { - return false - } - if src.ID == target && len(src.Members) < 2 { - return false - } - added, ok := a.moveIntoNewGroup(p, member) - if !ok { - return false - } - set.nextNode++ - set.layout = splitLeaf(set.layout, target, added, e, set.nextNode) - return true -} - -// placeInEmptyEditor moves group member into the first group of an editor that has none, -// which then fills the editor. -func (a *App) placeInEmptyEditor(p *project, member string) bool { - set := &p.terms - if set.layout != nil { - return false - } - added, ok := a.moveIntoNewGroup(p, member) - if !ok { - return false - } - set.layout = newLeaf(added) - return true -} - // terminalTitle is the name on a terminal's tab: the plugin's title, or "Local (n)". func (a *App) terminalTitle(t *terminal) string { if t.title != "" { From c0e6b3cedd3357df62b8f8f56b7968268b9cd5d0 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 09:34:06 +0800 Subject: [PATCH 08/11] =?UTF-8?q?fix(desktop):=20=E9=A1=B9=E7=9B=AE?= =?UTF-8?q?=E6=A0=91=E5=8F=AF=E8=A7=81=E8=A1=8C=E3=80=81=E9=80=89=E6=8B=A9?= =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E4=B8=8E=E5=A4=9A=E9=80=89=E6=94=B9=E7=94=B1?= =?UTF-8?q?=20Core=20=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 树的形状变化后(目录打开/关闭、列表返回、节点消失)调用一次 workspace.projectTree.rows,由 Core 给出显示的行、修正后的选择和视口顶端行; 不再每帧在 Go 里展平,缩放和重绘不调用 Core(1000 行缩放 397→394µs/op,分配不变)。 - 删除 Go 里的选择修正、视口锚点恢复、扩选范围和“已被标记目录包含”判断; 普通/Cmd/Shift 点击与批量结束走 workspace.rowSelection.reduce,批量目标用 Core 的 targets。 - Commit 窗口改动行的多选使用同一个归约。 - 同名目录被文件替换时选择跟随路径,选中顶层文件被删时选择回到根节点。 - 更新项目树 Agent Note,补选择归约和改动行多选的回归测试。 Closes #1800 --- .../2026-10-19-lazy-project-tree.md | 37 ++++- desktop/internal/core/project_tree.go | 132 ++++++++++++++++++ desktop/internal/core/project_tree_test.go | 109 +++++++++++++++ desktop/internal/workbench/app.go | 2 + .../internal/workbench/changelists_select.go | 65 ++++----- desktop/internal/workbench/filetree.go | 93 ++++-------- .../internal/workbench/filetree_actions.go | 19 +-- desktop/internal/workbench/filetree_batch.go | 75 ++-------- .../internal/workbench/filetree_bench_test.go | 2 +- desktop/internal/workbench/filetree_rows.go | 120 ++++++++++++++++ desktop/internal/workbench/filetree_test.go | 127 +++++++++++++++-- desktop/internal/workbench/filetree_view.go | 27 ++-- 12 files changed, 603 insertions(+), 205 deletions(-) create mode 100644 desktop/internal/core/project_tree.go create mode 100644 desktop/internal/core/project_tree_test.go create mode 100644 desktop/internal/workbench/filetree_rows.go diff --git a/.agents/notes/implemented/architecture/2026-10-19-lazy-project-tree.md b/.agents/notes/implemented/architecture/2026-10-19-lazy-project-tree.md index 5bc5a07c78..06208dbf55 100644 --- a/.agents/notes/implemented/architecture/2026-10-19-lazy-project-tree.md +++ b/.agents/notes/implemented/architecture/2026-10-19-lazy-project-tree.md @@ -18,9 +18,32 @@ Viva 客户端在已加载根目录后将根节点作为第 0 层行显示,包 13pt 文字及圆角选中背景参照迁移前原生实现;展开箭头直接使用原版 IDEA SVG。 这只覆盖了上述树行和基础交互,不能据此认为包压缩、多选、批量移动、完整菜单或逐像素视觉对照已完成。 原生窗口失焦时 Viva 的焦点接口目前只提供控件焦点,选中态的窗口失焦表现仍需实机确认。 -当前可见行投影和方向键目标仍在 Go 客户端,违反共享规则归属;已建 -[#1800](https://github.com/1lck/Lithe-IDEA/issues/1800) 跟踪下沉到 Core。原版多选规则 -不在当前 Core 接口中,不能继续把其状态转换新增到界面层;本次临时实现已撤回。 + +### 哪些行显示、选中谁,由 Core 决定(#1800) + +项目树“显示哪些行”和“选中、标记哪些行”是所有客户端都要一致的规则,所以放在 Rust Core, +界面只负责列目录的结果、哪些目录打开、焦点、滚动和绘制: + +- `workspace.projectTree.rows`(Core crate `lithe-project-tree`):树的形状变化后 + (目录打开或关闭、列表返回、节点消失),界面把已加载节点按先序连同层级和是否打开发给 Core, + Core 返回要显示的行、修正后的选择,以及变化前视口顶端那一行现在的位置。 + 选中的节点消失时,选择交给仍加载的最近上级目录;被关闭的目录挡住时,交给它上方最近的可见行。 + 被关闭目录里的标记保留,消失节点的标记和锚点丢弃。 +- `workspace.rowSelection.reduce`(Core crate `lithe-row-selection`):一次点击怎样改选择。 + 普通点击选中一行并清掉标记;Cmd/Ctrl 点击切换一行的标记并把它设为锚点(Shift 扩选的起点); + Shift 点击标记锚点(没有锚点时从选中行)到点击行之间的所有行。根节点永远不会被标记。 + 批量操作的目标是标记行去掉已被标记目录包含的那些。Commit 窗口的改动行使用同一个归约。 + +开发者要记住: + +- 只在树的形状变化后调用一次 `workspace.projectTree.rows`(Go 侧设置 `rowsDirty`, + 下一次绘制或列表返回时刷新),不要每帧发送整棵树。缩放窗口、滚动和重绘不调用 Core。 +- 不要在 Go 里自己算可见行、扩选范围或“选择移到哪里”。需要新的选择语义时改 Core 的 + fixture(`rust/fixtures/workspace/row-selection-v1.json`、`project-tree-rows-v1.json`)和 crate。 +- 方向键在行之间移动焦点由 Viva 的 `ui.Tree` 组件负责,选中行跟随焦点;这是通用控件行为, + 不是项目树专有规则。 +- Collapse All 把选中行藏起来时,界面把键盘焦点交给新选中的行;外部文件变化 + (例如选中的文件被删除)移动选择时只改选中行,不抢键盘焦点。 ## 问题 @@ -186,6 +209,10 @@ Windows 以后也没法复用。因此生产路径走 Rust,Swift 版本只作 ## 验证 - Viva 项目树回归:`./scripts/desktop/desktop-go.sh test -race ./internal/workbench -run TestProjectTree` +- 选择归约与改动行多选:`./scripts/desktop/desktop-go.sh test ./internal/workbench -run 'TestProjectTreeBatchSelectionFollowsCore|TestChangeListRowSelectionFollowsCore'` +- Core 规则与 fixture:在 Lithe-core-rust 运行 `cargo test -p lithe-core -- project_tree row_selection` +- 1000 行项目树缩放耗时:`./scripts/desktop/desktop-go.sh test ./internal/workbench -run '^$' -bench BenchmarkProjectTreeResize1000 -benchmem` + (#1800 前后同机约 397µs/op 与 394µs/op,内存分配不变) - `./scripts/desktop/verify/verify-runtime-bundle-immutability.sh` - `./scripts/agent-notes/verify-agent-notes.sh` - 旧版 macOS 的 Swift 和 Core 测试及共享契约脚本仅是迁移前的历史验证,不能代替 Viva 验收。 @@ -193,7 +220,11 @@ Windows 以后也没法复用。因此生产路径走 Rust,Swift 版本只作 ## 适用范围 - Lithe-core-rust 锁定修订:[rust/lithe-core/src/project/files.rs](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/0ffd327b4329261e393b08ed76fbd134b4dd17e9/rust/lithe-core/src/project/files.rs) +- Lithe-core-rust:`rust/crates/project-tree/`、`rust/crates/row-selection/` +- `desktop/internal/core/project_tree.go` - `desktop/internal/workbench/filetree.go` +- `desktop/internal/workbench/filetree_rows.go` +- `desktop/internal/workbench/changelists_select.go` - `desktop/internal/workbench/filetree_watch.go` - `desktop/internal/workbench/filetree_test.go` - 原版实现保留为历史参考:[ProjectTreeLoader.swift](https://github.com/1lck/Lithe-IDEA/blob/5a54c41aa37a4e6e6b68918a4b05765b9dd07a36/macos/Sources/Lithe/Models/Workspace/ProjectTreeLoader.swift)、[FileNodePathLookup.swift](https://github.com/1lck/Lithe-IDEA/blob/5a54c41aa37a4e6e6b68918a4b05765b9dd07a36/macos/Sources/LitheCoreContracts/Workspace/FileNodePathLookup.swift)、[LitheWorkspaceModule](https://github.com/1lck/Lithe-IDEA/tree/5a54c41aa37a4e6e6b68918a4b05765b9dd07a36/macos/Sources/LitheWorkspaceModule)。 diff --git a/desktop/internal/core/project_tree.go b/desktop/internal/core/project_tree.go new file mode 100644 index 0000000000..de26b197ea --- /dev/null +++ b/desktop/internal/core/project_tree.go @@ -0,0 +1,132 @@ +package core + +import ( + "context" + "encoding/json" +) + +// RowSelection is the multi-selection of rows that show workspace paths, such as the project +// tree and the changes of a change list. The empty path is the workspace root, which is never +// marked. +type RowSelection struct { + // Selected is the path of the selected row, nil when no row is selected. + Selected *string `json:"selected"` + // Marked are the paths marked for a batch, in path order. + Marked []string `json:"marked,omitempty"` + // Anchor is the path a Shift click extends from, empty when there is none. + Anchor string `json:"anchor,omitempty"` +} + +// RowAction is one click on a row, or the end of a batch. Build it with ChooseRow, ToggleRow, +// ExtendRow or ClearRows. +type RowAction struct { + kind, path string +} + +// ChooseRow is a plain click on the row of path: it selects the row and drops the marks and the +// anchor. +func ChooseRow(path string) RowAction { return RowAction{kind: "choose", path: path} } + +// ToggleRow is a Cmd or Ctrl click on the row of path: it marks or unmarks the row, selects it +// and makes it the anchor. +func ToggleRow(path string) RowAction { return RowAction{kind: "toggle", path: path} } + +// ExtendRow is a Shift click on the row of path: it marks every row from the anchor, else from +// the selected row, to this one, keeps the other marks and selects the row. +func ExtendRow(path string) RowAction { return RowAction{kind: "extend", path: path} } + +// ClearRows ends a batch: the marks and the anchor go and the selected row stays. +func ClearRows() RowAction { return RowAction{kind: "clear"} } + +// MarshalJSON encodes the action as the exact object of its kind. +func (a RowAction) MarshalJSON() ([]byte, error) { + if a.kind == "clear" || a.kind == "" { + return json.Marshal(struct { + Kind string `json:"kind"` + }{"clear"}) + } + return json.Marshal(struct { + Kind string `json:"kind"` + Path string `json:"path"` + }{a.kind, a.path}) +} + +// RowSelectionStale is the rejection of a click on a path that is not one of the rows, as when +// the row went away between the paint that showed it and the click. +const RowSelectionStale = "workspace.rowSelection.stale" + +// RowSelectionResult is the outcome of one workspace.rowSelection.reduce. +type RowSelectionResult struct { + Selection RowSelection `json:"selection"` + // Targets is what a batch acts on: the marked paths without those inside a marked folder, + // empty when nothing is marked. + Targets []string `json:"targets"` + // Rejection says why the action did not apply; Selection is then as sent. + Rejection string `json:"rejection"` +} + +// ReduceRowSelection applies action to selection over rows, the paths of the rows the host +// shows, top to bottom (workspace.rowSelection.reduce). The call only computes over its +// arguments and is fast enough for an event handler. +func (c *Client) ReduceRowSelection(ctx context.Context, rows []string, selection RowSelection, action RowAction) (RowSelectionResult, error) { + payload := struct { + Rows []string `json:"rows"` + Selection RowSelection `json:"selection"` + Action RowAction `json:"action"` + }{nonNil(rows), selection, action} + var result RowSelectionResult + if err := c.Execute(ctx, "workspace.rowSelection.reduce", payload, &result); err != nil { + return RowSelectionResult{}, err + } + result.Selection.Marked, result.Targets = nonNil(result.Selection.Marked), nonNil(result.Targets) + return result, nil +} + +// ProjectTreeNode is a project tree node the host loaded: its path, relative to the project +// root with "/" separators and empty for the root, its depth, 0 for the root, and whether it is +// a folder the user opened. +type ProjectTreeNode struct { + Path string `json:"path"` + Depth int `json:"depth"` + Open bool `json:"open,omitempty"` +} + +// ProjectTreeQuery is the shape of the project tree after a change. +type ProjectTreeQuery struct { + // Nodes are the loaded nodes in preorder; the first is the root. + Nodes []ProjectTreeNode + Selection RowSelection + // Top is the path of the row at the top of the view before the change, nil for none. + Top *string +} + +// ProjectTreeRows is the outcome of one workspace.projectTree.rows. +type ProjectTreeRows struct { + // Rows are the positions in the query's Nodes of the rows that show, top to bottom. + Rows []int `json:"rows"` + Selection RowSelection `json:"selection"` + // SelectionMoved says the selected row is not the one the query selected, because that node + // went away or a closed folder hides it. + SelectionMoved bool `json:"selectionMoved"` + // TopRow is the row the query's Top is now, nil when it no longer shows. + TopRow *int `json:"topRow"` + Targets []string `json:"targets"` +} + +// ProjectTreeRows has Core say which of the loaded nodes show as rows, keep the selection on a +// row that shows and find the row the top of the view was on (workspace.projectTree.rows). +// Nothing reads the disk; hosts ask once per change of the tree's shape, never per paint. +func (c *Client) ProjectTreeRows(ctx context.Context, query ProjectTreeQuery) (ProjectTreeRows, error) { + payload := struct { + Nodes []ProjectTreeNode `json:"nodes"` + Selection RowSelection `json:"selection"` + Top *string `json:"top,omitempty"` + }{nonNil(query.Nodes), query.Selection, query.Top} + var result ProjectTreeRows + if err := c.Execute(ctx, "workspace.projectTree.rows", payload, &result); err != nil { + return ProjectTreeRows{}, err + } + result.Rows, result.Targets = nonNil(result.Rows), nonNil(result.Targets) + result.Selection.Marked = nonNil(result.Selection.Marked) + return result, nil +} diff --git a/desktop/internal/core/project_tree_test.go b/desktop/internal/core/project_tree_test.go new file mode 100644 index 0000000000..59498ecaf8 --- /dev/null +++ b/desktop/internal/core/project_tree_test.go @@ -0,0 +1,109 @@ +package core + +import ( + "encoding/json" + "slices" + "testing" +) + +func TestReduceRowSelection(t *testing.T) { + client := NewClient() + ctx := testContext(t) + rows := []string{"", "a", "a/x", "b", "c"} + reduce := func(t *testing.T, selection RowSelection, action RowAction) RowSelectionResult { + t.Helper() + result, err := client.ReduceRowSelection(ctx, rows, selection, action) + if err != nil { + t.Fatalf("ReduceRowSelection() error: %v", err) + } + return result + } + + t.Run("a Shift click marks from the anchor and keeps the other marks", func(t *testing.T) { + result := reduce(t, RowSelection{Selected: new("a"), Marked: []string{"c"}, Anchor: "a/x"}, ExtendRow("b")) + if s := result.Selection; s.Selected == nil || *s.Selected != "b" || s.Anchor != "a/x" || !slices.Equal(s.Marked, []string{"a/x", "b", "c"}) { + t.Fatalf("selection = %+v, want b selected, a/x to c marked, anchor kept", s) + } + }) + + t.Run("a marked folder stands for its contents", func(t *testing.T) { + result := reduce(t, RowSelection{Selected: new("b")}, ExtendRow("a")) + if !slices.Equal(result.Targets, []string{"a", "b"}) { + t.Fatalf("targets = %v, want a and b", result.Targets) + } + }) + + t.Run("the root is never marked", func(t *testing.T) { + result := reduce(t, RowSelection{Selected: new("a")}, ToggleRow("")) + if len(result.Selection.Marked) != 0 || *result.Selection.Selected != "a" { + t.Fatalf("selection = %+v, want it unchanged", result.Selection) + } + }) + + t.Run("clear keeps the selected row", func(t *testing.T) { + result := reduce(t, RowSelection{Selected: new("b"), Marked: []string{"a", "b"}, Anchor: "a"}, ClearRows()) + if s := result.Selection; *s.Selected != "b" || len(s.Marked) != 0 || s.Anchor != "" || result.Targets == nil { + t.Fatalf("selection = %+v, targets %v; want b alone and no targets", s, result.Targets) + } + }) + + t.Run("a click on a row that went away is stale", func(t *testing.T) { + if got := reduce(t, RowSelection{}, ChooseRow("gone")).Rejection; got != RowSelectionStale { + t.Fatalf("rejection = %q, want %q", got, RowSelectionStale) + } + }) +} + +func TestProjectTreeRows(t *testing.T) { + client := NewClient() + ctx := testContext(t) + nodes := []ProjectTreeNode{ + {Path: "", Depth: 0, Open: true}, + {Path: "a", Depth: 1}, + {Path: "a/x", Depth: 2}, + {Path: "b", Depth: 1}, + } + result, err := client.ProjectTreeRows(ctx, ProjectTreeQuery{ + Nodes: nodes, + Selection: RowSelection{Selected: new("a/x"), Marked: []string{"a/x", "gone"}}, + Top: new("b"), + }) + if err != nil { + t.Fatalf("ProjectTreeRows() error: %v", err) + } + if !slices.Equal(result.Rows, []int{0, 1, 3}) { + t.Errorf("rows = %v, want the root, a and b", result.Rows) + } + if s := result.Selection; !result.SelectionMoved || s.Selected == nil || *s.Selected != "a" || !slices.Equal(s.Marked, []string{"a/x"}) { + t.Errorf("selection = %+v moved %v, want a, the hidden mark kept and the gone one dropped", s, result.SelectionMoved) + } + if result.TopRow == nil || *result.TopRow != 2 { + t.Errorf("top row = %v, want 2", result.TopRow) + } + if _, err := client.ProjectTreeRows(ctx, ProjectTreeQuery{Nodes: nodes[1:]}); err == nil { + t.Error("nodes without the root were accepted") + } +} + +func TestRowActionEncoding(t *testing.T) { + cases := []struct { + action RowAction + want string + }{ + {ChooseRow("a"), `{"kind":"choose","path":"a"}`}, + {ToggleRow(""), `{"kind":"toggle","path":""}`}, + {ExtendRow("b"), `{"kind":"extend","path":"b"}`}, + {ClearRows(), `{"kind":"clear"}`}, + {RowAction{}, `{"kind":"clear"}`}, + } + for _, c := range cases { + got, err := json.Marshal(c.action) + if err != nil || string(got) != c.want { + t.Errorf("Marshal = %s, %v; want %s", got, err, c.want) + } + } + got, _ := json.Marshal(RowSelection{}) + if want := `{"selected":null}`; string(got) != want { + t.Errorf("empty selection = %s, want %s", got, want) + } +} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 1558c48568..2de2451a84 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -129,6 +129,8 @@ type Kernel interface { GitHistoryDates(ctx context.Context, entries []core.HistoryDateEntry, after, before *int64) ([]string, error) ReduceEditorLayout(ctx context.Context, state core.EditorWorkbench, layout *core.EditorLayout, action core.EditorAction) (core.EditorLayoutResult, error) EditorDropTargets(ctx context.Context, query core.EditorDropQuery) (core.EditorDropRules, error) + ReduceRowSelection(ctx context.Context, rows []string, selection core.RowSelection, action core.RowAction) (core.RowSelectionResult, error) + ProjectTreeRows(ctx context.Context, query core.ProjectTreeQuery) (core.ProjectTreeRows, error) GitStage(ctx context.Context, root string, paths []string) error GitClone(ctx context.Context, root, source, destination string) error CheckProjectName(context.Context, string) (core.ProjectNameProblem, error) diff --git a/desktop/internal/workbench/changelists_select.go b/desktop/internal/workbench/changelists_select.go index 388e8a71a4..b13268f6c8 100644 --- a/desktop/internal/workbench/changelists_select.go +++ b/desktop/internal/workbench/changelists_select.go @@ -1,6 +1,7 @@ package workbench import ( + "context" "strconv" "github.com/1lck/Lithe-IDEA/desktop/internal/core" @@ -27,48 +28,44 @@ func (p *project) selectedChanges() []core.GitChange { return out } -// clickChangeRow applies a click on the row of change with the modifiers it came with. +// clickChangeRow applies a click on the row of change with the modifiers it came with, as Core +// says (workspace.rowSelection.reduce over the changes in the order they show). A plain click +// drops the marks; the row a click opens is the review's business, not the selection's. func (a *App) clickChangeRow(p *project, change core.GitChange, mods gfx.Modifiers) { l := &p.lists + action := core.ClearRows() switch { case mods&ui.Primary != 0: - if l.selected == nil { - l.selected = map[string]bool{} - } - if l.selected[change.Path] { - delete(l.selected, change.Path) - } else { - l.selected[change.Path] = true - } - l.anchor = change.Path + action = core.ToggleRow(change.Path) case mods&gfx.ModifierShift != 0: - if l.selected == nil { - l.selected = map[string]bool{} - } - from := l.anchor - if from == "" { - from = change.Path - } - lo, hi := changeRowIndex(p.git.status.Changes, from), changeRowIndex(p.git.status.Changes, change.Path) - if lo > hi { - lo, hi = hi, lo - } - for i := max(lo, 0); i <= hi && i < len(p.git.status.Changes); i++ { - l.selected[p.git.status.Changes[i].Path] = true - } - default: - l.selected, l.anchor = nil, "" + action = core.ExtendRow(change.Path) } -} - -// changeRowIndex is the index of the change at path in changes, -1 when there is none. -func changeRowIndex(changes []core.GitChange, path string) int { - for i, change := range changes { - if change.Path == path { - return i + rows := make([]string, len(p.git.status.Changes)) + for i, c := range p.git.status.Changes { + rows[i] = c.Path + } + selection := core.RowSelection{Anchor: l.anchor} + for at := range l.selected { + selection.Marked = append(selection.Marked, at) + } + ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + defer cancel() + result, err := a.kernel.ReduceRowSelection(ctx, rows, selection, action) + if err != nil { + a.notifyError(a.text.Errors.Core(err.Error())) + return + } + if result.Rejection != "" { + return + } + l.selected = nil + if len(result.Selection.Marked) > 0 { + l.selected = make(map[string]bool, len(result.Selection.Marked)) + for _, at := range result.Selection.Marked { + l.selected[at] = true } } - return -1 + l.anchor = result.Selection.Anchor } // changeListBatchMenu declares the batch items of a selected change's menu: how many changes the diff --git a/desktop/internal/workbench/filetree.go b/desktop/internal/workbench/filetree.go index d8c87ae270..8319602ff8 100644 --- a/desktop/internal/workbench/filetree.go +++ b/desktop/internal/workbench/filetree.go @@ -3,7 +3,6 @@ package workbench import ( "context" "errors" - "path" "path/filepath" "github.com/1lck/Lithe-IDEA/desktop/internal/core" @@ -41,9 +40,11 @@ type fileTree struct { // selected is the node whose row is highlighted, which the arrow keys move. selected *treeNode // marked are the paths a Ctrl or Shift click selected for a batch; anchor is the path a - // Shift click extends from (filetree_batch.go). - marked map[string]bool - anchor string + // Shift click extends from, and targets what a batch acts on, as Core last said + // (filetree_batch.go). + marked map[string]bool + anchor string + targets []string // batch is the batch delete dialog, open while the user confirms it. batch treeBatchDelete // rowRefs maps the hit identity of each row the last paint declared to its node, so a drag @@ -53,11 +54,13 @@ type fileTree struct { // failed is why the root could not be listed; empty otherwise. failed string next int - // rows are the nodes the last paint showed, top to bottom; view is the Tree that shows - // them, which declares only the ones in view and scrolls sideways when the widest row is - // wider than it, by view.RowWidth. - rows []*treeNode - view ui.TreeState + // rows are the nodes the tree shows, top to bottom, as Core laid them out when the shape of + // the tree last changed, and rowsDirty says it changed since (filetree_rows.go); view is the + // Tree that shows them, which declares only the ones in view and scrolls sideways when the + // widest row is wider than it, by view.RowWidth. + rows []*treeNode + rowsDirty bool + view ui.TreeState // area is where the tree was laid out in the last paint, read by its draw hook. area gfx.Rect areaDraw func(*ui.DrawContext) @@ -65,8 +68,8 @@ type fileTree struct { focusNode *treeNode // wake asks for a paint. wake func() - // measureDirty says a row was added, removed, opened or renamed since the width of the - // widest row was measured, and measureFont the font size it was measured with. + // measureDirty says the rows were laid out again since the width of the widest row was + // measured, and measureFont the font size it was measured with. measureDirty bool measureFont float32 // pending and reading coalesce native events into one bounded Core request. @@ -138,8 +141,8 @@ func (t *fileTree) forgetNode(n *treeNode) { } } -// replaceChildren keeps the identities and loaded descendants of entries that -// still exist. Selection must never point into a subtree that has disappeared. +// replaceChildren keeps the identities and loaded descendants of entries that still exist. +// The rows are laid out again after it, which moves a selection whose node went away. func (t *fileTree) replaceChildren(parent *treeNode, entries []core.WorkspaceNode) { old := make(map[string]*treeNode, len(parent.children)) for _, child := range parent.children { @@ -173,17 +176,7 @@ func (t *fileTree) replaceChildren(parent *treeNode, entries []core.WorkspaceNod t.forgetNode(removed) } parent.children = children - if t.selected != nil && t.find(t.selected.path) != t.selected { - selectedPath := t.selected.path - t.selected = nil - for ancestor := path.Dir(selectedPath); ancestor != "." && ancestor != "/"; ancestor = path.Dir(ancestor) { - if n := t.find(ancestor); n != nil && n.dir { - t.selected = n - break - } - } - } - t.measureDirty = true + t.rowsDirty = true } // listTree asks the kernel for the children of the folders at paths, away from the window @@ -250,7 +243,7 @@ func (a *App) pumpTreeListings(p *project) { // The tree listed again, so a later failure is a new one to report. t.failureReported = false } - anchor := a.treeViewportAnchor(t) + top := treeTopPath(t) loggedFailure := t.failureReported byPath := make(map[string]core.DirectoryListing, len(listings)) for _, listing := range listings { @@ -272,7 +265,7 @@ func (a *App) pumpTreeListings(p *project) { if n == t.root { t.failed = i18n.Shared(a.language(), "desktop.project.rootUnavailable") } else if !n.listed { - n.expanded = false + n.expanded, t.rowsDirty = false, true } continue } @@ -288,11 +281,14 @@ func (a *App) pumpTreeListings(p *project) { t.failed = i18n.Shared(a.language(), "desktop.project.rootUnavailable") } else { // log-exempt: 目标已消失:目录可能已被外部删除或隐藏。 - n.expanded = false + n.expanded, t.rowsDirty = false, true } } } - a.restoreTreeViewportAnchor(t, anchor) + if t.rowsDirty { + // Rows inserted or removed above the top of the view leave the same row at its top. + a.refreshTreeRows(p, top) + } a.pruneTreeWatches(p) if t.failed == "" { for _, path := range paths { @@ -311,43 +307,6 @@ func (a *App) pumpTreeListings(p *project) { }) } -// Keep the first visible row stable when an asynchronous listing inserts or removes rows above -// it. Selection is independent of this anchor: the selected row may be outside the viewport. -func (a *App) treeViewportAnchor(t *fileTree) *treeNode { - first, last := t.view.Visible() - if first <= 0 || first > last || first+treeOverscan >= len(t.rows) { - return nil - } - return t.rows[first+treeOverscan] -} - -func (a *App) restoreTreeViewportAnchor(t *fileTree, anchor *treeNode) { - if anchor == nil || t.root == nil { - return - } - index, found := 0, false - var visit func([]*treeNode) - visit = func(nodes []*treeNode) { - for _, n := range nodes { - if found { - return - } - if n == anchor { - found = true - return - } - index++ - if n.dir && n.expanded { - visit(n.children) - } - } - } - visit([]*treeNode{t.root}) - if found { - t.view.ScrollTo(index, ui.ListStart) - } -} - // toggleFolder expands a collapsed folder, listing it the first time, and collapses an // expanded one. func (a *App) toggleFolder(p *project, n *treeNode) { @@ -356,12 +315,12 @@ func (a *App) toggleFolder(p *project, n *treeNode) { } if n.expanded { n.expanded = false - p.tree.measureDirty = true + p.tree.rowsDirty = true a.pruneTreeWatches(p) return } n.expanded = true - p.tree.measureDirty = true + p.tree.rowsDirty = true // The directory may have changed while collapsed and unobserved. a.listTree(p, n.path) } diff --git a/desktop/internal/workbench/filetree_actions.go b/desktop/internal/workbench/filetree_actions.go index 97e08a65b8..e776bb8540 100644 --- a/desktop/internal/workbench/filetree_actions.go +++ b/desktop/internal/workbench/filetree_actions.go @@ -123,7 +123,7 @@ func (a *App) stepTreeReveal(p *project) { a.giveUpTreeReveal(p, "folder_unavailable") return } - n.expanded, t.measureDirty, t.revealAsked = true, true, n + n.expanded, t.rowsDirty, t.revealAsked = true, true, n a.listTree(p, n.path) return } @@ -188,7 +188,7 @@ func (a *App) retryProjectTree(p *project) { slot.close() delete(t.watches, "") } - t.failed, t.root.listed, t.root.expanded = "", false, true + t.failed, t.root.listed, t.root.expanded, t.rowsDirty = "", false, true, true a.listTree(p, "") } @@ -225,7 +225,7 @@ func (a *App) stepTreeExpandAll(p *project) { continue } t.expandSeen[n.id] = true - n.expanded, t.measureDirty = true, true + n.expanded, t.rowsDirty = true, true ask = append(ask, n.path) } if n.listed { @@ -264,16 +264,9 @@ func (a *App) collapseProjectTree(p *project) { } } collapse(t.root) - t.measureDirty = true - if s := t.selected; s != nil && s != t.root && (s.depth > 1 || !t.root.expanded) { - shown := t.root - if t.root.expanded { - top, _, _ := strings.Cut(s.path, "/") - if n := t.find(top); n != nil { - shown = n - } - } - t.selected, t.show = shown, shown + t.rowsDirty = true + if a.refreshTreeRows(p, nil) { + t.show = t.selected } a.pruneTreeWatches(p) } diff --git a/desktop/internal/workbench/filetree_batch.go b/desktop/internal/workbench/filetree_batch.go index b619f5c096..12fda1b856 100644 --- a/desktop/internal/workbench/filetree_batch.go +++ b/desktop/internal/workbench/filetree_batch.go @@ -27,67 +27,26 @@ type treeBatchDelete struct { paths []string } -// treeModifiedClick applies a Ctrl, Cmd or Shift click on the row of n to the marked set. +// treeModifiedClick applies a Ctrl, Cmd or Shift click on the row of n to the marked set, as +// Core says (filetree_rows.go). func (a *App) treeModifiedClick(p *project, n *treeNode, mods gfx.Modifiers) { - t := &p.tree - if n == nil || n == t.root { + if n == nil { return } - if t.marked == nil { - t.marked = map[string]bool{} + action := core.ExtendRow(n.path) + if mods&ui.Primary != 0 { + action = core.ToggleRow(n.path) } - switch { - case mods&ui.Primary != 0: - if t.marked[n.path] { - delete(t.marked, n.path) - } else { - t.marked[n.path] = true - } - t.anchor = n.path - case mods&gfx.ModifierShift != 0: - from := t.anchor - if from == "" && t.selected != nil { - from = t.selected.path - } - lo, hi := treeRowIndex(t.rows, from), treeRowIndex(t.rows, n.path) - if lo < 0 || hi < 0 { - lo, hi = treeRowIndex(t.rows, n.path), treeRowIndex(t.rows, n.path) - } - if lo > hi { - lo, hi = hi, lo - } - for i := lo; i <= hi && i >= 0 && i < len(t.rows); i++ { - t.marked[t.rows[i].path] = true - } - } - t.selected = n -} - -// treeRowIndex is the index of the row whose path is at, -1 when no visible row has it. -func treeRowIndex(rows []*treeNode, at string) int { - for i, n := range rows { - if n.path == at { - return i - } - } - return -1 + a.reduceTreeSelection(p, action) } // batchTargets are the nodes a batch operation acts on: the marked rows, without those inside -// another marked folder, in path order. Without marks it is the selected row alone. +// another marked folder, in path order, as Core said. Without marks it is the selected row +// alone. func (t *fileTree) batchTargets() []*treeNode { var nodes []*treeNode - if len(t.marked) > 0 { - paths := make([]string, 0, len(t.marked)) - for at := range t.marked { - paths = append(paths, at) - } - slices.Sort(paths) - for _, at := range paths { - n := t.byPath[at] - if n == nil || n == t.root || t.insideMarked(at) { - continue - } + for _, at := range t.targets { + if n := t.byPath[at]; n != nil && n != t.root { nodes = append(nodes, n) } } @@ -97,16 +56,6 @@ func (t *fileTree) batchTargets() []*treeNode { return nodes } -// insideMarked reports that a folder above at is marked, so at is part of the batch already. -func (t *fileTree) insideMarked(at string) bool { - for m := range t.marked { - if m != at && strings.HasPrefix(at, m+"/") { - return true - } - } - return false -} - // treeBatchMenu declares the batch items of the context menu of a marked row: how many rows the // batch holds, then the operations that apply to all of them. func (a *App) treeBatchMenu(c ui.C, p *project, menu *ui.MenuItems, nodes []*treeNode) { @@ -233,7 +182,7 @@ func treeParents(nodes []*treeNode) []string { // finishBatch clears the marks, lists the directories again and reads the status. A failure is // reported once, with the last reason, since the rest of the batch still ran; failure words it. func (a *App) finishBatch(p *project, parents []string, performed string, failed int, reason error, failure func(i18n.Language, string) string) { - p.tree.marked, p.tree.anchor = nil, "" + p.tree.marked, p.tree.anchor, p.tree.targets = nil, "", nil if failed > 0 && reason != nil { a.notifyError(failure(a.language(), treeErrorReason(reason))) } diff --git a/desktop/internal/workbench/filetree_bench_test.go b/desktop/internal/workbench/filetree_bench_test.go index 92590ae2bd..3623688e62 100644 --- a/desktop/internal/workbench/filetree_bench_test.go +++ b/desktop/internal/workbench/filetree_bench_test.go @@ -17,7 +17,7 @@ func BenchmarkProjectTreeResize1000(b *testing.B) { tree := &h.app.project.tree tree.root = &treeNode{name: "project", dir: true, expanded: true, listed: true} tree.byPath = nil - tree.measureDirty = true + tree.rowsDirty = true for i := 0; i < 1000; i++ { tree.root.children = append(tree.root.children, tree.node(core.WorkspaceNode{Path: fmt.Sprintf("file-%04d.txt", i), Name: fmt.Sprintf("file-%04d.txt", i)}, 1)) } diff --git a/desktop/internal/workbench/filetree_rows.go b/desktop/internal/workbench/filetree_rows.go new file mode 100644 index 0000000000..bf4af04d6f --- /dev/null +++ b/desktop/internal/workbench/filetree_rows.go @@ -0,0 +1,120 @@ +package workbench + +import ( + "context" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/vivaui/viva/ui" +) + +// The rows of the project tree and its selection follow Core's rules (matrix id +// workspace-tree-batch-files): which loaded nodes show, where a selection goes when its node +// goes away or a closed folder hides it, and what a click with or without Cmd, Ctrl or Shift +// does to the selected row, the marked rows and the anchor. The tree keeps the nodes it listed, +// which folders are open, focus, scrolling and painting, and asks Core once per change of the +// tree's shape, never per paint. + +// refreshTreeRows has Core lay out the rows of the tree after its shape changed, keep the +// selection on a row that shows, and scroll the row named by top, the path of the row at the +// top of the view before the change, back to the top; nil leaves the scroll as it is. It +// reports whether the selection moved. When Core cannot say, the banner says why and the rows +// stay as they were. +func (a *App) refreshTreeRows(p *project, top *string) bool { + t := &p.tree + if t.root == nil { + return false + } + t.rowsDirty = false + var order []*treeNode + var nodes []core.ProjectTreeNode + var walk func(*treeNode) + walk = func(n *treeNode) { + order = append(order, n) + nodes = append(nodes, core.ProjectTreeNode{Path: n.path, Depth: n.depth, Open: n.dir && n.expanded}) + for _, child := range n.children { + walk(child) + } + } + walk(t.root) + ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + defer cancel() + result, err := a.kernel.ProjectTreeRows(ctx, core.ProjectTreeQuery{Nodes: nodes, Selection: t.selection(), Top: top}) + if err != nil { + a.notifyError(a.text.Errors.Core(err.Error())) + return false + } + t.rows = t.rows[:0] + for _, i := range result.Rows { + t.rows = append(t.rows, order[i]) + } + t.adopt(result.Selection, result.Targets) + if result.TopRow != nil { + t.view.ScrollTo(*result.TopRow, ui.ListStart) + } + t.measureDirty = true + return result.SelectionMoved +} + +// treeTopPath is the path of the row at the top of the view, and nil while the view is +// scrolled to its top, where the first row stays in view whatever comes above the others. +func treeTopPath(t *fileTree) *string { + first, last := t.view.Visible() + if first <= 0 || first > last || first+treeOverscan >= len(t.rows) { + return nil + } + return new(t.rows[first+treeOverscan].path) +} + +// reduceTreeSelection applies a click on a row, or the end of a batch, to the tree's selection +// as Core says. It reports whether the selection changed: a click on a row that went away +// changes nothing, and when Core cannot say the banner says why. +func (a *App) reduceTreeSelection(p *project, action core.RowAction) bool { + t := &p.tree + if t.rowsDirty { + a.refreshTreeRows(p, nil) + } + rows := make([]string, len(t.rows)) + for i, n := range t.rows { + rows[i] = n.path + } + ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + defer cancel() + result, err := a.kernel.ReduceRowSelection(ctx, rows, t.selection(), action) + if err != nil { + a.notifyError(a.text.Errors.Core(err.Error())) + return false + } + if result.Rejection != "" { + return false + } + t.adopt(result.Selection, result.Targets) + return true +} + +// selection is the tree's selection as Core takes it. +func (t *fileTree) selection() core.RowSelection { + s := core.RowSelection{Anchor: t.anchor} + if t.selected != nil { + s.Selected = new(t.selected.path) + } + for at := range t.marked { + s.Marked = append(s.Marked, at) + } + return s +} + +// adopt takes the selection and the batch targets Core answered. +func (t *fileTree) adopt(selection core.RowSelection, targets []string) { + t.selected = nil + if selection.Selected != nil { + t.selected = t.find(*selection.Selected) + } + t.marked = nil + if len(selection.Marked) > 0 { + t.marked = make(map[string]bool, len(selection.Marked)) + for _, at := range selection.Marked { + t.marked[at] = true + } + } + t.anchor, t.targets = selection.Anchor, targets +} diff --git a/desktop/internal/workbench/filetree_test.go b/desktop/internal/workbench/filetree_test.go index 77e72e7221..cc008fe0b5 100644 --- a/desktop/internal/workbench/filetree_test.go +++ b/desktop/internal/workbench/filetree_test.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "runtime" + "slices" "strings" "sync" "sync/atomic" @@ -389,27 +390,137 @@ func TestProjectTreeDiscardsListingSupersededByChange(t *testing.T) { } func TestProjectTreeRefreshPreservesSurvivingState(t *testing.T) { - tree := fileTree{root: &treeNode{dir: true, expanded: true}} - tree.replaceChildren(tree.root, []core.WorkspaceNode{{Path: "src", Name: "src", IsDirectory: true}}) + h := newHarness(t, &testKernel{Client: core.NewClient()}) + p := &project{} + tree := &p.tree + tree.root = &treeNode{dir: true, expanded: true} + // replace lists a folder again and lays the rows out as Core says, as a listing does. + replace := func(n *treeNode, nodes []core.WorkspaceNode) { + t.Helper() + tree.replaceChildren(n, nodes) + if !tree.rowsDirty { + t.Fatal("a listing left the rows as they were") + } + h.app.refreshTreeRows(p, nil) + } + replace(tree.root, []core.WorkspaceNode{{Path: "src", Name: "src", IsDirectory: true}}) folder := tree.root.children[0] folder.expanded, folder.listed = true, true - tree.replaceChildren(folder, []core.WorkspaceNode{{Path: "src/a.go", Name: "a.go"}}) + replace(folder, []core.WorkspaceNode{{Path: "src/a.go", Name: "a.go"}}) file := folder.children[0] tree.selected = file - tree.replaceChildren(tree.root, []core.WorkspaceNode{ + replace(tree.root, []core.WorkspaceNode{ {Path: "src", Name: "src", IsDirectory: true}, {Path: "new", Name: "new"}, }) if tree.root.children[0] != folder || !folder.expanded || !folder.listed || tree.selected != file { t.Fatal("refresh lost a surviving folder or its selected descendant") } - tree.replaceChildren(folder, nil) + replace(folder, nil) if tree.selected != folder { t.Fatal("removing the selected file did not move selection to its parent") } - tree.replaceChildren(tree.root, []core.WorkspaceNode{{Path: "src", Name: "src"}}) - if tree.root.children[0] == folder || tree.selected != nil { - t.Fatal("replacing a directory with a file retained the old subtree") + // The selection is a path: a file in place of the selected folder is the selected row now. + replace(tree.root, []core.WorkspaceNode{{Path: "src", Name: "src"}}) + if replaced := tree.root.children[0]; replaced == folder || tree.selected != replaced || len(tree.rows) != 2 { + t.Fatalf("replacing a directory with a file left %+v selected and %d rows", tree.selected, len(tree.rows)) + } + replace(tree.root, nil) + if tree.selected != tree.root { + t.Fatalf("removing the selected file selected %+v, want the root", tree.selected) + } +} + +func TestProjectTreeBatchSelectionFollowsCore(t *testing.T) { + root := t.TempDir() + writeTreeFiles(t, root, "a/x.go", "b.txt", "c.txt") + h := newHarness(t, &testKernel{Client: core.NewClient()}) + p := h.openTree(t, root) + folder := p.tree.find("a") + h.app.toggleFolder(p, folder) + awaitDocumentState(t, h, func() bool { return folder.listed && p.tree.find("a/x.go") != nil }) + h.settle() + if len(p.tree.rows) != 5 { + t.Fatalf("the open folder shows %d rows, want the root, a, a/x.go, b.txt and c.txt", len(p.tree.rows)) + } + paths := func(nodes []*treeNode) []string { + out := make([]string, len(nodes)) + for i, n := range nodes { + out[i] = n.path + } + return out + } + + h.app.treeModifiedClick(p, p.tree.root, ui.Primary) + if len(p.tree.marked) != 0 { + t.Fatal("a Cmd click marked the root") + } + h.app.treeModifiedClick(p, folder, ui.Primary) + h.app.treeModifiedClick(p, p.tree.find("b.txt"), gfx.ModifierShift) + if got := paths(p.tree.batchTargets()); !slices.Equal(got, []string{"a", "b.txt"}) { + t.Fatalf("batch targets = %v, want the marked folder standing for a/x.go, and b.txt", got) + } + if p.tree.selected != p.tree.find("b.txt") || p.tree.anchor != "a" || !p.tree.marked["a/x.go"] { + t.Fatalf("selection = %v marked %v anchor %q", p.tree.selected, p.tree.marked, p.tree.anchor) + } + + // Closing the folder keeps the marks inside it; the batch is what it was. + h.app.toggleFolder(p, folder) + h.app.invalidator.Invalidate() + h.settle() + if !p.tree.marked["a/x.go"] || len(p.tree.rows) != 4 { + t.Fatalf("closing the folder left marks %v and %d rows", p.tree.marked, len(p.tree.rows)) + } + h.app.treeModifiedClick(p, folder, ui.Primary) + if got := paths(p.tree.batchTargets()); !slices.Equal(got, []string{"a/x.go", "b.txt"}) { + t.Fatalf("unmarking the folder left targets %v", got) + } + + // A plain click drops the marks, and a batch that ends drops them too. + hit := h.treeRowHit("c.txt") + h.click(center(hit.Bounds)) + if len(p.tree.marked) != 0 || p.tree.anchor != "" || p.tree.selected != p.tree.find("c.txt") { + t.Fatalf("a plain click left marks %v anchor %q selected %v", p.tree.marked, p.tree.anchor, p.tree.selected) + } + if got := paths(p.tree.batchTargets()); !slices.Equal(got, []string{"c.txt"}) { + t.Fatalf("without marks the batch is %v, want the selected row", got) + } + h.app.treeModifiedClick(p, p.tree.find("b.txt"), ui.Primary) + h.app.finishBatch(p, nil, "workspace.file.trashBatch", 0, nil, nil) + if len(p.tree.marked) != 0 || len(p.tree.targets) != 0 { + t.Fatalf("the end of a batch left marks %v targets %v", p.tree.marked, p.tree.targets) + } +} + +func TestChangeListRowSelectionFollowsCore(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + p := &project{} + p.git.status.Changes = []core.GitChange{{Path: "a.go"}, {Path: "b.go"}, {Path: "c.go"}, {Path: "new/"}} + click := func(at int, mods gfx.Modifiers) { h.app.clickChangeRow(p, p.git.status.Changes[at], mods) } + selected := func() []string { + var out []string + for _, change := range p.selectedChanges() { + out = append(out, change.Path) + } + return out + } + + click(2, gfx.ModifierShift) + if got := selected(); !slices.Equal(got, []string{"c.go"}) || p.lists.anchor != "" { + t.Fatalf("a Shift click without an anchor selected %v anchor %q, want c.go alone", got, p.lists.anchor) + } + click(0, ui.Primary) + click(3, gfx.ModifierShift) + if got := selected(); !slices.Equal(got, []string{"a.go", "b.go", "c.go", "new/"}) || p.lists.anchor != "a.go" { + t.Fatalf("a Shift click from a.go selected %v anchor %q", got, p.lists.anchor) + } + click(1, ui.Primary) + if got := selected(); !slices.Equal(got, []string{"a.go", "c.go", "new/"}) || p.lists.anchor != "b.go" { + t.Fatalf("a Cmd click on a selected change left %v anchor %q", got, p.lists.anchor) + } + click(0, 0) + if len(p.lists.selected) != 0 || p.lists.anchor != "" { + t.Fatalf("a plain click left %v anchor %q", p.lists.selected, p.lists.anchor) } } diff --git a/desktop/internal/workbench/filetree_view.go b/desktop/internal/workbench/filetree_view.go index beb1ffdac2..50ee044f5b 100644 --- a/desktop/internal/workbench/filetree_view.go +++ b/desktop/internal/workbench/filetree_view.go @@ -1,6 +1,7 @@ package workbench import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/fileicons" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/shortcuts" @@ -51,7 +52,7 @@ func (a *App) projectTree(c ui.C, p *project) { } if t.root == nil { t.root = &treeNode{name: p.name, dir: true, expanded: true} - t.measureDirty = true + t.rowsDirty = true a.listTree(p, "") } switch { @@ -67,19 +68,12 @@ func (a *App) projectTree(c ui.C, p *project) { a.panelMessage(c, a.text.Project.Loading, a.colors.Subtle) return } - // Flatten the already loaded rows; the Tree declares only the viewport and a little - // beyond it. Expanding a folder never enumerates its unexpanded descendants. - t.rows = t.rows[:0] - var collect func([]*treeNode) - collect = func(nodes []*treeNode) { - for _, n := range nodes { - t.rows = append(t.rows, n) - if n.dir && n.expanded { - collect(n.children) - } - } + // Core lays the loaded rows out again only after the shape of the tree changed; the Tree + // declares only the viewport and a little beyond it, and opening a folder never enumerates + // what is under it. + if t.rowsDirty { + a.refreshTreeRows(p, nil) } - collect([]*treeNode{t.root}) a.syncTreeSelection(c.Canvas(), t) t.view.RowWidth = a.measureTree(c.Canvas(), t) // Names are never cut short: the rows are as wide as the widest one, and the tree @@ -131,9 +125,10 @@ func (a *App) projectTree(c ui.C, p *project) { c.After(func() { a.treeModifiedClick(p, n, mods) }) } else { c.After(func() { - t.selected = n - if clicked { - t.marked, t.anchor = nil, "" + if !clicked { + t.selected = n + } else if !a.reduceTreeSelection(p, core.ChooseRow(n.path)) { + return } switch { case !n.dir: From 55cd13ed1c8c6840cb63ce7fb3e9075ebd6a440a Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 09:48:26 +0800 Subject: [PATCH 09/11] =?UTF-8?q?refactor(desktop):=20=E6=8A=8A=20AI=20?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=8A=BD=E6=88=90=E7=8B=AC=E7=AB=8B=E5=8C=85?= =?UTF-8?q?=20internal/ai?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新包 desktop/internal/ai 与 Core 的 lithe-ai crate 对应:Core AI 命令 (ai.configuration.*、ai.planCommit、ai.decodeCommitMessage、ai.inlineEdit.*、 ai.pullRequest.*)以及 git.commitMessageContext 的封装,Codex/Claude 服务商 发现与凭据定位,HTTP 请求(45 秒、不跟随重定向、2 MiB 上限),提交信息、 行内编辑、PR 描述三条生成流程。 - desktop/internal/core 删除 ai_generation.go、ai_configuration.go、 ai_pull_request.go,只保留 IDE API(IDEHostControl 并入 ide_host.go)。 - workbench 删除 ai_provider.go、aicommit_http.go 和 AIKernel/CoreAIKernel, 只保留界面状态与本地化错误文案,Options.AIKernel 改为 ai.Kernel。 - 测试随代码迁到 internal/ai;去掉没有调用方的 AICommitInputBudget 封装。 - 功能矩阵三条 AI 能力、Agent 对话删除 Note、viva-migration 改到新路径。 --- ...6-11-12-viva-agent-conversation-removed.md | 10 +- desktop/internal/ai/ai_test.go | 52 ++++ desktop/internal/ai/client.go | 42 +++ .../commands_test.go} | 51 ++-- desktop/internal/ai/commit.go | 216 ++++++++++++++ desktop/internal/ai/commit_test.go | 11 + desktop/internal/ai/configuration.go | 81 ++++++ .../configuration_test.go} | 33 +-- desktop/internal/ai/http.go | 95 ++++++ desktop/internal/ai/http_test.go | 97 +++++++ desktop/internal/ai/inline_edit.go | 134 +++++++++ desktop/internal/ai/inline_edit_test.go | 19 ++ desktop/internal/ai/provider.go | 271 ++++++++++++++++++ desktop/internal/ai/provider_test.go | 105 +++++++ desktop/internal/ai/pull_request.go | 86 ++++++ desktop/internal/core/ai_configuration.go | 86 ------ desktop/internal/core/ai_generation.go | 237 --------------- desktop/internal/core/ai_pull_request.go | 61 ---- desktop/internal/core/doc.go | 4 +- desktop/internal/core/ide_host.go | 12 + desktop/internal/workbench/ai_generation.go | 43 +-- .../internal/workbench/ai_generation_test.go | 17 -- desktop/internal/workbench/ai_provider.go | 240 ---------------- .../internal/workbench/ai_provider_test.go | 84 ------ desktop/internal/workbench/aicommit.go | 153 ++-------- desktop/internal/workbench/aicommit_http.go | 90 ------ desktop/internal/workbench/aicommit_test.go | 124 -------- desktop/internal/workbench/app.go | 14 +- desktop/internal/workbench/github_create.go | 43 +-- desktop/internal/workbench/inlinediff_test.go | 14 - desktop/internal/workbench/inlineedit.go | 92 +----- desktop/internal/workbench/startup.go | 3 +- docs/viva-migration.md | 2 +- .../features/ai-commit-generation.json | 28 +- .../features/ai-inline-edit.json | 12 +- .../features/ai-pull-request-description.json | 6 +- 36 files changed, 1365 insertions(+), 1303 deletions(-) create mode 100644 desktop/internal/ai/ai_test.go create mode 100644 desktop/internal/ai/client.go rename desktop/internal/{core/ai_generation_test.go => ai/commands_test.go} (53%) create mode 100644 desktop/internal/ai/commit.go create mode 100644 desktop/internal/ai/commit_test.go create mode 100644 desktop/internal/ai/configuration.go rename desktop/internal/{core/ai_configuration_test.go => ai/configuration_test.go} (83%) create mode 100644 desktop/internal/ai/http.go create mode 100644 desktop/internal/ai/http_test.go create mode 100644 desktop/internal/ai/inline_edit.go create mode 100644 desktop/internal/ai/inline_edit_test.go create mode 100644 desktop/internal/ai/provider.go create mode 100644 desktop/internal/ai/provider_test.go create mode 100644 desktop/internal/ai/pull_request.go delete mode 100644 desktop/internal/core/ai_configuration.go delete mode 100644 desktop/internal/core/ai_generation.go delete mode 100644 desktop/internal/core/ai_pull_request.go delete mode 100644 desktop/internal/workbench/ai_provider.go delete mode 100644 desktop/internal/workbench/ai_provider_test.go delete mode 100644 desktop/internal/workbench/aicommit_http.go delete mode 100644 desktop/internal/workbench/aicommit_test.go diff --git a/.agents/notes/implemented/feature/2026-11-12-viva-agent-conversation-removed.md b/.agents/notes/implemented/feature/2026-11-12-viva-agent-conversation-removed.md index e45a71380d..a09066802d 100644 --- a/.agents/notes/implemented/feature/2026-11-12-viva-agent-conversation-removed.md +++ b/.agents/notes/implemented/feature/2026-11-12-viva-agent-conversation-removed.md @@ -8,7 +8,7 @@ 第二轮清理把当时只标为“放弃”的记录也删掉了:功能矩阵里对应的 36 个条目、`shared/i18n/` 里全部 593 条含 `agent` 的词条,以及旧客户端 Agent 对话的 15 篇 Note。原因是旧 SwiftUI 与 Tauri 客户端目录已经在本分支整体删除,那些词条、能力和笔记不再有任何消费者;留在 `implemented/` 和矩阵里会让后来的人以为功能仍存在。 -保留 AI 提交信息生成、编辑器行内 AI 编辑和创建 PR 时的 AI 描述。三者共用的 Codex/Claude provider 发现搬到 `desktop/internal/workbench/ai_provider.go`,只调用 Core 的 `ai.configuration.sources` 和 `ai.configuration.parse`,不再经过 Agent 状态。设置窗口的 AI 分组只剩“生成”和“IDE 连接”两页。 +保留 AI 提交信息生成、编辑器行内 AI 编辑和创建 PR 时的 AI 描述。三者共用的 Codex/Claude provider 发现只调用 Core 的 `ai.configuration.sources` 和 `ai.configuration.parse`,不再经过 Agent 状态。2026-11-14 起,provider 发现、Core AI 命令的封装、HTTP 请求和三条生成流程都放在独立的 Go 包 `desktop/internal/ai`,与 Core 的 `lithe-ai` crate 对应,以后由用户团队单独维护;`desktop/internal/core` 不再含 AI 代码,`desktop/internal/workbench` 只保留界面状态和本地化的错误文案。设置窗口的 AI 分组只剩“生成”和“IDE 连接”两页。 Rust Core 的 Agent 宿主(`lithe-agent-host` 和 C ABI 里的 Agent 入口)以及 `shared/fixtures/agent/`、`shared/contracts/agent-turn-policy.json` 保持不变:它们属于 Core 的兼容面,删除要单独的 Core PR 并提升 `PINNED_CORE_REVISION`。桌面端不再调用它们。 @@ -25,7 +25,7 @@ Agent 对话是迁移中剩余最大的一块:旧客户端的历史、订阅 ## 决策 - **删除范围。** 桌面端删除 `desktop/internal/workbench/agent*.go`、`settings_mcp.go`、`desktop/internal/core/agent*.go`、`mcp.go`、`desktop/internal/agentbrand/`、`desktop/internal/mcpconfig/`、`desktop/internal/settingswindow/` 里的 Agent/MCP/技能/Hooks 页面,以及 `desktop/internal/i18n/` 中只给这些界面用的消息。快捷键表删除“新建 Agent 对话”和 Agent 分组。工具窗口布局里原来放助手的位置不再有占位。 -- **保留的 provider 发现只走 Core 的配置解析。** `discoverAIProviders` 先向 Core 要该来源的本机配置文件,再把文件文本交给 Core 解析;Go 只按 Core 返回的凭据定位器读取同一份 JSON 文本或进程环境。Key 只在内存里,不写设置、日志或错误信息。Codex `config.toml` 的内联 `experimental_bearer_token` 需要 TOML 路径解析,仍报“不支持”,不为这一条路径在 Go 里再写一份配置解析器。 +- **保留的 provider 发现只走 Core 的配置解析。** `ai.Discover` 先向 Core 要该来源的本机配置文件,再把文件文本交给 Core 解析;Go 只按 Core 返回的凭据定位器读取同一份 JSON 文本或进程环境。Key 只在内存里,不写设置、日志或错误信息。Codex `config.toml` 的内联 `experimental_bearer_token` 需要 TOML 路径解析,仍报“不支持”,不为这一条路径在 Go 里再写一份配置解析器。 - **生成选项归 AI 分组的“生成”页。** 原 Agent 设置里的生成来源、输出语言和自定义指令移到 `pageAIGeneration`(`desktop/internal/settingswindow/ai_generation*.go`);设置文件里的 `aiGeneration` 字段不变,已保存的选择继续生效。设置文件中原有的 `agentContextLimits`、`customAgents` 等 Agent 字段读取时忽略。AI 分组在 `desktop/internal/settingswindow/model.go` 的 `parents` 表里只声明“生成”和“IDE 连接”;以后新增 AI 页面仍只加进这个分组。 - **文案最终全删。** 第一轮只删掉被桌面端 Agent 界面用到的 474 条词条,剩下的 490 条因为与旧客户端共享,只去掉 `desktop` 平台并留给“旧客户端历史代码和其他平台”。旧客户端目录随后在本分支整体删除,这条理由不再成立,第二轮把两批合成一回:`shared/i18n/` 里 593 条含 `agent` 的词条全部删除。`native.sSHAgent` 与 `native.automaticTriesYourSSHAgentAndKeysFirst…` 属于 SSH agent,不是 Agent 对话,保留。 - **唯一还在用的文案改用通用词条。** `agent.state.cancel` 一直被 Git 提交、分支、日志窗口和设置窗口当作通用的“取消”按钮文案使用,第二轮把它换成 `ui.cancel`,并给 `ui.cancel` 补上 `desktop` 平台;此后桌面端没有任何 `agent.*` 词条引用。 @@ -52,7 +52,7 @@ Agent 对话是迁移中剩余最大的一块:旧客户端的历史、订阅 ## 验证 - `scripts/desktop/desktop-go.sh build ./...`、`scripts/desktop/desktop-go.sh vet ./internal/... ./cmd/...`:删除后桌面端编译、静态检查通过(在 `desktop/` 下运行)。 -- `scripts/desktop/desktop-go.sh test ./internal/workbench/ ./internal/settingswindow/ ./internal/core/ ./internal/shortcuts/ ./internal/i18n/ -count=1`:provider 发现用真实 Core 解析写入的配置文件、凭据定位器、AI 生成选项页、设置侧栏分组与搜索、工具窗口拖放和信号处理回归。 +- `scripts/desktop/desktop-go.sh test ./internal/ai/ ./internal/workbench/ ./internal/settingswindow/ ./internal/core/ ./internal/shortcuts/ ./internal/i18n/ -count=1`:provider 发现用真实 Core 解析写入的配置文件、凭据定位器、AI 生成选项页、设置侧栏分组与搜索、工具窗口拖放和信号处理回归。 - `node scripts/i18n/generate-i18n.mjs --check`、`node scripts/i18n/verify-app-language-localization.mjs`、`node --test --test-timeout=60000 scripts/i18n/test-i18n.mjs`:删到 11 067 条词条后生成结果一致、中英覆盖完整、界面文案仍全部走 i18n。 - `scripts/platform-feature-matrix/verify-platform-feature-matrix.sh`:删除 36 个条目后 219 条能力校验通过。 - `scripts/platform-feature-matrix/verify-platform-feature-matrix-change.sh <改动后快照>`:能力记录确有实质变更,门禁不要求 `matrix-exempt`。 @@ -60,13 +60,11 @@ Agent 对话是迁移中剩余最大的一块:旧客户端的历史、订阅 ## 适用范围 -- `desktop/internal/workbench/ai_provider.go` -- `desktop/internal/workbench/ai_provider_test.go` +- `desktop/internal/ai/` - `desktop/internal/workbench/ai_generation.go` - `desktop/internal/settingswindow/ai_generation.go` - `desktop/internal/settingswindow/ai_generation_view.go` - `desktop/internal/settingswindow/model.go` -- `desktop/internal/core/ai_configuration.go` - `desktop/internal/core/signal_guard_darwin_test.go` - `desktop/internal/i18n/` - `shared/i18n/messages.json` diff --git a/desktop/internal/ai/ai_test.go b/desktop/internal/ai/ai_test.go new file mode 100644 index 0000000000..bee7193f66 --- /dev/null +++ b/desktop/internal/ai/ai_test.go @@ -0,0 +1,52 @@ +package ai + +import ( + "context" + "encoding/json" + "errors" + "os" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// testDeadline bounds every wait in these tests, so a stuck kernel call fails the test with a +// diagnostic instead of waiting for the test binary's global timeout. +const testDeadline = 30 * time.Second + +// testContext returns a context that ends after testDeadline and is released with the test. +func testContext(t *testing.T) context.Context { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), testDeadline) + t.Cleanup(cancel) + return ctx +} + +// testClient is an AI client over the linked Core. +func testClient() *Client { return NewClient(core.NewClient()) } + +// requireCode fails the test unless err is a Core error with the code want. +func requireCode(t *testing.T, err error, want core.ErrorCode) { + t.Helper() + var coreErr *core.Error + if !errors.As(err, &coreErr) { + t.Fatalf("error = %v (%T), want *core.Error with code %q", err, err, want) + } + if coreErr.Code != want { + t.Fatalf("error code = %q, want %q (error: %v)", coreErr.Code, want, coreErr) + } +} + +// readCoreFixtureJSON decodes a fixture under rust/fixtures of the linked Core checkout. +func readCoreFixtureJSON(t *testing.T, path string, value any) { + t.Helper() + data, err := os.ReadFile(contractfixture.CoreFixture(path)) + if err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(data, value); err != nil { + t.Fatal(err) + } +} diff --git a/desktop/internal/ai/client.go b/desktop/internal/ai/client.go new file mode 100644 index 0000000000..182f861e20 --- /dev/null +++ b/desktop/internal/ai/client.go @@ -0,0 +1,42 @@ +// Package ai is the desktop side of Lithe's AI generation: the commit message (matrix id +// ai-commit-generation), the editor's inline edit (ai-inline-edit) and the pull request +// description draft. It mirrors Core's lithe-ai crate. Core names and parses the user's own +// Codex or Claude configuration, captures the commit evidence, plans every provider request and +// decodes every answer; this package reads the files Core names, resolves the credential +// locator, makes the HTTP call and runs each generation from the first call to the last. +// +// Windows keep their own state, words and painting and call in here; nothing in this package +// draws, notifies or knows about a project. A key stays in memory: it is never logged, +// persisted or sent to Core. +package ai + +import ( + "context" + "encoding/json" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// Kernel is what the AI features ask Core. *Client implements it; a test can embed a *Client +// and replace one call. +type Kernel interface { + ConfigurationSources(ctx context.Context, source, home string, environment map[string]string) ([]ConfigurationFile, error) + ParseConfiguration(ctx context.Context, request ConfigurationParseRequest) (*Configuration, error) + CommitContext(ctx context.Context, mode string, repositories []ContextRepository, maximumDiffCharacters int) (Evidence, error) + CommitContextIsCurrent(ctx context.Context, mode string, repositories []ContextRepository, token string) (bool, error) + PlanCommit(ctx context.Context, provider PlanProvider, options CommitOptions, files []EvidenceFile) (HTTPRequest, error) + DecodeCommitMessage(ctx context.Context, protocol string, response json.RawMessage, includeBody bool) (string, error) + PlanInlineEdit(ctx context.Context, provider InlineEditProvider, model InlineEditModel, edit InlineEdit) (InlineEditPlan, error) + DecodeInlineEdit(ctx context.Context, wireProtocol string, response json.RawMessage) (string, error) + PlanPullRequest(ctx context.Context, provider PlanProvider, options PullRequestOptions, comparison PullRequestComparison) (HTTPRequest, error) + DecodePullRequest(ctx context.Context, protocol string, response json.RawMessage) (title, description string, err error) +} + +// Client sends the AI commands over the Core client. Every call is read-only, may block, and +// runs off the window thread. +type Client struct{ core *core.Client } + +// NewClient is the AI client of one Core client. +func NewClient(c *core.Client) *Client { return &Client{core: c} } + +var _ Kernel = (*Client)(nil) diff --git a/desktop/internal/core/ai_generation_test.go b/desktop/internal/ai/commands_test.go similarity index 53% rename from desktop/internal/core/ai_generation_test.go rename to desktop/internal/ai/commands_test.go index 1993a0c3ad..dafdba893b 100644 --- a/desktop/internal/core/ai_generation_test.go +++ b/desktop/internal/ai/commands_test.go @@ -1,31 +1,16 @@ -package core +package ai import ( "encoding/json" - "os" "strings" "testing" - - "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" ) -// readCoreFixtureJSON decodes a fixture under rust/fixtures of the linked Core checkout. -func readCoreFixtureJSON(t *testing.T, path string, value any) { - t.Helper() - data, err := os.ReadFile(contractfixture.CoreFixture(path)) - if err != nil { - t.Fatal(err) - } - if err := json.Unmarshal(data, value); err != nil { - t.Fatal(err) - } -} - -func TestAICommitFixture(t *testing.T) { +func TestCommitFixture(t *testing.T) { var fixture struct { - Provider AICommitProvider `json:"provider"` - Options AICommitOptions `json:"options"` - Files []AICommitFile `json:"files"` + Provider PlanProvider `json:"provider"` + Options CommitOptions `json:"options"` + Files []EvidenceFile `json:"files"` Responses []struct { Protocol string `json:"protocol"` Body json.RawMessage `json:"body"` @@ -33,12 +18,12 @@ func TestAICommitFixture(t *testing.T) { ExpectedMessage string `json:"expectedMessage"` } readCoreFixtureJSON(t, "ai/commit-generation-v1.json", &fixture) - client := NewClient() + client := testClient() for i := range fixture.Files { n := len([]rune(fixture.Files[i].Diff)) fixture.Files[i].OriginalCharacters = &n } - request, err := client.AIPlanCommit(testContext(t), fixture.Provider, fixture.Options, fixture.Files) + request, err := client.PlanCommit(testContext(t), fixture.Provider, fixture.Options, fixture.Files) if err != nil { t.Fatal(err) } @@ -46,24 +31,20 @@ func TestAICommitFixture(t *testing.T) { t.Fatalf("request = %s %s", request.URL, request.Body) } for _, response := range fixture.Responses { - message, err := client.AIDecodeCommitMessage(testContext(t), response.Protocol, response.Body, false) + message, err := client.DecodeCommitMessage(testContext(t), response.Protocol, response.Body, false) if err != nil || message != fixture.ExpectedMessage { t.Fatalf("%s decoded %q %v", response.Protocol, message, err) } } - budget, err := client.AICommitInputBudget(testContext(t), 8000, []int{100, 50000}) - if err != nil || len(budget) != 2 || budget[0].Truncated || !budget[1].Truncated { - t.Fatalf("budget = %#v %v", budget, err) - } } -func TestAIInlineEditFixture(t *testing.T) { +func TestInlineEditFixture(t *testing.T) { var fixture struct { - Edit AIInlineEdit `json:"edit"` + Edit InlineEdit `json:"edit"` Plans []struct { - Case string `json:"case"` - Provider AIInlineEditProvider `json:"provider"` - Model AIInlineEditModel `json:"model"` + Case string `json:"case"` + Provider InlineEditProvider `json:"provider"` + Model InlineEditModel `json:"model"` Expected struct { URL string `json:"url"` Credential struct { @@ -75,13 +56,13 @@ func TestAIInlineEditFixture(t *testing.T) { } `json:"plans"` } readCoreFixtureJSON(t, "ai/inline-edit-v1.json", &fixture) - client := NewClient() + client := testClient() checked := 0 for _, item := range fixture.Plans { if item.Expected.URL == "" { continue } - plan, err := client.AIInlineEditPlan(testContext(t), item.Provider, item.Model, fixture.Edit) + plan, err := client.PlanInlineEdit(testContext(t), item.Provider, item.Model, fixture.Edit) if err != nil { t.Fatalf("%s: %v", item.Case, err) } @@ -94,7 +75,7 @@ func TestAIInlineEditFixture(t *testing.T) { if checked == 0 { t.Fatal("no plan checked") } - text, err := client.AIInlineEditDecode(testContext(t), "chatCompletions", json.RawMessage(`{"choices":[{"message":{"content":"`+"```go\\nx := 1\\n```"+`"}}]}`)) + text, err := client.DecodeInlineEdit(testContext(t), "chatCompletions", json.RawMessage(`{"choices":[{"message":{"content":"`+"```go\\nx := 1\\n```"+`"}}]}`)) if err != nil || text != "x := 1" { t.Fatalf("decoded %q %v", text, err) } diff --git a/desktop/internal/ai/commit.go b/desktop/internal/ai/commit.go new file mode 100644 index 0000000000..4bf8867c19 --- /dev/null +++ b/desktop/internal/ai/commit.go @@ -0,0 +1,216 @@ +package ai + +import ( + "context" + "encoding/json" + "errors" +) + +// The commit message generation: Core captures the evidence of the staged changes +// (git.commitMessageContext), plans the request (ai.planCommit) and decodes the answer +// (ai.decodeCommitMessage). A generation never stages, commits or pushes: its result is a +// draft, and it is checked against the Git state again before it replaces typed text. + +// PlanProvider is the credential-free provider description Core plans a commit or pull request +// request for. Credentials never cross the Core boundary. +type PlanProvider struct { + ID string `json:"id"` + Name string `json:"name"` + Endpoint string `json:"endpoint"` + Model string `json:"model"` + APIProtocol string `json:"apiProtocol"` + Authentication string `json:"authentication"` + Source string `json:"source"` + RequiresAPIKey bool `json:"requiresApiKey"` + AllowsInsecureHTTP bool `json:"allowsInsecureHttp"` + ChatTokenLimitField string `json:"chatTokenLimitField,omitempty"` +} + +// CommitOptions are the user choices of one commit message generation. +type CommitOptions struct { + Language string `json:"language"` + Format string `json:"format"` + CustomInstructions string `json:"customInstructions"` + IncludeBody bool `json:"includeBody"` + SubjectMaximumLength int `json:"subjectMaximumLength"` + MaximumDiffCharacters int `json:"maximumDiffCharacters"` + ReasoningEffort string `json:"reasoningEffort"` +} + +// NewCommitOptions are the options of a generation in language (english or simplifiedChinese), +// with or without a body and with the user's instructions, and the shared defaults of the +// contract for the rest. +func NewCommitOptions(language string, includeBody bool, instructions string) CommitOptions { + return CommitOptions{ + Language: language, Format: "conventional", SubjectMaximumLength: 72, + MaximumDiffCharacters: 32000, ReasoningEffort: "default", IncludeBody: includeBody, + CustomInstructions: instructions, + } +} + +// EvidenceFile is one file of commit evidence. OriginalCharacters is the untruncated diff +// length git.commitMessageContext reported. The planner expects it on every file, with Diff +// already cut to the budget. +type EvidenceFile struct { + Path string `json:"path"` + ChangeKind string `json:"changeKind"` + Diff string `json:"diff"` + OriginalCharacters *int `json:"originalCharacters,omitempty"` +} + +// HTTPRequest is a credential-free provider request. The host attaches the authentication +// headers and performs the HTTP call. +type HTTPRequest struct { + URL string `json:"url"` + Body json.RawMessage `json:"body"` +} + +// ContextFile is a selected file of git.commitMessageContext. +type ContextFile struct { + Path string `json:"path"` + OriginalPath string `json:"originalPath,omitempty"` + ChangeKind string `json:"changeKind"` +} + +// ContextRepository is one repository and its selected files. +type ContextRepository struct { + Root string `json:"root"` + Files []ContextFile `json:"files"` +} + +// Evidence is the bounded evidence captured for a generation and the token that says which Git +// state it was captured from. +type Evidence struct { + Files []EvidenceFile + Token string +} + +// StagedChangeKind names the index side of a porcelain status for git.commitMessageContext. +func StagedChangeKind(status string) string { + if status == "" { + return "modified" + } + switch status[0] { + case 'A': + return "added" + case 'D': + return "deleted" + case 'R': + return "renamed" + case 'C': + return "copied" + case 'U': + return "unmerged" + } + return "modified" +} + +type contextRequest struct { + Action string `json:"action"` + Mode string `json:"mode"` + Repositories []ContextRepository `json:"repositories"` + MaximumDiffCharacters int `json:"maximumDiffCharacters,omitempty"` + Token string `json:"token,omitempty"` +} + +// CommitContext captures the evidence without modifying the index (git.commitMessageContext). +// mode is staged or worktree and must match the commit operation. It runs Git. +func (c *Client) CommitContext(ctx context.Context, mode string, repositories []ContextRepository, maximumDiffCharacters int) (Evidence, error) { + var raw struct { + Files []struct { + Path string `json:"path"` + ChangeKind string `json:"changeKind"` + Diff string `json:"diff"` + OriginalCharacters int `json:"originalCharacters"` + } `json:"files"` + Token string `json:"token"` + } + err := c.core.Execute(ctx, "git.commitMessageContext", contextRequest{ + Action: "capture", Mode: mode, Repositories: repositories, MaximumDiffCharacters: maximumDiffCharacters, + }, &raw) + out := Evidence{Token: raw.Token} + for _, f := range raw.Files { + n := f.OriginalCharacters + out.Files = append(out.Files, EvidenceFile{Path: f.Path, ChangeKind: f.ChangeKind, Diff: f.Diff, OriginalCharacters: &n}) + } + return out, err +} + +// CommitContextIsCurrent checks the evidence token against the current Git state. Generated +// text applies only when it returns true. +func (c *Client) CommitContextIsCurrent(ctx context.Context, mode string, repositories []ContextRepository, token string) (bool, error) { + var result struct { + IsCurrent bool `json:"isCurrent"` + } + err := c.core.Execute(ctx, "git.commitMessageContext", contextRequest{ + Action: "check", Mode: mode, Repositories: repositories, Token: token, + }, &result) + return result.IsCurrent, err +} + +// PlanCommit builds the provider request for a commit message (ai.planCommit). +func (c *Client) PlanCommit(ctx context.Context, provider PlanProvider, options CommitOptions, files []EvidenceFile) (HTTPRequest, error) { + var result HTTPRequest + err := c.core.Execute(ctx, "ai.planCommit", struct { + Provider PlanProvider `json:"provider"` + Options CommitOptions `json:"options"` + Files []EvidenceFile `json:"files"` + }{provider, options, files}, &result) + return result, err +} + +// DecodeCommitMessage extracts the message from a provider answer (ai.decodeCommitMessage). +// Answers over 2 MiB are refused before it is called. +func (c *Client) DecodeCommitMessage(ctx context.Context, protocol string, response json.RawMessage, includeBody bool) (string, error) { + var result struct { + Message string `json:"message"` + } + err := c.core.Execute(ctx, "ai.decodeCommitMessage", struct { + Protocol string `json:"protocol"` + Response json.RawMessage `json:"response"` + IncludeBody bool `json:"includeBody"` + }{protocol, response, includeBody}, &result) + return result.Message, err +} + +// ErrStale reports that the staged changes moved while the message was generated. +var ErrStale = errors.New("staged changes changed") + +// GenerateCommitMessage generates a message for the staged files of repositories with the +// first usable provider of sources: it captures the evidence, plans and sends the request, +// decodes the answer and checks that the staged changes did not move meanwhile. It returns the +// message and the evidence token the caller checks again before the message replaces typed +// text. +func GenerateCommitMessage(ctx context.Context, k Kernel, repositories []ContextRepository, options CommitOptions, sources []string) (message, token string, err error) { + provider, err := Choose(ctx, k, sources) + if err != nil { + return "", "", err + } + evidence, err := k.CommitContext(ctx, "staged", repositories, options.MaximumDiffCharacters) + if err != nil { + return "", "", err + } + plan, err := k.PlanCommit(ctx, provider.plan(), options, evidence.Files) + if err != nil { + return "", "", err + } + answer, err := post(ctx, plan.URL, headers(provider.Protocol, provider.Authentication, provider.APIKey), plan.Body) + if err != nil { + return "", "", err + } + if !json.Valid(answer) { + return "", "", errors.New("AI_COMMIT_INVALID_RESPONSE") + } + message, err = k.DecodeCommitMessage(ctx, provider.Protocol, answer, options.IncludeBody) + if err != nil { + return "", "", err + } + current, err := k.CommitContextIsCurrent(ctx, "staged", repositories, evidence.Token) + if err != nil { + return "", "", err + } + if !current { + return "", "", ErrStale + } + return message, evidence.Token, nil +} diff --git a/desktop/internal/ai/commit_test.go b/desktop/internal/ai/commit_test.go new file mode 100644 index 0000000000..8853be2309 --- /dev/null +++ b/desktop/internal/ai/commit_test.go @@ -0,0 +1,11 @@ +package ai + +import "testing" + +func TestStagedChangeKindUsesTheIndexSide(t *testing.T) { + for status, want := range map[string]string{"A ": "added", "M ": "modified", "MM": "modified", "D ": "deleted", "R ": "renamed", "C ": "copied", "UU": "unmerged", "": "modified"} { + if got := StagedChangeKind(status); got != want { + t.Errorf("%q = %q, want %q", status, got, want) + } + } +} diff --git a/desktop/internal/ai/configuration.go b/desktop/internal/ai/configuration.go new file mode 100644 index 0000000000..b2ff154846 --- /dev/null +++ b/desktop/internal/ai/configuration.go @@ -0,0 +1,81 @@ +package ai + +import "context" + +// ConfigurationFile is one native file Core asks the platform to read for an AI CLI +// configuration source. File is the key the text is passed back under. +type ConfigurationFile struct { + File string `json:"file"` + Path string `json:"path"` +} + +// ConfigurationProvider is the credential-free provider metadata parsed from a local Codex or +// Claude configuration. APIProtocol is responses, chatCompletions or anthropicMessages; +// Authentication is bearer or apiKey. +type ConfigurationProvider struct { + ID string `json:"id"` + Name string `json:"name"` + Endpoint string `json:"endpoint"` + Model string `json:"model"` + APIProtocol string `json:"apiProtocol"` + Authentication string `json:"authentication"` + Source string `json:"source"` + RequiresAPIKey bool `json:"requiresApiKey"` +} + +// ConfigurationCredential locates the credential in the same files or environment that were +// passed to the parser. The value itself never crosses the Core boundary. +type ConfigurationCredential struct { + Kind string `json:"kind"` + Name string `json:"name,omitempty"` + File string `json:"file,omitempty"` + Path []string `json:"path,omitempty"` +} + +// Configuration is Core's parse result. A nil value from ParseConfiguration means nothing is +// configured. Provider is nil when the configuration parsed but is not a usable provider; Issue +// then names the stable reason code. +type Configuration struct { + Model string `json:"model"` + Provider *ConfigurationProvider `json:"provider"` + Issue *string `json:"issue"` + ReasoningEffort *string `json:"reasoningEffort"` + HasCredential bool `json:"hasCredential"` + Credential *ConfigurationCredential `json:"credential"` + UnsupportedAuthentication bool `json:"unsupportedAuthentication"` +} + +// ConfigurationParseRequest is the payload of ai.configuration.parse. Files is keyed like +// ConfigurationFile.File: config, auth, settings, credentials and root. Environment is the +// process snapshot the credential locator is resolved against; it is not returned or logged. +type ConfigurationParseRequest struct { + Source string `json:"source"` + Files map[string]string `json:"files,omitempty"` + Environment map[string]string `json:"environment,omitempty"` + AllowIncomplete bool `json:"allowIncomplete,omitempty"` +} + +// ConfigurationSources names the native files of one AI CLI source (ai.configuration.sources). +// Core decides the paths; the platform only reads them. +func (c *Client) ConfigurationSources(ctx context.Context, source, home string, environment map[string]string) ([]ConfigurationFile, error) { + var result struct { + Files []ConfigurationFile `json:"files"` + } + err := c.core.Execute(ctx, "ai.configuration.sources", struct { + Source string `json:"source"` + Home string `json:"home"` + Environment map[string]string `json:"environment,omitempty"` + }{Source: source, Home: home, Environment: environment}, &result) + return result.Files, err +} + +// ParseConfiguration applies Core's shared rules to the text of the files ConfigurationSources +// named (ai.configuration.parse). The result carries metadata and a credential locator only; +// the platform resolves the locator. +func (c *Client) ParseConfiguration(ctx context.Context, request ConfigurationParseRequest) (*Configuration, error) { + var result *Configuration + if err := c.core.Execute(ctx, "ai.configuration.parse", request, &result); err != nil { + return nil, err + } + return result, nil +} diff --git a/desktop/internal/core/ai_configuration_test.go b/desktop/internal/ai/configuration_test.go similarity index 83% rename from desktop/internal/core/ai_configuration_test.go rename to desktop/internal/ai/configuration_test.go index b97412ebab..6e6d6706e3 100644 --- a/desktop/internal/core/ai_configuration_test.go +++ b/desktop/internal/ai/configuration_test.go @@ -1,4 +1,4 @@ -package core +package ai import ( "encoding/json" @@ -8,11 +8,12 @@ import ( "testing" "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" ) -func TestAIConfigurationSourcesUsesCorePaths(t *testing.T) { +func TestConfigurationSourcesUsesCorePaths(t *testing.T) { home := t.TempDir() - files, err := NewClient().AIConfigurationSources(testContext(t), "codex", home, nil) + files, err := testClient().ConfigurationSources(testContext(t), "codex", home, nil) if err != nil { t.Fatal(err) } @@ -24,7 +25,7 @@ func TestAIConfigurationSourcesUsesCorePaths(t *testing.T) { } override := t.TempDir() - files, err = NewClient().AIConfigurationSources(testContext(t), "codex", home, map[string]string{"CODEX_HOME": override}) + files, err = testClient().ConfigurationSources(testContext(t), "codex", home, map[string]string{"CODEX_HOME": override}) if err != nil { t.Fatal(err) } @@ -32,7 +33,7 @@ func TestAIConfigurationSourcesUsesCorePaths(t *testing.T) { t.Fatalf("CODEX_HOME path = %q", files[0].Path) } - files, err = NewClient().AIConfigurationSources(testContext(t), "claude", home, map[string]string{"CLAUDE_CONFIG_DIR": override}) + files, err = testClient().ConfigurationSources(testContext(t), "claude", home, map[string]string{"CLAUDE_CONFIG_DIR": override}) if err != nil { t.Fatal(err) } @@ -43,10 +44,10 @@ func TestAIConfigurationSourcesUsesCorePaths(t *testing.T) { } } -func TestAIConfigurationParseReturnsMetadataAndLocatorOnly(t *testing.T) { +func TestConfigurationParseReturnsMetadataAndLocatorOnly(t *testing.T) { const secret = "fixture-secret-key" - client := NewClient() - configuration, err := client.ParseAIConfiguration(testContext(t), AIConfigurationParseRequest{ + client := testClient() + configuration, err := client.ParseConfiguration(testContext(t), ConfigurationParseRequest{ Source: "codex", Files: map[string]string{ "config": "model = 'fixture-model'\nmodel_provider = 'gateway'\n[model_providers.gateway]\nbase_url = 'https://example.test/v1'\nrequires_openai_auth = true\n", @@ -75,7 +76,7 @@ func TestAIConfigurationParseReturnsMetadataAndLocatorOnly(t *testing.T) { t.Fatal("parse result contains the credential value") } - configuration, err = client.ParseAIConfiguration(testContext(t), AIConfigurationParseRequest{ + configuration, err = client.ParseConfiguration(testContext(t), ConfigurationParseRequest{ Source: "claude", Files: map[string]string{ "settings": `{"env":{"ANTHROPIC_BASE_URL":"https://example.test/v1","ANTHROPIC_API_KEY":"` + secret + `"}}`, @@ -92,8 +93,8 @@ func TestAIConfigurationParseReturnsMetadataAndLocatorOnly(t *testing.T) { } } -func TestAIConfigurationParseReportsNothingConfigured(t *testing.T) { - configuration, err := NewClient().ParseAIConfiguration(testContext(t), AIConfigurationParseRequest{ +func TestConfigurationParseReportsNothingConfigured(t *testing.T) { + configuration, err := testClient().ParseConfiguration(testContext(t), ConfigurationParseRequest{ Source: "codex", Files: map[string]string{"config": " \n"}, }) @@ -105,12 +106,12 @@ func TestAIConfigurationParseReportsNothingConfigured(t *testing.T) { } } -func TestAIConfigurationRejectsUnknownSource(t *testing.T) { - _, err := NewClient().ParseAIConfiguration(testContext(t), AIConfigurationParseRequest{Source: "unknown"}) - requireCode(t, err, CodeInvalidRequest) +func TestConfigurationRejectsUnknownSource(t *testing.T) { + _, err := testClient().ParseConfiguration(testContext(t), ConfigurationParseRequest{Source: "unknown"}) + requireCode(t, err, core.CodeInvalidRequest) } -func TestAIConfigurationParseMatchesSharedFixture(t *testing.T) { +func TestConfigurationParseMatchesSharedFixture(t *testing.T) { data, err := os.ReadFile(contractfixture.CoreFixture("ai/cli-configuration-v1.json")) if err != nil { t.Fatal(err) @@ -132,7 +133,7 @@ func TestAIConfigurationParseMatchesSharedFixture(t *testing.T) { if test.Expected == nil { continue } - configuration, err := NewClient().ParseAIConfiguration(testContext(t), AIConfigurationParseRequest{ + configuration, err := testClient().ParseConfiguration(testContext(t), ConfigurationParseRequest{ Source: test.Source, Files: test.Files, Environment: test.Environment, diff --git a/desktop/internal/ai/http.go b/desktop/internal/ai/http.go new file mode 100644 index 0000000000..40cccdb80d --- /dev/null +++ b/desktop/internal/ai/http.go @@ -0,0 +1,95 @@ +package ai + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "time" +) + +// Provider requests are made here, by the platform: Core only plans the request and decodes +// the answer. The limits follow Lithe-core-rust rust/contracts/ai-commit.md: a 45-second +// deadline, no redirects, no cookies, and a 2 MiB cap on the answer. +const ( + // RequestTimeout bounds one provider request. + RequestTimeout = 45 * time.Second + responseLimit = 2 << 20 +) + +var ( + // ErrResponseTooLarge reports an answer over 2 MiB. + ErrResponseTooLarge = errors.New("ai response too large") + // ErrTimeout reports a provider that did not answer within RequestTimeout. + ErrTimeout = errors.New("ai request timed out") + // errNetwork is a transport failure. The transport error can contain the URL, so only the + // class is reported. + errNetwork = errors.New("AI_NETWORK_ERROR") +) + +// HTTPError is a provider answer that was not a success. It carries the status only: the body +// can echo the request, which holds the user's code. +type HTTPError struct{ Status int } + +func (e *HTTPError) Error() string { return "AI_HTTP_" + http.StatusText(e.Status) } + +// httpClient never follows a redirect and keeps no cookies, so a credential cannot be forwarded +// to another host. +var httpClient = &http.Client{ + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, +} + +// headers are the authentication headers of one commit or pull request provider request. The +// credential is attached here and nowhere else; it is never logged or returned. +func headers(protocol, authentication, key string) map[string]string { + out := map[string]string{"Content-Type": "application/json"} + switch { + case authentication == "apiKey": + out["x-api-key"] = key + default: + out["Authorization"] = "Bearer " + key + } + if protocol == "anthropicMessages" { + out["anthropic-version"] = "2023-06-01" + } + return out +} + +// post sends body to url and returns the answer, bounded to 2 MiB. +func post(ctx context.Context, url string, headers map[string]string, body []byte) ([]byte, error) { + ctx, cancel := context.WithTimeout(ctx, RequestTimeout) + defer cancel() + request, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) + if err != nil { + return nil, err + } + for name, value := range headers { + request.Header.Set(name, value) + } + response, err := httpClient.Do(request) + if err != nil { + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return nil, ErrTimeout + } + if ctx.Err() != nil { + return nil, ctx.Err() + } + return nil, errNetwork + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode > 299 { + return nil, &HTTPError{Status: response.StatusCode} + } + data, err := io.ReadAll(io.LimitReader(response.Body, responseLimit+1)) + if err != nil { + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return nil, ErrTimeout + } + return nil, errNetwork + } + if len(data) > responseLimit { + return nil, ErrResponseTooLarge + } + return data, nil +} diff --git a/desktop/internal/ai/http_test.go b/desktop/internal/ai/http_test.go new file mode 100644 index 0000000000..fb3ddc63ca --- /dev/null +++ b/desktop/internal/ai/http_test.go @@ -0,0 +1,97 @@ +package ai + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestHeadersFollowTheProviderAuthentication(t *testing.T) { + h := headers("anthropicMessages", "apiKey", "secret") + if h["x-api-key"] != "secret" || h["anthropic-version"] == "" || h["Authorization"] != "" { + t.Fatalf("headers = %v", h) + } + h = headers("responses", "bearer", "secret") + if h["Authorization"] != "Bearer secret" { + t.Fatalf("headers = %v", h) + } +} + +func TestPostBoundsTheAnswer(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/big": + _, _ = io.WriteString(w, strings.Repeat("x", responseLimit+1)) + case "/redirect": + http.Redirect(w, r, "/ok", http.StatusFound) + case "/error": + http.Error(w, "echoed secret body", http.StatusUnauthorized) + default: + if r.Header.Get("Authorization") != "Bearer k" { + http.Error(w, "no", http.StatusForbidden) + return + } + _, _ = io.WriteString(w, `{"ok":true}`) + } + })) + defer server.Close() + ctx := testContext(t) + auth := map[string]string{"Authorization": "Bearer k"} + if data, err := post(ctx, server.URL+"/ok", auth, []byte(`{}`)); err != nil || string(data) != `{"ok":true}` { + t.Fatalf("ok = %q %v", data, err) + } + if _, err := post(ctx, server.URL+"/big", auth, nil); !errors.Is(err, ErrResponseTooLarge) { + t.Fatalf("big = %v", err) + } + var status *HTTPError + if _, err := post(ctx, server.URL+"/redirect", auth, nil); !errors.As(err, &status) || status.Status != http.StatusFound { + t.Fatalf("redirect was followed or hidden: %v", err) + } + if _, err := post(ctx, server.URL+"/error", auth, nil); !errors.As(err, &status) || strings.Contains(err.Error(), "secret") { + t.Fatalf("error = %v", err) + } + cancelled, cancel := context.WithCancel(ctx) + cancel() + if _, err := post(cancelled, server.URL+"/ok", auth, nil); !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled = %v", err) + } +} + +// The plan Core makes for a staged diff is sent to the provider with the credential attached +// by this package only, and the answer decodes to the message. +func TestCommitRoundTripThroughCore(t *testing.T) { + var gotAuth, gotBody string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAuth = r.Header.Get("Authorization") + data, _ := io.ReadAll(r.Body) + gotBody = string(data) + _, _ = io.WriteString(w, `{"choices":[{"message":{"content":"feat: add thing"}}]}`) + })) + defer server.Close() + client := testClient() + ctx := testContext(t) + n := len("+x") + plan, err := client.PlanCommit(ctx, PlanProvider{ + ID: "codex", Name: "t", Endpoint: server.URL, Model: "m", APIProtocol: "chatCompletions", + Authentication: "bearer", Source: "codex", RequiresAPIKey: true, AllowsInsecureHTTP: true, + }, NewCommitOptions("english", false, ""), []EvidenceFile{{Path: "a.go", ChangeKind: "added", Diff: "+x", OriginalCharacters: &n}}) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(plan.Body), "Bearer") { + t.Fatal("the plan carries a credential") + } + answer, err := post(ctx, plan.URL, headers("chatCompletions", "bearer", "k"), plan.Body) + if err != nil { + t.Fatal(err) + } + message, err := client.DecodeCommitMessage(ctx, "chatCompletions", json.RawMessage(answer), false) + if err != nil || message != "feat: add thing" || gotAuth != "Bearer k" || !strings.Contains(gotBody, "a.go") { + t.Fatalf("message=%q err=%v auth=%q", message, err, gotAuth) + } +} diff --git a/desktop/internal/ai/inline_edit.go b/desktop/internal/ai/inline_edit.go new file mode 100644 index 0000000000..cc7e71b298 --- /dev/null +++ b/desktop/internal/ai/inline_edit.go @@ -0,0 +1,134 @@ +package ai + +import ( + "context" + "encoding/json" + "errors" + "unicode/utf8" +) + +// The editor's inline edit: Core plans the request (ai.inlineEdit.plan) and decodes the answer +// (ai.inlineEdit.decode). The editor applies an accepted edit itself, as one undoable step, +// and only when the selection did not change meanwhile. + +// InlineEditWindow is how many bytes of context are read on each side of the selection. Core +// keeps 12,000 Unicode scalars of them; a scalar is at most 4 bytes. +const InlineEditWindow = 48_000 + +// InlineEditProvider is the provider facts of an inline edit request. +type InlineEditProvider struct { + WireProtocol string `json:"wireProtocol"` + Endpoint string `json:"endpoint"` + RequiresAPIKey bool `json:"requiresApiKey"` + AllowsInsecureHTTP bool `json:"allowsInsecureHttp"` + AcceptsUnlistedModels bool `json:"acceptsUnlistedModels"` + ChatTokenLimitField string `json:"chatTokenLimitField,omitempty"` + SupportsTemperature bool `json:"supportsTemperature"` +} + +// InlineEditModel selects the model; Listing is catalog, discovered or unlisted. MaxTokens may +// be nil. +type InlineEditModel struct { + ID string `json:"id"` + Listing string `json:"listing"` + MaxTokens *int `json:"maxTokens"` +} + +// InlineEdit is the editor text window of one inline edit. +type InlineEdit struct { + BeforeSelection string `json:"beforeSelection"` + SelectedText string `json:"selectedText"` + AfterSelection string `json:"afterSelection"` + Instruction string `json:"instruction"` + FilePath string `json:"filePath"` + LanguageID string `json:"languageId"` +} + +// CredentialSlot tells the host where to attach its credential. Scheme is bearer or raw. +type CredentialSlot struct { + Required bool `json:"required"` + Header string `json:"header"` + Scheme string `json:"scheme"` +} + +// InlineEditPlan is the credential-free request of an inline edit. +type InlineEditPlan struct { + URL string `json:"url"` + Body json.RawMessage `json:"body"` + Headers map[string]string `json:"headers"` + Credential CredentialSlot `json:"credential"` +} + +// PlanInlineEdit builds the provider request for one inline edit (ai.inlineEdit.plan). +func (c *Client) PlanInlineEdit(ctx context.Context, provider InlineEditProvider, model InlineEditModel, edit InlineEdit) (InlineEditPlan, error) { + var result InlineEditPlan + err := c.core.Execute(ctx, "ai.inlineEdit.plan", struct { + Provider InlineEditProvider `json:"provider"` + Model InlineEditModel `json:"model"` + Edit InlineEdit `json:"edit"` + }{provider, model, edit}, &result) + return result, err +} + +// DecodeInlineEdit extracts the replacement text from a provider answer (ai.inlineEdit.decode). +// An empty replacement is a valid result the caller must report. +func (c *Client) DecodeInlineEdit(ctx context.Context, wireProtocol string, response json.RawMessage) (string, error) { + var result struct { + EditedText string `json:"editedText"` + } + err := c.core.Execute(ctx, "ai.inlineEdit.decode", struct { + WireProtocol string `json:"wireProtocol"` + Response json.RawMessage `json:"response"` + }{wireProtocol, response}, &result) + return result.EditedText, err +} + +// InlineContext is the text around the selection from start to end, at most InlineEditWindow +// bytes on each side and cut at character boundaries. +func InlineContext(text []byte, start, end int) (before, after string) { + from := max(0, start-InlineEditWindow) + for from < start && !utf8.RuneStart(text[from]) { + from++ + } + to := min(len(text), end+InlineEditWindow) + for to > end && to < len(text) && !utf8.RuneStart(text[to]) { + to-- + } + return string(text[from:start]), string(text[end:to]) +} + +// EditInline plans, sends and decodes one inline edit with the first usable provider of sources +// and returns the replacement of the selected text. +func EditInline(ctx context.Context, k Kernel, edit InlineEdit, sources []string) (string, error) { + provider, err := Choose(ctx, k, sources) + if err != nil { + return "", err + } + model := InlineEditModel{ID: provider.Model, Listing: "unlisted"} + plan, err := k.PlanInlineEdit(ctx, InlineEditProvider{ + WireProtocol: provider.Protocol, Endpoint: provider.Endpoint, RequiresAPIKey: true, + AcceptsUnlistedModels: true, ChatTokenLimitField: "max_completion_tokens", + }, model, edit) + if err != nil { + return "", err + } + out := map[string]string{"Content-Type": "application/json"} + for name, value := range plan.Headers { + out[name] = value + } + if plan.Credential.Required { + value := provider.APIKey + if plan.Credential.Scheme == "bearer" { + value = "Bearer " + value + } + out[plan.Credential.Header] = value + } + answer, err := post(ctx, plan.URL, out, plan.Body) + if err != nil { + return "", err + } + if !json.Valid(answer) { + return "", errors.New("AI_INLINE_EDIT_INVALID_RESPONSE") + } + return k.DecodeInlineEdit(ctx, provider.Protocol, answer) +} diff --git a/desktop/internal/ai/inline_edit_test.go b/desktop/internal/ai/inline_edit_test.go new file mode 100644 index 0000000000..65a4bbfddb --- /dev/null +++ b/desktop/internal/ai/inline_edit_test.go @@ -0,0 +1,19 @@ +package ai + +import ( + "strings" + "testing" + "unicode/utf8" +) + +func TestInlineContextNeverSplitsACharacter(t *testing.T) { + text := []byte(strings.Repeat("é", InlineEditWindow) + "SEL" + strings.Repeat("世", InlineEditWindow)) + start := len(strings.Repeat("é", InlineEditWindow)) + before, after := InlineContext(text, start, start+3) + if !utf8.ValidString(before) || !utf8.ValidString(after) { + t.Fatal("the context splits a character") + } + if len([]rune(before)) < 12000 || len([]rune(after)) < 12000 { + t.Fatalf("context is shorter than Core keeps: %d, %d", len([]rune(before)), len([]rune(after))) + } +} diff --git a/desktop/internal/ai/provider.go b/desktop/internal/ai/provider.go new file mode 100644 index 0000000000..9f88ccd3a4 --- /dev/null +++ b/desktop/internal/ai/provider.go @@ -0,0 +1,271 @@ +package ai + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + + "github.com/1lck/Lithe-IDEA/desktop/internal/loginenv" +) + +// Provider discovery: the endpoint, model and key the user's own Codex or Claude configuration +// names. Core finds the native files and parses them; this file only reads the files Core +// names and resolves the credential locator against the same text and environment. + +// configFileLimit matches Core's accepted configuration text size. +const configFileLimit = 1 << 20 + +// Stable reasons a discovered provider cannot be used. Generation only needs to know that a +// provider has one; the names keep the reasons apart when a test or a log needs them. +const ( + issueConfigRead = "configRead" + issueInvalidConfig = "invalidConfig" + issueUnsupportedAuth = "unsupportedAuth" + issueCredential = "credential" + issueCredentialUnsupported = "credentialUnsupported" +) + +var ( + errCredentialUnreadable = errors.New("AI credential unreadable") + errCredentialUnsupported = errors.New("AI credential unsupported") +) + +// ErrNoProvider reports that no configured provider can be used. +var ErrNoProvider = errors.New("no AI provider") + +// Provider is one provider discovered from the user's local Codex or Claude configuration. +// APIKey is memory-only and must never be logged or persisted. +type Provider struct { + Source string + Name string + Endpoint string + Model string + Protocol string + // Authentication is bearer or apiKey, as Core parsed it. + Authentication string + APIKey string + Issue string + MissingKey bool +} + +// Usable reports that the provider has no issue and holds a credential. +func (p Provider) Usable() bool { + return p.Issue == "" && !p.MissingKey && p.APIKey != "" && p.Endpoint != "" +} + +// plan is the credential-free description Core plans a commit or pull request request for. +func (p Provider) plan() PlanProvider { + return PlanProvider{ + ID: p.Source, Name: p.Name, Endpoint: p.Endpoint, Model: p.Model, + APIProtocol: p.Protocol, Authentication: p.Authentication, Source: p.Source, RequiresAPIKey: true, + } +} + +// Sources are the AI CLI configuration sources Core exposes, in the order generation tries +// them. +func Sources() []string { return []string{"codex", "claude"} } + +// Discover reads the local Codex and Claude configuration through Core and resolves each +// credential locator. A source that cannot be read or parsed contributes no provider; no error +// carries a secret. +func Discover(ctx context.Context, k Kernel) map[string][]Provider { + providers := map[string][]Provider{} + home, err := os.UserHomeDir() + if err != nil { + return providers + } + environment := Environment() + for _, source := range Sources() { + if provider, ok := discover(ctx, k, source, home, environment); ok { + providers[source] = append(providers[source], provider) + } + } + return providers +} + +// discover reads one source. It reports false when the source names no provider; a provider +// that cannot be used is returned with its Issue or MissingKey set. +func discover(ctx context.Context, k Kernel, source, home string, environment map[string]string) (Provider, bool) { + files, err := k.ConfigurationSources(ctx, source, home, environment) + if err != nil { + return Provider{}, false + } + texts := map[string]string{} + for _, file := range files { + value, present, err := readConfigurationFile(file.Path) + if err != nil { + return Provider{Source: source, Issue: issueConfigRead}, true + } + if present { + texts[file.File] = value + } + } + parsed, err := k.ParseConfiguration(ctx, ConfigurationParseRequest{ + Source: source, + Files: texts, + Environment: environment, + }) + if err != nil || parsed == nil { + return Provider{}, false + } + if parsed.Provider == nil { + if parsed.Issue != nil { + return Provider{Source: source, Issue: issueInvalidConfig}, true + } + return Provider{}, false + } + provider := Provider{ + Source: source, + Name: parsed.Provider.Name, + Endpoint: parsed.Provider.Endpoint, + Model: parsed.Provider.Model, + Protocol: parsed.Provider.APIProtocol, + Authentication: parsed.Provider.Authentication, + } + if provider.Name == "" { + provider.Name = parsed.Provider.Endpoint + } + if provider.Model == "" { + provider.Model = parsed.Model + } + switch { + case parsed.UnsupportedAuthentication: + provider.Issue = issueUnsupportedAuth + case parsed.HasCredential && parsed.Credential != nil: + key, err := resolveCredential(texts, environment, parsed.Credential) + switch { + case errors.Is(err, errCredentialUnsupported): + provider.Issue = issueCredentialUnsupported + case err != nil: + provider.Issue = issueCredential + case strings.TrimSpace(key) == "": + provider.MissingKey = true + default: + provider.APIKey = key + } + default: + // A generation request needs a key even when the provider metadata says it does not. + provider.MissingKey = true + } + return provider, true +} + +// Pick is the first usable provider of the given sources, in their order. +func Pick(providers map[string][]Provider, sources []string) (Provider, bool) { + for _, source := range sources { + for _, provider := range providers[source] { + if provider.Usable() { + return provider, true + } + } + } + return Provider{}, false +} + +// Choose discovers the providers and picks the first usable one of sources, or reports +// ErrNoProvider. +func Choose(ctx context.Context, k Kernel, sources []string) (Provider, error) { + provider, ok := Pick(Discover(ctx, k), sources) + if !ok { + return Provider{}, ErrNoProvider + } + return provider, nil +} + +// ConfigurationPath is the first native file of a source that exists, or the first file Core +// names when none does. Empty means Core named no file. +func ConfigurationPath(ctx context.Context, k Kernel, source string) string { + home, err := os.UserHomeDir() + if err != nil { + return "" + } + files, err := k.ConfigurationSources(ctx, source, home, Environment()) + if err != nil || len(files) == 0 { + return "" + } + for _, file := range files { + if _, err := os.Stat(file.Path); err == nil { + return file.Path + } + } + return files[0].Path +} + +// Environment is the process environment Core's configuration discovery and credential +// locators resolve against. The snapshot is not logged and never leaves the process. +func Environment() map[string]string { + environment := map[string]string{} + for _, entry := range loginenv.Environ() { + name, value, ok := strings.Cut(entry, "=") + if ok && name != "" { + environment[name] = value + } + } + return environment +} + +func readConfigurationFile(path string) (string, bool, error) { + file, err := os.Open(path) + if errors.Is(err, os.ErrNotExist) { + return "", false, nil + } + if err != nil { + return "", false, fmt.Errorf("read %s: %w", filepath.Base(path), err) + } + defer file.Close() + data, err := io.ReadAll(io.LimitReader(file, configFileLimit+1)) + if err != nil { + return "", false, fmt.Errorf("read %s: %w", filepath.Base(path), err) + } + if len(data) > configFileLimit { + return "", false, fmt.Errorf("%s is larger than %d bytes", filepath.Base(path), configFileLimit) + } + return string(data), true, nil +} + +func resolveCredential(texts, environment map[string]string, locator *ConfigurationCredential) (string, error) { + switch locator.Kind { + case "environment": + return environment[locator.Name], nil + case "file": + if locator.File == "config" { + // The Codex TOML locator is the only path that needs a TOML parser. + // It is reported instead of adding a second configuration parser. + return "", errCredentialUnsupported + } + value, err := resolveJSONPath(texts[locator.File], locator.Path) + if err != nil { + return "", errCredentialUnreadable + } + return value, nil + } + return "", errCredentialUnsupported +} + +func resolveJSONPath(text string, path []string) (string, error) { + var document any + if err := json.Unmarshal([]byte(text), &document); err != nil { + return "", err + } + current := document + for _, key := range path { + object, ok := current.(map[string]any) + if !ok { + return "", errors.New("not an object") + } + current, ok = object[key] + if !ok { + return "", errors.New("missing key") + } + } + value, ok := current.(string) + if !ok { + return "", errors.New("not a string") + } + return value, nil +} diff --git a/desktop/internal/ai/provider_test.go b/desktop/internal/ai/provider_test.go new file mode 100644 index 0000000000..c5e06d2397 --- /dev/null +++ b/desktop/internal/ai/provider_test.go @@ -0,0 +1,105 @@ +package ai + +import ( + "context" + "os" + "path/filepath" + "testing" +) + +func TestCredentialLocatorResolution(t *testing.T) { + texts := map[string]string{ + "auth": `{"OPENAI_API_KEY":"fixture-secret","nested":{"key":"nested-secret"}}`, + "config": "model = 'fixture'\n", + } + environment := map[string]string{"COMPANY_KEY": "environment-secret"} + value, err := resolveCredential(texts, environment, &ConfigurationCredential{Kind: "file", File: "auth", Path: []string{"OPENAI_API_KEY"}}) + if err != nil || value != "fixture-secret" { + t.Fatalf("auth locator = %q, %v", value, err) + } + value, err = resolveCredential(texts, environment, &ConfigurationCredential{Kind: "file", File: "auth", Path: []string{"nested", "key"}}) + if err != nil || value != "nested-secret" { + t.Fatalf("nested locator = %q, %v", value, err) + } + value, err = resolveCredential(texts, environment, &ConfigurationCredential{Kind: "environment", Name: "COMPANY_KEY"}) + if err != nil || value != "environment-secret" { + t.Fatalf("environment locator = %q, %v", value, err) + } + if _, err := resolveCredential(texts, environment, &ConfigurationCredential{Kind: "file", File: "config", Path: []string{"experimental_bearer_token"}}); err == nil { + t.Fatal("a TOML file locator must be reported as unsupported") + } + if _, err := resolveCredential(texts, environment, &ConfigurationCredential{Kind: "file", File: "auth", Path: []string{"missing"}}); err == nil { + t.Fatal("a missing JSON path must fail") + } +} + +// fileKernel uses the real Core parser with files the test writes. +type fileKernel struct { + *Client + files []ConfigurationFile +} + +func (k fileKernel) ConfigurationSources(_ context.Context, source, _ string, _ map[string]string) ([]ConfigurationFile, error) { + if source != "codex" { + return nil, nil + } + return k.files, nil +} + +func TestProviderDiscoveryUsesRealCoreParser(t *testing.T) { + directory := t.TempDir() + configPath := filepath.Join(directory, "config.toml") + authPath := filepath.Join(directory, "auth.json") + if err := os.WriteFile(configPath, []byte("model = 'fixture-model'\nmodel_provider = 'gateway'\n[model_providers.gateway]\nbase_url = 'https://example.test/v1'\nrequires_openai_auth = true\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(authPath, []byte(`{"OPENAI_API_KEY":"fixture-file-secret"}`), 0o600); err != nil { + t.Fatal(err) + } + kernel := fileKernel{Client: testClient(), files: []ConfigurationFile{ + {File: "config", Path: configPath}, + {File: "auth", Path: authPath}, + }} + providers := Discover(testContext(t), kernel) + if len(providers["codex"]) != 1 || len(providers["claude"]) != 0 { + t.Fatalf("providers = %d codex, %d claude; want one Codex provider", len(providers["codex"]), len(providers["claude"])) + } + provider := providers["codex"][0] + if provider.Issue != "" || provider.Endpoint != "https://example.test/v1" || provider.Model != "fixture-model" || + provider.Protocol != "responses" || provider.APIKey != "fixture-file-secret" { + t.Fatalf("provider issue=%q endpoint=%q model=%q protocol=%q keyPresent=%v", provider.Issue, provider.Endpoint, provider.Model, provider.Protocol, provider.APIKey != "") + } + if _, ok := Pick(providers, Sources()); !ok { + t.Fatal("the discovered provider is not usable for generation") + } + if got := ConfigurationPath(testContext(t), kernel, "codex"); got != configPath { + t.Fatalf("configuration path = %q, want %q", got, configPath) + } +} + +func TestPickNeedsACredential(t *testing.T) { + providers := map[string][]Provider{ + "codex": {{Endpoint: "https://a", MissingKey: true}}, + "claude": {{Endpoint: "https://b", APIKey: "k", Issue: ""}}, + } + got, ok := Pick(providers, Sources()) + if !ok || got.Endpoint != "https://b" { + t.Fatalf("picked %#v %v", got, ok) + } + if _, ok := Pick(map[string][]Provider{"codex": {{Endpoint: "https://a", APIKey: "k", Issue: issueCredential}}}, Sources()); ok { + t.Fatal("a provider with an issue was picked") + } + if _, ok := Pick(providers, []string{"codex"}); ok { + t.Fatal("a source outside the choice was picked") + } + both := map[string][]Provider{ + "codex": {{Endpoint: "https://a", APIKey: "k"}}, + "claude": {{Endpoint: "https://b", APIKey: "k"}}, + } + if got, ok := Pick(both, []string{"claude"}); !ok || got.Endpoint != "https://b" { + t.Fatalf("claude only picked %#v %v", got, ok) + } + if _, ok := Pick(map[string][]Provider{"claude": {{Endpoint: "https://b"}}}, []string{"claude"}); ok { + t.Fatal("a provider without a key was picked") + } +} diff --git a/desktop/internal/ai/pull_request.go b/desktop/internal/ai/pull_request.go new file mode 100644 index 0000000000..ff55ca2a13 --- /dev/null +++ b/desktop/internal/ai/pull_request.go @@ -0,0 +1,86 @@ +package ai + +import ( + "context" + "encoding/json" +) + +// The pull request description draft (Lithe-core-rust rust/contracts/ai-generation-requests.md): +// Core shapes the prompt, applies the sensitive-path policy and the diff budget, and decodes +// the model's answer; this package sends the planned request with the provider's credential. + +// PullRequestOptions are the options of a description: the language, the format and template, +// the diff budget and the reasoning effort ("default" omits the field). +type PullRequestOptions struct { + Language string `json:"language"` + Format string `json:"format"` + CustomTemplate string `json:"customTemplate,omitempty"` + MaximumDiffCharacters int `json:"maximumDiffCharacters"` + ReasoningEffort string `json:"reasoningEffort"` +} + +// PullRequestOptionsFor are the options of a description written in the language and with the +// diff budget and reasoning effort of a commit message generation. +func PullRequestOptionsFor(commit CommitOptions) PullRequestOptions { + return PullRequestOptions{ + Language: commit.Language, Format: "standard", MaximumDiffCharacters: commit.MaximumDiffCharacters, + ReasoningEffort: commit.ReasoningEffort, + } +} + +// PullRequestFile is one changed file of the comparison: its path, its change kind, and its +// textual patch, empty for a file without one. +type PullRequestFile struct { + Path string `json:"path"` + ChangeKind string `json:"changeKind"` + Diff string `json:"diff"` +} + +// PullRequestComparison is the base...head comparison a description is drafted from. +type PullRequestComparison struct { + Repository string `json:"repository"` + Base string `json:"base"` + Head string `json:"head"` + CommitMessages []string `json:"commitMessages"` + Files []PullRequestFile `json:"files"` +} + +// PlanPullRequest builds the provider request for a pull request description +// (ai.pullRequest.plan). +func (c *Client) PlanPullRequest(ctx context.Context, provider PlanProvider, options PullRequestOptions, comparison PullRequestComparison) (HTTPRequest, error) { + var result HTTPRequest + err := c.core.Execute(ctx, "ai.pullRequest.plan", struct { + Provider PlanProvider `json:"provider"` + Options PullRequestOptions `json:"options"` + Comparison PullRequestComparison `json:"comparison"` + }{provider, options, comparison}, &result) + return result, err +} + +// DecodePullRequest extracts the title and the Markdown description from a provider answer +// (ai.pullRequest.decode). +func (c *Client) DecodePullRequest(ctx context.Context, protocol string, response json.RawMessage) (title, description string, err error) { + var result struct { + Title string `json:"title"` + Description string `json:"description"` + } + err = c.core.Execute(ctx, "ai.pullRequest.decode", struct { + Protocol string `json:"protocol"` + Response json.RawMessage `json:"response"` + }{protocol, response}, &result) + return result.Title, result.Description, err +} + +// DraftPullRequest plans, sends and decodes one description of comparison with provider, which +// the caller chose before it fetched the comparison. +func DraftPullRequest(ctx context.Context, k Kernel, provider Provider, options PullRequestOptions, comparison PullRequestComparison) (title, description string, err error) { + plan, err := k.PlanPullRequest(ctx, provider.plan(), options, comparison) + if err != nil { + return "", "", err + } + answer, err := post(ctx, plan.URL, headers(provider.Protocol, provider.Authentication, provider.APIKey), plan.Body) + if err != nil { + return "", "", err + } + return k.DecodePullRequest(ctx, provider.Protocol, answer) +} diff --git a/desktop/internal/core/ai_configuration.go b/desktop/internal/core/ai_configuration.go deleted file mode 100644 index 7c136fa862..0000000000 --- a/desktop/internal/core/ai_configuration.go +++ /dev/null @@ -1,86 +0,0 @@ -package core - -import ( - "context" -) - -// AIConfigurationFile is one native file Core asks the platform to read for an -// AI CLI configuration source. File is the key the text is passed back under. -type AIConfigurationFile struct { - File string `json:"file"` - Path string `json:"path"` -} - -// AIConfigurationProvider is the credential-free provider metadata parsed from a -// local Codex or Claude configuration. APIProtocol is responses, -// chatCompletions or anthropicMessages; Authentication is bearer or apiKey. -type AIConfigurationProvider struct { - ID string `json:"id"` - Name string `json:"name"` - Endpoint string `json:"endpoint"` - Model string `json:"model"` - APIProtocol string `json:"apiProtocol"` - Authentication string `json:"authentication"` - Source string `json:"source"` - RequiresAPIKey bool `json:"requiresApiKey"` -} - -// AIConfigurationCredential locates the credential in the same files or -// environment that were passed to the parser. The value itself never crosses -// the Core boundary. -type AIConfigurationCredential struct { - Kind string `json:"kind"` - Name string `json:"name,omitempty"` - File string `json:"file,omitempty"` - Path []string `json:"path,omitempty"` -} - -// AIConfiguration is Core's parse result. A nil value from ParseAIConfiguration -// means nothing is configured. Provider is nil when the configuration parsed -// but is not a usable provider; Issue then names the stable reason code. -type AIConfiguration struct { - Model string `json:"model"` - Provider *AIConfigurationProvider `json:"provider"` - Issue *string `json:"issue"` - ReasoningEffort *string `json:"reasoningEffort"` - HasCredential bool `json:"hasCredential"` - Credential *AIConfigurationCredential `json:"credential"` - UnsupportedAuthentication bool `json:"unsupportedAuthentication"` -} - -// AIConfigurationParseRequest is the payload of ai.configuration.parse. Files is -// keyed like AIConfigurationFile.File: config, auth, settings, credentials and -// root. Environment is the process snapshot the credential locator is resolved -// against; it is not returned or logged. -type AIConfigurationParseRequest struct { - Source string `json:"source"` - Files map[string]string `json:"files,omitempty"` - Environment map[string]string `json:"environment,omitempty"` - AllowIncomplete bool `json:"allowIncomplete,omitempty"` -} - -// AIConfigurationSources names the native files of one AI CLI source. Core -// decides the paths; the platform only reads them. It is read-only and must run -// off the UI thread. -func (c *Client) AIConfigurationSources(ctx context.Context, source, home string, environment map[string]string) ([]AIConfigurationFile, error) { - var result struct { - Files []AIConfigurationFile `json:"files"` - } - err := c.Execute(ctx, "ai.configuration.sources", struct { - Source string `json:"source"` - Home string `json:"home"` - Environment map[string]string `json:"environment,omitempty"` - }{Source: source, Home: home, Environment: environment}, &result) - return result.Files, err -} - -// ParseAIConfiguration applies Core's shared rules to the text of the files -// named by AIConfigurationSources. The result carries metadata and a credential -// locator only; the platform resolves the locator natively. -func (c *Client) ParseAIConfiguration(ctx context.Context, request AIConfigurationParseRequest) (*AIConfiguration, error) { - var result *AIConfiguration - if err := c.Execute(ctx, "ai.configuration.parse", request, &result); err != nil { - return nil, err - } - return result, nil -} diff --git a/desktop/internal/core/ai_generation.go b/desktop/internal/core/ai_generation.go deleted file mode 100644 index 77be54739e..0000000000 --- a/desktop/internal/core/ai_generation.go +++ /dev/null @@ -1,237 +0,0 @@ -package core - -import ( - "context" - "encoding/json" -) - -// AICommitProvider is the credential-free provider description of the commit -// planner. Credentials never cross the Core boundary. -type AICommitProvider struct { - ID string `json:"id"` - Name string `json:"name"` - Endpoint string `json:"endpoint"` - Model string `json:"model"` - APIProtocol string `json:"apiProtocol"` - Authentication string `json:"authentication"` - Source string `json:"source"` - RequiresAPIKey bool `json:"requiresApiKey"` - AllowsInsecureHTTP bool `json:"allowsInsecureHttp"` - ChatTokenLimitField string `json:"chatTokenLimitField,omitempty"` -} - -// AICommitOptions are the user choices of one commit message generation. -type AICommitOptions struct { - Language string `json:"language"` - Format string `json:"format"` - CustomInstructions string `json:"customInstructions"` - IncludeBody bool `json:"includeBody"` - SubjectMaximumLength int `json:"subjectMaximumLength"` - MaximumDiffCharacters int `json:"maximumDiffCharacters"` - ReasoningEffort string `json:"reasoningEffort"` -} - -// AICommitFile is one file of commit evidence. OriginalCharacters is the -// untruncated diff length reported by git.commitMessageContext. The JSON -// command expects it on every file, with Diff already cut to the budget. -type AICommitFile struct { - Path string `json:"path"` - ChangeKind string `json:"changeKind"` - Diff string `json:"diff"` - OriginalCharacters *int `json:"originalCharacters,omitempty"` -} - -// AIHTTPRequest is a credential-free provider request. The host attaches the -// authentication headers and performs the HTTP call. -type AIHTTPRequest struct { - URL string `json:"url"` - Body json.RawMessage `json:"body"` -} - -// AIPlanCommit builds the provider request for a commit message. -func (c *Client) AIPlanCommit(ctx context.Context, provider AICommitProvider, options AICommitOptions, files []AICommitFile) (AIHTTPRequest, error) { - var result AIHTTPRequest - err := c.Execute(ctx, "ai.planCommit", struct { - Provider AICommitProvider `json:"provider"` - Options AICommitOptions `json:"options"` - Files []AICommitFile `json:"files"` - }{provider, options, files}, &result) - return result, err -} - -// AIDecodeCommitMessage extracts the message from a provider response body. The -// host rejects responses over 2 MiB before calling it. -func (c *Client) AIDecodeCommitMessage(ctx context.Context, protocol string, response json.RawMessage, includeBody bool) (string, error) { - var result struct { - Message string `json:"message"` - } - err := c.Execute(ctx, "ai.decodeCommitMessage", struct { - Protocol string `json:"protocol"` - Response json.RawMessage `json:"response"` - IncludeBody bool `json:"includeBody"` - }{protocol, response, includeBody}, &result) - return result.Message, err -} - -// AICommitBudgetFile is the budgeted prefix length of one file. -type AICommitBudgetFile struct { - Characters int `json:"characters"` - Truncated bool `json:"truncated"` -} - -// AICommitInputBudget distributes the diff budget across files given their -// Unicode scalar lengths. -func (c *Client) AICommitInputBudget(ctx context.Context, maximumDiffCharacters int, fileLengths []int) ([]AICommitBudgetFile, error) { - var result struct { - Files []AICommitBudgetFile `json:"files"` - } - err := c.Execute(ctx, "ai.commitInputBudget", struct { - MaximumDiffCharacters int `json:"maximumDiffCharacters"` - FileLengths []int `json:"fileLengths"` - }{maximumDiffCharacters, nonNil(fileLengths)}, &result) - return result.Files, err -} - -// AIInlineEditProvider is the provider facts of an inline edit request. -type AIInlineEditProvider struct { - WireProtocol string `json:"wireProtocol"` - Endpoint string `json:"endpoint"` - RequiresAPIKey bool `json:"requiresApiKey"` - AllowsInsecureHTTP bool `json:"allowsInsecureHttp"` - AcceptsUnlistedModels bool `json:"acceptsUnlistedModels"` - ChatTokenLimitField string `json:"chatTokenLimitField,omitempty"` - SupportsTemperature bool `json:"supportsTemperature"` -} - -// AIInlineEditModel selects the model; Listing is catalog, discovered or -// unlisted. MaxTokens may be nil. -type AIInlineEditModel struct { - ID string `json:"id"` - Listing string `json:"listing"` - MaxTokens *int `json:"maxTokens"` -} - -// AIInlineEdit is the editor text window of one inline edit. -type AIInlineEdit struct { - BeforeSelection string `json:"beforeSelection"` - SelectedText string `json:"selectedText"` - AfterSelection string `json:"afterSelection"` - Instruction string `json:"instruction"` - FilePath string `json:"filePath"` - LanguageID string `json:"languageId"` -} - -// AICredentialSlot tells the host where to attach its credential. Scheme is -// bearer or raw. -type AICredentialSlot struct { - Required bool `json:"required"` - Header string `json:"header"` - Scheme string `json:"scheme"` -} - -// AIInlineEditPlan is the credential-free request of an inline edit. -type AIInlineEditPlan struct { - URL string `json:"url"` - Body json.RawMessage `json:"body"` - Headers map[string]string `json:"headers"` - Credential AICredentialSlot `json:"credential"` -} - -// AIInlineEditPlan builds the provider request for one inline edit. -func (c *Client) AIInlineEditPlan(ctx context.Context, provider AIInlineEditProvider, model AIInlineEditModel, edit AIInlineEdit) (AIInlineEditPlan, error) { - var result AIInlineEditPlan - err := c.Execute(ctx, "ai.inlineEdit.plan", struct { - Provider AIInlineEditProvider `json:"provider"` - Model AIInlineEditModel `json:"model"` - Edit AIInlineEdit `json:"edit"` - }{provider, model, edit}, &result) - return result, err -} - -// AIInlineEditDecode extracts the replacement text from a provider response. An -// empty replacement is a valid result the caller must report. -func (c *Client) AIInlineEditDecode(ctx context.Context, wireProtocol string, response json.RawMessage) (string, error) { - var result struct { - EditedText string `json:"editedText"` - } - err := c.Execute(ctx, "ai.inlineEdit.decode", struct { - WireProtocol string `json:"wireProtocol"` - Response json.RawMessage `json:"response"` - }{wireProtocol, response}, &result) - return result.EditedText, err -} - -// CommitContextFile is a selected file of git.commitMessageContext. -type CommitContextFile struct { - Path string `json:"path"` - OriginalPath string `json:"originalPath,omitempty"` - ChangeKind string `json:"changeKind"` -} - -// CommitContextRepository is one repository and its selected files. -type CommitContextRepository struct { - Root string `json:"root"` - Files []CommitContextFile `json:"files"` -} - -// CommitContextEvidence is the bounded evidence captured for AI generation. -type CommitContextEvidence struct { - Files []AICommitFile - Token string -} - -type commitContextRequest struct { - Action string `json:"action"` - Mode string `json:"mode"` - Repositories []CommitContextRepository `json:"repositories"` - MaximumDiffCharacters int `json:"maximumDiffCharacters,omitempty"` - Token string `json:"token,omitempty"` -} - -// CommitMessageContext captures AI commit evidence without modifying the index. -// mode is staged or worktree and must match the commit operation. It runs Git -// and blocks; call it from a background goroutine. -func (c *Client) CommitMessageContext(ctx context.Context, mode string, repositories []CommitContextRepository, maximumDiffCharacters int) (CommitContextEvidence, error) { - var raw struct { - Files []struct { - Path string `json:"path"` - ChangeKind string `json:"changeKind"` - Diff string `json:"diff"` - OriginalCharacters int `json:"originalCharacters"` - } `json:"files"` - Token string `json:"token"` - } - err := c.Execute(ctx, "git.commitMessageContext", commitContextRequest{ - Action: "capture", Mode: mode, Repositories: repositories, MaximumDiffCharacters: maximumDiffCharacters, - }, &raw) - out := CommitContextEvidence{Token: raw.Token} - for _, f := range raw.Files { - n := f.OriginalCharacters - out.Files = append(out.Files, AICommitFile{Path: f.Path, ChangeKind: f.ChangeKind, Diff: f.Diff, OriginalCharacters: &n}) - } - return out, err -} - -// CommitMessageContextIsCurrent rechecks the captured evidence token against -// the current Git state. Apply generated text only when it returns true. -func (c *Client) CommitMessageContextIsCurrent(ctx context.Context, mode string, repositories []CommitContextRepository, token string) (bool, error) { - var result struct { - IsCurrent bool `json:"isCurrent"` - } - err := c.Execute(ctx, "git.commitMessageContext", commitContextRequest{ - Action: "check", Mode: mode, Repositories: repositories, Token: token, - }, &result) - return result.IsCurrent, err -} - -// IDEHostControl sends one ideHost.control action to the local capability -// broker and returns the raw result. Actions are open, close, closeOwner, poll, -// claim, respond, catalog, validate and output; see Lithe-core-rust rust/contracts/ide-api/v1.md. -func (c *Client) IDEHostControl(ctx context.Context, action string, arguments any) (json.RawMessage, error) { - var result json.RawMessage - err := c.Execute(ctx, "ideHost.control", struct { - Action string `json:"action"` - Arguments any `json:"arguments"` - }{action, arguments}, &result) - return result, err -} diff --git a/desktop/internal/core/ai_pull_request.go b/desktop/internal/core/ai_pull_request.go deleted file mode 100644 index 62b1a74c08..0000000000 --- a/desktop/internal/core/ai_pull_request.go +++ /dev/null @@ -1,61 +0,0 @@ -package core - -import ( - "context" - "encoding/json" -) - -// This file wraps the AI pull-request description commands (Lithe-core-rust rust/contracts/ai-generation-requests.md). -// Core shapes the prompt, applies the sensitive-path policy and the diff budget, and decodes the -// model's answer; the host sends the planned request with the provider's credentials. - -// AIPullRequestOptions are the options of a description: the language, the format and template, -// the diff budget and the reasoning effort ("default" omits the field). -type AIPullRequestOptions struct { - Language string `json:"language"` - Format string `json:"format"` - CustomTemplate string `json:"customTemplate,omitempty"` - MaximumDiffCharacters int `json:"maximumDiffCharacters"` - ReasoningEffort string `json:"reasoningEffort"` -} - -// PullRequestComparisonFile is one changed file of the comparison: its path, its change kind, and its -// textual patch, empty for a file without one. -type PullRequestComparisonFile struct { - Path string `json:"path"` - ChangeKind string `json:"changeKind"` - Diff string `json:"diff"` -} - -// PullRequestComparison is the base...head comparison a description is drafted from. -type PullRequestComparison struct { - Repository string `json:"repository"` - Base string `json:"base"` - Head string `json:"head"` - CommitMessages []string `json:"commitMessages"` - Files []PullRequestComparisonFile `json:"files"` -} - -// AIPlanPullRequest builds the provider request for a pull request description. -func (c *Client) AIPlanPullRequest(ctx context.Context, provider AICommitProvider, options AIPullRequestOptions, comparison PullRequestComparison) (AIHTTPRequest, error) { - var result AIHTTPRequest - err := c.Execute(ctx, "ai.pullRequest.plan", struct { - Provider AICommitProvider `json:"provider"` - Options AIPullRequestOptions `json:"options"` - Comparison PullRequestComparison `json:"comparison"` - }{provider, options, comparison}, &result) - return result, err -} - -// AIDecodePullRequest extracts the title and the Markdown description from a provider response. -func (c *Client) AIDecodePullRequest(ctx context.Context, protocol string, response json.RawMessage) (title, description string, err error) { - var result struct { - Title string `json:"title"` - Description string `json:"description"` - } - err = c.Execute(ctx, "ai.pullRequest.decode", struct { - Protocol string `json:"protocol"` - Response json.RawMessage `json:"response"` - }{protocol, response}, &result) - return result.Title, result.Description, err -} diff --git a/desktop/internal/core/doc.go b/desktop/internal/core/doc.go index eb4c48335c..7189e4910d 100644 --- a/desktop/internal/core/doc.go +++ b/desktop/internal/core/doc.go @@ -10,7 +10,9 @@ // {operationId, command, payload}, decodes {id, ok, data, error}, turns failures into a // typed *Error, and forwards context cancellation to the kernel through lithe_core_cancel. // 3. Typed commands (recent.go, git.go, chrome.go): small methods on *Client -// with Go request and response types, so the UI never builds JSON by hand. +// with Go request and response types, so the UI never builds JSON by hand. A feature that +// is maintained on its own wraps its commands in its own package on top of Client.Execute: +// the ai.* commands and git.commitMessageContext live in internal/ai, not here. // // Every call is synchronous and blocks the calling goroutine until the kernel answers. GitStatus // runs Git and can take anything from milliseconds to seconds, so it must be called from a diff --git a/desktop/internal/core/ide_host.go b/desktop/internal/core/ide_host.go index 3c03d84023..52388ad232 100644 --- a/desktop/internal/core/ide_host.go +++ b/desktop/internal/core/ide_host.go @@ -206,3 +206,15 @@ func (c *Client) IDEHostOutputPage(ctx context.Context, snapshot any, cursor str } return c.IDEHostControl(ctx, "output", args) } + +// IDEHostControl sends one ideHost.control action to the local capability +// broker and returns the raw result. Actions are open, close, closeOwner, poll, +// claim, respond, catalog, validate and output; see Lithe-core-rust rust/contracts/ide-api/v1.md. +func (c *Client) IDEHostControl(ctx context.Context, action string, arguments any) (json.RawMessage, error) { + var result json.RawMessage + err := c.Execute(ctx, "ideHost.control", struct { + Action string `json:"action"` + Arguments any `json:"arguments"` + }{action, arguments}, &result) + return result, err +} diff --git a/desktop/internal/workbench/ai_generation.go b/desktop/internal/workbench/ai_generation.go index 78195bd20c..ca344acdd1 100644 --- a/desktop/internal/workbench/ai_generation.go +++ b/desktop/internal/workbench/ai_generation.go @@ -2,8 +2,8 @@ package workbench import ( "context" - "os" + "github.com/1lck/Lithe-IDEA/desktop/internal/ai" "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" ) @@ -12,6 +12,9 @@ import ( // and never written into the Codex or Claude configuration. The provider each source offers // comes from the same discovery the generation uses, so Settings › AI › Generation shows what it reads. +// aiKernelReady reports whether the window can run AI generation at all. +func (a *App) aiKernelReady() bool { return a.aiKernel != nil } + // aiGenerationSettings is the stored choice; it is read on the window thread. func (a *App) aiGenerationSettings() settingswindow.AIGenerationSettings { return a.settings.AIGeneration @@ -63,42 +66,26 @@ func (a *App) aiGenerationSources() []string { if provider := a.aiGenerationSettings().Provider; provider != "" { return []string{provider} } - return aiProviderSources() + return ai.Sources() } // aiProviderStatuses reports, for each source, the provider discovery reads and the native // configuration file it comes from. It runs off the window thread and never returns a key. func (a *App) aiProviderStatuses(ctx context.Context) []settingswindow.AIProviderStatus { - providers := a.discoverAIProviders(ctx) var out []settingswindow.AIProviderStatus - for _, source := range aiProviderSources() { - status := settingswindow.AIProviderStatus{Source: source, Path: a.aiConfigurationPath(ctx, source)} - if provider, ok := pickAIProviderFrom(providers, []string{source}); ok { + var providers map[string][]ai.Provider + if a.aiKernel != nil { + providers = ai.Discover(ctx, a.aiKernel) + } + for _, source := range ai.Sources() { + status := settingswindow.AIProviderStatus{Source: source} + if a.aiKernel != nil { + status.Path = ai.ConfigurationPath(ctx, a.aiKernel, source) + } + if provider, ok := ai.Pick(providers, []string{source}); ok { status.Name, status.Model, status.Usable = provider.Name, provider.Model, true } out = append(out, status) } return out } - -// aiConfigurationPath is the first native file of a source that exists, or the first file Core -// names when none does. Empty means Core named no file. -func (a *App) aiConfigurationPath(ctx context.Context, source string) string { - if a.aiKernel == nil { - return "" - } - home, err := os.UserHomeDir() - if err != nil { - return "" - } - files, err := a.aiKernel.AIConfigurationSources(ctx, source, home, aiEnvironment()) - if err != nil || len(files) == 0 { - return "" - } - for _, file := range files { - if _, err := os.Stat(file.Path); err == nil { - return file.Path - } - } - return files[0].Path -} diff --git a/desktop/internal/workbench/ai_generation_test.go b/desktop/internal/workbench/ai_generation_test.go index ad598e5c9d..438cdfe47c 100644 --- a/desktop/internal/workbench/ai_generation_test.go +++ b/desktop/internal/workbench/ai_generation_test.go @@ -17,20 +17,3 @@ func TestAIGenerationSourcesFollowTheChosenProvider(t *testing.T) { t.Fatalf("claude sources = %v", got) } } - -func TestPickAIProviderFromRespectsTheSources(t *testing.T) { - providers := map[string][]aiProvider{ - "codex": {{Endpoint: "https://a", APIKey: "k"}}, - "claude": {{Endpoint: "https://b", APIKey: "k"}}, - } - got, ok := pickAIProviderFrom(providers, []string{"claude"}) - if !ok || got.Endpoint != "https://b" { - t.Fatalf("claude only picked %#v %v", got, ok) - } - if _, ok := pickAIProviderFrom(providers, []string{"codex"}); !ok { - t.Fatal("codex only found nothing") - } - if _, ok := pickAIProviderFrom(map[string][]aiProvider{"claude": {{Endpoint: "https://b"}}}, []string{"claude"}); ok { - t.Fatal("a provider without a key was picked") - } -} diff --git a/desktop/internal/workbench/ai_provider.go b/desktop/internal/workbench/ai_provider.go deleted file mode 100644 index 50e44c537c..0000000000 --- a/desktop/internal/workbench/ai_provider.go +++ /dev/null @@ -1,240 +0,0 @@ -package workbench - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "os" - "path/filepath" - "strings" - - "github.com/1lck/Lithe-IDEA/desktop/internal/core" - "github.com/1lck/Lithe-IDEA/desktop/internal/loginenv" -) - -// The provider discovery of commit message generation and inline edits: the endpoint, model and -// key the user's own Codex or Claude configuration names. Core finds the native files and parses -// them; this file only reads the files Core names and resolves the credential locator against -// the same text and environment. A key stays in memory and is never logged or persisted. - -// AIKernel is what provider discovery asks the kernel. *core.Client satisfies it through -// CoreAIKernel; a window built without one offers no AI generation. -type AIKernel interface { - AIConfigurationSources(ctx context.Context, source, home string, environment map[string]string) ([]core.AIConfigurationFile, error) - ParseAIConfiguration(ctx context.Context, request core.AIConfigurationParseRequest) (*core.AIConfiguration, error) -} - -// CoreAIKernel adapts the typed Core client to AIKernel. -type CoreAIKernel struct{ Client *core.Client } - -func (k CoreAIKernel) AIConfigurationSources(ctx context.Context, source, home string, environment map[string]string) ([]core.AIConfigurationFile, error) { - return k.Client.AIConfigurationSources(ctx, source, home, environment) -} - -func (k CoreAIKernel) ParseAIConfiguration(ctx context.Context, request core.AIConfigurationParseRequest) (*core.AIConfiguration, error) { - return k.Client.ParseAIConfiguration(ctx, request) -} - -// aiConfigFileLimit matches Core's accepted configuration text size. -const aiConfigFileLimit = 1 << 20 - -// Stable reasons a discovered provider cannot be used. Generation only needs to know that a -// provider has one; the names keep the reasons apart when a test or a log needs them. -const ( - aiIssueConfigRead = "configRead" - aiIssueInvalidConfig = "invalidConfig" - aiIssueUnsupportedAuth = "unsupportedAuth" - aiIssueCredential = "credential" - aiIssueCredentialUnsupported = "credentialUnsupported" -) - -var ( - errAICredentialUnreadable = errors.New("AI credential unreadable") - errAICredentialUnsupported = errors.New("AI credential unsupported") -) - -// aiProvider is one provider discovered from the user's local Codex or Claude configuration. -// APIKey is memory-only and must never be logged or persisted. -type aiProvider struct { - Source string - Name string - Endpoint string - Model string - Protocol string - // Authentication is bearer or apiKey, as Core parsed it. - Authentication string - APIKey string - Issue string - MissingKey bool -} - -// aiKernelReady reports whether the window can discover providers at all. -func (a *App) aiKernelReady() bool { return a.aiKernel != nil } - -// discoverAIProviders reads the local Codex and Claude configuration through Core and resolves -// each credential locator. A source that cannot be read or parsed contributes no provider; no -// error carries a secret. -func (a *App) discoverAIProviders(ctx context.Context) map[string][]aiProvider { - providers := map[string][]aiProvider{} - if a.aiKernel == nil { - return providers - } - home, err := os.UserHomeDir() - if err != nil { - return providers - } - environment := aiEnvironment() - for _, source := range aiProviderSources() { - if provider, ok := a.discoverAIProvider(ctx, source, home, environment); ok { - providers[source] = append(providers[source], provider) - } - } - return providers -} - -// discoverAIProvider reads one source. It reports false when the source names no provider; a -// provider that cannot be used is returned with its Issue or MissingKey set. -func (a *App) discoverAIProvider(ctx context.Context, source, home string, environment map[string]string) (aiProvider, bool) { - files, err := a.aiKernel.AIConfigurationSources(ctx, source, home, environment) - if err != nil { - return aiProvider{}, false - } - texts := map[string]string{} - for _, file := range files { - value, present, err := readAIConfigurationFile(file.Path) - if err != nil { - return aiProvider{Source: source, Issue: aiIssueConfigRead}, true - } - if present { - texts[file.File] = value - } - } - parsed, err := a.aiKernel.ParseAIConfiguration(ctx, core.AIConfigurationParseRequest{ - Source: source, - Files: texts, - Environment: environment, - }) - if err != nil || parsed == nil { - return aiProvider{}, false - } - if parsed.Provider == nil { - if parsed.Issue != nil { - return aiProvider{Source: source, Issue: aiIssueInvalidConfig}, true - } - return aiProvider{}, false - } - provider := aiProvider{ - Source: source, - Name: parsed.Provider.Name, - Endpoint: parsed.Provider.Endpoint, - Model: parsed.Provider.Model, - Protocol: parsed.Provider.APIProtocol, - Authentication: parsed.Provider.Authentication, - } - if provider.Name == "" { - provider.Name = parsed.Provider.Endpoint - } - if provider.Model == "" { - provider.Model = parsed.Model - } - switch { - case parsed.UnsupportedAuthentication: - provider.Issue = aiIssueUnsupportedAuth - case parsed.HasCredential && parsed.Credential != nil: - key, err := resolveAICredential(texts, environment, parsed.Credential) - switch { - case errors.Is(err, errAICredentialUnsupported): - provider.Issue = aiIssueCredentialUnsupported - case err != nil: - provider.Issue = aiIssueCredential - case strings.TrimSpace(key) == "": - provider.MissingKey = true - default: - provider.APIKey = key - } - default: - // A generation request needs a key even when the provider metadata says it does not. - provider.MissingKey = true - } - return provider, true -} - -// aiProviderSources are the AI CLI configuration sources Core exposes, in the order -// generation tries them. -func aiProviderSources() []string { return []string{"codex", "claude"} } - -// aiEnvironment is the process environment Core's configuration discovery and credential -// locators resolve against. The snapshot is not logged and never leaves the process. -func aiEnvironment() map[string]string { - environment := map[string]string{} - for _, entry := range loginenv.Environ() { - name, value, ok := strings.Cut(entry, "=") - if ok && name != "" { - environment[name] = value - } - } - return environment -} - -func readAIConfigurationFile(path string) (string, bool, error) { - file, err := os.Open(path) - if errors.Is(err, os.ErrNotExist) { - return "", false, nil - } - if err != nil { - return "", false, fmt.Errorf("read %s: %w", filepath.Base(path), err) - } - defer file.Close() - data, err := io.ReadAll(io.LimitReader(file, aiConfigFileLimit+1)) - if err != nil { - return "", false, fmt.Errorf("read %s: %w", filepath.Base(path), err) - } - if len(data) > aiConfigFileLimit { - return "", false, fmt.Errorf("%s is larger than %d bytes", filepath.Base(path), aiConfigFileLimit) - } - return string(data), true, nil -} - -func resolveAICredential(texts, environment map[string]string, locator *core.AIConfigurationCredential) (string, error) { - switch locator.Kind { - case "environment": - return environment[locator.Name], nil - case "file": - if locator.File == "config" { - // The Codex TOML locator is the only path that needs a TOML parser. - // It is reported instead of adding a second configuration parser. - return "", errAICredentialUnsupported - } - value, err := resolveJSONPath(texts[locator.File], locator.Path) - if err != nil { - return "", errAICredentialUnreadable - } - return value, nil - } - return "", errAICredentialUnsupported -} - -func resolveJSONPath(text string, path []string) (string, error) { - var document any - if err := json.Unmarshal([]byte(text), &document); err != nil { - return "", err - } - current := document - for _, key := range path { - object, ok := current.(map[string]any) - if !ok { - return "", errors.New("not an object") - } - current, ok = object[key] - if !ok { - return "", errors.New("missing key") - } - } - value, ok := current.(string) - if !ok { - return "", errors.New("not a string") - } - return value, nil -} diff --git a/desktop/internal/workbench/ai_provider_test.go b/desktop/internal/workbench/ai_provider_test.go deleted file mode 100644 index 1cded79b84..0000000000 --- a/desktop/internal/workbench/ai_provider_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package workbench - -import ( - "context" - "os" - "path/filepath" - "testing" - "time" - - "github.com/1lck/Lithe-IDEA/desktop/internal/core" -) - -func TestAICredentialLocatorResolution(t *testing.T) { - texts := map[string]string{ - "auth": `{"OPENAI_API_KEY":"fixture-secret","nested":{"key":"nested-secret"}}`, - "config": "model = 'fixture'\n", - } - environment := map[string]string{"COMPANY_KEY": "environment-secret"} - value, err := resolveAICredential(texts, environment, &core.AIConfigurationCredential{Kind: "file", File: "auth", Path: []string{"OPENAI_API_KEY"}}) - if err != nil || value != "fixture-secret" { - t.Fatalf("auth locator = %q, %v", value, err) - } - value, err = resolveAICredential(texts, environment, &core.AIConfigurationCredential{Kind: "file", File: "auth", Path: []string{"nested", "key"}}) - if err != nil || value != "nested-secret" { - t.Fatalf("nested locator = %q, %v", value, err) - } - value, err = resolveAICredential(texts, environment, &core.AIConfigurationCredential{Kind: "environment", Name: "COMPANY_KEY"}) - if err != nil || value != "environment-secret" { - t.Fatalf("environment locator = %q, %v", value, err) - } - if _, err := resolveAICredential(texts, environment, &core.AIConfigurationCredential{Kind: "file", File: "config", Path: []string{"experimental_bearer_token"}}); err == nil { - t.Fatal("a TOML file locator must be reported as unsupported") - } - if _, err := resolveAICredential(texts, environment, &core.AIConfigurationCredential{Kind: "file", File: "auth", Path: []string{"missing"}}); err == nil { - t.Fatal("a missing JSON path must fail") - } -} - -// fileAIKernel uses the real Core parser with files the test writes. -type fileAIKernel struct { - client *core.Client - files []core.AIConfigurationFile -} - -func (k fileAIKernel) AIConfigurationSources(_ context.Context, source, _ string, _ map[string]string) ([]core.AIConfigurationFile, error) { - if source != "codex" { - return nil, nil - } - return k.files, nil -} - -func (k fileAIKernel) ParseAIConfiguration(ctx context.Context, request core.AIConfigurationParseRequest) (*core.AIConfiguration, error) { - return k.client.ParseAIConfiguration(ctx, request) -} - -func TestAIProviderDiscoveryUsesRealCoreParser(t *testing.T) { - directory := t.TempDir() - configPath := filepath.Join(directory, "config.toml") - authPath := filepath.Join(directory, "auth.json") - if err := os.WriteFile(configPath, []byte("model = 'fixture-model'\nmodel_provider = 'gateway'\n[model_providers.gateway]\nbase_url = 'https://example.test/v1'\nrequires_openai_auth = true\n"), 0o600); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(authPath, []byte(`{"OPENAI_API_KEY":"fixture-file-secret"}`), 0o600); err != nil { - t.Fatal(err) - } - app := &App{aiKernel: fileAIKernel{client: core.NewClient(), files: []core.AIConfigurationFile{ - {File: "config", Path: configPath}, - {File: "auth", Path: authPath}, - }}} - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - providers := app.discoverAIProviders(ctx) - if len(providers["codex"]) != 1 || len(providers["claude"]) != 0 { - t.Fatalf("providers = %d codex, %d claude; want one Codex provider", len(providers["codex"]), len(providers["claude"])) - } - provider := providers["codex"][0] - if provider.Issue != "" || provider.Endpoint != "https://example.test/v1" || provider.Model != "fixture-model" || - provider.Protocol != "responses" || provider.APIKey != "fixture-file-secret" { - t.Fatalf("provider issue=%q endpoint=%q model=%q protocol=%q keyPresent=%v", provider.Issue, provider.Endpoint, provider.Model, provider.Protocol, provider.APIKey != "") - } - if _, ok := pickAIProvider(providers); !ok { - t.Fatal("the discovered provider is not usable for generation") - } -} diff --git a/desktop/internal/workbench/aicommit.go b/desktop/internal/workbench/aicommit.go index c0eec124fe..ebee092c73 100644 --- a/desktop/internal/workbench/aicommit.go +++ b/desktop/internal/workbench/aicommit.go @@ -2,30 +2,19 @@ package workbench import ( "context" - "encoding/json" "errors" "strings" - "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/ai" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/vivaui/viva/text" "github.com/vivaui/viva/ui" ) // This file is the Commit panel's "generate message" action (matrix id ai-commit-generation). -// Core owns the evidence (git.commitMessageContext), the request plan (ai.planCommit) and the -// decoding (ai.decodeCommitMessage); this file only picks the provider and its credential from -// the Codex or Claude configuration, makes the HTTP call, and puts the answer in the message -// field. A generation never stages, commits or pushes: its result is a draft. - -// aiCommitKernel is the part of the kernel the generation uses. *core.Client implements it; a -// kernel that does not (a test double) turns the button off. -type aiCommitKernel interface { - CommitMessageContext(ctx context.Context, mode string, repositories []core.CommitContextRepository, maximumDiffCharacters int) (core.CommitContextEvidence, error) - CommitMessageContextIsCurrent(ctx context.Context, mode string, repositories []core.CommitContextRepository, token string) (bool, error) - AIPlanCommit(ctx context.Context, provider core.AICommitProvider, options core.AICommitOptions, files []core.AICommitFile) (core.AIHTTPRequest, error) - AIDecodeCommitMessage(ctx context.Context, protocol string, response json.RawMessage, includeBody bool) (string, error) -} +// The ai package runs the generation with Core; this file keeps the panel's state, hands the +// staged changes of the active ChangeList to it and puts the answer in the message field. A +// generation never stages, commits or pushes: its result is a draft. // aiCommitState is what the commit area keeps of a generation. type aiCommitState struct { @@ -39,12 +28,12 @@ type aiCommitState struct { // token and repositories are the evidence the pending message was generated from; they // are checked again before it replaces the typed text. token string - repositories []core.CommitContextRepository + repositories []ai.ContextRepository } // aiCommitOptions are the options of a generation: the language, the body and the instructions -// the settings chose, and the shared defaults of the contract for the rest. -func (a *App) aiCommitOptions() core.AICommitOptions { +// the settings chose. +func (a *App) aiCommitOptions() ai.CommitOptions { generation := a.aiGenerationSettings() language := "english" if a.language() == i18n.Chinese { @@ -53,91 +42,44 @@ func (a *App) aiCommitOptions() core.AICommitOptions { if generation.Language != "" { language = generation.Language } - return core.AICommitOptions{ - Language: language, Format: "conventional", SubjectMaximumLength: 72, - MaximumDiffCharacters: 32000, ReasoningEffort: "default", IncludeBody: generation.IncludeBody, - CustomInstructions: strings.TrimSpace(generation.CustomInstructions), - } + return ai.NewCommitOptions(language, generation.IncludeBody, strings.TrimSpace(generation.CustomInstructions)) } // canGenerateCommit reports that the button may start a generation. func (a *App) canGenerateCommit(p *project) bool { - _, ok := a.kernel.(aiCommitKernel) c := &p.commit - return ok && a.aiKernelReady() && p.git.isRepository() && !c.busy && !c.ai.running && c.review == nil && + return a.aiKernelReady() && p.git.isRepository() && !c.busy && !c.ai.running && c.review == nil && p.listsReady() && p.activeStagedCount() > 0 && !p.otherStaged() } // stagedCommitRepositories are the repositories and staged files the generation reads, // matching what a commit takes: the staged changes of the active ChangeList. -func (p *project) stagedCommitRepositories() []core.CommitContextRepository { - var files []core.CommitContextFile +func (p *project) stagedCommitRepositories() []ai.ContextRepository { + var files []ai.ContextFile for _, change := range p.activeChanges() { if !change.Staged { continue } - files = append(files, core.CommitContextFile{Path: change.Path, OriginalPath: change.OriginalPath, ChangeKind: stagedChangeKind(change.Status)}) - } - return []core.CommitContextRepository{{Root: p.git.repositoryRoot(p.root), Files: files}} -} - -// stagedChangeKind names the index side of a porcelain status for Core. -func stagedChangeKind(status string) string { - if status == "" { - return "modified" - } - switch status[0] { - case 'A': - return "added" - case 'D': - return "deleted" - case 'R': - return "renamed" - case 'C': - return "copied" - case 'U': - return "unmerged" - } - return "modified" -} - -// pickAIProvider is the first provider of the Codex then the Claude configuration that can -// be used: it has no issue and holds a credential. -func pickAIProvider(providers map[string][]aiProvider) (aiProvider, bool) { - return pickAIProviderFrom(providers, aiProviderSources()) -} - -// pickAIProviderFrom is pickAIProvider over the given sources in their order. -func pickAIProviderFrom(providers map[string][]aiProvider, sources []string) (aiProvider, bool) { - for _, source := range sources { - for _, provider := range providers[source] { - if provider.Issue == "" && !provider.MissingKey && provider.APIKey != "" && provider.Endpoint != "" { - return provider, true - } - } + files = append(files, ai.ContextFile{Path: change.Path, OriginalPath: change.OriginalPath, ChangeKind: ai.StagedChangeKind(change.Status)}) } - return aiProvider{}, false + return []ai.ContextRepository{{Root: p.git.repositoryRoot(p.root), Files: files}} } -// errAINoProvider reports that no configured provider can be used. -var errAINoProvider = errors.New("no AI provider") - // generateCommitMessage starts a generation for the staged changes. func (a *App) generateCommitMessage(p *project) { - kernel, ok := a.kernel.(aiCommitKernel) c := &p.commit - if !ok || !a.canGenerateCommit(p) { + if !a.canGenerateCommit(p) { return } a.performed("ai.commitMessage", surfaceButton) ctx, cancel := context.WithCancel(p.ctx) c.ai.running, c.ai.cancel = true, cancel - repositories := p.stagedCommitRepositories() + kernel, repositories := a.aiKernel, p.stagedCommitRepositories() options := a.aiCommitOptions() sources := a.aiGenerationSources() a.background(p, 0, func(context.Context) func(*App) { defer cancel() - message, token, err := a.runCommitGeneration(ctx, kernel, repositories, options, sources) + message, token, err := ai.GenerateCommitMessage(ctx, kernel, repositories, options, sources) return func(a *App) { c.ai.running, c.ai.cancel = false, nil a.finishCommitGeneration(p, message, token, repositories, err) @@ -145,52 +87,9 @@ func (a *App) generateCommitMessage(p *project) { }) } -// runCommitGeneration captures the evidence, plans and sends the request and decodes the -// answer. It runs off the window thread. -func (a *App) runCommitGeneration(ctx context.Context, kernel aiCommitKernel, repositories []core.CommitContextRepository, options core.AICommitOptions, sources []string) (string, string, error) { - providers := a.discoverAIProviders(ctx) - provider, ok := pickAIProviderFrom(providers, sources) - if !ok { - return "", "", errAINoProvider - } - evidence, err := kernel.CommitMessageContext(ctx, "staged", repositories, options.MaximumDiffCharacters) - if err != nil { - return "", "", err - } - plan, err := kernel.AIPlanCommit(ctx, core.AICommitProvider{ - ID: provider.Source, Name: provider.Name, Endpoint: provider.Endpoint, Model: provider.Model, - APIProtocol: provider.Protocol, Authentication: provider.Authentication, Source: provider.Source, RequiresAPIKey: true, - }, options, evidence.Files) - if err != nil { - return "", "", err - } - answer, err := aiPost(ctx, plan.URL, aiHeaders(provider.Protocol, provider.Authentication, provider.APIKey), plan.Body) - if err != nil { - return "", "", err - } - if !json.Valid(answer) { - return "", "", errors.New("AI_COMMIT_INVALID_RESPONSE") - } - message, err := kernel.AIDecodeCommitMessage(ctx, provider.Protocol, answer, options.IncludeBody) - if err != nil { - return "", "", err - } - current, err := kernel.CommitMessageContextIsCurrent(ctx, "staged", repositories, evidence.Token) - if err != nil { - return "", "", err - } - if !current { - return "", "", errAIStale - } - return message, evidence.Token, nil -} - -// errAIStale reports that the staged changes moved while the message was generated. -var errAIStale = errors.New("staged changes changed") - // finishCommitGeneration applies a generated message, or reports why there is none. The // message replaces an empty field at once and a typed one only after the user confirms. -func (a *App) finishCommitGeneration(p *project, message, token string, repositories []core.CommitContextRepository, err error) { +func (a *App) finishCommitGeneration(p *project, message, token string, repositories []ai.ContextRepository, err error) { c := &p.commit if err != nil { if errors.Is(err, context.Canceled) { @@ -211,15 +110,15 @@ func (a *App) finishCommitGeneration(p *project, message, token string, reposito // aiCommitFailure is the notification for a failed generation. func (a *App) aiCommitFailure(err error) string { t := a.text.AI.Commit - var status *aiHTTPError + var status *ai.HTTPError switch { - case errors.Is(err, errAINoProvider): + case errors.Is(err, ai.ErrNoProvider): return t.NoProvider - case errors.Is(err, errAIStale): + case errors.Is(err, ai.ErrStale): return t.Stale - case errors.Is(err, errAIResponseTooLarge): + case errors.Is(err, ai.ErrResponseTooLarge): return t.Failed(t.ResponseTooLarge) - case errors.Is(err, errAITimeout): + case errors.Is(err, ai.ErrTimeout): return t.Failed(t.Timeout) case errors.As(err, &status): return t.Failed(t.HTTPStatus(status.Status)) @@ -244,19 +143,19 @@ func (a *App) confirmGeneratedMessage(p *project, replace bool) { } pending, token, repositories := c.ai.pending, c.ai.token, c.ai.repositories c.ai.pending, c.ai.hasPending, c.ai.token, c.ai.repositories = "", false, "", nil - kernel, ok := a.kernel.(aiCommitKernel) - if !replace || !ok { + kernel := a.aiKernel + if !replace || kernel == nil { return } typed := c.message() a.background(p, gitTimeout, func(ctx context.Context) func(*App) { - current, err := kernel.CommitMessageContextIsCurrent(ctx, "staged", repositories, token) + current, err := kernel.CommitContextIsCurrent(ctx, "staged", repositories, token) return func(a *App) { switch { case err != nil: a.notifyError(a.aiCommitFailure(err)) case !current: - a.notifyError(a.aiCommitFailure(errAIStale)) + a.notifyError(a.aiCommitFailure(ai.ErrStale)) case c.message() != typed: // The user kept typing: the draft is theirs, not ours. default: diff --git a/desktop/internal/workbench/aicommit_http.go b/desktop/internal/workbench/aicommit_http.go deleted file mode 100644 index 2325935040..0000000000 --- a/desktop/internal/workbench/aicommit_http.go +++ /dev/null @@ -1,90 +0,0 @@ -package workbench - -import ( - "bytes" - "context" - "errors" - "io" - "net/http" - "time" -) - -// AI provider requests are made here, by the platform: Core only plans the request and -// decodes the answer. The limits follow Lithe-core-rust rust/contracts/ai-commit.md: a 45-second -// deadline, no redirects, no cookies, and a 2 MiB cap on the answer. -const ( - aiRequestTimeout = 45 * time.Second - aiResponseLimit = 2 << 20 -) - -var ( - errAIResponseTooLarge = errors.New("ai response too large") - errAITimeout = errors.New("ai request timed out") -) - -// aiHTTPError is a provider answer that was not a success. It carries the status only: -// the body can echo the request, which holds the user's code. -type aiHTTPError struct{ Status int } - -func (e *aiHTTPError) Error() string { return "AI_HTTP_" + http.StatusText(e.Status) } - -// aiHTTPClient never follows a redirect and keeps no cookies, so a credential cannot be -// forwarded to another host. -var aiHTTPClient = &http.Client{ - CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, -} - -// aiHeaders are the authentication headers of one provider request. The credential is -// attached here and nowhere else; it is never logged or returned. -func aiHeaders(protocol, authentication, key string) map[string]string { - headers := map[string]string{"Content-Type": "application/json"} - switch { - case authentication == "apiKey": - headers["x-api-key"] = key - default: - headers["Authorization"] = "Bearer " + key - } - if protocol == "anthropicMessages" { - headers["anthropic-version"] = "2023-06-01" - } - return headers -} - -// aiPost sends body to url and returns the answer, bounded to 2 MiB. -func aiPost(ctx context.Context, url string, headers map[string]string, body []byte) ([]byte, error) { - ctx, cancel := context.WithTimeout(ctx, aiRequestTimeout) - defer cancel() - request, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) - if err != nil { - return nil, err - } - for name, value := range headers { - request.Header.Set(name, value) - } - response, err := aiHTTPClient.Do(request) - if err != nil { - if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return nil, errAITimeout - } - if ctx.Err() != nil { - return nil, ctx.Err() - } - // The transport error can contain the URL; the caller reports the class only. - return nil, errors.New("AI_NETWORK_ERROR") - } - defer response.Body.Close() - if response.StatusCode < 200 || response.StatusCode > 299 { - return nil, &aiHTTPError{Status: response.StatusCode} - } - data, err := io.ReadAll(io.LimitReader(response.Body, aiResponseLimit+1)) - if err != nil { - if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return nil, errAITimeout - } - return nil, errors.New("AI_NETWORK_ERROR") - } - if len(data) > aiResponseLimit { - return nil, errAIResponseTooLarge - } - return data, nil -} diff --git a/desktop/internal/workbench/aicommit_test.go b/desktop/internal/workbench/aicommit_test.go deleted file mode 100644 index 445ad11364..0000000000 --- a/desktop/internal/workbench/aicommit_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package workbench - -import ( - "context" - "encoding/json" - "errors" - "io" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "github.com/1lck/Lithe-IDEA/desktop/internal/core" -) - -func TestStagedChangeKindUsesTheIndexSide(t *testing.T) { - for status, want := range map[string]string{"A ": "added", "M ": "modified", "MM": "modified", "D ": "deleted", "R ": "renamed", "C ": "copied", "UU": "unmerged", "": "modified"} { - if got := stagedChangeKind(status); got != want { - t.Errorf("%q = %q, want %q", status, got, want) - } - } -} - -func TestPickAIProviderNeedsACredential(t *testing.T) { - providers := map[string][]aiProvider{ - "codex": {{Endpoint: "https://a", MissingKey: true}}, - "claude": {{Endpoint: "https://b", APIKey: "k", Issue: ""}}, - } - got, ok := pickAIProvider(providers) - if !ok || got.Endpoint != "https://b" { - t.Fatalf("picked %#v %v", got, ok) - } - if _, ok := pickAIProvider(map[string][]aiProvider{"codex": {{Endpoint: "https://a", APIKey: "k", Issue: aiIssueCredential}}}); ok { - t.Fatal("a provider with an issue was picked") - } -} - -func TestAIHeadersFollowTheProviderAuthentication(t *testing.T) { - h := aiHeaders("anthropicMessages", "apiKey", "secret") - if h["x-api-key"] != "secret" || h["anthropic-version"] == "" || h["Authorization"] != "" { - t.Fatalf("headers = %v", h) - } - h = aiHeaders("responses", "bearer", "secret") - if h["Authorization"] != "Bearer secret" { - t.Fatalf("headers = %v", h) - } -} - -func TestAIPostBoundsTheAnswer(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/big": - _, _ = io.WriteString(w, strings.Repeat("x", aiResponseLimit+1)) - case "/redirect": - http.Redirect(w, r, "/ok", http.StatusFound) - case "/error": - http.Error(w, "echoed secret body", http.StatusUnauthorized) - default: - if r.Header.Get("Authorization") != "Bearer k" { - http.Error(w, "no", http.StatusForbidden) - return - } - _, _ = io.WriteString(w, `{"ok":true}`) - } - })) - defer server.Close() - ctx := context.Background() - headers := map[string]string{"Authorization": "Bearer k"} - if data, err := aiPost(ctx, server.URL+"/ok", headers, []byte(`{}`)); err != nil || string(data) != `{"ok":true}` { - t.Fatalf("ok = %q %v", data, err) - } - if _, err := aiPost(ctx, server.URL+"/big", headers, nil); !errors.Is(err, errAIResponseTooLarge) { - t.Fatalf("big = %v", err) - } - var status *aiHTTPError - if _, err := aiPost(ctx, server.URL+"/redirect", headers, nil); !errors.As(err, &status) || status.Status != http.StatusFound { - t.Fatalf("redirect was followed or hidden: %v", err) - } - if _, err := aiPost(ctx, server.URL+"/error", headers, nil); !errors.As(err, &status) || strings.Contains(err.Error(), "secret") { - t.Fatalf("error = %v", err) - } - cancelled, cancel := context.WithCancel(ctx) - cancel() - if _, err := aiPost(cancelled, server.URL+"/ok", headers, nil); !errors.Is(err, context.Canceled) { - t.Fatalf("cancelled = %v", err) - } -} - -// The plan Core makes for a staged diff is sent to the provider with the credential attached -// by this package only, and the answer decodes to the message. -func TestCommitGenerationRoundTripThroughCore(t *testing.T) { - var gotAuth, gotBody string - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotAuth = r.Header.Get("Authorization") - data, _ := io.ReadAll(r.Body) - gotBody = string(data) - _, _ = io.WriteString(w, `{"choices":[{"message":{"content":"feat: add thing"}}]}`) - })) - defer server.Close() - client := core.NewClient() - ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) - defer cancel() - n := len("+x") - plan, err := client.AIPlanCommit(ctx, core.AICommitProvider{ - ID: "codex", Name: "t", Endpoint: server.URL, Model: "m", APIProtocol: "chatCompletions", - Authentication: "bearer", Source: "codex", RequiresAPIKey: true, AllowsInsecureHTTP: true, - }, core.AICommitOptions{Language: "english", Format: "conventional", SubjectMaximumLength: 72, MaximumDiffCharacters: 32000, ReasoningEffort: "default"}, - []core.AICommitFile{{Path: "a.go", ChangeKind: "added", Diff: "+x", OriginalCharacters: &n}}) - if err != nil { - t.Fatal(err) - } - if strings.Contains(string(plan.Body), "Bearer") { - t.Fatal("the plan carries a credential") - } - answer, err := aiPost(ctx, plan.URL, aiHeaders("chatCompletions", "bearer", "k"), plan.Body) - if err != nil { - t.Fatal(err) - } - message, err := client.AIDecodeCommitMessage(ctx, "chatCompletions", json.RawMessage(answer), false) - if err != nil || message != "feat: add thing" || gotAuth != "Bearer k" || !strings.Contains(gotBody, "a.go") { - t.Fatalf("message=%q err=%v auth=%q", message, err, gotAuth) - } -} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 2de2451a84..b3647953dc 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -26,6 +26,7 @@ import ( "sync/atomic" "time" + "github.com/1lck/Lithe-IDEA/desktop/internal/ai" "github.com/1lck/Lithe-IDEA/desktop/internal/buildinfo" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/documentio" @@ -220,10 +221,10 @@ type Options struct { // PluginRoot is the directory installed plugin packages live in. Empty asks // pluginpkg.DefaultRoot, which is the platform's own data directory. PluginRoot string - // AIKernel discovers the providers of commit message generation and inline edits from - // the user's Codex and Claude configuration. nil leaves AI generation unavailable - // instead of refusing to start. - AIKernel AIKernel + // AIKernel runs AI generation (the ai package): the commit message, the inline edit and + // the pull request description, with the providers of the user's Codex and Claude + // configuration. nil leaves AI generation unavailable instead of refusing to start. + AIKernel ai.Kernel // PluginInitializeTimeout bounds every plugin backend's startup handshake. // Zero keeps Core's default. Host tests whose fixture is a copy of the large // instrumented test binary raise it so scheduler load cannot masquerade as @@ -530,9 +531,8 @@ type App struct { // pluginServerMu guards the language-server maps because a build provider // may attach to a shared session from a background model load. pluginServerMu sync.Mutex - // aiKernel discovers AI generation providers (ai_provider.go), nil when the window was - // built without one. - aiKernel AIKernel + // aiKernel runs AI generation (ai_generation.go), nil when the window was built without one. + aiKernel ai.Kernel // inline is the editor's AI inline edit dialog (inlineedit.go). inline inlineEditState // ideAPIBridgeState lets the IDE Connection settings page reach the open project (settings_ide_api.go). diff --git a/desktop/internal/workbench/github_create.go b/desktop/internal/workbench/github_create.go index f3365fdefa..1c9d2a0807 100644 --- a/desktop/internal/workbench/github_create.go +++ b/desktop/internal/workbench/github_create.go @@ -6,6 +6,7 @@ import ( "errors" "strings" + "github.com/1lck/Lithe-IDEA/desktop/internal/ai" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/githubapi" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" @@ -204,23 +205,19 @@ func (a *App) generatePullRequestDescription(p *project) { cr := &a.prCreate client := a.githubAPI() token := a.githubToken() - kernel, ok := a.kernel.(interface { - AIPlanPullRequest(ctx context.Context, provider core.AICommitProvider, options core.AIPullRequestOptions, comparison core.PullRequestComparison) (core.AIHTTPRequest, error) - AIDecodePullRequest(ctx context.Context, protocol string, response json.RawMessage) (string, string, error) - }) - if !ok || client == nil || token == "" || cr.repo == nil || cr.generating || cr.base == "" || cr.head == "" || !a.aiKernelReady() { + kernel := a.aiKernel + if kernel == nil || client == nil || token == "" || cr.repo == nil || cr.generating || cr.base == "" || cr.head == "" { return } repo, base, head := *cr.repo, cr.base, cr.head cr.generating, cr.err = true, "" a.performed("ai.pullRequestDescription", surfaceButton) - options := a.aiCommitOptions() + options := ai.PullRequestOptionsFor(a.aiCommitOptions()) sources := a.aiGenerationSources() a.background(p, aiRequestTimeoutPR, func(ctx context.Context) func(*App) { - providers := a.discoverAIProviders(ctx) - provider, found := pickAIProviderFrom(providers, sources) - if !found { - return a.finishPullRequestDraft("", "", errAINoProvider) + provider, err := ai.Choose(ctx, kernel, sources) + if err != nil { + return a.finishPullRequestDraft("", "", err) } raw, err := client.Do(ctx, core.GitHubRequest{Operation: "compareBranches", Repository: &repo, Base: base, Head: head}, token) var comparison githubapi.Comparison @@ -230,32 +227,18 @@ func (a *App) generatePullRequestDescription(p *project) { if err != nil { return a.finishPullRequestDraft("", "", err) } - plan, err := kernel.AIPlanPullRequest(ctx, core.AICommitProvider{ - ID: provider.Source, Name: provider.Name, Endpoint: provider.Endpoint, Model: provider.Model, - APIProtocol: provider.Protocol, Authentication: provider.Authentication, Source: provider.Source, RequiresAPIKey: true, - }, core.AIPullRequestOptions{ - Language: options.Language, Format: "standard", MaximumDiffCharacters: options.MaximumDiffCharacters, - ReasoningEffort: options.ReasoningEffort, - }, comparisonForCore(repo, base, head, comparison)) - if err != nil { - return a.finishPullRequestDraft("", "", err) - } - answer, err := aiPost(ctx, plan.URL, aiHeaders(provider.Protocol, provider.Authentication, provider.APIKey), plan.Body) - if err != nil { - return a.finishPullRequestDraft("", "", err) - } - title, description, err := kernel.AIDecodePullRequest(ctx, provider.Protocol, answer) + title, description, err := ai.DraftPullRequest(ctx, kernel, provider, options, comparisonForCore(repo, base, head, comparison)) return a.finishPullRequestDraft(title, description, err) }) } // aiRequestTimeoutPR bounds a whole draft: the comparison, the provider call and the decode. -const aiRequestTimeoutPR = aiRequestTimeout +const aiRequestTimeoutPR = ai.RequestTimeout // comparisonForCore is the comparison Core plans from: the repository as owner/name, the branches, // the commit messages, and each file with its patch (an empty patch for a file without one). -func comparisonForCore(repo core.GitHubRepo, base, head string, comparison githubapi.Comparison) core.PullRequestComparison { - out := core.PullRequestComparison{Repository: repo.Owner + "/" + repo.Name, Base: base, Head: head} +func comparisonForCore(repo core.GitHubRepo, base, head string, comparison githubapi.Comparison) ai.PullRequestComparison { + out := ai.PullRequestComparison{Repository: repo.Owner + "/" + repo.Name, Base: base, Head: head} for _, commit := range comparison.Commits { out.CommitMessages = append(out.CommitMessages, commit.Message) } @@ -264,7 +247,7 @@ func comparisonForCore(repo core.GitHubRepo, base, head string, comparison githu if file.Patch != nil { diff = *file.Patch } - out.Files = append(out.Files, core.PullRequestComparisonFile{Path: file.Path, ChangeKind: file.Status, Diff: diff}) + out.Files = append(out.Files, ai.PullRequestFile{Path: file.Path, ChangeKind: file.Status, Diff: diff}) } return out } @@ -290,7 +273,7 @@ func (a *App) finishPullRequestDraft(title, description string, err error) func( // aiPullRequestFailure is the text a failed description draft shows. func aiPullRequestFailure(language i18n.Language, err error) string { - if errors.Is(err, errAINoProvider) { + if errors.Is(err, ai.ErrNoProvider) { return i18n.Shared(language, "desktop.github.draftNoProvider") } return i18n.SharedFormat(language, "desktop.github.draftFailed", map[string]string{"reason": err.Error()}) diff --git a/desktop/internal/workbench/inlinediff_test.go b/desktop/internal/workbench/inlinediff_test.go index b889f514a0..537c6a57f0 100644 --- a/desktop/internal/workbench/inlinediff_test.go +++ b/desktop/internal/workbench/inlinediff_test.go @@ -2,9 +2,7 @@ package workbench import ( "errors" - "strings" "testing" - "unicode/utf8" ) func TestLineDiffMarksOnlyWhatChanged(t *testing.T) { @@ -23,18 +21,6 @@ func TestLineDiffMarksOnlyWhatChanged(t *testing.T) { } } -func TestInlineContextNeverSplitsACharacter(t *testing.T) { - text := []byte(strings.Repeat("é", inlineEditWindow) + "SEL" + strings.Repeat("世", inlineEditWindow)) - start := len(strings.Repeat("é", inlineEditWindow)) - before, after := inlineContext(text, start, start+3) - if !utf8.ValidString(before) || !utf8.ValidString(after) { - t.Fatal("the context splits a character") - } - if len([]rune(before)) < 12000 || len([]rune(after)) < 12000 { - t.Fatalf("context is shorter than Core keeps: %d, %d", len([]rune(before)), len([]rune(after))) - } -} - func TestInlineEditCodeIsExtractedFromCoreErrors(t *testing.T) { err := errors.New("lithe core: ai.inlineEdit.plan: AI_INLINE_EDIT_MODEL_MISSING (invalid_request)") if got := inlineEditCode.FindString(err.Error()); got != "AI_INLINE_EDIT_MODEL_MISSING" { diff --git a/desktop/internal/workbench/inlineedit.go b/desktop/internal/workbench/inlineedit.go index 3bfcc1e92b..85290fa06b 100644 --- a/desktop/internal/workbench/inlineedit.go +++ b/desktop/internal/workbench/inlineedit.go @@ -2,32 +2,19 @@ package workbench import ( "context" - "encoding/json" "errors" "regexp" - "unicode/utf8" - "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/ai" "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" "github.com/vivaui/viva/ui" ) // This file is the editor's AI inline edit (matrix id ai-inline-edit): the user selects code, -// asks for a change, reviews a diff and accepts or rejects it. Core plans the request -// (ai.inlineEdit.plan) and decodes the answer (ai.inlineEdit.decode); this file picks the -// provider and credential from the Codex or Claude configuration, makes the HTTP call and -// applies an accepted edit as one undoable step. Nothing is applied before the user accepts, -// and nothing is applied if the file changed in the meantime. - -// inlineEditWindow is how many bytes of context are read on each side of the selection. Core -// keeps 12,000 Unicode scalars of them; a scalar is at most 4 bytes. -const inlineEditWindow = 48_000 - -// aiInlineKernel is the part of the kernel an inline edit uses. -type aiInlineKernel interface { - AIInlineEditPlan(ctx context.Context, provider core.AIInlineEditProvider, model core.AIInlineEditModel, edit core.AIInlineEdit) (core.AIInlineEditPlan, error) - AIInlineEditDecode(ctx context.Context, wireProtocol string, response json.RawMessage) (string, error) -} +// asks for a change, reviews a diff and accepts or rejects it. The ai package sends the +// request with Core; this file keeps the dialog's state and applies an accepted edit as one +// undoable step. Nothing is applied before the user accepts, and nothing is applied if the file +// changed in the meantime. // inlineEditState is the open inline edit, if any. type inlineEditState struct { @@ -61,7 +48,7 @@ var inlineEditCode = regexp.MustCompile(`AI_INLINE_EDIT_[A-Z_]+`) // requestInlineEdit opens the inline edit on the selection of the document that has the // keyboard. A missing selection or a read-only file is reported and nothing opens. func (a *App) requestInlineEdit(p *project, view *editorview.View) { - if _, ok := a.kernel.(aiInlineKernel); !ok || !a.aiKernelReady() || a.inline.open { + if !a.aiKernelReady() || a.inline.open { return } var doc *document @@ -99,29 +86,16 @@ func (a *App) requestInlineEdit(p *project, view *editorview.View) { *s = inlineEditState{open: true, doc: doc, start: start, end: end, selected: string(text[start:end]), revision: view.Revision(), currentLine: currentLine} } -// inlineContext is the text around the selection, cut at character boundaries. -func inlineContext(text []byte, start, end int) (before, after string) { - from := max(0, start-inlineEditWindow) - for from < start && !utf8.RuneStart(text[from]) { - from++ - } - to := min(len(text), end+inlineEditWindow) - for to > end && to < len(text) && !utf8.RuneStart(text[to]) { - to-- - } - return string(text[from:start]), string(text[end:to]) -} - // runInlineEdit sends the request. The answer replaces any earlier result. func (a *App) runInlineEdit(p *project) { s := &a.inline - kernel, ok := a.kernel.(aiInlineKernel) - if !ok || s.running || s.doc == nil { + kernel := a.aiKernel + if kernel == nil || s.running || s.doc == nil { return } text, _ := s.doc.view.Text() - before, after := inlineContext(text, s.start, s.end) - edit := core.AIInlineEdit{ + before, after := ai.InlineContext(text, s.start, s.end) + edit := ai.InlineEdit{ BeforeSelection: before, SelectedText: s.selected, AfterSelection: after, Instruction: s.instruction.Text(), FilePath: s.doc.path, LanguageID: s.doc.languageID, } @@ -130,7 +104,7 @@ func (a *App) runInlineEdit(p *project) { sources := a.inlineEditSources() a.background(p, 0, func(context.Context) func(*App) { defer cancel() - edited, err := a.fetchInlineEdit(ctx, kernel, edit, sources) + edited, err := ai.EditInline(ctx, kernel, edit, sources) return func(a *App) { s := &a.inline s.running, s.cancel = false, nil @@ -156,53 +130,17 @@ func (a *App) inlineEditSources() []string { return a.aiGenerationSources() } -// fetchInlineEdit plans, sends and decodes one request off the window thread. -func (a *App) fetchInlineEdit(ctx context.Context, kernel aiInlineKernel, edit core.AIInlineEdit, sources []string) (string, error) { - providers := a.discoverAIProviders(ctx) - provider, ok := pickAIProviderFrom(providers, sources) - if !ok { - return "", errAINoProvider - } - model := core.AIInlineEditModel{ID: provider.Model, Listing: "unlisted"} - plan, err := kernel.AIInlineEditPlan(ctx, core.AIInlineEditProvider{ - WireProtocol: provider.Protocol, Endpoint: provider.Endpoint, RequiresAPIKey: true, - AcceptsUnlistedModels: true, ChatTokenLimitField: "max_completion_tokens", - }, model, edit) - if err != nil { - return "", err - } - headers := map[string]string{"Content-Type": "application/json"} - for name, value := range plan.Headers { - headers[name] = value - } - if plan.Credential.Required { - value := provider.APIKey - if plan.Credential.Scheme == "bearer" { - value = "Bearer " + value - } - headers[plan.Credential.Header] = value - } - answer, err := aiPost(ctx, plan.URL, headers, plan.Body) - if err != nil { - return "", err - } - if !json.Valid(answer) { - return "", errors.New("AI_INLINE_EDIT_INVALID_RESPONSE") - } - return kernel.AIInlineEditDecode(ctx, provider.Protocol, answer) -} - // inlineEditFailure is the notice for a failed request: a stable code or a status, never a // response body or the request. func (a *App) inlineEditFailure(err error) string { t, c := a.text.AI.InlineEdit, a.text.AI.Commit - var status *aiHTTPError + var status *ai.HTTPError switch { - case errors.Is(err, errAINoProvider): + case errors.Is(err, ai.ErrNoProvider): return c.NoProvider - case errors.Is(err, errAIResponseTooLarge): + case errors.Is(err, ai.ErrResponseTooLarge): return t.Failed(c.ResponseTooLarge) - case errors.Is(err, errAITimeout): + case errors.Is(err, ai.ErrTimeout): return t.Failed(c.Timeout) case errors.As(err, &status): return t.Failed(c.HTTPStatus(status.Status)) diff --git a/desktop/internal/workbench/startup.go b/desktop/internal/workbench/startup.go index a6689b45dd..cd299b4219 100644 --- a/desktop/internal/workbench/startup.go +++ b/desktop/internal/workbench/startup.go @@ -1,6 +1,7 @@ package workbench import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/ai" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/store" ) @@ -9,5 +10,5 @@ import ( // explicit Options to isolate a surface, but the executable shares one Core // client between application, logging, plugin and AI adapters. func DesktopOptions(client *core.Client, preferences *store.Store, version string) Options { - return Options{Kernel: client, PluginKernel: client, Store: preferences, LogKernel: client, Version: version, AIKernel: CoreAIKernel{Client: client}} + return Options{Kernel: client, PluginKernel: client, Store: preferences, LogKernel: client, Version: version, AIKernel: ai.NewClient(client)} } diff --git a/docs/viva-migration.md b/docs/viva-migration.md index e963c49214..1480ea4ffd 100644 --- a/docs/viva-migration.md +++ b/docs/viva-migration.md @@ -460,7 +460,7 @@ MCP 管理随 Agent 对话失去消费者后,本轮整块删除,后续重新 ## 放弃:Agent 对话(38 项,2026-11-12 用户决定) -用户决定 Viva 桌面端不做 Agent 对话。#1799 删除了助手面板、会话与历史、卡片、Agent 安装与管理、自定义 Agent,以及 AI 设置下的 Agents、Instructions、Skills、Hooks、MCP 配置页。保留 AI 生成提交信息(`ai-commit-generation`)、编辑器内联 AI 编辑(`ai-inline-edit`)和 IDE 连接(`ide-mcp-connection`),它们读取用户 Codex/Claude 配置的服务商发现移到 `desktop/internal/workbench/ai_provider.go`。Rust Core 中的 Agent 代码与 `shared/fixtures/agent`、`shared/fixtures/mcp` 契约当时暂留,随后 Agent 代码由 Lithe-core-rust#18 删除,MCP 契约由 #19 删除;本仓库的 `shared/fixtures/agent` 与 `shared/contracts/agent-turn-policy.json` 在 #1853 删除整个 `shared/contracts`、`shared/fixtures` 副本时一并删除。 +用户决定 Viva 桌面端不做 Agent 对话。#1799 删除了助手面板、会话与历史、卡片、Agent 安装与管理、自定义 Agent,以及 AI 设置下的 Agents、Instructions、Skills、Hooks、MCP 配置页。保留 AI 生成提交信息(`ai-commit-generation`)、编辑器内联 AI 编辑(`ai-inline-edit`)和 IDE 连接(`ide-mcp-connection`),它们读取用户 Codex/Claude 配置的服务商发现先移到 `desktop/internal/workbench`,2026-11-14 起与 Core AI 命令封装、HTTP 请求和生成流程一起放在独立的 Go 包 `desktop/internal/ai`。Rust Core 中的 Agent 代码与 `shared/fixtures/agent`、`shared/fixtures/mcp` 契约当时暂留,随后 Agent 代码由 Lithe-core-rust#18 删除,MCP 契约由 #19 删除;本仓库的 `shared/fixtures/agent` 与 `shared/contracts/agent-turn-policy.json` 在 #1853 删除整个 `shared/contracts`、`shared/fixtures` 副本时一并删除。 第二轮清理删掉了只描述放弃能力的记录:`shared/i18n/` 里 593 条含 `agent` 的词条(唯一还被引用的 `agent.state.cancel` 改用通用 `ui.cancel`)、功能矩阵的 36 个 `agent-*.json` 条目(矩阵从 255 条降到 219 条),以及旧客户端 Agent 对话的 15 篇 Note(移入 `.agents/notes/archived/`)。下表保留为放弃清单,不再对应矩阵文件。 diff --git a/shared/platform-feature-matrix/features/ai-commit-generation.json b/shared/platform-feature-matrix/features/ai-commit-generation.json index 9f8bf0b431..10d2ff51b1 100644 --- a/shared/platform-feature-matrix/features/ai-commit-generation.json +++ b/shared/platform-feature-matrix/features/ai-commit-generation.json @@ -8,14 +8,15 @@ "verificationStatus": "pending", "evidence": [ "desktop/internal/workbench/aicommit.go", - "desktop/internal/workbench/aicommit_http.go", "desktop/internal/workbench/aicommit_view.go", - "desktop/internal/workbench/aicommit_test.go", - "desktop/internal/core/ai_generation.go", - "desktop/internal/core/ai_generation_test.go", + "desktop/internal/ai/commit.go", + "desktop/internal/ai/http.go", + "desktop/internal/ai/provider.go", + "desktop/internal/ai/configuration.go", + "desktop/internal/ai/commands_test.go", + "desktop/internal/ai/http_test.go", + "desktop/internal/ai/provider_test.go", "desktop/internal/i18n/ai_messages.go", - "desktop/internal/workbench/ai_provider.go", - "desktop/internal/workbench/ai_provider_test.go", "desktop/internal/settingswindow/ai_generation_view.go" ] }, @@ -24,20 +25,21 @@ "verificationStatus": "pending", "evidence": [ "desktop/internal/workbench/aicommit.go", - "desktop/internal/workbench/aicommit_http.go", "desktop/internal/workbench/aicommit_view.go", - "desktop/internal/workbench/aicommit_test.go", - "desktop/internal/core/ai_generation.go", - "desktop/internal/core/ai_generation_test.go", + "desktop/internal/ai/commit.go", + "desktop/internal/ai/http.go", + "desktop/internal/ai/provider.go", + "desktop/internal/ai/configuration.go", + "desktop/internal/ai/commands_test.go", + "desktop/internal/ai/http_test.go", + "desktop/internal/ai/provider_test.go", "desktop/internal/i18n/ai_messages.go", - "desktop/internal/workbench/ai_provider.go", - "desktop/internal/workbench/ai_provider_test.go", "desktop/internal/settingswindow/ai_generation_view.go" ] }, "owner": "Git / AI", "verification": "用相同 diff、规则和 Provider 配置比较请求计划、取消、错误和生成文本。 共享提交上下文的真实 Git 回归覆盖同路径重新暂存、未缓存工作区变化、截断外内容、多仓库同名文件、敏感重命名及目录展开;macOS 确认替换时再次核对并保留新输入,Windows 测试验证同一路径的内容变化和取消。两端原生完整界面验收仍为 pending。", - "notes": "2026-11-10:Viva Commit 面板新增“生成提交信息”按钮:Core 的 git.commitMessageContext(暂存区证据与状态令牌)、ai.planCommit、ai.decodeCommitMessage 经 desktop/internal/core 封装,Go 只从 Codex/Claude 本机配置选取首个带凭据的服务商、附加认证头并发起 HTTP(45 秒期限、不跟随重定向、响应 2 MiB 上限、错误不回显响应体),生成后再校验令牌;输入框已有文字时需确认替换并保留确认期间的新输入。生成永不暂存、提交或推送。未接入:设置页中的服务商选择与生成选项(语言、格式、长度、推理强度,当前用契约默认值)、手动服务商与密钥;真实供应商和原生界面验收仍为 pending。 2026-11-12:Agent 对话删除后,服务商发现移到 desktop/internal/workbench/ai_provider.go(只依赖 Core 的配置定位与解析),生成选项的设置页改为“设置 › AI › 生成”。", + "notes": "2026-11-10:Viva Commit 面板新增“生成提交信息”按钮:Core 的 git.commitMessageContext(暂存区证据与状态令牌)、ai.planCommit、ai.decodeCommitMessage 经 desktop/internal/core 封装,Go 只从 Codex/Claude 本机配置选取首个带凭据的服务商、附加认证头并发起 HTTP(45 秒期限、不跟随重定向、响应 2 MiB 上限、错误不回显响应体),生成后再校验令牌;输入框已有文字时需确认替换并保留确认期间的新输入。生成永不暂存、提交或推送。未接入:设置页中的服务商选择与生成选项(语言、格式、长度、推理强度,当前用契约默认值)、手动服务商与密钥;真实供应商和原生界面验收仍为 pending。 2026-11-12:Agent 对话删除后,服务商发现移到 desktop/internal/workbench/ai_provider.go(只依赖 Core 的配置定位与解析),生成选项的设置页改为“设置 › AI › 生成”。 2026-11-14:AI 代码移到独立 Go 包 desktop/internal/ai(Core AI 命令封装、Codex/Claude 服务商发现、HTTP 与生成流程),desktop/internal/core 不再含 AI 代码,workbench 只保留界面状态与本地化错误文案。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/ai-inline-edit.json b/shared/platform-feature-matrix/features/ai-inline-edit.json index 5c08a1487d..bf72d0140f 100644 --- a/shared/platform-feature-matrix/features/ai-inline-edit.json +++ b/shared/platform-feature-matrix/features/ai-inline-edit.json @@ -11,8 +11,9 @@ "desktop/internal/workbench/inlineedit_view.go", "desktop/internal/workbench/inlinediff.go", "desktop/internal/workbench/inlinediff_test.go", - "desktop/internal/core/ai_generation.go", - "desktop/internal/core/ai_generation_test.go" + "desktop/internal/ai/inline_edit.go", + "desktop/internal/ai/inline_edit_test.go", + "desktop/internal/ai/commands_test.go" ] }, "windows": { @@ -23,13 +24,14 @@ "desktop/internal/workbench/inlineedit_view.go", "desktop/internal/workbench/inlinediff.go", "desktop/internal/workbench/inlinediff_test.go", - "desktop/internal/core/ai_generation.go", - "desktop/internal/core/ai_generation_test.go" + "desktop/internal/ai/inline_edit.go", + "desktop/internal/ai/inline_edit_test.go", + "desktop/internal/ai/commands_test.go" ] }, "owner": "AI", "verification": "Windows:分别使用 OpenRouter、Anthropic、Gemini、Ollama 和自定义服务商对选区执行行内编辑,确认替换结果、缺少密钥/模型/地址时的本地化错误,以及输出被截断时不替换选区。", - "notes": "2026-11-10:Viva 编辑器选中代码后按 Cmd/Ctrl+K 打开 AI 行内编辑:输入指令,Core 的 ai.inlineEdit.plan 规划请求(上下文窗口取选区两侧各 48000 字节且不切开字符),Go 从 Codex/Claude 本机配置取首个带凭据的服务商并按 plan.credential 附加认证头、发起 HTTP(45 秒、不跟随重定向、2 MiB 上限、错误只显示状态码或稳定码),ai.inlineEdit.decode 解码后显示逐行差异,接受才作为一次可撤销编辑写入,选区文本已变化时拒绝应用,空替换需用户明确接受。未接入:模型选择器与服务商选择设置、手动服务商、选区浮动工具栏入口、AI 聊天中的行内编辑;真实供应商和原生窗口验收 pending。", + "notes": "2026-11-10:Viva 编辑器选中代码后按 Cmd/Ctrl+K 打开 AI 行内编辑:输入指令,Core 的 ai.inlineEdit.plan 规划请求(上下文窗口取选区两侧各 48000 字节且不切开字符),Go 从 Codex/Claude 本机配置取首个带凭据的服务商并按 plan.credential 附加认证头、发起 HTTP(45 秒、不跟随重定向、2 MiB 上限、错误只显示状态码或稳定码),ai.inlineEdit.decode 解码后显示逐行差异,接受才作为一次可撤销编辑写入,选区文本已变化时拒绝应用,空替换需用户明确接受。未接入:模型选择器与服务商选择设置、手动服务商、选区浮动工具栏入口、AI 聊天中的行内编辑;真实供应商和原生窗口验收 pending。 2026-11-14:AI 代码移到独立 Go 包 desktop/internal/ai(Core AI 命令封装、Codex/Claude 服务商发现、HTTP 与生成流程),desktop/internal/core 不再含 AI 代码,workbench 只保留界面状态与本地化错误文案。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/ai-pull-request-description.json b/shared/platform-feature-matrix/features/ai-pull-request-description.json index 89cd4dff4d..832455d97d 100644 --- a/shared/platform-feature-matrix/features/ai-pull-request-description.json +++ b/shared/platform-feature-matrix/features/ai-pull-request-description.json @@ -9,7 +9,7 @@ "evidence": [ "docs/viva-migration.md", "desktop/internal/workbench/github_create.go", - "desktop/internal/core/ai_pull_request.go" + "desktop/internal/ai/pull_request.go" ] }, "windows": { @@ -18,12 +18,12 @@ "evidence": [ "docs/viva-migration.md", "desktop/internal/workbench/github_create.go", - "desktop/internal/core/ai_pull_request.go" + "desktop/internal/ai/pull_request.go" ] }, "owner": "AI", "verification": "macOS:在测试仓库的新建 PR 页面生成描述,确认标题和描述同时填入、含敏感文件(如 credentials.json)的比较被拒绝、只返回标题的响应报错。Windows:使用 AI 提交服务商在新建 PR 页面生成草稿,确认使用本地 base...head 差异并报告本地化错误。", - "notes": "Viva:新建 PR 对话框填写标题、Markdown 描述、base/head 与是否草稿;可让已配置的 AI 提供方起草:GitHub 提供两分支的提交与补丁,Core 统一证据预算、敏感路径策略与提示词并严格解码标题和描述(ai.pullRequest.plan/decode),凭据与 HTTP 留在宿主;起草结果只是对话框文本,确认后才创建。未发布的分支或分离 HEAD 阻止创建,此处不提供发布分支。", + "notes": "Viva:新建 PR 对话框填写标题、Markdown 描述、base/head 与是否草稿;可让已配置的 AI 提供方起草:GitHub 提供两分支的提交与补丁,Core 统一证据预算、敏感路径策略与提示词并严格解码标题和描述(ai.pullRequest.plan/decode),凭据与 HTTP 留在宿主;起草结果只是对话框文本,确认后才创建。未发布的分支或分离 HEAD 阻止创建,此处不提供发布分支。 2026-11-14:AI 代码移到独立 Go 包 desktop/internal/ai(Core AI 命令封装、Codex/Claude 服务商发现、HTTP 与生成流程),desktop/internal/core 不再含 AI 代码,workbench 只保留界面状态与本地化错误文案。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { From 7f3699ecd39070dc3333fb29a048e717cc8e0c06 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 09:54:08 +0800 Subject: [PATCH 10/11] =?UTF-8?q?chore(desktop):=20Core=20=E5=9B=BA?= =?UTF-8?q?=E5=AE=9A=E5=88=B0=20Lithe-core-rust=20#30=20=E7=9A=84=20head?= =?UTF-8?q?=205efe90b?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #30 叠在 #28 上,提供本分支接入的宿主规则命令:gracefulStopRule、 代理 exclusionRules、git.changedFileGroups、工作树状态与 git.worktreeCreationPreview、plugins.installed.lifecycle、 editor.groupLayout.*、workspace.rowSelection.reduce 和 workspace.projectTree.rows。两者合入 main 后改成合并 commit。 --- scripts/desktop/build-desktop-core.sh | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 3383298b47..4ebe2e2ca4 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -28,9 +28,14 @@ native_path() { } PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" -# The head of Lithe-core-rust #28, not yet merged; replace it with the merge commit once #28 is -# in main. #28 splits 34 more crates out of lithe-core (46 in the workspace); command names, -# JSON, error codes and the C header are unchanged, except that a build system's +# The head of Lithe-core-rust #30, not yet merged, stacked on #28, not yet merged either; replace +# it with the merge commit once both are in main. #30 adds the host rules the desktop no longer +# keeps itself (processLifecycle gracefulStopRule, network.proxyPolicy exclusionRules, +# git.changedFileGroups, git.worktrees states and git.worktreeCreationPreview, +# plugins.installed.lifecycle, editor.groupLayout.*, workspace.rowSelection.reduce and +# workspace.projectTree.rows) in four new rule crates (50 in the workspace). #28 splits 34 +# more crates out of lithe-core (46 in the workspace); command names, JSON, error codes and the +# C header are unchanged, except that a build system's # source:"hostIntegration" is now refused as plugin.manifest.invalid. It is on top of #29 (cold # managed runtimes may finish LSP initialization), squash-merged into main, on top of # #27 (protocol, network, terminal, process, diff and github split into their own @@ -51,7 +56,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="d235401fa2d6a492f27beb45e0679be846d1b0a5" +PINNED_CORE_REVISION="5efe90b4c6adfb831c13c38059aab0c77c5b5263" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in From d666e855ae97215fae7498c262a94e54e5886bb5 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 14 Nov 2026 09:56:56 +0800 Subject: [PATCH 11/11] =?UTF-8?q?docs:=20=E5=8A=9F=E8=83=BD=E7=9F=A9?= =?UTF-8?q?=E9=98=B5=E5=92=8C=E9=A1=B9=E7=9B=AE=E6=A0=91=E7=AC=94=E8=AE=B0?= =?UTF-8?q?=E6=94=B9=E5=86=99=E4=B8=BA=E8=A7=84=E5=88=99=E5=B7=B2=E5=9C=A8?= =?UTF-8?q?=20Core?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 项目树、Diff 查找、Git 改动文件分组、工作树和代理排除项的说明还写着 “仍在 Go、下沉跟踪 #18xx”,改为现在由哪条 Core 命令计算。git-history 去掉“文件保持 Git 返回的顺序”,现在按自然顺序。 --- .../bug-fix/2026-10-05-project-tree-selection-and-moves.md | 5 +++-- shared/platform-feature-matrix/features/file-explorer.json | 2 +- shared/platform-feature-matrix/features/git-diff-review.json | 2 +- shared/platform-feature-matrix/features/git-history.json | 2 +- shared/platform-feature-matrix/features/git-worktrees.json | 2 +- .../features/network-proxy-settings.json | 2 +- 6 files changed, 8 insertions(+), 7 deletions(-) diff --git a/.agents/notes/implemented/bug-fix/2026-10-05-project-tree-selection-and-moves.md b/.agents/notes/implemented/bug-fix/2026-10-05-project-tree-selection-and-moves.md index 1f0eb96b39..e84bc40f55 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-05-project-tree-selection-and-moves.md +++ b/.agents/notes/implemented/bug-fix/2026-10-05-project-tree-selection-and-moves.md @@ -5,8 +5,9 @@ > 2026-11-08 Viva 迁移:本笔记记录的多选、批量移动和平台专属实现属于迁移前版本; > Viva 目前只接入目录单击选择、双击名称或点击箭头切换展开,以及方向键导航和选中项滚动到视口。 > 多选、批量移动、右键菜单和实机交互验收仍待完成,不能用下文旧测试证明已迁移。 -> 当前 Go 可见行投影和导航目标尚未下沉,跟踪 [#1800](https://github.com/1lck/Lithe-IDEA/issues/1800); -> 不得在界面层继续增加多选等共享规则。 +> 2026-11-14 起可见行、选择修正、视口顶端行和多选(普通、Cmd/Ctrl、Shift 点击与批量目标)由 Core 的 +> `workspace.projectTree.rows` 和 `workspace.rowSelection.reduce` 计算([#1800](https://github.com/1lck/Lithe-IDEA/issues/1800)), +> 规则见 `2026-10-19-lazy-project-tree.md`;不得在界面层再增加这类共享规则。 > 同一次目录批量请求失败只记录一次宿主错误,不复用 Core 拥有的目录跳过事件;Viva 日志 > 事件类型生成和静态使用门禁尚未恢复,跟踪 [#1802](https://github.com/1lck/Lithe-IDEA/issues/1802)。 diff --git a/shared/platform-feature-matrix/features/file-explorer.json b/shared/platform-feature-matrix/features/file-explorer.json index 1bff372121..a255c5394f 100644 --- a/shared/platform-feature-matrix/features/file-explorer.json +++ b/shared/platform-feature-matrix/features/file-explorer.json @@ -37,7 +37,7 @@ }, "owner": "Workspace", "verification": "macOS 和 Windows 无头测试覆盖目录选择、展开、键盘、虚拟绘制、长文件名滚动、外部新增删除、空目录变化、超过 128 个目录、隐藏路径过滤、视口锚定、过期读取以及与搜索共享监听的关闭和重试;真实 Core 测试覆盖共享自然排序样例及 Python 隐藏路径。运行 scripts/desktop/desktop-go.sh test -race ./internal/workbench -run 'TestProjectTree|TestProjectSearch|TestEverywhere' -count=3 和 scripts/desktop/desktop-go.sh test -race ./internal/core -run TestWorkspaceDirectory -count=3。完整文件树和原生窗口行为仍待验收。 标题栏按钮:运行 scripts/desktop/desktop-go.sh test ./internal/workbench -run 'TestProjectTree(Locate|ExpandsAndCollapses|ExpandAll|Refresh)' -count=1 和 scripts/desktop/desktop-go.sh test ./internal/treelist -count=1;实机打开深层文件后折叠祖先,点击定位确认展开、选中并滚动到中间,键盘焦点在该行;在超过 512 个目录的项目中全部展开出现提示;删除并恢复项目根目录后点击刷新恢复树。", - "notes": "Viva 接入 Core 按需列目录、单选、方向键及虚拟绘制;项目根节点(包括空项目)可显示和选择,树行尺寸与展开图标参照旧版,批量列目录失败只记录一次宿主错误;新增根节点和失败日志回归仅在 macOS 验证,Windows 待重跑。可见行投影及导航目标仍在 Go,Core 下沉跟踪 #1800,Viva 日志生成与使用门禁跟踪 #1802。macOS 和 Windows 用一个项目级递归监听,供项目树和搜索共用,事件经 Core 过滤,重读保持节点及视口锚点。Linux 暂用最多 128 个按需目录监听,超限提示。多选、批量移动、上下文菜单、完整旧版增量行为与平台差异仍需迁移,macOS 和 Windows 原生窗口、逐像素对照及大项目性能均待验收。 Project 标题栏有定位当前文件、刷新、全部展开、全部折叠四个按钮:定位逐级列出并展开祖先目录后选中、居中并聚焦目标行,路径不可见时放弃并记录 operation_rejected;刷新重读已展开目录,根目录读取失败时重新监听并读取;全部展开按广度优先最多打开 512 个目录,超出时提示;全部折叠保留根目录,被隐藏的选择移到其所在的顶层目录。项目树是 Viva 的 ui.Tree(只声明可见行,RowWidth 使行等宽于最长名称以横向滚动),行尺寸与文字色取自 desktop/internal/treelist,Git Log 改动文件共用。方向键只移动焦点环,选中行跟随点击、Enter 与箭头,待 Viva 提供 TreeState.RowID 后改为跟随焦点。", + "notes": "Viva 接入 Core 按需列目录、单选、方向键及虚拟绘制;项目根节点(包括空项目)可显示和选择,树行尺寸与展开图标参照旧版,批量列目录失败只记录一次宿主错误;新增根节点和失败日志回归仅在 macOS 验证,Windows 待重跑。2026-11-14 起可见行、选择修正、视口顶端行和多选由 Core 计算(workspace.projectTree.rows、workspace.rowSelection.reduce,#1800),树的形状变化时才调用,缩放和重绘不调用;Viva 日志生成与使用门禁跟踪 #1802。macOS 和 Windows 用一个项目级递归监听,供项目树和搜索共用,事件经 Core 过滤,重读保持节点及视口锚点。Linux 暂用最多 128 个按需目录监听,超限提示。多选、批量移动、上下文菜单、完整旧版增量行为与平台差异仍需迁移,macOS 和 Windows 原生窗口、逐像素对照及大项目性能均待验收。 Project 标题栏有定位当前文件、刷新、全部展开、全部折叠四个按钮:定位逐级列出并展开祖先目录后选中、居中并聚焦目标行,路径不可见时放弃并记录 operation_rejected;刷新重读已展开目录,根目录读取失败时重新监听并读取;全部展开按广度优先最多打开 512 个目录,超出时提示;全部折叠保留根目录,被隐藏的选择移到其所在的顶层目录。项目树是 Viva 的 ui.Tree(只声明可见行,RowWidth 使行等宽于最长名称以横向滚动),行尺寸与文字色取自 desktop/internal/treelist,Git Log 改动文件共用。方向键只移动焦点环,选中行跟随点击、Enter 与箭头,待 Viva 提供 TreeState.RowID 后改为跟随焦点。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/git-diff-review.json b/shared/platform-feature-matrix/features/git-diff-review.json index 6eda9306ac..ed0e3e6901 100644 --- a/shared/platform-feature-matrix/features/git-diff-review.json +++ b/shared/platform-feature-matrix/features/git-diff-review.json @@ -53,7 +53,7 @@ }, "owner": "Git", "verification": "验证新增、删除、重命名、二进制和多文件 Diff 的展示与定位;从源代码管理打开已修改和未跟踪文件的工作区 Diff 后保持静止,确认 Diff 不会自动关闭,且只在文件不再出现在 Git 状态中时关闭。 调整下方 Git Log 或终端高度时,上方 Diff 的全文测量、折叠和双栏规划不随尺寸重复计算;核对 GitCommitDiffReviewView、DiffReviewView 和共享 DiffPaneView 的新增/删除单栏、双栏、搜索/折叠/差异选择及收缩恢复行为。 长 Diff 双栏只创建可见区域附近的行;用 1,200 行夹具检查初始视口、滚动到末行和连续改变可见高度。 macOS 原生双栏 Diff 按 IDEA Islands/Darcula 配色显示新增绿、删除灰、修改蓝;JetBrains Mono Regular 13pt 与 22pt 行高;原版/新版行号分别固定在中央两侧,单侧增删后仍对应各自源文件行号。核对深浅外观、中央 1pt 分隔线、横向滚动和非等宽拖动后的连接带位置;单栏增删同步使用该配色。 双栏代码通过原生 NSTextView 连续选中,深色/浅色光标行号分别使用 A1A3AB/767A8A;整行修改背景按 IDEA 混合淡化,词内使用原修改色。分隔条允许先隐藏代码、再隐藏行号,双向完全收起后可恢复;窄窗口无负尺寸。1,200 行组件回归连续调整 60 次,检查文字存储不重建且固定容器排版不失效、透明定位/连接带不拦截代码点击。组件绘制耗时仅作诊断,完整应用的连续拖动视觉验收仍 pending。 历史提交 Diff 两行顶部显示紧凑工具栏与父/当前提交短哈希,左版本附中间省略的路径;隐藏补丁区块头,设置菜单保留词内高亮和关闭。切换单栏后版本标题上下排列,正文按旧/新顺序显示修改,左侧双源行号,仍可连续选中/复制。两侧滚动条按各自完整代码流标出增删改,点击跳至变更;纵向按视口三分之一锚点映射已有差异边界,匹配行连接带随滚动变平。检查真实原生 clip 偏移、标记颜色/点击、通知卸载和文字缓存不重建,保留共享折叠/区块操作。 历史提交页顶部按 Islands 独立工具栏层验证:40pt 内容、上 2pt/左右 6pt 留白与 6pt 圆角;版本标题四边 6pt 内边距、29pt 行高、1pt TEARLINE 底边;路径 13pt Regular/#73767C。布局选择由一个父外框及选中项边框绘制,检查未选项不重复描边、实际深浅像素和原生点击切换。 Windows 实现未改;完整工作区视觉与连续滚动性能验收保持 pending。 macOS 连续修改加多行插入、反向删除使用同一个左右源范围配对;纯插入/删除仍为绿/灰。检查行号、连接带、标记与整块正文一致,词内单侧变化使用增删色,滚动后空范围边界保留 1pt 线。 历史提交工具栏复用现有打开文件、当前提交内文件导航和 DiffCollapse,首尾/单文件箭头及删除文件打开入口禁用;双栏/单栏折叠、单区域展开和切换文件状态清理。版本标题使用真实布局高度,比较实际原生代码行转换到连接带的坐标,初始及滚动均无 29pt 偏移;中央宽度 24pt,源行号按真实字型测量并共享最大宽度,右数字不进入折叠空白区。Diff 错误条使用 14pt 宽标记(右 x=4、左 x=0),末行端点和 2pt 最小高度,滑块覆盖与点击定位保留。 Diff 正文和连接带不得绘制到工具栏或左右侧栏,平直连接带与行号区使用相同的排他行末端;差异导航不绘制蓝色竖线。只保留右侧纵向 thumb,左侧保留变更标记;真实窗口鼠标拖动右侧和底部横向 thumb 均改变代码偏移。嵌套工作区中将中央分隔条拖至两端后再次拉回,确认命中区域留在 Diff 内且外层面板不移动。多行调用重排按整段左右文本计算内部高亮,避免逐行配对造成绿色/灰色碎片;保留纯单侧内部变化颜色。 核对相邻等行数修改只高亮各行变化参数,正文保持淡色、中央保持原修改色;深浅主题下以 0/0.25/0.5/0.75pt 偏移验证相邻行背景无细缝。 中央连接带端点与行号填充采用相同设备像素覆盖范围;1×/2× 与小数滚动/拖动坐标下检查平直块跨中央区域无边框或接缝,保留曲线抗锯齿。 从源代码管理打开已修改和未跟踪文件的工作区 Diff 后保持静止,确认 Diff 不会自动关闭,且只在文件不再出现在 Git 状态中时关闭;在 Windows Commit、Git Log 及统一 Diff 中确认完整上下文不折叠,没有 hidden lines;核对中央行号两侧留白与竖线、Commit 动作区比 Git Log 更宽且不遮挡数字或代码,每个修改块仍可单独暂存;在 Windows 未暂存单文件 Diff 中点击某个修改块的“回滚”,2026-10-17 起与文件列表及整仓库丢弃一致遵守「丢弃前确认」设置:开启时先确认再恢复该块且暂存区不变,关闭时直接执行,最后一块回滚后文件从状态中消失时 Diff 关闭;暂存区、历史、分支比较与新增/未跟踪文件不显示回滚按钮。 在 Windows 从提交面板点击未提交文件,确认差异标签标题为「提交: 文件名」(英文为 Commit: )并显示差异图标,悬停显示完整标题;在提交面板切换到另一个文件时同一标签标题随之更新;从编辑器 gutter 打开整文件差异时标题保持「未提交的更改」。 macOS 工作区、linked worktree、目录、冲突、行标记、分支/引用、历史提交和 Stash/Shelf Diff 均显示普通共享编辑标签;切回文件/媒体/终端/Agent 不清空比较,重新进入不重复添加标签。重排、拖动分屏与关闭空组合并沿用普通分组逻辑;关闭当前项只关闭活动标签,后台 Diff 不截获文件关闭命令;从 Diff 按钮、设置菜单或 ⌘W 关闭时只清理目标比较状态并拒绝迟到结果,关闭活动 Diff 优先恢复本组标签。 审核回归另核对无末尾换行、CRLF-only 和内容伴随 CRLF:不能用有损行投影显示已包含或写入块,整文件暂存及实际提交的 blob 字节必须与磁盘一致。暂存 B 后磁盘恢复 HEAD 的 a,仍应显示暂存版本和文件框;二进制 A→B 暂存后磁盘 C,文件框显示部分包含,点击包含剩余内容。Unix 在公共可遍历父目录验证临时上下文没有组/其他用户访问权限,Drop 清理 HEAD/index;本机 Windows 权限执行范围与 macOS CI 断言应分别记录。 Windows Git Log 单文件和 Commit 文件 Diff 的词级高亮、显示空白符、统一/并排切换均在左侧,最右侧统计当前文件差异,区分无差异/单数/复数;Commit 勾选、部分包含、取消及刷新后 included 数同步变化,全部包含仍显示数量;加载、切换文件及图片/二进制不显示文本差异统计。核对中英文、明暗主题、窄窗口和按钮选中/禁用状态。 Windows 单文件 Diff 上箭头在首处继续进入上一文件最后一处,下箭头在末处进入下一文件首处,集合首尾不循环、加载中禁用;Commit 文件列表随跨文件导航更新选中行并展开祖先、滚动到可见位置,保留编辑器焦点和 include 状态;同文件刷新、历史 Diff、无关仓库和迟到读取不扰动列表。 Windows Git Log 鼠标或上下键选择提交后,异步 Diff 自动定位第一处改动但保持提交列表键盘焦点;并排与统一预览均不调用初始 focus。双击/Enter 打开完整 Diff、主动差异跳转及跨文件导航仍进入编辑器。 macOS Commit/Shelf 标题栏创建补丁按钮使用共享工具栏按钮样式,悬停保持箭头;打开补丁弹窗检查共享浮层外观与主次按钮,列表选择、生成预览、关闭及应用确认流程保持不变。 macOS 标题栏仅显示创建补丁入口,不额外显示应用补丁按钮。创建和应用补丁表单使用 Commit 共享标题栏对话框、背景、留白与主次按钮;打开或取消原生文件选择器以及内部下拉菜单均不得清空表单。窗口打开时后台主窗口不能触发另一编辑,关闭后恢复交互;标题和内容继承同一应用语言,主窗口关闭仍释放面板与监听。 macOS 共享居中弹窗需在单次点击后立即显示,关闭和重新打开无需其他交互;重复点击不得新增窗口,取消或卸载后不得显示过期弹窗。原生 SwiftUI 状态回归由 LitheCenteredPopupTests 覆盖。 macOS Commit 与 Git Log/Stash 共用 RepositoryDiffView;核对搜索、空白比较、整文件及块级暂存/取消暂存/丢弃仍可用,新建/删除文件使用新版单栏,历史入口无写入动作。旧面板与无调用渲染组件删除;真实工作区视觉验收仍需执行。 字节保真回退:CRLF(autocrlf=false/true、.gitattributes eol=crlf)与无末尾换行文件在预置非空暂存的仓库中逐块回退,目标块恢复为暂存区对应内容、未涉及区域原样保留、index 内容与 staged diff 前后不变;filter 或 working-tree-encoding 属性不安全的文件继续整文件降级。 块级回退确认:「丢弃前确认」开启时,预览面与 Monaco 块箭头均先弹确认,取消不写、确认后按打开时目标执行;确认期间同文件快照刷新后确认返回时不写入并提示选中内容已变化,切换文件或仓库后确认返回时不写入且不在新目标显示提示;重复点击只保留一个确认;设置关闭时直接执行。 macOS GitModuleTests 验证从linked worktree打开Diff后暂存/取消暂存仍保留比较、回滚后关闭,调用根目录不变且历史cursor不被关闭;实机工作树整文件与块级动作、切换工作树/仓库及后台刷新仍需验证。 多 Diff 回归:同时打开两个文件和同一文件的不同提交,检查独立标签、同一比较去重、切换保留内容/滚动、分屏各自显示、关闭一个不影响另一加载、Git Log 换提交不改变旧比较及工作区退出释放全部会话。 EditorTabOrderFeatureModelTests 验证同文件显式新标签与普通去重并存、关闭一个不影响另一个;VcsProviderAppModelTests 用可控基线请求覆盖成功、关闭标签、关闭工作区及焦点保持,确认任务和数据映射清空。真实插件新标签与分屏仍待目标产品验收。 Viva:运行 scripts/desktop/desktop-go.sh test ./internal/workbench -run TestDiffTab -count=1,覆盖查找两侧、忽略空白后差异数、无块计划时右侧编辑写入 document,以及有块计划时右侧只读。", - "notes": "Viva:Commit 面板的变更行右键/双击接入 Core 封装,对话框已实现;见 desktop/internal/workbench/gitreview*.go。未覆盖项见 PR 描述。 Diff 编辑区标签页(difftab*.go、diffpanes.go):并排为左右两个只读 Viva 编辑器,按文件语言做 TextMate 语法高亮;原版行号在中缝,改动之间用色带相连,块级勾选与回退放在中缝;折叠行带展开图标与横线;两侧同步滚动,差异跳转时两侧都把光标放到该处并居中;统一视图显示双行号。词内高亮、折叠行按上/下 20 行或全部展开、Diff 内查找(两侧、不区分大小写、循环跳转)与忽略空白已实现;右侧在工作副本且文件已打开、没有块计划时可编辑(未跟踪文件、忽略空白),编辑写入该文件的 document,保存后重读;有块计划(可逐块暂存/回退)时右侧保持只读,避免未保存编辑与磁盘上的块不一致。完整工作区视觉与连续滚动性能仍待实机验收。 Diff 设置菜单复用已有空白比较、折叠与关闭操作;TestDiffSettingsMenuUsesExistingWhitespaceAndCloseActions 验证状态切换和关闭释放,TestVisualWorkbench 采集深浅色并排/统一/菜单。未实现的旧版设置项未伪造入口。Diff 全文匹配下沉跟踪 #1847。", + "notes": "Viva:Commit 面板的变更行右键/双击接入 Core 封装,对话框已实现;见 desktop/internal/workbench/gitreview*.go。未覆盖项见 PR 描述。 Diff 编辑区标签页(difftab*.go、diffpanes.go):并排为左右两个只读 Viva 编辑器,按文件语言做 TextMate 语法高亮;原版行号在中缝,改动之间用色带相连,块级勾选与回退放在中缝;折叠行带展开图标与横线;两侧同步滚动,差异跳转时两侧都把光标放到该处并居中;统一视图显示双行号。词内高亮、折叠行按上/下 20 行或全部展开、Diff 内查找(两侧、不区分大小写、循环跳转)与忽略空白已实现;右侧在工作副本且文件已打开、没有块计划时可编辑(未跟踪文件、忽略空白),编辑写入该文件的 document,保存后重读;有块计划(可逐块暂存/回退)时右侧保持只读,避免未保存编辑与磁盘上的块不一致。完整工作区视觉与连续滚动性能仍待实机验收。 Diff 设置菜单复用已有空白比较、折叠与关闭操作;TestDiffSettingsMenuUsesExistingWhitespaceAndCloseActions 验证状态切换和关闭释放,TestVisualWorkbench 采集深浅色并排/统一/菜单。未实现的旧版设置项未伪造入口。2026-11-14 起 Diff 内查找在后台对两侧快照调用 Core editor.find,与编辑器查找栏同一套规则:Unicode 大小写折叠、最多 10000 处(计数显示 n+),两侧文本变化时重新查找(#1847)。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/git-history.json b/shared/platform-feature-matrix/features/git-history.json index 58f248611b..96a114d9f5 100644 --- a/shared/platform-feature-matrix/features/git-history.json +++ b/shared/platform-feature-matrix/features/git-history.json @@ -39,7 +39,7 @@ }, "owner": "Git", "verification": "双端多仓库打开 Git Log:隐藏中间工作树后其余仓库颜色保持,切换工作区不得显示旧颜色;共享 Core fixture、跨页桥接和异步界面测试覆盖,完整原生界面及滚动性能验收 pending。 提交历史由 Core 保留作者时区及绝对时间,macOS 与 Windows 日期展示使用该时间;macOS 日期范围通过 Core 按绝对边界比较,系统日历计算夏令时边界。真实 Git、跨时区、重复小时、23/25 小时日及原生缓存回归覆盖;完整双平台界面人工验收仍 pending。 Windows cherry-pick 资格根据当前 HEAD 标识判断,不能把筛选结果第一行当作 HEAD;真实菜单回归覆盖其他分支首行可操作和非首行 HEAD 禁用。分页浏览提交历史、分支图谱和提交详情,确认日期、作者和文件列表一致;macOS Git Log 工具窗口标签悬停有反馈,点击窗口内外时选中标签背景在活动色与非活动色之间切换,标签文字保持相同颜色与常规字重,按下时不变暗;分支最新提交的图谱连线从提交圆点开始,不超出到圆点上方;在双端使用同一包含本地分支、远端引用、标签和合并提交的仓库,核对永久图布局、图头引用排序、合并边投影及跨越 30 行的紧凑长边;在本地分支新增提交后确认分支颜色保持稳定,且不会因共用屏幕泳道直接沿用父分支颜色。双端使用 Community 完整颜色 ID 及明暗主题 RGB 规则;macOS Git Log 不再显示单独的 Fetch/Compare/Checkout/Cherry-pick 横向操作栏,分支树与竖向工具栏分离;检查 Fetch、分支比较、分支右键 Checkout、提交右键 Cherry-pick 和 Fetch 设置仍可用,分支搜索可筛选嵌套路径,并隐藏无匹配项的分组、显示无结果提示;定位按钮滚动到当前所选分支的首个可见提交而不重新加载历史;Git Log 的分支和提交搜索框复用 全局唯一的 LitheSearchFieldStyle,对照 IDEA SearchFieldWithExtension,核对 13pt 常规提示文字、Islands 明暗控件底色与边框色、36pt 外框内的 30pt 可见高度、3pt 外层留白、1pt 常态内描边、向外扩 1pt 的 2pt 聚焦描边及 4pt 圆角;图标与文字间距为 2pt,输入框清除按钮复用已有 16pt IDEA SVG 和 20pt 按钮区域,按上游预留清除图标宽度,移除分支搜索框重复外层水平内边距,提交搜索框按 15 列字体度量和 150pt 最小宽度布局,Search 与 Database 搜索输入框使用相同共享样式;竖栏更新按钮采用 IDEA ExpUI 的明暗 update 图标,按钮与侧边栏图标悬停使用共用工具提示样式,提示的明暗背景、文字色、1pt 内描边、圆角及内边距对齐 IDEA HelpTooltip;隐藏与显示分支使用 IDEA ExpUI 的 chevronLeft/chevronRight 明暗图标;竖栏宽 36pt,展开态按钮为 22pt 且四周保留工具栏内边距,展开态分支树左边框复用与 Commit 标题下边框同源的 1pt 分隔线;收缩态竖栏常态复用展开态侧栏背景,展开与收缩保留提交图谱和详情视图实例、滚动状态及分支宽度,仅切换分支面板与分隔条的占用宽度,按钮占满竖栏,深色 hover 使用 Islands Dark 的 #FFFFFF17,浅色 hover 使用 ExpUI Gray12,不在右侧显示 Show Branches 浮层提示,图标在顶部留 8pt 并使用常规小字号文字;展开后恢复分支树宽度。 使用原生 NSHostingView 渲染验证共享 LitheSearchTextField 的占位文字在深浅主题均为 IDEA Component.infoForeground 对应的 #73767C、13pt 常规字重;空输入框单独绘制占位文字,避免 SwiftUI 原生 prompt 替换其颜色与字重,有内容时占位文字消失并保留原生编辑和主文字色。 Git Log 分支树按 IDEA Community Islands 普通密度核对 24pt 行高、无行间额外间距、13pt 常规文字、12pt 次要计数与 4/12pt 树边距;展开箭头、路径文件夹、普通分支、当前分支和标签使用上游 16pt 明暗 SVG,Local/Remote/Tags 标题不附加图标,当前分支不显示额外蓝色勾选;HEAD 与当前分支是两个互斥选中节点,点击分支、HEAD、清除筛选和切换仓库时核对选中状态;深浅主题核对树行焦点/失焦选中色及 hover,保留多仓库名称、圆点、数量和只读菜单,移除分支行仓库色条;Windows 多仓库分支树的仓库行与 macOS 一致,仓库行使用中性色文件夹图标,并只在图标与名称之间显示 8px 仓库色点,仓库名保持普通文字色,不出现整组着色卡片底色、左侧色条或彩色名称,截断名称通过共享工具提示显示全名,行悬停为箭头光标;确认搜索、分组折叠、右键操作、缓存行比较和滚动状态正常。 Git Log 分支树右侧分隔线与 Commit 标题下边框共用 LitheTheme.toolWindowBorder 和 1pt 厚度,深色为 #26282C、浅色为 #E9EAEE;悬停、拖动开始/移动/结束均保持同色,不高亮,保留原生调整光标、命中区域、拖动尺寸约束及提交宽度行为。 Git Log 中间栏按 IDEA Community FilterComponent、VcsLogGraphTable 和 PaintParameters 核对四个筛选器的 13pt 常规文字、4pt 内边距、16pt 箭头和仅文字悬停反馈;工具栏使用 16pt IDEA 明暗 SVG、22pt 点击区域和共享提示,保留动作及禁用条件;提交列表为 26pt 连续行,图谱尺寸同比缩放,作者与日期同为 13pt 主文字色,日期列按打包字体度量,核对深浅主题行 hover、焦点/失焦选中色及选中覆盖 hover,筛选、分页、箭头命中、上下键导航和右键操作不回归。 分支竖栏设置齿轮复用 LitheIconButtonStyle 的 22pt 点击区域、4pt 圆角和主题 hover/按下背景;点击使用 LitheContextMenuPresenter 的共享操作菜单背景、1pt 边框、行 hover 与键盘导航,保留 Fetch Options 对话框、Show Worktree Repositories 勾选和无工作树时禁用行为,点击外部或按 Esc 关闭菜单。 macOS 下拉菜单仅保留 Project 同源的一套全局共享样式,移除 settingsStyle 切换;Project、Git Log 设置、Terminal、欢迎页及右键子菜单统一使用 8pt 外框圆角、1pt 内描边、24pt 行高、12.5pt 文字、6pt 外留白和 8pt 行内边距,设置选择下拉框共享同一外框与尺寸定义; Git Log 顶部按 IDEA 恢复 Branch: 已选分支名称,保留 Branch 筛选、清除和菜单内勾选;Branch、User、Date、Paths 按 IDEA FilterComponent 保留 4pt 内边距、3pt 箭头间距和 13pt 常规文字,四项文字 hover 为白色且不增加底色。Date 使用共享菜单呈现器,Branch/User 的可搜索列表与分组子菜单使用共享 LitheDropdownRowStyle、24pt 行高和共享菜单外框,Paths 输入面板复用共享菜单外框及搜索输入框样式,保留搜索、选项选中、路径 Apply/Cancel/Clear 和时间范围计算。 Branch/User/Paths 原生弹窗锚点不参与鼠标命中,核对按钮与文字收到 hover/点击、菜单正确弹出且关闭后可再次打开;Date 保持共享菜单呈现器。共享下拉外框裁剪内部内容,明暗主题下 Branch/User 搜索条不能覆盖圆角;Paths 输入框复用共享输入样式并显示正确焦点边框,Clear/Cancel/Apply 复用共享次按钮/主按钮,保留路径应用和清除行为。Branch、User、Paths 的可搜索内容同样使用 LitheContextMenuPresenter 的透明无边框面板,去掉 NSPopover 系统外框,复用 Project 共享背景、1pt 边框和圆角;分组展开与搜索动态调整弹窗尺寸,Esc、点击外部和切换菜单正确关闭。选择分支后清除筛选,确认 Branch 恢复默认标题且关闭按钮消失;关闭按钮保留 16pt closeSmall 明暗 SVG、22pt hover 区域及 4pt 圆角。展开分支树左侧固定线、中间分隔线和右侧详情拖动线均使用 toolWindowBorder 的 1pt 边框,右侧 hover 与拖动不高亮。右侧详情展示图标使用 IDEA previewVertically 明暗 SVG,装饰开关使用 show 眼睛而非 hide 工具窗口减号;所有工具栏展示图标复用 22pt、4pt 圆角的共享 hover 背景,保留原动作与提示。深浅主题渲染核对背景和边框,保留可选图标、勾选、快捷键、禁用、子菜单和键盘导航。 Git Log 提交标题、作者和日期使用 Inter 13 Normal,引用标签 12pt;核对至少 26pt 的字体度量行高、含 leading 的整数基线、长标题与中文/emoji 截断,以及选中合并提交的文字颜色。 所选分支存在时 Log 标签显示 Log: 分支短名(包含 codex/ 路径),选择另一分支立即更新;清除分支筛选后恢复 Log,保留本地化标题、原始分支名和原标签选择/焦点行为。 macOS 标题起点按缩放图谱列距、图文间距和 2pt 文字内边距计算,为对齐参考截图至少预留六列,密集行继续扩宽,不改变图谱节点、连线和箭头命中;在 SwiftUI/AppKit 两条渲染路径核对未选中的合并提交标题、作者、日期统一使用合并灰色,选中后恢复普通文字色,合并判定仅依赖至少两个父节点。 Git Log 右侧文件树使用共享 24pt 行高、19pt 层级缩进、常规字重、文件类型图标和 IDEA FileStatus 文件名颜色,无逐行横线及工具栏重复总数;核对文件夹折叠、文件打开 diff、长名称 hover 展开与横向滚动,拖动宽度不重建行内容。提交详情使用 14pt 外边距、10pt 内间距、等宽 bold 标题、同段作者邮箱时间与引用标签,长内容可滚动;文件树/详情之间分隔线复用共享边框,hover/拖动不高亮。左侧分支树从 180pt 专用下限改为共享 30pt 下限,独立 36pt 竖栏保持原宽,窄树裁剪后可拖回原宽,收缩/展开不重建图谱。 图谱圆点、连线、箭头按 SimpleGraphCellPainter/ PaintUtil 的 FLOOR/ODD 物理像素规则对齐;在 1×/2× 原生位图验证圆点与线宽,在真实 NSHostingView 检查对齐后的上下斜向箭头尖端及内侧描边可导航,切换屏幕只重绘且绘制/命中坐标一致。 时间列复用 Inter 13 常规字体的等宽数字与固定 AM/PM 区域,按应用语言使用英文 12h AM/PM 或中文 24h 格式;核对午夜、正午、未知日期回退、行起点一致及切换语言后的原生日期缓存失效,列表两条渲染路径和提交详情使用相同格式。 连续上下拖动 Git Log,包含上方长 Diff:原生列表只调整可见区域,保持文档身份、滚动位置、Shift/Command 多选、焦点色、键盘与箭头导航、分页和辅助功能;收缩再恢复后列表宽高正确。GitGraphInteractionTests 使用 300 条提交、80 次原生尺寸变化和共享分隔条事件验证,局部新旧路径计时作为诊断,不代替目标工作区帧率验证。 共享分隔容器按已有宽高直接分配两个面板与分隔条的确定矩形,避免 HStack/VStack 最小及理想尺寸探测;splitPaneBounds 覆盖横纵方向、leading/trailing、折叠、子视图身份和有限尺寸,达到尺寸限制后的相同结果不重复写状态。 通过键盘或程序化切换焦点时 Git 标签活动态双向更新;挂载或重新显示 Git Log 不主动抢走编辑器焦点。 在包含展开分支树的 Git Log 中连续拖动外层高度和内部宽度:共享分隔器只在拖动开始/结束传播环境状态,嵌套容器继承祖先状态;拖动期间共享行悬停不更新、提示不登记几何锚点、右键覆盖层暂停,松开后恢复菜单和提示,行内容及滚动状态不重挂载。69 行原生分隔条事件回归检查覆盖层暂停/恢复及内容身份;未悬停控件在平时同样不登记提示锚点。用目标工作区 Time Profiler/Animation Hitches 对照 Terminal 核对持续更新成本及起止开销,split.drag 整次手势时长不能当作单帧延迟;本次仅前端共享交互装饰调整,不修改后端及默认详情高度行为。 中文输入法组词期间,即使绑定文本仍为空,共享 LitheSearchTextField 占位文字立即隐藏;取消组词或删空后恢复,确认中文后仍隐藏。原生 setMarkedText 回归覆盖明暗主题和两个输入框互不影响;保留焦点、键盘提交、搜索/过滤语义及占位字号颜色。原生背景观察视图卸载和移出窗口时清理通知,匹配当前窗口的字段编辑器及所属输入区域,不修改业务绑定。 四个筛选弹窗均以各自按钮左下角为定位锚点,Date 不依赖鼠标点击坐标;空间不足时限制在屏幕可见范围内。原生面板回归核对操作菜单/可搜索内容相同锚点下的左上角、无展开动画和 Esc 关闭回调。共享搜索字段在未聚焦时悬停也显示文本编辑光标,离开或禁用时恢复箭头。 Git Console 左侧六个现有动作使用 Community 原始 16pt 明暗 SVG;22pt 背景、竖向 2/1 按钮留白、5/7 外边距和默认箭头光标。核对查找、软换行、跟随、停止、清空、复制的原有动作与禁用状态,组件资源检查不替代完整应用验收。 按 Community CurrentBranchHighlighter 标出当前本地分支可达的所有父提交,包含合并父节点;深色 #1D2336、浅色 #EDF3FF,选中背景优先,仅已加载图谱可证明的祖先被标记,当前分支/HEAD 单独筛选时不重复染色。引用默认显示并按 GitRefManager/SimpleRefGroup 紧凑合组:本地与上游同提交显示 remote & branch,HEAD/本地/远端/标签使用官方黄/绿/紫/灰轮廓及叠层,标签单独存在时默认只显示图标;长名称按列宽和 22 字符下限缩写,原生可见区 tooltip 保留所有完整名称,滚动后按当前鼠标位置解析。明暗原生渲染检查颜色、宽度、选择优先级及完整名称;GitLogReferenceResizeTests 在真实 GitLogView 中加载 1000 个分支并拖动外层高度,检查可见右键覆盖层数量和挂载生命周期,计时仅作诊断。最新正式预览已进入该工作树,观察全部引用下的深色背景、叠层缩写标签和多次上边缘拖动后的布局恢复;用户随后在本机明确确认“现在不卡顿了”,本次报告的高度拖动卡顿通过用户实机验收;组件计时和混合工作区采样不用于推断唯一根因或量化通用帧延迟,其他主题/悬浮等视觉项继续按各自范围验收。 在 Windows Git Log 选中带多行正文的提交,确认右侧详情在标题下方完整显示正文(保留空行与缩进),复制提交信息和打开提交 Diff 时也包含正文;分支最新提交的图谱连线从提交圆点开始,不超出到圆点上方;在双端使用同一包含本地分支、远端引用、标签和合并提交的仓库,核对永久图布局、图头引用排序、合并边投影及跨越 30 行的紧凑长边;在本地分支新增提交后确认分支颜色保持稳定,且不会因共用屏幕泳道直接沿用父分支颜色。双端使用 Community 完整颜色 ID 及明暗主题 RGB 规则。 读取提交正文期间切换仓库、重新打开另一提交或关闭面板,确认迟到结果不会打开旧 Diff 或覆盖新请求的加载状态。 Windows 另验证:单击提交后编辑区预览该提交第一个文件的 diff;单击或双击 Commit files 中的文件只显示该文件的 diff(不含提交说明,也不显示文件列表),并复用同一个预览标签;Commit files 树中过长的文件或目录名不折叠为省略号,区域随最宽行横向展开,可通过横向滚动条或触控板侧滑左右滑动查看完整名称(与源代码管理变更树一致);Git Log 刚打开、尚未点击提交时不会自动打开 diff;日期列将有 UTC 偏移的提交转换到本机时区后显示相对时间(刚刚、N 分钟前、今天/昨天);英文绝对日期和时间通过 Windows 原生接口遵循系统短日期/时间及用户自定义格式,中文使用中文地区格式,未知偏移仍显示绝对日期;验证美式月/日/年、英式日/月/年、自定义分隔符、12/24 小时制、跨时区相对时间和迟到原生结果保护,真实 WebView2 产品验收为 pending;鼠标移入行时刷新相对时间;作者/日期列可在行内列边缘拖动调整宽度并在重启后保留。 非连续多选提交修改同一路径时,预览保留每个提交的 diff 和提交标识,可通过文件导航分别查看;延迟请求返回前取消选择、隐藏 Git Log、切换仓库或卸载工具窗,确认旧请求不会重新打开或激活预览标签。 Windows 端提交历史仅通过 Git Log 工具窗浏览:源代码管理侧栏入口已更名为 Commit 面板,其 History 标签已移除,面板固定显示变更列表与提交区。命令面板中的 Git: Show History 入口同步移除。 Windows Commit Files 单文件预览使用独立页面:上下箭头导航差异,下箭头在当前文件最后一处后继续进入下一文件并在比较完成后定位第一处差异,整个文件集合末尾禁用且不循环;图片、二进制和无文本差异文件也允许下箭头继续,比较未就绪时禁用以防连续点击跳过文件。左右箭头直接切换当前比较集合的上一文件/下一文件;标签使用 IDEA 的 Repository Diff: 文件名并跟随导航更新,不附加提交 hash。Jump to Source 按最后聚焦侧的补丁位置打开预览所属仓库的文件,重命名使用新路径、删除行映射邻近保留行、已删除文件禁用源跳转;模型更新期间禁用差异动作。保留并排/统一视图、空白显示、Monaco 查找、图片和二进制呈现,普通全量提交比较仍使用多文件页面。真实 WebView2 内核及源文件打开还需目标产品运行验收。 Windows 单文件历史 Diff 外观验证:并排视图使用独立外侧 12px 滚动轨道、8px 滑块和概览,通常的统一视图保留 Monaco 原生 Diff 组件,整文件新增使用真实新行流的独立只读控件,深浅主题检查常态/悬停/拖动色、圆角及边框;实际拖动任一并排滑块后按差异边界同步对应行且模型身份保持。工具栏使用现有 Button,核对 40px 高度和 22px 图标按钮;保留用户字体与字号,默认行距按 14px 字号对应 22px 并随缩放,自定义行距不覆盖。词级高亮开关复用现有 Monaco 装饰能力,关闭只隐藏字符差异、保留整行差异,切换文件保留词级和空白开关。旧/新版本标题显示真实第一父提交、范围基线/目标或非连续提交各自身份,根提交旧侧为空树,重命名显示旧/新路径;短 hash 和截断路径的 tooltip 保留全文。并排标题列宽由独立布局所有者更新 CSS,拖动分隔条时标题跟随且不重建模型;统一视图标题纵向排列。以上浏览器真实组件验证不替代目标 WebView2 产品验收。 Windows 单文件 Diff 滚动条回归:两侧横纵滚动条默认显示,鼠标移到工具栏后仍可见,不依赖悬停;差异概览不绘制重复的宽矩形视口指示,并排由独立外侧轨道负责点击、拖动和滚轮,统一视图保留原生委托。明暗主题、并排/统一视图及长文本双向溢出下检查唯一可见滑块、并排横向同像素偏移同步、纵向对应行同步和模型身份。 历史 Diff 两侧滚动轨道与代码编辑器概览画布背景透明,鼠标不悬停时滑块仍显示;关闭代码编辑器重复概览通道,但保留 Diff 专用差异色条。横向轨道不额外增加内容高度,检查代码能显示在滑块后、底部内容与滚动位置正确,拖动命中保留,并排两侧横向同像素偏移同步、纵向对应行同步。 Windows 并排单文件 Diff 使用两个独立只读 Monaco 代码控件,取消 DiffEditor 的补空白对齐。左右横向滚动按同一像素偏移双向同步,较短侧由 Monaco 钳制到真实内容边界且不反向拉回主动侧;纵向原生代码区、外侧滑块拖动/点击、轨道键盘、滚轮和查找以视口三分之一处为锚点,按 Git 差异块起止边界同步对应行并保留行内偏移,短侧在不等长块内钳制、共同上下文恢复对齐。同步有重入与微小方向保护;双模型替换、布局、字体配置和显式上下导航期间暂停同步。新增旧侧/删除新侧画横跨可见代码区的双像素零行边界,修改区画上下单像素边界;两列行号背景为直边,曲线只在两列之间弯曲,实际偏移改变端点形状。检查文件开头/末尾零行、三态、明暗主题和窄列,代码不补空白、不扩展横向范围;连接面覆盖两列历史行号背景,行号选择和源映射正确。左右外侧各显示透明常显纵向滑块与增删改概览,横向保留原生滚动条,滚动范围截止真实最长代码行。验证深浅主题、折叠展开、Ctrl/Cmd+F 搜索折叠文本、词级开关和预算、统一视图及跨文件首处定位、连续拖动和窄窗口非负尺寸。高频帧二分筛选可见差异,缓存像素边界及概览,不扫描全文、不更新 React;卸载和迟到语言准备清理所有帧、监听、观察器、拖动、两个编辑器和模型。浏览器生产组件验证使用平台记录器,真实 WebView2 产品验收仍为 pending。 外侧轨道预留独立空间,不显示代码;左轨道距面板边缘、右轨道距代码视口各留 4px 间隙,窄列随可用宽度缩减,右侧文字与轨道不重叠;并排和统一预览关闭缩进及括号引导线,保留语法颜色;中央行号缩小边距和曲线间隙,整数布局边界及上下半像素描边消除与代码区的垂直接缝。滚轮在代码、行号和轨道统一加快到两倍,拖动仍映射各侧真实进度,纵向同步对应行;方向键按用户行高移动。有词级结果时修改正文底色按 40% 修改色与 60% 页面背景混合,完整修改色突出替换词的两侧,纯新增和纯删除词分别使用完整增删色,语法前景色和文字透明度保持;关闭词级或超限保留整行底色。验证三态与开头末尾、双向对应行同步、明暗主题、轨道无遮挡、宽窄字体布局和预算回退。 单文件并排及统一视图隐藏补丁 @@ 标题,但保留真正以 @@ 开头的源码、行 ID、源行映射和原始补丁;默认多文件与暂存投影不变。Islands Dark 继承 Darcula 背景,Islands Light 使用 Light 方案,独立差异轨道标记与连接、代码边界共用对应差异背景色。底部保留五个用户实际行高的 padding,模型不增加假行;从任意侧滚到底部验证共同末行对齐与五行留白,字号/行距变化同步更新。 Windows 单文件 Diff 首次打开、左右切文件和同路径新比较均在模型/比较准备完成后定位第一处改动;定位只消费一次,调整词级、空白、字号或主题保持用户当前位置。统一视图的原生 Monaco 增删行、字符与行号栏使用该预览相同的 Islands 背景变量,移除默认字符边框;新增整文件应为深色 #294436 或浅色 #BEE6BE,删除为 #484A4A 或 #D6D6D6,语法前景色不变且其他编辑器主题不被覆盖。 整文件新增采用单流只读代码控件,隐藏不存在的旧侧与连接带,新增背景覆盖行号、代码和底部留白,避免空旧模型的灰色删除行及外圈;新增仅显示新版本、删除仅显示旧版本的一组 hash 与路径。并排两侧及新增单流轨道的增删改标记与对应内容背景共用颜色;原生统一预览关闭 renderIndicators,历史行号旁不显示 +/-。这组新增显示修复按用户要求延后运行验证,提交或 PR 前核对新增文件、普通修改、删除、深浅主题、查找、源跳转与底部留白。 Windows Git Log 单文件和 Commit 文件 Diff 的词级高亮、显示空白符、统一/并排切换均在左侧,最右侧统计当前文件差异,区分无差异/单数/复数;Commit 勾选、部分包含、取消及刷新后 included 数同步变化,全部包含仍显示数量;加载、切换文件及图片/二进制不显示文本差异统计。核对中英文、明暗主题、窄窗口和按钮选中/禁用状态。 Windows 单文件 Diff 上箭头在首处继续进入上一文件最后一处,下箭头在末处进入下一文件首处,集合首尾不循环、加载中禁用;Commit 文件列表随跨文件导航更新选中行并展开祖先、滚动到可见位置,保留编辑器焦点和 include 状态;同文件刷新、历史 Diff、无关仓库和迟到读取不扰动列表。 Windows Git Log 右下角 Commit files 列表同样跟随 Diff 的上一/下一文件导航:选中行移到当前文件,被折叠的父目录自动展开,行滚动到可见位置;预览属于其他提交或范围时不改变选中,点击行不会改变横向滚动。 Windows Git Log 筛选后基于完整已加载历史投影可见祖先:隐藏中间提交以虚线连接,直接父子保持实线,无关分支不误连;合并路径去重并保留永久颜色,未加载父提交经隐藏节点传播,分页补齐后解除缺失标记;清空筛选恢复原图,核对文本、作者、分支名称三种范围、空结果与选择行为。算法和真实表格组件回归通过不代替 WebView2 原生验收,原生验证保持 pending。 Windows 未筛选图与筛选图共用上下半边打印元素:普通浏览的跨行泳道换列必须在共同中点连续连接,合流入边保留各自颜色到提交圆点;核对原始 IDEA 200 条历史输出的列号、方向、终止和颜色身份;截图/原生交互验收仍为 pending,组件输出和 golden 对照不代替 WebView2 验收。 Windows Git Graph 外观:核对明暗主题真实 IDEA RGB、实心节点、直线与筛选虚线、终止箭头及至少六列标题预留;默认 26px 行高,用户字号变化时虚拟行与 SVG 同步扩高;在 100%/125%/150%/200%/300% 缩放及跨屏 DPI 变化下核对奇数物理像素和相邻半边连续性,普通视口调整不重建历史图。箭头能跳到已加载且可见的父/子提交,未加载父节点没有可点击目标;浏览器生产组件验证不代替目标 WebView2 运行验收,原生验证保持 pending。 Windows 历史排序和图导航:在交错分支仓库核对首批/分页/回退及全引用上下文均使用日期顺序,切换分支保持可证明的永久颜色和基础顺序;上下文最多 5000 条,覆盖不完整或哈希重复时保留可见页并回退。核对 upstream/backup 等非 origin 远程引用分类及本地含斜杠分支;背景上下文不阻塞 50 条可见页,分页不取消或重读上下文,切仓库/刷新/卸载取消旧操作且关闭迟到游标。长边开关展开/收起不改变提交、筛选、选择和游标;验证 30/1000 行边界。点击或用 Enter/空格激活上下箭头,选择并滚动到屏幕外端点,挂载后键盘焦点随目标;不误选源行、不误开源行 Diff,保持普通选择/多选/双击/右键和原预览入口。明暗主题及 1x/1.25x/2x 检查箭头尖端与命中范围,真实 WebView2 运行验收保持 pending。 图谱颜色必须跟随 ThemeRegistry 根 data-theme-type 切换;不依赖页面存在 dark class。复用真实 Lithe 明暗主题检查同一已挂载节点与连线的颜色变化、布局不因主题重算,结合主题回归和浏览器真实切换验证。 Windows 分页稳定性:选中顶部提交后向下滚动触发连续分页,确认滚动位置不跳回已选提交,Commit Files 不清空或重读,已选文件及树折叠保持;更新引用、背景上下文和相同 hash 的元数据同样不导航。定位分支头通过独立请求仍能定位已经选中的头提交一次;新选择或切仓库仍读取新文件并丢弃旧结果。组件回归与真实浏览器虚拟列表/IntersectionObserver 验证通过,目标 WebView2 实机验收保持 pending。 Windows Git Log 标题栏不显示固定 Read-only/只读文字,关闭按钮保持靠右,刷新、设置及隐藏操作正常。 Windows Git Log 单个提交右键 New Tag… 输入非空且无空白的标签名,创建指向右键提交完整 hash 的轻量标签并刷新引用和历史;取消不写入,失败保留名称可重试,双击/Enter 不重复创建,多选和写操作期间禁用。仓库或工作区切换关闭旧弹窗,旧请求迟到不得刷新或关闭新弹窗。 Windows 提交区域点击后上下箭头更新可见提交选择和详情,焦点不随虚拟行移除而丢失;筛选、首尾边界、Home/End、Shift 范围选择和 Enter 正常,菜单与输入框保留自己的方向键。 Windows Git Log 鼠标或上下键选择提交后,异步 Diff 自动定位第一处改动但保持提交列表键盘焦点;并排与统一预览均不调用初始 focus。双击/Enter 打开完整 Diff、主动差异跳转及跨文件导航仍进入编辑器。 Windows Git Log 提交右键 New Tag 使用与 Tags 节点同源的 TagIcon(沿用现有标签轮廓图案),核对 16px 图标、菜单对齐和禁用反馈;新补图标的实机视觉确认待完成。 Windows 提交列表菜单键和 Shift+F10 打开当前选中提交的真实菜单;关闭后列表继续上下键导航,菜单操作仍针对所选提交。New Tag 在 tag.gpgSign=true 下生成轻量标签,不运行签名器或消息编辑器,不修改配置。 Windows 提交行高亮和紧凑引用组:在全部引用和其他分支视图核对当前检出分支全父祖先背景,当前分支/HEAD 视图关闭重复高亮;合并提交的说明、作者、日期未选中时弱化、选中后恢复,选中背景优先于分支并区分列表/文件树/窗口焦点。核对明暗主题固定基准色、真实 upstream 合并名称、游离 HEAD、每种最多两个叠加图标、仅标签图标和完整汇总悬停/无障碍提示。宽窄列及字号变化时按至少 22 字符缩略规则布局,只有一个视口尺寸观察器,列拖动不逐行读取宽度,卸载清理;分页不丢滚动/选择,成功后不重读 Commit Files;文件读取失败时 Commit Files 面板显示重试入口,重新选择同一提交或刷新历史也会重试一次,长边导航和新建标签原入口保持。组件与浏览器验证通过,目标 WebView2 实机验收 pending。 Windows Git Log 分支树和提交列表的普通滚轮使用 Community Windows 默认 200ms 和 (0.5,0.505,0.5,1) 曲线;连续同向累积、反向从当前位置重启。核对两处列表的中间帧、Shift 横向滚动、分页保持、顶底边界、键盘定位和滑块拖动取消惯性、关闭工具窗清理帧以及减少动态效果偏好。确定性动画与 DOM 回归通过,真实 WebView2 设备手感验收保持 pending。 Windows graph 标题不再固定预留六列:建议宽度取可见图边数的加权均值与标准差,最多以六列作统一基线,每行按节点与斜边中点扩展,密集行不把其他简单行扩成最大列宽。验证单线/少分支、罕见密集合并、超过六列、筛选、长边开关、引用标签可用宽度及字号/DPI,保持图谱颜色/连线/导航不变。 Windows Git Log 的 Commit Files 文件树沿用 IDEA Windows 默认 200ms 滚轮动画;在文件行、竖向/横向滚动条区域连续滚动、反向及 Shift 横向滚动,确认共用真实视口的动画目标,长文件名保持自然宽度;按下滚动条取消未完成惯性,减少动态效果时直接滚动,切换提交及卸载不残留帧。其它 ScrollArea 默认行为不变。真实 WebView2 交互验收 pending。 Windows Git Log 右键 New Tag 打开弹窗后焦点直接位于标签名输入框,无需点击即可输入,Enter 提交、Esc 关闭。 macOS Git Log 空状态:在非 Git 项目检查明暗主题、窄窗口和键盘操作:13pt 常规文字按 IDEA 左对齐,整组位于内容区上方三分之一处;显示 To track changes to code、GitHub/GitLab 官网链接、Initialize Git repository…、Open Git Settings 和带原始 ContextHelp 图标的 Version control integration(打开 Git 官方文档)。初始化仍先确认,不自动暂存或提交;设置打开既有 Git 设置。未提交仓库、无匹配提交、加载失败及重试保持原动作,所有空状态操作采用文字按钮。 非 Git 项目空状态隐藏 Log/Worktrees/Console 标签、添加按钮、分支树与动作条、筛选/搜索工具栏及提交详情,提示占满工具窗内容区;GitHub、GitLab、初始化、设置及帮助链接悬停仅给当前文字加主题强调色下划线并显示手形,离开后恢复;初始化或切换至真实仓库后恢复原有三栏布局,真实仓库无匹配提交仍保留筛选入口。 空状态字体与间距对照 Community c7f91397:按钮标签显式使用 Inter 13pt Regular;行首破折号按首行基线对齐,21pt 行高加 2pt 间隔,帮助图标间隔 2pt;灰字与链接分别沿 Component.infoForeground 和 Islands Link.activeForeground 核对明暗主题,悬停下划线仍使用当前主题强调色。 macOS 右侧提交详情的分支标签按可见区域懒加载,全部引用仍可滚动查看。重开面板初始化时恢复匹配的提交图和分支树,第一次布局即可读取全部已缓存数据,不依赖出现后的异步任务回填。重开面板复用未变化的分支树,单仓库不重复构建分组副本,多仓库活动根复用已有三类行;引用、仓库、工作树开关、折叠状态改变后拒绝旧树。原生绘制与无障碍日期文本复用缓存,语言改变后刷新。 macOS 大量引用首屏:同提交放置 1,500 个本地分支和 1,500 个远程引用,核对真实 upstream 优先、同名远程自然排序回退、完整提示及每类图标上限;反复切换 Terminal/Git Log,数据版本相同应复用已准备图,改变分支/筛选/图显示选项后不得复用旧图。运行 GitGraphInteractionTests 的 manyReferenceGroups 和 presentationCache;组件耗时仅诊断,整机卡顿以相同数据实测为准。 macOS Git Log 及终端按需创建后由工作台持有实际原生宿主;隐藏再重开及移动停靠位置复用控件。运行 GitLogReferenceResizeTests,验证同一工作台隐藏再重开时,固定原生表面上的提交文档和滚动容器对象身份不变,恢复可见性且尺寸正确,工作台释放后宿主释放;核对语言、主题、搜索、分支操作和终端会话。 Git Log 与终端同时停靠时,从外层横向和纵向分隔条中央及向面板两侧偏移 4pt 处,经窗口发送按下、拖动、松开,确认完整 10pt 命中区仍能提交尺寸、宿主身份保持,面板中央正常交互。;macOS 保留宿主圆角需在明暗主题、侧栏顶部与移动后、项目辉光改变、渐变开关及背景图切换时,与原工作台树四角像素一致(WorkbenchSurfaceBackgroundTests.retainedPaneCornersMatchWorkbenchGradient)。 Windows HEAD 按 Community HeadNodePainter 核对外圈、背景间隔和中心实点:26px 行高、100% 缩放时三层直径为 13/9/5px,125%/150%/200%/300% 按物理像素 FLOOR/ODD 对齐;深浅主题、悬停、当前分支及活动/非活动选择均透出真实行底色,穿过 HEAD 的连线不侵入间隔。普通节点及分叉、筛选、长边展开保持;同边双向终止元素键唯一。目标 WebView2 实机验收保持 pending。 macOS 在明暗主题的窄 Git Log 工具栏中选择长用户名、分支和路径,确认名称与选中值以同一行尾部截断,文字不重叠,清除按钮和重新选择仍可用。 macOS Git Log 接近底部时自动追加较早提交,正常浏览不出现必须点击的加载更多按钮;单一页面最多发起一次边缘请求,追加保留选择和原生视口偏移。无新提交或缺失后续游标时停止并释放游标;失败暂停自动读取,显式刷新重开历史而不重用失败游标。运行 GitGraphInteractionTests.automaticHistoryPaging 与 GitModuleTests.continuousHistoryPagingStopsOnDuplicatePagesAndRefreshesAfterFailure,真实大仓库连续滚动和 Windows WebView2 验收仍 pending。 macOS 深层历史后台刷新:文件状态变化不重开首批,元数据刷新保留已加载窗口和后续页占位,未变结果不重建提交图;外部新提交按可见 hash 与行内偏移保持原生视口,按新行位移补齐旧尾部,保留尾部选择。当前仓库引用只读取一次,多仓库仍独立加载。后台刷新打断自动分页后,即使历史相同也能继续读取新游标;失败仍暂停自动重试。运行 GitModuleTests.backgroundRefreshRetainsDeepHistoryAndSelectionWhileExternalCommitsStillAppear、引用聚合回归及 GitGraphInteractionTests.backgroundHistoryRefreshAnchorsVisibleCommitInsteadOfSelectedCommit/automaticHistoryPaging;真实大仓库长时间滚动仍待用户验收,原生进程 cleanup 超时未独立复现,不将减少重复查询等同于修复所有进程失败。 macOS #1542:显示保留的 Git Log/终端时,横纵分隔条中央及两侧偏移 4pt 仍经窗口事件完成拖动且只提交一次,宿主身份不变;根命中查询深度始终为 1,面板内部连续 100 次查询不产生额外根查询,鼠标移动不回查祖先 SwiftUI。验证禁用、收起(含嵌套分隔条)、恢复、卸载、跨窗口与登记表隔离、实时移动/裁剪、隐藏/透明和弱引用释放;保留宿主内部仍正常命中,外层边缘优先。Diff 两端收起后在普通与保留侧栏下均能经窗口拖回,不触发外层拖动。运行 GitLogReferenceResizeTests、SplitHandleHitTestTests 和 DiffScrollSynchronizationTests;旧实现先出现嵌套命中断言失败,新实现通过。较新 macOS 原生组件回归不替代 macOS 13 Intel 原报告崩溃验收,目标环境验证保持 pending。 历史菜单资格使用 Core 读取真实 HEAD 与第一父链;在筛选/分页、旁支首行、跳选、切换仓库、HEAD 变化和关闭菜单时验证动作状态及迟到结果隔离;两端原生界面验收 pending。 Git 控制台执行日志的记录状态(completed / unconfirmed)、单条与总量保留预算和脱敏由 Core 事件携带,两端不再各自归约或二次脱敏,单条输出预算统一为 32768 字符。 历史刷新的窗口大小、头部新增后保留旧尾部的延伸读取、翻页合并去重与上限、选中提交/焦点/范围锚点的保留统一由 Core `git.historyWindow` 决定;Windows 监听刷新不再把深层历史缩回第一页,选中与锚点在仍已加载时保留,像素级滚动锚点仍留在视图。滚动到深处后触发后台刷新,确认窗口深度、选中行与 Shift 范围起点不变;两端原生界面验收 pending。 Viva 改动文件折叠:运行 scripts/desktop/desktop-go.sh test ./internal/workbench -run 'TestLogChangedFiles|TestGroupLogFiles' -count=1;实机选择一个改动多个目录的提交,收起与展开文件夹、用方向键和双击操作,切换提交后文件夹重新展开。 Viva 提交详情改动文件横向滚动:运行 scripts/desktop/desktop-go.sh test ./internal/workbench -run TestLogChangedFiles -count=1 和 scripts/desktop/desktop-go.sh test ./internal/hscroll -count=1;实机选中路径很长的提交,确认改动文件列表可左右滚动、底部显示细滚动条,暗色主题下删除的文件显示为红色而不是灰色。 Viva 提交详情的哈希、作者、邮箱和日期不截断:运行 scripts/desktop/desktop-go.sh test ./internal/workbench -run TestLogCommitDetails -count=1;实机把详情面板拖到最窄,选中作者名和邮箱都很长的提交,确认放不下时换行显示,超长邮箱独占一行并在行内折行,没有省略号。 Viva 控制台:执行提交、推送或工作树清理等写操作后打开 Git 工具窗口的“控制台”页,核对命令、输出、退出码、搜索跳转、折叠、复制和清空;desktop/internal/workbench/gitconsole_test.go 覆盖列表、搜索和清空。", - "notes": "Viva 的 Git Log 已有提交列表、分支面板和提交详情,其余能力尚未逐项盘点。提交详情的改动文件按文件夹分组,文件夹先于文件、文件保持 Git 返回的顺序,使用与项目树相同的 desktop/internal/treelist 折叠列表:单击箭头、双击文件夹或方向键展开收起,Enter 打开文件差异;切换提交后所有文件夹重新展开。分组仍在 Go 中完成,下沉 Core 跟踪 #1814。legacy 是迁移前基线,不代表当前实现。 Viva 提交详情的改动文件列表与项目树共用 desktop/internal/hscroll 横向滚动:列宽取最长一行,滚轮或触控板横向滚动,底部细滚动条显示位置;删除的文件在明暗主题下都用红色(Deleted),不再用暗色下发灰的次要文字色,Commit 工具窗口同样适用。 Git 工具窗口新增“控制台”页:按时间列出 Core 记录的 Git 写操作命令、输出和退出码,支持搜索与上下跳转命中、折叠长输出、复制命令或输出和清空;只读命令不进入记录(Core 只记录 git.write 类命令)。", + "notes": "Viva 的 Git Log 已有提交列表、分支面板和提交详情,其余能力尚未逐项盘点。提交详情的改动文件按文件夹分组,文件夹先于文件,使用与项目树相同的 desktop/internal/treelist 折叠列表:单击箭头、双击文件夹或方向键展开收起,Enter 打开文件差异;切换提交后所有文件夹重新展开。2026-11-14 起分组由 Core git.changedFileGroups 计算(#1814):目录按段比较、文件按项目树的自然顺序排列(v0.1.4 在 v0.1.12 前),顶层目录为空字符串;Stash 和 Shelf 页同样适用。legacy 是迁移前基线,不代表当前实现。 Viva 提交详情的改动文件列表与项目树共用 desktop/internal/hscroll 横向滚动:列宽取最长一行,滚轮或触控板横向滚动,底部细滚动条显示位置;删除的文件在明暗主题下都用红色(Deleted),不再用暗色下发灰的次要文字色,Commit 工具窗口同样适用。 Git 工具窗口新增“控制台”页:按时间列出 Core 记录的 Git 写操作命令、输出和退出码,支持搜索与上下跳转命中、折叠长输出、复制命令或输出和清空;只读命令不进入记录(Core 只记录 git.write 类命令)。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/git-worktrees.json b/shared/platform-feature-matrix/features/git-worktrees.json index 9de65e2b53..8c4284018e 100644 --- a/shared/platform-feature-matrix/features/git-worktrees.json +++ b/shared/platform-feature-matrix/features/git-worktrees.json @@ -69,5 +69,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva 的 Git 工具窗口已有“工作树”页:列表与搜索、过期登记清理与修复、概览/更改/提交历史详情(历史滚动续页)、三种模式新建(新分支、已有分支、分离 HEAD)及建议路径、删除与强制删除、锁定/解锁、显示位置、复制路径和打开;更改页可逐个或全部暂存/取消暂存,并能显示差异、复制路径和回滚,均作用于所选 checkout;提交历史复用 Log 页的 Core 分支图(泳道、引用标签);更改页下方有提交区(Amend、暂存数、提交说明、Cmd+Enter、提交/提交并推送、结果与重试),每个 linked checkout 有独立草稿,只提交该 checkout 的暂存内容,项目所在 checkout 与 Commit 工具窗口共用草稿、AI 生成和当前 ChangeList 范围,审阅弹窗在工作台层显示;Core 按拒绝原因返回不同错误码(主工作区、当前工作区、已锁定、有修改、未登记)。Log 页 Git 工具菜单的“工作树”项直接切到该页(gitreview_tools_view.go),不再另开简化对话框。尚未迁移:在新窗口打开、悬停快速信息和工作树设置页。操作可用性、状态优先级和建议路径仍在 Go 中判定,下沉 Core 跟踪 #1817。legacy 是迁移前基线,不代表当前实现。" + "notes": "Viva 的 Git 工具窗口已有“工作树”页:列表与搜索、过期登记清理与修复、概览/更改/提交历史详情(历史滚动续页)、三种模式新建(新分支、已有分支、分离 HEAD)及建议路径、删除与强制删除、锁定/解锁、显示位置、复制路径和打开;更改页可逐个或全部暂存/取消暂存,并能显示差异、复制路径和回滚,均作用于所选 checkout;提交历史复用 Log 页的 Core 分支图(泳道、引用标签);更改页下方有提交区(Amend、暂存数、提交说明、Cmd+Enter、提交/提交并推送、结果与重试),每个 linked checkout 有独立草稿,只提交该 checkout 的暂存内容,项目所在 checkout 与 Commit 工具窗口共用草稿、AI 生成和当前 ChangeList 范围,审阅弹窗在工作台层显示;Core 按拒绝原因返回不同错误码(主工作区、当前工作区、已锁定、有修改、未登记)。Log 页 Git 工具菜单的“工作树”项直接切到该页(gitreview_tools_view.go),不再另开简化对话框。尚未迁移:在新窗口打开、悬停快速信息和工作树设置页。2026-11-14 起状态、被禁止的写操作及原因由 Core git.worktrees 给出,一次 countChanges 列出统计每个检出的改动数;新建对话框的可选项、分支名、建议目录和能否创建来自 git.worktreeCreationPreview(#1817)。legacy 是迁移前基线,不代表当前实现。" } diff --git a/shared/platform-feature-matrix/features/network-proxy-settings.json b/shared/platform-feature-matrix/features/network-proxy-settings.json index 703864bd0b..c33986b909 100644 --- a/shared/platform-feature-matrix/features/network-proxy-settings.json +++ b/shared/platform-feature-matrix/features/network-proxy-settings.json @@ -32,7 +32,7 @@ ] }, "owner": "Settings", - "notes": "Viva:设置 › 网络提供跟随系统、不走代理、自定义代理(HTTP/SOCKS5、地址、端口、用户名、排除列表),密码存平台密钥库;Core 归一化为代理策略(network.proxyPolicy),netproxy 把 http.DefaultTransport 指向当前策略,市场、插件与项目下载、GitHub、AI 提供方都经它,修改后对新请求生效。“测试连接”已实现:用未保存的草稿经 Core 解析策略(密码规则与保存相同:新输入的密码随草稿的端点,未改动时取已存密码、由 Core 校验它属于同一端点),只有自定义服务器完整时才发请求;在独立传输上 HEAD https://github.com,10 秒内、不跟随重定向,200–399 算成功并显示耗时,否则显示状态码或原因;不影响生效中的策略和它的连接。自动化测试:netproxy/netproxy_test.go(本地代理、凭据、重定向、排除列表、失败原因)、workbench/network_check_test.go(真实 Core 下的密码与端点规则)、settingswindow/network_view_test.go(页面流程)。未迁移:代理认证只有 Basic(旧客户端还应答 Digest/NTLM);旧钥匙串 app.lithe.desktop.proxy 的密码没有可选导入。", + "notes": "Viva:设置 › 网络提供跟随系统、不走代理、自定义代理(HTTP/SOCKS5、地址、端口、用户名、排除列表),密码存平台密钥库;Core 归一化为代理策略(network.proxyPolicy),netproxy 把 http.DefaultTransport 指向当前策略,市场、插件与项目下载、GitHub、AI 提供方都经它,修改后对新请求生效。“测试连接”已实现:用未保存的草稿经 Core 解析策略(密码规则与保存相同:新输入的密码随草稿的端点,未改动时取已存密码、由 Core 校验它属于同一端点),只有自定义服务器完整时才发请求;在独立传输上 HEAD https://github.com,10 秒内、不跟随重定向,200–399 算成功并显示耗时,否则显示状态码或原因;不影响生效中的策略和它的连接。自动化测试:netproxy/netproxy_test.go(本地代理、凭据、重定向、排除列表、失败原因)、workbench/network_check_test.go(真实 Core 下的密码与端点规则)、settingswindow/network_view_test.go(页面流程)。未迁移:代理认证只有 Basic(旧客户端还应答 Digest/NTLM);旧钥匙串 app.lithe.desktop.proxy 的密码没有可选导入。 2026-11-14 起排除项由 Core 解析(network.proxyPolicy 的 exclusionRules:host、suffix、ip、cidr、local),netproxy 只做契约规定的比较并回放 Core 的 network/proxy-bypass-v1.json;测试连接的结果后列出 Core 无法识别、不会生效的排除项(invalidExclusions,#1829)。", "verification": "Viva 本地验证(2026-11-12):bash scripts/desktop/desktop-go.sh test ./internal/netproxy/ ./internal/settingswindow/ ./internal/workbench/ -run 'TestCheck|TestNetworkPageChecks|TestNetworkCheck';变异检查(跟随重定向、忽略已存密码、Revert 不清结果)各让对应测试失败。真实代理的实机验收尚待进行。旧客户端基线:已完成实机验收(2026-10-29,macOS 15.8.1 Intel,打包构建):设置 › 外观与行为 › 网络三档切换生效;自定义 HTTP 代理 + 测试连接返回成功耗时,错误端口返回失败原因;保存后重启保留且密码经 Keychain 不回显;经自定义代理完成插件市场访问与安装。自动化:运行 ./.agents/skills/write-stable-tests/scripts/test-stability-macos.sh -- --filter 'NetworkProxySettingsTests|MacNetworkSessionProviderTests' 与 ./scripts/macos/test/test-macos.sh --filter 'NetworkProxySettingsTests|MacNetworkSessionProviderTests|AppSettingsTests|SettingsSidebarLayoutTests|SettingsSearchVocabularyTests';运行前后对比安装目录文件清单与哈希,确认运行时未写入发行目录。 本次安全与生命周期修复的真实认证代理/完整产品流程尚待复验,不沿用原实机验收作为新行为的 verified 证据。 本次修复本地验证:Swift 6.3.3 + macOS 26.5 SDK,逐项计时运行 8 套件 85 测试全过;Rust Core 1373 单元测试与 32 集成测试全过,网络策略 4 项另有逐项计时;i18n 35 项测试、语言/生成检查、共享契约、服务边界、bundle 只读、Agent Notes 与 Windows 静态边界门禁通过。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36",