跳到主要内容

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

浏览文件

terminal_session.go

239 行 · 5.7 KB历史下载
1package workbench
2
3import (
4 "context"
5 "errors"
6 "io"
7 "os"
8 "os/exec"
9 "sync"
10)
11
12var errTerminalInputFull = errors.New("terminal input queue is full")
13
14type terminalPTY interface {
15 io.ReadWriteCloser
16 Resize(cols, rows uint16) error
17 Wait() error
18 Kill() error
19}
20
21type terminalSession struct {
22 mu sync.Mutex
23 id, title string
24 sharedID string
25 connectionID string
26 conversationEnded bool
27 workspace string
28 kind, claudeAccountID string
29 loginGuestID string
30 loginLinkMu sync.Mutex
31 loginLinkCleanup sync.Once
32 claudeAccountSource string
33 cmd *exec.Cmd
34 file terminalPTY
35 history []byte
36 closed bool
37 clients map[chan []byte]bool
38 done chan struct{}
39 inputs chan string
40 stopping chan struct{}
41 closeOnce sync.Once
42 cliStartupDone chan struct{}
43}
44
45func (t *terminalSession) ownsConversation() bool {
46 t.mu.Lock()
47 defer t.mu.Unlock()
48 return !t.closed && !t.conversationEnded
49}
50
51func newTerminalSession(file terminalPTY) *terminalSession {
52 return &terminalSession{file: file, clients: map[chan []byte]bool{}, done: make(chan struct{}), inputs: make(chan string, 8), stopping: make(chan struct{})}
53}
54
55func (t *terminalSession) summary() map[string]any {
56 t.mu.Lock()
57 defer t.mu.Unlock()
58 closed := t.closed
59 if t.done != nil {
60 select {
61 case <-t.done:
62 closed = true
63 default:
64 closed = false
65 }
66 }
67 return map[string]any{"id": t.id, "title": t.title, "closed": closed, "workspace": t.workspace, "kind": t.kind,
68 "claude_account_id": t.claudeAccountID, "claude_account_source": t.claudeAccountSource, "cli_session_id": t.sharedID,
69 "cli_starting": t.cliStartupPendingLocked()}
70}
71
72func (t *terminalSession) cliStartupPendingLocked() bool {
73 if t.cliStartupDone == nil || t.closed {
74 return false
75 }
76 select {
77 case <-t.cliStartupDone:
78 return false
79 default:
80 return true
81 }
82}
83
84func (t *terminalSession) finishCLIStartup() {
85 t.mu.Lock()
86 defer t.mu.Unlock()
87 if t.cliStartupPendingLocked() {
88 close(t.cliStartupDone)
89 }
90}
91
92func (t *terminalSession) stopPTY() {
93 t.closeOnce.Do(func() {
94 t.mu.Lock()
95 t.closed = true
96 t.mu.Unlock()
97 if t.stopping != nil {
98 close(t.stopping)
99 }
100 if t.file != nil {
101 // Close may wait inside ConPTY. Never hold the session mutex while
102 // the reader needs it to drain the final output and finish.
103 _ = t.file.Kill()
104 _ = t.file.Close()
105 }
106 })
107}
108
109func (t *terminalSession) close() {
110 t.stopPTY()
111 if t.done != nil {
112 <-t.done
113 }
114}
115
116// Input belongs to the session once admitted. A viewer never waits inside a
117// PTY write, so disconnecting or locking the account can drain its handler
118// while a guest process is not reading input. A full queue rejects the viewer
119// immediately, so the handler never waits to read a WebSocket close either.
120func (t *terminalSession) enqueueInput(ctx context.Context, input string) error {
121 if err := ctx.Err(); err != nil {
122 return err
123 }
124 t.mu.Lock()
125 defer t.mu.Unlock()
126 if t.closed {
127 return os.ErrClosed
128 }
129 select {
130 case t.inputs <- input:
131 return nil
132 default:
133 return errTerminalInputFull
134 }
135}
136
137func (t *terminalSession) writeInput() {
138 for {
139 select {
140 case <-t.stopping:
141 return
142 case input := <-t.inputs:
143 if _, err := io.WriteString(t.file, input); err != nil {
144 t.stopPTY()
145 return
146 }
147 }
148 }
149}
150
151type terminalSubscription struct {
152 History []byte
153 Output <-chan []byte
154 CLIStartup <-chan struct{}
155 CLIStarting bool
156 session *terminalSession
157 channel chan []byte
158}
159
160// subscribe captures history and registers live output under the same lock.
161// Every byte belongs to exactly one side of this history/live boundary.
162func (t *terminalSession) subscribe() *terminalSubscription {
163 t.mu.Lock()
164 defer t.mu.Unlock()
165 channel := make(chan []byte, 64)
166 if t.closed {
167 close(channel)
168 } else {
169 t.clients[channel] = true
170 }
171 history := append([]byte(nil), t.history...)
172 if t.kind == "claude-login" {
173 history = []byte("请在 Cage 浏览器的临时登录页完成授权。若页面提供验证码,可返回此终端输入。\r\n")
174 }
175 return &terminalSubscription{History: history, Output: channel, CLIStartup: t.cliStartupDone,
176 CLIStarting: t.cliStartupPendingLocked(), session: t, channel: channel}
177}
178
179// Close detaches the viewer; the PTY and its process continue running.
180func (s *terminalSubscription) Close() {
181 s.session.mu.Lock()
182 defer s.session.mu.Unlock()
183 if s.session.clients[s.channel] {
184 delete(s.session.clients, s.channel)
185 close(s.channel)
186 }
187}
188
189func (t *terminalSession) run() {
190 writerDone := make(chan struct{})
191 go func() { defer close(writerDone); t.writeInput() }()
192 t.read()
193 // An SSH process can remain alive after its output side closes. Once no
194 // output can be read, terminate and reap it before completing the session.
195 t.stopPTY()
196 _ = t.file.Wait()
197 <-writerDone
198 // Admission is sealed under mu before stopping the writer. Release queued
199 // input even when the closed terminal remains visible with its history.
200 for len(t.inputs) > 0 {
201 <-t.inputs
202 }
203 t.mu.Lock()
204 for channel := range t.clients {
205 close(channel)
206 delete(t.clients, channel)
207 }
208 t.mu.Unlock()
209 close(t.done)
210}
211
212func (t *terminalSession) read() {
213 buffer := make([]byte, 16<<10)
214 for {
215 n, err := t.file.Read(buffer)
216 if n > 0 {
217 chunk := append([]byte(nil), buffer[:n]...)
218 t.mu.Lock()
219 if t.kind != "claude-login" {
220 t.history = append(t.history, chunk...)
221 if len(t.history) > 512<<10 {
222 t.history = t.history[len(t.history)-(512<<10):]
223 }
224 }
225 for channel := range t.clients {
226 select {
227 case channel <- chunk:
228 default:
229 close(channel)
230 delete(t.clients, channel)
231 }
232 }
233 t.mu.Unlock()
234 }
235 if err != nil {
236 break
237 }
238 }
239}