Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,40 @@ struct BrowserProfileRepositoryTests {
#expect(defaults.string(forKey: BrowserProfileRepository.lastUsedProfileDefaultsKey) == p.id.uuidString)
}

@Test func profileSelectionResolvesUUIDBeforeDisplayName() {
let (repo, _) = makeRepository()
let defaultID = BrowserProfileRepository.builtInDefaultProfileID
let namedLikeDefaultID = repo.createProfile(named: defaultID.uuidString)!

#expect(repo.resolveProfileSelection(defaultID.uuidString) == .matched(
repo.profileDefinition(id: defaultID)!
))
#expect(namedLikeDefaultID.id != defaultID)
}

@Test func profileSelectionFallsBackFromMissingUUIDToCaseInsensitiveDisplayName() {
let (repo, _) = makeRepository()
let missingID = UUID()
let namedLikeMissingID = repo.createProfile(named: missingID.uuidString)!
let work = repo.createProfile(named: "Work Profile")!

#expect(repo.resolveProfileSelection(missingID.uuidString.lowercased()) == .matched(namedLikeMissingID))
#expect(repo.resolveProfileSelection(" work profile ") == .matched(work))
}

@Test func profileSelectionReportsEveryAmbiguousDisplayNameCandidate() {
let (repo, _) = makeRepository()
let first = repo.createProfile(named: "Shared")!
let second = repo.createProfile(named: "shared")!

#expect(repo.resolveProfileSelection("SHARED") == .ambiguous([first, second]))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Order-sensitive ambiguity assertion will fail if implementation uses unordered storage

The assertion == .ambiguous([first, second]) depends on the implementation returning candidates in insertion/creation order. If resolveProfileSelection builds its candidate list from a Set, Dictionary, or any other unordered structure, this test will fail spuriously even when the result is semantically correct. The downstream socket test (BrowserProfileSocketTests) correctly avoids this by using Set-based comparison. Consider extracting IDs and comparing as a Set here too, or pinning the order expectation to whatever the production implementation guarantees (e.g. by name).

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 242422d: the test now compares the ambiguous candidate UUIDs as a Set, so it asserts membership without inventing an ordering contract.

— Claude Code

}

@Test func profileSelectionReportsUnknownSelector() {
let (repo, _) = makeRepository()
#expect(repo.resolveProfileSelection("Missing Profile") == .notFound)
}

@Test func effectiveLastUsedFallsBackWhenMissing() {
let (_, defaults) = makeRepository()
// Force lastUsed to a stale id via persistence, then reload.
Expand Down
4 changes: 4 additions & 0 deletions cmux.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources
B424PWRS000000000000PW01 /* BrowserPortalWebViewRenderingState.swift in Sources */ = {isa = PBXBuildFile; fileRef = B424PWRS000000000000PW02 /* BrowserPortalWebViewRenderingState.swift */; };
B4245003000000000000PW01 /* BrowserPrewarmedWebViewPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4245004000000000000PW01 /* BrowserPrewarmedWebViewPool.swift */; };
B6585001B6585001B658PW01 /* BrowserPrewarmedWebViewPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B6585002B6585002B658PW02 /* BrowserPrewarmedWebViewPoolTests.swift */; };
2720B0012720B0012720B001 /* BrowserProfileSocketTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2720F0012720F0012720F001 /* BrowserProfileSocketTests.swift */; };
8478A0000000000000000002 /* BrowserRecoveryHTTPServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8478A0000000000000000001 /* BrowserRecoveryHTTPServer.swift */; };
7B5F1A2E9C0D4B6A8E217304 /* BrowserReliabilityRegressionUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B5F1A2E9C0D4B6A8E217303 /* BrowserReliabilityRegressionUITests.swift */; };
BFBAC1A77CEE7A2DF91DA02C /* BrowserRemoteWorkspaceStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = 109D0E38E29A8779FA0BAE82 /* BrowserRemoteWorkspaceStatus.swift */; };
Expand Down Expand Up @@ -2636,6 +2637,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa =
B424PWRS000000000000PW02 /* BrowserPortalWebViewRenderingState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserPortalWebViewRenderingState.swift; sourceTree = "<group>"; };
B4245004000000000000PW01 /* BrowserPrewarmedWebViewPool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserPrewarmedWebViewPool.swift; sourceTree = "<group>"; };
B6585002B6585002B658PW02 /* BrowserPrewarmedWebViewPoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserPrewarmedWebViewPoolTests.swift; sourceTree = "<group>"; };
2720F0012720F0012720F001 /* BrowserProfileSocketTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserProfileSocketTests.swift; sourceTree = "<group>"; };
8478A0000000000000000001 /* BrowserRecoveryHTTPServer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserRecoveryHTTPServer.swift; sourceTree = "<group>"; };
7B5F1A2E9C0D4B6A8E217303 /* BrowserReliabilityRegressionUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserReliabilityRegressionUITests.swift; sourceTree = "<group>"; };
109D0E38E29A8779FA0BAE82 /* BrowserRemoteWorkspaceStatus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserRemoteWorkspaceStatus.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -6491,6 +6493,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa =
C46790000000000000000002 /* CLIForwardingLaunchArgumentTests.swift */,
C46790000000000000000008 /* RosettaNativeRelaunchTests.swift */,
C0DE31390000000000000102 /* CMUXOpenCommandTests.swift */,
2720F0012720F0012720F001 /* BrowserProfileSocketTests.swift */,
A6AC72080000000000000002 /* CMUXWorkspaceLoadingCLIRegressionTests.swift */,
C0DE31390000000000000112 /* CMUXOpenHTMLFocusTests.swift */,
C0DE75890000000000000004 /* DeflatedAssetTestSupport.swift */,
Expand Down Expand Up @@ -8912,6 +8915,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa =
C42660050000000000000001 /* BrowserPDFPreviewActionUnitTests.swift in Sources */,
C0DE78950000000000000001 /* BrowserPortalFirstRevealScrollTests.swift in Sources */,
B6585001B6585001B658PW01 /* BrowserPrewarmedWebViewPoolTests.swift in Sources */,
2720B0012720B0012720B001 /* BrowserProfileSocketTests.swift in Sources */,
8827C0010000000000000001 /* BrowserScreenshotCropTests.swift in Sources */,
C2035A060000000000000001 /* BrowserSSLTrustBypassStateTests.swift in Sources */,
C7B800062D4202A13C962D2D /* BrowserSystemProxyMirrorTests.swift in Sources */,
Expand Down
170 changes: 170 additions & 0 deletions cmuxTests/BrowserProfileSocketTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import Foundation
import Testing
#if canImport(cmux_DEV)
@testable import cmux_DEV
#elseif canImport(cmux)
@testable import cmux
#endif

