Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Agent 笔记:编辑器查找与恢复副本的职责

状态:已实现

## 先说结论

文件内查找、显示设置默认值、最近访问顺序、快捷键方案转换和恢复冲突判断由 Rust Core 决定。
桌面端只负责原生文本缓冲、绘制和文件读写。恢复副本独立于自动保存,关闭 Scratch 标签会保留内容,
遇到磁盘文件改变时必须由用户明确选择保留编辑器或载入磁盘。

## 问题

Viva(桌面界面框架)的编辑器已经拥有不可变文本树,重新在 Core 维护全文会增加常驻内存。
把全文塞进 JSON 请求也会在每次查找时产生多次转义和复制。另一方面,正常退出时保存标签位置不能
恢复崩溃前尚未写入文件的内容;自动保存关闭时也必须有独立的恢复路径。

## 决策

- 桌面端在窗口线程取得不可变文本快照,后台工作线程经借用式 C ABI(同步调用期间共享字节的跨语言接口)
提供 UTF-8 数据。Core 只返回有界的原始字节范围和替换计划,不缓存源文件。
原生文本树、行宽计算和单步撤销的准备在后台完成,回到窗口线程再次检查快照、查询代数和文档归属。
关闭查找栏、文档或项目会取消查询和定时器,过期结果不得修改编辑器。
- 显示偏好经过 Core 解析后才交给绘制。最近文件的排序、过滤和逻辑顺序不依赖墙上时钟。
原生工作队列保持同一窗口事件顺序,多个窗口的历史文件读写在原生边界串行完成。
快捷键方案保存独立绑定,切换方案同时切换实际工作台分发所用的绑定。
- 恢复适配器使用平台用户配置目录下的 `Lithe Desktop/EditorRecovery/`。
每个 `.draft` 文件包含小型元数据头和原始 UTF-8 内容;后台流式写入私有临时文件、同步后原子替换。
临时文件与最终文件在同一个目录,既不会混用两个代数,也不需要复制整篇内容到 JSON。
所有窗口共用原生写入锁,检查 Core 给出的单文档、总字节数和条数限制后再写入。
- 编辑器输入只安排短暂的合并定时器。实际写入由一个有界队列合并同一文档的快照;保存或丢弃操作在旧写入之后执行。
项目、窗口关闭时先提交最后的快照、停止定时器,再等待所属后台任务结束。
普通文件保存成功后移除恢复副本;Scratch 关闭时保留,另存为成功或明确丢弃才移除。
- 恢复时比较保存前基线摘要和实际磁盘内容。文件改变或消失时保留冲突;文件监听只比较重启后观察到的
磁盘基线,不能据此自动确认崩溃前的冲突。用户选择保留编辑器或载入磁盘前,手动保存和自动保存都不得覆盖磁盘。
更晚的外部修改仍由既有原生受保护写入检查拒绝。

正确做法:查找请求 A 返回前文本发生变化,丢弃 A;后台队列收到新快照后又收到保存成功通知,最终删除副本。
不要这样做:绘制时展开全文并查找、让旧替换结果修改新版本、把文件监听观察到的“未变化”当成恢复冲突已获用户确认。

## 考虑过的备选方案

- 在 Core 保留第二份文本:会重复原生编辑器的文档所有权,拒绝。
- 全文 JSON 请求:会转义和复制整个源文件,拒绝。
- 只依赖自动保存:用户关闭自动保存或发生外部修改时不能保障恢复,拒绝。
- 把草稿放到项目或发行包:会污染工作区,或者改变签名与增量更新基线,拒绝。
- 自建正则引擎:Core 已有成熟 `regex` 依赖,直接使用 Unicode 匹配和捕获组替换。

## 后果

查找需要后台临时连续字节快照,原生文本树仍是唯一长期全文所有者。恢复写入是编辑后短暂合并的检查点,
崩溃发生在检查点完成前时,最后一次检查点之后的按键无法保证恢复。配额满时明确报错并保留编辑器内容,
不静默淘汰未保存的用户数据。恢复文件和最近文件属于可变用户状态,禁止通过工作树资源复用流程共享。
它们始终位于安装目录之外,不影响代码签名和 Sparkle 增量更新。

