Repository Public
1import AppKit2import MCCCore3import SwiftUI45/// Plain-text log viewer. AppKit's text view is used because SwiftUI's `Text` cannot select across lines, scroll to6/// a range or highlight matches in a large buffer. The content is set as a plain string: never markup, never ANSI.7struct LogTextView: NSViewRepresentable {8 let text: String9 let matches: [NSRange]10 let current: Int?11 let followTail: Bool12 let colors: Colors1314 struct Colors: Equatable {15 var text: NSColor16 var background: NSColor17 var match: NSColor18 var currentMatch: NSColor19 }2021 final class Coordinator {22 var text = ""23 var matches: [NSRange] = []24 var current: Int?25 var colors: Colors?26 }2728 func makeCoordinator() -> Coordinator { Coordinator() }2930 func makeNSView(context: Context) -> NSScrollView {31 let scroll = NSTextView.scrollableTextView()32 guard let tv = scroll.documentView as? NSTextView else { return scroll }33 tv.isEditable = false34 tv.isSelectable = true35 tv.isRichText = false36 tv.usesFindBar = false37 tv.isAutomaticLinkDetectionEnabled = false38 tv.isAutomaticDataDetectionEnabled = false39 tv.textContainerInset = NSSize(width: 10, height: 10)40 tv.font = NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize(for: .regular), weight: .regular)41 tv.setAccessibilityLabel(tr("logs.text.label"))42 tv.setAccessibilityIdentifier("logs-text")43 scroll.hasVerticalScroller = true44 scroll.drawsBackground = true45 return scroll46 }4748 func updateNSView(_ scroll: NSScrollView, context: Context) {49 guard let tv = scroll.documentView as? NSTextView, let storage = tv.textStorage else { return }50 let c = context.coordinator51 let textChanged = c.text != text52 if textChanged || c.colors != colors {53 let font = NSFont.monospacedSystemFont(ofSize: NSFont.preferredFont(forTextStyle: .body).pointSize, weight: .regular)54 storage.setAttributedString(NSAttributedString(string: text, attributes: [.font: font, .foregroundColor: colors.text]))55 tv.backgroundColor = colors.background56 scroll.backgroundColor = colors.background57 c.text = text58 c.colors = colors59 c.matches = []60 c.current = nil61 }62 if c.matches != matches || c.current != current {63 let full = NSRange(location: 0, length: storage.length)64 storage.beginEditing()65 storage.removeAttribute(.backgroundColor, range: full)66 for (i, r) in matches.enumerated() where NSMaxRange(r) <= storage.length {67 storage.addAttribute(.backgroundColor, value: i == current ? colors.currentMatch : colors.match, range: r)68 }69 storage.endEditing()70 let moved = c.current != current71 c.matches = matches72 c.current = current73 if moved, let current, matches.indices.contains(current), NSMaxRange(matches[current]) <= storage.length {74 tv.scrollRangeToVisible(matches[current])75 return76 }77 }78 if textChanged, followTail { tv.scrollToEndOfDocument(nil) }79 }80}8182/// Logs window of one service, fed by the typed action `service.logs.tail`.83struct ServiceLogsView: View {84 @Environment(AppModel.self) private var app85 @Environment(\.mccTheme) private var theme86 let ref: LogsRef87 @State private var model: LogsTailModel?88 @State private var query = ""89 @State private var current = 09091 var body: some View {92 VStack(alignment: .leading, spacing: 0) {93 header94 Divider()95 if let model { content(model) } else { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }96 }97 .background(theme.canvas)98 .navigationTitle(tr("logs.window.title", ref.serviceName, ref.nodeAlias))99 .task {100 if model == nil {101 let m = LogsTailModel(serviceID: ref.serviceID, serviceName: ref.serviceName, session: app.session)102 model = m103 await m.prepare()104 if m.phase == .ready, app.session.canMutate { await m.request() }105 }106 }107 .onDisappear { model?.stop() }108 }109110 private var header: some View {111 HStack(spacing: Tokens.Space.s3) {112 VStack(alignment: .leading, spacing: 1) {113 Text(ref.serviceName).font(.headline).foregroundStyle(theme.textPrimary)114 Text(ref.nodeAlias).font(.caption).foregroundStyle(theme.textSecondary)115 }116 Spacer()117 if let t = model?.receivedAt {118 Text(tr("logs.received_at", Format.time(t, seconds: true))).font(.caption).foregroundStyle(theme.textTertiary)119 .accessibilityIdentifier("logs-received")120 }121 }122 .padding(.horizontal, Tokens.Space.s5)123 .padding(.vertical, Tokens.Space.s3)124 .accessibilityElement(children: .combine)125 }126127 @ViewBuilder128 private func content(_ model: LogsTailModel) -> some View {129 switch model.phase {130 case .preparing:131 ProgressView(tr("state.loading")).frame(maxWidth: .infinity, maxHeight: .infinity)132 case .catalogUnavailable(let reason):133 UnavailableStateView(reason: reason, error: model.catalogError) { Task { await model.prepare() } }134 case .typeMissing:135 EmptyStateView(tr("logs.type_missing.title"), message: tr("logs.type_missing.message"), systemImage: "doc.text.magnifyingglass")136 .accessibilityIdentifier("logs-type-missing")137 case .typeDisabled(let reason):138 EmptyStateView(tr("logs.type_disabled.title"), message: reason ?? tr("logs.type_disabled.message"), systemImage: "nosign")139 .accessibilityIdentifier("logs-type-disabled")140 case .ready:141 ready(model)142 }143 }144145 @ViewBuilder146 private func ready(_ model: LogsTailModel) -> some View {147 @Bindable var model = model148 let matches = LogSearch.ranges(of: query, in: model.text)149 let index = matches.isEmpty ? nil : min(current, matches.count - 1)150 VStack(alignment: .leading, spacing: 0) {151 HStack(spacing: Tokens.Space.s3) {152 Button { Task { await model.request() } } label: { Label(tr("logs.fetch"), systemImage: "arrow.clockwise") }153 .disabled(model.isRequesting || model.follow || app.session.isOffline)154 .keyboardShortcut("r", modifiers: .command)155 .accessibilityIdentifier("logs-fetch")156 Toggle(tr("logs.follow"), isOn: $model.follow).toggleStyle(.switch).controlSize(.small)157 .help(tr("logs.follow.help", Int(model.followInterval)))158 .disabled(app.session.isOffline)159 .accessibilityIdentifier("logs-follow")160 if model.lineField != nil {161 Stepper(value: Binding(get: { model.lineCount ?? model.lineRange.lowerBound }, set: { model.lineCount = $0 }),162 in: model.lineRange, step: 50) {163 Text(tr("logs.lines", model.lineCount ?? 0)).monospacedDigit()164 }165 .fixedSize()166 .accessibilityLabel(tr("logs.lines.label"))167 .accessibilityValue("\(model.lineCount ?? 0)")168 }169 if model.isRequesting { ProgressView().controlSize(.small).accessibilityLabel(tr("logs.requesting")) }170 Spacer(minLength: Tokens.Space.s3)171 TextField(tr("logs.search"), text: $query).textFieldStyle(.roundedBorder).frame(maxWidth: 200)172 .onSubmit { step(matches.count, forward: true) }173 .accessibilityLabel(tr("logs.search"))174 .accessibilityIdentifier("logs-search")175 if !query.trimmingCharacters(in: .whitespaces).isEmpty {176 Text(matches.isEmpty ? tr("logs.search.none") : tr("logs.search.position", (index ?? 0) + 1, matches.count))177 .font(.caption).foregroundStyle(theme.textSecondary).monospacedDigit()178 .accessibilityIdentifier("logs-search-count")179 Button { step(matches.count, forward: false) } label: { Label(tr("logs.search.previous"), systemImage: "chevron.up") }180 .labelStyle(.iconOnly).disabled(matches.isEmpty).keyboardShortcut("g", modifiers: [.command, .shift]).help(tr("logs.search.previous"))181 Button { step(matches.count, forward: true) } label: { Label(tr("logs.search.next"), systemImage: "chevron.down") }182 .labelStyle(.iconOnly).disabled(matches.isEmpty).keyboardShortcut("g", modifiers: .command).help(tr("logs.search.next"))183 }184 Button {185 NSPasteboard.general.clearContents()186 NSPasteboard.general.setString(model.text, forType: .string)187 } label: { Label(tr("logs.copy_all"), systemImage: "doc.on.doc") }188 .disabled(model.text.isEmpty)189 .accessibilityIdentifier("logs-copy")190 }191 .padding(.horizontal, Tokens.Space.s5)192 .padding(.vertical, Tokens.Space.s3)193194 VStack(alignment: .leading, spacing: Tokens.Space.s2) {195 Text(tr("logs.audit_notice")).font(.caption).foregroundStyle(theme.textTertiary)196 if app.session.isOffline { InfoBanner(tone: .offline, title: tr("logs.offline")) }197 if model.outcomeUnknown {198 InfoBanner(tone: .warning, title: tr("logs.outcome_unknown.title"),199 message: tr("logs.outcome_unknown.message") + (model.lastAction.map { "\n\(tr("error.correlation_id")) : \($0.correlationId)" } ?? ""))200 .accessibilityIdentifier("logs-outcome-unknown")201 } else if let e = model.requestError {202 VStack(alignment: .leading, spacing: Tokens.Space.s1) {203 Text(Self.explain(e)).font(.callout).foregroundStyle(theme.textPrimary)204 InlineErrorView(e)205 }206 .accessibilityIdentifier("logs-error")207 }208 if model.truncated { InfoBanner(tone: .info, title: tr("logs.truncated")) }209 }210 .padding(.horizontal, Tokens.Space.s5)211 .padding(.bottom, Tokens.Space.s3)212213 if model.text.isEmpty {214 EmptyStateView(model.isRequesting ? tr("logs.requesting") : (model.receivedAt != nil ? tr("logs.empty.title") : tr("logs.none_yet")),215 systemImage: "doc.plaintext")216 } else {217 LogTextView(text: model.text, matches: matches, current: index, followTail: model.follow || query.isEmpty,218 colors: .init(text: NSColor(theme.textPrimary), background: NSColor(theme.inset),219 match: NSColor(theme.accentMuted), currentMatch: NSColor(StatusTone.warning.muted(theme))))220 }221 }222 .onChange(of: query) { _, _ in current = 0 }223 }224225 private func step(_ count: Int, forward: Bool) {226 if let next = LogSearch.step(from: min(current, max(0, count - 1)), count: count, forward: forward) { current = next }227 }228229 /// Plain-language reason for the refusals the server can answer to a log request.230 static func explain(_ e: APIError) -> String {231 switch e.code {232 case "agent_offline": return tr("logs.error.agent_offline")233 case "capability_missing": return tr("logs.error.capability_missing")234 case "forbidden": return tr("logs.error.forbidden")235 case "node_in_maintenance": return tr("logs.error.maintenance")236 case "orchestrator_frozen": return tr("logs.error.frozen")237 case "target_locked": return tr("logs.error.locked")238 case APIError.codeOffline, APIError.codeNetwork, APIError.codeTimeout: return tr("logs.offline")239 default: return tr("logs.error.generic")240 }241 }242}243