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,49 @@
# Agent 笔记:控制台保留原始字节并逐行解码

状态:已实现

## 先说结论

运行、构建和测试的进程输出必须以原始字节交给 Rust Core。Core 按行选择编码,再移除终端转义并返回文字和颜色范围。应用的“构建、执行、部署 › 控制台”设置可以固定编码;自动模式的候选顺序来自同一个 Core 解析结果。

## 问题

Windows 程序向管道写入时可能使用系统 ANSI 代码页,例如简体中文系统的 GBK。Go 字符串可以保留这些字节,但直接把它作为 JSON 文本发送会先把非法 UTF-8 替换成乱码;到了 Core 已无法恢复。一次构建中的不同程序还可能分别输出 UTF-8 和 GBK,不能给整个控制台猜一次编码。

## 决策

- 平台适配器只读管道字节并报告是否为 Windows。默认在所有平台使用 UTF-8,仅 Windows 为不能按 UTF-8 读取的行增加 GBK 回退,不依赖系统语言或 ANSI 代码页;用户和插件仍可显式声明其他编码。
- Core 使用 `encoding_rs` 的编码表逐行选择。自动候选依次是插件显式声明、UTF-8,以及仅 Windows 的 GBK,去重;显式设置只用指定编码。候选都不能无损读取时,选择替换字符最少的结果,平手按候选顺序。
- 字节先按换行拆分,再解码;只支持换行和 ESC 不会出现在多字节字符内的兼容 ASCII 编码,因此不接受 UTF-16。跨块字符和未结束行由 Core 状态保留,桌面端不得先修正 UTF-8。
- 每个控制台启动时保存设置快照;后续设置变更只影响新控制台。后台进程观察器通过原子快照读取偏好,不直接访问界面线程持有的可变设置。
- 设置的自动候选由 Core 返回,编码显示名与文件编码选择器共用。加载、失败和自动候选都有明确文本;ⓘ 解释候选顺序和生效时机。解码失败沿用已有后台失败事件,每个控制台只记录一次降级。
- 插件通过通用的 `outputEncoding` 可选字段声明输出编码。运行时或构建工具专属参数由插件决定,不在宿主按工具名添加分支。完整接口与夹具只在 Core 仓库维护。

正确做法:将 `B9 B9 BD A8` 原样编码为 base64 发送,Core 得到“构建”,再供复制、搜索和链接识别使用。不要先把这些字节作为 JSON 的文本字段发送,也不要在平台层另外维护编码猜测顺序。

## 考虑过的备选方案

- 统一给程序添加 UTF-8 参数:不同运行时参数不同,子进程也可能不遵守;不能解决通用宿主的字节丢失,工具专属设置仍属于插件。
- 整个控制台只选一次编码:无法处理 UTF-8 和系统编码按行混合的输出。
- Go 端解码后发送文本:会让平台层持有第二份编码规则,改用 Core 统一处理。

## 后果

