diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 429faa2c..3ad1a7c5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -159,6 +159,87 @@ jobs: echo "Effective build: ${EFFECTIVE_BUILD}" echo "Release tag: ${RELEASE_TAG}" + # Shadow build only: verify the signed handoff without adding it to 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 + continue-on-error: true + 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")" + 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" | + 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" "$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" ]] + + - 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: >- @@ -526,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 @@ -595,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" @@ -648,6 +734,105 @@ 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_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 && + 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 + environment: shipit-preview + 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/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..8db8d7d1 --- /dev/null +++ b/CLI/CLI+AppLinkAgents.swift @@ -0,0 +1,127 @@ +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 + 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 + } + 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 new file mode 100644 index 00000000..22d3e978 --- /dev/null +++ b/CLI/CLI+Apps.swift @@ -0,0 +1,97 @@ +import AppKit +import Darwin +import Foundation + +private struct AppDiscoveryReport: Encodable { + let contract = 1 + let apps: [DarkroomPeer.Status] +} + +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] + execv(helper.path, argv) + let reason = String(cString: strerror(errno)) + argv.forEach { free($0) } + throw CLIError(message: "Could not run \(helper.path): \(reason)") + } + + 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 { $0.status() } + if jsonOutput || arguments.contains("--json") { + 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.rawValue)") } + } + 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]), peer.supportsAgentMCP, + 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 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 99b9cb55..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,45 +130,29 @@ 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)) ?? [] - } - - private func browseeIsRunning() -> Bool { - BrowseeApp.probePaths(home: browseeHome, fallbackFolder: browseeFallbackFolder, listFolder: browseeOwnedFolderEntries) - .contains { browseeSocketAccepts($0) } + private func browseeReadySocket(installation: DarkroomPeer.Installation?) -> String? { + BrowseeSocket.endpoint(pids: installation?.runningPIDs, home: browseeHome, fallbackFolder: browseeFallbackFolder) } - 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() } - /// 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 { - let descriptor = socket(AF_UNIX, SOCK_STREAM, 0) - guard descriptor >= 0 else { return false } - defer { Darwin.close(descriptor) } - 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) - return withUnsafePointer(to: &address) { - $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { - connect(descriptor, $0, socklen_t(MemoryLayout.size)) == 0 - } + 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) } - /// `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 +164,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 +183,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 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 @@ -285,9 +254,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..12ccb56d 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]"], @@ -138,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/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..105eb2b7 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -34,6 +34,9 @@ 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 */; }; 5582C929E24C4D5845606603 /* SettingsSearchIndex.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAF5C4C06180C3C78CC60875 /* SettingsSearchIndex.swift */; }; @@ -182,6 +185,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 */; }; @@ -337,6 +342,8 @@ 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 */; }; + 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 */; }; @@ -373,6 +380,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 */; }; @@ -443,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 */; }; @@ -481,6 +490,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 */, ); @@ -567,6 +577,9 @@ 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 = ""; }; EAF5C4C06180C3C78CC60875 /* SettingsSearchIndex.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsSearchIndex.swift; sourceTree = ""; }; @@ -710,6 +723,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 = ""; }; @@ -837,6 +851,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 = ""; }; @@ -866,6 +881,8 @@ 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 = ""; }; + 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 = ""; }; @@ -965,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 = ""; }; @@ -1150,6 +1168,9 @@ 102A507DEBDABE1023354973 /* SettingsShortcutsPane.swift */, AA5806D6D2EFE4538DEF636D /* SettingsAutomationPane.swift */, F4F272647ABD5BD0ACD6B3FC /* SettingsAgentsPane.swift */, + A21880000000000000000001 /* ScopedAgentStatusPublisher.swift */, + A21880000000000000000003 /* ScopedAgentStatusTransport.swift */, + EF2190000000000000000001 /* SettingsDarkroomApps.swift */, BAC531A0F930E986A2FC3C6D /* SettingsAppearancePane.swift */, 54B811D46EBCD241CBC31798 /* SettingsGeneralPanes.swift */, EAF5C4C06180C3C78CC60875 /* SettingsSearchIndex.swift */, @@ -1309,6 +1330,7 @@ 7B3F9A10C2D4E5F6A7B80001 /* ListeningProcess.swift */, 7B3F9A10C2D4E5F6A7B80003 /* PortsHubStore.swift */, E0A1B2C3D4E5F6071800A001 /* ExternalOpenPolicy.swift */, + EE2190000000000000000001 /* DarkroomAppDiscovery.swift */, 7B3F9A10C2D4E5F6A7B80005 /* PortsHubView.swift */, 7B3F9A10C2D4E5F6A7B80007 /* TerminalController+Ports.swift */, A5001544 /* TerminalPasteboardPlanner.swift */, @@ -1402,6 +1424,8 @@ B9000001A1B2C3D4E5F60719 /* programa.swift */, 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 */, @@ -1498,6 +1522,7 @@ A5002001 /* THIRD_PARTY_LICENSES.md */, AMDT000008 /* AgentDetection */, C1ADE00001A1B2C3D4E5F719 /* claude */, + DC21850001A1B2C3D4E5F719 /* codex */, A6SC00000000000000000001 /* restore-node-options.cjs */, DA7A10CA710E000000000001 /* Localizable.xcstrings */, DA7A10CA710E000000000002 /* InfoPlist.xcstrings */, @@ -1604,6 +1629,7 @@ PUW0000004 /* ProviderUsageWarningTests.swift */, 1D301919B10F22B8708E8883 /* WorkspaceManualUnreadTests.swift */, EE0171AF1F49F7547191CEE5 /* SidebarWidthPolicyTests.swift */, + A21880000000000000000005 /* ScopedAgentStatusTests.swift */, 491751CE2321474474F27DCF /* TerminalControllerSocketSecurityTests.swift */, PRTS000001 /* PortScannerTests.swift */, 7B3F9A10C2D4E5F6A7B8000B /* PortsHubTests.swift */, @@ -1818,6 +1844,9 @@ 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 */, 5582C929E24C4D5845606603 /* SettingsSearchIndex.swift in Sources */, @@ -1982,6 +2011,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 */, @@ -2156,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 */, @@ -2190,6 +2221,9 @@ FADE00000000000000000003 /* CLI+HookSettingsIO.swift in Sources */, 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 */, 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/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index e09f1934..5da7c088 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -1,6 +1,35 @@ { "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 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" : "%@ を開く"}}}}, + "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 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" : "アプリの状態を更新しました。"}}}}, + "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" : "ガラス"}}}}, @@ -49,7 +78,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/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[@]}" "$@" 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/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 6d25f48a..7e6c1f4b 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() } @@ -426,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() @@ -646,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) @@ -3261,8 +3287,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/DarkroomAppDiscovery.swift b/Sources/DarkroomAppDiscovery.swift new file mode 100644 index 00000000..c00a31dd --- /dev/null +++ b/Sources/DarkroomAppDiscovery.swift @@ -0,0 +1,300 @@ +import AppKit +import Darwin +import Foundation +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" + } + } + + 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)] + case .notetaker: + return [("Contents/MacOS/notetaker-mcp", "notetaker-mcp")] + } + } + + 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" : "\(title).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 available + 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), + let state = validatedState(for: identity, installedVersion: install.version) 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 + } + + 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() + 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) + } + +} 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/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..f85cf4f5 --- /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" 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 } + return SecCodeCheckValidity(code, flags, requirement) == errSecSuccess + } +} 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..cdf6793a --- /dev/null +++ b/Sources/SettingsDarkroomApps.swift @@ -0,0 +1,200 @@ +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 + + var body: some View { + Section { + 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) } + } + .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.title + 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 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 + } + } + + @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..d5e45102 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 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) } } @@ -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", "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"] diff --git a/contracts/link/v1/README.md b/contracts/link/v1/README.md new file mode 100644 index 00000000..f92f4f0d --- /dev/null +++ b/contracts/link/v1/README.md @@ -0,0 +1,22 @@ +# 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 | +| --- | --- | +| `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. | +| `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, 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/contracts/link/v1/apps.json b/contracts/link/v1/apps.json new file mode 100644 index 00000000..e5042b4a --- /dev/null +++ b/contracts/link/v1/apps.json @@ -0,0 +1,32 @@ +{ + "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"] + }, + { + "app": "notetaker", + "bundle_id": "engineering.darkroom.NoteTaker", + "status_entry_points": ["Contents/MacOS/notetaker-mcp"], + "mcp_entry_points": [] + } + ] +} 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"] +} diff --git a/contracts/link/v1/windows-apps.json b/contracts/link/v1/windows-apps.json new file mode 100644 index 00000000..c8488a6c --- /dev/null +++ b/contracts/link/v1/windows-apps.json @@ -0,0 +1,42 @@ +{ + "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": [] + }, + { + "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", + "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 new file mode 100644 index 00000000..4b08fd41 --- /dev/null +++ b/contracts/link/v1/windows.md @@ -0,0 +1,44 @@ +# 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 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. + +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. 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 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 + +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/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/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/app-sandbox-spike.md b/docs/app-sandbox-spike.md new file mode 100644 index 00000000..5e7148d1 --- /dev/null +++ b/docs/app-sandbox-spike.md @@ -0,0 +1,61 @@ +# 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. | + +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 + +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 +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. + +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, 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 + +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) diff --git a/docs/browsee.md b/docs/browsee.md index ba42c78b..4744aa6b 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 a read-only +registration report 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 diff --git a/docs/release.md b/docs/release.md index 892a9f34..3d4a73d8 100644 --- a/docs/release.md +++ b/docs/release.md @@ -59,6 +59,29 @@ 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. + +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 @@ -78,6 +101,46 @@ 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. + +```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. + +### 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 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. + ## What `rolling` carries - `appcast.xml` 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**. 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 + + + + + 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) } + } +} 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) } 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")] 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) } 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..1503f6c8 --- /dev/null +++ b/scripts/app-sandbox-spike/boundary.c @@ -0,0 +1,45 @@ +#include +#include +#include +#include +#include +#include +#include +extern char **environ; + +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, "%s_spawn=%s\n", label, strerror(result)); + return 1; + } + int status; + if (waitpid(child, &status, 0) < 0) { + fprintf(stderr, "%s_wait=%s\n", label, strerror(errno)); + return 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/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..a221d2ac --- /dev/null +++ b/scripts/app-sandbox-spike/observe-startup.py @@ -0,0 +1,75 @@ +"""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")): + 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 = 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_path.exists() and time.monotonic() < stop: + time.sleep(.10) + 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) + 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" 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" diff --git a/scripts/build-windows.ps1 b/scripts/build-windows.ps1 index 6b06f2c7..01d35a74 100644 --- a/scripts/build-windows.ps1 +++ b/scripts/build-windows.ps1 @@ -11,7 +11,11 @@ param( [string]$SignScript = $env:PROGRAMA_WINDOWS_SIGN_SCRIPT, # 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 = '' + [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 ) $ErrorActionPreference = 'Stop' @@ -23,6 +27,7 @@ if ([System.Environment]::OSVersion.Platform -ne [System.PlatformID]::Win32NT) { if ($Version -cnotmatch '^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$') { throw "Version must be a canonical semantic version, got '$Version'." } +if ($StorePackage -and [string]::IsNullOrWhiteSpace($PublishDirectory)) { throw 'A Store build needs PublishDirectory.' } if ($Build -cnotmatch '^[1-9][0-9]*$') { throw "Build must be a positive canonical decimal integer, got '$Build'." } if ($Commit -cnotmatch '^[0-9a-f]{40}$') { throw "Commit must be a 40-character lowercase hexadecimal SHA, got '$Commit'." } @@ -111,7 +116,7 @@ try { Invoke-Checked 'WinUI publish' { dotnet publish $AppProject --configuration Release --runtime win-x64 --self-contained true --output $PublishRoot ` --property:ProgramaNativeDirectory=$NativeRoot --property:ProgramaVersion=$Version ` - --property:ProgramaBuild=$Build --property:ProgramaCommit=$Commit + --property:ProgramaBuild=$Build --property:ProgramaCommit=$Commit --property:ProgramaMsix=$($StorePackage.IsPresent) } $BuiltExecutable = Join-Path $PublishRoot 'programa.exe' @@ -131,7 +136,13 @@ try { $ExpectedVersion = "programa $Version (build $Build, commit $Commit)" if ($ActualVersion -cne $ExpectedVersion) { throw "Version mismatch. Expected '$ExpectedVersion', got '$ActualVersion'." } $NativeProbe = (& $BuiltExecutable --verify-native-libraries | Out-String).Trim() - if ($LASTEXITCODE -ne 0 -or $NativeProbe -cne 'ok') { throw "The single-file executable could not extract and load both native libraries. Output: '$NativeProbe'." } + if ($LASTEXITCODE -ne 0 -or $NativeProbe -cne 'ok') { throw "The published executable could not load its native libraries or ConPTY. Output: '$NativeProbe'." } + + if ($StorePackage) { + Copy-Item -Path (Join-Path $PublishRoot '*') -Destination $ResolvedPublish -Recurse + Write-Output "Published Store payload: $ResolvedPublish" + return + } # .NET single-file apps extract their bundled payload to a per-app, per-build-hash # temp directory on first launch (DOTNET_BUNDLE_EXTRACT_BASE_DIR, default %TEMP%\.net). @@ -185,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" 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" + + + ${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, 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) => { + 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, workflowId, 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/); +}); + +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); +}); 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/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/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": { diff --git a/tests/test_cli_browsee_integration.py b/tests/test_cli_browsee_integration.py index ff6808e6..4a8e5477 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,63 @@ 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", "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}"] + 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() 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.Tests/CompanionDiscoveryTests.cs b/windows/Programa.Tests/CompanionDiscoveryTests.cs new file mode 100644 index 00000000..d9ab14a4 --- /dev/null +++ b/windows/Programa.Tests/CompanionDiscoveryTests.cs @@ -0,0 +1,164 @@ +using System.Text.Json; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using static Darkroom.AppLink.Windows.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 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() + { + 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 ExcludesTheCurrentAppBeforeProbingPeers() + { + foreach (var host in new[] { "browsee", "mesinyer", "programa" }) + { + var fixture = new Fixture(); + 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; } + + internal List ProbedApps { get; } = []; + + public IEnumerable Candidates(Identity app) + { + ProbedApps.Add(app.App); + return InstallFor?.Invoke(app) ?? Installs; + } + + public bool? Running(Candidate candidate) + { + RunningChecks++; + return UnknownRunningState ? null : candidate == RunningApp; + } + } +} 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/Companion.cs b/windows/Programa/Companion.cs index a4540802..ebea5e59 100644 --- a/windows/Programa/Companion.cs +++ b/windows/Programa/Companion.cs @@ -59,7 +59,7 @@ internal sealed class Identity internal static event Action? Changed; internal static string Directory { get; } = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programa", $"iPhone Companion{BuildIdentity.DevSuffix}"); + BuildIdentity.DataDirectory, $"iPhone Companion{BuildIdentity.DevSuffix}"); private static string ConfigurationPath => Path.Combine(Directory, "configuration.json"); private static string IdentityPath => Path.Combine(Directory, "identity.bin"); diff --git a/windows/Programa/CompanionDiscovery.cs b/windows/Programa/CompanionDiscovery.cs new file mode 100644 index 00000000..0a23fc24 --- /dev/null +++ b/windows/Programa/CompanionDiscovery.cs @@ -0,0 +1,120 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Darkroom.AppLink.Windows; + +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, + string? DirectCurrentUserDirectory = null); + + 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 enum OutsideAccess { Unknown, Enabled, Disabled } + internal delegate OutsideAccess StatusProbe(Identity identity, Candidate candidate); + + internal interface Platform + { + IEnumerable Candidates(Identity app); + bool? Running(Candidate candidate); + } + + 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."); + 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.Where(app => app.App != hostApp) + .Select(app => Discover(app, platform, probe)).ToArray()); + } + + 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, 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 + // 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 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, []); + } + + 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)}. {DescribeAccess(app)}."); + return 0; + } + + 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", + _ => 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/GlobalChatController.cs b/windows/Programa/GlobalChatController.cs index aa8c6fbd..e6ad58f4 100644 --- a/windows/Programa/GlobalChatController.cs +++ b/windows/Programa/GlobalChatController.cs @@ -116,7 +116,7 @@ internal GlobalChatController(string directory, IGlobalWorkspaces workspaces, IG ///

