From 054e9d0e2e9bdc2396b0c3b19c658d251407b259 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 01:58:36 +0800 Subject: [PATCH 01/11] =?UTF-8?q?=E8=AE=A9=E6=A8=A1=E5=9E=8B=E5=90=8D?= =?UTF-8?q?=E5=8D=95=E5=8F=AA=E4=BD=BF=E7=94=A8=E6=9C=8D=E5=8A=A1=E5=95=86?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...16\347\241\256\351\200\211\346\213\251.md" | 12 +++ .../Stores/WorkspaceStore+NativeAgent.swift | 25 ++++-- Sources/WeiBei/Stores/WorkspaceStore.swift | 3 +- .../WeiBei/Support/AgentAccountService.swift | 79 +++++++++++++++---- Sources/WeiBei/Views/ComposerView.swift | 5 -- .../Views/Settings/AgentModelPicker.swift | 16 ++-- .../Views/Settings/AgentSettingsView.swift | 57 +++++++++++-- .../WeiBei/Views/Settings/SettingsView.swift | 19 ----- .../DynamicModelSelectionTests.swift | 40 ++++++++++ 9 files changed, 199 insertions(+), 57 deletions(-) create mode 100644 "Docs/plans/2026-09-29-\345\212\250\346\200\201\346\250\241\345\236\213\345\220\215\345\215\225\344\270\216\346\230\216\347\241\256\351\200\211\346\213\251.md" create mode 100644 Tests/WeiBeiSafetyTests/DynamicModelSelectionTests.swift diff --git "a/Docs/plans/2026-09-29-\345\212\250\346\200\201\346\250\241\345\236\213\345\220\215\345\215\225\344\270\216\346\230\216\347\241\256\351\200\211\346\213\251.md" "b/Docs/plans/2026-09-29-\345\212\250\346\200\201\346\250\241\345\236\213\345\220\215\345\215\225\344\270\216\346\230\216\347\241\256\351\200\211\346\213\251.md" new file mode 100644 index 000000000..ea7501939 --- /dev/null +++ "b/Docs/plans/2026-09-29-\345\212\250\346\200\201\346\250\241\345\236\213\345\220\215\345\215\225\344\270\216\346\230\216\347\241\256\351\200\211\346\213\251.md" @@ -0,0 +1,12 @@ +# 动态模型名单与明确选择定案 + +## 结论 + +- 有模型查询端点时,只展示服务商实际返回的名单,不补路由默认模型。 +- 查询失败、返回空名单或保存的模型已失效时,保留用户原选择并明确提示;支持重试和手动输入。 +- 没有可查询名单时,由用户手动填写模型 ID。 +- 未明确选择模型时不发送请求,也不改用其他模型。 + +## 更新时机 + +打开设置、切换服务商或配置、修改服务地址、密钥变化及用户主动刷新时更新名单。聊天发送不触发名单刷新。 diff --git a/Sources/WeiBei/Stores/WorkspaceStore+NativeAgent.swift b/Sources/WeiBei/Stores/WorkspaceStore+NativeAgent.swift index aee88ea5f..61032f35c 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+NativeAgent.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+NativeAgent.swift @@ -207,11 +207,10 @@ extension WorkspaceStore { provider: selectedProvider, baseURL: agentRun.baseURL ) - let selectedModel = agentRun.modelName.trimmingCharacters(in: .whitespacesAndNewlines) - let routedModel = NativeProviderRouting.route(selectedProvider).defaultModel - let model = selectedModel.isEmpty - ? (routedModel.isEmpty ? "deepseek-chat" : routedModel) - : selectedModel + let model = try Self.explicitAgentModel( + agentRun.modelName, + language: interfaceLanguage + ) let adapter = try await NativeLLMAdapterFactory.make( provider: selectedProvider, model: model, @@ -338,6 +337,22 @@ extension WorkspaceStore { ) } + static func explicitAgentModel( + _ value: String, + language: WeiBeiInterfaceLanguage + ) throws -> String { + let model = value.trimmingCharacters(in: .whitespacesAndNewlines) + guard !model.isEmpty else { + throw AgentConversationTargetError( + message: language.text( + "尚未选择模型。请到设置中选择,或手动输入模型 ID 后重试。", + "No model is selected. Choose one in Settings, or enter a model ID manually, then try again." + ) + ) + } + return model + } + nonisolated private static func pagedSearchResult( query: String, items: [StudyAgentHostToolItem], diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index 925bb2d4c..93691a8ae 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -352,8 +352,7 @@ final class WorkspaceStore: ObservableObject { mode.effort(saved: agentReasoningMappings[agentReasoningMappingKey(mode)], levels: agentReasoningLevels) } var agentReasoningModelName: String { - let selected = modelName.trimmingCharacters(in: .whitespacesAndNewlines) - return selected.isEmpty ? NativeProviderRouting.route(agentProviderID).defaultModel : selected + modelName.trimmingCharacters(in: .whitespacesAndNewlines) } var agentReasoningModelKey: String { activeAgentProfileID.uuidString + ":" + agentReasoningModelName } var agentReasoningLevels: [String] { diff --git a/Sources/WeiBei/Support/AgentAccountService.swift b/Sources/WeiBei/Support/AgentAccountService.swift index 03735630e..29d8a684d 100644 --- a/Sources/WeiBei/Support/AgentAccountService.swift +++ b/Sources/WeiBei/Support/AgentAccountService.swift @@ -6,7 +6,7 @@ import WeiBeiCore import os /// Agent 账号与模型目录服务。 -/// 目录为服务商实时名单(失败时回退默认 ID;选择器永远允许手输任意 ID);凭据走 NativeAgentCredentialStore; +/// 目录只展示服务商实时名单;查询不可用或失败时由用户手动填写模型 ID;凭据走 NativeAgentCredentialStore; /// OpenAI 订阅登录走 NativeOpenAIOAuth 浏览器流程。 @MainActor final class AgentAccountService: ObservableObject { @@ -34,6 +34,9 @@ final class AgentAccountService: ObservableObject { @Published private(set) var lastError: LocalizedMessage? @Published private(set) var liveModelIDs: [String] = [] @Published private(set) var liveReasoningLevels: [String: [String]] = [:] + @Published private(set) var isRefreshingModels = false + @Published private(set) var modelListMessage: LocalizedMessage? + @Published private(set) var modelListCanRetry = false private var liveModelsProvider: AgentProviderID? private var loginTask: Task? private var loginID: UUID? @@ -49,26 +52,40 @@ final class AgentAccountService: ObservableObject { reloadCredentialSnapshot() } - /// 打开设置或更换服务/密钥后,向服务商拉取可用模型;失败时保留默认 ID。 + /// 打开设置、更换服务/端点/密钥或用户主动刷新时,向服务商拉取可用模型。 func refreshModels(provider: AgentProviderID, baseURL: String) { liveReasoningLevels = [:] modelListTask?.cancel() + liveModelsProvider = provider + liveModelIDs = [] + isRefreshingModels = true + modelListMessage = nil + modelListCanRetry = false modelListTask = Task { [weak self] in await self?.fetchLiveModels(provider: provider, baseURL: baseURL) } } - /// 已拉取的名单优先;没有名单时至少给出路由表默认模型。手输任意 ID 仍然有效。 + /// 只返回当前服务商端点实际拉取到的名单;手输任意 ID 仍然有效。 func models(provider: AgentProviderID) -> [String] { - var ids: [String] = [] - if liveModelsProvider == provider { - ids = liveModelIDs - } - let fallback = NativeProviderRouting.route(provider).defaultModel - if !fallback.isEmpty, !ids.contains(fallback) { - ids.insert(fallback, at: 0) - } + Self.catalogEntries(liveModelIDs, loadedFor: liveModelsProvider, provider: provider) + } + + static func catalogEntries( + _ ids: [String], + loadedFor: AgentProviderID?, + provider: AgentProviderID + ) -> [String] { + guard loadedFor == provider else { return [] } return ids + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + } + + func hasLoadedModels(provider: AgentProviderID) -> Bool { + liveModelsProvider == provider + && !isRefreshingModels + && modelListMessage == nil } func reasoningLevels(provider: AgentProviderID, model: String) -> [String] { @@ -280,7 +297,7 @@ final class AgentAccountService: ObservableObject { NativeProviderRouting.resolvedBaseURL(provider: provider, endpoint: $0) } ?? NativeProviderRouting.route(provider).baseURL let records = (try? NativeAgentCredentialStore.defaultStore().load()) ?? [:] - let record = records[provider.credentialProviderID] + let record = endpoint.flatMap { records[$0.credentialProviderID] } let apiKey = record?.apiKey ?? record?.accessToken ?? "" let strategy = NativeProviderRouting.modelListStrategy( provider: provider, @@ -292,6 +309,24 @@ final class AgentAccountService: ObservableObject { await MainActor.run { liveModelIDs = [] liveModelsProvider = provider + isRefreshingModels = false + modelListCanRetry = false + if provider == .openaiCodex { + modelListMessage = LocalizedMessage( + chinese: "请先连接服务商账号,再刷新模型名单。", + english: "Connect the provider account, then refresh the model list." + ) + } else if provider.requiresUserBaseURL, endpoint == nil { + modelListMessage = LocalizedMessage( + chinese: "请先填写有效的服务地址;如果该地址没有模型名单,请手动输入模型 ID。", + english: "Enter a valid service URL first. If it has no model list, enter a model ID manually." + ) + } else { + modelListMessage = LocalizedMessage( + chinese: "这个服务没有可查询的模型名单,请手动输入模型 ID。", + english: "This service has no queryable model list. Enter a model ID manually." + ) + } } return } @@ -316,19 +351,31 @@ final class AgentAccountService: ObservableObject { ? AgentModelListService(session: NativeProviderOAuth.networkSession) : .shared ids = try await modelService.fetchModels(strategy: strategy, apiKey: key) } + let modelIDs = Self.catalogEntries(ids, loadedFor: provider, provider: provider) + guard !modelIDs.isEmpty else { + throw ModelListError.decoding("empty model list") + } guard !Task.isCancelled else { return } await MainActor.run { liveReasoningLevels = reasoningLevels - liveModelIDs = ids + liveModelIDs = modelIDs liveModelsProvider = provider + isRefreshingModels = false + modelListMessage = nil + modelListCanRetry = false } } catch { guard !Task.isCancelled else { return } + logFailure("agent_model_list_failed", providerID: provider.credentialProviderID, error: error) await MainActor.run { - if liveModelsProvider != provider { - liveModelIDs = [] - } + liveModelIDs = [] liveModelsProvider = provider + isRefreshingModels = false + modelListCanRetry = true + modelListMessage = LocalizedMessage( + chinese: "模型名单获取失败,当前选择没有改变。请重试,或手动输入模型 ID。", + english: "Could not load the model list. Your selection is unchanged. Try again, or enter a model ID manually." + ) } } } diff --git a/Sources/WeiBei/Views/ComposerView.swift b/Sources/WeiBei/Views/ComposerView.swift index aacd08b78..e13f74062 100644 --- a/Sources/WeiBei/Views/ComposerView.swift +++ b/Sources/WeiBei/Views/ComposerView.swift @@ -5,7 +5,6 @@ import WeiBeiCore struct ComposerView: View { @EnvironmentObject private var store: WorkspaceStore @Environment(\.weiBeiTextScale) private var textScale - @ObservedObject private var agentAccount = AgentAccountService.shared @State private var draft = "" @State private var editorHeight: CGFloat = 0 @State private var editorActive = false @@ -159,10 +158,6 @@ struct ComposerView: View { } } .onChange(of: store.agentReasoningModelKey) { _, _ in showsReasoningPicker = false } - .task(id: store.activeAgentProfileID.uuidString + store.agentProviderID.rawValue + store.agentBaseURL) { - guard showsReasoningEffort else { return } - agentAccount.refreshModels(provider: store.agentProviderID, baseURL: store.agentBaseURL) - } .accessibilityIdentifier("agent-composer-compact") } diff --git a/Sources/WeiBei/Views/Settings/AgentModelPicker.swift b/Sources/WeiBei/Views/Settings/AgentModelPicker.swift index 577552af4..8098fcc89 100644 --- a/Sources/WeiBei/Views/Settings/AgentModelPicker.swift +++ b/Sources/WeiBei/Views/Settings/AgentModelPicker.swift @@ -46,11 +46,17 @@ extension SettingsView { } private var effectiveModelEntries: [String] { + oauthService.models(provider: store.agentProviderID) + } + + var selectedModelIsMissing: Bool { + store.modelName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + var selectedModelIsUnavailable: Bool { let current = store.modelName.trimmingCharacters(in: .whitespacesAndNewlines) - var entries = oauthService.models(provider: store.agentProviderID) - if !current.isEmpty, !entries.contains(current) { - entries.insert(current, at: 0) - } - return entries + return !current.isEmpty + && oauthService.hasLoadedModels(provider: store.agentProviderID) + && !effectiveModelEntries.contains(current) } } diff --git a/Sources/WeiBei/Views/Settings/AgentSettingsView.swift b/Sources/WeiBei/Views/Settings/AgentSettingsView.swift index 55651c986..d73a4e97c 100644 --- a/Sources/WeiBei/Views/Settings/AgentSettingsView.swift +++ b/Sources/WeiBei/Views/Settings/AgentSettingsView.swift @@ -68,8 +68,23 @@ extension SettingsView { // 模型 — dropdown backed by the live catalog. settingsRow(title: store.ui("模型", "Model"), detail: "") { - agentModelPicker() + HStack(spacing: 8) { + agentModelPicker() + Button { + oauthService.refreshModels( + provider: store.agentProviderID, + baseURL: store.agentBaseURL + ) + } label: { + Image(systemName: "arrow.clockwise") + } + .buttonStyle(WeiBeiIconButtonStyle(size: 24)) + .disabled(oauthService.isRefreshingModels) + .help(store.ui("刷新模型名单", "Refresh model list")) + .accessibilityLabel(store.ui("刷新模型名单", "Refresh model list")) + } } + modelCatalogStatus if !store.agentReasoningLevels.isEmpty { ForEach(AgentReasoningMode.allCases, id: \.self) { mode in @@ -218,10 +233,6 @@ extension SettingsView { private func applyProvider(_ provider: AgentProviderID) { apiKeyDraft = "" store.setAgentProviderID(provider) - oauthService.refreshModels(provider: provider, baseURL: store.agentBaseURL) - if let firstModel = oauthService.models(provider: provider).first { - store.updateModelName(firstModel) - } let authTypes = authTypes(for: provider) store.setAgentAuthMethod( authTypes.contains(.oauth) && (provider.kind == .subscription || !oauthService.isConfigured(providerID: provider.credentialProviderID, type: .apiKey)) @@ -230,6 +241,42 @@ extension SettingsView { ) } + @ViewBuilder + private var modelCatalogStatus: some View { + if oauthService.isRefreshingModels { + settingsNote( + store.ui("正在获取模型名单…", "Loading model list…"), + icon: "arrow.triangle.2.circlepath" + ) + } else if let message = oauthService.modelListMessage { + HStack(spacing: 8) { + settingsNote(store.ui(message.chinese, message.english), icon: "exclamationmark.triangle") + if oauthService.modelListCanRetry { + Button(store.ui("重试", "Retry")) { + oauthService.refreshModels( + provider: store.agentProviderID, + baseURL: store.agentBaseURL + ) + } + .buttonStyle(WeiBeiTextActionButtonStyle()) + } + } + } else if selectedModelIsMissing { + settingsNote( + store.ui("请选择一个模型,或手动输入模型 ID。", "Choose a model, or enter a model ID manually."), + icon: "exclamationmark.triangle" + ) + } else if selectedModelIsUnavailable { + settingsNote( + store.ui( + "已保存的模型不在当前名单中。魏碑不会替你切换,发送时仍使用这个模型。", + "The saved model is not in the current list. WeiBei will not switch it and will still use it when sending." + ), + icon: "exclamationmark.triangle" + ) + } + } + // MARK: ② Auth @ViewBuilder diff --git a/Sources/WeiBei/Views/Settings/SettingsView.swift b/Sources/WeiBei/Views/Settings/SettingsView.swift index 9f5bdaa4e..e667a7754 100644 --- a/Sources/WeiBei/Views/Settings/SettingsView.swift +++ b/Sources/WeiBei/Views/Settings/SettingsView.swift @@ -143,9 +143,6 @@ struct SettingsView: View { provider: provider, authMethod: .subscription ) - if let firstModel = oauthService.models(provider: provider).first { - store.updateModelName(firstModel) - } oauthService.refreshCatalog() oauthService.refreshModels(provider: store.agentProviderID, baseURL: store.agentBaseURL) } @@ -160,12 +157,6 @@ struct SettingsView: View { oauthService.refreshCatalog() oauthService.refreshModels(provider: store.agentProviderID, baseURL: store.agentBaseURL) } - .onChange(of: oauthService.catalog) { _, _ in - fillModelIfEmpty() - } - .onChange(of: oauthService.liveModelIDs) { _, _ in - fillModelIfEmpty() - } .onChange(of: store.agentBaseURL) { _, _ in oauthService.refreshModels(provider: store.agentProviderID, baseURL: store.agentBaseURL) } @@ -177,16 +168,6 @@ struct SettingsView: View { } } - private func fillModelIfEmpty() { - let models = oauthService.models(provider: store.agentProviderID) - let current = store.modelName.trimmingCharacters(in: .whitespacesAndNewlines) - if let firstModel = models.first, - !models.contains(current), - current.isEmpty { - store.updateModelName(firstModel) - } - } - enum Field: Hashable { case apiKey case model diff --git a/Tests/WeiBeiSafetyTests/DynamicModelSelectionTests.swift b/Tests/WeiBeiSafetyTests/DynamicModelSelectionTests.swift new file mode 100644 index 000000000..ecbb104c8 --- /dev/null +++ b/Tests/WeiBeiSafetyTests/DynamicModelSelectionTests.swift @@ -0,0 +1,40 @@ +import XCTest +@testable import WeiBei +import WeiBeiCore + +final class DynamicModelSelectionTests: XCTestCase { + @MainActor + func testCatalogNeverAddsDefaultsAndSendingRequiresExplicitModel() throws { + XCTAssertEqual( + AgentAccountService.catalogEntries( + ["server-model"], + loadedFor: .openai, + provider: .openai + ), + ["server-model"] + ) + XCTAssertEqual( + AgentAccountService.catalogEntries( + ["other-provider-model"], + loadedFor: .anthropic, + provider: .openai + ), + [] + ) + XCTAssertEqual( + AgentAccountService.catalogEntries( + ["", " ", " server-model "], + loadedFor: .openai, + provider: .openai + ), + ["server-model"] + ) + XCTAssertThrowsError( + try WorkspaceStore.explicitAgentModel(" \n", language: .chinese) + ) + XCTAssertEqual( + try WorkspaceStore.explicitAgentModel(" chosen-model ", language: .chinese), + "chosen-model" + ) + } +} From bf32bced444a3f204806845053ef0989bc055377 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 02:12:24 +0800 Subject: [PATCH 02/11] =?UTF-8?q?=E9=98=BB=E6=AD=A2=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E8=AF=B7=E6=B1=82=E4=BD=BF=E7=94=A8=E9=94=99=E7=BB=91=E5=AF=86?= =?UTF-8?q?=E9=92=A5=E6=88=96=E7=A9=BA=E6=A8=A1=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Stores/WorkspaceStore.swift | 23 +++++++++- .../WeiBei/Support/AgentAccountService.swift | 10 ++++- .../WeiBei/Views/AgentProviderReadiness.swift | 5 ++- .../WeiBeiCore/AgentCredentialProfiles.swift | 7 +++ .../NativeAgentCredentials.swift | 10 +++++ .../Providers/NativeLLMAdapterFactory.swift | 7 ++- .../AgentEndpointSecurityTests.swift | 43 +++++++++++++++++++ .../DynamicModelSelectionTests.swift | 23 ++++++++++ 8 files changed, 123 insertions(+), 5 deletions(-) diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index 93691a8ae..eb1eca557 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -9356,6 +9356,27 @@ final class WorkspaceStore: ObservableObject { !question.isEmpty else { return ui("当前无法提交这条回答。", "This response cannot be submitted right now.") } + let selectedModel: String + do { + selectedModel = try Self.explicitAgentModel(modelName, language: interfaceLanguage) + } catch { + let reason = Self.userFacingAgentFailureDetail(for: error) + ?? ui( + "尚未选择模型。请到设置中选择,或手动输入模型 ID 后重试。", + "No model is selected. Choose one in Settings, or enter a model ID manually, then try again." + ) + showImportantOperationError(reason) + return reason + } + if agentProviderID == .azureOpenAI, + !AgentProviderReadiness.hasActiveAPICredential(for: self) { + let reason = ui( + "当前 Azure 服务地址没有与之绑定的密钥。请在设置中为这个地址重新输入 API Key。", + "The current Azure service URL has no key bound to it. Re-enter the API key for this URL in Settings." + ) + showImportantOperationError(reason) + return reason + } let target: AgentConversationTarget do { if reusingLastUserMessage, let id { @@ -9395,7 +9416,7 @@ final class WorkspaceStore: ObservableObject { run.courseID = target.courseID run.authMethod = agentAuthMethod run.baseURL = agentBaseURL - run.modelName = modelName + run.modelName = selectedModel agentRuns[target.sessionID] = run objectWillChange.send() freshlyCreatedEmptyStudySessionID = nil diff --git a/Sources/WeiBei/Support/AgentAccountService.swift b/Sources/WeiBei/Support/AgentAccountService.swift index 29d8a684d..16570d758 100644 --- a/Sources/WeiBei/Support/AgentAccountService.swift +++ b/Sources/WeiBei/Support/AgentAccountService.swift @@ -298,7 +298,6 @@ final class AgentAccountService: ObservableObject { } ?? NativeProviderRouting.route(provider).baseURL let records = (try? NativeAgentCredentialStore.defaultStore().load()) ?? [:] let record = endpoint.flatMap { records[$0.credentialProviderID] } - let apiKey = record?.apiKey ?? record?.accessToken ?? "" let strategy = NativeProviderRouting.modelListStrategy( provider: provider, baseURL: resolved, @@ -331,6 +330,15 @@ final class AgentAccountService: ObservableObject { return } do { + let storedAPIKey: String? + if let endpoint { + storedAPIKey = try record?.apiKey(for: provider, endpoint: endpoint) + } else { + storedAPIKey = nil + } + let apiKey = storedAPIKey + ?? record?.accessToken + ?? "" let ids: [String] var reasoningLevels: [String: [String]] = [:] if provider == .openaiCodex { diff --git a/Sources/WeiBei/Views/AgentProviderReadiness.swift b/Sources/WeiBei/Views/AgentProviderReadiness.swift index 3137a6903..08fa03d59 100644 --- a/Sources/WeiBei/Views/AgentProviderReadiness.swift +++ b/Sources/WeiBei/Views/AgentProviderReadiness.swift @@ -60,7 +60,10 @@ enum AgentProviderReadiness { return isStored && oauth.catalog?.credentials.contains(where: { $0.providerId == AgentProviderID.azureOpenAI.credentialProviderID && $0.type == .apiKey - && $0.boundEndpoint == endpoint.baseURL + && endpoint.matchesCredentialBinding( + for: .azureOpenAI, + boundEndpoint: $0.boundEndpoint + ) }) == true } diff --git a/Sources/WeiBeiCore/AgentCredentialProfiles.swift b/Sources/WeiBeiCore/AgentCredentialProfiles.swift index 5cf9c8f06..6c88d2e4a 100644 --- a/Sources/WeiBeiCore/AgentCredentialProfiles.swift +++ b/Sources/WeiBeiCore/AgentCredentialProfiles.swift @@ -178,6 +178,13 @@ public struct AgentProviderEndpoint: Equatable, Sendable { } } + public func matchesCredentialBinding( + for provider: AgentProviderID, + boundEndpoint: String? + ) -> Bool { + provider != .azureOpenAI || boundEndpoint == baseURL + } + private static func isTrustedLocalHost(_ rawHost: String) -> Bool { let host = rawHost.trimmingCharacters(in: CharacterSet(charactersIn: "[]")).lowercased() if host == "localhost" || host.hasSuffix(".localhost") || host.hasSuffix(".local") { diff --git a/Sources/WeiBeiCore/NativeAgentRuntime/NativeAgentCredentials.swift b/Sources/WeiBeiCore/NativeAgentRuntime/NativeAgentCredentials.swift index 7aab9fe2a..327abf9a9 100644 --- a/Sources/WeiBeiCore/NativeAgentRuntime/NativeAgentCredentials.swift +++ b/Sources/WeiBeiCore/NativeAgentRuntime/NativeAgentCredentials.swift @@ -28,6 +28,16 @@ public struct NativeAgentCredentialRecord: Codable, Equatable, Sendable { self.accountID = accountID self.boundEndpoint = boundEndpoint } + + public func apiKey( + for provider: AgentProviderID, + endpoint: AgentProviderEndpoint + ) throws -> String? { + if !endpoint.matchesCredentialBinding(for: provider, boundEndpoint: boundEndpoint) { + throw AgentProviderEndpointError.azureCredentialRequiresReentry + } + return apiKey?.isEmpty == false ? apiKey : nil + } } public struct NativeAgentCredentialStore: Sendable { diff --git a/Sources/WeiBeiCore/NativeAgentRuntime/Providers/NativeLLMAdapterFactory.swift b/Sources/WeiBeiCore/NativeAgentRuntime/Providers/NativeLLMAdapterFactory.swift index f2d6154c9..4fc0bab13 100644 --- a/Sources/WeiBeiCore/NativeAgentRuntime/Providers/NativeLLMAdapterFactory.swift +++ b/Sources/WeiBeiCore/NativeAgentRuntime/Providers/NativeLLMAdapterFactory.swift @@ -156,8 +156,11 @@ public enum NativeLLMAdapterFactory { } return record?.accessToken } - if let store { return try store.load()[endpoint.credentialProviderID]?.apiKey } - return try NativeAgentCredentialStore.apiKey(forProviderID: endpoint.credentialProviderID) + let store = try store ?? NativeAgentCredentialStore.defaultStore() + return try store.load()[endpoint.credentialProviderID]?.apiKey( + for: provider, + endpoint: endpoint + ) } } diff --git a/Tests/WeiBeiSafetyTests/AgentEndpointSecurityTests.swift b/Tests/WeiBeiSafetyTests/AgentEndpointSecurityTests.swift index dca46c4dc..5b42f1d22 100644 --- a/Tests/WeiBeiSafetyTests/AgentEndpointSecurityTests.swift +++ b/Tests/WeiBeiSafetyTests/AgentEndpointSecurityTests.swift @@ -123,6 +123,49 @@ final class AgentEndpointSecurityTests: XCTestCase { XCTAssertNil(try store.load()[AgentProviderID.custom.credentialProviderID]) } + func testAzureCredentialCannotLeaveItsBoundEndpoint() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("WeiBeiAzureEndpointTest-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + let first = try AgentProviderEndpoint( + provider: .azureOpenAI, + baseURL: "https://first.openai.azure.com" + ) + let second = try AgentProviderEndpoint( + provider: .azureOpenAI, + baseURL: "https://second.openai.azure.com" + ) + let store = NativeAgentCredentialStore(fileURL: root.appendingPathComponent("credentials.json")) + try store.upsert(NativeAgentCredentialRecord( + provider: first.credentialProviderID, + apiKey: "first-secret", + boundEndpoint: first.baseURL + )) + XCTAssertTrue(first.matchesCredentialBinding(for: .azureOpenAI, boundEndpoint: first.baseURL)) + XCTAssertFalse(second.matchesCredentialBinding(for: .azureOpenAI, boundEndpoint: first.baseURL)) + + let matching = try await NativeLLMAdapterFactory.make( + provider: .azureOpenAI, + model: "deployment", + endpoint: first, + authMethod: .apiKey, + credentialStore: store + ) + XCTAssertEqual((matching as? OpenAIResponsesProvider)?.accessToken, "first-secret") + do { + _ = try await NativeLLMAdapterFactory.make( + provider: .azureOpenAI, + model: "deployment", + endpoint: second, + authMethod: .apiKey, + credentialStore: store + ) + XCTFail("Azure 旧地址的密钥不得发送到新地址") + } catch { + XCTAssertEqual(error as? AgentProviderEndpointError, .azureCredentialRequiresReentry) + } + } + @MainActor func testAgentOwnedRootsRejectSymlinksOutsideWorkspace() throws { enum OwnedRoot: String { diff --git a/Tests/WeiBeiSafetyTests/DynamicModelSelectionTests.swift b/Tests/WeiBeiSafetyTests/DynamicModelSelectionTests.swift index ecbb104c8..fd379ccf5 100644 --- a/Tests/WeiBeiSafetyTests/DynamicModelSelectionTests.swift +++ b/Tests/WeiBeiSafetyTests/DynamicModelSelectionTests.swift @@ -1,3 +1,4 @@ +import Foundation import XCTest @testable import WeiBei import WeiBeiCore @@ -37,4 +38,26 @@ final class DynamicModelSelectionTests: XCTestCase { "chosen-model" ) } + + @MainActor + func testEmptyModelBlocksBeforeHistoryAndPreservesDraft() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("WeiBeiEmptyModelTest-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + let store = WorkspaceStore( + workspaceDirectory: root, + startsAtBlankEntries: true, + startsCourseFileMaintenance: false + ) + let session = try XCTUnwrap(store.createStudySession(courseID: nil)) + store.modelName = " " + store.saveComposerDraft("保留这段未发送的问题", for: session.id) + + store.submitAgentDraft(sessionID: session.id) + + XCTAssertEqual(store.composerDraft(for: session.id), "保留这段未发送的问题") + XCTAssertTrue(store.conversationMessages(in: session.id).isEmpty) + XCTAssertNil(store.agentRuns[session.id]?.agentRequestTask) + XCTAssertNotNil(store.importantOperationError) + } } From 4ab6e60bf5e4dc031bcef57ebff780dd20dff9b3 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 02:17:40 +0800 Subject: [PATCH 03/11] =?UTF-8?q?test:=20=E4=B8=BA=E5=81=87=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=E5=9B=9E=E7=AD=94=E6=8C=87=E5=AE=9A=E6=A8=A1=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Tests/WeiBeiSafetyTests/ConversationSafetyTests.swift | 1 + Tests/WeiBeiSafetyTests/DailyWorkflowTests.swift | 1 + Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift | 1 + 3 files changed, 3 insertions(+) diff --git a/Tests/WeiBeiSafetyTests/ConversationSafetyTests.swift b/Tests/WeiBeiSafetyTests/ConversationSafetyTests.swift index 37899ed96..7bb168a60 100644 --- a/Tests/WeiBeiSafetyTests/ConversationSafetyTests.swift +++ b/Tests/WeiBeiSafetyTests/ConversationSafetyTests.swift @@ -52,6 +52,7 @@ final class ConversationSafetyTests: XCTestCase { startsAtBlankEntries: true, startsCourseFileMaintenance: false ) + store.modelName = "test-model" let session = try XCTUnwrap(store.createStudySession(courseID: nil)) return (store, session.id, { try? FileManager.default.removeItem(at: root) }) } diff --git a/Tests/WeiBeiSafetyTests/DailyWorkflowTests.swift b/Tests/WeiBeiSafetyTests/DailyWorkflowTests.swift index db4f4038c..e9ee4b4e8 100644 --- a/Tests/WeiBeiSafetyTests/DailyWorkflowTests.swift +++ b/Tests/WeiBeiSafetyTests/DailyWorkflowTests.swift @@ -12,6 +12,7 @@ final class DailyWorkflowTests: XCTestCase { func testConcurrentChatsKeepTheirQuestionStreamAndCancellation() throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) let store = WorkspaceStore(workspaceDirectory: root.appendingPathComponent("Workspace"), startsAtBlankEntries: true, startsCourseFileMaintenance: false) + store.modelName = "test-model" defer { store.selfCheckAgentResponder = nil; try? FileManager.default.removeItem(at: root) } let started = expectation(description: "Both requests reached their own responder") started.expectedFulfillmentCount = 2 diff --git a/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift b/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift index f7412dc51..1e2290b94 100644 --- a/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift +++ b/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift @@ -775,6 +775,7 @@ enum ImportedIdentitySelfCheck { } try data.write(to: url, options: [.atomic]) } + courseQuestionStore.modelName = "test-model" courseQuestionStore.activateCourse(courseA.id) courseQuestionStore.openCourseNote(note.id) try check( From 99c1424e6f218541b3ae1877fdbda592fa94fbd4 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 02:24:17 +0800 Subject: [PATCH 04/11] =?UTF-8?q?test:=20=E4=B8=BA=E8=AF=BE=E7=A8=8B=20Age?= =?UTF-8?q?nt=20=E8=87=AA=E6=A3=80=E6=8C=87=E5=AE=9A=E6=A8=A1=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift b/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift index 51d818045..56b3cde86 100644 --- a/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift +++ b/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift @@ -797,6 +797,7 @@ enum CourseProjectRootSelfCheck { let library = try fixture.makeDirectory("课程资料库") let imports = try fixture.makeDirectory("待导入") let store = makeStore(fixture: fixture) + store.modelName = "test-model" try store.configureCourseLibrary(at: library) let courseA = try store.createCourseInLibrary(title: "课程甲") let courseB = try store.createCourseInLibrary(title: "课程乙") From 420007ab33a745dee01dad81addace7bbc435230 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 02:56:42 +0800 Subject: [PATCH 05/11] =?UTF-8?q?fix:=20=E5=8C=BA=E5=88=86=E7=A9=BA?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E5=90=8D=E5=8D=95=E4=B8=8E=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../WeiBei/Support/AgentAccountService.swift | 26 ++++-- .../WeiBeiCore/AgentModelListService.swift | 18 ++-- .../DynamicModelSelectionTests.swift | 82 +++++++++++++++++++ 3 files changed, 113 insertions(+), 13 deletions(-) diff --git a/Sources/WeiBei/Support/AgentAccountService.swift b/Sources/WeiBei/Support/AgentAccountService.swift index 16570d758..93af7dabd 100644 --- a/Sources/WeiBei/Support/AgentAccountService.swift +++ b/Sources/WeiBei/Support/AgentAccountService.swift @@ -28,6 +28,11 @@ final class AgentAccountService: ObservableObject { var credentials: [CredentialInfo] = [] } + struct SuccessfulModelListState: Equatable, Sendable { + var message: LocalizedMessage? + var canRetry: Bool + } + @Published private(set) var catalog: CatalogInfo? @Published private(set) var isLoggingIn = false @Published private(set) var statusMessage: LocalizedMessage? @@ -82,6 +87,19 @@ final class AgentAccountService: ObservableObject { .filter { !$0.isEmpty } } + static func successfulModelListState(_ modelIDs: [String]) -> SuccessfulModelListState { + guard modelIDs.isEmpty else { + return SuccessfulModelListState(message: nil, canRetry: false) + } + return SuccessfulModelListState( + message: LocalizedMessage( + chinese: "服务返回的模型名单为空,当前选择没有改变。请刷新重试,或手动输入模型 ID。", + english: "The service returned an empty model list. Your selection is unchanged. Refresh to try again, or enter a model ID manually." + ), + canRetry: true + ) + } + func hasLoadedModels(provider: AgentProviderID) -> Bool { liveModelsProvider == provider && !isRefreshingModels @@ -360,17 +378,15 @@ final class AgentAccountService: ObservableObject { ids = try await modelService.fetchModels(strategy: strategy, apiKey: key) } let modelIDs = Self.catalogEntries(ids, loadedFor: provider, provider: provider) - guard !modelIDs.isEmpty else { - throw ModelListError.decoding("empty model list") - } + let state = Self.successfulModelListState(modelIDs) guard !Task.isCancelled else { return } await MainActor.run { liveReasoningLevels = reasoningLevels liveModelIDs = modelIDs liveModelsProvider = provider isRefreshingModels = false - modelListMessage = nil - modelListCanRetry = false + modelListMessage = state.message + modelListCanRetry = state.canRetry } } catch { guard !Task.isCancelled else { return } diff --git a/Sources/WeiBeiCore/AgentModelListService.swift b/Sources/WeiBeiCore/AgentModelListService.swift index 6b0f92cf9..23c3d1fcf 100644 --- a/Sources/WeiBeiCore/AgentModelListService.swift +++ b/Sources/WeiBeiCore/AgentModelListService.swift @@ -151,9 +151,11 @@ public actor AgentModelListService { guard let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw ModelListError.decoding("missing models array") } - let ids = Self.publisherModelIDs(object["publisherModels"] ?? object["models"]) - guard !ids.isEmpty else { throw ModelListError.decoding("missing models array") } - return ids + guard let rawModels = object["publisherModels"] ?? object["models"], + rawModels is [Any] else { + throw ModelListError.decoding("missing models array") + } + return Self.publisherModelIDs(rawModels) } /// ChatGPT/Codex subscription catalog. Mirrors the Codex backend's own model @@ -203,7 +205,6 @@ public actor AgentModelListService { throw ModelListError.decoding("missing models array") } let catalog = Self.codexModels(models) - guard !catalog.isEmpty else { throw ModelListError.decoding("no supported models") } codexCatalogs = codexCatalogs.filter { Date().timeIntervalSince($0.value.0) < 300 } codexCatalogs[cacheKey] = (Date(), catalog) return catalog @@ -249,7 +250,8 @@ public actor AgentModelListService { ) async throws -> [String] { let data = try await perform(request: request) guard let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], - let raw = object[dataKey] else { + let raw = object[dataKey], + raw is [Any] else { throw ModelListError.decoding("missing data array") } return Self.coerceModelIDs(raw, stripPrefix: stripPrefix) @@ -304,10 +306,10 @@ public actor AgentModelListService { static func coerceModelIDs(_ raw: Any?, stripPrefix: String?) -> [String] { let ids: [String] - if let array = raw as? [Any] { - ids = array.compactMap { ($0 as? [String: Any])?["id"] as? String } - } else if let strings = raw as? [String] { + if let strings = raw as? [String] { ids = strings + } else if let array = raw as? [Any] { + ids = array.compactMap { ($0 as? [String: Any])?["id"] as? String } } else { return [] } diff --git a/Tests/WeiBeiSafetyTests/DynamicModelSelectionTests.swift b/Tests/WeiBeiSafetyTests/DynamicModelSelectionTests.swift index fd379ccf5..fbfa47ce0 100644 --- a/Tests/WeiBeiSafetyTests/DynamicModelSelectionTests.swift +++ b/Tests/WeiBeiSafetyTests/DynamicModelSelectionTests.swift @@ -4,6 +4,34 @@ import XCTest import WeiBeiCore final class DynamicModelSelectionTests: XCTestCase { + private final class ModelListProtocol: URLProtocol { + static var response: (status: Int, json: [String: Any])? + + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + + override func startLoading() { + guard let response = Self.response else { + client?.urlProtocol(self, didFailWithError: URLError(.badServerResponse)) + return + } + let http = HTTPURLResponse( + url: request.url!, + statusCode: response.status, + httpVersion: nil, + headerFields: ["Content-Type": "application/json"] + )! + client?.urlProtocol(self, didReceive: http, cacheStoragePolicy: .notAllowed) + client?.urlProtocol( + self, + didLoad: try! JSONSerialization.data(withJSONObject: response.json) + ) + client?.urlProtocolDidFinishLoading(self) + } + + override func stopLoading() {} + } + @MainActor func testCatalogNeverAddsDefaultsAndSendingRequiresExplicitModel() throws { XCTAssertEqual( @@ -60,4 +88,58 @@ final class DynamicModelSelectionTests: XCTestCase { XCTAssertNil(store.agentRuns[session.id]?.agentRequestTask) XCTAssertNotNil(store.importantOperationError) } + + func testQueryableProvidersAcceptSuccessfulEmptyCatalogButRejectMissingArray() async throws { + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [ModelListProtocol.self] + let session = URLSession(configuration: configuration) + let service = AgentModelListService(session: session) + defer { + ModelListProtocol.response = nil + session.invalidateAndCancel() + } + + ModelListProtocol.response = (200, ["data": []]) + let openAIModels = try await service.fetchModels( + strategy: .openAICompatible(base: "https://models.example.test"), + apiKey: "test-key" + ) + XCTAssertTrue(openAIModels.isEmpty) + + ModelListProtocol.response = (200, ["publisherModels": []]) + let publisherModels = try await service.fetchModels( + strategy: .googlePublisherModels(base: "https://publisher.example.test"), + apiKey: "test-key" + ) + XCTAssertTrue(publisherModels.isEmpty) + + ModelListProtocol.response = (200, ["models": []]) + let codexModels = try await service.fetchModels( + strategy: .codexSubscription(token: "test-token", accountID: "test-account"), + apiKey: "" + ) + XCTAssertTrue(codexModels.isEmpty) + + ModelListProtocol.response = (200, [:]) + do { + _ = try await service.fetchModels( + strategy: .openAICompatible(base: "https://models.example.test"), + apiKey: "test-key" + ) + XCTFail("缺少模型数组必须继续显示为获取失败") + } catch let error as ModelListError { + XCTAssertEqual(error, .decoding("missing data array")) + } + } + + @MainActor + func testSuccessfulEmptyCatalogShowsRetryableEmptyState() { + let empty = AgentAccountService.successfulModelListState([]) + XCTAssertNotNil(empty.message) + XCTAssertTrue(empty.canRetry) + + let populated = AgentAccountService.successfulModelListState(["catalyst-second-check"]) + XCTAssertNil(populated.message) + XCTAssertFalse(populated.canRetry) + } } From aef7b6045a5d3a60ea5021dafbe061fd779c6670 Mon Sep 17 00:00:00 2001 From: Codex Acceptance Date: Wed, 30 Sep 2026 21:11:29 -1000 Subject: [PATCH 06/11] fix: load Codex reasoning capabilities for cold composers --- .../WeiBei/Support/AgentAccountService.swift | 40 +++++++++++++++++- Sources/WeiBei/Views/ComposerView.swift | 5 +++ .../ComposerReasoningCatalogTests.swift | 42 +++++++++++++++++++ 3 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift diff --git a/Sources/WeiBei/Support/AgentAccountService.swift b/Sources/WeiBei/Support/AgentAccountService.swift index 93af7dabd..0e12193fd 100644 --- a/Sources/WeiBei/Support/AgentAccountService.swift +++ b/Sources/WeiBei/Support/AgentAccountService.swift @@ -48,8 +48,14 @@ final class AgentAccountService: ObservableObject { @Published private(set) var authorizationCode: String? @Published private(set) var authorizationURL: URL? private var modelListTask: Task? + struct ModelCatalog { + var ids: [String] + var reasoningLevels: [String: [String]] + } + private let modelCatalogLoader: ((AgentProviderID, String) async throws -> ModelCatalog)? - private init() { + init(modelCatalogLoader: ((AgentProviderID, String) async throws -> ModelCatalog)? = nil) { + self.modelCatalogLoader = modelCatalogLoader reloadCredentialSnapshot() } @@ -71,6 +77,14 @@ final class AgentAccountService: ObservableObject { } } + /// 冷启动的输入框也需要实时推理能力,不要求先打开设置。 + /// 多个输入框同时出现时复用当前查询,不清空已加载的能力。 + func refreshReasoningCatalogIfNeeded(provider: AgentProviderID, baseURL: String) { + guard provider == .openaiCodex, !isRefreshingModels, + !hasLoadedModels(provider: provider) else { return } + refreshModels(provider: provider, baseURL: baseURL) + } + /// 只返回当前服务商端点实际拉取到的名单;手输任意 ID 仍然有效。 func models(provider: AgentProviderID) -> [String] { Self.catalogEntries(liveModelIDs, loadedFor: liveModelsProvider, provider: provider) @@ -310,6 +324,30 @@ final class AgentAccountService: ObservableObject { } private func fetchLiveModels(provider: AgentProviderID, baseURL: String) async { + if let modelCatalogLoader { + do { + let catalog = try await modelCatalogLoader(provider, baseURL) + guard !Task.isCancelled else { return } + let ids = Self.catalogEntries(catalog.ids, loadedFor: provider, provider: provider) + let state = Self.successfulModelListState(ids) + liveReasoningLevels = catalog.reasoningLevels + liveModelIDs = ids + liveModelsProvider = provider + isRefreshingModels = false + modelListMessage = state.message + modelListCanRetry = state.canRetry + } catch { + guard !Task.isCancelled else { return } + liveModelIDs = [] + liveReasoningLevels = [:] + liveModelsProvider = provider + isRefreshingModels = false + modelListCanRetry = true + modelListMessage = LocalizedMessage(chinese: "模型名单获取失败", english: "Could not load the model list") + } + return + } + let endpoint = try? AgentProviderEndpoint(provider: provider, baseURL: baseURL) let resolved = endpoint.flatMap { NativeProviderRouting.resolvedBaseURL(provider: provider, endpoint: $0) diff --git a/Sources/WeiBei/Views/ComposerView.swift b/Sources/WeiBei/Views/ComposerView.swift index e13f74062..1d3bdf198 100644 --- a/Sources/WeiBei/Views/ComposerView.swift +++ b/Sources/WeiBei/Views/ComposerView.swift @@ -5,6 +5,7 @@ import WeiBeiCore struct ComposerView: View { @EnvironmentObject private var store: WorkspaceStore @Environment(\.weiBeiTextScale) private var textScale + @ObservedObject private var agentAccount = AgentAccountService.shared @State private var draft = "" @State private var editorHeight: CGFloat = 0 @State private var editorActive = false @@ -158,6 +159,10 @@ struct ComposerView: View { } } .onChange(of: store.agentReasoningModelKey) { _, _ in showsReasoningPicker = false } + .task(id: store.activeAgentProfileID.uuidString + store.agentProviderID.rawValue + store.agentBaseURL) { + guard showsReasoningEffort, store.agentProviderID == .openaiCodex else { return } + agentAccount.refreshReasoningCatalogIfNeeded(provider: store.agentProviderID, baseURL: store.agentBaseURL) + } .accessibilityIdentifier("agent-composer-compact") } diff --git a/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift b/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift new file mode 100644 index 000000000..e90147abd --- /dev/null +++ b/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift @@ -0,0 +1,42 @@ +import Foundation +import XCTest +@testable import WeiBei +import WeiBeiCore + +final class ComposerReasoningCatalogTests: XCTestCase { + @MainActor + func testColdComposerPublishesCodexCapabilitiesWithoutSettingsOrRepeatedReset() async throws { + var loads = 0 + let account = AgentAccountService(modelCatalogLoader: { provider, _ in + XCTAssertEqual(provider, .openaiCodex) + loads += 1 + await Task.yield() + return .init(ids: ["synthetic-model"], reasoningLevels: ["synthetic-model": ["low", "high"]]) + }) + XCTAssertTrue(account.reasoningLevels(provider: .openaiCodex, model: "synthetic-model").isEmpty) + account.refreshReasoningCatalogIfNeeded(provider: .openaiCodex, baseURL: "") + account.refreshReasoningCatalogIfNeeded(provider: .openaiCodex, baseURL: "") + for _ in 0..<100 where account.isRefreshingModels { await Task.yield() } + XCTAssertFalse(account.isRefreshingModels) + XCTAssertEqual(loads, 1) + XCTAssertEqual(account.reasoningLevels(provider: .openaiCodex, model: "synthetic-model"), ["low", "high"]) + account.refreshReasoningCatalogIfNeeded(provider: .openaiCodex, baseURL: "") + XCTAssertEqual(loads, 1) + XCTAssertEqual(account.models(provider: .openaiCodex), ["synthetic-model"]) + XCTAssertTrue(account.reasoningLevels(provider: .openai, model: "synthetic-model").isEmpty) + } + + @MainActor + func testColdCapabilityLookupDoesNotQueryOtherProvidersOrChooseAModel() async throws { + var loads = 0 + let account = AgentAccountService(modelCatalogLoader: { _, _ in + loads += 1 + return .init(ids: ["server-first"], reasoningLevels: [:]) + }) + account.refreshReasoningCatalogIfNeeded(provider: .custom, baseURL: "https://synthetic.example.test") + await Task.yield() + XCTAssertEqual(loads, 0) + XCTAssertFalse(account.isRefreshingModels) + XCTAssertTrue(account.models(provider: .custom).isEmpty) + } +} From 67120c742211b118a0edf7d1da141d77313b0571 Mon Sep 17 00:00:00 2001 From: Codex Acceptance Date: Wed, 30 Sep 2026 21:24:10 -1000 Subject: [PATCH 07/11] test: exercise native cold composer capability loading --- Sources/WeiBei/Views/ComposerView.swift | 8 ++- .../ComposerReasoningCatalogTests.swift | 52 +++++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/Sources/WeiBei/Views/ComposerView.swift b/Sources/WeiBei/Views/ComposerView.swift index 1d3bdf198..6056582e5 100644 --- a/Sources/WeiBei/Views/ComposerView.swift +++ b/Sources/WeiBei/Views/ComposerView.swift @@ -5,7 +5,7 @@ import WeiBeiCore struct ComposerView: View { @EnvironmentObject private var store: WorkspaceStore @Environment(\.weiBeiTextScale) private var textScale - @ObservedObject private var agentAccount = AgentAccountService.shared + @ObservedObject var agentAccount = AgentAccountService.shared @State private var draft = "" @State private var editorHeight: CGFloat = 0 @State private var editorActive = false @@ -42,7 +42,7 @@ struct ComposerView: View { } private var hasReasoningControl: Bool { - showsReasoningEffort && !store.agentReasoningLevels.isEmpty + showsReasoningEffort && !agentAccount.reasoningLevels(provider: store.agentProviderID, model: store.agentReasoningModelName).isEmpty } private var showsControl: Bool { @@ -163,6 +163,10 @@ struct ComposerView: View { guard showsReasoningEffort, store.agentProviderID == .openaiCodex else { return } agentAccount.refreshReasoningCatalogIfNeeded(provider: store.agentProviderID, baseURL: store.agentBaseURL) } + .onReceive(NotificationCenter.default.publisher(for: .weiBeiAgentOAuthDidSucceed)) { _ in + guard showsReasoningEffort, store.agentProviderID == .openaiCodex else { return } + agentAccount.refreshReasoningCatalogIfNeeded(provider: store.agentProviderID, baseURL: store.agentBaseURL) + } .accessibilityIdentifier("agent-composer-compact") } diff --git a/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift b/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift index e90147abd..bd69063f3 100644 --- a/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift +++ b/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift @@ -40,3 +40,55 @@ final class ComposerReasoningCatalogTests: XCTestCase { XCTAssertTrue(account.models(provider: .custom).isEmpty) } } + +#if os(macOS) && !targetEnvironment(macCatalyst) +import AppKit +import SwiftUI + +private struct ColdComposerFixture: View { + var account: AgentAccountService + @FocusState var focused: Bool + var body: some View { + ComposerView(agentAccount: account, prompt: "Synthetic question", focused: $focused, + fontSize: 14, lineLimit: 1...3, height: 48, + sendButtonSize: 24, trailingPadding: 8, sendTrailing: 8, + showsReasoningEffort: true, submit: {}) + } +} + +extension ComposerReasoningCatalogTests { + @MainActor + func testNativeColdComposerStartsCapabilityLookupWithoutOpeningSettings() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let keys = ["weibei.agentCredentialProfiles.v1", "weibei.agentCredentialActiveProfileID.v1"] + let saved = keys.map { UserDefaults.standard.object(forKey: $0) } + defer { + for (key, value) in zip(keys, saved) { UserDefaults.standard.set(value, forKey: key) } + try? FileManager.default.removeItem(at: root) + } + let store = WorkspaceStore(workspaceDirectory: root, startsAtBlankEntries: true, startsCourseFileMaintenance: false) + store.setAgentProviderID(.openaiCodex) + store.updateModelName("synthetic-model") + var loads = 0 + let account = AgentAccountService(modelCatalogLoader: { _, _ in + loads += 1 + return .init(ids: ["synthetic-model"], reasoningLevels: ["synthetic-model": ["low", "high"]]) + }) + _ = NSApplication.shared + let hosting = NSHostingView(rootView: ColdComposerFixture(account: account).environmentObject(store)) + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 460, height: 130), + styleMask: [.borderless], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + window.contentView = hosting + window.orderFront(nil) + defer { window.close() } + let deadline = Date().addingTimeInterval(5) + while account.reasoningLevels(provider: .openaiCodex, model: "synthetic-model").isEmpty && Date() < deadline { + try await Task.sleep(for: .milliseconds(10)) + } + XCTAssertEqual(loads, 1, "Opening the real composer must start the cold capability lookup") + XCTAssertEqual(account.reasoningLevels(provider: .openaiCodex, model: "synthetic-model"), ["low", "high"]) + XCTAssertEqual(store.modelName, "synthetic-model") + } +} +#endif From 5b45ff639ad868b930366d7aa9e874de31343f7d Mon Sep 17 00:00:00 2001 From: Codex Acceptance Date: Wed, 30 Sep 2026 21:30:42 -1000 Subject: [PATCH 08/11] test: retain synthetic native cold composer screenshot --- .../WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift b/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift index bd69063f3..4c1e54dd9 100644 --- a/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift +++ b/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift @@ -89,6 +89,14 @@ extension ComposerReasoningCatalogTests { XCTAssertEqual(loads, 1, "Opening the real composer must start the cold capability lookup") XCTAssertEqual(account.reasoningLevels(provider: .openaiCodex, model: "synthetic-model"), ["low", "high"]) XCTAssertEqual(store.modelName, "synthetic-model") + hosting.layoutSubtreeIfNeeded() + let bitmap = try XCTUnwrap(hosting.bitmapImageRepForCachingDisplay(in: hosting.bounds)) + hosting.cacheDisplay(in: hosting.bounds, to: bitmap) + let png = try XCTUnwrap(bitmap.representation(using: .png, properties: [:])) + let evidence = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) + .appendingPathComponent(".build/native-fix-evidence", isDirectory: true) + try FileManager.default.createDirectory(at: evidence, withIntermediateDirectories: true) + try png.write(to: evidence.appendingPathComponent("cold-codex-composer.png")) } } #endif From 42a90d11280ad66806bf085496b68d5c3bb4ab90 Mon Sep 17 00:00:00 2001 From: Codex Acceptance Date: Wed, 30 Sep 2026 21:34:59 -1000 Subject: [PATCH 09/11] test: upload isolated native regression screenshots --- .github/workflows/pr-checks.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 78c5fa06d..ed600906d 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -159,6 +159,15 @@ jobs: stdbuf -oL -eL swift test --filter WeiBeiSafetyTests WEIBEI_NATIVE_EVAL_EFFORT=high swift run WeiBeiNativeCheck --native-eval-self-check + - name: 保留合成原生界面回归截图 + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: native-fix-evidence-${{ github.sha }} + path: .build/native-fix-evidence + retention-days: 2 + if-no-files-found: ignore + - name: 检查空白与生成文件 run: | git diff --check From 853ec5e7fd4841cededa0c064c699fcf1a22ad38 Mon Sep 17 00:00:00 2001 From: Codex Acceptance Date: Wed, 30 Sep 2026 21:51:24 -1000 Subject: [PATCH 10/11] fix: supersede other provider refreshes for cold Codex composers --- .../WeiBei/Support/AgentAccountService.swift | 10 +++++-- Sources/WeiBei/Views/ComposerView.swift | 2 +- .../ComposerReasoningCatalogTests.swift | 27 +++++++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/Sources/WeiBei/Support/AgentAccountService.swift b/Sources/WeiBei/Support/AgentAccountService.swift index 0e12193fd..28ebd5322 100644 --- a/Sources/WeiBei/Support/AgentAccountService.swift +++ b/Sources/WeiBei/Support/AgentAccountService.swift @@ -48,6 +48,8 @@ final class AgentAccountService: ObservableObject { @Published private(set) var authorizationCode: String? @Published private(set) var authorizationURL: URL? private var modelListTask: Task? + private var modelRequestProvider: AgentProviderID? + private var modelRequestBaseURL = "" struct ModelCatalog { var ids: [String] var reasoningLevels: [String: [String]] @@ -65,6 +67,8 @@ final class AgentAccountService: ObservableObject { /// 打开设置、更换服务/端点/密钥或用户主动刷新时,向服务商拉取可用模型。 func refreshModels(provider: AgentProviderID, baseURL: String) { + modelRequestProvider = provider + modelRequestBaseURL = baseURL liveReasoningLevels = [:] modelListTask?.cancel() liveModelsProvider = provider @@ -80,8 +84,10 @@ final class AgentAccountService: ObservableObject { /// 冷启动的输入框也需要实时推理能力,不要求先打开设置。 /// 多个输入框同时出现时复用当前查询,不清空已加载的能力。 func refreshReasoningCatalogIfNeeded(provider: AgentProviderID, baseURL: String) { - guard provider == .openaiCodex, !isRefreshingModels, - !hasLoadedModels(provider: provider) else { return } + guard provider == .openaiCodex else { return } + let sameRequest = modelRequestProvider == provider && modelRequestBaseURL == baseURL + if isRefreshingModels && sameRequest { return } + guard !hasLoadedModels(provider: provider) else { return } refreshModels(provider: provider, baseURL: baseURL) } diff --git a/Sources/WeiBei/Views/ComposerView.swift b/Sources/WeiBei/Views/ComposerView.swift index 6056582e5..90b89084e 100644 --- a/Sources/WeiBei/Views/ComposerView.swift +++ b/Sources/WeiBei/Views/ComposerView.swift @@ -165,7 +165,7 @@ struct ComposerView: View { } .onReceive(NotificationCenter.default.publisher(for: .weiBeiAgentOAuthDidSucceed)) { _ in guard showsReasoningEffort, store.agentProviderID == .openaiCodex else { return } - agentAccount.refreshReasoningCatalogIfNeeded(provider: store.agentProviderID, baseURL: store.agentBaseURL) + agentAccount.refreshModels(provider: store.agentProviderID, baseURL: store.agentBaseURL) } .accessibilityIdentifier("agent-composer-compact") } diff --git a/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift b/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift index 4c1e54dd9..0d24232d2 100644 --- a/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift +++ b/Tests/WeiBeiSafetyTests/ComposerReasoningCatalogTests.swift @@ -39,6 +39,33 @@ final class ComposerReasoningCatalogTests: XCTestCase { XCTAssertFalse(account.isRefreshingModels) XCTAssertTrue(account.models(provider: .custom).isEmpty) } + @MainActor + func testSwitchingToColdCodexSupersedesAnotherProvidersPendingCatalog() async throws { + var pending: [CheckedContinuation] = [] + let account = AgentAccountService(modelCatalogLoader: { _, _ in + try await withCheckedThrowingContinuation { pending.append($0) } + }) + account.refreshModels(provider: .openai, baseURL: "") + let firstDeadline = Date().addingTimeInterval(5) + while pending.count < 1 && Date() < firstDeadline { await Task.yield() } + guard pending.count == 1 else { return XCTFail("First synthetic request did not start") } + account.refreshReasoningCatalogIfNeeded(provider: .openaiCodex, baseURL: "") + let secondDeadline = Date().addingTimeInterval(5) + while pending.count < 2 && Date() < secondDeadline { await Task.yield() } + guard pending.count == 2 else { + pending[0].resume(throwing: CancellationError()) + return XCTFail("The cold Codex lookup was incorrectly blocked by another provider") + } + pending[1].resume(returning: .init(ids: ["codex-model"], reasoningLevels: ["codex-model": ["low", "high"]])) + let publishDeadline = Date().addingTimeInterval(5) + while account.isRefreshingModels && Date() < publishDeadline { await Task.yield() } + XCTAssertFalse(account.isRefreshingModels) + pending[0].resume(returning: .init(ids: ["obsolete-openai-model"], reasoningLevels: [:])) + await Task.yield() + XCTAssertEqual(account.models(provider: .openaiCodex), ["codex-model"]) + XCTAssertEqual(account.reasoningLevels(provider: .openaiCodex, model: "codex-model"), ["low", "high"]) + } + } #if os(macOS) && !targetEnvironment(macCatalyst) From 1fc51278052404165578b964003bfa4ce0c73d72 Mon Sep 17 00:00:00 2001 From: Codex Acceptance Date: Wed, 30 Sep 2026 23:00:29 -1000 Subject: [PATCH 11/11] fix: guard all cold model catalog publications by request generation --- .../WeiBei/Support/AgentAccountService.swift | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Sources/WeiBei/Support/AgentAccountService.swift b/Sources/WeiBei/Support/AgentAccountService.swift index 28ebd5322..a2858fcdb 100644 --- a/Sources/WeiBei/Support/AgentAccountService.swift +++ b/Sources/WeiBei/Support/AgentAccountService.swift @@ -50,6 +50,7 @@ final class AgentAccountService: ObservableObject { private var modelListTask: Task? private var modelRequestProvider: AgentProviderID? private var modelRequestBaseURL = "" + private var modelRequestGeneration = 0 struct ModelCatalog { var ids: [String] var reasoningLevels: [String: [String]] @@ -69,6 +70,8 @@ final class AgentAccountService: ObservableObject { func refreshModels(provider: AgentProviderID, baseURL: String) { modelRequestProvider = provider modelRequestBaseURL = baseURL + modelRequestGeneration += 1 + let generation = modelRequestGeneration liveReasoningLevels = [:] modelListTask?.cancel() liveModelsProvider = provider @@ -77,7 +80,7 @@ final class AgentAccountService: ObservableObject { modelListMessage = nil modelListCanRetry = false modelListTask = Task { [weak self] in - await self?.fetchLiveModels(provider: provider, baseURL: baseURL) + await self?.fetchLiveModels(provider: provider, baseURL: baseURL, generation: generation) } } @@ -329,11 +332,11 @@ final class AgentAccountService: ObservableObject { .sorted { $0.providerId < $1.providerId }) } - private func fetchLiveModels(provider: AgentProviderID, baseURL: String) async { + private func fetchLiveModels(provider: AgentProviderID, baseURL: String, generation: Int) async { if let modelCatalogLoader { do { let catalog = try await modelCatalogLoader(provider, baseURL) - guard !Task.isCancelled else { return } + guard generation == modelRequestGeneration, !Task.isCancelled else { return } let ids = Self.catalogEntries(catalog.ids, loadedFor: provider, provider: provider) let state = Self.successfulModelListState(ids) liveReasoningLevels = catalog.reasoningLevels @@ -343,7 +346,7 @@ final class AgentAccountService: ObservableObject { modelListMessage = state.message modelListCanRetry = state.canRetry } catch { - guard !Task.isCancelled else { return } + guard generation == modelRequestGeneration, !Task.isCancelled else { return } liveModelIDs = [] liveReasoningLevels = [:] liveModelsProvider = provider @@ -368,6 +371,7 @@ final class AgentAccountService: ObservableObject { ) guard let strategy else { await MainActor.run { + guard generation == modelRequestGeneration, !Task.isCancelled else { return } liveModelIDs = [] liveModelsProvider = provider isRefreshingModels = false @@ -423,8 +427,9 @@ final class AgentAccountService: ObservableObject { } let modelIDs = Self.catalogEntries(ids, loadedFor: provider, provider: provider) let state = Self.successfulModelListState(modelIDs) - guard !Task.isCancelled else { return } + guard generation == modelRequestGeneration, !Task.isCancelled else { return } await MainActor.run { + guard generation == modelRequestGeneration, !Task.isCancelled else { return } liveReasoningLevels = reasoningLevels liveModelIDs = modelIDs liveModelsProvider = provider @@ -433,9 +438,10 @@ final class AgentAccountService: ObservableObject { modelListCanRetry = state.canRetry } } catch { - guard !Task.isCancelled else { return } + guard generation == modelRequestGeneration, !Task.isCancelled else { return } logFailure("agent_model_list_failed", providerID: provider.credentialProviderID, error: error) await MainActor.run { + guard generation == modelRequestGeneration, !Task.isCancelled else { return } liveModelIDs = [] liveModelsProvider = provider isRefreshingModels = false