diff --git a/.agents/notes/implemented/bug-fix/2026-11-20-project-menu-remove-recent.md b/.agents/notes/implemented/bug-fix/2026-11-20-project-menu-remove-recent.md new file mode 100644 index 0000000000..06f293d913 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-20-project-menu-remove-recent.md @@ -0,0 +1,37 @@ +# Agent 笔记:项目菜单独立移除最近记录 + +状态:已实现 + +## 先说结论 + +标题栏项目菜单的最近项目每行都提供 X,只从最近列表移除记录,不打开项目、不删除目录,也不关闭菜单。当前项目行的 X 继续关闭项目,并保留最近记录。目录已经不存在时,该行不能打开,但 X 仍可用。 + +## 问题 + +项目菜单原来仅为当前项目绘制关闭按钮,最近项目没有直接移除入口。若将缺失项目整行禁用,后续加入的移除按钮也会一起失去交互能力。 + +## 决策 + +最近项目复用 Core(共享 Rust 规则层)的现有最近项目移除动作和持久化路径。行内 X 使用独立命中区与对应的本地化提示,移除动作优先于行打开动作,防止同一次点击又触发打开。 + +缺失项目继续灰显且禁止打开,移除按钮保持可点击。正确做法是分别处理行激活和 X;不要在父容器上禁用全部子控件。 + +## 考虑过的备选方案 + +- 只在右键菜单提供移除:入口不直观,无法满足项目菜单直接删除记录的操作。 +- 点击 X 后关闭整个菜单:连续整理最近记录时需要反复展开,现有列表更新已能原位呈现结果。 + +## 后果 + +用户可以直接整理存在或缺失目录的最近记录。两个区段的 X 有不同含义,因此分别使用“关闭项目”和“从最近项目移除”的提示;删除文件不属于这个入口。 + +## 验证 + +- `scripts/desktop/desktop-go.sh test ./internal/workbench -run 'TestProjectMenuRemoves|TestProjectMenuWheel' -count=1 -timeout=45s`:回归测试先确认缺少 X 时失败;修复后验证记录持久化、目录保留、菜单保留及当前项目关闭。 +- `scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/workbench -run TestVisualProjectMenuRemove -count=1 -timeout=45s`:使用真实临时目录生成中英文、明暗主题截图,检查存在与缺失两种最近记录。输出由 `LITHE_VISUAL_OUTPUT_DIR` 指定。 + +## 适用范围 + +- `desktop/internal/workbench/chrome_view.go` +- `desktop/internal/workbench/project_menu_test.go` +- `shared/platform-feature-matrix/features/workspace-open-switch.json` diff --git a/.agents/notes/implemented/feature/2026-11-20-cli-and-standalone-editor.md b/.agents/notes/implemented/feature/2026-11-20-cli-and-standalone-editor.md new file mode 100644 index 0000000000..a518ac2085 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-20-cli-and-standalone-editor.md @@ -0,0 +1,49 @@ +# Agent 笔记:可选 CLI 注册与单文件编辑 + +状态:已实现 + +## 先说结论 + +Lithe 默认不向用户的命令行环境注册命令。用户在设置的“通用 > CLI”卡片明确点击后,才创建用户级启动器并修改显示的配置来源。命令打开文件夹时沿用完整项目流程;打开文件时使用独立的文本编辑窗口,任何插件都不创建或激活,文件的父目录也不会因此成为工作区。 + +## 问题 + +将普通文件当成项目打开,会启动与临时编辑无关的插件、索引和 Git 观察。安装时自动修改 PATH 又会影响用户的 shell 配置;只保存一个“已注册”偏好无法判断实际配置有没有被删除、改写或指向旧安装。 + +## 决策 + +- Core(共享 Rust 规则层)解析启动参数、根据原生文件类型选择模式,并给出单文件模式允许的命令。桌面端只做路径观察、进程启动和界面呈现。单文件窗口借用既有文档与标签生命周期,不调用项目打开流程;父目录只是文件位置,不进行项目恢复、信任确认、递归搜索或插件上下文绑定。 +- 单文件模式保留内置语法高亮、文本编辑、查找替换、保存、编码与换行选择和单个文档的外部变更观察。项目侧栏、Git、运行、调试、测试及预览网页不呈现。终端默认关闭,由用户点击后才创建,使用当前文件所在目录,复用现有终端标签、分隔条及进程清理;隐藏面板保留会话,关闭标签或窗口释放 shell。单文件窗口不恢复或改写项目面板布局。双 Shift 和查找动作只列出允许的动作,不读取父目录。关闭全部文件后仍保持单文件空态。 +- 顶栏显示当前文件名与“单文件模式”,通过 ⓘ 解释边界。“以项目打开所在文件夹”使用当前选中文件的父目录,在另一窗口进入正常的项目信任和插件流程,保留原编辑窗口。 +- CLI 卡片直接读取默认 shell 配置与启动器内容。macOS zsh 使用 `.zshrc`(尊重 `ZDOTDIR`),bash 使用实际登录配置,fish 使用自身配置;Windows 编辑当前用户注册表 PATH,保留其原生字符串类型,并有界广播环境变更。已有终端需重新打开。 +- 打开页面只读,注册、修复和移除都来自明确按钮。Unix 来源使用带标记的配置块,Windows 只编辑匹配目录项;保留其他内容。写入前核对文件内容、来源目录和符号链接目标;读取后被外部改写则拒绝覆盖。Windows 注册表核对与单值写入间仍受外部进程竞争限制,不宣称跨进程事务。 +- 启动器只位于系统用户配置目录的 `Lithe/cli/bin`,指向应用当前可执行文件。它是用户运行状态,由 CLI 注册管理器持有,不进入 app bundle 或 Windows 安装目录,不影响签名和增量更新的源基线。应用移动后允许显式修复完整的 Lithe 启动器格式,不覆盖其他命令。移除注册后删除属于 Lithe 的启动器。 + +正确做法:`lithe notes.go` 只打开该文件,随后用户明确点击“以项目打开所在文件夹”才在新窗口创建项目服务。不要因为已知文件父目录而调用项目初始化,再在界面上隐藏面板;那样仍然付出了插件和目录观察的开销。 + +## 考虑过的备选方案 + +- 安装或首次启动时自动写 PATH:违背默认不注册的要求,也无法让用户审阅修改目标。 +- 在单文件窗口创建项目并禁用部分插件:项目管线仍会创建目录观察和恢复状态,无法保证任何插件都不激活。 +- 只注册全局系统目录中的符号链接:Windows 与 Unix 所需权限不同,还可能要求管理员权限。用户级启动器可以保持显式注册且不修改安装资源。 +- 在当前窗口将单文件直接升级为项目:会混合两种服务生命周期,产生插件初始化与未保存文档处理的隐含转换。使用正常项目新窗口复用已有完整流程,代价是多一个窗口。 + +## 后果 + +临时文件不再启动项目服务;命令可移除、可回读,并能发现外部改动。单文件模式也因此没有插件语言智能和项目预览;需要这些功能时必须明确打开所在文件夹。每次 CLI 调用会短暂启动一个只处理参数和路径的父进程,再脱离终端创建 GUI(图形界面)子进程,不保留 shell 管道或后台 shell。 + +## 验证 + +- `scripts/desktop/desktop-go.sh test ./cmd/lithe ./internal/cli ./internal/core ./internal/workbench -run 'TestCLI|TestStandalone|TestDesktopStartupMakesInstalledPluginSettingsReachable' -count=1 -timeout=90s`:链接同一 Core 检出,验证真实文件类型、共享 fixture、真实临时 shell 配置的注册/修复/移除/冲突保护和独立编辑保存。 +- `scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/settingswindow ./internal/workbench -run 'TestVisualCLISettings|TestVisualStandalone' -count=1 -timeout=90s`:生成明暗主题、中英文的真实渲染截图。通过 `LITHE_VISUAL_OUTPUT_DIR` 指定本工作树的输出目录。 +- `scripts/desktop/verify/verify-runtime-bundle-immutability.sh`:检查两个桌面平台的发行目录只读边界。 +- Windows 规则可以在 macOS 上以平台参数验证;注册表写入、环境广播与 cmd/PowerShell 调用仍需 Windows 原生环境验收,交叉编译不替代该验收。 + +## 适用范围 + +- `desktop/cmd/lithe/` +- `desktop/internal/cli/` +- `desktop/internal/core/cli.go` +- `desktop/internal/workbench/standalone.go` +- `desktop/internal/settingswindow/cli_view.go` +- `shared/platform-feature-matrix/features/cli-single-file-mode.json` diff --git a/desktop/cmd/lithe/detach_unix.go b/desktop/cmd/lithe/detach_unix.go new file mode 100644 index 0000000000..494da4fc8b --- /dev/null +++ b/desktop/cmd/lithe/detach_unix.go @@ -0,0 +1,10 @@ +//go:build !windows + +package main + +import ( + "os/exec" + "syscall" +) + +func detachGUI(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} } diff --git a/desktop/cmd/lithe/detach_windows.go b/desktop/cmd/lithe/detach_windows.go new file mode 100644 index 0000000000..33edc86e05 --- /dev/null +++ b/desktop/cmd/lithe/detach_windows.go @@ -0,0 +1,10 @@ +package main + +import ( + "os/exec" + "syscall" +) + +func detachGUI(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: 0x00000008 | syscall.CREATE_NEW_PROCESS_GROUP} +} diff --git a/desktop/cmd/lithe/main.go b/desktop/cmd/lithe/main.go index 06b4265266..e6b7d646e9 100644 --- a/desktop/cmd/lithe/main.go +++ b/desktop/cmd/lithe/main.go @@ -3,13 +3,18 @@ package main import ( + "context" "fmt" "os" + "os/exec" "path/filepath" "runtime" + "time" "github.com/1lck/Lithe-IDEA/desktop" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/installedpackage" "github.com/1lck/Lithe-IDEA/desktop/internal/loginenv" "github.com/1lck/Lithe-IDEA/desktop/internal/logstore" "github.com/1lck/Lithe-IDEA/desktop/internal/store" @@ -20,23 +25,50 @@ func main() { // AppKit needs the process's main thread for the application and its windows. Pin the // main goroutine before any setup that can yield, so the scheduler cannot move it. runtime.LockOSThread() + client := core.NewClient() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + launch, err := client.PlanCLILaunch(ctx, os.Args[1:]) + cancel() + if err != nil { + fail(err) + } + switch launch.Action { + case "help": + fmt.Println(i18n.Shared(i18n.Detect([]string{os.Getenv("LC_ALL"), os.Getenv("LC_MESSAGES"), os.Getenv("LANG")}), "desktop.cli.usage")) + return + case "version": + fmt.Println(desktop.Version()) + return + } + path, file, err := commandLineTarget(client, launch.Path) + if err != nil { + fail(err) + } + if launch.Detach { + if err := launchGUI(path); err != nil { + fail(err) + } + return + } // An app started from Finder or the Dock gets only the system PATH; take the login shell's - // before Core starts the threads that read the environment. - refreshLoginEnvironment := loginenv.Activate() + // before any project services start. The CLI requests above are synchronous pure rules. + var refreshLoginEnvironment func() + if !file { + refreshLoginEnvironment = loginenv.Activate() + } preferences, err := store.Open() if err != nil { fail(err) } - client := core.NewClient() if refreshLoginEnvironment != nil { go refreshLoginEnvironment() } version := desktop.Version() options := workbench.DesktopOptions(client, preferences, version) - // A project folder given on the command line is opened when the window starts; a worktree's - // "Open in New Window" starts the client that way. - if folder := commandLineFolder(os.Args[1:]); folder != "" { - options.OpenPath = folder + if file { + options.OpenFile = path + } else { + options.OpenPath = path } // A log that cannot be opened leaves the client without its log window instead of // keeping it from starting; the window says so when the log is asked for. @@ -61,19 +93,52 @@ func main() { } } -// commandLineFolder is the first argument that names an existing folder, made absolute; empty when -// there is none. -func commandLineFolder(args []string) string { - for _, arg := range args { - abs, err := filepath.Abs(arg) - if err != nil { - continue - } - if info, err := os.Stat(abs); err == nil && info.IsDir() { - return abs - } +// commandLineTarget observes the native file type; Core selects the session policy. +func commandLineTarget(client *core.Client, path string) (string, bool, error) { + if path == "" { + return "", false, nil + } + abs, err := filepath.Abs(path) + if err != nil { + return "", false, err + } + abs, err = filepath.EvalSymlinks(abs) + if err != nil { + return "", false, err + } + info, err := os.Stat(abs) + if err != nil { + return "", false, err + } + kind := "other" + if info.IsDir() { + kind = "directory" + } else if info.Mode().IsRegular() { + kind = "file" + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + target, err := client.CLIOpenTarget(ctx, kind) + return abs, target.Mode == "file", err +} + +// The shell launcher exits after starting the GUI, without a shell subprocess or +// inherited terminal streams. The child receives an absolute path and no --cli. +func launchGUI(path string) error { + executable, err := installedpackage.Executable() + if err != nil { + return err + } + args := []string{} + if path != "" { + args = []string{"--", path} + } + cmd := exec.Command(executable, args...) + detachGUI(cmd) + if err := cmd.Start(); err != nil { + return err } - return "" + return cmd.Process.Release() } // fail reports an error that keeps the client from starting or running and exits. diff --git a/desktop/cmd/lithe/main_test.go b/desktop/cmd/lithe/main_test.go new file mode 100644 index 0000000000..cba2688a56 --- /dev/null +++ b/desktop/cmd/lithe/main_test.go @@ -0,0 +1,31 @@ +package main + +import ( + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +func TestCLIClassifiesActualFileAndFolder(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "-中文 file.txt") + if err := os.WriteFile(path, []byte("text"), 0600); err != nil { + t.Fatal(err) + } + client := core.NewClient() + for _, test := range []struct { + path string + file bool + }{{root, false}, {path, true}} { + actual, file, err := commandLineTarget(client, test.path) + expected, resolveErr := filepath.EvalSymlinks(test.path) + if err != nil || resolveErr != nil || actual != expected || file != test.file { + t.Fatalf("classify %q: %q %v %v", test.path, actual, file, err) + } + } + if _, _, err := commandLineTarget(client, filepath.Join(root, "missing")); err == nil { + t.Fatal("missing target accepted") + } +} diff --git a/desktop/internal/cli/limits.go b/desktop/internal/cli/limits.go new file mode 100644 index 0000000000..bc41c48c34 --- /dev/null +++ b/desktop/internal/cli/limits.go @@ -0,0 +1,4 @@ +package cli + +// Shell configuration and launcher snapshots share Core's bounded text budget. +const maximumSourceBytes = 1 << 20 diff --git a/desktop/internal/cli/registration.go b/desktop/internal/cli/registration.go new file mode 100644 index 0000000000..6c3e4a26fb --- /dev/null +++ b/desktop/internal/cli/registration.go @@ -0,0 +1,132 @@ +// Package cli installs an opt-in launcher in user data and edits the native shell's +// actual configuration. The installed application and unrelated shell content stay read-only. +package cli + +import ( + "context" + "errors" + "os" + "path/filepath" + "sync" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/installedpackage" +) + +var ErrUnsupportedShell = errors.New("unsupported login shell") +var ErrLauncherConflict = errors.New("CLI launcher is not managed by Lithe") + +// State is a native read baseline, retained privately by the settings page until +// an explicit click. Apply rejects external edits rather than overwriting them. +type State struct { + Shell, Target, Launcher string + Installed, Registered bool + source nativeSource + launcher configfile.Snapshot +} + +// Manager owns publication within this settings controller; reads never create files. +type Manager struct { + mu sync.Mutex + Kernel *core.Client + Directory, Executable string + // Source is optional platform input for isolated integration tests. + source func(context.Context) (nativeSource, error) +} + +func New() *Manager { return &Manager{Kernel: core.NewClient()} } + +func (m *Manager) paths() (string, string, error) { + directory, executable := m.Directory, m.Executable + if directory == "" { + root, err := os.UserConfigDir() + if err != nil { + return "", "", err + } + directory = filepath.Join(root, "Lithe", "cli", "bin") + } + if executable == "" { + var err error + executable, err = installedpackage.Executable() + if err != nil { + return "", "", err + } + } + return directory, executable, nil +} + +func (m *Manager) Read(ctx context.Context) (State, error) { + m.mu.Lock() + defer m.mu.Unlock() + return m.read(ctx) +} + +func (m *Manager) read(ctx context.Context) (State, error) { + directory, executable, err := m.paths() + if err != nil { + return State{}, err + } + read := readNativeSource + if m.source != nil { + read = m.source + } + source, err := read(ctx) + if err != nil { + return State{}, err + } + launcher, err := configfile.Capture(ctx, directory, launcherName, maximumSourceBytes) + if err != nil { + return State{}, err + } + edit, err := m.Kernel.EditCLIRegistration(ctx, source.shell, source.text, directory, executable, "inspect", string(launcher.Bytes())) + if err != nil { + return State{}, err + } + installed := edit.Installed && string(launcher.Bytes()) == edit.Launcher && launcherExecutable(launcher.Path()) + return State{Shell: source.shell, Target: source.target, Launcher: launcher.Path(), Installed: installed, Registered: edit.Installed, source: source, launcher: launcher}, nil +} + +func (m *Manager) Apply(ctx context.Context, baseline State, install bool) (State, error) { + m.mu.Lock() + defer m.mu.Unlock() + directory, executable, err := m.paths() + if err != nil { + return State{}, err + } + if baseline.Launcher != filepath.Join(directory, launcherName) { + return State{}, configfile.ErrConflict + } + if err := baseline.source.verify(ctx); err != nil { + return State{}, err + } + action := "remove" + if install { + action = "install" + } + edit, err := m.Kernel.EditCLIRegistration(ctx, baseline.Shell, baseline.source.text, directory, executable, action, string(baseline.launcher.Bytes())) + if err != nil { + return State{}, err + } + if install { + // Repair only our complete owned launcher, including after an app update or move. + if baseline.launcher.Exists() && !edit.Owned { + return State{}, ErrLauncherConflict + } + if _, err := baseline.launcher.Replace(ctx, []byte(edit.Launcher), func() error { return baseline.source.verify(ctx) }); err != nil { + return State{}, err + } + if err := makeLauncherExecutable(baseline.Launcher); err != nil { + return State{}, err + } + } + if err := baseline.source.replace(ctx, edit.Source); err != nil { + return State{}, err + } + if !install && baseline.launcher.Exists() && edit.Owned { + if _, err := baseline.launcher.Remove(ctx, nil); err != nil { + return State{}, err + } + } + return m.read(ctx) +} diff --git a/desktop/internal/cli/registration_unix_test.go b/desktop/internal/cli/registration_unix_test.go new file mode 100644 index 0000000000..db2c731db0 --- /dev/null +++ b/desktop/internal/cli/registration_unix_test.go @@ -0,0 +1,150 @@ +//go:build !windows + +package cli + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +func TestCLIRegistrationReadsWithoutWritingAndPublishesGuardedEdits(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + root := t.TempDir() + source := filepath.Join(root, ".zshrc") + original := "# keep personal settings\nexport EDITOR=vi\n" + if err := os.WriteFile(source, []byte(original), 0600); err != nil { + t.Fatal(err) + } + m := &Manager{Kernel: core.NewClient(), Directory: filepath.Join(root, "user bin"), Executable: "/Applications/Lithe's.app/Contents/MacOS/lithe", source: func(ctx context.Context) (nativeSource, error) { return captureSource(ctx, "zsh", source) }} + state, err := m.Read(ctx) + if err != nil || state.Installed { + t.Fatalf("read: %+v %v", state, err) + } + if _, err := os.Stat(m.Directory); !os.IsNotExist(err) { + t.Fatalf("read created launcher directory: %v", err) + } + state, err = m.Apply(ctx, state, true) + if err != nil || !state.Installed { + t.Fatalf("install/readback: %+v %v", state, err) + } + registered, err := os.ReadFile(source) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(string(registered), original) { + t.Fatal("changed personal configuration") + } + state, err = m.Apply(ctx, state, true) + if err != nil || !state.Installed { + t.Fatalf("idempotent install: %v", err) + } + m.Executable = "/Applications/Updated Lithe.app/Contents/MacOS/lithe" + state, err = m.Read(ctx) + if err != nil || state.Installed || !state.Registered { + t.Fatalf("moved installation status: %+v %v", state, err) + } + state, err = m.Apply(ctx, state, true) + if err != nil || !state.Installed { + t.Fatalf("repair moved installation: %v", err) + } + if err := os.WriteFile(source, append(registered, []byte("# external edit\n")...), 0600); err != nil { + t.Fatal(err) + } + if _, err := m.Apply(ctx, state, false); !errors.Is(err, configfile.ErrConflict) { + t.Fatalf("external edit overwritten: %v", err) + } + state, err = m.Read(ctx) + if err != nil { + t.Fatal(err) + } + state, err = m.Apply(ctx, state, false) + if err != nil || state.Installed { + t.Fatalf("remove/readback: %v", err) + } + actual, err := os.ReadFile(source) + if err != nil || string(actual) != original+"# external edit\n" { + t.Fatalf("remove changed personal content: %q %v", actual, err) + } + if _, err := os.Stat(state.Launcher); !os.IsNotExist(err) { + t.Fatalf("launcher left after removal: %v", err) + } +} + +func TestCLIRegistrationRejectsUnrelatedLauncherAndRetargetedSymlink(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + root := t.TempDir() + target := filepath.Join(root, "profile") + link := filepath.Join(root, ".zshrc") + if err := os.WriteFile(target, []byte("# dotfiles\n"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, link); err != nil { + t.Fatal(err) + } + m := &Manager{Kernel: core.NewClient(), Directory: filepath.Join(root, "bin"), Executable: "/app/lithe", source: func(ctx context.Context) (nativeSource, error) { return captureSource(ctx, "zsh", link) }} + state, err := m.Read(ctx) + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(m.Directory, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(state.Launcher, []byte("#!/bin/sh\necho someone else\n"), 0700); err != nil { + t.Fatal(err) + } + state, err = m.Read(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := m.Apply(ctx, state, true); !errors.Is(err, ErrLauncherConflict) { + t.Fatalf("unrelated launcher overwritten: %v", err) + } + if err := os.Remove(link); err != nil { + t.Fatal(err) + } + other := filepath.Join(root, "other") + if err := os.WriteFile(other, []byte("# other\n"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Symlink(other, link); err != nil { + t.Fatal(err) + } + if _, err := m.Apply(ctx, state, true); !errors.Is(err, configfile.ErrConflict) { + t.Fatalf("retargeted symlink not rejected: %v", err) + } +} + +func TestCLILauncherPreservesNativeArguments(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + root := t.TempDir() + executable := filepath.Join(root, "Lithe's app") + if err := os.WriteFile(executable, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\"\n"), 0700); err != nil { + t.Fatal(err) + } + edit, err := core.NewClient().EditCLIRegistration(ctx, "zsh", "", filepath.Join(root, "bin"), executable, "install", "") + if err != nil { + t.Fatal(err) + } + launcher := filepath.Join(root, "lithe") + if err := os.WriteFile(launcher, []byte(edit.Launcher), 0700); err != nil { + t.Fatal(err) + } + cmd := exec.CommandContext(ctx, launcher, "--", "-中文 file.txt") + cmd.WaitDelay = time.Second + output, err := cmd.CombinedOutput() + if err != nil || string(output) != "--cli\n--\n-中文 file.txt\n" { + t.Fatalf("launcher arguments: %q %v", output, err) + } +} diff --git a/desktop/internal/cli/source_unix.go b/desktop/internal/cli/source_unix.go new file mode 100644 index 0000000000..8a0f26d902 --- /dev/null +++ b/desktop/internal/cli/source_unix.go @@ -0,0 +1,115 @@ +//go:build !windows + +package cli + +import ( + "context" + "os" + "path/filepath" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/localshell" +) + +const launcherName = "lithe" + +type nativeSource struct { + shell, target, text string + snapshot configfile.Snapshot + original string +} + +func readNativeSource(ctx context.Context) (nativeSource, error) { + home, err := os.UserHomeDir() + if err != nil { + return nativeSource{}, err + } + shell := filepath.Base(localshell.DefaultShell()) + var target string + switch shell { + case "zsh": + root := os.Getenv("ZDOTDIR") + if root == "" { + root = home + } + target = filepath.Join(root, ".zshrc") + case "bash": + // Login bash reads the first existing profile. Interactive non-login shells + // read .bashrc; the default login profile remains the registration source. + target = filepath.Join(home, ".bash_profile") + for _, name := range []string{".bash_profile", ".bash_login", ".profile"} { + candidate := filepath.Join(home, name) + _, err := os.Stat(candidate) + if err == nil { + target = candidate + break + } + // log-exempt: 预期的缺失:bash 按顺序选择第一个存在的登录配置。 + if !os.IsNotExist(err) { + return nativeSource{}, err + } + } + case "sh": + target = filepath.Join(home, ".profile") + case "fish": + root := os.Getenv("XDG_CONFIG_HOME") + if root == "" { + root = filepath.Join(home, ".config") + } + target = filepath.Join(root, "fish", "config.fish") + default: + return nativeSource{}, ErrUnsupportedShell + } + return captureSource(ctx, shell, target) +} + +func captureSource(ctx context.Context, shell, target string) (nativeSource, error) { + // Resolve an existing dotfile's symlink so dotfile managers keep their links. + original := target + resolved, err := filepath.EvalSymlinks(target) + if err == nil { + target = resolved + } else if !os.IsNotExist(err) { + return nativeSource{}, err + } + snapshot, err := configfile.Capture(ctx, filepath.Dir(target), filepath.Base(target), maximumSourceBytes) + if err != nil { + return nativeSource{}, err + } + text, err := snapshot.Text() + if err != nil { + return nativeSource{}, err + } + source := nativeSource{shell: shell, target: target, snapshot: snapshot, original: original} + if text != nil { + source.text = *text + } + return source, nil +} + +func (s nativeSource) verify(ctx context.Context) error { + resolved, err := filepath.EvalSymlinks(s.original) + if os.IsNotExist(err) && s.original == s.target { + return s.snapshot.Verify(ctx) + } + if err != nil { + return err + } + if resolved != s.target { + return configfile.ErrConflict + } + return s.snapshot.Verify(ctx) +} +func (s nativeSource) replace(ctx context.Context, text string) error { + if text == s.text { + return s.verify(ctx) + } + _, err := s.snapshot.Replace(ctx, []byte(text), func() error { return s.verify(ctx) }) + return err +} + +func makeLauncherExecutable(path string) error { return os.Chmod(path, 0o700) } +func launcherExecutable(path string) bool { + info, err := os.Stat(path) + return err == nil && info.Mode().Perm()&0o100 != 0 +} diff --git a/desktop/internal/cli/source_windows.go b/desktop/internal/cli/source_windows.go new file mode 100644 index 0000000000..fc45cf8618 --- /dev/null +++ b/desktop/internal/cli/source_windows.go @@ -0,0 +1,100 @@ +package cli + +import ( + "context" + "errors" + "syscall" + "unsafe" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "golang.org/x/sys/windows" + "golang.org/x/sys/windows/registry" +) + +const launcherName = "lithe.cmd" + +type nativeSource struct { + shell, target, text string + kind uint32 + exists bool +} + +func readNativeSource(ctx context.Context) (source nativeSource, err error) { + if err := ctx.Err(); err != nil { + return source, err + } + source = nativeSource{shell: "windows", target: `HKEY_CURRENT_USER\Environment\Path`, kind: registry.EXPAND_SZ} + key, err := registry.OpenKey(registry.CURRENT_USER, `Environment`, registry.QUERY_VALUE) + // log-exempt: 预期的缺失:首次注册前用户环境变量或 PATH 可以不存在。 + if errors.Is(err, windows.ERROR_FILE_NOT_FOUND) { + return source, nil + } + if err != nil { + return source, err + } + defer func() { err = errors.Join(err, key.Close()) }() + text, kind, err := key.GetStringValue("Path") + if errors.Is(err, windows.ERROR_FILE_NOT_FOUND) { + return source, nil + } + if err != nil { + return source, err + } + if len(text) > maximumSourceBytes { + return source, configfile.ErrTooLarge + } + source.text, source.kind, source.exists = text, kind, true + return source, nil +} + +func (s nativeSource) verify(ctx context.Context) error { + current, err := readNativeSource(ctx) + if err != nil { + return err + } + if current.text != s.text || current.kind != s.kind || current.exists != s.exists { + return configfile.ErrConflict + } + return nil +} + +func (s nativeSource) replace(ctx context.Context, text string) (err error) { + if err := s.verify(ctx); err != nil { + return err + } + if text == s.text { + return nil + } + key, _, err := registry.CreateKey(registry.CURRENT_USER, `Environment`, registry.SET_VALUE) + if err != nil { + return err + } + defer func() { err = errors.Join(err, key.Close()) }() + if s.kind == registry.SZ { + err = key.SetStringValue("Path", text) + } else { + err = key.SetExpandStringValue("Path", text) + } + if err != nil { + return err + } + // Existing processes retain their environment. Explorer and new terminals learn + // the user PATH through the standard bounded WM_SETTINGCHANGE broadcast. + name, err := windows.UTF16PtrFromString("Environment") + if err != nil { + return err + } + var result uintptr + call := windows.NewLazySystemDLL("user32.dll").NewProc("SendMessageTimeoutW") + ok, _, callErr := call.Call(0xffff, 0x001a, 0, uintptr(unsafe.Pointer(name)), 2, 2000, uintptr(unsafe.Pointer(&result))) + if ok == 0 { + if callErr == syscall.Errno(0) { + return errors.New("environment change broadcast timed out") + } + return callErr + } + return nil +} + +func makeLauncherExecutable(string) error { return nil } +func launcherExecutable(string) bool { return true } diff --git a/desktop/internal/core/cli.go b/desktop/internal/core/cli.go new file mode 100644 index 0000000000..10de8085db --- /dev/null +++ b/desktop/internal/core/cli.go @@ -0,0 +1,54 @@ +package core + +import "context" + +// CLILaunch is Core's interpretation of one bounded CLI invocation. +type CLILaunch struct { + Action string `json:"action"` + Path string `json:"path"` + Detach bool `json:"detach"` +} + +func (c *Client) PlanCLILaunch(ctx context.Context, args []string) (CLILaunch, error) { + var result CLILaunch + err := c.Execute(ctx, "application.cli.planLaunch", struct { + Args []string `json:"args"` + }{nonNil(args)}, &result) + return result, err +} + +// CLITarget is the session policy for an observed native path. +type CLITarget struct { + Mode string `json:"mode"` + Plugins bool `json:"plugins"` + Commands []string `json:"commands"` +} + +func (c *Client) CLIOpenTarget(ctx context.Context, kind string) (CLITarget, error) { + var result CLITarget + err := c.Execute(ctx, "application.cli.openTarget", struct { + Kind string `json:"kind"` + }{kind}, &result) + return result, err +} + +// CLIRegistrationEdit contains the complete owned launcher and source edit. +type CLIRegistrationEdit struct { + Installed bool `json:"installed"` + Owned bool `json:"owned"` + Source string `json:"source"` + Launcher string `json:"launcher"` +} + +func (c *Client) EditCLIRegistration(ctx context.Context, shell, source, directory, executable, action, launcherSource string) (CLIRegistrationEdit, error) { + var result CLIRegistrationEdit + err := c.Execute(ctx, "application.cli.editRegistration", struct { + Shell string `json:"shell"` + LauncherSource string `json:"launcherSource"` + Source string `json:"source"` + Directory string `json:"directory"` + Executable string `json:"executable"` + Action string `json:"action"` + }{shell, launcherSource, source, directory, executable, action}, &result) + return result, err +} diff --git a/desktop/internal/core/cli_test.go b/desktop/internal/core/cli_test.go new file mode 100644 index 0000000000..03817aef54 --- /dev/null +++ b/desktop/internal/core/cli_test.go @@ -0,0 +1,54 @@ +package core + +import ( + "context" + "encoding/json" + "os" + "slices" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" +) + +func TestCLISharedFixture(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + data, err := os.ReadFile(contractfixture.CoreFixture("application/cli-v1.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Launch []struct { + Args []string + Action string + Detach bool + } + Targets []struct { + Kind, Mode string + Plugins bool + Commands []string + } + } + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + client := NewClient() + for _, test := range fixture.Launch { + plan, err := client.PlanCLILaunch(ctx, test.Args) + if err != nil || plan.Action != test.Action || plan.Detach != test.Detach { + t.Fatalf("launch %+v: %+v %v", test, plan, err) + } + } + for _, test := range fixture.Targets { + target, err := client.CLIOpenTarget(ctx, test.Kind) + if err != nil || target.Mode != test.Mode || target.Plugins != test.Plugins { + t.Fatalf("target %+v: %+v %v", test, target, err) + } + for _, command := range test.Commands { + if !slices.Contains(target.Commands, command) { + t.Fatalf("target %s does not permit %s", test.Kind, command) + } + } + } +} diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 25fc0d191f..c4feb96d40 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -306,6 +306,21 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.buildSettings.why": "Why this one?", "desktop.buildSettings.writes": "· writes to {targets}", "desktop.changelists.moveSelected": "Move {count} Selected to Change List", + "desktop.cli.conflict": "The shell configuration changed. Refresh its status before applying again.", + "desktop.cli.failed": "Could not update CLI registration. Check the configuration permissions and refresh to try again.", + "desktop.cli.help": "Register the lithe command for your default shell. This writes only the shown shell configuration or user PATH and a launcher in your user data. Registration is off by default. Use lithe to open a project, or lithe for an editor with bundled highlighting and no plugins.", + "desktop.cli.launcherConflict": "Another command already exists at the launcher path. Move it aside, then refresh and register again.", + "desktop.cli.notRegistered": "Not registered", + "desktop.cli.refresh": "Refresh status", + "desktop.cli.register": "Register lithe command", + "desktop.cli.registered": "Registered", + "desktop.cli.remove": "Remove registration", + "desktop.cli.reopenTerminal": "Open a new terminal for the change to take effect.", + "desktop.cli.repair": "Repair registration", + "desktop.cli.source": "Configuration: {target}", + "desktop.cli.title": "CLI", + "desktop.cli.unsupportedShell": "This default shell is not supported yet. Use zsh, bash, sh or fish, then refresh.", + "desktop.cli.usage": "Usage: lithe [--] [file-or-folder]\nlithe --help\nlithe --version\n\nA folder opens a project; a file opens in Single File Mode without plugins.", "desktop.clone.busy": "Cloning…", "desktop.clone.cancel": "Cancel", "desktop.clone.choose": "Choose…", @@ -1998,6 +2013,11 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.settings.updates.upToDate": "Lithe {version} is up to date.", "desktop.settings.updates.update": "Update", "desktop.settings.updates.waiting": "Lithe moves back to Stable with the first stable release after {version}.", + "desktop.singleFile.help": "Bundled syntax highlighting and text editing, with an optional terminal. Project indexing, Git and all plugins remain inactive.", + "desktop.singleFile.mode": "Single File Mode", + "desktop.singleFile.openFile": "Open File…", + "desktop.singleFile.openFolder": "Open Folder as Project", + "desktop.singleFile.openFolderHelp": "Open the containing folder in a new project window, where project services and enabled plugins become available.", "desktop.sourceSettings.add": "Add override", "desktop.sourceSettings.allEntriesShown": "All available entries are shown.", "desktop.sourceSettings.cancel": "Cancel", @@ -3546,6 +3566,21 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.buildSettings.why": "为什么是这个?", "desktop.buildSettings.writes": "· 写入 {targets}", "desktop.changelists.moveSelected": "将所选 {count} 个变更移到变更列表", + "desktop.cli.conflict": "shell 配置已被修改。请刷新状态后重新操作。", + "desktop.cli.failed": "无法读取或更新 CLI 注册。请检查配置文件权限,刷新状态后重试。", + "desktop.cli.help": "为默认 shell 注册 lithe 命令。此操作会修改下方显示的 shell 配置或用户 PATH,并在用户数据目录创建启动器。默认不注册。lithe <文件夹> 打开项目,lithe <文件> 打开仅使用内置高亮、不激活插件的编辑器。", + "desktop.cli.launcherConflict": "启动器位置已存在其他命令。请先移走该文件,再刷新并重新注册。", + "desktop.cli.notRegistered": "未注册", + "desktop.cli.refresh": "刷新状态", + "desktop.cli.register": "注册 lithe 命令", + "desktop.cli.registered": "已注册", + "desktop.cli.remove": "移除注册", + "desktop.cli.reopenTerminal": "重新打开终端后生效。", + "desktop.cli.repair": "修复注册", + "desktop.cli.source": "配置来源:{target}", + "desktop.cli.title": "CLI", + "desktop.cli.unsupportedShell": "暂不支持当前默认 shell。请使用 zsh、bash、sh 或 fish,然后刷新状态。", + "desktop.cli.usage": "用法:lithe [--] [文件或文件夹]\nlithe --help\nlithe --version\n\n文件夹以项目打开;文件以不激活插件的单文件模式打开。", "desktop.clone.busy": "正在克隆…", "desktop.clone.cancel": "取消", "desktop.clone.choose": "选择…", @@ -5238,6 +5273,11 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.settings.updates.upToDate": "Lithe {version} 已是最新版本。", "desktop.settings.updates.update": "更新", "desktop.settings.updates.waiting": "正式版发布 {version} 之后的版本时切回正式版。", + "desktop.singleFile.help": "提供内置语法高亮和文本编辑,可按需打开终端。项目索引、Git 和所有插件保持关闭。", + "desktop.singleFile.mode": "单文件模式", + "desktop.singleFile.openFile": "打开文件…", + "desktop.singleFile.openFolder": "以项目打开所在文件夹", + "desktop.singleFile.openFolderHelp": "在新项目窗口中打开所在文件夹,启用项目服务和已启用的插件。", "desktop.sourceSettings.add": "添加覆盖", "desktop.sourceSettings.allEntriesShown": "所有可用条目已列出。", "desktop.sourceSettings.cancel": "取消", diff --git a/desktop/internal/settingswindow/cli_view.go b/desktop/internal/settingswindow/cli_view.go new file mode 100644 index 0000000000..559939f1bc --- /dev/null +++ b/desktop/internal/settingswindow/cli_view.go @@ -0,0 +1,130 @@ +package settingswindow + +import ( + "context" + "errors" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/cli" + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/ui" +) + +type cliRequest struct { + baseline cli.State + action string +} + +type cliRegistration struct { + effect *ui.EffectState[cli.State, *cliRequest] + request *cliRequest + state cli.State + err error + loaded bool + changed bool +} + +func (w *window) declareCLI(c ui.C) { + s := &w.cli + if s.effect != nil && s.request != nil { + ui.Effect(c, s.effect, s.request) + } +} + +// General > CLI reports the captured native source, and only the explicit +// install/remove button can publish. Leaving or cancelling settings never writes. +func (w *window) cliCard(c ui.C) { + manager := w.ctrl.opts.CLI + if manager == nil { + return + } + s := &w.cli + language := w.marketLanguage() + if s.effect == nil { + s.effect = ui.NewEffectKeyed[cli.State, *cliRequest](func(parent context.Context, request *cliRequest) (cli.State, error) { + ctx, cancel := context.WithTimeout(parent, 10*time.Second) + defer cancel() + if request.action == "read" { + return manager.Read(ctx) + } + return manager.Apply(ctx, request.baseline, request.action == "install") + }) + s.request = &cliRequest{action: "read"} + } + if state, err, ok := s.effect.Take(); ok { + s.changed = s.request != nil && s.request.action != "read" && err == nil + s.request, s.err, s.loaded = nil, err, err == nil + if err == nil { + s.state = state + } else { + // log-exempt: 用户取消:关闭设置窗口撤销尚未发布的读取或注册请求。 + if !errors.Is(err, context.Canceled) { + reportSettingsError(w.ctrl.opts, "cli_registration", err) + } + } + } + w.card(c, i18n.Shared(language, "desktop.cli.title"), i18n.Shared(language, "desktop.cli.help"), func() { + ui.Row(c).FillWidth().Items(ui.Center).Gap(10).Children(func() { + status := i18n.Shared(language, "desktop.cli.notRegistered") + if s.state.Installed { + status = i18n.Shared(language, "desktop.cli.registered") + } + if s.request != nil { + status = i18n.Shared(language, "native.loading") + } + ui.Text(c, status).Color(w.pal.muted).Grow(1) + if s.loaded { + label, action := i18n.Shared(language, "desktop.cli.register"), "install" + if s.state.Registered { + label, action = i18n.Shared(language, "desktop.cli.remove"), "remove" + } + if ui.Button(c, label).Outline().Disabled(s.request != nil).Clicked() { + c.After(func() { + if w.ctrl.opts.CLIAction != nil { + w.ctrl.opts.CLIAction(action) + } + s.request = &cliRequest{baseline: s.state, action: action} + }) + } + } + if s.loaded && s.state.Registered && !s.state.Installed { + if ui.Button(c, i18n.Shared(language, "desktop.cli.repair")).Outline().Disabled(s.request != nil).Clicked() { + c.After(func() { + if w.ctrl.opts.CLIAction != nil { + w.ctrl.opts.CLIAction("repair") + } + s.request = &cliRequest{baseline: s.state, action: "install"} + }) + } + } + if ui.Button(c, i18n.Shared(language, "desktop.cli.refresh")).Ghost().Disabled(s.request != nil).Clicked() { + c.After(func() { + if w.ctrl.opts.CLIAction != nil { + w.ctrl.opts.CLIAction("refresh") + } + s.request = &cliRequest{action: "read"} + }) + } + }) + if s.loaded { + ui.Wrap(c, i18n.SharedFormat(language, "desktop.cli.source", map[string]string{"target": s.state.Target})).FontSize(11).Color(w.pal.subtle) + ui.Wrap(c, s.state.Launcher).Mono().FontSize(11).Color(w.pal.subtle) + } + if s.changed { + ui.Wrap(c, i18n.Shared(language, "desktop.cli.reopenTerminal")).FontSize(12).Color(w.pal.muted) + } + if s.err != nil { + message := i18n.Shared(language, "desktop.cli.failed") + switch { + case errors.Is(s.err, cli.ErrUnsupportedShell): + message = i18n.Shared(language, "desktop.cli.unsupportedShell") + case errors.Is(s.err, cli.ErrLauncherConflict): + message = i18n.Shared(language, "desktop.cli.launcherConflict") + case errors.Is(s.err, configfile.ErrConflict): + message = i18n.Shared(language, "desktop.cli.conflict") + } + ui.Wrap(c, message).FontSize(12).Color(w.pal.danger) + } + }) +} diff --git a/desktop/internal/settingswindow/cli_visual_test.go b/desktop/internal/settingswindow/cli_visual_test.go new file mode 100644 index 0000000000..8c57445188 --- /dev/null +++ b/desktop/internal/settingswindow/cli_visual_test.go @@ -0,0 +1,59 @@ +//go:build vivahead && lithevisual + +package settingswindow + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/cli" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/headless" +) + +func TestVisualCLISettings(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, language := range []i18n.Language{i18n.Chinese, i18n.English} { + for _, theme := range []string{"dark", "light"} { + t.Run(language.Code()+"-"+theme, func(t *testing.T) { + // Actual shell configuration is read only. This scene never clicks registration. + manager := cli.New() + manager.Directory = filepath.Join(t.TempDir(), "bin") + w := newWindow(NewController(Options{CLI: manager, Text: func() *i18n.Messages { return i18n.For(language) }, Language: func() i18n.Language { return language }, SystemLanguage: language, SystemDark: func() bool { return theme == "dark" }}), Values{Theme: theme, Language: language.Code()}) + config := w.config() + config.Width, config.Height = 1120, 820 + session, err := headless.Open(config, nil, headless.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + d := &windowDriver{t: t, w: w, driver: session.Driver()} + d.pump() + deadline := time.NewTimer(5 * time.Second) + defer deadline.Stop() + for !w.cli.loaded && w.cli.err == nil { + select { + case <-d.driver.Wakes(): + d.pump() + case <-deadline.C: + t.Fatal("CLI source read timed out") + } + } + if w.cli.err != nil { + t.Fatal(w.cli.err) + } + if err := session.Screenshot(filepath.Join(out, "cli-settings-"+language.Code()+"-"+theme+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/desktop/internal/settingswindow/controller.go b/desktop/internal/settingswindow/controller.go index 9d0c8736bc..b01a0dc126 100644 --- a/desktop/internal/settingswindow/controller.go +++ b/desktop/internal/settingswindow/controller.go @@ -15,6 +15,7 @@ import ( "sync" "time" + "github.com/1lck/Lithe-IDEA/desktop/internal/cli" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/fontprefs" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" @@ -351,6 +352,8 @@ type SearchPreferencesSource interface { // Options configure the settings window. type Options struct { + CLI *cli.Manager + CLIAction func(string) SearchPreferences SearchPreferencesSource // PluginInstallsClosed releases downloads retained by the settings session. PluginInstallsClosed func() diff --git a/desktop/internal/settingswindow/model.go b/desktop/internal/settingswindow/model.go index b25a14c420..d6fb08ed39 100644 --- a/desktop/internal/settingswindow/model.go +++ b/desktop/internal/settingswindow/model.go @@ -321,6 +321,8 @@ func kindTitle(language i18n.Language, kind string) string { // pageKeywords are the words besides its title a search finds a page by. func pageKeywords(language i18n.Language, id pageID) string { switch id { + case pageGeneral: + return i18n.Shared(language, "desktop.cli.title") case pageBuild: return i18n.Shared(language, "desktop.buildSettings.keywordsBuild") case pageToolchains: diff --git a/desktop/internal/settingswindow/window.go b/desktop/internal/settingswindow/window.go index 62be178c9e..3d7de95c03 100644 --- a/desktop/internal/settingswindow/window.go +++ b/desktop/internal/settingswindow/window.go @@ -75,6 +75,7 @@ const ( // window is one open settings window and the model of its Page. Everything in it runs on // its window thread, but for the fields that say so. type window struct { + cli cliRegistration searchDraft searchPreferencesDraft editorDelay ui.Field editorDelayReady bool @@ -511,6 +512,7 @@ func (w *window) reportMarket(previous marketStatus) { // of the declaration, so a request made while the page was declared starts in the same // paint, and in every paint, so leaving a page does not cancel what it asked for. func (w *window) declareWork(c ui.C) { + w.declareCLI(c) if d := &w.searchDraft; d.effect != nil && d.work != nil { ui.Effect(c, d.effect, d.work) } diff --git a/desktop/internal/settingswindow/window_view.go b/desktop/internal/settingswindow/window_view.go index 5b536c2263..19d2f22163 100644 --- a/desktop/internal/settingswindow/window_view.go +++ b/desktop/internal/settingswindow/window_view.go @@ -565,6 +565,7 @@ func (w *window) generalPage(c ui.C) { w.themePick = w.sess.values.Theme w.languagePick = languageCode(languageIndex(w.sess.values.Language)) w.pageScroll(c, pageGeneral, func() { + w.cliCard(c) w.card(c, settings.Appearance, settings.AppearanceHelp, func() { choice := func() { ui.Choice(c, &w.themePick, themeValues[:], w.themeLabel).Width(420).Shrink(1).MinWidth(0).Label(settings.AppearanceMode) diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index b92053a33b..2877cf9474 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -52,6 +52,7 @@ import ( // the calls that read the disk or run Git, so a screen can be checked against answers the // test chooses. type Kernel interface { + CLIOpenTarget(context.Context, string) (core.CLITarget, error) ReadSourceSettings(context.Context, json.RawMessage) (core.SourceSettingsState, error) PlanSourceSettingsEdits(context.Context, core.SourceSettingsSnapshot, []core.SourceSettingsEdits, bool) ([]core.SourceSettingsWrite, error) DecodeSourceSettingsReceipt(context.Context, core.SourceSettingsWrite, json.RawMessage) (core.SourceSettingsReceipt, error) @@ -251,6 +252,8 @@ type Options struct { // OpenPath is a project folder the window opens when it starts; a window launched to show a // worktree in a new window gets it from the command line. OpenPath string + // OpenFile creates an isolated document session, before any plugin service exists. + OpenFile string // Languages are the system's preferred languages, most preferred first; nil asks // the system. Languages []string @@ -444,6 +447,8 @@ const ( // keeps the pointer it started for and its result is dropped once a.project is a // different one (see App.background). type project struct { + // standalone owns documents and opt-in terminals; root is a location, never a workspace. + standalone bool // root is the absolute, cleaned path of the project folder. root string // pluginContext belongs to this open project, not to any background consumer. @@ -579,8 +584,11 @@ type App struct { kernel Kernel store *store.Store // startupPath is the project folder the window opens once it exists (Options.OpenPath). - startupPath string - now func() time.Time + startupPath string + startupFile string + documentOnly bool + documentCommands map[string]bool + now func() time.Time // invalidator asks the window for a repaint. Every workbench of the window shares the one // the window was opened with (window_sessions.go). invalidator windowWake @@ -846,6 +854,8 @@ func New(options Options) *App { documentReader: readDocument, store: options.Store, startupPath: options.OpenPath, + startupFile: options.OpenFile, + documentOnly: options.OpenFile != "", now: now, systemLanguage: i18n.Detect(languages), chrome: newChromeState(), @@ -857,6 +867,17 @@ func New(options Options) *App { aiKernel: options.AIKernel, listShells: localshell.InstalledShells, } + if a.documentOnly { + a.aiKernel = nil + policy, err := a.kernel.CLIOpenTarget(context.Background(), "file") + a.documentCommands = make(map[string]bool, len(policy.Commands)) + for _, id := range policy.Commands { + a.documentCommands[id] = true + } + if err != nil { + a.backgroundFailed("single_file_policy", err) + } + } a.gitConsole = core.NewGitConsole(a.gitConsoleChanged) // The settings are read before the log sink is in place; a failure is recorded below, once // it is. The first window first restores the settings an update to another channel asked @@ -939,9 +960,13 @@ func New(options Options) *App { a.backgroundFailed("update_snapshot", restoreErr) } a.loadSearchPreferences() - a.openPlugins(options) + if !a.documentOnly { + a.openPlugins(options) + } a.settingsWindow = a.newSettingsWindow() - a.loadRecent() + if !a.documentOnly { + a.loadRecent() + } a.loadChrome() if options.first == nil && a.store != nil { a.restoreBackground() @@ -1028,15 +1053,23 @@ func (a *App) Run() error { a.startupPath = "" a.post(func(a *App) { a.openProject(path) }) } + if path := a.startupFile; path != "" { + a.startupFile = "" + a.post(func(a *App) { a.openStandaloneFile(path) }) + } // The plugin stack is assembled before the window exists, because opening a // window is what installs the invalidator its background work needs. a.reloadPluginLanguages() - a.loadGitHubAccount() + if !a.documentOnly { + a.loadGitHubAccount() + } // Core's stop time applies to every process stopped from now on, and Core decides what an // earlier run left behind; both need the window, which delivers their answers. - a.refreshStopGrace() - a.refreshConsoleEncodings() - a.planStartupSweep() + if !a.documentOnly { + a.refreshStopGrace() + a.refreshConsoleEncodings() + a.planStartupSweep() + } // Development builds mark the Dock icon without changing the product name in the UI. if buildinfo.Development { application.SetDockBadge(a.text.App.DevBadge) diff --git a/desktop/internal/workbench/catalog.go b/desktop/internal/workbench/catalog.go index d93966c673..98492289ee 100644 --- a/desktop/internal/workbench/catalog.go +++ b/desktop/internal/workbench/catalog.go @@ -553,6 +553,13 @@ const kernelCallTimeout = 2 * time.Second // kernel. A missing file is the default layout; an unreadable one is reported and // replaced by the default layout on the next change. func (a *App) loadChrome() { + if a.documentOnly { + // A standalone window never restores project panels or changes their saved layout. + layout := defaultLayout() + layout.Open = nil + a.chrome.apply(layout) + return + } var saved core.ChromeLayout found, err := a.store.Load(layoutFile, &saved) if err != nil { @@ -601,7 +608,7 @@ func (a *App) reduceChrome(action core.ChromeAction) { if !a.chrome.isOpen(catalogIndex[itemProblems]) { a.resetProblems() } - if !changed { + if !changed || a.documentOnly { return } saved := a.chrome.withAbsent(layout) diff --git a/desktop/internal/workbench/chrome_view.go b/desktop/internal/workbench/chrome_view.go index 4f6fcd84b2..d3663cc1b2 100644 --- a/desktop/internal/workbench/chrome_view.go +++ b/desktop/internal/workbench/chrome_view.go @@ -629,7 +629,7 @@ func (a *App) projectMenu(c ui.C, anchor ui.Box) { var buf [chromeMenuRecents]int recents := a.menuRecents(&buf) var created, chosen, cloned, current, closing bool - picked := -1 + picked, removed := -1, -1 spec := ui.PopoverSpec{Align: ui.Start, Offset: chromeMenuOffset, Width: chromeMenuWidth, ConsumeOutsidePress: true} open := true ui.PopoverWith(c, anchor, spec, &open, func() { @@ -655,7 +655,10 @@ func (a *App) projectMenu(c ui.C, anchor ui.Box) { row := a.welcome.row(path, len(a.recent)) missing := a.missing[path] // A folder that is gone cannot be opened, so its row is shown and not offered. - if hit, _ := a.projectMenuRow(c.Key(path), row, a.title.branches[path], false, missing); hit && !missing { + hit, remove := a.projectMenuRow(c.Key(path), row, a.title.branches[path], false, missing) + if remove { + removed = i + } else if hit && !missing { picked = i } } @@ -675,6 +678,12 @@ func (a *App) projectMenu(c ui.C, anchor ui.Box) { a.title.projectOpen = false a.performed("workspace.close", surfaceMenu) a.post(func(a *App) { a.closeProject() }) + case removed >= 0: + path := a.recent[removed].Path + c.After(func() { + a.performed("workspace.recent.remove", surfaceMenu) + a.reduceRecent(a.recent, core.RemoveRecent(path), true) + }) case picked >= 0: // The path is taken now: opening a project replaces the recent list the index is into. path := a.recent[picked].Path @@ -715,13 +724,14 @@ func (a *App) menuTitle(c ui.C, label string) { } // projectMenuRow declares one project of the menu: its badge, its name, its folder and, when -// it is a repository, its branch. It reports a click on the row and, for the open project, a -// click on the button at its end that closes the project. The open project is marked as +// it is a repository, its branch. The trailing X closes the current project or removes +// a recent record; removing a record never opens or deletes its folder. The open project is marked as // selected. A project whose folder is gone is faded and inert. func (a *App) projectMenuRow(c ui.C, row welcomeRow, branch string, current, missing bool) (clicked, closed bool) { options := gfx.HitOptions{Role: gfx.RoleMenuItem, Cursor: gfx.PointerCursorHand, Description: row.path, Selected: current} if missing { - options.Cursor, options.Disabled, options.Hint = gfx.PointerCursorDefault, true, a.text.Welcome.Missing + // Keep the row enabled so its independent remove button remains reachable. + options.Cursor, options.Hint = gfx.PointerCursorDefault, a.text.Welcome.Missing } item := ui.Row(c).FillWidth().MinHeight(chromeMenuProject).Shrink(0).Items(ui.Center).Gap(chromeMenuGap).PadX(chromeEdge).PadY(chromeMenuRowPad). Radius(a.theme.Metrics.RadiusItem()).HitWith(ui.ID(c), row.name, options) @@ -745,20 +755,21 @@ func (a *App) projectMenuRow(c ui.C, row welcomeRow, branch string, current, mis }) } }) + label := a.text.Welcome.MenuRemove if current { - closed = a.menuClose(c) + label = a.text.Title.CloseProject } + closed = a.menuProjectDismiss(c, label) }) - return item.Clicked(), closed + return item.Clicked() && !closed && !missing, closed } -// menuClose declares the button at the end of the open project's row that closes the -// project, and reports a click on it. -func (a *App) menuClose(c ui.C) bool { +// menuProjectDismiss presents the action appropriate to this section of the menu. +func (a *App) menuProjectDismiss(c ui.C, label string) bool { k := c.Part("close") button := a.chromeHover(ui.Row(k).Size(chromeMenuClosing, chromeMenuClosing).Shrink(0).Center(). Radius(a.theme.Metrics.RadiusItem()). - HitWith(ui.ID(k), a.text.Title.CloseProject, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand})) + HitWith(ui.ID(k), label, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand})).Tooltip(label) button.Children(func() { ui.Icon(k, icons.X).Size(chromeMarkSize, chromeMarkSize).Color(a.colors.Subtle). StateFrom(button).Hover(ui.Look{}.Color(a.colors.Text)) diff --git a/desktop/internal/workbench/commands.go b/desktop/internal/workbench/commands.go index 64b52173bf..8d9d4321d9 100644 --- a/desktop/internal/workbench/commands.go +++ b/desktop/internal/workbench/commands.go @@ -87,11 +87,14 @@ func (a *App) commands() []command { add("language.zh", t.GroupView, t.LanguageChinese, "", a.settings.Language != "zh-Hans", func() { a.setLanguage("zh-Hans") }) add("editor.vimMode", t.GroupEditor, t.ToggleVim, "", true, func() { a.setVimMode(!a.settings.VimMode) }) + if a.documentOnly { + add("document.open", t.GroupEditor, i18n.Shared(a.language(), "desktop.singleFile.openFile"), "", true, a.chooseStandaloneFile) + } addFrom("project.open", t.GroupProject, t.OpenProject, true, a.chooseProject) addFrom("project.new", t.GroupProject, t.NewProject, true, a.openNewProject) addFrom("project.clone", t.GroupProject, t.Clone, true, a.openClone) if p == nil { - return sortCommands(list) + return a.sessionCommands(sortCommands(list)) } add("editor.newScratch", t.GroupEditor, a.text.Commands.NewScratch, "", true, func() { a.newScratch(p) }) add("editor.scratchFiles", t.GroupEditor, a.text.Commands.ScratchFiles, "", true, a.openScratchList) @@ -167,6 +170,10 @@ func (a *App) commands() []command { id := it.id open := a.chrome.isOpen(index) add(toolCommandPrefix+id, t.GroupToolWindows, t.ShowTool(it.label(a.text)), "", !open, func() { + if a.documentOnly && id == itemTerminal { + a.toggleStandaloneTerminal() + return + } a.reduceChrome(core.SetChromeOpen(id, true)) }) } @@ -208,7 +215,7 @@ func (a *App) commands() []command { add("debug.toggleBreakpoint", t.GroupRun, t.ToggleBreakpoint, "", true, func() { a.toggleBreakpoint(p) }) add("terminal.new", t.GroupTerminal, t.NewTerminal, "", true, func() { a.openToolTerminal("") }) - return sortCommands(list) + return a.sessionCommands(sortCommands(list)) } // sortCommands orders the catalog by group, then title, so the list reads the diff --git a/desktop/internal/workbench/compact_menu.go b/desktop/internal/workbench/compact_menu.go index 370a708ad2..527774173e 100644 --- a/desktop/internal/workbench/compact_menu.go +++ b/desktop/internal/workbench/compact_menu.go @@ -73,10 +73,15 @@ func (a *App) compactMenu(c ui.C, anchor ui.Box) { commands := a.commands() ui.Menu(c, anchor, &open, func(menu *ui.MenuItems) { menu.WidthRange(220, 320) - for i, group := range compactMenuGroups(a.text.Commands) { - if i > 0 { + shown := 0 + for _, group := range compactMenuGroups(a.text.Commands) { + if len(compactMenuItems(commands, group.groups)) == 0 { + continue + } + if shown > 0 { menu.Separator() } + shown++ menu.Sub(group.title(a.text.Commands), func(sub *ui.MenuItems) { for _, cmd := range compactMenuItems(commands, group.groups) { item := sub.Item(cmd.title).Disabled(!cmd.enabled) diff --git a/desktop/internal/workbench/debug_gutter.go b/desktop/internal/workbench/debug_gutter.go index d1508493c1..eb5b139a75 100644 --- a/desktop/internal/workbench/debug_gutter.go +++ b/desktop/internal/workbench/debug_gutter.go @@ -31,7 +31,7 @@ type debugGutter struct { // changed, and lets a press on a line number toggle a breakpoint in a file that can have one. func (a *App) applyDebugGutter(p *project, d *document) { g := &d.debugGutter - if d.virtual { + if d.virtual || p.standalone { d.view.SetBreakpointClick(nil) } else { if g.click == nil { diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index 6a94be0ace..f5ff851b5b 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -278,7 +278,7 @@ func (a *App) openFile(p *project, path string) { a.selectDocument(p, d.id) return } - if kind, ok := viewerKindOf(path); ok { + if kind, ok := viewerKindOf(path); ok && !p.standalone { a.openViewer(p, path, kind) return } @@ -322,7 +322,7 @@ func (a *App) openFile(p *project, path string) { location := p.docs.locations[path] delete(p.docs.locations, path) defer a.openFinished(p, path, err) - if errors.Is(err, errNotText) { + if errors.Is(err, errNotText) && !p.standalone { // A binary file opens in the hex viewer rather than not at all. a.openViewer(p, path, viewerHex) return diff --git a/desktop/internal/workbench/editor_menu.go b/desktop/internal/workbench/editor_menu.go index 2c26ba6dc0..68dee749ed 100644 --- a/desktop/internal/workbench/editor_menu.go +++ b/desktop/internal/workbench/editor_menu.go @@ -24,37 +24,39 @@ func (a *App) editorMenuItems(c ui.C, p *project, d *document) func(*ui.MenuItem if menu.Item(a.text.Commands.Replace).Disabled(readOnly).Clicked() { c.After(func() { a.selectDocument(p, d.id); a.openEditorFind(true, surfaceContextMenu) }) } - menu.Separator() - if menu.Item(i18n.Shared(language, "desktop.editorMenu.goToDefinition")).Keys(primary, "b").Clicked() { - c.After(func() { - line, column := d.view.CaretUTF16() - a.startPluginDefinition(p, d, line, column, true) - }) - } - // A right click outside the selection has put the caret on the word clicked, so the - // usages are of that word. - if menu.Item(i18n.Shared(language, "desktop.editorMenu.findUsages")).Keys(gfx.ModifierShift, "f12").Clicked() { - c.After(func() { - line, column := d.view.CaretUTF16() - a.startPluginReferences(p, d, line, column) - }) - } - if menu.Item(i18n.Shared(language, "desktop.editorMenu.rename")).Keys(0, "f2").Disabled(readOnly).Clicked() { - c.After(func() { a.openPluginRename(p, d) }) - } - if menu.Item(i18n.Shared(language, "desktop.editorMenu.reformat")).Disabled(readOnly).Clicked() { - c.After(func() { a.startPluginFormattingAtSelection(p, d) }) - } - _, codeActions := a.editorServer(d, featureCodeActions) - if menu.Item(i18n.Shared(language, "desktop.editorMenu.codeActions")).Keys(gfx.ModifierAlt, "enter").Disabled(readOnly || !codeActions).Clicked() { - c.After(func() { a.startPluginCodeActions(p, d, nil, surfaceContextMenu) }) - } - _, parameterInfo := a.editorServer(d, featureSignatureHelp) - if menu.Item(i18n.Shared(language, "desktop.semantics.signatureHelp")).Keys(primary, "p").Disabled(!parameterInfo).Clicked() { - c.After(func() { - line, column := d.view.CaretUTF16() - a.startPluginSignatureHelp(p, d, line, column, surfaceContextMenu) - }) + if !p.standalone { + menu.Separator() + if menu.Item(i18n.Shared(language, "desktop.editorMenu.goToDefinition")).Keys(primary, "b").Clicked() { + c.After(func() { + line, column := d.view.CaretUTF16() + a.startPluginDefinition(p, d, line, column, true) + }) + } + // A right click outside the selection has put the caret on the word clicked, so the + // usages are of that word. + if menu.Item(i18n.Shared(language, "desktop.editorMenu.findUsages")).Keys(gfx.ModifierShift, "f12").Clicked() { + c.After(func() { + line, column := d.view.CaretUTF16() + a.startPluginReferences(p, d, line, column) + }) + } + if menu.Item(i18n.Shared(language, "desktop.editorMenu.rename")).Keys(0, "f2").Disabled(readOnly).Clicked() { + c.After(func() { a.openPluginRename(p, d) }) + } + if menu.Item(i18n.Shared(language, "desktop.editorMenu.reformat")).Disabled(readOnly).Clicked() { + c.After(func() { a.startPluginFormattingAtSelection(p, d) }) + } + _, codeActions := a.editorServer(d, featureCodeActions) + if menu.Item(i18n.Shared(language, "desktop.editorMenu.codeActions")).Keys(gfx.ModifierAlt, "enter").Disabled(readOnly || !codeActions).Clicked() { + c.After(func() { a.startPluginCodeActions(p, d, nil, surfaceContextMenu) }) + } + _, parameterInfo := a.editorServer(d, featureSignatureHelp) + if menu.Item(i18n.Shared(language, "desktop.semantics.signatureHelp")).Keys(primary, "p").Disabled(!parameterInfo).Clicked() { + c.After(func() { + line, column := d.view.CaretUTF16() + a.startPluginSignatureHelp(p, d, line, column, surfaceContextMenu) + }) + } } if browserPreviewable(d) { if menu.Item(i18n.Shared(language, "desktop.editorMenu.openInBrowser")).Clicked() { diff --git a/desktop/internal/workbench/editor_session.go b/desktop/internal/workbench/editor_session.go index 86194a3a71..739dd7d340 100644 --- a/desktop/internal/workbench/editor_session.go +++ b/desktop/internal/workbench/editor_session.go @@ -78,6 +78,9 @@ type editorRestoreItem struct { // saveEditorSession records the editor of p for the next time the project opens. A project // with no file open forgets its session. func (a *App) saveEditorSession(p *project) { + if p.standalone { + return + } all := map[string]savedEditorSession{} if _, err := a.store.Load(editorSessionFile, &all); err != nil { a.backgroundFailed("editor_session_load", documentLogError(err)) diff --git a/desktop/internal/workbench/editor_view.go b/desktop/internal/workbench/editor_view.go index c5977d5ce2..64a4642565 100644 --- a/desktop/internal/workbench/editor_view.go +++ b/desktop/internal/workbench/editor_view.go @@ -80,10 +80,10 @@ func (a *App) editorGroup(c ui.C, id string) ui.Box { // The tabs fill the strip and give up their room before the buttons do, so they // stay at the end of the strip's first row however many files are open. a.tabBar(c, place, layout, func() { - if isMarkdownDocument(doc) { + if !p.standalone && isMarkdownDocument(doc) { a.markdownContentsButton(c, p, doc) a.pageModeSwitch(c, doc) - } else if (isSVGDocument(doc) && a.previewWeb()) || a.htmlPreviewable(doc) { + } else if !p.standalone && ((isSVGDocument(doc) && a.previewWeb()) || a.htmlPreviewable(doc)) { a.pageModeSwitch(c, doc) } if doc != nil { @@ -110,6 +110,10 @@ func (a *App) editorGroup(c ui.C, id string) ui.Box { // with its rendered page, an SVG file with its picture, an HTML file with its page), of the Diff // tab, of the viewer tab, the LSP Logs tab or the terminal. func (a *App) groupBody(c ui.C, id string, doc *document) { + if a.project.standalone && doc != nil { + a.documentView(c, id, doc) + return + } if isMarkdownDocument(doc) { a.markdownDocument(c, a.project, id, doc) return diff --git a/desktop/internal/workbench/local_history.go b/desktop/internal/workbench/local_history.go index dcb768f056..68d3e1e1e2 100644 --- a/desktop/internal/workbench/local_history.go +++ b/desktop/internal/workbench/local_history.go @@ -106,7 +106,7 @@ func (a *App) renamedLocalHistory(p *project, oldPath, newPath string, before [] // when it is asked for. func (a *App) localHistoryJob(p *project, work func(ctx context.Context, kernel localHistoryKernel, root, storage string, policy core.HistoryPolicy) error) { kernel, ok := a.kernel.(localHistoryKernel) - if !ok || p == nil { + if !ok || p == nil || p.standalone { return } root, policy := p.root, a.settings.LocalHistory.Policy() @@ -188,7 +188,7 @@ type localHistoryState struct { // openLocalHistory shows the snapshots of the file at path. func (a *App) openLocalHistory(p *project, path string) { kernel, ok := a.kernel.(localHistoryKernel) - if !ok || p == nil { + if !ok || p == nil || p.standalone { return } rel, inside := projectRelative(p.root, path) diff --git a/desktop/internal/workbench/project_gradient.go b/desktop/internal/workbench/project_gradient.go index b80af9ea99..3aab8487ce 100644 --- a/desktop/internal/workbench/project_gradient.go +++ b/desktop/internal/workbench/project_gradient.go @@ -36,7 +36,7 @@ var ( // projectGradientOn reports whether the window paints the open project's color. func (a *App) projectGradientOn() bool { - return a.project != nil && !a.settings.HideProjectColors + return a.project != nil && !a.project.standalone && !a.settings.HideProjectColors } // chromeFill is the background of the chrome's own surfaces: none while the gradient or a diff --git a/desktop/internal/workbench/project_menu_test.go b/desktop/internal/workbench/project_menu_test.go new file mode 100644 index 0000000000..a64b179f07 --- /dev/null +++ b/desktop/internal/workbench/project_menu_test.go @@ -0,0 +1,62 @@ +package workbench + +import ( + "os" + "path/filepath" + "slices" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +func TestProjectMenuRemovesRecentRecordWithoutOpeningOrDeleting(t *testing.T) { + for _, missing := range []bool{false, true} { + t.Run(map[bool]string{false: "existing", true: "missing"}[missing], func(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + h.open(t.TempDir()) + p := h.app.project + path := filepath.Join(t.TempDir(), "RecentProject") + if !missing { + if err := os.Mkdir(path, 0700); err != nil { + t.Fatal(err) + } + } + entries := append([]core.RecentProject{{Path: path, LastOpenedAt: 123}}, h.app.recent...) + h.app.reduceRecent(entries, core.NormalizeRecent(), true) + h.app.openProjectMenu() + h.settle() + hit, ok := h.findPageHit(h.app.text.Welcome.MenuRemove) + if !ok { + t.Fatal("recent project has no remove X") + } + h.click(center(hit.Bounds)) + h.settle() + if h.app.project != p || !h.app.title.projectOpen { + t.Fatal("removing recent switched project or closed menu") + } + if slices.ContainsFunc(h.app.recent, func(entry core.RecentProject) bool { return entry.Path == path }) { + t.Fatal("recent record remains") + } + var saved []core.RecentProject + if _, err := h.store.Load(recentFile, &saved); err != nil { + t.Fatal(err) + } + if slices.ContainsFunc(saved, func(entry core.RecentProject) bool { return entry.Path == path }) { + t.Fatal("removed record was not persisted") + } + if !missing { + if info, err := os.Stat(path); err != nil || !info.IsDir() { + t.Fatalf("project folder was removed: %v", err) + } + } + h.clickNamed(h.app.text.Title.CloseProject) + h.settle() + if h.app.project != nil { + t.Fatal("open project's X no longer closes it") + } + if !slices.ContainsFunc(h.app.recent, func(entry core.RecentProject) bool { return entry.Path == p.root }) { + t.Fatal("closing project also erased recent record") + } + }) + } +} diff --git a/desktop/internal/workbench/project_menu_visual_test.go b/desktop/internal/workbench/project_menu_visual_test.go new file mode 100644 index 0000000000..6136923efc --- /dev/null +++ b/desktop/internal/workbench/project_menu_visual_test.go @@ -0,0 +1,60 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +func TestVisualProjectMenuRemove(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, theme := range []string{"dark", "light"} { + for _, language := range []string{"en-US", "zh-Hans"} { + t.Run(theme+"-"+language, func(t *testing.T) { + root := t.TempDir() + current, recent := filepath.Join(root, "CurrentProject"), filepath.Join(root, "RecentProject") + for _, path := range []string{current, recent} { + if err := os.Mkdir(path, 0700); err != nil { + t.Fatal(err) + } + } + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, map[string]string{"theme": theme}); err != nil { + t.Fatal(err) + } + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: &testKernel{Client: core.NewClient()}, Store: prefs, Languages: []string{language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1000, 640 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + h.open(current) + missing := filepath.Join(root, "MissingProject") + h.app.reduceRecent([]core.RecentProject{{Path: recent, LastOpenedAt: 3}, {Path: missing, LastOpenedAt: 2}}, core.NormalizeRecent(), true) + h.app.openProjectMenu() + h.await("missing recent project", func() bool { return h.app.missing[missing] }) + h.settle() + if err := session.Screenshot(filepath.Join(out, "project-menu-remove-"+theme+"-"+language+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/desktop/internal/workbench/project_open_destination.go b/desktop/internal/workbench/project_open_destination.go index affd5ffde6..f6743a16bd 100644 --- a/desktop/internal/workbench/project_open_destination.go +++ b/desktop/internal/workbench/project_open_destination.go @@ -21,6 +21,10 @@ import ( // openProject opens the folder at path, asking first where to open it when the window // already has a project. func (a *App) openProject(path string) { + if a.documentOnly { + a.openProjectInNewWindow(path) + return + } if a.missing[path] { a.askRemoveUnavailableRecent(path) return diff --git a/desktop/internal/workbench/recent_files.go b/desktop/internal/workbench/recent_files.go index 8de55aff8f..f0aceae58c 100644 --- a/desktop/internal/workbench/recent_files.go +++ b/desktop/internal/workbench/recent_files.go @@ -41,7 +41,7 @@ type recentFileState struct { func recentFilesName(root string) string { return "editor-recent-" + draftstore.Key(root) + ".json" } func (a *App) noteRecentFile(p *project, d *document, kind string) { - if d.virtual || d.scratch { + if p.standalone || d.virtual || d.scratch { return } relative, inside := projectRelative(p.root, d.path) diff --git a/desktop/internal/workbench/root.go b/desktop/internal/workbench/root.go index 71712475db..c839658052 100644 --- a/desktop/internal/workbench/root.go +++ b/desktop/internal/workbench/root.go @@ -142,7 +142,9 @@ func (a *App) endPaint() { // and an overlay that hangs off a point of the window is placed against the whole window. func (a *App) page(c ui.C) { ui.Stack(c).Fill().Children(func() { - if a.project == nil { + if a.documentOnly { + a.standaloneWorkbench(c) + } else if a.project == nil { a.welcomePanel(c) } else { a.workbench(c) @@ -158,6 +160,10 @@ func (a *App) page(c ui.C) { // workbench declares the window of an open project: the title bar over the stripes and the // main column, over the status bar. func (a *App) workbench(c ui.C) { + if a.project.standalone { + a.standaloneWorkbench(c) + return + } // A copy: a click on a stripe button changes a.chrome while this paint is still being // declared, and the panels must be declared for the same tool windows the sizes were // worked out for. @@ -245,7 +251,7 @@ func (a *App) shortcutApplies(c ui.C, id string) bool { focused := c.Canvas().Focused() switch id { case shortcuts.InlineEdit: - return a.project != nil && a.focusedDocument(focused) != nil + return a.project != nil && !a.project.standalone && a.focusedDocument(focused) != nil case shortcuts.GoToLine: return a.project != nil && a.focusedTerminal(focused) == nil && (runtime.GOOS == "darwin" || a.focusedDocument(focused) != nil) @@ -271,7 +277,7 @@ func (a *App) runShortcut(id string, view *editorview.View, term *terminal) { } return case shortcuts.InlineEdit: - if p != nil && view != nil { + if p != nil && !p.standalone && view != nil { a.requestInlineEdit(p, view) } return diff --git a/desktop/internal/workbench/search_everywhere.go b/desktop/internal/workbench/search_everywhere.go index bc7cee8d75..5843950e28 100644 --- a/desktop/internal/workbench/search_everywhere.go +++ b/desktop/internal/workbench/search_everywhere.go @@ -158,6 +158,9 @@ func (a *App) openEverywhere(p *project) { } a.everywhereView.open = true a.everywhereView.scope = 0 + if p.standalone { + a.everywhereView.scope = everywhereScopeActions + } a.everywhereView.query.SetText("") p.everywhere.selected = 0 a.focusEverywhere(p) @@ -208,6 +211,9 @@ func (a *App) closeEverywhere(p *project) { func (a *App) updateEverywhere(p *project, query string, scope int) { v, s := &a.everywhereView, &p.everywhere + if p.standalone { + scope = everywhereScopeActions + } options := v.options(scope) if s.query == query && s.scope == scope && s.options == options { return diff --git a/desktop/internal/workbench/search_everywhere_view.go b/desktop/internal/workbench/search_everywhere_view.go index 9159a9fbd3..36a47cf4b7 100644 --- a/desktop/internal/workbench/search_everywhere_view.go +++ b/desktop/internal/workbench/search_everywhere_view.go @@ -33,6 +33,9 @@ func (a *App) everywherePopup(c ui.C) { } s := &p.everywhere scope := v.effectiveScope() + if p.standalone { + scope = everywhereScopeActions + } a.updateEverywhere(p, v.query.Text(), scope) if v.focus { c.Canvas().RequestFocus(everywhereQueryID) @@ -56,7 +59,11 @@ func (a *App) everywherePopup(c ui.C) { Width: width, Offset: 1, Align: ui.Start, KeepOpenOnAnchor: true, }, &v.open, func() { ui.Column(c).FillWidth().Height(height).Gap(8).Children(func() { - a.everywhereScopes(c, p, language) + if p.standalone { + ui.Text(c, i18n.Shared(language, "desktop.everywhere.actions")).Bold() + } else { + a.everywhereScopes(c, p, language) + } field := ui.TextFieldID(c, everywhereQueryID, &v.query, i18n.Shared(language, "desktop.everywhere.title"), i18n.Shared(language, "native.typeToSeeCommands")). Icon(icons.Search).Action(icons.X, i18n.Shared(language, "native.clearSearch")) @@ -504,7 +511,7 @@ func (a *App) everywhereKey(p *project, event gfx.KeyEvent) gfx.EventResult { } } v := &a.everywhereView - if event.Key == gfx.KeyTab && (event.Modifiers == 0 || event.Modifiers == gfx.ModifierShift) { + if !p.standalone && event.Key == gfx.KeyTab && (event.Modifiers == 0 || event.Modifiers == gfx.ModifierShift) { step := 1 if event.Modifiers == gfx.ModifierShift { step = -1 @@ -516,7 +523,7 @@ func (a *App) everywhereKey(p *project, event gfx.KeyEvent) gfx.EventResult { if event.Modifiers != 0 { return gfx.EventResult{} } - if v.effectiveScope() == everywhereScopeActions { + if p.standalone || v.effectiveScope() == everywhereScopeActions { switch event.Key { case gfx.KeyUp: v.actionSelected = max(0, v.actionSelected-1) diff --git a/desktop/internal/workbench/settings.go b/desktop/internal/workbench/settings.go index 725d9d55ec..3626414107 100644 --- a/desktop/internal/workbench/settings.go +++ b/desktop/internal/workbench/settings.go @@ -7,6 +7,7 @@ import ( "runtime" "github.com/1lck/Lithe-IDEA/desktop/internal/buildinfo" + "github.com/1lck/Lithe-IDEA/desktop/internal/cli" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/fontprefs" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" @@ -31,6 +32,8 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { navigation = kernel.SettingsNavigation } return settingswindow.NewController(settingswindow.Options{ + CLI: cli.New(), + CLIAction: func(action string) { a.post(func(a *App) { a.performed("settings.cli."+action, surfaceButton) }) }, SearchPreferences: appSearchPreferences{app: a}, PluginInstallsClosed: func() { a.post(func(a *App) { a.closePluginDownloads() }) @@ -53,6 +56,9 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { a.post(func(a *App) { a.restartSettingsPlugin(id, version, scope, workspace) }) }, MarketplaceInstalled: func(ctx context.Context) (marketplace.Snapshot, error) { + if a.plugins == nil { + return marketplace.Snapshot{}, nil + } plugins, err := a.plugins.SettingsCatalog(ctx) if err != nil { if plugins == nil { diff --git a/desktop/internal/workbench/shell_view.go b/desktop/internal/workbench/shell_view.go index d90555860e..89f8b972f0 100644 --- a/desktop/internal/workbench/shell_view.go +++ b/desktop/internal/workbench/shell_view.go @@ -328,6 +328,15 @@ func (a *App) editorArea(c ui.C) { if a.editorGroups(c) { return } + if a.documentOnly { + ui.Column(c).Fill().Center().Background(a.colors.Editor).Children(func() { + ui.Text(c, i18n.Shared(a.language(), "desktop.singleFile.help")).Color(a.colors.Subtle) + if ui.Button(c, i18n.Shared(a.language(), "desktop.singleFile.openFile")).Outline().Clicked() { + c.After(a.chooseStandaloneFile) + } + }) + return + } hints := [...]struct { label string // command is the keymap command whose fixed gesture and bindings are shown. diff --git a/desktop/internal/workbench/standalone.go b/desktop/internal/workbench/standalone.go new file mode 100644 index 0000000000..9423385943 --- /dev/null +++ b/desktop/internal/workbench/standalone.go @@ -0,0 +1,149 @@ +package workbench + +import ( + "context" + "errors" + "path/filepath" + "slices" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +// Note: 隔离边界见 .agents/notes/implemented/feature/2026-11-20-cli-and-standalone-editor.md +// A standalone session borrows document ownership and editor layout, but never +// enters the project-open pipeline. In particular its parent is not indexed, +// watched as a workspace, restored, trusted or handed to a plugin. +func (a *App) openStandaloneFile(path string) { + a.requestCloseProject(func() { + ctx, cancel := context.WithCancel(context.Background()) + p := &project{standalone: true, root: filepath.Dir(path), name: filepath.Base(path), ctx: ctx, cancel: cancel} + a.project = p + a.openFile(p, path) + }) +} + +func (a *App) standaloneWorkbench(c ui.C) { + a.syncWindowTitle() + a.layout.capture() + a.layout.insetW, a.layout.insetH = 0, titleBarHeight+statusBarHeight + // Use the existing bottom panel and splitter without restoring any project panels. + open := [slotCount]int{-1, -1, -1, -1, -1, -1} + terminalIndex := catalogIndex[itemTerminal] + if a.project != nil && a.chrome.isOpen(terminalIndex) { + open[slotBottomLeft] = terminalIndex + } + plan := a.layout.arrange(c.Bounds(), open) + hidden := slotCount + language := a.language() + leading, trailing := app.TitlebarInsets() + ui.Column(c).Fill().Children(func() { + ui.Row(c).FillWidth().Height(titleBarHeight).Shrink(0).Items(ui.Center).Gap(8). + PadSides(0, trailing+chromeEdge, 0, leading+chromeEdge).MovesWindow().Children(func() { + a.compactMenuButton(c) + name := i18n.Shared(language, "desktop.singleFile.mode") + if a.project != nil { + name = a.project.name + } + if d := a.selectedEditorDocument(); d != nil { + name = d.name + } + ui.Text(c, name).Bold().Ellipsis().Color(a.colors.Text) + ui.Text(c, i18n.Shared(language, "desktop.singleFile.mode")).FontSize(11).Color(a.colors.Subtle) + a.drawRunOptionHelp(c.Part("single-file-help"), i18n.Shared(language, "desktop.singleFile.help")) + ui.Spacer(c) + if ui.Button(c, a.text.Tools.Terminal).Icon(icons.SquareTerminal).IconOnly().Ghost().Disabled(a.project == nil).Tooltip(a.text.Tools.Terminal).Clicked() { + c.After(func() { + a.performed("terminal.toggle", surfaceButton) + a.toggleStandaloneTerminal() + }) + } + if ui.Button(c, i18n.Shared(language, "desktop.singleFile.openFolder")).Disabled(a.selectedEditorDocument() == nil).Outline().Tooltip(i18n.Shared(language, "desktop.singleFile.openFolderHelp")).Clicked() { + c.After(func() { + a.performed("workspace.singleFile.openFolder", surfaceButton) + if d := a.selectedEditorDocument(); d != nil { + a.openProjectInNewWindow(filepath.Dir(d.path)) + } + }) + } + if ui.Button(c, i18n.Shared(language, "desktop.singleFile.openFile")).Icon(icons.Folder).Ghost().Clicked() { + c.After(a.chooseStandaloneFile) + } + if ui.Button(c, a.text.Settings.Title).Icon(icons.Settings).IconOnly().Ghost().Tooltip(a.text.Settings.Title).Clicked() { + c.After(func() { a.openSettingsPage(surfaceButton, settingsHome) }) + } + }) + a.shellMain(c, plan, open, &hidden) + ui.Row(c).FillWidth().Height(statusBarHeight).Shrink(0).Items(ui.Center).Gap(8).PadX(8).Children(func() { + if d := a.selectedEditorDocument(); d != nil { + ui.Text(c, d.path).Ellipsis().Grow(1).MinWidth(0).Color(a.colors.Subtle) + } + for _, id := range []string{itemCaret, itemIndent, itemEOL, itemEncoding, itemLock} { + if i := slices.IndexFunc(a.chrome.catalog, func(it item) bool { return it.id == id }); i >= 0 && a.chromeStatusItem(c, i) { + index := i + c.After(func() { a.activate(index) }) + } + } + }) + }) + if hidden != slotCount { + c.After(func() { + a.performed("workbench.toolWindow.hide", surfaceButton) + a.reduceChrome(core.SetChromeOpen(itemTerminal, false)) + a.invalidator.Invalidate() + }) + } +} + +func (a *App) toggleStandaloneTerminal() { + index := catalogIndex[itemTerminal] + if a.chrome.isOpen(index) { + a.reduceChrome(core.SetChromeOpen(itemTerminal, false)) + a.invalidator.Invalidate() + return + } + if len(a.project.terms.list) == 0 { + a.openToolTerminal("") + return + } + a.reduceChrome(core.SetChromeOpen(itemTerminal, true)) + a.invalidator.Invalidate() +} + +// Keep the normal editor commands while omitting project tools from menus and +// shortcuts. Their UI is absent from a standalone window too. +func (a *App) sessionCommands(list []command) []command { + if !a.documentOnly { + return list + } + return slices.DeleteFunc(list, func(cmd command) bool { return !a.documentCommands[cmd.id] }) +} + +func (a *App) chooseStandaloneFile() { + language := a.language() + a.performed("editor.singleFile.open", surfaceButton) + a.background(nil, 0, func(context.Context) func(*App) { + paths, err := app.OpenFiles(app.OpenFileOptions{Title: i18n.Shared(language, "desktop.singleFile.openFile")}) + return func(a *App) { + // log-exempt: 用户取消:关闭文件选择器不改变打开的文档。 + if errors.Is(err, app.ErrCanceled) { + return + } + if err != nil { + a.operationFailed("single_file_dialog", err) + a.notifyError(a.text.Errors.OpenFailed(err.Error())) + return + } + for _, path := range paths { + if a.project == nil { + a.openStandaloneFile(path) + } else { + a.openFile(a.project, path) + } + } + } + }) +} diff --git a/desktop/internal/workbench/standalone_test.go b/desktop/internal/workbench/standalone_test.go new file mode 100644 index 0000000000..93edc34851 --- /dev/null +++ b/desktop/internal/workbench/standalone_test.go @@ -0,0 +1,152 @@ +package workbench + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +func TestStandaloneEditsWithBundledSyntaxWithoutProjectServices(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "hello.go") + original := "package main\n\nfunc main() {}\n" + if err := os.WriteFile(path, []byte(original), 0600); err != nil { + t.Fatal(err) + } + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, map[string]string{"theme": "dark"}); err != nil { + t.Fatal(err) + } + options := DesktopOptions(core.NewClient(), prefs, "test") + options.Languages = []string{"en-US"} + options.OpenFile = path + options.PluginRoot = filepath.Join(root, "unread-plugins") + h := newHarnessWithOptions(t, options) + if h.app.plugins != nil || h.app.aiKernel != nil { + t.Fatal("standalone assembled plugin or AI services") + } + h.app.openStandaloneFile(path) + h.await("standalone file", func() bool { return h.app.project != nil && h.app.project.docs.byPath(path) != nil }) + h.settle() + p := h.app.project + d := p.docs.byPath(path) + if d.grammar == nil || d.languageID != "go" { + t.Fatalf("bundled highlighting absent: %q %v", d.languageID, d.grammar) + } + if !p.standalone || len(p.terms.list) != 0 || p.search.watch != nil || p.git.isRepository() { + t.Fatal("standalone started project services") + } + for _, cmd := range h.app.commands() { + if cmd.id == "search.files" || cmd.id == "debug.start" || cmd.id == "plugins.open" || cmd.id == "project.new" { + t.Fatalf("project command exposed: %s", cmd.id) + } + } + h.app.openEverywhere(p) + h.app.updateEverywhere(p, "sibling secret", 0) + if h.app.everywhereView.scope != everywhereScopeActions || p.everywhere.loading || p.search.watch != nil { + t.Fatal("standalone search entered parent workspace") + } + h.app.closeEverywhere(p) + d.view.SetSelection(d.view.TextSnapshot().Len(), d.view.TextSnapshot().Len()) + h.app.insertForTest(d, "// saved\n") + h.app.saveDocument(p, d.id) + h.await("standalone save", func() bool { return !d.saving && !d.dirty() }) + data, err := os.ReadFile(path) + if err != nil || string(data) != original+"// saved\n" { + t.Fatalf("saved: %q %v", data, err) + } + for _, name := range []string{recentFile, editorSessionFile, recentFilesName(root)} { + if _, err := os.Stat(filepath.Join(prefs.Dir(), name)); !os.IsNotExist(err) { + t.Fatalf("standalone persisted project state %s: %v", name, err) + } + } + h.app.closeProject() + h.settle() + for _, cmd := range h.app.commands() { + if cmd.id == "plugins.open" || cmd.id == "project.new" { + t.Fatalf("empty standalone exposed %s", cmd.id) + } + } +} + +func TestStandaloneTerminalStartsOnDemandInSelectedFileFolder(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("native /bin/sh PTY workflow; Windows needs its local guest") + } + root := t.TempDir() + path := filepath.Join(root, "first.go") + secondDir := filepath.Join(root, "nested") + if err := os.Mkdir(secondDir, 0700); err != nil { + t.Fatal(err) + } + second := filepath.Join(secondDir, "second.go") + for _, file := range []string{path, second} { + if err := os.WriteFile(file, []byte("package main\n"), 0600); err != nil { + t.Fatal(err) + } + } + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, map[string]string{"theme": "dark"}); err != nil { + t.Fatal(err) + } + options := DesktopOptions(core.NewClient(), prefs, "test") + options.Languages, options.OpenFile = []string{"en-US"}, path + h := newHarnessWithOptions(t, options) + h.app.openStandaloneFile(path) + h.await("first file", func() bool { return h.app.project != nil && h.app.project.docs.byPath(path) != nil }) + p := h.app.project + h.app.openFile(p, second) + h.await("second file", func() bool { + return h.app.selectedEditorDocument() != nil && h.app.selectedEditorDocument().path == second + }) + h.settle() + if len(p.terms.list) != 0 || h.app.chrome.isOpen(catalogIndex[itemTerminal]) { + t.Fatal("standalone created or restored a terminal before a user action") + } + h.app.settings.TerminalShell = "/bin/sh" + h.clickNamed(h.app.text.Tools.Terminal) + h.settle() + if len(p.terms.list) != 1 || p.terms.list[0].hit.IsZero() { + t.Fatal("terminal command did not show the integrated terminal") + } + term := p.terms.list[0] + // The real shell writes its actual working directory; its output is not supplied by the test. + if !term.view.SendLine("printf '\\nLITHE_CWD='; pwd -P") { + t.Fatal("terminal rejected command") + } + realDir, err := filepath.EvalSymlinks(secondDir) + if err != nil { + t.Fatal(err) + } + awaitStateWithin(t, h, 5*time.Second, "shell working directory", func() bool { + term.view.Pump() + return strings.Contains(term.view.RetainedText(1<<16), "LITHE_CWD="+realDir) + }) + if h.app.plugins != nil || p.search.watch != nil || p.git.isRepository() { + t.Fatal("opening a terminal activated project services") + } + if _, err := os.Stat(filepath.Join(prefs.Dir(), layoutFile)); !os.IsNotExist(err) { + t.Fatalf("standalone terminal modified project layout: %v", err) + } + h.clickNamed(h.app.text.Tools.Terminal) + h.settle() + if len(p.terms.list) != 1 { + t.Fatal("hiding the panel discarded its shell") + } + h.clickNamed(h.app.text.Tools.Terminal) + h.settle() + if len(p.terms.list) != 1 || p.terms.list[0] != term { + t.Fatal("showing the panel created a duplicate shell") + } + h.app.closeTerminal(p, term.id) + h.settle() + if len(p.terms.list) != 0 || h.app.chrome.isOpen(catalogIndex[itemTerminal]) { + t.Fatal("closing the last terminal did not release the panel") + } +} diff --git a/desktop/internal/workbench/standalone_visual_test.go b/desktop/internal/workbench/standalone_visual_test.go new file mode 100644 index 0000000000..9b9833aaaa --- /dev/null +++ b/desktop/internal/workbench/standalone_visual_test.go @@ -0,0 +1,82 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +func TestVisualStandalone(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, theme := range []string{"dark", "light"} { + for _, language := range []string{"en-US", "zh-Hans"} { + t.Run(theme+"-"+language, func(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "hello.go") + if err := os.WriteFile(path, []byte("package main\n\nimport \"fmt\"\n\n// A file opened directly from the terminal.\nfunc main() {\n\tfmt.Println(\"Hello, Lithe!\")\n}\n"), 0600); err != nil { + t.Fatal(err) + } + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, map[string]string{"theme": theme}); err != nil { + t.Fatal(err) + } + options := DesktopOptions(core.NewClient(), prefs, "test") + options.Languages = []string{language} + options.OpenFile = path + var session *headless.Session + h := newHarnessWithDriver(t, options, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1000, 640 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + h.app.openStandaloneFile(path) + h.await("standalone file", func() bool { return h.app.project != nil && h.app.project.docs.byPath(path) != nil }) + h.settle() + if err := session.Screenshot(filepath.Join(out, "single-file-"+theme+"-"+language+".png")); err != nil { + t.Fatal(err) + } + if runtime.GOOS != "windows" { + h.app.settings.TerminalShell = "/bin/sh" + h.clickNamed(h.app.text.Tools.Terminal) + h.await("terminal panel", func() bool { return len(h.app.project.terms.list) == 1 }) + term := h.app.project.terms.list[0] + if !term.view.SendLine("printf '\\nHello from the integrated terminal\\n'; pwd -P") { + t.Fatal("terminal rejected command") + } + realRoot, err := filepath.EvalSymlinks(root) + if err != nil { + t.Fatal(err) + } + awaitStateWithin(t, h, 5*time.Second, "actual shell output", func() bool { + term.view.Pump() + return strings.Contains(term.view.RetainedText(1<<16), realRoot) + }) + h.settle() + if err := session.Screenshot(filepath.Join(out, "single-file-terminal-"+theme+"-"+language+".png")); err != nil { + t.Fatal(err) + } + } + }) + } + } +} diff --git a/desktop/internal/workbench/tab_menu.go b/desktop/internal/workbench/tab_menu.go index f75ffca54c..97c79f5a8a 100644 --- a/desktop/internal/workbench/tab_menu.go +++ b/desktop/internal/workbench/tab_menu.go @@ -83,13 +83,13 @@ func (a *App) tabMenuItems(c ui.C, group string, t shownTab, tabs []shownTab) fu }) } _, inside := projectRelative(p.root, path) - if _, ok := a.kernel.(localHistoryKernel); ok && inside && menu.Item(i18n.Shared(language, "desktop.history.show")).Clicked() { + if _, ok := a.kernel.(localHistoryKernel); ok && !p.standalone && inside && menu.Item(i18n.Shared(language, "desktop.history.show")).Clicked() { c.After(func() { a.performed("localHistory.show", surfaceContextMenu) a.openLocalHistory(p, path) }) } - if inside && menu.Item(i18n.Shared(language, "desktop.tab.selectInProject")).Clicked() { + if !p.standalone && inside && menu.Item(i18n.Shared(language, "desktop.tab.selectInProject")).Clicked() { c.After(func() { a.performed("editor.tabs.selectInProject", surfaceContextMenu) a.selectDocument(p, d.id) diff --git a/desktop/internal/workbench/terminal_shells.go b/desktop/internal/workbench/terminal_shells.go index 15c9514f44..de9a43e2b8 100644 --- a/desktop/internal/workbench/terminal_shells.go +++ b/desktop/internal/workbench/terminal_shells.go @@ -3,6 +3,7 @@ package workbench import ( "context" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" "github.com/1lck/Lithe-IDEA/desktop/internal/localshell" "github.com/vivaui/viva/ui" @@ -62,6 +63,9 @@ func (a *App) shellMenuButton(c ui.C) { // Terminal setting's when shell is empty, and gives it the keyboard. func (a *App) openToolTerminal(shell string) { if t := a.newTerminal(a.project, shell); t != nil { + if a.documentOnly { + a.reduceChrome(core.SetChromeOpen(itemTerminal, true)) + } a.focusTerminal(t.id) } } diff --git a/desktop/internal/workbench/terminals.go b/desktop/internal/workbench/terminals.go index 7624fbc908..71dc05c3da 100644 --- a/desktop/internal/workbench/terminals.go +++ b/desktop/internal/workbench/terminals.go @@ -2,6 +2,7 @@ package workbench import ( "context" + "path/filepath" "slices" "strconv" "strings" @@ -355,7 +356,13 @@ func dockable(member string) bool { // The tool window's group is made if the state has none, so a project is never without // the group the tool window's tabs are listed in. func (a *App) newTerminal(p *project, shell string) *terminal { - return a.newTerminalWith(p, terminalOptions{shell: shell, activate: true}) + options := terminalOptions{shell: shell, activate: true} + if p.standalone { + if d := a.selectedEditorDocument(); d != nil { + options.dir = filepath.Dir(d.path) + } + } + return a.newTerminalWith(p, options) } // terminalOptions say what a terminal runs and whether opening it takes the tab group's diff --git a/desktop/internal/workbench/welcome_drop.go b/desktop/internal/workbench/welcome_drop.go index 233ce25455..78e48f3a20 100644 --- a/desktop/internal/workbench/welcome_drop.go +++ b/desktop/internal/workbench/welcome_drop.go @@ -9,6 +9,30 @@ import ( // fileDrop routes files dropped on the window. The start screen opens a dropped folder as a // project; with a project open, files dropped on a terminal are typed into it. func (a *App) fileDrop(event gfx.FileDropEvent) gfx.EventResult { + if a.documentOnly { + if result, handled := a.terminalFileDrop(event); handled { + return result + } + if event.Phase == gfx.FileDropDrop { + for _, path := range event.Paths { + info, err := os.Stat(path) + if err != nil { + a.operationFailed("single_file_drop", documentLogError(err)) + continue + } + if info.IsDir() { + a.openProject(path) + } else if info.Mode().IsRegular() { + if a.project == nil { + a.openStandaloneFile(path) + } else { + a.openFile(a.project, path) + } + } + } + } + return gfx.EventResult{Handled: true, Repaint: true} + } if a.project == nil { return a.welcomeFileDrop(event) } diff --git a/desktop/internal/workbench/window_title.go b/desktop/internal/workbench/window_title.go index 203de81463..0f90b2aab3 100644 --- a/desktop/internal/workbench/window_title.go +++ b/desktop/internal/workbench/window_title.go @@ -22,6 +22,12 @@ func (a *App) windowTitle() string { if p == nil { return a.text.App.Name } + if p.standalone { + if d := a.selectedEditorDocument(); d != nil { + return d.name + windowTitleSeparator + a.text.App.Name + } + return a.text.App.Name + } title := a.projectDisplayName(p) if runtime.GOOS == "darwin" { return title diff --git a/desktop/internal/workbench/workspace_trust.go b/desktop/internal/workbench/workspace_trust.go index 5bc2d5e7b9..a69d06ea4c 100644 --- a/desktop/internal/workbench/workspace_trust.go +++ b/desktop/internal/workbench/workspace_trust.go @@ -42,7 +42,7 @@ type projectTrust struct { func (t *projectTrust) allowed() bool { return t.codeAllowed.Load() } // safeMode reports whether p is open without trust. -func (p *project) safeMode() bool { return p != nil && !p.trust.allowed() } +func (p *project) safeMode() bool { return p != nil && !p.standalone && !p.trust.allowed() } // openProjectByTrust opens the folder at root once its trust is known. A trusted folder opens at // once; one the user previewed in safe mode before opens in safe mode; for one with no diff --git a/docs/ci-builds.md b/docs/ci-builds.md index 5907341d23..cd64d48a90 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -68,6 +68,8 @@ macOS 的本地手动打包可用 `package-desktop.sh --ad-hoc-sign` 生成有 ### 独立工作树的本地编译 +CLI 用户启动器由 `desktop/internal/cli` 在明确注册时生成到 `/Lithe/cli/bin/lithe`(Windows 为 `lithe.cmd`)。它绑定用户机器与当前应用可执行路径,随用户移除注册删除;它不是编译缓存,不跨工作树复制,不写安装目录,也不影响代码签名和增量更新基线。CLI 与单文件模式的无头截图可写入当前检出的 `.artifacts/cli-single-file/`;它们绑定本次源码、语言、主题、Viva/Core 修订和渲染环境,不跨工作树复制,由开发者或 CI 清理,不进入发行包。 + TextMate 首行元数据随各插件归档发布,从已安装版本目录只读加载。宿主的匹配缓存只保留当前进程内的编译结果,没有可跨工作树复用的状态。加载过程不写入应用或插件包,不改变签名和增量更新基线。 搜索偏好 `/search.json` 由桌面原生存储适配器持有,最多64 KiB;只在用户应用/恢复默认时条件原子写回,打开页面不创建文件。它是用户状态,没有源码、版本、平台、架构或工具链复用身份,不跨工作树复制。搜索索引和未保存快照仅在当前进程内,绑定工作区、可见性与读取预算,关闭项目后释放,不写入安装目录。它们不改变代码签名或增量更新基线。`TestVisualSearchResults` 和 `TestVisualSearchPreferences` 的截图写入当前检出的 `.artifacts/search-visual/`,绑定本次源码、语言、主题和渲染环境,不跨工作树复制;Linux Desktop CI上传后由runner清理,不进入发行包。 diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 86d811aca9..d07af0c471 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -289,7 +289,8 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # rows), #13, #8, #7, #6 and #4. # Search pages, unsaved snapshots, source identities and budgets from Core #125, # merged on top of the build-option changes through Core #124. -PINNED_CORE_REVISION="604699f0df9a7c5ec1b245d3f2526d158f5a8eed" +# CLI launch policy, isolated document command policy and opt-in shell registration. +PINNED_CORE_REVISION="ea502256b6537ff6aec7dff35892452cc5e8e7af" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/i18n/features/cli-single-file.json b/shared/i18n/features/cli-single-file.json new file mode 100644 index 0000000000..1114c3fbfa --- /dev/null +++ b/shared/i18n/features/cli-single-file.json @@ -0,0 +1,194 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.cli.title", + "description": "CLI registration and standalone editor: title", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.cli.help", + "description": "CLI registration and standalone editor: help", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.cli.notRegistered", + "description": "CLI registration and standalone editor: notRegistered", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.cli.registered", + "description": "CLI registration and standalone editor: registered", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.cli.register", + "description": "CLI registration and standalone editor: register", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.cli.remove", + "description": "CLI registration and standalone editor: remove", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.cli.refresh", + "description": "CLI registration and standalone editor: refresh", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.cli.source", + "description": "CLI registration and standalone editor: source", + "platforms": [ + "desktop" + ], + "parameters": { + "target": "string" + } + }, + { + "id": "desktop.cli.reopenTerminal", + "description": "CLI registration and standalone editor: reopenTerminal", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.cli.failed", + "description": "CLI registration and standalone editor: failed", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.cli.unsupportedShell", + "description": "CLI registration and standalone editor: unsupportedShell", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.cli.launcherConflict", + "description": "CLI registration and standalone editor: launcherConflict", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.cli.conflict", + "description": "CLI registration and standalone editor: conflict", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.singleFile.mode", + "description": "CLI registration and standalone editor: mode", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.singleFile.help", + "description": "CLI registration and standalone editor: help", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.singleFile.openFolder", + "description": "CLI registration and standalone editor: openFolder", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.singleFile.openFolderHelp", + "description": "CLI registration and standalone editor: openFolderHelp", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.singleFile.openFile", + "description": "CLI registration and standalone editor: openFile", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.cli.usage", + "description": "Command line help", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.cli.repair", + "description": "Repair the owned CLI launcher after moving the application", + "platforms": [ + "desktop" + ] + } + ], + "locales": { + "en-US": { + "desktop.cli.title": "CLI", + "desktop.cli.help": "Register the lithe command for your default shell. This writes only the shown shell configuration or user PATH and a launcher in your user data. Registration is off by default. Use lithe to open a project, or lithe for an editor with bundled highlighting and no plugins.", + "desktop.cli.notRegistered": "Not registered", + "desktop.cli.registered": "Registered", + "desktop.cli.register": "Register lithe command", + "desktop.cli.remove": "Remove registration", + "desktop.cli.refresh": "Refresh status", + "desktop.cli.source": "Configuration: {target}", + "desktop.cli.reopenTerminal": "Open a new terminal for the change to take effect.", + "desktop.cli.failed": "Could not update CLI registration. Check the configuration permissions and refresh to try again.", + "desktop.cli.unsupportedShell": "This default shell is not supported yet. Use zsh, bash, sh or fish, then refresh.", + "desktop.cli.launcherConflict": "Another command already exists at the launcher path. Move it aside, then refresh and register again.", + "desktop.cli.conflict": "The shell configuration changed. Refresh its status before applying again.", + "desktop.singleFile.mode": "Single File Mode", + "desktop.singleFile.help": "Bundled syntax highlighting and text editing, with an optional terminal. Project indexing, Git and all plugins remain inactive.", + "desktop.singleFile.openFolder": "Open Folder as Project", + "desktop.singleFile.openFolderHelp": "Open the containing folder in a new project window, where project services and enabled plugins become available.", + "desktop.singleFile.openFile": "Open File…", + "desktop.cli.usage": "Usage: lithe [--] [file-or-folder]\nlithe --help\nlithe --version\n\nA folder opens a project; a file opens in Single File Mode without plugins.", + "desktop.cli.repair": "Repair registration" + }, + "zh-CN": { + "desktop.cli.title": "CLI", + "desktop.cli.help": "为默认 shell 注册 lithe 命令。此操作会修改下方显示的 shell 配置或用户 PATH,并在用户数据目录创建启动器。默认不注册。lithe <文件夹> 打开项目,lithe <文件> 打开仅使用内置高亮、不激活插件的编辑器。", + "desktop.cli.notRegistered": "未注册", + "desktop.cli.registered": "已注册", + "desktop.cli.register": "注册 lithe 命令", + "desktop.cli.remove": "移除注册", + "desktop.cli.refresh": "刷新状态", + "desktop.cli.source": "配置来源:{target}", + "desktop.cli.reopenTerminal": "重新打开终端后生效。", + "desktop.cli.failed": "无法读取或更新 CLI 注册。请检查配置文件权限,刷新状态后重试。", + "desktop.cli.unsupportedShell": "暂不支持当前默认 shell。请使用 zsh、bash、sh 或 fish,然后刷新状态。", + "desktop.cli.launcherConflict": "启动器位置已存在其他命令。请先移走该文件,再刷新并重新注册。", + "desktop.cli.conflict": "shell 配置已被修改。请刷新状态后重新操作。", + "desktop.singleFile.mode": "单文件模式", + "desktop.singleFile.help": "提供内置语法高亮和文本编辑,可按需打开终端。项目索引、Git 和所有插件保持关闭。", + "desktop.singleFile.openFolder": "以项目打开所在文件夹", + "desktop.singleFile.openFolderHelp": "在新项目窗口中打开所在文件夹,启用项目服务和已启用的插件。", + "desktop.singleFile.openFile": "打开文件…", + "desktop.cli.usage": "用法:lithe [--] [文件或文件夹]\nlithe --help\nlithe --version\n\n文件夹以项目打开;文件以不激活插件的单文件模式打开。", + "desktop.cli.repair": "修复注册" + } + } +} diff --git a/shared/platform-feature-matrix/features/cli-single-file-mode.json b/shared/platform-feature-matrix/features/cli-single-file-mode.json new file mode 100644 index 0000000000..db6dede9eb --- /dev/null +++ b/shared/platform-feature-matrix/features/cli-single-file-mode.json @@ -0,0 +1,45 @@ +{ + "id": "cli-single-file-mode", + "area": "应用与设置", + "group": "CLI", + "capability": "可选注册 lithe 命令,按文件夹/单文件分别打开项目与轻量编辑器", + "owner": "Desktop", + "verification": "macOS:打开通用 > CLI 时不写来源;点击注册后新终端能使用 lithe,分别传入带空格/中文文件、文件夹和 -- 保护的路径;单文件只使用内置高亮,能编辑保存,默认不创建终端,无插件、项目树、Git、运行/调试/测试或父目录索引,查找动作不搜索工作区。点击终端后使用当前文件目录,真实命令输出可见,隐藏后重开复用会话,关闭窗口清理 shell。以项目打开所在文件夹在新窗口走正常信任和插件流程。修复应用移动后的启动器;移除注册保留无关 shell 内容。Windows:检查 HKCU Environment Path 类型与无关项保留、外部修改冲突、环境广播、新 cmd/PowerShell 中调用及移除,原生运行待验收。", + "notes": "已在 macOS 执行真实临时配置注册、修复、移除和冲突保护测试,并验证单文件真实编辑保存、真实 PTY 命令及中英/明暗无头截图。尚未通过真实系统终端完成注册到 GUI 的端到端验收。Windows 无本地来宾,规则测试及 Windows 目标编译通过,不代表原生验收完成。", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/cmd/lithe/main.go", + "desktop/internal/cli/registration.go", + "desktop/internal/core/cli.go", + "desktop/internal/workbench/standalone.go", + "desktop/internal/settingswindow/cli_view.go", + "desktop/internal/workbench/standalone_test.go", + "desktop/internal/core/cli_test.go", + "desktop/internal/workbench/standalone_visual_test.go", + "desktop/internal/settingswindow/cli_visual_test.go", + ".agents/notes/implemented/feature/2026-11-20-cli-and-standalone-editor.md", + "desktop/internal/cli/source_unix.go", + "desktop/internal/cli/registration_unix_test.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/cmd/lithe/main.go", + "desktop/internal/cli/registration.go", + "desktop/internal/core/cli.go", + "desktop/internal/workbench/standalone.go", + "desktop/internal/settingswindow/cli_view.go", + "desktop/internal/workbench/standalone_test.go", + "desktop/internal/core/cli_test.go", + "desktop/internal/workbench/standalone_visual_test.go", + "desktop/internal/settingswindow/cli_visual_test.go", + ".agents/notes/implemented/feature/2026-11-20-cli-and-standalone-editor.md", + "desktop/internal/cli/source_windows.go", + "desktop/cmd/lithe/detach_windows.go" + ] + } +} diff --git a/shared/platform-feature-matrix/features/workspace-open-switch.json b/shared/platform-feature-matrix/features/workspace-open-switch.json index 9ab47ebe91..2402ac1f63 100644 --- a/shared/platform-feature-matrix/features/workspace-open-switch.json +++ b/shared/platform-feature-matrix/features/workspace-open-switch.json @@ -9,7 +9,10 @@ "evidence": [ "desktop/internal/workbench/app.go", "desktop/internal/workbench/welcome.go", - "desktop/internal/workbench/welcome_test.go" + "desktop/internal/workbench/welcome_test.go", + "desktop/internal/workbench/chrome_view.go", + "desktop/internal/workbench/project_menu_test.go", + "desktop/internal/workbench/project_menu_visual_test.go" ] }, "windows": { @@ -18,12 +21,15 @@ "evidence": [ "desktop/internal/workbench/app.go", "desktop/internal/workbench/welcome.go", - "desktop/internal/workbench/welcome_test.go" + "desktop/internal/workbench/welcome_test.go", + "desktop/internal/workbench/chrome_view.go", + "desktop/internal/workbench/project_menu_test.go", + "desktop/internal/workbench/project_menu_visual_test.go" ] }, "owner": "Workspace", "verification": "打开多个项目并在项目之间切换,确认当前项目、文件树和编辑器状态正确;macOS 重启并恢复上次在 Search 等其他侧栏打开的工作区时,默认显示 Project 侧栏,打开的编辑器文件仍恢复。 macOS 欢迎页应用名、Projects、普通项目名及 New Project/Open/Clone Repository 按钮使用 Inter Regular 常规字重,与 IDEA WelcomeScreenComponentFactory 的 Font.PLAIN 和项目默认标签一致;搜索提示与项目路径保持常规字重。 打开多个项目并在项目之间切换,确认当前项目、文件树和编辑器状态正确。Windows 端询问弹窗提供 This Window(替换当前项目)/ New Window / Attach / Cancel 四个选项,勾选\"不再询问\"后记住所选目的地(设置项 projectOpenDefaultDestination),替换前对未保存缓冲区只弹一次确认,确认后原项目即锁定为关闭中(不可切回编辑),新项目打开失败时回滚保留原项目;关闭项目时若后继项目切换失败则中止关闭并保留原项目。 macOS 项目切换菜单按名称、路径和当前分支内容测量宽度,仅受屏幕可见区域限制;打开项目和最近项目中的 Git 仓库在路径下显示分支图标与名称,普通目录不显示该行。外部切换分支后重新打开菜单读取最新名称,元数据读取不覆盖 Git 身份草稿;检查明暗主题和长路径。 macOS 项目打开位置提示使用带标题的 LitheCenteredPopup、共享勾选框和统一按钮;在明暗主题及中英文验证长项目名换行、统一悬停底色、默认动作 Return、取消 Escape/关闭窗口、不再询问持久化、新窗口和此窗口打开。仅请求所属窗口显示,旧请求取消不得影响新请求,父窗口输入在提示期间被阻止。 Windows 端点击路径已不存在(或已不是文件夹)的最近项目时,弹出“Recent Project Unavailable”确认框,选择“Remove From List”会把该项从最近项目移除,取消则保留并标记为缺失;标题栏项目菜单的最近项目行悬浮显示移除按钮(聚焦行按 Delete/Backspace 同样移除),缺失项目头像和文字灰显且移除按钮常驻,点击移除不会打开项目也不会关闭菜单。 macOS 已保存 SSH 连接时,Open(欢迎页、菜单 Open Project…、项目切换器)弹出统一选择面板:左侧「本地文件夹」与各 SSH 连接,右侧在面板内浏览目录并显示修改时间与大小,选 SSH 主机时自动连接并浏览远程目录,点 Open 在当前窗口打开所选目录;没有保存连接时直接弹系统选择面板。在 800×650 的小窗口和大窗口验证面板完整显示、连续点击后尺寸不变,进入桌面等受保护文件夹时系统授权弹窗出现一次,Esc 取消,左下角“远程开发”进入连接管理。 最近项目的保留集合与顺序由 Core `workspace.recentProjects.reduce` 决定(#1662 WS-18):两端都保留最多 20 个未固定项目,按最近打开时间倒序;Windows 的固定项目排在最前且不占容量,取消固定后超出容量的最旧项目被移除;Windows 标题栏菜单仍只显示前 12 项。验证两端连续打开 21 个项目后最早的一个被移除,重新打开已有项目移到最前,导入其他 IDE 的最近项目不覆盖已有项目且排在本次会话打开的项目之后。", - "notes": "Viva 已支持打开本地文件夹、Core 最近项目排序及最近项目菜单移除;当前工作台只保留一个项目,打开另一个项目时先处理当前文档并关闭当前项目。多项目标签、Attach、独立窗口归属与打开目的地选择尚未迁移;Windows 实机验收待完成。legacy 是迁移前基线,不代表当前实现。", + "notes": "Viva 已支持打开本地文件夹、Core 最近项目排序及最近项目菜单移除;当前工作台只保留一个项目,打开另一个项目时先处理当前文档并关闭当前项目。多项目标签、Attach、独立窗口归属与打开目的地选择尚未迁移;Windows 实机验收待完成。legacy 是迁移前基线,不代表当前实现。 标题栏项目菜单的最近项目每行提供 X,复用 Core 移除并持久化;点击不打开目录、不删除目录、不关闭菜单,缺失目录同样可移除。当前项目行 X 只关闭项目且保留最近记录。macOS 已通过存在/缺失目录的回归测试和中英文、明暗主题截图;Windows 原生交互仍待验收。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": {