跳到主要内容

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

提交记录
修改docs/guide/workbench.md+2 −2看文件
@@ -60,9 +60,9 @@ macOS 用 `⌘1–9` 切换当前网页或当前目录的终端;Windows/Linux
6060
6161## 输入法与剪贴板
6262
63删除:先点击目标输入位置,再复制或粘贴。macOS 终端用 `⌘C/V`,Windows/Linux 终端用 `Ctrl+Shift+C/V`。普通网页、编辑器和本机输入框按所选键盘习惯操作;“设置 → 通用”可调整。
63新增:先点击目标输入位置,再复制或粘贴。macOS 终端用 `⌘C/V`,Windows/Linux 终端用 `Ctrl+Shift+C/V`。Cage 桌面应用中的 Claude 终端还支持 `Ctrl+V` 粘贴本机剪贴板里的截图或文字。图片会保存到客机并插入可供 Claude Code 读取的路径;传递完成前按 Enter 会等待,传递失败则取消这次待发送操作。普通网页、编辑器和本机输入框按所选键盘习惯操作;“设置 → 通用”可调整。
6464
65删除:终端程序接管鼠标时,Mac 按住 Option 拖选,Windows/Linux 按住 Shift 拖选,再复制。普通浏览器因权限限制无法使用剪贴板时,可用“文本传递”面板传纯文本。
65新增:Claude Code 自己管理的选区和 `/copy` 发出的文字复制会写入本机剪贴板,并参与现有共享剪贴板同步。终端重连时只恢复历史画面,不重复执行旧的复制。终端程序接管鼠标时,也可在 Mac 按住 Option 拖选,Windows/Linux 按住 Shift 拖选,再复制。Ctrl+C 保持终端中断行为。普通浏览器因权限限制无法使用剪贴板时,可用“文本传递”面板传纯文本。
6666
6767Cage 桌面应用运行 Linux 客机时,本机、Cage 浏览器和 Claude Desktop 双向共享文字、图片、文件和文件夹的剪贴板。点击应用内的复制按钮后可直接在另一端粘贴;切换画面与窗口失焦继续共享。拖选文字仅改变选区,复制后才更新共享内容。范围、大小限制与文件保留规则见 [Claude Desktop:复制与粘贴](desktop.md#复制与粘贴)。
6868
修改internal/workbench/terminal.go+4 −0看文件
@@ -70,6 +70,10 @@ func (s *Server) terminalStream(w http.ResponseWriter, r *http.Request) {
7070 }
7171 if len(subscription.History) > 0 {
7272 _ = ws.SetWriteDeadline(time.Now().Add(10 * time.Second))
73新增: // Replayed output must render without repeating clipboard side effects.
74新增: if err := ws.WriteJSON(map[string]string{"type": "history"}); err != nil {
75新增: return
76新增: }
7377 if err := ws.WriteMessage(websocket.BinaryMessage, subscription.History); err != nil {
7478 return
7579 }
修改internal/workbench/terminal_http_test.go+22 −0看文件
@@ -121,6 +121,28 @@ func TestTerminalViewerDisconnectJoinsSenderAndKeepsPTY(t *testing.T) {
121121 awaitTerminalSignal(t, finished)
122122}
123123
124新增:func TestTerminalHistoryIsMarkedBeforeClipboardReplay(t *testing.T) {
125新增: s := testServer(t)
126新增: t.Cleanup(s.terminals.close)
127新增: history := []byte("\x1b]52;c;Y29weQ==\x07previous output")
128新增: s.terminals.sessions = map[string]*terminalSession{"history": {id: "history", history: history, closed: true}}
129新增: server := httptest.NewServer(s.handler())
130新增: defer server.Close()
131新增: s.origin = server.URL
132新增: ws := connectTerminalViewer(t, s, server, "history")
133新增: _ = ws.SetReadDeadline(time.Now().Add(5 * time.Second))
134新增: var marker struct {
135新增: Type string `json:"type"`
136新增: }
137新增: if err := ws.ReadJSON(&marker); err != nil || marker.Type != "history" {
138新增: t.Fatalf("history marker: %+v, %v", marker, err)
139新增: }
140新增: kind, data, err := ws.ReadMessage()
141新增: if err != nil || kind != websocket.BinaryMessage || string(data) != string(history) {
142新增: t.Fatalf("history bytes changed: kind=%d data=%q err=%v", kind, data, err)
143新增: }
144新增:}
145新增:
124146type blockedInputTerminal struct {
125147 *controlledTerminal
126148 inputStarted chan struct{}
修改ui/scripts/image-input-smoke.mjs+2 −2看文件
@@ -25,7 +25,7 @@ await page.route("**/api/input/image", async (route) => {
2525 });
2626 await route.fulfill(
2727 fail
28删除: ? { status: 502, body: "测试:图片传递失败" }
28新增: ? { status: 502, contentType: "text/plain; charset=utf-8", body: "测试:图片传递失败" }
2929 : {
3030 json: {
3131 path: "/home/cage/.local/share/cage/attachments/image-test.png",
@@ -217,7 +217,7 @@ try {
217217 );
218218 assert.equal(received[2].target, "terminal");
219219 fail = true;
220删除: await imageEvent(".terminal-host", "drop");
220新增: await imageEvent(".xterm-helper-textarea", "paste");
221221 await poll(() => received.length === 4);
222222 await page.keyboard.press("Enter");
223223 release();
修改ui/scripts/rfb-wire-fixture.mjs+10 −4看文件
@@ -9,6 +9,7 @@ export async function startDisplay(upstream, { frameInterval = 50, sharedClipboa
99 const displays = new Set();
1010 const clipboardWriters = new Set();
1111 const sharedWriters = new Set(), sharedSockets = new Set();
12新增: const terminalWriters = new Set();
1213 let width = 640, height = 480, framesPaused = false;
1314 const server = http.createServer((req, res) => {
1415 if (req.url.startsWith("/api/")) {
@@ -23,7 +24,8 @@ export async function startDisplay(upstream, { frameInterval = 50, sharedClipboa
2324 });
2425 server.on("upgrade", (req, socket) => {
2526 const shared = sharedClipboard && new URL(req.url,upstream).pathname === "/api/clipboard";
26删除: if (!shared && !["/api/vnc", "/api/claude-desktop/vnc"].includes(new URL(req.url, upstream).pathname)) { socket.destroy(); return; }
27新增: const terminal = sharedClipboard && /^\/api\/terminals\/[^/]+\/stream$/.test(new URL(req.url, upstream).pathname);
28新增: if (!shared && !terminal && !["/api/vnc", "/api/claude-desktop/vnc"].includes(new URL(req.url, upstream).pathname)) { socket.destroy(); return; }
2729 sockets.add(socket);
2830 stats.connections++;
2931 const key = createHash("sha1").update(req.headers["sec-websocket-key"] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");
@@ -39,6 +41,8 @@ export async function startDisplay(upstream, { frameInterval = 50, sharedClipboa
3941 socket.write(Buffer.concat([header, payload]));
4042 };
4143 const sharedWrite = value => send(Buffer.from(JSON.stringify(value)),1);
44新增: const terminalWrite = text => send(Buffer.from(text));
45新增: if (terminal) terminalWriters.add(terminalWrite);
4246 if (shared) {
4347 stats.clipboardConnections++; sharedWriters.add(sharedWrite); sharedSockets.add(socket);
4448 sharedWrite({ hello: { version: 1, os: "linux", session: "fixture-session", formats: ["text", "png", "files"], available: true } });
@@ -133,12 +137,13 @@ export async function startDisplay(upstream, { frameInterval = 50, sharedClipboa
133137 const value = JSON.parse(payload.toString());
134138 stats.clipboardUpdates.push(value);
135139 sharedWrite({ ack: value.serial });
136删除: } else if (opcode === 1 || opcode === 2) consume(payload);
140新增: } else if (!terminal && (opcode === 1 || opcode === 2)) consume(payload);
137141 }
138142 });
139143 socket.on("error", () => {});
140删除: socket.on("close", () => { clearInterval(timer); displays.delete(resize); clipboardWriters.delete(clipboard); sharedWriters.delete(sharedWrite); sharedSockets.delete(socket); sockets.delete(socket); stats.closed++; });
141删除: if (!shared) send(Buffer.from("RFB 003.008\n"));
144新增: socket.on("close", () => { clearInterval(timer); displays.delete(resize); clipboardWriters.delete(clipboard); sharedWriters.delete(sharedWrite); terminalWriters.delete(terminalWrite); sharedSockets.delete(socket); sockets.delete(socket); stats.closed++; });
145新增: if (terminal) terminalWrite("Terminal clipboard ready\r\n$ ");
146新增: else if (!shared) send(Buffer.from("RFB 003.008\n"));
142147 });
143148 await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
144149 return {
@@ -147,6 +152,7 @@ export async function startDisplay(upstream, { frameInterval = 50, sharedClipboa
147152 pauseFrames(paused) { framesPaused = paused; },
148153 clipboard(text) { for (const write of clipboardWriters) write(text); },
149154 sharedClipboard(value) { for (const write of sharedWriters) write(value); },
155新增: terminalOutput(text) { for (const write of terminalWriters) write(text); },
150156 disconnectClipboard() { for (const socket of sharedSockets) socket.destroy(); },
151157 resize(size) { width = size.width; height = size.height; for (const resize of displays) resize(); },
152158 close: async () => {
修改ui/scripts/shared-clipboard-smoke.mjs+10 −1看文件
@@ -10,6 +10,7 @@ const writes = [];
1010const { browser, page, state, errors } = await createWorkbench({
1111 mockWebSockets: false, url: display.url,
1212 nativeRequest: request => {
13新增: if (request.action === "clipboardWrite") { clipboard = { text: request.text }; revision++; return true; }
1314 if (request.action === "clipboardRevision") return revision;
1415 if (request.action === "clipboardSyncRead") return { ...clipboard, revision };
1516 if (request.action === "clipboardSyncWrite") {
@@ -52,11 +53,19 @@ try {
5253 await waitFor(() => clipboard.text === "guest background copy");
5354 assert.equal(display.stats.clipboardConnections,1,"hiding a canvas retains the shared clipboard");
5455
56新增: await page.getByRole("button", { name: "新建终端", exact: true }).first().click();
57新增: await page.getByRole("menuitem", { name: "普通终端", exact: true }).click();
58新增: await page.waitForFunction(() => document.querySelector(".xterm-rows")?.textContent.includes("Terminal"));
59新增: await page.locator(".xterm-helper-textarea").focus();
60新增: const terminalCopy = "Claude 终端复制 → 共享剪贴板";
61新增: display.terminalOutput(`\x1b]52;c;${Buffer.from(terminalCopy).toString("base64")}\x07`);
62新增: await waitFor(() => clipboard.text === terminalCopy && display.stats.clipboardUpdates.at(-1).text === terminalCopy);
63新增:
5564 const connections = display.stats.clipboardConnections;
5665 display.disconnectClipboard();
5766 clipboard = { text:"copy during disconnection" }; revision++;
5867 await waitFor(() => display.stats.clipboardConnections > connections && display.stats.clipboardUpdates.at(-1).text === "copy during disconnection");
5968 await page.waitForFunction(() => window.cageSharedClipboardActive === true);
6069 assert.deepEqual(errors,[]);
61删除: console.log("PASS: Desktop text/image/files copy, no echo, native paste, background sharing, disconnect and fresh host snapshot on reconnect.");
70新增: console.log("PASS: Desktop text/image/files copy, terminal OSC 52 to shared guest clipboard, no echo, native paste, background sharing and reconnect.");
6271} finally { await browser.close(); await display.close(); }
修改ui/scripts/terminal-copy-smoke.mjs+27 −5看文件
@@ -23,9 +23,11 @@ for (const platform of ["MacIntel", "Win32", "Linux x86_64"]) {
2323 if (type === "input") {
2424 inputs.push(data);
2525 if (data === "\x03") interrupted.resolve();
26新增: if (data === "\x1b[99;6u") socket.send(Buffer.from(`\x1b]52;c;${Buffer.from("Claude 选中文本 🖼️").toString("base64")}\x07`));
2627 }
2728 });
28删除: socket.send(Buffer.from("CopyMe1234\r\n$ "));
29新增: socket.send(JSON.stringify({ type: "history" }));
30新增: socket.send(Buffer.from(`\x1b]52;c;${Buffer.from("旧复制不得重放").toString("base64")}\x07CopyMe1234\r\n$ `));
2931 });
3032 await page.reload();
3133 await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click();
@@ -40,17 +42,27 @@ for (const platform of ["MacIntel", "Win32", "Linux x86_64"]) {
4042 };
4143 const mac = platform === "MacIntel";
4244 const copy = () => page.keyboard.press(mac ? "Meta+c" : "Control+Shift+C");
45新增: assert.deepEqual(writes, [], "replayed OSC 52 must not overwrite the clipboard");
4346 await drag();
4447 await copy();
4548 await page.getByText("已复制终端选中文本", { exact: true }).waitFor();
4649 assert.deepEqual(writes, ["CopyMe"]);
4750
51新增: // Replay while the terminal already owns focus, as on a reconnect. The
52新增: // next live OSC 52 must still work after the replay has finished parsing.
53新增: terminalSocket.send(JSON.stringify({ type: "history" }));
54新增: terminalSocket.send(Buffer.from("\x1b]52;c;c3RhbGU=\x07REPLAY_DONE\r\n"));
55新增: await page.locator(".xterm-rows").getByText(/REPLAY_DONE/).waitFor();
56新增: assert.deepEqual(writes, ["CopyMe"]);
57新增:
4858 terminalSocket.send(Buffer.from("\x1b[?1002h\x1b[?1006h"));
4959 await page.locator(".xterm.enable-mouse-events").waitFor();
5060 await drag();
5161 await copy();
52删除: await page.getByText(new RegExp(`请按住 ${mac ? "Option" : "Shift"} 拖选文字`)).waitFor();
53删除: assert.deepEqual(writes, ["CopyMe"]);
62新增: await page.getByText("已复制终端选中文本", { exact: true }).waitFor();
63新增: const deadline = Date.now() + 3000;
64新增: while (writes.length < 2 && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 10));
65新增: assert.deepEqual(writes, ["CopyMe", "Claude 选中文本 🖼️"]);
5466 assert.ok(inputs.some(data => data.startsWith("\x1b[<")));
5567
5668 const previousInputs = inputs.length;
@@ -60,15 +72,25 @@ for (const platform of ["MacIntel", "Win32", "Linux x86_64"]) {
6072 await page.keyboard.up(modifier);
6173 await copy();
6274 await page.getByText("已复制终端选中文本", { exact: true }).waitFor();
63删除: assert.deepEqual(writes, ["CopyMe", "CopyMe"]);
75新增: const copyDeadline = Date.now() + 3000;
76新增: while (writes.length < 3 && Date.now() < copyDeadline) await new Promise(resolve => setTimeout(resolve, 10));
77新增: assert.deepEqual(writes, ["CopyMe", "Claude 选中文本 🖼️", "CopyMe"]);
6478 assert.equal(inputs.length, previousInputs);
6579 await page.keyboard.press("Control+c");
6680 await Promise.race([
6781 interrupted.promise,
6882 new Promise((_, reject) => setTimeout(() => reject(new Error("Ctrl+C 未传给终端")), 3000).unref()),
6983 ]);
84新增: // Output arriving while a local field owns focus cannot replace a copy.
85新增: await page.evaluate(() => {
86新增: const input = document.createElement("input"); input.id = "local-copy-target";
87新增: document.body.append(input); input.focus();
88新增: });
89新增: terminalSocket.send(Buffer.from(`\x1b]52;c;${Buffer.from("background copy").toString("base64")}\x07BACKGROUND_DONE`));
90新增: await page.locator(".xterm-rows").getByText(/BACKGROUND_DONE/).waitFor();
91新增: assert.equal(writes.length, 3);
7092 assert.deepEqual(errors, []);
71删除: console.log(`${platform}: drag selection, mouse tracking, clipboard shortcut and Ctrl+C passed`);
93新增: console.log(`${platform}: xterm/Claude selections, OSC 52, history/focus isolation and Ctrl+C passed`);
7294 } finally {
7395 await browser.close();
7496 }
新增ui/scripts/terminal-image-paste-smoke.mjs+93 −0看文件
@@ -0,0 +1,93 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a/e8AAAAASUVORK5CYII=";
5新增:for (const platform of ["MacIntel", "Win32", "Linux x86_64"]) {
6新增: const inputs = [], images = [];
7新增: let clipboard = { png }, reads = 0, release, fail = false;
8新增: const { page, browser, state, errors } = await createWorkbench({
9新增: mockWebSockets: false,
10新增: beforeNavigate: page => page.addInitScript(platform => {
11新增: Object.defineProperty(navigator, "platform", { value: platform });
12新增: }, platform),
13新增: nativeRequest: request => {
14新增: if (request.action === "clipboardReadContent") { reads++; return clipboard; }
15新增: },
16新增: });
17新增: const wait = async predicate => {
18新增: const deadline = Date.now() + 5000;
19新增: while (!predicate() && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 10));
20新增: assert.ok(predicate(), "terminal paste did not finish");
21新增: };
22新增: try {
23新增: await page.route("**/api/terminals", route => {
24新增: if (route.request().method() !== "POST") return route.fallback();
25新增: const terminal = { id: "claude-image", kind: "claude", title: "Claude 1", workspace: state.settings.workspace };
26新增: state.terminals = [terminal];
27新增: return route.fulfill({ json: terminal });
28新增: });
29新增: await page.route("**/api/input/paste/start", route => route.fulfill({ json: { available: true, context: "claude-image" } }));
30新增: await page.route("**/api/input/image", async route => {
31新增: images.push(route.request().postDataJSON());
32新增: await new Promise(resolve => { release = resolve; });
33新增: await route.fulfill(fail ? { status: 502, contentType: "text/plain", body: "测试:图片传递失败" }
34新增: : { json: { path: "/guest/attachments/image-test.png" } });
35新增: });
36新增: await page.routeWebSocket("**/api/**", socket => {
37新增: if (!socket.url().includes("/terminals/")) return socket.close();
38新增: socket.onMessage(message => { const value = JSON.parse(message); if (value.type === "input") inputs.push(value.data); });
39新增: socket.send(Buffer.from("\x1b[?2004hClaude image paste\r\n> "));
40新增: });
41新增: await page.reload();
42新增: await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click();
43新增: await page.getByRole("button", { name: "新建终端", exact: true }).first().click();
44新增: await page.getByRole("menuitem", { name: /Claude/ }).first().click();
45新增: await page.waitForFunction(() => document.querySelector(".xterm-rows")?.textContent.includes("Claude"));
46新增: await page.locator(".xterm-helper-textarea").focus();
47新增: const expected = "\x1b[200~'/guest/attachments/image-test.png' \x1b[201~";
48新增: // Claude's Ctrl+V reads the host image; Enter waits for its guest path.
49新增: await page.keyboard.press("Control+v");
50新增: await wait(() => images.length === 1);
51新增: await page.keyboard.press("Enter");
52新增: assert.deepEqual(inputs, []);
53新增: release();
54新增: await wait(() => inputs.length === 2);
55新增: assert.deepEqual(inputs, [expected, "\r"]);
56新增: assert.equal(images[0].png, png);
57新增: assert.equal(images[0].target, "terminal");
58新增: assert.equal(images[0].id, "claude-image");
59新增:
60新增: await page.keyboard.press(platform === "MacIntel" ? "Meta+v" : "Control+Shift+V");
61新增: await wait(() => images.length === 2);
62新增: release();
63新增: await wait(() => inputs.length === 3);
64新增: assert.equal(inputs.at(-1), expected);
65新增: assert.equal(reads, 2);
66新增:
67新增: // The desktop Edit > Paste action shares the same image path.
68新增: assert.equal(await page.evaluate(() => window.cageEditAction("paste")), true);
69新增: await wait(() => images.length === 3);
70新增: release();
71新增: await wait(() => inputs.length === 4);
72新增: assert.equal(inputs.at(-1), expected);
73新增:
74新增: fail = true;
75新增: await page.keyboard.press("Control+v");
76新增: await wait(() => images.length === 4);
77新增: await page.keyboard.press("Enter");
78新增: release();
79新增: await page.getByText("测试:图片传递失败", { exact: true }).waitFor();
80新增: assert.equal(inputs.length, 4, "a failed image must cancel its queued Enter");
81新增: fail = false;
82新增: clipboard = { text: "paste after failure" };
83新增: await page.keyboard.press("Control+v");
84新增: await wait(() => inputs.length === 5);
85新增: assert.equal(inputs.at(-1), "\x1b[200~paste after failure\x1b[201~");
86新增: assert.deepEqual(errors, []);
87新增: console.log(`${platform}: native Ctrl+V, primary paste, Edit > Paste, image/Enter ordering and failure recovery passed`);
88新增: } catch (error) {
89新增: console.error({ platform, reads, inputs, images: images.length, terminals: state.terminals,
90新增: recentRequests: state.requests.slice(-8), screen: await page.locator(".terminal-view").allTextContents(), errors });
91新增: throw error;
92新增: } finally { await browser.close(); }
93新增:}
修改ui/scripts/terminal-newline-smoke.mjs+2 −0看文件
@@ -24,9 +24,11 @@ for (const platform of ["MacIntel", "Win32", "Linux x86_64"]) {
2424 });
2525 remote.send(Buffer.from("$ "));
2626 });
27新增: await page.reload();
2728 await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click();
2829 await page.getByRole("button", { name: "新建终端", exact: true }).first().click();
2930 await page.getByRole("menuitem", { name: "普通终端", exact: true }).click();
31新增: await page.waitForFunction(() => document.querySelector(".xterm-rows")?.textContent.includes("$"));
3032 await page.locator(".xterm-helper-textarea").focus();
3133 async function press(key, expected) {
3234 const start = inputs.length;
新增ui/src/terminal-clipboard.mjs+13 −0看文件
@@ -0,0 +1,13 @@
1新增:// OSC 52 writes only. Never answer terminal requests to read the host clipboard.
2新增:export function terminalClipboardText(data) {
3新增: const separator = data.indexOf(";");
4新增: if (separator < 0 || !["", "c"].includes(data.slice(0, separator))) return;
5新增: const encoded = data.slice(separator + 1);
6新增: if (encoded === "?" || encoded.length > 4 * Math.ceil((2 * 1024 * 1024) / 3) ||
7新增: encoded.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(encoded)) return;
8新增: try {
9新增: const bytes = Uint8Array.from(atob(encoded), character => character.charCodeAt(0));
10新增: if (bytes.length > 2 * 1024 * 1024) return;
11新增: return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
12新增: } catch { /* Ignore malformed terminal output. */ }
13新增:}
新增ui/src/terminal-clipboard.test.mjs+17 −0看文件
@@ -0,0 +1,17 @@
1新增:import test from "node:test";
2新增:import assert from "node:assert/strict";
3新增:import { terminalClipboardText } from "./terminal-clipboard.mjs";
4新增:
5新增:test("OSC 52 accepts UTF-8 clipboard writes within the shared clipboard limit", () => {
6新增: const text = "Claude 回复\n含有换行和 emoji 🖼️";
7新增: assert.equal(terminalClipboardText(`c;${Buffer.from(text).toString("base64")}`), text);
8新增: assert.equal(terminalClipboardText(";"), "");
9新增: const maximum = "x".repeat(2 * 1024 * 1024);
10新增: assert.equal(terminalClipboardText(`c;${Buffer.from(maximum).toString("base64")}`), maximum);
11新增: assert.equal(terminalClipboardText(`c;${Buffer.from(maximum + "x").toString("base64")}`), undefined);
12新增:});
13新增:
14新增:test("OSC 52 ignores clipboard reads, other selections and malformed content", () => {
15新增: for (const value of ["c;?", "p;eA==", "c", "c;%%%", "c;eA", "c;e===", "c;/w=="])
16新增: assert.equal(terminalClipboardText(value), undefined, value);
17新增:});
修改ui/src/views.jsx+46 −6看文件
@@ -13,7 +13,8 @@ import { FitAddon } from "@xterm/addon-fit";
1313import RFB from "../.generated/novnc/core/rfb.js";
1414import { api, writeClipboard, nativeAvailable } from "./api";
1515import { runtimeSocketURL } from "./client-context.mjs";
16删除:import { readClipboardContent, transferFiles, hasFiles, prepareClipboardPaste, sendImage } from "./image-transfer";
16新增:import { readClipboardContent, transferFiles, hasFiles, imagePayload, prepareClipboardPaste, sendImage } from "./image-transfer";
17新增:import { terminalClipboardText } from "./terminal-clipboard.mjs";
1718import { sendFiles, shellFilePaths } from "./file-transfer";
1819import { installRemoteInput } from "./remote-input";
1920import { useWindowVisibility } from "./window-visibility";
@@ -353,6 +354,17 @@ export function TerminalView({ session, visible, focused = true, onStatus, onCon
353354 resize();
354355 if (startupVisible && visibleRef.current && focusedRef.current) terminal.focus();
355356 };
357新增: let historyFrame = false, replayingHistory = false;
358新增: const clipboardHandler = terminal.parser.registerOscHandler(52, async (data) => {
359新增: if (disposed || replayingHistory || !visibleRef.current || !focusedRef.current || !box.current?.contains(document.activeElement)) return true;
360新增: const text = terminalClipboardText(data);
361新增: if (text === undefined) return true;
362新增: try {
363新增: await writeClipboard(text);
364新增: if (!disposed) onStatus("已复制终端选中文本");
365新增: } catch { if (!disposed) onStatus("无法写入本机剪贴板"); }
366新增: return true;
367新增: });
356368 ws.onmessage = (event) => {
357369 if (typeof event.data === "string") {
358370 let state;
@@ -361,9 +373,14 @@ export function TerminalView({ session, visible, focused = true, onStatus, onCon
361373 startupPending = state.pending;
362374 terminal.refresh(0, terminal.rows - 1);
363375 }
376新增: if (state.type === "history") historyFrame = true;
364377 return;
365378 }
366删除: terminal.write(new Uint8Array(event.data));
379新增: if (historyFrame) {
380新增: historyFrame = false;
381新增: replayingHistory = true;
382新增: terminal.write(new Uint8Array(event.data), () => { replayingHistory = false; });
383新增: } else terminal.write(new Uint8Array(event.data));
367384 };
368385 ws.onclose = () => { setConnected(false); reveal(); };
369386 const send = (data) => {
@@ -388,7 +405,7 @@ export function TerminalView({ session, visible, focused = true, onStatus, onCon
388405 text = shellFilePaths(result.paths);
389406 }
390407 if (value.png) {
391删除: const result = await sendImage(value, "terminal", session.id);
408新增: const result = await sendImage(value, "terminal", session.id, { valid: () => !disposed && visibleRef.current && focusedRef.current && ws.readyState === WebSocket.OPEN });
392409 text = shellFilePaths([result.path]);
393410 }
394411 if (disposed || !visibleRef.current || !focusedRef.current) throw new Error("终端已切换,请回到原终端重新粘贴");
@@ -400,10 +417,11 @@ export function TerminalView({ session, visible, focused = true, onStatus, onCon
400417 };
401418 const host = box.current;
402419 const onPaste = (event) => {
403删除: if (!visibleRef.current) return;
420新增: if (!visibleRef.current || !focusedRef.current) return;
404421 event.preventDefault(); event.stopImmediatePropagation();
405422 const files = transferFiles(event.clipboardData);
406删除: if (files.length) receive({ files });
423新增: if (files.length === 1 && files[0].type.startsWith("image/")) receive(imagePayload(files[0]));
424新增: else if (files.length) receive({ files });
407425 else if (event.clipboardData?.types.includes("text/plain")) receive({ text: event.clipboardData.getData("text/plain") });
408426 };
409427 const onDragOver = (event) => {
@@ -422,6 +440,10 @@ export function TerminalView({ session, visible, focused = true, onStatus, onCon
422440 const copySelection = () => {
423441 const text = terminal.getSelection();
424442 if (!text) {
443新增: // Claude owns its TUI selection while mouse reporting is enabled. CSI-u
444新增: // preserves Ctrl+Shift+C, which cannot be represented as plain Ctrl+C.
445新增: if (terminal.modes.mouseTrackingMode !== "none")
446新增: void enqueue(() => send("\x1b[99;6u")).catch(() => {});
425447 onStatus(terminal.modes.mouseTrackingMode === "none"
426448 ? "请先拖选要复制的终端文字"
427449 : `当前程序接管了鼠标。请按住 ${isMac ? "Option" : "Shift"} 拖选文字,再复制。`);
@@ -431,6 +453,14 @@ export function TerminalView({ session, visible, focused = true, onStatus, onCon
431453 .then(() => onStatus("已复制终端选中文本"))
432454 .catch(() => onStatus("无法写入本机剪贴板"));
433455 };
456新增: const onCopy = (event) => {
457新增: if (!visibleRef.current || !focusedRef.current) return;
458新增: event.preventDefault(); event.stopImmediatePropagation();
459新增: const text = terminal.getSelection();
460新增: if (text) event.clipboardData?.setData("text/plain", text);
461新增: copySelection();
462新增: };
463新增: host.addEventListener("copy", onCopy, true);
434464 onControls?.({
435465 edit(action) {
436466 if (!box.current?.contains(document.activeElement)) return false;
@@ -461,7 +491,15 @@ export function TerminalView({ session, visible, focused = true, onStatus, onCon
461491 }
462492 return false;
463493 }
464删除: if (!terminalModifier(event) || event.type !== "keydown") return true;
494新增: if (event.type !== "keydown") return true;
495新增: const claudeImagePaste = ((session.terminalKind || session.kind) === "claude" || session.cli_session_id) &&
496新增: event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "v";
497新增: if (claudeImagePaste && nativeAvailable()) {
498新增: event.preventDefault();
499新增: receive(readClipboardContent());
500新增: return false;
501新增: }
502新增: if (!terminalModifier(event)) return true;
465503 const key = event.key.toLowerCase();
466504 if (key === "c") {
467505 event.preventDefault();
@@ -498,7 +536,9 @@ export function TerminalView({ session, visible, focused = true, onStatus, onCon
498536 clearTimeout(startupTimer);
499537 revealStartup.current = null;
500538 startupRender.dispose();
539新增: clipboardHandler.dispose();
501540 host.removeEventListener("paste", onPaste, true);
541新增: host.removeEventListener("copy", onCopy, true);
502542 host.removeEventListener("dragover", onDragOver);
503543 host.removeEventListener("drop", onDrop);
504544 onControls?.(null);