Where the app keeps the conversation: %LOCALAPPDATA%\Programa\Global Chat (the /// Development builds' own folder for them). internal static string DefaultDirectory { get; } = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programa", $"Global Chat{BuildIdentity.DevSuffix}"); + BuildIdentity.DataDirectory, $"Global Chat{BuildIdentity.DevSuffix}"); internal bool Busy => _running is not null; diff --git a/windows/Programa/LaunchLog.cs b/windows/Programa/LaunchLog.cs index fcd7b1a3..dc6603ce 100644 --- a/windows/Programa/LaunchLog.cs +++ b/windows/Programa/LaunchLog.cs @@ -11,8 +11,7 @@ namespace Programa; internal static partial class LaunchLog { internal static string LogPath { get; } = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), - "Programa", + BuildIdentity.DataDirectory, BuildIdentity.IsSmoke ? "launch-smoke.log" : "launch.log"); /// Set once the main window has been shown. Before that an unhandled exception means launch failed. diff --git a/windows/Programa/MainWindow.Help.cs b/windows/Programa/MainWindow.Help.cs index 9dcf6627..3755153e 100644 --- a/windows/Programa/MainWindow.Help.cs +++ b/windows/Programa/MainWindow.Help.cs @@ -16,6 +16,7 @@ public sealed partial class MainWindow // only programa-windows.exe), so Check for Updates opens the releases page. Check and install with // UpdateManager once ship-windows.yml publishes releases.win.json there. internal const string ReleasesUrl = RepositoryUrl + "/releases/latest"; + private const string UpdatesUrl = BuildIdentity.IsStore ? "ms-windows-store://downloadsandupdates" : ReleasesUrl; /// The Help menu's links, as on macOS. internal static readonly (string LabelKey, string Url)[] HelpLinks = @@ -55,7 +56,7 @@ private MenuFlyout HelpMenu() } menu.Items.Add(new MenuFlyoutSeparator()); var updates = MenuItem(Localizer.Get("CheckForUpdates"), CheckForUpdates); - AutomationProperties.SetHelpText(updates, ReleasesUrl); + AutomationProperties.SetHelpText(updates, UpdatesUrl); menu.Items.Add(updates); menu.Items.Add(MenuItem(Localizer.Get("AboutPrograma"), () => _ = ShowAboutAsync())); return menu; @@ -85,7 +86,7 @@ private void NewWorkspaceRunning(string command) NewWorkspace(); } - private static void CheckForUpdates() => OpenUrl(ReleasesUrl); + private static void CheckForUpdates() => OpenUrl(UpdatesUrl); private static void OpenUrl(string url) => _ = Windows.System.Launcher.LaunchUriAsync(new Uri(url)); diff --git a/windows/Programa/MainWindow.Integrations.cs b/windows/Programa/MainWindow.Integrations.cs new file mode 100644 index 00000000..3dbd4cd5 --- /dev/null +++ b/windows/Programa/MainWindow.Integrations.cs @@ -0,0 +1,77 @@ +using Darkroom.AppLink.Windows; +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 BrowseeWindowsStatus.ReadAsync(); + 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(AccessKey(peer)), 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", + "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/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/McpConfig.cs b/windows/Programa/McpConfig.cs index b5baca90..3f55dc51 100644 --- a/windows/Programa/McpConfig.cs +++ b/windows/Programa/McpConfig.cs @@ -20,7 +20,7 @@ internal static class McpConfig internal static void Write() { - var folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programa"); + var folder = Path.Combine(BuildIdentity.DataDirectory); var dev = BuildIdentity.DevSuffix; BinDirectory = StageTools(Path.Combine(folder, $"bin{dev}")); var server = Path.Combine(BinDirectory, "programa-mcp.exe"); diff --git a/windows/Programa/Program.cs b/windows/Programa/Program.cs index b5aa2d36..66db6e6d 100644 --- a/windows/Programa/Program.cs +++ b/windows/Programa/Program.cs @@ -1,9 +1,12 @@ +using Darkroom.AppLink.Windows; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Principal; using Microsoft.UI.Dispatching; using Microsoft.UI.Xaml; +#if !PROGRAMA_MSIX using Velopack; +#endif using WinRT; namespace Programa; @@ -13,9 +16,29 @@ public static class Program [STAThread] public static void Main(string[] args) { +#if !PROGRAMA_MSIX // Must run before anything else, --version included: Velopack's install, update and // uninstall hooks start the app with arguments that are handled and exit here. VelopackApp.Build().Run(); +#endif + + 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..], + () => BrowseeWindowsStatus.ReadAsync().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")) { @@ -32,10 +55,6 @@ public static void Main(string[] args) : ThemesCommand.Run(args[1..], ShortcutSettings.SettingsPath, ThemesCommand.ThemeDirectories(), output, error)); } var conptyLoaded = LoadBundledConpty(); - // Markdown panels' WebView2 data lives with the app's other data, not beside the executable, - // whose folder an update replaces. - if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBVIEW2_USER_DATA_FOLDER"))) - Environment.SetEnvironmentVariable("WEBVIEW2_USER_DATA_FOLDER", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programa", $"WebView2{BuildIdentity.DevSuffix}")); if (args.Contains("--verify-native-libraries", StringComparer.Ordinal)) { using var core = new CoreClient(); @@ -47,6 +66,11 @@ public static void Main(string[] args) return; } + // Markdown panels' WebView2 data lives with the app's other data, not beside the executable, + // whose folder an update replaces. + if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBVIEW2_USER_DATA_FOLDER"))) + Environment.SetEnvironmentVariable("WEBVIEW2_USER_DATA_FOLDER", Path.Combine(BuildIdentity.DataDirectory, $"WebView2{BuildIdentity.DevSuffix}")); + var smoke = BuildIdentity.IsSmoke; AppDomain.CurrentDomain.UnhandledException += (_, eventArgs) => @@ -134,8 +158,19 @@ public static class BuildIdentity /// What a development build adds to the names of its pipe and files: "-dev", or "-dev-" /// with PROGRAMA_DEV_TAG (letters, digits and hyphens), so tagged dev builds run side by side as - /// macOS reload.sh --tag builds do. Empty for an installed build. - public static string DevSuffix { get; } = IsSmoke ? "-smoke" : DevSuffixFor(Value, Environment.GetEnvironmentVariable("PROGRAMA_DEV_TAG")); + /// macOS reload.sh --tag builds do. The Store channel uses its own stable suffix. +#if PROGRAMA_MSIX + internal const bool IsStore = true; + private static readonly Lazy StoreData = new(() => Windows.Storage.ApplicationData.Current.LocalFolder.Path); + internal static string DataDirectory => StoreData.Value; +#else + internal const bool IsStore = false; + internal static string DataDirectory { get; } = + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programa"); +#endif + + public static string DevSuffix { get; } = IsSmoke ? "-smoke" + : IsStore ? "-store" : DevSuffixFor(Value, Environment.GetEnvironmentVariable("PROGRAMA_DEV_TAG")); internal static string DevSuffixFor(string identity, string? tag) => !identity.Contains("0.0.0-dev", StringComparison.Ordinal) ? string.Empty diff --git a/windows/Programa/Programa.csproj b/windows/Programa/Programa.csproj index eae74bbc..43037fda 100644 --- a/windows/Programa/Programa.csproj +++ b/windows/Programa/Programa.csproj @@ -42,7 +42,15 @@ programa + + $(DefineConstants);PROGRAMA_MSIX + false + false + false + + + @@ -51,7 +59,7 @@ OSC color queries and repaints the screen. Program.LoadBundledConpty wires it up. --> - + 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/Strings/en-US/Resources.resw b/windows/Programa/Strings/en-US/Resources.resw index 60bca6e9..ed2a40b1 100644 --- a/windows/Programa/Strings/en-US/Resources.resw +++ b/windows/Programa/Strings/en-US/Resources.resw @@ -295,4 +295,17 @@ 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 + 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 eba3c1a3..13e53cd3 100644 --- a/windows/Programa/Strings/ja-JP/Resources.resw +++ b/windows/Programa/Strings/ja-JP/Resources.resw @@ -295,4 +295,17 @@ エージェントが予期せず停止しました。{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 未確認 + インストール済み · 停止中 + 実行中 · 連携状態を確認できません + 実行中 + Browsee の外部アクセスは有効です + Browsee の外部アクセスは無効です + インストール済み · 実行状態は不明 + 連携アプリを確認できませんでした。更新して再試行してください。 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() { diff --git a/windows/Programa/WindowsCompanionPlatform.cs b/windows/Programa/WindowsCompanionPlatform.cs new file mode 100644 index 00000000..a099a4a2 --- /dev/null +++ b/windows/Programa/WindowsCompanionPlatform.cs @@ -0,0 +1,155 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security; +using Microsoft.Win32; +using Windows.ApplicationModel; +using Windows.Management.Deployment; + +namespace Darkroom.AppLink.Windows; + +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) { } + } + + 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 }) + { + 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; + 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; + 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 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) + { + unknown = true; + } + } + return unknown ? null : false; + } + finally + { + foreach (var process in processes) process.Dispose(); + } + } + + 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) + { + 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); +} diff --git a/windows/Programa/WindowsCompanionTrust.cs b/windows/Programa/WindowsCompanionTrust.cs new file mode 100644 index 00000000..603a7727 --- /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 Darkroom.AppLink.Windows; + +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); +} 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 00000000..731d7178 Binary files /dev/null and b/windows/msix/Assets/Square150x150Logo.png differ diff --git a/windows/msix/Assets/Square44x44Logo.png b/windows/msix/Assets/Square44x44Logo.png new file mode 100644 index 00000000..1b11e646 Binary files /dev/null and b/windows/msix/Assets/Square44x44Logo.png differ diff --git a/windows/msix/Assets/StoreLogo.png b/windows/msix/Assets/StoreLogo.png new file mode 100644 index 00000000..14a37992 Binary files /dev/null and b/windows/msix/Assets/StoreLogo.png differ diff --git a/windows/msix/README.md b/windows/msix/README.md new file mode 100644 index 00000000..fda0adc8 --- /dev/null +++ b/windows/msix/README.md @@ -0,0 +1,17 @@ +# Programa Windows Store pilot + +Programa's public repository cannot use the private Darky Body Windows runner group. The **Programa Windows Store pilot** dispatch runs from Shipit's protected default branch using the inherited Windows runner. Verify the runner group and `WIN_RUNNER` before the release batch. Pass the exact published Programa `main` SHA and an increasing Store package version such as `1.0.0.0`. The run checks out Programa's current `main`, verifies the SHA and uploads a validated MSIX artifact. This operation has no Partner Center credentials. + +The checked-in configuration uses the sideload package Identity Name `DarkroomEngineering.Programa.Pilot` and Publisher `CN=Programa MSIX Pilot`. For signed VM validation, provision a matching trusted code-signing certificate and set `PROGRAMA_MSIX_SIGNING_THUMBPRINT` in the private Shipit repo. For Store use, verify the identity in Partner Center and replace the pilot identity, providing the actual product ID and approved flight group. The MSIX version is independent of the committed Programa marketing version. [Windows package identity](https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/package-identity-overview) + +The Store build keeps the same pinned ConPTY, OpenConsole, Rust terminal host, core and companion libraries, CLI and MCP helpers. It publishes a self-contained multi-file app, checks the version and native libraries, and gives Windows ownership of package upgrades. Programa's packaged session, host connection, logs, WebView2, companion pairing and chat data use package LocalState. The package has its own instance mutex and pipe suffix. User-selected workspaces and the explicit user configuration under `~/.config/programa` remain accessible to both installations. Terminals launch the correct CLI and inherit their own `PROGRAMA_SOCKET_PATH`. The Store build's Check for Updates opens Microsoft Store. + +## Verify on the Windows VM + +1. Install a signed baseline MSIX and launch from Start. Verify the package identity and version with `Get-AppxPackage`. Open a workspace in an ordinary directory outside WindowsApps. In its terminal, run PowerShell, create a file, check encoding and colors, split panes, and open a repository worktree. Confirm the terminal uses bundled ConPTY and launches `programa-host.exe` and `OpenConsole.exe`. +2. Run the bundled `programa` from the terminal, inspect its `PROGRAMA_SOCKET_PATH`, list workspaces, and exercise a CLI command that launches the GUI executable in headless mode, such as `programa config check`. Verify MCP calls use the same package's pipe when the direct installer runs as well. +3. Launch the same package again and confirm only one GUI instance starts for the user. Quit and reopen with an active terminal and verify it reattaches. Verify another user session cannot control the first user's pipe. +4. Install a higher signed MSIX over the baseline with the same package identity. Confirm package LocalState and workspace restoration survive. Check both an idle app and a surviving terminal host while Windows applies an update. Document any required host exit or reboot and whether active shells are preserved. Verify the direct installer, its control pipe and its existing state are still independent. [Add-AppxPackage and deferred registration](https://learn.microsoft.com/en-us/powershell/module/appx/add-appxpackage) +5. Complete the first Partner Center release steps through the approved onboarding path. Then stage the exact validated artifact for an internal flight where available. An approved public release follows terminal and CLI acceptance. + +If a required journey cannot work in MSIX, compare a signed standalone silent EXE/MSI package with the current Windows installer. Its download would use the Store's EXE/MSI submission flow and the installer would retain update ownership. [Microsoft Store MSI and EXE package requirements](https://learn.microsoft.com/en-us/windows/apps/publish/publish-your-app/msi/app-package-requirements) diff --git a/windows/msix/build.ps1 b/windows/msix/build.ps1 new file mode 100644 index 00000000..b79ce35e --- /dev/null +++ b/windows/msix/build.ps1 @@ -0,0 +1,37 @@ +# Shipit's Store build command, using the same locked Rust inputs and WinUI checks as the direct build. +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +if ($env:SHIP_STORE_ARCH -ne 'x64') { throw 'The Programa Store pilot targets x64.' } +$root = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..\..')).Path +$output = Join-Path $env:SHIP_STORE_OUTPUT "Programa-$env:SHIP_STORE_VERSION-x64.msix" +$work = Join-Path ([System.IO.Path]::GetTempPath()) "programa-msix-$([Guid]::NewGuid())" +$payload = Join-Path $work 'payload' + +Push-Location $root +try { + $commit = (git rev-parse HEAD).Trim() + if ($LASTEXITCODE -ne 0) { throw 'Cannot identify the Programa checkout.' } + $project = Get-Content -Raw -LiteralPath 'GhosttyTabs.xcodeproj/project.pbxproj' + $marketing = [regex]::Match($project, '\bMARKETING_VERSION = ([0-9]+\.[0-9]+\.[0-9]+);') + if (!$marketing.Success) { throw 'Cannot read the committed Programa marketing version.' } + $version = [version] $env:SHIP_STORE_VERSION + $build = ([long]$version.Major * 4294967296) + ([long]$version.Minor * 65536) + $version.Build + New-Item -ItemType Directory -Path $work | Out-Null + .\scripts\build-windows.ps1 -Version $marketing.Groups[1].Value -Build $build -Commit $commit ` + -OutputDirectory (Join-Path $work 'exe') -PublishDirectory $payload -StorePackage + + foreach ($file in @( + 'programa.exe', 'programa_core.dll', 'programa_companion.dll', 'programa_terminal.dll', + 'programa-host.exe', 'conpty.dll', 'OpenConsole.exe', 'resources.pri', 'coreclr.dll', + 'bin\programa.exe', 'bin\programa-mcp.exe' + )) { + if (!(Test-Path -LiteralPath (Join-Path $payload $file) -PathType Leaf)) { throw "Missing package payload: $file" } + } + if (Test-Path -LiteralPath (Join-Path $payload 'Velopack.dll')) { throw 'Store packages must exclude Velopack.' } + & $env:SHIP_STORE_PACKER -Mode pack -Payload $payload -Manifest (Join-Path $PSScriptRoot 'AppxManifest.xml') ` + -Assets (Join-Path $PSScriptRoot 'Assets') -Package $output +} finally { + Pop-Location + if (Test-Path -LiteralPath $work) { Remove-Item -LiteralPath $work -Recurse -Force } +}