mirror of
https://github.com/awizemann/scarf.git
synced 2026-05-10 18:44:45 +00:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4757b5ae49 |
@@ -0,0 +1,34 @@
|
||||
import Foundation
|
||||
|
||||
/// Errors thrown by `CuratorService`. Each case carries enough detail
|
||||
/// to render a user-actionable message — the view model surfaces these
|
||||
/// inline as a banner above the leaderboard rather than blocking with a
|
||||
/// modal alert.
|
||||
public enum CuratorError: Error, LocalizedError, Sendable {
|
||||
/// `hermes` binary couldn't be located.
|
||||
case cliMissing
|
||||
/// Subprocess returned non-zero exit. `stderr` may carry a synthetic
|
||||
/// message when the transport itself failed.
|
||||
case nonZeroExit(verb: String, code: Int32, stderr: String)
|
||||
/// JSON decoding failed. Underlying message wrapped for diagnostics.
|
||||
case decoding(verb: String, message: String)
|
||||
/// Generic transport error — process couldn't start, IO failed, etc.
|
||||
case transport(message: String)
|
||||
|
||||
public var errorDescription: String? {
|
||||
switch self {
|
||||
case .cliMissing:
|
||||
return "Hermes CLI couldn't be found. Install Hermes v0.13+ and ensure it's on your PATH."
|
||||
case .nonZeroExit(let verb, let code, let stderr):
|
||||
let trimmed = stderr.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if trimmed.isEmpty {
|
||||
return "`hermes curator \(verb)` exited with code \(code)."
|
||||
}
|
||||
return trimmed
|
||||
case .decoding(let verb, let message):
|
||||
return "Couldn't decode `hermes curator \(verb)` output: \(message)"
|
||||
case .transport(let message):
|
||||
return message
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// Optimistic local mirror of the agent's currently-locked goal (set via
|
||||
/// the `/goal <text>` slash command, Hermes v0.13+). Scarf records this
|
||||
/// the moment the user sends `/goal …` so the chat header pill appears
|
||||
/// synchronously, without waiting for a server round-trip. There is no
|
||||
/// authoritative read-back path in v2.8.0 — see WS-2 plan Q1.
|
||||
///
|
||||
/// Plain value type, no mutation API. Drives the goal pill in
|
||||
/// `SessionInfoBar` and the inspector contextual menu.
|
||||
public struct HermesActiveGoal: Sendable, Equatable, Identifiable {
|
||||
/// The user's verbatim goal text (post-trim).
|
||||
public let text: String
|
||||
/// When Scarf observed the `/goal` send. Local clock — not the
|
||||
/// server's authoritative timestamp.
|
||||
public let setAt: Date
|
||||
|
||||
public var id: String {
|
||||
text + "@" + ISO8601DateFormatter().string(from: setAt)
|
||||
}
|
||||
|
||||
public init(text: String, setAt: Date) {
|
||||
self.text = text
|
||||
self.setAt = setAt
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import Foundation
|
||||
|
||||
/// One entry in the `hermes curator list-archived` output. Decoded
|
||||
/// tolerantly via `decodeIfPresent` so a stripped-down host (or a future
|
||||
/// Hermes that drops one of the optional columns) doesn't crash the view.
|
||||
///
|
||||
/// Only `name` is required — every other field is optional and the
|
||||
/// computed `*Label` accessors render `"—"` for missing values.
|
||||
public struct HermesCuratorArchivedSkill: Sendable, Equatable, Identifiable, Codable {
|
||||
public var id: String { name }
|
||||
public let name: String
|
||||
public let category: String?
|
||||
public let archivedAt: String?
|
||||
public let reason: String?
|
||||
public let sizeBytes: Int?
|
||||
public let path: String?
|
||||
|
||||
public init(
|
||||
name: String,
|
||||
category: String? = nil,
|
||||
archivedAt: String? = nil,
|
||||
reason: String? = nil,
|
||||
sizeBytes: Int? = nil,
|
||||
path: String? = nil
|
||||
) {
|
||||
self.name = name
|
||||
self.category = category
|
||||
self.archivedAt = archivedAt
|
||||
self.reason = reason
|
||||
self.sizeBytes = sizeBytes
|
||||
self.path = path
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case name
|
||||
case category
|
||||
case archivedAt = "archived_at"
|
||||
case reason
|
||||
case sizeBytes = "size_bytes"
|
||||
case path
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self.name = try c.decode(String.self, forKey: .name)
|
||||
self.category = try c.decodeIfPresent(String.self, forKey: .category)
|
||||
self.archivedAt = try c.decodeIfPresent(String.self, forKey: .archivedAt)
|
||||
self.reason = try c.decodeIfPresent(String.self, forKey: .reason)
|
||||
self.sizeBytes = try c.decodeIfPresent(Int.self, forKey: .sizeBytes)
|
||||
self.path = try c.decodeIfPresent(String.self, forKey: .path)
|
||||
}
|
||||
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var c = encoder.container(keyedBy: CodingKeys.self)
|
||||
try c.encode(name, forKey: .name)
|
||||
try c.encodeIfPresent(category, forKey: .category)
|
||||
try c.encodeIfPresent(archivedAt, forKey: .archivedAt)
|
||||
try c.encodeIfPresent(reason, forKey: .reason)
|
||||
try c.encodeIfPresent(sizeBytes, forKey: .sizeBytes)
|
||||
try c.encodeIfPresent(path, forKey: .path)
|
||||
}
|
||||
|
||||
/// "4.4 KB" / "1.2 MB" / "—" for nil. Uses the SI byte formatter so
|
||||
/// the labels match what Finder shows.
|
||||
public var sizeLabel: String {
|
||||
guard let bytes = sizeBytes else { return "—" }
|
||||
let formatter = ByteCountFormatter()
|
||||
formatter.allowedUnits = [.useAll]
|
||||
formatter.countStyle = .file
|
||||
return formatter.string(fromByteCount: Int64(bytes))
|
||||
}
|
||||
|
||||
/// `2026-04-22` (ISO date prefix) / "—". Hermes returns full ISO
|
||||
/// timestamps with seconds + Z; the date prefix is what the user
|
||||
/// actually wants in the archived list.
|
||||
public var archivedAtLabel: String {
|
||||
guard let iso = archivedAt, !iso.isEmpty else { return "—" }
|
||||
// Trim to date prefix if it looks like a full ISO timestamp.
|
||||
if let tIdx = iso.firstIndex(of: "T") {
|
||||
return String(iso[..<tIdx])
|
||||
}
|
||||
return iso
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of `hermes curator prune --dry-run` — what would be removed
|
||||
/// if the user confirms. The view derives `totalCount` from
|
||||
/// `wouldRemove.count` so the wire shape stays flat.
|
||||
public struct CuratorPruneSummary: Sendable, Equatable, Codable {
|
||||
public let wouldRemove: [HermesCuratorArchivedSkill]
|
||||
public let totalBytes: Int
|
||||
public var totalCount: Int { wouldRemove.count }
|
||||
|
||||
public init(wouldRemove: [HermesCuratorArchivedSkill], totalBytes: Int) {
|
||||
self.wouldRemove = wouldRemove
|
||||
self.totalBytes = totalBytes
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case wouldRemove = "would_remove"
|
||||
case totalBytes = "total_bytes"
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self.wouldRemove = try c.decodeIfPresent([HermesCuratorArchivedSkill].self, forKey: .wouldRemove) ?? []
|
||||
self.totalBytes = try c.decodeIfPresent(Int.self, forKey: .totalBytes) ?? 0
|
||||
}
|
||||
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var c = encoder.container(keyedBy: CodingKeys.self)
|
||||
try c.encode(wouldRemove, forKey: .wouldRemove)
|
||||
try c.encode(totalBytes, forKey: .totalBytes)
|
||||
}
|
||||
|
||||
/// "12.3 KB" / "—" for empty. Convenience for the confirm sheet header.
|
||||
public var totalBytesLabel: String {
|
||||
guard totalBytes > 0 else { return "—" }
|
||||
let formatter = ByteCountFormatter()
|
||||
formatter.allowedUnits = [.useAll]
|
||||
formatter.countStyle = .file
|
||||
return formatter.string(fromByteCount: Int64(totalBytes))
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// One queued prompt the user has staged via `/queue <text>` (Hermes
|
||||
/// v0.13+ ACP `/queue` slash command). Hermes is the authoritative owner
|
||||
/// of the actual queue server-side — Scarf maintains this mirror so the
|
||||
/// chat header chip + popover can show "what's pending" without an
|
||||
/// extra round-trip. The mirror drains best-effort when a turn
|
||||
/// completes (`RichChatViewModel.popQueuedPrompt`).
|
||||
///
|
||||
/// `id` is a Scarf-side UUID minted at queue-time — Hermes' wire
|
||||
/// protocol does not expose a per-queue-entry id, so we never round-trip
|
||||
/// an entry-level identifier. See WS-2 plan Q5.
|
||||
public struct HermesQueuedPrompt: Sendable, Equatable, Identifiable {
|
||||
public let id: UUID
|
||||
public let text: String
|
||||
public let queuedAt: Date
|
||||
|
||||
public init(id: UUID = UUID(), text: String, queuedAt: Date = Date()) {
|
||||
self.id = id
|
||||
self.text = text
|
||||
self.queuedAt = queuedAt
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
import Foundation
|
||||
#if canImport(os)
|
||||
import os
|
||||
#endif
|
||||
|
||||
/// Async, transport-aware client for `hermes curator …`. Wraps the v0.12
|
||||
/// verbs (`status / run / pause / resume / pin / unpin / restore`) plus
|
||||
/// the v0.13 archive surface (`archive / prune / list-archived` and a
|
||||
/// synchronous-blocking `run`).
|
||||
///
|
||||
/// **Concurrency.** Pure-I/O `actor` — no UI state. View models hold a
|
||||
/// service reference and `await` methods. Each public method dispatches
|
||||
/// the underlying CLI invocation through `Task.detached(priority:
|
||||
/// .utility)` so two concurrent reads from the VM don't queue end-to-end
|
||||
/// on a single thread. Mirrors `KanbanService` shape exactly.
|
||||
///
|
||||
/// **Capability gating happens at the call site, not in the service.**
|
||||
/// `runNow(synchronous:timeout:)` takes a flag from the VM (the VM reads
|
||||
/// `HermesCapabilities.hasCuratorArchive` to decide). The service stays
|
||||
/// version-agnostic — only the timeout differs in practice.
|
||||
public actor CuratorService {
|
||||
#if canImport(os)
|
||||
private static let logger = Logger(subsystem: "com.scarf", category: "CuratorService")
|
||||
#endif
|
||||
|
||||
private let context: ServerContext
|
||||
|
||||
public init(context: ServerContext) {
|
||||
self.context = context
|
||||
}
|
||||
|
||||
// MARK: - Reads
|
||||
|
||||
/// Run `hermes curator status` and parse stdout via
|
||||
/// `HermesCuratorStatusParser`. Combines the text output with the
|
||||
/// on-disk `.curator_state` JSON for richer last-run metadata.
|
||||
/// Never throws — a transport failure resolves to `.empty` so the
|
||||
/// view always has something to render.
|
||||
public func status() async -> HermesCuratorStatus {
|
||||
let context = self.context
|
||||
return await Task.detached(priority: .utility) { () -> HermesCuratorStatus in
|
||||
let textResult = Self.runHermesSync(context: context, args: ["curator", "status"], timeout: 30)
|
||||
let stateData = context.readData(context.paths.curatorStateFile)
|
||||
return HermesCuratorStatusParser.parse(text: textResult.output, stateFileJSON: stateData)
|
||||
}.value
|
||||
}
|
||||
|
||||
/// `hermes curator list-archived [--json]`. Prefers JSON; falls back
|
||||
/// to a defensive text parser. Empty / "no archived skills" sentinel
|
||||
/// folds to `[]`.
|
||||
public func listArchived() async throws -> [HermesCuratorArchivedSkill] {
|
||||
// TODO(WS-4-Q2): confirm `--json` is supported on v0.13
|
||||
// `list-archived`. If not, drop the flag and rely on the text
|
||||
// parser path. Until then we pass `--json` and parse the output
|
||||
// tolerantly.
|
||||
let args = ["curator", "list-archived", "--json"]
|
||||
let (code, stdout, stderr) = await runHermes(args: args, timeout: 30)
|
||||
|
||||
// If --json isn't recognized, the CLI typically emits
|
||||
// "unrecognized arguments: --json" or similar to stderr and
|
||||
// exits non-zero. Retry without the flag and parse text.
|
||||
if code != 0 {
|
||||
let lower = (stderr + stdout).lowercased()
|
||||
if lower.contains("unrecognized") || lower.contains("unknown") || lower.contains("no such option") {
|
||||
let (c2, out2, err2) = await runHermes(args: ["curator", "list-archived"], timeout: 30)
|
||||
try ensureSuccess(code: c2, stdout: out2, stderr: err2, verb: "list-archived")
|
||||
return Self.parseListArchivedText(out2)
|
||||
}
|
||||
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "list-archived")
|
||||
}
|
||||
|
||||
let trimmed = stdout.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if trimmed.isEmpty || trimmed.lowercased().contains("no archived skills") {
|
||||
return []
|
||||
}
|
||||
// Try JSON first — may also be a text dump if Hermes ignored `--json`.
|
||||
if let data = trimmed.data(using: .utf8),
|
||||
let arr = try? JSONDecoder().decode([HermesCuratorArchivedSkill].self, from: data) {
|
||||
return arr
|
||||
}
|
||||
// Some builds wrap in `{"archived": [...]}` envelope.
|
||||
struct Wrapper: Decodable { let archived: [HermesCuratorArchivedSkill] }
|
||||
if let data = trimmed.data(using: .utf8),
|
||||
let wrapped = try? JSONDecoder().decode(Wrapper.self, from: data) {
|
||||
return wrapped.archived
|
||||
}
|
||||
// Text fallback — defensive parse.
|
||||
return Self.parseListArchivedText(stdout)
|
||||
}
|
||||
|
||||
// MARK: - Writes (legacy v0.12 verbs; service form)
|
||||
|
||||
public func runNow(synchronous: Bool, timeout: TimeInterval) async throws {
|
||||
// TODO(WS-4-Q4): default 600s for v0.13 sync runs. No Cancel
|
||||
// button in v2.8 (transport.cancel parity not guaranteed across
|
||||
// LocalTransport / SSHTransport).
|
||||
let resolvedTimeout = synchronous ? timeout : 30
|
||||
let (code, stdout, stderr) = await runHermes(args: ["curator", "run"], timeout: resolvedTimeout)
|
||||
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "run")
|
||||
}
|
||||
|
||||
public func pause() async throws {
|
||||
let (code, stdout, stderr) = await runHermes(args: ["curator", "pause"], timeout: 15)
|
||||
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "pause")
|
||||
}
|
||||
|
||||
public func resume() async throws {
|
||||
let (code, stdout, stderr) = await runHermes(args: ["curator", "resume"], timeout: 15)
|
||||
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "resume")
|
||||
}
|
||||
|
||||
public func pin(_ name: String) async throws {
|
||||
let (code, stdout, stderr) = await runHermes(args: ["curator", "pin", name], timeout: 15)
|
||||
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "pin")
|
||||
}
|
||||
|
||||
public func unpin(_ name: String) async throws {
|
||||
let (code, stdout, stderr) = await runHermes(args: ["curator", "unpin", name], timeout: 15)
|
||||
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "unpin")
|
||||
}
|
||||
|
||||
public func restore(_ name: String) async throws {
|
||||
let (code, stdout, stderr) = await runHermes(args: ["curator", "restore", name], timeout: 30)
|
||||
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "restore")
|
||||
}
|
||||
|
||||
// MARK: - Writes (new in v0.13)
|
||||
|
||||
/// `hermes curator archive <name>` — non-destructive; moves the
|
||||
/// skill from the active set to the archived set. No `--json` is
|
||||
/// expected; the verb's success channel is the exit code.
|
||||
public func archive(_ name: String) async throws {
|
||||
let (code, stdout, stderr) = await runHermes(args: ["curator", "archive", name], timeout: 30)
|
||||
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "archive")
|
||||
}
|
||||
|
||||
/// `hermes curator prune [--dry-run]`. Destructive when `dryRun`
|
||||
/// is `false` — removes everything currently archived from disk.
|
||||
/// Returns a `CuratorPruneSummary` describing what was (or would be)
|
||||
/// removed. On `dryRun=false`, the wire shape may not include the
|
||||
/// `would_remove` list — the caller should not depend on it; the
|
||||
/// archived list is empty after a successful destructive prune.
|
||||
@discardableResult
|
||||
public func prune(dryRun: Bool) async throws -> CuratorPruneSummary {
|
||||
// TODO(WS-4-Q1): confirm v0.13 ships `--dry-run`. If not, fall
|
||||
// back to enumerating via `list-archived` and treat any prune
|
||||
// call as destructive. The retry-without-flag path below covers
|
||||
// the "unrecognized argument" case automatically.
|
||||
var args = ["curator", "prune"]
|
||||
if dryRun { args.append("--dry-run") }
|
||||
// `--json` requested for the dry-run path so we can parse the
|
||||
// would-remove list. Destructive mode runs without --json since
|
||||
// we only need the exit code.
|
||||
if dryRun { args.append("--json") }
|
||||
|
||||
let (code, stdout, stderr) = await runHermes(args: args, timeout: 60)
|
||||
|
||||
// Detect "unrecognized --dry-run" / "unknown --json" gracefully.
|
||||
if code != 0 {
|
||||
let lower = (stderr + stdout).lowercased()
|
||||
let unrecognized = lower.contains("unrecognized") || lower.contains("unknown") || lower.contains("no such option")
|
||||
if dryRun && unrecognized {
|
||||
// Q1 fallback: enumerate via list-archived. Caller still
|
||||
// uses this summary for confirm-sheet display.
|
||||
let archived = try await listArchived()
|
||||
let total = archived.compactMap { $0.sizeBytes }.reduce(0, +)
|
||||
return CuratorPruneSummary(wouldRemove: archived, totalBytes: total)
|
||||
}
|
||||
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "prune")
|
||||
}
|
||||
|
||||
if dryRun {
|
||||
return Self.parsePruneDryRun(stdout)
|
||||
}
|
||||
return CuratorPruneSummary(wouldRemove: [], totalBytes: 0)
|
||||
}
|
||||
|
||||
// MARK: - Pure parsers (nonisolated; safe to call from VMs without awaits)
|
||||
|
||||
/// Parse a `list-archived --json` payload. Tolerates the bare-array
|
||||
/// shape, the `{"archived": [...]}` envelope, and "no archived
|
||||
/// skills" / empty-string sentinels. Returns `[]` for any of the
|
||||
/// empty cases. Throws `CuratorError.decoding` only when the input
|
||||
/// is non-empty and clearly not JSON.
|
||||
public nonisolated static func parseListArchived(stdout: String) throws -> [HermesCuratorArchivedSkill] {
|
||||
let trimmed = stdout.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if trimmed.isEmpty || trimmed.lowercased().contains("no archived skills") {
|
||||
return []
|
||||
}
|
||||
guard let data = trimmed.data(using: .utf8) else {
|
||||
throw CuratorError.decoding(verb: "list-archived", message: "non-UTF8 stdout")
|
||||
}
|
||||
if let arr = try? JSONDecoder().decode([HermesCuratorArchivedSkill].self, from: data) {
|
||||
return arr
|
||||
}
|
||||
struct Wrapper: Decodable { let archived: [HermesCuratorArchivedSkill] }
|
||||
if let wrapped = try? JSONDecoder().decode(Wrapper.self, from: data) {
|
||||
return wrapped.archived
|
||||
}
|
||||
// Last resort: text fallback.
|
||||
let parsed = parseListArchivedText(stdout)
|
||||
if !parsed.isEmpty {
|
||||
return parsed
|
||||
}
|
||||
throw CuratorError.decoding(verb: "list-archived", message: "stdout was neither JSON nor a recognised text list")
|
||||
}
|
||||
|
||||
/// Defensive text parser for `list-archived` output when `--json`
|
||||
/// isn't supported. Format inferred from `curator status`: one row
|
||||
/// per non-blank line, leading whitespace, name in column 1, then
|
||||
/// optional `archived=YYYY-MM-DD`, `size=NNNN`, `reason=...` k/v
|
||||
/// pairs. Blank lines, header lines, and the empty-state sentinel
|
||||
/// are skipped.
|
||||
public nonisolated static func parseListArchivedText(_ text: String) -> [HermesCuratorArchivedSkill] {
|
||||
var rows: [HermesCuratorArchivedSkill] = []
|
||||
for raw in text.split(separator: "\n") {
|
||||
let line = raw.trimmingCharacters(in: .whitespaces)
|
||||
if line.isEmpty { continue }
|
||||
let lower = line.lowercased()
|
||||
// Skip header / sentinel lines.
|
||||
if lower.hasPrefix("name") && lower.contains("archived") { continue }
|
||||
if lower.contains("no archived skills") { continue }
|
||||
if line.unicodeScalars.allSatisfy({ $0.value == 0x2500 || $0.properties.isWhitespace }) {
|
||||
continue
|
||||
}
|
||||
// Skip lines that look like JSON / non-row chrome — `{`,
|
||||
// `}`, `[`, `]` at the start or quotes / colons mean we're
|
||||
// parsing a malformed JSON dump, not a row table.
|
||||
if let first = line.first, "{[}]\":,".contains(first) {
|
||||
continue
|
||||
}
|
||||
// Find the first whitespace-separated token as the name; if
|
||||
// the name carries an `=` it's a header chip we should skip.
|
||||
let parts = line.split(whereSeparator: { $0 == "\t" || $0 == " " }).map(String.init)
|
||||
guard let name = parts.first, !name.contains("=") else { continue }
|
||||
// Reject names that look like punctuation / JSON fragments.
|
||||
if name.contains("\"") || name.contains(":") || name.contains("{") || name.contains("}") || name.contains("[") || name.contains("]") {
|
||||
continue
|
||||
}
|
||||
// Pull k=v pairs from the remainder.
|
||||
var archivedAt: String?
|
||||
var sizeBytes: Int?
|
||||
var reason: String?
|
||||
var category: String?
|
||||
var path: String?
|
||||
for token in parts.dropFirst() {
|
||||
guard let eq = token.firstIndex(of: "=") else { continue }
|
||||
let key = String(token[..<eq])
|
||||
let value = String(token[token.index(after: eq)...])
|
||||
switch key {
|
||||
case "archived", "archived_at":
|
||||
archivedAt = value
|
||||
case "size", "size_bytes":
|
||||
sizeBytes = Int(value)
|
||||
case "reason":
|
||||
reason = value
|
||||
case "category":
|
||||
category = value
|
||||
case "path":
|
||||
path = value
|
||||
default:
|
||||
continue
|
||||
}
|
||||
}
|
||||
rows.append(
|
||||
HermesCuratorArchivedSkill(
|
||||
name: name,
|
||||
category: category,
|
||||
archivedAt: archivedAt,
|
||||
reason: reason,
|
||||
sizeBytes: sizeBytes,
|
||||
path: path
|
||||
)
|
||||
)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
/// Parse a `prune --dry-run --json` payload. Tolerates an empty
|
||||
/// payload (returns a zero summary) and the `{would_remove: [],
|
||||
/// total_bytes: N}` shape.
|
||||
public nonisolated static func parsePruneDryRun(_ stdout: String) -> CuratorPruneSummary {
|
||||
let trimmed = stdout.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else {
|
||||
return CuratorPruneSummary(wouldRemove: [], totalBytes: 0)
|
||||
}
|
||||
if let data = trimmed.data(using: .utf8),
|
||||
let summary = try? JSONDecoder().decode(CuratorPruneSummary.self, from: data) {
|
||||
return summary
|
||||
}
|
||||
// Tolerate a bare-array fallback (some Hermes builds may print
|
||||
// just the would-remove list when --json is missing the wrapper).
|
||||
if let data = trimmed.data(using: .utf8),
|
||||
let arr = try? JSONDecoder().decode([HermesCuratorArchivedSkill].self, from: data) {
|
||||
let total = arr.compactMap { $0.sizeBytes }.reduce(0, +)
|
||||
return CuratorPruneSummary(wouldRemove: arr, totalBytes: total)
|
||||
}
|
||||
// Last-resort text parse for "would remove N skills (X bytes)".
|
||||
return CuratorPruneSummary(wouldRemove: [], totalBytes: 0)
|
||||
}
|
||||
|
||||
// MARK: - CLI invocation
|
||||
|
||||
private nonisolated func runHermes(
|
||||
args: [String],
|
||||
timeout: TimeInterval
|
||||
) async -> (exitCode: Int32, stdout: String, stderr: String) {
|
||||
let context = self.context
|
||||
return await Task.detached(priority: .utility) { () -> (Int32, String, String) in
|
||||
let result = Self.runHermesSync(context: context, args: args, timeout: timeout)
|
||||
return (result.exitCode, result.output, result.stderr)
|
||||
}.value
|
||||
}
|
||||
|
||||
/// Synchronous, transport-level invocation. `output` is stdout; the
|
||||
/// caller usually only reads `output` for parser input but sometimes
|
||||
/// needs `stderr` (e.g. to detect "unrecognized argument" patterns).
|
||||
private nonisolated static func runHermesSync(
|
||||
context: ServerContext,
|
||||
args: [String],
|
||||
timeout: TimeInterval
|
||||
) -> (exitCode: Int32, output: String, stderr: String) {
|
||||
let transport = context.makeTransport()
|
||||
do {
|
||||
let result = try transport.runProcess(
|
||||
executable: context.paths.hermesBinary,
|
||||
args: args,
|
||||
stdin: nil,
|
||||
timeout: timeout
|
||||
)
|
||||
return (result.exitCode, result.stdoutString, result.stderrString)
|
||||
} catch let error as TransportError {
|
||||
let message = error.diagnosticStderr.isEmpty
|
||||
? (error.errorDescription ?? "transport error")
|
||||
: error.diagnosticStderr
|
||||
return (-1, "", message)
|
||||
} catch {
|
||||
return (-1, "", error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
private nonisolated func ensureSuccess(
|
||||
code: Int32,
|
||||
stdout: String,
|
||||
stderr: String,
|
||||
verb: String
|
||||
) throws {
|
||||
guard code != 0 else { return }
|
||||
if code == -1 && stderr.lowercased().contains("hermes binary not found") {
|
||||
throw CuratorError.cliMissing
|
||||
}
|
||||
let combined = stderr.isEmpty ? stdout : stderr
|
||||
#if canImport(os)
|
||||
Self.logger.warning("curator \(verb) exit=\(code, privacy: .public) stderr=\(combined, privacy: .public)")
|
||||
#endif
|
||||
throw CuratorError.nonZeroExit(verb: verb, code: code, stderr: combined)
|
||||
}
|
||||
}
|
||||
@@ -4,17 +4,19 @@ import Observation
|
||||
import os
|
||||
#endif
|
||||
|
||||
/// Mac + iOS view model for the v0.12 Curator surface.
|
||||
/// Mac + iOS view model for the Curator surface (v0.12 base + v0.13
|
||||
/// archive/prune additions).
|
||||
///
|
||||
/// Drives `hermes curator status / run / pause / resume / pin / unpin /
|
||||
/// restore` plus a parsed view of `~/.hermes/skills/.curator_state`
|
||||
/// JSON. The CLI doesn't ship a `--json` flag for `status`, so we
|
||||
/// text-parse stdout (HermesCuratorStatusParser) and use the state
|
||||
/// file for richer last-run metadata.
|
||||
/// restore` plus (v0.13+) `archive`, `prune`, `list-archived`. All CLI
|
||||
/// invocations route through `CuratorService` (the actor) so polling
|
||||
/// and writes share the same concurrency model and a single error path.
|
||||
///
|
||||
/// Capability-gated: callers should construct this only when
|
||||
/// `HermesCapabilities.hasCurator` is true. The view model does not
|
||||
/// gate itself — the gate happens at sidebar/tab routing time.
|
||||
/// `HermesCapabilities.hasCurator` is true. Archive-aware UI surfaces
|
||||
/// (Archive button, Archived section, Prune…) gate independently on
|
||||
/// `hasCuratorArchive`. The view model itself doesn't gate — it exposes
|
||||
/// every method and the View decides what to render.
|
||||
@Observable
|
||||
@MainActor
|
||||
public final class CuratorViewModel {
|
||||
@@ -27,20 +29,50 @@ public final class CuratorViewModel {
|
||||
public private(set) var status: HermesCuratorStatus = .empty
|
||||
public private(set) var isLoading = false
|
||||
public private(set) var lastReportMarkdown: String?
|
||||
|
||||
// Archive state (v0.13+ only — populated by `loadArchive()` on hosts
|
||||
// where `hasCuratorArchive` is true).
|
||||
public private(set) var archivedSkills: [HermesCuratorArchivedSkill] = []
|
||||
public private(set) var isLoadingArchive = false
|
||||
|
||||
// Prune state — `pruneSummary` non-nil while the confirm sheet is
|
||||
// mid-flight; `isPruning` flips during the destructive step.
|
||||
public private(set) var pruneSummary: CuratorPruneSummary?
|
||||
public private(set) var isPruning = false
|
||||
|
||||
// Track which active-skill row is currently being archived so the
|
||||
// row chrome can show an inline spinner without blocking the rest.
|
||||
public private(set) var pendingArchiveName: String?
|
||||
|
||||
/// Happy-path success toast ("Pinned X", "Resumed", "Archived
|
||||
/// legacy-helper"). Auto-clears 3s after assignment.
|
||||
public var transientMessage: String?
|
||||
|
||||
/// Failure path — populated by every CLI verb when it throws. Shown
|
||||
/// as an inline yellow banner above the status summary so users
|
||||
/// don't have to dismiss a modal alert during a high-frequency
|
||||
/// surface like the leaderboard. Manually dismissed via the View's
|
||||
/// "x" button (sets to nil).
|
||||
public var errorMessage: String?
|
||||
|
||||
@ObservationIgnored
|
||||
private let service: CuratorService
|
||||
|
||||
public init(context: ServerContext) {
|
||||
self.context = context
|
||||
self.service = CuratorService(context: context)
|
||||
}
|
||||
|
||||
// MARK: - Loads
|
||||
|
||||
public func load() async {
|
||||
isLoading = true
|
||||
defer { isLoading = false }
|
||||
let context = self.context
|
||||
// v2.8 — instrumented. Curator load fires `hermes curator
|
||||
// status` (CLI subprocess) plus 1-2 file reads; on remote
|
||||
// each is a separate SSH RTT. Visibility lets future captures
|
||||
// show how often the report file is missing or oversized.
|
||||
// status` (CLI subprocess) plus 1-2 file reads; on remote each
|
||||
// is a separate SSH RTT. Visibility lets future captures show
|
||||
// how often the report file is missing or oversized.
|
||||
let parsed = await ScarfMon.measureAsync(.diskIO, "curator.load") {
|
||||
await Task.detached(priority: .userInitiated) { () -> (HermesCuratorStatus, String?) in
|
||||
let textResult = Self.runCuratorStatus(context: context)
|
||||
@@ -69,46 +101,156 @@ public final class CuratorViewModel {
|
||||
self.lastReportMarkdown = parsed.1
|
||||
}
|
||||
|
||||
public func runNow() async {
|
||||
await runAndReload(args: ["curator", "run"], successMessage: "Curator run started")
|
||||
/// Refresh the archived-skills list. No-op on hosts without
|
||||
/// `hasCuratorArchive` — the caller gates the call.
|
||||
public func loadArchive() async {
|
||||
isLoadingArchive = true
|
||||
defer { isLoadingArchive = false }
|
||||
do {
|
||||
archivedSkills = try await service.listArchived()
|
||||
} catch {
|
||||
archivedSkills = []
|
||||
errorMessage = (error as? LocalizedError)?.errorDescription
|
||||
?? error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Writes (v0.12)
|
||||
|
||||
/// Run the curator manually. On v0.13+ hosts this blocks for the
|
||||
/// duration of the run (default 600s timeout); pre-v0.13 returns
|
||||
/// immediately. Caller passes the capability-decided flag.
|
||||
public func runNow(synchronous: Bool, timeout: TimeInterval = 600) async {
|
||||
await runWithReload(
|
||||
verb: "run",
|
||||
successMessage: synchronous ? "Curator run complete" : "Curator run started"
|
||||
) {
|
||||
try await self.service.runNow(synchronous: synchronous, timeout: timeout)
|
||||
}
|
||||
}
|
||||
|
||||
public func pause() async {
|
||||
await runAndReload(args: ["curator", "pause"], successMessage: "Curator paused")
|
||||
await runWithReload(verb: "pause", successMessage: "Curator paused") {
|
||||
try await self.service.pause()
|
||||
}
|
||||
}
|
||||
|
||||
public func resume() async {
|
||||
await runAndReload(args: ["curator", "resume"], successMessage: "Curator resumed")
|
||||
await runWithReload(verb: "resume", successMessage: "Curator resumed") {
|
||||
try await self.service.resume()
|
||||
}
|
||||
}
|
||||
|
||||
public func pin(_ skill: String) async {
|
||||
await runAndReload(args: ["curator", "pin", skill], successMessage: "Pinned \(skill)")
|
||||
await runWithReload(verb: "pin", successMessage: "Pinned \(skill)") {
|
||||
try await self.service.pin(skill)
|
||||
}
|
||||
}
|
||||
|
||||
public func unpin(_ skill: String) async {
|
||||
await runAndReload(args: ["curator", "unpin", skill], successMessage: "Unpinned \(skill)")
|
||||
await runWithReload(verb: "unpin", successMessage: "Unpinned \(skill)") {
|
||||
try await self.service.unpin(skill)
|
||||
}
|
||||
}
|
||||
|
||||
public func restore(_ skill: String) async {
|
||||
await runAndReload(args: ["curator", "restore", skill], successMessage: "Restored \(skill)")
|
||||
await runWithReload(verb: "restore", successMessage: "Restored \(skill)") {
|
||||
try await self.service.restore(skill)
|
||||
}
|
||||
// Restore drops the entry from the archived list — refresh it
|
||||
// so the row disappears immediately.
|
||||
await loadArchive()
|
||||
}
|
||||
|
||||
private func runAndReload(args: [String], successMessage: String) async {
|
||||
let context = self.context
|
||||
let exitCode = await Task.detached(priority: .userInitiated) {
|
||||
Self.runHermes(context: context, args: args).exitCode
|
||||
}.value
|
||||
transientMessage = exitCode == 0 ? successMessage : "Command failed"
|
||||
// MARK: - Writes (v0.13)
|
||||
|
||||
public func archive(_ skill: String) async {
|
||||
pendingArchiveName = skill
|
||||
await runWithReload(verb: "archive", successMessage: "Archived \(skill)") {
|
||||
try await self.service.archive(skill)
|
||||
}
|
||||
pendingArchiveName = nil
|
||||
await loadArchive()
|
||||
}
|
||||
|
||||
/// Stage 1 of the bulk-prune flow. Calls `prune --dry-run` and
|
||||
/// populates `pruneSummary`; the View binds its confirm sheet to
|
||||
/// the non-nil presence of this property.
|
||||
public func planPrune() async {
|
||||
do {
|
||||
pruneSummary = try await service.prune(dryRun: true)
|
||||
} catch {
|
||||
errorMessage = (error as? LocalizedError)?.errorDescription
|
||||
?? error.localizedDescription
|
||||
pruneSummary = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Stage 2 of the bulk-prune flow. Destructive — removes everything
|
||||
/// currently archived. Clears `pruneSummary` regardless of outcome
|
||||
/// so the confirm sheet dismisses.
|
||||
public func confirmPrune() async {
|
||||
isPruning = true
|
||||
do {
|
||||
_ = try await service.prune(dryRun: false)
|
||||
transientMessage = "Pruned archived skills"
|
||||
errorMessage = nil
|
||||
await loadArchive()
|
||||
await load()
|
||||
// Auto-clear toast after 3s.
|
||||
scheduleTransientClear()
|
||||
} catch {
|
||||
errorMessage = (error as? LocalizedError)?.errorDescription
|
||||
?? error.localizedDescription
|
||||
}
|
||||
isPruning = false
|
||||
pruneSummary = nil
|
||||
}
|
||||
|
||||
/// Cancel the in-flight prune-confirm flow without running.
|
||||
public func cancelPrune() {
|
||||
pruneSummary = nil
|
||||
}
|
||||
|
||||
/// User-driven dismissal of the inline error banner.
|
||||
public func dismissError() {
|
||||
errorMessage = nil
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Run a service call, route success → `transientMessage`, failure
|
||||
/// → `errorMessage`, and reload `status` either way. Mirrors the
|
||||
/// previous `runAndReload` helper but goes through the typed
|
||||
/// service surface.
|
||||
private func runWithReload(
|
||||
verb: String,
|
||||
successMessage: String,
|
||||
body: @escaping @Sendable () async throws -> Void
|
||||
) async {
|
||||
do {
|
||||
try await body()
|
||||
transientMessage = successMessage
|
||||
errorMessage = nil
|
||||
await load()
|
||||
scheduleTransientClear()
|
||||
} catch {
|
||||
let message = (error as? LocalizedError)?.errorDescription
|
||||
?? error.localizedDescription
|
||||
errorMessage = message
|
||||
transientMessage = nil
|
||||
await load()
|
||||
}
|
||||
}
|
||||
|
||||
private func scheduleTransientClear() {
|
||||
Task { @MainActor [weak self] in
|
||||
try? await Task.sleep(nanoseconds: 3_000_000_000)
|
||||
self?.transientMessage = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrap the transport-level `runProcess` so the call sites don't
|
||||
/// have to reach for it directly. Combined stdout+stderr.
|
||||
// MARK: - Legacy sync helpers (kept for `load`'s detached path)
|
||||
|
||||
nonisolated private static func runHermes(
|
||||
context: ServerContext,
|
||||
args: [String]
|
||||
|
||||
@@ -248,73 +248,15 @@ public final class RichChatViewModel {
|
||||
/// Hermes v2026.4.23+ but listed here unconditionally so older
|
||||
/// hosts that don't advertise it still surface the trigger; the
|
||||
/// agent will respond appropriately or no-op gracefully.
|
||||
///
|
||||
/// v2.8 / Hermes v0.13 adds `/goal` (lock the agent on a target
|
||||
/// across turns) and `/queue` (queue a prompt for after the current
|
||||
/// turn). Both ride the same `.acpNonInterruptive` source — Hermes
|
||||
/// parses them server-side, the wire shape is plain
|
||||
/// `session/prompt`, and the chat UI keeps the "Agent working…"
|
||||
/// indicator off when they're sent. They're listed unconditionally
|
||||
/// here; capability filtering happens in `availableCommands` so
|
||||
/// pre-v0.13 hosts don't see `/goal` or `/queue` in the slash menu.
|
||||
// TODO(WS-2-Q7): verify against a real v0.13 ACP host that `/goal`
|
||||
// is in fact non-interruptive on the wire. If Hermes treats it as a
|
||||
// regular prompt that flips "Agent working…", drop it from this
|
||||
// list and route it through the standard send path (the pill
|
||||
// bookkeeping in `recordActiveGoal` is independent of the
|
||||
// interruptive classification).
|
||||
public static let nonInterruptiveCommands: [HermesSlashCommand] = [
|
||||
HermesSlashCommand(
|
||||
name: "steer",
|
||||
description: "Nudge the agent mid-run (applies after the next tool call)",
|
||||
argumentHint: "<guidance>",
|
||||
source: .acpNonInterruptive
|
||||
),
|
||||
HermesSlashCommand(
|
||||
name: "goal",
|
||||
description: "Lock the agent on a goal that persists across turns",
|
||||
argumentHint: "<text>",
|
||||
source: .acpNonInterruptive
|
||||
),
|
||||
HermesSlashCommand(
|
||||
name: "queue",
|
||||
description: "Queue a prompt to run after the current turn",
|
||||
argumentHint: "<text>",
|
||||
source: .acpNonInterruptive
|
||||
)
|
||||
]
|
||||
|
||||
/// Capability snapshot the chat surface uses to filter
|
||||
/// `availableCommands`. Set by the chat controller (Mac
|
||||
/// `ChatViewModel`, iOS `ChatController`) at session-start time and
|
||||
/// kept fresh via the `HermesCapabilitiesStore` env binding. Default
|
||||
/// `.empty` means "no v0.13 surfaces" — pre-v0.13 hosts and harness
|
||||
/// scenarios (Previews, smoke tests) never expose `/goal` or
|
||||
/// `/queue` until the controller publishes a real capabilities
|
||||
/// value. `@ObservationIgnored` so capability refreshes don't trash
|
||||
/// the streaming-message render budget; controllers call
|
||||
/// `publishCapabilities(_:)` once per refresh tick.
|
||||
@ObservationIgnored
|
||||
public var capabilitiesGate: HermesCapabilities = .empty
|
||||
|
||||
/// Optimistic local mirror of the agent's currently-locked goal.
|
||||
/// Set by `recordActiveGoal(text:)` the moment the user sends
|
||||
/// `/goal …`; cleared on `/goal --clear` or `reset()`. Pre-v0.13
|
||||
/// hosts can't reach this code path (the slash menu hides `/goal`),
|
||||
/// but a typed-out `/goal foo` against an older host would still
|
||||
/// land here briefly until Hermes' "unknown command" reply lands —
|
||||
/// see WS-2 plan "Inconsistency caveat".
|
||||
public private(set) var activeGoal: HermesActiveGoal?
|
||||
|
||||
/// Optimistic mirror of prompts the user has queued via `/queue …`
|
||||
/// while a turn is in flight. Hermes is the authoritative owner
|
||||
/// server-side; this list drives the chat-header chip + popover and
|
||||
/// drains FIFO via `popQueuedPrompt()` when a turn completes.
|
||||
/// Best-effort: if Hermes' server-side queue gets out of sync
|
||||
/// (deferred prompt aborted, dropped on disconnect) the user sees a
|
||||
/// stale chip until their next interaction.
|
||||
public private(set) var queuedPrompts: [HermesQueuedPrompt] = []
|
||||
|
||||
/// Transient hint shown above the composer, e.g. "Guidance queued —
|
||||
/// applies after the next tool call." for `/steer`. The chat view
|
||||
/// auto-clears it after a short delay (handled in the view); the
|
||||
@@ -376,94 +318,12 @@ public final class RichChatViewModel {
|
||||
!acpNames.contains($0.name) && !projectNames.contains($0.name)
|
||||
}
|
||||
let occupied = acpNames.union(projectNames).union(Set(quicks.map(\.name)))
|
||||
// Capability gate: `/goal` and `/queue` are v0.13+ surfaces;
|
||||
// hide them when the connected host is older. `/steer` is
|
||||
// surfaced unconditionally — it works on v0.11+ during an
|
||||
// active turn; idle-session greying for pre-v0.13 hosts is
|
||||
// the input bar's concern (it reads `hasACPSteerOnIdle`).
|
||||
let supported: [HermesSlashCommand] = Self.nonInterruptiveCommands.filter { cmd in
|
||||
switch cmd.name {
|
||||
case "goal": return capabilitiesGate.hasGoals
|
||||
case "queue": return capabilitiesGate.hasACPQueue
|
||||
case "steer": return true
|
||||
default: return true
|
||||
let nonInterruptive = Self.nonInterruptiveCommands.filter {
|
||||
!occupied.contains($0.name)
|
||||
}
|
||||
}
|
||||
let nonInterruptive = supported.filter { !occupied.contains($0.name) }
|
||||
return acpCommands + projectAsHermes + quicks + nonInterruptive
|
||||
}
|
||||
|
||||
/// Publish a fresh capabilities snapshot from the controller.
|
||||
/// Called whenever `HermesCapabilitiesStore.capabilities` changes
|
||||
/// (initial detection, post-refresh, server switch). The chat input
|
||||
/// bar's slash menu re-reads `availableCommands` lazily, so this is
|
||||
/// just a stored-value swap — no observable churn.
|
||||
public func publishCapabilities(_ caps: HermesCapabilities) {
|
||||
capabilitiesGate = caps
|
||||
}
|
||||
|
||||
/// Optimistic write triggered when the user sends `/goal <text>`.
|
||||
/// Pass `nil` (or empty) to clear (the `/goal --clear` path). The
|
||||
/// pill renders synchronously off this state; there is no
|
||||
/// authoritative server read-back in v2.8.0 — see WS-2 plan Q1.
|
||||
// TODO(WS-2-Q1): hook a Hermes-supplied goal-state read-back path
|
||||
// here once we know whether v0.13 exposes goal state via an ACP
|
||||
// session-startup notification, a session-sidecar JSON field, or a
|
||||
// `/goal --status` reply. Until then `activeGoal` is purely
|
||||
// user-set and does not survive a session resume.
|
||||
public func recordActiveGoal(text: String?) {
|
||||
if let text, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
|
||||
activeGoal = HermesActiveGoal(
|
||||
text: text.trimmingCharacters(in: .whitespacesAndNewlines),
|
||||
setAt: Date()
|
||||
)
|
||||
} else {
|
||||
activeGoal = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Append an optimistically-queued prompt to the local mirror
|
||||
/// (driven by `/queue <text>`). No-op for empty / whitespace input.
|
||||
public func recordQueuedPrompt(text: String) {
|
||||
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else { return }
|
||||
queuedPrompts.append(HermesQueuedPrompt(text: trimmed))
|
||||
}
|
||||
|
||||
/// Drain the next queued prompt off the local mirror, FIFO. Called
|
||||
/// from `handlePromptComplete` once a turn settles — Hermes runs
|
||||
/// the actual queued prompt server-side; popping here keeps the
|
||||
/// header chip count honest. Returns the popped prompt for any
|
||||
/// caller that wants to log it; the chat UI ignores the return.
|
||||
@discardableResult
|
||||
public func popQueuedPrompt() -> HermesQueuedPrompt? {
|
||||
queuedPrompts.isEmpty ? nil : queuedPrompts.removeFirst()
|
||||
}
|
||||
|
||||
/// Parse the argument slug from a `/goal …` invocation. Pure
|
||||
/// function — exposed for unit tests. The chat dispatch reads this
|
||||
/// to decide whether to set, clear, or no-op the optimistic pill.
|
||||
public enum GoalCommandArgument: Equatable {
|
||||
case set(String)
|
||||
case clear
|
||||
/// User typed `/goal` with no argument — Hermes will reply
|
||||
/// with usage; Scarf shows a neutral hint and doesn't touch
|
||||
/// the pill state.
|
||||
case empty
|
||||
}
|
||||
|
||||
public static func parseGoalArgument(_ raw: String) -> GoalCommandArgument {
|
||||
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if trimmed.isEmpty { return .empty }
|
||||
// Accept `--clear`, `clear`, and case-insensitive variants so
|
||||
// typos don't accidentally lock the goal text to literal
|
||||
// "Clear". `--clear` is the canonical form (matches Hermes
|
||||
// CLI flag style).
|
||||
let lowered = trimmed.lowercased()
|
||||
if lowered == "--clear" || lowered == "clear" { return .clear }
|
||||
return .set(trimmed)
|
||||
}
|
||||
|
||||
/// True when `text` is a non-interruptive command that should NOT
|
||||
/// flip `isAgentWorking` to true on send. Used by the Mac/iOS chat
|
||||
/// view models to skip the "agent working" overlay change for
|
||||
@@ -614,14 +474,6 @@ public final class RichChatViewModel {
|
||||
turnDurations = [:]
|
||||
transientHint = nil
|
||||
pendingPermission = nil
|
||||
// v2.8 / Hermes v0.13 — drop optimistic v0.13 surfaces on
|
||||
// session reset so a fresh chat (or a resume into a different
|
||||
// session) doesn't paint stale goal / queue state from the
|
||||
// previous one. The capabilities gate stays on whatever the
|
||||
// controller most recently published; it's a host-level value
|
||||
// that doesn't change with session boundaries.
|
||||
activeGoal = nil
|
||||
queuedPrompts = []
|
||||
loadQuickCommands()
|
||||
}
|
||||
|
||||
@@ -960,22 +812,6 @@ public final class RichChatViewModel {
|
||||
acpThoughtTokens += response.thoughtTokens
|
||||
acpCachedReadTokens += response.cachedReadTokens
|
||||
isAgentWorking = false
|
||||
// v2.8 / Hermes v0.13 — Hermes runs the next `/queue`-deferred
|
||||
// prompt server-side now that this turn has settled. Drain the
|
||||
// local mirror FIFO so the header chip count matches what the
|
||||
// user staged. Best-effort: if Hermes' authoritative queue
|
||||
// diverged (deferred prompt aborted, dropped on disconnect),
|
||||
// the chip is one tick stale until the user's next interaction.
|
||||
if !queuedPrompts.isEmpty {
|
||||
popQueuedPrompt()
|
||||
}
|
||||
// TODO(v2.8.1): when this completes after an auto-resumed
|
||||
// checkpoint (Hermes v0.13's "Auto-resume interrupted sessions
|
||||
// after gateway restart"), surface a one-shot "Auto-resumed
|
||||
// from checkpoint" indicator. Wire-shape unknown until a v0.13
|
||||
// dogfooding pass confirms whether the resume lands as a
|
||||
// visible ACP event or is purely server-side. Deferred from
|
||||
// v2.8.0 per WS-2 plan Q3.
|
||||
buildMessageGroups()
|
||||
// Final position after the prompt settles. Catches fast responses
|
||||
// (slash commands, short replies) where `.defaultScrollAnchor(.bottom)`
|
||||
|
||||
@@ -151,4 +151,169 @@ import Foundation
|
||||
#expect(parsed?.patchCount == 2)
|
||||
#expect(parsed?.lastActivityLabel == "2026-04-25")
|
||||
}
|
||||
|
||||
// MARK: - v0.13 list-archived / prune fixtures (WS-4)
|
||||
|
||||
/// Empty JSON array → `[]`. Locks in the happy-path no-archives shape.
|
||||
@Test func listArchivedEmpty() throws {
|
||||
let result = try CuratorService.parseListArchived(stdout: "[]")
|
||||
#expect(result.isEmpty)
|
||||
}
|
||||
|
||||
/// Three archives with full optional fields. Asserts each
|
||||
/// optional value decodes through `decodeIfPresent` and that
|
||||
/// the computed labels resolve.
|
||||
@Test func listArchivedThreeSkills() throws {
|
||||
let json = """
|
||||
[
|
||||
{
|
||||
"name": "legacy-helper",
|
||||
"category": "templates",
|
||||
"archived_at": "2026-04-22T03:14:09Z",
|
||||
"reason": "stale: 91d unused",
|
||||
"size_bytes": 4521,
|
||||
"path": "/Users/u/.hermes/skills/.archived/legacy-helper"
|
||||
},
|
||||
{
|
||||
"name": "old-translator",
|
||||
"category": "user",
|
||||
"archived_at": "2026-04-23T10:00:00Z",
|
||||
"reason": "consolidated with translator",
|
||||
"size_bytes": 8192
|
||||
},
|
||||
{
|
||||
"name": "minimal"
|
||||
}
|
||||
]
|
||||
"""
|
||||
let result = try CuratorService.parseListArchived(stdout: json)
|
||||
#expect(result.count == 3)
|
||||
#expect(result[0].name == "legacy-helper")
|
||||
#expect(result[0].category == "templates")
|
||||
#expect(result[0].reason == "stale: 91d unused")
|
||||
#expect(result[0].sizeBytes == 4521)
|
||||
#expect(result[0].archivedAtLabel == "2026-04-22")
|
||||
#expect(result[0].path == "/Users/u/.hermes/skills/.archived/legacy-helper")
|
||||
|
||||
// Tolerant: only `name` set on the third row.
|
||||
#expect(result[2].name == "minimal")
|
||||
#expect(result[2].category == nil)
|
||||
#expect(result[2].reason == nil)
|
||||
#expect(result[2].archivedAtLabel == "—")
|
||||
#expect(result[2].sizeLabel == "—")
|
||||
}
|
||||
|
||||
/// `{"archived": [...]}` envelope is also accepted.
|
||||
@Test func listArchivedEnvelope() throws {
|
||||
let json = """
|
||||
{"archived": [
|
||||
{"name": "envelope-skill", "size_bytes": 1024}
|
||||
]}
|
||||
"""
|
||||
let result = try CuratorService.parseListArchived(stdout: json)
|
||||
#expect(result.count == 1)
|
||||
#expect(result[0].name == "envelope-skill")
|
||||
}
|
||||
|
||||
/// Text fallback when `--json` isn't supported. Each row carries
|
||||
/// the name in column 1 plus k=v chips for the optional fields.
|
||||
@Test func listArchivedTextFallback() {
|
||||
let text = """
|
||||
legacy-helper archived=2026-04-22 size=4521 reason=stale
|
||||
old-translator archived=2026-04-23 size=8192
|
||||
minimal-row
|
||||
"""
|
||||
let result = CuratorService.parseListArchivedText(text)
|
||||
#expect(result.count == 3)
|
||||
#expect(result[0].name == "legacy-helper")
|
||||
#expect(result[0].archivedAt == "2026-04-22")
|
||||
#expect(result[0].sizeBytes == 4521)
|
||||
#expect(result[0].reason == "stale")
|
||||
#expect(result[2].name == "minimal-row")
|
||||
#expect(result[2].sizeBytes == nil)
|
||||
}
|
||||
|
||||
/// Empty-state sentinel folds to `[]` (parallel to KanbanService's
|
||||
/// `"no matching tasks"` handling).
|
||||
@Test func listArchivedNoArchivedSentinel() throws {
|
||||
let result = try CuratorService.parseListArchived(stdout: "no archived skills\n")
|
||||
#expect(result.isEmpty)
|
||||
}
|
||||
|
||||
/// Whitespace-only stdout also folds to empty.
|
||||
@Test func listArchivedWhitespaceFoldsToEmpty() throws {
|
||||
let result = try CuratorService.parseListArchived(stdout: " \n\n")
|
||||
#expect(result.isEmpty)
|
||||
}
|
||||
|
||||
/// Decode failure (clearly non-JSON, non-text) throws. We accept
|
||||
/// JSON, the envelope, the empty sentinel, or text rows; anything
|
||||
/// else surfaces as a `CuratorError.decoding`.
|
||||
@Test func listArchivedNonsenseThrows() throws {
|
||||
do {
|
||||
_ = try CuratorService.parseListArchived(stdout: "{garbage")
|
||||
Issue.record("expected decoding throw")
|
||||
} catch let error as CuratorError {
|
||||
if case .decoding = error {
|
||||
// expected
|
||||
} else {
|
||||
Issue.record("unexpected error \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Prune-dry-run JSON with `would_remove` + `total_bytes`.
|
||||
@Test func pruneDryRunHappyPath() {
|
||||
let json = """
|
||||
{
|
||||
"would_remove": [
|
||||
{"name": "stale-a", "size_bytes": 1000},
|
||||
{"name": "stale-b", "size_bytes": 2000}
|
||||
],
|
||||
"total_bytes": 3000
|
||||
}
|
||||
"""
|
||||
let summary = CuratorService.parsePruneDryRun(json)
|
||||
#expect(summary.totalCount == 2)
|
||||
#expect(summary.totalBytes == 3000)
|
||||
#expect(summary.wouldRemove.first?.name == "stale-a")
|
||||
}
|
||||
|
||||
/// Zero-skill prune is a valid dry-run (no archives).
|
||||
@Test func pruneDryRunZeroSkills() {
|
||||
let json = """
|
||||
{"would_remove": [], "total_bytes": 0}
|
||||
"""
|
||||
let summary = CuratorService.parsePruneDryRun(json)
|
||||
#expect(summary.totalCount == 0)
|
||||
#expect(summary.totalBytes == 0)
|
||||
#expect(summary.totalBytesLabel == "—")
|
||||
}
|
||||
|
||||
/// Bare-array fallback: some Hermes builds may print just the
|
||||
/// would-remove list when the wrapper is missing.
|
||||
@Test func pruneDryRunBareArrayFallback() {
|
||||
let json = """
|
||||
[{"name": "lonely", "size_bytes": 500}]
|
||||
"""
|
||||
let summary = CuratorService.parsePruneDryRun(json)
|
||||
#expect(summary.totalCount == 1)
|
||||
#expect(summary.totalBytes == 500)
|
||||
}
|
||||
|
||||
/// Empty / whitespace stdout → zero summary (no decoding throw).
|
||||
@Test func pruneDryRunEmptyStaysSafe() {
|
||||
let summary = CuratorService.parsePruneDryRun(" \n")
|
||||
#expect(summary.totalCount == 0)
|
||||
#expect(summary.totalBytes == 0)
|
||||
}
|
||||
|
||||
/// Verify the size label uses the byte formatter (not raw bytes).
|
||||
@Test func archivedSkillSizeLabelFormats() {
|
||||
let big = HermesCuratorArchivedSkill(name: "x", sizeBytes: 1_500_000)
|
||||
// ByteCountFormatter produces a localized label; just verify
|
||||
// it's non-empty and not raw "1500000".
|
||||
#expect(!big.sizeLabel.isEmpty)
|
||||
#expect(big.sizeLabel != "1500000")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,150 +241,6 @@ import Foundation
|
||||
#expect(a == b)
|
||||
}
|
||||
|
||||
// MARK: - v0.13 non-interruptive commands (WS-2 / Persistent Goals + /queue)
|
||||
|
||||
@Test func nonInterruptiveListIncludesGoalAndQueue() {
|
||||
let names = RichChatViewModel.nonInterruptiveCommands.map(\.name)
|
||||
#expect(names.contains("steer"))
|
||||
#expect(names.contains("goal"))
|
||||
#expect(names.contains("queue"))
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func availableCommandsHidesGoalWhenCapabilityOff() {
|
||||
let vm = RichChatViewModel(context: .local)
|
||||
vm.publishCapabilities(.empty)
|
||||
let names = vm.availableCommands.map(\.name)
|
||||
#expect(!names.contains("goal"))
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func availableCommandsHidesQueueWhenCapabilityOff() {
|
||||
let vm = RichChatViewModel(context: .local)
|
||||
vm.publishCapabilities(.empty)
|
||||
let names = vm.availableCommands.map(\.name)
|
||||
#expect(!names.contains("queue"))
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func availableCommandsExposesAllThreeOnV013() {
|
||||
let vm = RichChatViewModel(context: .local)
|
||||
let caps = HermesCapabilities.parseLine("Hermes Agent v0.13.0 (2026.5.7)")
|
||||
vm.publishCapabilities(caps)
|
||||
let names = vm.availableCommands.map(\.name)
|
||||
#expect(names.contains("steer"))
|
||||
#expect(names.contains("goal"))
|
||||
#expect(names.contains("queue"))
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func availableCommandsExposesSteerButHidesV013OnV012() {
|
||||
let vm = RichChatViewModel(context: .local)
|
||||
let caps = HermesCapabilities.parseLine("Hermes Agent v0.12.0 (2026.4.30)")
|
||||
vm.publishCapabilities(caps)
|
||||
let names = vm.availableCommands.map(\.name)
|
||||
#expect(names.contains("steer"))
|
||||
#expect(!names.contains("goal"))
|
||||
#expect(!names.contains("queue"))
|
||||
}
|
||||
|
||||
@Test func parseGoalArgumentRecognizesClearVariants() {
|
||||
#expect(RichChatViewModel.parseGoalArgument("--clear") == .clear)
|
||||
#expect(RichChatViewModel.parseGoalArgument("clear") == .clear)
|
||||
#expect(RichChatViewModel.parseGoalArgument("Clear") == .clear)
|
||||
#expect(RichChatViewModel.parseGoalArgument(" --clear ") == .clear)
|
||||
}
|
||||
|
||||
@Test func parseGoalArgumentReturnsSetForArbitraryText() {
|
||||
#expect(
|
||||
RichChatViewModel.parseGoalArgument("finish v2.8 on time")
|
||||
== .set("finish v2.8 on time")
|
||||
)
|
||||
// Whitespace around set text is trimmed.
|
||||
#expect(
|
||||
RichChatViewModel.parseGoalArgument(" ship it ")
|
||||
== .set("ship it")
|
||||
)
|
||||
}
|
||||
|
||||
@Test func parseGoalArgumentReturnsEmptyForBlank() {
|
||||
#expect(RichChatViewModel.parseGoalArgument("") == .empty)
|
||||
#expect(RichChatViewModel.parseGoalArgument(" ") == .empty)
|
||||
#expect(RichChatViewModel.parseGoalArgument("\n\t") == .empty)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func recordActiveGoalSetsAndClears() {
|
||||
let vm = RichChatViewModel(context: .local)
|
||||
#expect(vm.activeGoal == nil)
|
||||
vm.recordActiveGoal(text: "ship v2.8")
|
||||
let goal = vm.activeGoal
|
||||
#expect(goal?.text == "ship v2.8")
|
||||
vm.recordActiveGoal(text: nil)
|
||||
#expect(vm.activeGoal == nil)
|
||||
// Empty / whitespace also clears.
|
||||
vm.recordActiveGoal(text: "x")
|
||||
vm.recordActiveGoal(text: " ")
|
||||
#expect(vm.activeGoal == nil)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func recordQueuedPromptAppendsAndPopsFIFO() {
|
||||
let vm = RichChatViewModel(context: .local)
|
||||
vm.recordQueuedPrompt(text: "first")
|
||||
vm.recordQueuedPrompt(text: "second")
|
||||
vm.recordQueuedPrompt(text: "third")
|
||||
#expect(vm.queuedPrompts.count == 3)
|
||||
let popped = vm.popQueuedPrompt()
|
||||
#expect(popped?.text == "first")
|
||||
#expect(vm.queuedPrompts.count == 2)
|
||||
let next = vm.popQueuedPrompt()
|
||||
#expect(next?.text == "second")
|
||||
#expect(vm.queuedPrompts.first?.text == "third")
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func recordQueuedPromptIgnoresBlank() {
|
||||
let vm = RichChatViewModel(context: .local)
|
||||
vm.recordQueuedPrompt(text: "")
|
||||
vm.recordQueuedPrompt(text: " ")
|
||||
#expect(vm.queuedPrompts.isEmpty)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func popQueuedPromptOnEmptyReturnsNil() {
|
||||
let vm = RichChatViewModel(context: .local)
|
||||
#expect(vm.popQueuedPrompt() == nil)
|
||||
}
|
||||
|
||||
@Test func isNonInterruptiveSlashRecognizesGoalAndQueue() {
|
||||
// Non-MainActor: the helper itself isn't MainActor-isolated;
|
||||
// construct a VM on MainActor and read through it on the test
|
||||
// actor to keep the assertion focused on classification.
|
||||
Task { @MainActor in
|
||||
let vm = RichChatViewModel(context: .local)
|
||||
#expect(vm.isNonInterruptiveSlash("/goal finish v2.8"))
|
||||
#expect(vm.isNonInterruptiveSlash("/queue summarize"))
|
||||
#expect(vm.isNonInterruptiveSlash("/queue"))
|
||||
#expect(vm.isNonInterruptiveSlash("/steer be careful"))
|
||||
#expect(!vm.isNonInterruptiveSlash("hello"))
|
||||
#expect(!vm.isNonInterruptiveSlash("/compress"))
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func resetClearsGoalAndQueue() {
|
||||
let vm = RichChatViewModel(context: .local)
|
||||
vm.recordActiveGoal(text: "x")
|
||||
vm.recordQueuedPrompt(text: "a")
|
||||
vm.recordQueuedPrompt(text: "b")
|
||||
#expect(vm.activeGoal != nil)
|
||||
#expect(vm.queuedPrompts.count == 2)
|
||||
vm.reset()
|
||||
#expect(vm.activeGoal == nil)
|
||||
#expect(vm.queuedPrompts.isEmpty)
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
static func makeTempProject() throws -> String {
|
||||
|
||||
@@ -109,17 +109,6 @@ struct ChatView: View {
|
||||
}
|
||||
)
|
||||
}
|
||||
// Forward the env-injected capabilities snapshot into the
|
||||
// shared `RichChatViewModel` whenever it changes. Drives the
|
||||
// capability gate `RichChatViewModel.availableCommands` reads.
|
||||
// Mirrors the Mac `ChatView` plumbing — the iOS chat surface
|
||||
// doesn't render `/goal` / `/queue` UI yet (deferred to WS-9),
|
||||
// but the VM-side state has to stay aligned across platforms
|
||||
// so the Mac surface is correct after a cross-device session
|
||||
// resume.
|
||||
.task(id: capabilitiesStore?.capabilities.versionLine ?? "") {
|
||||
controller.vm.publishCapabilities(capabilitiesStore?.capabilities ?? .empty)
|
||||
}
|
||||
.task {
|
||||
// Dashboard row taps set `pendingResumeSessionID`, Project
|
||||
// Detail's "New Chat" sets `pendingProjectChat`. Both fire
|
||||
@@ -1318,48 +1307,18 @@ final class ChatController {
|
||||
// even when they didn't type any caption.
|
||||
vm.addUserMessage(text: "[image attached]")
|
||||
}
|
||||
// Non-interruptive slash commands: keep the chat working
|
||||
// indicator off and surface a transient toast confirming the
|
||||
// command was accepted. v2.5 added `/steer`; v2.8 / Hermes
|
||||
// v0.13 adds `/goal` (lock the agent on a target across
|
||||
// turns) and `/queue` (queue a prompt for after the current
|
||||
// turn). Each gets its own optimistic side-effect on the VM
|
||||
// so the (Mac-rendered) chat header pill / queue chip update
|
||||
// synchronously. iOS doesn't surface those affordances yet
|
||||
// (WS-9), but mirroring the dispatch keeps the shared VM
|
||||
// state aligned across platforms — otherwise an iOS user who
|
||||
// ran `/goal` then opened the same session on Mac would see
|
||||
// an empty pill until they typed `/goal` again.
|
||||
let parsedSlash = Self.parseSlashName(text)
|
||||
switch parsedSlash.name {
|
||||
case "goal":
|
||||
// TODO(WS-2-Q7): verify on a real v0.13 host.
|
||||
let arg = RichChatViewModel.parseGoalArgument(parsedSlash.args)
|
||||
switch arg {
|
||||
case .set(let goalText):
|
||||
vm.recordActiveGoal(text: goalText)
|
||||
vm.transientHint = "Goal locked: \(Self.truncatedToastGoal(goalText))"
|
||||
case .clear:
|
||||
vm.recordActiveGoal(text: nil)
|
||||
vm.transientHint = "Goal cleared."
|
||||
case .empty:
|
||||
vm.transientHint = "Sent /goal — see the agent reply for current goal."
|
||||
}
|
||||
scheduleTransientHintClear(snapshot: vm.transientHint)
|
||||
case "queue":
|
||||
// TODO(WS-2-Q5): verify the verbatim wire shape on a
|
||||
// real v0.13 ACP host.
|
||||
let queuedText = parsedSlash.args.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if !queuedText.isEmpty {
|
||||
vm.recordQueuedPrompt(text: queuedText)
|
||||
}
|
||||
vm.transientHint = "Queued — runs after current turn."
|
||||
scheduleTransientHintClear(snapshot: vm.transientHint)
|
||||
case "steer" where vm.isNonInterruptiveSlash(text):
|
||||
// /steer is non-interruptive — the agent is still on its
|
||||
// current turn; the guidance applies after the next tool call.
|
||||
// Surface a transient toast confirming the guidance was
|
||||
// received. v2.5 / Hermes v2026.4.23+.
|
||||
if vm.isNonInterruptiveSlash(text) {
|
||||
vm.transientHint = "Guidance queued — applies after the next tool call."
|
||||
scheduleTransientHintClear(snapshot: vm.transientHint)
|
||||
default:
|
||||
break
|
||||
Task { @MainActor [weak vm] in
|
||||
try? await Task.sleep(nanoseconds: 4_000_000_000)
|
||||
if vm?.transientHint == "Guidance queued — applies after the next tool call." {
|
||||
vm?.transientHint = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
// Project-scoped slash commands expand client-side: the user
|
||||
// bubble shows the literal `/<name> args` they typed (above);
|
||||
@@ -1382,43 +1341,6 @@ final class ChatController {
|
||||
}
|
||||
}
|
||||
|
||||
/// Pull `(name, argTail)` out of a `/<name> [args]` invocation.
|
||||
/// Mirror of `ChatViewModel.parseSlashName` on Mac. Returns
|
||||
/// `(nil, "")` for non-slash input.
|
||||
static func parseSlashName(_ text: String) -> (name: String?, args: String) {
|
||||
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard trimmed.hasPrefix("/") else { return (nil, "") }
|
||||
let withoutSlash = trimmed.dropFirst()
|
||||
if let space = withoutSlash.firstIndex(of: " ") {
|
||||
return (
|
||||
name: String(withoutSlash[..<space]),
|
||||
args: String(withoutSlash[withoutSlash.index(after: space)...])
|
||||
)
|
||||
}
|
||||
return (name: String(withoutSlash), args: "")
|
||||
}
|
||||
|
||||
/// Cap goal text in transient toasts so a 1 KB user-typed goal
|
||||
/// doesn't blow out the hint pill. Mirror of
|
||||
/// `ChatViewModel.truncatedToastGoal`.
|
||||
static func truncatedToastGoal(_ text: String) -> String {
|
||||
text.count <= 60 ? text : String(text.prefix(57)) + "…"
|
||||
}
|
||||
|
||||
/// Auto-clear the chat composer's transient hint after 4s. Mirror
|
||||
/// of `ChatViewModel.scheduleHintClear` — uses a value snapshot
|
||||
/// rather than identity so a later toast that reuses the same
|
||||
/// string still triggers the clear once the latest value matches.
|
||||
@MainActor
|
||||
private func scheduleTransientHintClear(snapshot: String?) {
|
||||
Task { @MainActor [weak vm] in
|
||||
try? await Task.sleep(nanoseconds: 4_000_000_000)
|
||||
if vm?.transientHint == snapshot {
|
||||
vm?.transientHint = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mirror of `ChatViewModel.expandIfProjectScoped(_:)` on Mac.
|
||||
/// `/<name> args` matching a loaded project-scoped command is
|
||||
/// expanded; everything else is sent literally.
|
||||
|
||||
@@ -13,11 +13,24 @@ import ScarfDesign
|
||||
/// `HermesCapabilities.hasCurator` is true.
|
||||
struct CuratorView: View {
|
||||
@State private var viewModel: CuratorViewModel
|
||||
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||
|
||||
// TODO(WS-9): add a read-only "Archived" section mirroring the Mac
|
||||
// surface (no per-row Restore/Prune mutations on iOS in this
|
||||
// release). Gate on `capabilitiesStore?.capabilities.hasCuratorArchive`.
|
||||
|
||||
init(context: ServerContext) {
|
||||
_viewModel = State(initialValue: CuratorViewModel(context: context))
|
||||
}
|
||||
|
||||
/// Whether the connected host runs curator synchronously. Threaded
|
||||
/// into `runNow` so v0.13+ hosts block-with-spinner; pre-v0.13 fire
|
||||
/// and forget. WS-9 will surface a richer iOS progress affordance
|
||||
/// alongside the read-only Archived section.
|
||||
private var archiveAvailable: Bool {
|
||||
capabilitiesStore?.capabilities.hasCuratorArchive ?? false
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
List {
|
||||
Section {
|
||||
@@ -115,7 +128,7 @@ struct CuratorView: View {
|
||||
private var actionFooter: some View {
|
||||
HStack(spacing: 8) {
|
||||
Button {
|
||||
Task { await viewModel.runNow() }
|
||||
Task { await viewModel.runNow(synchronous: archiveAvailable, timeout: 600) }
|
||||
} label: {
|
||||
Label("Run now", systemImage: "play.fill")
|
||||
}
|
||||
|
||||
@@ -77,27 +77,6 @@ final class ChatViewModel {
|
||||
let richChatViewModel: RichChatViewModel
|
||||
private var coordinator: Coordinator?
|
||||
|
||||
/// Capability store the chat surface reads from. Set by `ChatView`
|
||||
/// at body-evaluation time via `attachCapabilitiesStore(_:)` —
|
||||
/// `@ObservationIgnored` so capability refreshes don't force a
|
||||
/// full chat re-render. Forwards into
|
||||
/// `RichChatViewModel.capabilitiesGate` whenever the published
|
||||
/// snapshot changes; the slash menu reads through that. v2.8 /
|
||||
/// Hermes v0.13 — gates `/goal` + `/queue` slash menu rows.
|
||||
@ObservationIgnored
|
||||
var capabilitiesStore: HermesCapabilitiesStore?
|
||||
|
||||
/// Wire the Mac chat view's environment-injected capabilities store
|
||||
/// into both this VM and its child rich-chat VM. Idempotent on the
|
||||
/// pointer (re-attaching the same store is a no-op); always
|
||||
/// re-publishes the latest snapshot so a refresh that fired before
|
||||
/// the chat view became visible still lands.
|
||||
@MainActor
|
||||
func attachCapabilitiesStore(_ store: HermesCapabilitiesStore?) {
|
||||
capabilitiesStore = store
|
||||
richChatViewModel.publishCapabilities(store?.capabilities ?? .empty)
|
||||
}
|
||||
|
||||
/// `callId` of the tool call currently surfaced in the chat
|
||||
/// inspector pane, or nil when nothing is focused. Set by
|
||||
/// `ToolCallCard` taps in the transcript; cleared by the inspector's
|
||||
@@ -342,47 +321,6 @@ final class ChatViewModel {
|
||||
richChatViewModel.clearACPErrorState()
|
||||
}
|
||||
|
||||
/// Auto-clear the chat composer's transient hint after 4 s. Shared
|
||||
/// helper for `/steer`, `/goal`, and `/queue` so the toast lifetime
|
||||
/// stays consistent across non-interruptive commands.
|
||||
@MainActor
|
||||
private func scheduleHintClear() {
|
||||
let snapshot = richChatViewModel.transientHint
|
||||
Task { @MainActor [weak self] in
|
||||
try? await Task.sleep(nanoseconds: 4_000_000_000)
|
||||
if self?.richChatViewModel.transientHint == snapshot {
|
||||
self?.richChatViewModel.transientHint = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pull the slash command name + raw argument tail out of the
|
||||
/// composer text. Returns `(name: nil, args: "")` for non-slash
|
||||
/// input. Mirrors the parser shape `RichChatViewModel.parseGoalArgument`
|
||||
/// expects; kept on `ChatViewModel` (not promoted to ScarfCore)
|
||||
/// because the Mac and iOS chat surfaces compose this with their
|
||||
/// own per-platform send paths.
|
||||
static func parseSlashName(_ text: String) -> (name: String?, args: String) {
|
||||
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard trimmed.hasPrefix("/") else { return (nil, "") }
|
||||
let withoutSlash = trimmed.dropFirst()
|
||||
if let space = withoutSlash.firstIndex(of: " ") {
|
||||
return (
|
||||
name: String(withoutSlash[..<space]),
|
||||
args: String(withoutSlash[withoutSlash.index(after: space)...])
|
||||
)
|
||||
}
|
||||
return (name: String(withoutSlash), args: "")
|
||||
}
|
||||
|
||||
/// Cap goal text in transient toasts so a 1 KB user-typed goal
|
||||
/// doesn't blow out the hint pill. The header pill applies its
|
||||
/// own 33-char cap; the toast is shorter so the hint stays
|
||||
/// glanceable.
|
||||
static func truncatedToastGoal(_ text: String) -> String {
|
||||
text.count <= 60 ? text : String(text.prefix(57)) + "…"
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func recordACPFailure(_ error: Error, client: ACPClient?, context: String) async {
|
||||
logger.error("\(context): \(error.localizedDescription)")
|
||||
@@ -637,59 +575,22 @@ final class ChatViewModel {
|
||||
// and Hermes-version-independent. v2.5.
|
||||
let wireText = expandIfProjectScoped(text)
|
||||
|
||||
// Non-interruptive slash commands keep the "Agent working…"
|
||||
// indicator off and surface a transient toast confirming the
|
||||
// command was accepted. v2.5 added `/steer`; v2.8 / Hermes
|
||||
// v0.13 adds `/goal` (lock the agent on a target across turns)
|
||||
// and `/queue` (queue a prompt for after the current turn).
|
||||
// Each gets its own optimistic side-effect on RichChatViewModel
|
||||
// so the chat header pill / queue chip update synchronously
|
||||
// without waiting for a server round-trip.
|
||||
let isNonInterruptive = richChatViewModel.isNonInterruptiveSlash(text)
|
||||
let parsed = Self.parseSlashName(text)
|
||||
switch parsed.name {
|
||||
case "goal":
|
||||
// TODO(WS-2-Q7): once a v0.13 host confirms the
|
||||
// wire-shape, this branch fires only when the host
|
||||
// advertises `hasGoals`; pre-v0.13 hosts hide the menu
|
||||
// row, but a power-user typing `/goal` directly still
|
||||
// lands here. We keep the optimistic write so the pill
|
||||
// appears synchronously — the agent's "unknown command"
|
||||
// reply on a pre-v0.13 host paints the inconsistency in
|
||||
// user-visible chat content (acceptable v1 behavior;
|
||||
// see WS-2 plan "Inconsistency caveat").
|
||||
let arg = RichChatViewModel.parseGoalArgument(parsed.args)
|
||||
switch arg {
|
||||
case .set(let goalText):
|
||||
richChatViewModel.recordActiveGoal(text: goalText)
|
||||
richChatViewModel.transientHint = "Goal locked: \(Self.truncatedToastGoal(goalText))"
|
||||
case .clear:
|
||||
richChatViewModel.recordActiveGoal(text: nil)
|
||||
richChatViewModel.transientHint = "Goal cleared."
|
||||
case .empty:
|
||||
richChatViewModel.transientHint = "Sent /goal — see the agent reply for current goal."
|
||||
}
|
||||
scheduleHintClear()
|
||||
case "queue":
|
||||
// TODO(WS-2-Q5): verify against a real v0.13 ACP host
|
||||
// that the verbatim "/queue <text>" wire shape is what
|
||||
// Hermes accepts (versus a structured arg shape). The
|
||||
// optimistic mirror logic below assumes verbatim text.
|
||||
let queuedText = parsed.args.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if !queuedText.isEmpty {
|
||||
richChatViewModel.recordQueuedPrompt(text: queuedText)
|
||||
}
|
||||
richChatViewModel.transientHint = "Queued — runs after current turn."
|
||||
scheduleHintClear()
|
||||
case "steer" where isNonInterruptive:
|
||||
// /steer is non-interruptive — the agent is still on its
|
||||
// current turn; the guidance applies after the next tool
|
||||
// call. Don't change the "Agent working..." status (it's
|
||||
// already on); show a transient toast so the user knows the
|
||||
// guidance was accepted. v2.5 / Hermes v2026.4.23+.
|
||||
let isSteer = richChatViewModel.isNonInterruptiveSlash(text)
|
||||
if isSteer {
|
||||
richChatViewModel.transientHint = "Guidance queued — applies after the next tool call."
|
||||
scheduleHintClear()
|
||||
default:
|
||||
// Regular interruptive prompt (or an unrecognized slash).
|
||||
// Don't flip "Agent working…" for any other
|
||||
// non-interruptive command (defensive; matches the
|
||||
// legacy contract).
|
||||
if !isNonInterruptive { acpStatus = ACPPhase.agentWorking }
|
||||
Task { @MainActor [weak self] in
|
||||
try? await Task.sleep(nanoseconds: 4_000_000_000)
|
||||
if self?.richChatViewModel.transientHint == "Guidance queued — applies after the next tool call." {
|
||||
self?.richChatViewModel.transientHint = nil
|
||||
}
|
||||
}
|
||||
} else {
|
||||
acpStatus = ACPPhase.agentWorking
|
||||
}
|
||||
acpPromptTask = Task { @MainActor in
|
||||
do {
|
||||
@@ -707,7 +608,7 @@ final class ChatViewModel {
|
||||
// notifier handles the foreground/disabled gating;
|
||||
// we just hand it the latest assistant text and
|
||||
// session title for the body line.
|
||||
if !isNonInterruptive {
|
||||
if !isSteer {
|
||||
let preview = richChatViewModel.messages
|
||||
.last(where: { $0.isAssistant })?
|
||||
.content ?? ""
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
import SwiftUI
|
||||
import ScarfCore
|
||||
import ScarfDesign
|
||||
|
||||
/// Header chip that surfaces prompts the user has queued via
|
||||
/// `/queue …` (Hermes v0.13). Tap → popover listing the queued
|
||||
/// prompt previews + their relative timestamps.
|
||||
///
|
||||
/// The chip is OPTIMISTIC — it's a Scarf-side mirror of what the user
|
||||
/// typed. Hermes owns the authoritative queue server-side. The popover
|
||||
/// header makes that explicit so the user understands per-entry
|
||||
/// removal isn't supported (Hermes has no remove-by-id verb), and the
|
||||
/// v2.8.0 plan removed the "Clear all" button rather than ship one
|
||||
/// that would lie about its effect on server-side state. See WS-2 plan
|
||||
/// Q2 for the wire-shape question that drove that decision.
|
||||
struct ChatQueueIndicator: View {
|
||||
let queuedPrompts: [HermesQueuedPrompt]
|
||||
@State private var isPopoverShown = false
|
||||
|
||||
var body: some View {
|
||||
if queuedPrompts.isEmpty {
|
||||
EmptyView()
|
||||
} else {
|
||||
chipButton
|
||||
.popover(isPresented: $isPopoverShown, arrowEdge: .bottom) {
|
||||
queuePopover
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var chipButton: some View {
|
||||
Button {
|
||||
isPopoverShown = true
|
||||
} label: {
|
||||
HStack(spacing: 4) {
|
||||
Image(systemName: "tray.full")
|
||||
Text("\(queuedPrompts.count) queued")
|
||||
}
|
||||
.scarfStyle(.caption)
|
||||
.padding(.horizontal, ScarfSpace.s2)
|
||||
.padding(.vertical, 2)
|
||||
.background(Capsule().fill(ScarfColor.warning.opacity(0.16)))
|
||||
.foregroundStyle(ScarfColor.warning)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("Prompts waiting to run after the current turn finishes")
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private var queuePopover: some View {
|
||||
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
|
||||
Text("Queued prompts")
|
||||
.scarfStyle(.headline)
|
||||
.foregroundStyle(ScarfColor.foregroundPrimary)
|
||||
Text("Local view — Hermes manages the actual queue server-side. The next prompt runs automatically when the current turn finishes.")
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
ScarfDivider()
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
|
||||
ForEach(Array(queuedPrompts.enumerated()), id: \.element.id) { index, prompt in
|
||||
queueRow(prompt, position: index + 1)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 2)
|
||||
}
|
||||
.frame(maxHeight: 220)
|
||||
}
|
||||
.padding(ScarfSpace.s4)
|
||||
.frame(width: 360)
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func queueRow(_ prompt: HermesQueuedPrompt, position: Int) -> some View {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
HStack(alignment: .firstTextBaseline, spacing: ScarfSpace.s2) {
|
||||
Text("#\(position)")
|
||||
.scarfStyle(.captionUppercase)
|
||||
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||
Text(prompt.queuedAt, style: .relative)
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||
.monospacedDigit()
|
||||
}
|
||||
Text(prompt.text)
|
||||
.scarfStyle(.body)
|
||||
.foregroundStyle(ScarfColor.foregroundPrimary)
|
||||
.lineLimit(3)
|
||||
.truncationMode(.tail)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
.padding(.vertical, 2)
|
||||
}
|
||||
}
|
||||
@@ -21,10 +21,7 @@ struct ChatTranscriptPane: View {
|
||||
acpOutputTokens: richChat.acpOutputTokens,
|
||||
acpThoughtTokens: richChat.acpThoughtTokens,
|
||||
projectName: chatViewModel.currentProjectName,
|
||||
gitBranch: chatViewModel.currentGitBranch,
|
||||
activeGoal: richChat.activeGoal,
|
||||
onClearGoal: { chatViewModel.sendText("/goal --clear") },
|
||||
queuedPrompts: richChat.queuedPrompts
|
||||
gitBranch: chatViewModel.currentGitBranch
|
||||
)
|
||||
Divider()
|
||||
|
||||
@@ -61,8 +58,7 @@ struct ChatTranscriptPane: View {
|
||||
onSend: onSend,
|
||||
isEnabled: isEnabled,
|
||||
commands: richChat.availableCommands,
|
||||
showCompressButton: richChat.supportsCompress && !richChat.hasBroaderCommandMenu,
|
||||
isAgentWorking: richChat.isAgentWorking
|
||||
showCompressButton: richChat.supportsCompress && !richChat.hasBroaderCommandMenu
|
||||
)
|
||||
.id(richChat.sessionId ?? "scarf.chat.no-session")
|
||||
}
|
||||
|
||||
@@ -5,12 +5,6 @@ struct ChatView: View {
|
||||
@Environment(ChatViewModel.self) private var viewModel
|
||||
@Environment(HermesFileWatcher.self) private var fileWatcher
|
||||
@Environment(AppCoordinator.self) private var coordinator
|
||||
/// Capabilities store for the active server (injected on
|
||||
/// `ContextBoundRoot`). Forwarded into `ChatViewModel` so the
|
||||
/// rich-chat slash menu can gate v0.13 surfaces (`/goal`, `/queue`,
|
||||
/// `/steer` on idle). Nil during harness scenarios; treated the
|
||||
/// same as `.empty` capabilities.
|
||||
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||
@State private var showErrorDetails = false
|
||||
|
||||
/// Side-pane visibility toggles (issue #58). Drive the new
|
||||
@@ -51,15 +45,6 @@ struct ChatView: View {
|
||||
.navigationTitle(
|
||||
viewModel.currentProjectName.map { "Chat · \($0)" } ?? "Chat"
|
||||
)
|
||||
// Forward the env-injected capabilities store into the chat VM
|
||||
// on every refresh tick so the rich-chat slash menu picks up
|
||||
// v0.13 surfaces the moment the host advertises them. The id
|
||||
// value is the capabilities-line string — a stable identity
|
||||
// that flips exactly when the detector fires. Nil store ↔
|
||||
// `.empty` capabilities, which is what the VM defaults to.
|
||||
.task(id: capabilitiesStore?.capabilities.versionLine ?? "") {
|
||||
viewModel.attachCapabilitiesStore(capabilitiesStore)
|
||||
}
|
||||
.task {
|
||||
await viewModel.loadRecentSessions()
|
||||
viewModel.refreshCredentialPreflight()
|
||||
|
||||
@@ -16,11 +16,6 @@ struct RichChatInputBar: View {
|
||||
let isEnabled: Bool
|
||||
var commands: [HermesSlashCommand] = []
|
||||
var showCompressButton: Bool = false
|
||||
/// Whether the agent is currently mid-turn. Used to grey-out
|
||||
/// `/steer` in the slash menu on idle pre-v0.13 hosts (where the
|
||||
/// command silently no-ops). v0.13+ hosts allow `/steer` on idle
|
||||
/// and the row stays interactive regardless of `isAgentWorking`.
|
||||
var isAgentWorking: Bool = false
|
||||
|
||||
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||
|
||||
@@ -57,8 +52,6 @@ struct RichChatInputBar: View {
|
||||
SlashCommandMenu(
|
||||
commands: filteredCommands,
|
||||
agentHasCommands: !commands.isEmpty,
|
||||
disabledCommandNames: disabledMenuCommandNames,
|
||||
disabledReason: disabledMenuReason,
|
||||
selectedIndex: $selectedIndex,
|
||||
onSelect: insertCommand
|
||||
)
|
||||
@@ -399,27 +392,6 @@ struct RichChatInputBar: View {
|
||||
SlashCommandMenu.filter(commands: commands, query: menuQuery)
|
||||
}
|
||||
|
||||
/// Names of menu rows that should render greyed-out + ignore taps.
|
||||
/// v2.8 / Hermes v0.13: `/steer` is greyed only when the connected
|
||||
/// host is pre-v0.13 AND the session is idle. Pre-v0.13 hosts
|
||||
/// silently no-op `/steer` outside an active turn — surfacing the
|
||||
/// row as "use during a turn" is friendlier than letting the user
|
||||
/// click and see nothing happen. v0.13+ hosts allow steer-on-idle
|
||||
/// (the command just sends as a regular prompt) so the row stays
|
||||
/// interactive there.
|
||||
private var disabledMenuCommandNames: Set<String> {
|
||||
let hasSteerOnIdle = capabilitiesStore?.capabilities.hasACPSteerOnIdle ?? false
|
||||
if !isAgentWorking && !hasSteerOnIdle {
|
||||
return ["steer"]
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
private var disabledMenuReason: String? {
|
||||
guard !disabledMenuCommandNames.isEmpty else { return nil }
|
||||
return "Use `/steer` while the agent is working — your Hermes version doesn't support steering on idle sessions."
|
||||
}
|
||||
|
||||
private func updateMenuState() {
|
||||
let shouldShow = shouldShowMenu
|
||||
|
||||
|
||||
@@ -20,17 +20,6 @@ struct SessionInfoBar: View {
|
||||
/// name. Nil for non-project chats and for projects that aren't
|
||||
/// git repos.
|
||||
var gitBranch: String? = nil
|
||||
/// Active locked goal (Hermes v0.13 `/goal`). Nil hides the pill.
|
||||
/// Optimistic — set by `RichChatViewModel.recordActiveGoal(text:)`
|
||||
/// when the user sends `/goal …`.
|
||||
var activeGoal: HermesActiveGoal? = nil
|
||||
/// Invoked when the user picks "Clear goal" from the goal pill's
|
||||
/// context menu. Caller dispatches `/goal --clear` so the optimistic
|
||||
/// pill clear and the server-side authoritative state stay in sync.
|
||||
var onClearGoal: (() -> Void)? = nil
|
||||
/// Local mirror of prompts queued via `/queue …` (Hermes v0.13).
|
||||
/// Empty list hides the chip.
|
||||
var queuedPrompts: [HermesQueuedPrompt] = []
|
||||
|
||||
/// Active Hermes profile name (issue #50). Resolved on each body
|
||||
/// re-evaluation; the resolver caches for 5s so this is cheap.
|
||||
@@ -73,42 +62,6 @@ struct SessionInfoBar: View {
|
||||
}
|
||||
}
|
||||
|
||||
// Goal pill (v2.8 / Hermes v0.13). `.info` keeps it
|
||||
// visually decodable from the rust accent (project /
|
||||
// branch) and the warning amber (queue chip). The
|
||||
// pill renders only when `activeGoal` is non-nil —
|
||||
// pre-v0.13 hosts can't reach the `/goal` send path
|
||||
// through the slash menu (it's filtered out in
|
||||
// `availableCommands`), so the pill stays absent there
|
||||
// by transitive impossibility.
|
||||
if let activeGoal {
|
||||
HStack(spacing: 4) {
|
||||
Image(systemName: "scope")
|
||||
Text(Self.truncatedGoal(activeGoal.text))
|
||||
}
|
||||
.scarfStyle(.caption)
|
||||
.padding(.horizontal, ScarfSpace.s2)
|
||||
.padding(.vertical, 2)
|
||||
.background(Capsule().fill(ScarfColor.info.opacity(0.16)))
|
||||
.foregroundStyle(ScarfColor.info)
|
||||
.help("Goal locked: \(activeGoal.text)")
|
||||
.contextMenu {
|
||||
if let onClearGoal {
|
||||
Button("Clear goal", role: .destructive, action: onClearGoal)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Queue chip (v2.8 / Hermes v0.13). Local mirror only —
|
||||
// Hermes is the authoritative owner of the actual
|
||||
// queue. Per-entry deletion isn't exposed (Hermes has
|
||||
// no remove-by-id verb), and the v2.8.0 plan drops the
|
||||
// global "Clear all" button to avoid lying about
|
||||
// server-side state. The popover is read-only.
|
||||
if !queuedPrompts.isEmpty {
|
||||
ChatQueueIndicator(queuedPrompts: queuedPrompts)
|
||||
}
|
||||
|
||||
HStack(spacing: 4) {
|
||||
Circle()
|
||||
.fill(isWorking ? ScarfColor.success : ScarfColor.foregroundFaint)
|
||||
@@ -181,11 +134,4 @@ struct SessionInfoBar: View {
|
||||
private func formatTokens(_ count: Int) -> String {
|
||||
count.formatted(.number.notation(.compactName).precision(.fractionLength(0...1)))
|
||||
}
|
||||
|
||||
/// Cap goal text in the chip to keep the SessionInfoBar from
|
||||
/// wrapping when the user locks a long goal. Full goal text is
|
||||
/// available in the tooltip via `.help(...)`.
|
||||
static func truncatedGoal(_ text: String) -> String {
|
||||
text.count <= 36 ? text : String(text.prefix(33)) + "…"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,13 +11,6 @@ struct SlashCommandMenu: View {
|
||||
/// Whether the agent advertised any commands at all. Lets us distinguish
|
||||
/// "agent hasn't sent commands yet" from "filter matched nothing".
|
||||
let agentHasCommands: Bool
|
||||
/// Names that render greyed-out + ignore taps. v2.8 uses this only
|
||||
/// for `/steer` on pre-v0.13 idle sessions; v0.13 hosts allow steer
|
||||
/// on idle and the set is empty.
|
||||
var disabledCommandNames: Set<String> = []
|
||||
/// Tooltip shown on disabled rows. Reused per-row in v2.8 — only
|
||||
/// one disabled case ships, so a single shared string is enough.
|
||||
var disabledReason: String? = nil
|
||||
@Binding var selectedIndex: Int
|
||||
var onSelect: (HermesSlashCommand) -> Void
|
||||
|
||||
@@ -57,17 +50,13 @@ struct SlashCommandMenu: View {
|
||||
ScrollView {
|
||||
LazyVStack(spacing: 0) {
|
||||
ForEach(Array(commands.enumerated()), id: \.element.id) { index, command in
|
||||
let isDisabled = disabledCommandNames.contains(command.name)
|
||||
SlashCommandRow(
|
||||
command: command,
|
||||
isSelected: index == selectedIndex,
|
||||
isDisabled: isDisabled,
|
||||
disabledReason: isDisabled ? disabledReason : nil
|
||||
isSelected: index == selectedIndex
|
||||
)
|
||||
.id(index)
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture {
|
||||
guard !isDisabled else { return }
|
||||
selectedIndex = index
|
||||
onSelect(command)
|
||||
}
|
||||
@@ -88,8 +77,6 @@ struct SlashCommandMenu: View {
|
||||
private struct SlashCommandRow: View {
|
||||
let command: HermesSlashCommand
|
||||
let isSelected: Bool
|
||||
var isDisabled: Bool = false
|
||||
var disabledReason: String? = nil
|
||||
|
||||
var body: some View {
|
||||
HStack(alignment: .firstTextBaseline, spacing: 8) {
|
||||
@@ -120,19 +107,11 @@ private struct SlashCommandRow: View {
|
||||
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||
.lineLimit(2)
|
||||
}
|
||||
if isDisabled, let reason = disabledReason {
|
||||
Text(reason)
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||
.lineLimit(2)
|
||||
}
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.padding(.horizontal, ScarfSpace.s3)
|
||||
.padding(.vertical, ScarfSpace.s2)
|
||||
.background(isSelected ? ScarfColor.accentTint : Color.clear)
|
||||
.opacity(isDisabled ? 0.55 : 1.0)
|
||||
.help(isDisabled ? (disabledReason ?? "") : "")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import SwiftUI
|
||||
import ScarfCore
|
||||
import ScarfDesign
|
||||
|
||||
/// Mac sub-view rendered between the active-skill leaderboards and the
|
||||
/// last-report block on Hermes v0.13+ hosts. Lists everything currently
|
||||
/// archived (`hermes curator list-archived`) with per-row Restore + a
|
||||
/// bulk Prune affordance routed through the parent's confirm sheet.
|
||||
///
|
||||
/// Empty-state copy explains what archive means — useful when the
|
||||
/// curator hasn't run yet on a fresh install (no archives ≠ a problem).
|
||||
struct CuratorArchivedSection: View {
|
||||
let archived: [HermesCuratorArchivedSkill]
|
||||
let isLoading: Bool
|
||||
let onRestore: (String) -> Void
|
||||
let onPruneAll: () -> Void
|
||||
|
||||
var body: some View {
|
||||
ScarfCard {
|
||||
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
|
||||
header
|
||||
if isLoading && archived.isEmpty {
|
||||
loadingRow
|
||||
} else if archived.isEmpty {
|
||||
emptyState
|
||||
} else {
|
||||
rows
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var header: some View {
|
||||
HStack(alignment: .firstTextBaseline) {
|
||||
ScarfSectionHeader("Archived")
|
||||
Spacer()
|
||||
Text("\(archived.count) skill\(archived.count == 1 ? "" : "s")")
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||
if !archived.isEmpty {
|
||||
Button("Prune All…") {
|
||||
onPruneAll()
|
||||
}
|
||||
.buttonStyle(ScarfDestructiveButton())
|
||||
.help("Remove every archived skill from disk. Cannot be undone.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var loadingRow: some View {
|
||||
HStack(spacing: ScarfSpace.s2) {
|
||||
ProgressView().controlSize(.small)
|
||||
Text("Loading archived skills…")
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
|
||||
private var emptyState: some View {
|
||||
VStack(alignment: .leading, spacing: ScarfSpace.s1) {
|
||||
Text("No archived skills.")
|
||||
.scarfStyle(.body)
|
||||
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||
Text("The curator moves stale or redundant skills here on its weekly review. Until then, this list stays empty.")
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||
}
|
||||
}
|
||||
|
||||
private var rows: some View {
|
||||
VStack(alignment: .leading, spacing: ScarfSpace.s1) {
|
||||
ForEach(archived) { skill in
|
||||
ArchivedSkillRow(
|
||||
skill: skill,
|
||||
onRestore: { onRestore(skill.name) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct ArchivedSkillRow: View {
|
||||
let skill: HermesCuratorArchivedSkill
|
||||
let onRestore: () -> Void
|
||||
|
||||
var body: some View {
|
||||
HStack(alignment: .center, spacing: ScarfSpace.s2) {
|
||||
Image(systemName: "archivebox.fill")
|
||||
.font(.system(size: 12))
|
||||
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(skill.name)
|
||||
.scarfStyle(.body)
|
||||
.foregroundStyle(ScarfColor.foregroundPrimary)
|
||||
.lineLimit(1)
|
||||
if let reason = skill.reason, !reason.isEmpty {
|
||||
Text(reason)
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
Text(skill.archivedAtLabel)
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||
.frame(width: 96, alignment: .trailing)
|
||||
Text(skill.sizeLabel)
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||
.frame(width: 72, alignment: .trailing)
|
||||
Button("Restore") {
|
||||
onRestore()
|
||||
}
|
||||
.buttonStyle(ScarfPrimaryButton())
|
||||
.controlSize(.small)
|
||||
.help("Restore \(skill.name) to the active skill set")
|
||||
}
|
||||
.padding(.vertical, 2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import SwiftUI
|
||||
import ScarfCore
|
||||
import ScarfDesign
|
||||
|
||||
/// Destructive-confirm sheet for `hermes curator prune` (bulk).
|
||||
///
|
||||
/// Pattern matches `TemplateUninstallSheet`: enumerate every entry that
|
||||
/// will be removed, surface the total count + bytes, and require an
|
||||
/// explicit click on a red `ScarfDestructiveButton` ("Prune
|
||||
/// permanently") before kicking off the destructive call. Cancel owns
|
||||
/// the keyboard default action so an accidental Enter-press doesn't
|
||||
/// nuke the archive.
|
||||
struct CuratorPruneConfirmSheet: View {
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
let summary: CuratorPruneSummary
|
||||
let isPruning: Bool
|
||||
let onConfirm: () -> Void
|
||||
let onCancel: () -> Void
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
header
|
||||
.padding(.bottom, ScarfSpace.s2)
|
||||
ScarfDivider()
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
|
||||
ForEach(summary.wouldRemove) { skill in
|
||||
row(skill: skill)
|
||||
}
|
||||
if summary.wouldRemove.isEmpty {
|
||||
Text("Nothing currently archived. Nothing to prune.")
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||
.padding(.vertical, ScarfSpace.s2)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, ScarfSpace.s2)
|
||||
}
|
||||
ScarfDivider()
|
||||
footer
|
||||
.padding(.top, ScarfSpace.s2)
|
||||
}
|
||||
.frame(minWidth: 520, minHeight: 380)
|
||||
.padding(ScarfSpace.s4)
|
||||
}
|
||||
|
||||
private var header: some View {
|
||||
VStack(alignment: .leading, spacing: ScarfSpace.s1) {
|
||||
HStack(alignment: .firstTextBaseline) {
|
||||
Text("Prune Archived Skills")
|
||||
.scarfStyle(.title2)
|
||||
.foregroundStyle(ScarfColor.foregroundPrimary)
|
||||
Spacer()
|
||||
if summary.totalCount > 0 {
|
||||
ScarfBadge("\(summary.totalCount)", kind: .danger)
|
||||
}
|
||||
}
|
||||
Text("This permanently deletes every archived skill from disk. Restoring an archived skill is no longer possible after pruning.")
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
if summary.totalBytes > 0 {
|
||||
Text("Total to remove: \(summary.totalBytesLabel)")
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func row(skill: HermesCuratorArchivedSkill) -> some View {
|
||||
HStack(spacing: ScarfSpace.s2) {
|
||||
Image(systemName: "minus.circle")
|
||||
.foregroundStyle(ScarfColor.danger)
|
||||
.font(.caption)
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(skill.name)
|
||||
.scarfStyle(.body)
|
||||
.foregroundStyle(ScarfColor.foregroundPrimary)
|
||||
.lineLimit(1)
|
||||
if let reason = skill.reason, !reason.isEmpty {
|
||||
Text(reason)
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
Spacer()
|
||||
Text(skill.archivedAtLabel)
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||
.frame(width: 96, alignment: .trailing)
|
||||
Text(skill.sizeLabel)
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||
.frame(width: 72, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
|
||||
private var footer: some View {
|
||||
HStack {
|
||||
Button("Cancel") {
|
||||
onCancel()
|
||||
dismiss()
|
||||
}
|
||||
.buttonStyle(ScarfGhostButton())
|
||||
// Cancel owns .defaultAction so accidental Enter-presses
|
||||
// don't trigger the destructive button (template-uninstall
|
||||
// pattern recommended in the WS-4 plan).
|
||||
.keyboardShortcut(.defaultAction)
|
||||
.disabled(isPruning)
|
||||
Spacer()
|
||||
if isPruning {
|
||||
ProgressView().controlSize(.small)
|
||||
}
|
||||
Button("Prune permanently") {
|
||||
onConfirm()
|
||||
}
|
||||
.buttonStyle(ScarfDestructiveButton())
|
||||
.disabled(isPruning || summary.wouldRemove.isEmpty)
|
||||
.accessibilityIdentifier("curatorPrune.confirm")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,18 +2,16 @@ import SwiftUI
|
||||
import ScarfCore
|
||||
import ScarfDesign
|
||||
|
||||
/// Modal that lists archived skills (state ≠ active) and exposes a
|
||||
/// one-click "Restore" action per row. v0.12 archives are recoverable —
|
||||
/// `hermes curator restore <name>` brings the skill back into
|
||||
/// `~/.hermes/skills/<category>/<name>/` and re-marks it active.
|
||||
/// Legacy v0.12 fallback for restoring an archived skill by typed
|
||||
/// name. Hermes v0.12 didn't ship `curator list-archived`, so the only
|
||||
/// way to restore was to remember the skill name and pass it through
|
||||
/// `hermes curator restore <name>`.
|
||||
///
|
||||
/// The Curator's `status` text doesn't enumerate archived skills with
|
||||
/// names; we surface what's available (counts + pinned list) and rely
|
||||
/// on the user knowing the names. Hermes ergo does an interactive
|
||||
/// `--name` arg if missing — but Scarf prefers explicit selection so
|
||||
/// users don't have to remember names. For v2.6 we render a free-form
|
||||
/// text field; once Hermes ships a `curator list-archived` (tracked
|
||||
/// upstream), swap to a pickable list.
|
||||
/// **v0.13+ flow (preferred):** `CuratorArchivedSection` renders a
|
||||
/// per-skill list with a one-click Restore button per row — no typing
|
||||
/// required. This sheet stays reachable from the overflow menu only on
|
||||
/// pre-v0.13 hosts (gated by `!hasCuratorArchive`). Don't delete this
|
||||
/// file even after WS-4 ships; v0.12 hosts still depend on it.
|
||||
struct CuratorRestoreSheet: View {
|
||||
let viewModel: CuratorViewModel
|
||||
|
||||
|
||||
@@ -2,57 +2,52 @@ import SwiftUI
|
||||
import ScarfCore
|
||||
import ScarfDesign
|
||||
|
||||
/// Mac UI for Hermes v0.12's autonomous skill curator.
|
||||
/// Mac UI for Hermes's autonomous skill curator (v0.12 base + v0.13
|
||||
/// archive/prune surface).
|
||||
///
|
||||
/// Surfaces the running state (enabled / paused / disabled), last-run
|
||||
/// metadata, agent-created skill counts, and the most/least-active /
|
||||
/// least-recently-active leaderboards. Pin-and-restore actions hit
|
||||
/// `hermes curator pin/unpin/restore` via CuratorViewModel.
|
||||
/// metadata, agent-created skill counts, the most/least-active /
|
||||
/// least-recently-active leaderboards, and on v0.13+ hosts the new
|
||||
/// archived-skills section + per-row Archive button on each leaderboard
|
||||
/// entry. Pin / unpin / restore / archive / prune route through
|
||||
/// CuratorViewModel → CuratorService.
|
||||
///
|
||||
/// Capability-gated upstream: AppCoordinator only wires the sidebar
|
||||
/// item when `HermesCapabilities.hasCurator` is true. This view assumes
|
||||
/// it's reachable on a v0.12+ host.
|
||||
/// item when `HermesCapabilities.hasCurator` is true. Archive surfaces
|
||||
/// gate independently on `hasCuratorArchive`; pre-v0.13 hosts see the
|
||||
/// v2.7.x layout unchanged (legacy `CuratorRestoreSheet` reachable from
|
||||
/// the overflow menu, no Archive section, fire-and-forget Run Now).
|
||||
struct CuratorView: View {
|
||||
@State private var viewModel: CuratorViewModel
|
||||
@State private var showRestoreSheet = false
|
||||
|
||||
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||
|
||||
init(context: ServerContext) {
|
||||
_viewModel = State(initialValue: CuratorViewModel(context: context))
|
||||
}
|
||||
|
||||
/// Single source of truth for "v0.13 archive surface visible". Read
|
||||
/// once in `body` and threaded into sub-views. Defensive default to
|
||||
/// `false` so previews / smoke tests behave like a pre-v0.13 host.
|
||||
private var archiveAvailable: Bool {
|
||||
capabilitiesStore?.capabilities.hasCuratorArchive ?? false
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: ScarfSpace.s4) {
|
||||
ScarfPageHeader(
|
||||
"Curator",
|
||||
subtitle: "Autonomous skill maintenance — Hermes v0.12+"
|
||||
subtitle: archiveAvailable
|
||||
? "Autonomous skill maintenance — archive, prune, restore"
|
||||
: "Autonomous skill maintenance — Hermes v0.12+"
|
||||
) {
|
||||
HStack(spacing: ScarfSpace.s2) {
|
||||
if viewModel.isLoading {
|
||||
ProgressView().controlSize(.small)
|
||||
}
|
||||
Button("Run Now") {
|
||||
Task { await viewModel.runNow() }
|
||||
}
|
||||
.buttonStyle(ScarfPrimaryButton())
|
||||
.disabled(viewModel.isLoading)
|
||||
Menu {
|
||||
switch viewModel.status.state {
|
||||
case .paused:
|
||||
Button("Resume") { Task { await viewModel.resume() } }
|
||||
case .enabled:
|
||||
Button("Pause") { Task { await viewModel.pause() } }
|
||||
default:
|
||||
EmptyView()
|
||||
}
|
||||
Button("Restore Archived…") {
|
||||
showRestoreSheet = true
|
||||
}
|
||||
.disabled(viewModel.status.archivedSkills == 0)
|
||||
} label: {
|
||||
Image(systemName: "ellipsis.circle")
|
||||
}
|
||||
headerActions
|
||||
}
|
||||
|
||||
if let errorMessage = viewModel.errorMessage {
|
||||
errorBanner(errorMessage)
|
||||
}
|
||||
|
||||
if let toast = viewModel.transientMessage {
|
||||
@@ -64,6 +59,19 @@ struct CuratorView: View {
|
||||
pinnedSection
|
||||
activityTables
|
||||
|
||||
if archiveAvailable {
|
||||
CuratorArchivedSection(
|
||||
archived: viewModel.archivedSkills,
|
||||
isLoading: viewModel.isLoadingArchive,
|
||||
onRestore: { name in
|
||||
Task { await viewModel.restore(name) }
|
||||
},
|
||||
onPruneAll: {
|
||||
Task { await viewModel.planPrune() }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
if let report = viewModel.lastReportMarkdown {
|
||||
lastReportSection(markdown: report)
|
||||
}
|
||||
@@ -71,10 +79,84 @@ struct CuratorView: View {
|
||||
.padding(ScarfSpace.s4)
|
||||
}
|
||||
.background(ScarfColor.backgroundPrimary)
|
||||
.task { await viewModel.load() }
|
||||
.task {
|
||||
await viewModel.load()
|
||||
if archiveAvailable {
|
||||
await viewModel.loadArchive()
|
||||
}
|
||||
}
|
||||
.sheet(isPresented: $showRestoreSheet) {
|
||||
CuratorRestoreSheet(viewModel: viewModel)
|
||||
}
|
||||
.sheet(
|
||||
isPresented: Binding(
|
||||
get: { viewModel.pruneSummary != nil },
|
||||
set: { isShown in
|
||||
if !isShown { viewModel.cancelPrune() }
|
||||
}
|
||||
)
|
||||
) {
|
||||
if let summary = viewModel.pruneSummary {
|
||||
CuratorPruneConfirmSheet(
|
||||
summary: summary,
|
||||
isPruning: viewModel.isPruning,
|
||||
onConfirm: {
|
||||
Task { await viewModel.confirmPrune() }
|
||||
},
|
||||
onCancel: {
|
||||
viewModel.cancelPrune()
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private var headerActions: some View {
|
||||
HStack(spacing: ScarfSpace.s2) {
|
||||
if viewModel.isLoading {
|
||||
ProgressView().controlSize(.small)
|
||||
}
|
||||
Button("Run Now") {
|
||||
Task {
|
||||
await viewModel.runNow(
|
||||
synchronous: archiveAvailable,
|
||||
timeout: 600
|
||||
)
|
||||
}
|
||||
}
|
||||
.buttonStyle(ScarfPrimaryButton())
|
||||
.disabled(viewModel.isLoading)
|
||||
.help(archiveAvailable
|
||||
? "Curator runs synchronously on Hermes v0.13+. Usually 10–90s."
|
||||
: "Trigger a curator run. Returns immediately on pre-v0.13 hosts.")
|
||||
|
||||
Menu {
|
||||
switch viewModel.status.state {
|
||||
case .paused:
|
||||
Button("Resume") { Task { await viewModel.resume() } }
|
||||
case .enabled:
|
||||
Button("Pause") { Task { await viewModel.pause() } }
|
||||
default:
|
||||
EmptyView()
|
||||
}
|
||||
|
||||
if archiveAvailable {
|
||||
Divider()
|
||||
Button("Prune Archived…", role: .destructive) {
|
||||
Task { await viewModel.planPrune() }
|
||||
}
|
||||
.disabled(viewModel.archivedSkills.isEmpty && !viewModel.isLoadingArchive)
|
||||
} else {
|
||||
Button("Restore Archived…") {
|
||||
showRestoreSheet = true
|
||||
}
|
||||
.disabled(viewModel.status.archivedSkills == 0)
|
||||
}
|
||||
} label: {
|
||||
Image(systemName: "ellipsis.circle")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var statusSummary: some View {
|
||||
@@ -206,6 +288,10 @@ struct CuratorView: View {
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help(viewModel.status.pinnedNames.contains(row.name) ? "Pinned" : "Pin skill")
|
||||
|
||||
if archiveAvailable {
|
||||
archiveButton(for: row.name)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 2)
|
||||
}
|
||||
@@ -213,6 +299,25 @@ struct CuratorView: View {
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func archiveButton(for name: String) -> some View {
|
||||
if viewModel.pendingArchiveName == name {
|
||||
ProgressView()
|
||||
.controlSize(.small)
|
||||
.frame(width: 14, height: 14)
|
||||
} else {
|
||||
Button {
|
||||
Task { await viewModel.archive(name) }
|
||||
} label: {
|
||||
Image(systemName: "archivebox")
|
||||
.font(.system(size: 12))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("Archive (move out of active set)")
|
||||
.disabled(viewModel.pendingArchiveName != nil)
|
||||
}
|
||||
}
|
||||
|
||||
private func counterChip(label: String, value: Int) -> some View {
|
||||
Text("\(label) \(value)")
|
||||
.font(ScarfFont.monoSmall)
|
||||
@@ -277,6 +382,35 @@ struct CuratorView: View {
|
||||
.background(ScarfColor.accentTint)
|
||||
.clipShape(RoundedRectangle(cornerRadius: ScarfRadius.md))
|
||||
}
|
||||
|
||||
/// Inline yellow banner for CLI failures. Non-blocking — sits above
|
||||
/// the status summary and dismisses with the "x" so users can keep
|
||||
/// interacting with the leaderboard. Mirrors the pattern in
|
||||
/// KanbanBoardView.
|
||||
private func errorBanner(_ message: String) -> some View {
|
||||
HStack(alignment: .top, spacing: ScarfSpace.s2) {
|
||||
Image(systemName: "exclamationmark.triangle.fill")
|
||||
.foregroundStyle(ScarfColor.warning)
|
||||
Text(message)
|
||||
.scarfStyle(.caption)
|
||||
.foregroundStyle(ScarfColor.foregroundPrimary)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
Button {
|
||||
viewModel.dismissError()
|
||||
} label: {
|
||||
Image(systemName: "xmark.circle.fill")
|
||||
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("Dismiss")
|
||||
}
|
||||
.padding(.horizontal, ScarfSpace.s3)
|
||||
.padding(.vertical, ScarfSpace.s2)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: ScarfRadius.md)
|
||||
.fill(ScarfColor.warning.opacity(0.12))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Simple `FlowLayout` for the pinned-skill chips. Custom layout
|
||||
|
||||
Reference in New Issue
Block a user