## 验证

- `desktop/internal/workbench/editor_essentials_test.go`:替换、单步撤销、过期隔离、磁盘冲突保护、草稿持久化与最近访问。
- `desktop/internal/settingswindow/editor_essentials_test.go`:实际设置回显、方案独立、切换、重复名称和默认方案保护。
- `desktop/internal/draftstore/store_test.go`:原子覆盖、重建适配器读取和配额拒绝时原内容保持。
- `editor_essentials_visual_test.go`:以真实 Page 无头渲染深色中文与浅色英文界面。
- Core 的可执行向量为 `rust/fixtures/editor/ide-essentials-v1.json`,借用式 C ABI 测试同时检查空指针和非法 UTF-8。
- 编辑器改动前后各运行六次原有性能基线;原生窗口与 Windows 平台验收独立记录,不能用无头截图代替。

## 适用范围

`desktop/internal/editorview/`、`desktop/internal/draftstore/`、工作台的 `editor_find.go`、`editor_recovery.go`、
`recent_files.go`、`scratch_files.go`,以及设置窗口相应组件。共享规则和正式接口文档属于外部 Core 仓库,
本笔记不作为第二份协议参考。
15 changes: 15 additions & 0 deletions desktop/internal/core/bridge.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,21 @@ func executeJSON(request []byte) []byte {
return C.GoBytes(unsafe.Pointer(response), C.int(C.strlen(response)))
}

// executeDocumentJSON borrows immutable source bytes for the synchronous Core call.
// Only the small request and bounded result are copied across the C ABI. Core never
// retains the Go pointer, and the slice contains no Go pointers.
func executeDocumentJSON(request, source []byte) []byte {
cRequest := C.CString(string(request))
defer C.free(unsafe.Pointer(cRequest))
response := C.lithe_core_execute_document_json(cRequest, (*C.uint8_t)(unsafe.Pointer(unsafe.SliceData(source))), C.size_t(len(source)))
runtime.KeepAlive(source)
if response == nil {
return nil
}
defer C.lithe_core_free_string(response)
return C.GoBytes(unsafe.Pointer(response), C.int(C.strlen(response)))
}

