-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathamux-desktop.swift
More file actions
285 lines (260 loc) · 10.9 KB
/
amux-desktop.swift
File metadata and controls
285 lines (260 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import Cocoa
import WebKit
// ── Persistent config ──
let configURL: URL = {
let dir = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent(".amux")
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
return dir.appendingPathComponent("desktop-config.json")
}()
struct Connection: Codable {
var name: String
var url: String
}
struct Config: Codable {
var connections: [Connection]
var lastUrl: String
}
func loadConfig() -> Config {
guard let data = try? Data(contentsOf: configURL),
let config = try? JSONDecoder().decode(Config.self, from: data) else {
return Config(connections: [
Connection(name: "localhost", url: "https://localhost:8822")
], lastUrl: "https://localhost:8822")
}
return config
}
func saveConfig(_ config: Config) {
if let data = try? JSONEncoder().encode(config) {
try? data.write(to: configURL)
}
}
// ── Connect page HTML ──
func connectPageHTML(_ config: Config) -> String {
let connsJson = (try? JSONEncoder().encode(config.connections))
.flatMap { String(data: $0, encoding: .utf8) } ?? "[]"
return """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", sans-serif;
background: #0d1117; color: #e6edf3;
display: flex; align-items: center; justify-content: center;
min-height: 100vh;
}
.container { width: 380px; }
h1 { font-size: 1.6rem; font-weight: 700; margin-bottom: 6px; letter-spacing: -0.02em; }
.subtitle { color: #8b949e; font-size: 0.85rem; margin-bottom: 28px; }
.input-row { display: flex; gap: 8px; margin-bottom: 20px; }
input[type="text"] {
flex: 1; padding: 10px 14px; border-radius: 8px;
border: 1px solid #30363d; background: #161b22; color: #e6edf3;
font-size: 0.9rem; outline: none; font-family: inherit;
}
input:focus { border-color: #58a6ff; }
input::placeholder { color: #484f58; }
.btn {
padding: 10px 20px; border-radius: 8px; border: none;
background: #238636; color: #fff; font-size: 0.85rem;
font-weight: 600; cursor: pointer; font-family: inherit;
}
.btn:hover { background: #2ea043; }
.divider { border-top: 1px solid #21262d; margin: 4px 0 16px; }
.label { font-size: 0.75rem; color: #8b949e; text-transform: uppercase;
letter-spacing: 0.05em; margin-bottom: 8px; }
.conn-item {
display: flex; align-items: center; gap: 10px; padding: 10px 12px;
background: #161b22; border: 1px solid #21262d; border-radius: 8px;
cursor: pointer; margin-bottom: 4px; transition: border-color 0.15s;
}
.conn-item:hover { border-color: #58a6ff; }
.conn-name { font-size: 0.88rem; font-weight: 600; }
.conn-url { font-size: 0.72rem; color: #8b949e; overflow: hidden;
text-overflow: ellipsis; white-space: nowrap; }
.conn-info { flex: 1; min-width: 0; }
.conn-remove {
background: none; border: none; color: #484f58; cursor: pointer;
font-size: 1rem; padding: 4px; opacity: 0; transition: opacity 0.15s;
}
.conn-item:hover .conn-remove { opacity: 1; }
.conn-remove:hover { color: #f85149; }
.conn-last { font-size: 0.65rem; color: #58a6ff; flex-shrink: 0; }
.empty { color: #484f58; font-size: 0.82rem; text-align: center; padding: 20px 0; }
</style>
</head>
<body>
<div class="container">
<h1>amux</h1>
<div class="subtitle">Connect to an amux server</div>
<div class="input-row">
<input type="text" id="url" placeholder="https://localhost:8822"
value="\(config.lastUrl)" autofocus
onkeydown="if(event.key==='Enter')doConnect()">
<button class="btn" onclick="doConnect()">Connect</button>
</div>
<div class="divider"></div>
<div class="label">Recent connections</div>
<div id="list"></div>
</div>
<script>
const conns = \(connsJson);
const lastUrl = "\(config.lastUrl)";
function render() {
const el = document.getElementById('list');
if (!conns.length) { el.innerHTML = '<div class="empty">No saved connections</div>'; return; }
el.innerHTML = conns.map((c, i) => {
const isLast = c.url.replace(/\\/+$/, '') === lastUrl.replace(/\\/+$/, '');
return '<div class="conn-item" onclick="go(\\'' + c.url + '\\')">' +
'<div class="conn-info"><div class="conn-name">' + esc(c.name) + '</div>' +
'<div class="conn-url">' + esc(c.url) + '</div></div>' +
(isLast ? '<span class="conn-last">last used</span>' : '') +
'<button class="conn-remove" onclick="event.stopPropagation();rm(' + i + ')" title="Remove">✕</button></div>';
}).join('');
}
function esc(s) { return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/'/g,'''); }
function doConnect() {
let url = document.getElementById('url').value.trim();
if (!url) url = 'https://localhost:8822';
if (!/^https?:\\/\\//.test(url)) url = 'https://' + url;
go(url);
}
function go(url) { window.location = 'amux-connect://' + btoa(url); }
function rm(i) {
conns.splice(i, 1);
window.location = 'amux-remove://' + i;
render();
}
render();
</script>
</body>
</html>
"""
}
// ── App delegate ──
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
var webView: WKWebView!
var config: Config!
func applicationDidFinishLaunching(_ notification: Notification) {
config = loadConfig()
let wkConfig = WKWebViewConfiguration()
wkConfig.preferences.setValue(true, forKey: "developerExtrasEnabled")
wkConfig.mediaTypesRequiringUserActionForPlayback = []
webView = WKWebView(frame: .zero, configuration: wkConfig)
webView.customUserAgent = "Amux-Desktop/1.0"
webView.navigationDelegate = self
let screen = NSScreen.main!.frame
let width: CGFloat = min(1440, screen.width * 0.85)
let height: CGFloat = min(900, screen.height * 0.85)
let x = (screen.width - width) / 2
let y = (screen.height - height) / 2
window = NSWindow(
contentRect: NSRect(x: x, y: y, width: width, height: height),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered,
defer: false
)
window.title = "Amux"
window.titlebarAppearsTransparent = true
window.titleVisibility = .hidden
window.backgroundColor = NSColor(red: 13/255, green: 17/255, blue: 23/255, alpha: 1)
window.minSize = NSSize(width: 800, height: 500)
window.contentView = webView
window.makeKeyAndOrderFront(nil)
showConnectPage()
}
func showConnectPage() {
config = loadConfig()
webView.loadHTMLString(connectPageHTML(config), baseURL: nil)
}
func connectToServer(_ urlString: String) {
var url = urlString
if !url.hasPrefix("http") { url = "https://" + url }
config.lastUrl = url
// Add to connections if new
if !config.connections.contains(where: { $0.url.replacingOccurrences(of: "/+$", with: "", options: .regularExpression) == url.replacingOccurrences(of: "/+$", with: "", options: .regularExpression) }) {
let name = URL(string: url)?.host ?? url
config.connections.append(Connection(name: name, url: url))
}
saveConfig(config)
loadWithRetry(url: url, attempts: 0)
}
func loadWithRetry(url: String, attempts: Int) {
guard let nsUrl = URL(string: url) else { return }
let request = URLRequest(url: nsUrl, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 3)
webView.load(request)
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
guard let self = self else { return }
if self.webView.isLoading { return }
if let host = self.webView.url?.host, host == (URL(string: url)?.host ?? "localhost") { return }
if attempts < 20 {
self.loadWithRetry(url: url, attempts: attempts + 1)
}
}
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
}
// ── Navigation delegate ──
extension AppDelegate: WKNavigationDelegate {
func webView(_ webView: WKWebView,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
// Trust localhost / private network self-signed certs
if let host = challenge.protectionSpace.host.components(separatedBy: ":").first,
(host == "localhost" || host == "127.0.0.1" || host.hasSuffix(".local")
|| host.hasPrefix("10.") || host.hasPrefix("192.168.")),
let trust = challenge.protectionSpace.serverTrust {
completionHandler(.useCredential, URLCredential(trust: trust))
} else {
completionHandler(.performDefaultHandling, nil)
}
}
func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else {
decisionHandler(.allow)
return
}
// Handle connect page actions via custom URL scheme
if url.scheme == "amux-connect" {
if let b64 = url.host, let data = Data(base64Encoded: b64),
let serverUrl = String(data: data, encoding: .utf8) {
connectToServer(serverUrl)
}
decisionHandler(.cancel)
return
}
if url.scheme == "amux-remove" {
if let idxStr = url.host, let idx = Int(idxStr), idx < config.connections.count {
config.connections.remove(at: idx)
saveConfig(config)
showConnectPage()
}
decisionHandler(.cancel)
return
}
// Open external links in default browser
if let host = url.host,
host != "localhost" && host != "127.0.0.1" && !host.hasSuffix(".local"),
navigationAction.navigationType == .linkActivated {
NSWorkspace.shared.open(url)
decisionHandler(.cancel)
return
}
decisionHandler(.allow)
}
}
// ── Launch ──
let app = NSApplication.shared
let delegate = AppDelegate()
app.delegate = delegate
app.setActivationPolicy(.regular)
app.activate(ignoringOtherApps: true)
app.run()