Skip to content

Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.

feat: add optional Discord activity and Rich Presence passthrough

Matias G.4be34d7fe06e
diff --git a/Scripts/make-app.sh b/Scripts/make-app.sh
index f152fde..0c62eb9 100755
--- a/Scripts/make-app.sh
+++ b/Scripts/make-app.sh
@@ -119,10 +119,12 @@ cp spike/tools/cabextract.LICENSE "$APP/Contents/Resources/tools/cabextract.LICE
if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
spike/epic-stub/build.sh >/dev/null
cp spike/epic-stub/EpicGamesLauncher.exe "$APP/Contents/Resources/EpicGamesLauncher.exe"
+ spike/discord-bridge/build.sh
+ cp spike/discord-bridge/highball-discord-bridge.exe "$APP/Contents/Resources/highball-discord-bridge.exe"
elif [ "$CONFIG" = release ]; then
echo "error: release build needs mingw-w64 (brew install mingw-w64) to build spike/epic-stub" >&2; exit 1
else
- echo "note: no mingw-w64, the Epic launcher stand-in is not bundled (debug build)"
+ echo "note: no mingw-w64, the Epic stand-in and Discord pipe bridge are not bundled (debug build)"
fi
RECIPES="../highball-db/recipes"
if [ ! -d "$RECIPES" ]; then
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index fe64236..8ef58a9 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -809,6 +809,7 @@ final class AppState {
installWatcher?.watch(bottles.flatMap(installDirectories) + MacSteam.steamappsDirectories())
macSteamGames = MacSteam.installedGames()
startSteamClientWatch()
+ startDiscordWatch()
libraryPlays = libraryStore.load()
libraryOverrides = libraryStore.rendererOverrides()
rebuildLibrary()
@@ -1625,6 +1626,90 @@ final class AppState {
var steamClients: Set<String> = []
@ObservationIgnored private var steamClientWatch: Task<Void, Never>?
+ @ObservationIgnored private var discordWatch: Task<Void, Never>?
+ @ObservationIgnored private var discordWatchID: UUID?
+ @ObservationIgnored private var discordStopping: Task<Void, Never>?
+ @ObservationIgnored private var discordEnvironments: [UUID: [String: String]] = [:]
+
+ var discordSharingEnabled = UserDefaults.standard.bool(forKey: DiscordPresence.enabledDefaultsKey) {
+ didSet {
+ UserDefaults.standard.set(discordSharingEnabled, forKey: DiscordPresence.enabledDefaultsKey)
+ DiscordPresence.shared.setEnabled(discordSharingEnabled)
+ if discordSharingEnabled { startDiscordWatch() }
+ else { stopDiscordWatch(); discordEnvironments.removeAll() }
+ }
+ }
+
+ private var discordIsOpen: Bool {
+ NSWorkspace.shared.runningApplications.contains {
+ ["com.hnc.Discord", "com.hnc.DiscordPTB", "com.hnc.DiscordCanary"].contains($0.bundleIdentifier ?? "")
+ }
+ }
+
+ private func stopDiscordWatch() {
+ guard let watch = discordWatch else { return }
+ watch.cancel()
+ discordWatch = nil
+ discordWatchID = nil
+ discordStopping = Task.detached(priority: .utility) {
+ // Close helpers now, even if the cancelled worker is awaiting a catalog response.
+ DiscordPresence.shared.stop()
+ await watch.value
+ }
+ }
+
+ /// Only the session watcher asks for a game's environment, reusing its process list.
+ private func discordEnvironmentPrefix(for session: GameSession) -> URL? {
+ guard discordSharingEnabled, discordIsOpen, runningSessions.contains(session),
+ discordEnvironments[session.id] == nil else { return nil }
+ return bottles.first { $0.name == session.bottleName }?.url
+ }
+
+ private func rememberDiscordEnvironment(_ environment: [String: String], for session: GameSession) {
+ guard discordSharingEnabled, discordIsOpen, runningSessions.contains(session) else { return }
+ discordEnvironments[session.id] = environment
+ startDiscordWatch()
+ }
+
+ private func startDiscordWatch() {
+ guard discordSharingEnabled, !runningSessions.isEmpty, discordWatch == nil, discordIsOpen else { return }
+ DiscordPresence.shared.setEnabled(true)
+ let stopping = discordStopping
+ let id = UUID()
+ discordWatchID = id
+ discordWatch = Task.detached(priority: .utility) { [weak self] in
+ // Complete the previous shutdown before creating another helper after a quick toggle.
+ await stopping?.value
+ let presence = DiscordPresence.shared
+ while !Task.isCancelled {
+ guard let self else { break }
+ let (sessions, bottles, engines, environments, paths, discordOpen) = await MainActor.run { [self] in
+ (self.runningSessions, self.bottles, self.engines, self.discordEnvironments, self.paths, self.discordIsOpen)
+ }
+ guard !Task.isCancelled, discordOpen, !sessions.isEmpty else { break }
+ let activeBottles = bottles.filter { bottle in sessions.contains { $0.bottleName == bottle.name } }
+ presence.retainBridges(for: activeBottles.map(\.url))
+ for bottle in activeBottles {
+ guard !Task.isCancelled,
+ let session = sessions.first(where: { $0.bottleName == bottle.name && environments[$0.id] != nil }),
+ let env = environments[session.id],
+ let engine = engines.first(where: { $0.id == bottle.settings.engineID }) else { continue }
+ presence.ensureBridge(engine: engine, bottle: bottle, environment: env)
+ }
+ await presence.update(games: DiscordSessions.games(sessions), paths: paths)
+ do { try await Task.sleep(for: .seconds(5)) } catch { break }
+ }
+ presence.stop()
+ await self?.discordWatchFinished(id)
+ }
+ }
+
+ private func discordWatchFinished(_ id: UUID) {
+ guard discordWatchID == id else { return }
+ discordWatch = nil
+ discordWatchID = nil
+ }
+
private func startSteamClientWatch() {
guard steamClientWatch == nil else { return }
steamClientWatch = Task.detached(priority: .utility) { [weak self] in
@@ -1746,28 +1831,44 @@ final class AppState {
func session(forAppID appid: Int) -> GameSession? { runningSessions.first { $0.appid == appid } }
- private func beginSession(_ session: GameSession) {
+ private func beginSession(_ session: GameSession, processList: String) {
runningSessions.append(session)
appendLog("\(session.title) is running")
if !FunnelLog.records(in: paths.logs).contains(where: { $0.event == .firstGameProcess }) { funnel(.firstGameProcess) }
sessionWatchers[session.id] = Task.detached { [weak self] in
+ if let prefix = await self?.discordEnvironmentPrefix(for: session),
+ let env = DiscordSessions.environment(for: session, prefix: prefix, processList: processList) {
+ await self?.rememberDiscordEnvironment(env, for: session)
+ }
// A game that is gone for two consecutive checks has ended; one miss can be a
// process table read racing a restart (some games relaunch themselves once).
// Detached: the `ps` behind isAlive must never run on the main thread.
var misses = 0
while !Task.isCancelled {
try? await Task.sleep(for: .seconds(5))
- if SessionWatch.isAlive(markers: session.markers, ps: SessionWatch.currentProcessList()) { misses = 0; continue }
+ let processes = SessionWatch.currentProcessList()
+ if SessionWatch.isAlive(markers: session.markers, ps: processes) {
+ misses = 0
+ if let prefix = await self?.discordEnvironmentPrefix(for: session),
+ let env = DiscordSessions.environment(for: session, prefix: prefix, processList: processes) {
+ await self?.rememberDiscordEnvironment(env, for: session)
+ }
+ await self?.startDiscordWatch()
+ continue
+ }
misses += 1
if misses >= 2 { break }
}
await MainActor.run { self?.endSession(session, reason: "ended") }
}
+ startDiscordWatch()
}
private func endSession(_ session: GameSession, reason: String) {
guard runningSessions.contains(session) else { return }
runningSessions.removeAll { $0.id == session.id }
+ discordEnvironments[session.id] = nil
+ if runningSessions.isEmpty { stopDiscordWatch() }
sessionWatchers[session.id]?.cancel()
sessionWatchers[session.id] = nil
let record = SessionRecord(title: session.title, bottle: session.bottleName, appid: session.appid,
@@ -1886,7 +1987,9 @@ final class AppState {
guard FileManager.default.fileExists(atPath: cef.path) else { return false }
return await Task.detached { WineRunner.steamIsRunning(inPrefix: prefix) }.value
}
- return SessionWatch.isAlive(markers: markers, ps: await Self.processList())
+ let processes = await Self.processList()
+ box.processList = processes
+ return SessionWatch.isAlive(markers: markers, ps: processes)
} crashed: { result in
// A program whose file is not a Windows executable never ran: Wine's loader hands
// it to start.exe, which reports "File not found" within seconds. Another graphics
@@ -1906,7 +2009,7 @@ final class AppState {
steamClients.insert(bottle.name) // the poll would take up to 8 s to notice
} else {
beginSession(GameSession(title: pin.name, bottleName: bottle.name, appid: nil, markers: markers,
- renderer: (pin.renderer ?? bottle.settings.renderer).rawValue))
+ renderer: (pin.renderer ?? bottle.settings.renderer).rawValue), processList: box.processList)
}
}
}
@@ -2048,7 +2151,9 @@ final class AppState {
try await runner.start(steam, arguments: ["-silent", "-applaunch", String(game.appid)] + extraArgs, renderer: renderer, extraEnvironment: gameEnvironment, headerNote: note, onOutput: log)
}
let handedOff = try await awaitHandoff(box, program: game.name, timeout: 360, exitEndsWait: false) {
- SessionWatch.isAlive(markers: markers, ps: await Self.processList())
+ let processes = await Self.processList()
+ box.processList = processes
+ return SessionWatch.isAlive(markers: markers, ps: processes)
} crashed: { result in
let current = servedRenderer
self.crashSuggestion = CrashSuggestion(program: game.name, bottleName: bottle.name,
@@ -2058,7 +2163,7 @@ final class AppState {
}
guard handedOff else { return }
beginSession(GameSession(title: game.name, bottleName: bottle.name, appid: game.appid, markers: markers,
- renderer: servedRenderer.rawValue))
+ renderer: servedRenderer.rawValue), processList: box.processList)
}
}
@@ -2070,6 +2175,8 @@ final class AppState {
/// After the hand-off the process's output goes to its file log only, so a client
/// that lives for hours cannot rewrite a later operation's stage line.
var handedOff = false
+ /// The existing launch liveness check supplies this; Discord does not run another scan.
+ var processList = ""
}
private func watchedLaunch(_ box: LaunchOutcome, _ body: @escaping @Sendable () async throws -> LaunchResult) {
@@ -2302,7 +2409,9 @@ final class AppState {
}
let markers = SessionWatch.markers(executable: info.executable)
let handedOff = try await awaitHandoff(box, program: game.app_title, timeout: 360) {
- SessionWatch.isAlive(markers: markers, ps: await Self.processList())
+ let processes = await Self.processList()
+ box.processList = processes
+ return SessionWatch.isAlive(markers: markers, ps: processes)
} crashed: { result in
let current = renderer ?? bottle.settings.renderer
self.crashSuggestion = CrashSuggestion(program: game.app_title, bottleName: bottle.name,
@@ -2312,7 +2421,7 @@ final class AppState {
}
guard handedOff else { return }
beginSession(GameSession(title: game.app_title, bottleName: bottle.name, appid: nil, markers: markers,
- renderer: (renderer ?? bottle.settings.renderer).rawValue))
+ renderer: (renderer ?? bottle.settings.renderer).rawValue), processList: box.processList)
}
}
diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swift
index 483f912..ac172c7 100644
--- a/Sources/HighballApp/HighballApp.swift
+++ b/Sources/HighballApp/HighballApp.swift
@@ -137,6 +137,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}
}
+ func applicationWillTerminate(_ notification: Notification) {
+ DiscordPresence.shared.setEnabled(false)
+ DiscordPresence.shared.stop()
+ }
+
func applicationDidFinishLaunching(_ notification: Notification) {
// The UI is dark by design (preferredColorScheme), but AppKit chrome (scroll bars,
// alerts, menus, open panels) follows the window appearance, which stayed light on a
diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swift
index e549f61..eec46b6 100644
--- a/Sources/HighballApp/L10n.swift
+++ b/Sources/HighballApp/L10n.swift
@@ -9,6 +9,8 @@ func L(_ en: String) -> String {
enum L10n {
static let fr: [String: String] = [
+ "Share game activity with Discord": "Partager l’activité de jeu avec Discord",
+ "Let Discord show what you play and the game's Rich Presence while both apps are open. Off by default.": "Autoriser Discord à afficher vos jeux et leur Rich Presence lorsque les deux applications sont ouvertes. Désactivé par défaut.",
"Frame generation (Lossless Scaling, beta)": "Génération d’images (Lossless Scaling, bêta)",
"How frame generation works": "Comment fonctionne la génération d’images",
"Off": "Désactivé",
diff --git a/Sources/HighballApp/SettingsView.swift b/Sources/HighballApp/SettingsView.swift
index fdb014c..022d8af 100644
--- a/Sources/HighballApp/SettingsView.swift
+++ b/Sources/HighballApp/SettingsView.swift
@@ -226,6 +226,7 @@ struct EnginePane: View {
@State private var showLicense = false
var body: some View {
+ @Bindable var state = state
VStack(alignment: .leading, spacing: 14) {
Text(L("The engine is the Wine build and graphics layers Highball runs games with. Highball picks it; an update never moves an environment to a different Wine build on its own."))
.font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
@@ -255,6 +256,13 @@ struct EnginePane: View {
.font(.caption).foregroundStyle(.secondary)
}.frame(maxWidth: .infinity, alignment: .leading)
}
+ GroupBox {
+ VStack(alignment: .leading, spacing: 6) {
+ Toggle(L("Share game activity with Discord"), isOn: $state.discordSharingEnabled)
+ Text(L("Let Discord show what you play and the game's Rich Presence while both apps are open. Off by default."))
+ .font(.caption).foregroundStyle(.secondary)
+ }.frame(maxWidth: .infinity, alignment: .leading)
+ }
if let update = state.engineUpdate {
GroupBox {
HStack {
diff --git a/Sources/HighballKit/DiscordBridge.swift b/Sources/HighballKit/DiscordBridge.swift
new file mode 100644
index 0000000..a5774b2
--- /dev/null
+++ b/Sources/HighballKit/DiscordBridge.swift
@@ -0,0 +1,113 @@
+import Foundation
+import Darwin
+
+/// Authenticated loopback transport from the Windows helper to the native Discord Unix
+/// socket. Each pipe client owns one Discord connection; replies, pings and subscriptions
+/// travel back to the original game. There is no DLL injection or Discord account access.
+final class DiscordBridge: @unchecked Sendable {
+ let token = UUID().uuidString
+ let port: UInt16
+ private let listener: DiscordSocket
+ private let lock = NSLock()
+ private var stopped = false
+ private var clients: [UUID: DiscordSocket] = [:]
+ private var controls: [String: DiscordSocket] = [:]
+ private let socketPaths: @Sendable () -> [String]
+ private let activity: @Sendable (UUID, Bool) -> Void
+
+ init(socketPaths: @escaping @Sendable () -> [String] = { DiscordIPC.socketPaths() }, activity: @escaping @Sendable (UUID, Bool) -> Void) throws {
+ self.activity = activity
+ self.socketPaths = socketPaths
+ let socket = try DiscordSocket(domain: AF_INET)
+ listener = socket
+ var address = sockaddr_in()
+ address.sin_family = sa_family_t(AF_INET)
+ address.sin_addr.s_addr = inet_addr("127.0.0.1")
+ let bound = withUnsafePointer(to: &address) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(socket.fd, $0, socklen_t(MemoryLayout<sockaddr_in>.size)) }
+ }
+ guard bound == 0, listen(socket.fd, 32) == 0 else { throw HighballError.failed("Could not start Discord bridge") }
+ var size = socklen_t(MemoryLayout<sockaddr_in>.size)
+ guard withUnsafeMutablePointer(to: &address, {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(socket.fd, $0, &size) }
+ }) == 0 else { throw HighballError.failed("Could not read Discord bridge port") }
+ port = UInt16(bigEndian: address.sin_port)
+ DispatchQueue.global(qos: .utility).async { [self] in acceptClients() }
+ }
+
+ func isReady(prefix: String) -> Bool { lock.withLock { controls[prefix] != nil } }
+ func stopControl(prefix: String) { lock.withLock { controls[prefix]?.stop() } }
+ func stop() {
+ lock.withLock {
+ stopped = true
+ listener.stop()
+ for client in clients.values { client.stop() }
+ }
+ }
+ private func acceptClients() {
+ while !lock.withLock({ stopped }) {
+ var p = pollfd(fd: listener.fd, events: Int16(POLLIN), revents: 0)
+ guard poll(&p, 1, 1000) > 0 else { continue }
+ let fd = accept(listener.fd, nil, nil)
+ guard fd >= 0 else { continue }
+ let client = DiscordSocket(fd: fd), id = UUID()
+ let accepted = lock.withLock { () -> Bool in
+ guard !stopped, clients.count < 64 else { return false }
+ clients[id] = client
+ return true
+ }
+ guard accepted else { client.stop(); continue }
+ DispatchQueue.global(qos: .utility).async { [self] in serve(client, id: id) }
+ }
+ }
+ private func serve(_ client: DiscordSocket, id: UUID) {
+ defer {
+ activity(id, false)
+ client.stop()
+ _ = lock.withLock { clients.removeValue(forKey: id) }
+ }
+ do {
+ let auth = try client.read(37, timeout: 3)
+ guard String(decoding: auth.prefix(36), as: UTF8.self) == token else { return }
+ if auth.last == 255 {
+ // The helper keeps this connection open. Closing it ends only that helper,
+ // including every pipe thread, when Highball quits.
+ let lengthData = try client.read(2, timeout: 3)
+ let length = lengthData.withUnsafeBytes { Int($0.loadUnaligned(as: UInt16.self).littleEndian) }
+ guard length > 0, length <= 4096 else { return }
+ let prefix = String(decoding: try client.read(length, timeout: 3), as: UTF8.self)
+ lock.withLock { controls[prefix] = client }
+ defer {
+ lock.withLock {
+ if controls[prefix] === client { controls[prefix] = nil }
+ }
+ }
+ _ = try client.read(1)
+ return
+ }
+ guard let index = auth.last, index < 10 else { return }
+ // Prefer the same slot, then try the remaining clients (Stable/PTB/Canary).
+ let paths = socketPaths()
+ let ordered = paths.filter { $0.hasSuffix("discord-ipc-\(index)") } + paths.filter { !$0.hasSuffix("discord-ipc-\(index)") }
+ let discord = try DiscordIPC.connect(paths: ordered)
+ defer { discord.stop() }
+ DispatchQueue.global(qos: .utility).async { [self] in
+ defer { discord.stop(); client.stop() }
+ do {
+ while true {
+ let frame = try discord.readFrame()
+ if frame.json?["cmd"] as? String == "SET_ACTIVITY", frame.json?["evt"] as? String == "ERROR" {
+ activity(id, false)
+ }
+ try client.write(frame)
+ }
+ } catch { }
+ }
+ while true {
+ let frame = try client.readFrame()
+ if let active = frame.activity { activity(id, active) }
+ try discord.write(frame.hostPID(getpid()))
+ }
+ } catch { /* An SDK reconnects when either side closes. */ }
+ }
+}
diff --git a/Sources/HighballKit/DiscordGameCatalog.swift b/Sources/HighballKit/DiscordGameCatalog.swift
new file mode 100644
index 0000000..3386c1b
--- /dev/null
+++ b/Sources/HighballKit/DiscordGameCatalog.swift
@@ -0,0 +1,83 @@
+import Foundation
+
+/// Discord's public detection catalog supplies the *game's* application id. No personal
+/// Discord token or Highball application id is involved. The endpoint is undocumented;
+/// keep the last valid catalog for offline use and fail without affecting game launches.
+struct DiscordGameCatalog: Sendable {
+ struct Application: Decodable, Sendable {
+ struct SKU: Decodable, Sendable { let distributor: String; let id: String? }
+ struct Executable: Decodable, Sendable { let name: String; let os: String; let is_launcher: Bool? }
+ let id: String
+ let name: String
+ let aliases: [String]?
+ let executables: [Executable]?
+ let third_party_skus: [SKU]?
+ }
+ let applications: [Application]
+ init(data: Data) throws { applications = try JSONDecoder().decode([Application].self, from: data) }
+
+ func match(steamID: Int?, title: String, executable: String?) -> Application? {
+ // Store ids win over names (localised titles and user renames are common).
+ if let steamID {
+ let matches = applications.filter { $0.third_party_skus?.contains { $0.distributor == "steam" && $0.id == String(steamID) } == true }
+ if matches.count == 1 { return matches.first }
+ }
+ let byName = applications.filter { app in
+ ([app.name] + (app.aliases ?? [])).contains { $0.caseInsensitiveCompare(title) == .orderedSame }
+ }
+ if byName.count == 1 { return byName.first }
+ if let executable {
+ let name = Self.basename(executable)
+ let matches = applications.filter { app in app.executables?.contains {
+ $0.os == "win32" && $0.is_launcher != true && Self.basename($0.name) == name
+ } == true }
+ if matches.count == 1 { return matches.first }
+ }
+ return nil // Never guess from fuzzy titles or an ambiguous executable like game.exe.
+ }
+ static func basename(_ path: String) -> String {
+ path.replacingOccurrences(of: "\\", with: "/").split(separator: "/").last.map(String.init)?.lowercased() ?? ""
+ }
+}
+
+actor DiscordCatalogStore {
+ private var catalog: DiscordGameCatalog?
+ private var lastAttempt = Date.distantPast
+ private var cacheURL: URL?
+ func load(paths: HighballPaths) async -> DiscordGameCatalog? {
+ let url = paths.home.appending(path: "discord-games.json")
+ if cacheURL != url {
+ catalog = (try? Data(contentsOf: url)).flatMap { try? DiscordGameCatalog(data: $0) }
+ cacheURL = url
+ lastAttempt = .distantPast
+ }
+ let age = (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate)
+ .map { Date().timeIntervalSince($0) } ?? .infinity
+ guard age > 7 * 86400, Date().timeIntervalSince(lastAttempt) > 3600 else { return catalog }
+ lastAttempt = Date()
+ do {
+ var request = URLRequest(url: URL(string: "https://discord.com/api/v10/applications/detectable")!)
+ request.timeoutInterval = 15
+ let (data, response) = try await URLSession.shared.data(for: request)
+ guard !Task.isCancelled else { return catalog }
+ guard (response as? HTTPURLResponse)?.statusCode == 200, data.count <= 32 * 1024 * 1024 else { return catalog }
+ let fresh = try DiscordGameCatalog(data: data)
+ guard !fresh.applications.isEmpty else { return catalog }
+ catalog = fresh
+ try? data.write(to: url, options: .atomic)
+ } catch { /* The cached catalog still works when offline. */ }
+ return catalog
+ }
+}
+
+public struct DiscordRunningGame: Sendable, Equatable {
+ public let identity: String
+ public let title: String
+ public let steamID: Int?
+ public let executable: String?
+ public let started: Date
+ public init(identity: String, title: String, steamID: Int?, executable: String?, started: Date) {
+ self.identity = identity; self.title = title; self.steamID = steamID
+ self.executable = executable; self.started = started
+ }
+}
diff --git a/Sources/HighballKit/DiscordIPC.swift b/Sources/HighballKit/DiscordIPC.swift
new file mode 100644
index 0000000..3623779
--- /dev/null
+++ b/Sources/HighballKit/DiscordIPC.swift
@@ -0,0 +1,127 @@
+import Foundation
+import Darwin
+
+/// Discord's local IPC framing. A Wine PID is not a macOS PID; use the host's PID so
+/// Discord can follow its lifetime. Everything else, including join secrets, is preserved.
+enum DiscordIPC {
+ static let maximumPayload = 1_048_576
+ struct Frame {
+ var opcode: UInt32
+ var payload: Data
+ var json: [String: Any]? { (try? JSONSerialization.jsonObject(with: payload)) as? [String: Any] }
+ var bytes: Data {
+ var out = Data()
+ for value in [opcode, UInt32(payload.count)] {
+ var le = value.littleEndian
+ withUnsafeBytes(of: &le) { out.append(contentsOf: $0) }
+ }
+ out.append(payload)
+ return out
+ }
+ init(opcode: UInt32, payload: Data) { self.opcode = opcode; self.payload = payload }
+ init(opcode: UInt32, json: [String: Any]) throws {
+ self.init(opcode: opcode, payload: try JSONSerialization.data(withJSONObject: json))
+ }
+ func hostPID(_ pid: pid_t) throws -> Frame {
+ guard opcode == 1, var object = json, object["cmd"] as? String == "SET_ACTIVITY",
+ var args = object["args"] as? [String: Any] else { return self }
+ args["pid"] = Int(pid)
+ object["args"] = args
+ return try Frame(opcode: opcode, json: object)
+ }
+ var activity: Bool? {
+ guard opcode == 1, let object = json, object["cmd"] as? String == "SET_ACTIVITY",
+ let args = object["args"] as? [String: Any], let activity = args["activity"] else { return nil }
+ return !(activity is NSNull)
+ }
+ }
+
+ static func socketPaths(environment: [String: String] = ProcessInfo.processInfo.environment) -> [String] {
+ let dirs = [environment["XDG_RUNTIME_DIR"], environment["TMPDIR"], environment["TMP"], environment["TEMP"],
+ NSTemporaryDirectory(), "/tmp"].compactMap { $0 }
+ var seen = Set<String>()
+ return dirs.flatMap { dir in (0..<10).map { URL(fileURLWithPath: dir).appending(path: "discord-ipc-\($0)").path } }
+ .filter { seen.insert($0).inserted }
+ }
+
+ static func connect(paths: [String] = socketPaths()) throws -> DiscordSocket {
+ for path in paths {
+ var address = sockaddr_un()
+ address.sun_family = sa_family_t(AF_UNIX)
+ let bytes = Array(path.utf8CString)
+ guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else { continue }
+ withUnsafeMutablePointer(to: &address.sun_path) {
+ $0.withMemoryRebound(to: CChar.self, capacity: bytes.count) { $0.update(from: bytes, count: bytes.count) }
+ }
+ let sock = try DiscordSocket(domain: AF_UNIX)
+ let result = withUnsafePointer(to: &address) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(sock.fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }
+ }
+ if result == 0 { return sock }
+ }
+ throw HighballError.failed("Discord is not running")
+ }
+}
+
+/// Owns the descriptor until every reader has finished. stop() only shuts it down:
+/// closing/reusing a descriptor while another thread reads it can affect an unrelated socket.
+final class DiscordSocket: @unchecked Sendable {
+ let fd: Int32
+ init(fd: Int32) {
+ self.fd = fd
+ var one: Int32 = 1
+ setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, socklen_t(MemoryLayout<Int32>.size))
+ _ = fcntl(fd, F_SETFD, FD_CLOEXEC)
+ }
+ convenience init(domain: Int32) throws {
+ let fd = Darwin.socket(domain, SOCK_STREAM, 0)
+ guard fd >= 0 else { throw HighballError.failed("Could not create Discord IPC socket") }
+ self.init(fd: fd)
+ }
+ deinit { Darwin.close(fd) }
+ func stop() { shutdown(fd, SHUT_RDWR) }
+ func read(_ count: Int, timeout: TimeInterval? = nil) throws -> Data {
+ var data = Data(count: count)
+ let deadline = timeout.map { Date().addingTimeInterval($0) }
+ try data.withUnsafeMutableBytes { buffer in
+ var offset = 0
+ while offset < count {
+ var p = pollfd(fd: fd, events: Int16(POLLIN), revents: 0)
+ let wait = deadline.map { max(0, min(1000, Int32($0.timeIntervalSinceNow * 1000))) } ?? 1000
+ let ready = poll(&p, 1, wait)
+ if ready < 0 && errno == EINTR { continue }
+ if let deadline, Date() >= deadline { throw HighballError.failed("Discord IPC timed out") }
+ if ready == 0 { continue }
+ guard ready > 0 else { throw HighballError.failed("Discord IPC read failed") }
+ let n = recv(fd, buffer.baseAddress!.advanced(by: offset), count - offset, 0)
+ if n < 0 && errno == EINTR { continue }
+ guard n > 0 else { throw HighballError.failed("Discord IPC disconnected") }
+ offset += n
+ }
+ }
+ return data
+ }
+ func write(_ data: Data) throws {
+ try data.withUnsafeBytes { buffer in
+ var offset = 0
+ while offset < data.count {
+ var p = pollfd(fd: fd, events: Int16(POLLOUT), revents: 0)
+ let ready = poll(&p, 1, 2000)
+ if ready < 0 && errno == EINTR { continue }
+ guard ready > 0 else { throw HighballError.failed("Discord IPC write timed out") }
+ let n = send(fd, buffer.baseAddress!.advanced(by: offset), data.count - offset, MSG_DONTWAIT)
+ if n < 0 && (errno == EINTR || errno == EAGAIN) { continue }
+ guard n > 0 else { throw HighballError.failed("Discord IPC write failed") }
+ offset += n
+ }
+ }
+ }
+ func readFrame(timeout: TimeInterval? = nil) throws -> DiscordIPC.Frame {
+ let header = try read(8, timeout: timeout)
+ let values = header.withUnsafeBytes { ($0.loadUnaligned(as: UInt32.self).littleEndian,
+ $0.loadUnaligned(fromByteOffset: 4, as: UInt32.self).littleEndian) }
+ guard values.1 <= DiscordIPC.maximumPayload else { throw HighballError.failed("Discord IPC frame is too large") }
+ return DiscordIPC.Frame(opcode: values.0, payload: try read(Int(values.1), timeout: timeout))
+ }
+ func write(_ frame: DiscordIPC.Frame) throws { try write(frame.bytes) }
+}
diff --git a/Sources/HighballKit/DiscordPresence.swift b/Sources/HighballKit/DiscordPresence.swift
new file mode 100644
index 0000000..64741b8
--- /dev/null
+++ b/Sources/HighballKit/DiscordPresence.swift
@@ -0,0 +1,212 @@
+import Foundation
+import Darwin
+
+/// The bridge and passive publisher share a lock so a passive update cannot overwrite
+/// a game's own Rich Presence. Socket I/O runs on utility threads, never the main actor.
+public final class DiscordPresence: @unchecked Sendable {
+ public static let shared = DiscordPresence()
+ public static let enabledDefaultsKey = "discordSharingEnabled"
+ private let loadCatalog: @Sendable (HighballPaths) async -> DiscordGameCatalog?
+ private let socketPaths: @Sendable () -> [String]
+ private let permissionLock = NSLock()
+ private var enabled = false
+ private var generation: UInt64 = 0
+ private let lock = NSLock()
+ private let bridgeLock = NSLock()
+ private var richClients: Set<UUID> = []
+ private var passive: DiscordSocket?
+ private var passiveIdentity: String?
+ private var bridge: DiscordBridge?
+ private var helpers: [String: Process] = [:]
+ private var message = "Waiting for a game"
+ public var status: String { isEnabled ? lock.withLock { message } : "Discord sharing is off" }
+ public var isEnabled: Bool { permissionLock.withLock { enabled } }
+ public init() {
+ let store = DiscordCatalogStore()
+ loadCatalog = { await store.load(paths: $0) }
+ socketPaths = { DiscordIPC.socketPaths() }
+ }
+ init(socketPaths: @escaping @Sendable () -> [String],
+ loadCatalog: (@Sendable (HighballPaths) async -> DiscordGameCatalog?)? = nil) {
+ self.socketPaths = socketPaths
+ let store = DiscordCatalogStore()
+ self.loadCatalog = loadCatalog ?? { await store.load(paths: $0) }
+ }
+
+ /// Revoke permission immediately, including updates waiting for a catalog response.
+ /// The session worker cancels and stops its connections/helpers off the main actor.
+ public func setEnabled(_ value: Bool) {
+ permissionLock.withLock {
+ if enabled != value { generation &+= 1 }
+ enabled = value
+ }
+ }
+
+ private func mayShare(generation expected: UInt64? = nil) -> Bool {
+ !Task.isCancelled && permissionLock.withLock { enabled && (expected == nil || generation == expected) }
+ }
+
+ /// Called with the *effective* Wine environment, after server sync adoption. The helper
+ /// must not cold-start a wineserver with different sync flags from the game it serves.
+ public func ensureBridge(engine: InstalledEngine, bottle: Bottle, environment: [String: String], helperURL: URL? = nil) {
+ guard mayShare(), socketPaths().contains(where: { FileManager.default.fileExists(atPath: $0) }) else { return }
+ guard FileManager.default.fileExists(atPath: bottle.driveC.appending(path: "windows").path) else { return }
+ let helper = helperURL ?? Bundle.main.url(forResource: "highball-discord-bridge", withExtension: "exe")
+ ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appending(path: "spike/discord-bridge/highball-discord-bridge.exe")
+ guard FileManager.default.fileExists(atPath: helper.path) else { return }
+ var waiting: (Process, DiscordBridge, String)?
+ bridgeLock.withLock {
+ guard mayShare() else { return }
+ let prefix = bottle.url.resolvingSymlinksInPath().path
+ if let process = helpers[prefix], process.isRunning { return }
+ do {
+ if bridge == nil { bridge = try DiscordBridge(socketPaths: socketPaths) { [weak self] id, active in self?.richActivity(id, active: active) } }
+ guard let bridge else { return }
+ let process = Process()
+ process.executableURL = engine.wineBinary
+ process.arguments = [helper.path]
+ process.environment = environment.merging([
+ "HIGHBALL_DISCORD_PORT": String(bridge.port), "HIGHBALL_DISCORD_TOKEN": bridge.token,
+ "HIGHBALL_DISCORD_PREFIX": prefix,
+ ]) { $1 }
+ // Windows plumbing directory: SessionWatch and the idle-prefix rule must not
+ // mistake the helper for a game or prevent a renderer/engine restart.
+ process.currentDirectoryURL = bottle.driveC.appending(path: "windows")
+ process.standardOutput = FileHandle.nullDevice
+ process.standardError = FileHandle.nullDevice
+ guard mayShare() else { return }
+ try process.run()
+ helpers[prefix] = process
+ waiting = (process, bridge, prefix)
+ } catch { /* Presence must never keep a game from launching. */ }
+ }
+ // This runs on the session worker after launch. Shutdown does not wait on readiness.
+ if let (process, bridge, prefix) = waiting {
+ let deadline = Date().addingTimeInterval(3)
+ while mayShare() && process.isRunning && !bridge.isReady(prefix: prefix) && Date() < deadline { usleep(20_000) }
+ }
+ }
+
+ public func retainBridges(for prefixes: [URL]) {
+ let active = Set(prefixes.map { $0.resolvingSymlinksInPath().path })
+ bridgeLock.withLock {
+ for prefix in Array(helpers.keys) where !active.contains(prefix) {
+ bridge?.stopControl(prefix: prefix)
+ // A failed/slow helper may not have established its control connection yet.
+ if let process = helpers[prefix], process.isRunning, bridge?.isReady(prefix: prefix) != true {
+ process.terminate()
+ }
+ helpers[prefix] = nil
+ }
+ }
+ }
+
+ func richActivity(_ id: UUID, active: Bool) {
+ lock.withLock {
+ if active && mayShare() {
+ richClients.insert(id)
+ clearPassive() // Clear BEFORE forwarding the richer activity to Discord.
+ message = "Game Rich Presence connected"
+ } else { richClients.remove(id) }
+ }
+ }
+
+ public func update(games: [DiscordRunningGame], paths: HighballPaths = HighballPaths()) async {
+ guard mayShare() else { return }
+ let revision = permissionLock.withLock { generation }
+ guard !games.isEmpty else {
+ lock.withLock { clearPassive(); message = richClients.isEmpty ? "Waiting for a game" : "Game Rich Presence connected" }
+ return
+ }
+ // Avoid the public catalog request unless a local Discord client is available.
+ guard socketPaths().contains(where: { FileManager.default.fileExists(atPath: $0) }) else {
+ lock.withLock { clearPassive(); message = "Open Discord to share your game" }
+ return
+ }
+ if lock.withLock({ !richClients.isEmpty }) { return }
+ let catalog = await loadCatalog(paths)
+ guard mayShare(generation: revision) else { return }
+ publish(games: games, catalog: catalog, generation: revision)
+ }
+
+ func publish(games: [DiscordRunningGame], catalog: DiscordGameCatalog?, generation: UInt64? = nil) {
+ lock.withLock {
+ guard mayShare(generation: generation) else { return }
+ guard richClients.isEmpty else { clearPassive(); message = "Game Rich Presence connected"; return }
+ guard !games.isEmpty else { clearPassive(); message = "Waiting for a game"; return }
+ guard let catalog else { clearPassive(); message = "Discord's game catalog is unavailable"; return }
+ // Keep a live selected game stable; otherwise the most recently started game wins.
+ let ordered = games.sorted {
+ if $0.identity == $1.identity { return false }
+ if $0.identity == passiveIdentity { return true }
+ if $1.identity == passiveIdentity { return false }
+ return $0.started > $1.started
+ }
+ guard let (game, app) = ordered.compactMap({ game in
+ catalog.match(steamID: game.steamID, title: game.title, executable: game.executable).map { (game, $0) }
+ }).first else { clearPassive(); message = "This game is not in Discord's catalog"; return }
+ do {
+ if passiveIdentity == game.identity, let passive {
+ // A closed Discord socket must reconnect even if the game did not change.
+ var p = pollfd(fd: passive.fd, events: Int16(POLLIN), revents: 0)
+ if poll(&p, 1, 0) == 0 { return }
+ let frame = try passive.readFrame(timeout: 0.5)
+ if frame.opcode == 3 {
+ try passive.write(DiscordIPC.Frame(opcode: 4, payload: frame.payload))
+ return
+ }
+ if frame.opcode == 1 { return }
+ clearPassive()
+ } else { clearPassive() }
+ let socket = try DiscordIPC.connect(paths: socketPaths())
+ do {
+ try socket.write(DiscordIPC.Frame(opcode: 0, json: ["v": 1, "client_id": app.id]))
+ try waitFor(socket, event: "READY", nonce: nil)
+ guard mayShare(generation: generation) else { throw CancellationError() }
+ let nonce = UUID().uuidString
+ try socket.write(DiscordIPC.Frame(opcode: 1, json: [
+ "cmd": "SET_ACTIVITY", "nonce": nonce,
+ "args": ["pid": Int(getpid()), "activity": ["timestamps": ["start": Int(game.started.timeIntervalSince1970)]]],
+ ]))
+ try waitFor(socket, event: nil, nonce: nonce)
+ guard mayShare(generation: generation) else { throw CancellationError() }
+ passive = socket; passiveIdentity = game.identity
+ message = "Sharing \(app.name)"
+ } catch { socket.stop(); throw error }
+ } catch { clearPassive(); message = "Discord could not accept this game's activity" }
+ }
+ }
+
+ private func waitFor(_ socket: DiscordSocket, event: String?, nonce: String?) throws {
+ let deadline = Date().addingTimeInterval(3)
+ while Date() < deadline {
+ guard mayShare() else { throw CancellationError() }
+ let frame = try socket.readFrame(timeout: max(0.01, deadline.timeIntervalSinceNow))
+ if frame.opcode == 3 { try socket.write(DiscordIPC.Frame(opcode: 4, payload: frame.payload)); continue }
+ guard frame.opcode == 1, let json = frame.json else { throw HighballError.failed("Discord rejected IPC") }
+ if json["evt"] as? String == "ERROR" { throw HighballError.failed("Discord rejected activity") }
+ if let event, json["evt"] as? String == event { return }
+ if let nonce, json["nonce"] as? String == nonce { return }
+ }
+ throw HighballError.failed("Discord IPC timed out")
+ }
+ // Caller owns lock.
+ private func clearPassive() {
+ if let passive {
+ if let clear = try? DiscordIPC.Frame(opcode: 1, json: ["cmd": "SET_ACTIVITY", "nonce": UUID().uuidString,
+ "args": ["pid": Int(getpid()), "activity": NSNull()]]) {
+ try? passive.write(clear)
+ }
+ passive.stop()
+ }
+ passive = nil; passiveIdentity = nil
+ }
+ public func stop() {
+ bridgeLock.withLock {
+ bridge?.stop(); bridge = nil
+ // The control connection ends the Windows helper without killing its prefix.
+ helpers.removeAll()
+ }
+ lock.withLock { clearPassive(); richClients.removeAll(); message = "Discord sharing stopped" }
+ }
+}
diff --git a/Sources/HighballKit/DiscordSessions.swift b/Sources/HighballKit/DiscordSessions.swift
new file mode 100644
index 0000000..9b9a960
--- /dev/null
+++ b/Sources/HighballKit/DiscordSessions.swift
@@ -0,0 +1,28 @@
+import Foundation
+
+/// Presence follows the sessions Highball already tracks. It never enumerates processes.
+public enum DiscordSessions {
+ public static func games(_ sessions: [GameSession]) -> [DiscordRunningGame] {
+ sessions.map { session in
+ DiscordRunningGame(identity: session.id.uuidString, title: session.title, steamID: session.appid,
+ executable: session.markers.first { $0.lowercased().hasSuffix(".exe") },
+ started: session.started)
+ }
+ }
+
+ /// Reuse a session watcher's existing `ps` snapshot, then read only matching game PIDs.
+ /// The prefix check keeps similarly named games in different environments apart.
+ public static func environment(for session: GameSession, prefix: URL, processList: String) -> [String: String]? {
+ let root = prefix.resolvingSymlinksInPath().path
+ for line in processList.split(whereSeparator: \.isNewline) {
+ guard session.markers.contains(where: { line.contains($0) }),
+ let first = line.split(whereSeparator: \.isWhitespace).first,
+ let pid = Int32(first),
+ let command = ProcessTable.commandLineAndEnvironment(of: pid),
+ let winePrefix = command.environment["WINEPREFIX"],
+ URL(fileURLWithPath: winePrefix).resolvingSymlinksInPath().path == root else { continue }
+ return command.environment
+ }
+ return nil
+ }
+}
diff --git a/Tests/HighballKitTests/DiscordPresenceTests.swift b/Tests/HighballKitTests/DiscordPresenceTests.swift
new file mode 100644
index 0000000..7def86e
--- /dev/null
+++ b/Tests/HighballKitTests/DiscordPresenceTests.swift
@@ -0,0 +1,365 @@
+import XCTest
+import Darwin
+@testable import HighballKit
+
+final class DiscordPresenceTests: XCTestCase {
+ private let catalogData = Data(#"""
+ [{"id":"356942674672091136","name":"Geometry Dash","aliases":["GD"],
+ "executables":[{"name":"geometry dash/geometrydash.exe","os":"win32"}],
+ "third_party_skus":[{"distributor":"steam","id":"322170"},{"distributor":"battlenet","id":null}]},
+ {"id":"2","name":"First","executables":[{"name":"game.exe","os":"win32"}]},
+ {"id":"3","name":"Second","executables":[{"name":"game.exe","os":"win32"}]},
+ {"id":"4","name":"A launcher","executables":[{"name":"launcher.exe","os":"win32","is_launcher":true}]}]
+ """#.utf8)
+
+ func testCurrentPublicCatalogWhenProvided() throws {
+ guard let path = ProcessInfo.processInfo.environment["HIGHBALL_DISCORD_CATALOG_FIXTURE"] else {
+ throw XCTSkip("Set HIGHBALL_DISCORD_CATALOG_FIXTURE to validate a downloaded public catalog")
+ }
+ let catalog = try DiscordGameCatalog(data: Data(contentsOf: URL(fileURLWithPath: path)))
+ XCTAssertGreaterThan(catalog.applications.count, 1000)
+ XCTAssertEqual(catalog.match(steamID: 322170, title: "Renamed game", executable: nil)?.name, "Geometry Dash")
+ }
+
+ func testCatalogPrefersSteamIDAndRejectsAmbiguousExecutables() throws {
+ let catalog = try DiscordGameCatalog(data: catalogData)
+ XCTAssertEqual(catalog.match(steamID: 322170, title: "My renamed game", executable: nil)?.name, "Geometry Dash")
+ XCTAssertEqual(catalog.match(steamID: nil, title: "gd", executable: nil)?.id, "356942674672091136")
+ XCTAssertEqual(catalog.match(steamID: nil, title: "", executable: #"C:\Games\GeometryDash.exe"#)?.name, "Geometry Dash")
+ XCTAssertNil(catalog.match(steamID: nil, title: "", executable: "game.exe"))
+ XCTAssertNil(catalog.match(steamID: nil, title: "", executable: "launcher.exe"))
+ XCTAssertNil(catalog.match(steamID: nil, title: "Geometry", executable: nil))
+ }
+
+ func testPresenceFollowsTrackedSessionsWithStableIdentityAndStartTime() {
+ let since = Date(timeIntervalSince1970: 100)
+ let first = GameSession(title: "Renamed game", bottleName: "a", appid: 322170,
+ markers: SessionWatch.markers(installdir: "Geometry Dash"), started: since)
+ let second = GameSession(title: "Another game", bottleName: "b", appid: nil,
+ markers: ["game.exe"], started: since.addingTimeInterval(10))
+ let games = DiscordSessions.games([first, second])
+ XCTAssertEqual(games[0].identity, first.id.uuidString)
+ XCTAssertEqual(games[0].steamID, 322170)
+ XCTAssertEqual(games[0].title, "Renamed game")
+ XCTAssertEqual(games[0].started, since)
+ XCTAssertNil(games[0].executable)
+ XCTAssertEqual(games[1].executable, "game.exe")
+ XCTAssertNotEqual(games[0].identity, games[1].identity)
+ XCTAssertEqual(DiscordSessions.games([second]), [games[1]], "Ending a session removes only that game's activity")
+ }
+
+ func testSharingDefaultsOffAndDoesNotAccessDiscordOrCatalog() async throws {
+ let access = DiscordAccessProbe()
+ let presence = DiscordPresence(socketPaths: { access.record(); return [] }, loadCatalog: { _ in
+ access.record(); return nil
+ })
+ defer { presence.stop() }
+ let catalog = try DiscordGameCatalog(data: catalogData)
+ let game = DiscordRunningGame(identity: "gd", title: "Geometry Dash", steamID: 322170,
+ executable: nil, started: Date())
+ let engine = InstalledEngine(manifest: EngineManifest(id: "test", displayName: "test", arch: "x86_64",
+ minMacOS: "14.0", components: [:]),
+ root: URL(fileURLWithPath: "/tmp/unused-discord-engine"))
+ let bottle = Bottle(url: URL(fileURLWithPath: "/tmp/unused-discord-prefix"),
+ settings: BottleSettings(name: "test", engineID: "test"))
+ XCTAssertFalse(presence.isEnabled)
+ await presence.update(games: [game])
+ presence.publish(games: [game], catalog: catalog)
+ presence.ensureBridge(engine: engine, bottle: bottle, environment: [:])
+ XCTAssertEqual(access.count, 0, "Disabled sharing must not inspect Discord sockets, load the catalog, or start helpers")
+ XCTAssertEqual(presence.status, "Discord sharing is off")
+ }
+
+ func testRevokingConsentDiscardsCatalogResponseEvenAfterReenabling() async throws {
+ let fake = try FakeDiscord()
+ defer { fake.stop() }
+ let catalog = try DiscordGameCatalog(data: catalogData)
+ let loading = expectation(description: "Catalog request started while enabled")
+ let (gate, release) = AsyncStream<Void>.makeStream()
+ let presence = DiscordPresence(socketPaths: { [fake.path] }, loadCatalog: { _ in
+ loading.fulfill()
+ for await _ in gate { break }
+ return catalog
+ })
+ presence.setEnabled(true)
+ defer { presence.stop() }
+ let game = DiscordRunningGame(identity: "gd", title: "Geometry Dash", steamID: 322170,
+ executable: nil, started: Date())
+ let update = Task { await presence.update(games: [game]) }
+ await fulfillment(of: [loading], timeout: 2)
+ presence.setEnabled(false)
+ presence.setEnabled(true)
+ release.yield(())
+ release.finish()
+ await update.value
+ XCTAssertTrue(fake.handshakes.isEmpty, "An update from the previous consent period must never publish")
+ }
+
+ func testFragmentedFrameAndPIDTranslationPreserveRichData() throws {
+ let (writer, reader) = try pair()
+ let frame = try DiscordIPC.Frame(opcode: 1, json: ["cmd": "SET_ACTIVITY", "nonce": "n",
+ "args": ["pid": 123, "activity": ["state": "In game", "secrets": ["join": "secret"], "assets": ["large_image": "map"]]]])
+ DispatchQueue.global().async { for byte in frame.bytes { try? writer.write(Data([byte])) } }
+ let received = try reader.readFrame(timeout: 2)
+ let rewritten = try received.hostPID(456)
+ XCTAssertEqual((rewritten.json?["args"] as? [String: Any])?["pid"] as? Int, 456)
+ let activity = (rewritten.json?["args"] as? [String: Any])?["activity"] as? [String: Any]
+ XCTAssertEqual((activity?["secrets"] as? [String: String])?["join"], "secret")
+ XCTAssertEqual(rewritten.json?["nonce"] as? String, "n")
+ XCTAssertEqual(received.activity, true)
+ let ping = DiscordIPC.Frame(opcode: 3, payload: Data([0, 255, 1]))
+ XCTAssertEqual(try ping.hostPID(456).bytes, ping.bytes)
+ }
+
+ func testRejectsOversizeAndTruncatedFrames() throws {
+ let (writer, reader) = try pair()
+ var header = Data([1, 0, 0, 0]); var size = UInt32(DiscordIPC.maximumPayload + 1).littleEndian
+ withUnsafeBytes(of: &size) { header.append(contentsOf: $0) }
+ try writer.write(header)
+ XCTAssertThrowsError(try reader.readFrame(timeout: 1))
+ let (writer2, reader2) = try pair()
+ try writer2.write(Data([1, 0, 0])); writer2.stop()
+ XCTAssertThrowsError(try reader2.readFrame(timeout: 1))
+ }
+
+ func testPassiveUsesGameIDClearsOnRichPresenceAndResumes() throws {
+ let fake = try FakeDiscord()
+ defer { fake.stop() }
+ let presence = DiscordPresence(socketPaths: { [fake.path] })
+ presence.setEnabled(true)
+ defer { presence.stop() }
+ let catalog = try DiscordGameCatalog(data: catalogData)
+ let game = DiscordRunningGame(identity: "gd", title: "My title", steamID: 322170, executable: nil, started: Date(timeIntervalSince1970: 123))
+ presence.publish(games: [game], catalog: catalog)
+ XCTAssertEqual(presence.status, "Sharing Geometry Dash")
+ XCTAssertEqual(fake.handshakes.last, "356942674672091136")
+ let id = UUID()
+ presence.richActivity(id, active: true)
+ presence.publish(games: [game], catalog: catalog)
+ XCTAssertEqual(presence.status, "Game Rich Presence connected")
+ XCTAssertEqual(fake.handshakes.count, 1)
+ presence.richActivity(id, active: false)
+ presence.publish(games: [game], catalog: catalog)
+ XCTAssertEqual(presence.status, "Sharing Geometry Dash")
+ XCTAssertEqual(fake.handshakes.count, 2)
+ presence.publish(games: [], catalog: catalog)
+ XCTAssertEqual(presence.status, "Waiting for a game")
+ }
+
+ func testPassiveReconnectsAfterDiscordRestartAndRespondsToPing() throws {
+ let fake = try FakeDiscord()
+ defer { fake.stop() }
+ let presence = DiscordPresence(socketPaths: { [fake.path] })
+ presence.setEnabled(true)
+ defer { presence.stop() }
+ let catalog = try DiscordGameCatalog(data: catalogData)
+ let game = DiscordRunningGame(identity: "gd", title: "Geometry Dash", steamID: 322170,
+ executable: nil, started: Date())
+ presence.publish(games: [game], catalog: catalog)
+ try fake.ping()
+ presence.publish(games: [game], catalog: catalog)
+ XCTAssertEqual(fake.handshakes.count, 1, "Ping must not republish the activity")
+ fake.disconnectClients()
+ presence.publish(games: [game], catalog: catalog)
+ presence.publish(games: [game], catalog: catalog)
+ XCTAssertEqual(presence.status, "Sharing Geometry Dash")
+ XCTAssertEqual(fake.handshakes.count, 2)
+ }
+
+ func testBridgeIsBidirectionalAndStopsConnections() throws {
+ let fake = try FakeDiscord()
+ defer { fake.stop() }
+ let bridge = try DiscordBridge(socketPaths: { [fake.path] }) { _, _ in }
+ defer { bridge.stop() }
+ let client = try tcp(port: bridge.port)
+ try client.write(Data(bridge.token.utf8) + Data([0]))
+ try client.write(DiscordIPC.Frame(opcode: 0, json: ["v": 1, "client_id": "356942674672091136"]))
+ XCTAssertEqual(try client.readFrame(timeout: 2).json?["evt"] as? String, "READY")
+ try client.write(DiscordIPC.Frame(opcode: 1, json: ["cmd": "SET_ACTIVITY", "nonce": "win",
+ "args": ["pid": 999, "activity": ["state": "A level"]]]))
+ let reply = try client.readFrame(timeout: 2)
+ XCTAssertEqual((reply.json?["args"] as? [String: Any])?["pid"] as? Int, Int(getpid()))
+ XCTAssertEqual(reply.json?["nonce"] as? String, "win")
+ bridge.stop()
+ XCTAssertThrowsError(try client.readFrame(timeout: 2))
+ }
+
+ func testWineNamedPipeSmokeWhenRequested() throws {
+ guard let enginePath = ProcessInfo.processInfo.environment["HIGHBALL_DISCORD_SMOKE_ENGINE"] else {
+ throw XCTSkip("Set HIGHBALL_DISCORD_SMOKE_ENGINE to an installed engine directory for the Wine smoke")
+ }
+ let engineRoot = URL(fileURLWithPath: enginePath)
+ let engine = InstalledEngine(manifest: try EngineManifest.load(from: engineRoot.appending(path: "manifest.json")), root: engineRoot)
+ let root = URL(fileURLWithPath: "/tmp/hb-discord-smoke-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ let bottle = Bottle(url: root, settings: BottleSettings(name: "discord-smoke", engineID: engine.id))
+ var env = engine.baseEnvironment().merging(ProcessInfo.processInfo.environment) { original, _ in original }
+ env["WINEPREFIX"] = root.path; env["WINEDEBUG"] = "-all"
+ env["WINEMSYNC"] = "0"; env["WINEESYNC"] = "0"
+ let boot = Process(); boot.executableURL = engine.wineBinary; boot.arguments = ["wineboot.exe", "--init"]
+ boot.environment = env; boot.standardOutput = FileHandle.nullDevice; boot.standardError = FileHandle.nullDevice
+ try boot.run()
+ defer {
+ let kill = Process(); kill.executableURL = engine.wineserverBinary; kill.arguments = ["-k"]
+ kill.environment = env; try? kill.run(); kill.waitUntilExit()
+ try? FileManager.default.removeItem(at: root)
+ }
+ XCTAssertTrue(waitUntil(seconds: 90) { !boot.isRunning }, "Wine boot timed out")
+ guard !boot.isRunning else { boot.terminate(); return }
+ XCTAssertEqual(boot.terminationStatus, 0)
+ let fake = try FakeDiscord()
+ defer { fake.stop() }
+ let presence = DiscordPresence(socketPaths: { [fake.path] })
+ presence.setEnabled(true)
+ defer { presence.stop() }
+ let repo = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ let helper = repo.appending(path: "spike/discord-bridge/highball-discord-bridge.exe")
+ let probe = repo.appending(path: "spike/discord-bridge/probe.exe")
+ for cycle in 0..<2 {
+ presence.setEnabled(true)
+ presence.ensureBridge(engine: engine, bottle: bottle, environment: env, helperURL: helper)
+ let session = GameSession(title: "Bridge environment probe", bottleName: bottle.name, appid: nil,
+ markers: ["highball-discord-bridge.exe"])
+ let inherited = DiscordSessions.environment(for: session, prefix: root, processList: SessionWatch.currentProcessList())
+ XCTAssertEqual(inherited?["WINEPREFIX"], root.path)
+ XCTAssertEqual(inherited?["WINEMSYNC"], env["WINEMSYNC"], "The session-side helper must inherit the game's sync mode")
+ XCTAssertNil(DiscordSessions.environment(for: session, prefix: root.appending(path: "another-prefix"),
+ processList: SessionWatch.currentProcessList()))
+ for slot in [0, 9, 0] {
+ let process = Process(), output = Pipe()
+ process.executableURL = engine.wineBinary; process.arguments = [probe.path, String(slot)]
+ process.environment = env; process.currentDirectoryURL = bottle.driveC
+ process.standardOutput = output; process.standardError = FileHandle.nullDevice
+ try process.run()
+ XCTAssertTrue(waitUntil(seconds: 15) { !process.isRunning }, "Named-pipe probe hung (cycle \(cycle), slot \(slot))")
+ guard !process.isRunning else { process.terminate(); return }
+ XCTAssertEqual(process.terminationStatus, 0, "Wine pipe probe failed")
+ let data = output.fileHandleForReading.readDataToEndOfFile()
+ let lines = String(decoding: data, as: UTF8.self).split(whereSeparator: \.isNewline)
+ XCTAssertEqual(lines.count, 2)
+ if let last = lines.last, let json = try JSONSerialization.jsonObject(with: Data(last.utf8)) as? [String: Any] {
+ XCTAssertEqual((json["args"] as? [String: Any])?["pid"] as? Int, Int(getpid()))
+ XCTAssertEqual(json["nonce"] as? String, "wine-probe")
+ }
+ }
+ presence.setEnabled(false)
+ presence.stop()
+ XCTAssertTrue(waitUntil(seconds: 5) {
+ !ProcessTable.allPIDs().contains { pid in
+ guard let command = ProcessTable.commandLineAndEnvironment(of: pid), command.environment["WINEPREFIX"] == root.path else { return false }
+ return command.arguments.contains { $0.contains("highball-discord-bridge.exe") }
+ }
+ }, "Bridge shutdown left the Wine helper alive")
+ presence.ensureBridge(engine: engine, bottle: bottle, environment: env, helperURL: helper)
+ XCTAssertFalse(ProcessTable.allPIDs().contains { pid in
+ guard let command = ProcessTable.commandLineAndEnvironment(of: pid), command.environment["WINEPREFIX"] == root.path else { return false }
+ return command.arguments.contains { $0.contains("highball-discord-bridge.exe") }
+ }, "Disabled sharing must not restart the helper")
+ }
+ }
+
+ func testEndingOnePrefixDoesNotStopAnotherBridgeControl() throws {
+ let bridge = try DiscordBridge(socketPaths: { [] }) { _, _ in }
+ defer { bridge.stop() }
+ func control(_ prefix: String) throws -> DiscordSocket {
+ let client = try tcp(port: bridge.port)
+ let path = Data(prefix.utf8)
+ var length = UInt16(path.count).littleEndian
+ var header = Data(bridge.token.utf8) + Data([255])
+ withUnsafeBytes(of: &length) { header.append(contentsOf: $0) }
+ try client.write(header + path)
+ return client
+ }
+ let first = try control("/tmp/first"), second = try control("/tmp/second")
+ defer { first.stop(); second.stop() }
+ XCTAssertTrue(waitUntil(seconds: 2) { bridge.isReady(prefix: "/tmp/first") && bridge.isReady(prefix: "/tmp/second") })
+ bridge.stopControl(prefix: "/tmp/first")
+ XCTAssertThrowsError(try first.read(1, timeout: 1))
+ XCTAssertTrue(waitUntil(seconds: 2) { !bridge.isReady(prefix: "/tmp/first") })
+ XCTAssertTrue(bridge.isReady(prefix: "/tmp/second"), "A game ending must not close another environment's helper")
+ }
+
+ private func waitUntil(seconds: TimeInterval, _ condition: () -> Bool) -> Bool {
+ let deadline = Date().addingTimeInterval(seconds)
+ while !condition() && Date() < deadline { usleep(20_000) }
+ return condition()
+ }
+
+ private func pair() throws -> (DiscordSocket, DiscordSocket) {
+ var fds: [Int32] = [-1, -1]
+ guard socketpair(AF_UNIX, SOCK_STREAM, 0, &fds) == 0 else { throw HighballError.failed("socketpair") }
+ return (DiscordSocket(fd: fds[0]), DiscordSocket(fd: fds[1]))
+ }
+}
+
+private func tcp(port: UInt16) throws -> DiscordSocket {
+ let sock = try DiscordSocket(domain: AF_INET)
+ var addr = sockaddr_in(); addr.sin_family = sa_family_t(AF_INET)
+ addr.sin_addr.s_addr = inet_addr("127.0.0.1"); addr.sin_port = port.bigEndian
+ let result = withUnsafePointer(to: &addr) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(sock.fd, $0, socklen_t(MemoryLayout<sockaddr_in>.size)) }
+ }
+ guard result == 0 else { throw HighballError.failed("connect") }
+ return sock
+}
+
+/// Real local Unix sockets, with no network access and no activity sent to the user's Discord.
+private final class FakeDiscord: @unchecked Sendable {
+ let path = "/tmp/hb-\(UUID().uuidString.prefix(12)).sock"
+ private let listener: DiscordSocket
+ private let lock = NSLock()
+ private var stopped = false
+ private var sockets: [DiscordSocket] = []
+ private var ids: [String] = []
+ var handshakes: [String] { lock.withLock { ids } }
+ init() throws {
+ listener = try DiscordSocket(domain: AF_UNIX)
+ let socket = listener
+ var addr = sockaddr_un(); addr.sun_family = sa_family_t(AF_UNIX)
+ let bytes = Array(path.utf8CString)
+ withUnsafeMutablePointer(to: &addr.sun_path) {
+ $0.withMemoryRebound(to: CChar.self, capacity: bytes.count) { $0.update(from: bytes, count: bytes.count) }
+ }
+ let result = withUnsafePointer(to: &addr) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(socket.fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }
+ }
+ guard result == 0, listen(socket.fd, 16) == 0 else { throw HighballError.failed("fake bind") }
+ DispatchQueue.global().async { [self] in
+ while !lock.withLock({ stopped }) {
+ var p = pollfd(fd: socket.fd, events: Int16(POLLIN), revents: 0)
+ guard poll(&p, 1, 100) > 0 else { continue }
+ let fd = accept(socket.fd, nil, nil)
+ guard fd >= 0 else { continue }
+ let client = DiscordSocket(fd: fd)
+ lock.withLock { sockets.append(client) }
+ DispatchQueue.global().async { [self] in
+ do {
+ let handshake = try client.readFrame(timeout: 2)
+ lock.withLock { ids.append(handshake.json?["client_id"] as? String ?? "") }
+ try client.write(DiscordIPC.Frame(opcode: 1, json: ["cmd": "DISPATCH", "evt": "READY", "data": [:]]))
+ while true {
+ let frame = try client.readFrame()
+ try client.write(frame) // echo nonce and rewritten args
+ }
+ } catch { client.stop() }
+ }
+ }
+ }
+ }
+ func ping() throws {
+ guard let client = lock.withLock({ sockets.last }) else { throw HighballError.failed("No fake client") }
+ try client.write(DiscordIPC.Frame(opcode: 3, payload: Data("ping".utf8)))
+ }
+ func disconnectClients() { lock.withLock { for client in sockets { client.stop() } } }
+ func stop() {
+ lock.withLock { stopped = true; listener.stop(); for client in sockets { client.stop() } }
+ unlink(path)
+ }
+}
+
+private final class DiscordAccessProbe: @unchecked Sendable {
+ private let lock = NSLock()
+ private var accesses = 0
+ var count: Int { lock.withLock { accesses } }
+ func record() { lock.withLock { accesses += 1 } }
+}
diff --git a/docs/discord-presence.md b/docs/discord-presence.md
new file mode 100644
index 0000000..d2fd3f9
--- /dev/null
+++ b/docs/discord-presence.md
@@ -0,0 +1,82 @@
+# Discord game activity on macOS
+
+Discord sharing is off by default. Enable **Share game activity with Discord** in
+Settings → Engine to share tracked Windows game sessions while Discord for Mac is
+open. With sharing off, Highball performs no Discord process discovery, starts no
+bridge helper, and makes no catalog request. Turning it off clears activity and
+stops the helpers without stopping the games. Discord's Activity Privacy settings
+also control whether friends see the activity.
+
+* **Basic presence:** Highball uses its existing game sessions, their Steam IDs,
+ titles, and executable markers. It resolves the game's Discord application ID from Discord's public
+ detection catalog and publishes the game's name and elapsed time through local
+ IPC. Steam IDs take precedence over titles; executable names are accepted only
+ when unambiguous. No Highball application ID or Discord account token is required.
+* **Rich Presence pass-through:** a small Windows helper creates
+ `\\.\pipe\discord-ipc-0` through `discord-ipc-9` in each environment with a tracked game session. It
+ connects to a native loopback listener authenticated with a per-run random token.
+ Highball relays framed messages and replies to Discord's Unix socket, replacing
+ Windows PIDs with Highball's macOS PID. Application IDs, assets, details, party
+ data, join secrets, subscriptions, and events retain the original game's values.
+ This forwards RPC; it does not implement an overlay or launch/join protocol handlers.
+
+A game's own Rich Presence takes priority over basic presence. Basic presence
+resumes after the richer connection ends. With multiple games running, Highball
+keeps its selected basic activity until that game closes, then picks the newest
+recognised game. Games absent from Discord's catalog cannot receive basic presence;
+Rich Presence pass-through remains available for those games.
+
+The catalog endpoint (`https://discord.com/api/v10/applications/detectable`) is
+public but undocumented and can change. The last valid catalog is cached as
+`discord-games.json` in Highball's data directory, refreshed weekly when a game and
+Discord are running. Failed requests are retried at most hourly. Game titles,
+process arguments, and account tokens are not sent in this request. An unavailable
+catalog or Discord client never prevents a game launch.
+
+The bridge starts on a background session worker after a game is running; game
+launches and installers never wait for it. It reuses the existing session watcher's
+process snapshot to read the game's Wine environment, without an additional process
+scan. Discord availability is checked through macOS's running applications. Closing
+Discord stops the bridges, and reopening it resumes sharing for active sessions.
+
+Presence follows sessions started through Highball. Games started directly in a
+launcher, or left running across a Highball restart, are not discovered separately.
+Quitting Highball closes the IPC connections and ends its Windows helpers,
+including when Windows programs are left running. The helpers run in `drive_c/windows`, so they count as plumbing for
+Highball's idle-prefix and renderer restart rules. No service, LaunchAgent, engine
+patch, or replacement Discord DLL is installed.
+
+## Local build and validation
+
+```sh
+Scripts/make-app.sh debug 0.10.7-discord-local
+open dist/Highball.app
+```
+
+The Windows helper is built from `spike/discord-bridge/main.c` with mingw-w64 and
+bundled as `Contents/Resources/highball-discord-bridge.exe`. Release builds require
+mingw-w64; debug builds warn when it is absent (basic presence still works).
+Bare `swift run HighballApp` builds can find the helper under `spike/discord-bridge`
+when run from the repository root; run its `build.sh` first.
+
+```sh
+swift test --filter DiscordPresenceTests
+spike/discord-bridge/build.sh
+x86_64-w64-mingw32-gcc -O2 -Wall -Wextra -Werror -static -s \
+ -o spike/discord-bridge/probe.exe spike/discord-bridge/probe.c
+HIGHBALL_DISCORD_SMOKE_ENGINE="/path/to/installed/Highball/engine" \
+ swift test --filter DiscordPresenceTests/testWineNamedPipeSmokeWhenRequested
+```
+
+Tests use a fake Discord Unix socket and publish nothing to the user's Discord.
+The optional Wine smoke boots a throwaway prefix with an installed engine, exercises
+fragmented SDK frames on slots 0 and 9, checks native PID translation and bidirectional
+replies, shuts down the bridge, verifies the helper exits, and repeats after restarting it.
+
+To check activity locally, enable sharing in Highball's Settings → Engine and in
+Discord, then start Geometry Dash through Highball. Check that Discord shows
+**Playing Geometry Dash** and clears it after quitting the game. Repeat with a game
+that has its own Rich Presence and restart Discord while playing. Turn Highball's
+sharing switch off during play: activity should clear while the game keeps running.
+
+Protocol reference: https://github.com/discord/discord-rpc/blob/master/documentation/hard-mode.md
diff --git a/spike/discord-bridge/build.sh b/spike/discord-bridge/build.sh
new file mode 100755
index 0000000..b716509
--- /dev/null
+++ b/spike/discord-bridge/build.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+set -euo pipefail
+cd "$(dirname "$0")"
+x86_64-w64-mingw32-gcc -O2 -Wall -Wextra -Werror -static -s -o highball-discord-bridge.exe main.c -lws2_32
diff --git a/spike/discord-bridge/main.c b/spike/discord-bridge/main.c
new file mode 100644
index 0000000..490bbaf
--- /dev/null
+++ b/spike/discord-bridge/main.c
@@ -0,0 +1,126 @@
+/* Wine-side Discord IPC bridge. Ordinary Win32 named pipes + Winsock work with both
+ * Intel Wine and the native arm64 Wine loader; no host syscalls or injected DLLs. */
+#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
+#include <windows.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+static char token[37], prefix[4097];
+static unsigned short port;
+static HANDLE ready[10];
+
+static int send_all(SOCKET s, const void *data, int count) {
+ const char *p = data;
+ while (count > 0) {
+ int n = send(s, p, count, 0);
+ if (n <= 0) return 0;
+ p += n; count -= n;
+ }
+ return 1;
+}
+static SOCKET connect_host(unsigned char index) {
+ SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (s == INVALID_SOCKET) return s;
+ struct sockaddr_in address = {0};
+ address.sin_family = AF_INET;
+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ address.sin_port = htons(port);
+ if (connect(s, (struct sockaddr *)&address, sizeof(address)) != 0 ||
+ !send_all(s, token, 36) || !send_all(s, &index, 1)) {
+ closesocket(s); return INVALID_SOCKET;
+ }
+ return s;
+}
+struct client { HANDLE pipe; HANDLE request_thread; SOCKET socket; };
+static DWORD WINAPI replies(void *arg) {
+ struct client *client = arg;
+ char buffer[16384]; int n;
+ while ((n = recv(client->socket, buffer, sizeof(buffer), 0)) > 0) {
+ int offset = 0;
+ while (offset < n) {
+ DWORD written;
+ if (!WriteFile(client->pipe, buffer + offset, (DWORD)(n - offset), &written, NULL) || !written) goto done;
+ offset += (int)written;
+ }
+ }
+done:
+ shutdown(client->socket, SD_BOTH);
+ /* Cancel the blocking pipe read of the opposite direction. */
+ CancelSynchronousIo(client->request_thread);
+ return 0;
+}
+static DWORD WINAPI connection(void *arg) {
+ struct client *client = arg;
+ DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(),
+ &client->request_thread, 0, FALSE, DUPLICATE_SAME_ACCESS);
+ HANDLE reader = CreateThread(NULL, 0, replies, client, 0, NULL);
+ if (reader) {
+ char buffer[16384]; DWORD n;
+ while (ReadFile(client->pipe, buffer, sizeof(buffer), &n, NULL) && n > 0)
+ if (!send_all(client->socket, buffer, (int)n)) break;
+ shutdown(client->socket, SD_BOTH);
+ CancelSynchronousIo(reader);
+ WaitForSingleObject(reader, INFINITE);
+ CloseHandle(reader);
+ }
+ if (client->request_thread) CloseHandle(client->request_thread);
+ DisconnectNamedPipe(client->pipe);
+ CloseHandle(client->pipe);
+ closesocket(client->socket);
+ free(client);
+ return 0;
+}
+static DWORD WINAPI pipe_server(void *arg) {
+ unsigned int index = (unsigned int)(uintptr_t)arg;
+ char name[64];
+ snprintf(name, sizeof(name), "\\\\.\\pipe\\discord-ipc-%u", index);
+ int first = 1;
+ for (;;) {
+ HANDLE pipe = CreateNamedPipeA(name, PIPE_ACCESS_DUPLEX,
+ PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
+ PIPE_UNLIMITED_INSTANCES, 65536, 65536, 0, NULL);
+ if (pipe == INVALID_HANDLE_VALUE) { if (first) SetEvent(ready[index]); return 0; }
+ if (first) { SetEvent(ready[index]); first = 0; }
+ if (!ConnectNamedPipe(pipe, NULL) && GetLastError() != ERROR_PIPE_CONNECTED) { CloseHandle(pipe); continue; }
+ SOCKET s = connect_host((unsigned char)index);
+ if (s == INVALID_SOCKET) { DisconnectNamedPipe(pipe); CloseHandle(pipe); Sleep(250); continue; }
+ struct client *client = calloc(1, sizeof(*client));
+ if (!client) { DisconnectNamedPipe(pipe); CloseHandle(pipe); closesocket(s); continue; }
+ client->pipe = pipe; client->socket = s;
+ HANDLE thread = CreateThread(NULL, 0, connection, client, 0, NULL);
+ if (thread) CloseHandle(thread);
+ else { DisconnectNamedPipe(pipe); CloseHandle(pipe); closesocket(s); free(client); }
+ }
+}
+int main(void) {
+ char port_string[8];
+ if (GetEnvironmentVariableA("HIGHBALL_DISCORD_TOKEN", token, sizeof(token)) != 36 ||
+ !GetEnvironmentVariableA("HIGHBALL_DISCORD_PORT", port_string, sizeof(port_string)) ||
+ !GetEnvironmentVariableA("HIGHBALL_DISCORD_PREFIX", prefix, sizeof(prefix))) return 1;
+ port = (unsigned short)atoi(port_string);
+ if (!port) return 1;
+ HANDLE mutex = CreateMutexA(NULL, TRUE, "Local\\HighballDiscordBridge");
+ if (!mutex || GetLastError() == ERROR_ALREADY_EXISTS) return 0;
+ WSADATA data;
+ if (WSAStartup(MAKEWORD(2, 2), &data) != 0) return 1;
+ /* Control connection is also a host-lifetime watchdog. */
+ SOCKET control = connect_host(255);
+ if (control == INVALID_SOCKET) return 1;
+ for (unsigned int i = 0; i < 10; i++) {
+ ready[i] = CreateEventA(NULL, TRUE, FALSE, NULL);
+ if (!ready[i]) return 1;
+ HANDLE thread = CreateThread(NULL, 0, pipe_server, (void *)(uintptr_t)i, 0, NULL);
+ if (!thread) return 1;
+ CloseHandle(thread);
+ }
+ WaitForMultipleObjects(10, ready, TRUE, INFINITE);
+ uint16_t length = (uint16_t)strlen(prefix);
+ if (!send_all(control, &length, 2) || !send_all(control, prefix, length)) return 1;
+ for (unsigned int i = 0; i < 10; i++) CloseHandle(ready[i]);
+ char byte;
+ recv(control, &byte, 1, 0); /* host gone: process exit releases all named pipes */
+ return 0;
+}
diff --git a/spike/discord-bridge/probe.c b/spike/discord-bridge/probe.c
new file mode 100644
index 0000000..ea07b50
--- /dev/null
+++ b/spike/discord-bridge/probe.c
@@ -0,0 +1,49 @@
+/* Development smoke probe: imitates a game's Discord SDK, never contacts Discord itself. */
+#include <windows.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static int write_frame(HANDLE pipe, uint32_t op, const char *json) {
+ uint32_t size = (uint32_t)strlen(json); unsigned char frame[2048];
+ if (size > sizeof(frame) - 8) return 0;
+ memcpy(frame, &op, 4); memcpy(frame + 4, &size, 4); memcpy(frame + 8, json, size);
+ /* Fragment writes to exercise stream framing rather than relying on message boundaries. */
+ for (uint32_t i = 0; i < size + 8; i++) {
+ DWORD n;
+ if (!WriteFile(pipe, frame + i, 1, &n, NULL) || n != 1) return 0;
+ }
+ return 1;
+}
+static int read_exact(HANDLE pipe, void *buffer, DWORD size) {
+ char *p = buffer;
+ while (size) {
+ DWORD n;
+ if (!ReadFile(pipe, p, size, &n, NULL) || !n) return 0;
+ p += n; size -= n;
+ }
+ return 1;
+}
+static int read_frame(HANDLE pipe) {
+ uint32_t header[2]; char json[4096];
+ if (!read_exact(pipe, header, 8) || header[1] >= sizeof(json)) return 0;
+ if (!read_exact(pipe, json, header[1])) return 0;
+ json[header[1]] = 0;
+ puts(json); fflush(stdout);
+ return header[0] == 1;
+}
+int main(int argc, char **argv) {
+ const char *slot = argc > 1 ? argv[1] : "0";
+ char name[80]; snprintf(name, sizeof(name), "\\\\.\\pipe\\discord-ipc-%s", slot);
+ HANDLE pipe = INVALID_HANDLE_VALUE;
+ for (int i = 0; i < 100 && pipe == INVALID_HANDLE_VALUE; i++) {
+ pipe = CreateFileA(name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
+ if (pipe == INVALID_HANDLE_VALUE) Sleep(50);
+ }
+ if (pipe == INVALID_HANDLE_VALUE) return 1;
+ if (!write_frame(pipe, 0, "{\"v\":1,\"client_id\":\"356942674672091136\"}") || !read_frame(pipe)) return 2;
+ if (!write_frame(pipe, 1, "{\"cmd\":\"SET_ACTIVITY\",\"nonce\":\"wine-probe\",\"args\":{\"pid\":999,\"activity\":{\"state\":\"A level\",\"secrets\":{\"join\":\"kept\"}}}}") || !read_frame(pipe)) return 3;
+ CloseHandle(pipe);
+ return 0;
+}