-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathRunInTerminalToolView.swift
More file actions
359 lines (319 loc) · 13.4 KB
/
RunInTerminalToolView.swift
File metadata and controls
359 lines (319 loc) · 13.4 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import ChatService
import ComposableArchitecture
import ConversationServiceProvider
import GitHubCopilotService
import SharedUIComponents
import SwiftUI
import Terminal
import XcodeInspector
struct RunInTerminalToolView: View {
let tool: AgentToolCall
let command: String?
let explanation: String?
let isBackground: Bool?
let chat: StoreOf<Chat>
private var title: String = "Run command in terminal"
@AppStorage(\.codeBackgroundColorLight) var codeBackgroundColorLight
@AppStorage(\.codeForegroundColorLight) var codeForegroundColorLight
@AppStorage(\.codeBackgroundColorDark) var codeBackgroundColorDark
@AppStorage(\.codeForegroundColorDark) var codeForegroundColorDark
@AppStorage(\.chatFontSize) var chatFontSize
@Environment(\.colorScheme) var colorScheme
init(tool: AgentToolCall, chat: StoreOf<Chat>) {
self.tool = tool
self.chat = chat
let input = (tool.invokeParams?.input as? [String: AnyCodable]) ?? tool.input
if let input {
self.command = input["command"]?.value as? String
self.explanation = input["explanation"]?.value as? String
self.isBackground = input["isBackground"]?.value as? Bool
self.title = (isBackground != nil && isBackground!) ? "Run command in background terminal" : "Run command in terminal"
} else {
self.command = nil
self.explanation = nil
self.isBackground = nil
}
}
var terminalSession: TerminalSession? {
return TerminalSessionManager.shared.getSession(for: tool.id)
}
var statusIcon: some View {
Group {
switch tool.status {
case .running:
ProgressView()
.controlSize(.small)
.scaleEffect(0.7)
case .completed:
Image(systemName: "checkmark")
.foregroundColor(.green.opacity(0.5))
case .error:
Image(systemName: "xmark.circle")
.foregroundColor(.red.opacity(0.5))
case .cancelled:
Image(systemName: "slash.circle")
.foregroundColor(.gray.opacity(0.5))
case .waitForConfirmation:
EmptyView()
case .accepted:
EmptyView()
}
}
}
var body: some View {
WithPerceptionTracking {
if tool.status == .waitForConfirmation || terminalSession != nil {
VStack {
HStack {
Image("Terminal")
.resizable()
.scaledToFit()
.scaledFrame(width: 16, height: 16)
Text(self.title)
.scaledFont(size: chatFontSize, weight: .semibold)
.foregroundStyle(.primary)
.background(Color.clear)
.frame(maxWidth: .infinity, alignment: .leading)
}
toolView
}
.scaledPadding(8)
.cornerRadius(8)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.gray.opacity(0.2), lineWidth: 1)
)
} else {
toolView
}
}
}
var codeBackgroundColor: Color {
if colorScheme == .light, let color = codeBackgroundColorLight.value {
return color.swiftUIColor
} else if let color = codeBackgroundColorDark.value {
return color.swiftUIColor
}
return Color(nsColor: .textBackgroundColor).opacity(0.7)
}
var codeForegroundColor: Color {
if colorScheme == .light, let color = codeForegroundColorLight.value {
return color.swiftUIColor
} else if let color = codeForegroundColorDark.value {
return color.swiftUIColor
}
return Color(nsColor: .textColor)
}
var toolView: some View {
WithPerceptionTracking {
VStack {
if command != nil {
HStack(spacing: 4) {
statusIcon
.scaledFrame(width: 16, height: 16)
Text(command!)
.lineLimit(nil)
.textSelection(.enabled)
.scaledFont(size: chatFontSize, design: .monospaced)
.scaledPadding(8)
.frame(maxWidth: .infinity, alignment: .leading)
.fixedSize(horizontal: false, vertical: true)
.foregroundStyle(codeForegroundColor)
.background(codeBackgroundColor)
.clipShape(RoundedRectangle(cornerRadius: 6))
.overlay {
RoundedRectangle(cornerRadius: 6).stroke(Color.primary.opacity(0.05), lineWidth: 1)
}
}
} else {
Text("Invalid parameter in the toolcall for runInTerminal")
}
if let terminalSession = terminalSession {
XTermView(
terminalSession: terminalSession,
onTerminalInput: terminalSession.handleTerminalInput
)
.scaledFrame(minHeight: 200, maxHeight: 400)
} else if tool.status == .waitForConfirmation {
ThemedMarkdownText(text: explanation ?? "", chat: chat)
.frame(maxWidth: .infinity, alignment: .leading)
HStack {
Button(action: {
chat.send(.toolCallCancelled(tool.id))
}) {
Text("Skip")
.scaledFont(.body)
}
if FeatureFlagNotifierImpl.shared.featureFlags.agentModeAutoApproval &&
CopilotPolicyNotifierImpl.shared.copilotPolicy.agentModeAutoApprovalEnabled,
let command, !command.isEmpty {
SplitButton(
title: "Allow",
isDisabled: false,
primaryAction: {
chat.send(.toolCallAccepted(tool.id))
},
menuItems: terminalMenuItems(command: command),
style: .prominent
)
} else {
Button(action: {
chat.send(.toolCallAccepted(tool.id))
}) {
Text("Allow")
.scaledFont(.body)
}
.buttonStyle(BorderedProminentButtonStyle())
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.scaledPadding(.top, 4)
}
}
}
}
private func terminalMenuItems(command: String) -> [SplitButtonMenuItem] {
var items: [SplitButtonMenuItem] = []
let subCommands = ToolAutoApprovalManager.extractSubCommandsWithTreeSitter(command)
let commandNames = extractCommandNamesForMenu(subCommands)
let commandNamesLabel = formatCommandNameListForMenu(commandNames)
let trimmedCommand = command.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedSubCommands = subCommands
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { !$0.isEmpty }
let shouldShowExactCommandLineItems = !(
trimmedSubCommands.count == 1 &&
trimmedSubCommands[0] == trimmedCommand &&
commandNames.contains(trimmedCommand)
)
let conversationId = tool.invokeParams?.conversationId ?? ""
let hasConversationId = !conversationId.isEmpty
// Session-scoped
if hasConversationId, !commandNames.isEmpty {
items.append(
SplitButtonMenuItem(title: sessionAllowCommandsTitle(commandNamesLabel: commandNamesLabel, commandCount: commandNames.count)) {
chat.send(
.toolCallAcceptedWithApproval(
tool.id,
.terminal(
scope: .session(conversationId),
commands: commandNames
)
)
)
}
)
}
// Global
if !commandNames.isEmpty {
items.append(
SplitButtonMenuItem(title: alwaysAllowCommandsTitle(commandNamesLabel: commandNamesLabel, commandCount: commandNames.count)) {
chat.send(
.toolCallAcceptedWithApproval(
tool.id,
.terminal(
scope: .global,
commands: commandNames
)
)
)
}
)
}
items.append(.divider())
if shouldShowExactCommandLineItems {
// Session-scoped exact command line
if hasConversationId {
items.append(
SplitButtonMenuItem(title: "Allow Exact Command Line in this Session") {
chat.send(
.toolCallAcceptedWithApproval(
tool.id,
.terminal(
scope: .session(conversationId),
commands: [command]
)
)
)
}
)
}
// Global exact command line
items.append(
SplitButtonMenuItem(title: "Always Allow Exact Command Line") {
chat.send(
.toolCallAcceptedWithApproval(
tool.id,
.terminal(
scope: .global,
commands: [command]
)
)
)
}
)
items.append(.divider())
}
// Session-scoped allow all
if hasConversationId {
items.append(
SplitButtonMenuItem(title: "Allow All Commands in this Session") {
chat.send(
.toolCallAcceptedWithApproval(
tool.id,
.terminal(
scope: .session(conversationId),
commands: []
)
)
)
}
)
}
items.append(.divider())
items.append(
SplitButtonMenuItem(title: "Configure Auto Approve...") {
chat.send(.openAutoApproveSettings)
}
)
return items
}
private func formatSubCommandListForMenu(_ subCommands: [String]) -> String {
let trimmed = subCommands.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
guard !trimmed.isEmpty else { return "(none)" }
return trimmed.joined(separator: ", ")
}
private func extractCommandNamesForMenu(_ subCommands: [String]) -> [String] {
var result: [String] = []
var seen: Set<String> = []
for subCommand in subCommands {
guard let name = ToolAutoApprovalManager.extractTerminalCommandName(fromSubCommand: subCommand) else {
continue
}
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { continue }
guard !seen.contains(trimmed) else { continue }
seen.insert(trimmed)
result.append(trimmed)
}
return result
}
private func formatCommandNameListForMenu(_ commandNames: [String]) -> String {
let trimmed = commandNames.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
guard !trimmed.isEmpty else { return "(none)" }
func suffixEllipsis(_ name: String) -> String { "`\(name) ...`" }
return trimmed.map(suffixEllipsis).joined(separator: ", ")
}
private func sessionAllowCommandsTitle(commandNamesLabel: String, commandCount: Int) -> String {
if commandCount == 1 {
return "Allow \(commandNamesLabel) in this Session"
}
return "Allow Commands \(commandNamesLabel) in this Session"
}
private func alwaysAllowCommandsTitle(commandNamesLabel: String, commandCount: Int) -> String {
if commandCount == 1 {
return "Always Allow \(commandNamesLabel)"
}
return "Always Allow Commands \(commandNamesLabel)"
}
}