// cancelOperation asks the kernel to cancel the in-flight request whose operationId is
// operationID. It reports whether the kernel found an active operation with that id: the C
// function returns 1 when it did and 0 when it did not (the operation already finished, has not
Expand Down
43 changes: 40 additions & 3 deletions desktop/internal/core/desktop_go_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,17 +154,39 @@ func TestBuildDesktopCoreChecksOutFreshPinnedRevision(t *testing.T) {
script := filepath.Join(fixture, "scripts/desktop/build-desktop-core.sh")
write(script, strings.Replace(string(build), pinPrefix+pin+`"`, pinPrefix+revision+`"`, 1), 0o700)
write(filepath.Join(fixture, "bin/rustc"), "#!/usr/bin/env bash\nif [[ \"$1\" == -vV ]]; then echo 'host: x86_64-unknown-linux-gnu'; else echo 'rustc fixture'; fi\n", 0o700)
write(filepath.Join(fixture, "bin/cargo"), "#!/usr/bin/env bash\nif [[ \"$1\" == clean ]]; then exit 0; fi\nmkdir -p \"$CARGO_TARGET_DIR/debug\"\nprintf fixture > \"$CARGO_TARGET_DIR/debug/liblithe_core.a\"\nprintf helper > \"$CARGO_TARGET_DIR/debug/lithe-mcp\"\nfor arg in \"$@\"; do case \"$arg\" in native-static-libs=*) printf '%s\\n' '-lm' > \"${arg#native-static-libs=}\";; esac; done\n", 0o700)
write(filepath.Join(fixture, "bin/cargo"), `#!/usr/bin/env bash
set -euo pipefail
if [[ "$1" == clean ]]; then exit 0; fi
out="$CARGO_TARGET_DIR/debug"
helper=lithe-mcp
libs=-lm
for ((i=1; i<=$#; i++)); do
if [[ "${!i}" == --target ]]; then
j=$((i+1))
out="$CARGO_TARGET_DIR/${!j}/debug"
if [[ "${!j}" == *-windows-gnu ]]; then
[[ "${WINAPI_NO_BUNDLED_LIBRARIES:-}" == 1 ]] || { echo 'winapi still requires Cargo-private import libraries' >&2; exit 1; }
helper=lithe-mcp.exe
libs=-lkernel32
fi
fi
done
mkdir -p "$out"
printf fixture > "$out/liblithe_core.a"
printf helper > "$out/$helper"
for arg in "$@"; do case "$arg" in native-static-libs=*) printf '%s\n' "$libs" > "${arg#native-static-libs=}";; esac; done
`, 0o700)
target := "x86_64-unknown-linux-gnu"
runBuild := func() ([]byte, error) {
t.Helper()
cmd := exec.CommandContext(testContext(t), bash, script)
for _, entry := range os.Environ() {
upper := strings.ToUpper(entry)
if !strings.HasPrefix(upper, "PATH=") && !strings.HasPrefix(upper, "LITHE_CORE_RUST_DIR=") && !strings.HasPrefix(upper, "LITHE_CORE_TARGET=") {
if !strings.HasPrefix(upper, "PATH=") && !strings.HasPrefix(upper, "LITHE_CORE_RUST_DIR=") && !strings.HasPrefix(upper, "LITHE_CORE_TARGET=") && !strings.HasPrefix(upper, "WINAPI_NO_BUNDLED_LIBRARIES=") {
cmd.Env = append(cmd.Env, entry)
}
}
cmd.Env = append(cmd.Env, "PATH="+filepath.Join(fixture, "bin")+string(os.PathListSeparator)+os.Getenv("PATH"))
cmd.Env = append(cmd.Env, "PATH="+filepath.Join(fixture, "bin")+string(os.PathListSeparator)+os.Getenv("PATH"), "LITHE_CORE_TARGET="+target)
return cmd.CombinedOutput()
}
// A no-index directory may still contain untracked user files. Recovery
Expand All @@ -188,6 +210,21 @@ func TestBuildDesktopCoreChecksOutFreshPinnedRevision(t *testing.T) {
if _, err := os.Stat(filepath.Join(checkout, "rust/Cargo.toml")); err != nil {
t.Fatalf("pinned worktree was not checked out: %v", err)
}
// The GNU cgo lane must ask winapi to use MinGW's system import libraries,
// not private libwinapi_* archives from a transient Cargo registry path.
target = "x86_64-pc-windows-gnu"
output, err = runBuild()
if err != nil {
t.Fatalf("building Windows Core with system import libraries: %v\n%s", err, output)
}
stage := filepath.Join(fixture, ".artifacts/desktop/lithe-core", target, "debug")
if libs, err := os.ReadFile(filepath.Join(stage, "native-static-libs.txt")); err != nil || string(libs) != "-lkernel32\n" {
t.Fatalf("unexpected Windows linker inputs: %q, %v", libs, err)
}
if identity, err := os.ReadFile(filepath.Join(stage, "identity.txt")); err != nil || !strings.Contains(string(identity), "winapi-import-libraries=mingw-system\n") {
t.Fatalf("Windows import library identity missing: %q, %v", identity, err)
}
target = "x86_64-unknown-linux-gnu"
// Once a worktree has an index, a deliberate deletion must not be repaired
// by checkout behind the user's back, even if the build cannot proceed.
if err := os.Remove(manifest); err != nil {
Expand Down
171 changes: 171 additions & 0 deletions desktop/internal/core/editor_essentials.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
package core

import (
"context"
"encoding/json"
"fmt"
)

// EditorStoredPreferences preserves missing values from earlier settings versions.
// Core alone supplies defaults and validates ranges and style identifiers.
type EditorStoredPreferences struct {
LineNumbers *bool `json:"lineNumbers,omitempty"`
Whitespace *bool `json:"whitespace,omitempty"`
CursorStyle string `json:"cursorStyle,omitempty"`
CursorBlink *bool `json:"cursorBlink,omitempty"`
AutoSaveDelayMilliseconds *uint64 `json:"autoSaveDelayMilliseconds,omitempty"`
}

// EditorPreferences is the actual presentation configuration resolved by Core.
type EditorPreferences struct {
LineNumbers bool `json:"lineNumbers"`
Whitespace bool `json:"whitespace"`
CursorStyle string `json:"cursorStyle"`
CursorBlink bool `json:"cursorBlink"`
AutoSaveDelayMilliseconds uint64 `json:"autoSaveDelayMilliseconds"`
MinimumAutoSaveDelayMilliseconds uint64 `json:"minimumAutoSaveDelayMilliseconds"`
MaximumAutoSaveDelayMilliseconds uint64 `json:"maximumAutoSaveDelayMilliseconds"`
}

func (c *Client) ResolveEditorPreferences(ctx context.Context, stored EditorStoredPreferences) (EditorPreferences, error) {
var result EditorPreferences
err := c.Execute(ctx, "editor.preferences.resolve", stored, &result)
return result, err
}

// EditorByteRange is a half-open byte span of the exact immutable snapshot searched.
type EditorByteRange struct {
Start int `json:"start"`
End int `json:"end"`
}

type EditorFindRequest struct {
Query string `json:"query"`
CaseSensitive bool `json:"caseSensitive"`
WholeWord bool `json:"wholeWord"`
Regex bool `json:"regex"`
Range *EditorByteRange `json:"range,omitempty"`
Replacement *string `json:"replacement,omitempty"`
ReplaceStart *int `json:"replaceStart,omitempty"`
Caret int `json:"caret"`
Backwards bool `json:"backwards"`
}

type EditorReplacement struct {
EditorByteRange
Text string `json:"text"`
}

type EditorFindResult struct {
Range *EditorByteRange `json:"range,omitempty"`
Matches []EditorByteRange `json:"matches"`
Edits []EditorReplacement `json:"edits"`
Selected *int `json:"selected"`
Truncated bool `json:"truncated"`
}

// FindEditorText runs on a worker: source is an immutable snapshot, borrowed by Rust
// rather than copied into a JSON string. Operation cancellation uses the ordinary registry.
func (c *Client) FindEditorText(ctx context.Context, source []byte, input EditorFindRequest) (EditorFindResult, error) {
var result EditorFindResult
if err := ctx.Err(); err != nil {
return result, err
}
id := fmt.Sprintf("desktop-%d", nextCoreOperation.Add(1))
request, err := json.Marshal(requestEnvelope{OperationID: id, Command: "editor.find", Payload: input})
if err != nil {
return result, err
}
stop := watchCancellation(ctx, id)
defer stop()
err = decodeResponse(ctx, "editor.find", executeDocumentJSON(request, source), &result)
return result, err
}

type EditorRecentEntry struct {
Path string `json:"path"`
Name string `json:"name"`
Line int `json:"line"`
Column int `json:"column"`
Opened uint64 `json:"opened"`
Edited uint64 `json:"edited"`
}

type EditorRecentEvent struct {
Kind string `json:"kind"`
Path string `json:"path"`
Name string `json:"name"`
Line int `json:"line"`
Column int `json:"column"`
}

type EditorRecentRequest struct {
Entries []EditorRecentEntry `json:"entries,omitempty"`
Event *EditorRecentEvent `json:"event,omitempty"`
Query string `json:"query"`
OnlyEdited bool `json:"onlyEdited"`
}

type EditorRecentResult struct {
Entries []EditorRecentEntry `json:"entries"`
Results []EditorRecentEntry `json:"results"`
}

func (c *Client) ReduceEditorRecent(ctx context.Context, input EditorRecentRequest) (EditorRecentResult, error) {
var result EditorRecentResult
err := c.Execute(ctx, "editor.recent.reduce", input, &result)
return result, err
}

type EditorRecoveryRequest struct {
BaseHash string `json:"baseHash"`
DiskHash *string `json:"diskHash"`
Scratch bool `json:"scratch"`
Bytes uint64 `json:"bytes"`
Saved bool `json:"saved"`
Discarded bool `json:"discarded"`
}

type EditorRecoveryDecision struct {
Action string `json:"action"`
MaxDocumentBytes int64 `json:"maxDocumentBytes"`
MaxStorageBytes int64 `json:"maxStorageBytes"`
MaxDocuments int `json:"maxDocuments"`
}

func (c *Client) DecideEditorRecovery(ctx context.Context, input EditorRecoveryRequest) (EditorRecoveryDecision, error) {
var result EditorRecoveryDecision
err := c.Execute(ctx, "editor.recovery.decide", input, &result)
return result, err
}

type KeymapScheme struct {
ID string `json:"id"`
Name string `json:"name"`
Bindings map[string][]string `json:"bindings"`
}

type KeymapSchemes struct {
Active string `json:"active"`
Schemes []KeymapScheme `json:"schemes,omitempty"`
}

type KeymapSchemeRequest struct {
State KeymapSchemes `json:"state"`
Current map[string][]string `json:"current,omitempty"`
Operation string `json:"operation"`
ID string `json:"id"`
Name string `json:"name"`
Bindings map[string][]string `json:"bindings,omitempty"`
}

type KeymapSchemeResult struct {
State KeymapSchemes `json:"state"`
Bindings map[string][]string `json:"bindings"`
}

func (c *Client) ReduceKeymapSchemes(ctx context.Context, input KeymapSchemeRequest) (KeymapSchemeResult, error) {
var result KeymapSchemeResult
err := c.Execute(ctx, "keymap.schemes.reduce", input, &result)
return result, err
}
60 changes: 60 additions & 0 deletions desktop/internal/core/editor_essentials_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package core

import (
"context"
"errors"
"testing"
)

func TestEditorFindBorrowsUnicodeSourceAndPlansReplacements(t *testing.T) {
c := NewClient()
replacement := "${1}!"
got, err := c.FindEditorText(context.Background(), []byte("😀 αβ\nαβ"), EditorFindRequest{Query: "(αβ)", Regex: true, Replacement: &replacement})
if err != nil {
t.Fatal(err)
}
if len(got.Matches) != 2 || got.Matches[0].Start != 5 || got.Matches[1].Start != 10 || len(got.Edits) != 2 || got.Edits[0].Text != "αβ!" {
t.Fatalf("unexpected Unicode plan: %+v", got)
}
_, err = c.FindEditorText(context.Background(), []byte("secret"), EditorFindRequest{Query: "[", Regex: true})
var failure *Error
if !errors.As(err, &failure) || failure.Details != "invalid_pattern" {
t.Fatalf("invalid regex: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err = c.FindEditorText(ctx, []byte("x"), EditorFindRequest{Query: "x"}); !errors.Is(err, context.Canceled) {
t.Fatalf("cancelled search: %v", err)
}
}

func TestEditorEssentialsResolveDefaultsAndKeepIndependentSchemes(t *testing.T) {
c := NewClient()
ctx := context.Background()
prefs, err := c.ResolveEditorPreferences(ctx, EditorStoredPreferences{})
if err != nil {
t.Fatal(err)
}
if !prefs.LineNumbers || !prefs.CursorBlink || prefs.CursorStyle != "line" || prefs.AutoSaveDelayMilliseconds != 1500 {
t.Fatalf("preferences: %+v", prefs)
}
state, err := c.ReduceKeymapSchemes(ctx, KeymapSchemeRequest{Current: map[string][]string{"search.files": {"meta+f"}}})
if err != nil {
t.Fatal(err)
}
cloned, err := c.ReduceKeymapSchemes(ctx, KeymapSchemeRequest{State: state.State, Operation: "saveAs", ID: "mine", Name: "Mine"})
if err != nil {
t.Fatal(err)
}
if cloned.State.Active != "mine" || len(cloned.State.Schemes) != 2 || cloned.Bindings["search.files"][0] != "meta+f" {
t.Fatalf("scheme: %+v", cloned)
}
recent, err := c.ReduceEditorRecent(ctx, EditorRecentRequest{Event: &EditorRecentEvent{Kind: "edited", Path: "src/a.go", Name: "a.go", Line: 2}})
if err != nil || len(recent.Results) != 1 || recent.Results[0].Line != 2 {
t.Fatalf("recent: %+v %v", recent, err)
}
decision, err := c.DecideEditorRecovery(ctx, EditorRecoveryRequest{BaseHash: "old"})
if err != nil || decision.Action != "restoreConflict" {
t.Fatalf("recovery: %+v %v", decision, err)
}
}
Loading
Loading