@MainActor
@Suite(.serialized)
struct BrowserProfileSocketTests {
@Test func browserCreationCommandsHonorExplicitProfilesAndRejectInvalidSelectors() throws {
let defaults = UserDefaults.standard
let wasBrowserDisabled = BrowserAvailabilitySettings.isDisabled(defaults: defaults)
let store = BrowserProfileStore.shared
let previousLastUsedProfileID = store.effectiveLastUsedProfileID
let suffix = UUID().uuidString
let target = try #require(store.createProfile(named: "Issue 2720 Target \(suffix)"))
let fallback = try #require(store.createProfile(named: "Issue 2720 Fallback \(suffix)"))
let ambiguousName = "Issue 2720 Shared \(suffix)"
let ambiguousFirst = try #require(store.createProfile(named: ambiguousName))
let ambiguousSecond = try #require(store.createProfile(named: ambiguousName.lowercased()))
let createdProfileIDs = [target.id, fallback.id, ambiguousFirst.id, ambiguousSecond.id]

BrowserAvailabilitySettings.setDisabled(false, defaults: defaults)
defer {
TerminalController.shared.setActiveTabManager(nil)
for profileID in createdProfileIDs {
_ = store.deleteProfile(id: profileID)
}
store.noteUsed(previousLastUsedProfileID)
BrowserAvailabilitySettings.setDisabled(wasBrowserDisabled, defaults: defaults)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

store.noteUsed(fallback.id)
let openManager = TabManager()
defer { openManager.tabs.forEach { $0.teardownAllPanels() } }
let openWorkspace = try #require(openManager.selectedWorkspace)
let openSourceID = try #require(openWorkspace.focusedPanelId)
TerminalController.shared.setActiveTabManager(openManager)

let openResponse = try call(
method: "browser.open_split",
params: [
"workspace_id": openWorkspace.id.uuidString,
"surface_id": openSourceID.uuidString,
"url": "about:blank",
"profile": target.displayName.lowercased(),
"focus": false,
]
)
let openResult = try successfulResult(openResponse)
let openedSurfaceID = try #require(
(openResult["surface_id"] as? String).flatMap(UUID.init(uuidString:))
)
let openedPanel = try #require(openWorkspace.panels[openedSurfaceID] as? BrowserPanel)
#expect(openedPanel.profileID == target.id)

store.noteUsed(fallback.id)
let paneManager = TabManager()
defer { paneManager.tabs.forEach { $0.teardownAllPanels() } }
let paneWorkspace = try #require(paneManager.selectedWorkspace)
let paneSourceID = try #require(paneWorkspace.focusedPanelId)
TerminalController.shared.setActiveTabManager(paneManager)

let paneResponse = try call(
method: "pane.create",
params: [
"workspace_id": paneWorkspace.id.uuidString,
"surface_id": paneSourceID.uuidString,
"direction": "right",
"type": "browser",
"url": "about:blank",
"profile": target.id.uuidString,
"focus": false,
]
)
let paneResult = try successfulResult(paneResponse)
let paneSurfaceID = try #require(
(paneResult["surface_id"] as? String).flatMap(UUID.init(uuidString:))
)
let panePanel = try #require(paneWorkspace.panels[paneSurfaceID] as? BrowserPanel)
#expect(panePanel.profileID == target.id)

store.noteUsed(fallback.id)
let fallbackManager = TabManager()
defer { fallbackManager.tabs.forEach { $0.teardownAllPanels() } }
let fallbackWorkspace = try #require(fallbackManager.selectedWorkspace)
let fallbackSourceID = try #require(fallbackWorkspace.focusedPanelId)
TerminalController.shared.setActiveTabManager(fallbackManager)

let fallbackResponse = try call(
method: "browser.open_split",
params: [
"workspace_id": fallbackWorkspace.id.uuidString,
"surface_id": fallbackSourceID.uuidString,
"url": "about:blank",
"focus": false,
]
)
let fallbackResult = try successfulResult(fallbackResponse)
let fallbackSurfaceID = try #require(
(fallbackResult["surface_id"] as? String).flatMap(UUID.init(uuidString:))
)
let fallbackPanel = try #require(fallbackWorkspace.panels[fallbackSurfaceID] as? BrowserPanel)
#expect(fallbackPanel.profileID == fallback.id)

