| 1 | import { browserRequest, desktopRequest } from "./transport.mjs"; |
| 2 | |
| 3 | const clamp = (value, low, high) => Math.max(low, Math.min(high, value)); |
| 4 | export function viewportSize(element) { |
| 5 | return { |
| 6 | width: clamp(Math.round(element.clientWidth), 240, 1440), |
| 7 | height: clamp(Math.round(element.clientHeight), 160, 1600), |
| 8 | }; |
| 9 | } |
| 10 | |
| 11 | export function framePoint(rect, frame, x, y) { |
| 12 | const width = frame.content_width || frame.width; |
| 13 | const height = frame.content_height || frame.height; |
| 14 | const scale = Math.min(rect.width / width, rect.height / height); |
| 15 | if (!(scale > 0)) return null; |
| 16 | const left = rect.left + (rect.width - width * scale) / 2; |
| 17 | const top = rect.top + (rect.height - height * scale) / 2; |
| 18 | const px = Math.floor((x - left) / scale); |
| 19 | const py = Math.floor((y - top) / scale); |
| 20 | return px >= 0 && px < width && py >= 0 && py < height ? {x: px, y: py, scale} : null; |
| 21 | } |
| 22 | |
| 23 | |
| 24 | |
| 25 | export function connectDisplay(stage, update, id, start, tool, initialURL) { |
| 26 | const desktop = tool === "desktop"; |
| 27 | const request = desktop ? desktopRequest : browserRequest; |
| 28 | const toolName = desktop ? "Claude Desktop" : "远程浏览器"; |
| 29 | let waitingSince = 0, homeNotice = ""; |
| 30 | const base = "/" + id; |
| 31 | let alive = true, visible = true, opened = false, opening = true, writing = false; |
| 32 | let frame = null, read, timer, paused = false, mayExist = false; |
| 33 | let generation = 0, actionFrame = false, quietReads = 0, writeType = ""; |
| 34 | let pixelRatioSupported = false; |
| 35 | const displaySize = () => ({...viewportSize(stage), |
| 36 | ...(pixelRatioSupported ? {pixel_ratio:clamp(window.devicePixelRatio || 1, 1, 8)} : {})}); |
| 37 | const needsResize = size => frame && (frame.width !== size.width || frame.height !== size.height || |
| 38 | (pixelRatioSupported && frame.requested_pixel_ratio !== size.pixel_ratio)); |
| 39 | let queuedScroll = null, scrollTimer; |
| 40 | |
| 41 | |
| 42 | function cancelScroll() { |
| 43 | clearTimeout(scrollTimer); scrollTimer = null; queuedScroll = null; |
| 44 | } |
| 45 | let awaitingResizeFrame = false, pendingAddress = null; |
| 46 | const lifetime = new AbortController(); |
| 47 | function discardAddress() { |
| 48 | awaitingResizeFrame = false; |
| 49 | pendingAddress?.resolve(false); |
| 50 | pendingAddress = null; |
| 51 | } |
| 52 | const closeRemote = () => { |
| 53 | if (mayExist) void request(base + "/close", {body: {}, keepalive: true}).catch(() => {}); |
| 54 | }; |
| 55 | const publish = (state) => { if (alive && visible) update(homeNotice && state.frame ? {...state, homeNotice} : state); }; |
| 56 | const cancelRead = () => { clearTimeout(timer); read?.abort(); read = null; }; |
| 57 | function failure(error, operation) { |
| 58 | discardAddress(); cancelScroll(); |
| 59 | frame = null; |
| 60 | paused = true; |
| 61 | if (!desktop && operation === "frame" && error.status === 503) opened = mayExist = false; |
| 62 | const reopen = !opened || [401, 404, 410, 423].includes(error.status) || (error.status === 403 && operation !== "action"); |
| 63 | const message = error.status === 404 && !opened ? "这台电脑尚不支持" + toolName + ",请更新电脑端 Cage。" : |
| 64 | error.message; |
| 65 | publish({error: message, uncertain: operation === "action" && !error.status, reopen}); |
| 66 | } |
| 67 | const sameSurface = (first, second) => first && second && first.document === second.document && |
| 68 | first.width === second.width && first.height === second.height && |
| 69 | first.content_width === second.content_width && first.content_height === second.content_height; |
| 70 | function finishFrame(changed, fromAction = false) { |
| 71 | awaitingResizeFrame = false; |
| 72 | if (pendingAddress) { |
| 73 | const {url, resolve} = pendingAddress; |
| 74 | pendingAddress = null; |
| 75 | void send({type:"navigate", url}, frame).then(resolve); |
| 76 | return; |
| 77 | } |
| 78 | if (changed || fromAction) publish({frame, busy:false}); |
| 79 | const size = displaySize(); |
| 80 | if (needsResize(size)) { |
| 81 | cancelScroll(); |
| 82 | timer = setTimeout(resize, 0); |
| 83 | return; |
| 84 | } |
| 85 | if (queuedScroll && !sameSurface(queuedScroll.expected, frame)) cancelScroll(); |
| 86 | if (queuedScroll) { flushScroll(); return; } |
| 87 | quietReads = changed || fromAction ? 0 : Math.min(5, quietReads + 1); |
| 88 | |
| 89 | |
| 90 | const delay = desktop ? 450 : [90, 180, 380, 800, 1500, 2500][quietReads]; |
| 91 | timer = setTimeout(readFrame, delay); |
| 92 | } |
| 93 | async function decodeFrame(next, valid) { |
| 94 | if (next?.id !== id || typeof next.image !== "string" || !next.image || |
| 95 | typeof next.document !== "string" || !Number.isInteger(next.width) || next.width <= 0 || |
| 96 | !Number.isInteger(next.height) || next.height <= 0) throw new Error("主机返回的画面无效。"); |
| 97 | if ((next.content_width !== undefined || next.content_height !== undefined) && |
| 98 | (!Number.isFinite(next.content_width) || next.content_width <= 0 || |
| 99 | !Number.isFinite(next.content_height) || next.content_height <= 0)) throw new Error("主机返回的画面尺寸无效。"); |
| 100 | const src = "data:image/jpeg;base64," + next.image; |
| 101 | const changed = frame?.image !== src || !sameSurface(frame, next) || frame.focus !== next.focus || |
| 102 | frame.url !== next.url || frame.title !== next.title || frame.password !== next.password || frame.window !== next.window || frame.shared !== next.shared || |
| 103 | frame.login_supported !== next.login_supported || frame.content_width !== next.content_width || frame.content_height !== next.content_height; |
| 104 | if (frame?.image !== src) { |
| 105 | const image = new Image(); |
| 106 | image.src = src; |
| 107 | await image.decode(); |
| 108 | } |
| 109 | if (!valid()) return null; |
| 110 | if (next.url && next.url !== "about:blank") homeNotice = ""; |
| 111 | if (!desktop && next.action_frame === true) actionFrame = true; |
| 112 | pixelRatioSupported = desktop && next.pixel_ratio_supported === true; |
| 113 | waitingSince = 0; |
| 114 | frame = {...next, image:src}; |
| 115 | return changed; |
| 116 | } |
| 117 | async function readFrame() { |
| 118 | if (!alive || !visible || !opened || paused || writing || read) return; |
| 119 | const controller = new AbortController(); |
| 120 | read = controller; |
| 121 | const valid = () => read === controller && !controller.signal.aborted && alive && visible && !paused; |
| 122 | const known = frame; |
| 123 | const tag = actionFrame && /^[a-f0-9]{32}$/.test(known?.frame_tag || "") ? known.frame_tag : ""; |
| 124 | try { |
| 125 | const next = await request(base + "/frame" + (tag ? "?after=" + tag : ""), {signal:controller.signal}); |
| 126 | if (!valid()) return; |
| 127 | let changed = false; |
| 128 | if (next?.unchanged === true) { |
| 129 | if (!tag || frame !== known || next.id !== id || next.frame_tag !== tag) throw new Error("远程画面的版本不匹配,请重新读取。"); |
| 130 | } else { |
| 131 | changed = await decodeFrame(next, valid); |
| 132 | if (changed === null) return; |
| 133 | } |
| 134 | read = null; |
| 135 | finishFrame(changed); |
| 136 | } catch (error) { |
| 137 | if (valid()) { |
| 138 | if (error.status === 425 && (!waitingSince || Date.now() - waitingSince < 90000)) { |
| 139 | waitingSince ||= Date.now(); |
| 140 | frame = null; |
| 141 | publish({waiting:true}); |
| 142 | timer = setTimeout(readFrame, 1000); |
| 143 | } else { |
| 144 | failure(error, "frame"); |
| 145 | } |
| 146 | } |
| 147 | } finally { |
| 148 | if (read === controller) read = null; |
| 149 | } |
| 150 | } |
| 151 | function canSend(expected, focus) { |
| 152 | return alive && visible && !writing && !paused && frame && expected && |
| 153 | sameSurface(frame, expected) && |
| 154 | (!focus || focus === frame.focus); |
| 155 | } |
| 156 | async function send(payload, expected, operation = "action") { |
| 157 | if (!canSend(expected, payload.focus)) return false; |
| 158 | if (["navigate","back","forward","reload"].includes(payload.type)) homeNotice = ""; |
| 159 | if (payload.type !== "scroll") cancelScroll(); |
| 160 | cancelRead(); |
| 161 | const current = generation; |
| 162 | const valid = () => alive && visible && !paused && current === generation; |
| 163 | writing = true; writeType = payload.type; |
| 164 | if (operation === "resize") awaitingResizeFrame = true; |
| 165 | publish({frame, busy:true}); |
| 166 | let feedback = false; |
| 167 | try { |
| 168 | const body = {...payload, document:expected.document}; |
| 169 | if (actionFrame) body.return_frame = true; |
| 170 | const result = await request(base + "/action", {body, signal:lifetime.signal}); |
| 171 | if (!valid()) return false; |
| 172 | if (actionFrame && result?.image) { |
| 173 | feedback = await decodeFrame(result, valid) !== null; |
| 174 | } else { |
| 175 | if (result?.id !== id) throw new Error("主机未确认这次操作,请重新读取画面。"); |
| 176 | frame = null; |
| 177 | } |
| 178 | return valid(); |
| 179 | } catch (error) { |
| 180 | if (valid()) failure(error, operation); |
| 181 | return false; |
| 182 | } finally { |
| 183 | writing = false; writeType = ""; |
| 184 | if (alive && visible && !paused) { |
| 185 | if (feedback && valid()) finishFrame(true, true); |
| 186 | else void readFrame(); |
| 187 | } |
| 188 | } |
| 189 | } |
| 190 | function flushScroll() { |
| 191 | clearTimeout(scrollTimer); scrollTimer = null; |
| 192 | if (!queuedScroll || writing || !frame || paused || !alive || !visible) return; |
| 193 | const next = queuedScroll; |
| 194 | if (!sameSurface(next.expected, frame)) { cancelScroll(); return; } |
| 195 | const dx = clamp(next.dx, -3200, 3200), dy = clamp(next.dy, -3200, 3200); |
| 196 | next.dx -= dx; next.dy -= dy; |
| 197 | if (!next.dx && !next.dy) queuedScroll = null; |
| 198 | void send({type:"scroll", x:next.x, y:next.y, dx, dy}, frame); |
| 199 | } |
| 200 | function scroll(expected, {x,y,dx,dy}) { |
| 201 | if (desktop || !alive || !visible || paused || !opened || (!dx && !dy) || |
| 202 | (writing && writeType !== "scroll") || (frame && !sameSurface(expected, frame))) return; |
| 203 | if (!queuedScroll || queuedScroll.x !== x || queuedScroll.y !== y || !sameSurface(queuedScroll.expected, expected)) { |
| 204 | queuedScroll = {expected, x, y, dx:0, dy:0}; |
| 205 | } |
| 206 | queuedScroll.dx += dx; queuedScroll.dy += dy; |
| 207 | if (!queuedScroll.dx && !queuedScroll.dy) { cancelScroll(); return; } |
| 208 | |
| 209 | |
| 210 | if (!scrollTimer) scrollTimer = setTimeout(() => {scrollTimer = null; flushScroll();}, 16); |
| 211 | } |
| 212 | function resize() { |
| 213 | if (!frame || !alive || !visible || writing || paused) return; |
| 214 | const size = displaySize(); |
| 215 | if (needsResize(size)) { |
| 216 | void send({type: "resize", ...size}, frame, "resize"); |
| 217 | } |
| 218 | } |
| 219 | async function open() { |
| 220 | try { |
| 221 | const body = {id, ...viewportSize(stage)}; |
| 222 | if (tool === "browser" && initialURL) body.url = initialURL; |
| 223 | if (tool === "claude") body.url = "https://claude.ai/"; |
| 224 | const result = await request("/open", {body}); |
| 225 | if (result?.id !== id) throw new Error("主机未确认这次画面连接。"); |
| 226 | if (tool === "browser" && typeof result.home_notice === "string") homeNotice = result.home_notice; |
| 227 | actionFrame = !desktop && result.action_frame === true; |
| 228 | opened = true; mayExist = true; |
| 229 | void readFrame(); |
| 230 | } catch (error) { |
| 231 | mayExist = !error.status || error.status >= 500; |
| 232 | if (alive) failure(error, "open"); |
| 233 | } finally { |
| 234 | opening = false; |
| 235 | if (!alive) void closeRemote(); |
| 236 | } |
| 237 | } |
| 238 | const observer = new ResizeObserver(() => { |
| 239 | |
| 240 | clearTimeout(resizeTimer); |
| 241 | resizeTimer = setTimeout(resize, 160); |
| 242 | }); |
| 243 | let resizeTimer; |
| 244 | observer.observe(stage); |
| 245 | if (start) { |
| 246 | void open(); |
| 247 | } else { |
| 248 | |
| 249 | |
| 250 | opened = true; opening = false; mayExist = true; |
| 251 | void readFrame(); |
| 252 | } |
| 253 | return { |
| 254 | send, canSend, scroll, cancelScroll, |
| 255 | async navigate(url) { |
| 256 | if (!alive || !visible || !opened || paused) throw new Error("请先恢复远程画面,再前往网址。"); |
| 257 | if (awaitingResizeFrame && !pendingAddress) { |
| 258 | return new Promise(resolve => {pendingAddress = {url, resolve};}); |
| 259 | } |
| 260 | if (writing || !frame || pendingAddress) throw new Error("上一项操作尚未完成,请稍后再次前往。"); |
| 261 | return send({type: "navigate", url}, frame); |
| 262 | }, |
| 263 | offline() { |
| 264 | if (!alive) return; |
| 265 | generation++; cancelRead(); clearTimeout(resizeTimer); |
| 266 | failure(new Error("网络已断开,恢复后请重新读取画面。"), writing && writeType !== "resize" ? "action" : "frame"); |
| 267 | }, |
| 268 | refresh() { |
| 269 | if (!opened || !alive || !visible) return; |
| 270 | paused = false; waitingSince = 0; |
| 271 | publish({}); |
| 272 | void readFrame(); |
| 273 | }, |
| 274 | visibility(active) { |
| 275 | if (active === visible) return; |
| 276 | visible = active; |
| 277 | if (!visible) { |
| 278 | generation++; cancelScroll(); discardAddress(); |
| 279 | cancelRead(); clearTimeout(resizeTimer); frame = null; |
| 280 | if (alive) update({}); |
| 281 | } else if (alive) { |
| 282 | if (!opened && !opening) publish({error: "远程画面未连接。", reopen: true}); |
| 283 | else if (paused) publish({error: "请重新读取远程画面。", reopen: !opened}); |
| 284 | else void readFrame(); |
| 285 | } |
| 286 | }, |
| 287 | close() { |
| 288 | if (!alive) return; |
| 289 | alive = false; generation++; cancelScroll(); |
| 290 | discardAddress(); |
| 291 | cancelRead(); clearTimeout(resizeTimer); observer.disconnect(); |
| 292 | frame = null; |
| 293 | lifetime.abort(); |
| 294 | |
| 295 | |
| 296 | if (!opening) void closeRemote(); |
| 297 | }, |
| 298 | }; |
| 299 | } |