-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPIServer.swift
More file actions
407 lines (339 loc) · 13.1 KB
/
APIServer.swift
File metadata and controls
407 lines (339 loc) · 13.1 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import Foundation
import Network
// MARK: - API Response Types
struct WindowResponse: Codable {
let id: String
let pid: Int32
let axIndex: Int
let title: String
let claudeState: String
let displayName: String
let workstreamName: String?
let hasClaudeProcess: Bool
}
struct WindowsResponse: Codable {
let windows: [WindowResponse]
}
struct HealthResponse: Codable {
let status: String
let version: String
}
struct LaunchResponse: Codable {
let theme: String
let windowName: String
}
struct ErrorResponse: Codable {
let error: String
}
struct WorkstreamResponse: Codable {
let id: String
let name: String
let theme: String
let directory: String?
let hasCommand: Bool
}
struct WorkstreamsResponse: Codable {
let workstreams: [WorkstreamResponse]
}
struct WorkstreamLaunchResponse: Codable {
let name: String
let theme: String
}
// MARK: - API Server
class APIServer {
static let shared = APIServer()
private var listener: NWListener?
private var port: UInt16 = 0
private let portFilePath = NSHomeDirectory() + "/.ghostty-api-port"
private let basePort: UInt16 = 49876
private let maxPortAttempts = 10
// Reference to get window data - set by the app
var windowDataProvider: (() -> [GhosttyWindow])?
var focusWindowHandler: ((Int, pid_t) -> Void)?
var launchRandomHandler: (() -> (theme: String, windowName: String)?)?
var workstreamsProvider: (() -> [WorkstreamResponse])?
var launchWorkstreamHandler: ((String) -> (name: String, theme: String)?)?
var openQuickLaunchHandler: (() -> Void)?
private init() {}
func start() {
// Try ports starting from basePort
for offset in 0..<maxPortAttempts {
let tryPort = basePort + UInt16(offset)
if startListener(on: tryPort) {
port = tryPort
writePortFile()
print("API Server started on port \(port)")
return
}
}
print("Failed to start API server - no available ports")
}
func stop() {
listener?.cancel()
listener = nil
removePortFile()
print("API Server stopped")
}
private func startListener(on port: UInt16) -> Bool {
do {
let parameters = NWParameters.tcp
parameters.allowLocalEndpointReuse = true
parameters.requiredLocalEndpoint = NWEndpoint.hostPort(host: .ipv4(.loopback), port: NWEndpoint.Port(rawValue: port)!)
listener = try NWListener(using: parameters)
listener?.stateUpdateHandler = { [weak self] state in
switch state {
case .ready:
print("API Server listening on port \(port)")
case .failed(let error):
print("API Server failed: \(error)")
self?.listener = nil
case .cancelled:
print("API Server cancelled")
default:
break
}
}
listener?.newConnectionHandler = { [weak self] connection in
self?.handleConnection(connection)
}
listener?.start(queue: .main)
// Give it a moment to fail if port is in use
RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.1))
return listener?.state == .ready
} catch {
print("Failed to create listener on port \(port): \(error)")
return false
}
}
private func writePortFile() {
do {
try String(port).write(toFile: portFilePath, atomically: true, encoding: .utf8)
print("Wrote port file: \(portFilePath)")
} catch {
print("Failed to write port file: \(error)")
}
}
private func removePortFile() {
try? FileManager.default.removeItem(atPath: portFilePath)
}
private func handleConnection(_ connection: NWConnection) {
connection.stateUpdateHandler = { state in
switch state {
case .ready:
self.receiveRequest(connection)
case .failed(let error):
print("Connection failed: \(error)")
connection.cancel()
default:
break
}
}
connection.start(queue: .main)
}
private func receiveRequest(_ connection: NWConnection) {
connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] data, _, isComplete, error in
guard let self = self else { return }
if let data = data, !data.isEmpty {
if let request = String(data: data, encoding: .utf8) {
self.handleHTTPRequest(request, connection: connection)
}
}
if isComplete || error != nil {
connection.cancel()
}
}
}
private func handleHTTPRequest(_ request: String, connection: NWConnection) {
let lines = request.components(separatedBy: "\r\n")
guard let requestLine = lines.first else {
sendResponse(connection, status: 400, body: ErrorResponse(error: "Invalid request"))
return
}
let parts = requestLine.components(separatedBy: " ")
guard parts.count >= 2 else {
sendResponse(connection, status: 400, body: ErrorResponse(error: "Invalid request line"))
return
}
let method = parts[0]
let path = parts[1]
// Route the request
switch (method, path) {
case ("GET", "/api/health"):
handleHealth(connection)
case ("GET", "/api/windows"):
handleGetWindows(connection)
case ("POST", "/api/launch-random"):
handleLaunchRandom(connection)
case ("GET", "/api/workstreams"):
handleGetWorkstreams(connection)
case ("POST", "/api/quick-launch"):
handleOpenQuickLaunch(connection)
case ("POST", _) where path.hasPrefix("/api/workstreams/") && path.hasSuffix("/launch"):
let workstreamId = extractWorkstreamId(from: path)
handleLaunchWorkstream(connection, workstreamId: workstreamId)
case ("POST", _) where path.hasPrefix("/api/windows/") && path.hasSuffix("/focus"):
let windowId = extractWindowId(from: path)
handleFocusWindow(connection, windowId: windowId)
case ("OPTIONS", _):
// Handle CORS preflight
sendCORSResponse(connection)
default:
sendResponse(connection, status: 404, body: ErrorResponse(error: "Not found"))
}
}
private func extractWindowId(from path: String) -> String {
// /api/windows/{id}/focus -> extract {id}
let components = path.components(separatedBy: "/")
if components.count >= 4 {
return components[3]
}
return ""
}
private func extractWorkstreamId(from path: String) -> String {
// /api/workstreams/{id}/launch -> extract {id}
let components = path.components(separatedBy: "/")
if components.count >= 4 {
return components[3]
}
return ""
}
private func handleHealth(_ connection: NWConnection) {
let response = HealthResponse(status: "ok", version: "1.0.0")
sendResponse(connection, status: 200, body: response)
}
private func handleGetWindows(_ connection: NWConnection) {
guard let provider = windowDataProvider else {
sendResponse(connection, status: 503, body: ErrorResponse(error: "Window data not available"))
return
}
let windows = provider()
let windowResponses = windows.map { window -> WindowResponse in
WindowResponse(
id: "\(window.pid)-\(window.axIndex)",
pid: window.pid,
axIndex: window.axIndex,
title: window.name,
claudeState: claudeStateString(window.claudeState),
displayName: window.displayName,
workstreamName: window.workstreamName,
hasClaudeProcess: window.hasClaudeProcess
)
}
let response = WindowsResponse(windows: windowResponses)
sendResponse(connection, status: 200, body: response)
}
private func claudeStateString(_ state: ClaudeState) -> String {
switch state {
case .asking: return "asking"
case .waiting: return "waiting"
case .working: return "working"
case .running: return "running"
case .notRunning: return "notRunning"
}
}
private func handleFocusWindow(_ connection: NWConnection, windowId: String) {
// Parse window ID (format: "pid-axIndex")
let parts = windowId.components(separatedBy: "-")
guard parts.count == 2,
let pid = pid_t(parts[0]),
let axIndex = Int(parts[1]) else {
sendResponse(connection, status: 400, body: ErrorResponse(error: "Invalid window ID"))
return
}
if let handler = focusWindowHandler {
handler(axIndex, pid)
sendResponse(connection, status: 200, body: ["success": true])
} else {
sendResponse(connection, status: 503, body: ErrorResponse(error: "Focus handler not available"))
}
}
private func handleLaunchRandom(_ connection: NWConnection) {
guard let handler = launchRandomHandler else {
sendResponse(connection, status: 503, body: ErrorResponse(error: "Launch handler not available"))
return
}
guard let result = handler() else {
sendResponse(connection, status: 500, body: ErrorResponse(error: "No themes available"))
return
}
let response = LaunchResponse(theme: result.theme, windowName: result.windowName)
sendResponse(connection, status: 200, body: response)
}
private func handleGetWorkstreams(_ connection: NWConnection) {
guard let provider = workstreamsProvider else {
sendResponse(connection, status: 503, body: ErrorResponse(error: "Workstreams not available"))
return
}
let workstreams = provider()
let response = WorkstreamsResponse(workstreams: workstreams)
sendResponse(connection, status: 200, body: response)
}
private func handleLaunchWorkstream(_ connection: NWConnection, workstreamId: String) {
guard let handler = launchWorkstreamHandler else {
sendResponse(connection, status: 503, body: ErrorResponse(error: "Workstream launch handler not available"))
return
}
guard let result = handler(workstreamId) else {
sendResponse(connection, status: 404, body: ErrorResponse(error: "Workstream not found"))
return
}
let response = WorkstreamLaunchResponse(name: result.name, theme: result.theme)
sendResponse(connection, status: 200, body: response)
}
private func handleOpenQuickLaunch(_ connection: NWConnection) {
guard let handler = openQuickLaunchHandler else {
sendResponse(connection, status: 503, body: ErrorResponse(error: "Quick launch handler not available"))
return
}
handler()
sendResponse(connection, status: 200, body: ["success": true])
}
private func sendResponse<T: Encodable>(_ connection: NWConnection, status: Int, body: T) {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
guard let jsonData = try? encoder.encode(body),
let jsonString = String(data: jsonData, encoding: .utf8) else {
connection.cancel()
return
}
let statusText = httpStatusText(status)
let response = """
HTTP/1.1 \(status) \(statusText)\r
Content-Type: application/json\r
Content-Length: \(jsonData.count)\r
Access-Control-Allow-Origin: *\r
Access-Control-Allow-Methods: GET, POST, OPTIONS\r
Access-Control-Allow-Headers: Content-Type\r
Connection: close\r
\r
\(jsonString)
"""
connection.send(content: response.data(using: .utf8), completion: .contentProcessed { _ in
connection.cancel()
})
}
private func sendCORSResponse(_ connection: NWConnection) {
let response = """
HTTP/1.1 204 No Content\r
Access-Control-Allow-Origin: *\r
Access-Control-Allow-Methods: GET, POST, OPTIONS\r
Access-Control-Allow-Headers: Content-Type\r
Connection: close\r
\r
"""
connection.send(content: response.data(using: .utf8), completion: .contentProcessed { _ in
connection.cancel()
})
}
private func httpStatusText(_ status: Int) -> String {
switch status {
case 200: return "OK"
case 204: return "No Content"
case 400: return "Bad Request"
case 404: return "Not Found"
case 500: return "Internal Server Error"
case 503: return "Service Unavailable"
default: return "Unknown"
}
}
}