Skip to content
Merged
Show file tree
Hide file tree
Changes from 84 commits
Commits
Show all changes
112 commits
Select commit Hold shift + click to select a range
25f1b52
test: reproduce dropped Cloud placement diagnostics
austinywang Sep 20, 2026
720dbe0
test: reproduce structured provider failure misclassification
austinywang Sep 14, 2026
abf81ca
fix: prioritize HTTP status over provider missing-message heuristics
austinywang Sep 14, 2026
8b5a209
test: align VM stats fixture with ownership lookup
austinywang Sep 19, 2026
05ce6e3
fix: ignore invalid provider status sentinels
austinywang Sep 20, 2026
937d936
test: reproduce ambiguous guest install exits and lost rollback failures
austinywang Sep 14, 2026
6441a49
test: reproduce unsafe guest shim publication in real filesystem
austinywang Sep 14, 2026
e1d7d35
test: gate guest bootstrap rollback and idempotency on PostgreSQL
austinywang Sep 14, 2026
74e3dec
fix: verify guest CLI publication and retain unconfirmed allocations
austinywang Sep 14, 2026
00702e6
test: preserve full environment in guest CLI runtime fixture
austinywang Sep 15, 2026
dc6ce9a
fix: accept native Cloud placement diagnostics
austinywang Sep 20, 2026
3f318ca
test: verify guest installer integration with current browser and tim…
austinywang Sep 20, 2026
124e6ec
integrate: consolidate Cloud authentication deadline fixes
austinywang Sep 20, 2026
5e40f87
integrate: bound Cloud reads while retaining current resource and tea…
austinywang Sep 20, 2026
2725d74
fix: align guest regression fixtures and hosted runner selection
austinywang Sep 20, 2026
3839b65
ci: validate auth on the configured Swift package runner
austinywang Sep 20, 2026
72716d2
test: expose hidden Cloud refresh and mutation fanout regressions
austinywang Sep 20, 2026
26a3ef4
fix: bound Cloud read invalidation and cooldown ownership
austinywang Sep 20, 2026
67a8fb1
Merge current main and preserve landed Cloud fixes
austinywang Sep 20, 2026
b41abae
fix: preserve the absolute Cloud token deadline across phases
austinywang Sep 20, 2026
67e8928
chore: normalize Cloud read project entries
austinywang Sep 20, 2026
40413b6
test: evaluate mutable cooldown reads before assertion macros
austinywang Sep 20, 2026
870a5bb
test: reproduce rejected RC Cloud diagnostics
austinywang Sep 20, 2026
b1a6c3c
test: cover Cloud read gate revocation
austinywang Sep 20, 2026
c414a04
fix: enforce Cloud gates around shared reads
austinywang Sep 20, 2026
cc4e7ae
fix: accept release-candidate Cloud diagnostics
austinywang Sep 20, 2026
a94d5ef
test: reproduce stale Cloud stats batch replacement
austinywang Sep 20, 2026
6859a90
fix: replace stale Cloud stats batches
austinywang Sep 20, 2026
9bbce05
test: cover independent Cloud caller deadlines
austinywang Sep 20, 2026
593964f
fix: separate Cloud transport and caller deadlines
austinywang Sep 20, 2026
6fbafa6
Merge current main verification fixes
austinywang Sep 20, 2026
90652ba
test: cover team usage rate-limit cooldowns
austinywang Sep 20, 2026
4e525e1
fix: record usage cooldowns before HTTP rejection
austinywang Sep 20, 2026
2a2d12c
ci: require focused Cloud regression verdicts
austinywang Sep 20, 2026
ae60921
Merge landed auth fixes and preserve Cloud follow-ups
austinywang Sep 20, 2026
f0a3304
Merge latest main and reconcile concurrent guest setup
austinywang Sep 20, 2026
fecc288
Merge main preview updates and preserve Cloud project entries
austinywang Sep 20, 2026
68883b3
test: isolate ambient Git config in reftable fixture
austinywang Sep 20, 2026
e7f8e69
Merge latest main CI and reftable fixes
austinywang Sep 20, 2026
97d949b
ci: preserve focused Cloud guard step contract
austinywang Sep 20, 2026
e3c1aed
Merge latest main into Axiom Cloud coverage
austinywang Sep 20, 2026
5c777dd
fix Cloud review findings in Swift client and fixtures
austinywang Sep 20, 2026
20c95a5
fix Cloud cleanup and guest installation rollback
austinywang Sep 20, 2026
1f96860
fix guest prompt asset bundling and cleanup claim races
austinywang Sep 20, 2026
1226163
fence concurrent Cloud cleanup claims by lease time
austinywang Sep 20, 2026
91e7817
avoid duplicate in-process Cloud cleanup work
austinywang Sep 20, 2026
c0e9bda
stabilize Cloud cleanup test isolation and guest assets
austinywang Sep 20, 2026
0315a73
isolate guest cleanup fixture provider ids
austinywang Sep 20, 2026
bc36d65
close final Cloud review findings
austinywang Sep 20, 2026
28cb83e
harden final Cloud lifecycle review paths
austinywang Sep 20, 2026
0f7dc6e
Merge branch 'main' of https://github.com/manaflow-ai/cmux into feat-…
austinywang Sep 20, 2026
ed62571
fix offline first-load recovery state
austinywang Sep 20, 2026
eb5cb90
address Cloud review findings
austinywang Sep 20, 2026
c2a5e70
keep guest failure complexity within gate
austinywang Sep 20, 2026
c9f4fab
Merge branch 'main' of https://github.com/manaflow-ai/cmux into feat-…
austinywang Sep 20, 2026
df94720
keep Cloud acceptance suites out of batch shards
austinywang Sep 20, 2026
4485438
isolate Cloud network monitor ownership
austinywang Sep 20, 2026
bf16a4b
test Cloud identity and guest failure boundaries
austinywang Sep 20, 2026
37fad75
close Cloud identity and guest error boundaries
austinywang Sep 20, 2026
fe18715
normalize Cloud identity test wiring
austinywang Sep 20, 2026
79e7067
annotate Cloud identity tests on main actor
austinywang Sep 20, 2026
332b3f1
stabilize Cloud stats transport assertion
austinywang Sep 20, 2026
db91e34
gate Cloud stats overlap before release
austinywang Sep 20, 2026
cff081f
test strict provider deletion confirmation
austinywang Sep 20, 2026
5b2de01
preserve unconfirmed provider cleanup ownership
austinywang Sep 20, 2026
df1ac86
test strict Freestyle deletion confirmation
austinywang Sep 20, 2026
3a01475
preserve unknown provider deletion failures
austinywang Sep 20, 2026
dbfd7c8
complete Freestyle destroy fixture dependency
austinywang Sep 20, 2026
5ee8aa9
Merge branch 'main' of https://github.com/manaflow-ai/cmux into feat-…
austinywang Sep 20, 2026
726df3c
test explicit Cloud team usage
austinywang Sep 20, 2026
a64e449
preserve explicit Cloud team usage fence
austinywang Sep 20, 2026
f211bc1
Merge branch 'main' of https://github.com/manaflow-ai/cmux into feat-…
austinywang Sep 20, 2026
95b7f27
fence Cloud route results after await
austinywang Sep 21, 2026
b0f955a
fence private Cloud routes on policy revocation
austinywang Sep 21, 2026
8488a2c
Merge latest main and preserve Cloud installer fixes
austinywang Sep 21, 2026
524576f
reconcile guest distribution with transactional install
austinywang Sep 21, 2026
16af391
Merge origin/main and preserve Cloud read hardening
austinywang Sep 21, 2026
8d31156
Keep guest CLI distribution transactional
austinywang Sep 21, 2026
4992854
Use the Cloud operation context wrapper
austinywang Sep 21, 2026
c35d55f
Make guest distribution fixture paths explicit
austinywang Sep 21, 2026
2069f2a
Make guest distribution tests deterministic
austinywang Sep 21, 2026
ab9768d
Merge origin/main and preserve Cloud read coordination
austinywang Sep 21, 2026
6eca228
Close Cloud reachability and guest rollback review gaps
austinywang Sep 21, 2026
3725f6f
Broadcast Cloud reachability changes
austinywang Sep 21, 2026
93590a2
Restore structured guest rollback
austinywang Sep 21, 2026
a563611
Allow unreferenced guest release cache after rollback
austinywang Sep 21, 2026
e79e6ac
Align retry policy usage with main
austinywang Sep 21, 2026
f9183e4
Allow identity fixture team selection
austinywang Sep 21, 2026
3239933
Make explicit team usage test independent of selection
austinywang Sep 21, 2026
c3ec4d7
Replay current Cloud reachability to new subscribers
austinywang Sep 21, 2026
6c95ef3
Merge branch 'main' of https://github.com/manaflow-ai/cmux into feat-…
austinywang Sep 21, 2026
0178dc3
Merge branch 'main' of https://github.com/manaflow-ai/cmux into feat-…
austinywang Sep 23, 2026
b0c399a
chore: refresh generated config schema
austinywang Sep 23, 2026
8be0c85
Merge branch 'main' of https://github.com/manaflow-ai/cmux into feat-…
austinywang Sep 23, 2026
a118484
fix: align Cloud CI gates with current workflows
austinywang Sep 24, 2026
61472b2
fix: close current Cloud review findings
austinywang Sep 24, 2026
9c2ca27
ci: gate dual Xcode runner fallback
austinywang Sep 24, 2026
5fbf36a
fix: import Cloud read test fixture module
austinywang Sep 24, 2026
e8bfb10
test: cover Canvas zoom while a Markdown source editor is focused
austinywang Sep 24, 2026
4d38f45
fix: scope file-editor focus to file-editor shortcuts only
austinywang Sep 24, 2026
0987025
test: stop racing the hook queue's drain task for tool admission
teamleaderleo Sep 24, 2026
2346292
test: wait for child processes without pinning a global-pool thread
teamleaderleo Sep 23, 2026
21cabfb
test: wait for the key-window change instead of a fixed 50 ms
teamleaderleo Sep 23, 2026
baa7f27
test: scale the SSH retry-budget harness deadline with its attempts
teamleaderleo Sep 23, 2026
0fa1f55
Wait for config reload fanout by suspending, not spinning the run loop
teamleaderleo Sep 23, 2026
6846508
test: prove the font barrier holds the reload, not that it has not ru…
teamleaderleo Sep 24, 2026
fe8c900
test: settle earlier config reloads before the font-size reset checks
austinywang Sep 24, 2026
8e18225
Merge remote-tracking branch 'origin/main' into axiom/13151-green
austinywang Sep 24, 2026
ad02f4e
test: report the geometry behind a too-small Cloud failure card
teamleaderleo Sep 24, 2026
054bd4b
fix: import workspace liveness type
austinywang Sep 24, 2026
497209c
Merge remote-tracking branch 'origin/main' into axiom/13151-green
austinywang Sep 24, 2026
ae95394
Merge remote-tracking branch 'origin/main' into axiom/13151-green
austinywang Sep 24, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/auth-refresh-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@ concurrency:

