跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

提交记录

Linux 客机的状态轮询与画面操作复用同一条控制连接

工作台原先为每个控制脚本新建一次 SSH 连接:密钥交换、登录 shell 和 多个进程在主客两侧重复发生。Desktop 文件请求每 1.5 秒查询一次,状态 每 5 秒一次,使用 Desktop 时每分钟新建约 50 条连接。 这些幂等的查询,以及调整画面尺寸、读取画面凭据和显示或隐藏 Desktop 窗口,现在经由一条常驻连接执行。每个脚本仍在独立的 shell 中运行, 取消会结束对应脚本的进程组,输出保持原有 64 KiB 上限。连接空闲 30 秒 后关闭,环境重新启动或服务退出时一并回收;脚本尚未发出时回退到单次 连接。其余控制脚本、macOS 与 Windows 客机沿用原有通道。 Co-Authored-By: Claude <[email protected]>

作者
Lee-xeo
时间
2026/11/10 22:38
提交
51b286d
上一个
b4194b6
这个版本的全部文件
修改internal/workbench/claude_desktop.go+3 −3看文件
@@ -55,7 +55,7 @@ func (s *Server) claudeDesktopStatus(w http.ResponseWriter, r *http.Request) {
5555 }
5656 return json.Marshal(result)
5757 }
58删除: return s.guest(ctx, claudeDesktopSnapshot)
58新增: return s.guestQuick(ctx, claudeDesktopSnapshot)
5959 })
6060 var state claudeDesktopState
6161 if err != nil {
@@ -190,7 +190,7 @@ func (s *Server) claudeDesktopCredentials(w http.ResponseWriter, r *http.Request
190190 }
191191 ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
192192 defer cancel()
193删除: b, err := s.guest(ctx, `set -eu
193新增: b, err := s.guestQuick(ctx, `set -eu
194194systemctl is-active --quiet cage-claude-desktop.service
195195password=$(cat /home/cage/.config/claude-cage/desktop-password)
196196printf '%s\n' "$password"
@@ -249,7 +249,7 @@ for old in $(xrandr --query | awk '/^ +cage-/ {print $1}'); do
249249done`, wid, hei, wid, hei, float64((wid+32)*(hei+8)*60)/1000000, wid, wid+8, wid+16, wid+32, hei, hei+1, hei+2, hei+8)
250250 ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
251251 defer cancel()
252删除: if _, err := s.guest(ctx, script); err != nil {
252新增: if _, err := s.guestQuick(ctx, script); err != nil {
253253 http.Error(w, "Claude Desktop 画面尺寸未能调整", 502)
254254 return
255255 }
修改internal/workbench/desktop_visibility.go+1 −1看文件
@@ -87,7 +87,7 @@ func (s *Server) updateDesktopVisibility(show bool) error {
8787 return ctx.Err()
8888 }
8989 script := "/usr/bin/python3 - " + strconv.FormatBool(show) + " <<'CAGE_DESKTOP_VISIBILITY'\n" + linuxDesktopVisibility + "\nCAGE_DESKTOP_VISIBILITY\n"
90删除: _, err := s.guest(ctx, script)
90新增: _, err := s.guestQuick(ctx, script)
9191 if err != nil && ctx.Err() == nil {
9292 _ = diagnostics.New(s.profile).Record("warn", "desktop-visibility", "应用窗口显示状态未能同步:"+err.Error())
9393 }
修改internal/workbench/file_input.go+29 −16看文件
@@ -125,26 +125,39 @@ func (s *Server) guestFiles(ctx context.Context, target, method, path string, bo
125125 }
126126 script += " " + shellescape.Quote("http://localhost"+path)
127127 }
128新增: var stderr fileControlStderr
129新增: var data []byte
130新增: var err, readErr error
131新增: shared := false
128132 if target != "terminal" && method == "GET" && path == "/requests" {
129133 script = desktopFilesPoll + script
134新增: // The workbench asks for pending requests every second or two.
135新增: var reply guestSessionReply
136新增: if reply, shared, err = s.guestShared(ctx, script); shared {
137新增: data, stderr.data = reply.stdout, reply.stderr
138新增: if err == nil && reply.code != 0 {
139新增: err = fmt.Errorf("exit status %d", reply.code)
140新增: }
141新增: }
130142 }
131删除: command := "exec /bin/bash --noprofile --norc -c " + shellescape.Quote(script)
132删除: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", command)
133删除: var stderr fileControlStderr
134删除: cmd.Stderr = &stderr
135删除: cmd.Stdin = body
136删除: pipe, err := cmd.StdoutPipe()
137删除: if err != nil {
138删除: return nil, err
139删除: }
140删除: if err = cmd.Start(); err != nil {
141删除: return nil, usererror.Wrap("连接文件传递服务", err, "请确认 Cage 安装完整,环境已经启动;持续失败时在设置中导出诊断包。")
142删除: }
143删除: data, readErr := io.ReadAll(io.LimitReader(pipe, 65537+64))
144删除: if readErr != nil || len(data) > 65536+64 {
145删除: _ = cmd.Process.Kill()
143新增: if !shared {
144新增: command := "exec /bin/bash --noprofile --norc -c " + shellescape.Quote(script)
145新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", command)
146新增: cmd.Stderr = &stderr
147新增: cmd.Stdin = body
148新增: pipe, pipeErr := cmd.StdoutPipe()
149新增: if pipeErr != nil {
150新增: return nil, pipeErr
151新增: }
152新增: if err = cmd.Start(); err != nil {
153新增: return nil, usererror.Wrap("连接文件传递服务", err, "请确认 Cage 安装完整,环境已经启动;持续失败时在设置中导出诊断包。")
154新增: }
155新增: data, readErr = io.ReadAll(io.LimitReader(pipe, 65537+64))
156新增: if readErr != nil || len(data) > 65536+64 {
157新增: _ = cmd.Process.Kill()
158新增: }
159新增: err = cmd.Wait()
146160 }
147删除: err = cmd.Wait()
148161 httpStatus := 0
149162 if at := bytes.LastIndex(data, []byte("\nCAGE_FILE_HTTP:")); at >= 0 && target != "terminal" {
150163 httpStatus, _ = strconv.Atoi(strings.TrimSpace(string(data[at+len("\nCAGE_FILE_HTTP:"):])))
新增internal/workbench/guest-session.py+81 −0看文件
@@ -0,0 +1,81 @@
1新增:"""Run the workbench's control scripts over one SSH connection.
2新增:
3新增:Requests: "R <id> <length>\n" followed by the script, or "C <id>\n" to stop
4新增:one. Replies: "D <id> <exit> <stdout length> <stderr length>\n" and both.
5新增:"""
6新增:import os
7新增:import signal
8新增:import subprocess
9新增:import sys
10新增:import threading
11新增:
12新增:# Above the caller's 64 KiB limit, so that it can tell an oversized answer.
13新增:OUTPUT_LIMIT = 64 * 1024 + 256
14新增:ERROR_LIMIT = 4096
15新增:SCRIPT_LIMIT = 1 << 20
16新增:requests, replies = sys.stdin.buffer, sys.stdout.buffer
17新增:writing = threading.Lock()
18新增:running = {}
19新增:
20新增:
21新增:def stop(child):
22新增: try:
23新增: os.killpg(child.pid, signal.SIGKILL)
24新增: except OSError:
25新增: pass
26新增:
27新增:
28新增:def keep(pipe, limit, exceeded=None):
29新增: """The first `limit` bytes. The rest is read and dropped, or refused."""
30新增: data = b''
31新增: while True:
32新增: chunk = pipe.read1(65536)
33新增: if not chunk:
34新增: return data
35新增: data += chunk[:limit - len(data)]
36新增: if len(data) == limit and exceeded:
37新增: exceeded()
38新增: exceeded = None
39新增:
40新增:
41新增:def run(ident, script):
42新增: code, output, errors = 127, b'', []
43新增: try:
44新增: child = subprocess.Popen(['/bin/bash', '--noprofile', '--norc', '-c', script], stdin=subprocess.DEVNULL,
45新增: stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True)
46新增: except OSError as error:
47新增: errors.append(str(error).encode()[:ERROR_LIMIT])
48新增: else:
49新增: running[ident] = child
50新增: drain = threading.Thread(target=lambda: errors.append(keep(child.stderr, ERROR_LIMIT)), daemon=True)
51新增: drain.start()
52新增: output = keep(child.stdout, OUTPUT_LIMIT, lambda: stop(child))
53新增: code = child.wait()
54新增: drain.join()
55新增: running.pop(ident, None)
56新增: with writing:
57新增: replies.write(b'D %d %d %d %d\n' % (ident, code, len(output), len(errors[0])) + output + errors[0])
58新增: replies.flush()
59新增:
60新增:
61新增:replies.write(b'CAGE-GUEST-SESSION 1\n')
62新增:replies.flush()
63新增:while True:
64新增: fields = requests.readline(64).split()
65新增: try:
66新增: if len(fields) == 3 and fields[0] == b'R' and 0 < int(fields[2]) <= SCRIPT_LIMIT:
67新增: script = requests.read(int(fields[2]))
68新增: if len(script) != int(fields[2]):
69新增: break
70新增: threading.Thread(target=run, args=(int(fields[1]), script.decode()), daemon=True).start()
71新增: elif len(fields) == 2 and fields[0] == b'C':
72新增: child = running.get(int(fields[1]))
73新增: if child:
74新增: stop(child)
75新增: else:
76新增: break
77新增: except ValueError:
78新增: break
79新增:# The connection closed: nothing is left to receive an answer.
80新增:for child in list(running.values()):
81新增: stop(child)
新增internal/workbench/guest_session.go+279 −0看文件
@@ -0,0 +1,279 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bufio"
5新增: "context"
6新增: _ "embed"
7新增: "errors"
8新增: "fmt"
9新增: "io"
10新增: "os/exec"
11新增: "strconv"
12新增: "strings"
13新增: "sync"
14新增: "time"
15新增:
16新增: "al.essio.dev/pkg/shellescape"
17新增:)
18新增:
19新增://go:embed guest-session.py
20新增:var guestSessionServer string
21新增:
22新增:const (
23新增: guestSessionReady = "CAGE-GUEST-SESSION 1"
24新增: guestSessionIdle = 30 * time.Second
25新增: guestSessionRetry = 30 * time.Second
26新增: guestSessionStartup = 5 * time.Second
27新增:)
28新增:
29新增:var errGuestSessionEnded = errors.New("guest control session ended")
30新增:
31新增:type guestSessionReply struct {
32新增: code int
33新增: stdout, stderr []byte
34新增:}
35新增:
36新增:// guestSession carries control scripts to a Linux guest over one SSH
37新增:// connection. Opening a connection per script costs a key exchange, a login
38新增:// shell and several processes on both sides, while status polls and display
39新增:// changes arrive every second or two. It closes after a short idle period.
40新增:type guestSession struct {
41新增: mu sync.Mutex
42新增: conn *guestSessionConn
43新增: retryAt time.Time
44新增: idle *time.Timer
45新增:}
46新增:
47新增:type guestSessionConn struct {
48新增: cancel context.CancelFunc
49新增: stdin io.WriteCloser
50新增: writing sync.Mutex
51新增: mu sync.Mutex
52新增: waiting map[uint64]chan guestSessionReply
53新增: next uint64
54新增: ended chan struct{}
55新增:}
56新增:
57新增:func (c *guestSessionConn) close() { c.cancel(); _ = c.stdin.Close() }
58新增:
59新增:func (c *guestSessionConn) alive() bool {
60新增: select {
61新增: case <-c.ended:
62新增: return false
63新增: default:
64新增: return true
65新增: }
66新增:}
67新增:
68新增:func (c *guestSessionConn) receive(output *bufio.Reader, done func()) {
69新增: defer done()
70新增: defer close(c.ended)
71新增: defer c.close()
72新增: for {
73新增: line, err := output.ReadString('\n')
74新增: if err != nil {
75新增: return
76新增: }
77新增: fields := strings.Fields(line)
78新增: if len(fields) != 5 || fields[0] != "D" {
79新增: return
80新增: }
81新增: id, idErr := strconv.ParseUint(fields[1], 10, 64)
82新增: code, codeErr := strconv.Atoi(fields[2])
83新增: outSize, outErr := strconv.Atoi(fields[3])
84新增: errSize, errErr := strconv.Atoi(fields[4])
85新增: if idErr != nil || codeErr != nil || outErr != nil || errErr != nil || outSize < 0 || outSize > 1<<20 || errSize < 0 || errSize > 1<<16 {
86新增: return
87新增: }
88新增: data := make([]byte, outSize+errSize)
89新增: if _, err = io.ReadFull(output, data); err != nil {
90新增: return
91新增: }
92新增: c.mu.Lock()
93新增: waiter := c.waiting[id]
94新增: delete(c.waiting, id)
95新增: c.mu.Unlock()
96新增: if waiter != nil {
97新增: waiter <- guestSessionReply{code: code, stdout: data[:outSize], stderr: data[outSize:]}
98新增: }
99新增: }
100新增:}
101新增:
102新增:// openGuestSession starts the server on the guest. The command's stdin and
103新增:// stdout belong to the returned connection.
104新增:func openGuestSession(parent context.Context, command func(context.Context) *exec.Cmd) (*guestSessionConn, error) {
105新增: ctx, cancel := context.WithCancel(parent)
106新增: cmd := command(ctx)
107新增: stdin, err := cmd.StdinPipe()
108新增: if err != nil {
109新增: cancel()
110新增: return nil, err
111新增: }
112新增: stdout, err := cmd.StdoutPipe()
113新增: if err != nil {
114新增: cancel()
115新增: return nil, err
116新增: }
117新增: if err = cmd.Start(); err != nil {
118新增: cancel()
119新增: return nil, err
120新增: }
121新增: conn := &guestSessionConn{cancel: cancel, stdin: stdin, waiting: map[uint64]chan guestSessionReply{}, ended: make(chan struct{})}
122新增: output := bufio.NewReaderSize(stdout, 64<<10)
123新增: ready := make(chan error, 1)
124新增: go func() {
125新增: // A login shell may print before the server starts.
126新增: for skipped := 0; skipped < 64; skipped++ {
127新增: line, err := output.ReadString('\n')
128新增: if err != nil {
129新增: ready <- err
130新增: return
131新增: }
132新增: if strings.TrimSpace(line) == guestSessionReady {
133新增: ready <- nil
134新增: return
135新增: }
136新增: }
137新增: ready <- errors.New("guest control session did not start")
138新增: }()
139新增: select {
140新增: case err = <-ready:
141新增: case <-time.After(guestSessionStartup):
142新增: err = errors.New("guest control session start timed out")
143新增: case <-ctx.Done():
144新增: err = ctx.Err()
145新增: }
146新增: if err != nil {
147新增: conn.close()
148新增: _ = cmd.Wait()
149新增: return nil, err
150新增: }
151新增: go conn.receive(output, func() { _ = cmd.Wait() })
152新增: return conn, nil
153新增:}
154新增:
155新增:// run sends one script. sent reports whether the guest may have started it:
156新增:// when false, the caller can safely use a connection of its own instead.
157新增:func (g *guestSession) run(ctx context.Context, lifetime context.Context, command func(context.Context) *exec.Cmd, script string) (reply guestSessionReply, sent bool, err error) {
158新增: g.mu.Lock()
159新增: conn := g.conn
160新增: if conn == nil || !conn.alive() {
161新增: g.conn = nil
162新增: if time.Now().Before(g.retryAt) {
163新增: g.mu.Unlock()
164新增: return reply, false, errGuestSessionEnded
165新增: }
166新增: if conn, err = openGuestSession(lifetime, command); err != nil {
167新增: g.retryAt = time.Now().Add(guestSessionRetry)
168新增: g.mu.Unlock()
169新增: return reply, false, err
170新增: }
171新增: g.conn = conn
172新增: }
173新增: if g.idle != nil {
174新增: g.idle.Stop()
175新增: }
176新增: conn.mu.Lock()
177新增: conn.next++
178新增: id, waiter := conn.next, make(chan guestSessionReply, 1)
179新增: conn.waiting[id] = waiter
180新增: conn.mu.Unlock()
181新增: g.mu.Unlock()
182新增: defer g.release(conn)
183新增: forget := func() { conn.mu.Lock(); delete(conn.waiting, id); conn.mu.Unlock() }
184新增: conn.writing.Lock()
185新增: _, err = io.WriteString(conn.stdin, fmt.Sprintf("R %d %d\n%s", id, len(script), script))
186新增: conn.writing.Unlock()
187新增: if err != nil {
188新增: // A partial request never runs: the server needs its full length.
189新增: forget()
190新增: conn.close()
191新增: return reply, false, err
192新增: }
193新增: select {
194新增: case reply = <-waiter:
195新增: return reply, true, nil
196新增: case <-ctx.Done():
197新增: forget()
198新增: conn.writing.Lock()
199新增: _, _ = io.WriteString(conn.stdin, fmt.Sprintf("C %d\n", id))
200新增: conn.writing.Unlock()
201新增: return reply, true, ctx.Err()
202新增: case <-conn.ended:
203新增: forget()
204新增: return reply, true, errGuestSessionEnded
205新增: }
206新增:}
207新增:
208新增:func (g *guestSession) release(conn *guestSessionConn) {
209新增: g.mu.Lock()
210新增: defer g.mu.Unlock()
211新增: conn.mu.Lock()
212新增: busy := len(conn.waiting) > 0
213新增: conn.mu.Unlock()
214新增: if busy || g.conn != conn {
215新增: return
216新增: }
217新增: if g.idle != nil {
218新增: g.idle.Stop()
219新增: }
220新增: g.idle = time.AfterFunc(guestSessionIdle, func() {
221新增: g.mu.Lock()
222新增: defer g.mu.Unlock()
223新增: conn.mu.Lock()
224新增: busy := len(conn.waiting) > 0
225新增: conn.mu.Unlock()
226新增: if g.conn == conn && !busy {
227新增: g.conn = nil
228新增: conn.close()
229新增: }
230新增: })
231新增:}
232新增:
233新增:// close ends the connection; a script still running on it reports an error.
234新增:func (g *guestSession) close() {
235新增: g.mu.Lock()
236新增: defer g.mu.Unlock()
237新增: if g.idle != nil {
238新增: g.idle.Stop()
239新增: }
240新增: if g.conn != nil {
241新增: g.conn.close()
242新增: g.conn = nil
243新增: }
244新增: g.retryAt = time.Time{}
245新增:}
246新增:
247新增:func (s *Server) guestSessionCommand(ctx context.Context) *exec.Cmd {
248新增: return s.sshCommand(ctx, "-T", s.sshTarget(), "--", "exec /usr/bin/python3 -I -u -c "+shellescape.Quote(guestSessionServer))
249新增:}
250新增:
251新增:// guestShared runs a script on the shared connection. ok is false when the
252新增:// script was not sent and the caller should open a connection of its own.
253新增:func (s *Server) guestShared(ctx context.Context, script string) (reply guestSessionReply, ok bool, err error) {
254新增: if s.windowsGuest != nil || s.macosGuest != nil {
255新增: return reply, false, nil
256新增: }
257新增: reply, sent, err := s.controlSession.run(ctx, s.lifetimeContext(), s.guestSessionCommand, script)
258新增: return reply, sent, err
259新增:}
260新增:
261新增:// guestQuick is guest for idempotent scripts that run often or while the
262新增:// user waits: status polls and display changes share one SSH connection.
263新增:// The scripts must not depend on environment changed after it was opened.
264新增:func (s *Server) guestQuick(ctx context.Context, script string) ([]byte, error) {
265新增: reply, ok, err := s.guestShared(ctx, script)
266新增: if !ok {
267新增: return s.guest(ctx, script)
268新增: }
269新增: if err != nil {
270新增: return nil, err
271新增: }
272新增: if len(reply.stdout) > 64<<10 {
273新增: return nil, errors.New("guest control response exceeded its limit")
274新增: }
275新增: if reply.code != 0 {
276新增: return nil, fmt.Errorf("guest control script: exit status %d", reply.code)
277新增: }
278新增: return reply.stdout, nil
279新增:}
新增internal/workbench/guest_session_unix_test.go+220 −0看文件
@@ -0,0 +1,220 @@
1新增://go:build !windows
2新增:
3新增:package workbench
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增: "os"
9新增: "os/exec"
10新增: "path/filepath"
11新增: "runtime"
12新增: "strconv"
13新增: "strings"
14新增: "sync"
15新增: "sync/atomic"
16新增: "syscall"
17新增: "testing"
18新增: "time"
19新增:)
20新增:
21新增:// The server that runs on the guest, started here as a local process.
22新增:func localGuestSession(t *testing.T) (run func(context.Context, string) (guestSessionReply, bool, error), session *guestSession, starts *atomic.Int32) {
23新增: t.Helper()
24新增: if runtime.GOOS == "windows" {
25新增: t.Skip("the control session serves Linux guests")
26新增: }
27新增: for _, name := range []string{"python3", "bash"} {
28新增: if _, err := exec.LookPath(name); err != nil {
29新增: t.Skip(name + " is unavailable")
30新增: }
31新增: }
32新增: lifetime, cancel := context.WithCancel(context.Background())
33新增: session, starts = &guestSession{}, &atomic.Int32{}
34新增: t.Cleanup(func() { session.close(); cancel() })
35新增: command := func(ctx context.Context) *exec.Cmd {
36新增: starts.Add(1)
37新增: return exec.CommandContext(ctx, "python3", "-I", "-u", "-c", guestSessionServer)
38新增: }
39新增: return func(ctx context.Context, script string) (guestSessionReply, bool, error) {
40新增: return session.run(ctx, lifetime, command, script)
41新增: }, session, starts
42新增:}
43新增:
44新增:func TestGuestSessionRunsScriptsOverOneConnection(t *testing.T) {
45新增: run, _, starts := localGuestSession(t)
46新增: ctx := context.Background()
47新增: reply, sent, err := run(ctx, "printf 'out %s' \"$0\"; printf problem >&2; exit 7")
48新增: if err != nil || !sent || reply.code != 7 || string(reply.stdout) != "out /bin/bash" || string(reply.stderr) != "problem" {
49新增: t.Fatalf("reply %+v sent=%v err=%v", reply, sent, err)
50新增: }
51新增: // Each script is a separate shell: no state passes between them.
52新增: if reply, _, err = run(ctx, "cd /tmp; export LEFT=1"); err != nil || reply.code != 0 {
53新增: t.Fatal(reply, err)
54新增: }
55新增: if reply, _, err = run(ctx, "printf '%s' \"${LEFT:-unset}\"; test \"$PWD\" != /tmp"); err != nil || reply.code != 0 || string(reply.stdout) != "unset" {
56新增: t.Fatalf("state leaked between scripts: %+v %v", reply, err)
57新增: }
58新增: // stdin is empty, as on a connection of its own.
59新增: if reply, _, err = run(ctx, "cat; printf done"); err != nil || string(reply.stdout) != "done" {
60新增: t.Fatalf("stdin was not empty: %+v %v", reply, err)
61新增: }
62新增: if reply, _, err = run(ctx, "printf '多字节 ✓\\n\\0binary'"); err != nil || string(reply.stdout) != "多字节 ✓\n\x00binary" {
63新增: t.Fatalf("output changed in transit: %q %v", reply.stdout, err)
64新增: }
65新增: if starts.Load() != 1 {
66新增: t.Fatalf("%d connections were opened for consecutive scripts", starts.Load())
67新增: }
68新增:}
69新增:
70新增:func TestGuestSessionSlowScriptDoesNotDelayOthers(t *testing.T) {
71新增: run, _, starts := localGuestSession(t)
72新增: slow := make(chan error, 1)
73新增: go func() {
74新增: reply, _, err := run(context.Background(), "sleep 1; printf slow")
75新增: if err == nil && string(reply.stdout) != "slow" {
76新增: err = errors.New("slow script lost its output")
77新增: }
78新增: slow <- err
79新增: }()
80新增: time.Sleep(100 * time.Millisecond)
81新增: started := time.Now()
82新增: var group sync.WaitGroup
83新增: for i := 0; i < 8; i++ {
84新增: group.Add(1)
85新增: go func(i int) {
86新增: defer group.Done()
87新增: reply, _, err := run(context.Background(), "printf "+strconv.Itoa(i))
88新增: if err != nil || string(reply.stdout) != strconv.Itoa(i) {
89新增: t.Errorf("script %d: %+v %v", i, reply, err)
90新增: }
91新增: }(i)
92新增: }
93新增: group.Wait()
94新增: if time.Since(started) > 700*time.Millisecond {
95新增: t.Fatal("quick scripts waited for the slow one")
96新增: }
97新增: if err := <-slow; err != nil {
98新增: t.Fatal(err)
99新增: }
100新增: if starts.Load() != 1 {
101新增: t.Fatal("concurrent scripts opened more connections")
102新增: }
103新增:}
104新增:
105新增:func TestGuestSessionCancellationStopsTheScript(t *testing.T) {
106新增: run, _, _ := localGuestSession(t)
107新增: file := filepath.Join(t.TempDir(), "pid")
108新增: ctx, cancel := context.WithCancel(context.Background())
109新增: done := make(chan error, 1)
110新增: go func() {
111新增: _, _, err := run(ctx, "sleep 60 & echo $! > "+file+"; wait")
112新增: done <- err
113新增: }()
114新增: var pid int
115新增: for deadline := time.Now().Add(3 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
116新增: if data, err := os.ReadFile(file); err == nil && len(data) > 1 {
117新增: pid, _ = strconv.Atoi(strings.TrimSpace(string(data)))
118新增: break
119新增: }
120新增: }
121新增: if pid == 0 {
122新增: t.Fatal("script did not start")
123新增: }
124新增: cancel()
125新增: if err := <-done; !errors.Is(err, context.Canceled) {
126新增: t.Fatal(err)
127新增: }
128新增: for deadline := time.Now().Add(3 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
129新增: if syscall.Kill(pid, 0) != nil {
130新增: break
131新增: }
132新增: }
133新增: if syscall.Kill(pid, 0) == nil {
134新增: _ = syscall.Kill(pid, syscall.SIGKILL)
135新增: t.Fatal("a cancelled script kept its background process")
136新增: }
137新增: // The connection stays usable.
138新增: if reply, _, err := run(context.Background(), "printf ok"); err != nil || string(reply.stdout) != "ok" {
139新增: t.Fatal(reply, err)
140新增: }
141新增:}
142新增:
143新增:func TestGuestSessionBoundsOutput(t *testing.T) {
144新增: run, _, _ := localGuestSession(t)
145新增: started := time.Now()
146新增: reply, _, err := run(context.Background(), "yes | head -c 100000000; yes x >&2 | true; head -c 100000 /dev/zero >&2")
147新增: if err != nil || len(reply.stdout) <= 64<<10 || len(reply.stdout) > 64<<10+256 || len(reply.stderr) > 4096 || reply.code == 0 {
148新增: t.Fatalf("stdout=%d stderr=%d code=%d err=%v", len(reply.stdout), len(reply.stderr), reply.code, err)
149新增: }
150新增: if time.Since(started) > 5*time.Second {
151新增: t.Fatal("an oversized answer was not stopped")
152新增: }
153新增:}
154新增:
155新增:func TestGuestSessionFallsBackOnlyBeforeTheScriptIsSent(t *testing.T) {
156新增: if runtime.GOOS == "windows" {
157新增: t.Skip("the control session serves Linux guests")
158新增: }
159新增: session, starts := &guestSession{}, 0
160新增: missing := func(ctx context.Context) *exec.Cmd {
161新增: starts++
162新增: return exec.CommandContext(ctx, filepath.Join(t.TempDir(), "missing"))
163新增: }
164新增: for i := 0; i < 3; i++ {
165新增: if _, sent, err := session.run(context.Background(), context.Background(), missing, "true"); sent || err == nil {
166新增: t.Fatal("an unavailable session claimed to run the script")
167新增: }
168新增: }
169新增: // It is not started again for every poll.
170新增: if starts != 1 {
171新增: t.Fatalf("an unavailable session was started %d times", starts)
172新增: }
173新增:
174新增: run, session, opened := localGuestSession(t)
175新增: done := make(chan error, 1)
176新增: go func() {
177新增: _, sent, err := run(context.Background(), "sleep 30")
178新增: if !sent {
179新增: err = errors.New("a script cut off by the connection was reported as unsent")
180新增: }
181新增: done <- err
182新增: }()
183新增: time.Sleep(200 * time.Millisecond)
184新增: session.close()
185新增: if err := <-done; !errors.Is(err, errGuestSessionEnded) {
186新增: t.Fatal(err)
187新增: }
188新增: if reply, sent, err := run(context.Background(), "printf again"); err != nil || !sent || string(reply.stdout) != "again" || opened.Load() != 2 {
189新增: t.Fatalf("a closed session did not reopen: %+v %v %v %d", reply, sent, err, opened.Load())
190新增: }
191新增:}
192新增:
193新增:func TestGuestSessionToleratesLoginShellOutputAndRejectsOtherServers(t *testing.T) {
194新增: if runtime.GOOS == "windows" {
195新增: t.Skip("the control session serves Linux guests")
196新增: }
197新增: if _, err := exec.LookPath("python3"); err != nil {
198新增: t.Skip("python3 is unavailable")
199新增: }
200新增: noisy := func(ctx context.Context) *exec.Cmd {
201新增: return exec.CommandContext(ctx, "bash", "-c", "echo 'Welcome to the guest'; exec python3 -I -u -c \"$0\"", guestSessionServer)
202新增: }
203新增: session := &guestSession{}
204新增: defer session.close()
205新增: if reply, sent, err := session.run(context.Background(), context.Background(), noisy, "printf ok"); err != nil || !sent || string(reply.stdout) != "ok" {
206新增: t.Fatalf("%+v %v %v", reply, sent, err)
207新增: }
208新增: other := &guestSession{}
209新增: defer other.close()
210新增: silent := func(ctx context.Context) *exec.Cmd {
211新增: return exec.CommandContext(ctx, "bash", "-c", "echo not-a-session; sleep 30")
212新增: }
213新增: started := time.Now()
214新增: if _, sent, err := other.run(context.Background(), context.Background(), silent, "true"); sent || err == nil {
215新增: t.Fatal("an unknown server was used")
216新增: }
217新增: if time.Since(started) > guestSessionStartup+2*time.Second {
218新增: t.Fatal("startup was not bounded")
219新增: }
220新增:}
修改internal/workbench/lifecycle.go+1 −0看文件
@@ -147,6 +147,7 @@ func (s *Server) closeService() error {
147147 if browser != nil {
148148 browser.close()
149149 }
150新增: s.controlSession.close()
150151 if s.windowsGuest == nil {
151152 s.closeErr = s.closeProxyGate("控制服务正在退出,外网保持关闭")
152153 }
修改internal/workbench/runtime.go+1 −0看文件
@@ -312,6 +312,7 @@ func (s *Server) runCage(args ...string) error {
312312func (s *Server) startEnvironment(syncTimezone bool) error {
313313 s.desktopViews.reset()
314314 s.browserViews.reset()
315新增: s.controlSession.close()
315316 s.desktopStatus.invalidate()
316317 defer s.desktopStatus.invalidate()
317318 if err := s.requireStorageReady(); err != nil {
修改internal/workbench/server.go+1 −0看文件
@@ -82,6 +82,7 @@ type Server struct {
8282 diagnosticCount int
8383 tickets map[string]time.Time
8484 browserControl *browserClient
85新增: controlSession guestSession
8586 windowsBrowserControl *windowsBrowserClient
8687 nativeDownloads map[string]*nativeDownload
8788 nativeDownloadSlots chan struct{}