Repository navigation
cloud: share a port with your team from the sidebar #17122
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lucasr1b
wants to merge
43
commits into
main
Choose a base branch
from
cloud-port-share
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,615
−887
Open
Changes from 15 commits
Commits
Show all changes
43 commits
Select commit
Hold shift + click to select a range
ec98a52
web: optional edge-only forward-auth origin for publications
lucasr1b 4a578c0
cloud: share a port with your team from the sidebar
lucasr1b 421664f
cloud: port share button always visible, link icon, inline copied note
lucasr1b b963458
cloud: neutral share labels, keep the copied note visible
lucasr1b 75704a7
web: name the forward-auth origin in its validation error, document i…
lucasr1b 0474417
cloud: port share review fixes
lucasr1b 71f01f9
Merge remote-tracking branch 'origin/publication-edge-origin' into cl…
lucasr1b 520099f
web: blank forward-auth origin means unset
lucasr1b 3ae2ec4
Merge remote-tracking branch 'origin/publication-edge-origin' into cl…
lucasr1b c899316
Merge origin/main into cloud-port-share
austinywang a1dad97
Merge origin/main into cloud-port-share
austinywang b727789
fix(web): treat blank forward-auth origin as unset
austinywang 1eb03e9
Merge main (186cec797812) into pr-17123
austinywang 9cd54c1
Merge remote-tracking branch 'origin/publication-edge-origin' into cl…
austinywang da3435e
Merge green main into cloud-port-share
austinywang 21c4a11
Test cancelled port sharing and migration fetch fallback
austinywang 536cfb0
Harden port share cancellation and CI fetch fallback
austinywang 16e0e6c
Wait for public port shares to reach the edge
austinywang 8f2ae9a
Make port probe transport testable
austinywang e1050c3
Restore deterministic browser test window helper
austinywang feab59a
Cover port probe transport with injectable session
austinywang e537663
Stabilize cloud sheet layout checks
austinywang 7699afd
Fix deferred cloud sheet size reset
austinywang cfff115
Defer sheet size restoration after attachment
austinywang cbd26ea
Retain cloud sheet controllers while presented
austinywang c6a68c3
Fix intrinsic sizing for attached cloud sheets
austinywang a17a52a
Measure cloud sheets before attachment
austinywang 74850a0
Measure cloud sheet content without an infinite frame
austinywang 8405411
Preserve cloud sheet anchor during size restoration
austinywang 5020295
Drive attached sheet layout before measuring
austinywang 568d028
test: stabilize cloud sheet anchor and defaults policy
austinywang bf6e731
docs: clarify managed defaults fallback
austinywang 71e1ab1
perf: limit managed defaults fallback reads
austinywang be826f3
fix: preserve attached cloud sheet top edge
austinywang 8190638
fix: follow moved cloud sheet hosts
austinywang d5c996f
test: verify attached sheet follows host
austinywang 2276f91
fix: preserve attached sheet anchor during resize
austinywang 28bcd54
fix: ignore stale host move notifications
austinywang 64bbf3f
fix: refresh attached sheet anchor after host moves
austinywang 3e4b0e3
fix: correct attached sheet edge after resize
austinywang 695b868
fix: repair attached sheet anchor after appkit moves
austinywang 25501d2
fix: apply pending sheet size after host move
austinywang f7b26fe
fix: defer sheet anchor correction during host moves
austinywang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
153 changes: 153 additions & 0 deletions
153
Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareService.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| 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 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. 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, | ||
| port: port, | ||
| hostname: nil, | ||
| accessMode: nil, | ||
| teamID: nil, | ||
| scopeTeamID: scopeTeamID | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| public enum CloudPortShareError: Error, Equatable, Sendable { | ||
| /// The link exists but did not start serving within the wait. | ||
| case stillProvisioning | ||
| } | ||
|
|
||
| /// 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, 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(4), .seconds(5), | ||
| .seconds(5), .seconds(10), .seconds(10), .seconds(10), .seconds(10), | ||
| ] | ||
|
|
||
| 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 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 && $0.domainKind == "generated" && Self.isLive($0.state) | ||
| } | ||
| } | ||
|
|
||
| /// 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 delays = pollDelays.makeIterator() | ||
| var publication = try await existing(vmID: vmID, port: port, teamID: teamID) | ||
| while true { | ||
| 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 | ||
| } | ||
| } | ||
| 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) | ||
| } | ||
| } | ||
|
|
||
| /// 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 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 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. | ||
| public static let signedOutStatus: Probe = { url in | ||
| let configuration = URLSessionConfiguration.ephemeral | ||
| configuration.timeoutIntervalForRequest = 5 | ||
| 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 = "HEAD" | ||
| 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 | ||
| } | ||
| } |
65 changes: 65 additions & 0 deletions
65
Packages/macOS/CmuxCloud/Sources/CmuxCloud/VMClient/CloudPortShareStore.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| 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 | ||
| @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 | ||
| } | ||
|
|
||
| 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 typealias Sleep = @Sendable (Duration) async throws -> Void | ||
|
|
||
| public static let shared = CloudPortShareStore() | ||
|
|
||
| public private(set) var phases: [Key: Phase] = [:] | ||
| @ObservationIgnored private var resetTasks: [Key: Task<Void, Never>] = [:] | ||
| @ObservationIgnored private let sleep: Sleep | ||
|
|
||
| /// `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] } | ||
|
|
||
| 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 } | ||
| let sleep = sleep | ||
| resetTasks[key] = Task { @MainActor [weak self] in | ||
| do { try await sleep(holdFor) } catch { return } | ||
| guard 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 | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 6252
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 42161
🏁 Script executed:
Repository: manaflow-ai/cmux
Length of output: 13352
Inject
CloudPortShareStorethrough the Cloud sidebar owner.CloudPortShareStore.sharedis new mutable runtime state.MachinesPanelViewalready createsCloudTreeNodeActions.bound(...)and passes the action bundle throughCloudTreeOutlineViewandCloudTreeCellViewtoCloudTreeRowHoverButtons. Use that composition path to create one store, inject it into the bound action, and pass the same instance toCloudPortShareButton. Then removeshared.This is required by the no-ambient-global-state rule. The current binding also prevents tests from substituting a store in the real action path.
🤖 Prompt for AI Agents