new features
This commit is contained in:
@@ -0,0 +1,197 @@
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
|
||||
struct PegasusIndexStatus: Decodable, Sendable {
|
||||
struct Run: Decodable, Sendable {
|
||||
let started: TimeInterval
|
||||
let finished: TimeInterval?
|
||||
let exitCode: Int?
|
||||
}
|
||||
|
||||
let mounted: Bool
|
||||
let documents: String
|
||||
let database: String
|
||||
let running: Bool
|
||||
let externalRunning: Bool
|
||||
let sources: Int?
|
||||
let chunks: Int?
|
||||
let currentRootChunks: Int?
|
||||
let bytes: Int64?
|
||||
let freeBytes: Int64?
|
||||
let modified: TimeInterval?
|
||||
let lastRun: Run?
|
||||
let log: String?
|
||||
let processed: Int?
|
||||
let totalFiles: Int?
|
||||
let statisticsError: String?
|
||||
|
||||
var indexing: Bool { running || externalRunning }
|
||||
|
||||
var activity: String {
|
||||
if !mounted { return "Volume not mounted" }
|
||||
if running { return "Indexing" }
|
||||
if externalRunning { return "Indexing outside AI Studio" }
|
||||
if let exitCode = lastRun?.exitCode { return exitCode == 0 ? "Last refresh completed" : "Last refresh failed (\(exitCode))" }
|
||||
return lastRun == nil ? "Idle" : "Last refresh interrupted"
|
||||
}
|
||||
}
|
||||
|
||||
private enum PegasusIndex {
|
||||
struct Start: Decodable {
|
||||
let started: Bool
|
||||
let message: String
|
||||
}
|
||||
|
||||
static func status() async throws -> PegasusIndexStatus { try await request("status") }
|
||||
static func start() async throws -> Start { try await request("start") }
|
||||
|
||||
private static func request<T: Decodable & Sendable>(_ action: String) async throws -> T {
|
||||
guard let url = Bundle.main.url(forResource: "pegasus-index", withExtension: "py") else {
|
||||
throw StudioError("AI Studio is missing the Pegasus indexing tool.")
|
||||
}
|
||||
let script = try Data(contentsOf: url)
|
||||
return try await Task.detached {
|
||||
let process = Process()
|
||||
let input = Pipe()
|
||||
let output = Pipe()
|
||||
process.executableURL = URL(fileURLWithPath: "/usr/bin/ssh")
|
||||
process.arguments = [
|
||||
"-T", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes",
|
||||
"-o", "ConnectTimeout=5", "-o", "ServerAliveInterval=5", "-o", "ServerAliveCountMax=2",
|
||||
"pegasus", "/usr/bin/timeout", "20", "/mnt/knowledge-base/.venv-linux/bin/python", "-B", "-", action
|
||||
]
|
||||
process.standardInput = input
|
||||
process.standardOutput = output
|
||||
process.standardError = output
|
||||
try process.run()
|
||||
defer {
|
||||
try? input.fileHandleForWriting.close()
|
||||
try? output.fileHandleForReading.close()
|
||||
}
|
||||
try input.fileHandleForWriting.write(contentsOf: script)
|
||||
try input.fileHandleForWriting.close()
|
||||
try? output.fileHandleForWriting.close()
|
||||
let data = output.fileHandleForReading.readDataToEndOfFile()
|
||||
process.waitUntilExit()
|
||||
guard process.terminationStatus == 0 else {
|
||||
let detail = String(decoding: data.suffix(1000), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
throw StudioError(detail.isEmpty ? "Could not reach the Pegasus indexer." : detail)
|
||||
}
|
||||
do { return try JSONDecoder().decode(T.self, from: data) }
|
||||
catch { throw StudioError("Pegasus returned an invalid index status.") }
|
||||
}.value
|
||||
}
|
||||
}
|
||||
|
||||
struct PegasusKnowledgeSettings: View {
|
||||
@ObservedObject var studio: StudioModel
|
||||
@State private var snapshot: PegasusIndexStatus?
|
||||
@State private var busy = false
|
||||
@State private var confirm = false
|
||||
@State private var error = ""
|
||||
@State private var result = ""
|
||||
@State private var updated: Date?
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
Section("Pegasus Indexer") {
|
||||
LabeledContent("Connection", value: "SSH · pegasus")
|
||||
LabeledContent("Status", value: snapshot?.activity ?? "Status unavailable")
|
||||
LabeledContent("Chat knowledge access", value: studio.connectedKnowledge == nil ? "Disconnected" : "Connected through MCP")
|
||||
if let updated { LabeledContent("Last checked", value: updated.formatted(date: .omitted, time: .standard)) }
|
||||
HStack {
|
||||
Button("Refresh Status") { Task { await refresh() } }
|
||||
Button("Start Index Refresh…") { confirm = true }
|
||||
.buttonStyle(.borderedProminent)
|
||||
.disabled(snapshot?.mounted != true || snapshot?.indexing == true || !error.isEmpty)
|
||||
if busy { ProgressView().controlSize(.small) }
|
||||
}
|
||||
.disabled(busy)
|
||||
if !result.isEmpty { Text(result).foregroundStyle(.secondary) }
|
||||
if !error.isEmpty { Text(error).foregroundStyle(.red).textSelection(.enabled) }
|
||||
}
|
||||
if let snapshot {
|
||||
Section("Index Statistics") {
|
||||
LabeledContent("Distinct source paths", value: snapshot.sources?.formatted() ?? "Unavailable")
|
||||
LabeledContent("Total indexed chunks", value: snapshot.chunks?.formatted() ?? "Unavailable")
|
||||
LabeledContent("Chunks from mounted documents", value: snapshot.currentRootChunks?.formatted() ?? "Unavailable")
|
||||
LabeledContent("Index size", value: ModelLibrarySize.label(snapshot.bytes))
|
||||
LabeledContent("Free space on Pegasus", value: ModelLibrarySize.label(snapshot.freeBytes))
|
||||
LabeledContent("Document folder", value: snapshot.documents)
|
||||
LabeledContent("Index folder", value: snapshot.database)
|
||||
if let modified = snapshot.modified {
|
||||
LabeledContent("Database modified", value: Date(timeIntervalSince1970: modified).formatted())
|
||||
}
|
||||
if let error = snapshot.statisticsError {
|
||||
Text(error).foregroundStyle(.secondary).textSelection(.enabled)
|
||||
}
|
||||
}
|
||||
Section("Latest AI Studio Run") {
|
||||
if let run = snapshot.lastRun {
|
||||
LabeledContent("Started", value: Date(timeIntervalSince1970: run.started).formatted())
|
||||
if let finished = run.finished {
|
||||
LabeledContent("Finished", value: Date(timeIntervalSince1970: finished).formatted())
|
||||
}
|
||||
if snapshot.running, let processed = snapshot.processed, let total = snapshot.totalFiles, total > 0 {
|
||||
ProgressView("Processing file \(processed.formatted()) of \(total.formatted())",
|
||||
value: Double(max(0, processed - 1)), total: Double(total))
|
||||
}
|
||||
}
|
||||
if let log = snapshot.log, !log.isEmpty {
|
||||
ScrollView {
|
||||
Text(log).font(.system(.caption, design: .monospaced))
|
||||
.textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.frame(maxHeight: 175)
|
||||
} else {
|
||||
Text("Run output appears here after AI Studio starts an index refresh.")
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
.confirmationDialog("Start an index refresh on Pegasus?", isPresented: $confirm, titleVisibility: .visible) {
|
||||
Button("Start Index Refresh") { Task { await start() } }
|
||||
} message: {
|
||||
Text("Scan the mounted document folder using the existing incremental indexer.")
|
||||
}
|
||||
.task {
|
||||
await refresh()
|
||||
while !Task.isCancelled {
|
||||
do { try await Task.sleep(for: .seconds(snapshot?.indexing == true ? 4 : 30)) }
|
||||
catch { return }
|
||||
await refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func refresh() async {
|
||||
guard !busy else { return }
|
||||
busy = true
|
||||
defer { busy = false }
|
||||
await update()
|
||||
}
|
||||
|
||||
private func update() async {
|
||||
do {
|
||||
snapshot = try await PegasusIndex.status()
|
||||
updated = .now
|
||||
error = ""
|
||||
} catch {
|
||||
self.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
private func start() async {
|
||||
guard !busy, snapshot?.mounted == true, snapshot?.indexing == false else { return }
|
||||
busy = true
|
||||
defer { busy = false }
|
||||
do {
|
||||
result = try await PegasusIndex.start().message
|
||||
await update()
|
||||
} catch {
|
||||
self.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user