jobs:
auth-refresh-tests:
runs-on: ${{ vars.MACOS_RUNNER_26 || 'blacksmith-6vcpu-macos-26' }}
runs-on: ${{ vars.MACOS_RUNNER_DUAL_XCODE || 'blacksmith-6vcpu-macos-15' }}
timeout-minutes: 15
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
with:
persist-credentials: false
- name: Select pinned Xcode
run: ./scripts/select-ci-xcode.sh
- name: Exercise shared refresh transport and deadlines without credentials
run: swift test --package-path vendor/stack-auth-swift-sdk-prerelease --filter 'RefreshLifecycleTests|RefreshDeadlineTests|RefreshTransportTimingTests|RateLimitRetryTests'
- name: Exercise coordinator cancellation, sessions, and recovery
Expand Down
5 changes: 3 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1746,8 +1746,9 @@ jobs:
# Separate invocations prove each selector executed tests; a healthy
# suite cannot mask a miswired or accidentally empty selector.
set -euo pipefail
for suite in CloudMachineDragSourceTests CloudMachineOrderingTests; do
test_log="$RUNNER_TEMP/cmux-cloud-ordering-${suite}.txt"
for suite in CloudMachineDragSourceTests CloudMachineOrderingTests \
CloudOperationRecorderTests CloudReadRequestCoordinatorTests VMClientReadCoalescingTests; do
test_log="$RUNNER_TEMP/cmux-cloud-acceptance-${suite}.txt"
scripts/ci/run-in-console-session.sh \
scripts/ci/run-app-host-xcodebuild.sh \
-xctestrun "$CMUX_APP_HOST_XCTESTRUN" \
Expand Down
66 changes: 66 additions & 0 deletions .github/workflows/cloud-vm-guest-install.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
name: Cloud VM guest installation

