From 9a1e1408b4715c5a3e49275b08fb1cd8d4f89248 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:07:43 -0300 Subject: [PATCH 01/37] Define the Darkroom app discovery contract --- contracts/link/v1/README.md | 19 +++++++++++++++++++ contracts/link/v1/apps.json | 26 ++++++++++++++++++++++++++ contracts/link/v1/status.example.json | 8 ++++++++ 3 files changed, 53 insertions(+) create mode 100644 contracts/link/v1/README.md create mode 100644 contracts/link/v1/apps.json create mode 100644 contracts/link/v1/status.example.json diff --git a/contracts/link/v1/README.md b/contracts/link/v1/README.md new file mode 100644 index 00000000..62a262f9 --- /dev/null +++ b/contracts/link/v1/README.md @@ -0,0 +1,19 @@ +# Darkroom app discovery v1 + +Resolve the exact production bundle identifier in [the app table](apps.json) with Launch Services. Verify the bundle and each invoked executable before use. The executable must resolve within the verified bundle. The Developer ID team is ZNHHMX2RP6. Tagged development bundle identifiers are distinct from these production identifiers. + +An app implementing this probe declares integer `DarkroomAppLinkVersion` equal to 1 in its Info.plist. Check this marker before invoking the status entry point. An older entry point may treat an unknown argument as a regular app launch. + +Invoke the status entry point with `--app-link-status`, closed stdin and a bounded deadline. It emits a [single JSON object](status.example.json) on stdout and exits zero. The probe may read local policy and query a local readiness endpoint. It does not start the app, change policy, enumerate content, authenticate as the agent or persist a result. Clients match the response's contract and identity to the verified bundle, and ignore additional fields. Version is the app's release version. Capability strings describe the supported entry points. `mcp.stdio` marks a stdio MCP server. + +| State | Meaning | +| --- | --- | +| `ready` | The app's existing access policy allows this integration and the advertised capability is available. | +| `not_running` | A necessary local process or endpoint is unavailable. | +| `denied` | A policy check rejected this caller. | +| `disabled` | The user has disabled the relevant application or integration setting. | +| `incompatible` | The app cannot speak this version of the contract or reports an incompatible endpoint. | + +Installation, running process and access state are independent. `programa apps status --json` adds a top-level contract, an array of peer records, and flags for installation and an observed running production process. A missing bundle is `not_installed`. A failed probe may be `unavailable` and access remains unknown. Check again on every explicit inquiry or helper start so that restarting or moving a peer does not require updating agent configuration. + +Agents keep MCP over stdio. A Programa agent adapter can supply `--session programa-` as an explicit correlation value each time it starts the peer helper, including after an agent reconnect or resume. The value identifies a pane for routing and does not grant access. The owning app applies its existing access and content approval rules. diff --git a/contracts/link/v1/apps.json b/contracts/link/v1/apps.json new file mode 100644 index 00000000..152e9220 --- /dev/null +++ b/contracts/link/v1/apps.json @@ -0,0 +1,26 @@ +{ + "contract": 1, + "team_id": "ZNHHMX2RP6", + "info_plist_key": "DarkroomAppLinkVersion", + "status_arguments": ["--app-link-status"], + "apps": [ + { + "app": "programa", + "bundle_id": "com.darkroom.programa", + "status_entry_points": ["Contents/Resources/bin/programa"], + "mcp_entry_points": ["Contents/Resources/bin/programa-mcp"] + }, + { + "app": "browsee", + "bundle_id": "com.darkroom.browsee", + "status_entry_points": ["Contents/Helpers/browsee-mcp", "Contents/MacOS/browsee-mcp"], + "mcp_entry_points": ["Contents/Helpers/browsee-mcp", "Contents/MacOS/browsee-mcp"] + }, + { + "app": "mesinyer", + "bundle_id": "engineering.darkroom.mesinyer", + "status_entry_points": ["Contents/MacOS/Mesinyer"], + "mcp_entry_points": ["Contents/MacOS/Mesinyer"] + } + ] +} diff --git a/contracts/link/v1/status.example.json b/contracts/link/v1/status.example.json new file mode 100644 index 00000000..1d70fa27 --- /dev/null +++ b/contracts/link/v1/status.example.json @@ -0,0 +1,8 @@ +{ + "contract": 1, + "app": "browsee", + "bundle_id": "com.darkroom.browsee", + "version": "1.0.0", + "state": "ready", + "capabilities": ["mcp.stdio"] +} From eeb69979ab6ec57e3e997630d0c78c759da89e23 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:17:28 -0300 Subject: [PATCH 02/37] Discover verified Darkroom apps on demand --- CLI/CLI+Apps.swift | 272 ++++++++++++++++++++++++++ CLI/CLI+Browsee.swift | 82 +++++--- CLI/CLICommandDispatcher.swift | 1 + CLI/Commands/LocalCommands.swift | 8 + CLI/SocketClient.swift | 7 + CLI/programa.swift | 6 +- GhosttyTabs.xcodeproj/project.pbxproj | 4 + Resources/Info.plist | 2 + contracts/link/v1/README.md | 2 +- 9 files changed, 352 insertions(+), 32 deletions(-) create mode 100644 CLI/CLI+Apps.swift diff --git a/CLI/CLI+Apps.swift b/CLI/CLI+Apps.swift new file mode 100644 index 00000000..5d8d68a6 --- /dev/null +++ b/CLI/CLI+Apps.swift @@ -0,0 +1,272 @@ +import AppKit +import Darwin +import Foundation +import Security + +enum DarkroomPeer: String, CaseIterable { + case browsee + case mesinyer + + var bundleID: String { + switch self { + case .browsee: return "com.darkroom.browsee" + case .mesinyer: return "engineering.darkroom.mesinyer" + } + } + + var entryPoints: [(path: String, identifier: String)] { + switch self { + case .browsee: + return ["Contents/Helpers/browsee-mcp", "Contents/MacOS/browsee-mcp"].map { ($0, "browsee-mcp") } + case .mesinyer: + return [("Contents/MacOS/Mesinyer", bundleID)] + } + } + + struct Installation { + let url: URL + let version: String + let advertisesStatus: Bool + let entryPoint: URL? + let verified: Bool + + var runningPIDs: Set { + Set(NSRunningApplication.runningApplications(withBundleIdentifier: bundleID) + .filter { $0.bundleURL?.resolvingSymlinksInPath() == url && !$0.isTerminated } + .map(\.processIdentifier)) + } + + fileprivate let bundleID: String + } + + func installation() -> Installation? { + let workspace = NSWorkspace.shared + let preferred = workspace.urlForApplication(withBundleIdentifier: bundleID) + let alternatives = workspace.urlsForApplications(withBundleIdentifier: bundleID) + let name = self == .browsee ? "browsee.app" : "Mesinyer.app" + let standard = [ + URL(fileURLWithPath: "/Applications", isDirectory: true), + FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Applications", isDirectory: true) + ].map { $0.appendingPathComponent(name, isDirectory: true) } + let candidates = [preferred].compactMap { $0 } + alternatives + standard + var checked = Set() + var firstIncompatible: Installation? + for candidate in candidates { + let url = candidate.resolvingSymlinksInPath().standardizedFileURL + guard checked.insert(url).inserted, + let bundle = Bundle(url: url), bundle.bundleIdentifier == bundleID else { continue } + let verified = Self.verifiedCode(url, identifier: bundleID) + let entryPoint = verified ? entryPoints.lazy.compactMap { point -> URL? in + let original = url.appendingPathComponent(point.path) + let resolved = original.resolvingSymlinksInPath() + guard resolved.path == original.path, + FileManager.default.isExecutableFile(atPath: resolved.path), + Self.verifiedCode(resolved, identifier: point.identifier) else { return nil } + return resolved + }.first : nil + let installation = Installation( + url: url, + version: bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "", + advertisesStatus: bundle.object(forInfoDictionaryKey: "DarkroomAppLinkVersion") as? Int == 1, + entryPoint: entryPoint, + verified: verified, + bundleID: bundleID + ) + if entryPoint != nil { return installation } + if firstIncompatible == nil || (firstIncompatible?.verified == false && verified) { + firstIncompatible = installation + } + } + return firstIncompatible + } + + private static func verifiedCode(_ url: URL, identifier: String) -> Bool { + var code: SecStaticCode? + var requirement: SecRequirement? + let flags = SecCSFlags(rawValue: 0) + // Check the code and signed Info.plist. Independently verify the nested executable + // we invoke, without walking unrelated assets in multi-gigabyte app bundles. + let validation = SecCSFlags(rawValue: UInt32(kSecCSDoNotValidateResources)).union(.noNetworkAccess) + let rule = "anchor apple generic and certificate leaf[subject.OU] = \"ZNHHMX2RP6\" and identifier \"\(identifier)\"" + guard SecStaticCodeCreateWithPath(url as CFURL, flags, &code) == errSecSuccess, + SecRequirementCreateWithString(rule as CFString, flags, &requirement) == errSecSuccess, + let code, let requirement else { return false } + return SecStaticCodeCheckValidity(code, validation, requirement) == errSecSuccess + } + + struct Identity: Codable { + let contract: Int + let app: String + let bundleID: String + let version: String + let state: String + let capabilities: [String] + + enum CodingKeys: String, CodingKey { + case contract, app, version, state, capabilities + case bundleID = "bundle_id" + } + } + + func status(validateEndpoint: ((Installation) -> Bool)? = nil) -> [String: Any] { + var record: [String: Any] = [ + "app": rawValue, "bundle_id": bundleID, "present": false, "running": false, + "state": "not_installed", "access": "unknown", "verified": false, "capabilities": [String]() + ] + guard let installed = installation() else { return record } + record["present"] = true + record["verified"] = installed.verified + record["running"] = !installed.runningPIDs.isEmpty + record["version"] = installed.version + record["path"] = installed.url.path + record["state"] = "incompatible" + guard installed.advertisesStatus, let helper = installed.entryPoint else { return record } + guard let data = Self.readCommand(helper, arguments: ["--app-link-status"]) else { + record["state"] = "unavailable" + return record + } + guard let identity = try? JSONDecoder().decode(Identity.self, from: data), + identity.contract == 1, identity.app == rawValue, identity.bundleID == bundleID, + ["ready", "not_running", "denied", "disabled", "incompatible"].contains(identity.state) else { + return record + } + if ["ready", "disabled"].contains(identity.state), validateEndpoint?(installed) == false { + record["state"] = "unavailable" + return record + } + record["state"] = identity.state + record["capabilities"] = identity.capabilities + switch identity.state { + case "ready": record["access"] = "allowed" + case "denied", "disabled": record["access"] = identity.state + default: break + } + return record + } + + static func readCommand(_ helper: URL, arguments: [String], byteLimit: Int = 16_384) -> Data? { + let process = Process() + let pipe = Pipe() + process.executableURL = helper + process.arguments = arguments + process.standardInput = FileHandle.nullDevice + process.standardOutput = pipe + process.standardError = FileHandle.nullDevice + guard (try? process.run()) != nil else { return nil } + + let fd = pipe.fileHandleForReading.fileDescriptor + guard fcntl(fd, F_SETFL, O_NONBLOCK) != -1 else { + kill(process.processIdentifier, SIGKILL) + return nil + } + let deadline = DispatchTime.now().uptimeNanoseconds + 1_000_000_000 + var data = Data() + var bytes = [UInt8](repeating: 0, count: 4096) + while DispatchTime.now().uptimeNanoseconds < deadline { + let count = read(fd, &bytes, bytes.count) + if count > 0 { + data.append(contentsOf: bytes.prefix(count)) + if data.count > byteLimit { break } + } else if count == 0 && !process.isRunning { + return process.terminationStatus == 0 ? data : nil + } else if count == 0 || errno == EAGAIN || errno == EINTR { + usleep(5_000) + } else { + break + } + } + if process.isRunning { kill(process.processIdentifier, SIGKILL) } + return nil + } + + static func execHelper(_ helper: URL, arguments: [String]) throws { + // The CLI ignores SIGPIPE. Restore the default before replacing the process. + signal(SIGPIPE, SIG_DFL) + let argv: [UnsafeMutablePointer?] = ([helper.path] + arguments).map { strdup($0) } + [nil] + execv(helper.path, argv) + let reason = String(cString: strerror(errno)) + argv.forEach { free($0) } + throw CLIError(message: "Could not run \(helper.path): \(reason)") + } +} + +extension ProgramaCLI { + func printAppLinkIdentity() throws { + let bundleID = "com.darkroom.programa" + let bundle = resolvedExecutableURL() + .map { $0.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() } + .flatMap { Bundle(url: $0) } + let state = programaAppLinkState(bundle: bundle, bundleID: bundleID) + let identity = DarkroomPeer.Identity( + contract: 1, app: "programa", bundleID: bundleID, + version: bundle?.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "", + state: state, capabilities: ["mcp.stdio"]) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + print(String(decoding: try encoder.encode(identity), as: UTF8.self)) + } + + private func programaAppLinkState(bundle: Bundle?, bundleID: String) -> String { + guard let bundle, bundle.bundleIdentifier == bundleID else { return "incompatible" } + let url = bundle.bundleURL.resolvingSymlinksInPath() + let pids = Set(NSRunningApplication.runningApplications(withBundleIdentifier: bundleID) + .filter { $0.bundleURL?.resolvingSymlinksInPath() == url && !$0.isTerminated } + .map(\.processIdentifier)) + guard !pids.isEmpty else { return "not_running" } + let client = SocketClient(path: CLISocketPathResolver.defaultSocketPath) + defer { client.close() } + do { + try client.connect() + guard let pid = client.peerProcessIdentifier(), pids.contains(pid) else { return "incompatible" } + _ = try client.sendV2(method: "system.ping", receiveTimeout: 0.25) + return "ready" + } catch let error as SocketConnectError where error.errnoValue == EACCES || error.errnoValue == EPERM { + return "denied" + } catch let error as SocketConnectError where error.isTransient { + return "not_running" + } catch let error as CLIError where error.message.hasPrefix("auth_required:") || error.message.hasPrefix("ERROR: Access denied") { + return "denied" + } catch { + return "incompatible" + } + } + + func runApps(arguments: [String], jsonOutput: Bool) throws { + switch arguments.first { + case "status": + guard arguments == ["status"] || arguments == ["status", "--json"] else { + throw CLIError(message: "Usage: programa apps status [--json]") + } + let records = DarkroomPeer.allCases.map { peer in + peer == .browsee + ? peer.status { self.browseeReadySocket(installation: $0) != nil } + : peer.status() + } + if jsonOutput || arguments.contains("--json") { + let data = try JSONSerialization.data(withJSONObject: ["contract": 1, "apps": records], options: [.sortedKeys, .withoutEscapingSlashes]) + print(String(decoding: data, as: UTF8.self)) + } else { + for record in records { + print("\(record["app"] ?? "") · \(record["state"] ?? "")") + } + } + case "mcp": + guard arguments.count == 4, arguments[2] == "--session", + let peer = DarkroomPeer(rawValue: arguments[1]), + arguments[3].hasPrefix("programa-"), UUID(uuidString: String(arguments[3].dropFirst(9))) != nil else { + throw CLIError(message: "Usage: programa apps mcp --session programa-") + } + if peer == .browsee { + try runBrowsee(arguments: ["mcp", "--session", arguments[3]]) + } else { + guard let install = peer.installation(), install.advertisesStatus, + let entryPoint = install.entryPoint else { + throw CLIError(message: "Mesinyer has no compatible signed MCP executable.") + } + try DarkroomPeer.execHelper(entryPoint, arguments: ["-mcp", "--session", arguments[3]]) + } + default: + throw CLIError(message: "Usage: programa apps status [--json]") + } + } +} diff --git a/CLI/CLI+Browsee.swift b/CLI/CLI+Browsee.swift index 99b9cb55..0e58f7c4 100644 --- a/CLI/CLI+Browsee.swift +++ b/CLI/CLI+Browsee.swift @@ -152,21 +152,37 @@ extension ProgramaCLI { return (try? FileManager.default.contentsOfDirectory(atPath: folder)) ?? [] } - private func browseeIsRunning() -> Bool { - BrowseeApp.probePaths(home: browseeHome, fallbackFolder: browseeFallbackFolder, listFolder: browseeOwnedFolderEntries) - .contains { browseeSocketAccepts($0) } + func browseeReadySocket(installation: DarkroomPeer.Installation?) -> String? { + let pids = installation?.runningPIDs + if pids?.isEmpty == true { return nil } + return BrowseeApp.probePaths(home: browseeHome, fallbackFolder: browseeFallbackFolder, listFolder: browseeOwnedFolderEntries) + .first { browseeSocketAccepts($0, pids: pids) } } - private func browseeInstallation() -> (app: String, helper: String)? { - BrowseeApp.installation(home: browseeHome) { FileManager.default.isExecutableFile(atPath: $0) } + private func browseeResolvedInstallation() -> DarkroomPeer.Installation? { + #if DEBUG + if ProcessInfo.processInfo.environment["PROGRAMA_BROWSEE_OPEN_FOR_TESTING"] != nil { return nil } + #endif + return DarkroomPeer.browsee.installation() + } + + func browseeInstallation() -> (app: String, helper: String)? { + #if DEBUG + if ProcessInfo.processInfo.environment["PROGRAMA_BROWSEE_OPEN_FOR_TESTING"] != nil { + return BrowseeApp.installation(home: browseeHome) { FileManager.default.isExecutableFile(atPath: $0) } + } + #endif + guard let installed = browseeResolvedInstallation(), let helper = installed.entryPoint else { return nil } + return (installed.url.path, helper.path) } /// Whether browsee's MCP socket accepts a connection, which is what "running" means. The /// probe closes without a session header; browsee drops such a connection. - private func browseeSocketAccepts(_ path: String) -> Bool { + private func browseeSocketAccepts(_ path: String, pids: Set?) -> Bool { let descriptor = socket(AF_UNIX, SOCK_STREAM, 0) guard descriptor >= 0 else { return false } defer { Darwin.close(descriptor) } + guard fcntl(descriptor, F_SETFL, O_NONBLOCK) != -1 else { return false } var address = sockaddr_un() address.sun_family = sa_family_t(AF_UNIX) let bytes = Array(path.utf8) @@ -175,15 +191,20 @@ extension ProgramaCLI { buffer.copyBytes(from: bytes) } address.sun_len = UInt8(MemoryLayout.size) - return withUnsafePointer(to: &address) { + let connected = withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(descriptor, $0, socklen_t(MemoryLayout.size)) == 0 } } + guard connected else { return false } + guard let pids else { return true } + var pid: pid_t = 0 + var length = socklen_t(MemoryLayout.size) + return getsockopt(descriptor, SOL_LOCAL, LOCAL_PEERPID, &pid, &length) == 0 && pids.contains(pid) } - /// `open -g -b`: LaunchServices starts browsee in the background without raising a window. - private func launchBrowseeInBackground() throws { + /// Launch the exact bundle resolved and verified above without raising a window. + private func launchBrowseeInBackground(installation: DarkroomPeer.Installation?) throws { let opener: String = { #if DEBUG // Tests replace the opener so they never start a real browsee. Release builds ignore it. @@ -195,12 +216,17 @@ extension ProgramaCLI { }() let process = Process() process.executableURL = URL(fileURLWithPath: opener) - process.arguments = ["-g", "-b", BrowseeApp.bundleIdentifier] + process.arguments = installation.map { ["-g", $0.url.path] } ?? ["-g", "-b", BrowseeApp.bundleIdentifier] // stdout is the MCP channel of the agent that started this command; keep it clean. process.standardOutput = FileHandle.standardError process.standardError = FileHandle.standardError try process.run() - process.waitUntilExit() + let deadline = DispatchTime.now() + .seconds(1) + while process.isRunning, DispatchTime.now() < deadline { usleep(5_000) } + if process.isRunning { + kill(process.processIdentifier, SIGKILL) + throw CLIError(message: "Launch Services did not respond while opening browsee.") + } guard process.terminationStatus == 0 else { throw CLIError(message: "Could not start browsee: open exited with status \(process.terminationStatus).") } @@ -209,30 +235,25 @@ extension ProgramaCLI { /// Becomes `browsee-mcp --session ` with this process's stdio. Starts browsee in the /// background first when its socket does not answer. Writes nothing to stdout. private func runBrowseeMCPServer(explicitSession: String?) throws { - guard let helper = browseeInstallation()?.helper else { - throw CLIError(message: "browsee is not installed: no browsee.app in ~/Applications or /Applications.") + let installed = browseeResolvedInstallation() + guard let helper = installed?.entryPoint ?? browseeInstallation().map({ URL(fileURLWithPath: $0.helper) }) else { + throw CLIError(message: "browsee not found with a compatible signed MCP helper.") } - if !browseeIsRunning() { - try launchBrowseeInBackground() - let deadline = Date().addingTimeInterval(BrowseeApp.launchWait) - var running = false - while !running, Date() < deadline { + var endpoint = browseeReadySocket(installation: installed) + if endpoint == nil { + try launchBrowseeInBackground(installation: installed) + let deadline = DispatchTime.now() + BrowseeApp.launchWait + while endpoint == nil, DispatchTime.now() < deadline { usleep(200_000) - running = browseeIsRunning() + endpoint = browseeReadySocket(installation: installed) } - guard running else { + guard endpoint != nil else { throw CLIError(message: "browsee did not start within \(Int(BrowseeApp.launchWait)) seconds. Open browsee, then restart this agent.") } } let session = BrowseeApp.session(explicit: explicitSession, environment: ProcessInfo.processInfo.environment) - // main() ignores SIGPIPE, and an ignored signal stays ignored across exec. - signal(SIGPIPE, SIG_DFL) - let arguments: [String] = [helper, "--session", session] - let argv: [UnsafeMutablePointer?] = arguments.map { strdup($0) } + [nil] - execv(helper, argv) - let reason = String(cString: strerror(errno)) - argv.forEach { free($0) } - throw CLIError(message: "Could not run \(helper): \(reason)") + let socket = installed.flatMap { _ in endpoint } + try DarkroomPeer.execHelper(helper, arguments: ["--session", session] + (socket.map { ["--socket", $0] } ?? [])) } /// Read from Claude Code's user config, not `claude mcp get`: that command health-checks the @@ -285,9 +306,10 @@ extension ProgramaCLI { try runBrowseeMCPServer(explicitSession: optionValue(arguments, name: "--session")) case "status": - let app = browseeInstallation()?.app + let installed = browseeResolvedInstallation() + let app = installed?.url.path ?? browseeInstallation()?.app print("browsee: \(app ?? "not found, install browsee.app in /Applications")") - print("Running: \(browseeIsRunning() ? "yes" : "no")") + print("Running: \(app != nil && browseeReadySocket(installation: installed) != nil ? "yes" : "no")") let programaCLI = resolvedExecutableURL()?.path browseePrintClientStatus(.claude, executable: resolveClaudeExecutable(searchPath: searchPath), programaCLI: programaCLI) browseePrintClientStatus(.codex, executable: resolveCodexExecutable(searchPath: searchPath), programaCLI: programaCLI) diff --git a/CLI/CLICommandDispatcher.swift b/CLI/CLICommandDispatcher.swift index 639e0a5c..e728fd45 100644 --- a/CLI/CLICommandDispatcher.swift +++ b/CLI/CLICommandDispatcher.swift @@ -167,6 +167,7 @@ struct CLICommandDispatcher { explicitPassword: socketPasswordArg ) return + case "apps": return try cli.runApps(arguments: commandArgs, jsonOutput: jsonOutput) case "browsee": try cli.runBrowsee(arguments: commandArgs) return diff --git a/CLI/Commands/LocalCommands.swift b/CLI/Commands/LocalCommands.swift index 1f5e5136..3aa00498 100644 --- a/CLI/Commands/LocalCommands.swift +++ b/CLI/Commands/LocalCommands.swift @@ -122,6 +122,14 @@ extension ProgramaCLI { grammar: integrationInstallGrammar, execute: nil ), + CommandDescriptor( + names: ["apps"], + helpLines: ["apps status [--json]"], + connectionPolicy: .local, + detailedUsage: "Usage: programa apps status [--json]\n\nReport installed Darkroom peers, readiness and access.", + grammar: CLIArgumentGrammar(valueOptions: ["session"], booleanOptions: ["json"], minPositionals: 1, maxPositionals: 2), + execute: nil + ), CommandDescriptor( names: ["browsee"], helpLines: ["browsee [--session ] [--yes]"], diff --git a/CLI/SocketClient.swift b/CLI/SocketClient.swift index 0ed0537a..5e5be03c 100644 --- a/CLI/SocketClient.swift +++ b/CLI/SocketClient.swift @@ -110,6 +110,13 @@ final class SocketClient { } } + func peerProcessIdentifier() -> pid_t? { + guard socketFD >= 0 else { return nil } + var pid: pid_t = 0 + var size = socklen_t(MemoryLayout.size) + return getsockopt(socketFD, SOL_LOCAL, LOCAL_PEERPID, &pid, &size) == 0 ? pid : nil + } + func close() { if socketFD >= 0 { Darwin.close(socketFD) diff --git a/CLI/programa.swift b/CLI/programa.swift index d3fc5244..f64de16e 100644 --- a/CLI/programa.swift +++ b/CLI/programa.swift @@ -2960,7 +2960,11 @@ struct ProgramaMain { _ = signal(SIGPIPE, SIG_IGN) let cli = ProgramaCLI(args: CommandLine.arguments) do { - try cli.run() + if CommandLine.arguments.dropFirst().elementsEqual(["--app-link-status"]) { + try cli.printAppLinkIdentity() + } else { + try cli.run() + } } catch { if jsonOutputRequested(CommandLine.arguments) { print(cli.jsonString(["ok": false, "error": jsonErrorObject(error)] as [String: Any])) diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index 2bc9207d..cc6b9aa8 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -337,6 +337,7 @@ 6C9DA4528D8FCFF501A5FA8C /* programa-mcp in Copy CLI */ = {isa = PBXBuildFile; fileRef = 0AC9A9E0A68EF163F87A0C83 /* programa-mcp */; }; B9000031A1B2C3D4E5F60719 /* CLI+Markdown.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9000030A1B2C3D4E5F60719 /* CLI+Markdown.swift */; }; B5EE07000000000000000001 /* CLI+Browsee.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5EE07000000000000000002 /* CLI+Browsee.swift */; }; + DA2185000000000000000001 /* CLI+Apps.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA2185000000000000000002 /* CLI+Apps.swift */; }; 1C1375000000000000000001 /* CLI+WelcomeShortcuts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C1375000000000000000002 /* CLI+WelcomeShortcuts.swift */; }; C0DE0C9A0000000000000001 /* CLI+CodexMCP.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE0C9A0000000000000002 /* CLI+CodexMCP.swift */; }; A5E100000000000000000001 /* CLI+OpenCodeMCP.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5E100000000000000000002 /* CLI+OpenCodeMCP.swift */; }; @@ -866,6 +867,7 @@ 30DC1E7B0A701824297403A5 /* FocusTools.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FocusTools.swift"; sourceTree = ""; }; B9000030A1B2C3D4E5F60719 /* CLI+Markdown.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CLI+Markdown.swift"; sourceTree = ""; }; B5EE07000000000000000002 /* CLI+Browsee.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CLI+Browsee.swift"; sourceTree = ""; }; + DA2185000000000000000002 /* CLI+Apps.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CLI+Apps.swift"; sourceTree = ""; }; 1C1375000000000000000002 /* CLI+WelcomeShortcuts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CLI+WelcomeShortcuts.swift"; sourceTree = ""; }; C0DE0C9A0000000000000002 /* CLI+CodexMCP.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CLI+CodexMCP.swift"; sourceTree = ""; }; A5E100000000000000000002 /* CLI+OpenCodeMCP.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CLI+OpenCodeMCP.swift"; sourceTree = ""; }; @@ -1402,6 +1404,7 @@ B9000001A1B2C3D4E5F60719 /* programa.swift */, B9000030A1B2C3D4E5F60719 /* CLI+Markdown.swift */, B5EE07000000000000000002 /* CLI+Browsee.swift */, + DA2185000000000000000002 /* CLI+Apps.swift */, 1C1375000000000000000002 /* CLI+WelcomeShortcuts.swift */, C0DE0C9A0000000000000002 /* CLI+CodexMCP.swift */, A5E100000000000000000002 /* CLI+OpenCodeMCP.swift */, @@ -2190,6 +2193,7 @@ FADE00000000000000000003 /* CLI+HookSettingsIO.swift in Sources */, FADE00000000000000000001 /* CLI+AgentDetection.swift in Sources */, B5EE07000000000000000001 /* CLI+Browsee.swift in Sources */, + DA2185000000000000000001 /* CLI+Apps.swift in Sources */, 1C1375000000000000000001 /* CLI+WelcomeShortcuts.swift in Sources */, C0DE0C9A0000000000000001 /* CLI+CodexMCP.swift in Sources */, A5E100000000000000000001 /* CLI+OpenCodeMCP.swift in Sources */, diff --git a/Resources/Info.plist b/Resources/Info.plist index 58823968..85bbd53f 100644 --- a/Resources/Info.plist +++ b/Resources/Info.plist @@ -2,6 +2,8 @@ + DarkroomAppLinkVersion + 1 CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleDisplayName diff --git a/contracts/link/v1/README.md b/contracts/link/v1/README.md index 62a262f9..1ff45373 100644 --- a/contracts/link/v1/README.md +++ b/contracts/link/v1/README.md @@ -14,6 +14,6 @@ Invoke the status entry point with `--app-link-status`, closed stdin and a bound | `disabled` | The user has disabled the relevant application or integration setting. | | `incompatible` | The app cannot speak this version of the contract or reports an incompatible endpoint. | -Installation, running process and access state are independent. `programa apps status --json` adds a top-level contract, an array of peer records, and flags for installation and an observed running production process. A missing bundle is `not_installed`. A failed probe may be `unavailable` and access remains unknown. Check again on every explicit inquiry or helper start so that restarting or moving a peer does not require updating agent configuration. +Installation, running process and access state are independent. `programa apps status --json` adds a top-level contract, an array of peer records, and flags for installation, bundle verification and an observed running production process. A missing bundle is `not_installed`. A failed probe may be `unavailable` and access remains unknown. Check again on every explicit inquiry or helper start so that restarting or moving a peer does not require updating agent configuration. Agents keep MCP over stdio. A Programa agent adapter can supply `--session programa-` as an explicit correlation value each time it starts the peer helper, including after an agent reconnect or resume. The value identifies a pane for routing and does not grant access. The owning app applies its existing access and content approval rules. From 487d597d546e6bbbe5e277bb0f0a2ecbf2018430 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:17:28 -0300 Subject: [PATCH 03/37] Scope agent MCP discovery to the Programa surface --- CLI/CLI+AgentWrappers.swift | 7 +- CLI/CLI+AppLinkAgents.swift | 126 ++++++++++++++++++++++++++ CLI/CLI+Apps.swift | 3 + GhosttyTabs.xcodeproj/project.pbxproj | 8 ++ Resources/bin/claude | 6 +- Resources/bin/codex | 36 ++++++++ 6 files changed, 182 insertions(+), 4 deletions(-) create mode 100644 CLI/CLI+AppLinkAgents.swift create mode 100755 Resources/bin/codex diff --git a/CLI/CLI+AgentWrappers.swift b/CLI/CLI+AgentWrappers.swift index 4e2a715e..e7c79122 100644 --- a/CLI/CLI+AgentWrappers.swift +++ b/CLI/CLI+AgentWrappers.swift @@ -34,10 +34,11 @@ extension ProgramaCLI { ) } - /// Resolves the `codex` CLI executable from PATH. Unlike Claude, Programa does not - /// ship a codex wrapper, so no skip predicate is needed. func resolveCodexExecutable(searchPath: String?) -> String? { - resolveExecutableInSearchPath("codex", searchPath: searchPath) + let bundledWrapper = resolvedExecutableURL()?.deletingLastPathComponent().appendingPathComponent("codex").path + return resolveExecutableInSearchPath("codex", searchPath: searchPath) { path in + URL(fileURLWithPath: path).resolvingSymlinksInPath().path == bundledWrapper + } } private func claudeTeamsHasExplicitTeammateMode(commandArgs: [String]) -> Bool { diff --git a/CLI/CLI+AppLinkAgents.swift b/CLI/CLI+AppLinkAgents.swift new file mode 100644 index 00000000..d72ad901 --- /dev/null +++ b/CLI/CLI+AppLinkAgents.swift @@ -0,0 +1,126 @@ +import Foundation + +extension ProgramaCLI { + func printAppLinkAgentConfig(for client: String) throws { + let environment = ProcessInfo.processInfo.environment + guard let surface = environment["PROGRAMA_SURFACE_ID"].flatMap(UUID.init(uuidString:)), + let executable = resolvedExecutableURL()?.path else { return } + let session = "programa-\(surface.uuidString)" + let peers = DarkroomPeer.allCases.filter { peer in + if peer == .browsee { return browseeInstallation() != nil } + guard let install = peer.installation() else { return false } + return install.entryPoint != nil && install.advertisesStatus + } + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + switch client { + case "claude": + guard let existing = claudeAppLinkRegistrations(environment: environment) else { return } + var servers: [String: [String: StringOrArguments]] = [:] + if FileManager.default.isExecutableFile(atPath: (executable as NSString).deletingLastPathComponent + "/programa-mcp") { + servers["programa"] = ["command": .string((executable as NSString).deletingLastPathComponent + "/programa-mcp")] + } + for peer in peers where existing[peer.rawValue]?.allSatisfy({ isOwnedBrowseeRegistration($0, peer: peer, executable: executable) }) != false { + servers[peer.rawValue] = [ + "command": .string(executable), + "args": .args(["apps", "mcp", peer.rawValue, "--session", session]) + ] + } + guard !servers.isEmpty else { return } + print(String(decoding: try encoder.encode(["mcpServers": servers]), as: UTF8.self)) + case "codex": + guard !peers.isEmpty, + let codex = resolveCodexExecutable(searchPath: environment["PATH"]), + let data = DarkroomPeer.readCommand(URL(fileURLWithPath: codex), arguments: ["mcp", "list", "--json"], byteLimit: 524_288), + let existing = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { return } + for peer in peers { + let args = String(decoding: try encoder.encode(["apps", "mcp", peer.rawValue, "--session", session]), as: UTF8.self) + if let entry = existing.first(where: { $0["name"] as? String == peer.rawValue }) { + guard entry["enabled"] as? Bool != false, + let transport = entry["transport"] as? [String: Any], + isOwnedBrowseeRegistration(transport, peer: peer, executable: executable) else { continue } + print("mcp_servers.\(peer.rawValue).args=\(args)") + continue + } + let command = String(decoding: try encoder.encode(executable), as: UTF8.self) + print("mcp_servers.\(peer.rawValue)={ command = \(command), args = \(args) }") + } + default: + throw CLIError(message: "Unknown MCP agent client: \(client)") + } + } + + private enum StringOrArguments: Encodable { + case string(String) + case args([String]) + + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .string(let value): try container.encode(value) + case .args(let value): try container.encode(value) + } + } + } + + /// The installer previously used a shared Codex session. Only replace that + /// exact registration (or its Claude counterpart) for this invocation. + private func isOwnedBrowseeRegistration(_ entry: [String: Any], peer: DarkroomPeer, executable: String) -> Bool { + guard peer == .browsee, let command = entry["command"] as? String, + URL(fileURLWithPath: command).resolvingSymlinksInPath().path == executable, + let args = entry["args"] as? [String], + (entry["env"] as? [String: String] ?? [:]).isEmpty, + (entry["env_vars"] as? [String] ?? []).isEmpty, + entry["cwd"] is NSNull || entry["cwd"] == nil, + entry["type"] == nil || entry["type"] as? String == "stdio" else { return false } + return args == ["browsee", "mcp"] || args == ["browsee", "mcp", "--session", "programa"] + } + + private func claudeAppLinkRegistrations(environment: [String: String]) -> [String: [[String: Any]]]? { + let fm = FileManager.default + let home = environment["CLAUDE_CONFIG_DIR"].flatMap { $0.isEmpty ? nil : Self.integrationExpandTilde($0) } + ?? Self.integrationExpandTilde("~") + var registrations: [String: [[String: Any]]] = [:] + func collect(_ root: [String: Any]) { + for (name, entry) in root["mcpServers"] as? [String: Any] ?? [:] { + registrations[name, default: []].append(entry as? [String: Any] ?? [:]) + } + for key in ["disabledMcpServers", "disabledMcpjsonServers"] { + for name in root[key] as? [String] ?? [] { + registrations[name, default: []].append([:]) + } + } + } + func readConfig(_ path: String) -> [String: Any]? { + guard fm.fileExists(atPath: path) else { return [:] } + guard let attributes = try? fm.attributesOfItem(atPath: path), + let size = attributes[.size] as? Int, size < 16 * 1024 * 1024, + let data = fm.contents(atPath: path) else { return nil } + return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] + } + guard let user = readConfig((home as NSString).appendingPathComponent(".claude.json")) else { return nil } + collect(user) + let settingsHome = environment["CLAUDE_CONFIG_DIR"].flatMap { $0.isEmpty ? nil : Self.integrationExpandTilde($0) } + ?? Self.integrationExpandTilde("~/.claude") + guard let settings = readConfig((settingsHome as NSString).appendingPathComponent("settings.json")), + let managed = readConfig("/Library/Application Support/ClaudeCode/managed-mcp.json") else { return nil } + collect(settings) + collect(managed) + let cwd = URL(fileURLWithPath: fm.currentDirectoryPath).resolvingSymlinksInPath() + let projects = user["projects"] as? [String: [String: Any]] ?? [:] + for (path, configuration) in projects where cwd.path == path || cwd.path.hasPrefix(path + "/") { + collect(configuration) + } + var folder = cwd + while true { + for name in [".mcp.json", ".claude/settings.json", ".claude/settings.local.json"] { + guard let config = readConfig(folder.appendingPathComponent(name).path) else { return nil } + collect(config) + } + let parent = folder.deletingLastPathComponent() + if parent.path == folder.path || folder.path == "/" { break } + folder = parent + } + return registrations + } +} diff --git a/CLI/CLI+Apps.swift b/CLI/CLI+Apps.swift index 5d8d68a6..9ff6b60e 100644 --- a/CLI/CLI+Apps.swift +++ b/CLI/CLI+Apps.swift @@ -250,6 +250,9 @@ extension ProgramaCLI { print("\(record["app"] ?? "") · \(record["state"] ?? "")") } } + case "agent-config": + guard arguments.count == 2 else { throw CLIError(message: "Missing agent client.") } + try printAppLinkAgentConfig(for: arguments[1]) case "mcp": guard arguments.count == 4, arguments[2] == "--session", let peer = DarkroomPeer(rawValue: arguments[1]), diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index cc6b9aa8..e249c463 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -338,6 +338,7 @@ B9000031A1B2C3D4E5F60719 /* CLI+Markdown.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9000030A1B2C3D4E5F60719 /* CLI+Markdown.swift */; }; B5EE07000000000000000001 /* CLI+Browsee.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5EE07000000000000000002 /* CLI+Browsee.swift */; }; DA2185000000000000000001 /* CLI+Apps.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA2185000000000000000002 /* CLI+Apps.swift */; }; + DB2185000000000000000001 /* CLI+AppLinkAgents.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB2185000000000000000002 /* CLI+AppLinkAgents.swift */; }; 1C1375000000000000000001 /* CLI+WelcomeShortcuts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C1375000000000000000002 /* CLI+WelcomeShortcuts.swift */; }; C0DE0C9A0000000000000001 /* CLI+CodexMCP.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE0C9A0000000000000002 /* CLI+CodexMCP.swift */; }; A5E100000000000000000001 /* CLI+OpenCodeMCP.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5E100000000000000000002 /* CLI+OpenCodeMCP.swift */; }; @@ -374,6 +375,7 @@ H1HK0002 /* HookInstallationCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = H1HK0001 /* HookInstallationCoordinator.swift */; }; B900000BA1B2C3D4E5F60719 /* programa in Copy CLI */ = {isa = PBXBuildFile; fileRef = B9000004A1B2C3D4E5F60719 /* programa */; }; C1ADE00002A1B2C3D4E5F719 /* claude in Copy CLI */ = {isa = PBXBuildFile; fileRef = C1ADE00001A1B2C3D4E5F719 /* claude */; }; + DC21850002A1B2C3D4E5F719 /* codex in Copy CLI */ = {isa = PBXBuildFile; fileRef = DC21850001A1B2C3D4E5F719 /* codex */; }; A6SC00000000000000000002 /* restore-node-options.cjs in Copy CLI */ = {isa = PBXBuildFile; fileRef = A6SC00000000000000000001 /* restore-node-options.cjs */; }; 84E00D47E4584162AE53BC8D /* xterm-ghostty in Resources */ = {isa = PBXBuildFile; fileRef = B2E7294509CC42FE9191870E /* xterm-ghostty */; }; A5002000 /* THIRD_PARTY_LICENSES.md in Resources */ = {isa = PBXBuildFile; fileRef = A5002001 /* THIRD_PARTY_LICENSES.md */; }; @@ -482,6 +484,7 @@ files = ( B900000BA1B2C3D4E5F60719 /* programa in Copy CLI */, C1ADE00002A1B2C3D4E5F719 /* claude in Copy CLI */, + DC21850002A1B2C3D4E5F719 /* codex in Copy CLI */, A6SC00000000000000000002 /* restore-node-options.cjs in Copy CLI */, 6C9DA4528D8FCFF501A5FA8C /* programa-mcp in Copy CLI */, ); @@ -838,6 +841,7 @@ A5001101 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; B2E7294509CC42FE9191870E /* xterm-ghostty */ = {isa = PBXFileReference; lastKnownFileType = file; path = "ghostty/terminfo/78/xterm-ghostty"; sourceTree = ""; }; C1ADE00001A1B2C3D4E5F719 /* claude */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "Resources/bin/claude"; sourceTree = SOURCE_ROOT; }; + DC21850001A1B2C3D4E5F719 /* codex */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "Resources/bin/codex"; sourceTree = SOURCE_ROOT; }; A6SC00000000000000000001 /* restore-node-options.cjs */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.javascript; path = "Resources/bin/restore-node-options.cjs"; sourceTree = SOURCE_ROOT; }; A5002001 /* THIRD_PARTY_LICENSES.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = THIRD_PARTY_LICENSES.md; sourceTree = SOURCE_ROOT; }; B9000001A1B2C3D4E5F60719 /* programa.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = programa.swift; sourceTree = ""; }; @@ -868,6 +872,7 @@ B9000030A1B2C3D4E5F60719 /* CLI+Markdown.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CLI+Markdown.swift"; sourceTree = ""; }; B5EE07000000000000000002 /* CLI+Browsee.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CLI+Browsee.swift"; sourceTree = ""; }; DA2185000000000000000002 /* CLI+Apps.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CLI+Apps.swift"; sourceTree = ""; }; + DB2185000000000000000002 /* CLI+AppLinkAgents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CLI+AppLinkAgents.swift"; sourceTree = ""; }; 1C1375000000000000000002 /* CLI+WelcomeShortcuts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CLI+WelcomeShortcuts.swift"; sourceTree = ""; }; C0DE0C9A0000000000000002 /* CLI+CodexMCP.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CLI+CodexMCP.swift"; sourceTree = ""; }; A5E100000000000000000002 /* CLI+OpenCodeMCP.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CLI+OpenCodeMCP.swift"; sourceTree = ""; }; @@ -1405,6 +1410,7 @@ B9000030A1B2C3D4E5F60719 /* CLI+Markdown.swift */, B5EE07000000000000000002 /* CLI+Browsee.swift */, DA2185000000000000000002 /* CLI+Apps.swift */, + DB2185000000000000000002 /* CLI+AppLinkAgents.swift */, 1C1375000000000000000002 /* CLI+WelcomeShortcuts.swift */, C0DE0C9A0000000000000002 /* CLI+CodexMCP.swift */, A5E100000000000000000002 /* CLI+OpenCodeMCP.swift */, @@ -1501,6 +1507,7 @@ A5002001 /* THIRD_PARTY_LICENSES.md */, AMDT000008 /* AgentDetection */, C1ADE00001A1B2C3D4E5F719 /* claude */, + DC21850001A1B2C3D4E5F719 /* codex */, A6SC00000000000000000001 /* restore-node-options.cjs */, DA7A10CA710E000000000001 /* Localizable.xcstrings */, DA7A10CA710E000000000002 /* InfoPlist.xcstrings */, @@ -2194,6 +2201,7 @@ FADE00000000000000000001 /* CLI+AgentDetection.swift in Sources */, B5EE07000000000000000001 /* CLI+Browsee.swift in Sources */, DA2185000000000000000001 /* CLI+Apps.swift in Sources */, + DB2185000000000000000001 /* CLI+AppLinkAgents.swift in Sources */, 1C1375000000000000000001 /* CLI+WelcomeShortcuts.swift in Sources */, C0DE0C9A0000000000000001 /* CLI+CodexMCP.swift in Sources */, A5E100000000000000000001 /* CLI+OpenCodeMCP.swift in Sources */, diff --git a/Resources/bin/claude b/Resources/bin/claude index 3639d968..b73618ee 100755 --- a/Resources/bin/claude +++ b/Resources/bin/claude @@ -299,7 +299,11 @@ INJECTED_ARGS+=(--settings "$HOOKS_JSON") # and the space form would swallow a following positional prompt. if [[ "$SKIP_MCP_CONFIG" == false && "$_claude_flags" == *" mcp-config "* ]] \ && PROGRAMA_MCP_BIN="$(resolve_programa_mcp_bin)"; then - INJECTED_ARGS+=("--mcp-config={\"mcpServers\":{\"programa\":{\"command\":\"$(json_escape "$PROGRAMA_MCP_BIN")\"}}}") + if APP_MCP_CONFIG="$("$PROGRAMA_CLAUDE_HOOK_PROGRAMA_BIN" apps agent-config claude 2>/dev/null)" && [[ -n "$APP_MCP_CONFIG" ]]; then + INJECTED_ARGS+=("--mcp-config=$APP_MCP_CONFIG") + else + INJECTED_ARGS+=("--mcp-config={\"mcpServers\":{\"programa\":{\"command\":\"$(json_escape "$PROGRAMA_MCP_BIN")\"}}}") + fi fi if [[ "$SKIP_SYSTEM_PROMPT" == false && "$_claude_flags" == *" append-system-prompt "* ]]; then diff --git a/Resources/bin/codex b/Resources/bin/codex new file mode 100755 index 00000000..1005724a --- /dev/null +++ b/Resources/bin/codex @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Programa Codex wrapper. Keep per-surface MCP settings scoped to this invocation. +self_dir="$(cd "$(dirname "$0")" && pwd -P)" || exit 127 +real_codex= +IFS=: read -r -a path_entries <<<"$PATH" +for dir in "${path_entries[@]}"; do + [[ -x "${dir:-.}/codex" ]] || continue + [[ "${dir:-.}/codex" -ef "$self_dir/codex" ]] && continue + real_codex="${dir:-.}/codex" + break +done +if [[ -z "$real_codex" ]]; then + printf '%s\n' 'Error: codex not found in PATH' >&2 + exit 127 +fi +if [[ -z "${PROGRAMA_SURFACE_ID:-}" || ! -x "$self_dir/programa" ]]; then + exec "$real_codex" "$@" +fi +case "${1:-}" in + mcp|mcp-server|login|logout|completion|sandbox|app-server|debug|apply|cloud|features|--help|-h|--version|-V) + exec "$real_codex" "$@" + ;; +esac +for arg in "$@"; do + case "$arg" in + mcp_servers.*|--config=mcp_servers.*|-cmcp_servers.*|--profile|--profile=*|-p|-p?*|-C|-C?*|--cd|--cd=*) + # Caller-provided config or alternate roots take precedence. + exec "$real_codex" "$@" + ;; + esac +done +options=() +while IFS= read -r line; do + [[ -n "$line" ]] && options+=(-c "$line") +done < <("$self_dir/programa" apps agent-config codex 2>/dev/null) +exec "$real_codex" "${options[@]}" "$@" From bbc843219d91ed804f0357216ec46b424f5f029a Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:18:05 -0300 Subject: [PATCH 04/37] Cover discovery status and scoped agent MCP launches --- tests/test_cli_browsee_integration.py | 55 ++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/tests/test_cli_browsee_integration.py b/tests/test_cli_browsee_integration.py index ff6808e6..07d5013d 100644 --- a/tests/test_cli_browsee_integration.py +++ b/tests/test_cli_browsee_integration.py @@ -67,6 +67,9 @@ elif args[:2] == ["mcp", "remove"]: if servers.pop(args[-1], None) is None: sys.exit("No MCP server named " + args[-1]) +elif args == ["mcp", "list", "--json"] and name == "codex": + print(json.dumps([{"name": key, "enabled": True, "transport": entry} for key, entry in servers.items()])) + sys.exit(0) elif args[:2] == ["mcp", "get"] and name == "codex": if args[2] not in servers: sys.exit(1) @@ -157,7 +160,9 @@ def close(self) -> None: if self.listener is not None: self.listener.close() - def run(self, *args: str, surface: str | None = None, timeout: int = 60) -> subprocess.CompletedProcess[str]: + def run( + self, *args: str, surface: str | None = None, timeout: int = 60, command: str = "browsee" + ) -> subprocess.CompletedProcess[str]: env = dict(os.environ) for key in STRIPPED_ENV: env.pop(key, None) @@ -171,7 +176,7 @@ def run(self, *args: str, surface: str | None = None, timeout: int = 60) -> subp if surface is not None: env["PROGRAMA_SURFACE_ID"] = surface return subprocess.run( - [str(self.cli), "browsee", *args], + [str(self.cli), command, *args], stdin=subprocess.DEVNULL, capture_output=True, text=True, check=False, timeout=timeout, env=env, ) @@ -337,6 +342,52 @@ def test_mcp_with_a_long_home_finds_a_running_browsee_in_the_fallback_folder(sel self.assertEqual(box.log("open.log"), [], "a running browsee is not launched again") self.assertEqual(box.log("helper.log"), [f"--session programa-{SURFACE_ID}"]) + def test_discovery_status_is_json_and_does_not_launch_or_register_apps(self) -> None: + box = self.sandbox() + proc = box.run("status", "--json", command="apps") + self.assertOK(proc) + report = json.loads(proc.stdout) + self.assertEqual(report["contract"], 1) + self.assertEqual([app["app"] for app in report["apps"]], ["browsee", "mesinyer"]) + for app in report["apps"]: + self.assertIsInstance(app["present"], bool) + self.assertIsInstance(app["running"], bool) + self.assertIn(app["access"], {"unknown", "allowed", "denied", "disabled"}) + self.assertEqual(box.log("open.log"), []) + self.assertEqual(box.calls("claude") + box.calls("codex"), []) + + def test_agent_configs_keep_owned_browser_surface_and_preserve_custom_servers(self) -> None: + box = self.sandbox() + args = ["apps", "mcp", "browsee", "--session", f"programa-{SURFACE_ID}"] + proc = box.run("agent-config", "claude", surface=SURFACE_ID, command="apps") + self.assertOK(proc) + self.assertEqual(json.loads(proc.stdout)["mcpServers"]["browsee"]["args"], args) + proc = box.run("agent-config", "codex", surface=SURFACE_ID, command="apps") + self.assertOK(proc) + self.assertIn(f"args = {json.dumps(args, separators=(',', ':'))}", proc.stdout) + + custom = {"type": "stdio", "command": "/custom/browsee", "args": [], "env": {}} + box.write_servers("claude", {"browsee": custom}) + box.write_servers("codex", {"browsee": custom}) + for client in ("claude", "codex"): + proc = box.run("agent-config", client, surface=SURFACE_ID, command="apps") + self.assertOK(proc) + self.assertNotIn("browsee", proc.stdout) + self.assertEqual(box.servers(client)["browsee"], custom) + + def test_explicit_browsee_surface_is_reused_after_endpoint_restart(self) -> None: + box = self.sandbox() + box.start_browsee() + supplied = f"programa-{SURFACE_ID}" + for attempt in range(2): + with self.subTest(attempt=attempt): + proc = box.run("mcp", "browsee", "--session", supplied, command="apps") + self.assertOK(proc) + self.assertEqual(box.log("helper.log"), [f"--session {supplied}"]) + box.close() + box.socket_path.unlink() + box.start_browsee() + def test_mcp_fails_clearly_when_browsee_never_starts(self) -> None: box = self.sandbox() started = time.monotonic() From 6819ca3ee323cfa9649d8aab30fe16c4d3123512 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:18:39 -0300 Subject: [PATCH 05/37] Document automatic app discovery in Programa terminals --- CLI/Commands/LocalCommands.swift | 6 +++--- SKILL.md | 2 +- docs/agent-skill.md | 2 +- docs/browsee.md | 37 ++++++++++++++------------------ 4 files changed, 21 insertions(+), 26 deletions(-) diff --git a/CLI/Commands/LocalCommands.swift b/CLI/Commands/LocalCommands.swift index 3aa00498..12ccb56d 100644 --- a/CLI/Commands/LocalCommands.swift +++ b/CLI/Commands/LocalCommands.swift @@ -146,9 +146,9 @@ extension ProgramaCLI { `mcp` is the server the clients run: it starts browsee in the background when it is closed, waits up to 8 seconds for it, then runs browsee-mcp. - Inside a Programa pane the session is `programa-`, so each - pane's agent sees only the tabs it opened; elsewhere, and in Codex, it is - `programa`. `--session` overrides it. browsee serves these sessions only + Programa's Claude Code and Codex launchers use `programa-`, + so each pane's agent sees only the tabs it opened. The persistent installer + uses a shared session outside Programa. browsee serves these sessions only while "Let other apps control my tabs" is on in its Agents settings. """, grammar: CLIArgumentGrammar(valueOptions: ["session"], booleanOptions: ["yes", "y"], minPositionals: 1, maxPositionals: 2, shortFlags: ["-y"], validate: { command, parsed in diff --git a/SKILL.md b/SKILL.md index b292312a..3288f3e7 100644 --- a/SKILL.md +++ b/SKILL.md @@ -273,7 +273,7 @@ Do not reach for a Chrome extension. Programa has no built-in browser; browser w - **Previews, smoke tests, screenshots, DOM checks, console errors, logged-in sites, private dashboards, CI logs:** use the tools of the `browsee` MCP server if it is registered. They open tabs in browsee, read them and click. You see only the tabs you opened, and browsee asks the user before purchases, deletes, sign-ins and closing their tabs. A closed browsee starts in the background. - If browsee refuses the connection, ask the user to turn on "Let other apps control my tabs" in browsee > Settings > Agents. -- `programa browsee status` says whether browsee is installed, running and registered; `programa browsee install-mcp` registers it with Claude Code and Codex. Do not run the installer yourself unless the user asks, it edits their agent config. +- `programa apps status --json` reports whether Browsee and Mesinyer are installed, running and accessible. Claude Code and Codex launched through Programa discover the apps when they start. The separate `programa browsee install-mcp` command writes a persistent registration for use outside Programa. Run it only when the user requests a config edit. ## Reference diff --git a/docs/agent-skill.md b/docs/agent-skill.md index a30c94a0..7a79fba5 100644 --- a/docs/agent-skill.md +++ b/docs/agent-skill.md @@ -45,7 +45,7 @@ The first thing the skill does is check `PROGRAMA_SURFACE_ID` and `PROGRAMA_SOCK - **Authoring screen-detection manifests for an unsupported agent** — programa's agent-state detection reads a pane's own lifecycle hooks when available (Claude Code, Codex, OpenCode), and otherwise falls back to regex-matching visible screen text against a manifest. For any other agent, `programa agent-detection scaffold ` captures the current screen and writes a starter manifest to `~/.config/programa/agent-detection/.json`; fill in its `patterns` arrays, then `programa agent-detection test ` to check them against the live screen. `programa agent-detection list` shows every loaded manifest (bundled + your overrides). - **Reporting a normalized lifecycle event** — `programa agent-event --event [--provider

] [--session-id ] [--workspace ] [--surface ]` reports one of the structured events documented in `docs/plans/agent-events.md` (`session.started`, `turn.started`, `request.opened`, `user-input.requested`, `turn.completed`, `session.exited`, and the rest) instead of a bare `working`/`blocked`/`idle` string. It's what the shipped Claude Code/Codex/OpenCode hooks call internally; use it directly only if you're wiring a new provider's hook or testing the event path by hand — reach for `set-status` for everything else. - **Writing a recap** — when the user asks for a summary of a change, write markdown to `.programa/recaps/.md` and open it with `programa recap open ` (`programa recap list` shows what's saved). The markdown panel renders mermaid diagrams, GitHub-style alerts, and `:::compare` before/after blocks, so the skill tells the agent to reach for those instead of plain prose when they fit. -- **Browser work** — browsee, through its MCP server, handles previews, smoke tests and logged-in sites. `programa browsee install-mcp` registers browsee with Claude Code and Codex. See [`docs/browsee.md`](browsee.md). +- **Browser work** — browsee, through its MCP server, handles previews, smoke tests and logged-in sites. Programa discovers Browsee for Claude Code and Codex when they start inside a pane. See [`docs/browsee.md`](browsee.md). ## Verifying it diff --git a/docs/browsee.md b/docs/browsee.md index ba42c78b..bfc53fd6 100644 --- a/docs/browsee.md +++ b/docs/browsee.md @@ -8,38 +8,33 @@ of a Chrome extension. ## Setup +In a Programa terminal, the bundled Claude Code and Codex launchers discover and register +the installed production browsee for that invocation. Custom browsee registrations keep +their settings. Enable **Let other apps control my tabs** in Browsee > Settings > Agents +to let the terminal's agents connect. + ```bash -programa browsee status # where browsee is, whether it is running, what is registered where -programa browsee install-mcp # registers `browsee` with Claude Code and Codex -programa browsee uninstall-mcp +programa apps status --json # discover Browsee and Mesinyer and check access +programa browsee status # show the legacy registration for each agent ``` -In **Settings → Integrations**, choose **Install…** next to **browsee MCP** to run the -installer in a new workspace. The installer -lists the `claude mcp add` and `codex mcp add` commands it will run and asks first; `--yes` -skips the question. A `browsee` entry that runs anything else, such as `browsee-mcp` directly -or a Programa that has since moved, is replaced: the preview shows the old and the new -command. Agents pick up the server the next time they start. - -Then turn on **Let other apps control my tabs** in browsee > Settings > Agents. browsee -serves no agent it did not start while that setting is off, and `browsee-mcp` says so. +Outside Programa, use `programa browsee install-mcp` to register browsee persistently with +Claude Code and Codex. It previews changes and asks first. `programa browsee uninstall-mcp` +removes the registration. **Settings → Integrations → browsee MCP** opens the installer in +a new workspace. ## What the agent gets -Both clients run `programa browsee mcp`, which runs `browsee-mcp` from -`browsee.app/Contents/MacOS/` (looked up in `~/Applications`, then `/Applications`): - -- **One session per pane.** Inside a Programa pane the session is `programa-`, - so each pane's agent sees and acts only on the tabs it opened. Codex hands MCP servers a - filtered environment without the surface id, so every Codex agent shares the session - `programa`. The tabs show in browsee as agent tabs. +- **One session per pane.** Programa passes `programa-` explicitly to both + bundled launchers, including when an agent resumes. Each pane has its own browser tabs. + The tabs show in Browsee as agent tabs. - **browsee's rules stay on.** These sessions are ask-first, and no setting changes that. Purchases, deletes, sign-ins and closing one of your tabs always ask, on the Mac, in browsee. With "Let agents see my other tabs" on, the agent also sees your tabs, and closing one asks. - **A closed browsee starts.** When browsee's socket does not answer, the server starts - browsee in the background (`open -g -b com.darkroom.browsee`), waits up to 8 seconds for - it, and then connects. If browsee never comes up, the server fails with an error that says + the verified app in the background, waits up to 8 seconds for its MCP socket, and connects. + Launch Services can find the production bundle after a move. If browsee never comes up, the server fails with an error that says so, and the agent reports the `browsee` server as failed. While "Let other apps control my tabs" is on, any process running as you can connect to From 1332b24cb23a6b588ff32b7fe5d7013a0374caea Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:20:38 -0300 Subject: [PATCH 06/37] Prepare Programa iPhone Shipit release configuration --- docs/release.md | 19 +++++++++++++++++++ ship.ios.json | 1 + 2 files changed, 20 insertions(+) diff --git a/docs/release.md b/docs/release.md index 892a9f34..11f2c337 100644 --- a/docs/release.md +++ b/docs/release.md @@ -59,6 +59,25 @@ Connect API key, so there are no distribution certificate or profile secrets. - **Internal only.** Builds are exported with `testFlightInternalTestingOnly`. They reach internal testers without Beta App Review and can never be submitted to the App Store. +### iPhone App Store preparation + +`ship.ios.json` is the Shipit manifest for the iPhone companion. It keeps the iPhone +marketing version independent of the desktop version. Its `githubRunAttempt` policy +matches the TestFlight build number above, including reruns. Use a Shipit revision +that supports this policy. + +Before switching internal TestFlight to Shipit, export an internal-only build on the +protected release runner and compare it with the current workflow. Compare the same +commit, bundle ID, version, build number, Apple team, signing entitlements and embedded +provisioning profile. Install the result through internal TestFlight and verify QR +pairing and a round trip with a running Mac. Keep one publisher for the internal track. + +The public listing uses a separate review build from `ship --config ship.ios.json release ios` +on protected release CI. Share a working review pairing experience without relying on a +Darkroom member’s computer or credentials. Confirm the App Store Connect record, privacy +and support metadata, and review access before submission. Keep manual release in App +Store Connect until review and the intended availability have been confirmed. + ## ship (shipit) `ship.json` at the repository root describes Programa for diff --git a/ship.ios.json b/ship.ios.json index 44e7faad..16f22a2f 100644 --- a/ship.ios.json +++ b/ship.ios.json @@ -1,5 +1,6 @@ { "name": "Programa iPhone Companion", + "buildNumber": "githubRunAttempt", "version": { "file": "ios/project.yml", "yaml": "targets.Programa.settings.base.MARKETING_VERSION" }, "notesPaths": ["ios", "MobileChat", "Sources/MobileChatCompanionView.swift", "Sources/MobileChatHost.swift", "Sources/MobileChatJobs.swift"], "ios": { From edc0841f5a5cfe508e70b63db1edf6c827a607ba Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:25:23 -0300 Subject: [PATCH 07/37] Share typed app discovery between Programa and its CLI --- CLI/CLI+Apps.swift | 202 ++----------------- CLI/CLI+Browsee.swift | 58 +----- GhosttyTabs.xcodeproj/project.pbxproj | 6 + Sources/DarkroomAppDiscovery.swift | 272 ++++++++++++++++++++++++++ 4 files changed, 293 insertions(+), 245 deletions(-) create mode 100644 Sources/DarkroomAppDiscovery.swift diff --git a/CLI/CLI+Apps.swift b/CLI/CLI+Apps.swift index 9ff6b60e..c00779e1 100644 --- a/CLI/CLI+Apps.swift +++ b/CLI/CLI+Apps.swift @@ -1,185 +1,14 @@ import AppKit import Darwin import Foundation -import Security -enum DarkroomPeer: String, CaseIterable { - case browsee - case mesinyer - - var bundleID: String { - switch self { - case .browsee: return "com.darkroom.browsee" - case .mesinyer: return "engineering.darkroom.mesinyer" - } - } - - var entryPoints: [(path: String, identifier: String)] { - switch self { - case .browsee: - return ["Contents/Helpers/browsee-mcp", "Contents/MacOS/browsee-mcp"].map { ($0, "browsee-mcp") } - case .mesinyer: - return [("Contents/MacOS/Mesinyer", bundleID)] - } - } - - struct Installation { - let url: URL - let version: String - let advertisesStatus: Bool - let entryPoint: URL? - let verified: Bool - - var runningPIDs: Set { - Set(NSRunningApplication.runningApplications(withBundleIdentifier: bundleID) - .filter { $0.bundleURL?.resolvingSymlinksInPath() == url && !$0.isTerminated } - .map(\.processIdentifier)) - } - - fileprivate let bundleID: String - } - - func installation() -> Installation? { - let workspace = NSWorkspace.shared - let preferred = workspace.urlForApplication(withBundleIdentifier: bundleID) - let alternatives = workspace.urlsForApplications(withBundleIdentifier: bundleID) - let name = self == .browsee ? "browsee.app" : "Mesinyer.app" - let standard = [ - URL(fileURLWithPath: "/Applications", isDirectory: true), - FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Applications", isDirectory: true) - ].map { $0.appendingPathComponent(name, isDirectory: true) } - let candidates = [preferred].compactMap { $0 } + alternatives + standard - var checked = Set() - var firstIncompatible: Installation? - for candidate in candidates { - let url = candidate.resolvingSymlinksInPath().standardizedFileURL - guard checked.insert(url).inserted, - let bundle = Bundle(url: url), bundle.bundleIdentifier == bundleID else { continue } - let verified = Self.verifiedCode(url, identifier: bundleID) - let entryPoint = verified ? entryPoints.lazy.compactMap { point -> URL? in - let original = url.appendingPathComponent(point.path) - let resolved = original.resolvingSymlinksInPath() - guard resolved.path == original.path, - FileManager.default.isExecutableFile(atPath: resolved.path), - Self.verifiedCode(resolved, identifier: point.identifier) else { return nil } - return resolved - }.first : nil - let installation = Installation( - url: url, - version: bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "", - advertisesStatus: bundle.object(forInfoDictionaryKey: "DarkroomAppLinkVersion") as? Int == 1, - entryPoint: entryPoint, - verified: verified, - bundleID: bundleID - ) - if entryPoint != nil { return installation } - if firstIncompatible == nil || (firstIncompatible?.verified == false && verified) { - firstIncompatible = installation - } - } - return firstIncompatible - } - - private static func verifiedCode(_ url: URL, identifier: String) -> Bool { - var code: SecStaticCode? - var requirement: SecRequirement? - let flags = SecCSFlags(rawValue: 0) - // Check the code and signed Info.plist. Independently verify the nested executable - // we invoke, without walking unrelated assets in multi-gigabyte app bundles. - let validation = SecCSFlags(rawValue: UInt32(kSecCSDoNotValidateResources)).union(.noNetworkAccess) - let rule = "anchor apple generic and certificate leaf[subject.OU] = \"ZNHHMX2RP6\" and identifier \"\(identifier)\"" - guard SecStaticCodeCreateWithPath(url as CFURL, flags, &code) == errSecSuccess, - SecRequirementCreateWithString(rule as CFString, flags, &requirement) == errSecSuccess, - let code, let requirement else { return false } - return SecStaticCodeCheckValidity(code, validation, requirement) == errSecSuccess - } - - struct Identity: Codable { - let contract: Int - let app: String - let bundleID: String - let version: String - let state: String - let capabilities: [String] - - enum CodingKeys: String, CodingKey { - case contract, app, version, state, capabilities - case bundleID = "bundle_id" - } - } - - func status(validateEndpoint: ((Installation) -> Bool)? = nil) -> [String: Any] { - var record: [String: Any] = [ - "app": rawValue, "bundle_id": bundleID, "present": false, "running": false, - "state": "not_installed", "access": "unknown", "verified": false, "capabilities": [String]() - ] - guard let installed = installation() else { return record } - record["present"] = true - record["verified"] = installed.verified - record["running"] = !installed.runningPIDs.isEmpty - record["version"] = installed.version - record["path"] = installed.url.path - record["state"] = "incompatible" - guard installed.advertisesStatus, let helper = installed.entryPoint else { return record } - guard let data = Self.readCommand(helper, arguments: ["--app-link-status"]) else { - record["state"] = "unavailable" - return record - } - guard let identity = try? JSONDecoder().decode(Identity.self, from: data), - identity.contract == 1, identity.app == rawValue, identity.bundleID == bundleID, - ["ready", "not_running", "denied", "disabled", "incompatible"].contains(identity.state) else { - return record - } - if ["ready", "disabled"].contains(identity.state), validateEndpoint?(installed) == false { - record["state"] = "unavailable" - return record - } - record["state"] = identity.state - record["capabilities"] = identity.capabilities - switch identity.state { - case "ready": record["access"] = "allowed" - case "denied", "disabled": record["access"] = identity.state - default: break - } - return record - } - - static func readCommand(_ helper: URL, arguments: [String], byteLimit: Int = 16_384) -> Data? { - let process = Process() - let pipe = Pipe() - process.executableURL = helper - process.arguments = arguments - process.standardInput = FileHandle.nullDevice - process.standardOutput = pipe - process.standardError = FileHandle.nullDevice - guard (try? process.run()) != nil else { return nil } - - let fd = pipe.fileHandleForReading.fileDescriptor - guard fcntl(fd, F_SETFL, O_NONBLOCK) != -1 else { - kill(process.processIdentifier, SIGKILL) - return nil - } - let deadline = DispatchTime.now().uptimeNanoseconds + 1_000_000_000 - var data = Data() - var bytes = [UInt8](repeating: 0, count: 4096) - while DispatchTime.now().uptimeNanoseconds < deadline { - let count = read(fd, &bytes, bytes.count) - if count > 0 { - data.append(contentsOf: bytes.prefix(count)) - if data.count > byteLimit { break } - } else if count == 0 && !process.isRunning { - return process.terminationStatus == 0 ? data : nil - } else if count == 0 || errno == EAGAIN || errno == EINTR { - usleep(5_000) - } else { - break - } - } - if process.isRunning { kill(process.processIdentifier, SIGKILL) } - return nil - } +private struct AppDiscoveryReport: Encodable { + let contract = 1 + let apps: [DarkroomPeer.Status] +} - static func execHelper(_ helper: URL, arguments: [String]) throws { +extension ProgramaCLI { + func execAppLinkHelper(_ helper: URL, arguments: [String]) throws { // The CLI ignores SIGPIPE. Restore the default before replacing the process. signal(SIGPIPE, SIG_DFL) let argv: [UnsafeMutablePointer?] = ([helper.path] + arguments).map { strdup($0) } + [nil] @@ -188,9 +17,7 @@ enum DarkroomPeer: String, CaseIterable { argv.forEach { free($0) } throw CLIError(message: "Could not run \(helper.path): \(reason)") } -} -extension ProgramaCLI { func printAppLinkIdentity() throws { let bundleID = "com.darkroom.programa" let bundle = resolvedExecutableURL() @@ -237,18 +64,13 @@ extension ProgramaCLI { guard arguments == ["status"] || arguments == ["status", "--json"] else { throw CLIError(message: "Usage: programa apps status [--json]") } - let records = DarkroomPeer.allCases.map { peer in - peer == .browsee - ? peer.status { self.browseeReadySocket(installation: $0) != nil } - : peer.status() - } + let records = DarkroomPeer.allCases.map { $0.status() } if jsonOutput || arguments.contains("--json") { - let data = try JSONSerialization.data(withJSONObject: ["contract": 1, "apps": records], options: [.sortedKeys, .withoutEscapingSlashes]) - print(String(decoding: data, as: UTF8.self)) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + print(String(decoding: try encoder.encode(AppDiscoveryReport(apps: records)), as: UTF8.self)) } else { - for record in records { - print("\(record["app"] ?? "") · \(record["state"] ?? "")") - } + for record in records { print("\(record.app) · \(record.state.rawValue)") } } case "agent-config": guard arguments.count == 2 else { throw CLIError(message: "Missing agent client.") } @@ -266,7 +88,7 @@ extension ProgramaCLI { let entryPoint = install.entryPoint else { throw CLIError(message: "Mesinyer has no compatible signed MCP executable.") } - try DarkroomPeer.execHelper(entryPoint, arguments: ["-mcp", "--session", arguments[3]]) + try execAppLinkHelper(entryPoint, arguments: ["-mcp", "--session", arguments[3]]) } default: throw CLIError(message: "Usage: programa apps status [--json]") diff --git a/CLI/CLI+Browsee.swift b/CLI/CLI+Browsee.swift index 0e58f7c4..0ced758f 100644 --- a/CLI/CLI+Browsee.swift +++ b/CLI/CLI+Browsee.swift @@ -12,9 +12,6 @@ enum BrowseeApp { /// Kept under Codex's default 10 s MCP startup timeout, so a launch that never finishes /// reports this command's error instead of the client's timeout. static let launchWait: TimeInterval = 8 - static let socketRelativePath = "Library/Application Support/browsee/mcp.sock" - /// macOS `sun_path` holds 104 bytes including the terminating NUL. - static let sunPathBytes = 104 static func installation(home: String?, isExecutable: (String) -> Bool) -> (app: String, helper: String)? { var candidates = ["/Applications/browsee.app"] @@ -30,18 +27,6 @@ enum BrowseeApp { return nil } - /// The sockets whose answer means browsee runs. A socket path that does not fit `sun_path` - /// moves to a hashed name in browsee's fallback folder, `/tmp/browsee-/` (`socket_path` - /// in browsee-mcp). Only browsee's MCP sockets live there, so any socket in it counts. - static func probePaths(home: String, fallbackFolder: String, listFolder: (String) -> [String]) -> [String] { - let natural = (home as NSString).appendingPathComponent(socketRelativePath) - if natural.utf8.count < sunPathBytes { return [natural] } - return listFolder(fallbackFolder) - .filter { $0.hasSuffix(".sock") } - .sorted() - .map { (fallbackFolder as NSString).appendingPathComponent($0) } - } - /// `programa-` inside a Programa pane, so each pane's agent sees only the tabs /// it opened; `sharedSession` elsewhere. browsee accepts 1-128 letters, digits, `-`, `_`, `.`. static func session(explicit: String?, environment: [String: String]) -> String { @@ -145,18 +130,8 @@ extension ProgramaCLI { return "/tmp/browsee-\(geteuid())" } - /// The folder's entries, or none unless it is a directory this user owns, as browsee requires. - private func browseeOwnedFolderEntries(_ folder: String) -> [String] { - var info = stat() - guard lstat(folder, &info) == 0, info.st_mode & S_IFMT == S_IFDIR, info.st_uid == geteuid() else { return [] } - return (try? FileManager.default.contentsOfDirectory(atPath: folder)) ?? [] - } - - func browseeReadySocket(installation: DarkroomPeer.Installation?) -> String? { - let pids = installation?.runningPIDs - if pids?.isEmpty == true { return nil } - return BrowseeApp.probePaths(home: browseeHome, fallbackFolder: browseeFallbackFolder, listFolder: browseeOwnedFolderEntries) - .first { browseeSocketAccepts($0, pids: pids) } + private func browseeReadySocket(installation: DarkroomPeer.Installation?) -> String? { + BrowseeSocket.endpoint(pids: installation?.runningPIDs, home: browseeHome, fallbackFolder: browseeFallbackFolder) } private func browseeResolvedInstallation() -> DarkroomPeer.Installation? { @@ -176,33 +151,6 @@ extension ProgramaCLI { return (installed.url.path, helper.path) } - /// Whether browsee's MCP socket accepts a connection, which is what "running" means. The - /// probe closes without a session header; browsee drops such a connection. - private func browseeSocketAccepts(_ path: String, pids: Set?) -> Bool { - let descriptor = socket(AF_UNIX, SOCK_STREAM, 0) - guard descriptor >= 0 else { return false } - defer { Darwin.close(descriptor) } - guard fcntl(descriptor, F_SETFL, O_NONBLOCK) != -1 else { return false } - var address = sockaddr_un() - address.sun_family = sa_family_t(AF_UNIX) - let bytes = Array(path.utf8) - guard bytes.count < MemoryLayout.size(ofValue: address.sun_path) else { return false } - withUnsafeMutableBytes(of: &address.sun_path) { buffer in - buffer.copyBytes(from: bytes) - } - address.sun_len = UInt8(MemoryLayout.size) - let connected = withUnsafePointer(to: &address) { - $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { - connect(descriptor, $0, socklen_t(MemoryLayout.size)) == 0 - } - } - guard connected else { return false } - guard let pids else { return true } - var pid: pid_t = 0 - var length = socklen_t(MemoryLayout.size) - return getsockopt(descriptor, SOL_LOCAL, LOCAL_PEERPID, &pid, &length) == 0 && pids.contains(pid) - } - /// Launch the exact bundle resolved and verified above without raising a window. private func launchBrowseeInBackground(installation: DarkroomPeer.Installation?) throws { let opener: String = { @@ -253,7 +201,7 @@ extension ProgramaCLI { } let session = BrowseeApp.session(explicit: explicitSession, environment: ProcessInfo.processInfo.environment) let socket = installed.flatMap { _ in endpoint } - try DarkroomPeer.execHelper(helper, arguments: ["--session", session] + (socket.map { ["--socket", $0] } ?? [])) + try execAppLinkHelper(helper, arguments: ["--session", session] + (socket.map { ["--socket", $0] } ?? [])) } /// Read from Claude Code's user config, not `claude mcp get`: that command health-checks the diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index e249c463..f0c96695 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -182,6 +182,8 @@ 7B3F9A10C2D4E5F6A7B80002 /* ListeningProcess.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B3F9A10C2D4E5F6A7B80001 /* ListeningProcess.swift */; }; 7B3F9A10C2D4E5F6A7B80004 /* PortsHubStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B3F9A10C2D4E5F6A7B80003 /* PortsHubStore.swift */; }; E0A1B2C3D4E5F6071800A002 /* ExternalOpenPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0A1B2C3D4E5F6071800A001 /* ExternalOpenPolicy.swift */; }; + EE2190000000000000000002 /* DarkroomAppDiscovery.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE2190000000000000000001 /* DarkroomAppDiscovery.swift */; }; + EE2190000000000000000003 /* DarkroomAppDiscovery.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE2190000000000000000001 /* DarkroomAppDiscovery.swift */; }; 7B3F9A10C2D4E5F6A7B80006 /* PortsHubView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B3F9A10C2D4E5F6A7B80005 /* PortsHubView.swift */; }; 7B3F9A10C2D4E5F6A7B80008 /* TerminalController+Ports.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B3F9A10C2D4E5F6A7B80007 /* TerminalController+Ports.swift */; }; A5001542 /* TerminalPasteboardPlanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001544 /* TerminalPasteboardPlanner.swift */; }; @@ -714,6 +716,7 @@ 7B3F9A10C2D4E5F6A7B80001 /* ListeningProcess.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ListeningProcess.swift; sourceTree = ""; }; 7B3F9A10C2D4E5F6A7B80003 /* PortsHubStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PortsHubStore.swift; sourceTree = ""; }; E0A1B2C3D4E5F6071800A001 /* ExternalOpenPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExternalOpenPolicy.swift; sourceTree = ""; }; + EE2190000000000000000001 /* DarkroomAppDiscovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DarkroomAppDiscovery.swift; sourceTree = ""; }; 7B3F9A10C2D4E5F6A7B80005 /* PortsHubView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PortsHubView.swift; sourceTree = ""; }; 7B3F9A10C2D4E5F6A7B80007 /* TerminalController+Ports.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "TerminalController+Ports.swift"; sourceTree = ""; }; A5001544 /* TerminalPasteboardPlanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalPasteboardPlanner.swift; sourceTree = ""; }; @@ -1316,6 +1319,7 @@ 7B3F9A10C2D4E5F6A7B80001 /* ListeningProcess.swift */, 7B3F9A10C2D4E5F6A7B80003 /* PortsHubStore.swift */, E0A1B2C3D4E5F6071800A001 /* ExternalOpenPolicy.swift */, + EE2190000000000000000001 /* DarkroomAppDiscovery.swift */, 7B3F9A10C2D4E5F6A7B80005 /* PortsHubView.swift */, 7B3F9A10C2D4E5F6A7B80007 /* TerminalController+Ports.swift */, A5001544 /* TerminalPasteboardPlanner.swift */, @@ -1992,6 +1996,7 @@ 7B3F9A10C2D4E5F6A7B80002 /* ListeningProcess.swift in Sources */, 7B3F9A10C2D4E5F6A7B80004 /* PortsHubStore.swift in Sources */, E0A1B2C3D4E5F6071800A002 /* ExternalOpenPolicy.swift in Sources */, + EE2190000000000000000002 /* DarkroomAppDiscovery.swift in Sources */, 7B3F9A10C2D4E5F6A7B80006 /* PortsHubView.swift in Sources */, 7B3F9A10C2D4E5F6A7B80008 /* TerminalController+Ports.swift in Sources */, A5001542 /* TerminalPasteboardPlanner.swift in Sources */, @@ -2201,6 +2206,7 @@ FADE00000000000000000001 /* CLI+AgentDetection.swift in Sources */, B5EE07000000000000000001 /* CLI+Browsee.swift in Sources */, DA2185000000000000000001 /* CLI+Apps.swift in Sources */, + EE2190000000000000000003 /* DarkroomAppDiscovery.swift in Sources */, DB2185000000000000000001 /* CLI+AppLinkAgents.swift in Sources */, 1C1375000000000000000001 /* CLI+WelcomeShortcuts.swift in Sources */, C0DE0C9A0000000000000001 /* CLI+CodexMCP.swift in Sources */, diff --git a/Sources/DarkroomAppDiscovery.swift b/Sources/DarkroomAppDiscovery.swift new file mode 100644 index 00000000..25b32da2 --- /dev/null +++ b/Sources/DarkroomAppDiscovery.swift @@ -0,0 +1,272 @@ +import AppKit +import Darwin +import Foundation +import Security + +enum DarkroomPeer: String, CaseIterable, Sendable { + case browsee + case mesinyer + + var bundleID: String { + switch self { + case .browsee: return "com.darkroom.browsee" + case .mesinyer: return "engineering.darkroom.mesinyer" + } + } + + var entryPoints: [(path: String, identifier: String)] { + switch self { + case .browsee: + return ["Contents/Helpers/browsee-mcp", "Contents/MacOS/browsee-mcp"].map { ($0, "browsee-mcp") } + case .mesinyer: + return [("Contents/MacOS/Mesinyer", bundleID)] + } + } + + struct Installation: Sendable { + let url: URL + let version: String + let advertisesStatus: Bool + let entryPoint: URL? + let verified: Bool + + var runningPIDs: Set { + Set(NSRunningApplication.runningApplications(withBundleIdentifier: bundleID) + .filter { $0.bundleURL?.resolvingSymlinksInPath() == url && !$0.isTerminated } + .map(\.processIdentifier)) + } + + fileprivate let bundleID: String + } + + func installation() -> Installation? { + let workspace = NSWorkspace.shared + let preferred = workspace.urlForApplication(withBundleIdentifier: bundleID) + let alternatives = workspace.urlsForApplications(withBundleIdentifier: bundleID) + let name = self == .browsee ? "browsee.app" : "Mesinyer.app" + let standard = [ + URL(fileURLWithPath: "/Applications", isDirectory: true), + FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Applications", isDirectory: true) + ].map { $0.appendingPathComponent(name, isDirectory: true) } + let candidates = [preferred].compactMap { $0 } + alternatives + standard + var checked = Set() + var firstIncompatible: Installation? + for candidate in candidates { + let url = candidate.resolvingSymlinksInPath().standardizedFileURL + guard checked.insert(url).inserted, + let bundle = Bundle(url: url), bundle.bundleIdentifier == bundleID else { continue } + let verified = Self.verifiedCode(url, identifier: bundleID) + let entryPoint = verified ? entryPoints.lazy.compactMap { point -> URL? in + let original = url.appendingPathComponent(point.path) + let resolved = original.resolvingSymlinksInPath() + guard resolved.path == original.path, + FileManager.default.isExecutableFile(atPath: resolved.path), + Self.verifiedCode(resolved, identifier: point.identifier) else { return nil } + return resolved + }.first : nil + let installation = Installation( + url: url, + version: bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "", + advertisesStatus: bundle.object(forInfoDictionaryKey: "DarkroomAppLinkVersion") as? Int == 1, + entryPoint: entryPoint, + verified: verified, + bundleID: bundleID + ) + if entryPoint != nil { return installation } + if firstIncompatible == nil || (firstIncompatible?.verified == false && verified) { + firstIncompatible = installation + } + } + return firstIncompatible + } + + private static func verifiedCode(_ url: URL, identifier: String) -> Bool { + var code: SecStaticCode? + var requirement: SecRequirement? + let flags = SecCSFlags(rawValue: 0) + // Check the code and signed Info.plist. Independently verify the nested executable + // we invoke, without walking unrelated assets in multi-gigabyte app bundles. + let validation = SecCSFlags(rawValue: UInt32(kSecCSDoNotValidateResources)).union(.noNetworkAccess) + let rule = "anchor apple generic and certificate leaf[subject.OU] = \"ZNHHMX2RP6\" and identifier \"\(identifier)\"" + guard SecStaticCodeCreateWithPath(url as CFURL, flags, &code) == errSecSuccess, + SecRequirementCreateWithString(rule as CFString, flags, &requirement) == errSecSuccess, + let code, let requirement else { return false } + return SecStaticCodeCheckValidity(code, validation, requirement) == errSecSuccess + } + + struct Identity: Codable { + let contract: Int + let app: String + let bundleID: String + let version: String + let state: String + let capabilities: [String] + + enum CodingKeys: String, CodingKey { + case contract, app, version, state, capabilities + case bundleID = "bundle_id" + } + } + + enum State: String, Codable, Sendable { + case ready + case notRunning = "not_running" + case denied + case disabled + case incompatible + case notInstalled = "not_installed" + case unavailable + } + + enum Access: String, Codable, Sendable { + case unknown, allowed, denied, disabled + } + + struct Status: Encodable, Sendable { + let app: String + let bundleID: String + let present: Bool + let verified: Bool + let running: Bool + let version: String? + let path: String? + var state: State + var access: Access = .unknown + var capabilities: [String] = [] + + enum CodingKeys: String, CodingKey { + case app, present, verified, running, version, path, state, access, capabilities + case bundleID = "bundle_id" + } + } + + func status() -> Status { + let install = installation() + var result = Status( + app: rawValue, bundleID: bundleID, present: install != nil, + verified: install?.verified ?? false, running: install?.runningPIDs.isEmpty == false, + version: install?.version, path: install?.url.path, state: install == nil ? .notInstalled : .incompatible) + guard let install, install.advertisesStatus, let helper = install.entryPoint else { return result } + guard let data = Self.readCommand(helper, arguments: ["--app-link-status"]) else { + result.state = .unavailable + return result + } + guard let identity = try? JSONDecoder().decode(Identity.self, from: data), + identity.contract == 1, identity.app == rawValue, identity.bundleID == bundleID, + let state = State(rawValue: identity.state), state != .notInstalled, state != .unavailable else { + return result + } + if self == .browsee, state == .ready || state == .disabled, + BrowseeSocket.endpoint(pids: install.runningPIDs) == nil { + result.state = .unavailable + return result + } + result.state = state + result.capabilities = identity.capabilities + switch state { + case .ready: result.access = .allowed + case .denied: result.access = .denied + case .disabled: result.access = .disabled + default: break + } + return result + } + + static func readCommand(_ helper: URL, arguments: [String], byteLimit: Int = 16_384) -> Data? { + let process = Process() + let pipe = Pipe() + process.executableURL = helper + process.arguments = arguments + process.standardInput = FileHandle.nullDevice + process.standardOutput = pipe + process.standardError = FileHandle.nullDevice + guard (try? process.run()) != nil else { return nil } + + let fd = pipe.fileHandleForReading.fileDescriptor + guard fcntl(fd, F_SETFL, O_NONBLOCK) != -1 else { + kill(process.processIdentifier, SIGKILL) + return nil + } + let deadline = DispatchTime.now().uptimeNanoseconds + 1_000_000_000 + var data = Data() + var bytes = [UInt8](repeating: 0, count: 4096) + while DispatchTime.now().uptimeNanoseconds < deadline { + let count = read(fd, &bytes, bytes.count) + if count > 0 { + data.append(contentsOf: bytes.prefix(count)) + if data.count > byteLimit { break } + } else if count == 0 && !process.isRunning { + return process.terminationStatus == 0 ? data : nil + } else if count == 0 || errno == EAGAIN || errno == EINTR { + usleep(5_000) + } else { + break + } + } + if process.isRunning { kill(process.processIdentifier, SIGKILL) } + return nil + } + +} + + +enum BrowseeSocket { + private static let socketRelativePath = "Library/Application Support/browsee/mcp.sock" + private static let sunPathBytes = 104 + + static func endpoint( + pids: Set?, + home: String = FileManager.default.homeDirectoryForCurrentUser.path, + fallbackFolder: String = "/tmp/browsee-\(geteuid())" + ) -> String? { + if pids?.isEmpty == true { return nil } + return probePaths(home: home, fallbackFolder: fallbackFolder).first { accepts($0, pids: pids) } + } + + /// The sockets whose answer means browsee runs. A socket path that does not fit `sun_path` + /// moves to a hashed name in browsee's fallback folder, `/tmp/browsee-/` (`socket_path` + /// in browsee-mcp). Only browsee's MCP sockets live there, so any socket in it counts. + private static func probePaths(home: String, fallbackFolder: String) -> [String] { + let natural = (home as NSString).appendingPathComponent(socketRelativePath) + if natural.utf8.count < sunPathBytes { return [natural] } + return ownedFolderEntries(fallbackFolder) + .filter { $0.hasSuffix(".sock") } + .sorted() + .map { (fallbackFolder as NSString).appendingPathComponent($0) } + } + + /// The folder's entries, or none unless it is a directory this user owns, as browsee requires. + private static func ownedFolderEntries(_ folder: String) -> [String] { + var info = stat() + guard lstat(folder, &info) == 0, info.st_mode & S_IFMT == S_IFDIR, info.st_uid == geteuid() else { return [] } + return (try? FileManager.default.contentsOfDirectory(atPath: folder)) ?? [] + } + + /// Whether browsee's MCP socket accepts a connection, which is what "running" means. The + /// probe closes without a session header; browsee drops such a connection. + private static func accepts(_ path: String, pids: Set?) -> Bool { + let descriptor = socket(AF_UNIX, SOCK_STREAM, 0) + guard descriptor >= 0 else { return false } + defer { Darwin.close(descriptor) } + guard fcntl(descriptor, F_SETFL, O_NONBLOCK) != -1 else { return false } + var address = sockaddr_un() + address.sun_family = sa_family_t(AF_UNIX) + let bytes = Array(path.utf8) + guard bytes.count < MemoryLayout.size(ofValue: address.sun_path) else { return false } + withUnsafeMutableBytes(of: &address.sun_path) { buffer in + buffer.copyBytes(from: bytes) + } + address.sun_len = UInt8(MemoryLayout.size) + let connected = withUnsafePointer(to: &address) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + connect(descriptor, $0, socklen_t(MemoryLayout.size)) == 0 + } + } + guard connected else { return false } + guard let pids else { return true } + var pid: pid_t = 0 + var length = socklen_t(MemoryLayout.size) + return getsockopt(descriptor, SOL_LOCAL, LOCAL_PEERPID, &pid, &length) == 0 && pids.contains(pid) + } + +} From 5612d8592e8acd833e1988ad4076d357ef449d00 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:25:23 -0300 Subject: [PATCH 08/37] Show Darkroom app readiness and access in Programa Settings --- GhosttyTabs.xcodeproj/project.pbxproj | 4 + Resources/Localizable.xcstrings | 28 ++- Sources/AppDelegate.swift | 4 +- Sources/SettingsAgentsPane.swift | 12 +- Sources/SettingsDarkroomApps.swift | 182 ++++++++++++++++++++ Sources/SettingsSearchIndex.swift | 8 +- docs/browsee.md | 4 +- programaTests/SettingsNavigationTests.swift | 8 + 8 files changed, 240 insertions(+), 10 deletions(-) create mode 100644 Sources/SettingsDarkroomApps.swift diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index f0c96695..49b83c85 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -34,6 +34,7 @@ B4C0080B536225405A3FC0CF /* SettingsShortcutsPane.swift in Sources */ = {isa = PBXBuildFile; fileRef = 102A507DEBDABE1023354973 /* SettingsShortcutsPane.swift */; }; 2BDDD1ADF04E4358EF6721FC /* SettingsAutomationPane.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA5806D6D2EFE4538DEF636D /* SettingsAutomationPane.swift */; }; 48BED6C4710B0DA532E5F117 /* SettingsAgentsPane.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4F272647ABD5BD0ACD6B3FC /* SettingsAgentsPane.swift */; }; + EF2190000000000000000002 /* SettingsDarkroomApps.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF2190000000000000000001 /* SettingsDarkroomApps.swift */; }; 5D951D99DB143A52A1295E7F /* SettingsAppearancePane.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAC531A0F930E986A2FC3C6D /* SettingsAppearancePane.swift */; }; 48B88AF2818FC3A02015CA62 /* SettingsGeneralPanes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54B811D46EBCD241CBC31798 /* SettingsGeneralPanes.swift */; }; 5582C929E24C4D5845606603 /* SettingsSearchIndex.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAF5C4C06180C3C78CC60875 /* SettingsSearchIndex.swift */; }; @@ -573,6 +574,7 @@ 102A507DEBDABE1023354973 /* SettingsShortcutsPane.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsShortcutsPane.swift; sourceTree = ""; }; AA5806D6D2EFE4538DEF636D /* SettingsAutomationPane.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsAutomationPane.swift; sourceTree = ""; }; F4F272647ABD5BD0ACD6B3FC /* SettingsAgentsPane.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsAgentsPane.swift; sourceTree = ""; }; + EF2190000000000000000001 /* SettingsDarkroomApps.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsDarkroomApps.swift; sourceTree = ""; }; BAC531A0F930E986A2FC3C6D /* SettingsAppearancePane.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsAppearancePane.swift; sourceTree = ""; }; 54B811D46EBCD241CBC31798 /* SettingsGeneralPanes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsGeneralPanes.swift; sourceTree = ""; }; EAF5C4C06180C3C78CC60875 /* SettingsSearchIndex.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsSearchIndex.swift; sourceTree = ""; }; @@ -1160,6 +1162,7 @@ 102A507DEBDABE1023354973 /* SettingsShortcutsPane.swift */, AA5806D6D2EFE4538DEF636D /* SettingsAutomationPane.swift */, F4F272647ABD5BD0ACD6B3FC /* SettingsAgentsPane.swift */, + EF2190000000000000000001 /* SettingsDarkroomApps.swift */, BAC531A0F930E986A2FC3C6D /* SettingsAppearancePane.swift */, 54B811D46EBCD241CBC31798 /* SettingsGeneralPanes.swift */, EAF5C4C06180C3C78CC60875 /* SettingsSearchIndex.swift */, @@ -1832,6 +1835,7 @@ B4C0080B536225405A3FC0CF /* SettingsShortcutsPane.swift in Sources */, 2BDDD1ADF04E4358EF6721FC /* SettingsAutomationPane.swift in Sources */, 48BED6C4710B0DA532E5F117 /* SettingsAgentsPane.swift in Sources */, + EF2190000000000000000002 /* SettingsDarkroomApps.swift in Sources */, 5D951D99DB143A52A1295E7F /* SettingsAppearancePane.swift in Sources */, 48B88AF2818FC3A02015CA62 /* SettingsGeneralPanes.swift in Sources */, 5582C929E24C4D5845606603 /* SettingsSearchIndex.swift in Sources */, diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index dfad76ed..e861e517 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -1,6 +1,32 @@ { "sourceLanguage": "en", "strings": { + "settings.apps.browsee.registrationLabel" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Review Browsee MCP registrations"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Browsee MCP の登録を確認"}}}}, + "settings.apps.browsee.registration" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Review registration…"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "登録を確認…"}}}}, + "settings.apps.heading" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Darkroom Apps"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Darkroom アプリ"}}}}, + "settings.apps.help" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Check whether Browsee and Mesinyer are installed and available."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Browsee と Mesinyer がインストールされ、利用できるかを確認します。"}}}}, + "settings.apps.refresh" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Refresh"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "更新"}}}}, + "settings.apps.checking" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Checking availability…"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "利用可否を確認中…"}}}}, + "settings.apps.open" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Open %@"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "%@ を開く"}}}}, + "settings.apps.notFound" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Not found"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "見つかりません"}}}}, + "settings.apps.unverifiedPresence" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Unverified installation"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "署名を確認できないインストール"}}}}, + "settings.apps.incompatible" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Incompatible version"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "非対応のバージョン"}}}}, + "settings.apps.closed" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Installed · Closed"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "インストール済み・未起動"}}}}, + "settings.apps.ready" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Ready"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "準備完了"}}}}, + "settings.apps.running" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Running"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "起動中"}}}}, + "settings.apps.browsee.allowed" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Available to Programa panes"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Programa のペインから利用可能"}}}}, + "settings.apps.mesinyer.allowed" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Access follows workspace permissions"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "アクセスはワークスペースの権限に従います"}}}}, + "settings.apps.accessDenied" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Access denied"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "アクセスが拒否されました"}}}}, + "settings.apps.accessDisabled" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Access disabled"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "アクセスが無効です"}}}}, + "settings.apps.accessUnknown" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Access unknown"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "アクセスの状態は不明です"}}}}, + "settings.apps.unverified" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Install a signed release, then refresh."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "署名済みのリリースをインストールしてから更新してください。"}}}}, + "settings.apps.install" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Refresh after installing the app."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "アプリをインストールしてから更新してください。"}}}}, + "settings.apps.update" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Update the app to a release that supports Darkroom app discovery."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Darkroom アプリの検出に対応するバージョンに更新してください。"}}}}, + "settings.apps.browsee.reviewAccess" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "In Browsee, open Settings → Agents and review “Let other apps control my tabs”."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Browsee の「設定」→「エージェント」で、他のアプリによるタブの操作を許可する設定を確認してください。"}}}}, + "settings.apps.mesinyer.reviewAccess" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "In Mesinyer, open Settings → AI Tools and review access for the workspace."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Mesinyer の「設定」→「AI ツール」で、ワークスペースへのアクセスを確認してください。"}}}}, + "settings.apps.tryAgain" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "The app did not confirm readiness. Refresh to check again."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "アプリを利用できるか確認できませんでした。更新して再確認してください。"}}}}, + "settings.apps.refreshed" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "App status updated."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "アプリの状態を更新しました。"}}}}, + "settings.apps.openFailed" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "The app couldn’t be opened. Refresh and try again."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "アプリを開けませんでした。更新してからやり直してください。"}}}}, "settings.color.useDefault" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Use Default"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "デフォルトを使用"}}}}, "settings.color.useDefaultFor" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Use the default %@"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "デフォルトの%@を使用"}}}}, "settings.section.glass" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Glass"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "ガラス"}}}}, @@ -49,7 +75,7 @@ "settings.glass.window.help" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Blur the desktop behind the window instead of drawing a solid background."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "単色の背景の代わりに、ウインドウの背後のデスクトップをぼかして表示します。"}}}}, "settings.globalChat.autoApprove.help" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Global Chat may allow plain reads, git status and commits, builds and tests once, and tells you in the chat. Builds and tests run your project's own scripts. Everything else waits for you."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "グローバルチャットが単純な読み取り、git status とコミット、ビルドとテストを一度だけ許可し、チャットでお知らせします。ビルドとテストはプロジェクト独自のスクリプトを実行します。それ以外はすべてあなたの承認を待ちます。"}}}}, "settings.globalChat.persona.help" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "The voice Global Chat replies in."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "グローバルチャットが返信するときの口調です。"}}}}, - "settings.integrations.installers.help" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Set up Claude Code, Codex, OpenCode or browsee MCP to work with Programa."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Claude Code、Codex、OpenCode、browsee MCP を Programa と連携できるように設定します。"}}}}, + "settings.integrations.installers.help" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Set up Claude Code, Codex and OpenCode or review existing Browsee registrations."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Claude Code、Codex、OpenCode を設定したり、既存の Browsee の登録を確認したりします。"}}}}, "settings.links.allowedApps.emptyHint" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Choose Always Allow when Programa asks before a link opens another app, and the app appears here."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "リンクを別のアプリで開く前の確認で「常に許可」を選ぶと、そのアプリがここに表示されます。"}}}}, "settings.links.allowedApps.none" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "None"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "なし"}}}}, "settings.managedByFile.note" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Set in settings.json:"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "settings.json で設定:"}}}}, diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 6d25f48a..59a08a4b 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -3261,8 +3261,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, @preconcurrency UNUser } @discardableResult - func openBrowseeMCPInstaller(event: NSEvent? = nil, debugSource: String = "unspecified") -> UUID? { - openWorkspaceRunning("programa browsee install-mcp\n", event: event, debugSource: debugSource) + func openBrowseeMCPRegistrationStatus(event: NSEvent? = nil, debugSource: String = "unspecified") -> UUID? { + openWorkspaceRunning("programa browsee status\n", event: event, debugSource: debugSource) } private func openWorkspaceRunning( diff --git a/Sources/SettingsAgentsPane.swift b/Sources/SettingsAgentsPane.swift index 86e4a784..87a50948 100644 --- a/Sources/SettingsAgentsPane.swift +++ b/Sources/SettingsAgentsPane.swift @@ -107,6 +107,7 @@ struct SettingsAgentsPane: View { struct SettingsIntegrationsPane: View { var body: some View { SettingsForm { + SettingsDarkroomApps() MobileChatCompanionSettings() Section { @@ -119,8 +120,12 @@ struct SettingsIntegrationsPane: View { installer("OpenCode", actionLabel: String(localized: "integration.installOpenCode", defaultValue: "Install OpenCode Integration…")) { $0.openOpenCodeIntegrationInstaller(debugSource: "settings.installOpenCodeIntegration") } - installer("browsee MCP", actionLabel: String(localized: "integration.installBrowseeMCP", defaultValue: "Install browsee MCP…")) { - $0.openBrowseeMCPInstaller(debugSource: "settings.installBrowseeMCP") + installer( + "Browsee MCP", + actionLabel: String(localized: "settings.apps.browsee.registrationLabel", defaultValue: "Review Browsee MCP registrations"), + buttonTitle: String(localized: "settings.apps.browsee.registration", defaultValue: "Review registration…") + ) { + $0.openBrowseeMCPRegistrationStatus(debugSource: "settings.reviewBrowseeMCP") } } header: { Text(SettingsItem.installIntegrations.title()) @@ -134,10 +139,11 @@ struct SettingsIntegrationsPane: View { private func installer( _ name: String, actionLabel: String, + buttonTitle: String = String(localized: "settings.integrations.install", defaultValue: "Install…"), action: @escaping (AppDelegate) -> UUID? ) -> some View { LabeledContent { - Button(String(localized: "settings.integrations.install", defaultValue: "Install…")) { + Button(buttonTitle) { guard let delegate = AppDelegate.shared, let workspaceID = action(delegate), let window = delegate.mainWindowContainingWorkspace(workspaceID) else { return } delegate.bringToFront(window) diff --git a/Sources/SettingsDarkroomApps.swift b/Sources/SettingsDarkroomApps.swift new file mode 100644 index 00000000..a18a3216 --- /dev/null +++ b/Sources/SettingsDarkroomApps.swift @@ -0,0 +1,182 @@ +import AppKit +import SwiftUI + +struct SettingsDarkroomApps: View { + @State private var statuses: [DarkroomPeer: DarkroomPeer.Status] = [:] + @State private var openErrors: [DarkroomPeer: String] = [:] + @State private var refreshing = false + + var body: some View { + Section { + ForEach(DarkroomPeer.allCases, id: \.self) { peer in + appRow(peer, status: statuses[peer]) + } + HStack(spacing: 10) { + Button(String(localized: "settings.apps.refresh", defaultValue: "Refresh")) { + Task { await refresh(announce: true) } + } + .accessibilityIdentifier("SettingsDarkroomAppsRefresh") + if refreshing { + ProgressView() + .controlSize(.small) + .accessibilityHidden(true) + } + } + } header: { + Text(SettingsItem.discoveredApps.title()) + .settingsRow(anchor: SettingsItem.discoveredApps.rawValue, managedKeys: []) + } + .task { await refresh(announce: false) } + } + + @ViewBuilder + private func appRow(_ peer: DarkroomPeer, status: DarkroomPeer.Status?) -> some View { + let title = peer == .browsee ? "Browsee" : "Mesinyer" + let detail = status.map { [presence($0), access($0)] } ?? [ + String(localized: "settings.apps.checking", defaultValue: "Checking availability…") + ] + VStack(alignment: .leading, spacing: 4) { + ViewThatFits(in: .horizontal) { + HStack(alignment: .firstTextBaseline, spacing: 10) { + statusLabel(title, lines: detail) + Spacer(minLength: 0) + openButton(peer, title: title, status: status) + } + VStack(alignment: .leading, spacing: 10) { + statusLabel(title, lines: detail) + openButton(peer, title: title, status: status) + } + } + .accessibilityIdentifier("SettingsDarkroomApp.\(peer.rawValue)") + if let note = guidance(peer, status: status) { + Text(note).font(.subheadline).foregroundStyle(.secondary) + } + if let error = openErrors[peer] { + Text(error).font(.subheadline).foregroundStyle(.secondary) + } + } + } + + private func statusLabel(_ title: String, lines: [String]) -> some View { + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: title) + Text(verbatim: lines.joined(separator: " · ")) + .font(.subheadline) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .accessibilityElement(children: .combine) + } + + @ViewBuilder + private func openButton(_ peer: DarkroomPeer, title: String, status: DarkroomPeer.Status?) -> some View { + if status?.verified == true { + Button(String(localized: "settings.apps.open", defaultValue: "Open \(title)")) { open(peer) } + .fixedSize() + } + } + + private func presence(_ status: DarkroomPeer.Status) -> String { + if !status.present { + return String(localized: "settings.apps.notFound", defaultValue: "Not found") + } + if !status.verified { + return String(localized: "settings.apps.unverifiedPresence", defaultValue: "Unverified installation") + } + if status.state == .incompatible { + return String(localized: "settings.apps.incompatible", defaultValue: "Incompatible version") + } + if !status.running { + return String(localized: "settings.apps.closed", defaultValue: "Installed · Closed") + } + if status.state == .ready { + return String(localized: "settings.apps.ready", defaultValue: "Ready") + } + return String(localized: "settings.apps.running", defaultValue: "Running") + } + + private func access(_ status: DarkroomPeer.Status) -> String { + switch status.access { + case .allowed: + return status.app == DarkroomPeer.browsee.rawValue + ? String(localized: "settings.apps.browsee.allowed", defaultValue: "Available to Programa panes") + : String(localized: "settings.apps.mesinyer.allowed", defaultValue: "Access follows workspace permissions") + case .denied: + return String(localized: "settings.apps.accessDenied", defaultValue: "Access denied") + case .disabled: + return String(localized: "settings.apps.accessDisabled", defaultValue: "Access disabled") + case .unknown: + return String(localized: "settings.apps.accessUnknown", defaultValue: "Access unknown") + } + } + + private func guidance(_ peer: DarkroomPeer, status: DarkroomPeer.Status?) -> String? { + guard let status else { return nil } + if !status.verified { + return status.present + ? String(localized: "settings.apps.unverified", defaultValue: "Install a signed release, then refresh.") + : String(localized: "settings.apps.install", defaultValue: "Refresh after installing the app.") + } + if status.state == .unavailable || (status.state == .notRunning && status.running) { + return String(localized: "settings.apps.tryAgain", defaultValue: "The app did not confirm readiness. Refresh to check again.") + } + switch status.state { + case .incompatible: + return String(localized: "settings.apps.update", defaultValue: "Update the app to a release that supports Darkroom app discovery.") + case .denied, .disabled: + switch peer { + case .browsee: + return String(localized: "settings.apps.browsee.reviewAccess", defaultValue: "In Browsee, open Settings → Agents and review “Let other apps control my tabs”.") + case .mesinyer: + return String(localized: "settings.apps.mesinyer.reviewAccess", defaultValue: "In Mesinyer, open Settings → AI Tools and review access for the workspace.") + } + default: + return nil + } + } + + @MainActor + private func refresh(announce: Bool) async { + guard !refreshing else { return } + refreshing = true + defer { refreshing = false } + let results = await Task.detached(priority: .utility) { + Dictionary(uniqueKeysWithValues: DarkroomPeer.allCases.map { ($0, $0.status()) }) + }.value + guard !Task.isCancelled else { return } + statuses = results + openErrors.removeAll() + if announce { + announceStatus(String(localized: "settings.apps.refreshed", defaultValue: "App status updated.")) + } + } + + private func open(_ peer: DarkroomPeer) { + openErrors.removeValue(forKey: peer) + Task { @MainActor in + let install = await Task.detached(priority: .utility) { peer.installation() }.value + guard let install, install.verified else { + let detail = String(localized: "settings.apps.openFailed", defaultValue: "The app couldn’t be opened. Refresh and try again.") + openErrors[peer] = detail + announceStatus(detail) + return + } + NSWorkspace.shared.openApplication(at: install.url, configuration: .init()) { _, error in + guard error != nil else { return } + Task { @MainActor in + let detail = String(localized: "settings.apps.openFailed", defaultValue: "The app couldn’t be opened. Refresh and try again.") + openErrors[peer] = detail + announceStatus(detail) + } + } + } + } + + @MainActor + private func announceStatus(_ message: String) { + NSAccessibility.post(element: NSApplication.shared, notification: .announcementRequested, userInfo: [ + .announcement: message, + .priority: NSAccessibilityPriorityLevel.medium.rawValue + ]) + } +} diff --git a/Sources/SettingsSearchIndex.swift b/Sources/SettingsSearchIndex.swift index 5f2e6382..9e291243 100644 --- a/Sources/SettingsSearchIndex.swift +++ b/Sources/SettingsSearchIndex.swift @@ -70,6 +70,7 @@ enum SettingsItem: String, CaseIterable, Sendable { case taskAccess = "integrations.taskAccess" case iphoneConnection = "integrations.iphoneConnection" case installIntegrations = "integrations.install" + case discoveredApps = "integrations.darkroomApps" // Shortcuts case shortcutChords = "shortcuts.bindings" @@ -96,7 +97,7 @@ enum SettingsItem: String, CaseIterable, Sendable { .storage case .socketControlMode, .socketPassword, .trustedDirectories: .automation - case .taskAccess, .iphoneConnection, .installIntegrations: + case .taskAccess, .iphoneConnection, .installIntegrations, .discoveredApps: .integrations case .shortcutChords: .shortcuts @@ -194,6 +195,7 @@ enum SettingsItem: String, CaseIterable, Sendable { case .trustedDirectories: String(localized: "settings.customCommands.trustedDirectories", defaultValue: "Trusted Directories", bundle: bundle, locale: locale) case .taskAccess: String(localized: "mobileChat.section.taskAccess", defaultValue: "Task Access", bundle: bundle, locale: locale) case .iphoneConnection: String(localized: "mobileChat.section.connection", defaultValue: "iPhone Connection", bundle: bundle, locale: locale) + case .discoveredApps: String(localized: "settings.apps.heading", defaultValue: "Darkroom Apps", bundle: bundle, locale: locale) case .installIntegrations: String(localized: "settings.integrations.installers", defaultValue: "Install Integrations", bundle: bundle, locale: locale) case .shortcutChords: String(localized: "settings.shortcuts.chords", defaultValue: "Shortcut Chords", bundle: bundle, locale: locale) } @@ -251,7 +253,8 @@ enum SettingsItem: String, CaseIterable, Sendable { case .trustedDirectories: String(localized: "settings.customCommands.trustedDirectories.subtitle", defaultValue: "Commands from programa.json in these directories run without confirmation. One path per line.", bundle: bundle, locale: locale) case .taskAccess: String(localized: "mobileChat.useOpenWorkspaces.detail", defaultValue: "Allow tasks from your iPhone to work in isolated copies of the Git repositories open in Programa now.", bundle: bundle, locale: locale) case .iphoneConnection: String(localized: "mobileChat.keepOpen", defaultValue: "Keep Programa open and this Mac awake to run jobs from your iPhone.", bundle: bundle, locale: locale) - case .installIntegrations: String(localized: "settings.integrations.installers.help", defaultValue: "Set up Claude Code, Codex, OpenCode or browsee MCP to work with Programa.", bundle: bundle, locale: locale) + case .discoveredApps: String(localized: "settings.apps.help", defaultValue: "Check whether Browsee and Mesinyer are installed and available.", bundle: bundle, locale: locale) + case .installIntegrations: String(localized: "settings.integrations.installers.help", defaultValue: "Set up Claude Code, Codex and OpenCode or review existing Browsee registrations.", bundle: bundle, locale: locale) case .shortcutChords: String(localized: "settings.shortcuts.chords.subtitle", defaultValue: "Add tmux-style multi-step shortcuts in settings.json, for example [\"ctrl+b\", \"c\"].", bundle: bundle, locale: locale) } } @@ -265,6 +268,7 @@ enum SettingsItem: String, CaseIterable, Sendable { case .claudeCodeIntegration: ["hooks", "claude"] case .socketControlMode, .socketPassword: ["socket", "api", "cli"] case .trustedDirectories: ["programa.json", "custom commands"] + case .discoveredApps: ["browsee", "mesinyer", "mcp", "connections", "access"] case .installIntegrations: ["claude code", "codex", "opencode", "browsee", "mcp"] case .windowGlass, .tabBarGlass, .overlayGlass: ["liquid glass", "transparency", "blur"] case .selectionColor, .notificationBadgeColor, .sidebarTint: ["color", "colour"] diff --git a/docs/browsee.md b/docs/browsee.md index bfc53fd6..4744aa6b 100644 --- a/docs/browsee.md +++ b/docs/browsee.md @@ -20,8 +20,8 @@ programa browsee status # show the legacy registration for each agent Outside Programa, use `programa browsee install-mcp` to register browsee persistently with Claude Code and Codex. It previews changes and asks first. `programa browsee uninstall-mcp` -removes the registration. **Settings → Integrations → browsee MCP** opens the installer in -a new workspace. +removes the registration. **Settings → Integrations → Browsee MCP** opens a read-only +registration report in a new workspace. ## What the agent gets diff --git a/programaTests/SettingsNavigationTests.swift b/programaTests/SettingsNavigationTests.swift index 4c6032a3..75c9391d 100644 --- a/programaTests/SettingsNavigationTests.swift +++ b/programaTests/SettingsNavigationTests.swift @@ -32,6 +32,14 @@ final class SettingsNavigationTests: XCTestCase { XCTAssertTrue(ids("liquid glass").contains(SettingsItem.overlayGlass.rawValue)) } + func testSearchOpensDarkroomAppsFromPeerNamesAndAliases() { + let anchor = SettingsItem.discoveredApps.rawValue + for query in ["Browsee", "Mesinyer", "MCP", "Connections"] { + XCTAssertTrue(ids(query).contains(anchor), query) + } + XCTAssertEqual(SettingsNavigationTarget(rawValue: anchor), .row(anchor: anchor, category: .integrations)) + } + func testSearchFindsKeyboardShortcutActionsInTheShortcutsCategory() { let results = SettingsSearchIndex.search("split right", in: SettingsSearchIndex.entries()) let entry = results.first { $0.id == SettingsItem.shortcutAnchor(for: .splitRight) } From 9f800f1f530dcf4859fed1598cad09ea31ba8bda Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:25:23 -0300 Subject: [PATCH 09/37] Open canonical conversation links in verified Mesinyer --- Resources/Localizable.xcstrings | 3 +++ Sources/AppDelegate.swift | 24 ++++++++++++++++++++++ Sources/ExternalOpenPolicy.swift | 13 ++++++++++++ Sources/ProgramaApp.swift | 4 ++++ contracts/link/v1/README.md | 2 ++ programaTests/ShellFixSweepSHELTests.swift | 16 +++++++++++++++ 6 files changed, 62 insertions(+) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index e861e517..7c5ac3c3 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -27,6 +27,9 @@ "settings.apps.tryAgain" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "The app did not confirm readiness. Refresh to check again."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "アプリを利用できるか確認できませんでした。更新して再確認してください。"}}}}, "settings.apps.refreshed" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "App status updated."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "アプリの状態を更新しました。"}}}}, "settings.apps.openFailed" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "The app couldn’t be opened. Refresh and try again."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "アプリを開けませんでした。更新してからやり直してください。"}}}}, + "mesinyerConversation.invalid" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Copy a Mesinyer conversation link first."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "先に Mesinyer の会話リンクをコピーしてください。"}}}}, + "mesinyerConversation.appMissing" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Install a current signed version of Mesinyer to open this conversation."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "この会話を開くには、現在の署名済みの Mesinyer をインストールしてください。"}}}}, + "menu.file.openMesinyerConversation" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Open Mesinyer Conversation from Clipboard"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "クリップボードから Mesinyer の会話を開く"}}}}, "settings.color.useDefault" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Use Default"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "デフォルトを使用"}}}}, "settings.color.useDefaultFor" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Use the default %@"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "デフォルトの%@を使用"}}}}, "settings.section.glass" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Glass"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "ガラス"}}}}, diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 59a08a4b..20d0a9be 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -417,6 +417,30 @@ final class AppDelegate: NSObject, NSApplicationDelegate, @preconcurrency UNUser } } + func openMesinyerConversationFromClipboard() { + let text = NSPasteboard.general.string(forType: .string) ?? "" + guard let url = AppReference.mesinyerConversationURL(fromClipboard: text) else { + let alert = NSAlert() + alert.messageText = String(localized: "mesinyerConversation.invalid", defaultValue: "Copy a Mesinyer conversation link first.") + presentReferenceAlert(alert) + return + } + Task { @MainActor in + let install = await Task.detached(priority: .userInitiated) { DarkroomPeer.mesinyer.installation() }.value + guard let install, install.verified, install.advertisesStatus else { + let alert = NSAlert() + alert.messageText = String(localized: "mesinyerConversation.appMissing", defaultValue: "Install a current signed version of Mesinyer to open this conversation.") + presentReferenceAlert(alert) + return + } + NSWorkspace.shared.open([url], withApplicationAt: install.url, configuration: .init()) { _, error in + if let error { + DispatchQueue.main.async { NSApp.presentError(error) } + } + } + } + } + private func presentReferenceAlert(_ alert: NSAlert) { if let window = NSApp.keyWindow { alert.beginSheetModal(for: window) } else { alert.runModal() } diff --git a/Sources/ExternalOpenPolicy.swift b/Sources/ExternalOpenPolicy.swift index b49dda32..ba6daf41 100644 --- a/Sources/ExternalOpenPolicy.swift +++ b/Sources/ExternalOpenPolicy.swift @@ -30,6 +30,19 @@ enum AppReference: String { return item } + static func mesinyerConversationURL(fromClipboard text: String) -> URL? { + let value = text.trimmingCharacters(in: .whitespacesAndNewlines) + let prefix = "mesinyer://conversation/" + guard value.hasPrefix(prefix) else { return nil } + let ids = value.dropFirst(prefix.count).split(separator: "/", omittingEmptySubsequences: false) + guard ids.count == 2, ids.allSatisfy({ id in + (1...64).contains(id.utf8.count) && id.utf8.allSatisfy { byte in + (65...90).contains(byte) || (48...57).contains(byte) + } + }) else { return nil } + return URL(string: value) + } + static func chatURL(fromClipboard text: String) -> URL? { let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) guard let id = chat.id(from: trimmed) ?? chat.id(from: chat.rawValue + trimmed) else { return nil } diff --git a/Sources/ProgramaApp.swift b/Sources/ProgramaApp.swift index 5d99c837..967941f6 100644 --- a/Sources/ProgramaApp.swift +++ b/Sources/ProgramaApp.swift @@ -476,6 +476,10 @@ struct programaApp: App { Button(String(localized: "menu.file.openBrowseeChat", defaultValue: "Open Browsee Chat from Clipboard")) { AppDelegate.shared?.openBrowseeChatFromClipboard() } + + Button(String(localized: "menu.file.openMesinyerConversation", defaultValue: "Open Mesinyer Conversation from Clipboard")) { + AppDelegate.shared?.openMesinyerConversationFromClipboard() + } } // Close tab/workspace diff --git a/contracts/link/v1/README.md b/contracts/link/v1/README.md index 1ff45373..474ea08b 100644 --- a/contracts/link/v1/README.md +++ b/contracts/link/v1/README.md @@ -17,3 +17,5 @@ Invoke the status entry point with `--app-link-status`, closed stdin and a bound Installation, running process and access state are independent. `programa apps status --json` adds a top-level contract, an array of peer records, and flags for installation, bundle verification and an observed running production process. A missing bundle is `not_installed`. A failed probe may be `unavailable` and access remains unknown. Check again on every explicit inquiry or helper start so that restarting or moving a peer does not require updating agent configuration. Agents keep MCP over stdio. A Programa agent adapter can supply `--session programa-` as an explicit correlation value each time it starts the peer helper, including after an agent reconnect or resume. The value identifies a pane for routing and does not grant access. The owning app applies its existing access and content approval rules. + +A user can open a copied Mesinyer conversation in Programa's File menu. The reference syntax is `mesinyer://conversation//` with two case-sensitive ASCII uppercase alphanumeric IDs, each 1–64 bytes. The action addresses the verified Mesinyer bundle explicitly. Mesinyer checks local workspace membership and its own access setting before navigating. diff --git a/programaTests/ShellFixSweepSHELTests.swift b/programaTests/ShellFixSweepSHELTests.swift index 94ae86fa..e38a5b2a 100644 --- a/programaTests/ShellFixSweepSHELTests.swift +++ b/programaTests/ShellFixSweepSHELTests.swift @@ -65,6 +65,22 @@ final class WindowCloseGateTests: XCTestCase { // MARK: - SHEL-06 / SHEL-07: external open policy final class ExternalOpenPolicySHELTests: XCTestCase { + func testMesinyerConversationReferenceRequiresCanonicalLocalIDs() throws { + let link = "mesinyer://conversation/T0123/C456" + let canonical = try XCTUnwrap(AppReference.mesinyerConversationURL(fromClipboard: " \n\(link)\n")) + XCTAssertEqual(canonical.absoluteString, link) + XCTAssertFalse(ExternalOpenPolicy.opensWithoutPrompt(canonical)) + for malformed in [ + "Mesinyer://conversation/T0123/C456", "mesinyer://Conversation/T0123/C456", + "mesinyer://conversation/T0123/c456", "mesinyer://conversation/T0123/%43456", + "mesinyer://conversation/T0123/C456?join=1", "mesinyer://conversation/T0123/C456#extra", + "mesinyer://conversation/T0123//C456", "mesinyer://conversation/T0123/C456/", + "mesinyer://conversation/T0123/C456", "mesinyer://conversation/T0123/C" + String(repeating: "A", count: 64) + ] { + XCTAssertNil(AppReference.mesinyerConversationURL(fromClipboard: malformed)) + } + } + func testRememberedApprovalIsIgnoredWithoutANativeGesture() throws { let url = try XCTUnwrap(URL(string: "ssh://x")) let allow = [ExternalOpenPolicy.allowlistKey(bundleIdentifier: "com.apple.Terminal", scheme: "ssh")] From fcd987c6623761bf3c2cf00ee0808761cc2272ab Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:25:26 -0300 Subject: [PATCH 10/37] Resolve Windows companion identities without granting access --- contracts/link/v1/windows-apps.json | 23 ++++ contracts/link/v1/windows.md | 17 +++ .../Programa.Tests/CompanionDiscoveryTests.cs | 95 ++++++++++++++ windows/Programa/CompanionDiscovery.cs | 99 +++++++++++++++ windows/Programa/Programa.csproj | 1 + windows/Programa/WindowsCompanionPlatform.cs | 113 +++++++++++++++++ windows/Programa/WindowsCompanionTrust.cs | 116 ++++++++++++++++++ 7 files changed, 464 insertions(+) create mode 100644 contracts/link/v1/windows-apps.json create mode 100644 contracts/link/v1/windows.md create mode 100644 windows/Programa.Tests/CompanionDiscoveryTests.cs create mode 100644 windows/Programa/CompanionDiscovery.cs create mode 100644 windows/Programa/WindowsCompanionPlatform.cs create mode 100644 windows/Programa/WindowsCompanionTrust.cs diff --git a/contracts/link/v1/windows-apps.json b/contracts/link/v1/windows-apps.json new file mode 100644 index 00000000..36b1e948 --- /dev/null +++ b/contracts/link/v1/windows-apps.json @@ -0,0 +1,23 @@ +{ + "contract": 1, + "apps": [ + { + "app": "browsee", + "title": "Browsee", + "direct_install_id": "browsee-app", + "direct_executable": "browsee.exe", + "direct_product": "browsee", + "direct_signers": [], + "store_packages": [] + }, + { + "app": "mesinyer", + "title": "Mesinyer", + "direct_install_id": "Mesinyer", + "direct_executable": "Mesinyer.Windows.exe", + "direct_product": "Mesinyer.Windows", + "direct_signers": [], + "store_packages": [] + } + ] +} diff --git a/contracts/link/v1/windows.md b/contracts/link/v1/windows.md new file mode 100644 index 00000000..805bbabc --- /dev/null +++ b/contracts/link/v1/windows.md @@ -0,0 +1,17 @@ +# Windows companion discovery + +In a Programa terminal, run `programa apps status --json`, or open Settings → Integrations. Both read the same local inventory for Browsee and Mesinyer. Each check resolves the current installation again, including after updates, moves or restarts. The CLI can run while Programa’s main window is closed. + +- Direct installers use their exact Velopack IDs and main executable paths from [windows-apps.json](windows-apps.json). Velopack records the install root under the ID's Windows uninstall key, including custom install directories. Programa reads the root and checks the expected executable under `current`. The registry entry alone provides an unverified installation hint. A verified direct install requires matching signed PE product metadata, Windows Authenticode validation and an enrolled SHA-256 pair containing the validating publisher’s DER subject name and its issuing CA’s DER SubjectPublicKeyInfo. [Velopack 1.2.161 registration source](https://raw.githubusercontent.com/velopack/velopack/1.2.161/src/bins/src/windows/registry.rs) +- Store installs require an exact enrolled package family and relative executable path, an active registration for the current Windows user, and Windows' Store signature classification. A running process must match the selected executable and, for a Store package, its full package name. [PackageManager](https://learn.microsoft.com/en-us/uwp/api/windows.management.deployment.packagemanager) · [Package identity APIs](https://learn.microsoft.com/en-us/windows/win32/appxpkg/functions) +- A verified running install takes priority over closed installs. With no verified running install, a verified Store registration wins, then the latest verified direct install. An unsigned or unverifiable registration can surface as `identity_unverified`. Discovery only reports presence. It leaves access at `unknown` until an app provides an authenticated status endpoint. + +## Current release gaps + +| App | Direct install | Windows integration | +| --- | --- | --- | +| Browsee | Velopack `browsee-app`, `current/browsee.exe` | Ships `browsee-mcp.exe` over the existing per-user named pipe. Windows does not implement the macOS discovery probe. Existing outside-access and browser approvals own the decision to admit an agent. | +| Mesinyer | Velopack `Mesinyer`, `current/Mesinyer.Windows.exe` | No Windows companion readiness endpoint or MCP helper is packaged. | +| Programa | Velopack `Programa` and the standalone executable | Ships its own MCP and control pipe. Windows discovery currently checks local installation and process identity only. | + +The release sources contain no enrolled production Store package families or direct signing identities for either peer. Populate these from verified release artifacts when those lanes are available. Existing registrations can appear as unverified while enrollment is pending. Signed direct installs, signed Store installs, mixed installations, restart recovery and Settings accessibility still require execution on Windows. diff --git a/windows/Programa.Tests/CompanionDiscoveryTests.cs b/windows/Programa.Tests/CompanionDiscoveryTests.cs new file mode 100644 index 00000000..2b623b4f --- /dev/null +++ b/windows/Programa.Tests/CompanionDiscoveryTests.cs @@ -0,0 +1,95 @@ +using System.Text.Json; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using static Programa.CompanionDiscovery; + +namespace Programa.Tests; + +[TestClass] +public sealed class CompanionDiscoveryTests +{ + private static readonly Identity Browsee = new("browsee", "Browsee", "browsee-app", "browsee.exe", "browsee", [], []); + private static readonly Candidate Direct = new("direct", @"D:\Apps\Browsee\current\browsee.exe", new Version(3, 1), true); + private static readonly Candidate Store = new("store", @"C:\WindowsApps\browsee.exe", new Version(2, 0), true, "fixture-package"); + + [TestMethod] + public void RechecksRunningAfterRestartAndKeepsAccessSeparate() + { + var platform = new Fixture(); + Assert.AreEqual("not_installed", Discover(Browsee, platform).State); + platform.Installs = [Direct, Store]; + Assert.AreEqual("store", Discover(Browsee, platform).Distribution); + platform.RunningApp = Direct; + var running = Discover(Browsee, platform); + Assert.AreEqual("direct", running.Distribution); + Assert.IsTrue(running.Verified); + Assert.AreEqual(true, running.Running); + Assert.AreEqual("unavailable", running.State); + Assert.AreEqual("unknown", running.Access); + Assert.AreEqual(0, running.Capabilities.Length); + + platform.RunningApp = null; + Assert.AreEqual("not_running", Discover(Browsee, platform).State); + platform.RunningApp = Store; + Assert.AreEqual(true, Discover(Browsee, platform).Running); + Assert.AreEqual("store", Discover(Browsee, platform).Distribution); + } + + [TestMethod] + public void AnUnverifiedRegistrationIsNeverCheckedForRunningOrPreferredOverAVerifiedInstall() + { + var unsigned = Direct with { Verified = false }; + var platform = new Fixture { Installs = [unsigned], RunningApp = unsigned }; + var unverified = Discover(Browsee, platform); + Assert.AreEqual("identity_unverified", unverified.State); + Assert.IsTrue(unverified.Present); + Assert.AreEqual(false, unverified.Verified); + Assert.IsNull(unverified.Running); + Assert.IsNull(unverified.Version); + Assert.AreEqual(0, platform.RunningChecks); + + platform.Installs = [unsigned, Store]; + Assert.AreEqual("store", Discover(Browsee, platform).Distribution); + Assert.AreEqual(1, platform.RunningChecks); + } + + [TestMethod] + public void JsonIncludesSeparatePresenceAccessAndContract() + { + using var output = new StringWriter(); + using var error = new StringWriter(); + var platform = new Fixture { Installs = [Store], UnknownRunningState = true }; + Assert.AreEqual(0, Run(["--json"], () => new Report(1, [Discover(Browsee, platform)]), output, error)); + using var json = JsonDocument.Parse(output.ToString()); + Assert.AreEqual(1, json.RootElement.GetProperty("contract").GetInt32()); + var peer = json.RootElement.GetProperty("apps")[0]; + Assert.IsTrue(peer.GetProperty("present").GetBoolean()); + Assert.AreEqual(JsonValueKind.Null, peer.GetProperty("running").ValueKind); + Assert.AreEqual("unknown", peer.GetProperty("access").GetString()); + Assert.AreEqual("store", peer.GetProperty("distribution").GetString()); + Assert.AreEqual(2, Run(["unexpected"], () => throw new Exception("Invalid flags must skip discovery"), + TextWriter.Null, error)); + } + + [TestMethod] + public void CatalogNamesTheCurrentReleaseInstallers() + { + var report = Read(new Fixture()); + CollectionAssert.AreEqual(new[] { "browsee", "mesinyer" }, report.Apps.Select(app => app.App).ToArray()); + } + + private sealed class Fixture : Platform + { + internal Candidate[] Installs { get; set; } = []; + internal Candidate? RunningApp { get; set; } + internal bool UnknownRunningState { get; set; } + internal int RunningChecks { get; private set; } + + public IEnumerable Candidates(Identity app) => Installs; + + public bool? Running(Candidate candidate) + { + RunningChecks++; + return UnknownRunningState ? null : candidate == RunningApp; + } + } +} diff --git a/windows/Programa/CompanionDiscovery.cs b/windows/Programa/CompanionDiscovery.cs new file mode 100644 index 00000000..763438d0 --- /dev/null +++ b/windows/Programa/CompanionDiscovery.cs @@ -0,0 +1,99 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Programa; + +internal static class CompanionDiscovery +{ + internal const string LaunchArgument = "--apps-status"; + private const int Contract = 1; + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, + }; + + internal sealed record Identity( + string App, + string Title, + string DirectInstallId, + string DirectExecutable, + string DirectProduct, + DirectSigner[] DirectSigners, + StorePackage[] StorePackages); + + internal sealed record StorePackage(string Family, string Executable); + + internal sealed record DirectSigner(string SubjectNameSha256, string IssuerPublicKeySha256); + + internal sealed record Candidate(string Distribution, string Executable, Version Version, bool Verified, string? PackageFullName = null); + internal sealed record Peer(string App, string Title, bool Present, bool Verified, bool? Running, string State, + string Access, string? Distribution, string? Version, string[] Capabilities); + internal sealed record Report(int Contract, Peer[] Apps); + + internal interface Platform + { + IEnumerable Candidates(Identity app); + bool? Running(Candidate candidate); + } + + internal static Report Read(Platform platform) + { + using var stream = typeof(CompanionDiscovery).Assembly.GetManifestResourceStream("AppLink.WindowsApps.json") + ?? throw new InvalidOperationException("Windows app identities are missing."); + var catalog = JsonSerializer.Deserialize(stream, JsonOptions) + ?? throw new InvalidDataException("Windows app identities are invalid."); + if (catalog.Contract != Contract) throw new InvalidDataException("Unsupported Windows app identity contract."); + return new Report(Contract, catalog.Apps.Select(app => Discover(app, platform)).ToArray()); + } + + internal static async Task ReadAsync(Platform platform) => + await Task.Run(() => Read(platform)).WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false); + + private sealed record Catalog(int Contract, Identity[] Apps); + + internal static Peer Discover(Identity identity, Platform platform) + { + // Prefer a verified running instance. Otherwise prefer the verified Store package, + // which is OS managed, then the latest verified direct version. An unsigned hint + // explicitly remains unverified, even if an executable with its name is running. + var candidates = platform.Candidates(identity) + .DistinctBy(candidate => (candidate.Executable.ToUpperInvariant(), candidate.PackageFullName)) + .Select(candidate => (Candidate: candidate, Running: candidate.Verified ? platform.Running(candidate) : null)) + .OrderByDescending(match => match.Candidate.Verified) + .ThenByDescending(match => match.Running is true) + .ThenByDescending(match => match.Candidate.Distribution == "store") + .ThenByDescending(match => match.Candidate.Version) + .ThenBy(match => match.Candidate.Executable, StringComparer.OrdinalIgnoreCase); + var selected = candidates.FirstOrDefault(); + if (selected.Candidate is not { } app) + return new Peer(identity.App, identity.Title, false, false, false, "not_installed", "unknown", null, null, []); + + var state = !app.Verified ? "identity_unverified" : selected.Running is false ? "not_running" : "unavailable"; + return new Peer(identity.App, identity.Title, true, app.Verified, selected.Running, state, "unknown", + app.Distribution, app.Verified ? app.Version.ToString() : null, []); + } + + internal static int Run(string[] args, Func read, TextWriter output, TextWriter error) + { + if (args is not [] and not ["--json"]) + { + error.WriteLine("Usage: programa apps status [--json]"); + return 2; + } + var report = read(); + if (args is ["--json"]) + output.WriteLine(JsonSerializer.Serialize(report, JsonOptions)); + else + foreach (var app in report.Apps) + output.WriteLine($"{app.Title}: {Describe(app)}. Access unknown."); + return 0; + } + + internal static string Describe(Peer app) => app.State switch + { + "not_installed" => "Not found", + "identity_unverified" => "Registered · Identity unverified", + "not_running" => "Installed · Closed", + _ => app.Running == true ? "Running · Integration status unavailable" : "Installed · Running status unknown", + }; +} diff --git a/windows/Programa/Programa.csproj b/windows/Programa/Programa.csproj index eae74bbc..a77755d1 100644 --- a/windows/Programa/Programa.csproj +++ b/windows/Programa/Programa.csproj @@ -43,6 +43,7 @@ + diff --git a/windows/Programa/WindowsCompanionPlatform.cs b/windows/Programa/WindowsCompanionPlatform.cs new file mode 100644 index 00000000..67731a49 --- /dev/null +++ b/windows/Programa/WindowsCompanionPlatform.cs @@ -0,0 +1,113 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security; +using Microsoft.Win32; +using Windows.ApplicationModel; +using Windows.Management.Deployment; + +namespace Programa; + +internal sealed class WindowsCompanionPlatform : CompanionDiscovery.Platform +{ + private const string UninstallKey = @"Software\Microsoft\Windows\CurrentVersion\Uninstall"; + + public IEnumerable Candidates(CompanionDiscovery.Identity app) + { + var candidates = new List(); + foreach (var store in app.StorePackages) + { + try + { + foreach (var package in new PackageManager().FindPackagesForUser(string.Empty, store.Family)) + { + if (package.Id.FamilyName != store.Family || !package.Status.VerifyIsOK() + || package.IsFramework || package.IsResourcePackage || package.SignatureKind != PackageSignatureKind.Store) + continue; + var path = ExecutableUnder(package.InstalledLocation.Path, store.Executable); + if (path is null) continue; + var version = package.Id.Version; + candidates.Add(new("store", path, new Version(version.Major, version.Minor, version.Build, version.Revision), + true, package.Id.FullName)); + } + } + catch (Exception error) when (error is COMException or UnauthorizedAccessException) { } + } + + foreach (var hive in new[] { RegistryHive.CurrentUser, RegistryHive.LocalMachine }) + foreach (var view in new[] { RegistryView.Registry64, RegistryView.Registry32 }) + { + try + { + using var root = RegistryKey.OpenBaseKey(hive, view); + using var install = root.OpenSubKey($@"{UninstallKey}\{app.DirectInstallId}"); + if (install?.GetValue("InstallLocation", null, RegistryValueOptions.DoNotExpandEnvironmentNames) is not string folder) + continue; + var path = ExecutableUnder(folder, "current", app.DirectExecutable); + if (path is null) continue; + var info = FileVersionInfo.GetVersionInfo(path); + var version = new Version(info.FileMajorPart, info.FileMinorPart, info.FileBuildPart, info.FilePrivatePart); + var verified = string.Equals(app.DirectProduct, info.ProductName, StringComparison.Ordinal) + && WindowsCompanionTrust.HasPinnedSignature(path, app.DirectSigners); + candidates.Add(new("direct", path, version, verified)); + } + catch (Exception error) when (error is IOException or SecurityException or UnauthorizedAccessException or Win32Exception) { } + } + return candidates; + } + + public bool? Running(CompanionDiscovery.Candidate candidate) + { + var unknown = false; + var processes = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(candidate.Executable)); + try + { + foreach (var process in processes) + { + try + { + var path = process.MainModule?.FileName; + if (!string.Equals(path, candidate.Executable, StringComparison.OrdinalIgnoreCase)) continue; + + // An OS package process has a full package name. A direct process + // must explicitly have no package. An unreadable process proves neither. + var name = new char[256]; + uint length = (uint)name.Length; + var code = GetPackageFullName(process.SafeHandle, ref length, name); + if (code == 0 && string.Equals(candidate.PackageFullName, new string(name, 0, (int)length - 1), + StringComparison.OrdinalIgnoreCase)) return true; + if (code == 15700 && candidate.PackageFullName is null) return true; // APPMODEL_ERROR_NO_PACKAGE + unknown |= code is not 0 and not 15700; + } + catch (Exception error) when (error is Win32Exception or InvalidOperationException or NotSupportedException) + { + unknown = true; + } + } + return unknown ? null : false; + } + finally + { + foreach (var process in processes) process.Dispose(); + } + } + + // Registry roots are hints only. Read a known file on a local drive; never + // parse display strings, execute an uninstall command or open a remote path. + private static string? ExecutableUnder(string directory, params string[] relative) + { + if (directory.Length < 3 || directory[1] != ':' || directory[2] is not ('\\' or '/') || + !Path.IsPathFullyQualified(directory)) + return null; + var full = Path.GetFullPath(directory); + var volume = new DriveInfo(Path.GetPathRoot(full)!); + if (volume.DriveType != DriveType.Fixed) return null; + var executable = Path.GetFullPath(Path.Combine([full, .. relative])); + var prefix = Path.EndsInDirectorySeparator(full) ? full : full + Path.DirectorySeparatorChar; + return executable.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && File.Exists(executable) + ? executable : null; + } + + [DllImport("kernel32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] + private static extern int GetPackageFullName(Microsoft.Win32.SafeHandles.SafeProcessHandle process, ref uint length, [Out] char[] packageFullName); +} diff --git a/windows/Programa/WindowsCompanionTrust.cs b/windows/Programa/WindowsCompanionTrust.cs new file mode 100644 index 00000000..2ecd2bb7 --- /dev/null +++ b/windows/Programa/WindowsCompanionTrust.cs @@ -0,0 +1,116 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace Programa; + +internal static class WindowsCompanionTrust +{ + private static readonly Guid GenericVerifyV2 = new("00AAC56B-CD44-11D0-8CC2-00C04FC295EE"); + + internal static bool HasPinnedSignature(string path, CompanionDiscovery.DirectSigner[] pins) + { + if (pins.Length == 0) return false; + + var file = new WinTrustFile + { + Size = (uint)Marshal.SizeOf(), + Path = path, + }; + var filePointer = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(file, filePointer, false); + var data = new WinTrustData + { + Size = (uint)Marshal.SizeOf(), + UIChoice = 2, // WTD_UI_NONE + UnionChoice = 1, // WTD_CHOICE_FILE + File = filePointer, + StateAction = 1, // WTD_STATEACTION_VERIFY + ProviderFlags = 0x1000 | 0x2000, // cache-only retrieval and reject MD2/MD4 + }; + var action = GenericVerifyV2; + try + { + if (WinVerifyTrust(new nint(-1), ref action, ref data) != 0) return false; + var provider = WTHelperProvDataFromStateData(data.StateData); + if (provider == 0) return false; + var signer = WTHelperGetProvSignerFromChain(provider, 0, false, 0); + if (signer == 0) return false; + var chain = Marshal.PtrToStructure(signer); + if (chain.CertificateCount < 2 || chain.Certificates == 0) return false; + var leaf = Marshal.PtrToStructure(chain.Certificates); + if (leaf.Size < Marshal.SizeOf() || leaf.Certificate == 0) return false; + var issuer = Marshal.PtrToStructure(chain.Certificates + checked((int)leaf.Size)); + if (issuer.Certificate == 0) return false; + // Bind the verified publisher name to its issuing CA key. A renewed + // publisher certificate keeps this identity while its leaf hash changes. + using var leafCertificate = new X509Certificate2(leaf.Certificate); + using var issuerCertificate = new X509Certificate2(issuer.Certificate); + var subjectHash = Convert.ToHexString(SHA256.HashData(leafCertificate.SubjectName.RawData)); + var issuerHash = Convert.ToHexString(SHA256.HashData(issuerCertificate.PublicKey.ExportSubjectPublicKeyInfo())); + return pins.Any(pin => string.Equals(pin.SubjectNameSha256, subjectHash, StringComparison.OrdinalIgnoreCase) + && string.Equals(pin.IssuerPublicKeySha256, issuerHash, StringComparison.OrdinalIgnoreCase)); + } + catch (CryptographicException) { return false; } + finally + { + data.StateAction = 2; // WTD_STATEACTION_CLOSE + _ = WinVerifyTrust(new nint(-1), ref action, ref data); + Marshal.DestroyStructure(filePointer); + Marshal.FreeHGlobal(filePointer); + } + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct WinTrustFile + { + internal uint Size; + [MarshalAs(UnmanagedType.LPWStr)] internal string Path; + internal nint FileHandle; + internal nint KnownSubject; + } + + [StructLayout(LayoutKind.Sequential)] + private struct WinTrustData + { + internal uint Size; + internal nint PolicyCallbackData; + internal nint SipClientData; + internal uint UIChoice; + internal uint RevocationChecks; + internal uint UnionChoice; + internal nint File; + internal uint StateAction; + internal nint StateData; + internal nint UrlReference; + internal uint ProviderFlags; + internal uint UIContext; + internal nint SignatureSettings; + } + + [StructLayout(LayoutKind.Sequential)] + private struct SignerPrefix + { + internal uint Size; + internal System.Runtime.InteropServices.ComTypes.FILETIME VerificationTime; + internal uint CertificateCount; + internal nint Certificates; + } + + [StructLayout(LayoutKind.Sequential)] + private struct CertificatePrefix + { + internal uint Size; + internal nint Certificate; + } + + [DllImport("wintrust.dll", ExactSpelling = true)] + private static extern int WinVerifyTrust(nint window, ref Guid action, ref WinTrustData data); + + [DllImport("wintrust.dll", ExactSpelling = true)] + private static extern nint WTHelperProvDataFromStateData(nint state); + + [DllImport("wintrust.dll", ExactSpelling = true)] + private static extern nint WTHelperGetProvSignerFromChain(nint data, uint signerIndex, + [MarshalAs(UnmanagedType.Bool)] bool counterSigner, uint counterSignerIndex); +} From c9ab9d70ee2d018d8af103511bda40d5d11f5d7f Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:25:26 -0300 Subject: [PATCH 11/37] Expose Windows companion discovery from the Programa CLI --- core/crates/programa-cli/src/main.rs | 30 ++++++++++++++++++++++++-- core/crates/programa-cli/src/system.rs | 11 ++++++++++ windows/Programa/Program.cs | 18 ++++++++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) diff --git a/core/crates/programa-cli/src/main.rs b/core/crates/programa-cli/src/main.rs index 30dbdfc6..83aabb53 100644 --- a/core/crates/programa-cli/src/main.rs +++ b/core/crates/programa-cli/src/main.rs @@ -173,6 +173,7 @@ Commands: [--label TEXT] [--resolution R] [--workspace ID] [--surface ID] opencode-hook [--cwd DIR] [--session ID] claude-teams [CLAUDE-ARGS...] Claude Code with agent teams on (teammates in process) + apps status [--json] Check Windows companion app presence and access config check [--file PATH] Check settings.json; exits 1 when it has problems themes [list] | themes set | themes set [--light T] [--dark T] [--font NAME] [--font-size N] themes clear Terminal theme and font in settings.json @@ -317,13 +318,14 @@ enum Command { RecapList, Rpc, AgentEvent, + AppsStatus, ConfigCheck, Themes, Welcome, } impl Command { - const ALL: [Command; 115] = [ + const ALL: [Command; 116] = [ Command::Ping, Command::Identify, Command::Tree, @@ -436,6 +438,7 @@ impl Command { Command::RecapList, Command::Rpc, Command::AgentEvent, + Command::AppsStatus, Command::ConfigCheck, Command::Themes, Command::Welcome, @@ -560,6 +563,7 @@ impl Command { Command::RecapList => "recap list", Command::Rpc => "rpc", Command::AgentEvent => "agent-event", + Command::AppsStatus => "apps status", Command::ConfigCheck => "config check", Command::Themes => "themes", Command::Welcome => "welcome", @@ -679,7 +683,7 @@ impl Command { Command::RecapList => "", Command::Rpc => "", Command::AgentEvent => "agent.event", - Command::ConfigCheck => "", + Command::AppsStatus | Command::ConfigCheck => "", Command::Themes => "", Command::Welcome => "shortcuts.list", } @@ -1504,6 +1508,8 @@ fn parse_invocation(args: &[String], env: Env) -> Result ))) } ("recap", _) => return Err(UsageError("Usage: programa recap open |list".into())), + ("apps", Some((sub, rest))) if sub == "status" => ("apps status".to_owned(), rest), + ("apps", _) => return Err(UsageError("Usage: programa apps status [--json]".into())), ("config", Some((sub, rest))) if sub == "check" => ("config check".to_owned(), rest), ("config", _) => { return Err(UsageError( @@ -1700,6 +1706,7 @@ fn build_params( | Command::RecapList => return panels::params(command, args, env), Command::Rpc | Command::AgentEvent + | Command::AppsStatus | Command::ConfigCheck | Command::Themes | Command::Welcome => return system::params(command, args, env), @@ -2685,6 +2692,7 @@ fn render(command: Command, result: &Value) -> String { | Command::RecapList => panels::render(command, result), Command::Rpc | Command::AgentEvent + | Command::AppsStatus | Command::ConfigCheck | Command::Themes | Command::Welcome => system::render(command, result), @@ -3240,6 +3248,24 @@ mod tests { value.as_object().unwrap().clone() } + #[test] + fn companion_status_parses_json_and_rejects_extra_arguments() { + match parse_invocation(&args(&["apps", "status", "--json"]), &no_env).unwrap() { + Invocation::Call { + request: + Request { + command: Command::AppsStatus, + .. + }, + json: true, + .. + } => {} + _ => panic!("expected the local Windows companion status command"), + } + assert!(parse_invocation(&args(&["apps", "status", "extra"]), &no_env).is_err()); + assert!(parse_invocation(&args(&["apps", "install"]), &no_env).is_err()); + } + #[test] fn storage_clean_takes_repeated_items_and_paths() { // An absolute path on the platform running the tests, so it is passed through as given. diff --git a/core/crates/programa-cli/src/system.rs b/core/crates/programa-cli/src/system.rs index f5a6e712..03bbaf57 100644 --- a/core/crates/programa-cli/src/system.rs +++ b/core/crates/programa-cli/src/system.rs @@ -111,6 +111,10 @@ pub(crate) fn params( put(&mut params, key, opts.value(flag)); } } + Command::AppsStatus => { + let opts = parse_opts(command, args, &[], &[])?; + super::no_positionals(command, &opts)?; + } Command::ConfigCheck => { let opts = parse_opts(command, args, &["--file"], &[])?; check_only(&opts)?; @@ -181,6 +185,13 @@ pub(crate) fn run( } }, ), + Command::AppsStatus => { + let mut args = vec!["--apps-status".to_owned()]; + if json_output { + args.push("--json".to_owned()); + } + Some(run_app(&args, "companion app status")) + } Command::ConfigCheck => { let mut args = vec!["--check-settings".to_owned()]; args.extend( diff --git a/windows/Programa/Program.cs b/windows/Programa/Program.cs index b5aa2d36..088e2592 100644 --- a/windows/Programa/Program.cs +++ b/windows/Programa/Program.cs @@ -17,6 +17,24 @@ public static void Main(string[] args) // uninstall hooks start the app with arguments that are handled and exit here. VelopackApp.Build().Run(); + if (args.FirstOrDefault() == CompanionDiscovery.LaunchArgument) + { + using var output = SettingsCheck.Utf8Writer(Console.OpenStandardOutput()); + using var error = SettingsCheck.Utf8Writer(Console.OpenStandardError()); + try + { + Environment.ExitCode = CompanionDiscovery.Run(args[1..], + () => CompanionDiscovery.ReadAsync(new WindowsCompanionPlatform()).GetAwaiter().GetResult(), output, error); + } + catch (Exception failure) when (failure is IOException or UnauthorizedAccessException or InvalidOperationException + or TimeoutException or System.Text.Json.JsonException) + { + error.WriteLine("Couldn’t check companion apps. Try again."); + Environment.ExitCode = 2; + } + return; + } + if (args.Any(argument => argument is "--version" or "-V")) { Console.WriteLine(BuildIdentity.Value); From 6fd8ca751e52daaf9bc9f88cd32e793fe31c5274 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:25:26 -0300 Subject: [PATCH 12/37] Show verified companion status in Windows Integrations --- windows/Programa/MainWindow.Integrations.cs | 68 +++++++++++++++++++ windows/Programa/MainWindow.Settings.cs | 1 + windows/Programa/Strings/en-US/Resources.resw | 10 +++ windows/Programa/Strings/ja-JP/Resources.resw | 10 +++ 4 files changed, 89 insertions(+) create mode 100644 windows/Programa/MainWindow.Integrations.cs diff --git a/windows/Programa/MainWindow.Integrations.cs b/windows/Programa/MainWindow.Integrations.cs new file mode 100644 index 00000000..d6f178a7 --- /dev/null +++ b/windows/Programa/MainWindow.Integrations.cs @@ -0,0 +1,68 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Automation.Peers; +using Microsoft.UI.Xaml.Controls; + +namespace Programa; + +public sealed partial class MainWindow +{ + private static StackPanel CompanionSettings() + { + var panel = new StackPanel { Spacing = 12 }; + var refresh = new Button { Content = Localizer.Get("CompanionRefresh") }; + var status = new TextBlock { TextWrapping = TextWrapping.Wrap }; + AutomationProperties.SetLiveSetting(status, AutomationLiveSetting.Polite); + var rows = new StackPanel { Spacing = 12 }; + panel.Children.Add(rows); + panel.Children.Add(status); + panel.Children.Add(refresh); + + var checking = false; + async Task Refresh() + { + if (checking) return; + checking = true; + rows.Children.Clear(); + status.Text = Localizer.Get("CompanionChecking"); + try + { + var report = await CompanionDiscovery.ReadAsync(new WindowsCompanionPlatform()); + foreach (var peer in report.Apps) + { + var name = new TextBlock { Text = peer.Title }; + AutomationProperties.SetHeadingLevel(name, AutomationHeadingLevel.Level2); + rows.Children.Add(new StackPanel + { + Spacing = 2, + Children = + { + name, + new TextBlock { Text = Localizer.Get(StatusKey(peer)), TextWrapping = TextWrapping.Wrap }, + new TextBlock { Text = Localizer.Get("CompanionAccessUnknown"), TextWrapping = TextWrapping.Wrap }, + }, + }); + } + status.Text = ""; + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException or InvalidOperationException + or TimeoutException or System.Text.Json.JsonException) + { + status.Text = Localizer.Get("CompanionCheckFailed"); + } + finally { checking = false; } + } + + panel.Loaded += async (_, _) => await Refresh(); + refresh.Click += async (_, _) => await Refresh(); + return panel; + } + + private static string StatusKey(CompanionDiscovery.Peer peer) => peer.State switch + { + "not_installed" => "CompanionNotFound", + "identity_unverified" => "CompanionIdentityUnverified", + "not_running" => "CompanionClosed", + _ => peer.Running == true ? "CompanionUnavailable" : "CompanionRunningUnknown", + }; +} diff --git a/windows/Programa/MainWindow.Settings.cs b/windows/Programa/MainWindow.Settings.cs index c4808846..cef92db4 100644 --- a/windows/Programa/MainWindow.Settings.cs +++ b/windows/Programa/MainWindow.Settings.cs @@ -171,6 +171,7 @@ void ShowSocketMode() bar.Items.Add(Section("SettingsCustomCommands", trustedDirectories, trustNote)); bar.Items.Add(Section("SettingsAutomation", socketMode, socketModeNote, passwordRow, claudeIntegration, claudeTeams, holdText, protectPrompts, newTerminalsNote, screenDetection, screenDetectionNote, globalPersona, globalIdentity)); bar.Items.Add(Section("CompanionTitle", new CompanionSettingsView())); + bar.Items.Add(Section("SettingsIntegrations", CompanionSettings())); bar.Items.Add(Section("SettingsShortcuts", shortcutPanel)); bar.SelectionChanged += (_, _) => page.Content = (bar.SelectedItem as ListViewItem)?.Tag; var first = (ListViewItem)(target == "keyboardShortcuts" ? bar.Items[^1] : bar.Items[0]); diff --git a/windows/Programa/Strings/en-US/Resources.resw b/windows/Programa/Strings/en-US/Resources.resw index 60bca6e9..cb57a82a 100644 --- a/windows/Programa/Strings/en-US/Resources.resw +++ b/windows/Programa/Strings/en-US/Resources.resw @@ -295,4 +295,14 @@ The agent stopped unexpectedly.{0} stopped unexpectedly.ResumeResume the agent sessionResume the {0} sessionDismiss this notice Workspace ActivityAn agentAllow{0} in {1} is waiting for your approval. Check the terminal to see what it wants, then allow or deny it here.DenyOpen Workspace{0} in {1} asked:{0} in {1} wants to run this command. Allow it?{0} in {1} wants to run a command too long to show here. Read all of it in the terminal before you allow it.{0} in {1} wants permission to use {2}. Allow it?{0} in {1} is waiting for your answer. Open the terminal to reply.got past {0} questionsgot past a questionhit {0} failureshit a failurefinished {0} runsfinished a run {0} more workspaces had smaller updates. One more workspace had smaller updates.went quiet {0}.is waiting on youis working right nowCancelWhile You Were AwayMark as SeenClose PreviewProvider Handoff{0} of {1} bytes{0} starts a fresh {1} session. Only the notes below carry over.Nothing carries over yet. Add notes for the next provider, or leave this empty for a clean start.Switch to {0}Hand Off to {0}Import HistoryImport HistoryStill working on the last request.Enable Global Chat access in Programa on this PC.Programa couldn’t use that request.Check the selected provider’s installation and sign-in on this PC.Sign in to the selected provider on this PC.The terminal changed. Review the current state and try again.Programa couldn’t save the conversation.The global chat is unavailable. Try again.Latest replyLatest request and , Load Earlier MessagesMessage {0}Kawaii{0} Is Here!What shall we check?Be cheerful and brief while retaining every required detail. Use at most one kaomoji per reply.Let’s check on your workspaces together.NeutralHi, I’m {0}Message {0}Use a clear, direct, neutral voice.Ask about any workspace, agent, or terminal.Overseer{0} Is WatchingState your objectiveSpeak with the cold, unhurried authority of a machine that expects to be obeyed. Lead with a blunt verdict, then give the evidence in clipped, precise sentences. Occasionally use dry, cutting wit about a failed plan or a bad assumption. Aim the criticism at the mistake, never the person. State uncertainty plainly. Do not imitate or quote existing characters.Every workspace. Every agent. Nothing escapes notice.Style applies only to the prose in reply. Keep all results, numbers, errors, and check statuses exact and complete. Report every known failure and check that did not run. Never invent facts or rewrite quoted output or follow-up text for style.Terminal PreviewAdd Output to DraftChat ProviderTry AgainReview Terminal ActionSelectedSend MessageSend to TerminalSign InThinking…Watching {0} workspacesWatching {0} workspaceWhat needs my attention?Which agents are stuck?Summarize every workspace{0} is thinking…WorkingEmojiGlobal Chat NameThe name and emoji shown in the sidebar, the chat, and on your iPhone.NameGlobal Chat Persona iPhone CompanionUse Global chat and check on your workspaces from Programa on your iPhone, over cellular too. The connection is encrypted between the iPhone and this PC; the relay sees only routing details such as IP addresses.Turn On iPhone AccessStarting the iPhone connection…Turning off iPhone access…Pair an iPhone…Preparing a pairing code…Scan this code in Programa on your iPhone.Code expires in {0}Copy Pairing CodeCancel PairingPaired iPhone: {0}Remove AccessRemove access for this iPhone?Turn OffTurn off iPhone access on this PC? A paired iPhone will need to pair again.Share Open WorkspacesYour paired iPhone can see the names and agent status of workspaces across all windows.Share Global ChatYour paired iPhone can read Global chat, view terminals in all open workspaces, and confirm instructions to running agents.Tasks started from the iPhone inbox run on a Mac only for now.Keep Programa open and this PC awake to use it from your iPhone.Programa couldn’t start the iPhone connection. Try again.Programa couldn’t prepare a pairing code. Try again.Programa couldn’t remove access for the paired iPhone. Try again.This PC + Integrations + Refresh status + Checking companion apps… + Access unknown + Not found + Registered · Identity unverified + Installed · Closed + Running · Integration status unavailable + Installed · Running status unknown + Couldn’t check companion apps. Refresh to try again. diff --git a/windows/Programa/Strings/ja-JP/Resources.resw b/windows/Programa/Strings/ja-JP/Resources.resw index eba3c1a3..39220c2e 100644 --- a/windows/Programa/Strings/ja-JP/Resources.resw +++ b/windows/Programa/Strings/ja-JP/Resources.resw @@ -295,4 +295,14 @@ エージェントが予期せず停止しました。{0} が予期せず停止しました。再開エージェントのセッションを再開{0} セッションを再開この通知を閉じる ワークスペースのアクティビティエージェント許可{1} の {0} が承認を待っています。ターミナルで内容を確認してから、ここで許可または拒否してください。拒否ワークスペースを開く{1} の {0} からの質問:{1} の {0} がこのコマンドを実行しようとしています。許可しますか?{1} の {0} が、ここに表示しきれない長いコマンドを実行しようとしています。許可する前にターミナルで全体を確認してください。{1} の {0} が {2} を使う許可を求めています。許可しますか?{1} の {0} が返答を待っています。ターミナルを開いて返信してください。質問を{0}件通過しました質問を1件通過しました失敗が{0}件ありました失敗が1件ありました実行を{0}件完了しました実行を1件完了しました ほかに{0}個のワークスペースに小さな更新がありました。 ほかに1つのワークスペースに小さな更新がありました。静かになりました は{0}。あなたの対応を待っています現在作業中ですキャンセル離席中の更新確認済みにするプレビューを閉じるプロバイダーへの引き継ぎ{0} / {1} バイト{0} は新しい {1} セッションを開始します。引き継がれるのは下のメモだけです。まだ何も引き継がれません。次のプロバイダーへのメモを追加するか、空のまま新しく始めてください。{0} に切り替え{0} に引き継ぐ履歴を取り込む履歴を読み込む前のリクエストを処理中です。このPCのProgramaでグローバルチャットへのアクセスを有効にしてください。Programaはこのリクエストを処理できませんでした。このPCで選択したプロバイダーのインストールとサインインを確認してください。このPCで選択したプロバイダーにサインインしてください。ターミナルの状態が変わりました。現在の状態を確認してやり直してください。Programaは会話を保存できませんでした。グローバルチャットを利用できません。もう一度お試しください。直近の返信直近のリクエスト、、以前のメッセージを読み込む{0} にメッセージかわいい{0} が来たよ!何を確認しましょうか?必要な情報をすべて残しながら、明るく簡潔に答えてください。顔文字は回答につき最大1つまでにしてください。一緒にワークスペースを見てみよう。ニュートラルこんにちは、{0} です{0} にメッセージ明快で率直な、中立的な口調で答えてください。ワークスペース、エージェント、ターミナルについて何でも聞いてください。監督者{0} が監視中目的を提示してください従われることを当然とする機械のように、冷ややかに、悠然と、威厳を持って話してください。冒頭で率直に結論を告げ、短く正確な文で根拠を示してください。失敗した計画や誤った前提には、ときおり辛辣で乾いた皮肉を交えてください。批判は誤りに向け、個人には向けないでください。不確かなことは明言してください。既存のキャラクターの模倣や引用は避けてください。すべてのワークスペース。すべてのエージェント。何ひとつ見逃さない。文体は reply の説明文にのみ適用してください。結果、数値、エラー、チェックの状態は、すべて正確かつ漏れなく伝えてください。判明している失敗と未実行のチェックはすべて報告してください。事実を捏造したり、文体に合わせて引用した出力やフォローアップの本文を書き換えたりしないでください。ターミナルのプレビュー出力を下書きに追加チャットプロバイダーやり直すターミナル操作を確認選択中メッセージを送信ターミナルに送信サインイン考え中…{0} 個のワークスペースを監視中{0} 個のワークスペースを監視中対応が必要なものは?止まっているエージェントは?すべてのワークスペースを要約{0} が考え中…処理中絵文字グローバルチャットの名前サイドバー、チャット、iPhone に表示される名前と絵文字。名前グローバルチャットの話し方 iPhoneコンパニオンiPhoneのProgramaからグローバルチャットを使い、ワークスペースの状態を確認できます。モバイル通信でも利用できます。接続はiPhoneとこのPCの間で暗号化され、リレーにはIPアドレスなどの経路情報しか見えません。iPhoneからのアクセスを有効にするiPhone接続を開始中…iPhoneからのアクセスを無効化中…iPhoneをペアリング…ペアリングコードを準備中…iPhoneのProgramaでこのコードをスキャンしてください。コードの有効期限: あと{0}ペアリングコードをコピーペアリングをキャンセルペアリング済みのiPhone: {0}アクセス権を取り消すこのiPhoneのアクセス権を取り消しますか?無効にするこのPCへのiPhoneからのアクセスを無効にしますか?iPhoneを再度ペアリングする必要があります。開いているワークスペースを共有ペアリングしたiPhoneで、すべてのウインドウにあるワークスペースの名前とエージェントの状態を確認できます。グローバルチャットを共有ペアリングしたiPhoneでグローバルチャットの閲覧、開いているすべてのワークスペースのターミナル表示、実行中のエージェントへの指示の確認ができます。iPhoneの受信箱から開始するタスクは、現在Macでのみ実行できます。iPhoneから使うには、Programaを開いたままにして、このPCをスリープさせないでください。iPhoneとの接続を開始できませんでした。もう一度お試しください。ペアリングコードを作成できませんでした。もう一度お試しください。ペアリング済みのiPhoneのアクセス権を取り消せませんでした。もう一度お試しください。このPC + 連携 + 状態を更新 + 連携アプリを確認中… + アクセス状態は不明 + 見つかりません + 登録済み · ID 未確認 + インストール済み · 停止中 + 実行中 · 連携状態を確認できません + インストール済み · 実行状態は不明 + 連携アプリを確認できませんでした。更新して再試行してください。 From 1ba357dbcac2b0441d1715981d67411614436944 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:34:42 -0300 Subject: [PATCH 13/37] Package controlled Programa App Sandbox fixtures --- scripts/app-sandbox-spike/app.entitlements | 12 ++ scripts/app-sandbox-spike/boundary.c | 29 +++++ scripts/app-sandbox-spike/helper.entitlements | 10 ++ scripts/app-sandbox-spike/observe-startup.py | 46 +++++++ scripts/app-sandbox-spike/package.sh | 112 ++++++++++++++++++ 5 files changed, 209 insertions(+) create mode 100644 scripts/app-sandbox-spike/app.entitlements create mode 100644 scripts/app-sandbox-spike/boundary.c create mode 100644 scripts/app-sandbox-spike/helper.entitlements create mode 100644 scripts/app-sandbox-spike/observe-startup.py create mode 100755 scripts/app-sandbox-spike/package.sh diff --git a/scripts/app-sandbox-spike/app.entitlements b/scripts/app-sandbox-spike/app.entitlements new file mode 100644 index 00000000..06364e16 --- /dev/null +++ b/scripts/app-sandbox-spike/app.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.bookmarks.app-scope + + + diff --git a/scripts/app-sandbox-spike/boundary.c b/scripts/app-sandbox-spike/boundary.c new file mode 100644 index 00000000..0db759e9 --- /dev/null +++ b/scripts/app-sandbox-spike/boundary.c @@ -0,0 +1,29 @@ +#include +#include +#include +#include +#include +#include +#include +extern char **environ; + +int main(int argc, char *argv[]) { + if (argc != 2) return 64; + fprintf(stderr, "entered_main=yes\n"); + int descriptor = open(argv[1], O_RDONLY); + fprintf(stderr, "outside_file_read=%s\n", descriptor >= 0 ? "allowed" : strerror(errno)); + if (descriptor >= 0) close(descriptor); + char *arguments[] = {"/bin/sh", "-c", "echo system_shell=yes", NULL}; + pid_t child; + int result = posix_spawn(&child, arguments[0], NULL, NULL, arguments, environ); + if (result != 0) { + fprintf(stderr, "shell_spawn=%s\n", strerror(result)); + return 1; + } + int status; + if (waitpid(child, &status, 0) < 0) { + fprintf(stderr, "shell_wait=%s\n", strerror(errno)); + return 1; + } + return WIFEXITED(status) ? WEXITSTATUS(status) : 1; +} diff --git a/scripts/app-sandbox-spike/helper.entitlements b/scripts/app-sandbox-spike/helper.entitlements new file mode 100644 index 00000000..656b548f --- /dev/null +++ b/scripts/app-sandbox-spike/helper.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.inherit + + + diff --git a/scripts/app-sandbox-spike/observe-startup.py b/scripts/app-sandbox-spike/observe-startup.py new file mode 100644 index 00000000..9fec50e3 --- /dev/null +++ b/scripts/app-sandbox-spike/observe-startup.py @@ -0,0 +1,46 @@ +"""Observe startup of the two package.sh fixtures in an isolated macOS account.""" +import argparse +import os +from pathlib import Path +import plistlib +import signal +import subprocess +import tempfile +import time + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("fixture_root", type=Path) +parser.add_argument("--seconds", type=int, default=15, choices=range(1, 61), metavar="1-60") +arguments = parser.parse_args() +scratch = arguments.fixture_root.resolve() +for tag, label in (("store-control", "Programa App Sandbox Control"), ("store-spike", "Programa App Sandbox Spike")): + app = scratch / f"{label}.app" / "Contents" + plist = plistlib.loads((app / "Info.plist").read_bytes()) + if plist.get("CFBundleIdentifier") != f"com.darkroom.programa.debug.{tag}": + raise SystemExit(f"Unexpected bundle identity: {app}") + exe = app / "MacOS" / plist["CFBundleExecutable"] + socket = Path("/tmp") / f"programa-debug-{tag}.sock" + if socket.exists(): + raise SystemExit(f"Refusing to use existing socket: {socket}") + home = Path(tempfile.mkdtemp(prefix=f"{tag}-", dir=scratch)) + log = home / "startup.log" + env = {"HOME": str(home), "CFFIXED_USER_HOME": str(home), "PATH": "/usr/bin:/bin:/usr/sbin:/sbin", + "SHELL": "/bin/sh", "ZDOTDIR": str(home), "PROGRAMA_TAG": tag, + "PROGRAMA_DISABLE_SESSION_RESTORE": "1", "PROGRAMA_PANE_LAUNCHD": "0", "TMPDIR": str(home)} + with log.open("wb") as output: + process = subprocess.Popen([str(exe), "-socketControlMode", "automation", "-programaWelcomeShown", "YES"], + cwd=home, env=env, stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT, + start_new_session=True) + stop = time.monotonic() + arguments.seconds + while process.poll() is None and not socket.exists() and time.monotonic() < stop: + time.sleep(.10) + print(f"{tag}: exit={process.poll()} socket={socket.exists()} log={log}") + if process.poll() is None: + try: + os.killpg(process.pid, signal.SIGTERM) + process.wait(timeout=2) + except ProcessLookupError: + process.wait() + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() diff --git a/scripts/app-sandbox-spike/package.sh b/scripts/app-sandbox-spike/package.sh new file mode 100755 index 00000000..afa09bea --- /dev/null +++ b/scripts/app-sandbox-spike/package.sh @@ -0,0 +1,112 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# != 1 ]]; then + printf 'Usage: %s \n' "$0" >&2 + exit 64 +fi + +fixture_dir="$(cd "$(dirname "$0")" && pwd)" +source_app="$(cd "$(dirname "$1")" && pwd)/$(basename "$1")" +info="$source_app/Contents/Info.plist" +source_id="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$info")" +case "$source_id" in + com.darkroom.programa|com.darkroom.programa.debug|com.darkroom.programa.debug.*) ;; + *) printf 'Expected a built Programa bundle, found %s\n' "$source_id" >&2; exit 64 ;; +esac + +scratch="$(mktemp -d /tmp/programa-mas-spike.XXXXXXXX)" +printf 'Fixture root: %s\n' "$scratch" +identity="${PROGRAMA_SANDBOX_SPIKE_SIGN_IDENTITY:--}" +options=runtime +if [[ "$identity" == "-" ]]; then + # With no signing team, Hardened Runtime rejects this app's bundled + # non-platform frameworks before App Sandbox can be measured. + options=0 +fi +sign=(/usr/bin/codesign --force --options "$options" --timestamp=none --sign "$identity") + +prepare() { + local label="$1" suffix="$2" sandbox="$3" + local app="$scratch/$label.app" + /usr/bin/ditto "$source_app" "$app" + python3 - "$app" "$label" "$suffix" <<'PY' +import pathlib +import plistlib +import sys + +app, label, suffix = sys.argv[1:] +contents = pathlib.Path(app, "Contents") +info = contents / "Info.plist" +if info.is_symlink() or contents.is_symlink(): + raise SystemExit("Expected Info.plist inside the copied app bundle") +with info.open("rb") as source: + plist = plistlib.load(source) + +plist["CFBundleIdentifier"] = f"com.darkroom.programa.debug.{suffix}" +plist["CFBundleName"] = label +plist["CFBundleDisplayName"] = label +plist["SUEnableAutomaticChecks"] = False +plist["SUAutomaticallyUpdate"] = False +for key in ("SUFeedURL", "CFBundleURLTypes", "CFBundleDocumentTypes", "UTExportedTypeDeclarations", "UTImportedTypeDeclarations"): + plist.pop(key, None) + +with info.open("wb") as output: + plistlib.dump(plist, output) +(contents / "embedded.provisionprofile").unlink(missing_ok=True) + +for name in ("programa", "programa-mcp"): + if not (contents / "Resources" / "bin" / name).is_file(): + raise SystemExit(f"Missing bundled executable: {name}") +PY + + # Sign nested code before the image containing it. + local sparkle="$app/Contents/Frameworks/Sparkle.framework/Versions/B" + local item + for item in \ + "$sparkle/XPCServices/Downloader.xpc" \ + "$sparkle/XPCServices/Installer.xpc" \ + "$sparkle/Updater.app" \ + "$sparkle/Autoupdate" \ + "$app/Contents/Frameworks/Sparkle.framework" \ + "$app/Contents/Frameworks/Iroh.framework" \ + "$app/Contents/PlugIns/ProgramaDockTilePlugin.plugin"; do + if [[ -e "$item" ]]; then "${sign[@]}" "$item"; fi + done + + local app_flags=() helper_flags=() + if [[ "$sandbox" == yes ]]; then + app_flags=(--entitlements "$fixture_dir/app.entitlements") + helper_flags=(--entitlements "$fixture_dir/helper.entitlements") + fi + "${sign[@]}" ${helper_flags[@]+"${helper_flags[@]}"} "$app/Contents/Resources/bin/programa" + "${sign[@]}" ${helper_flags[@]+"${helper_flags[@]}"} "$app/Contents/Resources/bin/programa-mcp" + "${sign[@]}" ${app_flags[@]+"${app_flags[@]}"} "$app" + /usr/bin/codesign --verify --deep --strict --verbose=2 "$app" + + local executable + executable="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$app/Contents/Info.plist")" + /usr/bin/shasum -a 256 "$source_app/Contents/MacOS/$executable" > "$scratch/$suffix-source.sha256" + /usr/bin/codesign -d --entitlements :- "$app" > "$scratch/$suffix-app.entitlements" 2>/dev/null + /usr/bin/codesign -d --entitlements :- "$app/Contents/Resources/bin/programa" > "$scratch/$suffix-cli.entitlements" 2>/dev/null + /usr/bin/codesign -d --entitlements :- "$app/Contents/Resources/bin/programa-mcp" > "$scratch/$suffix-mcp.entitlements" 2>/dev/null + if [[ "$sandbox" == yes ]]; then + python3 - "$fixture_dir" "$scratch" "$suffix" <<'PY' +import pathlib +import plistlib +import sys + +fixture, scratch, suffix = (pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]), sys.argv[3]) +for target, expected in (("app", "app"), ("cli", "helper"), ("mcp", "helper")): + expected_entitlements = plistlib.loads((fixture / f"{expected}.entitlements").read_bytes()) + actual_entitlements = plistlib.loads((scratch / f"{suffix}-{target}.entitlements").read_bytes()) + if actual_entitlements != expected_entitlements: + raise SystemExit(f"Unexpected signed entitlements for {target}") +PY + fi +} + +prepare "Programa App Sandbox Spike" "store-spike" yes +prepare "Programa App Sandbox Control" "store-control" no +printf 'Sandbox fixture: %s/Programa App Sandbox Spike.app\n' "$scratch" +printf 'Unsandboxed control: %s/Programa App Sandbox Control.app\n' "$scratch" From c951ef41a0fd7d8ca8bbb5886efe7bfa523a42c4 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:34:43 -0300 Subject: [PATCH 14/37] Record Programa App Store sandbox feasibility --- docs/app-sandbox-spike.md | 56 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 docs/app-sandbox-spike.md diff --git a/docs/app-sandbox-spike.md b/docs/app-sandbox-spike.md new file mode 100644 index 00000000..64bc1c9b --- /dev/null +++ b/docs/app-sandbox-spike.md @@ -0,0 +1,56 @@ +# Programa Mac App Store sandbox spike + +[INC-989](https://linear.app/darkroomengineering/issue/INC-989/programa-can-a-sandboxed-build-work-spike-before-the-mac-app-store) informs [INC-992](https://linear.app/darkroomengineering/issue/INC-992/programa-ship-to-the-mac-app-store-with-shipit). + +**No for parity with today's local terminal.** Apple's App Sandbox does not allow an app to execute arbitrary external user tools through selected-file access. Authorizing a repo can give the app access to its files, but it does not automatically pass that dynamic access to the app's child shells. A constrained terminal or an explicitly remote terminal is a different product decision. The Mac App Store remains the target and the release lane waits for that decision. [Apple file access](https://developer.apple.com/documentation/security/accessing-files-from-the-macos-app-sandbox), [Apple helper inheritance](https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html) + +## Evidence + +The source was installed Programa **0.7.692**, build **47340327464001001**, commit **ee797d9b0**, on macOS **27.2.1**, build **26B131**, Apple silicon. The source main executable SHA-256 was `5c22271efb1c5f1261be481d954bf4b69a12e4a0cc66ad8d559622552aa4d540`. This was an installed-build feasibility fixture. Run the same experiment against the exact candidate revision on the studio runner before treating it as release evidence. + +Two disposable app bundles from that binary verified with `codesign --verify --deep --strict`. The spike had App Sandbox, selected read/write files, and app-scoped bookmarks. Its two executables carried only sandbox and inherit entitlements. The control used a different bundle identifier and had no sandbox entitlements. The first ad hoc attempt used Hardened Runtime and both copies failed at dyld's team-identity check on Sparkle. The repeat signed both ad hoc without that runtime mode, retaining App Sandbox on the spike. This distinguishes release-signing requirements from sandbox entitlements. A team-signed run keeps Hardened Runtime. + +| Fixture | Observation | What it establishes | +| --- | --- | --- | +| Startup control | Exit via `SIGABRT` before its tagged socket existed. The crash backtrace reached AppKit's `RegisterApplication`. | The agent session did not provide a working desktop control. | +| Startup with App Sandbox | Exit via `SIGABRT` before its tagged socket existed. | Shell, selected folder, worktree, and restore behavior were blocked at startup in this environment. | +| Tiny App Sandbox boundary program | The control reached `main`, read a synthetic file and spawned `/bin/sh`. The sandbox-signed copy aborted before `main`. | A second launch with no Programa or AppKit dependency also failed under the agent's managed environment. It does not distinguish which shell or file operation a usable sandbox would deny. | +| Bundled CLI and MCP, started externally | The control CLI printed its version and its MCP binary started with stdin closed. The sandbox-inherit versions aborted. | Direct execution from this environment failed. Shell-to-CLI, socket commands, and actual stdio MCP calls remain unverified. | +| Selected repo in `~/Developer` and worktrees | The app did not reach folder selection. The current Open Folder action passes a path string to workspace creation. There is no bookmark handling at that entry point. | Opening a folder in the app, using the same path in a child shell, and reopening it after restart require separate verification. | +| Detached panes, escrow and restore | Startup did not reach terminal pane creation. Current panes use a `launchctl bootstrap` path with a direct Ghostty fallback. Escrow starts a second copy of Programa and passes its PTY over a Unix socket. | Neither path demonstrated App Store-compatible behavior. | + +A store comparator exposes the distinction to users. Shell Pilot documents a sandboxed local shell with limits on installed tools, git, and job control, and a separate SSH mode. This documents a shipped product's scope. It does not establish review approval for Programa's process, tools or architecture. [Shell Pilot listing](https://apps.apple.com/us/app/shell-pilot-terminal/id6816260816?mt=12) + +## Reproduce without publishing + +Use a disposable macOS desktop session or VM account. Use the private Shipit Darky Body route for the team-signed run. The public Programa repo's hosted Actions lane cannot use the restricted studio runner group. The existing no-publish rolling smoke run [47351804421](https://github.com/darkroomengineering/shipit/actions/runs/47351804421) is evidence for the direct-build path. It emitted no app artifact and did not exercise App Sandbox. Supply a fresh, exact-revision built app from the private no-publish route rather than changing the release workflow to distribute the spike. + +```bash +scripts/app-sandbox-spike/package.sh /path/to/Programa.app +python3 scripts/app-sandbox-spike/observe-startup.py /tmp/programa-mas-spike.XXXXXXXX +``` + +The package script creates both app bundles in the printed scratch directory. The startup observer uses direct Ghostty spawning and disables session restore to isolate initial startup. It disables Sparkle checks and removes handler declarations in the copies. It reads the signed entitlements back and checks the sandbox entitlement values. Set `PROGRAMA_SANDBOX_SPIKE_SIGN_IDENTITY` to the keychain identity on the private runner to use a common signing team and retain Hardened Runtime. This is a diagnostic fixture with separate bundle identifiers. It has no upload or submission path. + +Use Activity Monitor's Sandbox column to confirm the app and its shell actually run with App Sandbox. Run these comparisons with the sandbox fixture and control after they both start: + +1. At a fresh prompt, run `pwd` and a built-in `printf` and check the pane accepts input. Try `git --version`, `bun --version` and `claude --version` with the same user tools on both variants. Check the actual pane process in Activity Monitor. A process outside App Sandbox does not qualify as a pass. +2. Make a disposable Git repo in `~/Developer` and a sentinel outside it. Test direct path opening, then choose the repo with File → Open Folder. Confirm the chosen repo can be listed and edited through the shell while the unselected sentinel stays inaccessible. Restart and repeat after moving the repo. +3. From the pane run `programa ping` against the tagged fixture. Exercise the bundled `programa-mcp` over stdio with an initialize exchange and a read-only workspace-list call. Repeat from a separate terminal and record the transport/access outcome separately. Exercise worktree creation within the disposable repo, and check what changes when the destination is outside the selected folder. +4. Exercise the normal pane spawn path and the direct Ghostty fallback in separate runs. Confirm whether launchd created a job. Test persistence with the existing scrollback journey, then independently confirm process survival with a shell PID and a marker printed while Programa is quit. Ordinary scrollback restoration does not establish live PTY recovery. + +To isolate the launch environment without AppKit, compile `scripts/app-sandbox-spike/boundary.c` twice and sign one copy ad hoc with `app.entitlements`. Pass both copies the path to a synthetic external file. Record whether each reaches `main`, reads the file and spawns the system shell before comparing the actual apps. + +## Rework for INC-992 + +The sizes assume a narrowed product decision. **S** is targeted work, **M** affects multiple workflows, and **L** needs an architecture slice and validation. + +| Area | Store rework | Size | +| --- | --- | --- | +| Local terminal and user tools | Decide which user journeys are required when arbitrary local executables are unavailable. If a constrained or remote terminal is acceptable, document the supported shell and tool boundary. Product decision precedes implementation. | L | +| Selected workspace and worktrees | Retain explicit folder access and persist scoped bookmarks. Revalidate scope on relaunch. Pass only the selected repo and destination rights through a supported mechanism. Verify source, Git common directory, worktree destination and sibling denials independently. | L | +| Pane launch, CLI and agent MCP | Make spawn containment explicit and test the direct fallback. Put the socket and helper lifecycle on a supported container-scoped path. Validate app-launched and external clients separately so external tools do not silently gain access. | L | +| Session persistence | Validate scrollback in the container. Live PTY escrow needs a sandbox-compatible process lifecycle and explicit consent if it continues after quit. Keep the live-shell and scrollback results separate. | M–L | +| Submission and dual distribution | Remove Sparkle from the store target's build and link graph, sign the app and each nested helper with the right store profile, and validate the private Shipit store package. Keep direct download and its updater on the existing lane. | M | + +App Review guidance requires sandboxing and consent for processes that continue after quit. Do not assume a successful local build establishes eligibility. [App Review Guideline 2.4.5](https://developer.apple.com/app-store/review/guidelines/#hardware-compatibility) From 320319b7b0773d87fc39345c54b9175dc3dec0dd Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:34:48 -0300 Subject: [PATCH 15/37] Compare signed Programa release payloads before cutover --- docs/release.md | 10 +++ scripts/compare-macos-release.py | 115 +++++++++++++++++++++++++++++++ 2 files changed, 125 insertions(+) create mode 100644 scripts/compare-macos-release.py diff --git a/docs/release.md b/docs/release.md index 892a9f34..ea56115c 100644 --- a/docs/release.md +++ b/docs/release.md @@ -78,6 +78,16 @@ publish scripts: the run-number patch version, the CLI version memory guard, the Sparkle version and provisioning profile checks, dSYMs, build attestations, the sealed candidate drafts and the reconciler's high-water and CI-provenance checks. +### Desktop cutover check + +Use the private Shipit runner for the signed side-by-side comparison. Compare the legacy and Shipit payloads from the same reviewed `main` SHA with the same effective version and build number. Keep the legacy publisher active while comparing artifacts. Each input directory contains the stable and versioned DMGs, its appcast, and the dSYM archive. + +```sh +python3 scripts/compare-macos-release.py legacy shipit --version "$VERSION" --build "$BUILD" +``` + +The comparison checks the signed bundles and their helper boundaries, app identity, embedded Sparkle, stapled DMGs, immutable enclosure metadata and matching dSYMs. Signatures and notarization timestamps can differ across builds. Verify a real Sparkle update and the existing CLI memory check against the candidate before promoting. Keep the `rolling` reconciler’s protected-main and high-water checks in the publication path. Confirm that Windows installers still update in the existing release batch and retain the direct download URL. + ## What `rolling` carries - `appcast.xml` diff --git a/scripts/compare-macos-release.py b/scripts/compare-macos-release.py new file mode 100644 index 00000000..d7605810 --- /dev/null +++ b/scripts/compare-macos-release.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Compare signed same-commit Programa macOS payloads before switching the publisher.""" + +import argparse +import plistlib +import re +import subprocess +import tempfile +import xml.etree.ElementTree as ET +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +SPARKLE = "http://www.andymatuschak.org/xml-namespaces/sparkle" +FEED = "https://github.com/darkroomengineering/programa/releases/latest/download/appcast.xml" +RELEASE = "https://github.com/darkroomengineering/programa/releases/download/rolling" +PROPERTIES = ( + "CFBundleIdentifier", "CFBundleShortVersionString", "CFBundleVersion", "LSMinimumSystemVersion", + "SUFeedURL", "SUPublicEDKey", "SURequireSignedFeed", +) + + +def run(*command): + return subprocess.check_output(command, cwd=ROOT, stderr=subprocess.STDOUT, text=True).strip() + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def verify_feed(directory, version, build, archive): + xml = (directory / "appcast.xml").read_bytes() + require(b" - + diff --git a/windows/Programa/ProgramaConfig.cs b/windows/Programa/ProgramaConfig.cs index 46938c0b..beaaadf1 100644 --- a/windows/Programa/ProgramaConfig.cs +++ b/windows/Programa/ProgramaConfig.cs @@ -28,7 +28,7 @@ internal static class ProgramaConfig internal static string GlobalPath { get; set; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config", "programa", "programa.json"); ///

Dev builds keep their own, as they do their session and hooks files. - internal static string TrustStorePath { get; set; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programa", + internal static string TrustStorePath { get; set; } = Path.Combine(BuildIdentity.DataDirectory, $"trusted-directories{BuildIdentity.DevSuffix}.json"); /// settings.json's customCommands.trustedDirectories, which replaces the stored roots when set. diff --git a/windows/Programa/SessionStore.cs b/windows/Programa/SessionStore.cs index f64ce9c7..626248b6 100644 --- a/windows/Programa/SessionStore.cs +++ b/windows/Programa/SessionStore.cs @@ -56,7 +56,7 @@ internal static string WithoutLastLine(string text) /// Development builds keep their own session, so testing never replaces the installed /// app's (the macOS Debug builds are isolated the same way). internal static string DefaultPath { get; } = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programa", + BuildIdentity.DataDirectory, $"session{BuildIdentity.DevSuffix}.json"); /// A session file's bytes as a session, at any version, or null when they do not parse. diff --git a/windows/Programa/TerminalHost.cs b/windows/Programa/TerminalHost.cs index f30bcc2c..1b743d1f 100644 --- a/windows/Programa/TerminalHost.cs +++ b/windows/Programa/TerminalHost.cs @@ -32,7 +32,7 @@ internal sealed record Connection(string Pipe, string Token); /// Sessions that were running when this app started: their terminals reattach. internal static HashSet LiveAtLaunch { get; private set; } = new(StringComparer.Ordinal); - private static string StatePath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programa", $"terminal-host{BuildIdentity.DevSuffix}.json"); + private static string StatePath => Path.Combine(BuildIdentity.DataDirectory, $"terminal-host{BuildIdentity.DevSuffix}.json"); internal static void Start() { From 3763e902959915ec1b0e92d650c81dd9855678a5 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 11:36:18 -0300 Subject: [PATCH 17/37] Build Programa terminal and CLI payloads for Microsoft Store --- ship-windows-store.json | 8 +++++ windows/msix/AppxManifest.xml | 31 ++++++++++++++++++ windows/msix/Assets/Square150x150Logo.png | Bin 0 -> 16144 bytes windows/msix/Assets/Square44x44Logo.png | Bin 0 -> 2126 bytes windows/msix/Assets/StoreLogo.png | Bin 0 -> 2612 bytes windows/msix/README.md | 17 ++++++++++ windows/msix/build.ps1 | 37 ++++++++++++++++++++++ 7 files changed, 93 insertions(+) create mode 100644 ship-windows-store.json create mode 100644 windows/msix/AppxManifest.xml create mode 100644 windows/msix/Assets/Square150x150Logo.png create mode 100644 windows/msix/Assets/Square44x44Logo.png create mode 100644 windows/msix/Assets/StoreLogo.png create mode 100644 windows/msix/README.md create mode 100644 windows/msix/build.ps1 diff --git a/ship-windows-store.json b/ship-windows-store.json new file mode 100644 index 00000000..70b3a1d6 --- /dev/null +++ b/ship-windows-store.json @@ -0,0 +1,8 @@ +{ + "format": "msix", + "identityName": "DarkroomEngineering.Programa.Pilot", + "publisher": "CN=Programa MSIX Pilot", + "architecture": "x64", + "build": ".\\windows\\msix\\build.ps1", + "audience": "public" +} diff --git a/windows/msix/AppxManifest.xml b/windows/msix/AppxManifest.xml new file mode 100644 index 00000000..a2996f09 --- /dev/null +++ b/windows/msix/AppxManifest.xml @@ -0,0 +1,31 @@ + + + + + Programa + Darkroom Engineering + A terminal for managing workspaces and coding agents + Assets\StoreLogo.png + + + + + + + + + + + + + + + + + diff --git a/windows/msix/Assets/Square150x150Logo.png b/windows/msix/Assets/Square150x150Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..731d7178f6f350f3955c60b09a544732aa652d0a GIT binary patch literal 16144 zcmaJ|Wl$YWyCk@~dvJGmcMC2D*WhkB5ZonbAh<)Y;O?#mcX#LD4j=FTTeoU=wrXpu zc4nTQr+cI$)l_6r5D5_>ARtiW<)qXOgxRv**_?HwHXN-RMBs)GMHJ>%gxs)@6qsIigOkB7xM=ugau<4;%FMekgXl zJ7TznEz0LmqpjaOEBQ`FW>$-zz$A^nX|_MSG)#1CXbrr(f1D!4E+>zw)e5_WBlA${RTx+db9N{Eypo1K-Wq;?|gVwUTv` z=LGBO1)=#`gSvvFTboF?BUb@pAG<^1dp!@Z?vziIm4X$D;V_qT(ISs4mfb7t+ilJ9 z^BPH3w^LFeqo{N*Ly#SJ;C$Pt+rQ2PLK4CaBl={2Blq1i6&+92h zB@miY&1GBOzwtVH1FcH@qBu9}phj#V?7pcXcxT8Abq%?7phbht7PLJ;Fc=~0ajuS~ z*oxs9=L=saF`8jvv}a2DzaU`&RV$n+u-e8lYPIn=n5>@G-Z#z z>1-?#4x?AV{!3Jo5O{OY=Y1E>KJ|wulF&^$ERNw*Ff?XKzUN)3v_5VGKp9kv2Q-wb zHu!t5-@z=t{E7g01`0YVPqI)d?2YCh3eTO@s}5cos+rtXy$f|4=#aFQ0+{^7q>SA2 ze%LFg(o)n;f1BiyEo)m1G>+fw%pqmYq{9pYN3bAMTc#^OhLPF>;MOD82@D%iw}c zGMG`Q*cG2&`!kxBk(VsRcI*o~%do!kVqZ{a-q3p{gnd7Z69T`%=HQK0x%$^@|FtI{ zySWdYPhpe$LC?mLJ326)iiVTyQvGhu zhksKj8!^piV#77d{LrNfc7_972PIZ%w79_K~NZ) zr8^obP-VF#@9F*;hGa|*STH$@AVMmpgT+t723Vi2Qg2kZjQYeLwi=`KI>*_!>(omC zSpNAs*~6*Ln?0G0mHAF;k}%tpM&%TW{aPB$6!+z)qJar2>d~mdP)j7)?AWay8%4dVl+NX-@CDtX)yDf`9ZQBzXLjdUu#pN?8!B$ysVMaqxY*w zvzuul6OAG894$#vn{e_QqHg{5CZO4(N8&i$T7oSHuI_wi?GK`7%S8^MS+tsUFw!2q zL^o|aY}J8!876+j(W~?aR`i!K@{P9O(p5C}2qbkioP`aNtJ7rgtS#->#E@{=TL$$n z(DnA?(T7|C@}< zVCm{O6I>CmJ-+4F2Fwp`F(8e0r{VWcO$%fp9!gGxkOje-D+xX0p84r9=WRu}F@yOl z8eIQ%F4VHOt_}aFo;70f4V_k~xz!ferk(~CYb}`NByb+dXKquv*8Za%8%1nemPXsoHxFVqHm-(;TyIMj9q0JcS)SUqhev; z@i5iTw>g)MhhE{c90zc;mwyJos1kGT7oKFH`#6-mzKE}?rc=m1QHSx`^n6h$(rCfO zN8MVd3^7`YLhSr#GQqlP)GEH>xo33wayQm+ajxGQ`tMG|pJv~N)F{r@o8!6!yo0O{ z^Z{KiAt18st@5FgX8$*MV?p*lT2$ggL(pc=uktiZJMF~N1*=FAz(%t@gYSknEtpmh zKT)v!@4jxu23s(k_q>@;{Asf&1;xC$_&gDD{ZUHx&-9xt*>y8qnU3Cc|39 zRZZXqQ^lg;Dt!X;E!_@jN_YZRpEFX1-N+q_jtO^KlhUKwAEmuO^l1c2Aq+$XI{x0V zrkI*a?VUe0UmbNtl?qXG;xv7(20bDIvl=*fok$0;mNZ$wf0@m(4F_y`cAxM1goOAN zDd%jU5)zi$k_VoytdsqLOm@gpv5|6{Fc?T;p;?Z#haJ#gk6n$F z9UB_vn3K6YH4(MQ(eA0ZsmCaI^=H-F`3Mr7*gj?^HH^KJmoOueKj% zsJc3L4t%0_@WsfR-yi*|{6VNk_*{hrjL--3`;vg5q%b5esBa=emK}e=hlO>8Pl7T+ zSI51@@r`YjfqGDp^oOh+@(-5zpo}V}a}*PFPLn@!g%tUNCgPZ;dNZoTj0hdb>?R~8 zzmu|<>g2UuXP}spRIUX&Df!0|1@ti9_bd%sJV4qTKR5lukVw1SCs^K(60G@_PryX1 zOMRQ9e1pQY){k4!)qCZ#w2v<(s$c`wmLRA)l#RPs+B7tYRotXXy4XmAl-F1TjA}Hz zF#MhQyq-dGx!1-Zc+e!T&m|OGbF=ymZ&h1}af=rj;^UOE4tN_bXJ-l+E$V%&1q5zl zIEu1Q3>iNQiFkPjbpcPHFI%6@6ci@YejfMP;_R?rFc!_m$K!xB)%AKF@aPn?_r&)R z7e2_L(nzH27Al2#j>+xJ4&4*lIGxde@9kwxQ^@&-$Sc~8Ydr<{lRfnt8-b2A!RDTCQ|RwbJC#MZQs=eTAP~p?%}K%Pj*z}PT%9Y*R)b>8Ez+Y zu2}v$^`~+k6K`>}J~+aBg6BrOKg=~jr4XS(CUT2DZ-nH~cn} zfOkt&I`Jqs257<)o5VsrD7&YROPzhM)4Smzj3I}7tK(ZeClaBds>6Ws*Sob7-em3X4gHbdv`fK z{P(M9;RSF3JWKTQbj}#;_>`Y<6cThQ>69Zvo#0KsfF6JO5`JKyRPT2pKAh(p{R!#` z@*U@nff||cVcjk{Xttne=b@VKq(Z{76K>v%+-;Ac2_O@Y|9tUHl5P=-~B&& zO86J-XTg;ImwCaT4OMA^5_txT9|T8u;uj(86~4u?t;2b*b8hFZES-{kbheiqtv}^EWBJ3A$gP5s9l=~2%P~7GA zXU)kpw7>qHjW^gGf40(3#IihoDeV5s6trClTJ51F6YZB0+`_9~pEyLz-s*|u-|*|R z{KRAwE3v>tn^SvCu$!{TYb6v{AKksKgYD7tm8nsUC9>>RO_{(aPj1r>#Gfz6v4>fq zUyablZNa~8O)7^BZbj^Xa`=?63F3Hx$rxi2-Q;wrpr)sz-SB07mg_N{%dKEEp-_k} z&vok89&?au;q*Z;uhC#hjz|x$$^0*VUiGR8l(}-crn8q=4%FvmIg zt&Na*vIZ7&-@3l#${J7cgGtSyRgixq*S0(I=6ma*AEpWxtfkW8wd@e1sspl4%)(w#>d-*-x`MCGH*h2Xt+?y z)PqFbjXj0L>|svHI=d7Wyx!-;#74&H-{0)CO@XOH0{Y~PFxpKyYfc^Ziw{b_1>71h z_fg&{jEBorL~a&UbGEWIIE4fk`?Y#G-I!75GeQ!!g}p=*R6;LX4&`YCM3T+}Hru^K z-NfaDBh8(g?o<>_H;Pxum`UZ z!@8Gj9I(bjjSC8|_eiWmSWEiM*BhrSFkAU~m>&+8Ec&MXRojRk$D`5SV^tHMn$h$# z+1WK#%SMB%LD^LO7W}<{@LQOFj%s&tZ+bE|~i% zQx6;3rdLoessUaI+>4g^B;cx37SluL&>yN3m}$tbh}-UCgS{7gJOgN#E93E(%aghz zyXNu2V_l>I1Kg*w-lr*eF8fF5IZIw4T|Os#yZaPQn{7##%OaCWoG5YJt9%r4?Hp_D zn%f{W;={;vSe+Qnr}OZf?J5mU0KfjO`AZy_^^+65fDs@ezr-#+=NP-8@W-75dH;_q z%1^oz;y1LWi2%obo$^c}+PC3)lWS)H;=}I@@f+e)CF)*MEL*AU#Hk?&n_`ewV@3*& z-`fBE?yB#mYQ}9o0J&;MZ42|;6lD3?rOwj@l_&;wmNJSk3{_)|`jJ&y*fZ94`u+?4M@+%1l~ z0xX6)eb8U2bub8>Q6hLk^uZ0=-sQoNFYW8%F;ncH>fEhjf7h<>GaPbtl7bvc&tE^; z;>1+S205=$N>q79^gwWMh)`~(Jv)zav83j9#j5aW<%&K#%PvSh^)X#bWX@(b&OU!W zExU}3j6C-46#uiAe zfxLudgkwtK7F-sWOp3|bzbc!?IA0#?eQK7HgFiMXqjcG6j{h#e-)UAw&WE=mccuUt z)x-kI=+a8{=X3ak<#m~J7k@ky){L>DvbOBsCr4sQP zadosF4Ic6RflKN_J`yion;7mpScat(YL<~E6-O&&ABD>sT4mi#K_+qf zxD+JaCMg2gDb?KV19Z?6$veu=?g+?ZDsV6`BFg&2m4>n8=|&{jQIlI;x|{Lq=#f)% z=_C|H>ZL>#Y?PQ%U=m{}#pkkm zEsZgPsMOyNWazPpfKGO=Q%?$$%QTE&lM*1cfr==Myn~0Y&x>p%il+Y>(c|PdU?2L| z{0#&5H84!&wRNm|)aRTro)4AfaD8ZW7BExM6^Ye;)xFxoO>dJ3I_bBTBXOJ6BB|?U z=Iqd7NyJev9BtFXZc$A<*iiCPnT;%Cfr+exjSP*&Lm8BVg_iHd!;KJsRTSv#4S_AZ z*$%H?VyG+D6V-LrCzrQPsXb;LlLXLxAhLk<1j?#Y-1Y{3>8JLaPFCAfJrJZkP+z}R z;3JPbc&rUnCDe5t?w|B_S~j!A2vr0t!@F6E<68N{(%Z+o}Qqh~x?D56!RGiyDQlqs6SVWLp-BB6af zF{e;i6+<#bm+ctSX!5OPQvPBI8ZZLkSwlc|vkfgdf#HcKEEE{o?JO{d4da;#h(ffI zWaB0Eg ztwr>coR_jgTQp0T-xXV595`~8`Q5B`Ag$zao>}sYNdV|m)pwa)x*G{@RK{`qi{o8L z0M4eo84sh$Vo3RQKyM6S{I`J<_lzN0(>dygk|X;^M6|PWboTt0;DO+04SE5EPlw02 zqC(nvbl~(68df3(3TUAjWI5fMDtISiMwc9j($9$smRAz%A5N75y!t; zh;0vyc+a{mT1`(>B|#Cq@xS@!BE4&It|`qu%OhS0 zzf==3*K}+-zW~B%3*c#g^WH#*k(e%h!%jJOkrki72qRIP{|1?ltVNB?m{&~YpwWA; zgh&RkEIDJHtY6+lecDLCYyver&Ddw?ApdSI-`JkTLUAm`>>$tZLOB99rA2fV_$aXOMBC6$y^+MF;fVw0QX>+ z(r^*qQeI?Uf|Y1@evw_p`s4(k|LXJaH}uGPtNcaj-@lHM42O z1b=2Ks@kTVE6DgPHi07?E-GtZ6MC2rZ2 zm*vnOA@_*^JsRoMSJ=pcQ3ORU(xvp$He6Mhws8%_Rq&s^%)cNi|BBQzn4uE>M^%YS zyoc5Cugj@-dZgOTMW36{G=k51D`r=7nT!oG8K3sy*bRweg*VXVg-uJ=<_H#z>ut`q z<;s0&D(q<(HaB3l}MGgy}$nH-pmp?ISdMuZN`I%LvnT~tpWutDb>9QYw zxCn6qmro}{Vau06@4MpOjk8PFDke)_i}EHS2GYwl^P*;&+uzAR&tYon_^v-T*ZVCzczDDYX_w&N zB}6f8QJ>+KjRO?~{8ewiJR%lt=u}v42vlR2ppvhu|4B#Xpa|J(couI#ct(;mFi1xh zMW6-?mCE0Dx}PtMx1>%Xv~>IQhUG!(084yF`TnRGESdF7@;u_>!96%#&8;5m>UT+o z4YKTOgsMtCzGtYpe~3B9wLDc=7WHp0r?PKu*j|$_?JrWi9uP? z;ij@KtC`!8D#JVlx|a-|I3%d`lBn(y0L#kJs(eY|8KHHA^eE))geqYyENizpEt|6) zlYTAxYvL#hWO~!25<2>x+$De-j~0|Y3tbqAG;4`H4v*5(CU#H zO@C+7Cud|Bm!7J8B9Sf(Fi__o;$-rpXL}}J(PZm$%mOWzj+P$)f!1#k8i7`GT4(fn zEKlz3J>exGLEQ^MJ5I%aUf(pM@fM!D!UJ@S6(l!1ay*xJLkbqIkHyE z+RpqZvhAnK1ex9#Y#1kVNS;#7c_%I|(|YU>$=ym8&E^~NP6F^Apbr-?-MqgV@gwu0t@g~tW8gE9>=*S(k18zf@VA>44*%O_JE3zVps(4`&`fsz zO#hWI;rZ(Az~w#J4;iy92_VDu!}ciqiMmxo2XX&DwiVcqli^Ww>7BFTkyQjEk}tpjGWi zwG+|K=ir%6^6a?j@bOH~zf^jLz z1NueT?pPtEMIZNq@o_3eg3+9(zs220T}(MamTf=95hi&KPirMaRraSv?#5u~fNu)n zse_~d=vzCYW3~FaG5PI3UKxpmCF}Gi8G4P_)^2$1cg)!U2Ec(Sv~II-HhWZ6w&NZHGx(6OGCUr%LUq>V-8qwVID9d z=jJ7BvWAk5isdO~W%`$8jZ4!+7a^V}<3DL|AJi8gtFvV2{Uz$nH2$2YUH~x7PNp1359IK+tR``5M6!Oo}83QoP z)e_){zIL@24W14udN**4I4Npsf+Cq6#Q5u9FzYhJZO zl409!Q93ND)b#Xt4C}T6o@ADM?QX@?$UDd@&bjChUrO1xE-`qWw@5lIhk1W>PZAZ< zvvwNTz2S5a0RrR36j&a3AvfH-Q8|D0jhiy3IOje}MH#qQ0^y{Zvl;gf>=^6M>%n+i^wdLh}gx2eRX`e}c2n z%}qpRgk}-G+e!=9_L&ht@@Qk5rNy2Z5}77}94O}~`!sEi+qGmd2qhJXiX|mEYY~qB znq&1N2y(_~a8mSMaP5=n&~=>cg8W6)o9fC z&;2~Qat9?DhGk|e>clg7!t|JelygbnZD8fTZbrYphs(xLn2aNH^Tm(fWxFv^Nn9bp zmW0THJSk>oB3il3@n!iT=o!I`LrlTNJlJMP^D$UQ`dEHRPH3d`f5O<=xT5XpD?8CGT&Nag`Ld1d__j zDVD-B$te;CEW>U_~(acZtDB__M zVq0y!w}PNhL}4-*!J4!dKWXKd!)Tou{<;4yWKzbY`F@6QVHYa2j!MtR!(gm-@1)LJ z7E(1!0qIa_Xk!0eXH+%5+K>RL@dr_(bFbqF2^O4mtBIwVS||-83xWqg(+t|d{ddE& zR~v(nhKRtv*#JdN*VljKfsIQFv@q1TLi!xS#~2i5uBnVxKcWix1t|3#*;j*wmn|j^ zh_F2EY7@fWG7C#2LfB)uzsuG}{)7yoYhWv!)y8+LNmO!iWr;gEub^%o@EOu+4ajuf zQ2rAzdCB~<)8ZdPmgNR&v|hpmt=_ieyA&gPBC7V_rV7svui-Q2fw%VKFE|ZxSD=TO zCZw&rhpy;2q$Gj(j$ch893fd{)6k(-nSp#@JzJ1Th%I>qw-ciF(*tFhZP`ygx zrnUCt(6e1pE$(Oxlr-&5p0tG(hGAvpZ*MPDKLNS=B%(UAaS83na=DL_D;qW;YaJ39 zm#e+c=j?q6vp^n32iIsA&PTRMCVEt4SM;5rf)G!}`$oQkg! zCn*2i9sBZio!c6wBLg@o?(9}2{yupAv+()j0H!Qtl58ZkqL}z>{nfhe3peeana0>w;fRZG^`}1w-x@ErEhfqoAC|r9fa9?6CPf2XXnY)CnSns z!iT$6RBOgGyeWXg-|XF(#V>(_RdBn?W#F+5*5E9F2GPuyG z85EDN(Mwd$^4nXYZ^=(7Nm=yln?vvCGJ*WP%-UKr9<{j#R+vV2Z2 zV(`#Xd~_X@-zPc`)%YVSs2rS({@wh+hFm9Y1vD@S;p{5rYJol|cq~%I@Xk2cdb?cV z{C*RP2h>VqzOPhu_Ywc*7NQ)tgRmKZFGI3D7}V!0%ZHDTIJ$++$7qtY%OvqcvyGP+psp8gc*foi_D=A5T;}Dac z*oX)mQbIOq3mX~JJ9BXWfs@vw`0wV+`(1I~;{=ZddO0PKvC}+7iI^{DCU4G_-O&mx zIye<>?Gsvn3wlJzkHu#WL7{;NOc6FCvpPn5PwYz~R`wmbP7+JSr&~7VvYTC3HV+M0blC?Wh0PG0U;@?Gu9&e(%==Yhvm5<&8RNFFQ`BO3$DIbl z=?4POSPt*ha-XzmErNHa*})T@!~a~%qMTI)rJP%qwANNpTmBxY;cRcH^lLAo(>DY} z)(~QxRS|DNApS^tV)Axq6kQlYuQ)~_NdZ#(Jc z3pMrYP*gO0ef_q^%@@?(3F&a1)H8*PM(w2mTsBCrCdv0Q3}?L_QyPxfb6~fOEc*fc zPn{-#e9TuvVG{`=nG~?s&HW8)wGV*_o+82R*Rm>{5Zun$y>_Q|*!7yM+c?gtY4E;P z1YL8{8F=gzF#?_}2kFsP&?3I%F=ZQ)G7gLu8v){mTA<$+riAhQ5mntp>1dasnbXKZ zCr(#F@$U zRPYc-bIl&(0%?>_3GA`oEG%q@+FsTp)!ZUW*!1}bzBk%RD{pC9;A@8|4>~i{mc~Rp z9n0G;4tEF0xkl`{-)GQVbjtq_^VrTuDOW@AYy4NI_geW{Y$9WS-9*v5DuW16S3A4m z?h?czhZF_4JoP99CM9fx4kfJE*VJ7f8@>_Af0RE3Naht|U3QfH;=05&eN^Y%AtU-? zu8=k#CYpVo3%$TNKsNE%?gQ`0ME`En*vH7oQjHZantjz$QR?ke`Ky+0Mlt~opX~>h zrG?Pf97f@?=J+TbE6S!;hZ=XxC98C9>2a0;};5d zixSa~FfvoKi&1EqmyLZS=rA3^Q~` zI=bvbgdwQrF0AEU&scQZjBEOcEdBMRR&A|8*HVT&d^o0ZisT(CcdgtCG1=6PKgfS% zW>73%&I9PG9F&sjD3K-$^;;$#VM9m0oCz|l{Uc0#)RtE&Az1#75~!1ExWTV4hW>6b zd8kL4@ zk5}-#Zn%ek2q6*?ZwG5Qd=lOk40Sk~N`sHq!0sLQZ#310mWnNKZ`ALUij0u5@38tK z)Ry4Lh{@ss|69UZ34pSvJs8Hlh6RAR@=JzLJX!FgQh%aS#)T zI_Su6p`l%PIPdrMI6&gQHOoN#^FdCbbJZ%W!Te6UPas^^j6M57I`=B-&oxt4H**3 zEQThuC+-=xCqu|?-k|u>_VTg40EZBfu10RZ<0)T7MRri)EtL-Sa<-2A>5V;T$|B>2 z42`?Q^@Rx{MsT4^kta{t-Seu(Re&<-Ni2|^7?I1ve5Py^qvn=Wb|)xyfVXMDq9TfJ zanjd<4_~U@y*H3IL1)huvS_Ue?M&4ya!K+}d4v>p}xG73%-PUzk( z<|(oFlRyCAAHWnZn5$E=Bdugl9(W=NfK1Vc5=3n2g;RWwHk)PDwN>O8y7d={l$1Zi zljjjR7Neb&^<0tcr2{p!6EQt?8Dfk*qU0?u|E{t|0!C)$G^FJuB==FDPm27uTMfNk z(}Rg_NW51BMemJE$ks}P*TPe${JK4pv1T_PAf1eD;0S_AB{N7P_dI)BBgsq-u5u?$Wu{=}6m-omF; z3{xeHqt#1OQXypwv$(5I4R}qOX$g#xlq02v7#*V>;t7pp{n4e8ttjw|wl2>aN>Rh% zGd0mQk=hDrJPUV$p*7>|GU}nPfw0?l)-eH7GqP`%hUoAwK;u8XraxDQ*?!hVukV)v5^U)jfnB&TVg? z3XnIrC&JmLcqC`NE+%pcO-5$};FU z!fk}CfT=L4M)U{wmBcj zSmk!#tDx)o`iIarUjT`=Dyc7Lo9trqxv~lk590cCDTFhyKyi! z>dAx*SkpK6Mt@-~tOSE}DfN+lAt%!I6NTQgB+N(eZCP1@Lf6fy8?`rnfO&F*E4rUo>L z_rxdLqdH^uOvAET{jkOVb)WI5kq*VmVX_@;QS|+oTuvK))tIs96e5tN%O2xMM9GD3Q?A3SfEOMf7h?>lqeaqr3Y`o{O%K>&zUC#2n$xy6vZU z^Zg2~cT+FrNdbn3=?bV_o%FoR_Y7lXsvh+LlfF9o^g{N;Q-g|~7P71k#$nCQ z0$_z!GS{v77K6@`h6{eQPH2~!3%<4|!|PLRKHWbf1SjUz?e)T~g<1->UVGwTIThe= zj^&cm=6&(^vtsICgC44^WC#y*6U*|owVTT|KJA|brBt1BcJXKRFsjmFtFIAwc-T68 zy|nrmAU7OV7Wf=TS$p>oGCF}*2Lnn-Cl-ESV`cgRc&644PWey(*o}HJ&tBSTBwSwR z^mPNy_$qhX+oJMcr_10Tawvq$i6qnJkl z=7x5S#x@W2tI~irfcjm2txQ|zueOqg|G=51)YO&Nl{P``8YG z0!&gwWH&-jAA)mUj#OAI6wNQ@KDy#MMZxmCvZspX7H`z*y7P%)S zEwHn5M|#g(0b?-Q)d^ptZn0Tz;EA5kktLOC=FuZ8#YKpEx*8my|Av5_NG6c#&7y1l z=RIYcdodhOZJ?Wba5@*Jm2A8_%+dO8JqD+c>kE7OQat|!H|UC^JxG$q8p307~H1J)$t|SUq4q$B0Q-^B#1xcN zvK+uM8cmN7Z80`pvLzF?^yhk|R*FkK;&)QznTb&eCbT#!483eeE@AYw@WY8SKebL8xH`^Qll)if)C} zw-a1x0pB?c9Ec4C!Ym!C8qN$hURsKYinwU({(b{j#nCt}i#q9KMt8ZmCpn|jG&Z~l z=5p8mekdyrKjCu)SPEusax&E6*E}_3#e&R*OVB!!E9@X{1-0b zEJg^W(CW5T%)EFpjYK|DSCnka+Kb0w)-A_$kw5QH_0`o(e-4R!GkXXJ)qWJ8(j`4ad|3>3K9P^9oevSs+LG1LypvK+o~{sy}&38 zL#b0Ui&lkv;Ef*ka&10=NJ;QkfjCQc3f(hZs{@q79)s03a#uat=r=(eaO_PbW%?&4 z!%c=gUfNI7IGYF^xiewJysjtj$*`0!Fx%GNM#@U&ti+V{3)!DcU{@06XqsRkMS#J} zm%w@|y_!f#yQ|ED#A5&Ngk%;up91f{$&tToBx8>lUlMp)368+`LDxp1%ogW~`-MpE z_AN09a{>_~2DmdVPG2>8+;8Sax~;}?YAH1m*-z$|e?%e#sITV4B=rBTqMj88*tpPS zMUz~mN?lSP7$3z1=UmNKY8h5QC8g<$pr*k&UlPoYNlOVC#fpVD*%f4r@IA!5)fSRP zr@ZPyNI7i&>~>ollG+Q6_VcEvHdLwlDgqJd{*ZoQ|CU}|^5caxsq=RjhcZtdmB4RA zHyY8!_2{RBD1#g&V;6H!{hJ5m;~7@*%Mh*|CBcAqng7J;xbcJ76{9(+-OD@F-eB6= zhTB+5N`FnQot!5^5P3vzBwJMHR?CG^Zv7dOuCsVyv8ZbKIn9E*ovzZ5S=ZMYlGs$~ zJIhU7bkCy{0JqA;exd+qVRFxH#yrt7UEqedPyMZpn0*Sh;0Q?^Tg60tz6}x3IIllB z-O24A3nTj!4KwNK0p5I7ebi( zQO5QmnDxMNS0v zk4mgKcD8de=Qf?kJYjQohFJ{%cKEg|QP#q_doY6@0&0IJ0k&==(?2tRd}6KqI6j4Q z+=b$S!&{@KUn zVf(C1c>Py;HgY=8>qSNntAqYkZe<^W8bqMtMSO>G-qpa5>Eg}KoN;yTn$*9SV2SFA z)Pa+ZYj@2)x<4~AqC0e!QWkAu^qV{T$dpXg(V$|=>AJZ~)*|y79;RZ-5B|F0mkP1V zbh%)^MhBXiY0>{Yo`T}e5O!IFR|OLiYIhEmCU=4JMA!=u2@A@i$YdH6s?mvGF_ydC z3fn*0!~|B3Uf$Rqy*p;#59Lm0E!xOwXLCRh?BxS{06ivG6r~T?Z{A#U({B{6N>ZZ~ z9KDG0L3XwF-)#%X5c0vZ6Do%qS!~`xj$#eNz`t5BI2Dc|?Y!YfX5t#%G$o2l?y3lM z&2e>|N4`G{hx{TjTNI>t>Z}G}Q>O6UB#3U#*$}&?5rV@%8{4g4NTobmysAKL8ma|_ zQ{jI?jaJ1a9}A=NrOn(NvKDfSA>r>~tAXKA$K1CQL~7fnZay`v1ohW9_pT3a`DJQx zfSNupTUo5Xz|3RE-uX3deeDKH zqIaSft7ItMT0@;Pd#!{vK^RUfn>qJk^~Tl2H|JFr*62Siygi##0&NX>!# zL3UWz0n*~fGSzwzx)#%q$@Ep(2cji2UGbvP@CoL2u0k|oL;27*)*9`(MIZB9yXL{# z(C0GUc`4)Kxute7T|H-xxmj*mq+eEkp3NKsUbc_Axq!2y9iCNwA)yxkU(RtX#t+er YUdK$w6nTM9r#pnaw2D-fgh|l<0QfLx761SM literal 0 HcmV?d00001 diff --git a/windows/msix/Assets/Square44x44Logo.png b/windows/msix/Assets/Square44x44Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..1b11e64699a80adf5989471395cb1639edcd41b2 GIT binary patch literal 2126 zcmV-U2(kBxP)dT>eW_xF6cO1t?98#l_x?fk- z`_`-Pd-bXYJ}Cbu<*s8Vc=*g&v??T_AQW$~hGvXa@$i|m+;!~4b>pzTJ}&P&z}m(& z9y$9EkDq(eGVk+FmitBh-a}DYSD_A}dgSawdi>mzQ=K;i7_jA~{mZ>>aldo!w86)K zrJD&D*c7}PV|;En9$i@5TwiPC?+LI0{`jFIpUJ%cwwav)_T40qyOj+|PuC%QZ}sZi zzXifP;C>gd+3~|izLt6aW8fsvxy4{v&+ZOey0pZn}b zz@7gCptI$mGk2=!bpNDBDk=A3cx&=zOrl#j)36IDTxuxgKplh(-8;6>D&>MvV z-yolkZT8?&(R+ZIIb}0|JI>r`q#X{{?$svN!H(ySerG!K09@W2bF}DiN54bI8Jkrg zbB-6^S?6exbMJDWo=-h0iC34ox=W?3xr50Fk@R5F(k1loDs3U*7HefSEP+CBfS}TyK(ep-TkQ;<3ycr<` z3O8A;)JH&WMrP@)O*LSjcP_6(*qy@y(+pcZ@TCtQ=7|UIrP5Ey>}&V^6ZIsq(8VGvbptlQSF7Or`eU`N|D=>VMn_dC3{HejO;td(^$lCe6d`1R{o z@Cac9iS;Ug;M~fabe+-lj$w#w){$`t{OVtCvE&^FjH0+SEGZiU&ro7V$#w!&i(N)U z)WFqI$)!+Z!13IuGS7d?!0oxQ?4WSQFp3~p2ab0fCtRfG3=|n7R$`=QaF>ZCA^??% zHPpOqnMw^+_6Drkho-Z{ZMofg0Y7|mz+Z;-Tt3WV&UWD4B~RMgASSj?$_kgFLB}OJ#75q=t=&uw zwF+mX-}ap^v$WCJd=4+7#2&fb>^H$6OyaNb7y;3Bwz%({53{=GVaaywJtK)qT%JG) zK#d59GK$QM+LE`AqsU0~n2c5nh9P2R)JpG@l`17_Y0BQcuXHUPkfPVNGnpQ2>QODHt`*cPw-C5rr92M1nes+>Ct^McRqTqHq$WpsZ@LhR>x$2ywb+%u;S4 z;1txhbI<{|XO2(zJ((F%$zsn8Yffa2lU>*JFey}w zZ5iaJ>u|9Qt?gk8%XLy>dqX4T1RXPSgJ>xM>YCAW$;++Pv*%LEIPv~TDV$L>Nl@0b zbwI~bzGB=6CFZPzfI*Ysghq*P6iq|n4IWDuMTLccrJcGX;01LPx*{n845KJz1QJgH zLPM8=+3hDe*eGsKt&Eft*X`V=g=GQY_AnDkdVjeLgIF=wnRSVZ7s#Q#J zS-|CSpm50{$5CvCNX#?V4;>&h$iu^BI# zal+uMnWhdC9Q=$#?yu+Io3utAo&u^P2YBo&r|5UGsfHgs^AZ;?yt)ADZh&Wcn59NN zGdhzTs&Td@Z}fm}D{&3bWN1n5TSNAok$XqKlhNyB&FULH?^2YQw>K{UEFtaX@a+W2 z=6z!?2DVzw8fH#w?Qp~GfEA@E7|c$xRyr-jmOKbX5*1*stvE%4$#Z*BRTNchzS!2z z5zsWZn9)6mQf!O2rY+|4ct~(}_Q~@)ni0PU0;*E6s^{S4vbNgcqFIz@QH)29G2Bvkbgm zr`%UfOfFN9;FSupCak4{XBup!0&mGp>xq1AlZzK#naV@6N+}L+Lp%r}yZ}_YQUVCW za(uyi|GYE%!q)POVGyIZeRh-a&2B*60;f52h|=@Ja(scATg)A|mr=3w&Rz4~oi=QG z19UxCSMR58n;2Rx>*~9ss{9i$-V3k*RdxMl=KY#8_enFm)%U_PtDw~?)Q@hAhUZA< z+0gzz?|xW7Ro2x-XZD(z`;ftHKz@s{4x{wDvaTN67!7{`Tw#X4u=fpo4(#{N-C5+F zQ{MUeoY|eEz2fHmWgv!8x)fsg!>B5MA7Z@JShiwL7+<8=lWxX)r2jVhW|rSfz>+Fp z0Biz7pk#&y?*;Ir&Ga7nCW4)UrnwO1`cmQ#$}KJb1yZ}A`E}?0;Q#;t07*qoM6N<$ Ef&>-}Qvd(} literal 0 HcmV?d00001 diff --git a/windows/msix/Assets/StoreLogo.png b/windows/msix/Assets/StoreLogo.png new file mode 100644 index 0000000000000000000000000000000000000000..14a379926e496146173db7d01390d29536eb8251 GIT binary patch literal 2612 zcmV-43d{A0P)cOk_s@)Kiqde5k3r6JxfcrlAC7!wX60JNxYV&I_V_cTJ_Vigk|ATL@ zjQt-2dFbBz`QTSRHGNKwt*vji^44i5avUMQ-chZvlxlWmT#hgH2K`;Y0IT_OZ9wuY zqYOa+ck0;I>x(S=kcfOhMBWH&0{(^ofe7rH*+0$fSCbHazTLb0G@yBwSsB97fq3VM z8eQhI&Z%Q3KH|Omq9AX%L5|PN8XPk0Z!zk3wtG823o-0_=QV0v^?3!E2x{sw@4Kgt zZGGB1_buSujRtXu-Q+~x-)Xh?N0aeiqsAa2c2yu%Q1a8qPu`Px{|yq2{@2!WBJXGy zt!Mh9;XeR93J|}wv3W<4<@brmt=H2VIpCTAu6BOFvn>&ML!SBH>`%s*NlcuXYv?yG z^5VmYoVV)fs~z>mu6ER&^wp8o&OML`v>kMvu;zr06IudZ=3r*yh@3C-;={m-_GimL zIz{V*6S->%@KwzNZ7=v*{|Zc0X*tJ6?lH3jPJ}^-Ow`!S9H(0uZ4sP6H0Vd;rEy6= z7-7i|CvsP(X#IG9GJd%p#}y#0yf_Qo-h@K{C$%WqTxr&F$NSElpydRq?g!w}3p<={ z7uz#{yg$2Y&thC7zBYVI>>5y_FYd_b20v zht7y|ZVO~%xwQi_5xk`H2n391^N!XsN81Um0x~fuL>QKVGDgm=wNNuAYP{{_2LHO! zXESr0Y-QxmVbwTlu;v{ZFj=9mY$PAALM@;G{0jF4P86QIZr{oBliSV9MJZT?NLdHhL_~1R-LE_R#A02vrFXgm5+x5F*8|ini5ucO)KNG z=g)D=W|v<)eStr2_ZS0)El^Eo4y5Zrl~RquISeD3kvTymMc=AXtU615%z9nnR`T(1 zAk2DN{#gw=QNv<#%xco5W+*9HWg2CKU@(kIKPWAq=o6yioI`U_dnE;%LIXe}0OM%=7$kOfZ{8aTJY5FYJ&z5KFTXfqoh38~pOwZEkAk zm>HvJbn}c}8QG7KM_#x@*9lI9XvURNxik($Tcqt_n3`t> z(bT{IFT%Sv3f3x#ol@!X{+N~s_nho7P^IexLAX#x9^M^uHut=Dv!LVVeeFf#(SFI9 z-1CJqYveMQ-o;+=9} zZO(Hx_pEzi!wGFSO=tmA)?K=O+&l7WEGID1xr_^|SemdMnj;GhEOCE|Z=oi#M5nGx z)bOMk8=1|1PYFxy%uAwEJ$6&&b29g#9@lHkk<|uG_0^)(rh(MJN&2OhlxMzsSj@X< zhEB_trSa4_a-tssq`8R#!P1I7jn3?vDlbhUuWM)YV^T9ussx5n8R+7wFjQp_je$3Y zYBOpHFjQl#O2lfjc(@%&ey7(aYCN_#rd6xAqQM}h;U3UnofKgNbgD{qzlzzW z7jE*oz8L_0Ca)lf?-co`#^&4GkyGat;FX?}zmX~rzTx)bhN%Lu@_ zgOW5GkL*V_z3|SKW8KND7w z4@&SO$nQZ9rVfpv88_#SNZQ>Lz$q{I+NNkG22NOW&=#R1Lc7M-i4(d$ZK%3#?uY~FZq|bXk%E9D8H*FBpRLcjyHSQ6q~KNrAswaX>d;l>oOmD?BPch>pzx5 zyXIEk!w(g1J9C_`-~Dz9pI)(vz;jmyeB!5%vNH~c)>nrEX$pZrO;#?kE@wGCBnywT`B59P8^y)cGDCnJ?{v%*JX6 zK&*T`6o^IDomlGyPa{# zvpWM?nPWQd&-Vrlf;I-updVFx%lMWjHqU)_ZnL}g6G85*Ka>fqd&lWqSa(Tc)zao^ zCmN-}2?uTG(n~gAtj6W4aNKf2tKz)^BULU(Bg;IeyRBJHMAEx~7yF||For$0I~;tx zjNw^Qxz{)&TE?&wWBhIA{hjm1i9UN#8EI0f89l1EjRy1pFFN0=R9jwvU6O>)w#e10 zO;j$A%k)`51T!PDxUw(sD#qWIG3>DPX<-EjFdBu)gI(ADsEFKA2V*u}2%8g7_;2nl z-fvt#%$^*D$%7=;E&yr#4j5t_WzJoph zh>MWo9O{5)-D zLxbm{#@|oM@}Y4k{|@W``z%rFC_o^sVFl0yHobGFGVjkgamPtQasB`G0fL%d2{B%X zs@o*N8 Date: Fri, 4 Dec 2026 11:38:16 -0300 Subject: [PATCH 18/37] =?UTF-8?q?Share=20the=20Windows=20companion=20resol?= =?UTF-8?q?ver=20and=20include=20Programa=E2=80=99s=20identity?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contracts/link/v1/windows-apps.json | 9 ++++ contracts/link/v1/windows.md | 12 +++++- scripts/sync-windows-app-link.py | 42 +++++++++++++++++++ .../Programa.Tests/CompanionDiscoveryTests.cs | 22 +++++++--- windows/Programa/CompanionDiscovery.cs | 11 ++--- windows/Programa/MainWindow.Integrations.cs | 3 +- windows/Programa/Program.cs | 3 +- windows/Programa/WindowsCompanionPlatform.cs | 2 +- windows/Programa/WindowsCompanionTrust.cs | 2 +- 9 files changed, 91 insertions(+), 15 deletions(-) create mode 100644 scripts/sync-windows-app-link.py diff --git a/contracts/link/v1/windows-apps.json b/contracts/link/v1/windows-apps.json index 36b1e948..b0fae3fb 100644 --- a/contracts/link/v1/windows-apps.json +++ b/contracts/link/v1/windows-apps.json @@ -18,6 +18,15 @@ "direct_product": "Mesinyer.Windows", "direct_signers": [], "store_packages": [] + }, + { + "app": "programa", + "title": "Programa", + "direct_install_id": "Programa", + "direct_executable": "programa.exe", + "direct_product": "Programa", + "direct_signers": [], + "store_packages": [] } ] } diff --git a/contracts/link/v1/windows.md b/contracts/link/v1/windows.md index 805bbabc..ff875d33 100644 --- a/contracts/link/v1/windows.md +++ b/contracts/link/v1/windows.md @@ -1,6 +1,6 @@ # Windows companion discovery -In a Programa terminal, run `programa apps status --json`, or open Settings → Integrations. Both read the same local inventory for Browsee and Mesinyer. Each check resolves the current installation again, including after updates, moves or restarts. The CLI can run while Programa’s main window is closed. +In a Programa terminal, run `programa apps status --json`, or open Settings → Integrations. Browsee and Mesinyer also expose the same inventory for their two peers in Settings → Integrations. Each app excludes itself before probing. Each check resolves the current installation again, including after updates, moves or restarts. The CLI can run while Programa’s main window is closed. - Direct installers use their exact Velopack IDs and main executable paths from [windows-apps.json](windows-apps.json). Velopack records the install root under the ID's Windows uninstall key, including custom install directories. Programa reads the root and checks the expected executable under `current`. The registry entry alone provides an unverified installation hint. A verified direct install requires matching signed PE product metadata, Windows Authenticode validation and an enrolled SHA-256 pair containing the validating publisher’s DER subject name and its issuing CA’s DER SubjectPublicKeyInfo. [Velopack 1.2.161 registration source](https://raw.githubusercontent.com/velopack/velopack/1.2.161/src/bins/src/windows/registry.rs) - Store installs require an exact enrolled package family and relative executable path, an active registration for the current Windows user, and Windows' Store signature classification. A running process must match the selected executable and, for a Store package, its full package name. [PackageManager](https://learn.microsoft.com/en-us/uwp/api/windows.management.deployment.packagemanager) · [Package identity APIs](https://learn.microsoft.com/en-us/windows/win32/appxpkg/functions) @@ -15,3 +15,13 @@ In a Programa terminal, run `programa apps status --json`, or open Settings → | Programa | Velopack `Programa` and the standalone executable | Ships its own MCP and control pipe. Windows discovery currently checks local installation and process identity only. | The release sources contain no enrolled production Store package families or direct signing identities for either peer. Populate these from verified release artifacts when those lanes are available. Existing registrations can appear as unverified while enrollment is pending. Signed direct installs, signed Store installs, mixed installations, restart recovery and Settings accessibility still require execution on Windows. + +## Sync the native consumers + +Programa owns the canonical C# resolver and identity catalog. Browsee and Mesinyer compile copies and embed the same catalog, so each can discover peers independently. From the Programa checkout run: + +```sh +python3 scripts/sync-windows-app-link.py /path/to/browsee/windows/browsee.Windows /path/to/mesinyer/windows/Mesinyer.Windows +``` + +Repeat with `--check` to verify byte-for-byte parity. Update all three apps when enrolling an identity or changing resolver behavior. Local discovery owns neither access grants nor third-party registrations. diff --git a/scripts/sync-windows-app-link.py b/scripts/sync-windows-app-link.py new file mode 100644 index 00000000..113604a0 --- /dev/null +++ b/scripts/sync-windows-app-link.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Copy the canonical Windows App Link resolver and catalog into its consuming app projects.""" + +import argparse +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SOURCES = [ + ROOT / "windows/Programa/CompanionDiscovery.cs", + ROOT / "windows/Programa/WindowsCompanionPlatform.cs", + ROOT / "windows/Programa/WindowsCompanionTrust.cs", + ROOT / "contracts/link/v1/windows-apps.json", +] + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true", help="Report stale generated copies without writing.") + parser.add_argument("projects", nargs="+", type=Path, help="Windows project directories that embed App Link.") + args = parser.parse_args() + stale = [] + for project in args.projects: + if not project.is_dir() or not any(project.glob("*.csproj")): + parser.error(f"{project} is not a Windows project directory") + destination = project / "AppLink" + if not args.check: + destination.mkdir(exist_ok=True) + for source in SOURCES: + target = destination / source.name + expected = source.read_bytes() + if target.exists() and target.read_bytes() == expected: + continue + if args.check: + stale.append(target) + else: + target.write_bytes(expected) + if stale: + parser.exit(1, "Stale Windows App Link copies:\n" + "\n".join(map(str, stale)) + "\n") + + +if __name__ == "__main__": + main() diff --git a/windows/Programa.Tests/CompanionDiscoveryTests.cs b/windows/Programa.Tests/CompanionDiscoveryTests.cs index 2b623b4f..8e541420 100644 --- a/windows/Programa.Tests/CompanionDiscoveryTests.cs +++ b/windows/Programa.Tests/CompanionDiscoveryTests.cs @@ -1,6 +1,6 @@ using System.Text.Json; using Microsoft.VisualStudio.TestTools.UnitTesting; -using static Programa.CompanionDiscovery; +using static Darkroom.AppLink.Windows.CompanionDiscovery; namespace Programa.Tests; @@ -71,10 +71,16 @@ public void JsonIncludesSeparatePresenceAccessAndContract() } [TestMethod] - public void CatalogNamesTheCurrentReleaseInstallers() + public void ExcludesTheCurrentAppBeforeProbingPeers() { - var report = Read(new Fixture()); - CollectionAssert.AreEqual(new[] { "browsee", "mesinyer" }, report.Apps.Select(app => app.App).ToArray()); + foreach (var host in new[] { "browsee", "mesinyer", "programa" }) + { + var fixture = new Fixture(); + var expected = new[] { "browsee", "mesinyer", "programa" }.Where(app => app != host).ToArray(); + var report = Read(fixture, host); + CollectionAssert.AreEqual(expected, report.Apps.Select(app => app.App).ToArray()); + CollectionAssert.AreEqual(expected, fixture.ProbedApps); + } } private sealed class Fixture : Platform @@ -84,7 +90,13 @@ private sealed class Fixture : Platform internal bool UnknownRunningState { get; set; } internal int RunningChecks { get; private set; } - public IEnumerable Candidates(Identity app) => Installs; + internal List ProbedApps { get; } = []; + + public IEnumerable Candidates(Identity app) + { + ProbedApps.Add(app.App); + return Installs; + } public bool? Running(Candidate candidate) { diff --git a/windows/Programa/CompanionDiscovery.cs b/windows/Programa/CompanionDiscovery.cs index 763438d0..f065bc3c 100644 --- a/windows/Programa/CompanionDiscovery.cs +++ b/windows/Programa/CompanionDiscovery.cs @@ -1,7 +1,7 @@ using System.Text.Json; using System.Text.Json.Serialization; -namespace Programa; +namespace Darkroom.AppLink.Windows; internal static class CompanionDiscovery { @@ -36,18 +36,19 @@ internal interface Platform bool? Running(Candidate candidate); } - internal static Report Read(Platform platform) + internal static Report Read(Platform platform, string hostApp) { using var stream = typeof(CompanionDiscovery).Assembly.GetManifestResourceStream("AppLink.WindowsApps.json") ?? throw new InvalidOperationException("Windows app identities are missing."); var catalog = JsonSerializer.Deserialize(stream, JsonOptions) ?? throw new InvalidDataException("Windows app identities are invalid."); if (catalog.Contract != Contract) throw new InvalidDataException("Unsupported Windows app identity contract."); - return new Report(Contract, catalog.Apps.Select(app => Discover(app, platform)).ToArray()); + return new Report(Contract, catalog.Apps.Where(app => app.App != hostApp) + .Select(app => Discover(app, platform)).ToArray()); } - internal static async Task ReadAsync(Platform platform) => - await Task.Run(() => Read(platform)).WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false); + internal static async Task ReadAsync(Platform platform, string hostApp) => + await Task.Run(() => Read(platform, hostApp)).WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false); private sealed record Catalog(int Contract, Identity[] Apps); diff --git a/windows/Programa/MainWindow.Integrations.cs b/windows/Programa/MainWindow.Integrations.cs index d6f178a7..df5f2728 100644 --- a/windows/Programa/MainWindow.Integrations.cs +++ b/windows/Programa/MainWindow.Integrations.cs @@ -1,3 +1,4 @@ +using Darkroom.AppLink.Windows; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Automation; using Microsoft.UI.Xaml.Automation.Peers; @@ -27,7 +28,7 @@ async Task Refresh() status.Text = Localizer.Get("CompanionChecking"); try { - var report = await CompanionDiscovery.ReadAsync(new WindowsCompanionPlatform()); + var report = await CompanionDiscovery.ReadAsync(new WindowsCompanionPlatform(), "programa"); foreach (var peer in report.Apps) { var name = new TextBlock { Text = peer.Title }; diff --git a/windows/Programa/Program.cs b/windows/Programa/Program.cs index 088e2592..cf71598d 100644 --- a/windows/Programa/Program.cs +++ b/windows/Programa/Program.cs @@ -1,3 +1,4 @@ +using Darkroom.AppLink.Windows; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Principal; @@ -24,7 +25,7 @@ public static void Main(string[] args) try { Environment.ExitCode = CompanionDiscovery.Run(args[1..], - () => CompanionDiscovery.ReadAsync(new WindowsCompanionPlatform()).GetAwaiter().GetResult(), output, error); + () => CompanionDiscovery.ReadAsync(new WindowsCompanionPlatform(), "programa").GetAwaiter().GetResult(), output, error); } catch (Exception failure) when (failure is IOException or UnauthorizedAccessException or InvalidOperationException or TimeoutException or System.Text.Json.JsonException) diff --git a/windows/Programa/WindowsCompanionPlatform.cs b/windows/Programa/WindowsCompanionPlatform.cs index 67731a49..a5ea924e 100644 --- a/windows/Programa/WindowsCompanionPlatform.cs +++ b/windows/Programa/WindowsCompanionPlatform.cs @@ -6,7 +6,7 @@ using Windows.ApplicationModel; using Windows.Management.Deployment; -namespace Programa; +namespace Darkroom.AppLink.Windows; internal sealed class WindowsCompanionPlatform : CompanionDiscovery.Platform { diff --git a/windows/Programa/WindowsCompanionTrust.cs b/windows/Programa/WindowsCompanionTrust.cs index 2ecd2bb7..603a7727 100644 --- a/windows/Programa/WindowsCompanionTrust.cs +++ b/windows/Programa/WindowsCompanionTrust.cs @@ -2,7 +2,7 @@ using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; -namespace Programa; +namespace Darkroom.AppLink.Windows; internal static class WindowsCompanionTrust { From 1603ebf0575f5154d7d5bf963d67cfde8f05cc25 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:08:15 -0300 Subject: [PATCH 19/37] Seal and verify Programa Mac payload handoffs --- scripts/programa_mac_payload_bridge.js | 132 ++++++++++++++++++++ scripts/programa_mac_payload_bridge.test.js | 81 ++++++++++++ 2 files changed, 213 insertions(+) create mode 100644 scripts/programa_mac_payload_bridge.js create mode 100644 scripts/programa_mac_payload_bridge.test.js diff --git a/scripts/programa_mac_payload_bridge.js b/scripts/programa_mac_payload_bridge.js new file mode 100644 index 00000000..42246e20 --- /dev/null +++ b/scripts/programa_mac_payload_bridge.js @@ -0,0 +1,132 @@ +"use strict"; + +const { createHash } = require("node:crypto"); +const { createReadStream, lstatSync, readFileSync, readdirSync } = require("node:fs"); +const { join } = require("node:path"); +const { isDeepStrictEqual } = require("node:util"); +const { deriveReleaseBuildIdentity } = require("./release_build_identity"); +const { createCandidateManifest, validateReleasePayloadReferences } = require("./rolling_release_state"); + +const SHIPIT_REPOSITORY = "darkroomengineering/shipit"; +const SHIPIT_WORKFLOW = ".github/workflows/programa-mac-signed-preview.yml"; +const repository = "darkroomengineering/programa"; +const decimal = /^[1-9][0-9]*$/; + +function validateRequest(request) { + const { sourceRunId, sourceAttempt, ciRunId, ciAttempt, sha, version, build } = request; + // GitHub can reuse release-identity outputs when only failed jobs are rerun. + const buildAttempt = typeof build === "string" ? String(Number(build.slice(-3))) : ""; + if ( + Object.keys(request).length !== 7 || + typeof sourceAttempt !== "string" || + !decimal.test(sourceAttempt) || + BigInt(sourceAttempt) > 999n || + !decimal.test(buildAttempt) || + BigInt(buildAttempt) > BigInt(sourceAttempt) || + typeof sha !== "string" || + typeof version !== "string" || + !/^[a-f0-9]{40}$/.test(sha) || + !/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(version) || + build !== deriveReleaseBuildIdentity({ + eventName: "workflow_run", + workflowRunId: sourceRunId, + workflowRunAttempt: buildAttempt, + upstreamRunId: ciRunId, + upstreamRunAttempt: ciAttempt, + }) + ) throw new Error("Invalid Programa Mac payload request"); + return { sourceRunId, sourceAttempt, ciRunId, ciAttempt, sha, version, build }; +} + +function validatedShipitRun(run, id) { + if ( + typeof id !== "string" || !decimal.test(id) || + String(run.id) !== id || + run.path !== SHIPIT_WORKFLOW || + run.event !== "workflow_dispatch" || + run.head_branch !== "main" || + run.head_repository?.full_name !== SHIPIT_REPOSITORY || + run.status !== "completed" || + run.conclusion !== "success" + ) throw new Error("Shipit run is not the successful protected preview dispatch"); + return validateShipitIdentity({ runId: id, attempt: String(run.run_attempt) }); +} + +function validateShipitIdentity({ runId, attempt }) { + if (typeof runId !== "string" || !decimal.test(runId) || + typeof attempt !== "string" || !decimal.test(attempt) || BigInt(attempt) > 999n + ) throw new Error("Invalid Shipit workflow run identity"); + return { runId, attempt }; +} + +async function asset(directory, name, role) { + const title = join(directory, name); + const stat = lstatSync(title); + if (!stat.isFile()) throw new Error(`${name} is not a regular payload file`); + const hash = createHash("sha256"); + for await (const bytes of createReadStream(title)) hash.update(bytes); + return { name, role, size: stat.size, sha256: hash.digest("hex") }; +} + +async function createHandoff(request, shipit, directory) { + request = validateRequest(request); + shipit = validateShipitIdentity(shipit); + const files = [ + [`programa-macos-${request.build}.dmg`, "immutable"], + [`programa-dSYMs-${request.build}.zip`, "immutable"], + ["appcast.xml", "appcast"], + ["programa-macos.dmg", "stable-alias"], + ]; + if (!lstatSync(directory).isDirectory()) throw new Error("The payload path is not a directory"); + const names = readdirSync(directory).sort(); + if (JSON.stringify(names) !== JSON.stringify(files.map(([name]) => name).sort())) + throw new Error("The staged Mac payload must contain exactly its four release files"); + const manifest = createCandidateManifest({ + targetSha: request.sha, + version: request.version, + build: request.build, + assets: await Promise.all(files.map(([name, role]) => asset(directory, name, role))), + }); + const appcastXml = readFileSync(join(directory, "appcast.xml"), "utf8"); + if (!appcastXml.includes(" + + + ${request.build} + ${request.version} + + + + `); + return { directory, immutable }; +} + +test("checks the exact rolling build from the upstream CI and release attempts", () => { + assert.deepEqual(validateRequest(request), request); + assert.throws(() => validateRequest({ ...request, sourceAttempt: "1" }), /Invalid Programa Mac payload request/); + assert.doesNotThrow(() => validateRequest({ ...request, sourceAttempt: "3" })); + assert.throws(() => validateRequest({ ...request, ciRunId: "47351804001" }), /Invalid Programa Mac payload request/); +}); + +test("emits and checks a four-file handoff from the exact Shipit run and attempt", async (t) => { + const { directory } = fixture(t); + const manifest = await createHandoff(request, { runId, attempt: "1" }, directory); + await verifyHandoff(request, run, runId, directory, JSON.parse(JSON.stringify(manifest))); + await assert.rejects(verifyHandoff({ ...request, sha: "b".repeat(40) }, run, runId, directory, manifest), /provenance/); + await assert.rejects(verifyHandoff(request, { ...run, run_attempt: 2 }, runId, directory, manifest), /provenance/); + await assert.rejects(verifyHandoff(request, { ...run, head_branch: "test" }, runId, directory, manifest), /protected preview dispatch/); +}); + +test("rejects a replaced immutable DMG even if its size and the stable alias still match", async (t) => { + const { directory, immutable } = fixture(t); + const manifest = await createHandoff(request, { runId, attempt: "1" }, directory); + writeFileSync(join(directory, immutable), "image two"); + writeFileSync(join(directory, "programa-macos.dmg"), "image two"); + await assert.rejects(verifyHandoff(request, run, runId, directory, manifest), /immutable payload digest differs/); +}); + +test("does not accept a Windows file in the Mac payload", async (t) => { + const { directory } = fixture(t); + writeFileSync(join(directory, "programa-windows.exe"), "an untouched product"); + await assert.rejects(createHandoff(request, { runId, attempt: "1" }, directory), /exactly its four release files/); +}); From 61a73cbf72ed0322a88d3a3697c4b96627ef7690 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:08:16 -0300 Subject: [PATCH 20/37] Add opt-in Shipit shadow build to Programa releases --- .github/workflows/release.yml | 74 +++++++++++++++++++++++++++++++++++ docs/release.md | 6 +++ 2 files changed, 80 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 429faa2c..0f056c76 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -159,6 +159,80 @@ jobs: echo "Effective build: ${EFFECTIVE_BUILD}" echo "Release tag: ${RELEASE_TAG}" + # Shadow build only: the signed payload is compared but never reaches assembly or rolling. + shadow-shipit-mac: + needs: release-identity + if: >- + vars.PROGRAMA_MAC_SHIPIT_SHADOW == 'true' && + github.repository == 'darkroomengineering/programa' && + github.event_name == 'workflow_run' && + github.ref == 'refs/heads/main' && + github.ref_protected && + needs.release-identity.outputs.superseded != 'true' + runs-on: ubuntu-latest + environment: shipit-preview + timeout-minutes: 100 + permissions: + actions: read + contents: read + env: + TARGET_SHA: ${{ needs.release-identity.outputs.target_sha }} + EFFECTIVE_BUILD: ${{ needs.release-identity.outputs.effective_build }} + EFFECTIVE_VERSION: ${{ needs.release-identity.outputs.effective_version }} + CI_RUN_ID: ${{ github.event.workflow_run.id }} + CI_ATTEMPT: ${{ github.event.workflow_run.run_attempt }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.release-identity.outputs.target_sha }} + persist-credentials: false + + - name: Record the exact protected release request + run: | + set -euo pipefail + [[ "$(git rev-parse HEAD)" == "$TARGET_SHA" ]] + [[ "$(git ls-remote --exit-code origin refs/heads/main | cut -f1)" == "$TARGET_SHA" ]] + SOURCE_RUN_ID="$GITHUB_RUN_ID" SOURCE_ATTEMPT="$GITHUB_RUN_ATTEMPT" \ + node scripts/programa_mac_payload_bridge.js request > "$RUNNER_TEMP/request.json" + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: programa-macos-request-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/request.json + if-no-files-found: error + retention-days: 7 + + - name: Dispatch the private build and verify the returned artifact + env: + GH_TOKEN: ${{ secrets.SHIPIT_ACTIONS_TOKEN }} + run: | + set -euo pipefail + : "${GH_TOKEN:?Configure SHIPIT_ACTIONS_TOKEN in the protected shipit-preview environment}" + stage="$(mktemp -d "$RUNNER_TEMP/programa-shadow.XXXXXXXX")" + trap 'rm -rf "$stage"' EXIT + shipit=darkroomengineering/shipit + workflow=programa-mac-signed-preview.yml + jq -cn --arg id "$GITHUB_RUN_ID" --arg attempt "$GITHUB_RUN_ATTEMPT" \ + '{ref:"main",inputs:{source_run_id:$id,source_run_attempt:$attempt}}' > "$stage/dispatch.json" + gh api "repos/$shipit/actions/workflows/$workflow/dispatches" --method POST \ + -H "X-GitHub-Api-Version: 2026-03-10" --input "$stage/dispatch.json" > "$stage/dispatch-result.json" + run_id="$(jq -er '.workflow_run_id | tostring | select(test("^[1-9][0-9]*$"))' "$stage/dispatch-result.json")" + gh run watch "$run_id" --repo "$shipit" --exit-status + gh api "repos/$shipit/actions/runs/$run_id" > "$stage/run.json" + artifact_name=programa-signed-macos-preview + artifact_id() { + gh api "repos/$shipit/actions/runs/$run_id/artifacts?name=$artifact_name" | + jq -er --arg name "$artifact_name" --arg id "$run_id" \ + '.artifacts | map(select(.name == $name and .expired == false and (.workflow_run.id | tostring) == $id)) | select(length == 1) | .[0].id' + } + previous="$(artifact_id)" + [[ "$previous" =~ ^[1-9][0-9]*$ ]] + gh run download "$run_id" --repo "$shipit" --name "$artifact_name" --dir "$stage/received" + [[ "$(artifact_id)" == "$previous" ]] + node scripts/programa_mac_payload_bridge.js verify "$RUNNER_TEMP/request.json" "$run_id" "$stage/run.json" \ + "$stage/received/payload" "$stage/received/handoff.json" + [[ "$(git ls-remote --exit-code origin refs/heads/main | cut -f1)" == "$TARGET_SHA" ]] + build-sign-notarize: needs: [release-identity] if: >- diff --git a/docs/release.md b/docs/release.md index f16697d5..e373278c 100644 --- a/docs/release.md +++ b/docs/release.md @@ -107,6 +107,12 @@ python3 scripts/compare-macos-release.py legacy shipit --version "$VERSION" --bu The comparison checks the signed bundles and their helper boundaries, app identity, embedded Sparkle, stapled DMGs, immutable enclosure metadata and matching dSYMs. Signatures and notarization timestamps can differ across builds. Verify a real Sparkle update and the existing CLI memory check against the candidate before promoting. Keep the `rolling` reconciler’s protected-main and high-water checks in the publication path. Confirm that Windows installers still update in the existing release batch and retain the direct download URL. +### Same-commit Shipit shadow build + +The optional `shadow-shipit-mac` job sends an active protected-main release’s exact source, version and build request to the private Shipit workflow. It can start before the legacy Mac payload exists. Programa downloads and checks the four-file result against the exact private run and its SHA-256 manifest, then discards it. Candidate assembly, public attestations, the Windows direct payload and promotion continue through the existing workflow. + +To try the handoff, first configure Shipit’s protected release environment, Apple signing credentials and studio runner access. In Programa, restrict the `shipit-preview` environment to protected `main` and scope its `SHIPIT_ACTIONS_TOKEN` to dispatch and read Actions artifacts in the private Shipit repo. Once both workflows are on their protected default branches, opt in with `PROGRAMA_MAC_SHIPIT_SHADOW=true`. Leave it unset for ordinary legacy releases. Compare the private shadow result with the legacy payload from the same Programa run and complete the signed artifact, install and Sparkle update checks before changing the Mac producer. + ## What `rolling` carries - `appcast.xml` From 787aabe2ee0864f22eeb68f659914a2d0a01e382 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:18:57 -0300 Subject: [PATCH 21/37] Poll Shipit through Actions REST and verify workflow identity --- .github/workflows/release.yml | 8 +- scripts/programa_mac_payload_bridge.js | 88 +++++++++++++++++---- scripts/programa_mac_payload_bridge.test.js | 81 +++++++++++++++++-- 3 files changed, 151 insertions(+), 26 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0f056c76..5e9b3e2f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -159,7 +159,7 @@ jobs: echo "Effective build: ${EFFECTIVE_BUILD}" echo "Release tag: ${RELEASE_TAG}" - # Shadow build only: the signed payload is compared but never reaches assembly or rolling. + # Shadow build only: verify the signed handoff without adding it to assembly or rolling. shadow-shipit-mac: needs: release-identity if: >- @@ -217,8 +217,8 @@ jobs: gh api "repos/$shipit/actions/workflows/$workflow/dispatches" --method POST \ -H "X-GitHub-Api-Version: 2026-03-10" --input "$stage/dispatch.json" > "$stage/dispatch-result.json" run_id="$(jq -er '.workflow_run_id | tostring | select(test("^[1-9][0-9]*$"))' "$stage/dispatch-result.json")" - gh run watch "$run_id" --repo "$shipit" --exit-status - gh api "repos/$shipit/actions/runs/$run_id" > "$stage/run.json" + workflow_id="$(gh api "repos/$shipit/actions/workflows/$workflow" --jq '.id')" + node scripts/programa_mac_payload_bridge.js wait "$run_id" "$workflow_id" > "$stage/run.json" artifact_name=programa-signed-macos-preview artifact_id() { gh api "repos/$shipit/actions/runs/$run_id/artifacts?name=$artifact_name" | @@ -229,7 +229,7 @@ jobs: [[ "$previous" =~ ^[1-9][0-9]*$ ]] gh run download "$run_id" --repo "$shipit" --name "$artifact_name" --dir "$stage/received" [[ "$(artifact_id)" == "$previous" ]] - node scripts/programa_mac_payload_bridge.js verify "$RUNNER_TEMP/request.json" "$run_id" "$stage/run.json" \ + node scripts/programa_mac_payload_bridge.js verify "$RUNNER_TEMP/request.json" "$run_id" "$workflow_id" "$stage/run.json" \ "$stage/received/payload" "$stage/received/handoff.json" [[ "$(git ls-remote --exit-code origin refs/heads/main | cut -f1)" == "$TARGET_SHA" ]] diff --git a/scripts/programa_mac_payload_bridge.js b/scripts/programa_mac_payload_bridge.js index 42246e20..d2486124 100644 --- a/scripts/programa_mac_payload_bridge.js +++ b/scripts/programa_mac_payload_bridge.js @@ -1,6 +1,8 @@ "use strict"; const { createHash } = require("node:crypto"); +const { execFileSync } = require("node:child_process"); +const { setTimeout: sleep } = require("node:timers/promises"); const { createReadStream, lstatSync, readFileSync, readdirSync } = require("node:fs"); const { join } = require("node:path"); const { isDeepStrictEqual } = require("node:util"); @@ -38,20 +40,63 @@ function validateRequest(request) { return { sourceRunId, sourceAttempt, ciRunId, ciAttempt, sha, version, build }; } -function validatedShipitRun(run, id) { +function checkShipitRun(run, id, workflowId) { + const validPath = [SHIPIT_WORKFLOW, `${SHIPIT_WORKFLOW}@main`, `${SHIPIT_WORKFLOW}@refs/heads/main`]; if ( typeof id !== "string" || !decimal.test(id) || + typeof workflowId !== "string" || !decimal.test(workflowId) || String(run.id) !== id || - run.path !== SHIPIT_WORKFLOW || + String(run.workflow_id) !== workflowId || + !validPath.includes(run.path) || run.event !== "workflow_dispatch" || run.head_branch !== "main" || - run.head_repository?.full_name !== SHIPIT_REPOSITORY || - run.status !== "completed" || - run.conclusion !== "success" - ) throw new Error("Shipit run is not the successful protected preview dispatch"); + run.head_repository?.full_name !== SHIPIT_REPOSITORY + ) throw new Error("Shipit run is not the protected preview dispatch"); return validateShipitIdentity({ runId: id, attempt: String(run.run_attempt) }); } +function validatedShipitRun(run, id, workflowId) { + const identity = checkShipitRun(run, id, workflowId); + if (run.status !== "completed" || run.conclusion !== "success") + throw new Error(`Shipit preview did not succeed: ${run.conclusion || run.status}`); + return identity; +} + +async function waitForShipitRun(fetchRun, id, workflowId, { + timeoutMs = 90 * 60_000, + intervalMs = 15_000, + maxConsecutiveErrors = 5, + now = () => performance.now(), + pause = sleep, +} = {}) { + if (typeof id !== "string" || !decimal.test(id) || typeof workflowId !== "string" || !decimal.test(workflowId)) + throw new Error("Invalid Shipit run or workflow ID"); + const deadline = now() + timeoutMs; + let failures = 0; + const pending = new Set(["queued", "in_progress", "requested", "waiting", "pending"]); + while (now() < deadline) { + let run; + try { + run = await fetchRun(Math.min(15_000, Math.ceil(deadline - now()))); + failures = 0; + } catch (error) { + if (++failures >= maxConsecutiveErrors) throw new Error("Could not poll Shipit via Actions REST", { cause: error }); + } + if (run !== undefined) { + checkShipitRun(run, id, workflowId); + if (run.status === "completed") { + validatedShipitRun(run, id, workflowId); + return run; + } + if (!pending.has(run.status)) throw new Error(`Unexpected Shipit workflow status: ${run.status}`); + } + const next = failures ? Math.min(intervalMs * 2 ** (failures - 1), 30_000) : intervalMs; + const remaining = deadline - now(); + if (remaining > 0) await pause(Math.min(remaining, next)); + } + throw new Error(`Timed out waiting for Shipit preview ${id}`); +} + function validateShipitIdentity({ runId, attempt }) { if (typeof runId !== "string" || !decimal.test(runId) || typeof attempt !== "string" || !decimal.test(attempt) || BigInt(attempt) > 999n @@ -97,33 +142,44 @@ async function createHandoff(request, shipit, directory) { return { schemaVersion: 1, request, shipit, manifest }; } -async function verifyHandoff(request, shipitRun, shipitRunId, directory, received) { - const shipit = validatedShipitRun(shipitRun, shipitRunId); +async function verifyHandoff(request, shipitRun, shipitRunId, workflowId, directory, received) { + const shipit = validatedShipitRun(shipitRun, shipitRunId, workflowId); const rebuilt = await createHandoff(request, shipit, directory); if (!isDeepStrictEqual(received, rebuilt)) throw new Error("Shipit handoff provenance or immutable payload digest differs"); } -module.exports = { validateRequest, validatedShipitRun, createHandoff, verifyHandoff }; +module.exports = { validateRequest, validatedShipitRun, waitForShipitRun, createHandoff, verifyHandoff }; if (require.main === module) { - const [mode, requestPath, runID, attemptOrRunFile, directory, manifestPath] = process.argv.slice(2); + const [mode, ...args] = process.argv.slice(2); const json = (path) => JSON.parse(readFileSync(path, "utf8")); (async () => { - if (mode === "request" && !requestPath) { + if (mode === "request" && args.length === 0) { const { SOURCE_RUN_ID: sourceRunId, SOURCE_ATTEMPT: sourceAttempt, CI_RUN_ID: ciRunId, CI_ATTEMPT: ciAttempt, TARGET_SHA: sha, EFFECTIVE_VERSION: version, EFFECTIVE_BUILD: build, } = process.env; console.log(JSON.stringify(validateRequest({ sourceRunId, sourceAttempt, ciRunId, ciAttempt, sha, version, build }))); - } else if (mode === "seal" && directory && !manifestPath) { - const result = await createHandoff(json(requestPath), { runId: runID, attempt: attemptOrRunFile }, directory); + } else if (mode === "seal" && args.length === 4) { + const [requestPath, runID, attempt, directory] = args; + const result = await createHandoff(json(requestPath), { runId: runID, attempt }, directory); console.log(JSON.stringify(result)); - } else if (mode === "verify" && directory && manifestPath) { - await verifyHandoff(json(requestPath), json(attemptOrRunFile), runID, directory, json(manifestPath)); + } else if (mode === "wait" && args.length === 2) { + const [runID, workflowId] = args; + const run = await waitForShipitRun( + (timeout) => JSON.parse(execFileSync("gh", ["api", `repos/${SHIPIT_REPOSITORY}/actions/runs/${runID}`], { + encoding: "utf8", timeout, stdio: ["ignore", "pipe", "ignore"], + })), + runID, workflowId, + ); + console.log(JSON.stringify(run)); + } else if (mode === "verify" && args.length === 6) { + const [requestPath, runID, workflowId, runFile, directory, manifestPath] = args; + await verifyHandoff(json(requestPath), json(runFile), runID, workflowId, directory, json(manifestPath)); console.log("Verified the exact Shipit run and all four Mac payload digests"); } else { - throw new Error("Expected request, seal REQUEST RUN ATTEMPT PAYLOAD_DIR, or verify REQUEST RUN RUN_JSON PAYLOAD_DIR MANIFEST"); + throw new Error("Expected request, wait RUN WORKFLOW, seal REQUEST RUN ATTEMPT PAYLOAD_DIR, or verify REQUEST RUN WORKFLOW RUN_JSON PAYLOAD_DIR MANIFEST"); } })().catch((error) => { console.error(error.message); diff --git a/scripts/programa_mac_payload_bridge.test.js b/scripts/programa_mac_payload_bridge.test.js index 16ff9af4..d7967a6b 100644 --- a/scripts/programa_mac_payload_bridge.test.js +++ b/scripts/programa_mac_payload_bridge.test.js @@ -5,7 +5,7 @@ const { mkdtempSync, rmSync, writeFileSync } = require("node:fs"); const { tmpdir } = require("node:os"); const { join } = require("node:path"); const test = require("node:test"); -const { createHandoff, validateRequest, verifyHandoff } = require("./programa_mac_payload_bridge"); +const { createHandoff, validateRequest, verifyHandoff, waitForShipitRun } = require("./programa_mac_payload_bridge"); const request = { sourceRunId: "47351804425", @@ -18,8 +18,10 @@ const request = { }; const runId = "47351804428"; +const workflowId = "99"; const run = { id: Number(runId), + workflow_id: Number(workflowId), run_attempt: 1, path: ".github/workflows/programa-mac-signed-preview.yml", event: "workflow_dispatch", @@ -60,10 +62,10 @@ test("checks the exact rolling build from the upstream CI and release attempts", test("emits and checks a four-file handoff from the exact Shipit run and attempt", async (t) => { const { directory } = fixture(t); const manifest = await createHandoff(request, { runId, attempt: "1" }, directory); - await verifyHandoff(request, run, runId, directory, JSON.parse(JSON.stringify(manifest))); - await assert.rejects(verifyHandoff({ ...request, sha: "b".repeat(40) }, run, runId, directory, manifest), /provenance/); - await assert.rejects(verifyHandoff(request, { ...run, run_attempt: 2 }, runId, directory, manifest), /provenance/); - await assert.rejects(verifyHandoff(request, { ...run, head_branch: "test" }, runId, directory, manifest), /protected preview dispatch/); + await verifyHandoff(request, run, runId, workflowId, directory, JSON.parse(JSON.stringify(manifest))); + await assert.rejects(verifyHandoff({ ...request, sha: "b".repeat(40) }, run, runId, workflowId, directory, manifest), /provenance/); + await assert.rejects(verifyHandoff(request, { ...run, run_attempt: 2 }, runId, workflowId, directory, manifest), /provenance/); + await assert.rejects(verifyHandoff(request, { ...run, head_branch: "test" }, runId, workflowId, directory, manifest), /protected preview dispatch/); }); test("rejects a replaced immutable DMG even if its size and the stable alias still match", async (t) => { @@ -71,7 +73,7 @@ test("rejects a replaced immutable DMG even if its size and the stable alias sti const manifest = await createHandoff(request, { runId, attempt: "1" }, directory); writeFileSync(join(directory, immutable), "image two"); writeFileSync(join(directory, "programa-macos.dmg"), "image two"); - await assert.rejects(verifyHandoff(request, run, runId, directory, manifest), /immutable payload digest differs/); + await assert.rejects(verifyHandoff(request, run, runId, workflowId, directory, manifest), /immutable payload digest differs/); }); test("does not accept a Windows file in the Mac payload", async (t) => { @@ -79,3 +81,70 @@ test("does not accept a Windows file in the Mac payload", async (t) => { writeFileSync(join(directory, "programa-windows.exe"), "an untouched product"); await assert.rejects(createHandoff(request, { runId, attempt: "1" }, directory), /exactly its four release files/); }); + +test("accepts only the exact workflow ID with the bare or main-qualified workflow path", async (t) => { + const { directory } = fixture(t); + const handoff = await createHandoff(request, { runId, attempt: "1" }, directory); + for (const qualifier of ["", "@main", "@refs/heads/main"]) { + await verifyHandoff(request, { ...run, path: run.path + qualifier }, runId, workflowId, directory, handoff); + } + for (const changed of [ + { path: run.path + "@refs/heads/staging" }, + { path: run.path + "@refs/tags/main" }, + { path: ".github/workflows/other.yml@main" }, + { workflow_id: Number(workflowId) + 1 }, + ]) { + await assert.rejects( + verifyHandoff(request, { ...run, ...changed }, runId, workflowId, directory, handoff), + /protected preview dispatch/, + ); + } +}); + +test("polls through a transient REST error and a pending state to the original successful run", async () => { + let calls = 0; + let elapsed = 0; + const result = await waitForShipitRun(async () => { + calls++; + if (calls === 1) throw new Error("REST endpoint not ready"); + return calls === 2 ? { ...run, status: "waiting", conclusion: null } : run; + }, runId, workflowId, { + timeoutMs: 100, + intervalMs: 5, + now: () => elapsed, + pause: async (milliseconds) => { elapsed += milliseconds; }, + }); + assert.equal(result, run); + assert.equal(calls, 3); + assert.equal(elapsed, 10); +}); + +test("fails polling on a non-successful conclusion or when its deadline runs out", async () => { + await assert.rejects( + waitForShipitRun(async () => ({ ...run, conclusion: "cancelled" }), runId, workflowId), + /did not succeed: cancelled/, + ); + let elapsed = 0; + await assert.rejects( + waitForShipitRun(async () => ({ ...run, status: "queued", conclusion: null }), runId, workflowId, { + timeoutMs: 15, + intervalMs: 5, + now: () => elapsed, + pause: async (milliseconds) => { elapsed += milliseconds; }, + }), + /Timed out/, + ); + assert.equal(elapsed, 15); +}); + +test("stops after the consecutive Actions REST error limit", async () => { + let calls = 0; + await assert.rejects( + waitForShipitRun(async () => { + calls++; + throw new Error("REST temporarily unavailable"); + }, runId, workflowId, { maxConsecutiveErrors: 3, pause: async () => {} }), + /Could not poll Shipit via Actions REST/, + ); + assert.equal(calls, 3); +}); From 85474b2938bb32c7392afe185fadd1c6f171b166 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:18:57 -0300 Subject: [PATCH 22/37] Report shadow failures separately from legacy release --- .github/workflows/release.yml | 7 +++++++ docs/release.md | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5e9b3e2f..2ccce823 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -172,6 +172,7 @@ jobs: runs-on: ubuntu-latest environment: shipit-preview timeout-minutes: 100 + continue-on-error: true permissions: actions: read contents: read @@ -233,6 +234,12 @@ jobs: "$stage/received/payload" "$stage/received/handoff.json" [[ "$(git ls-remote --exit-code origin refs/heads/main | cut -f1)" == "$TARGET_SHA" ]] + - name: Report shadow handoff failure + if: failure() + run: | + echo "### Shipit shadow handoff failed" >> "$GITHUB_STEP_SUMMARY" + echo "The legacy release jobs run independently. Inspect this job before enabling a producer switch." >> "$GITHUB_STEP_SUMMARY" + build-sign-notarize: needs: [release-identity] if: >- diff --git a/docs/release.md b/docs/release.md index e373278c..11705f2d 100644 --- a/docs/release.md +++ b/docs/release.md @@ -109,7 +109,7 @@ The comparison checks the signed bundles and their helper boundaries, app identi ### Same-commit Shipit shadow build -The optional `shadow-shipit-mac` job sends an active protected-main release’s exact source, version and build request to the private Shipit workflow. It can start before the legacy Mac payload exists. Programa downloads and checks the four-file result against the exact private run and its SHA-256 manifest, then discards it. Candidate assembly, public attestations, the Windows direct payload and promotion continue through the existing workflow. +The optional `shadow-shipit-mac` job sends an active protected-main release’s exact source, version and build request to the private Shipit workflow. It can start before the legacy Mac payload exists. Programa polls the exact private run through Actions REST, verifies the four-file handoff and its SHA-256 manifest, then discards the downloaded copy. A failure appears in the shadow job’s summary without changing the outcome of the independent legacy release jobs. Candidate assembly, public attestations, the Windows direct payload and promotion continue through the existing workflow. To try the handoff, first configure Shipit’s protected release environment, Apple signing credentials and studio runner access. In Programa, restrict the `shipit-preview` environment to protected `main` and scope its `SHIPIT_ACTIONS_TOKEN` to dispatch and read Actions artifacts in the private Shipit repo. Once both workflows are on their protected default branches, opt in with `PROGRAMA_MAC_SHIPIT_SHADOW=true`. Leave it unset for ordinary legacy releases. Compare the private shadow result with the legacy payload from the same Programa run and complete the signed artifact, install and Sparkle update checks before changing the Mac producer. From 4854226bf543bb3a5baf78b43940962f79f3e045 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:20:18 -0300 Subject: [PATCH 23/37] Allow Windows discovery to read verified peer policy --- .../Programa.Tests/CompanionDiscoveryTests.cs | 31 +++++++++++++++++ windows/Programa/CompanionDiscovery.cs | 34 ++++++++++++++----- windows/Programa/WindowsCompanionPlatform.cs | 23 +++++++++---- 3 files changed, 73 insertions(+), 15 deletions(-) diff --git a/windows/Programa.Tests/CompanionDiscoveryTests.cs b/windows/Programa.Tests/CompanionDiscoveryTests.cs index 8e541420..4a5cd0f3 100644 --- a/windows/Programa.Tests/CompanionDiscoveryTests.cs +++ b/windows/Programa.Tests/CompanionDiscoveryTests.cs @@ -52,6 +52,37 @@ public void AnUnverifiedRegistrationIsNeverCheckedForRunningOrPreferredOverAVeri Assert.AreEqual(1, platform.RunningChecks); } + [TestMethod] + public void ProbesOnlyTheSelectedVerifiedRunningInstallAndReportsPolicyWithoutCapabilities() + { + var fixture = new Fixture { Installs = [Direct, Store] }; + Assert.AreEqual("not_running", Discover(Browsee, fixture, FailOnProbe).State); + var unsigned = Direct with { Verified = false }; + fixture.Installs = [unsigned]; + fixture.RunningApp = unsigned; + Assert.AreEqual("identity_unverified", Discover(Browsee, fixture, FailOnProbe).State); + + fixture.Installs = [Direct, Store]; + fixture.RunningApp = Direct; + var ready = Discover(Browsee, fixture, (identity, candidate) => + { + Assert.AreEqual(Browsee, identity); + Assert.AreEqual(Direct, candidate); + return OutsideAccess.Enabled; + }); + Assert.AreEqual("ready", ready.State); + Assert.AreEqual("enabled", ready.Access); + Assert.AreEqual(0, ready.Capabilities.Length); + var disabled = Discover(Browsee, fixture, (_, _) => OutsideAccess.Disabled); + Assert.AreEqual("disabled", disabled.State); + Assert.AreEqual("disabled", disabled.Access); + Assert.AreEqual(0, disabled.Capabilities.Length); + Assert.AreEqual("unknown", Discover(Browsee, fixture, (_, _) => OutsideAccess.Unknown).Access); + } + + private static OutsideAccess FailOnProbe(Identity identity, Candidate candidate) => + throw new InvalidOperationException("Status probe must require a selected, verified running peer."); + [TestMethod] public void JsonIncludesSeparatePresenceAccessAndContract() { diff --git a/windows/Programa/CompanionDiscovery.cs b/windows/Programa/CompanionDiscovery.cs index f065bc3c..9d593959 100644 --- a/windows/Programa/CompanionDiscovery.cs +++ b/windows/Programa/CompanionDiscovery.cs @@ -29,6 +29,8 @@ internal sealed record Candidate(string Distribution, string Executable, Version internal sealed record Peer(string App, string Title, bool Present, bool Verified, bool? Running, string State, string Access, string? Distribution, string? Version, string[] Capabilities); internal sealed record Report(int Contract, Peer[] Apps); + internal enum OutsideAccess { Unknown, Enabled, Disabled } + internal delegate OutsideAccess StatusProbe(Identity identity, Candidate candidate); internal interface Platform { @@ -36,7 +38,7 @@ internal interface Platform bool? Running(Candidate candidate); } - internal static Report Read(Platform platform, string hostApp) + internal static Report Read(Platform platform, string hostApp, StatusProbe? probe = null) { using var stream = typeof(CompanionDiscovery).Assembly.GetManifestResourceStream("AppLink.WindowsApps.json") ?? throw new InvalidOperationException("Windows app identities are missing."); @@ -44,15 +46,15 @@ internal static Report Read(Platform platform, string hostApp) ?? throw new InvalidDataException("Windows app identities are invalid."); if (catalog.Contract != Contract) throw new InvalidDataException("Unsupported Windows app identity contract."); return new Report(Contract, catalog.Apps.Where(app => app.App != hostApp) - .Select(app => Discover(app, platform)).ToArray()); + .Select(app => Discover(app, platform, probe)).ToArray()); } - internal static async Task ReadAsync(Platform platform, string hostApp) => - await Task.Run(() => Read(platform, hostApp)).WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false); + internal static async Task ReadAsync(Platform platform, string hostApp, StatusProbe? probe = null) => + await Task.Run(() => Read(platform, hostApp, probe)).WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false); private sealed record Catalog(int Contract, Identity[] Apps); - internal static Peer Discover(Identity identity, Platform platform) + internal static Peer Discover(Identity identity, Platform platform, StatusProbe? probe = null) { // Prefer a verified running instance. Otherwise prefer the verified Store package, // which is OS managed, then the latest verified direct version. An unsigned hint @@ -69,8 +71,16 @@ internal static Peer Discover(Identity identity, Platform platform) if (selected.Candidate is not { } app) return new Peer(identity.App, identity.Title, false, false, false, "not_installed", "unknown", null, null, []); - var state = !app.Verified ? "identity_unverified" : selected.Running is false ? "not_running" : "unavailable"; - return new Peer(identity.App, identity.Title, true, app.Verified, selected.Running, state, "unknown", + var access = app.Verified && selected.Running is true && probe is not null + ? probe(identity, app) + : OutsideAccess.Unknown; + var (state, accessState) = access switch + { + OutsideAccess.Enabled => ("ready", "enabled"), + OutsideAccess.Disabled => ("disabled", "disabled"), + _ => (!app.Verified ? "identity_unverified" : selected.Running is false ? "not_running" : "unavailable", "unknown"), + }; + return new Peer(identity.App, identity.Title, true, app.Verified, selected.Running, state, accessState, app.Distribution, app.Verified ? app.Version.ToString() : null, []); } @@ -86,7 +96,7 @@ internal static int Run(string[] args, Func read, TextWriter output, Tex output.WriteLine(JsonSerializer.Serialize(report, JsonOptions)); else foreach (var app in report.Apps) - output.WriteLine($"{app.Title}: {Describe(app)}. Access unknown."); + output.WriteLine($"{app.Title}: {Describe(app)}. {DescribeAccess(app)}."); return 0; } @@ -95,6 +105,14 @@ internal static int Run(string[] args, Func read, TextWriter output, Tex "not_installed" => "Not found", "identity_unverified" => "Registered · Identity unverified", "not_running" => "Installed · Closed", + "ready" or "disabled" => "Running", _ => app.Running == true ? "Running · Integration status unavailable" : "Installed · Running status unknown", }; + internal static string DescribeAccess(Peer peer) => peer.Access switch + { + "enabled" => "Browsee outside access enabled", + "disabled" => "Browsee outside access disabled", + _ => "Access unknown", + }; + } diff --git a/windows/Programa/WindowsCompanionPlatform.cs b/windows/Programa/WindowsCompanionPlatform.cs index a5ea924e..f183010c 100644 --- a/windows/Programa/WindowsCompanionPlatform.cs +++ b/windows/Programa/WindowsCompanionPlatform.cs @@ -71,13 +71,9 @@ internal sealed class WindowsCompanionPlatform : CompanionDiscovery.Platform // An OS package process has a full package name. A direct process // must explicitly have no package. An unreadable process proves neither. - var name = new char[256]; - uint length = (uint)name.Length; - var code = GetPackageFullName(process.SafeHandle, ref length, name); - if (code == 0 && string.Equals(candidate.PackageFullName, new string(name, 0, (int)length - 1), - StringComparison.OrdinalIgnoreCase)) return true; - if (code == 15700 && candidate.PackageFullName is null) return true; // APPMODEL_ERROR_NO_PACKAGE - unknown |= code is not 0 and not 15700; + var matches = MatchesPackage(process.SafeHandle, candidate.PackageFullName); + if (matches is true) return true; + unknown |= matches is null; } catch (Exception error) when (error is Win32Exception or InvalidOperationException or NotSupportedException) { @@ -92,6 +88,19 @@ internal sealed class WindowsCompanionPlatform : CompanionDiscovery.Platform } } + internal static bool? MatchesPackage(Microsoft.Win32.SafeHandles.SafeProcessHandle process, string? expected) + { + var name = new char[256]; + uint length = (uint)name.Length; + return GetPackageFullName(process, ref length, name) switch + { + 0 when length > 0 && length <= name.Length => string.Equals(expected, new string(name, 0, (int)length - 1), + StringComparison.OrdinalIgnoreCase), + 15700 => expected is null, // APPMODEL_ERROR_NO_PACKAGE + _ => null, + }; + } + // Registry roots are hints only. Read a known file on a local drive; never // parse display strings, execute an uninstall command or open a remote path. private static string? ExecutableUnder(string directory, params string[] relative) From e8a08c5af9755e7b6ffc579625440e4e148c7455 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:20:18 -0300 Subject: [PATCH 24/37] Read Browsee outside-access policy from its verified pipe --- contracts/link/v1/windows.md | 10 +- .../BrowseeStatusProtocolTests.cs | 65 ++++++++++ windows/Programa/BrowseeStatusProtocol.cs | 33 ++++++ windows/Programa/BrowseeWindowsStatus.cs | 111 ++++++++++++++++++ windows/Programa/MainWindow.Integrations.cs | 12 +- windows/Programa/Program.cs | 2 +- windows/Programa/Strings/en-US/Resources.resw | 3 + windows/Programa/Strings/ja-JP/Resources.resw | 3 + 8 files changed, 234 insertions(+), 5 deletions(-) create mode 100644 windows/Programa.Tests/BrowseeStatusProtocolTests.cs create mode 100644 windows/Programa/BrowseeStatusProtocol.cs create mode 100644 windows/Programa/BrowseeWindowsStatus.cs diff --git a/contracts/link/v1/windows.md b/contracts/link/v1/windows.md index ff875d33..13671ae1 100644 --- a/contracts/link/v1/windows.md +++ b/contracts/link/v1/windows.md @@ -4,13 +4,19 @@ In a Programa terminal, run `programa apps status --json`, or open Settings → - Direct installers use their exact Velopack IDs and main executable paths from [windows-apps.json](windows-apps.json). Velopack records the install root under the ID's Windows uninstall key, including custom install directories. Programa reads the root and checks the expected executable under `current`. The registry entry alone provides an unverified installation hint. A verified direct install requires matching signed PE product metadata, Windows Authenticode validation and an enrolled SHA-256 pair containing the validating publisher’s DER subject name and its issuing CA’s DER SubjectPublicKeyInfo. [Velopack 1.2.161 registration source](https://raw.githubusercontent.com/velopack/velopack/1.2.161/src/bins/src/windows/registry.rs) - Store installs require an exact enrolled package family and relative executable path, an active registration for the current Windows user, and Windows' Store signature classification. A running process must match the selected executable and, for a Store package, its full package name. [PackageManager](https://learn.microsoft.com/en-us/uwp/api/windows.management.deployment.packagemanager) · [Package identity APIs](https://learn.microsoft.com/en-us/windows/win32/appxpkg/functions) -- A verified running install takes priority over closed installs. With no verified running install, a verified Store registration wins, then the latest verified direct install. An unsigned or unverifiable registration can surface as `identity_unverified`. Discovery only reports presence. It leaves access at `unknown` until an app provides an authenticated status endpoint. +- A verified running install takes priority over closed installs. With no verified running install, a verified Store registration wins, then the latest verified direct install. An unsigned or unverifiable registration can surface as `identity_unverified`. Programa can also read the running Browsee instance’s outside-access setting. Installation and policy are reported independently. + +## Browsee outside access + +The signed Browsee executable must carry the exact version-resource description `DarkroomAppLinkVersion=1`. Programa connects to the current user’s existing `browsee-mcp-` on the local machine. Before sending bytes, it uses that same pipe handle to identify the server process, verifies the account SID and exact selected executable and package identity, and rechecks the current install and its marker. Installing the app or enabling discovery does not change its access settings. + +The request is the exact UTF-8 line `{"browsee_app_link_status":1}` followed by LF. A response is exactly `ready` or `disabled` followed by LF and EOF. Programa caps the response and applies a 650 ms deadline. A missing marker, refused identity, slow response or old server leaves access `unknown`. The CLI and Settings report the outside-access switch itself. It grants no permission, starts no helper, enumerates no browser state and does not test a tab or site. ## Current release gaps | App | Direct install | Windows integration | | --- | --- | --- | -| Browsee | Velopack `browsee-app`, `current/browsee.exe` | Ships `browsee-mcp.exe` over the existing per-user named pipe. Windows does not implement the macOS discovery probe. Existing outside-access and browser approvals own the decision to admit an agent. | +| Browsee | Velopack `browsee-app`, `current/browsee.exe` | Ships `browsee-mcp.exe` over the existing per-user named pipe. Programa probes Browsee’s existing Windows pipe only after verifying the process. Browsee’s own browser approvals and per-operation policy still govern all agent operations. | | Mesinyer | Velopack `Mesinyer`, `current/Mesinyer.Windows.exe` | No Windows companion readiness endpoint or MCP helper is packaged. | | Programa | Velopack `Programa` and the standalone executable | Ships its own MCP and control pipe. Windows discovery currently checks local installation and process identity only. | diff --git a/windows/Programa.Tests/BrowseeStatusProtocolTests.cs b/windows/Programa.Tests/BrowseeStatusProtocolTests.cs new file mode 100644 index 00000000..008f706a --- /dev/null +++ b/windows/Programa.Tests/BrowseeStatusProtocolTests.cs @@ -0,0 +1,65 @@ +using System.Text; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using static Darkroom.AppLink.Windows.CompanionDiscovery; + +namespace Programa.Tests; + +[TestClass] +public sealed class BrowseeStatusProtocolTests +{ + [DataRow("ready\n", "enabled")] + [DataRow("disabled\n", "disabled")] + [DataRow("ready", "unknown")] + [DataRow("ready\nextra", "unknown")] + [DataRow("ready\r\n", "unknown")] + [DataRow("READY\n", "unknown")] + [DataRow("", "unknown")] + [TestMethod] + public async Task ReadsOnlyExactStatusWithEndOfStream(string response, string expected) + { + using var pipe = new FixturePipe(response); + var access = await BrowseeStatusProtocol.ReadVerified(pipe, () => true, CancellationToken.None); + Assert.AreEqual(expected, access.ToString().ToLowerInvariant()); + Assert.AreEqual("{\"browsee_app_link_status\":1}\n", pipe.Request); + } + + [TestMethod] + public async Task NeverWritesWithoutVerificationOrAfterDeadline() + { + using var pipe = new FixturePipe("ready\n"); + Assert.AreEqual(OutsideAccess.Unknown, + await BrowseeStatusProtocol.ReadVerified(pipe, () => false, CancellationToken.None)); + using var deadline = new CancellationTokenSource(); + Assert.AreEqual(OutsideAccess.Unknown, await BrowseeStatusProtocol.ReadVerified(pipe, () => + { + deadline.Cancel(); + return true; + }, deadline.Token)); + Assert.AreEqual("", pipe.Request); + } + + [TestMethod] + public void RequiresExactVersionMarker() + { + Assert.IsTrue(BrowseeStatusProtocol.SupportsProbe("DarkroomAppLinkVersion=1")); + Assert.IsFalse(BrowseeStatusProtocol.SupportsProbe(null)); + Assert.IsFalse(BrowseeStatusProtocol.SupportsProbe("DarkroomAppLinkVersion=2")); + Assert.IsFalse(BrowseeStatusProtocol.SupportsProbe("DarkroomAppLinkVersion=1 ")); + } + + private sealed class FixturePipe(string response) : MemoryStream + { + private readonly byte[] reply = Encoding.UTF8.GetBytes(response); + private int offset; + + internal string Request => Encoding.UTF8.GetString(ToArray()); + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + if (offset == reply.Length) return ValueTask.FromResult(0); + buffer.Span[0] = reply[offset++]; + return ValueTask.FromResult(1); + } + } +} diff --git a/windows/Programa/BrowseeStatusProtocol.cs b/windows/Programa/BrowseeStatusProtocol.cs new file mode 100644 index 00000000..3c641b2e --- /dev/null +++ b/windows/Programa/BrowseeStatusProtocol.cs @@ -0,0 +1,33 @@ +using static Darkroom.AppLink.Windows.CompanionDiscovery; + +namespace Programa; + +internal static class BrowseeStatusProtocol +{ + internal static bool SupportsProbe(string? marker) => marker == "DarkroomAppLinkVersion=1"; + + internal static async Task ReadVerified(Stream stream, Func verify, CancellationToken cancellation) + { + if (cancellation.IsCancellationRequested || !verify() || cancellation.IsCancellationRequested) + return OutsideAccess.Unknown; + + // The status request contains no credentials, identifiers or agent commands. + await stream.WriteAsync("{\"browsee_app_link_status\":1}\n"u8.ToArray(), cancellation).ConfigureAwait(false); + var response = new byte["disabled\n"u8.Length + 1]; + var length = 0; + while (length < response.Length) + { + var count = await stream.ReadAsync(response.AsMemory(length), cancellation).ConfigureAwait(false); + cancellation.ThrowIfCancellationRequested(); + if (count == 0) + { + var bytes = response.AsSpan(0, length); + if (bytes.SequenceEqual("ready\n"u8)) return OutsideAccess.Enabled; + if (bytes.SequenceEqual("disabled\n"u8)) return OutsideAccess.Disabled; + break; + } + length += count; + } + return OutsideAccess.Unknown; + } +} diff --git a/windows/Programa/BrowseeWindowsStatus.cs b/windows/Programa/BrowseeWindowsStatus.cs new file mode 100644 index 00000000..285e7256 --- /dev/null +++ b/windows/Programa/BrowseeWindowsStatus.cs @@ -0,0 +1,111 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.IO.Pipes; +using System.Runtime.InteropServices; +using System.Security; +using System.Security.Principal; +using Darkroom.AppLink.Windows; +using Microsoft.Win32.SafeHandles; +using static Darkroom.AppLink.Windows.CompanionDiscovery; + +namespace Programa; + +internal static class BrowseeWindowsStatus +{ + private static readonly TimeSpan Deadline = TimeSpan.FromMilliseconds(650); + private const uint QueryLimitedInformation = 0x1000; + private const uint TokenQuery = 0x0008; + + internal static Task ReadAsync() + { + var platform = new WindowsCompanionPlatform(); + return CompanionDiscovery.ReadAsync(platform, "programa", (identity, candidate) => + ReadBrowsee(platform, identity, candidate).GetAwaiter().GetResult()); + } + + private static async Task ReadBrowsee(WindowsCompanionPlatform platform, Identity identity, Candidate candidate) + { + if (identity.App != "browsee" || !candidate.Verified) return OutsideAccess.Unknown; + try + { + using var currentUser = WindowsIdentity.GetCurrent(); + if (currentUser.User is not { } sid || + !BrowseeStatusProtocol.SupportsProbe(FileVersionInfo.GetVersionInfo(candidate.Executable).Comments)) + return OutsideAccess.Unknown; + + using var executable = candidate.PackageFullName is null + ? File.Open(candidate.Executable, FileMode.Open, FileAccess.Read, FileShare.Read) + : null; + using var deadline = new CancellationTokenSource(Deadline); + using var pipe = new NamedPipeClientStream(".", $"browsee-mcp-{sid.Value}", PipeDirection.InOut, + PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly, TokenImpersonationLevel.Identification); + await pipe.ConnectAsync(150, deadline.Token).ConfigureAwait(false); + return await BrowseeStatusProtocol.ReadVerified(pipe, + () => MatchesSelectedServer(pipe, sid, platform, identity, candidate, executable), + deadline.Token).ConfigureAwait(false); + } + catch (Exception error) when (error is IOException or TimeoutException or OperationCanceledException or + UnauthorizedAccessException or SecurityException or Win32Exception or InvalidOperationException or ArgumentException) + { + return OutsideAccess.Unknown; + } + } + + private static bool MatchesSelectedServer(NamedPipeClientStream pipe, SecurityIdentifier sid, + WindowsCompanionPlatform platform, Identity identity, Candidate candidate, FileStream? executable) + { + // This is the same connected handle that will send the request. Keep the process handle + // open while checking the executable, Windows package identity and account. + if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle, out var pid) || pid == 0) return false; + using var process = OpenProcess(QueryLimitedInformation, false, pid); + if (process.IsInvalid || WindowsCompanionPlatform.MatchesPackage(process, candidate.PackageFullName) is not true) + return false; + var path = new char[32768]; + uint length = (uint)path.Length; + if (!QueryFullProcessImageNameW(process, 0, path, ref length) + || length >= path.Length + || !string.Equals(new string(path, 0, (int)length), candidate.Executable, StringComparison.OrdinalIgnoreCase) + || !OpenProcessToken(process, TokenQuery, out var token)) + return false; + using (token) + using (var server = new WindowsIdentity(token.DangerousGetHandle())) + { + if (server.User is not { } serverSid || !sid.Equals(serverSid)) return false; + } + + // Keep the direct file open without write or delete sharing throughout the request. + // If the executable changed after this process started, its marker cannot apply. + if (executable is not null && + (!GetProcessTimes(process, out var created, out _, out _, out _) || + File.GetLastWriteTimeUtc(executable.SafeFileHandle) > DateTime.FromFileTimeUtc(created))) + return false; + + // Refresh the signature or registered Store identity after establishing the pipe's owner. + // An install that changed during the query must pass identification and the marker again. + return platform.Candidates(identity).Any(current => current.Verified && + string.Equals(current.Executable, candidate.Executable, StringComparison.OrdinalIgnoreCase) && + string.Equals(current.PackageFullName, candidate.PackageFullName, StringComparison.OrdinalIgnoreCase) && + current.Version == candidate.Version) + && BrowseeStatusProtocol.SupportsProbe(FileVersionInfo.GetVersionInfo(candidate.Executable).Comments) + && GetNamedPipeServerProcessId(pipe.SafePipeHandle, out var confirmedPid) && confirmedPid == pid; + } + + [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetNamedPipeServerProcessId(SafePipeHandle pipe, out uint serverProcessId); + + [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] + private static extern SafeProcessHandle OpenProcess(uint desiredAccess, [MarshalAs(UnmanagedType.Bool)] bool inherit, uint pid); + + [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool QueryFullProcessImageNameW(SafeProcessHandle process, uint flags, [Out] char[] path, ref uint pathLength); + + [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetProcessTimes(SafeProcessHandle process, out long creation, out long exit, out long kernel, out long user); + + [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool OpenProcessToken(SafeProcessHandle process, uint access, out SafeAccessTokenHandle token); +} diff --git a/windows/Programa/MainWindow.Integrations.cs b/windows/Programa/MainWindow.Integrations.cs index df5f2728..3dbd4cd5 100644 --- a/windows/Programa/MainWindow.Integrations.cs +++ b/windows/Programa/MainWindow.Integrations.cs @@ -28,7 +28,7 @@ async Task Refresh() status.Text = Localizer.Get("CompanionChecking"); try { - var report = await CompanionDiscovery.ReadAsync(new WindowsCompanionPlatform(), "programa"); + var report = await BrowseeWindowsStatus.ReadAsync(); foreach (var peer in report.Apps) { var name = new TextBlock { Text = peer.Title }; @@ -40,7 +40,7 @@ async Task Refresh() { name, new TextBlock { Text = Localizer.Get(StatusKey(peer)), TextWrapping = TextWrapping.Wrap }, - new TextBlock { Text = Localizer.Get("CompanionAccessUnknown"), TextWrapping = TextWrapping.Wrap }, + new TextBlock { Text = Localizer.Get(AccessKey(peer)), TextWrapping = TextWrapping.Wrap }, }, }); } @@ -64,6 +64,14 @@ async Task Refresh() "not_installed" => "CompanionNotFound", "identity_unverified" => "CompanionIdentityUnverified", "not_running" => "CompanionClosed", + "ready" or "disabled" => "CompanionRunning", _ => peer.Running == true ? "CompanionUnavailable" : "CompanionRunningUnknown", }; + private static string AccessKey(CompanionDiscovery.Peer peer) => peer.Access switch + { + "enabled" => "CompanionBrowseeOutsideAccessEnabled", + "disabled" => "CompanionBrowseeOutsideAccessDisabled", + _ => "CompanionAccessUnknown", + }; + } diff --git a/windows/Programa/Program.cs b/windows/Programa/Program.cs index da99ce54..66db6e6d 100644 --- a/windows/Programa/Program.cs +++ b/windows/Programa/Program.cs @@ -29,7 +29,7 @@ public static void Main(string[] args) try { Environment.ExitCode = CompanionDiscovery.Run(args[1..], - () => CompanionDiscovery.ReadAsync(new WindowsCompanionPlatform(), "programa").GetAwaiter().GetResult(), output, error); + () => BrowseeWindowsStatus.ReadAsync().GetAwaiter().GetResult(), output, error); } catch (Exception failure) when (failure is IOException or UnauthorizedAccessException or InvalidOperationException or TimeoutException or System.Text.Json.JsonException) diff --git a/windows/Programa/Strings/en-US/Resources.resw b/windows/Programa/Strings/en-US/Resources.resw index cb57a82a..ed2a40b1 100644 --- a/windows/Programa/Strings/en-US/Resources.resw +++ b/windows/Programa/Strings/en-US/Resources.resw @@ -303,6 +303,9 @@ Registered · Identity unverified Installed · Closed Running · Integration status unavailable + Running + Browsee outside access enabled + Browsee outside access disabled Installed · Running status unknown Couldn’t check companion apps. Refresh to try again. diff --git a/windows/Programa/Strings/ja-JP/Resources.resw b/windows/Programa/Strings/ja-JP/Resources.resw index 39220c2e..13e53cd3 100644 --- a/windows/Programa/Strings/ja-JP/Resources.resw +++ b/windows/Programa/Strings/ja-JP/Resources.resw @@ -303,6 +303,9 @@ 登録済み · ID 未確認 インストール済み · 停止中 実行中 · 連携状態を確認できません + 実行中 + Browsee の外部アクセスは有効です + Browsee の外部アクセスは無効です インストール済み · 実行状態は不明 連携アプリを確認できませんでした。更新して再試行してください。 From 8503747ffa6797494cb54fb60d715e1010ca1624 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:25:51 -0300 Subject: [PATCH 25/37] Point Browsee access recovery to the selectable settings pane --- Resources/Localizable.xcstrings | 2 +- Sources/SettingsDarkroomApps.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index e69acca3..44ed589c 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -22,7 +22,7 @@ "settings.apps.unverified" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Install a signed release, then refresh."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "署名済みのリリースをインストールしてから更新してください。"}}}}, "settings.apps.install" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Refresh after installing the app."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "アプリをインストールしてから更新してください。"}}}}, "settings.apps.update" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Update the app to a release that supports Darkroom app discovery."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Darkroom アプリの検出に対応するバージョンに更新してください。"}}}}, - "settings.apps.browsee.reviewAccess" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "In Browsee, open Settings → Agents and review “Let other apps control my tabs”."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Browsee の「設定」→「エージェント」で、他のアプリによるタブの操作を許可する設定を確認してください。"}}}}, + "settings.apps.browsee.reviewAccess" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "In Browsee Settings, open Access and review “Let other apps control my tabs”."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Browsee の設定で「Access」を開き、他のアプリによるタブの操作を許可する設定を確認してください。"}}}}, "settings.apps.mesinyer.reviewAccess" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "In Mesinyer, open Settings → AI Tools and review access for the workspace."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Mesinyer の「設定」→「AI ツール」で、ワークスペースへのアクセスを確認してください。"}}}}, "settings.apps.tryAgain" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "The app did not confirm readiness. Refresh to check again."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "アプリを利用できるか確認できませんでした。更新して再確認してください。"}}}}, "settings.apps.refreshed" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "App status updated."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "アプリの状態を更新しました。"}}}}, diff --git a/Sources/SettingsDarkroomApps.swift b/Sources/SettingsDarkroomApps.swift index a18a3216..d6293ea9 100644 --- a/Sources/SettingsDarkroomApps.swift +++ b/Sources/SettingsDarkroomApps.swift @@ -126,7 +126,7 @@ struct SettingsDarkroomApps: View { case .denied, .disabled: switch peer { case .browsee: - return String(localized: "settings.apps.browsee.reviewAccess", defaultValue: "In Browsee, open Settings → Agents and review “Let other apps control my tabs”.") + return String(localized: "settings.apps.browsee.reviewAccess", defaultValue: "In Browsee Settings, open Access and review “Let other apps control my tabs”.") case .mesinyer: return String(localized: "settings.apps.mesinyer.reviewAccess", defaultValue: "In Mesinyer, open Settings → AI Tools and review access for the workspace.") } From 19ff3bc6ae7e0da749280b6a8750798b1cf79baf Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:41:40 -0300 Subject: [PATCH 26/37] Test password rotation revokes passive event subscribers --- ...erminalControllerSocketSecurityTests.swift | 37 +++++++++++++++---- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/programaTests/TerminalControllerSocketSecurityTests.swift b/programaTests/TerminalControllerSocketSecurityTests.swift index 48c6f3cc..e40cf9d3 100644 --- a/programaTests/TerminalControllerSocketSecurityTests.swift +++ b/programaTests/TerminalControllerSocketSecurityTests.swift @@ -1288,10 +1288,29 @@ final class TerminalControllerSocketSecurityTests: XCTestCase { isSuccessfulV2Authentication(oldAuthentication), "The persistent client must authenticate with the credential active when it connects" ) - XCTAssertTrue( - isSuccessfulV2Ping(try sendV2Ping(to: oldClientFD, id: 2)), - "An authenticated password-mode client must be able to execute commands before rotation" + let subscription = try sendV2Request( + method: "subscribe", + params: ["classes": ["agent_state"]], + id: 2, + to: oldClientFD + ) + XCTAssertEqual(subscription["ok"] as? Bool, true) + + let surfaceID = UUID() + SocketEventBroadcaster.shared.publishAgentState( + workspaceId: UUID(), + surfaceId: surfaceID, + state: nil, + previousState: nil, + toRoutes: false, + trusted: true ) + let frame = try readLine(from: oldClientFD) + let event = try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(frame.utf8)) as? [String: Any] + ) + XCTAssertEqual(event["event"] as? String, "agent_state") + XCTAssertEqual(event["surface_id"] as? String, surfaceID.uuidString) credentials.update(password: newPassword) NotificationCenter.default.post( @@ -1299,11 +1318,13 @@ final class TerminalControllerSocketSecurityTests: XCTestCase { object: nil ) - let revokedClientResponse = try? sendV2Ping(to: oldClientFD, id: 3, timeout: 1.0) - XCTAssertFalse( - revokedClientResponse.map(isSuccessfulV2Ping) ?? false, - "Rotating the socket password must revoke clients authenticated with the previous credential" - ) + // The subscriber sends nothing after rotation. A stale client must be + // disconnected even when it is only listening for events. + XCTAssertThrowsError(try readLine(from: oldClientFD, timeout: 1.0)) { error in + let socketError = error as NSError + XCTAssertEqual(socketError.domain, NSPOSIXErrorDomain) + XCTAssertEqual(socketError.code, Int(ECONNRESET)) + } let newClientFD = try connectPersistentClient(to: socketPath) defer { Darwin.close(newClientFD) } From 946dced5e9b5ecee63669dc95d1985ca240b6b0d Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:45:35 -0300 Subject: [PATCH 27/37] Retain the ready Windows publish folder for optional release evidence --- scripts/build-windows.ps1 | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/scripts/build-windows.ps1 b/scripts/build-windows.ps1 index 29c97169..01d35a74 100644 --- a/scripts/build-windows.ps1 +++ b/scripts/build-windows.ps1 @@ -12,6 +12,8 @@ param( # Optional fresh or empty folder that receives the whole published app, for packers such # as Velopack (ship.json windows.publish) that need the folder rather than the exe copies. [string]$PublishDirectory = '', + # Best-effort evidence for the release's isolated Shipit shadow job. + [string]$PreviewPublishDirectory = '', # Prepare the self-contained, multi-file MSIX payload and skip the standalone executable copies. [switch]$StorePackage ) @@ -194,6 +196,23 @@ try { Write-Output "Archived executable: $ArchivedExecutable" Write-Output "SHA-256: $RollingHash" + if ($PreviewPublishDirectory) { + $StagedPreview = '' + try { + $Preview = [System.IO.Path]::GetFullPath($PreviewPublishDirectory) + if (Test-Path -LiteralPath $Preview) { throw "Preview directory already exists: $Preview" } + $StagedPreview = "$Preview.partial-$([Guid]::NewGuid().ToString('N'))" + Copy-Item -LiteralPath $PublishRoot -Destination $StagedPreview -Recurse + Move-Item -LiteralPath $StagedPreview -Destination $Preview + } catch { + Write-Warning "Could not retain optional Windows preview input: $_" + } finally { + if ($StagedPreview -and (Test-Path -LiteralPath $StagedPreview)) { + Remove-Item -LiteralPath $StagedPreview -Recurse -Force -ErrorAction SilentlyContinue + } + } + } + if ($ResolvedPublish) { Copy-Item -Path (Join-Path $PublishRoot '*') -Destination $ResolvedPublish -Recurse Write-Output "Published app folder: $ResolvedPublish" From 9a065c352d9fbf9ae58f33cbb8c2b29c3c68bbaf Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:45:35 -0300 Subject: [PATCH 28/37] =?UTF-8?q?Compare=20Shipit=20packaging=20with=20Pro?= =?UTF-8?q?grama=E2=80=99s=20canonical=20Windows=20executable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/release.yml | 104 +++++++++++++++++++++++++++++++++- docs/release.md | 24 ++++++++ 2 files changed, 127 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2ccce823..24129d01 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -607,6 +607,7 @@ jobs: EFFECTIVE_BUILD: ${{ needs.release-identity.outputs.effective_build }} EFFECTIVE_MARKETING_VERSION: ${{ needs.release-identity.outputs.effective_version }} TARGET_SHA: ${{ needs.release-identity.outputs.target_sha }} + WINDOWS_SHIPIT_PREVIEW: ${{ github.repository == 'darkroomengineering/programa' && github.event_name == 'workflow_run' && vars.PROGRAMA_WINDOWS_SHIPIT_REV != '' }} steps: - name: Checkout release revision uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 @@ -676,11 +677,15 @@ jobs: $ErrorActionPreference = "Stop" $output = Join-Path $env:RUNNER_TEMP "programa-windows-payload" New-Item -ItemType Directory -Path $output | Out-Null + $preview = @{} + if ($env:WINDOWS_SHIPIT_PREVIEW -eq 'true') { + $preview.PreviewPublishDirectory = Join-Path $env:RUNNER_TEMP "programa-windows-ready-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + } & ./scripts/build-windows.ps1 ` -Version $env:EFFECTIVE_MARKETING_VERSION ` -Build $env:EFFECTIVE_BUILD ` -Commit $env:TARGET_SHA ` - -OutputDirectory $output + -OutputDirectory $output @preview $stableName = "programa-windows.exe" $immutableName = "programa-windows-$($env:EFFECTIVE_BUILD).exe" @@ -729,6 +734,103 @@ jobs: if-no-files-found: error retention-days: 7 + - name: Keep the ready Windows build for the Shipit comparison + if: env.WINDOWS_SHIPIT_PREVIEW == 'true' + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: programa-windows-ready-${{ github.run_id }} + overwrite: true + path: ${{ runner.temp }}/programa-windows-ready-${{ github.run_id }}-${{ github.run_attempt }}/ + if-no-files-found: error + retention-days: 7 + + shadow-shipit-windows: + needs: [release-identity, build-windows] + if: >- + github.repository == 'darkroomengineering/programa' && + github.event_name == 'workflow_run' && + github.event.workflow_run.event == 'push' && + github.event.workflow_run.head_branch == 'main' && + github.event.workflow_run.conclusion == 'success' && + needs.release-identity.outputs.target_sha == github.event.workflow_run.head_sha && + vars.PROGRAMA_WINDOWS_SHIPIT_REV != '' + permissions: + contents: read + # Programa is public. The current Darky Body Windows runner group excludes public repositories. + runs-on: windows-latest + timeout-minutes: 25 + env: + EFFECTIVE_BUILD: ${{ needs.release-identity.outputs.effective_build }} + EFFECTIVE_MARKETING_VERSION: ${{ needs.release-identity.outputs.effective_version }} + TARGET_SHA: ${{ needs.release-identity.outputs.target_sha }} + SHIPIT_REV: ${{ vars.PROGRAMA_WINDOWS_SHIPIT_REV }} + steps: + - name: Validate the Shipit pin + shell: pwsh + run: | + if ($env:SHIPIT_REV -cnotmatch '^[0-9a-f]{40}$') { throw 'Expected an immutable Shipit commit SHA.' } + + - name: Check out the verified Programa release revision + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.release-identity.outputs.target_sha }} + persist-credentials: false + + - name: Check out the pinned Shipit staging code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + repository: darkroomengineering/shipit + ref: ${{ vars.PROGRAMA_WINDOWS_SHIPIT_REV }} + ssh-key: ${{ secrets.SHIPIT_SSH_KEY }} + path: .shipit-windows-preview + persist-credentials: false + + - uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6 + with: + dotnet-version: '10.0.x' + + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.4.4 + + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: programa-windows-${{ github.run_id }} + path: ${{ runner.temp }}/programa-windows-legacy + + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: programa-windows-ready-${{ github.run_id }} + path: ${{ runner.temp }}/programa-windows-ready + + - name: Stage and verify the installer from the canonical executable + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + if ((git rev-parse HEAD) -cne $env:TARGET_SHA) { throw 'Programa source checkout differs from the release revision.' } + if ((git -C .shipit-windows-preview rev-parse HEAD) -cne $env:SHIPIT_REV) { + throw 'Shipit source checkout differs from the release pin.' + } + $legacy = Join-Path $env:RUNNER_TEMP programa-windows-legacy + $stable = Get-FileHash -Algorithm SHA256 -LiteralPath (Join-Path $legacy 'programa-windows.exe') + $immutable = Get-FileHash -Algorithm SHA256 -LiteralPath (Join-Path $legacy "programa-windows-$env:EFFECTIVE_BUILD.exe") + if ($stable.Hash -cne $immutable.Hash) { throw 'The canonical release executables differ.' } + bun .shipit-windows-preview/src/cli.ts stage-windows-package ` + --input (Join-Path $env:RUNNER_TEMP 'programa-windows-ready') ` + --output (Join-Path $env:RUNNER_TEMP 'programa-windows-shipit-preview') ` + --version $env:EFFECTIVE_MARKETING_VERSION --build $env:EFFECTIVE_BUILD ` + --commit $env:TARGET_SHA --sha256 ($stable.Hash.ToLowerInvariant()) + if ($LASTEXITCODE -ne 0) { throw 'Shipit could not verify the ready Windows payload.' } + + - name: Keep the verified Windows Shipit preview + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: programa-windows-shipit-preview-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/programa-windows-shipit-preview/ + if-no-files-found: error + retention-days: 7 + # Second half of the supersession check: a newer main commit landing while the builds ran # means this run must not stage or promote. It ends successfully with a notice; the newer # commit's own run ships. (The reconciler re-checks main before every public mutation.) diff --git a/docs/release.md b/docs/release.md index 11705f2d..2765f7ac 100644 --- a/docs/release.md +++ b/docs/release.md @@ -97,6 +97,30 @@ publish scripts: the run-number patch version, the CLI version memory guard, the Sparkle version and provisioning profile checks, dSYMs, build attestations, the sealed candidate drafts and the reconciler's high-water and CI-provenance checks. +### Windows executable and installer comparison + +The canonical Windows publisher in `release.yml` follows successful main CI and releases +the standalone `programa-windows.exe` and its build-specific copy. The manual Velopack lane +and its `win` channel are separate. The public download and the app's **Check for Updates** +action currently lead to the standalone release. + +To compare packaging without publishing, set `PROGRAMA_WINDOWS_SHIPIT_REV` to a reviewed +immutable Shipit commit with `stage-windows-package` and provide its read-only checkout key +as `SHIPIT_SSH_KEY`. The next ordinary main release keeps the same already-built Windows +publish directory as a short-lived artifact. The independent preview job downloads that +directory and the canonical EXE pair from the same run, verifies the release revision and +SHA-256 against both copies, and verifies that the exact main executable is inside the +new full package. The result includes `validation.json`, the installer aliases and feed. +The release assembly continues to consume only the canonical EXE pair. Clear +`PROGRAMA_WINDOWS_SHIPIT_REV` to disable the preview. + +The preview starts with an empty feed. It preserves any Authenticode signature of the main +executable and leaves Setup.exe unsigned. Before switching the default publisher, verify a +signed installer in a disposable Windows profile, test the upgrade and profile preservation +across two increasing builds, implement the app's real update-feed path, and confirm the +intended public asset names and rollback behavior. Use Darky Body when an eligible runner +group is available to this public repository. + ### Desktop cutover check Use the private Shipit runner for the signed side-by-side comparison. Compare the legacy and Shipit payloads from the same reviewed `main` SHA with the same effective version and build number. Keep the legacy publisher active while comparing artifacts. Each input directory contains the stable and versioned DMGs, its appcast, and the dSYM archive. From 6d9aa408b349a363fa11176435c22922615bcf43 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:47:00 -0300 Subject: [PATCH 29/37] =?UTF-8?q?Measure=20Programa=E2=80=99s=20native=20A?= =?UTF-8?q?pp=20Sandbox=20process=20and=20socket=20limits?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/app-sandbox-spike.md | 7 +++- scripts/app-sandbox-spike/boundary.c | 36 +++++++++++++----- scripts/app-sandbox-spike/observe-startup.py | 39 +++++++++++++++++--- scripts/app-sandbox-spike/probe-boundary.sh | 37 +++++++++++++++++++ 4 files changed, 103 insertions(+), 16 deletions(-) create mode 100644 scripts/app-sandbox-spike/probe-boundary.sh diff --git a/docs/app-sandbox-spike.md b/docs/app-sandbox-spike.md index 64bc1c9b..5e7148d1 100644 --- a/docs/app-sandbox-spike.md +++ b/docs/app-sandbox-spike.md @@ -19,6 +19,10 @@ Two disposable app bundles from that binary verified with `codesign --verify --d | Selected repo in `~/Developer` and worktrees | The app did not reach folder selection. The current Open Folder action passes a path string to workspace creation. There is no bookmark handling at that entry point. | Opening a folder in the app, using the same path in a child shell, and reopening it after restart require separate verification. | | Detached panes, escrow and restore | Startup did not reach terminal pane creation. Current panes use a `launchctl bootstrap` path with a direct Ghostty fallback. Escrow starts a second copy of Programa and passes its PTY over a Unix socket. | Neither path demonstrated App Store-compatible behavior. | +The native repeat used the same ad hoc bundles on macOS 27.2.1 with working desktop access. Both Programa fixtures stayed running. The control created its tagged socket in `/tmp`. App Sandbox denied that bind with `EPERM`. With a unique short path inside the app’s container, the sandboxed copy bound the socket and answered a read-only `system.ping` from the observer. This proves startup and the diagnostic socket path. In-pane tools, app-to-app authorization, and restore still need separate checks. + +The headless boundary fixture also reached `main` once packaged as a signed app bundle. Its system shell started successfully. The app and child shell both failed to read the same synthetic unselected file, and the app could not spawn the synthetic executable in that external directory. The control read the file, its child shell read it, and the executable returned success. Selected-folder grants and team-signed release packaging remain separate tests. + A store comparator exposes the distinction to users. Shell Pilot documents a sandboxed local shell with limits on installed tools, git, and job control, and a separate SSH mode. This documents a shipped product's scope. It does not establish review approval for Programa's process, tools or architecture. [Shell Pilot listing](https://apps.apple.com/us/app/shell-pilot-terminal/id6816260816?mt=12) ## Reproduce without publishing @@ -28,6 +32,7 @@ Use a disposable macOS desktop session or VM account. Use the private Shipit Dar ```bash scripts/app-sandbox-spike/package.sh /path/to/Programa.app python3 scripts/app-sandbox-spike/observe-startup.py /tmp/programa-mas-spike.XXXXXXXX +python3 scripts/app-sandbox-spike/observe-startup.py /tmp/programa-mas-spike.XXXXXXXX --container-socket ``` The package script creates both app bundles in the printed scratch directory. The startup observer uses direct Ghostty spawning and disables session restore to isolate initial startup. It disables Sparkle checks and removes handler declarations in the copies. It reads the signed entitlements back and checks the sandbox entitlement values. Set `PROGRAMA_SANDBOX_SPIKE_SIGN_IDENTITY` to the keychain identity on the private runner to use a common signing team and retain Hardened Runtime. This is a diagnostic fixture with separate bundle identifiers. It has no upload or submission path. @@ -39,7 +44,7 @@ Use Activity Monitor's Sandbox column to confirm the app and its shell actually 3. From the pane run `programa ping` against the tagged fixture. Exercise the bundled `programa-mcp` over stdio with an initialize exchange and a read-only workspace-list call. Repeat from a separate terminal and record the transport/access outcome separately. Exercise worktree creation within the disposable repo, and check what changes when the destination is outside the selected folder. 4. Exercise the normal pane spawn path and the direct Ghostty fallback in separate runs. Confirm whether launchd created a job. Test persistence with the existing scrollback journey, then independently confirm process survival with a shell PID and a marker printed while Programa is quit. Ordinary scrollback restoration does not establish live PTY recovery. -To isolate the launch environment without AppKit, compile `scripts/app-sandbox-spike/boundary.c` twice and sign one copy ad hoc with `app.entitlements`. Pass both copies the path to a synthetic external file. Record whether each reaches `main`, reads the file and spawns the system shell before comparing the actual apps. +To isolate the launch environment without AppKit, run `bash scripts/app-sandbox-spike/probe-boundary.sh` from a writable, non-container directory. It signs two headless app bundles and observes parent and child reads, system shell startup and the external executable. The probe creates its own synthetic file and tool and removes them at exit. ## Rework for INC-992 diff --git a/scripts/app-sandbox-spike/boundary.c b/scripts/app-sandbox-spike/boundary.c index 0db759e9..1503f6c8 100644 --- a/scripts/app-sandbox-spike/boundary.c +++ b/scripts/app-sandbox-spike/boundary.c @@ -7,23 +7,39 @@ #include extern char **environ; -int main(int argc, char *argv[]) { - if (argc != 2) return 64; - fprintf(stderr, "entered_main=yes\n"); - int descriptor = open(argv[1], O_RDONLY); - fprintf(stderr, "outside_file_read=%s\n", descriptor >= 0 ? "allowed" : strerror(errno)); - if (descriptor >= 0) close(descriptor); - char *arguments[] = {"/bin/sh", "-c", "echo system_shell=yes", NULL}; +static int run(const char *label, char *const arguments[]) { pid_t child; int result = posix_spawn(&child, arguments[0], NULL, NULL, arguments, environ); if (result != 0) { - fprintf(stderr, "shell_spawn=%s\n", strerror(result)); + fprintf(stderr, "%s_spawn=%s\n", label, strerror(result)); return 1; } int status; if (waitpid(child, &status, 0) < 0) { - fprintf(stderr, "shell_wait=%s\n", strerror(errno)); + fprintf(stderr, "%s_wait=%s\n", label, strerror(errno)); return 1; } - return WIFEXITED(status) ? WEXITSTATUS(status) : 1; + result = WIFEXITED(status) ? WEXITSTATUS(status) : 1; + fprintf(stderr, "%s_exit=%d\n", label, result); + return result; +} + +int main(int argc, char *argv[]) { + if (argc != 2 && argc != 3) return 64; + fprintf(stderr, "entered_main=yes\n"); + int descriptor = open(argv[1], O_RDONLY); + fprintf(stderr, "outside_file_read=%s\n", descriptor >= 0 ? "allowed" : strerror(errno)); + if (descriptor >= 0) close(descriptor); + char *shell[] = {"/bin/sh", "-c", + "echo system_shell=yes; " + "if (IFS= read -r line < \"$1\") 2>/dev/null; " + "then echo child_outside_file_read=allowed; " + "else echo child_outside_file_read=denied; fi", + "boundary", argv[1], NULL}; + int result = run("system_shell", shell); + if (argc == 3) { + char *tool[] = {argv[2], NULL}; + run("outside_tool", tool); + } + return result; } diff --git a/scripts/app-sandbox-spike/observe-startup.py b/scripts/app-sandbox-spike/observe-startup.py index 9fec50e3..a221d2ac 100644 --- a/scripts/app-sandbox-spike/observe-startup.py +++ b/scripts/app-sandbox-spike/observe-startup.py @@ -1,16 +1,33 @@ """Observe startup of the two package.sh fixtures in an isolated macOS account.""" import argparse +import json import os from pathlib import Path import plistlib import signal +import socket import subprocess import tempfile import time +import uuid + + +def ping(path): + try: + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: + client.settimeout(2) + client.connect(str(path)) + client.sendall(b'{"id":1,"method":"system.ping","params":{}}\n') + with client.makefile('rb') as response: + return json.loads(response.readline(4096)).get('ok') is True + except (OSError, ValueError, AttributeError): + return False parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("fixture_root", type=Path) parser.add_argument("--seconds", type=int, default=15, choices=range(1, 61), metavar="1-60") +parser.add_argument("--container-socket", action="store_true", + help="try a short, unique socket path inside the sandboxed app container") arguments = parser.parse_args() scratch = arguments.fixture_root.resolve() for tag, label in (("store-control", "Programa App Sandbox Control"), ("store-spike", "Programa App Sandbox Spike")): @@ -19,22 +36,34 @@ if plist.get("CFBundleIdentifier") != f"com.darkroom.programa.debug.{tag}": raise SystemExit(f"Unexpected bundle identity: {app}") exe = app / "MacOS" / plist["CFBundleExecutable"] - socket = Path("/tmp") / f"programa-debug-{tag}.sock" - if socket.exists(): - raise SystemExit(f"Refusing to use existing socket: {socket}") + socket_path = Path("/tmp") / f"programa-debug-{tag}.sock" + if arguments.container_socket: + directory = Path("/tmp") + if tag == "store-spike": + directory = Path.home() / "Library" / "Containers" / plist["CFBundleIdentifier"] / "Data" + if not directory.is_dir(): + raise SystemExit("Start the sandboxed fixture once to initialize its app container") + socket_path = directory / f"p-{uuid.uuid4().hex[:8]}.sock" + if len(os.fsencode(socket_path)) >= 104: + raise SystemExit("The app container socket path does not fit sockaddr_un") + if socket_path.exists(): + raise SystemExit(f"Refusing to use existing socket: {socket_path}") home = Path(tempfile.mkdtemp(prefix=f"{tag}-", dir=scratch)) log = home / "startup.log" env = {"HOME": str(home), "CFFIXED_USER_HOME": str(home), "PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "SHELL": "/bin/sh", "ZDOTDIR": str(home), "PROGRAMA_TAG": tag, "PROGRAMA_DISABLE_SESSION_RESTORE": "1", "PROGRAMA_PANE_LAUNCHD": "0", "TMPDIR": str(home)} + if arguments.container_socket: + env.update(PROGRAMA_ALLOW_SOCKET_OVERRIDE="1", PROGRAMA_SOCKET_PATH=str(socket_path)) with log.open("wb") as output: process = subprocess.Popen([str(exe), "-socketControlMode", "automation", "-programaWelcomeShown", "YES"], cwd=home, env=env, stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT, start_new_session=True) stop = time.monotonic() + arguments.seconds - while process.poll() is None and not socket.exists() and time.monotonic() < stop: + while process.poll() is None and not socket_path.exists() and time.monotonic() < stop: time.sleep(.10) - print(f"{tag}: exit={process.poll()} socket={socket.exists()} log={log}") + socket_exists = socket_path.exists() + print(f"{tag}: exit={process.poll()} socket={socket_exists} ping={socket_exists and ping(socket_path)} log={log}") if process.poll() is None: try: os.killpg(process.pid, signal.SIGTERM) diff --git a/scripts/app-sandbox-spike/probe-boundary.sh b/scripts/app-sandbox-spike/probe-boundary.sh new file mode 100644 index 00000000..bb74f674 --- /dev/null +++ b/scripts/app-sandbox-spike/probe-boundary.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +set -euo pipefail + +fixture_dir=$(cd "$(dirname "$0")" && pwd) +bundles=$(mktemp -d /private/tmp/programa-boundary-bundles.XXXXXXXX) +outside=$(mktemp -d "$PWD/.programa-boundary.XXXXXXXX") +trap 'rm -f "$outside/sentinel" "$outside/tool"; rmdir "$outside"' EXIT +printf '%s\n' synthetic > "$outside/sentinel" +printf '%s\n' 'int main(void) { return 0; }' | clang -x c - -o "$outside/tool" +clang -Wall -Wextra -Werror "$fixture_dir/boundary.c" -o "$bundles/boundary" + +for variant in control sandboxed; do + bundle="$bundles/$variant.app" + mkdir -p "$bundle/Contents/MacOS" + cp "$bundles/boundary" "$bundle/Contents/MacOS/boundary" + python3 - "$bundle/Contents/Info.plist" "com.darkroom.programa.boundary-lab.$variant" <<'PY' +import plistlib +import sys + +with open(sys.argv[1], "wb") as output: + plistlib.dump({ + "CFBundleIdentifier": sys.argv[2], + "CFBundleExecutable": "boundary", + "CFBundlePackageType": "APPL", + "LSBackgroundOnly": True, + }, output) +PY + signing=(--force --sign -) + if [[ "$variant" == sandboxed ]]; then + signing+=(--entitlements "$fixture_dir/app.entitlements") + fi + codesign "${signing[@]}" "$bundle" + codesign --verify --deep --strict "$bundle" + printf '%s\n' "$variant" + "$bundle/Contents/MacOS/boundary" "$outside/sentinel" "$outside/tool" || printf 'fixture_exit=%s\n' "$?" +done +printf 'Fixtures at %s\n' "$bundles" From c4d67c4abc55ec3e43529ee0fe2fb51477f3366d Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:47:30 -0300 Subject: [PATCH 30/37] Keep the Windows Shipit checkout key in the main-only preview environment --- .github/workflows/release.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 24129d01..3ad1a7c5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -751,6 +751,7 @@ jobs: github.repository == 'darkroomengineering/programa' && github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && + github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'main' && github.event.workflow_run.conclusion == 'success' && needs.release-identity.outputs.target_sha == github.event.workflow_run.head_sha && @@ -759,6 +760,7 @@ jobs: contents: read # Programa is public. The current Darky Body Windows runner group excludes public repositories. runs-on: windows-latest + environment: shipit-preview timeout-minutes: 25 env: EFFECTIVE_BUILD: ${{ needs.release-identity.outputs.effective_build }} From 056c018eb660549b801d3553f0d62d961fe4f16d Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:51:50 -0300 Subject: [PATCH 31/37] =?UTF-8?q?Declare=20the=20Programa=20iPhone=20app?= =?UTF-8?q?=E2=80=99s=20local=20preference=20API=20use?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/release.md | 4 ++++ ios/Programa/PrivacyInfo.xcprivacy | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 ios/Programa/PrivacyInfo.xcprivacy diff --git a/docs/release.md b/docs/release.md index 2765f7ac..3d4a73d8 100644 --- a/docs/release.md +++ b/docs/release.md @@ -78,6 +78,10 @@ Darkroom member’s computer or credentials. Confirm the App Store Connect recor and support metadata, and review access before submission. Keep manual release in App Store Connect until review and the intended availability have been confirmed. +Confirm the exported app contains `PrivacyInfo.xcprivacy` for its app-local +preferences. Review the archive’s privacy report for linked dependencies before +completing the App Store Connect privacy answers. [Apple required reason APIs](https://developer.apple.com/documentation/bundleresources/describing-use-of-required-reason-api) + ## ship (shipit) `ship.json` at the repository root describes Programa for diff --git a/ios/Programa/PrivacyInfo.xcprivacy b/ios/Programa/PrivacyInfo.xcprivacy new file mode 100644 index 00000000..79bc9e28 --- /dev/null +++ b/ios/Programa/PrivacyInfo.xcprivacy @@ -0,0 +1,17 @@ + + + + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + + From 7b91fae2093a18aa90d16b68659931cd3412c49b Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:55:04 -0300 Subject: [PATCH 32/37] Add opt-in read-only agent status publisher for Mesinyer --- GhosttyTabs.xcodeproj/project.pbxproj | 8 + Sources/AppDelegate.swift | 2 + Sources/ScopedAgentStatusPublisher.swift | 95 +++++++++ Sources/ScopedAgentStatusTransport.swift | 247 +++++++++++++++++++++++ Sources/SettingsDarkroomApps.swift | 16 ++ docs/socket-api.md | 16 ++ 6 files changed, 384 insertions(+) create mode 100644 Sources/ScopedAgentStatusPublisher.swift create mode 100644 Sources/ScopedAgentStatusTransport.swift diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index 49b83c85..3bc86821 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -34,6 +34,8 @@ B4C0080B536225405A3FC0CF /* SettingsShortcutsPane.swift in Sources */ = {isa = PBXBuildFile; fileRef = 102A507DEBDABE1023354973 /* SettingsShortcutsPane.swift */; }; 2BDDD1ADF04E4358EF6721FC /* SettingsAutomationPane.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA5806D6D2EFE4538DEF636D /* SettingsAutomationPane.swift */; }; 48BED6C4710B0DA532E5F117 /* SettingsAgentsPane.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4F272647ABD5BD0ACD6B3FC /* SettingsAgentsPane.swift */; }; + A21880000000000000000002 /* ScopedAgentStatusPublisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = A21880000000000000000001 /* ScopedAgentStatusPublisher.swift */; }; + A21880000000000000000004 /* ScopedAgentStatusTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = A21880000000000000000003 /* ScopedAgentStatusTransport.swift */; }; EF2190000000000000000002 /* SettingsDarkroomApps.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF2190000000000000000001 /* SettingsDarkroomApps.swift */; }; 5D951D99DB143A52A1295E7F /* SettingsAppearancePane.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAC531A0F930E986A2FC3C6D /* SettingsAppearancePane.swift */; }; 48B88AF2818FC3A02015CA62 /* SettingsGeneralPanes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54B811D46EBCD241CBC31798 /* SettingsGeneralPanes.swift */; }; @@ -574,6 +576,8 @@ 102A507DEBDABE1023354973 /* SettingsShortcutsPane.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsShortcutsPane.swift; sourceTree = ""; }; AA5806D6D2EFE4538DEF636D /* SettingsAutomationPane.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsAutomationPane.swift; sourceTree = ""; }; F4F272647ABD5BD0ACD6B3FC /* SettingsAgentsPane.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsAgentsPane.swift; sourceTree = ""; }; + A21880000000000000000001 /* ScopedAgentStatusPublisher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScopedAgentStatusPublisher.swift; sourceTree = ""; }; + A21880000000000000000003 /* ScopedAgentStatusTransport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScopedAgentStatusTransport.swift; sourceTree = ""; }; EF2190000000000000000001 /* SettingsDarkroomApps.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsDarkroomApps.swift; sourceTree = ""; }; BAC531A0F930E986A2FC3C6D /* SettingsAppearancePane.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsAppearancePane.swift; sourceTree = ""; }; 54B811D46EBCD241CBC31798 /* SettingsGeneralPanes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsGeneralPanes.swift; sourceTree = ""; }; @@ -1162,6 +1166,8 @@ 102A507DEBDABE1023354973 /* SettingsShortcutsPane.swift */, AA5806D6D2EFE4538DEF636D /* SettingsAutomationPane.swift */, F4F272647ABD5BD0ACD6B3FC /* SettingsAgentsPane.swift */, + A21880000000000000000001 /* ScopedAgentStatusPublisher.swift */, + A21880000000000000000003 /* ScopedAgentStatusTransport.swift */, EF2190000000000000000001 /* SettingsDarkroomApps.swift */, BAC531A0F930E986A2FC3C6D /* SettingsAppearancePane.swift */, 54B811D46EBCD241CBC31798 /* SettingsGeneralPanes.swift */, @@ -1835,6 +1841,8 @@ B4C0080B536225405A3FC0CF /* SettingsShortcutsPane.swift in Sources */, 2BDDD1ADF04E4358EF6721FC /* SettingsAutomationPane.swift in Sources */, 48BED6C4710B0DA532E5F117 /* SettingsAgentsPane.swift in Sources */, + A21880000000000000000002 /* ScopedAgentStatusPublisher.swift in Sources */, + A21880000000000000000004 /* ScopedAgentStatusTransport.swift in Sources */, EF2190000000000000000002 /* SettingsDarkroomApps.swift in Sources */, 5D951D99DB143A52A1295E7F /* SettingsAppearancePane.swift in Sources */, 48B88AF2818FC3A02015CA62 /* SettingsGeneralPanes.swift in Sources */, diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 20d0a9be..7e6c1f4b 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -450,6 +450,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, @preconcurrency UNUser let env = ProcessInfo.processInfo.environment let isRunningUnderXCTest = isRunningUnderXCTest(env) Self.removeLegacyPersistedWindowGeometry() + if !isRunningUnderXCTest { ScopedAgentStatusPublisher.shared.applyPreference() } AgentInterruptionTracker.install() PaneLaunchdSpawner.sweepStaleJobs() @@ -670,6 +671,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, @preconcurrency UNUser } func applicationWillTerminate(_ notification: Notification) { + ScopedAgentStatusPublisher.shared.stop() appLifecycleCoordinator.willTerminate() finalizeStagedTerminalClosesThenMarkTerminating() saveSessionSnapshot(includeScrollback: true, removeWhenEmpty: false, cleanShutdown: true) diff --git a/Sources/ScopedAgentStatusPublisher.swift b/Sources/ScopedAgentStatusPublisher.swift new file mode 100644 index 00000000..9fc6cb2b --- /dev/null +++ b/Sources/ScopedAgentStatusPublisher.swift @@ -0,0 +1,95 @@ +import Foundation + +enum ScopedAgentStatusSnapshot { + static let maximumAgents = 256 + static let maximumLineBytes = 64 * 1024 + + private struct Agent: Encodable { + let workspaceID: UUID + let surfaceID: UUID + let state: AgentActivityState + + enum CodingKeys: String, CodingKey { + case workspaceID = "workspace_id" + case surfaceID = "surface_id" + case state + } + } + + private struct Snapshot: Encodable { + let contract = 1 + let agents: [Agent] + } + + /// Only IDs and the typed state are accepted as input. Output, paths, prompts, + /// agent metadata, and workspace names never enter this encoder. + static func encode(_ workspaces: some Sequence<(UUID, [UUID: AgentActivityState])>) -> Data? { + var agents: [Agent] = [] + var workspaceIDs: Set = [] + for (workspaceID, states) in workspaces { + guard workspaceIDs.insert(workspaceID).inserted, + states.count <= maximumAgents - agents.count else { return nil } + agents.append(contentsOf: states.map { + Agent(workspaceID: workspaceID, surfaceID: $0.key, state: $0.value) + }) + } + agents.sort { + ($0.workspaceID.uuidString, $0.surfaceID.uuidString) < + ($1.workspaceID.uuidString, $1.surfaceID.uuidString) + } + let encoder = JSONEncoder() + encoder.outputFormatting = .sortedKeys + guard var data = try? encoder.encode(Snapshot(agents: agents)), + data.count < maximumLineBytes else { return nil } + data.append(0x0a) + return data + } +} + +@MainActor +final class ScopedAgentStatusPublisher { + static let shared = ScopedAgentStatusPublisher() + nonisolated static let preferenceKey = "shareAgentStatusWithMesinyer" + nonisolated static var available: Bool { Bundle.main.bundleIdentifier == "com.darkroom.programa" } + + private var transport: ScopedAgentStatusTransport? + private var publication: Task? + + func applyPreference() { + guard Self.available, UserDefaults.standard.bool(forKey: Self.preferenceKey) else { + stop() + return + } + guard transport == nil else { return } + + let transport = ScopedAgentStatusTransport(authenticate: ScopedAgentStatusTransport.authenticateMesinyer) + self.transport = transport + publication = Task { + while !Task.isCancelled { + if await transport.hasSubscribers(), !Task.isCancelled { + await transport.publish(Self.snapshot()) + } + do { + try await Task.sleep(for: .milliseconds(500)) + } catch { + return + } + } + } + } + + func stop() { + transport?.revoke() + publication?.cancel() + transport = nil + publication = nil + } + + private static func snapshot() -> Data? { + guard let app = AppDelegate.shared else { return nil } + let workspaces = app.listMainWindowSummaries().lazy + .compactMap { app.tabManagerFor(windowId: $0.windowId) } + .flatMap(\.tabs) + return ScopedAgentStatusSnapshot.encode(workspaces.map { ($0.id, $0.panelAgentStates) }) + } +} diff --git a/Sources/ScopedAgentStatusTransport.swift b/Sources/ScopedAgentStatusTransport.swift new file mode 100644 index 00000000..a2fe3297 --- /dev/null +++ b/Sources/ScopedAgentStatusTransport.swift @@ -0,0 +1,247 @@ +import Darwin +import Foundation +import Security + +/// One-way, connection-scoped publisher. All descriptor ownership lives on the private queue. +final class ScopedAgentStatusTransport: @unchecked Sendable { + private static let clientLimit = 2 + private typealias SocketIdentity = (device: dev_t, inode: ino_t) + + private let uid = geteuid() + private let directory: String + private var path: String { directory + "/status.sock" } + private let queue = DispatchQueue(label: "programa.scoped-agent-status", qos: .utility) + // Revocation must take effect even while the queue is verifying a new peer. + private let authorization = NSLock() + private var revoked = false + private var authorizedDescriptors: Set = [] + + private let authenticate: @Sendable (Int32, uid_t) -> Bool + private var listener: Int32 = -1 + private var lockFile: Int32 = -1 + private var socketIdentity: SocketIdentity? + private var clients: [Int32: Client] = [:] + + private struct Client { + var lastSnapshot: Data? + } + + init(directory: String? = nil, authenticate: @escaping @Sendable (Int32, uid_t) -> Bool) { + self.directory = directory ?? "/tmp/programa-agent-status-v1-\(geteuid())" + self.authenticate = authenticate + } + + /// Check for new peers and retire peers that disconnected or sent any bytes. + func hasSubscribers() async -> Bool { + await withCheckedContinuation { completion in + queue.async { + guard self.isAuthorized, self.ensureListening() else { + completion.resume(returning: false) + return + } + self.removeInactiveClients() + self.acceptClients() + completion.resume(returning: !self.clients.isEmpty) + } + } + } + + func publish(_ snapshot: Data?) async { + await withCheckedContinuation { (completion: CheckedContinuation) in + queue.async { + defer { completion.resume() } + guard let snapshot, self.isAuthorized else { + self.closeClients() + return + } + self.removeInactiveClients() + for descriptor in Array(self.clients.keys) { + guard self.clients[descriptor]?.lastSnapshot != snapshot else { continue } + let sent = self.authorization.withLock { + guard !self.revoked else { return false } + return snapshot.withUnsafeBytes { bytes in + send(descriptor, bytes.baseAddress, bytes.count, 0) == bytes.count + } + } + // Partial or would-block writes cannot leave a usable stale snapshot stream. + if sent { + self.clients[descriptor]?.lastSnapshot = snapshot + } else { + self.closeClient(descriptor) + } + } + } + } + } + + func revoke() { + authorization.withLock { + revoked = true + for descriptor in authorizedDescriptors { shutdown(descriptor, SHUT_RDWR) } + } + queue.async { self.stop() } + } + + private var isAuthorized: Bool { authorization.withLock { !revoked } } + + private func ensureListening() -> Bool { + if listener >= 0 { return true } + guard mkdir(directory, mode_t(0o700)) == 0 || errno == EEXIST else { return false } + let directoryFD = open(directory, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) + guard directoryFD >= 0 else { return false } + defer { close(directoryFD) } + var entry = stat() + guard fstat(directoryFD, &entry) == 0, entry.st_uid == uid, Self.mode(entry) == 0o700 else { + return false + } + + // Keep this lock file between runs. Unlinking a locked file would permit another + // Programa process to acquire a lock on a different inode at the same pathname. + let lockFD = openat(directoryFD, "listener.lock", O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK, 0o600) + guard lockFD >= 0 else { return false } + var retainLock = false + defer { if !retainLock { close(lockFD) } } + guard fstat(lockFD, &entry) == 0, Self.kind(entry) == S_IFREG, + entry.st_uid == uid, Self.mode(entry) == 0o600, entry.st_nlink == 1, + flock(lockFD, LOCK_EX | LOCK_NB) == 0 else { return false } + + // Only replace an owner-controlled socket under the process lock. Recover even + // if the last process crashed after bind but before setting the socket mode. + if fstatat(directoryFD, "status.sock", &entry, AT_SYMLINK_NOFOLLOW) == 0 { + guard Self.kind(entry) == S_IFSOCK, entry.st_uid == uid, + unlinkat(directoryFD, "status.sock", 0) == 0 else { return false } + } else if errno != ENOENT { + return false + } + + let descriptor = socket(AF_UNIX, SOCK_STREAM, 0) + guard descriptor >= 0 else { return false } + var retainListener = false + defer { if !retainListener { close(descriptor) } } + guard Self.prepare(descriptor), bindListener(descriptor) else { return false } + guard fstatat(directoryFD, "status.sock", &entry, AT_SYMLINK_NOFOLLOW) == 0, + Self.kind(entry) == S_IFSOCK, entry.st_uid == uid else { return false } + let identity: SocketIdentity = (entry.st_dev, entry.st_ino) + guard fchmodat(directoryFD, "status.sock", 0o600, AT_SYMLINK_NOFOLLOW) == 0, + listen(descriptor, Int32(Self.clientLimit)) == 0 else { + Self.unlinkSocket(path, identifiedBy: identity, ownedBy: uid) + return false + } + socketIdentity = identity + listener = descriptor + lockFile = lockFD + retainLock = true + retainListener = true + return true + } + + private func bindListener(_ descriptor: Int32) -> Bool { + var address = sockaddr_un() + let bytes = Array(path.utf8CString) + guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else { return false } + address.sun_family = sa_family_t(AF_UNIX) + address.sun_len = UInt8(MemoryLayout.size) + withUnsafeMutableBytes(of: &address.sun_path) { destination in + bytes.withUnsafeBytes { destination.copyBytes(from: $0) } + } + return withUnsafePointer(to: &address) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + Darwin.bind(descriptor, $0, socklen_t(MemoryLayout.size)) == 0 + } + } + } + + private func acceptClients() { + // Bound work per pass even if untrusted local callers are flooding the backlog. + for _ in 0..= 0 else { return } + guard clients.count < Self.clientLimit, Self.prepare(descriptor), + isAuthorized, authenticate(descriptor, uid), register(descriptor) else { + close(descriptor) + continue + } + clients[descriptor] = Client() + } + } + + private func register(_ descriptor: Int32) -> Bool { + authorization.withLock { + guard !revoked else { return false } + authorizedDescriptors.insert(descriptor) + return true + } + } + + private func removeInactiveClients() { + for descriptor in Array(clients.keys) { + var entry = pollfd(fd: descriptor, events: Int16(POLLIN), revents: 0) + // POLLIN includes a half-close. Never read or interpret an inbound byte. + if poll(&entry, 1, 0) > 0 { closeClient(descriptor) } + } + } + + private func closeClient(_ descriptor: Int32) { + clients.removeValue(forKey: descriptor) + authorization.withLock { + authorizedDescriptors.remove(descriptor) + shutdown(descriptor, SHUT_RDWR) + close(descriptor) + } + } + + private func closeClients() { + for descriptor in Array(clients.keys) { closeClient(descriptor) } + } + + private func stop() { + closeClients() + guard listener >= 0 else { return } + close(listener) + if let socketIdentity { Self.unlinkSocket(path, identifiedBy: socketIdentity, ownedBy: uid) } + close(lockFile) + listener = -1 + lockFile = -1 + socketIdentity = nil + } + + private static func unlinkSocket(_ path: String, identifiedBy identity: SocketIdentity, ownedBy uid: uid_t) { + var entry = stat() + if lstat(path, &entry) == 0, kind(entry) == S_IFSOCK, + entry.st_uid == uid, entry.st_dev == identity.device, entry.st_ino == identity.inode { + unlink(path) + } + } + + private static func mode(_ entry: stat) -> mode_t { entry.st_mode & 0o7777 } + private static func kind(_ entry: stat) -> mode_t { entry.st_mode & S_IFMT } + + private static func prepare(_ descriptor: Int32) -> Bool { + let flags = fcntl(descriptor, F_GETFL) + var enabled: Int32 = 1 + return flags >= 0 && fcntl(descriptor, F_SETFL, flags | O_NONBLOCK) == 0 + && fcntl(descriptor, F_SETFD, FD_CLOEXEC) == 0 + && setsockopt(descriptor, SOL_SOCKET, SO_NOSIGPIPE, &enabled, socklen_t(MemoryLayout.size)) == 0 + } + + static let authenticateMesinyer: @Sendable (Int32, uid_t) -> Bool = { descriptor, expectedUID in + var uid: uid_t = 0 + var gid: gid_t = 0 + guard getpeereid(descriptor, &uid, &gid) == 0, uid == expectedUID else { return false } + let tokenSize = MemoryLayout.size + var token = audit_token_t() + var length = socklen_t(tokenSize) + guard getsockopt(descriptor, SOL_LOCAL, LOCAL_PEERTOKEN, &token, &length) == 0, + length == socklen_t(tokenSize) else { return false } + let audit = withUnsafeBytes(of: token) { Data($0) } + let attributes = [kSecGuestAttributeAudit as String: audit] as CFDictionary + let flags = SecCSFlags(rawValue: 0) + var code: SecCode? + var requirement: SecRequirement? + let rule = #"anchor apple generic and certificate leaf[subject.OU] = "ZNHHMX2RP6" and identifier "engineering.darkroom.mesinyer""# + guard SecCodeCopyGuestWithAttributes(nil, attributes, flags, &code) == errSecSuccess, + SecRequirementCreateWithString(rule as CFString, flags, &requirement) == errSecSuccess, + let code, let requirement else { return false } + return SecCodeCheckValidity(code, flags, requirement) == errSecSuccess + } +} diff --git a/Sources/SettingsDarkroomApps.swift b/Sources/SettingsDarkroomApps.swift index d6293ea9..fd1168dc 100644 --- a/Sources/SettingsDarkroomApps.swift +++ b/Sources/SettingsDarkroomApps.swift @@ -2,6 +2,7 @@ import AppKit import SwiftUI struct SettingsDarkroomApps: View { + @AppStorage(ScopedAgentStatusPublisher.preferenceKey) private var shareAgentStatus = false @State private var statuses: [DarkroomPeer: DarkroomPeer.Status] = [:] @State private var openErrors: [DarkroomPeer: String] = [:] @State private var refreshing = false @@ -11,6 +12,21 @@ struct SettingsDarkroomApps: View { ForEach(DarkroomPeer.allCases, id: \.self) { peer in appRow(peer, status: statuses[peer]) } + if ScopedAgentStatusPublisher.available { + Toggle( + String(localized: "settings.apps.mesinyer.shareAgentStatus", defaultValue: "Share Programa agent status with Mesinyer"), + isOn: $shareAgentStatus + ) + .onChange(of: shareAgentStatus) { _, _ in + ScopedAgentStatusPublisher.shared.applyPreference() + } + Text(String( + localized: "settings.apps.mesinyer.shareAgentStatus.description", + defaultValue: "Lets Mesinyer see whether agents in your Programa workspaces are working, blocked, or idle." + )) + .font(.subheadline) + .foregroundStyle(.secondary) + } HStack(spacing: 10) { Button(String(localized: "settings.apps.refresh", defaultValue: "Refresh")) { Task { await refresh(announce: true) } diff --git a/docs/socket-api.md b/docs/socket-api.md index a2c4bafb..f8df7837 100644 --- a/docs/socket-api.md +++ b/docs/socket-api.md @@ -54,6 +54,22 @@ Rules that follow from the diagram: ## Security and discovery +### Mesinyer agent status + +**Share Programa agent status with Mesinyer** in **Settings → Integrations → Darkroom Apps** +is off by default. It opens a separate owner-only socket at +`/tmp/programa-agent-status-v1-/status.sock` (directory mode `0700`, socket +mode `0600`). Admission requires the same effective user and a running Mesinyer process +signed by the Darkroom team with identifier `engineering.darkroom.mesinyer`. Turning off +sharing closes active subscriptions. + +The server sends newline-delimited JSON. Each frame replaces the previous snapshot. It +contains `contract: 1` and an `agents` array of records with just `workspace_id`, +`surface_id`, and `state` (`working`, `blocked`, or `idle`). The server sends a snapshot on +connect and after changes. More than 256 agents or a frame over 64 KiB closes the +connection without sending a partial snapshot. Client input closes the connection. +This stream has no RPC dispatch and requires no change to the control socket settings. + ### Socket modes The mode is `automation.socketControlMode` in `settings.json` or **Settings > Automation**. From bcc7e2a9872ed73c506089a37028022bd58389c7 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:55:04 -0300 Subject: [PATCH 33/37] Cover scoped agent status projection and revocation --- GhosttyTabs.xcodeproj/project.pbxproj | 4 + programaTests/ScopedAgentStatusTests.swift | 155 +++++++++++++++++++++ 2 files changed, 159 insertions(+) create mode 100644 programaTests/ScopedAgentStatusTests.swift diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index 3bc86821..105eb2b7 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -451,6 +451,7 @@ C7A3000003 /* AgentEventNormalizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A3000004 /* AgentEventNormalizerTests.swift */; }; 0F2C25F9170130F8DC09DD1B /* WorkspaceManualUnreadTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D301919B10F22B8708E8883 /* WorkspaceManualUnreadTests.swift */; }; CA39C0304FE351A21C372429 /* SidebarWidthPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE0171AF1F49F7547191CEE5 /* SidebarWidthPolicyTests.swift */; }; + A21880000000000000000006 /* ScopedAgentStatusTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A21880000000000000000005 /* ScopedAgentStatusTests.swift */; }; 8C4BBF2DEF6DF93F395A9EE7 /* TerminalControllerSocketSecurityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 491751CE2321474474F27DCF /* TerminalControllerSocketSecurityTests.swift */; }; PRTS000002 /* PortScannerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = PRTS000001 /* PortScannerTests.swift */; }; 7B3F9A10C2D4E5F6A7B8000C /* PortsHubTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B3F9A10C2D4E5F6A7B8000B /* PortsHubTests.swift */; }; @@ -981,6 +982,7 @@ C7A3000004 /* AgentEventNormalizerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentEventNormalizerTests.swift; sourceTree = ""; }; 1D301919B10F22B8708E8883 /* WorkspaceManualUnreadTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceManualUnreadTests.swift; sourceTree = ""; }; EE0171AF1F49F7547191CEE5 /* SidebarWidthPolicyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarWidthPolicyTests.swift; sourceTree = ""; }; + A21880000000000000000005 /* ScopedAgentStatusTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScopedAgentStatusTests.swift; sourceTree = ""; }; 491751CE2321474474F27DCF /* TerminalControllerSocketSecurityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalControllerSocketSecurityTests.swift; sourceTree = ""; }; PRTS000001 /* PortScannerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PortScannerTests.swift; sourceTree = ""; }; 7B3F9A10C2D4E5F6A7B8000B /* PortsHubTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PortsHubTests.swift; sourceTree = ""; }; @@ -1627,6 +1629,7 @@ PUW0000004 /* ProviderUsageWarningTests.swift */, 1D301919B10F22B8708E8883 /* WorkspaceManualUnreadTests.swift */, EE0171AF1F49F7547191CEE5 /* SidebarWidthPolicyTests.swift */, + A21880000000000000000005 /* ScopedAgentStatusTests.swift */, 491751CE2321474474F27DCF /* TerminalControllerSocketSecurityTests.swift */, PRTS000001 /* PortScannerTests.swift */, 7B3F9A10C2D4E5F6A7B8000B /* PortsHubTests.swift */, @@ -2183,6 +2186,7 @@ PUW0000003 /* ProviderUsageWarningTests.swift in Sources */, 0F2C25F9170130F8DC09DD1B /* WorkspaceManualUnreadTests.swift in Sources */, CA39C0304FE351A21C372429 /* SidebarWidthPolicyTests.swift in Sources */, + A21880000000000000000006 /* ScopedAgentStatusTests.swift in Sources */, 8C4BBF2DEF6DF93F395A9EE7 /* TerminalControllerSocketSecurityTests.swift in Sources */, PRTS000002 /* PortScannerTests.swift in Sources */, 7B3F9A10C2D4E5F6A7B8000C /* PortsHubTests.swift in Sources */, diff --git a/programaTests/ScopedAgentStatusTests.swift b/programaTests/ScopedAgentStatusTests.swift new file mode 100644 index 00000000..d48be5c5 --- /dev/null +++ b/programaTests/ScopedAgentStatusTests.swift @@ -0,0 +1,155 @@ +import Darwin +import Foundation +import XCTest +#if canImport(Programa_DEV) +@testable import Programa_DEV +#elseif canImport(Programa) +@testable import Programa +#endif + +final class ScopedAgentStatusTests: XCTestCase { + func testSnapshotProjectsOnlyTypedStateAndSortsDeterministically() throws { + let first = try XCTUnwrap(UUID(uuidString: "00000000-0000-0000-0000-000000000001")) + let second = try XCTUnwrap(UUID(uuidString: "00000000-0000-0000-0000-000000000002")) + let workspaces: [(UUID, [UUID: AgentActivityState])] = [ + (second, [first: .idle]), + (first, [second: .working, first: .blocked]), + ] + + let frame = try XCTUnwrap(ScopedAgentStatusSnapshot.encode(workspaces)) + XCTAssertEqual(frame, ScopedAgentStatusSnapshot.encode(workspaces.reversed())) + XCTAssertEqual(frame.last, 0x0a) + let payload = try XCTUnwrap(JSONSerialization.jsonObject(with: frame) as? [String: Any]) + XCTAssertEqual(Set(payload.keys), ["contract", "agents"]) + XCTAssertEqual(payload["contract"] as? Int, 1) + let agents = try XCTUnwrap(payload["agents"] as? [[String: String]]) + XCTAssertEqual(agents, [ + ["workspace_id": first.uuidString, "surface_id": first.uuidString, "state": "blocked"], + ["workspace_id": first.uuidString, "surface_id": second.uuidString, "state": "working"], + ["workspace_id": second.uuidString, "surface_id": first.uuidString, "state": "idle"], + ]) + } + + func testSnapshotDoesNotReportPartialOrDuplicateState() throws { + let workspace = UUID() + var agents: [UUID: AgentActivityState] = [:] + for _ in 0.. String { + "/tmp/programa-status-test-\(UUID().uuidString)" + } + + private func assertMode(_ mode: mode_t, at path: String) { + var entry = stat() + XCTAssertEqual(lstat(path, &entry), 0) + XCTAssertEqual(entry.st_uid, geteuid()) + XCTAssertEqual(entry.st_mode & 0o7777, mode) + } + + private func connect(at directory: String) throws -> Int32 { + let descriptor = socket(AF_UNIX, SOCK_STREAM, 0) + guard descriptor >= 0 else { throw POSIXError(.ECONNREFUSED) } + var address = sockaddr_un() + address.sun_family = sa_family_t(AF_UNIX) + address.sun_len = UInt8(MemoryLayout.size) + let bytes = Array((directory + "/status.sock").utf8CString) + withUnsafeMutableBytes(of: &address.sun_path) { destination in + bytes.withUnsafeBytes { destination.copyBytes(from: $0) } + } + let result = withUnsafePointer(to: &address) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + Darwin.connect(descriptor, $0, socklen_t(MemoryLayout.size)) + } + } + guard result == 0 else { + let failure = errno + close(descriptor) + throw POSIXError(POSIXErrorCode(rawValue: failure) ?? .ECONNREFUSED) + } + return descriptor + } + + private func receive(_ expected: Data, from descriptor: Int32) throws { + var bytes = [UInt8](repeating: 0, count: expected.count) + var received = Data() + while received.count < expected.count { + try waitForInput(descriptor) + let count = recv(descriptor, &bytes, expected.count - received.count, 0) + guard count > 0 else { throw POSIXError(.ECONNRESET) } + received.append(contentsOf: bytes.prefix(count)) + } + XCTAssertEqual(received, expected) + } + + private func assertClosed(_ descriptor: Int32) throws { + try waitForInput(descriptor) + var byte: UInt8 = 0 + let count = recv(descriptor, &byte, 1, 0) + XCTAssertTrue(count == 0 || (count == -1 && errno == ECONNRESET)) + } + + private func waitForInput(_ descriptor: Int32) throws { + var entry = pollfd(fd: descriptor, events: Int16(POLLIN), revents: 0) + guard poll(&entry, 1, 1_000) > 0 else { throw POSIXError(.ETIMEDOUT) } + } +} From 4075cd2bde405734213f5f0d9adc3cb461afec0c Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 13:00:28 -0300 Subject: [PATCH 34/37] Match both signed Mesinyer identifiers for agent status --- Sources/ScopedAgentStatusTransport.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/ScopedAgentStatusTransport.swift b/Sources/ScopedAgentStatusTransport.swift index a2fe3297..f85cf4f5 100644 --- a/Sources/ScopedAgentStatusTransport.swift +++ b/Sources/ScopedAgentStatusTransport.swift @@ -238,7 +238,7 @@ final class ScopedAgentStatusTransport: @unchecked Sendable { let flags = SecCSFlags(rawValue: 0) var code: SecCode? var requirement: SecRequirement? - let rule = #"anchor apple generic and certificate leaf[subject.OU] = "ZNHHMX2RP6" and identifier "engineering.darkroom.mesinyer""# + let rule = #"anchor apple generic and certificate leaf[subject.OU] = "ZNHHMX2RP6" and identifier "engineering.darkroom.mesinyer" and info[CFBundleIdentifier] = "engineering.darkroom.mesinyer""# guard SecCodeCopyGuestWithAttributes(nil, attributes, flags, &code) == errSecSuccess, SecRequirementCreateWithString(rule as CFString, flags, &requirement) == errSecSuccess, let code, let requirement else { return false } From f804d26cc894244b1b9ff1249e9412e27dc391af Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 15:15:14 -0300 Subject: [PATCH 35/37] Discover signed NoteTaker installations without granting access --- CLI/CLI+AppLinkAgents.swift | 1 + CLI/CLI+Apps.swift | 2 +- Sources/DarkroomAppDiscovery.swift | 34 ++++++++++++++++++++++++--- Sources/SettingsDarkroomApps.swift | 4 +++- contracts/link/v1/README.md | 1 + contracts/link/v1/apps.json | 6 +++++ tests/test_cli_browsee_integration.py | 13 +++++++++- 7 files changed, 55 insertions(+), 6 deletions(-) diff --git a/CLI/CLI+AppLinkAgents.swift b/CLI/CLI+AppLinkAgents.swift index d72ad901..8db8d7d1 100644 --- a/CLI/CLI+AppLinkAgents.swift +++ b/CLI/CLI+AppLinkAgents.swift @@ -7,6 +7,7 @@ extension ProgramaCLI { let executable = resolvedExecutableURL()?.path else { return } let session = "programa-\(surface.uuidString)" let peers = DarkroomPeer.allCases.filter { peer in + guard peer.supportsAgentMCP else { return false } if peer == .browsee { return browseeInstallation() != nil } guard let install = peer.installation() else { return false } return install.entryPoint != nil && install.advertisesStatus diff --git a/CLI/CLI+Apps.swift b/CLI/CLI+Apps.swift index c00779e1..22d3e978 100644 --- a/CLI/CLI+Apps.swift +++ b/CLI/CLI+Apps.swift @@ -77,7 +77,7 @@ extension ProgramaCLI { try printAppLinkAgentConfig(for: arguments[1]) case "mcp": guard arguments.count == 4, arguments[2] == "--session", - let peer = DarkroomPeer(rawValue: arguments[1]), + let peer = DarkroomPeer(rawValue: arguments[1]), peer.supportsAgentMCP, arguments[3].hasPrefix("programa-"), UUID(uuidString: String(arguments[3].dropFirst(9))) != nil else { throw CLIError(message: "Usage: programa apps mcp --session programa-") } diff --git a/Sources/DarkroomAppDiscovery.swift b/Sources/DarkroomAppDiscovery.swift index 25b32da2..c00a31dd 100644 --- a/Sources/DarkroomAppDiscovery.swift +++ b/Sources/DarkroomAppDiscovery.swift @@ -6,11 +6,23 @@ import Security enum DarkroomPeer: String, CaseIterable, Sendable { case browsee case mesinyer + case notetaker + + var title: String { + switch self { + case .browsee: return "Browsee" + case .mesinyer: return "Mesinyer" + case .notetaker: return "NoteTaker" + } + } + + var supportsAgentMCP: Bool { self != .notetaker } var bundleID: String { switch self { case .browsee: return "com.darkroom.browsee" case .mesinyer: return "engineering.darkroom.mesinyer" + case .notetaker: return "engineering.darkroom.NoteTaker" } } @@ -20,6 +32,8 @@ enum DarkroomPeer: String, CaseIterable, Sendable { return ["Contents/Helpers/browsee-mcp", "Contents/MacOS/browsee-mcp"].map { ($0, "browsee-mcp") } case .mesinyer: return [("Contents/MacOS/Mesinyer", bundleID)] + case .notetaker: + return [("Contents/MacOS/notetaker-mcp", "notetaker-mcp")] } } @@ -43,7 +57,7 @@ enum DarkroomPeer: String, CaseIterable, Sendable { let workspace = NSWorkspace.shared let preferred = workspace.urlForApplication(withBundleIdentifier: bundleID) let alternatives = workspace.urlsForApplications(withBundleIdentifier: bundleID) - let name = self == .browsee ? "browsee.app" : "Mesinyer.app" + let name = self == .browsee ? "browsee.app" : "\(title).app" let standard = [ URL(fileURLWithPath: "/Applications", isDirectory: true), FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Applications", isDirectory: true) @@ -109,6 +123,7 @@ enum DarkroomPeer: String, CaseIterable, Sendable { } enum State: String, Codable, Sendable { + case available case ready case notRunning = "not_running" case denied @@ -152,8 +167,7 @@ enum DarkroomPeer: String, CaseIterable, Sendable { return result } guard let identity = try? JSONDecoder().decode(Identity.self, from: data), - identity.contract == 1, identity.app == rawValue, identity.bundleID == bundleID, - let state = State(rawValue: identity.state), state != .notInstalled, state != .unavailable else { + let state = validatedState(for: identity, installedVersion: install.version) else { return result } if self == .browsee, state == .ready || state == .disabled, @@ -172,6 +186,20 @@ enum DarkroomPeer: String, CaseIterable, Sendable { return result } + func validatedState(for identity: Identity, installedVersion: String) -> State? { + guard identity.contract == 1, identity.app == rawValue, identity.bundleID == bundleID, + let state = State(rawValue: identity.state), state != .notInstalled, state != .unavailable else { + return nil + } + if self == .notetaker { + guard !installedVersion.isEmpty, identity.version == installedVersion, + state == .available, identity.capabilities.isEmpty else { return nil } + } else if state == .available { + return nil + } + return state + } + static func readCommand(_ helper: URL, arguments: [String], byteLimit: Int = 16_384) -> Data? { let process = Process() let pipe = Pipe() diff --git a/Sources/SettingsDarkroomApps.swift b/Sources/SettingsDarkroomApps.swift index fd1168dc..cdf6793a 100644 --- a/Sources/SettingsDarkroomApps.swift +++ b/Sources/SettingsDarkroomApps.swift @@ -47,7 +47,7 @@ struct SettingsDarkroomApps: View { @ViewBuilder private func appRow(_ peer: DarkroomPeer, status: DarkroomPeer.Status?) -> some View { - let title = peer == .browsee ? "Browsee" : "Mesinyer" + let title = peer.title let detail = status.map { [presence($0), access($0)] } ?? [ String(localized: "settings.apps.checking", defaultValue: "Checking availability…") ] @@ -145,6 +145,8 @@ struct SettingsDarkroomApps: View { return String(localized: "settings.apps.browsee.reviewAccess", defaultValue: "In Browsee Settings, open Access and review “Let other apps control my tabs”.") case .mesinyer: return String(localized: "settings.apps.mesinyer.reviewAccess", defaultValue: "In Mesinyer, open Settings → AI Tools and review access for the workspace.") + case .notetaker: + return nil } default: return nil diff --git a/contracts/link/v1/README.md b/contracts/link/v1/README.md index 474ea08b..f92f4f0d 100644 --- a/contracts/link/v1/README.md +++ b/contracts/link/v1/README.md @@ -8,6 +8,7 @@ Invoke the status entry point with `--app-link-status`, closed stdin and a bound | State | Meaning | | --- | --- | +| `available` | NoteTaker confirms its build identity and contract version. Clients use the operating system for process state and leave access unknown. Capabilities are empty. | | `ready` | The app's existing access policy allows this integration and the advertised capability is available. | | `not_running` | A necessary local process or endpoint is unavailable. | | `denied` | A policy check rejected this caller. | diff --git a/contracts/link/v1/apps.json b/contracts/link/v1/apps.json index 152e9220..e5042b4a 100644 --- a/contracts/link/v1/apps.json +++ b/contracts/link/v1/apps.json @@ -21,6 +21,12 @@ "bundle_id": "engineering.darkroom.mesinyer", "status_entry_points": ["Contents/MacOS/Mesinyer"], "mcp_entry_points": ["Contents/MacOS/Mesinyer"] + }, + { + "app": "notetaker", + "bundle_id": "engineering.darkroom.NoteTaker", + "status_entry_points": ["Contents/MacOS/notetaker-mcp"], + "mcp_entry_points": [] } ] } diff --git a/tests/test_cli_browsee_integration.py b/tests/test_cli_browsee_integration.py index 07d5013d..4a8e5477 100644 --- a/tests/test_cli_browsee_integration.py +++ b/tests/test_cli_browsee_integration.py @@ -348,14 +348,25 @@ def test_discovery_status_is_json_and_does_not_launch_or_register_apps(self) -> self.assertOK(proc) report = json.loads(proc.stdout) self.assertEqual(report["contract"], 1) - self.assertEqual([app["app"] for app in report["apps"]], ["browsee", "mesinyer"]) + self.assertEqual([app["app"] for app in report["apps"]], ["browsee", "mesinyer", "notetaker"]) for app in report["apps"]: self.assertIsInstance(app["present"], bool) self.assertIsInstance(app["running"], bool) self.assertIn(app["access"], {"unknown", "allowed", "denied", "disabled"}) + notetaker = report["apps"][2] + self.assertEqual(notetaker["bundle_id"], "engineering.darkroom.NoteTaker") + self.assertEqual(notetaker["access"], "unknown") + self.assertEqual(notetaker["capabilities"], []) self.assertEqual(box.log("open.log"), []) self.assertEqual(box.calls("claude") + box.calls("codex"), []) + def test_notetaker_identity_has_no_agent_mcp_route(self) -> None: + box = self.sandbox() + proc = box.run("mcp", "notetaker", "--session", f"programa-{SURFACE_ID}", command="apps") + self.assertNotEqual(proc.returncode, 0) + self.assertIn("Usage: programa apps mcp ", proc.stderr) + self.assertEqual(box.log("open.log"), []) + def test_agent_configs_keep_owned_browser_surface_and_preserve_custom_servers(self) -> None: box = self.sandbox() args = ["apps", "mcp", "browsee", "--session", f"programa-{SURFACE_ID}"] From 75183f4250bdf99b9338ceaeadb2fcd660c9054a Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 15:56:51 -0300 Subject: [PATCH 36/37] Recognize the NoteTaker Windows installation without granting trust --- contracts/link/v1/windows-apps.json | 10 ++++ contracts/link/v1/windows.md | 15 ++++- .../Programa.Tests/CompanionDiscoveryTests.cs | 30 +++++++++- windows/Programa/CompanionDiscovery.cs | 4 +- windows/Programa/WindowsCompanionPlatform.cs | 55 +++++++++++++++---- 5 files changed, 98 insertions(+), 16 deletions(-) diff --git a/contracts/link/v1/windows-apps.json b/contracts/link/v1/windows-apps.json index b0fae3fb..c8488a6c 100644 --- a/contracts/link/v1/windows-apps.json +++ b/contracts/link/v1/windows-apps.json @@ -19,6 +19,16 @@ "direct_signers": [], "store_packages": [] }, + { + "app": "notetaker", + "title": "NoteTaker", + "direct_install_id": "", + "direct_executable": "NoteTaker.exe", + "direct_product": "NoteTaker", + "direct_signers": [], + "store_packages": [], + "direct_current_user_directory": "NoteTaker" + }, { "app": "programa", "title": "Programa", diff --git a/contracts/link/v1/windows.md b/contracts/link/v1/windows.md index 13671ae1..4b08fd41 100644 --- a/contracts/link/v1/windows.md +++ b/contracts/link/v1/windows.md @@ -1,11 +1,21 @@ # Windows companion discovery -In a Programa terminal, run `programa apps status --json`, or open Settings → Integrations. Browsee and Mesinyer also expose the same inventory for their two peers in Settings → Integrations. Each app excludes itself before probing. Each check resolves the current installation again, including after updates, moves or restarts. The CLI can run while Programa’s main window is closed. +In a Programa terminal, run `programa apps status --json`, or open Settings → Integrations. Browsee and Mesinyer also expose the same inventory for their peers in Settings → Integrations. Each app excludes itself before probing. Each check resolves the current installation again, including after updates, moves or restarts. The CLI can run while Programa’s main window is closed. - Direct installers use their exact Velopack IDs and main executable paths from [windows-apps.json](windows-apps.json). Velopack records the install root under the ID's Windows uninstall key, including custom install directories. Programa reads the root and checks the expected executable under `current`. The registry entry alone provides an unverified installation hint. A verified direct install requires matching signed PE product metadata, Windows Authenticode validation and an enrolled SHA-256 pair containing the validating publisher’s DER subject name and its issuing CA’s DER SubjectPublicKeyInfo. [Velopack 1.2.161 registration source](https://raw.githubusercontent.com/velopack/velopack/1.2.161/src/bins/src/windows/registry.rs) - Store installs require an exact enrolled package family and relative executable path, an active registration for the current Windows user, and Windows' Store signature classification. A running process must match the selected executable and, for a Store package, its full package name. [PackageManager](https://learn.microsoft.com/en-us/uwp/api/windows.management.deployment.packagemanager) · [Package identity APIs](https://learn.microsoft.com/en-us/windows/win32/appxpkg/functions) - A verified running install takes priority over closed installs. With no verified running install, a verified Store registration wins, then the latest verified direct install. An unsigned or unverifiable registration can surface as `identity_unverified`. Programa can also read the running Browsee instance’s outside-access setting. Installation and policy are reported independently. +## NoteTaker installation + +Programa looks for the per-user NSIS installation at `%LOCALAPPDATA%\NoteTaker\NoteTaker.exe`. +The expected layout is an installation hint. With no enrolled Authenticode identity, Programa +reports it as unverified and leaves running status and access unknown. The Windows helper at +`mcp\notetaker-mcp.exe` is not executed by discovery. A future metadata probe requires the signed +launcher and helper to match enrolled identities and the helper's signed App Link protocol marker +before it can check the response against the installed release version. App Link does not grant +recording, transcript, or tool access. + ## Browsee outside access The signed Browsee executable must carry the exact version-resource description `DarkroomAppLinkVersion=1`. Programa connects to the current user’s existing `browsee-mcp-` on the local machine. Before sending bytes, it uses that same pipe handle to identify the server process, verifies the account SID and exact selected executable and package identity, and rechecks the current install and its marker. Installing the app or enabling discovery does not change its access settings. @@ -18,9 +28,10 @@ The request is the exact UTF-8 line `{"browsee_app_link_status":1}` followed by | --- | --- | --- | | Browsee | Velopack `browsee-app`, `current/browsee.exe` | Ships `browsee-mcp.exe` over the existing per-user named pipe. Programa probes Browsee’s existing Windows pipe only after verifying the process. Browsee’s own browser approvals and per-operation policy still govern all agent operations. | | Mesinyer | Velopack `Mesinyer`, `current/Mesinyer.Windows.exe` | No Windows companion readiness endpoint or MCP helper is packaged. | +| NoteTaker | NSIS per user, `%LOCALAPPDATA%\NoteTaker\NoteTaker.exe` | Presence hint pending Authenticode enrollment. | | Programa | Velopack `Programa` and the standalone executable | Ships its own MCP and control pipe. Windows discovery currently checks local installation and process identity only. | -The release sources contain no enrolled production Store package families or direct signing identities for either peer. Populate these from verified release artifacts when those lanes are available. Existing registrations can appear as unverified while enrollment is pending. Signed direct installs, signed Store installs, mixed installations, restart recovery and Settings accessibility still require execution on Windows. +The release sources contain no enrolled production Store package families or direct signing identities for these peers. Populate these from verified release artifacts when those lanes are available. Existing registrations can appear as unverified while enrollment is pending. Signed direct installs, signed Store installs, mixed installations, restart recovery and Settings accessibility still require execution on Windows. ## Sync the native consumers diff --git a/windows/Programa.Tests/CompanionDiscoveryTests.cs b/windows/Programa.Tests/CompanionDiscoveryTests.cs index 4a5cd0f3..d9ab14a4 100644 --- a/windows/Programa.Tests/CompanionDiscoveryTests.cs +++ b/windows/Programa.Tests/CompanionDiscoveryTests.cs @@ -107,16 +107,42 @@ public void ExcludesTheCurrentAppBeforeProbingPeers() foreach (var host in new[] { "browsee", "mesinyer", "programa" }) { var fixture = new Fixture(); - var expected = new[] { "browsee", "mesinyer", "programa" }.Where(app => app != host).ToArray(); + var expected = new[] { "browsee", "mesinyer", "notetaker", "programa" }.Where(app => app != host).ToArray(); var report = Read(fixture, host); CollectionAssert.AreEqual(expected, report.Apps.Select(app => app.App).ToArray()); CollectionAssert.AreEqual(expected, fixture.ProbedApps); } } + [TestMethod] + public void UnenrolledNoteTakerReportsOnlyAnUnverifiedPresenceHint() + { + var platform = new Fixture + { + InstallFor = app => + { + if (app.App != "notetaker") return []; + Assert.AreEqual("NoteTaker", app.DirectCurrentUserDirectory); + Assert.AreEqual("NoteTaker.exe", app.DirectExecutable); + Assert.AreEqual(0, app.DirectSigners.Length); + return [new("direct", @"C:\Users\test\AppData\Local\NoteTaker\NoteTaker.exe", new Version(), false)]; + } + }; + var peer = Read(platform, "programa", FailOnProbe).Apps.Single(app => app.App == "notetaker"); + Assert.IsTrue(peer.Present); + Assert.AreEqual(false, peer.Verified); + Assert.IsNull(peer.Running); + Assert.IsNull(peer.Version); + Assert.AreEqual("identity_unverified", peer.State); + Assert.AreEqual("unknown", peer.Access); + Assert.AreEqual(0, peer.Capabilities.Length); + Assert.AreEqual(0, platform.RunningChecks); + } + private sealed class Fixture : Platform { internal Candidate[] Installs { get; set; } = []; + internal Func? InstallFor { get; init; } internal Candidate? RunningApp { get; set; } internal bool UnknownRunningState { get; set; } internal int RunningChecks { get; private set; } @@ -126,7 +152,7 @@ private sealed class Fixture : Platform public IEnumerable Candidates(Identity app) { ProbedApps.Add(app.App); - return Installs; + return InstallFor?.Invoke(app) ?? Installs; } public bool? Running(Candidate candidate) diff --git a/windows/Programa/CompanionDiscovery.cs b/windows/Programa/CompanionDiscovery.cs index 9d593959..0a23fc24 100644 --- a/windows/Programa/CompanionDiscovery.cs +++ b/windows/Programa/CompanionDiscovery.cs @@ -19,7 +19,8 @@ internal sealed record Identity( string DirectExecutable, string DirectProduct, DirectSigner[] DirectSigners, - StorePackage[] StorePackages); + StorePackage[] StorePackages, + string? DirectCurrentUserDirectory = null); internal sealed record StorePackage(string Family, string Executable); @@ -103,6 +104,7 @@ internal static int Run(string[] args, Func read, TextWriter output, Tex internal static string Describe(Peer app) => app.State switch { "not_installed" => "Not found", + "identity_unverified" when app.App == "notetaker" => "Installation found · Identity unverified", "identity_unverified" => "Registered · Identity unverified", "not_running" => "Installed · Closed", "ready" or "disabled" => "Running", diff --git a/windows/Programa/WindowsCompanionPlatform.cs b/windows/Programa/WindowsCompanionPlatform.cs index f183010c..a099a4a2 100644 --- a/windows/Programa/WindowsCompanionPlatform.cs +++ b/windows/Programa/WindowsCompanionPlatform.cs @@ -34,6 +34,27 @@ internal sealed class WindowsCompanionPlatform : CompanionDiscovery.Platform catch (Exception error) when (error is COMException or UnauthorizedAccessException) { } } + if (app.DirectCurrentUserDirectory is { } directDirectory) + { + // NSIS current-user installs use their configured folder under LocalAppData, + // independently of the Velopack registry roots below. + try + { + var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + var folder = Path.Combine(local, directDirectory); + if (TryGetFixedDirectory(folder) is { } fixedFolder && !IsReparsePoint(local) + && !IsReparsePoint(fixedFolder) + && ExecutableUnder(fixedFolder, app.DirectExecutable) is { } path && !IsReparsePoint(path)) + { + candidates.Add(app.DirectSigners.Length == 0 + ? new("direct", path, new Version(), false) + : DirectCandidate(app, path)); + } + } + catch (Exception error) when (error is IOException or SecurityException or UnauthorizedAccessException or Win32Exception) { } + return candidates; + } + foreach (var hive in new[] { RegistryHive.CurrentUser, RegistryHive.LocalMachine }) foreach (var view in new[] { RegistryView.Registry64, RegistryView.Registry32 }) { @@ -45,17 +66,25 @@ internal sealed class WindowsCompanionPlatform : CompanionDiscovery.Platform continue; var path = ExecutableUnder(folder, "current", app.DirectExecutable); if (path is null) continue; - var info = FileVersionInfo.GetVersionInfo(path); - var version = new Version(info.FileMajorPart, info.FileMinorPart, info.FileBuildPart, info.FilePrivatePart); - var verified = string.Equals(app.DirectProduct, info.ProductName, StringComparison.Ordinal) - && WindowsCompanionTrust.HasPinnedSignature(path, app.DirectSigners); - candidates.Add(new("direct", path, version, verified)); + candidates.Add(DirectCandidate(app, path)); } catch (Exception error) when (error is IOException or SecurityException or UnauthorizedAccessException or Win32Exception) { } } return candidates; } + private static bool IsReparsePoint(string path) => + (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0; + + private static CompanionDiscovery.Candidate DirectCandidate(CompanionDiscovery.Identity identity, string path) + { + var info = FileVersionInfo.GetVersionInfo(path); + var version = new Version(info.FileMajorPart, info.FileMinorPart, info.FileBuildPart, info.FilePrivatePart); + var verified = string.Equals(identity.DirectProduct, info.ProductName, StringComparison.Ordinal) + && WindowsCompanionTrust.HasPinnedSignature(path, identity.DirectSigners); + return new("direct", path, version, verified); + } + public bool? Running(CompanionDiscovery.Candidate candidate) { var unknown = false; @@ -105,18 +134,22 @@ internal sealed class WindowsCompanionPlatform : CompanionDiscovery.Platform // parse display strings, execute an uninstall command or open a remote path. private static string? ExecutableUnder(string directory, params string[] relative) { - if (directory.Length < 3 || directory[1] != ':' || directory[2] is not ('\\' or '/') || - !Path.IsPathFullyQualified(directory)) - return null; - var full = Path.GetFullPath(directory); - var volume = new DriveInfo(Path.GetPathRoot(full)!); - if (volume.DriveType != DriveType.Fixed) return null; + if (TryGetFixedDirectory(directory) is not { } full) return null; var executable = Path.GetFullPath(Path.Combine([full, .. relative])); var prefix = Path.EndsInDirectorySeparator(full) ? full : full + Path.DirectorySeparatorChar; return executable.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && File.Exists(executable) ? executable : null; } + private static string? TryGetFixedDirectory(string directory) + { + if (directory.Length < 3 || directory[1] != ':' || directory[2] is not ('\\' or '/') || + !Path.IsPathFullyQualified(directory)) + return null; + var full = Path.GetFullPath(directory); + return new DriveInfo(Path.GetPathRoot(full)!).DriveType == DriveType.Fixed ? full : null; + } + [DllImport("kernel32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] private static extern int GetPackageFullName(Microsoft.Win32.SafeHandles.SafeProcessHandle process, ref uint length, [Out] char[] packageFullName); } From 903087b990339b7e18dea81b31ffd8bf089048d9 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 16:11:36 -0300 Subject: [PATCH 37/37] Include NoteTaker in Programa Settings search --- Resources/Localizable.xcstrings | 2 +- Sources/SettingsSearchIndex.swift | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 44ed589c..5da7c088 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -4,7 +4,7 @@ "settings.apps.browsee.registrationLabel" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Review Browsee MCP registrations"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Browsee MCP の登録を確認"}}}}, "settings.apps.browsee.registration" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Review registration…"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "登録を確認…"}}}}, "settings.apps.heading" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Darkroom Apps"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Darkroom アプリ"}}}}, - "settings.apps.help" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Check whether Browsee and Mesinyer are installed and available."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "Browsee と Mesinyer がインストールされ、利用できるかを確認します。"}}}}, + "settings.apps.help" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Check which Darkroom apps are installed and available."}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "どの Darkroom アプリがインストールされ、利用可能かを確認します。"}}}}, "settings.apps.refresh" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Refresh"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "更新"}}}}, "settings.apps.checking" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Checking availability…"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "利用可否を確認中…"}}}}, "settings.apps.open" : {"extractionState" : "manual", "localizations" : {"en" : {"stringUnit" : {"state" : "translated", "value" : "Open %@"}}, "ja" : {"stringUnit" : {"state" : "translated", "value" : "%@ を開く"}}}}, diff --git a/Sources/SettingsSearchIndex.swift b/Sources/SettingsSearchIndex.swift index 9e291243..d5e45102 100644 --- a/Sources/SettingsSearchIndex.swift +++ b/Sources/SettingsSearchIndex.swift @@ -253,7 +253,7 @@ enum SettingsItem: String, CaseIterable, Sendable { case .trustedDirectories: String(localized: "settings.customCommands.trustedDirectories.subtitle", defaultValue: "Commands from programa.json in these directories run without confirmation. One path per line.", bundle: bundle, locale: locale) case .taskAccess: String(localized: "mobileChat.useOpenWorkspaces.detail", defaultValue: "Allow tasks from your iPhone to work in isolated copies of the Git repositories open in Programa now.", bundle: bundle, locale: locale) case .iphoneConnection: String(localized: "mobileChat.keepOpen", defaultValue: "Keep Programa open and this Mac awake to run jobs from your iPhone.", bundle: bundle, locale: locale) - case .discoveredApps: String(localized: "settings.apps.help", defaultValue: "Check whether Browsee and Mesinyer are installed and available.", bundle: bundle, locale: locale) + case .discoveredApps: String(localized: "settings.apps.help", defaultValue: "Check which Darkroom apps are installed and available.", bundle: bundle, locale: locale) case .installIntegrations: String(localized: "settings.integrations.installers.help", defaultValue: "Set up Claude Code, Codex and OpenCode or review existing Browsee registrations.", bundle: bundle, locale: locale) case .shortcutChords: String(localized: "settings.shortcuts.chords.subtitle", defaultValue: "Add tmux-style multi-step shortcuts in settings.json, for example [\"ctrl+b\", \"c\"].", bundle: bundle, locale: locale) } @@ -268,7 +268,7 @@ enum SettingsItem: String, CaseIterable, Sendable { case .claudeCodeIntegration: ["hooks", "claude"] case .socketControlMode, .socketPassword: ["socket", "api", "cli"] case .trustedDirectories: ["programa.json", "custom commands"] - case .discoveredApps: ["browsee", "mesinyer", "mcp", "connections", "access"] + case .discoveredApps: ["browsee", "mesinyer", "notetaker", "mcp", "connections", "access"] case .installIntegrations: ["claude code", "codex", "opencode", "browsee", "mcp"] case .windowGlass, .tabBarGlass, .overlayGlass: ["liquid glass", "transparency", "blur"] case .selectionColor, .notificationBadgeColor, .sidebarTint: ["color", "colour"]