Repository Public
1import AIAssistant2import SessionStore3import SSHKit4import SwiftUI5import TerminalCore6import WorkspaceKit78struct SheetHost: View {9 let sheet: SheetKind10 @Bindable var state: WindowState11 let model: AppModel1213 var body: some View {14 Group {15 switch sheet {16 case .pasteConfirmation(let request): PasteConfirmationSheet(request: request, state: state, model: model)17 case .renamePane(let pane, let current):18 RenameSheet(title: "Rename Session", initial: current) { model.rename(pane: pane, to: $0) } close: { close() }19 case .renameTab(let tab, let current):20 RenameSheet(title: "Rename Tab", initial: current) { model.rename(tab: tab, in: state, to: $0) } close: { close() }21 case .saveWorkspace:22 RenameSheet(title: "Save Workspace", initial: "", prompt: "Name",23 note: "Saves the arrangement of all windows, their displays, session types and directories. Opening it later starts new processes.") {24 if !$0.trimmingCharacters(in: .whitespaces).isEmpty { model.saveCurrentWorkspace(named: $0) }25 } close: { close() }26 case .snippet(let run): SnippetSheet(run: run, state: state, model: model)27 case .hostEditor(let draft): HostEditorSheet(draft: draft, state: state, model: model)28 case .fleetPicker: FleetPickerSheet(state: state, model: model)29 case .broadcastConfirm(let tab): BroadcastConfirmSheet(tab: tab, state: state, model: model)30 case .commandConfirm(let confirmation): CommandConfirmSheet(confirmation: confirmation, state: state, model: model)31 case .clipboardWrite(let text, let source): ClipboardWriteSheet(text: text, source: source, state: state, model: model)32 }33 }34 .padding(20)35 .frame(minWidth: 460)36 }3738 private func close() {39 state.sheet = nil40 model.focusCurrentPane(in: state)41 }42}4344struct RenameSheet: View {45 let title: String46 let initial: String47 var prompt = "Title"48 var note: String?49 let commit: (String) -> Void50 let close: () -> Void51 @State private var text = ""5253 var body: some View {54 VStack(alignment: .leading, spacing: 12) {55 Text(title).font(.headline)56 if let note { Text(note).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }57 TextField(prompt, text: $text).textFieldStyle(.roundedBorder).onSubmit { commit(text); close() }58 HStack {59 Spacer()60 Button("Cancel", role: .cancel) { close() }.keyboardShortcut(.cancelAction)61 Button("OK") { commit(text); close() }.keyboardShortcut(.defaultAction)62 }63 }64 .onAppear { text = initial }65 }66}6768/// Shows exactly what is about to be pasted and why SP Term is asking.69struct PasteConfirmationSheet: View {70 let request: PasteRequest71 @Bindable var state: WindowState72 let model: AppModel7374 var body: some View {75 let assessment = PasteGuard.assess(request.text)76 VStack(alignment: .leading, spacing: 12) {77 Label(assessment.isSuspicious ? "This text contains terminal control sequences" : "Paste \(assessment.lineCount) lines?",78 systemImage: assessment.isSuspicious ? "exclamationmark.triangle.fill" : "doc.on.clipboard")79 .font(.headline).foregroundStyle(assessment.isSuspicious ? Color.red : Color.primary)80 VStack(alignment: .leading, spacing: 4) {81 if assessment.containsBracketEscape {82 Text("• It contains an “end of paste” marker, a known trick to make the rest run as if you had typed it.")83 }84 if assessment.containsControlCharacters && !assessment.containsBracketEscape {85 Text("• It contains invisible control characters.")86 }87 if assessment.isMultiline { Text("• Several lines: a shell starts running the first lines before you can read the rest.") }88 if assessment.endsWithNewline { Text("• It ends with a line break: the last line would run immediately.") }89 if assessment.mentionsSudo { Text("• It mentions sudo.") }90 }91 .font(.callout).foregroundStyle(.secondary)92 ScrollView {93 Text(visible(request.text))94 .font(.system(size: 12, design: .monospaced))95 .frame(maxWidth: .infinity, alignment: .leading)96 .textSelection(.enabled)97 .padding(8)98 }99 .frame(minHeight: 80, maxHeight: 220)100 .background(RoundedRectangle(cornerRadius: 6).fill(Color.primary.opacity(0.06)))101 .accessibilityLabel("Text to paste")102 HStack {103 Text("\(assessment.byteCount) bytes").font(.caption).foregroundStyle(.secondary)104 Spacer()105 Button("Cancel", role: .cancel) { close() }.keyboardShortcut(.cancelAction)106 if !assessment.isSuspicious {107 Button("Paste") { pasteOriginal() }108 }109 Button(assessment.isSuspicious ? "Paste Sanitized" : "Paste Without Final Line Break") { pasteSanitized() }110 .keyboardShortcut(.defaultAction)111 }112 }113 .frame(width: 560)114 }115116 /// Control characters are shown as visible symbols so nothing hides in the preview.117 private func visible(_ text: String) -> String {118 var result = ""119 for scalar in text.unicodeScalars {120 switch scalar.value {121 case 0x1b: result += "␛"122 case 0x0a: result += "⏎\n"123 case 0x0d: result += "␍"124 case 0x09: result += "\t"125 case 0..<0x20, 0x7f, 0x80...0x9f: result += "�"126 default: result.unicodeScalars.append(scalar)127 }128 }129 return String(result.prefix(20_000))130 }131132 private func pasteOriginal() {133 close()134 if request.isDrop || NSPasteboard.general.changeCount != request.changeCount {135 // The clipboard changed while the sheet was open: paste the text that was reviewed.136 model.sendPasteText(request.text, to: request.pane)137 } else {138 model.session(for: request.pane)?.view.pasteApproved()139 }140 }141142 private func pasteSanitized() {143 close()144 model.sendPasteText(PasteGuard.sanitize(request.text), to: request.pane)145 }146147 private func close() {148 state.sheet = nil149 model.focusCurrentPane(in: state)150 }151}152153struct BroadcastConfirmSheet: View {154 let tab: TabID155 @Bindable var state: WindowState156 let model: AppModel157158 var body: some View {159 let panes = state.tabs.first { $0.id == tab }?.layout.panes ?? []160 VStack(alignment: .leading, spacing: 12) {161 Label("Broadcast input to \(panes.count) sessions?", systemImage: "dot.radiowaves.left.and.right").font(.headline)162 Text("Every key you press in one pane of this tab will also be sent to the others — including passwords and Return.")163 .fixedSize(horizontal: false, vertical: true)164 VStack(alignment: .leading, spacing: 2) {165 ForEach(panes, id: \.self) { pane in166 Label(model.paneTitle(pane) + (model.remoteHost(of: pane).map { " — \($0)" } ?? ""), systemImage: "terminal").font(.callout)167 }168 }169 Text("A yellow banner stays visible while broadcasting. Commands that look destructive or use sudo are held and need a second confirmation before they reach the other panes. Broadcasting is never restored automatically.")170 .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)171 HStack {172 Spacer()173 Button("Cancel", role: .cancel) { close() }.keyboardShortcut(.cancelAction)174 Button("Start Broadcasting") {175 model.enableBroadcast(tab: tab, in: state)176 close()177 }178 }179 }180 .frame(width: 500)181 }182183 private func close() {184 state.sheet = nil185 model.focusCurrentPane(in: state)186 }187}188189/// The only place where SP Term runs a command on the user's behalf. Shows the full command,190/// where it will run and why it is risky; risky commands need a typed phrase.191struct CommandConfirmSheet: View {192 let confirmation: CommandConfirmation193 @Bindable var state: WindowState194 let model: AppModel195 @State private var typed = ""196 @State private var error: String?197198 var body: some View {199 let proposal = confirmation.proposal200 let requirement = model.gate.requirement(for: proposal)201 let phrase = model.gate.confirmationPhrase(for: proposal)202 VStack(alignment: .leading, spacing: 12) {203 Label(confirmation.title, systemImage: proposal.risk.level == .destructive ? "exclamationmark.octagon.fill" : "play.circle")204 .font(.headline)205 .foregroundStyle(proposal.risk.level == .destructive ? Color.red : Color.primary)206 ScrollView {207 Text(proposal.text).font(.system(size: 12, design: .monospaced)).textSelection(.enabled)208 .frame(maxWidth: .infinity, alignment: .leading).padding(8)209 }210 .frame(minHeight: 44, maxHeight: 160)211 .background(RoundedRectangle(cornerRadius: 6).fill(Color.primary.opacity(0.06)))212 .accessibilityLabel("Command")213 Grid(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 3) {214 GridRow { Text("Target").foregroundStyle(.secondary); Text(confirmation.targetDescription) }215 GridRow { Text("Host").foregroundStyle(.secondary); Text(proposal.host ?? "this Mac") }216 GridRow { Text("Directory").foregroundStyle(.secondary); Text(proposal.workingDirectory.map(Formatters.abbreviate(path:)) ?? "—") }217 GridRow { Text("Risk").foregroundStyle(.secondary); Text(riskLabel(proposal.risk.level)) }218 }219 .font(.callout)220 if !proposal.risk.explanations.isEmpty {221 VStack(alignment: .leading, spacing: 2) {222 ForEach(proposal.risk.explanations, id: \.self) { Text("• " + $0) }223 }224 .font(.callout).foregroundStyle(.secondary)225 }226 if requirement == .reinforced {227 Text("Type “\(phrase)” to confirm.").font(.callout.weight(.medium))228 TextField(phrase, text: $typed).textFieldStyle(.roundedBorder).accessibilityLabel("Confirmation phrase")229 }230 if let error { Text(error).font(.callout).foregroundStyle(.red) }231 HStack {232 Spacer()233 Button("Cancel", role: .cancel) {234 confirmation.onCancelled()235 close()236 }237 .keyboardShortcut(.cancelAction)238 Button(requirement == .reinforced ? "Run Anyway" : "Run") { approve(requirement) }239 .disabled(requirement == .reinforced && typed.isEmpty)240 }241 }242 .frame(width: 540)243 }244245 private func riskLabel(_ level: RiskLevel) -> String {246 switch level {247 case .safe: return "No known risky pattern"248 case .caution: return "Caution"249 case .destructive: return "Destructive"250 }251 }252253 private func approve(_ requirement: ConsentRequirement) {254 do {255 let approved = try model.gate.approve(confirmation.proposal,256 with: requirement == .reinforced ? .reinforced(typedPhrase: typed) : .standard)257 close()258 confirmation.onApproved(approved)259 } catch {260 self.error = "The confirmation phrase does not match."261 }262 }263264 private func close() {265 state.sheet = nil266 model.focusCurrentPane(in: state)267 }268}269270struct ClipboardWriteSheet: View {271 let text: String272 let source: String273 @Bindable var state: WindowState274 let model: AppModel275276 var body: some View {277 VStack(alignment: .leading, spacing: 12) {278 Label("“\(source)” wants to replace the clipboard", systemImage: "doc.on.clipboard").font(.headline)279 ScrollView {280 Text(String(text.prefix(4000))).font(.system(size: 12, design: .monospaced)).textSelection(.enabled)281 .frame(maxWidth: .infinity, alignment: .leading).padding(8)282 }283 .frame(minHeight: 50, maxHeight: 160)284 .background(RoundedRectangle(cornerRadius: 6).fill(Color.primary.opacity(0.06)))285 Text("Programs can request this with an escape sequence (OSC 52), including programs on remote hosts. You can change this behaviour in Settings › Safety.")286 .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)287 HStack {288 Spacer()289 Button("Don’t Allow", role: .cancel) { close() }.keyboardShortcut(.cancelAction)290 Button("Copy to Clipboard") {291 NSPasteboard.general.clearContents()292 NSPasteboard.general.setString(text, forType: .string)293 close()294 }295 }296 }297 .frame(width: 480)298 }299300 private func close() {301 state.sheet = nil302 model.focusCurrentPane(in: state)303 }304}305306/// Fills the variables of a snippet and shows the resulting command before anything happens.307struct SnippetSheet: View {308 let run: SnippetRun309 @Bindable var state: WindowState310 let model: AppModel311 @State private var values: [String: String] = [:]312313 var body: some View {314 if let snippet = model.snippets.first(where: { $0.id == run.snippetID }) {315 let rendered = snippet.render(values)316 VStack(alignment: .leading, spacing: 12) {317 Text(snippet.name).font(.headline)318 if !snippet.note.isEmpty { Text(snippet.note).font(.callout).foregroundStyle(.secondary) }319 ForEach(snippet.variables, id: \.name) { variable in320 HStack {321 Text(variable.name).frame(width: 90, alignment: .trailing).foregroundStyle(.secondary)322 TextField(variable.defaultValue.isEmpty ? "value" : variable.defaultValue, text: Binding(323 get: { values[variable.name] ?? "" },324 set: { values[variable.name] = $0.isEmpty ? nil : $0 }))325 .textFieldStyle(.roundedBorder)326 }327 }328 Text("Command").font(.caption).foregroundStyle(.secondary)329 Text(rendered).font(.system(size: 12, design: .monospaced)).textSelection(.enabled)330 .frame(maxWidth: .infinity, alignment: .leading).padding(8)331 .background(RoundedRectangle(cornerRadius: 6).fill(Color.primary.opacity(0.06)))332 Text("Values are quoted for the shell. “Insert” places the command at the prompt without running it.")333 .font(.caption).foregroundStyle(.secondary)334 HStack {335 Spacer()336 Button("Cancel", role: .cancel) { close() }.keyboardShortcut(.cancelAction)337 Button("Review & Run…") {338 guard let pane = run.pane ?? state.focusedPane else { return }339 state.sheet = nil340 DispatchQueue.main.async { model.requestRun(command: rendered, in: pane, source: "snippet", title: "Run this snippet?") }341 }342 Button("Insert at Prompt") {343 if let pane = run.pane ?? state.focusedPane { model.insert(command: rendered, into: pane) }344 close()345 }346 .keyboardShortcut(.defaultAction)347 }348 }349 .frame(width: 520)350 } else {351 Text("This snippet no longer exists.").onAppear { state.sheet = nil }352 }353 }354355 private func close() {356 state.sheet = nil357 model.focusCurrentPane(in: state)358 }359}360361struct HostEditorSheet: View {362 @State var draft: HostDraft363 @Bindable var state: WindowState364 let model: AppModel365 @State private var error: String?366367 init(draft: HostDraft, state: WindowState, model: AppModel) {368 _draft = State(initialValue: draft)369 self.state = state370 self.model = model371 }372373 var body: some View {374 VStack(alignment: .leading, spacing: 10) {375 Text(draft.isNew ? "New SSH Host" : "Edit SSH Host").font(.headline)376 Form {377 TextField("Label", text: $draft.label)378 TextField("Host name or address", text: $draft.host)379 TextField("User (optional)", text: $draft.user)380 TextField("Port (optional)", text: $draft.port)381 TextField("ProxyJump (optional)", text: $draft.proxyJump)382 TextField("Group (optional)", text: $draft.group)383 }384 .formStyle(.columns)385 Text("SP Term runs the system ssh. Keys stay in your agent and ~/.ssh; passwords are typed in the terminal and never stored. Host keys are always verified by OpenSSH.")386 .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)387 if let error { Text(error).font(.callout).foregroundStyle(.red) }388 HStack {389 Spacer()390 Button("Cancel", role: .cancel) { state.sheet = nil }.keyboardShortcut(.cancelAction)391 Button("Save") { save() }.keyboardShortcut(.defaultAction)392 }393 }394 .frame(width: 460)395 }396397 private func save() {398 let port = draft.port.trimmingCharacters(in: .whitespaces)399 if !port.isEmpty, Int(port) == nil { error = "The port must be a number."; return }400 let profile = SSHHostProfile(id: draft.id, label: draft.label.isEmpty ? draft.host : draft.label, host: draft.host.trimmingCharacters(in: .whitespaces),401 user: draft.user.isEmpty ? nil : draft.user, port: Int(port), proxyJump: draft.proxyJump.isEmpty ? nil : draft.proxyJump,402 group: draft.group.isEmpty ? nil : draft.group, isFavorite: false, source: .manual)403 do {404 // Reject anything the command builder would refuse (injection attempts, bad ports…).405 _ = try SSHCommandBuilder.sshCommand(for: profile)406 } catch {407 self.error = error.localizedDescription408 return409 }410 model.manualHosts.removeAll { $0.id == profile.id }411 model.manualHosts.append(profile)412 model.saveHosts()413 state.sheet = nil414 }415}416417/// Choose the hosts of an "SSH Fleet" grid. Nothing connects until the user confirms.418struct FleetPickerSheet: View {419 @Bindable var state: WindowState420 let model: AppModel421 @State private var selected: Set<UUID> = []422423 var body: some View {424 let hosts = model.hosts425 VStack(alignment: .leading, spacing: 10) {426 Text("SSH Fleet").font(.headline)427 Text("Opens one pane per selected host. Each pane only starts ssh; no command is sent to the hosts.")428 .font(.callout).foregroundStyle(.secondary)429 if hosts.isEmpty {430 Text("No hosts yet. Add one in the SSH Hosts panel or in ~/.ssh/config.").foregroundStyle(.secondary).padding(.vertical, 12)431 }432 ScrollView {433 VStack(alignment: .leading, spacing: 2) {434 ForEach(hosts) { host in435 Toggle(isOn: Binding(get: { selected.contains(host.id) },436 set: { if $0 { selected.insert(host.id) } else { selected.remove(host.id) } })) {437 Text(host.label) + Text(host.group.map { " \($0)" } ?? "").foregroundStyle(.secondary)438 }439 }440 }441 .frame(maxWidth: .infinity, alignment: .leading)442 }443 .frame(maxHeight: 260)444 HStack {445 Button("Select All") { selected = Set(hosts.map(\.id)) }446 Spacer()447 Button("Cancel", role: .cancel) { state.sheet = nil }.keyboardShortcut(.cancelAction)448 Button("Open \(selected.count) Sessions") {449 let aliases = hosts.filter { selected.contains($0.id) }.map(\.host)450 state.sheet = nil451 model.open(preset: .sshFleet, hosts: aliases, replacing: state)452 }453 .disabled(selected.isEmpty)454 .keyboardShortcut(.defaultAction)455 }456 }457 .frame(width: 440)458 }459}460