on:
pull_request:
paths:
- web/services/vms/drivers/**
- web/services/vms/guestCli*.ts
- web/services/vms/guestPrompt.ts
- web/services/vms/workflows.ts
- web/services/vms/repository.ts
- web/services/vms/routeHelpers.ts
- web/services/vms/vmErrorMessages.ts
- web/messages/**
- web/tests/vm-guest-*.test.ts
- web/tests/fixtures/freestyleGuest.ts
- web/tests/vm-workflows.test.ts
- web/package.json
- web/bun.lock
- .github/workflows/cloud-vm-guest-install.yml
workflow_dispatch: {}

permissions:
contents: read

concurrency:
group: cloud-vm-guest-install-${{ github.ref }}
cancel-in-progress: true

jobs:
guest-install:
runs-on: ${{ vars.LINUX_RUNNER || 'blacksmith-4vcpu-ubuntu-2404' }}
timeout-minutes: 15
defaults:
run:
working-directory: web
services:
postgres:
image: postgres:16-alpine@sha256:3c5c8892d184f738f4fe282d14ddaa613a38f00f4189d2d94725ebe6f2909ddb
env:
POSTGRES_DB: cmux_test
POSTGRES_PASSWORD: cmux
POSTGRES_USER: cmux
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U cmux -d cmux_test"
--health-interval 1s --health-timeout 5s --health-retries 30
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
with:
persist-credentials: false
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6
with:
bun-version: "1.3.14"
- run: bun install --frozen-lockfile
- name: SDK and guest filesystem regressions
run: bun test tests/vm-guest-install.test.ts tests/vm-guest-install-runtime.test.ts tests/vm-guest-install-deadline.test.ts tests/vm-guest-create-response.test.ts
- name: Migrate isolated database
env:
DATABASE_URL: postgres://cmux:cmux@localhost:5432/cmux_test
run: bunx drizzle-kit migrate --config drizzle.config.ts
- name: Guest provisioning and idempotency in PostgreSQL
env:
CMUX_DB_TEST: "1"
DATABASE_URL: postgres://cmux:cmux@localhost:5432/cmux_test
run: bun test --timeout=30000 --test-name-pattern 'guest bootstrap|unconfirmed guest' tests/vm-workflows.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ public struct StackAuthClient: AuthClient {
await stack.getAccessToken()
}

/// Resolves access with typed cancellation/deadline failures when supported.
/// - Parameter forceRefresh: Bypasses the cached token after server rejection.
/// - Returns: A usable access token, or `nil` when unavailable.
/// - Throws: Cancellation or a classified transient refresh failure.
public func resolvedAccessToken(forceRefresh: Bool) async throws -> String? {
let pair = await stack.resolvedTokenPair(forceRefresh: forceRefresh)
try Task.checkCancellation()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ extension AuthCoordinator {
}
try Task.checkCancellation()
guard !deadline.hasExpired() else { throw AuthError.timedOut }
return try await runTokenTouchingPhase(.accessToken, timeout: deadline.remaining()) {
return try await runTokenTouchingPhase(
.accessToken,
timeout: deadline.remaining(),
deadline: deadline
) {
return try await self.captureCloudTokens()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,28 @@ extension AuthCoordinator {
_ phase: AuthPhase,
timeout: Duration,
_ operation: @escaping @Sendable () async throws -> T
) async throws -> T {
try await runTokenTouchingPhase(
phase,
timeout: timeout,
deadline: clock.authTokenDeadline(after: timeout),
operation
)
}

func runTokenTouchingPhase<T: Sendable>(
_ phase: AuthPhase,
timeout: Duration,
deadline: AuthTokenDeadline,
_ operation: @escaping @Sendable () async throws -> T
) async throws -> T {
expireTimedOutTokenTouchingPhaseIfNeeded(phase)
guard timedOutTokenTouchingPhaseStates[phase] == nil else {
log.log("auth.phase=\(phase.rawValue) previous timed-out token work still active")
throw AuthError.timedOut
}
try Task.checkCancellation()
let deadline = clock.authTokenDeadline(after: timeout)
guard !deadline.hasExpired() else { throw AuthError.timedOut }
let phaseID = UUID()
let generation = sessionGeneration
let signOutEpoch = signOutEpoch
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,55 @@ import Testing
await waitUntilTokenTouchingCleanupFinished(coordinator)
}

@Test func inheritedDeadlineIsNotRebasedWhenTokenPhaseStartsLate() async {
let clock = ManualTestClock()
let deadline = clock.authTokenDeadline(after: .seconds(2))
clock.advance(by: .seconds(1))
let coordinator = makeCoordinator(client: FakeAuthClient(), clock: clock)
let entered = TestPhaseSignal()
let release = TestPhaseSignal()
let phase = Task {
try await coordinator.runTokenTouchingPhase(
.accessToken,
timeout: .seconds(2),
deadline: deadline
) {
await entered.markStarted()
await release.waitUntilStarted()
return "captured"
}
}

await entered.waitUntilStarted()
await clock.waitUntilSleepers()
clock.advance(by: .seconds(1))
// Even if the operation resumes first at the boundary, the phase's
// post-operation check must apply the inherited absolute deadline.
await release.markStarted()
await #expect(throws: AuthError.timedOut) { try await phase.value }
}

@Test func expiredInheritedDeadlineSkipsTokenOperation() async {
let clock = ManualTestClock()
let deadline = clock.authTokenDeadline(after: .seconds(2))
clock.advance(by: .seconds(2))
let coordinator = makeCoordinator(client: FakeAuthClient(), clock: clock)
let entered = TestPhaseSignal()
let phase = Task {
try await coordinator.runTokenTouchingPhase(
.accessToken,
timeout: .seconds(2),
deadline: deadline
) {
await entered.markStarted()
return "unexpected"
}
}

await #expect(throws: AuthError.timedOut) { try await phase.value }
#expect(await entered.didStart == false)
}

private func waitUntilTokenTouchingPhaseGated(_ coordinator: AuthCoordinator, phase: AuthPhase) async {
for _ in 0..<100 {
if coordinator.timedOutTokenTouchingPhaseStates[phase] != nil {
Expand Down
4 changes: 2 additions & 2 deletions Sources/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2558,12 +2558,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
let cloudTunnel = makeCloudTunnelCoordinator()
cloudTunnelCoordinator = cloudTunnel
CmuxTuiSurfaceProviderRegistry.shared.portAccess.coordinator = cloudTunnel
VMClient.bootstrap(auth: auth.coordinator, operations: cloudOperations)
let cloudReads = VMClient.bootstrap(auth: auth.coordinator, operations: cloudOperations)
TerminalController.shared.cloudTunnel = cloudTunnel
RemotesClient.bootstrap(auth: auth.coordinator)
AIAccountsClient.bootstrap(auth: auth.coordinator)
CoderouterClient.bootstrap(auth: auth.coordinator)
MachineUsageClient.bootstrap(auth: auth.coordinator, operations: cloudOperations)
MachineUsageClient.bootstrap(auth: auth.coordinator, operations: cloudOperations, readRequests: cloudReads)
PhonePushClient.shared.configure(auth: auth.coordinator)
MobileHostService.shared.configure(auth: auth.coordinator)
caffeineController.onStateChange = { [weak self] enabled in
Expand Down
8 changes: 8 additions & 0 deletions Sources/Cloud/CloudReadCooldownStore+Cooldown.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import Foundation

extension CloudReadCooldownStore {
struct Cooldown: Sendable {
let until: TimeInterval
let response: CloudReadRequestCoordinator.Response
}
}
8 changes: 8 additions & 0 deletions Sources/Cloud/CloudReadCooldownStore+Session.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import Foundation

extension CloudReadCooldownStore {
struct Session: Equatable, Sendable {
let accountID: String?
let generation: UInt64?
}
}
69 changes: 69 additions & 0 deletions Sources/Cloud/CloudReadCooldownStore.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import Foundation

/// Bounds retained throttling state without turning eviction into an early retry.
struct CloudReadCooldownStore: Sendable {
Comment thread
austinywang marked this conversation as resolved.
Resolved
private let capacity: Int
private var session: Session?
private var cooldowns: [CloudReadRequestCoordinator.Key: Cooldown] = [:]

init(capacity: Int = 256) {
self.capacity = max(1, capacity)
}

var retainedCount: Int { cooldowns.count }

mutating func activateSession(for key: CloudReadRequestCoordinator.Key) {
let incoming = Session(accountID: key.accountID, generation: key.generation)
guard incoming != session else { return }
if let session {
// AuthCoordinator generations increase across account replacement.
// An old read admitted late cannot reactivate a retired session.
guard let generation = incoming.generation else { return }
if let previousGeneration = session.generation, generation <= previousGeneration { return }
}
session = incoming
cooldowns.removeAll(keepingCapacity: true)
}

mutating func response(for key: CloudReadRequestCoordinator.Key, now: TimeInterval) -> CloudReadRequestCoordinator.Response? {
guard matchesSession(key) else { return nil }
prune(now: now)
return cooldowns[key]?.response
}

mutating func record(
_ key: CloudReadRequestCoordinator.Key, until: TimeInterval, now: TimeInterval,
response: CloudReadRequestCoordinator.Response
) {
guard matchesSession(key), until > now else { return }
prune(now: now)
let compactResponse = CloudReadRequestCoordinator.Response(
data: Data(#"{"error":"rate_limited"}"#.utf8),
http: HTTPURLResponse(
url: response.http.url ?? URL(fileURLWithPath: "/"), statusCode: 429,
httpVersion: nil, headerFields: nil
)!
)
let cooldown = Cooldown(until: until, response: compactResponse)
if let existing = cooldowns[key] {
if until > existing.until { cooldowns[key] = cooldown }
} else if cooldowns.count < capacity {
cooldowns[key] = cooldown
} else if let evicted = cooldowns.min(by: { $0.value.until < $1.value.until }) {
// Evict only an exact-key minimum when the bounded store is full.
// A session-wide barrier would fabricate 429s for unrelated paths;
// an evicted key may ask the server again, where its real minimum
// is enforced without blocking another machine's read.
cooldowns.removeValue(forKey: evicted.key)
cooldowns[key] = cooldown
}
}

private func matchesSession(_ key: CloudReadRequestCoordinator.Key) -> Bool {
session == Session(accountID: key.accountID, generation: key.generation)
}

private mutating func prune(now: TimeInterval) {
cooldowns = cooldowns.filter { $0.value.until > now }
}
}
52 changes: 52 additions & 0 deletions Sources/Cloud/CloudReadMutation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import Foundation

/// Identifies the read snapshots changed by one successful control-plane mutation.
struct CloudReadMutation: Sendable {
let scope: CloudReadRequestCoordinator.Key
let affectedPaths: Set<String>

init(method: String, scope: CloudReadRequestCoordinator.Key, responseData: Data) {
self.scope = scope
var paths: Set<String> = []
let parts = scope.path.split(separator: "/").map(String.init)
let createsMachine = method == "POST" && [
"/api/vm", "/api/vm/restore", "/api/vm/base/open", "/api/vm/base/reset"
].contains(scope.path)
var forksMachine = false
if createsMachine {
paths.insert("/api/vm")
paths.insert("/api/coderouter/vm-usage/team")
} else if parts.count >= 3, parts[0] == "api", parts[1] == "vm",
!["base", "restore", "tunnel", "publications", "domains"].contains(parts[2]) {
let machinePath = "/api/vm/\(parts[2])"
if parts.count == 3, method == "PATCH" || method == "DELETE" {
paths.insert("/api/vm")
paths.insert("/api/coderouter/vm-usage/team")
if method == "DELETE" { paths.insert("\(machinePath)/stats") }
} else if parts.count == 4, method == "POST", [
"pause", "resume", "resize", "fork", "attach-endpoint", "ssh-endpoint",
"scp-endpoint", "sessions", "exec", "open-port"
].contains(parts[3]) {
// Open/exec/file-transfer routes can wake a suspended machine.
// Other machines' samples remain valid while this one changes.
paths.insert("/api/vm")
paths.insert("\(machinePath)/stats")
if parts[3] == "fork" {
forksMachine = true
paths.insert("/api/coderouter/vm-usage/team")
}
}
}
if createsMachine || forksMachine {
if let object = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any],
let id = object["id"] as? String, !id.isEmpty {
var allowed = CharacterSet.urlPathAllowed
allowed.remove(charactersIn: "/?#")
if let encodedID = id.addingPercentEncoding(withAllowedCharacters: allowed) {
paths.insert("/api/vm/\(encodedID)/stats")
}
}
}
affectedPaths = paths
}
}
27 changes: 27 additions & 0 deletions Sources/Cloud/CloudReadNetworkMonitor.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import Foundation
@preconcurrency import Network

/// One path observer for the VM client. The actor owns the mutable
/// Network.framework monitor; only its sendable stream crosses the actor
/// boundary, and it never protects domain state or runs UI work.
actor CloudReadNetworkMonitor {
private let monitor: NWPathMonitor
nonisolated let updates: AsyncStream<Bool>

init() {
let monitor = NWPathMonitor()
self.monitor = monitor
let (updates, continuation) = AsyncStream<Bool>.makeStream(bufferingPolicy: .bufferingNewest(1))
self.updates = updates
monitor.pathUpdateHandler = { continuation.yield($0.status != .unsatisfied) }
continuation.onTermination = { _ in monitor.cancel() }
monitor.start(queue: DispatchQueue(label: "cmux.cloud.read-network"))
}

deinit { monitor.cancel() }
}

extension Notification.Name {
static let cmuxCloudReadNetworkChanged = Notification.Name("cmux.cloud.readNetworkChanged")
static let cmuxCloudReadNetworkRecovered = Notification.Name("cmux.cloud.readNetworkRecovered")
}
Loading
Loading