let unknownSelector = "Issue 2720 Missing \(suffix)"
let unknownResponse = try call(
method: "browser.open_split",
params: [
"workspace_id": fallbackWorkspace.id.uuidString,
"surface_id": fallbackSourceID.uuidString,
"profile": unknownSelector,
]
)
let unknownError = try errorPayload(unknownResponse)
#expect(unknownError["code"] as? String == "invalid_params")
#expect((unknownError["message"] as? String)?.contains(unknownSelector) == true)
#expect((unknownError["data"] as? [String: Any])?["profile"] as? String == unknownSelector)

let ambiguousResponse = try call(
method: "pane.create",
params: [
"workspace_id": fallbackWorkspace.id.uuidString,
"surface_id": fallbackSourceID.uuidString,
"direction": "right",
"type": "browser",
"profile": ambiguousName.uppercased(),
]
)
let ambiguousError = try errorPayload(ambiguousResponse)
let ambiguousMessage = try #require(ambiguousError["message"] as? String)
let ambiguousCandidates = try #require(
(ambiguousError["data"] as? [String: Any])?["candidates"] as? [[String: Any]]
)
#expect(ambiguousError["code"] as? String == "invalid_params")
#expect(ambiguousMessage.contains(ambiguousFirst.id.uuidString))
#expect(ambiguousMessage.contains(ambiguousSecond.id.uuidString))
#expect(Set(ambiguousCandidates.compactMap { $0["id"] as? String }) == [
ambiguousFirst.id.uuidString,
ambiguousSecond.id.uuidString,
])
}

private func call(method: String, params: [String: Any]) throws -> [String: Any] {
let request: [String: Any] = [
"jsonrpc": "2.0",
"id": UUID().uuidString,
"method": method,
"params": params,
]
let data = try JSONSerialization.data(withJSONObject: request)
let line = try #require(String(data: data, encoding: .utf8))
let response = TerminalController.shared.handleSocketLine(line)
return try #require(
JSONSerialization.jsonObject(with: Data(response.utf8)) as? [String: Any]
)
}

private func successfulResult(_ response: [String: Any]) throws -> [String: Any] {
#expect(response["ok"] as? Bool == true)
return try #require(response["result"] as? [String: Any])
}

private func errorPayload(_ response: [String: Any]) throws -> [String: Any] {
#expect(response["ok"] as? Bool == false)
return try #require(response["error"] as? [String: Any])
}
}
Comment on lines +13 to +350

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Five independent scenarios fused into one @Test function hides partial failures

All five scenarios — name-based open_split, UUID-based pane.create, no-profile fallback, unknown selector, and ambiguous selector — share a single @Test function. Because the function uses try #require and try successfulResult(...), the first failing call short-circuits the rest. When the unknown-selector path breaks, the ambiguous-selector coverage silently disappears, and vice versa. The sibling unit tests in BrowserProfileRepositoryTests correctly use one @Test func per scenario.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping this as one serialized behavior flow is intentional: it shares one BrowserProfileStore lifecycle and verifies the complete socket contract (name, UUID, fallback, unknown, ambiguous) without multiplying mutation of persisted global profile state. Each scenario has localized #expect/#require diagnostics, while repository edge cases remain split into isolated unit tests.

— Claude Code

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair point — the shared profile lifecycle and the layered "each subsequent scenario builds on the previous state" structure are real constraints that would complicate splitting. The distinction between socket-level behavioral flow tests and isolated unit tests is a reasonable boundary to draw here.

The short-circuit risk from try #require is still present, but given that all five scenarios share a single profile store setup and teardown, the consolidation tradeoff makes sense. Acknowledged.

Loading