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,80 @@
# Agent 笔记:远程工作区在主机上运行内置的程序和脚本运行配置及其执行前步骤

状态:已实现

## 先说结论

本笔记覆盖 #2231 R1 的 #43a 和 #43b。远程工作区里,运行配置的读写、校验和启动计划由 Core 路由到主机(Core #161):配置文件经 `lithe_workspace::fs` 存在主机的项目目录,计划按主机平台(Linux、macOS)生成,从不生成批处理或 PowerShell。桌面端拿到计划后,用 `remote.runProcess` 在主机上启动内置的程序和脚本运行(`process.*`),输出进 Run 窗口,标签页带“主机”徽标。

配置“执行前”列表里引用的其他内置运行配置(#43b)同样在主机上按顺序运行,输出进同一个控制台。插件提供的执行前任务、构建工具、插件提供的运行和调试要由本机插件后端计划主机上的进程,属于 #2231 的 R3/R4,本阶段不做,各自说明原因(`desktop.run.remote.*`)。

## 问题

- 远程工作区的项目只在主机上,本机的占位目录永远是空的。照本机方式起进程,会在空目录里跑,读不到项目文件。
- 运行配置本身存在项目目录里。不路由到主机,就会在占位目录里读到“没有配置”,写入时还会把文件写进占位目录。
- 主机上的程序输出可能很快、很多。Core 只缓存 1024 个未送出的事件,观察回调一旦阻塞,Core 会丢事件甚至结束请求。
- 程序输出里的路径是主机路径,本机打不开;工作区以外的主机文件也要能点开(与 Zed 一致)。

## 决策

### 只有内置运行在主机上启动

`startRunConfigurationWith` 在远程工作区只放行 `configuration.IsProcess()` 且不是调试的启动,其余以 `desktop.run.remote.unsupported` 拒绝。标题栏的“运行”放行选中的配置,“调试”和“当前文件”仍走 `refuseRemote`;选中的配置不是内置运行时,直接说明不支持,而不是报“构建目标缺失”。

`loadBuildSystems` 在远程工作区不探测构建系统:本机占位目录里没有项目,探测只会得到空结果。它把 `p.build.failed` 设成 `desktop.run.remote.buildTools`,运行配置菜单把这句话显示为不可点的说明;非空的 `failed` 也让生成层快照保持为空,所以不会往主机写生成层。

“执行前”列表里有插件任务的配置拒绝启动(`desktop.run.remote.beforeLaunch`):任务由插件后端在本机计划,读不到主机上的项目文件(#2231 §2,R3)。只引用内置运行配置的列表照常运行,见下文。需要通过工具链选择程序的计划(`executable.toolchain`)也拒绝(`desktop.run.remote.toolchain`),因为工具链解析读的是本机。

### 进程的启动、输出和结束

`desktop/internal/workbench/remote_run.go` 的 `launchRemoteProcessRun`:

1. 用 `remote.hostRequest` 的 `tempDirectory` 在主机临时目录建 `lithe-run-script-*`,把它作为脚本基名交给 `runConfig.createLaunchPlan`。脚本按计划写到这个目录(写入用“文件必须不存在”的预期版本),运行结束后不论成败、是否被停止都递归删除。连接断开或主机崩溃时留下的目录,由主机的临时目录清理负责。
2. 工作目录是项目相对的 `/` 路径,`remoteRunDirectory` 拼到主机根下,拒绝 `..` 和绝对路径。环境用主机的登录环境,叠加计划的 `environment` 和配置的 `env`。
3. 输出经 `remoteRunOutput` 交给控制台:观察回调只追加到缓冲区,从不等待;独立的泵按顺序送出。缓冲区上限 8 MiB,超出时丢弃最旧的未送出部分,并在控制台写一行提示(`desktop.run.remote.outputDropped`)。
4. “停止”先用 `process.kill`(force 为 false)给进程组发 SIGTERM,超过停止等待时间(`buildprocess.StopGrace`)仍未结束就取消请求,由 Core 强制结束。再按一次“停止”立即强制结束。
5. 进程以非零退出码结束时运行失败,被信号结束时说明信号编号;连接断开时说明“无法确定是否仍在主机上运行”,并交给窗口重新连接(断线后接回输出是 #43c)。

主机上的进程 id 不是本机的,`Pid()` 返回 0,所以 Run 窗口不采样它的端口、CPU 和内存。主机端口由端口工具窗口列出。

### 执行前步骤(#43b)

Core 只允许“执行前”列表引用内置进程运行(`process.*`),所以配置步骤在远程工作区一定能在主机上运行。`runBeforeLaunchSteps` 在远程工作区为这次启动建一个 `remoteRunHost`,每个配置步骤经 `remoteRunHost.runStep` 运行:与主运行一样在主机临时目录规划并写脚本、用 `remote.runProcess` 启动、输出经 `remoteRunOutput` 进同一个控制台,进程标签为步骤名;临时目录在下一步开始前删除。

步骤与本机步骤一样受准备时间(`runPreparationTimeout`)限制。请求本身不随准备上下文取消:准备上下文结束(“停止”或超时)时,先对已启动的进程调用 `remoteProcess.Stop`(SIGTERM,超过停止等待时间再取消请求),还没启动时直接取消请求。这样主机步骤的停止与本机 `buildprocess` 的先请求、后强杀一致。被要求结束后以 0 退出的步骤仍按停止或超时处理,不会接着启动配置。

`failBeforeLaunch` 按 `ExitCode() int` 读退出码,本机的 `*exec.ExitError` 和主机的 `remoteRunExit` 都能说明“以退出码 N 结束”。确认询问(按指纹记住)与本机共用,主机步骤不另加询问。

### 输出里的路径

`flushOutputLinks` 在远程工作区用主机根作为工作区根、按 `linux` 平台匹配路径。点击时用 `remote.stat` 找第一个主机上存在的文件,经 `remoteplaceholder.LocalPath` 换成占位路径交给编辑器打开;工作区以外的路径落在占位根旁的 `.lithe-remote-host` 下,与“工作区以外的远端文件按 Zed 方式打开”一致。需要插件解析的链接拒绝,因为插件读的是本机文件。

### 日志

日志只记命令和错误码,不记主机、路径、命令行或输出。早返回带 `// log-exempt:` 说明。

## 考虑过的备选方案

- **在本机用 ssh 直接起进程**:绕过 Core 的会话、认证和 S26 环境白名单,也拿不到 Core 的进程组管理和事件缓冲。
- **把脚本写到主机的项目目录**:会弄脏用户的工作区,可能被 Git 看到或被提交。
- **远程工作区也探测构建系统**:探测在本机占位目录里运行,结果永远为空,还会误导用户以为项目没有构建工具。
- **远程工作区拒绝所有执行前步骤**(#43a 的做法):配置步骤只是另一个内置运行,主机已经能运行它;一起拒绝会让常见的“先编译再运行”脚本链用不了。
- **把主机步骤的请求直接挂在准备上下文上**:停止时 Core 立即强杀,主机程序没有机会清理,与本机步骤的停止行为不一致。

## 后果

- 远程工作区里能直接运行项目自带的程序和脚本配置,输出、停止和退出码与本机一致;Run 窗口的“主机”徽标说明它在哪里运行。
- “执行前”列表里的内置运行配置在主机上按顺序运行,失败、停止和超时与本机一致。
- 插件提供的执行前任务、构建工具、插件运行、调试和“当前文件”暂时不可用,各自给出说明;它们依赖 #2231 的 R3(插件按主机路径计划进程)和 R4(远程调试),本阶段不做。
- 断线时运行结束为“无法确定是否仍在主机上运行”,主机上的进程可能还在;断线后接回输出由 #43c 负责。
- 主机临时目录里可能残留断线或崩溃时没删掉的 `lithe-run-script-*` 目录,由主机的临时目录清理回收。

## 验证

- `desktop/internal/workbench/remote_run_test.go`:主机上的启动参数、工作目录、环境、脚本写入和删除;退出码和信号;“停止”先发 SIGTERM;执行前的配置步骤在主机上依次运行、失败时不启动配置、停止时先发 SIGTERM;插件任务步骤、工具链和调试的拒绝;输出缓冲丢弃最旧部分;输出链接的主机文件查找;不记主机和路径。
- `desktop/internal/core/remote_process_test.go`:`remote.runProcess` 事件的解析。
- `scripts/desktop/verify/verify-runtime-bundle-immutability.sh`:运行时不写发行目录。

## 适用范围

适用于远程工作区(`project.remote` 非空)里运行配置的读取、启动、停止、输出和输出链接。本机工作区的运行流程不受影响;插件任务步骤、构建工具、插件运行和调试在主机上的执行以 #2231 R3/R4 的笔记为准。
174 changes: 174 additions & 0 deletions desktop/internal/core/remote_process.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
package core

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

// RemoteProcessOpen is how a host process starts.
type RemoteProcessOpen struct {
// Argv is the program and its arguments; a program without "/" is looked up on the PATH of
// Environment.
Argv []string `json:"argv"`
// Cwd is the absolute host working directory; empty starts in the user's home.
Cwd string `json:"cwd,omitempty"`
// Environment is the base environment: "login" asks the user's login shell for it, as an SSH
// login sees it, and "server" (the default when empty) is the remote server's own.
Environment string `json:"environment,omitempty"`
// Env adds variables to the base environment.
Env map[string]string `json:"env,omitempty"`
// PipeStdin keeps the program's standard input open; false gives it /dev/null.
PipeStdin bool `json:"pipeStdin,omitempty"`
// Label is what server.state reports for the process, so the window that closes the session
// can name what still runs. Nil reports none.
Label *RemoteResourceLabel `json:"label,omitempty"`
}

// RemoteProcessEnvironmentLogin is the base environment of a process the user starts: the one
// their login shell sets up, so tools installed through the profile are on the PATH.
const RemoteProcessEnvironmentLogin = "login"

// RemoteProcessEvents receive a host process's events. Both run on the request's goroutine and
// must return at once: they must not wait for a UI thread. Core holds 1024 undelivered events
// per process and ends the process, and with it the request, when a subscriber stops reading.
type RemoteProcessEvents struct {
// Started is called once, before any output, with the id process.kill takes and the
// process's id on the host.
Started func(processID uint64, pid int)
// Output receives the bytes the program wrote to stream, "stdout" or "stderr", in order.
// Output owns data.
Output func(stream string, data []byte)
}

// RemoteProcessExit is how a host process's leader ended: ExitCode when it exited, Signal when a
// signal ended it.
type RemoteProcessExit struct {
ExitCode *int `json:"exitCode"`
Signal *int `json:"signal"`
}

// remoteProcessEvent is one remote event of remote.runProcess.
type remoteProcessEvent struct {
Type string `json:"type"`
Event string `json:"event"`
Params struct {
ProcessID uint64 `json:"processId"`
PID *int `json:"pid"`
Stream string `json:"stream"`
Data string `json:"data"`
} `json:"params"`
}

// errRemoteProcessEvent is an event of remote.runProcess the client cannot read.
var errRemoteProcessEvent = errors.New("core: unreadable remote process event")

// RemoteRunProcess runs a process on the host of sessionID until its leader exits, and returns
// how it ended. It blocks the calling goroutine for the process's whole life, so run it off the
// UI thread. Ending ctx kills the process: Core sends process.kill with force, which kills every
// process of its session, and returns the context's error. A broken or unknown session fails
// with CodeConnectionClosed, and a program that cannot start with CodeProcessFailed. An event
// the client cannot read ends the process too and is returned as the error, since its output
// would be incomplete.
func (c *Client) RemoteRunProcess(ctx context.Context, sessionID string, open RemoteProcessOpen, events RemoteProcessEvents) (RemoteProcessExit, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var unreadable error
observer := func(raw json.RawMessage) {
if unreadable != nil {
return
}
if err := deliverRemoteProcessEvent(raw, events); err != nil {
// Cancelling ends the process rather than letting it run unseen.
unreadable = err
cancel()
}
}
var exit RemoteProcessExit
observationErr, err := c.ExecuteWithEvents(ctx, "remote.runProcess", struct {
SessionID string `json:"sessionId"`
Params RemoteProcessOpen `json:"params"`
}{sessionID, open}, &exit, observer)
switch {
case unreadable != nil:
return RemoteProcessExit{}, unreadable
case err != nil:
return RemoteProcessExit{}, err
case observationErr != nil:
return RemoteProcessExit{}, observationErr
}
return exit, nil
}

// deliverRemoteProcessEvent hands one event of remote.runProcess to events. Events of other kinds
// are not the process's and are ignored.
func deliverRemoteProcessEvent(raw json.RawMessage, events RemoteProcessEvents) error {
if !bytes.Contains(raw, []byte(`"remote"`)) {
return nil
}
var event remoteProcessEvent
if err := json.Unmarshal(raw, &event); err != nil || event.Type != "remote" {
return nil
}
switch event.Event {
case "process.started":
if events.Started != nil {
pid := 0
if event.Params.PID != nil {
pid = *event.Params.PID
}
events.Started(event.Params.ProcessID, pid)
}
case "process.output":
if event.Params.Stream != "stdout" && event.Params.Stream != "stderr" {
return errRemoteProcessEvent
}
data, err := base64.StdEncoding.DecodeString(event.Params.Data)
if err != nil {
return errRemoteProcessEvent
}
if events.Output != nil && len(data) > 0 {
events.Output(event.Params.Stream, data)
}
}
return nil
}

// RemoteProcessKill signals every process of the host process processID of sessionID: SIGTERM,
// or SIGKILL with force. A process whose session already ended is no error.
func (c *Client) RemoteProcessKill(ctx context.Context, sessionID string, processID uint64, force bool) error {
err := c.RemoteHostRequest(ctx, sessionID, "process.kill", struct {
ProcessID uint64 `json:"processId"`
Force bool `json:"force"`
}{processID, force}, nil)
if remoteHostCode(err) == "UNKNOWN_RESOURCE" {
return nil
}
return err
}

// RemoteTempDirectory creates a fresh folder only the host account can open (0700) in the host's
// temporary directory and returns its absolute path. prefix names it for diagnostics: one to 64
// ASCII letters, digits, "-" and "_". The caller removes it (RemoteRemove) when done.
func (c *Client) RemoteTempDirectory(ctx context.Context, sessionID, prefix string) (string, error) {
var result struct {
Path string `json:"path"`
}
if err := c.RemoteHostRequest(ctx, sessionID, "fs.tempDirectory", struct {
Prefix string `json:"prefix"`
}{prefix}, &result); err != nil {
return "", err
}
return result.Path, nil
}

// RemoteRemove deletes the host path, a folder with everything in it when recursive. Links are
// removed, never followed.
func (c *Client) RemoteRemove(ctx context.Context, sessionID, path string, recursive bool) error {
return c.RemoteHostRequest(ctx, sessionID, "fs.remove", struct {
Path string `json:"path"`
Recursive bool `json:"recursive"`
}{path, recursive}, nil)
}
46 changes: 46 additions & 0 deletions desktop/internal/core/remote_process_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package core

import (
"encoding/json"
"errors"
"slices"
"testing"
)

// A host process's events reach their callbacks in order: started with its process id, then its
// output as bytes. Events that are not the process's and empty output are not delivered. Output of
// an unknown stream or that is not base64 is an error, since the console would miss it.
func TestRemoteProcessEventsReachTheirCallbacks(t *testing.T) {
var got []string
events := RemoteProcessEvents{
Started: func(processID uint64, pid int) {
if processID == 7 && pid == 4242 {
got = append(got, "started")
}
},
Output: func(stream string, data []byte) { got = append(got, stream+":"+string(data)) },
}
for _, raw := range []string{
`{"type":"progress","event":"process.output","params":{"stream":"stdout","data":"aGk="}}`,
`{"type":"remote","event":"process.started","params":{"processId":7,"pid":4242}}`,
`{"type":"remote","event":"process.output","params":{"stream":"stdout","data":"aGk="}}`,
`{"type":"remote","event":"process.output","params":{"stream":"stderr","data":""}}`,
`{"type":"remote","event":"process.output","params":{"stream":"stderr","data":"b29wcw=="}}`,
`{"type":"remote","event":"terminal.output","params":{}}`,
} {
if err := deliverRemoteProcessEvent(json.RawMessage(raw), events); err != nil {
t.Fatalf("event %d: %v", len(got), err)
}
}
if want := []string{"started", "stdout:hi", "stderr:oops"}; !slices.Equal(got, want) {
t.Fatalf("delivered %d events, want %d", len(got), len(want))
}
for _, bad := range []string{
`{"type":"remote","event":"process.output","params":{"stream":"stdin","data":"aGk="}}`,
`{"type":"remote","event":"process.output","params":{"stream":"stdout","data":"not base64!"}}`,
} {
if err := deliverRemoteProcessEvent(json.RawMessage(bad), events); !errors.Is(err, errRemoteProcessEvent) {
t.Fatalf("an unreadable event was %v", err)
}
}
}
Loading
Loading