-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectedServicesView.swift
More file actions
288 lines (261 loc) · 10.5 KB
/
Copy pathConnectedServicesView.swift
File metadata and controls
288 lines (261 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import SwiftUI
import ManifoldInference
#if canImport(ManifoldMCP)
import ManifoldMCP
import Observation
struct ConnectedServicesView: View {
@Environment(\.dismiss) private var dismiss
@State private var coordinator: DemoMCPCoordinator
@State private var pendingConnect: MCPServerDescriptor?
private let disclosureConsentStore: MCPDataDisclosureConsentStore
init(
toolRegistry: ToolRegistry,
isFoundationModelsActive: @escaping () -> Bool = { false },
userDefaults: UserDefaults = .standard
) {
_coordinator = State(initialValue: DemoMCPCoordinator(
toolRegistry: toolRegistry,
isFoundationModelsActive: isFoundationModelsActive
))
self.disclosureConsentStore = MCPDataDisclosureConsentStore(userDefaults: userDefaults)
}
var body: some View {
NavigationStack {
Group {
if coordinator.catalog.isEmpty {
ContentUnavailableView {
Label("No services configured", systemImage: "link.badge.plus")
} description: {
Text(coordinator.catalogHelpText)
}
.accessibilityIdentifier("connected-services-catalog-empty-message")
} else {
List {
Section("Connected Services") {
ForEach(coordinator.catalog, id: \.id) { descriptor in
serviceRow(for: descriptor)
}
}
}
}
}
.navigationTitle("Connected Services")
.accessibilityIdentifier("connected-services-sheet")
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") {
dismiss()
}
}
}
.task {
coordinator.startListenersIfNeeded()
}
.confirmationDialog(
"Review data use",
isPresented: Binding(
get: { pendingConnect != nil },
set: { if !$0 { pendingConnect = nil } }
),
titleVisibility: .visible
) {
if let descriptor = pendingConnect {
Button("Connect") {
disclosureConsentStore.accept(serverID: descriptor.id)
coordinator.connect(descriptor)
pendingConnect = nil
}
}
Button("Cancel", role: .cancel) {
pendingConnect = nil
}
} message: {
if let descriptor = pendingConnect {
Text(disclosureMessage(for: descriptor))
}
}
}
}
@ViewBuilder
private func serviceRow(for descriptor: MCPServerDescriptor) -> some View {
let snapshot = coordinator.snapshot(for: descriptor.id)
VStack(alignment: .leading, spacing: 8) {
HStack(alignment: .firstTextBaseline) {
VStack(alignment: .leading, spacing: 4) {
Text(descriptor.displayName)
.font(.headline)
Text(snapshot.statusText)
.font(.caption)
.foregroundStyle(.secondary)
.accessibilityIdentifier("connected-service-status-\(descriptor.id.uuidString)")
}
Spacer()
if snapshot.isBusy {
ProgressView()
.controlSize(.small)
}
if snapshot.isConnected {
Button("Disconnect", role: .destructive) {
coordinator.disconnect(descriptor.id)
}
.buttonStyle(.bordered)
.disabled(snapshot.isBusy)
.accessibilityIdentifier("connected-service-disconnect-\(descriptor.id.uuidString)")
} else {
Button("Connect") {
if disclosureConsentStore.hasAccepted(serverID: descriptor.id) {
coordinator.connect(descriptor)
} else {
pendingConnect = descriptor
}
}
.buttonStyle(.borderedProminent)
.disabled(snapshot.isBusy)
.accessibilityIdentifier("connected-service-connect-\(descriptor.id.uuidString)")
}
}
if let auth = snapshot.authorizationRequest {
Label("Authorization required", systemImage: "person.badge.key")
.font(.caption)
.foregroundStyle(.orange)
if auth.requiredScopes.isEmpty == false {
Text("Scopes: \(auth.requiredScopes.joined(separator: ", "))")
.font(.caption2)
.foregroundStyle(.secondary)
}
}
if let error = snapshot.errorMessage {
Text(error)
.font(.caption2)
.foregroundStyle(.red)
.lineLimit(3)
}
if snapshot.foundationModelsCapActive,
snapshot.isConnected,
snapshot.enabledToolCount < snapshot.toolCount {
Label(
"Apple Intelligence supports up to \(MCPToolFilter.foundationModelsToolCap) tools with simple schemas — extras are hidden until you switch to a different backend.",
systemImage: "exclamationmark.shield"
)
.font(.caption2)
.foregroundStyle(.secondary)
.accessibilityIdentifier("connected-service-cap-footnote-\(descriptor.id.uuidString)")
}
DisclosureGroup("Data use") {
VStack(alignment: .leading, spacing: 6) {
Text(descriptor.dataDisclosure)
.font(.caption)
Text("Approval policy: \(approvalLabel(descriptor.approvalPolicy))")
.font(.caption2)
.foregroundStyle(.secondary)
}
}
.font(.caption)
}
.padding(.vertical, 4)
.accessibilityIdentifier("connected-service-row-\(descriptor.id.uuidString)")
}
private func approvalLabel(_ policy: MCPApprovalPolicy) -> String {
switch policy {
case .perCall: return "Per call"
case .perTurn: return "Per turn"
case .sessionForTool: return "Session per tool"
case .sessionForServer: return "Session per server"
case .persistentForTool: return "Persistent per tool"
}
}
private func disclosureMessage(for descriptor: MCPServerDescriptor) -> String {
let scopes: String = {
guard case .oauth(let oauth) = descriptor.authorization else { return "" }
guard oauth.scopes.isEmpty == false else { return "" }
return "\n\nRequested scopes: \(oauth.scopes.joined(separator: ", "))."
}()
return "\(descriptor.dataDisclosure)\(scopes)\n\nYou will only see this disclosure the first time you connect this service."
}
}
struct MCPDataDisclosureConsentStore {
private let userDefaults: UserDefaults
private let keyPrefix = "manifold.demo.mcp.dataDisclosure.accepted."
init(userDefaults: UserDefaults = .standard) {
self.userDefaults = userDefaults
}
func hasAccepted(serverID: UUID) -> Bool {
userDefaults.bool(forKey: key(for: serverID))
}
func accept(serverID: UUID) {
userDefaults.set(true, forKey: key(for: serverID))
}
private func key(for serverID: UUID) -> String {
keyPrefix + serverID.uuidString
}
}
struct ConnectedServiceSnapshot {
var state: MCPConnectionState = .idle
var isConnected = false
var isBusy = false
/// Total number of MCP tools registered for this server after the source's
/// own filter (allowList/denyList/maxToolCount) has been applied.
var toolCount = 0
/// Number of tools currently surfaced to the active backend. When the
/// Foundation Models cap (D18 + D21) is biting, this drops below
/// ``toolCount`` and the UI shows "X of Y enabled" so users can see
/// the cap in action.
var enabledToolCount = 0
/// Mirror of `DemoMCPCoordinator.isFoundationModelsActive()` captured at
/// the most recent refresh. The view uses this to decide whether to
/// surface the cap explanation footnote.
var foundationModelsCapActive = false
var errorMessage: String?
var authorizationRequest: MCPAuthorizationRequest?
var statusText: String {
let stateText: String = {
switch state {
case .idle: return "Idle"
case .connecting: return "Connecting"
case .ready: return "Connected"
case .reconnecting: return "Reconnecting"
case .failed: return "Failed"
}
}()
if isConnected {
return "\(stateText) · \(enabledToolCount) of \(toolCount) tools enabled"
}
return stateText
}
}
#else
struct ConnectedServicesView: View {
@Environment(\.dismiss) private var dismiss
let toolRegistry: ToolRegistry
init(
toolRegistry: ToolRegistry,
isFoundationModelsActive: @escaping () -> Bool = { false },
userDefaults: UserDefaults = .standard
) {
self.toolRegistry = toolRegistry
// Probe is captured but unused — there's no MCP surface to filter when
// ManifoldMCP isn't linked. Keeps call sites symmetrical.
_ = isFoundationModelsActive
_ = userDefaults
}
var body: some View {
NavigationStack {
List {
Section("Connected Services") {
Label("ManifoldMCP is not linked in this build.", systemImage: "link.slash")
.font(.footnote)
.foregroundStyle(.secondary)
}
}
.navigationTitle("Connected Services")
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") {
dismiss()
}
}
}
}
}
}
#endif