From ec98a52c1f4f18ae03f94fccd6d9f8a24243d2fd Mon Sep 17 00:00:00 2001 From: Lucas Ribeiro Date: Sat, 3 Oct 2026 18:10:57 +1300 Subject: [PATCH 01/36] web: optional edge-only forward-auth origin for publications dev stacks are tailnet-only, so freestyle can't call their forward-auth route. CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN lets an operator point the edge at a tunnel while browsers keep signing in on the auth origin. unset in prod, malformed fails closed. --- web/app/api/vm/publications/routeShared.ts | 8 +++++++- web/app/env.ts | 7 +++++++ web/tests/vm-publication-workflows.test.ts | 14 ++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/web/app/api/vm/publications/routeShared.ts b/web/app/api/vm/publications/routeShared.ts index f1b5d53e55a1..5aba1fd8dc02 100644 --- a/web/app/api/vm/publications/routeShared.ts +++ b/web/app/api/vm/publications/routeShared.ts @@ -121,7 +121,13 @@ export function publicationForwardAuthConfig( ): PublicationForwardAuthConfig | undefined { const serviceToken = environment.CMUX_VM_PUBLICATION_FORWARD_AUTH_SECRET?.trim(); if (!serviceToken) return undefined; - const origin = normalizePublicationAuthOrigin(environment.CMUX_VM_PUBLICATION_AUTH_ORIGIN); + // A development stack the edge cannot reach sets a separate public origin + // for the edge alone; browsers still sign in on the auth origin. A set but + // malformed override fails closed instead of falling back. + const override = environment.CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN?.trim(); + const origin = normalizePublicationAuthOrigin( + override || environment.CMUX_VM_PUBLICATION_AUTH_ORIGIN, + ); return { url: origin ? new URL("/api/freestyle/forward-auth", origin).href : "", serviceToken, diff --git a/web/app/env.ts b/web/app/env.ts index 4ff517891356..3febc7f61ca1 100644 --- a/web/app/env.ts +++ b/web/app/env.ts @@ -332,6 +332,10 @@ export const env = createEnv({ // pushed to Freestyle as the account-wide forward-auth target. It is never // derived from a request; protected publications fail closed without it. CMUX_VM_PUBLICATION_AUTH_ORIGIN: publicationAuthOrigin.optional(), + // Optional origin Freestyle calls for forward-auth when it differs from + // the sign-in origin, e.g. a tunnel to a development stack the edge can't + // reach. Unset in production: the auth origin serves both. + CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN: publicationAuthOrigin.optional(), // Zone generated Cloud VM publication hostnames are minted under // (.). The CMUX Freestyle account must own it: verify the // zone, CNAME `*` to the Freestyle edge, delegate `_acme-challenge`, and @@ -551,6 +555,9 @@ export const env = createEnv({ CMUX_VM_PUBLICATION_AUTH_ORIGIN: trimEnv( process.env.CMUX_VM_PUBLICATION_AUTH_ORIGIN, ), + CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN: trimEnv( + process.env.CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN, + ), CMUX_VM_PUBLICATION_GENERATED_DOMAIN: trimEnv( process.env.CMUX_VM_PUBLICATION_GENERATED_DOMAIN, ), diff --git a/web/tests/vm-publication-workflows.test.ts b/web/tests/vm-publication-workflows.test.ts index e46d35334a2e..dd2a9fdad1b2 100644 --- a/web/tests/vm-publication-workflows.test.ts +++ b/web/tests/vm-publication-workflows.test.ts @@ -1901,6 +1901,20 @@ describe("Cloud VM publication REST adapters", () => { } }); + test("an edge-only forward-auth origin overrides the target and fails closed when malformed", () => { + const secret = "a-secret-long-enough-for-the-provider"; + expect(publicationForwardAuthConfig({ + CMUX_VM_PUBLICATION_FORWARD_AUTH_SECRET: secret, + CMUX_VM_PUBLICATION_AUTH_ORIGIN: "https://cmux-dev.example.ts.net:4252", + CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN: "https://edge-tunnel.example.com", + })).toEqual({ url: "https://edge-tunnel.example.com/api/freestyle/forward-auth", serviceToken: secret }); + expect(publicationForwardAuthConfig({ + CMUX_VM_PUBLICATION_FORWARD_AUTH_SECRET: secret, + CMUX_VM_PUBLICATION_AUTH_ORIGIN: "https://cmux.com", + CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN: "http://edge-tunnel.example.com", + })).toEqual({ url: "", serviceToken: secret }); + }); + test("resolves the requested team before authenticating a publication mutation", async () => { const verified: unknown[] = []; const verify: Parameters[3] = async (_request, options) => { From 4a578c0e41f0efc74b04706269126766ddc0e6ec Mon Sep 17 00:00:00 2001 From: Lucas Ribeiro Date: Sat, 3 Oct 2026 18:10:58 +1300 Subject: [PATCH 02/36] cloud: share a port with your team from the sidebar hover share button and copy team link on cloud machine port rows. reuses the port's publication or creates one with the server default (team for team machines), waits until it's active and the link actually answers, then copies it. requests run as the machine's owning team. --- .../VMClient/CloudPortShareService.swift | 139 +++++ .../VMClient/CloudPortShareStore.swift | 53 ++ .../Sources/CmuxCloud/VMClient/VMClient.swift | 27 +- .../CloudPortShareServiceTests.swift | 137 +++++ Resources/Localizable.xcstrings | 531 ++++++++++++++++++ Sources/Cloud/CloudTreeNodeActions.swift | 41 ++ Sources/Cloud/CloudTreeOutlineView.swift | 3 + Sources/Cloud/CloudTreeRowHoverButtons.swift | 63 +++ 8 files changed, 984 insertions(+), 10 deletions(-) create mode 100644 Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift create mode 100644 Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareStore.swift create mode 100644 Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift diff --git a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift new file mode 100644 index 000000000000..20b2a7359db0 --- /dev/null +++ b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift @@ -0,0 +1,139 @@ +import Foundation + +/// The publication calls Share needs, scoped to the machine's owning team. +/// `VMClient` is the live implementation; tests use a fake. +public protocol CloudPortPublishing: Sendable { + func listPublications(scopeTeamID: String?) async throws -> [VMPublication] + func createDefaultPublication(vmID: String, port: Int, scopeTeamID: String?) async throws -> VMPublication + func verifyPublication(id: String, scopeTeamID: String?) async throws -> VMPublication + func deletePublication(id: String, scopeTeamID: String?) async throws +} + +extension VMClient: CloudPortPublishing { + /// No access mode and no team: the server picks team access for a team + /// machine and owner-only access for a personal one. + public func createDefaultPublication(vmID: String, port: Int, scopeTeamID: String?) async throws -> VMPublication { + try await createPublication( + vmID: vmID, + port: port, + hostname: nil, + accessMode: nil, + teamID: nil, + scopeTeamID: scopeTeamID + ) + } +} + +public enum CloudPortShareError: Error, Equatable, Sendable { + /// The link exists but its route never became ready within the wait. + case stillProvisioning + /// The service reports the publication can't serve (for example `unavailable`). + case unavailable(state: String) +} + +/// Finds or creates the shareable link for one machine port, and waits until +/// it serves before handing it back, so a copied link is never a dead one. +public struct CloudPortShareService: Sendable { + public typealias Sleep = @Sendable (Duration) async throws -> Void + /// Opens the link once as a signed-out visitor and returns the HTTP + /// status, or nil when the edge could not be reached. + public typealias Probe = @Sendable (URL) async -> Int? + + /// Waits between readiness checks. Creation provisions the route right + /// away; the wait only covers the edge certificate catching up. + public static let defaultPollDelays: [Duration] = [ + .seconds(1), .seconds(2), .seconds(3), .seconds(5), .seconds(5), + .seconds(10), .seconds(10), .seconds(15), .seconds(15), .seconds(15), + .seconds(15), .seconds(15), + ] + + private let api: any CloudPortPublishing + private let pollDelays: [Duration] + private let sleep: Sleep + private let probe: Probe + + public init( + api: any CloudPortPublishing, + pollDelays: [Duration] = CloudPortShareService.defaultPollDelays, + sleep: @escaping Sleep = { try await Task.sleep(for: $0) }, + probe: @escaping Probe = CloudPortShareService.signedOutStatus + ) { + self.api = api + self.pollDelays = pollDelays + self.sleep = sleep + self.probe = probe + } + + /// The live publication for this port, if there is one. + public func existing(vmID: String, port: Int, teamID: String?) async throws -> VMPublication? { + try await api.listPublications(scopeTeamID: teamID).first { + $0.vmID == vmID && $0.port == port && Self.isLive($0.state) + } + } + + /// Reuses the port's publication (whatever its access) or creates one with + /// the server's default access, then waits until the link itself answers: + /// `active` on the server can run ahead of the edge, which shows a 503 + /// page until its authorization check and route are ready. + public func share(vmID: String, port: Int, teamID: String?) async throws -> VMPublication { + var publication: VMPublication + if let found = try await existing(vmID: vmID, port: port, teamID: teamID) { + publication = found + } else { + publication = try await api.createDefaultPublication(vmID: vmID, port: port, scopeTeamID: teamID) + } + var delays = pollDelays.makeIterator() + while true { + switch publication.state { + case "active": + if let url = URL(string: publication.url), let status = await probe(url), status < 500 { + return publication + } + guard let delay = delays.next() else { throw CloudPortShareError.stillProvisioning } + try await sleep(delay) + case "provisioning": + guard let delay = delays.next() else { throw CloudPortShareError.stillProvisioning } + try await sleep(delay) + publication = try await api.verifyPublication(id: publication.id, scopeTeamID: teamID) + default: + throw CloudPortShareError.unavailable(state: publication.state) + } + } + } + + /// Unpublishes the port. Its link stops working on the next request. + public func stopSharing(publicationID: String, teamID: String?) async throws { + try await api.deletePublication(id: publicationID, scopeTeamID: teamID) + } + + /// A signed-out GET that doesn't follow redirects: a protected link answers + /// with its sign-in redirect (302) or 401/403, a public one with the app. + public static let signedOutStatus: Probe = { url in + let configuration = URLSessionConfiguration.ephemeral + configuration.timeoutIntervalForRequest = 10 + configuration.httpCookieStorage = nil + configuration.httpShouldSetCookies = false + let session = URLSession(configuration: configuration, delegate: NoRedirects(), delegateQueue: nil) + defer { session.finishTasksAndInvalidate() } + var request = URLRequest(url: url) + request.httpMethod = "GET" + guard let (_, response) = try? await session.data(for: request) else { return nil } + return (response as? HTTPURLResponse)?.statusCode + } + + /// `disabling` and `disabled` rows are on their way out and can't be reused. + private static func isLive(_ state: String) -> Bool { + state != "disabling" && state != "disabled" + } +} + +private final class NoRedirects: NSObject, URLSessionTaskDelegate, Sendable { + func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest + ) async -> URLRequest? { + nil + } +} diff --git a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareStore.swift b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareStore.swift new file mode 100644 index 000000000000..9c94ce204745 --- /dev/null +++ b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareStore.swift @@ -0,0 +1,53 @@ +import Combine +import Foundation + +/// Per-port Share progress, so the port row can show a spinner while its link +/// is being made and a checkmark once it has been copied. +@MainActor +public final class CloudPortShareStore: ObservableObject { + public enum Phase: Equatable, Sendable { + case creating + case copied(VMPublicationAccessMode) + case failed + } + + public struct Key: Hashable, Sendable { + public let machineID: String + public let port: Int + public init(machineID: String, port: Int) { + self.machineID = machineID + self.port = port + } + } + + public static let shared = CloudPortShareStore() + + @Published public private(set) var phases: [Key: Phase] = [:] + private var resetTasks: [Key: Task] = [:] + + public init() {} + + public func phase(for key: Key) -> Phase? { phases[key] } + + public func isCreating(_ key: Key) -> Bool { phases[key] == .creating } + + /// Shows `phase` on the row; a finished phase clears itself after `holdFor`. + public func set(_ phase: Phase, for key: Key, holdFor: Duration? = nil) { + resetTasks[key]?.cancel() + resetTasks[key] = nil + phases[key] = phase + guard let holdFor else { return } + resetTasks[key] = Task { @MainActor [weak self] in + try? await Task.sleep(for: holdFor) + guard !Task.isCancelled, let self, self.phases[key] == phase else { return } + self.phases[key] = nil + self.resetTasks[key] = nil + } + } + + public func clear(_ key: Key) { + resetTasks[key]?.cancel() + resetTasks[key] = nil + phases[key] = nil + } +} diff --git a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/VMClient.swift b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/VMClient.swift index fa2a9f2267df..334095b706bb 100644 --- a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/VMClient.swift +++ b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/VMClient.swift @@ -1146,9 +1146,11 @@ public actor VMClient { try await listPage(allowWhenCloudDisabled: false, expectedTeamScope: nil) } - public func listPublications() async throws -> [VMPublication] { + /// `scopeTeamID` runs the request as that team (a machine's owning team) + /// instead of the selected one; nil keeps the selected team. + public func listPublications(scopeTeamID: String? = nil) async throws -> [VMPublication] { return try await withOperation(.publication, foreground: true) { - let (data, http) = try await request("GET", path: "/api/vm/publications") + let (data, http) = try await request("GET", path: "/api/vm/publications", teamID: scopeTeamID) try ensureOK(http, data: data) let object = try decodeJSONObject(data) guard let items = (object["publications"] as? [[String: Any]]) @@ -1204,7 +1206,8 @@ public actor VMClient { accessMode: VMPublicationAccessMode?, teamID: String?, organizationSlug: String? = nil, - confirmPublic: Bool = false + confirmPublic: Bool = false, + scopeTeamID: String? = nil ) async throws -> VMPublication { return try await withOperation(.publication, foreground: true) { var body: [String: Any] = [ @@ -1219,19 +1222,21 @@ public actor VMClient { let (data, http) = try await request( "POST", path: "/api/vm/publications", - jsonBody: body + jsonBody: body, + teamID: scopeTeamID ) try ensureOK(http, data: data) return try Self.decodePublicationMutation(try decodeJSONObject(data)) } } - public func verifyPublication(id: String) async throws -> VMPublication { + public func verifyPublication(id: String, scopeTeamID: String? = nil) async throws -> VMPublication { return try await withOperation(.publication, foreground: true) { let encodedID = try pathSegment(id, fieldName: "publication id") let (data, http) = try await request( "POST", - path: "/api/vm/publications/\(encodedID)/verify" + path: "/api/vm/publications/\(encodedID)/verify", + teamID: scopeTeamID ) try ensureOK(http, data: data) return try Self.decodePublicationMutation(try decodeJSONObject(data)) @@ -1242,7 +1247,8 @@ public actor VMClient { id: String, accessMode: VMPublicationAccessMode, teamID: String?, - confirmPublic: Bool = false + confirmPublic: Bool = false, + scopeTeamID: String? = nil ) async throws -> VMPublication { return try await withOperation(.publication, foreground: true) { let encodedID = try pathSegment(id, fieldName: "publication id") @@ -1255,7 +1261,8 @@ public actor VMClient { let (data, http) = try await request( "PATCH", path: "/api/vm/publications/\(encodedID)", - jsonBody: body + jsonBody: body, + teamID: scopeTeamID ) try ensureOK(http, data: data) return try Self.decodePublicationMutation(try decodeJSONObject(data)) @@ -1274,10 +1281,10 @@ public actor VMClient { } } - public func deletePublication(id: String) async throws { + public func deletePublication(id: String, scopeTeamID: String? = nil) async throws { return try await withOperation(.publication, foreground: true) { let encodedID = try pathSegment(id, fieldName: "publication id") - let (data, http) = try await request("DELETE", path: "/api/vm/publications/\(encodedID)") + let (data, http) = try await request("DELETE", path: "/api/vm/publications/\(encodedID)", teamID: scopeTeamID) try ensureOK(http, data: data) } } diff --git a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift new file mode 100644 index 000000000000..f184472bf7b3 --- /dev/null +++ b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift @@ -0,0 +1,137 @@ +import CmuxCloud +import Foundation +import Testing + +@Suite("Cloud port share service") +struct CloudPortShareServiceTests { + @Test("creates a link with the server default and waits until it serves") + func createsAndWaits() async throws { + let api = FakePublishing(created: publication(state: "provisioning"), verifyStates: ["provisioning", "active"]) + let link = try await service(api).share(vmID: "brave-otter", port: 8000, teamID: "team-1") + #expect(link.state == "active") + #expect(await api.calls == [ + "list team-1", + "create brave-otter:8000 team-1", + "verify pub-1 team-1", + "verify pub-1 team-1", + ]) + } + + @Test("reuses the port's existing link instead of creating another") + func reusesExisting() async throws { + let api = FakePublishing(listed: [ + publication(id: "other", port: 3000, state: "active"), + publication(id: "mine", state: "active"), + ]) + let link = try await service(api).share(vmID: "brave-otter", port: 8000, teamID: "team-1") + #expect(link.id == "mine") + #expect(await api.calls == ["list team-1"]) + } + + @Test("does not reuse a link that is being removed") + func skipsDisabling() async throws { + let api = FakePublishing( + listed: [publication(id: "old", state: "disabling")], + created: publication(id: "new", state: "active") + ) + let link = try await service(api).share(vmID: "brave-otter", port: 8000, teamID: nil) + #expect(link.id == "new") + } + + @Test("gives up with stillProvisioning once the waits run out") + func timesOut() async { + let api = FakePublishing(created: publication(state: "provisioning"), verifyStates: ["provisioning", "provisioning"]) + await #expect(throws: CloudPortShareError.stillProvisioning) { + _ = try await service(api, delays: [.seconds(1), .seconds(1)]).share(vmID: "brave-otter", port: 8000, teamID: nil) + } + } + + @Test("an unavailable link is an error, not a copied dead URL") + func unavailableFails() async { + let api = FakePublishing(created: publication(state: "unavailable")) + await #expect(throws: CloudPortShareError.unavailable(state: "unavailable")) { + _ = try await service(api).share(vmID: "brave-otter", port: 8000, teamID: nil) + } + } + + @Test("waits past the edge's 503 before handing back an active link") + func waitsForEdge() async throws { + let api = FakePublishing(created: publication(state: "active")) + let statuses = Statuses([503, nil, 302]) + let link = try await service(api, probe: { _ in await statuses.next() }).share(vmID: "brave-otter", port: 8000, teamID: nil) + #expect(link.state == "active") + #expect(await statuses.remaining == 0) + } + + @Test("an edge that never answers is stillProvisioning, not a copied 503") + func edgeNeverReady() async { + let api = FakePublishing(created: publication(state: "active")) + await #expect(throws: CloudPortShareError.stillProvisioning) { + _ = try await service(api, delays: [.seconds(1)], probe: { _ in 503 }).share(vmID: "brave-otter", port: 8000, teamID: nil) + } + } + + private func service( + _ api: FakePublishing, + delays: [Duration] = [.seconds(1), .seconds(1), .seconds(1)], + probe: @escaping CloudPortShareService.Probe = { _ in 302 } + ) -> CloudPortShareService { + CloudPortShareService(api: api, pollDelays: delays, sleep: { _ in }, probe: probe) + } +} + +private func publication(id: String = "pub-1", port: Int = 8000, state: String) -> VMPublication { + VMPublication( + id: id, + hostname: "brave-otter--team--\(port).cmux.sh", + url: "https://brave-otter--team--\(port).cmux.sh", + domainKind: "managed", + vmID: "brave-otter", + port: port, + accessMode: .team, + teamID: "team-1", + state: state, + routingRevision: 1, + verification: nil + ) +} + +private actor Statuses { + private var values: [Int?] + init(_ values: [Int?]) { self.values = values } + var remaining: Int { values.count } + func next() -> Int? { values.isEmpty ? 302 : values.removeFirst() } +} + +private actor FakePublishing: CloudPortPublishing { + private(set) var calls: [String] = [] + private let listed: [VMPublication] + private let created: VMPublication? + private var verifyStates: [String] + + init(listed: [VMPublication] = [], created: VMPublication? = nil, verifyStates: [String] = []) { + self.listed = listed + self.created = created + self.verifyStates = verifyStates + } + + func listPublications(scopeTeamID: String?) async throws -> [VMPublication] { + calls.append("list \(scopeTeamID ?? "-")") + return listed + } + + func createDefaultPublication(vmID: String, port: Int, scopeTeamID: String?) async throws -> VMPublication { + calls.append("create \(vmID):\(port) \(scopeTeamID ?? "-")") + return created! + } + + func verifyPublication(id: String, scopeTeamID: String?) async throws -> VMPublication { + calls.append("verify \(id) \(scopeTeamID ?? "-")") + let state = verifyStates.isEmpty ? "active" : verifyStates.removeFirst() + return publication(id: id, state: state) + } + + func deletePublication(id: String, scopeTeamID: String?) async throws { + calls.append("delete \(id) \(scopeTeamID ?? "-")") + } +} diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 20e27d27aee4..36bbe9509554 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -618360,6 +618360,537 @@ } } } + }, + "cloudTree.port.share.error.timeout": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The link is still being set up. Try sharing again in a minute." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "لا يزال الرابط قيد الإعداد. حاول المشاركة مرة أخرى بعد دقيقة." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Der Link wird noch eingerichtet. Versuche es in einer Minute erneut." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "El enlace aún se está configurando. Vuelve a compartirlo en un minuto." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Le lien est encore en cours de configuration. Réessayez de le partager dans une minute." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "リンクはまだ準備中です。1分ほどしてからもう一度共有してください。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "링크를 아직 설정하는 중입니다. 1분 후에 다시 공유해 보세요." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "链接仍在设置中。请一分钟后再尝试共享。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "連結仍在設定中。請在一分鐘後再試著分享。" + } + } + } + }, + "cloudTree.port.share.error.unavailable": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The Cloud service couldn't create a link for this port. Try again." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "تعذّر على خدمة السحابة إنشاء رابط لهذا المنفذ. حاول مرة أخرى." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Der Cloud-Dienst konnte keinen Link für diesen Port erstellen. Versuche es erneut." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "El servicio Cloud no pudo crear un enlace para este puerto. Inténtalo de nuevo." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Le service Cloud n’a pas pu créer de lien pour ce port. Réessayez." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Cloud サービスでこのポートのリンクを作成できませんでした。もう一度お試しください。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "Cloud 서비스에서 이 포트의 링크를 만들지 못했습니다. 다시 시도하세요." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "Cloud 服务无法为此端口创建链接。请重试。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "Cloud 服務無法為此連接埠建立連結。請再試一次。" + } + } + } + }, + "cloudTree.menu.copyTeamLink": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Copy Team Link" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "نسخ رابط الفريق" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Team-Link kopieren" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Copiar enlace del equipo" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Copier le lien d’équipe" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "チームリンクをコピー" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "팀 링크 복사" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "复制团队链接" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "拷貝團隊連結" + } + } + } + }, + "cloudTree.port.share": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Share with Team" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "مشاركة مع الفريق" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Mit Team teilen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Compartir con el equipo" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Partager avec l’équipe" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "チームと共有" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "팀과 공유" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "与团队共享" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "與團隊分享" + } + } + } + }, + "cloudTree.port.share.copiedPersonal": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Link copied. Only you can open it." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "تم نسخ الرابط. يمكنك أنت فقط فتحه." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Link kopiert. Nur du kannst ihn öffnen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Enlace copiado. Solo tú puedes abrirlo." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Lien copié. Vous seul pouvez l’ouvrir." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "リンクをコピーしました。開けるのはあなただけです。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "링크를 복사했습니다. 나만 열 수 있습니다." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已复制链接。只有你可以打开。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已拷貝連結。只有你可以開啟。" + } + } + } + }, + "cloudTree.port.share.copiedPublic": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Link copied. Anyone with the link can open it." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "تم نسخ الرابط. يمكن لأي شخص لديه الرابط فتحه." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Link kopiert. Jeder mit dem Link kann ihn öffnen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Enlace copiado. Cualquiera con el enlace puede abrirlo." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Lien copié. Toute personne disposant du lien peut l’ouvrir." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "リンクをコピーしました。リンクを知っている人なら誰でも開けます。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "링크를 복사했습니다. 링크가 있는 누구나 열 수 있습니다." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已复制链接。任何拥有链接的人都可以打开。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已拷貝連結。任何擁有連結的人都可以開啟。" + } + } + } + }, + "cloudTree.port.share.copiedTeam": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Link copied. Your team can open it after signing in." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "تم نسخ الرابط. يمكن لفريقك فتحه بعد تسجيل الدخول." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Link kopiert. Dein Team kann ihn nach der Anmeldung öffnen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Enlace copiado. Tu equipo puede abrirlo después de iniciar sesión." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Lien copié. Votre équipe peut l’ouvrir après s’être connectée." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "リンクをコピーしました。チームのメンバーはサインイン後に開けます。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "링크를 복사했습니다. 팀원은 로그인한 후 열 수 있습니다." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已复制链接。你的团队登录后即可打开。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已拷貝連結。你的團隊登入後即可開啟。" + } + } + } + }, + "cloudTree.port.share.creating": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Creating link…" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "جارٍ إنشاء الرابط…" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Link wird erstellt…" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Creando el enlace…" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Création du lien…" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "リンクを作成しています…" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "링크를 만드는 중…" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "正在创建链接…" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "正在建立連結…" + } + } + } + }, + "cloudTree.port.share.failed": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Couldn't create link" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "تعذّر إنشاء الرابط" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Link konnte nicht erstellt werden" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudo crear el enlace" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Impossible de créer le lien" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "リンクを作成できませんでした" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "링크를 만들 수 없음" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "无法创建链接" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "無法建立連結" + } + } + } } }, "version": "1.0" diff --git a/Sources/Cloud/CloudTreeNodeActions.swift b/Sources/Cloud/CloudTreeNodeActions.swift index 690b252da077..6b799e17bf7b 100644 --- a/Sources/Cloud/CloudTreeNodeActions.swift +++ b/Sources/Cloud/CloudTreeNodeActions.swift @@ -62,6 +62,9 @@ struct CloudTreeNodeActions { let copyToPasteboard: @MainActor (_ text: String) -> Void /// Copy the machine port's private URL without changing network state. let copyPortLink: @MainActor (_ resource: SurfaceResourceID) -> Void + /// Copy a link to the port that teammates can open after signing in, + /// creating it first when the port has none. + var sharePort: @MainActor (_ resource: SurfaceResourceID) -> Void = { _ in } let refresh: @MainActor () -> Void var discoverPorts: @MainActor (SurfaceMachineID) -> Void = { _ in } var setDeviceDiscovery: @MainActor (Bool) -> Void = { _ in } @@ -595,6 +598,44 @@ struct CloudTreeNodeActions { operationController: operationController ?? AppDelegate.shared?.cloudWorkspaceOperationController ) actions.openRemoteTerminal = { navigation.open(machine: $0, group: $1, resource: $2, view: $3, openIn: $4) } + actions.sharePort = { resource in + guard let port = resource.forwardedPort else { return } + let store = CloudPortShareStore.shared + let key = CloudPortShareStore.Key(machineID: resource.machine.rawValue, port: port) + guard !store.isCreating(key) else { return } + store.set(.creating, for: key) + run( + String(localized: "cloudTree.port.share.creating", defaultValue: "Creating link\u{2026}"), + { catalog in + do { + guard let provider = catalog.provider(for: resource.machine) as? CmuxTuiSurfaceProvider, + let client = VMClient.shared else { + throw SurfaceCatalogError.unsupported(SurfaceCatalog.portPreviewUnavailableMessage(machineID: resource.machine.rawValue)) + } + let publication = try await CloudPortShareService(api: client) + .share(vmID: provider.machineID, port: port, teamID: provider.ownerTeamID) + Self.copyToPasteboard(publication.url) + store.set(.copied(publication.accessMode), for: key, holdFor: .seconds(2)) + } catch is CancellationError { + store.clear(key) + throw CancellationError() + } catch { + store.set(.failed, for: key, holdFor: .seconds(4)) + throw error + } + }, + failureDescription: { error in + switch error as? CloudPortShareError { + case .stillProvisioning: + return String(localized: "cloudTree.port.share.error.timeout", defaultValue: "The link is still being set up. Try sharing again in a minute.") + case .unavailable: + return String(localized: "cloudTree.port.share.error.unavailable", defaultValue: "The Cloud service couldn't create a link for this port. Try again.") + case nil: + return (error as? LocalizedError)?.errorDescription ?? String(describing: error) + } + } + ) + } return actions } @MainActor diff --git a/Sources/Cloud/CloudTreeOutlineView.swift b/Sources/Cloud/CloudTreeOutlineView.swift index 0775f6a1b5f8..8fb62b7207a3 100644 --- a/Sources/Cloud/CloudTreeOutlineView.swift +++ b/Sources/Cloud/CloudTreeOutlineView.swift @@ -890,6 +890,9 @@ struct CloudTreeOutlineView: NSViewRepresentable { if resource.id.isForwardedPort, !isLocal { // Copying the private URL never creates a forward. items.append(item(String(localized: "cloudTree.menu.copyPrivateURL", defaultValue: "Copy Private Address URL")) { [nodeActions] in nodeActions.copyPortLink(resource.id) }) + if CloudTreeRowHoverButtons.shareablePort(resource) != nil { + items.append(item(String(localized: "cloudTree.menu.copyTeamLink", defaultValue: "Copy Team Link")) { [nodeActions] in nodeActions.sharePort(resource.id) }) + } } else if let portURL { items.append(item(String(localized: "cloudTree.menu.copyLink", defaultValue: "Copy Link")) { [nodeActions] in nodeActions.copyToPasteboard(portURL) }) } else if let port = resource.port, resource.kind == .browser { diff --git a/Sources/Cloud/CloudTreeRowHoverButtons.swift b/Sources/Cloud/CloudTreeRowHoverButtons.swift index 488787cb1b06..0a4dc3ee47d2 100644 --- a/Sources/Cloud/CloudTreeRowHoverButtons.swift +++ b/Sources/Cloud/CloudTreeRowHoverButtons.swift @@ -1,4 +1,5 @@ import CmuxCloud +import CmuxSurfaceCatalogModel import SwiftUI struct CloudTreeRowHoverButtons: View { @@ -112,6 +113,15 @@ struct CloudTreeRowHoverButtons: View { nodeActions.closeTerminal(row.resource.id) } } + case .port(let resource, _, _): + if let port = Self.shareablePort(resource) { + CloudPortShareButton( + key: CloudPortShareStore.Key(machineID: resource.machine.rawValue, port: port), + store: CloudPortShareStore.shared + ) { + nodeActions.sharePort(resource.id) + } + } default: EmptyView() } @@ -130,11 +140,19 @@ struct CloudTreeRowHoverButtons: View { return row.canCreateWorkspacesAndTerminals case .terminal(let row): return !row.resource.machine.isLocal + case .port(let resource, _, _): + return shareablePort(resource) != nil default: return false } } + /// A Cloud machine's forwarded port can be shared; This Mac and SSH hosts can't. + static func shareablePort(_ resource: SurfaceResource) -> Int? { + guard resource.machine.cloudMachineID != nil else { return nil } + return resource.id.forwardedPort + } + /// True when the row's buttons stay visible without hover. Machine rows /// keep + and ⋯ on screen so their actions are discoverable at rest. static func showsAtRest(for kind: CloudTreeNode.Kind) -> Bool { @@ -160,6 +178,51 @@ struct CloudTreeRowHoverButtons: View { } } +/// Share on a Cloud port row: a spinner while the link is made, a checkmark +/// once it is on the clipboard. +private struct CloudPortShareButton: View { + let key: CloudPortShareStore.Key + @ObservedObject var store: CloudPortShareStore + let action: () -> Void + + var body: some View { + let phase = store.phase(for: key) + MachinesChromeIconButton( + symbolName: symbolName(phase), + accessibilityLabel: label(phase), + isBusy: phase == .creating, + action: action + ) + .help(label(phase)) + .accessibilityIdentifier("CloudPortShareButton") + } + + private func symbolName(_ phase: CloudPortShareStore.Phase?) -> String { + switch phase { + case .copied: return "checkmark" + case .failed: return "exclamationmark.triangle" + case .creating, nil: return "square.and.arrow.up" + } + } + + private func label(_ phase: CloudPortShareStore.Phase?) -> String { + switch phase { + case .creating: + return String(localized: "cloudTree.port.share.creating", defaultValue: "Creating link\u{2026}") + case .copied(.team): + return String(localized: "cloudTree.port.share.copiedTeam", defaultValue: "Link copied. Your team can open it after signing in.") + case .copied(.personal): + return String(localized: "cloudTree.port.share.copiedPersonal", defaultValue: "Link copied. Only you can open it.") + case .copied(.public): + return String(localized: "cloudTree.port.share.copiedPublic", defaultValue: "Link copied. Anyone with the link can open it.") + case .failed: + return String(localized: "cloudTree.port.share.failed", defaultValue: "Couldn't create link") + case nil: + return String(localized: "cloudTree.port.share", defaultValue: "Share with Team") + } + } +} + /// The My Devices header's "..." menu. Same size, tint and hover fill as the /// Cloud Machines "+" (`MachinesChromeIconButton`), so both headers hover alike. private struct CloudTreeDevicesMenuButton: View { From 421664f85d832fce7fa89d2d70594daa31460f66 Mon Sep 17 00:00:00 2001 From: Lucas Ribeiro Date: Sat, 3 Oct 2026 18:33:10 +1300 Subject: [PATCH 03/36] cloud: port share button always visible, link icon, inline copied note the share button stays on cloud port rows at rest, uses the link symbol, and shows creating link / copied to clipboard beside it. the readiness check is now a signed-out POST on protected links only: cmux answers 401 without minting a sign-in transaction, and public links aren't probed since that would hit the user's app. --- .../VMClient/CloudPortShareService.swift | 15 +++-- .../CloudPortShareServiceTests.swift | 19 +++++- Resources/Localizable.xcstrings | 59 +++++++++++++++++++ Sources/Cloud/CloudTreeRowHoverButtons.swift | 52 ++++++++++++---- 4 files changed, 126 insertions(+), 19 deletions(-) diff --git a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift index 20b2a7359db0..56b16fd71efe 100644 --- a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift +++ b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift @@ -35,8 +35,8 @@ public enum CloudPortShareError: Error, Equatable, Sendable { /// it serves before handing it back, so a copied link is never a dead one. public struct CloudPortShareService: Sendable { public typealias Sleep = @Sendable (Duration) async throws -> Void - /// Opens the link once as a signed-out visitor and returns the HTTP - /// status, or nil when the edge could not be reached. + /// Asks the link once, signed out, whether the edge can serve it, and + /// returns the HTTP status, or nil when the edge could not be reached. public typealias Probe = @Sendable (URL) async -> Int? /// Waits between readiness checks. Creation provisions the route right @@ -86,6 +86,9 @@ public struct CloudPortShareService: Sendable { while true { switch publication.state { case "active": + // Only protected links can be probed without side effects; a + // public link would send the request to the user's app. + guard publication.accessMode != .public else { return publication } if let url = URL(string: publication.url), let status = await probe(url), status < 500 { return publication } @@ -106,8 +109,10 @@ public struct CloudPortShareService: Sendable { try await api.deletePublication(id: publicationID, scopeTeamID: teamID) } - /// A signed-out GET that doesn't follow redirects: a protected link answers - /// with its sign-in redirect (302) or 401/403, a public one with the app. + /// A signed-out POST to a protected link. cmux's authorization check + /// answers it with 401 without starting a sign-in or reaching the machine, + /// so a 401 means the edge and its check are both serving; the edge's own + /// 503 means they aren't yet. public static let signedOutStatus: Probe = { url in let configuration = URLSessionConfiguration.ephemeral configuration.timeoutIntervalForRequest = 10 @@ -116,7 +121,7 @@ public struct CloudPortShareService: Sendable { let session = URLSession(configuration: configuration, delegate: NoRedirects(), delegateQueue: nil) defer { session.finishTasksAndInvalidate() } var request = URLRequest(url: url) - request.httpMethod = "GET" + request.httpMethod = "POST" guard let (_, response) = try? await session.data(for: request) else { return nil } return (response as? HTTPURLResponse)?.statusCode } diff --git a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift index f184472bf7b3..8872de1c73c3 100644 --- a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift +++ b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift @@ -71,6 +71,14 @@ struct CloudPortShareServiceTests { } } + @Test("a public link is never probed, since the probe would reach the user's app") + func publicSkipsProbe() async throws { + let api = FakePublishing(created: publication(state: "active", access: .public)) + let link = try await service(api, probe: { _ in Issue.record("probed a public link"); return 503 }) + .share(vmID: "brave-otter", port: 8000, teamID: nil) + #expect(link.accessMode == .public) + } + private func service( _ api: FakePublishing, delays: [Duration] = [.seconds(1), .seconds(1), .seconds(1)], @@ -80,7 +88,12 @@ struct CloudPortShareServiceTests { } } -private func publication(id: String = "pub-1", port: Int = 8000, state: String) -> VMPublication { +private func publication( + id: String = "pub-1", + port: Int = 8000, + state: String, + access: VMPublicationAccessMode = .team +) -> VMPublication { VMPublication( id: id, hostname: "brave-otter--team--\(port).cmux.sh", @@ -88,8 +101,8 @@ private func publication(id: String = "pub-1", port: Int = 8000, state: String) domainKind: "managed", vmID: "brave-otter", port: port, - accessMode: .team, - teamID: "team-1", + accessMode: access, + teamID: access == .team ? "team-1" : nil, state: state, routingRevision: 1, verification: nil diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 36bbe9509554..bbaa5e382471 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -618891,6 +618891,65 @@ } } } + }, + "cloudTree.port.share.copied": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Copied to clipboard" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "تم النسخ إلى الحافظة" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "In die Zwischenablage kopiert" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Copiado al portapapeles" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Copié dans le presse-papiers" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "クリップボードにコピーしました" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "클립보드에 복사됨" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已复制到剪贴板" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已拷貝到剪貼板" + } + } + } } }, "version": "1.0" diff --git a/Sources/Cloud/CloudTreeRowHoverButtons.swift b/Sources/Cloud/CloudTreeRowHoverButtons.swift index 0a4dc3ee47d2..d2816eca93b0 100644 --- a/Sources/Cloud/CloudTreeRowHoverButtons.swift +++ b/Sources/Cloud/CloudTreeRowHoverButtons.swift @@ -156,8 +156,15 @@ struct CloudTreeRowHoverButtons: View { /// True when the row's buttons stay visible without hover. Machine rows /// keep + and ⋯ on screen so their actions are discoverable at rest. static func showsAtRest(for kind: CloudTreeNode.Kind) -> Bool { - if case .machine = kind { return true } - return false + switch kind { + case .machine: + return true + case .port(let resource, _, _): + // Sharing is the port row's main action, so it stays discoverable. + return shareablePort(resource) != nil + default: + return false + } } /// The Displays affordance remains visible while guest discovery is pending @@ -187,21 +194,44 @@ private struct CloudPortShareButton: View { var body: some View { let phase = store.phase(for: key) - MachinesChromeIconButton( - symbolName: symbolName(phase), - accessibilityLabel: label(phase), - isBusy: phase == .creating, - action: action - ) - .help(label(phase)) - .accessibilityIdentifier("CloudPortShareButton") + HStack(spacing: 2) { + if let status = status(phase) { + Text(status) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .lineLimit(1) + .transition(.opacity) + } + MachinesChromeIconButton( + symbolName: symbolName(phase), + accessibilityLabel: label(phase), + isBusy: phase == .creating, + action: action + ) + .help(label(phase)) + .accessibilityIdentifier("CloudPortShareButton") + } + .animation(.easeOut(duration: 0.15), value: phase) } private func symbolName(_ phase: CloudPortShareStore.Phase?) -> String { switch phase { case .copied: return "checkmark" case .failed: return "exclamationmark.triangle" - case .creating, nil: return "square.and.arrow.up" + case .creating, nil: return "link" + } + } + + /// The short inline note beside the button while sharing runs and right + /// after the link lands on the clipboard. + private func status(_ phase: CloudPortShareStore.Phase?) -> String? { + switch phase { + case .creating: + return String(localized: "cloudTree.port.share.creating", defaultValue: "Creating link\u{2026}") + case .copied: + return String(localized: "cloudTree.port.share.copied", defaultValue: "Copied to clipboard") + case .failed, nil: + return nil } } From b963458ea684f7cd2a36252970219b1eb6772011 Mon Sep 17 00:00:00 2001 From: Lucas Ribeiro Date: Sat, 3 Oct 2026 19:25:23 +1300 Subject: [PATCH 04/36] cloud: neutral share labels, keep the copied note visible copy share link / share link instead of team wording, since a personal machine's link is owner-only; the note after copying still says who can open it. the inline note is fixed size so the controls host can't squeeze it to nothing. --- Resources/Localizable.xcstrings | 160 +++++++++---------- Sources/Cloud/CloudTreeOutlineView.swift | 2 +- Sources/Cloud/CloudTreeRowHoverButtons.swift | 7 +- 3 files changed, 87 insertions(+), 82 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index bbaa5e382471..31e9f92c45a1 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -618479,474 +618479,474 @@ } } }, - "cloudTree.menu.copyTeamLink": { + "cloudTree.port.share.copiedPersonal": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Copy Team Link" + "value": "Link copied. Only you can open it." } }, "ar": { "stringUnit": { "state": "translated", - "value": "نسخ رابط الفريق" + "value": "تم نسخ الرابط. يمكنك أنت فقط فتحه." } }, "de": { "stringUnit": { "state": "translated", - "value": "Team-Link kopieren" + "value": "Link kopiert. Nur du kannst ihn öffnen." } }, "es": { "stringUnit": { "state": "translated", - "value": "Copiar enlace del equipo" + "value": "Enlace copiado. Solo tú puedes abrirlo." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Copier le lien d’équipe" + "value": "Lien copié. Vous seul pouvez l’ouvrir." } }, "ja": { "stringUnit": { "state": "translated", - "value": "チームリンクをコピー" + "value": "リンクをコピーしました。開けるのはあなただけです。" } }, "ko": { "stringUnit": { "state": "translated", - "value": "팀 링크 복사" + "value": "링크를 복사했습니다. 나만 열 수 있습니다." } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "复制团队链接" + "value": "已复制链接。只有你可以打开。" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "拷貝團隊連結" + "value": "已拷貝連結。只有你可以開啟。" } } } }, - "cloudTree.port.share": { + "cloudTree.port.share.copiedPublic": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Share with Team" + "value": "Link copied. Anyone with the link can open it." } }, "ar": { "stringUnit": { "state": "translated", - "value": "مشاركة مع الفريق" + "value": "تم نسخ الرابط. يمكن لأي شخص لديه الرابط فتحه." } }, "de": { "stringUnit": { "state": "translated", - "value": "Mit Team teilen" + "value": "Link kopiert. Jeder mit dem Link kann ihn öffnen." } }, "es": { "stringUnit": { "state": "translated", - "value": "Compartir con el equipo" + "value": "Enlace copiado. Cualquiera con el enlace puede abrirlo." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Partager avec l’équipe" + "value": "Lien copié. Toute personne disposant du lien peut l’ouvrir." } }, "ja": { "stringUnit": { "state": "translated", - "value": "チームと共有" + "value": "リンクをコピーしました。リンクを知っている人なら誰でも開けます。" } }, "ko": { "stringUnit": { "state": "translated", - "value": "팀과 공유" + "value": "링크를 복사했습니다. 링크가 있는 누구나 열 수 있습니다." } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "与团队共享" + "value": "已复制链接。任何拥有链接的人都可以打开。" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "與團隊分享" + "value": "已拷貝連結。任何擁有連結的人都可以開啟。" } } } }, - "cloudTree.port.share.copiedPersonal": { + "cloudTree.port.share.copiedTeam": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Link copied. Only you can open it." + "value": "Link copied. Your team can open it after signing in." } }, "ar": { "stringUnit": { "state": "translated", - "value": "تم نسخ الرابط. يمكنك أنت فقط فتحه." + "value": "تم نسخ الرابط. يمكن لفريقك فتحه بعد تسجيل الدخول." } }, "de": { "stringUnit": { "state": "translated", - "value": "Link kopiert. Nur du kannst ihn öffnen." + "value": "Link kopiert. Dein Team kann ihn nach der Anmeldung öffnen." } }, "es": { "stringUnit": { "state": "translated", - "value": "Enlace copiado. Solo tú puedes abrirlo." + "value": "Enlace copiado. Tu equipo puede abrirlo después de iniciar sesión." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Lien copié. Vous seul pouvez l’ouvrir." + "value": "Lien copié. Votre équipe peut l’ouvrir après s’être connectée." } }, "ja": { "stringUnit": { "state": "translated", - "value": "リンクをコピーしました。開けるのはあなただけです。" + "value": "リンクをコピーしました。チームのメンバーはサインイン後に開けます。" } }, "ko": { "stringUnit": { "state": "translated", - "value": "링크를 복사했습니다. 나만 열 수 있습니다." + "value": "링크를 복사했습니다. 팀원은 로그인한 후 열 수 있습니다." } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "已复制链接。只有你可以打开。" + "value": "已复制链接。你的团队登录后即可打开。" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "已拷貝連結。只有你可以開啟。" + "value": "已拷貝連結。你的團隊登入後即可開啟。" } } } }, - "cloudTree.port.share.copiedPublic": { + "cloudTree.port.share.creating": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Link copied. Anyone with the link can open it." + "value": "Creating link…" } }, "ar": { "stringUnit": { "state": "translated", - "value": "تم نسخ الرابط. يمكن لأي شخص لديه الرابط فتحه." + "value": "جارٍ إنشاء الرابط…" } }, "de": { "stringUnit": { "state": "translated", - "value": "Link kopiert. Jeder mit dem Link kann ihn öffnen." + "value": "Link wird erstellt…" } }, "es": { "stringUnit": { "state": "translated", - "value": "Enlace copiado. Cualquiera con el enlace puede abrirlo." + "value": "Creando el enlace…" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Lien copié. Toute personne disposant du lien peut l’ouvrir." + "value": "Création du lien…" } }, "ja": { "stringUnit": { "state": "translated", - "value": "リンクをコピーしました。リンクを知っている人なら誰でも開けます。" + "value": "リンクを作成しています…" } }, "ko": { "stringUnit": { "state": "translated", - "value": "링크를 복사했습니다. 링크가 있는 누구나 열 수 있습니다." + "value": "링크를 만드는 중…" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "已复制链接。任何拥有链接的人都可以打开。" + "value": "正在创建链接…" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "已拷貝連結。任何擁有連結的人都可以開啟。" + "value": "正在建立連結…" } } } }, - "cloudTree.port.share.copiedTeam": { + "cloudTree.port.share.failed": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Link copied. Your team can open it after signing in." + "value": "Couldn't create link" } }, "ar": { "stringUnit": { "state": "translated", - "value": "تم نسخ الرابط. يمكن لفريقك فتحه بعد تسجيل الدخول." + "value": "تعذّر إنشاء الرابط" } }, "de": { "stringUnit": { "state": "translated", - "value": "Link kopiert. Dein Team kann ihn nach der Anmeldung öffnen." + "value": "Link konnte nicht erstellt werden" } }, "es": { "stringUnit": { "state": "translated", - "value": "Enlace copiado. Tu equipo puede abrirlo después de iniciar sesión." + "value": "No se pudo crear el enlace" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Lien copié. Votre équipe peut l’ouvrir après s’être connectée." + "value": "Impossible de créer le lien" } }, "ja": { "stringUnit": { "state": "translated", - "value": "リンクをコピーしました。チームのメンバーはサインイン後に開けます。" + "value": "リンクを作成できませんでした" } }, "ko": { "stringUnit": { "state": "translated", - "value": "링크를 복사했습니다. 팀원은 로그인한 후 열 수 있습니다." + "value": "링크를 만들 수 없음" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "已复制链接。你的团队登录后即可打开。" + "value": "无法创建链接" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "已拷貝連結。你的團隊登入後即可開啟。" + "value": "無法建立連結" } } } }, - "cloudTree.port.share.creating": { + "cloudTree.port.share.copied": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Creating link…" + "value": "Copied to clipboard" } }, "ar": { "stringUnit": { "state": "translated", - "value": "جارٍ إنشاء الرابط…" + "value": "تم النسخ إلى الحافظة" } }, "de": { "stringUnit": { "state": "translated", - "value": "Link wird erstellt…" + "value": "In die Zwischenablage kopiert" } }, "es": { "stringUnit": { "state": "translated", - "value": "Creando el enlace…" + "value": "Copiado al portapapeles" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Création du lien…" + "value": "Copié dans le presse-papiers" } }, "ja": { "stringUnit": { "state": "translated", - "value": "リンクを作成しています…" + "value": "クリップボードにコピーしました" } }, "ko": { "stringUnit": { "state": "translated", - "value": "링크를 만드는 중…" + "value": "클립보드에 복사됨" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "正在创建链接…" + "value": "已复制到剪贴板" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "正在建立連結…" + "value": "已拷貝到剪貼板" } } } }, - "cloudTree.port.share.failed": { + "cloudTree.menu.copyShareLink": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Couldn't create link" + "value": "Copy Share Link" } }, "ar": { "stringUnit": { "state": "translated", - "value": "تعذّر إنشاء الرابط" + "value": "نسخ رابط المشاركة" } }, "de": { "stringUnit": { "state": "translated", - "value": "Link konnte nicht erstellt werden" + "value": "Freigabelink kopieren" } }, "es": { "stringUnit": { "state": "translated", - "value": "No se pudo crear el enlace" + "value": "Copiar enlace para compartir" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Impossible de créer le lien" + "value": "Copier le lien de partage" } }, "ja": { "stringUnit": { "state": "translated", - "value": "リンクを作成できませんでした" + "value": "共有リンクをコピー" } }, "ko": { "stringUnit": { "state": "translated", - "value": "링크를 만들 수 없음" + "value": "공유 링크 복사" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "无法创建链接" + "value": "复制共享链接" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "無法建立連結" + "value": "拷貝分享連結" } } } }, - "cloudTree.port.share.copied": { + "cloudTree.port.shareLink": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Copied to clipboard" + "value": "Share Link" } }, "ar": { "stringUnit": { "state": "translated", - "value": "تم النسخ إلى الحافظة" + "value": "مشاركة الرابط" } }, "de": { "stringUnit": { "state": "translated", - "value": "In die Zwischenablage kopiert" + "value": "Link teilen" } }, "es": { "stringUnit": { "state": "translated", - "value": "Copiado al portapapeles" + "value": "Compartir enlace" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Copié dans le presse-papiers" + "value": "Partager le lien" } }, "ja": { "stringUnit": { "state": "translated", - "value": "クリップボードにコピーしました" + "value": "リンクを共有" } }, "ko": { "stringUnit": { "state": "translated", - "value": "클립보드에 복사됨" + "value": "링크 공유" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "已复制到剪贴板" + "value": "共享链接" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "已拷貝到剪貼板" + "value": "分享連結" } } } diff --git a/Sources/Cloud/CloudTreeOutlineView.swift b/Sources/Cloud/CloudTreeOutlineView.swift index 8fb62b7207a3..906126b21adc 100644 --- a/Sources/Cloud/CloudTreeOutlineView.swift +++ b/Sources/Cloud/CloudTreeOutlineView.swift @@ -891,7 +891,7 @@ struct CloudTreeOutlineView: NSViewRepresentable { // Copying the private URL never creates a forward. items.append(item(String(localized: "cloudTree.menu.copyPrivateURL", defaultValue: "Copy Private Address URL")) { [nodeActions] in nodeActions.copyPortLink(resource.id) }) if CloudTreeRowHoverButtons.shareablePort(resource) != nil { - items.append(item(String(localized: "cloudTree.menu.copyTeamLink", defaultValue: "Copy Team Link")) { [nodeActions] in nodeActions.sharePort(resource.id) }) + items.append(item(String(localized: "cloudTree.menu.copyShareLink", defaultValue: "Copy Share Link")) { [nodeActions] in nodeActions.sharePort(resource.id) }) } } else if let portURL { items.append(item(String(localized: "cloudTree.menu.copyLink", defaultValue: "Copy Link")) { [nodeActions] in nodeActions.copyToPasteboard(portURL) }) diff --git a/Sources/Cloud/CloudTreeRowHoverButtons.swift b/Sources/Cloud/CloudTreeRowHoverButtons.swift index d2816eca93b0..2c9dbb82bc52 100644 --- a/Sources/Cloud/CloudTreeRowHoverButtons.swift +++ b/Sources/Cloud/CloudTreeRowHoverButtons.swift @@ -196,10 +196,15 @@ private struct CloudPortShareButton: View { let phase = store.phase(for: key) HStack(spacing: 2) { if let status = status(phase) { + // The row's content keeps its trailing edge at just below + // required priority, so the controls host shrinks to its + // minimum width; a fixed-size note keeps that minimum honest + // instead of truncating to nothing. Text(status) .font(.system(size: 11)) .foregroundStyle(.secondary) .lineLimit(1) + .fixedSize() .transition(.opacity) } MachinesChromeIconButton( @@ -248,7 +253,7 @@ private struct CloudPortShareButton: View { case .failed: return String(localized: "cloudTree.port.share.failed", defaultValue: "Couldn't create link") case nil: - return String(localized: "cloudTree.port.share", defaultValue: "Share with Team") + return String(localized: "cloudTree.port.shareLink", defaultValue: "Share Link") } } } From 75704a712b831b5f49582da2319b16cd0be21d84 Mon Sep 17 00:00:00 2001 From: Lucas Ribeiro Date: Sat, 3 Oct 2026 19:31:55 +1300 Subject: [PATCH 05/36] web: name the forward-auth origin in its validation error, document it in .env.example --- web/.env.example | 3 +++ web/app/env.ts | 8 +++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/web/.env.example b/web/.env.example index 041ae661a37f..5528f12b755c 100644 --- a/web/.env.example +++ b/web/.env.example @@ -182,6 +182,9 @@ FREESTYLE_API_KEY= CMUX_VM_PUBLICATION_FORWARD_AUTH_SECRET= # Canonical HTTPS CMUX origin used for protected-domain browser sign-in. CMUX_VM_PUBLICATION_AUTH_ORIGIN=https://cmux.com +# Optional origin Freestyle calls for forward-auth when it can't reach the auth origin, +# e.g. a tunnel to a tailnet-only development stack. Leave unset in production. +CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN= # Zone for generated Cloud VM publication hostnames (.). The CMUX Freestyle # account must own it: verify the zone, CNAME `*` to beta-web.freestyle.sh, delegate # `_acme-challenge` to beta-dns.freestyle.sh, and request its wildcard certificate. diff --git a/web/app/env.ts b/web/app/env.ts index 3febc7f61ca1..c95a78ea3b2b 100644 --- a/web/app/env.ts +++ b/web/app/env.ts @@ -126,7 +126,7 @@ const irohMinterUrl = z.string().url().superRefine((value, context) => { }); } }); -const publicationAuthOrigin = z.string().url().superRefine((value, context) => { +const bareHttpsOrigin = (name: string) => z.string().url().superRefine((value, context) => { let parsed: URL | null = null; try { parsed = new URL(value); @@ -146,10 +146,12 @@ const publicationAuthOrigin = z.string().url().superRefine((value, context) => { context.addIssue({ code: z.ZodIssueCode.custom, message: - "CMUX_VM_PUBLICATION_AUTH_ORIGIN must be a bare https:// origin with no path, query, or credentials", + `${name} must be a bare https:// origin with no path, query, or credentials`, }); } }); +const publicationAuthOrigin = bareHttpsOrigin("CMUX_VM_PUBLICATION_AUTH_ORIGIN"); +const publicationForwardAuthOrigin = bareHttpsOrigin("CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN"); const irohBindingLimit = z.string().regex(/^[1-9][0-9]{0,3}$/).superRefine((value, context) => { if (Number(value) > 4_096) { context.addIssue({ @@ -335,7 +337,7 @@ export const env = createEnv({ // Optional origin Freestyle calls for forward-auth when it differs from // the sign-in origin, e.g. a tunnel to a development stack the edge can't // reach. Unset in production: the auth origin serves both. - CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN: publicationAuthOrigin.optional(), + CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN: publicationForwardAuthOrigin.optional(), // Zone generated Cloud VM publication hostnames are minted under // (.). The CMUX Freestyle account must own it: verify the // zone, CNAME `*` to the Freestyle edge, delegate `_acme-challenge`, and From 04744178468d91ded2211c19e26e798c1858d8ea Mon Sep 17 00:00:00 2001 From: Lucas Ribeiro Date: Sat, 3 Oct 2026 19:38:02 +1300 Subject: [PATCH 06/36] cloud: port share review fixes - only reuse cmux-generated links; a custom domain on the port is left alone - poll by creating again (idempotent, resumes provisioning or unavailable rows, works on a teammate's row); 409 removing and 503 busy just mean not yet - probe accepts only 2xx/3xx or the forward-auth 401, total wait about a minute - don't overwrite the clipboard if it changed while the link was made; show link ready and copy on the next click - sidebar gets plain error copy instead of the cli wording from the server - store is @Observable with an injected sleep for its auto-dismiss - note swaps without animation so it can't slide under the row - tests for the store and the new paths (12 pass) --- .../VMClient/CloudPortShareService.swift | 88 ++++++----- .../VMClient/CloudPortShareStore.swift | 26 +++- .../CloudPortShareServiceTests.swift | 146 +++++++++++++----- Resources/Localizable.xcstrings | 118 ++++++++++++++ Sources/Cloud/CloudTreeNodeActions.swift | 31 +++- Sources/Cloud/CloudTreeRowHoverButtons.swift | 14 +- 6 files changed, 324 insertions(+), 99 deletions(-) diff --git a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift index 56b16fd71efe..1f8d39abb177 100644 --- a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift +++ b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift @@ -5,13 +5,15 @@ import Foundation public protocol CloudPortPublishing: Sendable { func listPublications(scopeTeamID: String?) async throws -> [VMPublication] func createDefaultPublication(vmID: String, port: Int, scopeTeamID: String?) async throws -> VMPublication - func verifyPublication(id: String, scopeTeamID: String?) async throws -> VMPublication func deletePublication(id: String, scopeTeamID: String?) async throws } extension VMClient: CloudPortPublishing { /// No access mode and no team: the server picks team access for a team - /// machine and owner-only access for a personal one. + /// machine and owner-only access for a personal one. Repeating it is safe: + /// the generated hostname is fixed per machine and port, so the server + /// returns the existing row and resumes provisioning it, including a row a + /// teammate created. public func createDefaultPublication(vmID: String, port: Int, scopeTeamID: String?) async throws -> VMPublication { try await createPublication( vmID: vmID, @@ -25,26 +27,27 @@ extension VMClient: CloudPortPublishing { } public enum CloudPortShareError: Error, Equatable, Sendable { - /// The link exists but its route never became ready within the wait. + /// The link exists but did not start serving within the wait. case stillProvisioning - /// The service reports the publication can't serve (for example `unavailable`). - case unavailable(state: String) } /// Finds or creates the shareable link for one machine port, and waits until /// it serves before handing it back, so a copied link is never a dead one. +/// +/// The wait polls because the service has no push channel for publication +/// readiness; the delays and the sleep are injected so tests run without real +/// time. public struct CloudPortShareService: Sendable { public typealias Sleep = @Sendable (Duration) async throws -> Void /// Asks the link once, signed out, whether the edge can serve it, and /// returns the HTTP status, or nil when the edge could not be reached. public typealias Probe = @Sendable (URL) async -> Int? - /// Waits between readiness checks. Creation provisions the route right - /// away; the wait only covers the edge certificate catching up. + /// Waits between readiness checks, about a minute in total. Creation + /// provisions the route right away; the wait covers the edge catching up. public static let defaultPollDelays: [Duration] = [ - .seconds(1), .seconds(2), .seconds(3), .seconds(5), .seconds(5), - .seconds(10), .seconds(10), .seconds(15), .seconds(15), .seconds(15), - .seconds(15), .seconds(15), + .seconds(1), .seconds(2), .seconds(3), .seconds(4), .seconds(5), + .seconds(5), .seconds(10), .seconds(10), .seconds(10), .seconds(10), ] private let api: any CloudPortPublishing @@ -64,43 +67,38 @@ public struct CloudPortShareService: Sendable { self.probe = probe } - /// The live publication for this port, if there is one. + /// The live cmux-generated link for this port, if there is one. A custom + /// domain on the same port is left alone: it may still be waiting on the + /// user's DNS, and it isn't the link Share hands out. public func existing(vmID: String, port: Int, teamID: String?) async throws -> VMPublication? { try await api.listPublications(scopeTeamID: teamID).first { - $0.vmID == vmID && $0.port == port && Self.isLive($0.state) + $0.vmID == vmID && $0.port == port && $0.domainKind == "generated" && Self.isLive($0.state) } } - /// Reuses the port's publication (whatever its access) or creates one with - /// the server's default access, then waits until the link itself answers: - /// `active` on the server can run ahead of the edge, which shows a 503 - /// page until its authorization check and route are ready. + /// Reuses the port's generated link (whatever its access) or creates one + /// with the server's default access, then waits until the link itself + /// answers: `active` on the server can run ahead of the edge, which shows + /// a 503 page until its authorization check and route are ready. public func share(vmID: String, port: Int, teamID: String?) async throws -> VMPublication { - var publication: VMPublication - if let found = try await existing(vmID: vmID, port: port, teamID: teamID) { - publication = found - } else { - publication = try await api.createDefaultPublication(vmID: vmID, port: port, scopeTeamID: teamID) - } var delays = pollDelays.makeIterator() + var publication = try await existing(vmID: vmID, port: port, teamID: teamID) while true { - switch publication.state { - case "active": - // Only protected links can be probed without side effects; a - // public link would send the request to the user's app. - guard publication.accessMode != .public else { return publication } - if let url = URL(string: publication.url), let status = await probe(url), status < 500 { - return publication + if publication?.state != "active" { + // Creating again resumes a provisioning or unavailable row. A + // row still being removed (409) or a busy provisioning lease + // (503) only means "not yet". + do { + publication = try await api.createDefaultPublication(vmID: vmID, port: port, scopeTeamID: teamID) + } catch VMClientError.httpStatus(let status, _) where status == 409 || status == 503 { + publication = nil } - guard let delay = delays.next() else { throw CloudPortShareError.stillProvisioning } - try await sleep(delay) - case "provisioning": - guard let delay = delays.next() else { throw CloudPortShareError.stillProvisioning } - try await sleep(delay) - publication = try await api.verifyPublication(id: publication.id, scopeTeamID: teamID) - default: - throw CloudPortShareError.unavailable(state: publication.state) } + if let current = publication, current.state == "active", await serves(current) { + return current + } + guard let delay = delays.next() else { throw CloudPortShareError.stillProvisioning } + try await sleep(delay) } } @@ -109,13 +107,21 @@ public struct CloudPortShareService: Sendable { try await api.deletePublication(id: publicationID, scopeTeamID: teamID) } + /// A public link would send the probe to the user's app, so it is taken as + /// is. A protected link must answer the signed-out probe the way cmux's + /// authorization check does (401), or serve or redirect; anything else, + /// such as the edge's 503 or a 404 for a route it doesn't know yet, waits. + private func serves(_ publication: VMPublication) async -> Bool { + guard publication.accessMode != .public else { return true } + guard let url = URL(string: publication.url), let status = await probe(url) else { return false } + return (200..<400).contains(status) || status == 401 + } + /// A signed-out POST to a protected link. cmux's authorization check - /// answers it with 401 without starting a sign-in or reaching the machine, - /// so a 401 means the edge and its check are both serving; the edge's own - /// 503 means they aren't yet. + /// answers it with 401 without starting a sign-in or reaching the machine. public static let signedOutStatus: Probe = { url in let configuration = URLSessionConfiguration.ephemeral - configuration.timeoutIntervalForRequest = 10 + configuration.timeoutIntervalForRequest = 5 configuration.httpCookieStorage = nil configuration.httpShouldSetCookies = false let session = URLSession(configuration: configuration, delegate: NoRedirects(), delegateQueue: nil) diff --git a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareStore.swift b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareStore.swift index 9c94ce204745..a4eccbeef066 100644 --- a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareStore.swift +++ b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareStore.swift @@ -1,13 +1,17 @@ -import Combine import Foundation +import Observation /// Per-port Share progress, so the port row can show a spinner while its link /// is being made and a checkmark once it has been copied. @MainActor -public final class CloudPortShareStore: ObservableObject { +@Observable +public final class CloudPortShareStore { public enum Phase: Equatable, Sendable { case creating case copied(VMPublicationAccessMode) + /// The link is ready but wasn't copied, because the clipboard changed + /// while it was being made. Clicking again copies it at once. + case ready case failed } @@ -20,12 +24,19 @@ public final class CloudPortShareStore: ObservableObject { } } + public typealias Sleep = @Sendable (Duration) async throws -> Void + public static let shared = CloudPortShareStore() - @Published public private(set) var phases: [Key: Phase] = [:] - private var resetTasks: [Key: Task] = [:] + public private(set) var phases: [Key: Phase] = [:] + @ObservationIgnored private var resetTasks: [Key: Task] = [:] + @ObservationIgnored private let sleep: Sleep - public init() {} + /// `sleep` times the auto-dismiss of a finished phase (a brief "copied" + /// note); it is injected so tests don't wait in real time. + public init(sleep: @escaping Sleep = { try await Task.sleep(for: $0) }) { + self.sleep = sleep + } public func phase(for key: Key) -> Phase? { phases[key] } @@ -37,9 +48,10 @@ public final class CloudPortShareStore: ObservableObject { resetTasks[key] = nil phases[key] = phase guard let holdFor else { return } + let sleep = sleep resetTasks[key] = Task { @MainActor [weak self] in - try? await Task.sleep(for: holdFor) - guard !Task.isCancelled, let self, self.phases[key] == phase else { return } + do { try await sleep(holdFor) } catch { return } + guard let self, self.phases[key] == phase else { return } self.phases[key] = nil self.resetTasks[key] = nil } diff --git a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift index 8872de1c73c3..99dcd400f838 100644 --- a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift +++ b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift @@ -6,18 +6,17 @@ import Testing struct CloudPortShareServiceTests { @Test("creates a link with the server default and waits until it serves") func createsAndWaits() async throws { - let api = FakePublishing(created: publication(state: "provisioning"), verifyStates: ["provisioning", "active"]) + let api = FakePublishing(creates: [.row(publication(state: "provisioning")), .row(publication(state: "active"))]) let link = try await service(api).share(vmID: "brave-otter", port: 8000, teamID: "team-1") #expect(link.state == "active") #expect(await api.calls == [ "list team-1", "create brave-otter:8000 team-1", - "verify pub-1 team-1", - "verify pub-1 team-1", + "create brave-otter:8000 team-1", ]) } - @Test("reuses the port's existing link instead of creating another") + @Test("reuses the port's existing generated link instead of creating another") func reusesExisting() async throws { let api = FakePublishing(listed: [ publication(id: "other", port: 3000, state: "active"), @@ -28,36 +27,56 @@ struct CloudPortShareServiceTests { #expect(await api.calls == ["list team-1"]) } - @Test("does not reuse a link that is being removed") - func skipsDisabling() async throws { + @Test("a custom domain on the same port is not the link Share hands out") + func ignoresCustomDomain() async throws { + let api = FakePublishing( + listed: [publication(id: "custom", state: "provisioning", domainKind: "custom")], + creates: [.row(publication(id: "generated", state: "active"))] + ) + let link = try await service(api).share(vmID: "brave-otter", port: 8000, teamID: nil) + #expect(link.id == "generated") + } + + @Test("a link being removed or a busy server only means not yet") + func retriesTransientConflicts() async throws { let api = FakePublishing( listed: [publication(id: "old", state: "disabling")], - created: publication(id: "new", state: "active") + creates: [.status(409), .status(503), .row(publication(id: "new", state: "active"))] ) let link = try await service(api).share(vmID: "brave-otter", port: 8000, teamID: nil) #expect(link.id == "new") } + @Test("an unavailable link is resumed by creating again, not given up on") + func resumesUnavailable() async throws { + let api = FakePublishing( + listed: [publication(state: "unavailable")], + creates: [.row(publication(state: "active"))] + ) + let link = try await service(api).share(vmID: "brave-otter", port: 8000, teamID: nil) + #expect(link.state == "active") + } + + @Test("other server errors end the share") + func otherErrorsThrow() async { + let api = FakePublishing(creates: [.status(404)]) + await #expect(throws: VMClientError.self) { + _ = try await service(api).share(vmID: "brave-otter", port: 8000, teamID: nil) + } + } + @Test("gives up with stillProvisioning once the waits run out") func timesOut() async { - let api = FakePublishing(created: publication(state: "provisioning"), verifyStates: ["provisioning", "provisioning"]) + let api = FakePublishing(creates: [.row(publication(state: "provisioning"))]) await #expect(throws: CloudPortShareError.stillProvisioning) { _ = try await service(api, delays: [.seconds(1), .seconds(1)]).share(vmID: "brave-otter", port: 8000, teamID: nil) } } - @Test("an unavailable link is an error, not a copied dead URL") - func unavailableFails() async { - let api = FakePublishing(created: publication(state: "unavailable")) - await #expect(throws: CloudPortShareError.unavailable(state: "unavailable")) { - _ = try await service(api).share(vmID: "brave-otter", port: 8000, teamID: nil) - } - } - - @Test("waits past the edge's 503 before handing back an active link") + @Test("waits past the edge's 503 and unknown-route 404 before handing back a link") func waitsForEdge() async throws { - let api = FakePublishing(created: publication(state: "active")) - let statuses = Statuses([503, nil, 302]) + let api = FakePublishing(creates: [.row(publication(state: "active"))]) + let statuses = Statuses([503, nil, 404, 401]) let link = try await service(api, probe: { _ in await statuses.next() }).share(vmID: "brave-otter", port: 8000, teamID: nil) #expect(link.state == "active") #expect(await statuses.remaining == 0) @@ -65,7 +84,7 @@ struct CloudPortShareServiceTests { @Test("an edge that never answers is stillProvisioning, not a copied 503") func edgeNeverReady() async { - let api = FakePublishing(created: publication(state: "active")) + let api = FakePublishing(creates: [.row(publication(state: "active"))]) await #expect(throws: CloudPortShareError.stillProvisioning) { _ = try await service(api, delays: [.seconds(1)], probe: { _ in 503 }).share(vmID: "brave-otter", port: 8000, teamID: nil) } @@ -73,7 +92,7 @@ struct CloudPortShareServiceTests { @Test("a public link is never probed, since the probe would reach the user's app") func publicSkipsProbe() async throws { - let api = FakePublishing(created: publication(state: "active", access: .public)) + let api = FakePublishing(creates: [.row(publication(state: "active", access: .public))]) let link = try await service(api, probe: { _ in Issue.record("probed a public link"); return 503 }) .share(vmID: "brave-otter", port: 8000, teamID: nil) #expect(link.accessMode == .public) @@ -81,24 +100,57 @@ struct CloudPortShareServiceTests { private func service( _ api: FakePublishing, - delays: [Duration] = [.seconds(1), .seconds(1), .seconds(1)], - probe: @escaping CloudPortShareService.Probe = { _ in 302 } + delays: [Duration] = [.seconds(1), .seconds(1), .seconds(1), .seconds(1)], + probe: @escaping CloudPortShareService.Probe = { _ in 401 } ) -> CloudPortShareService { CloudPortShareService(api: api, pollDelays: delays, sleep: { _ in }, probe: probe) } } +@Suite("Cloud port share store") +@MainActor +struct CloudPortShareStoreTests { + private let key = CloudPortShareStore.Key(machineID: "brave-otter", port: 8000) + + @Test("a held phase clears itself after the hold") + func holdClears() async { + let gate = Gate() + let store = CloudPortShareStore(sleep: { _ in await gate.wait() }) + store.set(.copied(.team), for: key, holdFor: .seconds(2)) + #expect(store.phase(for: key) == .copied(.team)) + await gate.open() + await waitUntil { store.phase(for: key) == nil } + #expect(store.phase(for: key) == nil) + } + + @Test("a newer phase is not cleared by an older phase's hold") + func newerPhaseSurvives() async { + let gate = Gate() + let store = CloudPortShareStore(sleep: { _ in await gate.wait() }) + store.set(.failed, for: key, holdFor: .seconds(4)) + store.set(.creating, for: key) + await gate.open() + for _ in 0..<20 { await Task.yield() } + #expect(store.phase(for: key) == .creating) + } + + private func waitUntil(_ condition: @MainActor () -> Bool) async { + for _ in 0..<100 where !condition() { await Task.yield() } + } +} + private func publication( id: String = "pub-1", port: Int = 8000, state: String, - access: VMPublicationAccessMode = .team + access: VMPublicationAccessMode = .team, + domainKind: String = "generated" ) -> VMPublication { VMPublication( id: id, hostname: "brave-otter--team--\(port).cmux.sh", url: "https://brave-otter--team--\(port).cmux.sh", - domainKind: "managed", + domainKind: domainKind, vmID: "brave-otter", port: port, accessMode: access, @@ -113,19 +165,37 @@ private actor Statuses { private var values: [Int?] init(_ values: [Int?]) { self.values = values } var remaining: Int { values.count } - func next() -> Int? { values.isEmpty ? 302 : values.removeFirst() } + func next() -> Int? { values.isEmpty ? 401 : values.removeFirst() } +} + +/// Holds sleepers until the test opens it. +private actor Gate { + private var isOpen = false + private var waiters: [CheckedContinuation] = [] + func wait() async { + if isOpen { return } + await withCheckedContinuation { waiters.append($0) } + } + func open() { + isOpen = true + waiters.forEach { $0.resume() } + waiters = [] + } } private actor FakePublishing: CloudPortPublishing { + enum Create { + case row(VMPublication) + case status(Int) + } + private(set) var calls: [String] = [] private let listed: [VMPublication] - private let created: VMPublication? - private var verifyStates: [String] + private var creates: [Create] - init(listed: [VMPublication] = [], created: VMPublication? = nil, verifyStates: [String] = []) { + init(listed: [VMPublication] = [], creates: [Create] = []) { self.listed = listed - self.created = created - self.verifyStates = verifyStates + self.creates = creates } func listPublications(scopeTeamID: String?) async throws -> [VMPublication] { @@ -133,15 +203,15 @@ private actor FakePublishing: CloudPortPublishing { return listed } + /// Plays the scripted answers in order, repeating the last one. func createDefaultPublication(vmID: String, port: Int, scopeTeamID: String?) async throws -> VMPublication { calls.append("create \(vmID):\(port) \(scopeTeamID ?? "-")") - return created! - } - - func verifyPublication(id: String, scopeTeamID: String?) async throws -> VMPublication { - calls.append("verify \(id) \(scopeTeamID ?? "-")") - let state = verifyStates.isEmpty ? "active" : verifyStates.removeFirst() - return publication(id: id, state: state) + guard let next = creates.first else { throw VMClientError.httpStatus(500, "no scripted create") } + if creates.count > 1 { creates.removeFirst() } + switch next { + case .row(let publication): return publication + case .status(let status): throw VMClientError.httpStatus(status, "{}") + } } func deletePublication(id: String, scopeTeamID: String?) async throws { diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 31e9f92c45a1..86c32d2d2974 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -618950,6 +618950,124 @@ } } } + }, + "cloudTree.port.share.ready": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Link ready" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "الرابط جاهز" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Link bereit" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Enlace listo" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Lien prêt" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "リンクの準備ができました" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "링크 준비됨" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "链接已就绪" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "連結已就緒" + } + } + } + }, + "cloudTree.port.share.readyHelp": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The link is ready. Click to copy it." + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "الرابط جاهز. انقر لنسخه." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Der Link ist bereit. Klicke, um ihn zu kopieren." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "El enlace está listo. Haz clic para copiarlo." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Le lien est prêt. Cliquez pour le copier." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "リンクの準備ができました。クリックしてコピーします。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "링크가 준비되었습니다. 클릭하여 복사하세요." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "链接已就绪。点按即可复制。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "連結已就緒。按一下即可拷貝。" + } + } + } } }, "version": "1.0" diff --git a/Sources/Cloud/CloudTreeNodeActions.swift b/Sources/Cloud/CloudTreeNodeActions.swift index 6b799e17bf7b..7bbbdef22d1b 100644 --- a/Sources/Cloud/CloudTreeNodeActions.swift +++ b/Sources/Cloud/CloudTreeNodeActions.swift @@ -604,18 +604,26 @@ struct CloudTreeNodeActions { let key = CloudPortShareStore.Key(machineID: resource.machine.rawValue, port: port) guard !store.isCreating(key) else { return } store.set(.creating, for: key) + // Making a link can take a while; if something else lands on the + // clipboard meanwhile, don't replace it. The row says the link is + // ready instead, and the next click copies it straight away. + let clipboardAtClick = NSPasteboard.general.changeCount run( String(localized: "cloudTree.port.share.creating", defaultValue: "Creating link\u{2026}"), { catalog in do { guard let provider = catalog.provider(for: resource.machine) as? CmuxTuiSurfaceProvider, let client = VMClient.shared else { - throw SurfaceCatalogError.unsupported(SurfaceCatalog.portPreviewUnavailableMessage(machineID: resource.machine.rawValue)) + throw CloudPortShareFailure.unavailable } let publication = try await CloudPortShareService(api: client) .share(vmID: provider.machineID, port: port, teamID: provider.ownerTeamID) - Self.copyToPasteboard(publication.url) - store.set(.copied(publication.accessMode), for: key, holdFor: .seconds(2)) + if NSPasteboard.general.changeCount == clipboardAtClick { + Self.copyToPasteboard(publication.url) + store.set(.copied(publication.accessMode), for: key, holdFor: .seconds(2)) + } else { + store.set(.ready, for: key, holdFor: .seconds(10)) + } } catch is CancellationError { store.clear(key) throw CancellationError() @@ -625,13 +633,15 @@ struct CloudTreeNodeActions { } }, failureDescription: { error in - switch error as? CloudPortShareError { - case .stillProvisioning: + switch error { + case CloudPortShareError.stillProvisioning: return String(localized: "cloudTree.port.share.error.timeout", defaultValue: "The link is still being set up. Try sharing again in a minute.") - case .unavailable: - return String(localized: "cloudTree.port.share.error.unavailable", defaultValue: "The Cloud service couldn't create a link for this port. Try again.") - case nil: + case VMClientError.notSignedIn, VMClientError.sessionRefreshFailed: return (error as? LocalizedError)?.errorDescription ?? String(describing: error) + default: + // Server and client errors here are written for the + // CLI ("Run `cmux ...`"); the sidebar gets plain copy. + return String(localized: "cloudTree.port.share.error.unavailable", defaultValue: "The Cloud service couldn't create a link for this port. Try again.") } } ) @@ -648,3 +658,8 @@ struct CloudTreeNodeActions { #endif } } + +/// The machine isn't reachable through a Cloud provider right now. +private enum CloudPortShareFailure: Error { + case unavailable +} diff --git a/Sources/Cloud/CloudTreeRowHoverButtons.swift b/Sources/Cloud/CloudTreeRowHoverButtons.swift index 2c9dbb82bc52..4b22e8793a95 100644 --- a/Sources/Cloud/CloudTreeRowHoverButtons.swift +++ b/Sources/Cloud/CloudTreeRowHoverButtons.swift @@ -189,12 +189,14 @@ struct CloudTreeRowHoverButtons: View { /// once it is on the clipboard. private struct CloudPortShareButton: View { let key: CloudPortShareStore.Key - @ObservedObject var store: CloudPortShareStore + let store: CloudPortShareStore let action: () -> Void var body: some View { let phase = store.phase(for: key) - HStack(spacing: 2) { + // No transition: the controls host resizes with the note, and an + // animated swap slides the note out under the row's content. + HStack(spacing: 4) { if let status = status(phase) { // The row's content keeps its trailing edge at just below // required priority, so the controls host shrinks to its @@ -205,7 +207,6 @@ private struct CloudPortShareButton: View { .foregroundStyle(.secondary) .lineLimit(1) .fixedSize() - .transition(.opacity) } MachinesChromeIconButton( symbolName: symbolName(phase), @@ -216,14 +217,13 @@ private struct CloudPortShareButton: View { .help(label(phase)) .accessibilityIdentifier("CloudPortShareButton") } - .animation(.easeOut(duration: 0.15), value: phase) } private func symbolName(_ phase: CloudPortShareStore.Phase?) -> String { switch phase { case .copied: return "checkmark" case .failed: return "exclamationmark.triangle" - case .creating, nil: return "link" + case .creating, .ready, nil: return "link" } } @@ -235,6 +235,8 @@ private struct CloudPortShareButton: View { return String(localized: "cloudTree.port.share.creating", defaultValue: "Creating link\u{2026}") case .copied: return String(localized: "cloudTree.port.share.copied", defaultValue: "Copied to clipboard") + case .ready: + return String(localized: "cloudTree.port.share.ready", defaultValue: "Link ready") case .failed, nil: return nil } @@ -250,6 +252,8 @@ private struct CloudPortShareButton: View { return String(localized: "cloudTree.port.share.copiedPersonal", defaultValue: "Link copied. Only you can open it.") case .copied(.public): return String(localized: "cloudTree.port.share.copiedPublic", defaultValue: "Link copied. Anyone with the link can open it.") + case .ready: + return String(localized: "cloudTree.port.share.readyHelp", defaultValue: "The link is ready. Click to copy it.") case .failed: return String(localized: "cloudTree.port.share.failed", defaultValue: "Couldn't create link") case nil: From 520099f0b7772a460f8bb54e9520543b5f164111 Mon Sep 17 00:00:00 2001 From: Lucas Ribeiro Date: Sat, 3 Oct 2026 20:19:53 +1300 Subject: [PATCH 07/36] web: blank forward-auth origin means unset --- web/app/env.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/web/app/env.ts b/web/app/env.ts index c95a78ea3b2b..fc447b25907e 100644 --- a/web/app/env.ts +++ b/web/app/env.ts @@ -557,9 +557,10 @@ export const env = createEnv({ CMUX_VM_PUBLICATION_AUTH_ORIGIN: trimEnv( process.env.CMUX_VM_PUBLICATION_AUTH_ORIGIN, ), + // Blank (as in .env.example) means unset, not an invalid origin. CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN: trimEnv( process.env.CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN, - ), + ) || undefined, CMUX_VM_PUBLICATION_GENERATED_DOMAIN: trimEnv( process.env.CMUX_VM_PUBLICATION_GENERATED_DOMAIN, ), From b727789b05d9f2dd045e6ea0161141637d28aedf Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Sun, 4 Oct 2026 17:15:26 -0700 Subject: [PATCH 08/36] fix(web): treat blank forward-auth origin as unset --- web/app/env.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/web/app/env.ts b/web/app/env.ts index fc447b25907e..91fde092263d 100644 --- a/web/app/env.ts +++ b/web/app/env.ts @@ -151,7 +151,10 @@ const bareHttpsOrigin = (name: string) => z.string().url().superRefine((value, c } }); const publicationAuthOrigin = bareHttpsOrigin("CMUX_VM_PUBLICATION_AUTH_ORIGIN"); -const publicationForwardAuthOrigin = bareHttpsOrigin("CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN"); +const publicationForwardAuthOrigin = z.preprocess( + (value) => typeof value === "string" && value.trim() === "" ? undefined : value, + bareHttpsOrigin("CMUX_VM_PUBLICATION_FORWARD_AUTH_ORIGIN").optional(), +); const irohBindingLimit = z.string().regex(/^[1-9][0-9]{0,3}$/).superRefine((value, context) => { if (Number(value) > 4_096) { context.addIssue({ From 21c4a11eeb927068fd78490363fd742940b5250d Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 19:34:41 -0700 Subject: [PATCH 09/36] Test cancelled port sharing and migration fetch fallback --- .../CloudPortShareServiceTests.swift | 84 ++++++++++++++++++- tests/test_backend_migrations_plan.py | 13 +++ 2 files changed, 96 insertions(+), 1 deletion(-) diff --git a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift index 99dcd400f838..e839c423f68f 100644 --- a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift +++ b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift @@ -4,6 +4,59 @@ import Testing @Suite("Cloud port share service") struct CloudPortShareServiceTests { + enum CancellationPoint: CaseIterable, Sendable { + case beforeStart, list, create, probe, retryDelay + } + + @Test("cancellation stops sharing even when a dependency finishes normally", arguments: CancellationPoint.allCases) + func cancellationStopsSharing(at point: CancellationPoint) async { + let entered = Gate() + let release = Gate() + let pause: @Sendable () async -> Void = { + await entered.open() + await release.wait() + } + let api = FakePublishing( + creates: [.row(publication(state: point == .retryDelay ? "provisioning" : "active"))], + beforeListReturn: { if point == .list { await pause() } }, + beforeCreateReturn: { if point == .create { await pause() } } + ) + let service = CloudPortShareService( + api: api, + pollDelays: [.seconds(1)], + sleep: { _ in if point == .retryDelay { await pause() } }, + probe: { _ in + if point == .probe { await pause() } + return 401 + } + ) + let task = Task { + if point == .beforeStart { await pause() } + return try await service.share(vmID: "brave-otter", port: 8000, teamID: "team-1") + } + await entered.wait() + task.cancel() + await release.open() + await #expect(throws: CancellationError.self) { _ = try await task.value } + let expectedCalls: [String] = point == .beforeStart ? [] : point == .list + ? ["list team-1"] : ["list team-1", "create brave-otter:8000 team-1"] + #expect(await api.calls == expectedCalls) + } + + @Test("the signed-out readiness request uses a safe HTTP method") + func readinessRequestIsSafe() async throws { + try #require(URLProtocol.registerClass(PortShareProbeProtocol.self)) + defer { URLProtocol.unregisterClass(PortShareProbeProtocol.self) } + let url = try #require(URL(string: "https://port-share-probe-test.invalid/")) + let status = await CloudPortShareService.signedOutStatus(url) + #expect(status == 200) + let request = try #require(PortShareProbeProtocol.capturedRequest()) + #expect(request.httpMethod == "HEAD") + #expect(request.httpBody == nil) + #expect(request.value(forHTTPHeaderField: "Authorization") == nil) + #expect(request.value(forHTTPHeaderField: "Cookie") == nil) + } + @Test("creates a link with the server default and waits until it serves") func createsAndWaits() async throws { let api = FakePublishing(creates: [.row(publication(state: "provisioning")), .row(publication(state: "active"))]) @@ -192,20 +245,30 @@ private actor FakePublishing: CloudPortPublishing { private(set) var calls: [String] = [] private let listed: [VMPublication] private var creates: [Create] + private let beforeListReturn: @Sendable () async -> Void + private let beforeCreateReturn: @Sendable () async -> Void - init(listed: [VMPublication] = [], creates: [Create] = []) { + init( + listed: [VMPublication] = [], creates: [Create] = [], + beforeListReturn: @escaping @Sendable () async -> Void = {}, + beforeCreateReturn: @escaping @Sendable () async -> Void = {} + ) { self.listed = listed self.creates = creates + self.beforeListReturn = beforeListReturn + self.beforeCreateReturn = beforeCreateReturn } func listPublications(scopeTeamID: String?) async throws -> [VMPublication] { calls.append("list \(scopeTeamID ?? "-")") + await beforeListReturn() return listed } /// Plays the scripted answers in order, repeating the last one. func createDefaultPublication(vmID: String, port: Int, scopeTeamID: String?) async throws -> VMPublication { calls.append("create \(vmID):\(port) \(scopeTeamID ?? "-")") + await beforeCreateReturn() guard let next = creates.first else { throw VMClientError.httpStatus(500, "no scripted create") } if creates.count > 1 { creates.removeFirst() } switch next { @@ -218,3 +281,22 @@ private actor FakePublishing: CloudPortPublishing { calls.append("delete \(id) \(scopeTeamID ?? "-")") } } + +/// Intercepts only this test's hostname; other URLSession traffic is unaffected. +private final class PortShareProbeProtocol: URLProtocol, @unchecked Sendable { + private static let lock = NSLock() + nonisolated(unsafe) private static var captured: URLRequest? + + static func capturedRequest() -> URLRequest? { lock.withLock { captured } } + override class func canInit(with request: URLRequest) -> Bool { + request.url?.host == "port-share-probe-test.invalid" + } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func startLoading() { + Self.lock.withLock { Self.captured = request } + let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocolDidFinishLoading(self) + } + override func stopLoading() {} +} diff --git a/tests/test_backend_migrations_plan.py b/tests/test_backend_migrations_plan.py index 5dce8417cfad..6be7397e521b 100644 --- a/tests/test_backend_migrations_plan.py +++ b/tests/test_backend_migrations_plan.py @@ -81,6 +81,19 @@ def test_a_pr_that_adds_a_migration_still_lists_its_files(self): self.assertNotEqual(code, 0, log) self.assertNotIn("migrations=false", output) + def test_unfetchable_head_without_migrations_uses_files_api(self): + (self.tmp / "bin/gh").write_text("#!/bin/sh\nprintf 'modified\\twebviews/App.tsx\\t\\n'\n") + code, output, log = self.run_plan("f" * 40) + self.assertEqual(code, 0, log) + self.assertIn("migrations=false", output) + + def test_unfetchable_head_with_migrations_fails_closed(self): + (self.tmp / "bin/gh").write_text("#!/bin/sh\nprintf 'added\\tbackend/db/migrations/0002_more.sql\\t\\n'\n") + code, output, log = self.run_plan("f" * 40) + self.assertNotEqual(code, 0, log) + self.assertIn("migrations=true", output) + self.assertNotIn("migrations=false", output) + if __name__ == "__main__": unittest.main() From 536cfb0a39d3df0a30ad57533822d791249512c3 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 19:44:34 -0700 Subject: [PATCH 10/36] Harden port share cancellation and CI fetch fallback --- .github/workflows/backend-migrations.yml | 10 ++++--- .../VMClient/CloudPortShareService.swift | 25 +++++++++++++---- .../VMClient/CloudPortShareStore.swift | 22 +++++++++++++++ .../CloudPortShareServiceTests.swift | 12 +++++++++ Sources/Cloud/CloudTreeNodeActions.swift | 18 ++++++++----- cmuxTests/BrowserReplRenderHostTests.swift | 27 +------------------ 6 files changed, 72 insertions(+), 42 deletions(-) diff --git a/.github/workflows/backend-migrations.yml b/.github/workflows/backend-migrations.yml index ae20cf66ac7f..362c114feca3 100644 --- a/.github/workflows/backend-migrations.yml +++ b/.github/workflows/backend-migrations.yml @@ -70,10 +70,12 @@ jobs: # installation's API quota ran out under load and failed the plan on UI PRs (#17602). # The same backend/db/migrations tree as the base means no migration change; a # different one (the PR's change, or a base move it has not merged) is listed below. - git -C trusted fetch --quiet --no-tags --depth=1 origin "$HEAD_SHA" - base_tree=$(git -C trusted rev-parse --verify --quiet "$BASE_SHA:backend/db/migrations" || echo none) - head_tree=$(git -C trusted rev-parse --verify --quiet "$HEAD_SHA:backend/db/migrations" || echo none) - if [ "$base_tree" = "$head_tree" ]; then + # This is only an optimization. A fork head may not be fetchable from + # the base remote; missing trees must also fall back to the files API. + if git -C trusted fetch --quiet --no-tags --depth=1 origin "$HEAD_SHA" && + base_tree=$(git -C trusted rev-parse --verify --quiet "$BASE_SHA:backend/db/migrations") && + head_tree=$(git -C trusted rev-parse --verify --quiet "$HEAD_SHA:backend/db/migrations") && + [ "$base_tree" = "$head_tree" ]; then echo "migrations=false" >> "$GITHUB_OUTPUT"; echo "no migration changes (backend/db/migrations matches the base)"; exit 0 fi gh api --paginate "repos/$REPO/pulls/$PR/files" --jq '.[] | "\(.status)\t\(.filename)\t\(.previous_filename // "")"' > changes.tsv diff --git a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift index 09b69bc5b795..858d1b8eebf8 100644 --- a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift +++ b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift @@ -81,9 +81,22 @@ public struct CloudPortShareService: Sendable { /// answers: `active` on the server can run ahead of the edge, which shows /// a 503 page until its authorization check and route are ready. public func share(vmID: String, port: Int, teamID: String?) async throws -> VMPublication { + do { + return try await shareUntilReady(vmID: vmID, port: port, teamID: teamID) + } catch { + // A cancelled request can finish with a transport or API error. + // Preserve cancellation so callers do not show a stale failure. + try Task.checkCancellation() + throw error + } + } + + private func shareUntilReady(vmID: String, port: Int, teamID: String?) async throws -> VMPublication { + try Task.checkCancellation() var delays = pollDelays.makeIterator() var publication = try await existing(vmID: vmID, port: port, teamID: teamID) while true { + try Task.checkCancellation() if publication?.state != "active" { // Creating again resumes a provisioning or unavailable row. A // row still being removed (409) or a busy provisioning lease @@ -93,10 +106,13 @@ public struct CloudPortShareService: Sendable { } catch VMClientError.httpStatus(let status, _) where status == 409 || status == 503 { publication = nil } + try Task.checkCancellation() } if let current = publication, current.state == "active", await serves(current) { + try Task.checkCancellation() return current } + try Task.checkCancellation() guard let delay = delays.next() else { throw CloudPortShareError.stillProvisioning } try await sleep(delay) } @@ -117,11 +133,10 @@ public struct CloudPortShareService: Sendable { return (200..<400).contains(status) || status == 401 } - /// A signed-out HEAD to a protected link. cmux's authorization check - /// answers it with 401 without starting a sign-in or reaching the machine. - /// HEAD stays safe if a protected publication becomes public while the - /// request is in flight: the edge can forward it to the user's app, but - /// it cannot carry a request body or trigger a POST mutation. + /// A signed-out HEAD to a protected link. The authorization check can + /// reject it or redirect to sign-in; redirects are never followed. + /// If the publication becomes public during the request, the app receives + /// a safe-method readiness check rather than a POST that could mutate data. public static let signedOutStatus: Probe = { url in let configuration = URLSessionConfiguration.ephemeral configuration.timeoutIntervalForRequest = 5 diff --git a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareStore.swift b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareStore.swift index a4eccbeef066..1d2905d1cf33 100644 --- a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareStore.swift +++ b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareStore.swift @@ -30,6 +30,7 @@ public final class CloudPortShareStore { public private(set) var phases: [Key: Phase] = [:] @ObservationIgnored private var resetTasks: [Key: Task] = [:] + @ObservationIgnored private var operationIDs: [Key: UUID] = [:] @ObservationIgnored private let sleep: Sleep /// `sleep` times the auto-dismiss of a finished phase (a brief "copied" @@ -42,6 +43,16 @@ public final class CloudPortShareStore { public func isCreating(_ key: Key) -> Bool { phases[key] == .creating } + /// Starts a new operation and returns its identity. A late completion from + /// an older operation cannot clear or overwrite a replacement. + public func beginCreating(_ key: Key) -> UUID? { + guard phases[key] != .creating else { return nil } + let id = UUID() + operationIDs[key] = id + set(.creating, for: key) + return id + } + /// Shows `phase` on the row; a finished phase clears itself after `holdFor`. public func set(_ phase: Phase, for key: Key, holdFor: Duration? = nil) { resetTasks[key]?.cancel() @@ -61,5 +72,16 @@ public final class CloudPortShareStore { resetTasks[key]?.cancel() resetTasks[key] = nil phases[key] = nil + operationIDs[key] = nil + } + + public func set(_ phase: Phase, for key: Key, operationID: UUID, holdFor: Duration? = nil) { + guard operationIDs[key] == operationID else { return } + set(phase, for: key, holdFor: holdFor) + } + + public func clear(_ key: Key, operationID: UUID) { + guard operationIDs[key] == operationID else { return } + clear(key) } } diff --git a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift index e839c423f68f..45cc62f7e218 100644 --- a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift +++ b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift @@ -187,6 +187,18 @@ struct CloudPortShareStoreTests { #expect(store.phase(for: key) == .creating) } + @Test("a cancelled operation cannot clear its replacement") + func cancelledOperationDoesNotClearReplacement() throws { + let store = CloudPortShareStore() + let first = #require(store.beginCreating(key)) + store.clear(key, operationID: first) + let replacement = #require(store.beginCreating(key)) + store.clear(key, operationID: first) + #expect(store.phase(for: key) == .creating) + store.clear(key, operationID: replacement) + #expect(store.phase(for: key) == nil) + } + private func waitUntil(_ condition: @MainActor () -> Bool) async { for _ in 0..<100 where !condition() { await Task.yield() } } diff --git a/Sources/Cloud/CloudTreeNodeActions.swift b/Sources/Cloud/CloudTreeNodeActions.swift index 49d70e084dd0..6390fea313e6 100644 --- a/Sources/Cloud/CloudTreeNodeActions.swift +++ b/Sources/Cloud/CloudTreeNodeActions.swift @@ -699,8 +699,7 @@ struct CloudTreeNodeActions { guard let port = resource.forwardedPort else { return } let store = CloudPortShareStore.shared let key = CloudPortShareStore.Key(machineID: resource.machine.rawValue, port: port) - guard !store.isCreating(key) else { return } - store.set(.creating, for: key) + guard let operationID = store.beginCreating(key) else { return } // Making a link can take a while; if something else lands on the // clipboard meanwhile, don't replace it. The row says the link is // ready instead, and the next click copies it straight away. @@ -711,6 +710,7 @@ struct CloudTreeNodeActions { String(localized: "cloudTree.port.share.creating", defaultValue: "Creating link\u{2026}"), { catalog in do { + try Task.checkCancellation() guard let provider = catalog.provider(for: resource.machine) as? CmuxTuiSurfaceProvider, let client = VMClient.shared else { throw CloudPortShareFailure.unavailable @@ -723,15 +723,19 @@ struct CloudTreeNodeActions { try Task.checkCancellation() if NSPasteboard.general.changeCount == clipboardAtClick { Self.copyToPasteboard(publication.url) - store.set(.copied(publication.accessMode), for: key, holdFor: .seconds(2)) + store.set(.copied(publication.accessMode), for: key, operationID: operationID, holdFor: .seconds(2)) } else { - store.set(.ready, for: key, holdFor: .seconds(10)) + store.set(.ready, for: key, operationID: operationID, holdFor: .seconds(10)) } } catch is CancellationError { - store.clear(key) + store.clear(key, operationID: operationID) throw CancellationError() } catch { - store.set(.failed, for: key, holdFor: .seconds(4)) + if Task.isCancelled { + store.clear(key, operationID: operationID) + throw CancellationError() + } + store.set(.failed, for: key, operationID: operationID, holdFor: .seconds(4)) throw error } }, @@ -752,7 +756,7 @@ struct CloudTreeNodeActions { if !started { // No lifecycle owner admitted the work (for example while // Cloud is being torn down), so do not leave a spinner behind. - store.clear(key) + store.clear(key, operationID: operationID) } } return actions diff --git a/cmuxTests/BrowserReplRenderHostTests.swift b/cmuxTests/BrowserReplRenderHostTests.swift index 568c58a7bac9..7d56bd4376df 100644 --- a/cmuxTests/BrowserReplRenderHostTests.swift +++ b/cmuxTests/BrowserReplRenderHostTests.swift @@ -28,23 +28,6 @@ struct BrowserReplRenderHostTests { ) } - private func makeWindow() throws -> (NSWindow, NSView) { - let window = NSWindow( - contentRect: NSRect(x: 0, y: 0, width: 480, height: 320), - styleMask: [.titled, .closable], - backing: .buffered, - defer: false - ) - window.makeKeyAndOrderFront(nil) - window.displayIfNeeded() - window.contentView?.layoutSubtreeIfNeeded() - RunLoop.current.run(until: Date().addingTimeInterval(0.05)) - let contentView = try #require(window.contentView) - let anchor = NSView(frame: NSRect(x: 24, y: 24, width: 360, height: 220)) - contentView.addSubview(anchor) - return (window, anchor) - } - private func visibleRenderWindows() -> [NSWindow] { NSApp.windows.filter { $0.identifier?.rawValue == Self.renderWindowIdentifier && $0.isVisible @@ -53,18 +36,10 @@ struct BrowserReplRenderHostTests { } @Test func hiddenDrivenTabRendersOffEveryScreenAndReturnsToItsPane() throws { - let (window, anchor) = try makeWindow() + let (window, anchor, panel, paneHost) = try makePane(key: true) defer { window.orderOut(nil) } - let panel = BrowserPanel( - workspaceId: UUID(), - initialURL: URL(string: "about:blank")!, - isRemoteWorkspace: false - ) let webView = panel.webView defer { BrowserWindowPortalRegistry.detach(webView: webView) } - BrowserWindowPortalRegistry.bind(webView: webView, to: anchor, visibleInUI: true) - BrowserWindowPortalRegistry.synchronizeForAnchor(anchor) - let paneHost = try #require(webView.cmuxBrowserViewportAttachmentSuperview) // A background tab: no pane shows it, so a driving session moves it // into the render window. From 16e0e6ccb73befd83205b91173ce0008f6f241bb Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 19:56:56 -0700 Subject: [PATCH 11/36] Wait for public port shares to reach the edge --- .../CmuxCloud/VMClient/CloudPortShareService.swift | 11 ++++++----- .../CmuxCloudTests/CloudPortShareServiceTests.swift | 8 +++++--- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift index 858d1b8eebf8..50a9f461e09c 100644 --- a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift +++ b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift @@ -123,13 +123,14 @@ public struct CloudPortShareService: Sendable { try await api.deletePublication(id: publicationID, scopeTeamID: teamID) } - /// A public link would send the probe to the user's app, so it is taken as - /// is. A protected link must answer the signed-out probe the way cmux's - /// authorization check does (401), or serve or redirect; anything else, - /// such as the edge's 503 or a 404 for a route it doesn't know yet, waits. + /// Probe both access modes with HEAD. A public app can return any ordinary + /// HTTP response, including 404, once the edge is forwarding; edge 5xx + /// responses and network failures still mean that the route is not ready. + /// A protected link must answer the signed-out probe with 401, or serve or + /// redirect; an edge 503 or unknown-route 404 waits in that mode. private func serves(_ publication: VMPublication) async -> Bool { - guard publication.accessMode != .public else { return true } guard let url = URL(string: publication.url), let status = await probe(url) else { return false } + if publication.accessMode == .public { return status < 500 } return (200..<400).contains(status) || status == 401 } diff --git a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift index 45cc62f7e218..5dcaa52eaab0 100644 --- a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift +++ b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift @@ -143,12 +143,14 @@ struct CloudPortShareServiceTests { } } - @Test("a public link is never probed, since the probe would reach the user's app") - func publicSkipsProbe() async throws { + @Test("a public link waits for the edge before copying") + func publicWaitsForEdge() async throws { let api = FakePublishing(creates: [.row(publication(state: "active", access: .public))]) - let link = try await service(api, probe: { _ in Issue.record("probed a public link"); return 503 }) + let statuses = Statuses([503, 200]) + let link = try await service(api, probe: { _ in await statuses.next() }) .share(vmID: "brave-otter", port: 8000, teamID: nil) #expect(link.accessMode == .public) + #expect(await statuses.remaining == 0) } private func service( From 8f2ae9a7b80b5eaf0680ad11c5dc9924acabe500 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 20:02:13 -0700 Subject: [PATCH 12/36] Make port probe transport testable --- .../Sources/CmuxCloud/VMClient/CloudPortShareService.swift | 7 ++++++- .../Tests/CmuxCloudTests/CloudPortShareServiceTests.swift | 4 +++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift index 50a9f461e09c..0e93d64d8f7f 100644 --- a/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift +++ b/Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift @@ -139,7 +139,12 @@ public struct CloudPortShareService: Sendable { /// If the publication becomes public during the request, the app receives /// a safe-method readiness check rather than a POST that could mutate data. public static let signedOutStatus: Probe = { url in - let configuration = URLSessionConfiguration.ephemeral + await signedOutStatus(url, configuration: .ephemeral) + } + + /// The configuration overload keeps the transport test deterministic while + /// production continues to use an ephemeral, cookie-free session. + static func signedOutStatus(_ url: URL, configuration: URLSessionConfiguration) async -> Int? { configuration.timeoutIntervalForRequest = 5 configuration.httpCookieStorage = nil configuration.httpShouldSetCookies = false diff --git a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift index 5dcaa52eaab0..da4610c22b8f 100644 --- a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift +++ b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift @@ -48,7 +48,9 @@ struct CloudPortShareServiceTests { try #require(URLProtocol.registerClass(PortShareProbeProtocol.self)) defer { URLProtocol.unregisterClass(PortShareProbeProtocol.self) } let url = try #require(URL(string: "https://port-share-probe-test.invalid/")) - let status = await CloudPortShareService.signedOutStatus(url) + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [PortShareProbeProtocol.self] + let status = await CloudPortShareService.signedOutStatus(url, configuration: configuration) #expect(status == 200) let request = try #require(PortShareProbeProtocol.capturedRequest()) #expect(request.httpMethod == "HEAD") From e1050c39208fecfd34dbd981dd84af8e7bc8c827 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 20:29:47 -0700 Subject: [PATCH 13/36] Restore deterministic browser test window helper --- cmuxTests/BrowserReplRenderHostTests.swift | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/cmuxTests/BrowserReplRenderHostTests.swift b/cmuxTests/BrowserReplRenderHostTests.swift index 7d56bd4376df..e965ece65a79 100644 --- a/cmuxTests/BrowserReplRenderHostTests.swift +++ b/cmuxTests/BrowserReplRenderHostTests.swift @@ -82,6 +82,25 @@ struct BrowserReplRenderHostTests { override var isKeyWindow: Bool { reportsKey } } + /// A deterministic ordinary pane window for tests that exercise only the + /// render-host focus transition. Headless runners do not reliably activate + /// a newly-created AppKit window, so its key status is explicit. + private func makeWindow() throws -> (NSWindow, NSView) { + let window = KeyStatusWindow( + contentRect: NSRect(x: 0, y: 0, width: 480, height: 320), + styleMask: [.titled, .closable], + backing: .buffered, + defer: false + ) + window.reportsKey = true + window.orderFront(nil) + window.displayIfNeeded() + let contentView = try #require(window.contentView) + let anchor = NSView(frame: NSRect(x: 24, y: 24, width: 360, height: 220)) + contentView.addSubview(anchor) + return (window, anchor) + } + private func makePane(key: Bool) throws -> (KeyStatusWindow, NSView, BrowserPanel, NSView) { let window = KeyStatusWindow( contentRect: NSRect(x: 0, y: 0, width: 480, height: 320), From feab59ad8a7dd813313b9ce104dc7b88a4971e26 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 21:31:53 -0700 Subject: [PATCH 14/36] Cover port probe transport with injectable session --- .../Tests/CmuxCloudTests/CloudPortShareServiceTests.swift | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift index da4610c22b8f..f8e37e5495f5 100644 --- a/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift +++ b/Packages/macOS/CmuxCloud/Tests/CmuxCloudTests/CloudPortShareServiceTests.swift @@ -1,4 +1,4 @@ -import CmuxCloud +@testable import CmuxCloud import Foundation import Testing @@ -45,8 +45,6 @@ struct CloudPortShareServiceTests { @Test("the signed-out readiness request uses a safe HTTP method") func readinessRequestIsSafe() async throws { - try #require(URLProtocol.registerClass(PortShareProbeProtocol.self)) - defer { URLProtocol.unregisterClass(PortShareProbeProtocol.self) } let url = try #require(URL(string: "https://port-share-probe-test.invalid/")) let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [PortShareProbeProtocol.self] @@ -194,9 +192,9 @@ struct CloudPortShareStoreTests { @Test("a cancelled operation cannot clear its replacement") func cancelledOperationDoesNotClearReplacement() throws { let store = CloudPortShareStore() - let first = #require(store.beginCreating(key)) + let first = try #require(store.beginCreating(key)) store.clear(key, operationID: first) - let replacement = #require(store.beginCreating(key)) + let replacement = try #require(store.beginCreating(key)) store.clear(key, operationID: first) #expect(store.phase(for: key) == .creating) store.clear(key, operationID: replacement) From e537663f8d941d356e91d6da5334b856dd5283dd Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 19:01:10 -0700 Subject: [PATCH 15/36] Stabilize cloud sheet layout checks --- Sources/Cloud/CloudSheetWindow.swift | 11 ++++++++++- cmuxTests/NewMachineSheetLayoutTests.swift | 7 +++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index 5988683966bf..c935694c5f4b 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -22,6 +22,7 @@ import SwiftUI @MainActor final class CloudSheetWindow { let window: NSWindow + private let initialContentSize: NSSize private var isOpening = false private var pendingContentSize: NSSize? private var isResizeScheduled = false @@ -34,8 +35,9 @@ final class CloudSheetWindow { controller.sizingOptions = [] window = NSWindow(contentViewController: controller) let initialSize = controller.view.fittingSize + initialContentSize = Self.rounded(initialSize) if initialSize.width > 0, initialSize.height > 0 { - window.setContentSize(Self.rounded(initialSize)) + window.setContentSize(initialContentSize) } reporter.owner = self } @@ -46,6 +48,13 @@ final class CloudSheetWindow { isOpening = true host.beginSheet(window, completionHandler: completionHandler) isOpening = false + // Some AppKit versions reset a newly attached sheet to a 1×0 content + // rect while the host is inactive. Restore the measured first layout + // before applying any later geometry report. + let current = window.contentRect(forFrameRect: window.frame).size + if (current.width <= 1 || current.height <= 1), initialContentSize.width > 0, initialContentSize.height > 0 { + window.setContentSize(initialContentSize) + } applyPendingContentSize() } diff --git a/cmuxTests/NewMachineSheetLayoutTests.swift b/cmuxTests/NewMachineSheetLayoutTests.swift index f7bfc98eec26..8b7c80ff2161 100644 --- a/cmuxTests/NewMachineSheetLayoutTests.swift +++ b/cmuxTests/NewMachineSheetLayoutTests.swift @@ -159,9 +159,12 @@ struct NewMachineSheetLayoutTests { #expect(abs(leading[0] - leading[1]) <= 1, "Base starts at \(leading[0]), Size at \(leading[1])") for (name, popUp) in rows { let width = popUp.convert(popUp.bounds, to: host).width + // AppKit's intrinsicContentSize excludes a few points of the + // menu control's border/accessory; fittingSize is its measured + // natural width after those decorations are included. #expect( - width <= popUp.intrinsicContentSize.width + 1, - "\(name) pop-up is \(width)pt wide; its own width is \(popUp.intrinsicContentSize.width)pt" + width <= popUp.fittingSize.width + 1, + "\(name) pop-up is \(width)pt wide; its fitting width is \(popUp.fittingSize.width)pt" ) } } From 7699afdacb2060dfa762f021e6ac0d0e55ea80a1 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 19:40:46 -0700 Subject: [PATCH 16/36] Fix deferred cloud sheet size reset --- Sources/Cloud/CloudSheetWindow.swift | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index c935694c5f4b..47e11397d590 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -51,11 +51,15 @@ final class CloudSheetWindow { // Some AppKit versions reset a newly attached sheet to a 1×0 content // rect while the host is inactive. Restore the measured first layout // before applying any later geometry report. - let current = window.contentRect(forFrameRect: window.frame).size - if (current.width <= 1 || current.height <= 1), initialContentSize.width > 0, initialContentSize.height > 0 { - window.setContentSize(initialContentSize) - } + restoreInitialContentSizeIfNeeded() applyPendingContentSize() + // The reset can happen on the next run-loop turn, after beginSheet + // returns. Reapply after AppKit has attached the sheet as well. + DispatchQueue.main.async { [weak self] in + guard let self else { return } + self.restoreInitialContentSizeIfNeeded() + self.applyPendingContentSize() + } } /// Shows the sheet as a centered floating window when no host is on screen. @@ -65,6 +69,11 @@ final class CloudSheetWindow { window.makeKeyAndOrderFront(nil) isOpening = false applyPendingContentSize() + DispatchQueue.main.async { [weak self] in + guard let self else { return } + self.restoreInitialContentSizeIfNeeded() + self.applyPendingContentSize() + } } fileprivate func contentIdealSizeChanged(_ size: NSSize) { @@ -93,6 +102,13 @@ final class CloudSheetWindow { window.setFrame(frame, display: window.isVisible, animate: false) } + private func restoreInitialContentSizeIfNeeded() { + guard initialContentSize.width > 1, initialContentSize.height > 1 else { return } + let current = window.contentRect(forFrameRect: window.frame).size + guard current.width <= 1 || current.height <= 1 else { return } + window.setContentSize(initialContentSize) + } + private static func rounded(_ size: NSSize) -> NSSize { NSSize(width: ceil(size.width), height: ceil(size.height)) } From cfff115dec3ecdb7a494c7679a9ee93510cd740d Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 19:41:27 -0700 Subject: [PATCH 17/36] Defer sheet size restoration after attachment --- Sources/Cloud/CloudSheetWindow.swift | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index 47e11397d590..355ce4159ba8 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -51,13 +51,20 @@ final class CloudSheetWindow { // Some AppKit versions reset a newly attached sheet to a 1×0 content // rect while the host is inactive. Restore the measured first layout // before applying any later geometry report. - restoreInitialContentSizeIfNeeded() + let current = window.contentRect(forFrameRect: window.frame).size + if (current.width <= 1 || current.height <= 1), initialContentSize.width > 0, initialContentSize.height > 0 { + window.setContentSize(initialContentSize) + } applyPendingContentSize() - // The reset can happen on the next run-loop turn, after beginSheet - // returns. Reapply after AppKit has attached the sheet as well. + // AppKit may perform one more sheet-host layout on the next turn and + // reset the frame after beginSheet returns. Reapply after that pass so + // the first geometry report has a usable window to measure against. DispatchQueue.main.async { [weak self] in guard let self else { return } - self.restoreInitialContentSizeIfNeeded() + let current = self.window.contentRect(forFrameRect: self.window.frame).size + if (current.width <= 1 || current.height <= 1), self.initialContentSize.width > 0, self.initialContentSize.height > 0 { + self.window.setContentSize(self.initialContentSize) + } self.applyPendingContentSize() } } @@ -69,11 +76,6 @@ final class CloudSheetWindow { window.makeKeyAndOrderFront(nil) isOpening = false applyPendingContentSize() - DispatchQueue.main.async { [weak self] in - guard let self else { return } - self.restoreInitialContentSizeIfNeeded() - self.applyPendingContentSize() - } } fileprivate func contentIdealSizeChanged(_ size: NSSize) { @@ -102,13 +104,6 @@ final class CloudSheetWindow { window.setFrame(frame, display: window.isVisible, animate: false) } - private func restoreInitialContentSizeIfNeeded() { - guard initialContentSize.width > 1, initialContentSize.height > 1 else { return } - let current = window.contentRect(forFrameRect: window.frame).size - guard current.width <= 1 || current.height <= 1 else { return } - window.setContentSize(initialContentSize) - } - private static func rounded(_ size: NSSize) -> NSSize { NSSize(width: ceil(size.width), height: ceil(size.height)) } From cbd26ea4e9ffd8e2a476c9a2f43f750a131dcbc7 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 19:46:42 -0700 Subject: [PATCH 18/36] Retain cloud sheet controllers while presented --- Sources/Cloud/CloudCreateTeamSheetPresenter.swift | 3 +++ Sources/Cloud/CloudNetworkPolicySheetPresenter.swift | 3 +++ Sources/Cloud/CloudSheetWindow.swift | 4 ++-- Sources/Cloud/NewMachineSheetPresenter.swift | 3 +++ 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/Sources/Cloud/CloudCreateTeamSheetPresenter.swift b/Sources/Cloud/CloudCreateTeamSheetPresenter.swift index 91758c19757e..b0390ac97ea1 100644 --- a/Sources/Cloud/CloudCreateTeamSheetPresenter.swift +++ b/Sources/Cloud/CloudCreateTeamSheetPresenter.swift @@ -8,6 +8,7 @@ import SwiftUI final class CloudCreateTeamSheetPresenter: NSObject, NSWindowDelegate { private let resolveHostWindow: @MainActor (NSWindow?) -> NSWindow? private var sheetWindow: NSWindow? + private var sheetController: CloudSheetWindow? private weak var hostWindow: NSWindow? /// Identifies the current sheet, so a late finish from an earlier sheet /// cannot close this one. @@ -61,6 +62,7 @@ final class CloudCreateTeamSheetPresenter: NSObject, NSWindowDelegate { window.delegate = self window.title = String(localized: "cloud.teamPicker.createSheet.title", defaultValue: "Create Team") window.isReleasedWhenClosed = false + sheetController = sheet sheetWindow = window let host = resolveHostWindow(preferredWindow ?? NSApp.keyWindow) @@ -92,6 +94,7 @@ final class CloudCreateTeamSheetPresenter: NSObject, NSWindowDelegate { } private func reset() { + sheetController = nil sheetWindow = nil hostWindow = nil sessionID = nil diff --git a/Sources/Cloud/CloudNetworkPolicySheetPresenter.swift b/Sources/Cloud/CloudNetworkPolicySheetPresenter.swift index 053f0a444e34..36fdda7fdf7e 100644 --- a/Sources/Cloud/CloudNetworkPolicySheetPresenter.swift +++ b/Sources/Cloud/CloudNetworkPolicySheetPresenter.swift @@ -10,6 +10,7 @@ final class CloudNetworkPolicySheetPresenter { static let shared = CloudNetworkPolicySheetPresenter() private var sheetWindow: NSWindow? + private var sheetController: CloudSheetWindow? private var hostWindow: NSWindow? private var model: CloudNetworkPolicySheetModel? private var loadTask: Task? @@ -40,6 +41,7 @@ final class CloudNetworkPolicySheetPresenter { window.title = String(localized: "cloud.network.section.label", defaultValue: "Network") window.isReleasedWhenClosed = false self.model = model + sheetController = sheet sheetWindow = window loadTask = Task { [weak model] in await model?.load() } @@ -61,6 +63,7 @@ final class CloudNetworkPolicySheetPresenter { host.endSheet(window) } window.orderOut(nil) + sheetController = nil sheetWindow = nil hostWindow = nil model = nil diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index 355ce4159ba8..5b63ed847e79 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -28,8 +28,8 @@ final class CloudSheetWindow { private var isResizeScheduled = false init(rootView: Content) { - // The root view retains this object through `report`; the window is - // weakly reachable from here only through `window`, so no cycle. + // The presenter retains this wrapper while the window is presented; + // the root view retains the reporter that points back to this owner. let reporter = SizeReporter() let controller = NSHostingController(rootView: CloudSheetContent(content: rootView, report: reporter)) controller.sizingOptions = [] diff --git a/Sources/Cloud/NewMachineSheetPresenter.swift b/Sources/Cloud/NewMachineSheetPresenter.swift index fcb9bcfe011a..c0358f442d9c 100644 --- a/Sources/Cloud/NewMachineSheetPresenter.swift +++ b/Sources/Cloud/NewMachineSheetPresenter.swift @@ -12,6 +12,7 @@ final class NewMachineSheetPresenter: NSObject, NewMachineSheetPresenting { static let shared = NewMachineSheetPresenter() private var sheetWindow: NSWindow? + private var sheetController: CloudSheetWindow? private var hostWindow: NSWindow? private var model: NewMachineModel? private var pendingSelectionID: UUID? @@ -180,6 +181,7 @@ final class NewMachineSheetPresenter: NSObject, NewMachineSheetPresenting { self?.dismiss() } self.model = model + sheetController = sheet sheetWindow = window NotificationCenter.default.addObserver( self, @@ -446,6 +448,7 @@ final class NewMachineSheetPresenter: NSObject, NewMachineSheetPresenting { host.endSheet(window) } window.orderOut(nil) + sheetController = nil sheetWindow = nil hostWindow = nil model = nil From c6a68c339b248a4043583c881d04b2bcb9c284b9 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 19:49:06 -0700 Subject: [PATCH 19/36] Fix intrinsic sizing for attached cloud sheets --- Sources/Cloud/CloudSheetWindow.swift | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index 5b63ed847e79..1c7b780d47a1 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -123,7 +123,13 @@ struct CloudSheetContent: View { var body: some View { content - .fixedSize(horizontal: false, vertical: true) + // Sheets in this wrapper all declare a natural width. Measuring + // horizontally as flexible lets an attached sheet's temporary + // 1-point proposal collapse the content to 1×0, so later model + // updates never produce a usable geometry report. Keep both axes + // intrinsic while the wrapper applies the measured size outside + // AppKit's layout pass. + .fixedSize(horizontal: true, vertical: true) .onGeometryChange(for: CGSize.self) { proxy in proxy.size } action: { size in From a17a52a2f026517f6de09245384603f874585017 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 20:18:36 -0700 Subject: [PATCH 20/36] Measure cloud sheets before attachment --- Sources/Cloud/CloudSheetWindow.swift | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index 1c7b780d47a1..a4f8357a60ca 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -34,7 +34,12 @@ final class CloudSheetWindow { let controller = NSHostingController(rootView: CloudSheetContent(content: rootView, report: reporter)) controller.sizingOptions = [] window = NSWindow(contentViewController: controller) - let initialSize = controller.view.fittingSize + // NSHostingController's flexible root view can report its temporary + // attached-sheet proposal (1×0). Measure an unattached hosting view so + // the first window frame is based on the content's intrinsic size. + let initialSize = NSHostingView( + rootView: CloudSheetContent(content: rootView, report: reporter) + ).fittingSize initialContentSize = Self.rounded(initialSize) if initialSize.width > 0, initialSize.height > 0 { window.setContentSize(initialContentSize) From 74850a09707b15858fc36d7f651ce3ffb9c22055 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 20:26:06 -0700 Subject: [PATCH 21/36] Measure cloud sheet content without an infinite frame --- Sources/Cloud/CloudSheetWindow.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index a4f8357a60ca..3248992cc0fc 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -140,6 +140,5 @@ struct CloudSheetContent: View { } action: { size in report.owner?.contentIdealSizeChanged(size) } - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) } } From 8405411c8572f00e14aab1e4df500272543e4334 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 22:07:37 -0700 Subject: [PATCH 22/36] Preserve cloud sheet anchor during size restoration --- Sources/Cloud/CloudSheetWindow.swift | 26 +++++++++++++++------- cmuxTests/NewMachineSheetLayoutTests.swift | 2 ++ 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index 3248992cc0fc..09b14d209c5e 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -56,20 +56,14 @@ final class CloudSheetWindow { // Some AppKit versions reset a newly attached sheet to a 1×0 content // rect while the host is inactive. Restore the measured first layout // before applying any later geometry report. - let current = window.contentRect(forFrameRect: window.frame).size - if (current.width <= 1 || current.height <= 1), initialContentSize.width > 0, initialContentSize.height > 0 { - window.setContentSize(initialContentSize) - } + restoreInitialContentSizeIfNeeded() applyPendingContentSize() // AppKit may perform one more sheet-host layout on the next turn and // reset the frame after beginSheet returns. Reapply after that pass so // the first geometry report has a usable window to measure against. DispatchQueue.main.async { [weak self] in guard let self else { return } - let current = self.window.contentRect(forFrameRect: self.window.frame).size - if (current.width <= 1 || current.height <= 1), self.initialContentSize.width > 0, self.initialContentSize.height > 0 { - self.window.setContentSize(self.initialContentSize) - } + self.restoreInitialContentSizeIfNeeded() self.applyPendingContentSize() } } @@ -109,6 +103,22 @@ final class CloudSheetWindow { window.setFrame(frame, display: window.isVisible, animate: false) } + private func restoreInitialContentSizeIfNeeded() { + guard initialContentSize.width > 1, initialContentSize.height > 1 else { return } + let current = window.contentRect(forFrameRect: window.frame).size + guard current.width <= 1 || current.height <= 1 else { return } + + // An attached sheet hangs from its top edge. setContentSize preserves + // the bottom-left origin, which detaches the sheet from its host when + // repairing AppKit's temporary 1×0 frame. Restore through a frame so + // the top edge remains anchored while the content gets its size back. + let oldFrame = window.frame + var frame = window.frameRect(forContentRect: NSRect(origin: .zero, size: initialContentSize)) + frame.origin.x = oldFrame.midX - frame.width / 2 + frame.origin.y = oldFrame.maxY - frame.height + window.setFrame(frame, display: window.isVisible, animate: false) + } + private static func rounded(_ size: NSSize) -> NSSize { NSSize(width: ceil(size.width), height: ceil(size.height)) } diff --git a/cmuxTests/NewMachineSheetLayoutTests.swift b/cmuxTests/NewMachineSheetLayoutTests.swift index 8b7c80ff2161..0581db8a3f46 100644 --- a/cmuxTests/NewMachineSheetLayoutTests.swift +++ b/cmuxTests/NewMachineSheetLayoutTests.swift @@ -102,6 +102,7 @@ struct NewMachineSheetLayoutTests { NewMachineSheetPresenter.shared.present(model: model, preferredWindow: host, loadPlanFromCache: false) defer { model.cancel() } let sheet = try #require(host.attachedSheet, "the sheet was not attached to its host window") + let initialTopEdge = sheet.frame.maxY for tick in 0..<12 { let pool = CloudVMResourcePool(poolVcpus: 40, poolMemoryMb: 81920, usedVcpus: 32 + tick % 3, usedMemoryMb: 65536) @@ -124,6 +125,7 @@ struct NewMachineSheetLayoutTests { let content = sheet.contentRect(forFrameRect: sheet.frame).size #expect(abs(content.height - ceil(ideal.height)) <= 1, "sheet content \(content) does not fit its content \(ideal)") #expect(abs(content.width - ceil(ideal.width)) <= 1, "sheet content \(content) does not fit its content \(ideal)") + #expect(abs(sheet.frame.maxY - initialTopEdge) <= 1, "sheet top edge moved from \(initialTopEdge) to \(sheet.frame.maxY)") } /// The grid's pop-ups read as one column: each starts at the column's From 5020295f0c39f579a7ab15e2ebd4fe827cf6a034 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Thu, 8 Oct 2026 22:34:49 -0700 Subject: [PATCH 23/36] Drive attached sheet layout before measuring --- cmuxTests/NewMachineSheetLayoutTests.swift | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/cmuxTests/NewMachineSheetLayoutTests.swift b/cmuxTests/NewMachineSheetLayoutTests.swift index 0581db8a3f46..0c602c4e0a12 100644 --- a/cmuxTests/NewMachineSheetLayoutTests.swift +++ b/cmuxTests/NewMachineSheetLayoutTests.swift @@ -119,9 +119,21 @@ struct NewMachineSheetLayoutTests { Self.runMainLoopTurns() } model.selectBaseImage(.machine(model.sourceMachines[3])) - Self.runMainLoopTurns() let ideal = NSHostingView(rootView: NewMachineSheet(model: model)).fittingSize + // The attached sheet's hosting view is not necessarily laid out just + // because the model changed. Drive the same layout/display path used + // by the detached rendering helpers until the async geometry report + // has been applied, or until the bounded test deadline expires. + for _ in 0..<100 { + sheet.contentView?.layoutSubtreeIfNeeded() + sheet.displayIfNeeded() + let content = sheet.contentRect(forFrameRect: sheet.frame).size + if abs(content.height - ceil(ideal.height)) <= 1, abs(content.width - ceil(ideal.width)) <= 1 { + break + } + _ = RunLoop.main.run(mode: .default, before: Date(timeIntervalSinceNow: 0.01)) + } let content = sheet.contentRect(forFrameRect: sheet.frame).size #expect(abs(content.height - ceil(ideal.height)) <= 1, "sheet content \(content) does not fit its content \(ideal)") #expect(abs(content.width - ceil(ideal.width)) <= 1, "sheet content \(content) does not fit its content \(ideal)") From 568d028e853b714e8f797a867411f3c6f9400336 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:14:58 -0700 Subject: [PATCH 24/36] test: stabilize cloud sheet anchor and defaults policy --- Resources/bin/cmux-claude-wrapper | 23 +++++++++++----------- cmuxTests/NewMachineSheetLayoutTests.swift | 5 +++++ 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/Resources/bin/cmux-claude-wrapper b/Resources/bin/cmux-claude-wrapper index 3b7c6b0807a6..36446b43f51b 100755 --- a/Resources/bin/cmux-claude-wrapper +++ b/Resources/bin/cmux-claude-wrapper @@ -1413,25 +1413,24 @@ cmux_claude_sideload_flags_disabled_uncached() { local domain_dump flag_value local newline=$'\n' local flag_prefix=$'\n disableSideloadFlags = ' - local escaped_newline='\\n' quoted_one='"1' quoted_end='";' + local quoted_one='"1' quoted_end='";' if domain_dump="$("$defaults_bin" read "$plist_domain" 2>/dev/null)"; then domain_dump="$newline$domain_dump$newline" [[ "$domain_dump" == *"$newline policyHelper = "* ]] && return 0 flag_value="${domain_dump#*"$flag_prefix"}" if [[ "$flag_value" != "$domain_dump" ]]; then flag_value="${flag_value%%"$newline"*}" - # The per-key read printed `1` for true, 1, 1.0 and "1", which - # all dump as `1;`. It also printed `1` for "1" followed by - # newlines, because $(...) strips them; that dumps as - # `"1\\n";`, `"1\\n\\n";` and so on. + # The per-key read printed 1 for true, 1, 1.0 and "1", which + # all dump as 1;. For quoted values, ask the key-specific + # form only when the whole-domain dump could contain a trailing + # newline. Command substitution strips those newlines, matching + # the old per-key decision without depending on how this + # macOS version escapes backslashes in a whole-domain dump. [[ "$flag_value" == "1;" ]] && return 0 - if [[ "$flag_value" == "$quoted_one$escaped_newline"*"$quoted_end" ]]; then - flag_value="${flag_value#"$quoted_one"}" - flag_value="${flag_value%"$quoted_end"}" - while [[ "$flag_value" == "$escaped_newline"* ]]; do - flag_value="${flag_value#"$escaped_newline"}" - done - [[ -z "$flag_value" ]] && return 0 + if [[ "$flag_value" == "$quoted_one"*"$quoted_end" ]]; then + local per_key_value + per_key_value="$("$defaults_bin" read "$plist_domain" disableSideloadFlags 2>/dev/null)" || per_key_value="" + [[ "$per_key_value" == "1" ]] && return 0 fi fi fi diff --git a/cmuxTests/NewMachineSheetLayoutTests.swift b/cmuxTests/NewMachineSheetLayoutTests.swift index 0c602c4e0a12..b27eff9412f5 100644 --- a/cmuxTests/NewMachineSheetLayoutTests.swift +++ b/cmuxTests/NewMachineSheetLayoutTests.swift @@ -102,6 +102,11 @@ struct NewMachineSheetLayoutTests { NewMachineSheetPresenter.shared.present(model: model, preferredWindow: host, loadPlanFromCache: false) defer { model.cancel() } let sheet = try #require(host.attachedSheet, "the sheet was not attached to its host window") + // AppKit may finish attaching and restore the initial sheet frame on + // the next main-loop turn. Capture the anchor after that deferred + // pass so later content-driven resizes are compared with the stable + // attached frame rather than the temporary 1×0 frame. + Self.runMainLoopTurns() let initialTopEdge = sheet.frame.maxY for tick in 0..<12 { From bf6e7314fea7023ae114e17b3af1f69e8ea5de32 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:19:22 -0700 Subject: [PATCH 25/36] docs: clarify managed defaults fallback --- Resources/bin/cmux-claude-wrapper | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Resources/bin/cmux-claude-wrapper b/Resources/bin/cmux-claude-wrapper index 36446b43f51b..d52e64b98b23 100755 --- a/Resources/bin/cmux-claude-wrapper +++ b/Resources/bin/cmux-claude-wrapper @@ -1421,11 +1421,10 @@ cmux_claude_sideload_flags_disabled_uncached() { if [[ "$flag_value" != "$domain_dump" ]]; then flag_value="${flag_value%%"$newline"*}" # The per-key read printed 1 for true, 1, 1.0 and "1", which - # all dump as 1;. For quoted values, ask the key-specific - # form only when the whole-domain dump could contain a trailing - # newline. Command substitution strips those newlines, matching - # the old per-key decision without depending on how this - # macOS version escapes backslashes in a whole-domain dump. + # all dump as 1;. For quoted values, ask the key-specific form + # to preserve the old per-key decision without depending on + # how this macOS version escapes backslashes in a whole-domain + # dump. Command substitution still strips trailing newlines. [[ "$flag_value" == "1;" ]] && return 0 if [[ "$flag_value" == "$quoted_one"*"$quoted_end" ]]; then local per_key_value From 71e1ab1c47b8dc2b9e7d877a04fb7fcee07d0adf Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:22:22 -0700 Subject: [PATCH 26/36] perf: limit managed defaults fallback reads --- Resources/bin/cmux-claude-wrapper | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Resources/bin/cmux-claude-wrapper b/Resources/bin/cmux-claude-wrapper index d52e64b98b23..693c396c847b 100755 --- a/Resources/bin/cmux-claude-wrapper +++ b/Resources/bin/cmux-claude-wrapper @@ -1426,7 +1426,7 @@ cmux_claude_sideload_flags_disabled_uncached() { # how this macOS version escapes backslashes in a whole-domain # dump. Command substitution still strips trailing newlines. [[ "$flag_value" == "1;" ]] && return 0 - if [[ "$flag_value" == "$quoted_one"*"$quoted_end" ]]; then + if [[ "$flag_value" == "$quoted_one"*"$quoted_end" && "$flag_value" == *\\* ]]; then local per_key_value per_key_value="$("$defaults_bin" read "$plist_domain" disableSideloadFlags 2>/dev/null)" || per_key_value="" [[ "$per_key_value" == "1" ]] && return 0 From be826f366dc8afaa8aab144a8bb1bc215921f360 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:53:22 -0700 Subject: [PATCH 27/36] fix: preserve attached cloud sheet top edge --- Sources/Cloud/CloudSheetWindow.swift | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index 09b14d209c5e..4d92627a5950 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -26,6 +26,10 @@ final class CloudSheetWindow { private var isOpening = false private var pendingContentSize: NSSize? private var isResizeScheduled = false + // AppKit may expand an attached sheet from its bottom edge before the + // deferred geometry callback runs. Keep the first stable top edge so a + // content-driven resize cannot inherit that temporary shift. + private var topEdgeAnchor: CGFloat? init(rootView: Content) { // The presenter retains this wrapper while the window is presented; @@ -64,6 +68,7 @@ final class CloudSheetWindow { DispatchQueue.main.async { [weak self] in guard let self else { return } self.restoreInitialContentSizeIfNeeded() + self.topEdgeAnchor = self.topEdgeAnchor ?? self.window.frame.maxY self.applyPendingContentSize() } } @@ -74,6 +79,7 @@ final class CloudSheetWindow { window.center() window.makeKeyAndOrderFront(nil) isOpening = false + topEdgeAnchor = window.frame.maxY applyPendingContentSize() } @@ -99,7 +105,7 @@ final class CloudSheetWindow { let oldFrame = window.frame var frame = window.frameRect(forContentRect: NSRect(origin: .zero, size: size)) frame.origin.x = oldFrame.midX - frame.width / 2 - frame.origin.y = oldFrame.maxY - frame.height + frame.origin.y = (topEdgeAnchor ?? oldFrame.maxY) - frame.height window.setFrame(frame, display: window.isVisible, animate: false) } @@ -115,7 +121,7 @@ final class CloudSheetWindow { let oldFrame = window.frame var frame = window.frameRect(forContentRect: NSRect(origin: .zero, size: initialContentSize)) frame.origin.x = oldFrame.midX - frame.width / 2 - frame.origin.y = oldFrame.maxY - frame.height + frame.origin.y = (topEdgeAnchor ?? oldFrame.maxY) - frame.height window.setFrame(frame, display: window.isVisible, animate: false) } From 81906387dd419eefa0b413bbfa0b2a87c1e2af92 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:18:57 -0700 Subject: [PATCH 28/36] fix: follow moved cloud sheet hosts --- Sources/Cloud/CloudSheetWindow.swift | 50 +++++++++++++++++++++- cmuxTests/NewMachineSheetLayoutTests.swift | 8 +++- 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index 4d92627a5950..f8529021e34b 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -30,6 +30,11 @@ final class CloudSheetWindow { // deferred geometry callback runs. Keep the first stable top edge so a // content-driven resize cannot inherit that temporary shift. private var topEdgeAnchor: CGFloat? + // Registration is main-actor-only; deinit only removes these opaque + // Foundation tokens through NotificationCenter's thread-safe cleanup API. + nonisolated(unsafe) private var windowMoveObserver: NSObjectProtocol? + nonisolated(unsafe) private var hostMoveObserver: NSObjectProtocol? + private var isApplyingFrame = false init(rootView: Content) { // The presenter retains this wrapper while the window is presented; @@ -49,11 +54,38 @@ final class CloudSheetWindow { window.setContentSize(initialContentSize) } reporter.owner = self + windowMoveObserver = NotificationCenter.default.addObserver( + forName: NSWindow.didMoveNotification, + object: window, + queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + self?.recordExternalMoveIfStable() + } + } + } + + deinit { + if let windowMoveObserver { + NotificationCenter.default.removeObserver(windowMoveObserver) + } + if let hostMoveObserver { + NotificationCenter.default.removeObserver(hostMoveObserver) + } } /// Attaches the sheet to `host`; the size is held until the open /// animation has finished. func beginSheet(on host: NSWindow, completionHandler: ((NSApplication.ModalResponse) -> Void)? = nil) { + hostMoveObserver = NotificationCenter.default.addObserver( + forName: NSWindow.didMoveNotification, + object: host, + queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + self?.recordExternalMoveIfStable() + } + } isOpening = true host.beginSheet(window, completionHandler: completionHandler) isOpening = false @@ -106,7 +138,7 @@ final class CloudSheetWindow { var frame = window.frameRect(forContentRect: NSRect(origin: .zero, size: size)) frame.origin.x = oldFrame.midX - frame.width / 2 frame.origin.y = (topEdgeAnchor ?? oldFrame.maxY) - frame.height - window.setFrame(frame, display: window.isVisible, animate: false) + setFrameInternally(frame) } private func restoreInitialContentSizeIfNeeded() { @@ -122,7 +154,23 @@ final class CloudSheetWindow { var frame = window.frameRect(forContentRect: NSRect(origin: .zero, size: initialContentSize)) frame.origin.x = oldFrame.midX - frame.width / 2 frame.origin.y = (topEdgeAnchor ?? oldFrame.maxY) - frame.height + setFrameInternally(frame) + } + + private func setFrameInternally(_ frame: NSRect) { + isApplyingFrame = true window.setFrame(frame, display: window.isVisible, animate: false) + isApplyingFrame = false + } + + private func recordExternalMoveIfStable() { + guard !isOpening, !isApplyingFrame else { return } + let contentSize = window.contentRect(forFrameRect: window.frame).size + // During attachment AppKit can briefly publish a 1×0 frame and move + // its bottom edge. It is not a user move and must not replace the + // stable anchor used to restore the initial content size. + guard contentSize.width > 1, contentSize.height > 1 else { return } + topEdgeAnchor = window.frame.maxY } private static func rounded(_ size: NSSize) -> NSSize { diff --git a/cmuxTests/NewMachineSheetLayoutTests.swift b/cmuxTests/NewMachineSheetLayoutTests.swift index b27eff9412f5..b75b9110d525 100644 --- a/cmuxTests/NewMachineSheetLayoutTests.swift +++ b/cmuxTests/NewMachineSheetLayoutTests.swift @@ -108,6 +108,12 @@ struct NewMachineSheetLayoutTests { // attached frame rather than the temporary 1×0 frame. Self.runMainLoopTurns() let initialTopEdge = sheet.frame.maxY + // Moving the host moves an attached sheet. Its later content-driven + // resizes must follow that new position instead of snapping back to + // the top edge captured at presentation. + host.setFrameOrigin(NSPoint(x: host.frame.minX, y: host.frame.minY - 80)) + Self.runMainLoopTurns() + let movedTopEdge = sheet.frame.maxY for tick in 0..<12 { let pool = CloudVMResourcePool(poolVcpus: 40, poolMemoryMb: 81920, usedVcpus: 32 + tick % 3, usedMemoryMb: 65536) @@ -142,7 +148,7 @@ struct NewMachineSheetLayoutTests { let content = sheet.contentRect(forFrameRect: sheet.frame).size #expect(abs(content.height - ceil(ideal.height)) <= 1, "sheet content \(content) does not fit its content \(ideal)") #expect(abs(content.width - ceil(ideal.width)) <= 1, "sheet content \(content) does not fit its content \(ideal)") - #expect(abs(sheet.frame.maxY - initialTopEdge) <= 1, "sheet top edge moved from \(initialTopEdge) to \(sheet.frame.maxY)") + #expect(abs(sheet.frame.maxY - movedTopEdge) <= 1, "sheet top edge moved from \(movedTopEdge) to \(sheet.frame.maxY) after the host moved (initially \(initialTopEdge))") } /// The grid's pop-ups read as one column: each starts at the column's From d5c996f9f5c4dd0fdabef64e25c5178ca2a011ab Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:22:00 -0700 Subject: [PATCH 29/36] test: verify attached sheet follows host --- cmuxTests/NewMachineSheetLayoutTests.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/cmuxTests/NewMachineSheetLayoutTests.swift b/cmuxTests/NewMachineSheetLayoutTests.swift index b75b9110d525..85310b5fcc4e 100644 --- a/cmuxTests/NewMachineSheetLayoutTests.swift +++ b/cmuxTests/NewMachineSheetLayoutTests.swift @@ -114,6 +114,7 @@ struct NewMachineSheetLayoutTests { host.setFrameOrigin(NSPoint(x: host.frame.minX, y: host.frame.minY - 80)) Self.runMainLoopTurns() let movedTopEdge = sheet.frame.maxY + #expect(abs(movedTopEdge - initialTopEdge) > 1, "moving the host did not move the attached sheet") for tick in 0..<12 { let pool = CloudVMResourcePool(poolVcpus: 40, poolMemoryMb: 81920, usedVcpus: 32 + tick % 3, usedMemoryMb: 65536) From 2276f9183b364f734a9f54f4452f801605b9d4ad Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:59:48 -0700 Subject: [PATCH 30/36] fix: preserve attached sheet anchor during resize --- Sources/Cloud/CloudSheetWindow.swift | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index f8529021e34b..72cd0e129cb7 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -60,7 +60,7 @@ final class CloudSheetWindow { queue: .main ) { [weak self] _ in MainActor.assumeIsolated { - self?.recordExternalMoveIfStable() + self?.recordFloatingWindowMoveIfStable() } } } @@ -83,7 +83,7 @@ final class CloudSheetWindow { queue: .main ) { [weak self] _ in MainActor.assumeIsolated { - self?.recordExternalMoveIfStable() + self?.recordHostMoveIfStable() } } isOpening = true @@ -163,7 +163,19 @@ final class CloudSheetWindow { isApplyingFrame = false } - private func recordExternalMoveIfStable() { + private func recordFloatingWindowMoveIfStable() { + // An attached sheet's frame can emit didMove after AppKit resizes it + // from the bottom edge. That is an internal layout move, not a new + // anchor; only floating windows can be moved directly by the user. + guard window.sheetParent == nil else { return } + recordStableTopEdge() + } + + private func recordHostMoveIfStable() { + recordStableTopEdge() + } + + private func recordStableTopEdge() { guard !isOpening, !isApplyingFrame else { return } let contentSize = window.contentRect(forFrameRect: window.frame).size // During attachment AppKit can briefly publish a 1×0 frame and move From 28bcd54e4393841721d80be18dd072743448c94b Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:41:25 -0700 Subject: [PATCH 31/36] fix: ignore stale host move notifications --- Sources/Cloud/CloudSheetWindow.swift | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index 72cd0e129cb7..bd43d73841a3 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -34,6 +34,9 @@ final class CloudSheetWindow { // Foundation tokens through NotificationCenter's thread-safe cleanup API. nonisolated(unsafe) private var windowMoveObserver: NSObjectProtocol? nonisolated(unsafe) private var hostMoveObserver: NSObjectProtocol? + private weak var hostWindow: NSWindow? + private var lastHostOrigin: NSPoint? + private var isAttachedToHost = false private var isApplyingFrame = false init(rootView: Content) { @@ -77,13 +80,16 @@ final class CloudSheetWindow { /// Attaches the sheet to `host`; the size is held until the open /// animation has finished. func beginSheet(on host: NSWindow, completionHandler: ((NSApplication.ModalResponse) -> Void)? = nil) { + hostWindow = host + lastHostOrigin = host.frame.origin + isAttachedToHost = true hostMoveObserver = NotificationCenter.default.addObserver( forName: NSWindow.didMoveNotification, object: host, queue: .main ) { [weak self] _ in MainActor.assumeIsolated { - self?.recordHostMoveIfStable() + self?.recordHostMoveIfStable(host) } } isOpening = true @@ -107,6 +113,9 @@ final class CloudSheetWindow { /// Shows the sheet as a centered floating window when no host is on screen. func orderFrontFloating() { + hostWindow = nil + lastHostOrigin = nil + isAttachedToHost = false isOpening = true window.center() window.makeKeyAndOrderFront(nil) @@ -167,11 +176,15 @@ final class CloudSheetWindow { // An attached sheet's frame can emit didMove after AppKit resizes it // from the bottom edge. That is an internal layout move, not a new // anchor; only floating windows can be moved directly by the user. - guard window.sheetParent == nil else { return } + guard !isAttachedToHost else { return } recordStableTopEdge() } - private func recordHostMoveIfStable() { + private func recordHostMoveIfStable(_ host: NSWindow) { + guard isAttachedToHost, hostWindow === host else { return } + guard !isOpening, !isApplyingFrame else { return } + guard host.frame.origin != lastHostOrigin else { return } + lastHostOrigin = host.frame.origin recordStableTopEdge() } From 64bbf3fbb8513692fff222e959dde4883a9d6d72 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:13:35 -0700 Subject: [PATCH 32/36] fix: refresh attached sheet anchor after host moves --- Sources/Cloud/CloudSheetWindow.swift | 36 +++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index bd43d73841a3..0b98fbb53258 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -37,6 +37,8 @@ final class CloudSheetWindow { private weak var hostWindow: NSWindow? private var lastHostOrigin: NSPoint? private var isAttachedToHost = false + private var isHostMovePending = false + private var isHostAnchorRefreshScheduled = false private var isApplyingFrame = false init(rootView: Content) { @@ -63,7 +65,12 @@ final class CloudSheetWindow { queue: .main ) { [weak self] _ in MainActor.assumeIsolated { - self?.recordFloatingWindowMoveIfStable() + guard let self else { return } + if self.isAttachedToHost { + self.recordAttachedSheetMoveIfHostMoveIsPending() + } else { + self.recordFloatingWindowMoveIfStable() + } } } } @@ -83,6 +90,7 @@ final class CloudSheetWindow { hostWindow = host lastHostOrigin = host.frame.origin isAttachedToHost = true + isHostMovePending = false hostMoveObserver = NotificationCenter.default.addObserver( forName: NSWindow.didMoveNotification, object: host, @@ -138,7 +146,7 @@ final class CloudSheetWindow { } private func applyPendingContentSize() { - guard !isOpening, let size = pendingContentSize else { return } + guard !isOpening, !isHostMovePending, let size = pendingContentSize else { return } pendingContentSize = nil let current = window.contentRect(forFrameRect: window.frame).size guard size != current else { return } @@ -185,7 +193,29 @@ final class CloudSheetWindow { guard !isOpening, !isApplyingFrame else { return } guard host.frame.origin != lastHostOrigin else { return } lastHostOrigin = host.frame.origin - recordStableTopEdge() + isHostMovePending = true + scheduleHostAnchorRefresh() + } + + private func recordAttachedSheetMoveIfHostMoveIsPending() { + guard isHostMovePending else { return } + guard !isOpening, !isApplyingFrame else { return } + let contentSize = window.contentRect(forFrameRect: window.frame).size + guard contentSize.width > 1, contentSize.height > 1 else { return } + topEdgeAnchor = window.frame.maxY + isHostMovePending = false + } + + private func scheduleHostAnchorRefresh() { + guard !isHostAnchorRefreshScheduled else { return } + isHostAnchorRefreshScheduled = true + DispatchQueue.main.async { [weak self] in + guard let self else { return } + self.isHostAnchorRefreshScheduled = false + guard self.isAttachedToHost, !self.isOpening, !self.isApplyingFrame else { return } + self.recordAttachedSheetMoveIfHostMoveIsPending() + self.applyPendingContentSize() + } } private func recordStableTopEdge() { From 3e4b0e35611db0c2d5059dea3cc9d6a60c805670 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:37:39 -0700 Subject: [PATCH 33/36] fix: correct attached sheet edge after resize --- Sources/Cloud/CloudSheetWindow.swift | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index 0b98fbb53258..b61adc181221 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -39,6 +39,7 @@ final class CloudSheetWindow { private var isAttachedToHost = false private var isHostMovePending = false private var isHostAnchorRefreshScheduled = false + private var isAnchorCorrectionScheduled = false private var isApplyingFrame = false init(rootView: Content) { @@ -156,6 +157,7 @@ final class CloudSheetWindow { frame.origin.x = oldFrame.midX - frame.width / 2 frame.origin.y = (topEdgeAnchor ?? oldFrame.maxY) - frame.height setFrameInternally(frame) + scheduleAttachedSheetAnchorCorrection() } private func restoreInitialContentSizeIfNeeded() { @@ -180,6 +182,22 @@ final class CloudSheetWindow { isApplyingFrame = false } + private func scheduleAttachedSheetAnchorCorrection() { + guard isAttachedToHost, topEdgeAnchor != nil, !isAnchorCorrectionScheduled else { return } + isAnchorCorrectionScheduled = true + DispatchQueue.main.async { [weak self] in + guard let self else { return } + self.isAnchorCorrectionScheduled = false + guard self.isAttachedToHost, !self.isOpening, !self.isApplyingFrame, + let anchor = self.topEdgeAnchor else { return } + let delta = anchor - self.window.frame.maxY + guard abs(delta) > 0.5 else { return } + var frame = self.window.frame + frame.origin.y += delta + self.setFrameInternally(frame) + } + } + private func recordFloatingWindowMoveIfStable() { // An attached sheet's frame can emit didMove after AppKit resizes it // from the bottom edge. That is an internal layout move, not a new From 695b868bd2e70bb8d81a24422c78cfa6aec36005 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:13:49 -0700 Subject: [PATCH 34/36] fix: repair attached sheet anchor after appkit moves --- Sources/Cloud/CloudSheetWindow.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index b61adc181221..b79976815e87 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -69,6 +69,7 @@ final class CloudSheetWindow { guard let self else { return } if self.isAttachedToHost { self.recordAttachedSheetMoveIfHostMoveIsPending() + self.scheduleAttachedSheetAnchorCorrection() } else { self.recordFloatingWindowMoveIfStable() } From 25501d2c167e024afae2a96d7434410ce65cb4e6 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:30:57 -0700 Subject: [PATCH 35/36] fix: apply pending sheet size after host move --- Sources/Cloud/CloudSheetWindow.swift | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index b79976815e87..439297e2fed7 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -68,7 +68,14 @@ final class CloudSheetWindow { MainActor.assumeIsolated { guard let self else { return } if self.isAttachedToHost { - self.recordAttachedSheetMoveIfHostMoveIsPending() + let didRefreshHostAnchor = self.recordAttachedSheetMoveIfHostMoveIsPending() + if didRefreshHostAnchor { + // A host move can arrive while AppKit still exposes a + // transient 1×0 sheet. The later sheet move completes + // the handshake; apply any content size that arrived + // while resizing was blocked. + self.applyPendingContentSize() + } self.scheduleAttachedSheetAnchorCorrection() } else { self.recordFloatingWindowMoveIfStable() @@ -216,13 +223,15 @@ final class CloudSheetWindow { scheduleHostAnchorRefresh() } - private func recordAttachedSheetMoveIfHostMoveIsPending() { - guard isHostMovePending else { return } - guard !isOpening, !isApplyingFrame else { return } + @discardableResult + private func recordAttachedSheetMoveIfHostMoveIsPending() -> Bool { + guard isHostMovePending else { return false } + guard !isOpening, !isApplyingFrame else { return false } let contentSize = window.contentRect(forFrameRect: window.frame).size - guard contentSize.width > 1, contentSize.height > 1 else { return } + guard contentSize.width > 1, contentSize.height > 1 else { return false } topEdgeAnchor = window.frame.maxY isHostMovePending = false + return true } private func scheduleHostAnchorRefresh() { From f7b26fe39950a4d02a916cb73318eb988d687176 Mon Sep 17 00:00:00 2001 From: Austin Wang <38676809+austinywang@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:33:53 -0700 Subject: [PATCH 36/36] fix: defer sheet anchor correction during host moves --- Sources/Cloud/CloudSheetWindow.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Sources/Cloud/CloudSheetWindow.swift b/Sources/Cloud/CloudSheetWindow.swift index 439297e2fed7..05733f368dfe 100644 --- a/Sources/Cloud/CloudSheetWindow.swift +++ b/Sources/Cloud/CloudSheetWindow.swift @@ -191,12 +191,13 @@ final class CloudSheetWindow { } private func scheduleAttachedSheetAnchorCorrection() { - guard isAttachedToHost, topEdgeAnchor != nil, !isAnchorCorrectionScheduled else { return } + guard isAttachedToHost, !isHostMovePending, topEdgeAnchor != nil, !isAnchorCorrectionScheduled else { return } isAnchorCorrectionScheduled = true DispatchQueue.main.async { [weak self] in guard let self else { return } self.isAnchorCorrectionScheduled = false guard self.isAttachedToHost, !self.isOpening, !self.isApplyingFrame, + !self.isHostMovePending, let anchor = self.topEdgeAnchor else { return } let delta = anchor - self.window.frame.maxY guard abs(delta) > 0.5 else { return }