原始字节穿过 JSON 边界后仍可恢复,现有颜色、复制、搜索、链接和输出快照沿用解码后的文本。代价是 base64 传输和未结束行预览;块大小、行长度、样式数量继续受 Core 限额约束。自动模式是候选校验,不是任意语言的可靠识别;存在字节歧义时需要插件声明或用户固定编码。已按用户指定在 SSH Windows 11 原生 x64 主机验证管道、编码、设置与竞态;完整应用窗口的 Run、Build、Tests 及复制、链接操作仍须逐项验收,无头截图不能替代它。宿主固定到 Core PR [#128](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/128) 的 `604699f` 修订,包含最终 UTF-8/Windows GBK 策略与插件声明契约;本地也可用 `LITHE_CORE_RUST_DIR` 链接配套 Core 工作区。

## 验证

- macOS 定向计时记录 94 项通过,Windows 11 原生 x64(SSH 主机)记录 95 项通过;真实 stdout/stderr 子进程先写半个 GBK 字符,收到 stdin 握手后再写余下字节。两端相关工作台和设置测试均通过竞态检测,中英文明暗设置截图均已生成。未进行完整应用窗口验收。
- Apple M4 上 release 桥接基准每批约 256 KiB、32 KiB 分块、5 次中位数:纯 UTF-8 的旧 text 通道 3.156 ms、新 bytes 通道 3.631 ms(约 +15%),99% UTF-8 行混入 1% GBK 行 3.551 ms。Go 累计分配约从 1.91 MiB/批增至 2.55 MiB/批;不代表常驻内存,不包含 Rust 分配或 UI 绘制。这是同一 Core 保留的 text 通道对照,不是旧版二进制;混合结果在波动范围内,不能据此声称零开销或更快。原始报告保存在本地 `.artifacts/console-encoding/`。
- `scripts/desktop/desktop-go.sh test ./internal/core ./internal/workbench ./internal/pluginservice ./internal/buildprocess ./internal/settingswindow -count=1`:重放所链接 Core 的编码与样式夹具,验证声明传递、跨块字符、设置快照、设置选择与恢复。
- `LITHE_VISUAL_OUTPUT_DIR=.artifacts/console-encoding/screenshots scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/settingswindow -run '^TestVisualConsoleEncoding$' -count=1`:检查中英文、明暗主题的设置页和编码下拉。
- `scripts/desktop/verify/verify-runtime-bundle-immutability.sh`:确认平台生产路径保持发行目录只读。

## 适用范围

- `desktop/internal/core/output_style.go`
- `desktop/internal/workbench/output_style.go`
- `desktop/internal/workbench/console_encoding.go`
- `desktop/internal/buildprocess/`
- `desktop/internal/settingswindow/console_view.go`
- `shared/platform-feature-matrix/features/console-output-encoding.json`
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
| 外观与行为 | 应用本身的外观、编辑器显示与输入、快捷键,以及应用自身网络请求的代理设置 |
| 插件 | 插件的安装、启用和插件自带的选项;一级页面,不属于任何分组 |
| 版本控制 | Git、SVN 等版本控制系统的配置 |
| 构建、执行、部署 | 分组本身是目录页;固定子页“工具链”(插件声明的全部工具,包括项目 JDK)和“调试器”(单步过滤等调试设置);插件声明的构建工具页、编译器页按种类排在后面,以及运行配置、服务运行和框架、构建工具注入的配置 |
| 构建、执行、部署 | 分组本身是目录页;固定子页“工具链”(插件声明的全部工具,包括项目 JDK)、“调试器”(单步过滤等调试设置)和“控制台”(程序输出编码);插件声明的构建工具页、编译器页按种类排在后面,以及运行配置、服务运行和框架、构建工具注入的配置 |
| 语言与框架 | 语言服务(LSP)的开关,以及 Spring Boot 等框架的配置 |
| 工具 | 终端、搜索(搜索和替换文件大小预算)等通用工具;插件带来的专用工具可以放进对应工具页。日志与诊断不属于设置,它是独立的日志窗口 |
| AI | 与 AI 有关的全部配置:MCP、Skill、全局指令、AI 提交信息、Agents、AI 服务商 |
Expand Down
8 changes: 5 additions & 3 deletions desktop/internal/buildprocess/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,11 @@ type Process struct {
stopping atomic.Bool
}

// Start runs spec and reports every output chunk to observe. observe runs on a
// reader goroutine and must return promptly. The process is killed when ctx
// ends; Stop does the same explicitly.
// Start runs spec and reports every output chunk to observe. A chunk is the bytes
// the process wrote, in whatever encoding it chose, and may end inside a
// character; Core decides the characters (core.Client.DecodeOutputStyle). observe
// runs on a reader goroutine and must return promptly. The process is killed when
// ctx ends; Stop does the same explicitly.
//
// The host owns explicit pipes rather than exec.Cmd.StdoutPipe so root exit and
// pipe EOF are independent. Wait first reaps the root, then ends descendants
Expand Down
1 change: 1 addition & 0 deletions desktop/internal/core/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ type BuildLaunch struct {
Arguments []string `json:"arguments"`
WorkingDirectory string `json:"workingDirectory"`
Environment map[string]string `json:"environment"`
OutputEncoding string `json:"outputEncoding,omitempty"`
}

// BuildDecodeRunRequest validates the raw result of lithe/build/prepareRun.
Expand Down
12 changes: 12 additions & 0 deletions desktop/internal/core/build_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,15 @@ func TestBuildDecodeRunKeepsValidatedExecutable(t *testing.T) {
if err := json.Unmarshal(raw, &fixture); err != nil {
t.Fatal(err)
}
var result map[string]any
if err := json.Unmarshal(fixture.Result, &result); err != nil {
t.Fatal(err)
}
result["outputEncoding"] = "cp936"
fixture.Result, err = json.Marshal(result)
if err != nil {
t.Fatal(err)
}
launch, err := client.DecodeBuildRun(ctx, manifest, "gradle", BuildDecodeRunRequest{
WorkspaceRoot: root,
Root: ".",
Expand All @@ -205,6 +214,9 @@ func TestBuildDecodeRunKeepsValidatedExecutable(t *testing.T) {
if launch.WorkingDirectory != "app" || len(launch.Arguments) != 4 || launch.Environment["APP_ENV"] != "test" {
t.Fatalf("launch = %+v", launch)
}
if launch.OutputEncoding != "gbk" {
t.Fatalf("output encoding = %q, want normalized GBK", launch.OutputEncoding)
}
}

func TestBuildProviderRequestNeedsAnOpenSession(t *testing.T) {
Expand Down
59 changes: 45 additions & 14 deletions desktop/internal/core/output_style.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package core

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

Expand Down Expand Up @@ -46,32 +47,62 @@ type OutputStyleDecoding struct {
// Lines are the lines the chunk finished, oldest first; the first one
// continues the previous answer's Open line.
Lines []OutputLine
// Open is the line still being written, shown after Lines.
// Open is the line still being written, shown after Lines. Core holds its
// bytes until it ends, so a later answer may show it differently.
Open OutputLine
// State is passed back unchanged with the console's next chunk.
State json.RawMessage
}

// DecodeOutputStyle turns one chunk of console output with ANSI escapes into
// plain lines and styled ranges. state is the State of the previous answer for
// the same console, or nil for its first chunk; chunks are at most 1 MiB.
func (c *Client) DecodeOutputStyle(ctx context.Context, text string, state json.RawMessage) (OutputStyleDecoding, error) {
// OutputEncodingPolicy is how Core decides the characters of a process's
// output bytes, line by line.
type OutputEncodingPolicy struct {
// Setting is the user's console encoding: empty or "auto" tries the
// candidates in order, any other id decodes every line with that encoding.
Setting string `json:"setting,omitempty"`
// Declared is the encoding whoever started the process says it writes, such
// as a plugin's run plan; empty when nobody said.
Declared string `json:"declared,omitempty"`
// Windows enables the Windows default: try GBK only after UTF-8 fails.
Windows bool `json:"windows,omitempty"`
}

// OutputEncodings is what an output encoding policy means on this machine.
type OutputEncodings struct {
// Candidates are the encoding ids a line is tried in, in order.
Candidates []string `json:"candidates"`
// Encodings are every id a setting may choose, in menu order.
Encodings []string `json:"encodings"`
}

// DecodeOutputStyle turns one chunk of a process's output bytes with ANSI
// escapes into plain lines and styled ranges, decoding each line with the
// encoding policy picks for it. state is the State of the previous answer for
// the same console, or nil for its first chunk; chunks are at most 1 MiB and
// may end inside a character.
func (c *Client) DecodeOutputStyle(ctx context.Context, chunk []byte, policy OutputEncodingPolicy, state json.RawMessage) (OutputStyleDecoding, error) {
request := struct {
Text string `json:"text"`
State json.RawMessage `json:"state,omitempty"`
}{Text: text, State: state}
Bytes string `json:"bytes"`
Encoding OutputEncodingPolicy `json:"encoding"`
State json.RawMessage `json:"state,omitempty"`
}{Bytes: base64.StdEncoding.EncodeToString(chunk), Encoding: policy, State: state}
var response struct {
Lines []OutputLine `json:"lines"`
Open OutputLine `json:"open"`
State json.RawMessage `json:"state"`
}
if err := c.Execute(ctx, "outputStyle.decode", request, &response); err != nil {
return OutputStyleDecoding{}, err
}
var open struct {
Line OutputLine `json:"line"`
}
if err := json.Unmarshal(response.State, &open); err != nil {
return OutputStyleDecoding{}, err
return OutputStyleDecoding{Lines: response.Lines, Open: response.Open, State: response.State}, nil
}

// ResolveOutputEncoding asks Core which encodings policy tries, in order, and
// which encodings a setting may choose, for the console encoding setting.
func (c *Client) ResolveOutputEncoding(ctx context.Context, policy OutputEncodingPolicy) (OutputEncodings, error) {
var response OutputEncodings
if err := c.Execute(ctx, "outputEncoding.resolve", policy, &response); err != nil {
return OutputEncodings{}, err
}
return OutputStyleDecoding{Lines: response.Lines, Open: open.Line, State: response.State}, nil
return response, nil
}
102 changes: 102 additions & 0 deletions desktop/internal/core/output_style_bench_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package core

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

// BenchmarkOutputEncodingBridge compares the previous text request and the byte request
// through the actual C ABI, including Go JSON, base64, Rust decoding and response parsing.
// The same Core binary retains the text command, so the two paths share compiler settings.
// Mixed input has no text baseline: JSON would replace GBK before Core sees it.
func BenchmarkOutputEncodingBridge(b *testing.B) {
for _, kind := range []string{"ascii", "utf8", "mixed-1pct-gbk", "gbk"} {
for _, chunkSize := range []int{4096, 32768} {
data, expected := outputEncodingBenchmarkData(kind)
for _, mode := range []string{"text", "bytes"} {
if mode == "text" && (kind == "mixed-1pct-gbk" || kind == "gbk") {
continue
}
b.Run(fmt.Sprintf("%s/%d/%s", kind, chunkSize, mode), func(b *testing.B) {
client := NewClient()
ctx := context.Background()
// Chunk once outside the timed loop. Split both paths on the same UTF-8
// boundary: the old caller held incomplete characters before JSON.
var chunks [][]byte
for remaining := data; len(remaining) > 0; {
end := min(len(remaining), chunkSize)
if kind == "utf8" && end < len(remaining) {
for end > 0 && remaining[end]&0xc0 == 0x80 {
end--
}
}
chunks = append(chunks, remaining[:end])
remaining = remaining[end:]
}
run := func(check bool) {
var state json.RawMessage
line := 0
for _, chunk := range chunks {
var decoded OutputStyleDecoding
var err error
if mode == "bytes" {
decoded, err = client.DecodeOutputStyle(ctx, chunk, OutputEncodingPolicy{Windows: true}, state)
} else {
err = client.Execute(ctx, "outputStyle.decode", struct {
Text string `json:"text"`
State json.RawMessage `json:"state,omitempty"`
}{string(chunk), state}, &decoded)
}
if err != nil {
b.Fatal(err)
}
if check {
for _, got := range decoded.Lines {
if line >= len(expected) || got.Text != expected[line] {
b.Fatalf("line %d decoded incorrectly: %q", line, got.Text)
}
line++
}
}
state = decoded.State
}
if check && line != len(expected) {
b.Fatalf("decoded %d lines, want %d", line, len(expected))
}
}
run(true)
b.ReportAllocs()
b.SetBytes(int64(len(data)))
b.ResetTimer()
for b.Loop() {
run(false)
}
})
}
}
}
}

// Each batch is about 256 KiB, with one GBK line in every hundred in the mixed case.
func outputEncodingBenchmarkData(kind string) ([]byte, []string) {
ascii := []byte("[INFO] compile src/Example.java:42 finished successfully; module=example; duration=123ms\n")
utf8 := []byte("[INFO] 编译 src/Example.java:42 构建成功;模块=example;耗时=123ms\n")
gbk := []byte("[INFO] \xb1\xe0\xd2\xeb src/Example.java:42 \xb9\xb9\xbd\xa8\xb3\xc9\xb9\xa6; module=example; duration=123ms\n")
gbkText := "[INFO] 编译 src/Example.java:42 构建成功; module=example; duration=123ms"
var data []byte
var expected []string
for i := 0; len(data) < 256<<10; i++ {
line, text := utf8, string(bytes.TrimSuffix(utf8, []byte{'\n'}))
if kind == "ascii" {
line, text = ascii, string(bytes.TrimSuffix(ascii, []byte{'\n'}))
} else if kind == "gbk" || (kind == "mixed-1pct-gbk" && i%100 == 99) {
line, text = gbk, gbkText
}
data = append(data, line...)
expected = append(expected, text)
}
return data, expected
}
Loading
Loading