| 1 | |
| 2 | #if targetEnvironment(simulator) |
| 3 | import SwiftUI |
| 4 | import WebKit |
| 5 | |
| 6 | enum SimulatorWorkspacePreview { |
| 7 | final class Preview: NSObject, WKURLSchemeHandler, WKNavigationDelegate { |
| 8 | func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) { |
| 9 | guard let url = urlSchemeTask.request.url, |
| 10 | let root = Bundle.main.url(forResource: "mobile-ui", withExtension: nil) else {return} |
| 11 | let file = root.appendingPathComponent(url.path == "/" ? "mobile.html" : String(url.path.dropFirst())).standardizedFileURL |
| 12 | guard file.path.hasPrefix(root.path + "/"), let data = try? Data(contentsOf: file) else { |
| 13 | urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist)); return |
| 14 | } |
| 15 | let types = ["html": "text/html", "js": "text/javascript", "css": "text/css", "png": "image/png"] |
| 16 | urlSchemeTask.didReceive(URLResponse(url: url, mimeType: types[file.pathExtension] ?? "application/octet-stream", |
| 17 | expectedContentLength: data.count, textEncodingName: "utf-8")) |
| 18 | urlSchemeTask.didReceive(data); urlSchemeTask.didFinish() |
| 19 | } |
| 20 | func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {} |
| 21 | func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, |
| 22 | decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { |
| 23 | decisionHandler(action.request.url?.scheme == "cage-preview" ? .allow : .cancel) |
| 24 | } |
| 25 | } |
| 26 | static func makeWebView(model: ConnectionModel, id: String) -> (web: WKWebView, delegate: Preview) { |
| 27 | let delegate = Preview() |
| 28 | let origin = URL(string: "cage-preview://app/")! |
| 29 | let config = WKWebViewConfiguration() |
| 30 | config.websiteDataStore = .nonPersistent() |
| 31 | config.applicationNameForUserAgent = "CageMobile/1" |
| 32 | config.setURLSchemeHandler(delegate, forURLScheme: "cage-preview") |
| 33 | config.userContentController.add(DeviceWebBridge(model: model, id: id, origin: origin), name: "cageDevices") |
| 34 | config.userContentController.addUserScript(WKUserScript(source: fixture, injectionTime: .atDocumentStart, forMainFrameOnly: true)) |
| 35 | let view = WKWebView(frame: .zero, configuration: config) |
| 36 | view.scrollView.contentInsetAdjustmentBehavior = .never |
| 37 | view.navigationDelegate = delegate |
| 38 | view.load(URLRequest(url: origin)) |
| 39 | return (view, delegate) |
| 40 | } |
| 41 | |
| 42 | static let fixture = #""" |
| 43 | (() => { |
| 44 | const projects = [{name: "Cage", path: "/示例项目/cage"}, {name: "个人网站", path: "/示例项目/website"}]; |
| 45 | let sequence = 0; |
| 46 | const uuid = () => "preview-" + (++sequence); |
| 47 | if (!crypto.randomUUID) crypto.randomUUID = uuid; |
| 48 | const snapshot = (id, workspace, title, turns = []) => ({id, workspace, title, turns, |
| 49 | revision: 1, generation: "simulator-preview", updated_at: new Date().toISOString()}); |
| 50 | const sessions = [ |
| 51 | snapshot("preview-ui", projects[0].path, "检查移动端界面", [{id: "turn-ui", prompt: "帮我检查移动端的布局和侧栏。", |
| 52 | text: "这里是示例会话,可以查看消息排版、输入框和项目切换。\n\n你也可以新建会话,输入一条消息查看交互效果。", status: "completed"}]), |
| 53 | snapshot("preview-approval", projects[0].path, "工具审批示例", [{id: "turn-approval", prompt: "查看项目目录。", text: "需要确认以下工具调用。", |
| 54 | status: "running", approval: {id: "approval-demo", tool: "Bash", input: {command: "ls -la", description: "查看示例项目文件"}}}]), |
| 55 | snapshot("preview-website", projects[1].path, "调整首页排版", [{id: "turn-website", prompt: "看看首页标题的间距。", |
| 56 | text: "这是第二个项目的示例会话。", status: "completed"}]) |
| 57 | ]; |
| 58 | window.fetch = async (input, options = {}) => { |
| 59 | const url = new URL(typeof input === "string" ? input : input.url, location.href); |
| 60 | const path = url.pathname.replace("/api/mobile/cli", ""); |
| 61 | const body = options.body ? JSON.parse(options.body) : null; |
| 62 | let value; |
| 63 | if (path === "/projects") value = {host: window.__cageDevices?.devices.find(d => d.id === window.__cageDevices.current)?.name || "模拟器预览", ready: true, projects}; |
| 64 | else if (path === "/sessions" && !body) value = {sessions}; |
| 65 | else if (path === "/sessions") { |
| 66 | value = snapshot(uuid(), body.workspace, "新会话"); sessions.unshift(value); |
| 67 | } else { |
| 68 | const [, , id, action] = path.split("/"); |
| 69 | value = sessions.find(s => s.id === id); |
| 70 | if (!value) return new Response("示例会话不存在", {status: 404, headers: {"Content-Type": "text/plain"}}); |
| 71 | if (action === "metadata") { |
| 72 | if (body.title !== undefined) value.title = value.custom_title = body.title; |
| 73 | if (body.pinned !== undefined) value.pinned = body.pinned; |
| 74 | value.metadata_set = true; |
| 75 | } else if (action === "delete") { |
| 76 | sessions.splice(sessions.indexOf(value), 1); |
| 77 | return new Response(JSON.stringify({ok: true}), {headers: {"Content-Type": "application/json"}}); |
| 78 | } else if (action === "messages") { |
| 79 | if (!value.custom_title) value.title = body.text.slice(0, 30); |
| 80 | value.turns.push({id: body.request_id, prompt: body.text, status: "completed", |
| 81 | text: "已收到示例消息。这是模拟器界面预览,没有连接电脑,也没有调用模型。"}); |
| 82 | } else if (action === "approval") { |
| 83 | const turn = value.turns.at(-1); |
| 84 | turn.status = "completed"; delete turn.approval; |
| 85 | turn.text = body.allow ? "示例审批已允许。实际命令不会执行。" : "示例审批已拒绝。"; |
| 86 | } else if (action === "stop") value.turns.at(-1).status = "stopped"; |
| 87 | if (body) {value.revision++; value.updated_at = new Date().toISOString();} |
| 88 | } |
| 89 | return new Response(JSON.stringify(value), {headers: {"Content-Type": "application/json"}}); |
| 90 | }; |
| 91 | })(); |
| 92 | """# |
| 93 | } |
| 94 | #endif |