mirror of
https://github.com/awizemann/scarf.git
synced 2026-05-10 18:44:45 +00:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b4482e5ee7 |
@@ -0,0 +1,76 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Hermes v0.13 added cross-platform recipient allowlists to the Messaging
|
||||||
|
/// Gateway. Each platform stores the list under a different YAML key
|
||||||
|
/// depending on the platform's primary noun for "addressable destination":
|
||||||
|
///
|
||||||
|
/// - **`allowed_channels`** — Slack, Mattermost, Google Chat
|
||||||
|
/// - **`allowed_chats`** — Telegram, WhatsApp
|
||||||
|
/// - **`allowed_rooms`** — Matrix, DingTalk
|
||||||
|
///
|
||||||
|
/// `GatewayAllowlistKind` encodes the (platform → key) mapping plus a few
|
||||||
|
/// presentation hints (placeholder strings, singular noun) so the allowlist
|
||||||
|
/// editor can render the right copy without the per-platform setup view
|
||||||
|
/// needing to know the YAML shape.
|
||||||
|
public enum GatewayAllowlistKind: String, Sendable, Equatable {
|
||||||
|
case channels // -> allowed_channels
|
||||||
|
case chats // -> allowed_chats
|
||||||
|
case rooms // -> allowed_rooms
|
||||||
|
|
||||||
|
/// YAML scalar key segment under `gateway.platforms.<platform>.<key>`.
|
||||||
|
public var yamlKey: String {
|
||||||
|
switch self {
|
||||||
|
case .channels: return "allowed_channels"
|
||||||
|
case .chats: return "allowed_chats"
|
||||||
|
case .rooms: return "allowed_rooms"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Placeholder copy for the editor's "add row" text field. Picks the
|
||||||
|
/// most common identifier shape per platform family — Slack channel IDs
|
||||||
|
/// for `channels`, Telegram username/numeric for `chats`, Matrix room
|
||||||
|
/// IDs for `rooms`. Users can paste in any platform-specific format the
|
||||||
|
/// gateway accepts; this is a hint, not validation.
|
||||||
|
public var inputPlaceholder: String {
|
||||||
|
switch self {
|
||||||
|
case .channels: return "C0123ABCD or #channel-name"
|
||||||
|
case .chats: return "@username or 12345678"
|
||||||
|
case .rooms: return "!RoomId:matrix.org"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Singular noun for prose surfaces ("Add a channel", "1 chat allowed",
|
||||||
|
/// "0 rooms"). Capitalization is the caller's responsibility.
|
||||||
|
public var noun: String {
|
||||||
|
switch self {
|
||||||
|
case .channels: return "channel"
|
||||||
|
case .chats: return "chat"
|
||||||
|
case .rooms: return "room"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Plural noun for headings + counts.
|
||||||
|
public var pluralNoun: String {
|
||||||
|
switch self {
|
||||||
|
case .channels: return "channels"
|
||||||
|
case .chats: return "chats"
|
||||||
|
case .rooms: return "rooms"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Map a Hermes platform identifier to the allowlist kind it supports.
|
||||||
|
/// Returns `nil` for platforms without v0.13 allowlist support
|
||||||
|
/// (`cli`, `signal`, `email`, `imessage`, `homeassistant`, `webhook`,
|
||||||
|
/// `yuanbao`, `microsoft-teams`, `feishu`, `discord`).
|
||||||
|
///
|
||||||
|
/// `googlechat` and `google-chat` both map to `.channels` so we round-trip
|
||||||
|
/// regardless of which spelling Hermes lands on. // TODO(WS-5-Q1)
|
||||||
|
public static func kind(for platform: String) -> GatewayAllowlistKind? {
|
||||||
|
switch platform {
|
||||||
|
case "slack", "mattermost", "google-chat", "googlechat": return .channels
|
||||||
|
case "telegram", "whatsapp": return .chats
|
||||||
|
case "matrix", "dingtalk": return .rooms
|
||||||
|
default: return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Per-platform Messaging Gateway settings introduced in Hermes v0.13. Bundles
|
||||||
|
/// the allowlist (the platform-appropriate flavor of `allowed_channels` /
|
||||||
|
/// `allowed_chats` / `allowed_rooms`) and three behavior toggles
|
||||||
|
/// (`busy_ack_enabled`, `gateway_restart_notification`,
|
||||||
|
/// `slash_command_notice_ttl_seconds`).
|
||||||
|
///
|
||||||
|
/// The struct carries all three list fields so a single shape fits every
|
||||||
|
/// platform; only the field matching `GatewayAllowlistKind.kind(for:)` is
|
||||||
|
/// surfaced in the editor for a given platform. The other two stay empty
|
||||||
|
/// and round-trip through the YAML parser unchanged.
|
||||||
|
///
|
||||||
|
/// **Defaults track Hermes v0.13.** `busyAckEnabled = true`,
|
||||||
|
/// `gatewayRestartNotification = false`, `slashCommandNoticeTTLSeconds = 0`
|
||||||
|
/// (disabled). An "all-default" instance therefore produces no `gateway:`
|
||||||
|
/// block in YAML — see `HermesConfig+YAML` parsing logic which only inserts
|
||||||
|
/// an entry into `gatewayPlatforms` when at least one v0.13 key is present
|
||||||
|
/// in the file.
|
||||||
|
public struct GatewayPlatformSettings: Sendable, Equatable {
|
||||||
|
/// `gateway.platforms.<platform>.allowed_channels` — Slack, Mattermost,
|
||||||
|
/// Google Chat. Empty when the platform doesn't use channels.
|
||||||
|
public var allowedChannels: [String]
|
||||||
|
/// `gateway.platforms.<platform>.allowed_chats` — Telegram, WhatsApp.
|
||||||
|
/// Empty when the platform doesn't use chats.
|
||||||
|
public var allowedChats: [String]
|
||||||
|
/// `gateway.platforms.<platform>.allowed_rooms` — Matrix, DingTalk.
|
||||||
|
/// Empty when the platform doesn't use rooms.
|
||||||
|
public var allowedRooms: [String]
|
||||||
|
/// `gateway.platforms.<platform>.busy_ack_enabled`. Default `true` — set
|
||||||
|
/// to `false` to suppress per-message "agent is working…" acks.
|
||||||
|
public var busyAckEnabled: Bool
|
||||||
|
/// `gateway.platforms.<platform>.gateway_restart_notification`. Default
|
||||||
|
/// `false` — set to `true` to post a "Gateway restarted" notice on boot.
|
||||||
|
public var gatewayRestartNotification: Bool
|
||||||
|
/// `gateway.platforms.<platform>.slash_command_notice_ttl_seconds`.
|
||||||
|
/// Default `0` (disabled). Positive values auto-delete slash-command
|
||||||
|
/// notices after N seconds.
|
||||||
|
public var slashCommandNoticeTTLSeconds: Int
|
||||||
|
|
||||||
|
public init(
|
||||||
|
allowedChannels: [String] = [],
|
||||||
|
allowedChats: [String] = [],
|
||||||
|
allowedRooms: [String] = [],
|
||||||
|
busyAckEnabled: Bool = true,
|
||||||
|
gatewayRestartNotification: Bool = false,
|
||||||
|
slashCommandNoticeTTLSeconds: Int = 0
|
||||||
|
) {
|
||||||
|
self.allowedChannels = allowedChannels
|
||||||
|
self.allowedChats = allowedChats
|
||||||
|
self.allowedRooms = allowedRooms
|
||||||
|
self.busyAckEnabled = busyAckEnabled
|
||||||
|
self.gatewayRestartNotification = gatewayRestartNotification
|
||||||
|
self.slashCommandNoticeTTLSeconds = slashCommandNoticeTTLSeconds
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All-default instance. `HermesConfig.empty` initializes
|
||||||
|
/// `gatewayPlatforms: [:]` so this is rarely used directly; provided
|
||||||
|
/// for symmetry with the other settings types.
|
||||||
|
public static let empty = GatewayPlatformSettings()
|
||||||
|
|
||||||
|
/// The list field matching this allowlist kind, or `nil` for
|
||||||
|
/// platforms without an allowlist surface.
|
||||||
|
public func items(for kind: GatewayAllowlistKind) -> [String] {
|
||||||
|
switch kind {
|
||||||
|
case .channels: return allowedChannels
|
||||||
|
case .chats: return allowedChats
|
||||||
|
case .rooms: return allowedRooms
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -667,6 +667,17 @@ public struct HermesConfig: Sendable {
|
|||||||
/// useful for cost auditing and screen-recording demos.
|
/// useful for cost auditing and screen-recording demos.
|
||||||
public var runtimeMetadataFooter: Bool
|
public var runtimeMetadataFooter: Bool
|
||||||
|
|
||||||
|
// -- Hermes v0.13 additions ----------------------------------------
|
||||||
|
// Per-platform Messaging Gateway settings dictionary keyed by Hermes
|
||||||
|
// platform identifier (`slack`, `telegram`, `matrix`, `mattermost`,
|
||||||
|
// `whatsapp`, `dingtalk`, `google-chat`). Populated only for platforms
|
||||||
|
// whose `gateway.platforms.<platform>.*` block exists in config.yaml —
|
||||||
|
// platforms without an explicit block don't appear in the dictionary.
|
||||||
|
// Editing surfaces (per-platform setup forms) read with a `?? .empty`
|
||||||
|
// fallback so a missing entry behaves identically to an all-default
|
||||||
|
// entry.
|
||||||
|
public var gatewayPlatforms: [String: GatewayPlatformSettings]
|
||||||
|
|
||||||
// Grouped blocks
|
// Grouped blocks
|
||||||
public var display: DisplaySettings
|
public var display: DisplaySettings
|
||||||
public var terminal: TerminalSettings
|
public var terminal: TerminalSettings
|
||||||
@@ -747,11 +758,13 @@ public struct HermesConfig: Sendable {
|
|||||||
homeAssistant: HomeAssistantSettings,
|
homeAssistant: HomeAssistantSettings,
|
||||||
cacheTTL: String = "5m",
|
cacheTTL: String = "5m",
|
||||||
redactionEnabled: Bool = false,
|
redactionEnabled: Bool = false,
|
||||||
runtimeMetadataFooter: Bool = false
|
runtimeMetadataFooter: Bool = false,
|
||||||
|
gatewayPlatforms: [String: GatewayPlatformSettings] = [:]
|
||||||
) {
|
) {
|
||||||
self.cacheTTL = cacheTTL
|
self.cacheTTL = cacheTTL
|
||||||
self.redactionEnabled = redactionEnabled
|
self.redactionEnabled = redactionEnabled
|
||||||
self.runtimeMetadataFooter = runtimeMetadataFooter
|
self.runtimeMetadataFooter = runtimeMetadataFooter
|
||||||
|
self.gatewayPlatforms = gatewayPlatforms
|
||||||
self.model = model
|
self.model = model
|
||||||
self.provider = provider
|
self.provider = provider
|
||||||
self.maxTurns = maxTurns
|
self.maxTurns = maxTurns
|
||||||
|
|||||||
@@ -1,158 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
|
|
||||||
/// A structured signal Hermes emits when it observes worker / task
|
|
||||||
/// distress. Hermes v0.13 introduced a generic diagnostics engine that
|
|
||||||
/// attaches these to a task (cross-run signals) and/or a run (per-attempt
|
|
||||||
/// signals). Pre-v0.13 hosts never emit diagnostics so the array decodes
|
|
||||||
/// empty and downstream UI no-ops.
|
|
||||||
///
|
|
||||||
/// **Wire shape (best inference from release notes — verify against live
|
|
||||||
/// JSON during integration):** an array of objects with `kind`, optional
|
|
||||||
/// `message`, optional `detected_at` (ISO-8601 string OR Unix integer,
|
|
||||||
/// matching the rest of `HermesKanbanTask`'s timestamp tolerance).
|
|
||||||
///
|
|
||||||
/// **Forward compat:** `kind` stays a `String` so a future Hermes can
|
|
||||||
/// add new diagnostic kinds without a Scarf release. `KanbanDiagnosticKind`
|
|
||||||
/// is the typed mirror — it falls back to `.unknown` for unrecognized
|
|
||||||
/// kinds and renders the raw string verbatim.
|
|
||||||
public struct HermesKanbanDiagnostic: Sendable, Equatable, Identifiable, Codable {
|
|
||||||
/// Synthetic id — not on the wire. Lets SwiftUI `ForEach` over a
|
|
||||||
/// diagnostic array without forcing a deterministic id from the
|
|
||||||
/// server (Hermes doesn't currently mint one).
|
|
||||||
public let id: UUID
|
|
||||||
/// Wire-side `kind` string. Compared case-insensitively via
|
|
||||||
/// `KanbanDiagnosticKind.from(_:)`.
|
|
||||||
public let kind: String
|
|
||||||
/// Human-friendly elaboration ("no heartbeat for 4m20s", "exit code
|
|
||||||
/// 0 with no complete call", etc.). May be nil; render the raw
|
|
||||||
/// `kind` then.
|
|
||||||
public let message: String?
|
|
||||||
/// ISO-8601 string. Decoder accepts Unix integer seconds (Hermes's
|
|
||||||
/// SQLite-backed shape) and converts to ISO-8601 so consumers see
|
|
||||||
/// one type — same pattern as `HermesKanbanTask.decodeFlexibleTimestamp`.
|
|
||||||
public let detectedAt: String?
|
|
||||||
|
|
||||||
public init(
|
|
||||||
kind: String,
|
|
||||||
message: String? = nil,
|
|
||||||
detectedAt: String? = nil
|
|
||||||
) {
|
|
||||||
self.id = UUID()
|
|
||||||
self.kind = kind
|
|
||||||
self.message = message
|
|
||||||
self.detectedAt = detectedAt
|
|
||||||
}
|
|
||||||
|
|
||||||
enum CodingKeys: String, CodingKey {
|
|
||||||
case kind
|
|
||||||
case message
|
|
||||||
case detectedAt = "detected_at"
|
|
||||||
}
|
|
||||||
|
|
||||||
public init(from decoder: any Decoder) throws {
|
|
||||||
let c = try decoder.container(keyedBy: CodingKeys.self)
|
|
||||||
self.id = UUID()
|
|
||||||
self.kind = try c.decodeIfPresent(String.self, forKey: .kind) ?? "unknown"
|
|
||||||
self.message = try c.decodeIfPresent(String.self, forKey: .message)
|
|
||||||
// Flexible timestamp decode mirrors HermesKanbanTask's pattern.
|
|
||||||
if !c.contains(.detectedAt) {
|
|
||||||
self.detectedAt = nil
|
|
||||||
} else if let unix = try? c.decodeIfPresent(Double.self, forKey: .detectedAt) {
|
|
||||||
let date = Date(timeIntervalSince1970: unix)
|
|
||||||
self.detectedAt = Self.isoFormatter.string(from: date)
|
|
||||||
} else {
|
|
||||||
self.detectedAt = try c.decodeIfPresent(String.self, forKey: .detectedAt)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public func encode(to encoder: any Encoder) throws {
|
|
||||||
var c = encoder.container(keyedBy: CodingKeys.self)
|
|
||||||
try c.encode(kind, forKey: .kind)
|
|
||||||
try c.encodeIfPresent(message, forKey: .message)
|
|
||||||
try c.encodeIfPresent(detectedAt, forKey: .detectedAt)
|
|
||||||
}
|
|
||||||
|
|
||||||
public static func == (lhs: HermesKanbanDiagnostic, rhs: HermesKanbanDiagnostic) -> Bool {
|
|
||||||
// Compare on wire fields, not synthetic id — round-trip decoding
|
|
||||||
// mints fresh ids.
|
|
||||||
lhs.kind == rhs.kind
|
|
||||||
&& lhs.message == rhs.message
|
|
||||||
&& lhs.detectedAt == rhs.detectedAt
|
|
||||||
}
|
|
||||||
|
|
||||||
private static let isoFormatter: ISO8601DateFormatter = {
|
|
||||||
let f = ISO8601DateFormatter()
|
|
||||||
f.formatOptions = [.withInternetDateTime]
|
|
||||||
return f
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Typed mirror
|
|
||||||
|
|
||||||
/// Typed view of `HermesKanbanDiagnostic.kind`. Models keep the raw
|
|
||||||
/// string for forward compatibility; UI helpers read this enum to pick
|
|
||||||
/// the right glyph + tint without string-matching at every callsite.
|
|
||||||
///
|
|
||||||
/// `unknown` is the fallback for any kind a future Hermes adds that
|
|
||||||
/// Scarf doesn't recognize. Views render the raw string verbatim in
|
|
||||||
/// that case so the user still sees what Hermes flagged.
|
|
||||||
// TODO(WS-3-Q5): The exact `kind` string for darwin-zombie detection is
|
|
||||||
// inferred from the v0.13 release notes ("Detect darwin zombie workers");
|
|
||||||
// confirm against live `hermes kanban show --json` output during
|
|
||||||
// integration. Same for `worker_exit_no_complete` and the heartbeat-stalled
|
|
||||||
// kinds — typed mirror falls through to `.unknown` if the wire string
|
|
||||||
// drifts, and the raw string is still rendered.
|
|
||||||
public enum KanbanDiagnosticKind: String, Sendable, CaseIterable {
|
|
||||||
case heartbeatStalled = "heartbeat_stalled"
|
|
||||||
case toolErrorLoop = "tool_error_loop"
|
|
||||||
case retryCapHit = "retry_cap_hit"
|
|
||||||
case unboundedRetry = "unbounded_retry"
|
|
||||||
case darwinZombieDetected = "darwin_zombie_detected"
|
|
||||||
case spawnFailure = "spawn_failure"
|
|
||||||
case workerExitNoComplete = "worker_exit_no_complete"
|
|
||||||
case unknown
|
|
||||||
|
|
||||||
/// Map a wire string (case-insensitive) to a typed kind. Unknown
|
|
||||||
/// values fall through to `.unknown` so callers can still surface
|
|
||||||
/// the raw string.
|
|
||||||
public static func from(_ raw: String) -> KanbanDiagnosticKind {
|
|
||||||
KanbanDiagnosticKind(rawValue: raw.lowercased()) ?? .unknown
|
|
||||||
}
|
|
||||||
|
|
||||||
/// SF Symbol name to render alongside the diagnostic. View code
|
|
||||||
/// reaches through the typed enum so glyph choices live in one
|
|
||||||
/// place.
|
|
||||||
public var glyphName: String {
|
|
||||||
switch self {
|
|
||||||
case .heartbeatStalled: return "waveform.path.badge.minus"
|
|
||||||
case .toolErrorLoop: return "arrow.triangle.2.circlepath.exclamationmark"
|
|
||||||
case .retryCapHit: return "nosign"
|
|
||||||
case .unboundedRetry: return "arrow.clockwise.circle.fill"
|
|
||||||
case .darwinZombieDetected: return "apple.logo"
|
|
||||||
case .spawnFailure: return "bolt.slash"
|
|
||||||
case .workerExitNoComplete: return "figure.walk.departure"
|
|
||||||
case .unknown: return "stethoscope"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Severity tier for this kind — drives badge tint. `.danger` for
|
|
||||||
/// terminal-class signals (retry cap hit, zombie, spawn failure);
|
|
||||||
/// `.warning` for recoverable signals (heartbeat stalled, tool
|
|
||||||
/// error loop); `.neutral` only for unknown / forward-compat kinds.
|
|
||||||
public var severity: DiagnosticSeverity {
|
|
||||||
switch self {
|
|
||||||
case .retryCapHit, .darwinZombieDetected, .spawnFailure:
|
|
||||||
return .danger
|
|
||||||
case .heartbeatStalled, .toolErrorLoop, .unboundedRetry, .workerExitNoComplete:
|
|
||||||
return .warning
|
|
||||||
case .unknown:
|
|
||||||
return .neutral
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public enum DiagnosticSeverity: Sendable {
|
|
||||||
case warning
|
|
||||||
case danger
|
|
||||||
case neutral
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -24,19 +24,6 @@ public struct HermesKanbanRun: Sendable, Equatable, Identifiable, Codable {
|
|||||||
/// raw string so we don't lock the typed shape.
|
/// raw string so we don't lock the typed shape.
|
||||||
public let metadataJSON: String?
|
public let metadataJSON: String?
|
||||||
|
|
||||||
// v0.13 (v2026.5.7) fields. Both Optional / empty-default so a v0.12
|
|
||||||
// host's run row decodes without error.
|
|
||||||
/// Per-attempt distress signals. Cross-run signals (retry cap hit,
|
|
||||||
/// etc.) hang off `HermesKanbanTask.diagnostics`; in-flight signals
|
|
||||||
/// (heartbeat stalled, darwin zombie detected) attach here.
|
|
||||||
public let diagnostics: [HermesKanbanDiagnostic]
|
|
||||||
/// Server-side unified failure counter (renamed from three separate
|
|
||||||
/// spawn / timeout / crash counters in v0.13). Optional — when nil,
|
|
||||||
/// callers fall back to counting failed runs in the runs array.
|
|
||||||
// TODO(WS-3-Q4): Verify whether v0.13 exposes this field on the per-run
|
|
||||||
// shape OR only at the task level. Tolerant decode handles either.
|
|
||||||
public let failureCount: Int?
|
|
||||||
|
|
||||||
public init(
|
public init(
|
||||||
id: Int,
|
id: Int,
|
||||||
taskId: String,
|
taskId: String,
|
||||||
@@ -53,9 +40,7 @@ public struct HermesKanbanRun: Sendable, Equatable, Identifiable, Codable {
|
|||||||
outcome: String? = nil,
|
outcome: String? = nil,
|
||||||
summary: String? = nil,
|
summary: String? = nil,
|
||||||
error: String? = nil,
|
error: String? = nil,
|
||||||
metadataJSON: String? = nil,
|
metadataJSON: String? = nil
|
||||||
diagnostics: [HermesKanbanDiagnostic] = [],
|
|
||||||
failureCount: Int? = nil
|
|
||||||
) {
|
) {
|
||||||
self.id = id
|
self.id = id
|
||||||
self.taskId = taskId
|
self.taskId = taskId
|
||||||
@@ -73,8 +58,6 @@ public struct HermesKanbanRun: Sendable, Equatable, Identifiable, Codable {
|
|||||||
self.summary = summary
|
self.summary = summary
|
||||||
self.error = error
|
self.error = error
|
||||||
self.metadataJSON = metadataJSON
|
self.metadataJSON = metadataJSON
|
||||||
self.diagnostics = diagnostics
|
|
||||||
self.failureCount = failureCount
|
|
||||||
}
|
}
|
||||||
|
|
||||||
enum CodingKeys: String, CodingKey {
|
enum CodingKeys: String, CodingKey {
|
||||||
@@ -94,8 +77,6 @@ public struct HermesKanbanRun: Sendable, Equatable, Identifiable, Codable {
|
|||||||
case summary
|
case summary
|
||||||
case error
|
case error
|
||||||
case metadata
|
case metadata
|
||||||
case diagnostics
|
|
||||||
case failureCount = "failure_count"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public init(from decoder: any Decoder) throws {
|
public init(from decoder: any Decoder) throws {
|
||||||
@@ -139,11 +120,6 @@ public struct HermesKanbanRun: Sendable, Equatable, Identifiable, Codable {
|
|||||||
} else {
|
} else {
|
||||||
self.metadataJSON = nil
|
self.metadataJSON = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// v0.13 diagnostics array — `try?` so a malformed entry doesn't
|
|
||||||
// poison the whole run row. Empty default for pre-v0.13 hosts.
|
|
||||||
self.diagnostics = (try? c.decodeIfPresent([HermesKanbanDiagnostic].self, forKey: .diagnostics)) ?? []
|
|
||||||
self.failureCount = try c.decodeIfPresent(Int.self, forKey: .failureCount)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public func encode(to encoder: any Encoder) throws {
|
public func encode(to encoder: any Encoder) throws {
|
||||||
@@ -164,7 +140,5 @@ public struct HermesKanbanRun: Sendable, Equatable, Identifiable, Codable {
|
|||||||
try c.encodeIfPresent(summary, forKey: .summary)
|
try c.encodeIfPresent(summary, forKey: .summary)
|
||||||
try c.encodeIfPresent(error, forKey: .error)
|
try c.encodeIfPresent(error, forKey: .error)
|
||||||
try c.encodeIfPresent(metadataJSON, forKey: .metadata)
|
try c.encodeIfPresent(metadataJSON, forKey: .metadata)
|
||||||
try c.encode(diagnostics, forKey: .diagnostics)
|
|
||||||
try c.encodeIfPresent(failureCount, forKey: .failureCount)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,9 +9,8 @@ import Foundation
|
|||||||
/// `link`/`unlink`, `comment`, `dispatch`).
|
/// `link`/`unlink`, `comment`, `dispatch`).
|
||||||
///
|
///
|
||||||
/// Hermes has no `update` verb — `priority` / `title` / `body` /
|
/// Hermes has no `update` verb — `priority` / `title` / `body` /
|
||||||
/// `tenant` / `max_retries` are write-once at create time. Mutations
|
/// `tenant` are write-once at create time. Mutations after that are
|
||||||
/// after that are expressed as state transitions (status, assignee) or
|
/// expressed as state transitions (status, assignee) or new comments.
|
||||||
/// new comments.
|
|
||||||
public struct HermesKanbanTask: Sendable, Equatable, Identifiable, Codable {
|
public struct HermesKanbanTask: Sendable, Equatable, Identifiable, Codable {
|
||||||
public let id: String
|
public let id: String
|
||||||
public let title: String
|
public let title: String
|
||||||
@@ -35,29 +34,6 @@ public struct HermesKanbanTask: Sendable, Equatable, Identifiable, Codable {
|
|||||||
public let maxRuntimeSeconds: Int?
|
public let maxRuntimeSeconds: Int?
|
||||||
public let currentRunId: Int?
|
public let currentRunId: Int?
|
||||||
|
|
||||||
// v0.13 (v2026.5.7) reliability + recovery fields. All Optional with
|
|
||||||
// `nil` decoded for pre-v0.13 hosts so the v2.7.5 surface keeps
|
|
||||||
// rendering unchanged when the connected Hermes hasn't shipped them.
|
|
||||||
/// Per-task retry budget set at create time via `--max-retries N`.
|
|
||||||
/// Hermes pattern is write-once — no `set_max_retries` verb. Scarf
|
|
||||||
/// surfaces this read-only on the inspector header.
|
|
||||||
public let maxRetries: Int?
|
|
||||||
/// Server-supplied reason a task was auto-blocked (e.g. "worker
|
|
||||||
/// exited (code 0) without calling `kanban complete`"). Surfaced
|
|
||||||
/// verbatim in the inspector banner.
|
|
||||||
public let autoBlockedReason: String?
|
|
||||||
/// `pending` / `verified` / `rejected` / nil. Pending means a worker
|
|
||||||
/// claimed it created this card but Hermes hasn't confirmed the
|
|
||||||
/// underlying work exists. Read through `KanbanHallucinationGate.from`
|
|
||||||
/// to map to a typed mirror — kept as a String at the wire level so
|
|
||||||
/// Hermes can add new gate states (e.g. `quarantined`) without a
|
|
||||||
/// Scarf release.
|
|
||||||
public let hallucinationGateStatus: String?
|
|
||||||
/// Cross-run distress signals (retry cap hit, etc.). Per-run signals
|
|
||||||
/// hang off `HermesKanbanRun.diagnostics`. Empty array for pre-v0.13
|
|
||||||
/// hosts AND for tasks the diagnostics engine hasn't flagged.
|
|
||||||
public let diagnostics: [HermesKanbanDiagnostic]
|
|
||||||
|
|
||||||
public init(
|
public init(
|
||||||
id: String,
|
id: String,
|
||||||
title: String,
|
title: String,
|
||||||
@@ -77,11 +53,7 @@ public struct HermesKanbanTask: Sendable, Equatable, Identifiable, Codable {
|
|||||||
idempotencyKey: String? = nil,
|
idempotencyKey: String? = nil,
|
||||||
lastHeartbeatAt: String? = nil,
|
lastHeartbeatAt: String? = nil,
|
||||||
maxRuntimeSeconds: Int? = nil,
|
maxRuntimeSeconds: Int? = nil,
|
||||||
currentRunId: Int? = nil,
|
currentRunId: Int? = nil
|
||||||
maxRetries: Int? = nil,
|
|
||||||
autoBlockedReason: String? = nil,
|
|
||||||
hallucinationGateStatus: String? = nil,
|
|
||||||
diagnostics: [HermesKanbanDiagnostic] = []
|
|
||||||
) {
|
) {
|
||||||
self.id = id
|
self.id = id
|
||||||
self.title = title
|
self.title = title
|
||||||
@@ -102,10 +74,6 @@ public struct HermesKanbanTask: Sendable, Equatable, Identifiable, Codable {
|
|||||||
self.lastHeartbeatAt = lastHeartbeatAt
|
self.lastHeartbeatAt = lastHeartbeatAt
|
||||||
self.maxRuntimeSeconds = maxRuntimeSeconds
|
self.maxRuntimeSeconds = maxRuntimeSeconds
|
||||||
self.currentRunId = currentRunId
|
self.currentRunId = currentRunId
|
||||||
self.maxRetries = maxRetries
|
|
||||||
self.autoBlockedReason = autoBlockedReason
|
|
||||||
self.hallucinationGateStatus = hallucinationGateStatus
|
|
||||||
self.diagnostics = diagnostics
|
|
||||||
}
|
}
|
||||||
|
|
||||||
enum CodingKeys: String, CodingKey {
|
enum CodingKeys: String, CodingKey {
|
||||||
@@ -121,10 +89,6 @@ public struct HermesKanbanTask: Sendable, Equatable, Identifiable, Codable {
|
|||||||
case lastHeartbeatAt = "last_heartbeat_at"
|
case lastHeartbeatAt = "last_heartbeat_at"
|
||||||
case maxRuntimeSeconds = "max_runtime_seconds"
|
case maxRuntimeSeconds = "max_runtime_seconds"
|
||||||
case currentRunId = "current_run_id"
|
case currentRunId = "current_run_id"
|
||||||
case maxRetries = "max_retries"
|
|
||||||
case autoBlockedReason = "auto_blocked_reason"
|
|
||||||
case hallucinationGateStatus = "hallucination_gate_status"
|
|
||||||
case diagnostics
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public init(from decoder: any Decoder) throws {
|
public init(from decoder: any Decoder) throws {
|
||||||
@@ -153,17 +117,6 @@ public struct HermesKanbanTask: Sendable, Equatable, Identifiable, Codable {
|
|||||||
self.lastHeartbeatAt = try Self.decodeFlexibleTimestamp(c, forKey: .lastHeartbeatAt)
|
self.lastHeartbeatAt = try Self.decodeFlexibleTimestamp(c, forKey: .lastHeartbeatAt)
|
||||||
self.maxRuntimeSeconds = try c.decodeIfPresent(Int.self, forKey: .maxRuntimeSeconds)
|
self.maxRuntimeSeconds = try c.decodeIfPresent(Int.self, forKey: .maxRuntimeSeconds)
|
||||||
self.currentRunId = try c.decodeIfPresent(Int.self, forKey: .currentRunId)
|
self.currentRunId = try c.decodeIfPresent(Int.self, forKey: .currentRunId)
|
||||||
// v0.13 fields — every one is `decodeIfPresent` so a v0.12 host's
|
|
||||||
// task row decodes successfully with these all nil/empty. The
|
|
||||||
// tolerant-decode contract is pinned by KanbanModelsTests.
|
|
||||||
self.maxRetries = try c.decodeIfPresent(Int.self, forKey: .maxRetries)
|
|
||||||
self.autoBlockedReason = try c.decodeIfPresent(String.self, forKey: .autoBlockedReason)
|
|
||||||
self.hallucinationGateStatus = try c.decodeIfPresent(String.self, forKey: .hallucinationGateStatus)
|
|
||||||
// Wrap diagnostics decode in `try?` so a single malformed entry
|
|
||||||
// (or the whole array being the wrong shape) doesn't poison the
|
|
||||||
// task row — the rest of the decoder still produces a usable
|
|
||||||
// task. Empty default matches the `skills` pattern.
|
|
||||||
self.diagnostics = (try? c.decodeIfPresent([HermesKanbanDiagnostic].self, forKey: .diagnostics)) ?? []
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Decode a timestamp that may arrive as a Unix integer or an
|
/// Decode a timestamp that may arrive as a Unix integer or an
|
||||||
@@ -256,27 +209,3 @@ public enum KanbanBoardColumn: String, Sendable, CaseIterable, Identifiable {
|
|||||||
.triage, .upNext, .running, .blocked, .done
|
.triage, .upNext, .running, .blocked, .done
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Hallucination gate (v0.13)
|
|
||||||
|
|
||||||
/// Typed mirror of Hermes v0.13's hallucination-gate state. Worker-created
|
|
||||||
/// cards land in `pending` until something verifies the underlying work
|
|
||||||
/// exists; Scarf surfaces a Verify / Reject UX above the task body so the
|
|
||||||
/// user can act as the verification gate.
|
|
||||||
///
|
|
||||||
/// Kept separate from `KanbanStatus` because hallucination state is
|
|
||||||
/// orthogonal to the lifecycle — a card can be `ready` *and* `pending`,
|
|
||||||
/// for example.
|
|
||||||
public enum KanbanHallucinationGate: String, Sendable, CaseIterable {
|
|
||||||
case pending
|
|
||||||
case verified
|
|
||||||
case rejected
|
|
||||||
|
|
||||||
/// Map a raw `hallucination_gate_status` string (case-insensitive) to
|
|
||||||
/// a typed gate. Returns nil for empty/nil/unknown values so callers
|
|
||||||
/// can short-circuit "no gate" branches with `if let gate = …`.
|
|
||||||
public static func from(_ raw: String?) -> KanbanHallucinationGate? {
|
|
||||||
guard let raw, !raw.isEmpty else { return nil }
|
|
||||||
return KanbanHallucinationGate(rawValue: raw.lowercased())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -12,27 +12,17 @@ public struct HermesKanbanTaskDetail: Sendable, Equatable, Codable {
|
|||||||
/// to the worker as upstream context; surfacing them in the
|
/// to the worker as upstream context; surfacing them in the
|
||||||
/// inspector is useful for understanding why a task started.
|
/// inspector is useful for understanding why a task started.
|
||||||
public let parentResults: [String: String]
|
public let parentResults: [String: String]
|
||||||
/// Envelope-level diagnostics array (sibling to `task`, not nested
|
|
||||||
/// inside it). Defensive — Hermes v0.13's wire shape may attach
|
|
||||||
/// diagnostics to the task itself OR to the envelope.
|
|
||||||
/// `allDiagnostics` dedupes both sources by `(kind, detected_at)`.
|
|
||||||
// TODO(WS-3-Q2): Confirm against live `hermes kanban show --json`
|
|
||||||
// whether diagnostics live on the task envelope, the inner task, or
|
|
||||||
// both. Current decode is tolerant of either.
|
|
||||||
public let envelopeDiagnostics: [HermesKanbanDiagnostic]?
|
|
||||||
|
|
||||||
public init(
|
public init(
|
||||||
task: HermesKanbanTask,
|
task: HermesKanbanTask,
|
||||||
comments: [HermesKanbanComment] = [],
|
comments: [HermesKanbanComment] = [],
|
||||||
events: [HermesKanbanEvent] = [],
|
events: [HermesKanbanEvent] = [],
|
||||||
parentResults: [String: String] = [:],
|
parentResults: [String: String] = [:]
|
||||||
envelopeDiagnostics: [HermesKanbanDiagnostic]? = nil
|
|
||||||
) {
|
) {
|
||||||
self.task = task
|
self.task = task
|
||||||
self.comments = comments
|
self.comments = comments
|
||||||
self.events = events
|
self.events = events
|
||||||
self.parentResults = parentResults
|
self.parentResults = parentResults
|
||||||
self.envelopeDiagnostics = envelopeDiagnostics
|
|
||||||
}
|
}
|
||||||
|
|
||||||
enum CodingKeys: String, CodingKey {
|
enum CodingKeys: String, CodingKey {
|
||||||
@@ -40,7 +30,6 @@ public struct HermesKanbanTaskDetail: Sendable, Equatable, Codable {
|
|||||||
case comments
|
case comments
|
||||||
case events
|
case events
|
||||||
case parentResults = "parent_results"
|
case parentResults = "parent_results"
|
||||||
case envelopeDiagnostics = "diagnostics"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public init(from decoder: any Decoder) throws {
|
public init(from decoder: any Decoder) throws {
|
||||||
@@ -59,9 +48,6 @@ public struct HermesKanbanTaskDetail: Sendable, Equatable, Codable {
|
|||||||
self.comments = (try? container.decodeIfPresent([HermesKanbanComment].self, forKey: .comments)) ?? []
|
self.comments = (try? container.decodeIfPresent([HermesKanbanComment].self, forKey: .comments)) ?? []
|
||||||
self.events = (try? container.decodeIfPresent([HermesKanbanEvent].self, forKey: .events)) ?? []
|
self.events = (try? container.decodeIfPresent([HermesKanbanEvent].self, forKey: .events)) ?? []
|
||||||
self.parentResults = (try? container.decodeIfPresent([String: String].self, forKey: .parentResults)) ?? [:]
|
self.parentResults = (try? container.decodeIfPresent([String: String].self, forKey: .parentResults)) ?? [:]
|
||||||
// Same `try?` shield as the rest — a malformed envelope
|
|
||||||
// diagnostics array shouldn't reject the whole show response.
|
|
||||||
self.envelopeDiagnostics = try? container.decodeIfPresent([HermesKanbanDiagnostic].self, forKey: .envelopeDiagnostics)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public func encode(to encoder: any Encoder) throws {
|
public func encode(to encoder: any Encoder) throws {
|
||||||
@@ -70,20 +56,5 @@ public struct HermesKanbanTaskDetail: Sendable, Equatable, Codable {
|
|||||||
try c.encode(comments, forKey: .comments)
|
try c.encode(comments, forKey: .comments)
|
||||||
try c.encode(events, forKey: .events)
|
try c.encode(events, forKey: .events)
|
||||||
try c.encode(parentResults, forKey: .parentResults)
|
try c.encode(parentResults, forKey: .parentResults)
|
||||||
try c.encodeIfPresent(envelopeDiagnostics, forKey: .envelopeDiagnostics)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Unified diagnostics view for the inspector. Combines `task.diagnostics`
|
|
||||||
/// with envelope-level diagnostics (when present) and dedupes on the
|
|
||||||
/// `(kind, detectedAt)` tuple. Wire-side dupes are unlikely but cheap to
|
|
||||||
/// filter. Empty for pre-v0.13 hosts.
|
|
||||||
public var allDiagnostics: [HermesKanbanDiagnostic] {
|
|
||||||
let onTask = task.diagnostics
|
|
||||||
let onEnvelope = envelopeDiagnostics ?? []
|
|
||||||
var seen = Set<String>()
|
|
||||||
return (onTask + onEnvelope).filter { diag in
|
|
||||||
let key = "\(diag.kind)|\(diag.detectedAt ?? "")"
|
|
||||||
return seen.insert(key).inserted
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,6 +60,17 @@ public enum KnownPlatforms {
|
|||||||
// platform identifiers.
|
// platform identifiers.
|
||||||
HermesToolPlatform(name: "yuanbao", displayName: "Yuanbao 元宝", icon: "bubble.left.and.bubble.right.fill"),
|
HermesToolPlatform(name: "yuanbao", displayName: "Yuanbao 元宝", icon: "bubble.left.and.bubble.right.fill"),
|
||||||
HermesToolPlatform(name: "microsoft-teams", displayName: "Microsoft Teams", icon: "person.2.fill"),
|
HermesToolPlatform(name: "microsoft-teams", displayName: "Microsoft Teams", icon: "person.2.fill"),
|
||||||
|
// -- v0.13 additions ---------------------------------------------
|
||||||
|
// Google Chat is the 20th gateway platform. It's a generic
|
||||||
|
// `env_enablement_fn` / `cron_deliver_env_var`-driven adapter; setup
|
||||||
|
// runs through `hermes setup` rather than per-field forms because
|
||||||
|
// the auth dance is OAuth-style and lives outside Scarf. Identifier
|
||||||
|
// is `google-chat` (kebab-case, mirroring `microsoft-teams`).
|
||||||
|
// TODO(WS-5-Q1): verify identifier against Hermes v0.13 GA — if it
|
||||||
|
// ships as `googlechat` instead, update both this entry and
|
||||||
|
// `KnownPlatforms.icon(for:)` below. `GatewayAllowlistKind.kind(for:)`
|
||||||
|
// already accepts both spellings defensively.
|
||||||
|
HermesToolPlatform(name: "google-chat", displayName: "Google Chat", icon: "bubble.left.fill"),
|
||||||
]
|
]
|
||||||
|
|
||||||
public static func icon(for platform: String) -> String {
|
public static func icon(for platform: String) -> String {
|
||||||
@@ -79,6 +90,7 @@ public enum KnownPlatforms {
|
|||||||
case "imessage": return "message.fill"
|
case "imessage": return "message.fill"
|
||||||
case "yuanbao": return "bubble.left.and.bubble.right.fill"
|
case "yuanbao": return "bubble.left.and.bubble.right.fill"
|
||||||
case "microsoft-teams": return "person.2.fill"
|
case "microsoft-teams": return "person.2.fill"
|
||||||
|
case "google-chat", "googlechat": return "bubble.left.fill"
|
||||||
default: return "bubble.left"
|
default: return "bubble.left"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,15 +17,6 @@ public struct KanbanCreateRequest: Sendable, Equatable {
|
|||||||
public var maxRuntimeSeconds: Int?
|
public var maxRuntimeSeconds: Int?
|
||||||
public var createdBy: String?
|
public var createdBy: String?
|
||||||
public var skills: [String]
|
public var skills: [String]
|
||||||
/// v0.13: per-task retry budget. `--max-retries N` is write-once at
|
|
||||||
/// create time — no `set_max_retries` verb. Pass `nil` to let Hermes
|
|
||||||
/// pick its built-in default (3 as of v0.13.0). Capability-gated in
|
|
||||||
/// the create sheet on `hasKanbanDiagnostics`.
|
|
||||||
// TODO(WS-3-Q6): Confirm Hermes's global default for `max_retries`
|
|
||||||
// (v0.13 release notes don't enumerate it). The create sheet defaults
|
|
||||||
// the field to 3; if Hermes config exposes a different default, mirror
|
|
||||||
// it.
|
|
||||||
public var maxRetries: Int?
|
|
||||||
|
|
||||||
public init(
|
public init(
|
||||||
title: String,
|
title: String,
|
||||||
@@ -39,8 +30,7 @@ public struct KanbanCreateRequest: Sendable, Equatable {
|
|||||||
idempotencyKey: String? = nil,
|
idempotencyKey: String? = nil,
|
||||||
maxRuntimeSeconds: Int? = nil,
|
maxRuntimeSeconds: Int? = nil,
|
||||||
createdBy: String? = nil,
|
createdBy: String? = nil,
|
||||||
skills: [String] = [],
|
skills: [String] = []
|
||||||
maxRetries: Int? = nil
|
|
||||||
) {
|
) {
|
||||||
self.title = title
|
self.title = title
|
||||||
self.body = body
|
self.body = body
|
||||||
@@ -54,7 +44,6 @@ public struct KanbanCreateRequest: Sendable, Equatable {
|
|||||||
self.maxRuntimeSeconds = maxRuntimeSeconds
|
self.maxRuntimeSeconds = maxRuntimeSeconds
|
||||||
self.createdBy = createdBy
|
self.createdBy = createdBy
|
||||||
self.skills = skills
|
self.skills = skills
|
||||||
self.maxRetries = maxRetries
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build the argv suffix this request maps to (everything after
|
/// Build the argv suffix this request maps to (everything after
|
||||||
@@ -89,9 +78,6 @@ public struct KanbanCreateRequest: Sendable, Equatable {
|
|||||||
if let maxRuntimeSeconds {
|
if let maxRuntimeSeconds {
|
||||||
args.append(contentsOf: ["--max-runtime", "\(maxRuntimeSeconds)s"])
|
args.append(contentsOf: ["--max-runtime", "\(maxRuntimeSeconds)s"])
|
||||||
}
|
}
|
||||||
if let maxRetries {
|
|
||||||
args.append(contentsOf: ["--max-retries", String(maxRetries)])
|
|
||||||
}
|
|
||||||
if let createdBy, !createdBy.isEmpty {
|
if let createdBy, !createdBy.isEmpty {
|
||||||
args.append(contentsOf: ["--created-by", createdBy])
|
args.append(contentsOf: ["--created-by", createdBy])
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -225,6 +225,58 @@ public extension HermesConfig {
|
|||||||
cooldownSeconds: int("platforms.homeassistant.extra.cooldown_seconds", default: 30)
|
cooldownSeconds: int("platforms.homeassistant.extra.cooldown_seconds", default: 30)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// -- v0.13: per-platform Messaging Gateway settings --------------
|
||||||
|
// Read `gateway.platforms.<platform>.{allowed_channels|allowed_chats|
|
||||||
|
// allowed_rooms|busy_ack_enabled|gateway_restart_notification|
|
||||||
|
// slash_command_notice_ttl_seconds}` and bundle each platform that
|
||||||
|
// has at least one v0.13 key present in the file. Platforms without
|
||||||
|
// an explicit block don't appear in the dictionary, so the
|
||||||
|
// editor's `?? .empty` fallback hands the user the v0.13 defaults
|
||||||
|
// without leaving stale keys littered across the YAML.
|
||||||
|
//
|
||||||
|
// TODO(WS-5-Q2): the `gateway.platforms.*` path is unverified —
|
||||||
|
// Hermes v0.13 may emit allowlists under `platforms.<platform>.*`
|
||||||
|
// (sibling to existing `platforms.slack.reply_to_mode`) instead.
|
||||||
|
// If so, swap the `prefix` line below to `"platforms.\(platform)."`
|
||||||
|
// and update `GatewayConfigWriter` in lockstep.
|
||||||
|
let gatewayAllowlistPlatforms = [
|
||||||
|
"slack", "mattermost", "google-chat",
|
||||||
|
"telegram", "whatsapp",
|
||||||
|
"matrix", "dingtalk",
|
||||||
|
]
|
||||||
|
var gatewayPlatforms: [String: GatewayPlatformSettings] = [:]
|
||||||
|
for platform in gatewayAllowlistPlatforms {
|
||||||
|
let prefix = "gateway.platforms.\(platform)."
|
||||||
|
let allowedChannels = lists[prefix + "allowed_channels"] ?? []
|
||||||
|
let allowedChats = lists[prefix + "allowed_chats"] ?? []
|
||||||
|
let allowedRooms = lists[prefix + "allowed_rooms"] ?? []
|
||||||
|
let busy = bool(prefix + "busy_ack_enabled", default: true)
|
||||||
|
let restartNotice = bool(prefix + "gateway_restart_notification",
|
||||||
|
default: false)
|
||||||
|
let ttl = int(prefix + "slash_command_notice_ttl_seconds",
|
||||||
|
default: 0)
|
||||||
|
// Skip platforms with no v0.13 fields present anywhere in the
|
||||||
|
// file. Without this guard, every supported platform would
|
||||||
|
// round-trip an all-default block back through writes even
|
||||||
|
// when the user never touched the new surface.
|
||||||
|
let isEmpty = allowedChannels.isEmpty
|
||||||
|
&& allowedChats.isEmpty
|
||||||
|
&& allowedRooms.isEmpty
|
||||||
|
&& values[prefix + "busy_ack_enabled"] == nil
|
||||||
|
&& values[prefix + "gateway_restart_notification"] == nil
|
||||||
|
&& values[prefix + "slash_command_notice_ttl_seconds"] == nil
|
||||||
|
if !isEmpty {
|
||||||
|
gatewayPlatforms[platform] = GatewayPlatformSettings(
|
||||||
|
allowedChannels: allowedChannels,
|
||||||
|
allowedChats: allowedChats,
|
||||||
|
allowedRooms: allowedRooms,
|
||||||
|
busyAckEnabled: busy,
|
||||||
|
gatewayRestartNotification: restartNotice,
|
||||||
|
slashCommandNoticeTTLSeconds: ttl
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
self.init(
|
self.init(
|
||||||
model: str("model.default", default: "unknown"),
|
model: str("model.default", default: "unknown"),
|
||||||
provider: str("model.provider", default: "unknown"),
|
provider: str("model.provider", default: "unknown"),
|
||||||
@@ -284,7 +336,8 @@ public extension HermesConfig {
|
|||||||
homeAssistant: homeAssistant,
|
homeAssistant: homeAssistant,
|
||||||
cacheTTL: str("prompt_caching.cache_ttl", default: "5m"),
|
cacheTTL: str("prompt_caching.cache_ttl", default: "5m"),
|
||||||
redactionEnabled: bool("redaction.enabled", default: false),
|
redactionEnabled: bool("redaction.enabled", default: false),
|
||||||
runtimeMetadataFooter: bool("agent.runtime_metadata_footer", default: false)
|
runtimeMetadataFooter: bool("agent.runtime_metadata_footer", default: false),
|
||||||
|
gatewayPlatforms: gatewayPlatforms
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,396 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Direct YAML editor for `gateway.platforms.<platform>.allowed_<kind>:` list
|
||||||
|
/// blocks. Hermes v0.13 added these list-valued keys, but `hermes config set`
|
||||||
|
/// stringifies arrays (the same gotcha that forced Home Assistant's watch
|
||||||
|
/// lists to stay read-only). The Messaging Gateway editor sidesteps the CLI
|
||||||
|
/// for these keys by editing `~/.hermes/config.yaml` directly.
|
||||||
|
///
|
||||||
|
/// **Pure-function `setList`** is the heart of the editor — it splits the
|
||||||
|
/// YAML into lines, finds (or creates) the targeted block, and splices the
|
||||||
|
/// new items in while preserving every byte outside the block. The async
|
||||||
|
/// `saveList` wrapper wires it through `ServerContext.readText` /
|
||||||
|
/// `writeText`, so the same code path works on `.local` and `.ssh` servers
|
||||||
|
/// — local goes through `LocalTransport`, remote round-trips via SCP.
|
||||||
|
///
|
||||||
|
/// **Scalar fields don't go through here.** `busy_ack_enabled`,
|
||||||
|
/// `gateway_restart_notification`, and `slash_command_notice_ttl_seconds`
|
||||||
|
/// are scalars that `hermes config set` handles cleanly — `GatewayBehaviorViewModel`
|
||||||
|
/// routes those through `PlatformSetupHelpers.saveForm` like every other
|
||||||
|
/// platform toggle.
|
||||||
|
///
|
||||||
|
/// **Why not use a real YAML library?** Same answer as everywhere else in
|
||||||
|
/// Scarf: zero external dependencies. The Hermes config flavor is a tightly
|
||||||
|
/// scoped subset (indent-based blocks, scalar-or-list values, no anchors /
|
||||||
|
/// aliases / flow style), and the targeted edit doesn't need to understand
|
||||||
|
/// the full grammar — only "find this block, replace it, preserve the rest".
|
||||||
|
public enum GatewayConfigWriter {
|
||||||
|
|
||||||
|
/// Insert or replace `gateway.platforms.<platform>.<key>:` block in the
|
||||||
|
/// YAML, preserving everything else byte-for-byte.
|
||||||
|
///
|
||||||
|
/// - When `items` is empty, the block (and only the block — siblings
|
||||||
|
/// stay) is removed from the YAML if present, and the function is a
|
||||||
|
/// no-op if the block was already absent.
|
||||||
|
/// - When the block is absent and `items` is non-empty, the function
|
||||||
|
/// appends a `gateway:` / `platforms:` / `<platform>:` scaffold at
|
||||||
|
/// the end of the file, creating any missing ancestors. This keeps
|
||||||
|
/// the function idempotent on round-trip but means the new block is
|
||||||
|
/// appended rather than spliced into an existing top-level
|
||||||
|
/// `gateway:` section. (See WS-5 plan §Notes for the trade-off; the
|
||||||
|
/// alternative would mean reflowing existing siblings, which is the
|
||||||
|
/// exact opposite of "preserve the surrounding YAML byte-for-byte".)
|
||||||
|
/// - When the block is present, its bullet rows are replaced with the
|
||||||
|
/// new items at the same indent. Items containing YAML-special
|
||||||
|
/// characters (`:` `#` `@` or leading whitespace) are single-quoted
|
||||||
|
/// defensively.
|
||||||
|
public static func setList(
|
||||||
|
in yaml: String,
|
||||||
|
platform: String,
|
||||||
|
key: String,
|
||||||
|
items: [String]
|
||||||
|
) -> String {
|
||||||
|
let blockIndent = 6 // `gateway:\n platforms:\n <platform>:\n <key>:`
|
||||||
|
let itemIndent = 8
|
||||||
|
|
||||||
|
let lines = yaml.components(separatedBy: "\n")
|
||||||
|
let blockHeaderText = " \(key):" // indented match for find()
|
||||||
|
let trimmedItems = items.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }
|
||||||
|
|
||||||
|
// Locate ` <key>:` whose lineage is gateway → platforms → <platform>.
|
||||||
|
// We find the start of the gateway block, walk down the indent tree, and
|
||||||
|
// bail out if any ancestor is missing.
|
||||||
|
let location = locateBlock(
|
||||||
|
in: lines,
|
||||||
|
platform: platform,
|
||||||
|
key: key
|
||||||
|
)
|
||||||
|
|
||||||
|
switch location {
|
||||||
|
case .found(let blockRange):
|
||||||
|
return replaceBlock(
|
||||||
|
in: lines,
|
||||||
|
blockRange: blockRange,
|
||||||
|
key: key,
|
||||||
|
items: trimmedItems,
|
||||||
|
blockIndent: blockIndent,
|
||||||
|
itemIndent: itemIndent
|
||||||
|
)
|
||||||
|
case .platformPresentKeyMissing(let insertAfter):
|
||||||
|
if trimmedItems.isEmpty {
|
||||||
|
// No-op: empty target, no existing block.
|
||||||
|
return yaml
|
||||||
|
}
|
||||||
|
return spliceNewKey(
|
||||||
|
lines: lines,
|
||||||
|
insertAfterLineIndex: insertAfter,
|
||||||
|
key: key,
|
||||||
|
items: trimmedItems,
|
||||||
|
itemIndent: itemIndent
|
||||||
|
)
|
||||||
|
case .ancestorMissing:
|
||||||
|
if trimmedItems.isEmpty {
|
||||||
|
// Nothing to write, no existing block.
|
||||||
|
return yaml
|
||||||
|
}
|
||||||
|
return appendScaffold(
|
||||||
|
yaml: yaml,
|
||||||
|
platform: platform,
|
||||||
|
key: key,
|
||||||
|
items: trimmedItems
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// (unreachable — switch is exhaustive)
|
||||||
|
_ = blockHeaderText
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Async wrapper that reads, mutates, writes via the given context.
|
||||||
|
/// Returns `false` on read or write failure.
|
||||||
|
///
|
||||||
|
/// The actual I/O happens via `ServerContext.readText` / `writeText`,
|
||||||
|
/// which are `nonisolated` — safe to call from `MainActor` for the
|
||||||
|
/// short config.yaml writes the platform setup forms run. For remote
|
||||||
|
/// hosts the call rounds through SCP under `Task.detached` upstream
|
||||||
|
/// (per Swift 6 concurrency rules in `~/.claude/CLAUDE.md`).
|
||||||
|
public static func saveList(
|
||||||
|
context: ServerContext,
|
||||||
|
platform: String,
|
||||||
|
key: String,
|
||||||
|
items: [String]
|
||||||
|
) -> Bool {
|
||||||
|
let path = context.paths.configYAML
|
||||||
|
let existing = context.readText(path) ?? ""
|
||||||
|
let updated = setList(in: existing, platform: platform, key: key, items: items)
|
||||||
|
if updated == existing { return true } // no-op: already correct
|
||||||
|
return context.writeText(path, content: updated)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Internals
|
||||||
|
|
||||||
|
/// Result of locating the targeted block in the YAML line array.
|
||||||
|
private enum BlockLocation {
|
||||||
|
/// Block found; the closed range covers the header line + all bullet
|
||||||
|
/// rows attributed to it. Replacing this slice with the new block
|
||||||
|
/// completes the edit.
|
||||||
|
case found(ClosedRange<Int>)
|
||||||
|
/// `gateway → platforms → <platform>` exists, but the leaf `<key>:`
|
||||||
|
/// is absent under it. The associated value is the line index after
|
||||||
|
/// which the new key should be inserted (last line in the platform's
|
||||||
|
/// block, or the platform header itself if the platform's body is
|
||||||
|
/// empty).
|
||||||
|
case platformPresentKeyMissing(insertAfter: Int)
|
||||||
|
/// One of the ancestor section headers is missing. The whole
|
||||||
|
/// scaffold needs to be appended.
|
||||||
|
case ancestorMissing
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func locateBlock(
|
||||||
|
in lines: [String],
|
||||||
|
platform: String,
|
||||||
|
key: String
|
||||||
|
) -> BlockLocation {
|
||||||
|
// Walk top-to-bottom looking for `gateway:` at indent 0.
|
||||||
|
guard let gatewayIdx = firstIndex(of: lines, headerLineEqualTo: "gateway:", indent: 0) else {
|
||||||
|
return .ancestorMissing
|
||||||
|
}
|
||||||
|
// Inside `gateway:`, find ` platforms:` at indent 2.
|
||||||
|
guard let platformsIdx = firstIndex(
|
||||||
|
of: lines,
|
||||||
|
after: gatewayIdx,
|
||||||
|
headerLineEqualTo: "platforms:",
|
||||||
|
indent: 2,
|
||||||
|
stopWhenIndentLessThan: 2
|
||||||
|
) else {
|
||||||
|
return .ancestorMissing
|
||||||
|
}
|
||||||
|
// Inside `platforms:`, find ` <platform>:` at indent 4.
|
||||||
|
guard let platformIdx = firstIndex(
|
||||||
|
of: lines,
|
||||||
|
after: platformsIdx,
|
||||||
|
headerLineEqualTo: "\(platform):",
|
||||||
|
indent: 4,
|
||||||
|
stopWhenIndentLessThan: 4
|
||||||
|
) else {
|
||||||
|
return .ancestorMissing
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inside the platform block, find `<key>:` at indent 6, OR the end
|
||||||
|
// of the platform's body if the key is missing.
|
||||||
|
var keyIdx: Int?
|
||||||
|
var lastBodyIdx = platformIdx
|
||||||
|
var i = platformIdx + 1
|
||||||
|
while i < lines.count {
|
||||||
|
let line = lines[i]
|
||||||
|
let indent = leadingSpaces(line)
|
||||||
|
let trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||||
|
if trimmed.isEmpty || trimmed.hasPrefix("#") {
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if indent < 6 {
|
||||||
|
// Out of the platform's block.
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if indent == 6 && trimmed == "\(key):" {
|
||||||
|
keyIdx = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
lastBodyIdx = i
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
guard let keyIdx else {
|
||||||
|
return .platformPresentKeyMissing(insertAfter: lastBodyIdx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Walk down the bullet rows until we leave the block (indent shrinks
|
||||||
|
// below the bullet indent OR we hit a sibling key at indent 6).
|
||||||
|
var endIdx = keyIdx
|
||||||
|
var j = keyIdx + 1
|
||||||
|
while j < lines.count {
|
||||||
|
let line = lines[j]
|
||||||
|
let trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||||
|
if trimmed.isEmpty || trimmed.hasPrefix("#") {
|
||||||
|
j += 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let indent = leadingSpaces(line)
|
||||||
|
// Block-style YAML allows bullets at the same indent as their
|
||||||
|
// parent key; tolerate 6-space `- item` rows alongside the
|
||||||
|
// canonical 8-space ones.
|
||||||
|
let isBullet = trimmed.hasPrefix("- ")
|
||||||
|
if isBullet && (indent == 8 || indent == 6) {
|
||||||
|
endIdx = j
|
||||||
|
j += 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Anything not a bullet at indent ≥ 8 ends the block.
|
||||||
|
if indent <= 6 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
// Indent > 8 with no bullet — unusual but tolerate (e.g. inline
|
||||||
|
// continuation). Treat as still in the block and advance.
|
||||||
|
endIdx = j
|
||||||
|
j += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return .found(keyIdx...endIdx)
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func replaceBlock(
|
||||||
|
in lines: [String],
|
||||||
|
blockRange: ClosedRange<Int>,
|
||||||
|
key: String,
|
||||||
|
items: [String],
|
||||||
|
blockIndent: Int,
|
||||||
|
itemIndent: Int
|
||||||
|
) -> String {
|
||||||
|
var newLines = Array(lines.prefix(blockRange.lowerBound))
|
||||||
|
if !items.isEmpty {
|
||||||
|
newLines.append("\(spaces(blockIndent))\(key):")
|
||||||
|
for item in items {
|
||||||
|
newLines.append("\(spaces(itemIndent))- \(yamlQuoteIfNeeded(item))")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Drop the old block but keep everything after it.
|
||||||
|
let tailStart = blockRange.upperBound + 1
|
||||||
|
if tailStart < lines.count {
|
||||||
|
newLines.append(contentsOf: lines.suffix(from: tailStart))
|
||||||
|
}
|
||||||
|
return newLines.joined(separator: "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func spliceNewKey(
|
||||||
|
lines: [String],
|
||||||
|
insertAfterLineIndex: Int,
|
||||||
|
key: String,
|
||||||
|
items: [String],
|
||||||
|
itemIndent: Int
|
||||||
|
) -> String {
|
||||||
|
var newLines = Array(lines.prefix(insertAfterLineIndex + 1))
|
||||||
|
newLines.append(" \(key):")
|
||||||
|
for item in items {
|
||||||
|
newLines.append("\(spaces(itemIndent))- \(yamlQuoteIfNeeded(item))")
|
||||||
|
}
|
||||||
|
if insertAfterLineIndex + 1 < lines.count {
|
||||||
|
newLines.append(contentsOf: lines.suffix(from: insertAfterLineIndex + 1))
|
||||||
|
}
|
||||||
|
return newLines.joined(separator: "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func appendScaffold(
|
||||||
|
yaml: String,
|
||||||
|
platform: String,
|
||||||
|
key: String,
|
||||||
|
items: [String]
|
||||||
|
) -> String {
|
||||||
|
var trimmed = yaml
|
||||||
|
// Ensure exactly one trailing newline before the appended block,
|
||||||
|
// so the scaffold sits on its own line cleanly.
|
||||||
|
while trimmed.hasSuffix("\n\n") {
|
||||||
|
trimmed.removeLast()
|
||||||
|
}
|
||||||
|
if !trimmed.isEmpty && !trimmed.hasSuffix("\n") {
|
||||||
|
trimmed.append("\n")
|
||||||
|
}
|
||||||
|
var lines: [String] = []
|
||||||
|
if !trimmed.isEmpty {
|
||||||
|
lines.append("") // blank separator
|
||||||
|
}
|
||||||
|
lines.append("gateway:")
|
||||||
|
lines.append(" platforms:")
|
||||||
|
lines.append(" \(platform):")
|
||||||
|
lines.append(" \(key):")
|
||||||
|
for item in items {
|
||||||
|
lines.append(" - \(yamlQuoteIfNeeded(item))")
|
||||||
|
}
|
||||||
|
lines.append("") // trailing newline so subsequent edits append cleanly
|
||||||
|
return trimmed + lines.joined(separator: "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - YAML scanning helpers
|
||||||
|
|
||||||
|
private static func leadingSpaces(_ line: String) -> Int {
|
||||||
|
var n = 0
|
||||||
|
for c in line {
|
||||||
|
if c == " " { n += 1 } else { break }
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Find the first line whose trimmed content equals `header` AND whose
|
||||||
|
/// leading-space count equals `indent`. Comment-only and blank lines
|
||||||
|
/// are skipped. Returns the line's index or `nil`.
|
||||||
|
private static func firstIndex(
|
||||||
|
of lines: [String],
|
||||||
|
headerLineEqualTo header: String,
|
||||||
|
indent: Int
|
||||||
|
) -> Int? {
|
||||||
|
for (i, line) in lines.enumerated() {
|
||||||
|
let trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||||
|
if trimmed.isEmpty || trimmed.hasPrefix("#") { continue }
|
||||||
|
if leadingSpaces(line) == indent && trimmed == header {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Scoped variant: search starts at `after + 1`, stops if a line at indent
|
||||||
|
/// `< stopWhenIndentLessThan` is encountered (we've left the parent block).
|
||||||
|
private static func firstIndex(
|
||||||
|
of lines: [String],
|
||||||
|
after: Int,
|
||||||
|
headerLineEqualTo header: String,
|
||||||
|
indent: Int,
|
||||||
|
stopWhenIndentLessThan: Int
|
||||||
|
) -> Int? {
|
||||||
|
var i = after + 1
|
||||||
|
while i < lines.count {
|
||||||
|
let line = lines[i]
|
||||||
|
let trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||||
|
if trimmed.isEmpty || trimmed.hasPrefix("#") {
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let lineIndent = leadingSpaces(line)
|
||||||
|
if lineIndent < stopWhenIndentLessThan {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if lineIndent == indent && trimmed == header {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func spaces(_ n: Int) -> String {
|
||||||
|
String(repeating: " ", count: n)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Quote a YAML scalar if it contains characters that the parser would
|
||||||
|
/// otherwise interpret as structure (colon, hash, leading at-sign, etc.).
|
||||||
|
/// Plain alphanumeric IDs (the common case for Slack channel IDs and
|
||||||
|
/// Telegram numeric chat IDs) are emitted unquoted.
|
||||||
|
private static func yamlQuoteIfNeeded(_ raw: String) -> String {
|
||||||
|
if raw.isEmpty { return "''" }
|
||||||
|
let needsQuoting = raw.contains(":")
|
||||||
|
|| raw.contains("#")
|
||||||
|
|| raw.contains("&")
|
||||||
|
|| raw.contains("*")
|
||||||
|
|| raw.contains(">")
|
||||||
|
|| raw.contains("|")
|
||||||
|
|| raw.first == "@"
|
||||||
|
|| raw.first == "-"
|
||||||
|
|| raw.first == " "
|
||||||
|
|| raw.last == " "
|
||||||
|
|| raw.first == "\""
|
||||||
|
|| raw.first == "'"
|
||||||
|
if !needsQuoting { return raw }
|
||||||
|
// Single-quote, escaping any embedded single quotes by doubling.
|
||||||
|
let escaped = raw.replacingOccurrences(of: "'", with: "''")
|
||||||
|
return "'\(escaped)'"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Cross-profile snapshot returned by `hermes gateway list --json` (Hermes
|
||||||
|
/// v0.13+). Each profile is one configured Messaging Gateway instance — most
|
||||||
|
/// users have a single `default` profile, but power users keep separate
|
||||||
|
/// profiles for work / personal / project-specific accounts.
|
||||||
|
public struct GatewayListSnapshot: Sendable, Equatable {
|
||||||
|
public struct ProfileEntry: Sendable, Equatable {
|
||||||
|
public let profile: String
|
||||||
|
public let isRunning: Bool
|
||||||
|
public let pid: Int?
|
||||||
|
public let platforms: [String] // platform names connected/configured
|
||||||
|
|
||||||
|
public init(
|
||||||
|
profile: String,
|
||||||
|
isRunning: Bool,
|
||||||
|
pid: Int?,
|
||||||
|
platforms: [String]
|
||||||
|
) {
|
||||||
|
self.profile = profile
|
||||||
|
self.isRunning = isRunning
|
||||||
|
self.pid = pid
|
||||||
|
self.platforms = platforms
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public let profiles: [ProfileEntry]
|
||||||
|
public let detectedAt: Date
|
||||||
|
|
||||||
|
public init(profiles: [ProfileEntry], detectedAt: Date = Date()) {
|
||||||
|
self.profiles = profiles
|
||||||
|
self.detectedAt = detectedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One-line digest for the Messaging Gateway page header. Format depends
|
||||||
|
/// on shape:
|
||||||
|
/// - 0 profiles: `"no profiles configured"`
|
||||||
|
/// - 1 profile, running: `"default profile · running · slack, telegram"`
|
||||||
|
/// - 1 profile, stopped: `"default profile · stopped"`
|
||||||
|
/// - >1 profile: `"3 profiles (2 running) · default: slack, telegram"`
|
||||||
|
public var headerDigest: String {
|
||||||
|
if profiles.isEmpty { return "no profiles configured" }
|
||||||
|
|
||||||
|
if profiles.count == 1 {
|
||||||
|
let p = profiles[0]
|
||||||
|
let state = p.isRunning ? "running" : "stopped"
|
||||||
|
if p.isRunning && !p.platforms.isEmpty {
|
||||||
|
let plats = p.platforms.joined(separator: ", ")
|
||||||
|
return "\(p.profile) profile · \(state) · \(plats)"
|
||||||
|
}
|
||||||
|
return "\(p.profile) profile · \(state)"
|
||||||
|
}
|
||||||
|
|
||||||
|
let runningCount = profiles.filter(\.isRunning).count
|
||||||
|
// Surface the platforms of the first running profile (or first profile
|
||||||
|
// if none are running) so the digest carries one specimen of context
|
||||||
|
// beyond just counts.
|
||||||
|
let highlight = profiles.first(where: \.isRunning) ?? profiles[0]
|
||||||
|
let platsClause: String
|
||||||
|
if highlight.platforms.isEmpty {
|
||||||
|
platsClause = ""
|
||||||
|
} else {
|
||||||
|
platsClause = " · \(highlight.profile): \(highlight.platforms.joined(separator: ", "))"
|
||||||
|
}
|
||||||
|
return "\(profiles.count) profiles (\(runningCount) running)\(platsClause)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pure parser + sync fetcher for `hermes gateway list --json`. Pre-v0.13
|
||||||
|
/// hosts exit non-zero on the unknown subcommand; the fetcher returns `nil`
|
||||||
|
/// in that case so the digest row hides itself.
|
||||||
|
///
|
||||||
|
/// The detection is **synchronous** — run from a `Task.detached` to avoid
|
||||||
|
/// blocking MainActor on remote SSH round-trips. The pure `parse(_:)`
|
||||||
|
/// helper has no I/O and can be used in tests against canned JSON.
|
||||||
|
public enum HermesGatewayListService {
|
||||||
|
|
||||||
|
/// Parse a JSON blob from `hermes gateway list --json` into a snapshot.
|
||||||
|
/// Tolerant of unknown keys; returns `nil` for unparseable / empty input.
|
||||||
|
///
|
||||||
|
/// // TODO(WS-5-Q3): the JSON shape below is the plan's best-guess.
|
||||||
|
/// Confirm against actual Hermes v0.13 output once available. Possible
|
||||||
|
/// alternative shapes:
|
||||||
|
/// - root array of profile objects (no `profiles` wrapper)
|
||||||
|
/// - `state` enum string instead of `running` bool
|
||||||
|
/// - `connected_platforms` instead of `platforms`
|
||||||
|
/// The parser is intentionally tolerant so a small shape change can be
|
||||||
|
/// absorbed by tweaking field names without breaking older fixtures.
|
||||||
|
public static func parse(_ json: Data) -> GatewayListSnapshot? {
|
||||||
|
guard !json.isEmpty,
|
||||||
|
let raw = try? JSONSerialization.jsonObject(with: json) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Accept both `{"profiles": [...]}` and a bare `[...]` of profiles.
|
||||||
|
let profilesArray: [Any]
|
||||||
|
if let dict = raw as? [String: Any], let arr = dict["profiles"] as? [Any] {
|
||||||
|
profilesArray = arr
|
||||||
|
} else if let arr = raw as? [Any] {
|
||||||
|
profilesArray = arr
|
||||||
|
} else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var entries: [GatewayListSnapshot.ProfileEntry] = []
|
||||||
|
for raw in profilesArray {
|
||||||
|
guard let obj = raw as? [String: Any] else { continue }
|
||||||
|
let profile = (obj["name"] as? String)
|
||||||
|
?? (obj["profile"] as? String)
|
||||||
|
?? "default"
|
||||||
|
let isRunning: Bool
|
||||||
|
if let v = obj["running"] as? Bool {
|
||||||
|
isRunning = v
|
||||||
|
} else if let s = obj["state"] as? String {
|
||||||
|
isRunning = s.lowercased() == "running"
|
||||||
|
} else {
|
||||||
|
isRunning = false
|
||||||
|
}
|
||||||
|
let pid = obj["pid"] as? Int
|
||||||
|
let platforms = (obj["platforms"] as? [String])
|
||||||
|
?? (obj["connected_platforms"] as? [String])
|
||||||
|
?? []
|
||||||
|
entries.append(GatewayListSnapshot.ProfileEntry(
|
||||||
|
profile: profile,
|
||||||
|
isRunning: isRunning,
|
||||||
|
pid: pid,
|
||||||
|
platforms: platforms
|
||||||
|
))
|
||||||
|
}
|
||||||
|
return GatewayListSnapshot(profiles: entries)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Synchronous fetch helper — call from a `Task.detached`. Returns
|
||||||
|
/// `nil` when the subcommand fails (pre-v0.13 host) or when the
|
||||||
|
/// output isn't parseable.
|
||||||
|
public static func fetch(context: ServerContext) -> GatewayListSnapshot? {
|
||||||
|
let transport = context.makeTransport()
|
||||||
|
let executable = context.paths.hermesBinary
|
||||||
|
do {
|
||||||
|
let result = try transport.runProcess(
|
||||||
|
executable: executable,
|
||||||
|
args: ["gateway", "list", "--json"],
|
||||||
|
stdin: nil,
|
||||||
|
timeout: 10
|
||||||
|
)
|
||||||
|
guard result.exitCode == 0 else { return nil }
|
||||||
|
return parse(result.stdout)
|
||||||
|
} catch {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -321,61 +321,6 @@ public actor KanbanService {
|
|||||||
try ensureSuccess(code: code, stdout: "", stderr: stderr, verb: "unlink")
|
try ensureSuccess(code: code, stdout: "", stderr: stderr, verb: "unlink")
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Hallucination gate (v0.13)
|
|
||||||
|
|
||||||
/// Mark a worker-created card as user-verified — flips
|
|
||||||
/// `hallucination_gate_status` from `pending` to `verified` so the
|
|
||||||
/// dispatcher can pick it up. The polling loop picks up the new
|
|
||||||
/// state on the next tick (and the VM optimistically clears the
|
|
||||||
/// pending banner immediately on the click).
|
|
||||||
///
|
|
||||||
/// **Pre-v0.13 hosts:** the verb doesn't exist; callers MUST gate
|
|
||||||
/// on `HermesCapabilities.hasKanbanDiagnostics` before invoking this.
|
|
||||||
/// A pre-v0.13 binary will surface the failure as
|
|
||||||
/// `KanbanError.nonZeroExit` with stderr containing "unknown command".
|
|
||||||
// TODO(WS-3-Q1): Confirm the exact CLI verb name for the
|
|
||||||
// hallucination-gate verify path against a v0.13 binary (`hermes
|
|
||||||
// kanban --help`). The v0.13 release notes describe "hallucination
|
|
||||||
// gate + recovery UX" but don't enumerate the verb name. This
|
|
||||||
// implementation assumes `hermes kanban verify <id>`. If Hermes ships
|
|
||||||
// it as `hermes kanban gate verify <id>`, `hermes kanban hallucination
|
|
||||||
// verify <id>`, or another name, update the args here. The Reject
|
|
||||||
// path does NOT depend on this verb (it routes through
|
|
||||||
// `archive` + a comment), so the recovery UX stays functional even
|
|
||||||
// if Verify is a stub for an early v0.13.x.
|
|
||||||
public func verify(taskId: String) async throws {
|
|
||||||
let args = ["kanban", "verify", taskId]
|
|
||||||
let (code, _, stderr) = await runHermes(args: args, timeout: 15)
|
|
||||||
try ensureSuccess(code: code, stdout: "", stderr: stderr, verb: "verify")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reject a worker-created card as a hallucinated reference. There
|
|
||||||
/// is no dedicated `kanban reject` verb in v0.13; the right action
|
|
||||||
/// per the v0.13 release notes is to archive the card (the work
|
|
||||||
/// doesn't exist) with a comment recording the rejection reason for
|
|
||||||
/// the audit trail. Routing this through the existing `comment` +
|
|
||||||
/// `archive` verbs keeps the wire shape stable across versions.
|
|
||||||
///
|
|
||||||
/// If a future Hermes adds a dedicated `kanban reject` verb, swap
|
|
||||||
/// the body here — the public surface stays "reject" returning Void.
|
|
||||||
public func rejectHallucinated(taskId: String) async throws {
|
|
||||||
// Best-effort comment first so the audit trail records the
|
|
||||||
// rejection. A failure here shouldn't block the archive — log
|
|
||||||
// and continue.
|
|
||||||
do {
|
|
||||||
try await comment(
|
|
||||||
taskId: taskId,
|
|
||||||
text: "Rejected as hallucinated (no underlying work).",
|
|
||||||
author: nil
|
|
||||||
)
|
|
||||||
} catch {
|
|
||||||
#if canImport(os)
|
|
||||||
Self.logger.warning("kanban reject: comment failed, proceeding to archive (\(error.localizedDescription, privacy: .public))")
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
try await archive(taskIds: [taskId])
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Drag-drop transition mapper
|
// MARK: - Drag-drop transition mapper
|
||||||
|
|
||||||
/// Map a board-level column transition to the right Hermes verb call.
|
/// Map a board-level column transition to the right Hermes verb call.
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
@testable import ScarfCore
|
||||||
|
|
||||||
|
/// Pure mapping tests for `GatewayAllowlistKind`. Locks down the (platform →
|
||||||
|
/// kind) table so a refactor doesn't accidentally drop a platform.
|
||||||
|
@Suite struct GatewayAllowlistKindTests {
|
||||||
|
|
||||||
|
@Test func mapsKnownPlatformsToCorrectKind() {
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "slack") == .channels)
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "mattermost") == .channels)
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "google-chat") == .channels)
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "telegram") == .chats)
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "whatsapp") == .chats)
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "matrix") == .rooms)
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "dingtalk") == .rooms)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func acceptsBothGoogleChatSpellings() {
|
||||||
|
// // TODO(WS-5-Q1) — both spellings round-trip until Hermes confirms
|
||||||
|
// the wire identifier.
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "google-chat") == .channels)
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "googlechat") == .channels)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func returnsNilForPlatformsWithoutAllowlist() {
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "cli") == nil)
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "yuanbao") == nil)
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "microsoft-teams") == nil)
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "discord") == nil)
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "signal") == nil)
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "homeassistant") == nil)
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "") == nil)
|
||||||
|
#expect(GatewayAllowlistKind.kind(for: "unknown") == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func yamlKeyMatchesHermesContract() {
|
||||||
|
#expect(GatewayAllowlistKind.channels.yamlKey == "allowed_channels")
|
||||||
|
#expect(GatewayAllowlistKind.chats.yamlKey == "allowed_chats")
|
||||||
|
#expect(GatewayAllowlistKind.rooms.yamlKey == "allowed_rooms")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func nounsAreUserFacingSafe() {
|
||||||
|
#expect(GatewayAllowlistKind.channels.noun == "channel")
|
||||||
|
#expect(GatewayAllowlistKind.chats.noun == "chat")
|
||||||
|
#expect(GatewayAllowlistKind.rooms.noun == "room")
|
||||||
|
#expect(GatewayAllowlistKind.channels.pluralNoun == "channels")
|
||||||
|
#expect(GatewayAllowlistKind.chats.pluralNoun == "chats")
|
||||||
|
#expect(GatewayAllowlistKind.rooms.pluralNoun == "rooms")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func placeholdersAreNonEmpty() {
|
||||||
|
// Smoke test — placeholder strings are advisory; we just don't want
|
||||||
|
// them silently emptied during a refactor.
|
||||||
|
#expect(!GatewayAllowlistKind.channels.inputPlaceholder.isEmpty)
|
||||||
|
#expect(!GatewayAllowlistKind.chats.inputPlaceholder.isEmpty)
|
||||||
|
#expect(!GatewayAllowlistKind.rooms.inputPlaceholder.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func gatewayPlatformSettingsItemsForKind() {
|
||||||
|
let s = GatewayPlatformSettings(
|
||||||
|
allowedChannels: ["C01"],
|
||||||
|
allowedChats: ["@user"],
|
||||||
|
allowedRooms: ["!room:matrix.org"]
|
||||||
|
)
|
||||||
|
#expect(s.items(for: .channels) == ["C01"])
|
||||||
|
#expect(s.items(for: .chats) == ["@user"])
|
||||||
|
#expect(s.items(for: .rooms) == ["!room:matrix.org"])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
@testable import ScarfCore
|
||||||
|
|
||||||
|
/// Round-trip + idempotence tests for `GatewayConfigWriter.setList`. Pure
|
||||||
|
/// `String` operations only — runs cleanly on Linux SwiftPM.
|
||||||
|
@Suite struct GatewayConfigWriterTests {
|
||||||
|
|
||||||
|
// MARK: - Insert
|
||||||
|
|
||||||
|
@Test func setListInsertsBlockOnEmpty() {
|
||||||
|
let yaml = ""
|
||||||
|
let updated = GatewayConfigWriter.setList(
|
||||||
|
in: yaml,
|
||||||
|
platform: "slack",
|
||||||
|
key: "allowed_channels",
|
||||||
|
items: ["C0123ABCD", "C0456EFGH"]
|
||||||
|
)
|
||||||
|
#expect(updated.contains("gateway:"))
|
||||||
|
#expect(updated.contains(" platforms:"))
|
||||||
|
#expect(updated.contains(" slack:"))
|
||||||
|
#expect(updated.contains(" allowed_channels:"))
|
||||||
|
#expect(updated.contains("- C0123ABCD"))
|
||||||
|
#expect(updated.contains("- C0456EFGH"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func setListAppendsScaffoldPreservingPriorContent() {
|
||||||
|
let yaml = """
|
||||||
|
model:
|
||||||
|
default: gpt-4o
|
||||||
|
provider: openai
|
||||||
|
"""
|
||||||
|
let updated = GatewayConfigWriter.setList(
|
||||||
|
in: yaml,
|
||||||
|
platform: "slack",
|
||||||
|
key: "allowed_channels",
|
||||||
|
items: ["C01"]
|
||||||
|
)
|
||||||
|
// Original content preserved verbatim at the top.
|
||||||
|
#expect(updated.contains("model:"))
|
||||||
|
#expect(updated.contains(" default: gpt-4o"))
|
||||||
|
#expect(updated.contains(" provider: openai"))
|
||||||
|
// New scaffold appended.
|
||||||
|
#expect(updated.contains("gateway:"))
|
||||||
|
#expect(updated.contains(" slack:"))
|
||||||
|
#expect(updated.contains("- C01"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Replace
|
||||||
|
|
||||||
|
@Test func setListReplacesExistingBlock() {
|
||||||
|
let yaml = """
|
||||||
|
gateway:
|
||||||
|
platforms:
|
||||||
|
slack:
|
||||||
|
allowed_channels:
|
||||||
|
- C_OLD_1
|
||||||
|
- C_OLD_2
|
||||||
|
"""
|
||||||
|
let updated = GatewayConfigWriter.setList(
|
||||||
|
in: yaml,
|
||||||
|
platform: "slack",
|
||||||
|
key: "allowed_channels",
|
||||||
|
items: ["C_NEW_1"]
|
||||||
|
)
|
||||||
|
#expect(updated.contains("- C_NEW_1"))
|
||||||
|
#expect(!updated.contains("- C_OLD_1"))
|
||||||
|
#expect(!updated.contains("- C_OLD_2"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func setListPreservesScalarSiblings() {
|
||||||
|
// The `busy_ack_enabled` scalar sibling of `allowed_channels` must
|
||||||
|
// stay byte-for-byte after a list-write to the same platform.
|
||||||
|
let yaml = """
|
||||||
|
gateway:
|
||||||
|
platforms:
|
||||||
|
slack:
|
||||||
|
allowed_channels:
|
||||||
|
- C_OLD
|
||||||
|
busy_ack_enabled: false
|
||||||
|
gateway_restart_notification: true
|
||||||
|
"""
|
||||||
|
let updated = GatewayConfigWriter.setList(
|
||||||
|
in: yaml,
|
||||||
|
platform: "slack",
|
||||||
|
key: "allowed_channels",
|
||||||
|
items: ["C_NEW"]
|
||||||
|
)
|
||||||
|
#expect(updated.contains("- C_NEW"))
|
||||||
|
#expect(!updated.contains("- C_OLD"))
|
||||||
|
// Scalars at the same indent must survive.
|
||||||
|
#expect(updated.contains("busy_ack_enabled: false"))
|
||||||
|
#expect(updated.contains("gateway_restart_notification: true"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func setListPreservesOtherPlatformsBlocks() {
|
||||||
|
// Editing slack must not touch matrix.
|
||||||
|
let yaml = """
|
||||||
|
gateway:
|
||||||
|
platforms:
|
||||||
|
slack:
|
||||||
|
allowed_channels:
|
||||||
|
- C_SLACK
|
||||||
|
matrix:
|
||||||
|
allowed_rooms:
|
||||||
|
- '!room1:matrix.org'
|
||||||
|
- '!room2:matrix.org'
|
||||||
|
"""
|
||||||
|
let updated = GatewayConfigWriter.setList(
|
||||||
|
in: yaml,
|
||||||
|
platform: "slack",
|
||||||
|
key: "allowed_channels",
|
||||||
|
items: ["C_SLACK_NEW"]
|
||||||
|
)
|
||||||
|
#expect(updated.contains("- C_SLACK_NEW"))
|
||||||
|
// Matrix block intact.
|
||||||
|
#expect(updated.contains(" matrix:"))
|
||||||
|
#expect(updated.contains("'!room1:matrix.org'"))
|
||||||
|
#expect(updated.contains("'!room2:matrix.org'"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Remove
|
||||||
|
|
||||||
|
@Test func setListWithEmptyItemsRemovesBlock() {
|
||||||
|
let yaml = """
|
||||||
|
gateway:
|
||||||
|
platforms:
|
||||||
|
slack:
|
||||||
|
allowed_channels:
|
||||||
|
- C01
|
||||||
|
- C02
|
||||||
|
busy_ack_enabled: true
|
||||||
|
"""
|
||||||
|
let updated = GatewayConfigWriter.setList(
|
||||||
|
in: yaml,
|
||||||
|
platform: "slack",
|
||||||
|
key: "allowed_channels",
|
||||||
|
items: []
|
||||||
|
)
|
||||||
|
// Block removed; sibling scalar preserved.
|
||||||
|
#expect(!updated.contains("allowed_channels:"))
|
||||||
|
#expect(!updated.contains("- C01"))
|
||||||
|
#expect(!updated.contains("- C02"))
|
||||||
|
#expect(updated.contains("busy_ack_enabled: true"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func setListWithEmptyItemsOnAbsentBlockIsNoOp() {
|
||||||
|
let yaml = """
|
||||||
|
model:
|
||||||
|
default: gpt-4o
|
||||||
|
"""
|
||||||
|
let updated = GatewayConfigWriter.setList(
|
||||||
|
in: yaml,
|
||||||
|
platform: "slack",
|
||||||
|
key: "allowed_channels",
|
||||||
|
items: []
|
||||||
|
)
|
||||||
|
#expect(updated == yaml)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Idempotence
|
||||||
|
|
||||||
|
@Test func setListIsIdempotent() {
|
||||||
|
let yaml = """
|
||||||
|
model:
|
||||||
|
default: gpt-4o
|
||||||
|
"""
|
||||||
|
let once = GatewayConfigWriter.setList(
|
||||||
|
in: yaml,
|
||||||
|
platform: "telegram",
|
||||||
|
key: "allowed_chats",
|
||||||
|
items: ["@alice", "@bob"]
|
||||||
|
)
|
||||||
|
let twice = GatewayConfigWriter.setList(
|
||||||
|
in: once,
|
||||||
|
platform: "telegram",
|
||||||
|
key: "allowed_chats",
|
||||||
|
items: ["@alice", "@bob"]
|
||||||
|
)
|
||||||
|
#expect(once == twice)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func setListReplaceThenReplaceIsStable() {
|
||||||
|
let yaml = ""
|
||||||
|
let a = GatewayConfigWriter.setList(
|
||||||
|
in: yaml, platform: "matrix", key: "allowed_rooms",
|
||||||
|
items: ["!a:m", "!b:m"]
|
||||||
|
)
|
||||||
|
let b = GatewayConfigWriter.setList(
|
||||||
|
in: a, platform: "matrix", key: "allowed_rooms",
|
||||||
|
items: ["!c:m"]
|
||||||
|
)
|
||||||
|
#expect(b.contains("- '!c:m'"))
|
||||||
|
#expect(!b.contains("'!a:m'"))
|
||||||
|
#expect(!b.contains("'!b:m'"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Quoting
|
||||||
|
|
||||||
|
@Test func setListQuotesItemsContainingColons() {
|
||||||
|
// Matrix room IDs contain `:` — must be single-quoted.
|
||||||
|
let yaml = ""
|
||||||
|
let updated = GatewayConfigWriter.setList(
|
||||||
|
in: yaml, platform: "matrix", key: "allowed_rooms",
|
||||||
|
items: ["!RoomId:matrix.org"]
|
||||||
|
)
|
||||||
|
#expect(updated.contains("'!RoomId:matrix.org'"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func setListQuotesItemsStartingWithAt() {
|
||||||
|
// Telegram usernames `@alice`.
|
||||||
|
let yaml = ""
|
||||||
|
let updated = GatewayConfigWriter.setList(
|
||||||
|
in: yaml, platform: "telegram", key: "allowed_chats",
|
||||||
|
items: ["@alice"]
|
||||||
|
)
|
||||||
|
#expect(updated.contains("'@alice'"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func setListLeavesPlainAlphanumericUnquoted() {
|
||||||
|
// Slack channel IDs are A-Z0-9 — emit unquoted for readability.
|
||||||
|
let yaml = ""
|
||||||
|
let updated = GatewayConfigWriter.setList(
|
||||||
|
in: yaml, platform: "slack", key: "allowed_channels",
|
||||||
|
items: ["C0123ABCD"]
|
||||||
|
)
|
||||||
|
#expect(updated.contains("- C0123ABCD"))
|
||||||
|
#expect(!updated.contains("'C0123ABCD'"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func setListEscapesEmbeddedSingleQuotes() {
|
||||||
|
let yaml = ""
|
||||||
|
let updated = GatewayConfigWriter.setList(
|
||||||
|
in: yaml, platform: "slack", key: "allowed_channels",
|
||||||
|
items: ["weird:'name"]
|
||||||
|
)
|
||||||
|
// Embedded single quote doubled per YAML spec.
|
||||||
|
#expect(updated.contains("'weird:''name'"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Insertion when ancestors exist but key is absent
|
||||||
|
|
||||||
|
@Test func setListInsertsKeyUnderExistingPlatformBlock() {
|
||||||
|
// `gateway → platforms → slack` exists with a busy_ack_enabled
|
||||||
|
// scalar; `allowed_channels` is missing. Add it without disturbing
|
||||||
|
// the scalar sibling.
|
||||||
|
let yaml = """
|
||||||
|
gateway:
|
||||||
|
platforms:
|
||||||
|
slack:
|
||||||
|
busy_ack_enabled: false
|
||||||
|
"""
|
||||||
|
let updated = GatewayConfigWriter.setList(
|
||||||
|
in: yaml, platform: "slack", key: "allowed_channels",
|
||||||
|
items: ["C42"]
|
||||||
|
)
|
||||||
|
#expect(updated.contains("busy_ack_enabled: false"))
|
||||||
|
#expect(updated.contains("allowed_channels:"))
|
||||||
|
#expect(updated.contains("- C42"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Round-trip with the YAML loader
|
||||||
|
|
||||||
|
@Test func roundTripsThroughHermesConfigYAMLLoader() {
|
||||||
|
// Write a list, then parse the result through HermesConfig+YAML and
|
||||||
|
// confirm we read back what we wrote.
|
||||||
|
var yaml = ""
|
||||||
|
yaml = GatewayConfigWriter.setList(
|
||||||
|
in: yaml, platform: "slack", key: "allowed_channels",
|
||||||
|
items: ["C01", "C02"]
|
||||||
|
)
|
||||||
|
let cfg = HermesConfig(yaml: yaml)
|
||||||
|
let block = cfg.gatewayPlatforms["slack"]
|
||||||
|
#expect(block?.allowedChannels == ["C01", "C02"])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
@testable import ScarfCore
|
||||||
|
|
||||||
|
/// Parser tests for `hermes gateway list --json`. Pure — no transport, no
|
||||||
|
/// process calls.
|
||||||
|
@Suite struct HermesGatewayListServiceTests {
|
||||||
|
|
||||||
|
private func data(_ s: String) -> Data { s.data(using: .utf8)! }
|
||||||
|
|
||||||
|
@Test func parsesSingleProfileSinglePlatform() {
|
||||||
|
let json = data(#"""
|
||||||
|
{"profiles":[{"name":"default","running":true,"pid":1234,
|
||||||
|
"platforms":["slack","telegram"]}]}
|
||||||
|
"""#)
|
||||||
|
let snap = HermesGatewayListService.parse(json)
|
||||||
|
#expect(snap?.profiles.count == 1)
|
||||||
|
#expect(snap?.profiles[0].profile == "default")
|
||||||
|
#expect(snap?.profiles[0].pid == 1234)
|
||||||
|
#expect(snap?.profiles[0].isRunning == true)
|
||||||
|
#expect(snap?.profiles[0].platforms == ["slack", "telegram"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func parsesMultipleProfiles() {
|
||||||
|
let json = data(#"""
|
||||||
|
{"profiles":[
|
||||||
|
{"name":"work","running":true,"pid":2001,"platforms":["slack"]},
|
||||||
|
{"name":"personal","running":false,"platforms":["telegram"]}
|
||||||
|
]}
|
||||||
|
"""#)
|
||||||
|
let snap = HermesGatewayListService.parse(json)
|
||||||
|
#expect(snap?.profiles.count == 2)
|
||||||
|
#expect(snap?.profiles[0].profile == "work")
|
||||||
|
#expect(snap?.profiles[0].isRunning == true)
|
||||||
|
#expect(snap?.profiles[1].profile == "personal")
|
||||||
|
#expect(snap?.profiles[1].isRunning == false)
|
||||||
|
#expect(snap?.profiles[1].pid == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func parsesBareArrayShape() {
|
||||||
|
// Tolerance for a top-level array (no `profiles` wrapper).
|
||||||
|
let json = data(#"""
|
||||||
|
[{"name":"default","running":true,"pid":42,"platforms":["discord"]}]
|
||||||
|
"""#)
|
||||||
|
let snap = HermesGatewayListService.parse(json)
|
||||||
|
#expect(snap?.profiles.count == 1)
|
||||||
|
#expect(snap?.profiles[0].profile == "default")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func toleratesAlternateFieldNames() {
|
||||||
|
// `profile` instead of `name`, `state` instead of `running`,
|
||||||
|
// `connected_platforms` instead of `platforms` — defensive defaults
|
||||||
|
// keep the parser happy if Hermes ships any of these.
|
||||||
|
let json = data(#"""
|
||||||
|
{"profiles":[{"profile":"alt","state":"running","pid":7,
|
||||||
|
"connected_platforms":["matrix"]}]}
|
||||||
|
"""#)
|
||||||
|
let snap = HermesGatewayListService.parse(json)
|
||||||
|
#expect(snap?.profiles[0].profile == "alt")
|
||||||
|
#expect(snap?.profiles[0].isRunning == true)
|
||||||
|
#expect(snap?.profiles[0].platforms == ["matrix"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func returnsNilOnEmptyData() {
|
||||||
|
#expect(HermesGatewayListService.parse(Data()) == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func returnsNilOnUnparseableJSON() {
|
||||||
|
let json = data("not-json")
|
||||||
|
#expect(HermesGatewayListService.parse(json) == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func returnsEmptySnapshotOnEmptyProfilesArray() {
|
||||||
|
let json = data(#"{"profiles":[]}"#)
|
||||||
|
let snap = HermesGatewayListService.parse(json)
|
||||||
|
#expect(snap?.profiles.isEmpty == true)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func toleratesUnknownKeys() {
|
||||||
|
// Forward-compat: a future v0.13.x Hermes adds extra fields, parser
|
||||||
|
// still works.
|
||||||
|
let json = data(#"""
|
||||||
|
{"profiles":[{"name":"default","running":true,"platforms":["slack"],
|
||||||
|
"future_field":"value","another":42}]}
|
||||||
|
"""#)
|
||||||
|
let snap = HermesGatewayListService.parse(json)
|
||||||
|
#expect(snap?.profiles[0].profile == "default")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - headerDigest
|
||||||
|
|
||||||
|
@Test func headerDigestEmptyProfiles() {
|
||||||
|
let snap = GatewayListSnapshot(profiles: [])
|
||||||
|
#expect(snap.headerDigest == "no profiles configured")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func headerDigestSingleProfileRunning() {
|
||||||
|
let snap = GatewayListSnapshot(profiles: [
|
||||||
|
.init(profile: "default", isRunning: true, pid: 100,
|
||||||
|
platforms: ["slack", "telegram"])
|
||||||
|
])
|
||||||
|
#expect(snap.headerDigest == "default profile · running · slack, telegram")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func headerDigestSingleProfileStopped() {
|
||||||
|
let snap = GatewayListSnapshot(profiles: [
|
||||||
|
.init(profile: "default", isRunning: false, pid: nil, platforms: [])
|
||||||
|
])
|
||||||
|
#expect(snap.headerDigest == "default profile · stopped")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func headerDigestMultipleProfilesSomeRunning() {
|
||||||
|
let snap = GatewayListSnapshot(profiles: [
|
||||||
|
.init(profile: "work", isRunning: true, pid: 1, platforms: ["slack"]),
|
||||||
|
.init(profile: "home", isRunning: false, pid: nil, platforms: ["matrix"]),
|
||||||
|
.init(profile: "extra", isRunning: true, pid: 2, platforms: [])
|
||||||
|
])
|
||||||
|
// 3 profiles total, 2 running, surface first running profile's
|
||||||
|
// platform list as the highlight.
|
||||||
|
#expect(snap.headerDigest == "3 profiles (2 running) · work: slack")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func headerDigestMultipleProfilesNoneRunning() {
|
||||||
|
let snap = GatewayListSnapshot(profiles: [
|
||||||
|
.init(profile: "a", isRunning: false, pid: nil, platforms: ["slack"]),
|
||||||
|
.init(profile: "b", isRunning: false, pid: nil, platforms: ["matrix"])
|
||||||
|
])
|
||||||
|
// No running profile — fall back to the first profile's platforms.
|
||||||
|
#expect(snap.headerDigest == "2 profiles (0 running) · a: slack")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -327,196 +327,4 @@ import Foundation
|
|||||||
#expect(stats.glanceString.isEmpty)
|
#expect(stats.glanceString.isEmpty)
|
||||||
#expect(stats.activeCount == 0)
|
#expect(stats.activeCount == 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - v0.13 (Hermes 2026.5.7) tolerant decode
|
|
||||||
//
|
|
||||||
// The contract these tests pin: a v0.13 host's task / run / detail
|
|
||||||
// JSON decodes successfully WITH the new fields populated, AND a
|
|
||||||
// pre-v0.13 (v0.12) host's task / run / detail JSON decodes
|
|
||||||
// successfully WITHOUT the new fields (everything resolves to nil
|
|
||||||
// or empty). Drift from this pair = a regression that bites every
|
|
||||||
// user not yet on Hermes v0.13.
|
|
||||||
|
|
||||||
@Test func decodeV013TaskFields() throws {
|
|
||||||
let json = """
|
|
||||||
{
|
|
||||||
"id": "t_v013",
|
|
||||||
"title": "v0.13 task",
|
|
||||||
"status": "blocked",
|
|
||||||
"max_retries": 5,
|
|
||||||
"auto_blocked_reason": "worker exited without `kanban complete`",
|
|
||||||
"hallucination_gate_status": "pending",
|
|
||||||
"diagnostics": [
|
|
||||||
{"kind": "worker_exit_no_complete", "message": "exit code 0 with no complete call", "detected_at": 1778160614},
|
|
||||||
{"kind": "darwin_zombie_detected", "detected_at": "2026-05-09T12:00:00Z"}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
let task = try JSONDecoder().decode(HermesKanbanTask.self, from: Data(json.utf8))
|
|
||||||
#expect(task.maxRetries == 5)
|
|
||||||
#expect(task.autoBlockedReason?.contains("kanban complete") == true)
|
|
||||||
#expect(task.hallucinationGateStatus == "pending")
|
|
||||||
#expect(task.diagnostics.count == 2)
|
|
||||||
#expect(task.diagnostics.first?.kind == "worker_exit_no_complete")
|
|
||||||
#expect(task.diagnostics.last?.detectedAt?.contains("2026") == true)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func decodeV012TaskHasNoNewFields() throws {
|
|
||||||
// The most damaging failure mode is a v0.12 user upgrading Scarf
|
|
||||||
// and having the board stop loading because a v0.13-only field
|
|
||||||
// is required. Pin the contract.
|
|
||||||
let json = """
|
|
||||||
{"id": "t_legacy", "title": "v0.12 task", "status": "ready"}
|
|
||||||
"""
|
|
||||||
let task = try JSONDecoder().decode(HermesKanbanTask.self, from: Data(json.utf8))
|
|
||||||
#expect(task.maxRetries == nil)
|
|
||||||
#expect(task.autoBlockedReason == nil)
|
|
||||||
#expect(task.hallucinationGateStatus == nil)
|
|
||||||
#expect(task.diagnostics.isEmpty)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func decodeMalformedDiagnosticTolerated() throws {
|
|
||||||
// If Hermes emits a malformed diagnostics value, the rest of the
|
|
||||||
// task should still decode. We use try? on the diagnostics decode
|
|
||||||
// so a single bad entry doesn't reject the whole row.
|
|
||||||
let json = """
|
|
||||||
{
|
|
||||||
"id": "t_x",
|
|
||||||
"title": "x",
|
|
||||||
"status": "ready",
|
|
||||||
"diagnostics": "not-an-array"
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
let task = try JSONDecoder().decode(HermesKanbanTask.self, from: Data(json.utf8))
|
|
||||||
#expect(task.id == "t_x")
|
|
||||||
// Diagnostics field couldn't decode — treat as empty.
|
|
||||||
#expect(task.diagnostics.isEmpty)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func hallucinationGateMirrorMapsKnownValues() {
|
|
||||||
#expect(KanbanHallucinationGate.from("pending") == .pending)
|
|
||||||
#expect(KanbanHallucinationGate.from("verified") == .verified)
|
|
||||||
#expect(KanbanHallucinationGate.from("REJECTED") == .rejected) // case-insensitive
|
|
||||||
#expect(KanbanHallucinationGate.from(nil) == nil)
|
|
||||||
#expect(KanbanHallucinationGate.from("") == nil)
|
|
||||||
// Unknown wire values fall through to nil so the banner stays
|
|
||||||
// hidden; future Hermes versions can add `quarantined` etc.
|
|
||||||
// without a Scarf release.
|
|
||||||
#expect(KanbanHallucinationGate.from("quarantined") == nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func diagnosticKindMirrorMapsKnownValues() {
|
|
||||||
#expect(KanbanDiagnosticKind.from("heartbeat_stalled") == .heartbeatStalled)
|
|
||||||
#expect(KanbanDiagnosticKind.from("DARWIN_ZOMBIE_DETECTED") == .darwinZombieDetected)
|
|
||||||
// Unknown kinds fall through to .unknown so views can render
|
|
||||||
// the raw string verbatim.
|
|
||||||
#expect(KanbanDiagnosticKind.from("future_kind_v014") == .unknown)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func diagnosticSeverityMapping() {
|
|
||||||
#expect(KanbanDiagnosticKind.retryCapHit.severity == .danger)
|
|
||||||
#expect(KanbanDiagnosticKind.darwinZombieDetected.severity == .danger)
|
|
||||||
#expect(KanbanDiagnosticKind.heartbeatStalled.severity == .warning)
|
|
||||||
#expect(KanbanDiagnosticKind.workerExitNoComplete.severity == .warning)
|
|
||||||
#expect(KanbanDiagnosticKind.unknown.severity == .neutral)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func createRequestArgvIncludesMaxRetries() {
|
|
||||||
let req = KanbanCreateRequest(title: "t", maxRetries: 5)
|
|
||||||
let argv = req.argv()
|
|
||||||
#expect(argv.contains("--max-retries"))
|
|
||||||
#expect(argv.contains("5"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func createRequestArgvOmitsMaxRetriesWhenAbsent() {
|
|
||||||
let req = KanbanCreateRequest(title: "t")
|
|
||||||
let argv = req.argv()
|
|
||||||
#expect(!argv.contains("--max-retries"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func decodeRunWithDiagnostics() throws {
|
|
||||||
let json = """
|
|
||||||
{
|
|
||||||
"id": 1,
|
|
||||||
"task_id": "t_x",
|
|
||||||
"status": "failed",
|
|
||||||
"started_at": 1778160000,
|
|
||||||
"ended_at": 1778160300,
|
|
||||||
"outcome": "crashed",
|
|
||||||
"error": "OOM",
|
|
||||||
"diagnostics": [
|
|
||||||
{"kind": "retry_cap_hit", "message": "3/3 retries exhausted"}
|
|
||||||
],
|
|
||||||
"failure_count": 3
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
let run = try JSONDecoder().decode(HermesKanbanRun.self, from: Data(json.utf8))
|
|
||||||
#expect(run.diagnostics.count == 1)
|
|
||||||
#expect(run.diagnostics.first?.kind == "retry_cap_hit")
|
|
||||||
#expect(run.failureCount == 3)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func decodeRunWithoutDiagnostics() throws {
|
|
||||||
// v0.12 run row — no diagnostics, no failure_count, must still
|
|
||||||
// decode cleanly.
|
|
||||||
let json = """
|
|
||||||
{"id": 1, "task_id": "t_x", "status": "running", "started_at": 1778160000}
|
|
||||||
"""
|
|
||||||
let run = try JSONDecoder().decode(HermesKanbanRun.self, from: Data(json.utf8))
|
|
||||||
#expect(run.diagnostics.isEmpty)
|
|
||||||
#expect(run.failureCount == nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func taskDetailMergesEnvelopeAndTaskDiagnostics() throws {
|
|
||||||
// Hermes's wire shape may put diagnostics on the task envelope OR
|
|
||||||
// on the inner task. `allDiagnostics` dedupes by (kind, detected_at)
|
|
||||||
// so a server emitting both sides doesn't surface dupes.
|
|
||||||
let json = """
|
|
||||||
{
|
|
||||||
"task": {
|
|
||||||
"id": "t_y",
|
|
||||||
"title": "y",
|
|
||||||
"status": "blocked",
|
|
||||||
"diagnostics": [
|
|
||||||
{"kind": "heartbeat_stalled", "detected_at": "2026-05-09T12:00:00Z"}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"comments": [],
|
|
||||||
"events": [],
|
|
||||||
"diagnostics": [
|
|
||||||
{"kind": "heartbeat_stalled", "detected_at": "2026-05-09T12:00:00Z"},
|
|
||||||
{"kind": "retry_cap_hit"}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
let detail = try JSONDecoder().decode(HermesKanbanTaskDetail.self, from: Data(json.utf8))
|
|
||||||
let merged = detail.allDiagnostics
|
|
||||||
#expect(merged.count == 2)
|
|
||||||
#expect(merged.contains(where: { $0.kind == "heartbeat_stalled" }))
|
|
||||||
#expect(merged.contains(where: { $0.kind == "retry_cap_hit" }))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func taskDetailWithoutEnvelopeDiagnosticsDecodes() throws {
|
|
||||||
// Pre-v0.13 task detail — no envelope diagnostics. Must decode.
|
|
||||||
let json = """
|
|
||||||
{
|
|
||||||
"task": {"id": "t_z", "title": "z", "status": "ready"},
|
|
||||||
"comments": [],
|
|
||||||
"events": []
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
let detail = try JSONDecoder().decode(HermesKanbanTaskDetail.self, from: Data(json.utf8))
|
|
||||||
#expect(detail.envelopeDiagnostics == nil)
|
|
||||||
#expect(detail.allDiagnostics.isEmpty)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func diagnosticDecodesUnixTimestamp() throws {
|
|
||||||
let json = """
|
|
||||||
{"kind": "spawn_failure", "detected_at": 1778160614}
|
|
||||||
"""
|
|
||||||
let diag = try JSONDecoder().decode(HermesKanbanDiagnostic.self, from: Data(json.utf8))
|
|
||||||
#expect(diag.kind == "spawn_failure")
|
|
||||||
// Decoder normalizes Unix int → ISO-8601 string.
|
|
||||||
#expect(diag.detectedAt?.contains("2026") == true)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -228,6 +228,87 @@ import Foundation
|
|||||||
#expect(c.timezone == "America/New_York")
|
#expect(c.timezone == "America/New_York")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - v0.13 gateway.platforms.<platform> block
|
||||||
|
|
||||||
|
@Test func gatewayPlatformsEmptyByDefault() {
|
||||||
|
let c = HermesConfig(yaml: "")
|
||||||
|
#expect(c.gatewayPlatforms.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func parsesGatewayAllowlistsForSlack() {
|
||||||
|
let yaml = """
|
||||||
|
gateway:
|
||||||
|
platforms:
|
||||||
|
slack:
|
||||||
|
allowed_channels:
|
||||||
|
- C01
|
||||||
|
- C02
|
||||||
|
busy_ack_enabled: false
|
||||||
|
gateway_restart_notification: true
|
||||||
|
slash_command_notice_ttl_seconds: 120
|
||||||
|
"""
|
||||||
|
let cfg = HermesConfig(yaml: yaml)
|
||||||
|
let block = cfg.gatewayPlatforms["slack"]
|
||||||
|
#expect(block?.allowedChannels == ["C01", "C02"])
|
||||||
|
#expect(block?.busyAckEnabled == false)
|
||||||
|
#expect(block?.gatewayRestartNotification == true)
|
||||||
|
#expect(block?.slashCommandNoticeTTLSeconds == 120)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func parsesGatewayAllowlistsForTelegramAndMatrix() {
|
||||||
|
let yaml = """
|
||||||
|
gateway:
|
||||||
|
platforms:
|
||||||
|
telegram:
|
||||||
|
allowed_chats:
|
||||||
|
- '@alice'
|
||||||
|
- '12345'
|
||||||
|
matrix:
|
||||||
|
allowed_rooms:
|
||||||
|
- '!room:matrix.org'
|
||||||
|
"""
|
||||||
|
let cfg = HermesConfig(yaml: yaml)
|
||||||
|
#expect(cfg.gatewayPlatforms["telegram"]?.allowedChats == ["@alice", "12345"])
|
||||||
|
#expect(cfg.gatewayPlatforms["matrix"]?.allowedRooms == ["!room:matrix.org"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func gatewayBlockCoexistsWithLegacyPlatformBlocks() {
|
||||||
|
// Regression: legacy `platforms.slack.reply_to_mode` and
|
||||||
|
// `matrix.require_mention` must keep parsing when the new
|
||||||
|
// `gateway:` block is also present — no key collisions.
|
||||||
|
let yaml = """
|
||||||
|
platforms:
|
||||||
|
slack:
|
||||||
|
reply_to_mode: all
|
||||||
|
matrix:
|
||||||
|
require_mention: false
|
||||||
|
gateway:
|
||||||
|
platforms:
|
||||||
|
slack:
|
||||||
|
allowed_channels:
|
||||||
|
- C01
|
||||||
|
"""
|
||||||
|
let cfg = HermesConfig(yaml: yaml)
|
||||||
|
#expect(cfg.slack.replyToMode == "all")
|
||||||
|
#expect(cfg.matrix.requireMention == false)
|
||||||
|
#expect(cfg.gatewayPlatforms["slack"]?.allowedChannels == ["C01"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func gatewayPlatformsSkipsPlatformsWithoutV013Keys() {
|
||||||
|
// The `gateway:` block exists but only Slack has a v0.13 key —
|
||||||
|
// platforms without keys must NOT appear in `gatewayPlatforms`.
|
||||||
|
let yaml = """
|
||||||
|
gateway:
|
||||||
|
platforms:
|
||||||
|
slack:
|
||||||
|
busy_ack_enabled: true
|
||||||
|
"""
|
||||||
|
let cfg = HermesConfig(yaml: yaml)
|
||||||
|
#expect(cfg.gatewayPlatforms["slack"] != nil)
|
||||||
|
#expect(cfg.gatewayPlatforms["mattermost"] == nil)
|
||||||
|
#expect(cfg.gatewayPlatforms["telegram"] == nil)
|
||||||
|
}
|
||||||
|
|
||||||
@Test func cronScheduleMemberwise() {
|
@Test func cronScheduleMemberwise() {
|
||||||
let s = CronSchedule(
|
let s = CronSchedule(
|
||||||
kind: "cron",
|
kind: "cron",
|
||||||
|
|||||||
@@ -254,6 +254,47 @@ struct HermesFileService: Sendable {
|
|||||||
cooldownSeconds: int("platforms.homeassistant.extra.cooldown_seconds", default: 30)
|
cooldownSeconds: int("platforms.homeassistant.extra.cooldown_seconds", default: 30)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// -- v0.13: per-platform Messaging Gateway settings --------------
|
||||||
|
// Mirrors the canonical extractor in
|
||||||
|
// `ScarfCore/Parsing/HermesConfig+YAML.swift`. Behaviour parity
|
||||||
|
// matters: both parsers must populate `gatewayPlatforms` the same
|
||||||
|
// way so iOS and Mac surfaces stay in lockstep.
|
||||||
|
// TODO(WS-5-Q2): YAML key path unverified — see the comment in the
|
||||||
|
// ScarfCore extractor for the resolution path.
|
||||||
|
let gatewayAllowlistPlatforms = [
|
||||||
|
"slack", "mattermost", "google-chat",
|
||||||
|
"telegram", "whatsapp",
|
||||||
|
"matrix", "dingtalk",
|
||||||
|
]
|
||||||
|
var gatewayPlatforms: [String: GatewayPlatformSettings] = [:]
|
||||||
|
for platform in gatewayAllowlistPlatforms {
|
||||||
|
let prefix = "gateway.platforms.\(platform)."
|
||||||
|
let allowedChannels = lists[prefix + "allowed_channels"] ?? []
|
||||||
|
let allowedChats = lists[prefix + "allowed_chats"] ?? []
|
||||||
|
let allowedRooms = lists[prefix + "allowed_rooms"] ?? []
|
||||||
|
let busy = bool(prefix + "busy_ack_enabled", default: true)
|
||||||
|
let restartNotice = bool(prefix + "gateway_restart_notification",
|
||||||
|
default: false)
|
||||||
|
let ttl = int(prefix + "slash_command_notice_ttl_seconds",
|
||||||
|
default: 0)
|
||||||
|
let isEmpty = allowedChannels.isEmpty
|
||||||
|
&& allowedChats.isEmpty
|
||||||
|
&& allowedRooms.isEmpty
|
||||||
|
&& values[prefix + "busy_ack_enabled"] == nil
|
||||||
|
&& values[prefix + "gateway_restart_notification"] == nil
|
||||||
|
&& values[prefix + "slash_command_notice_ttl_seconds"] == nil
|
||||||
|
if !isEmpty {
|
||||||
|
gatewayPlatforms[platform] = GatewayPlatformSettings(
|
||||||
|
allowedChannels: allowedChannels,
|
||||||
|
allowedChats: allowedChats,
|
||||||
|
allowedRooms: allowedRooms,
|
||||||
|
busyAckEnabled: busy,
|
||||||
|
gatewayRestartNotification: restartNotice,
|
||||||
|
slashCommandNoticeTTLSeconds: ttl
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return HermesConfig(
|
return HermesConfig(
|
||||||
model: str("model.default", default: "unknown"),
|
model: str("model.default", default: "unknown"),
|
||||||
provider: str("model.provider", default: "unknown"),
|
provider: str("model.provider", default: "unknown"),
|
||||||
@@ -313,7 +354,8 @@ struct HermesFileService: Sendable {
|
|||||||
homeAssistant: homeAssistant,
|
homeAssistant: homeAssistant,
|
||||||
cacheTTL: str("prompt_caching.cache_ttl", default: "5m"),
|
cacheTTL: str("prompt_caching.cache_ttl", default: "5m"),
|
||||||
redactionEnabled: bool("redaction.enabled", default: false),
|
redactionEnabled: bool("redaction.enabled", default: false),
|
||||||
runtimeMetadataFooter: bool("agent.runtime_metadata_footer", default: false)
|
runtimeMetadataFooter: bool("agent.runtime_metadata_footer", default: false),
|
||||||
|
gatewayPlatforms: gatewayPlatforms
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import ScarfCore
|
import ScarfCore
|
||||||
|
|
||||||
struct GatewayInfo {
|
// **Local rename for v0.13 / WS-5.** The user-facing label is "Messaging
|
||||||
|
// Gateway"; the type names mirror that. The `SidebarSection.gateway` enum
|
||||||
|
// case + `gateway_state.json` / `gateway.log` paths intentionally stay
|
||||||
|
// unchanged — those aren't user-facing strings, and renaming them would
|
||||||
|
// churn unrelated callers without changing what users see.
|
||||||
|
|
||||||
|
struct MessagingGatewayInfo {
|
||||||
let pid: Int?
|
let pid: Int?
|
||||||
let state: String
|
let state: String
|
||||||
let exitReason: String?
|
let exitReason: String?
|
||||||
@@ -37,32 +43,48 @@ struct PendingPairing: Identifiable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Observable
|
@Observable
|
||||||
final class GatewayViewModel {
|
@MainActor
|
||||||
|
final class MessagingGatewayViewModel {
|
||||||
let context: ServerContext
|
let context: ServerContext
|
||||||
|
/// Capability snapshot at view-init time. Read for the v0.13 cross-
|
||||||
|
/// profile digest (`hasGatewayList`); other v0.13 surfaces live on
|
||||||
|
/// per-platform setup views. `.empty` is fine outside the per-server
|
||||||
|
/// `ContextBoundRoot` (Previews, smoke tests).
|
||||||
|
let capabilities: HermesCapabilities
|
||||||
|
|
||||||
init(context: ServerContext = .local) {
|
init(context: ServerContext = .local, capabilities: HermesCapabilities = .empty) {
|
||||||
self.context = context
|
self.context = context
|
||||||
|
self.capabilities = capabilities
|
||||||
}
|
}
|
||||||
|
|
||||||
var gateway = GatewayInfo(pid: nil, state: "unknown", exitReason: nil, startTime: nil, updatedAt: nil, platforms: [], isLoaded: false, isStale: false)
|
var gateway = MessagingGatewayInfo(pid: nil, state: "unknown", exitReason: nil, startTime: nil, updatedAt: nil, platforms: [], isLoaded: false, isStale: false)
|
||||||
var approvedUsers: [PairedUser] = []
|
var approvedUsers: [PairedUser] = []
|
||||||
var pendingPairings: [PendingPairing] = []
|
var pendingPairings: [PendingPairing] = []
|
||||||
var isLoading = false
|
var isLoading = false
|
||||||
var actionMessage: String?
|
var actionMessage: String?
|
||||||
|
/// `hermes gateway list --json` snapshot. `nil` when the verb fails
|
||||||
|
/// (pre-v0.13 host or no profiles registered yet) — the digest row
|
||||||
|
/// hides itself in that case.
|
||||||
|
var gatewayList: GatewayListSnapshot?
|
||||||
|
|
||||||
func load() {
|
func load() {
|
||||||
isLoading = true
|
isLoading = true
|
||||||
let ctx = context
|
let ctx = context
|
||||||
|
let caps = capabilities
|
||||||
Task.detached { [weak self] in
|
Task.detached { [weak self] in
|
||||||
// Two sync transport calls + two CLI invocations — substantial
|
// Two sync transport calls + two CLI invocations — substantial
|
||||||
// remote latency. Detach the whole load and commit at the end.
|
// remote latency. Detach the whole load and commit at the end.
|
||||||
let status = Self.fetchGatewayStatus(context: ctx)
|
let status = Self.fetchGatewayStatus(context: ctx)
|
||||||
let pairing = Self.fetchPairing(context: ctx)
|
let pairing = Self.fetchPairing(context: ctx)
|
||||||
|
let listSnap = caps.hasGatewayList
|
||||||
|
? HermesGatewayListService.fetch(context: ctx)
|
||||||
|
: nil
|
||||||
await MainActor.run { [weak self] in
|
await MainActor.run { [weak self] in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
self.gateway = status
|
self.gateway = status
|
||||||
self.approvedUsers = pairing.approved
|
self.approvedUsers = pairing.approved
|
||||||
self.pendingPairings = pairing.pending
|
self.pendingPairings = pairing.pending
|
||||||
|
self.gatewayList = listSnap
|
||||||
self.isLoading = false
|
self.isLoading = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -70,7 +92,7 @@ final class GatewayViewModel {
|
|||||||
|
|
||||||
/// Static form of the gateway-status walk so the detached load can call
|
/// Static form of the gateway-status walk so the detached load can call
|
||||||
/// it without bouncing back to MainActor.
|
/// it without bouncing back to MainActor.
|
||||||
nonisolated private static func fetchGatewayStatus(context: ServerContext) -> GatewayInfo {
|
nonisolated private static func fetchGatewayStatus(context: ServerContext) -> MessagingGatewayInfo {
|
||||||
let stateJSON = context.readData(context.paths.gatewayStateJSON)
|
let stateJSON = context.readData(context.paths.gatewayStateJSON)
|
||||||
var pid: Int?
|
var pid: Int?
|
||||||
var state = "unknown"
|
var state = "unknown"
|
||||||
@@ -102,7 +124,7 @@ final class GatewayViewModel {
|
|||||||
let isLoaded = statusOutput.contains("service is loaded")
|
let isLoaded = statusOutput.contains("service is loaded")
|
||||||
let isStale = statusOutput.contains("stale")
|
let isStale = statusOutput.contains("stale")
|
||||||
|
|
||||||
return GatewayInfo(
|
return MessagingGatewayInfo(
|
||||||
pid: pid, state: state, exitReason: exitReason,
|
pid: pid, state: state, exitReason: exitReason,
|
||||||
startTime: startTime, updatedAt: updatedAt,
|
startTime: startTime, updatedAt: updatedAt,
|
||||||
platforms: platforms, isLoaded: isLoaded, isStale: isStale
|
platforms: platforms, isLoaded: isLoaded, isStale: isStale
|
||||||
|
|||||||
@@ -2,12 +2,24 @@ import SwiftUI
|
|||||||
import ScarfCore
|
import ScarfCore
|
||||||
import ScarfDesign
|
import ScarfDesign
|
||||||
|
|
||||||
|
/// Messaging Gateway page. Routes outbound chat to Discord / Telegram /
|
||||||
|
/// Slack / etc. — distinct from the v0.10 **Tool Gateway** (Nous Portal
|
||||||
|
/// subscription routing for web search / image / TTS / browser), which
|
||||||
|
/// lives under `Features/Health/`. The user-facing label here is always
|
||||||
|
/// "Messaging Gateway"; the SwiftUI struct stays `GatewayView` because
|
||||||
|
/// `ContentView` references it by name (rename-on-touch invariant —
|
||||||
|
/// avoid churning unrelated callers).
|
||||||
struct GatewayView: View {
|
struct GatewayView: View {
|
||||||
@State private var viewModel: GatewayViewModel
|
@State private var viewModel: MessagingGatewayViewModel
|
||||||
@Environment(HermesFileWatcher.self) private var fileWatcher
|
@Environment(HermesFileWatcher.self) private var fileWatcher
|
||||||
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
|
||||||
init(context: ServerContext) {
|
init(context: ServerContext) {
|
||||||
_viewModel = State(initialValue: GatewayViewModel(context: context))
|
// Capabilities arrive via environment after init runs, so the VM
|
||||||
|
// is constructed with `.empty` and refreshed on first appear via
|
||||||
|
// `attach(capabilities:)`. Same pattern as the per-platform setup
|
||||||
|
// views — see `MessagingGatewayViewModel.capabilities` doc comment.
|
||||||
|
_viewModel = State(initialValue: MessagingGatewayViewModel(context: context))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -15,10 +27,15 @@ struct GatewayView: View {
|
|||||||
VStack(spacing: 0) {
|
VStack(spacing: 0) {
|
||||||
ScarfPageHeader(
|
ScarfPageHeader(
|
||||||
"Messaging Gateway",
|
"Messaging Gateway",
|
||||||
subtitle: "Outbound channel bridge — Discord, Telegram, Slack, etc."
|
subtitle: "Outbound channel bridge — Discord, Telegram, Slack, Google Chat, etc."
|
||||||
)
|
)
|
||||||
ScrollView {
|
ScrollView {
|
||||||
VStack(alignment: .leading, spacing: 24) {
|
VStack(alignment: .leading, spacing: ScarfSpace.s4) {
|
||||||
|
if let snap = viewModel.gatewayList,
|
||||||
|
viewModel.capabilities.hasGatewayList,
|
||||||
|
!snap.profiles.isEmpty {
|
||||||
|
crossProfileDigest(snap)
|
||||||
|
}
|
||||||
serviceSection
|
serviceSection
|
||||||
platformsSection
|
platformsSection
|
||||||
pairingSection
|
pairingSection
|
||||||
@@ -29,14 +46,58 @@ struct GatewayView: View {
|
|||||||
}
|
}
|
||||||
.background(ScarfColor.backgroundPrimary)
|
.background(ScarfColor.backgroundPrimary)
|
||||||
.navigationTitle("Messaging Gateway")
|
.navigationTitle("Messaging Gateway")
|
||||||
.onAppear { viewModel.load() }
|
.onAppear {
|
||||||
|
attachCapabilitiesIfNeeded()
|
||||||
|
viewModel.load()
|
||||||
|
}
|
||||||
.onChange(of: fileWatcher.lastChangeDate) { viewModel.load() }
|
.onChange(of: fileWatcher.lastChangeDate) { viewModel.load() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Re-create the VM with the resolved capabilities the first time the
|
||||||
|
/// store hands us non-empty data. Same shape as `KanbanBoardView`'s
|
||||||
|
/// `attach` helper.
|
||||||
|
private func attachCapabilitiesIfNeeded() {
|
||||||
|
guard let store = capabilitiesStore,
|
||||||
|
store.capabilities.detected,
|
||||||
|
!viewModel.capabilities.detected else { return }
|
||||||
|
viewModel = MessagingGatewayViewModel(
|
||||||
|
context: viewModel.context,
|
||||||
|
capabilities: store.capabilities
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - v0.13 cross-profile digest
|
||||||
|
|
||||||
|
/// One-line summary above the gateway controls when the host is on
|
||||||
|
/// v0.13+ and `hermes gateway list --json` returned at least one
|
||||||
|
/// profile. Doubly-guarded — `hasGatewayList` AND `profiles != []`
|
||||||
|
/// — so a v0.13 host with no registered profiles doesn't render
|
||||||
|
/// an empty pill.
|
||||||
|
private func crossProfileDigest(_ snap: GatewayListSnapshot) -> some View {
|
||||||
|
HStack(spacing: ScarfSpace.s2) {
|
||||||
|
Image(systemName: "dot.radiowaves.left.and.right")
|
||||||
|
.foregroundStyle(ScarfColor.accent)
|
||||||
|
Text(snap.headerDigest)
|
||||||
|
.scarfStyle(.captionStrong)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundPrimary)
|
||||||
|
Spacer()
|
||||||
|
}
|
||||||
|
.padding(.horizontal, ScarfSpace.s3)
|
||||||
|
.padding(.vertical, ScarfSpace.s2)
|
||||||
|
.background(
|
||||||
|
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
|
||||||
|
.fill(ScarfColor.backgroundSecondary)
|
||||||
|
)
|
||||||
|
.overlay(
|
||||||
|
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
|
||||||
|
.strokeBorder(ScarfColor.border, lineWidth: 1)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Service
|
// MARK: - Service
|
||||||
|
|
||||||
private var serviceSection: some View {
|
private var serviceSection: some View {
|
||||||
VStack(alignment: .leading, spacing: 12) {
|
VStack(alignment: .leading, spacing: ScarfSpace.s3) {
|
||||||
HStack {
|
HStack {
|
||||||
Text("Service")
|
Text("Service")
|
||||||
.font(.headline)
|
.font(.headline)
|
||||||
@@ -46,15 +107,20 @@ struct GatewayView: View {
|
|||||||
.font(.caption)
|
.font(.caption)
|
||||||
.foregroundStyle(.secondary)
|
.foregroundStyle(.secondary)
|
||||||
}
|
}
|
||||||
HStack(spacing: 8) {
|
HStack(spacing: ScarfSpace.s2) {
|
||||||
Button("Start") { viewModel.startGateway() }
|
Button("Start") { viewModel.startGateway() }
|
||||||
|
.buttonStyle(ScarfPrimaryButton())
|
||||||
|
.controlSize(.small)
|
||||||
Button("Stop") { viewModel.stopGateway() }
|
Button("Stop") { viewModel.stopGateway() }
|
||||||
|
.buttonStyle(ScarfSecondaryButton())
|
||||||
|
.controlSize(.small)
|
||||||
Button("Restart") { viewModel.restartGateway() }
|
Button("Restart") { viewModel.restartGateway() }
|
||||||
}
|
.buttonStyle(ScarfSecondaryButton())
|
||||||
.controlSize(.small)
|
.controlSize(.small)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
HStack(spacing: 16) {
|
HStack(spacing: ScarfSpace.s3) {
|
||||||
StatusBadge(
|
StatusBadge(
|
||||||
label: viewModel.gateway.state,
|
label: viewModel.gateway.state,
|
||||||
isActive: viewModel.gateway.state == "running"
|
isActive: viewModel.gateway.state == "running"
|
||||||
@@ -97,7 +163,7 @@ struct GatewayView: View {
|
|||||||
// MARK: - Platforms
|
// MARK: - Platforms
|
||||||
|
|
||||||
private var platformsSection: some View {
|
private var platformsSection: some View {
|
||||||
VStack(alignment: .leading, spacing: 8) {
|
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
|
||||||
Text("Platforms")
|
Text("Platforms")
|
||||||
.font(.headline)
|
.font(.headline)
|
||||||
if viewModel.gateway.platforms.isEmpty {
|
if viewModel.gateway.platforms.isEmpty {
|
||||||
@@ -105,7 +171,7 @@ struct GatewayView: View {
|
|||||||
.font(.caption)
|
.font(.caption)
|
||||||
.foregroundStyle(.secondary)
|
.foregroundStyle(.secondary)
|
||||||
} else {
|
} else {
|
||||||
HStack(spacing: 12) {
|
HStack(spacing: ScarfSpace.s3) {
|
||||||
ForEach(viewModel.gateway.platforms) { platform in
|
ForEach(viewModel.gateway.platforms) { platform in
|
||||||
VStack(spacing: 6) {
|
VStack(spacing: 6) {
|
||||||
Image(systemName: platform.icon)
|
Image(systemName: platform.icon)
|
||||||
@@ -119,9 +185,9 @@ struct GatewayView: View {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
.frame(maxWidth: .infinity)
|
.frame(maxWidth: .infinity)
|
||||||
.padding(12)
|
.padding(ScarfSpace.s3)
|
||||||
.background(.quaternary.opacity(0.5))
|
.background(.quaternary.opacity(0.5))
|
||||||
.clipShape(RoundedRectangle(cornerRadius: 8))
|
.clipShape(RoundedRectangle(cornerRadius: ScarfRadius.md))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -131,12 +197,12 @@ struct GatewayView: View {
|
|||||||
// MARK: - Pairing
|
// MARK: - Pairing
|
||||||
|
|
||||||
private var pairingSection: some View {
|
private var pairingSection: some View {
|
||||||
VStack(alignment: .leading, spacing: 12) {
|
VStack(alignment: .leading, spacing: ScarfSpace.s3) {
|
||||||
Text("Paired Users")
|
Text("Paired Users")
|
||||||
.font(.headline)
|
.font(.headline)
|
||||||
|
|
||||||
if !viewModel.pendingPairings.isEmpty {
|
if !viewModel.pendingPairings.isEmpty {
|
||||||
VStack(alignment: .leading, spacing: 8) {
|
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
|
||||||
Label("Pending Approvals", systemImage: "clock.badge.questionmark")
|
Label("Pending Approvals", systemImage: "clock.badge.questionmark")
|
||||||
.font(.caption.bold())
|
.font(.caption.bold())
|
||||||
.foregroundStyle(.orange)
|
.foregroundStyle(.orange)
|
||||||
@@ -150,12 +216,12 @@ struct GatewayView: View {
|
|||||||
viewModel.approvePairing(platform: pending.platform, code: pending.code)
|
viewModel.approvePairing(platform: pending.platform, code: pending.code)
|
||||||
}
|
}
|
||||||
.controlSize(.small)
|
.controlSize(.small)
|
||||||
.buttonStyle(.borderedProminent)
|
.buttonStyle(ScarfPrimaryButton())
|
||||||
}
|
}
|
||||||
.font(.caption)
|
.font(.caption)
|
||||||
.padding(8)
|
.padding(ScarfSpace.s2)
|
||||||
.background(.orange.opacity(0.1))
|
.background(.orange.opacity(0.1))
|
||||||
.clipShape(RoundedRectangle(cornerRadius: 6))
|
.clipShape(RoundedRectangle(cornerRadius: ScarfRadius.sm))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -182,9 +248,9 @@ struct GatewayView: View {
|
|||||||
}
|
}
|
||||||
.controlSize(.small)
|
.controlSize(.small)
|
||||||
}
|
}
|
||||||
.padding(8)
|
.padding(ScarfSpace.s2)
|
||||||
.background(.quaternary.opacity(0.3))
|
.background(.quaternary.opacity(0.3))
|
||||||
.clipShape(RoundedRectangle(cornerRadius: 6))
|
.clipShape(RoundedRectangle(cornerRadius: ScarfRadius.sm))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,22 +55,9 @@ final class KanbanBoardViewModel {
|
|||||||
var assigneeFilter: String? // nil = all assignees
|
var assigneeFilter: String? // nil = all assignees
|
||||||
var showArchived: Bool = false
|
var showArchived: Bool = false
|
||||||
|
|
||||||
/// Optimistic in-flight overrides keyed by task id; cleared when the
|
/// Optimistic moves keyed by task id; cleared when the polled
|
||||||
/// polled response confirms the new state.
|
/// response includes the same status the optimistic move set.
|
||||||
/// - Status side: drag-drop column moves.
|
private var optimisticOverrides: [String: String] = [:]
|
||||||
/// - Hallucination-gate side (v0.13): Verify clicks flip `pending` →
|
|
||||||
/// `verified` locally so the banner disappears immediately.
|
|
||||||
/// The override entry is dropped from the dictionary entirely once
|
|
||||||
/// both sides are nil (no override needed).
|
|
||||||
private struct OptimisticOverride {
|
|
||||||
var status: String?
|
|
||||||
var hallucinationGate: KanbanHallucinationGate?
|
|
||||||
|
|
||||||
var isEmpty: Bool {
|
|
||||||
status == nil && hallucinationGate == nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
private var optimisticOverrides: [String: OptimisticOverride] = [:]
|
|
||||||
/// Tasks dropped into invalid columns produce a transient "denied"
|
/// Tasks dropped into invalid columns produce a transient "denied"
|
||||||
/// banner. Stored as an explicit error to support the Cmd-Z style
|
/// banner. Stored as an explicit error to support the Cmd-Z style
|
||||||
/// undo we don't ship in v2.7.5 but want to leave room for.
|
/// undo we don't ship in v2.7.5 but want to leave room for.
|
||||||
@@ -190,10 +177,8 @@ final class KanbanBoardViewModel {
|
|||||||
// Optimistic mutation — flip the local row's status to a
|
// Optimistic mutation — flip the local row's status to a
|
||||||
// value within the destination column's range. We pick a
|
// value within the destination column's range. We pick a
|
||||||
// representative status per column.
|
// representative status per column.
|
||||||
let optimisticStatusValue = optimisticStatus(for: destination)
|
let optimisticStatus = optimisticStatus(for: destination)
|
||||||
var override = optimisticOverrides[taskId] ?? OptimisticOverride()
|
optimisticOverrides[taskId] = optimisticStatus
|
||||||
override.status = optimisticStatusValue
|
|
||||||
optimisticOverrides[taskId] = override
|
|
||||||
|
|
||||||
let svc = service
|
let svc = service
|
||||||
Task {
|
Task {
|
||||||
@@ -205,11 +190,11 @@ final class KanbanBoardViewModel {
|
|||||||
// without waiting for the 5s tick.
|
// without waiting for the 5s tick.
|
||||||
await refresh()
|
await refresh()
|
||||||
} catch let err as KanbanError {
|
} catch let err as KanbanError {
|
||||||
clearStatusOverride(for: taskId)
|
optimisticOverrides.removeValue(forKey: taskId)
|
||||||
lastError = err.errorDescription
|
lastError = err.errorDescription
|
||||||
logger.warning("kanban move failed: \(err.errorDescription ?? "", privacy: .public)")
|
logger.warning("kanban move failed: \(err.errorDescription ?? "", privacy: .public)")
|
||||||
} catch {
|
} catch {
|
||||||
clearStatusOverride(for: taskId)
|
optimisticOverrides.removeValue(forKey: taskId)
|
||||||
lastError = error.localizedDescription
|
lastError = error.localizedDescription
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -284,48 +269,6 @@ final class KanbanBoardViewModel {
|
|||||||
return task
|
return task
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Hallucination gate (v0.13)
|
|
||||||
|
|
||||||
/// User confirmed the worker-created card is real. Optimistically
|
|
||||||
/// flip the gate to `verified` so the banner disappears immediately;
|
|
||||||
/// the polling loop confirms the new state on the next tick. On
|
|
||||||
/// failure (e.g. the verb name is wrong on this v0.13.x build), the
|
|
||||||
/// override is cleared and the error surfaces in `lastError`.
|
|
||||||
func verifyHallucination(taskId: String) {
|
|
||||||
var override = optimisticOverrides[taskId] ?? OptimisticOverride()
|
|
||||||
override.hallucinationGate = .verified
|
|
||||||
optimisticOverrides[taskId] = override
|
|
||||||
Task {
|
|
||||||
do {
|
|
||||||
try await service.verify(taskId: taskId)
|
|
||||||
await refresh()
|
|
||||||
} catch let err as KanbanError {
|
|
||||||
clearHallucinationOverride(for: taskId)
|
|
||||||
lastError = err.errorDescription
|
|
||||||
logger.warning("kanban verify failed: \(err.errorDescription ?? "", privacy: .public)")
|
|
||||||
} catch {
|
|
||||||
clearHallucinationOverride(for: taskId)
|
|
||||||
lastError = error.localizedDescription
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// User rejected the worker-created card as a hallucinated reference.
|
|
||||||
/// Routes through `comment` + `archive` per `KanbanService.rejectHallucinated`
|
|
||||||
/// so there's an audit trail for why the card disappeared.
|
|
||||||
func rejectHallucination(taskId: String) {
|
|
||||||
Task {
|
|
||||||
do {
|
|
||||||
try await service.rejectHallucinated(taskId: taskId)
|
|
||||||
await refresh()
|
|
||||||
} catch let err as KanbanError {
|
|
||||||
lastError = err.errorDescription
|
|
||||||
} catch {
|
|
||||||
lastError = error.localizedDescription
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Private helpers
|
// MARK: - Private helpers
|
||||||
|
|
||||||
private func mergePolledTasks(_ polled: [HermesKanbanTask]) {
|
private func mergePolledTasks(_ polled: [HermesKanbanTask]) {
|
||||||
@@ -339,75 +282,25 @@ final class KanbanBoardViewModel {
|
|||||||
filtered = polled
|
filtered = polled
|
||||||
}
|
}
|
||||||
let presentIds = Set(filtered.map(\.id))
|
let presentIds = Set(filtered.map(\.id))
|
||||||
// Drop optimistic overrides for tasks Hermes confirmed. Two
|
// Drop optimistic overrides for tasks Hermes confirmed.
|
||||||
// independent sides — clear them separately so a Verify click
|
for (id, optimistic) in optimisticOverrides {
|
||||||
// still in-flight survives a status-side poll confirmation, and
|
if let row = filtered.first(where: { $0.id == id }) {
|
||||||
// vice versa.
|
if columnFromStatus(optimistic) == columnFromStatus(row.status) {
|
||||||
for (id, override) in optimisticOverrides {
|
|
||||||
guard let row = filtered.first(where: { $0.id == id }) else {
|
|
||||||
if !presentIds.contains(id) {
|
|
||||||
// Task no longer in the polled set (archived, deleted,
|
|
||||||
// or filtered out). Drop the override entirely.
|
|
||||||
optimisticOverrides.removeValue(forKey: id)
|
optimisticOverrides.removeValue(forKey: id)
|
||||||
}
|
}
|
||||||
continue
|
} else if !presentIds.contains(id) {
|
||||||
}
|
// Task no longer in the polled set (archived, deleted,
|
||||||
// Status side — optimistic move confirmed.
|
// or filtered out). Drop the optimistic entry.
|
||||||
if let optStatus = override.status,
|
|
||||||
columnFromStatus(optStatus) == columnFromStatus(row.status) {
|
|
||||||
optimisticOverrides[id]?.status = nil
|
|
||||||
}
|
|
||||||
// Hallucination-gate side — optimistic verify/reject confirmed.
|
|
||||||
if let optGate = override.hallucinationGate,
|
|
||||||
KanbanHallucinationGate.from(row.hallucinationGateStatus) == optGate {
|
|
||||||
optimisticOverrides[id]?.hallucinationGate = nil
|
|
||||||
}
|
|
||||||
if optimisticOverrides[id]?.isEmpty ?? true {
|
|
||||||
optimisticOverrides.removeValue(forKey: id)
|
optimisticOverrides.removeValue(forKey: id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
tasks = filtered
|
tasks = filtered
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Drop the status side of a task's override (preserving any
|
|
||||||
/// in-flight hallucination-gate optimistic state).
|
|
||||||
private func clearStatusOverride(for taskId: String) {
|
|
||||||
guard var override = optimisticOverrides[taskId] else { return }
|
|
||||||
override.status = nil
|
|
||||||
if override.isEmpty {
|
|
||||||
optimisticOverrides.removeValue(forKey: taskId)
|
|
||||||
} else {
|
|
||||||
optimisticOverrides[taskId] = override
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drop the hallucination-gate side of a task's override (preserving
|
|
||||||
/// any in-flight status-side drag-drop).
|
|
||||||
private func clearHallucinationOverride(for taskId: String) {
|
|
||||||
guard var override = optimisticOverrides[taskId] else { return }
|
|
||||||
override.hallucinationGate = nil
|
|
||||||
if override.isEmpty {
|
|
||||||
optimisticOverrides.removeValue(forKey: taskId)
|
|
||||||
} else {
|
|
||||||
optimisticOverrides[taskId] = override
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Effective hallucination gate for a task — the optimistic override
|
|
||||||
/// wins if one is in flight; otherwise the polled value. View code
|
|
||||||
/// reads through this so the banner / dim state matches the moment-
|
|
||||||
/// after-click experience.
|
|
||||||
func effectiveHallucinationGate(_ task: HermesKanbanTask) -> KanbanHallucinationGate? {
|
|
||||||
if let override = optimisticOverrides[task.id]?.hallucinationGate {
|
|
||||||
return override
|
|
||||||
}
|
|
||||||
return KanbanHallucinationGate.from(task.hallucinationGateStatus)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Return the effective board column for a task — the optimistic
|
/// Return the effective board column for a task — the optimistic
|
||||||
/// override wins if one is in flight; otherwise the polled status.
|
/// override wins if one is in flight; otherwise the polled status.
|
||||||
private func effectiveColumn(_ task: HermesKanbanTask) -> KanbanBoardColumn {
|
private func effectiveColumn(_ task: HermesKanbanTask) -> KanbanBoardColumn {
|
||||||
if let overrideStatus = optimisticOverrides[task.id]?.status {
|
if let overrideStatus = optimisticOverrides[task.id] {
|
||||||
return columnFromStatus(overrideStatus)
|
return columnFromStatus(overrideStatus)
|
||||||
}
|
}
|
||||||
return columnFromStatus(task.status)
|
return columnFromStatus(task.status)
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import ScarfDesign
|
|||||||
/// tenant.
|
/// tenant.
|
||||||
struct KanbanBoardView: View {
|
struct KanbanBoardView: View {
|
||||||
@State private var viewModel: KanbanBoardViewModel
|
@State private var viewModel: KanbanBoardViewModel
|
||||||
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
|
||||||
|
|
||||||
/// When non-nil, a project board hosts this view. Drives header
|
/// When non-nil, a project board hosts this view. Drives header
|
||||||
/// chrome (subtitle, hidden tenant filter) and create-sheet
|
/// chrome (subtitle, hidden tenant filter) and create-sheet
|
||||||
@@ -34,15 +33,6 @@ struct KanbanBoardView: View {
|
|||||||
self.projectName = projectName
|
self.projectName = projectName
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convenience read for the v0.13 diagnostics flag — gates the
|
|
||||||
/// max_retries field, hallucination banner, diagnostics rendering,
|
|
||||||
/// and the auto-blocked reason banner. Pre-v0.13 hosts get the
|
|
||||||
/// v2.7.5 surface unchanged. Treats a missing store as "off" so
|
|
||||||
/// harness contexts (Previews) don't accidentally surface gated UI.
|
|
||||||
private var supportsKanbanDiagnostics: Bool {
|
|
||||||
capabilitiesStore?.capabilities.hasKanbanDiagnostics ?? false
|
|
||||||
}
|
|
||||||
|
|
||||||
@State private var inspectorTaskId: String?
|
@State private var inspectorTaskId: String?
|
||||||
@State private var showingCreateSheet = false
|
@State private var showingCreateSheet = false
|
||||||
@State private var blockSheetTaskId: String?
|
@State private var blockSheetTaskId: String?
|
||||||
@@ -81,8 +71,7 @@ struct KanbanBoardView: View {
|
|||||||
KanbanCreateSheet(
|
KanbanCreateSheet(
|
||||||
assignees: viewModel.assignees,
|
assignees: viewModel.assignees,
|
||||||
tenantPrefill: viewModel.tenantFilter,
|
tenantPrefill: viewModel.tenantFilter,
|
||||||
projectWorkspacePath: viewModel.projectPath,
|
projectWorkspacePath: viewModel.projectPath
|
||||||
supportsKanbanDiagnostics: supportsKanbanDiagnostics
|
|
||||||
) { request in
|
) { request in
|
||||||
_ = try await viewModel.createTask(request)
|
_ = try await viewModel.createTask(request)
|
||||||
}
|
}
|
||||||
@@ -199,9 +188,7 @@ struct KanbanBoardView: View {
|
|||||||
onDrop: { ref in
|
onDrop: { ref in
|
||||||
handleDrop(ref.id, on: column)
|
handleDrop(ref.id, on: column)
|
||||||
},
|
},
|
||||||
canCreate: column == .upNext || column == .triage,
|
canCreate: column == .upNext || column == .triage
|
||||||
supportsKanbanDiagnostics: supportsKanbanDiagnostics,
|
|
||||||
effectiveHallucinationGate: { viewModel.effectiveHallucinationGate($0) }
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Spacer(minLength: ScarfSpace.s4)
|
Spacer(minLength: ScarfSpace.s4)
|
||||||
@@ -221,8 +208,6 @@ struct KanbanBoardView: View {
|
|||||||
service: viewModel.service,
|
service: viewModel.service,
|
||||||
taskId: taskId,
|
taskId: taskId,
|
||||||
availableAssignees: viewModel.assignees,
|
availableAssignees: viewModel.assignees,
|
||||||
supportsKanbanDiagnostics: supportsKanbanDiagnostics,
|
|
||||||
effectiveHallucinationGate: { viewModel.effectiveHallucinationGate($0) },
|
|
||||||
onClose: { inspectorTaskId = nil },
|
onClose: { inspectorTaskId = nil },
|
||||||
onClaim: {
|
onClaim: {
|
||||||
viewModel.attemptMove(taskId: taskId, to: .running)
|
viewModel.attemptMove(taskId: taskId, to: .running)
|
||||||
@@ -247,15 +232,6 @@ struct KanbanBoardView: View {
|
|||||||
},
|
},
|
||||||
onReassign: { profile in
|
onReassign: { profile in
|
||||||
viewModel.reassignTask(taskId: taskId, to: profile)
|
viewModel.reassignTask(taskId: taskId, to: profile)
|
||||||
},
|
|
||||||
onVerifyHallucination: {
|
|
||||||
viewModel.verifyHallucination(taskId: taskId)
|
|
||||||
},
|
|
||||||
onRejectHallucination: {
|
|
||||||
viewModel.rejectHallucination(taskId: taskId)
|
|
||||||
// Card vanishes from active board after archive — close
|
|
||||||
// the inspector so it doesn't dangle on a deleted task.
|
|
||||||
inspectorTaskId = nil
|
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,40 +24,12 @@ struct KanbanTaskRef: Transferable {
|
|||||||
/// - **Running** gets a blue left-edge accent + live shimmer
|
/// - **Running** gets a blue left-edge accent + live shimmer
|
||||||
/// - **Blocked** gets a warning left-edge accent + ⚠ glyph
|
/// - **Blocked** gets a warning left-edge accent + ⚠ glyph
|
||||||
/// - **Done** dims to 0.7 opacity (0.55 in dark mode)
|
/// - **Done** dims to 0.7 opacity (0.55 in dark mode)
|
||||||
/// - **Hallucination-gate pending** (v0.13+) dims to 0.6 + ⚠ glyph and
|
|
||||||
/// shows a one-line auto-blocked reason in the footer when present.
|
|
||||||
struct KanbanCardView: View {
|
struct KanbanCardView: View {
|
||||||
let task: HermesKanbanTask
|
let task: HermesKanbanTask
|
||||||
let onTap: () -> Void
|
let onTap: () -> Void
|
||||||
/// True when the connected Hermes is on v0.13+ — gates the
|
|
||||||
/// hallucination dim/glyph, auto-block sub-line, and diagnostics
|
|
||||||
/// dot on the card. Pre-v0.13 hosts see the v2.7.5 chrome unchanged.
|
|
||||||
let supportsKanbanDiagnostics: Bool
|
|
||||||
/// Optimistic-aware accessor. Pre-v0.13 always nil. Otherwise delegates
|
|
||||||
/// to the board VM so a Verify click un-dims the card immediately.
|
|
||||||
let effectiveHallucinationGate: (HermesKanbanTask) -> KanbanHallucinationGate?
|
|
||||||
|
|
||||||
init(
|
|
||||||
task: HermesKanbanTask,
|
|
||||||
supportsKanbanDiagnostics: Bool = false,
|
|
||||||
effectiveHallucinationGate: @escaping (HermesKanbanTask) -> KanbanHallucinationGate? = { _ in nil },
|
|
||||||
onTap: @escaping () -> Void
|
|
||||||
) {
|
|
||||||
self.task = task
|
|
||||||
self.supportsKanbanDiagnostics = supportsKanbanDiagnostics
|
|
||||||
self.effectiveHallucinationGate = effectiveHallucinationGate
|
|
||||||
self.onTap = onTap
|
|
||||||
}
|
|
||||||
|
|
||||||
@Environment(\.colorScheme) private var colorScheme
|
@Environment(\.colorScheme) private var colorScheme
|
||||||
|
|
||||||
/// Cached gate read — derived once per body eval rather than recomputed
|
|
||||||
/// in each subview helper.
|
|
||||||
private var hallucinationGate: KanbanHallucinationGate? {
|
|
||||||
guard supportsKanbanDiagnostics else { return nil }
|
|
||||||
return effectiveHallucinationGate(task)
|
|
||||||
}
|
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
Button(action: onTap) {
|
Button(action: onTap) {
|
||||||
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
|
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
|
||||||
@@ -94,22 +66,13 @@ struct KanbanCardView: View {
|
|||||||
}
|
}
|
||||||
.buttonStyle(.plain)
|
.buttonStyle(.plain)
|
||||||
.scarfShadow(.sm)
|
.scarfShadow(.sm)
|
||||||
// v0.13: hallucination-pending cards dim to 0.6 to signal "needs
|
.opacity(task.isDone ? doneOpacity : 1.0)
|
||||||
// verification before running" without making them unreadable.
|
|
||||||
// Done cards stay at the established doneOpacity (0.7 / 0.55).
|
|
||||||
.opacity(cardOpacity)
|
|
||||||
.draggable(KanbanTaskRef(id: task.id)) {
|
.draggable(KanbanTaskRef(id: task.id)) {
|
||||||
// Drag preview — the live card with a heavier shadow.
|
// Drag preview — the live card with a heavier shadow.
|
||||||
self.dragPreview
|
self.dragPreview
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var cardOpacity: Double {
|
|
||||||
if task.isDone { return doneOpacity }
|
|
||||||
if hallucinationGate == .pending { return 0.6 }
|
|
||||||
return 1.0
|
|
||||||
}
|
|
||||||
|
|
||||||
private var titleRow: some View {
|
private var titleRow: some View {
|
||||||
HStack(alignment: .top, spacing: ScarfSpace.s2) {
|
HStack(alignment: .top, spacing: ScarfSpace.s2) {
|
||||||
statusGlyph
|
statusGlyph
|
||||||
@@ -119,15 +82,7 @@ struct KanbanCardView: View {
|
|||||||
.lineLimit(2)
|
.lineLimit(2)
|
||||||
.multilineTextAlignment(.leading)
|
.multilineTextAlignment(.leading)
|
||||||
Spacer(minLength: 0)
|
Spacer(minLength: 0)
|
||||||
// v0.13 hallucination glyph takes precedence over the
|
if needsAssignmentWarning {
|
||||||
// unassigned glyph — the hallucination state is the more
|
|
||||||
// specific signal (a worker created this card; verify it).
|
|
||||||
if hallucinationGate == .pending {
|
|
||||||
Image(systemName: "questionmark.diamond.fill")
|
|
||||||
.foregroundStyle(ScarfColor.warning)
|
|
||||||
.font(.system(size: 11, weight: .semibold))
|
|
||||||
.help("Worker-created — verify before running")
|
|
||||||
} else if needsAssignmentWarning {
|
|
||||||
Image(systemName: "exclamationmark.triangle.fill")
|
Image(systemName: "exclamationmark.triangle.fill")
|
||||||
.foregroundStyle(ScarfColor.warning)
|
.foregroundStyle(ScarfColor.warning)
|
||||||
.font(.system(size: 11, weight: .semibold))
|
.font(.system(size: 11, weight: .semibold))
|
||||||
@@ -231,40 +186,16 @@ struct KanbanCardView: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private var footerRow: some View {
|
private var footerRow: some View {
|
||||||
VStack(alignment: .leading, spacing: 2) {
|
|
||||||
// v0.13: server-supplied auto-blocked reason. Renders verbatim
|
|
||||||
// (truncated to one line; full reason in the inspector).
|
|
||||||
// Pre-v0.13 hosts always have task.autoBlockedReason == nil.
|
|
||||||
if supportsKanbanDiagnostics,
|
|
||||||
KanbanStatus.from(task.status) == .blocked,
|
|
||||||
let reason = task.autoBlockedReason, !reason.isEmpty {
|
|
||||||
Text(reason)
|
|
||||||
.scarfStyle(.caption)
|
|
||||||
.foregroundStyle(ScarfColor.danger)
|
|
||||||
.lineLimit(1)
|
|
||||||
.truncationMode(.tail)
|
|
||||||
.help(reason)
|
|
||||||
}
|
|
||||||
HStack(spacing: ScarfSpace.s2) {
|
HStack(spacing: ScarfSpace.s2) {
|
||||||
Text(relativeTimeLabel)
|
Text(relativeTimeLabel)
|
||||||
.scarfStyle(.caption)
|
.scarfStyle(.caption)
|
||||||
.foregroundStyle(ScarfColor.foregroundFaint)
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
Spacer(minLength: 0)
|
Spacer(minLength: 0)
|
||||||
// v0.13: diagnostics dot — small stethoscope glyph when
|
|
||||||
// any cross-run distress signal is attached. Matches the
|
|
||||||
// chip count in the inspector.
|
|
||||||
if supportsKanbanDiagnostics, !task.diagnostics.isEmpty {
|
|
||||||
Image(systemName: "stethoscope")
|
|
||||||
.font(.system(size: 9))
|
|
||||||
.foregroundStyle(ScarfColor.warning)
|
|
||||||
.help("\(task.diagnostics.count) diagnostic signal\(task.diagnostics.count == 1 ? "" : "s")")
|
|
||||||
}
|
|
||||||
if let priority = task.priority, priority >= 70 {
|
if let priority = task.priority, priority >= 70 {
|
||||||
priorityIndicator(priority)
|
priorityIndicator(priority)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private func priorityIndicator(_ priority: Int) -> some View {
|
private func priorityIndicator(_ priority: Int) -> some View {
|
||||||
let color: Color = priority >= 90 ? ScarfColor.danger : ScarfColor.warning
|
let color: Color = priority >= 90 ? ScarfColor.danger : ScarfColor.warning
|
||||||
|
|||||||
@@ -17,38 +17,6 @@ struct KanbanColumnView: View {
|
|||||||
let onCreate: () -> Void
|
let onCreate: () -> Void
|
||||||
let onDrop: (KanbanTaskRef) -> Void
|
let onDrop: (KanbanTaskRef) -> Void
|
||||||
let canCreate: Bool
|
let canCreate: Bool
|
||||||
/// True when the connected Hermes is on v0.13+. Forwarded to each
|
|
||||||
/// `KanbanCardView` so the hallucination dim/glyph + diagnostics dot
|
|
||||||
/// + auto-block sub-line gate uniformly.
|
|
||||||
let supportsKanbanDiagnostics: Bool
|
|
||||||
/// Optimistic-aware accessor forwarded to cards. Default is
|
|
||||||
/// "no override" so Previews and harness contexts still render
|
|
||||||
/// without wiring up a board VM.
|
|
||||||
let effectiveHallucinationGate: (HermesKanbanTask) -> KanbanHallucinationGate?
|
|
||||||
|
|
||||||
init(
|
|
||||||
column: KanbanBoardColumn,
|
|
||||||
tasks: [HermesKanbanTask],
|
|
||||||
isLive: Bool,
|
|
||||||
readyPillCount: Int,
|
|
||||||
onTaskTap: @escaping (HermesKanbanTask) -> Void,
|
|
||||||
onCreate: @escaping () -> Void,
|
|
||||||
onDrop: @escaping (KanbanTaskRef) -> Void,
|
|
||||||
canCreate: Bool,
|
|
||||||
supportsKanbanDiagnostics: Bool = false,
|
|
||||||
effectiveHallucinationGate: @escaping (HermesKanbanTask) -> KanbanHallucinationGate? = { _ in nil }
|
|
||||||
) {
|
|
||||||
self.column = column
|
|
||||||
self.tasks = tasks
|
|
||||||
self.isLive = isLive
|
|
||||||
self.readyPillCount = readyPillCount
|
|
||||||
self.onTaskTap = onTaskTap
|
|
||||||
self.onCreate = onCreate
|
|
||||||
self.onDrop = onDrop
|
|
||||||
self.canCreate = canCreate
|
|
||||||
self.supportsKanbanDiagnostics = supportsKanbanDiagnostics
|
|
||||||
self.effectiveHallucinationGate = effectiveHallucinationGate
|
|
||||||
}
|
|
||||||
|
|
||||||
@State private var isTargeted = false
|
@State private var isTargeted = false
|
||||||
|
|
||||||
@@ -68,11 +36,7 @@ struct KanbanColumnView: View {
|
|||||||
.padding(.top, ScarfSpace.s4)
|
.padding(.top, ScarfSpace.s4)
|
||||||
} else {
|
} else {
|
||||||
ForEach(tasks) { task in
|
ForEach(tasks) { task in
|
||||||
KanbanCardView(
|
KanbanCardView(task: task) {
|
||||||
task: task,
|
|
||||||
supportsKanbanDiagnostics: supportsKanbanDiagnostics,
|
|
||||||
effectiveHallucinationGate: effectiveHallucinationGate
|
|
||||||
) {
|
|
||||||
onTaskTap(task)
|
onTaskTap(task)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,12 +14,6 @@ struct KanbanCreateSheet: View {
|
|||||||
/// Pre-filled project workspace path on per-project boards. When
|
/// Pre-filled project workspace path on per-project boards. When
|
||||||
/// non-nil, the workspace picker is locked to "Project Dir".
|
/// non-nil, the workspace picker is locked to "Project Dir".
|
||||||
let projectWorkspacePath: String?
|
let projectWorkspacePath: String?
|
||||||
/// True when the connected Hermes is on v0.13+ — gates the
|
|
||||||
/// `--max-retries` field and decides whether to strip newlines from
|
|
||||||
/// the title at submit time. Pre-v0.13 hosts may truncate at the
|
|
||||||
/// first `\n`; we keep the multi-line input rendering on either way
|
|
||||||
/// since a taller `TextField` is harmless on v0.12.
|
|
||||||
let supportsKanbanDiagnostics: Bool
|
|
||||||
/// Closure invoked when the user submits — VM owner constructs the
|
/// Closure invoked when the user submits — VM owner constructs the
|
||||||
/// `KanbanService.create` call.
|
/// `KanbanService.create` call.
|
||||||
let onSubmit: (KanbanCreateRequest) async throws -> Void
|
let onSubmit: (KanbanCreateRequest) async throws -> Void
|
||||||
@@ -39,11 +33,6 @@ struct KanbanCreateSheet: View {
|
|||||||
@State private var skillsInput: String = ""
|
@State private var skillsInput: String = ""
|
||||||
@State private var tenant: String = ""
|
@State private var tenant: String = ""
|
||||||
@State private var sendToTriage: Bool = false
|
@State private var sendToTriage: Bool = false
|
||||||
/// v0.13: per-task retry budget. Toggle-gated so the user can opt
|
|
||||||
/// into "send the flag" vs. "let Hermes pick its default" (the
|
|
||||||
/// release notes default to 3 — see TODO in KanbanCreateRequest).
|
|
||||||
@State private var maxRetriesEnabled: Bool = false
|
|
||||||
@State private var maxRetries: Int = 3
|
|
||||||
@State private var isSubmitting: Bool = false
|
@State private var isSubmitting: Bool = false
|
||||||
@State private var submitError: String?
|
@State private var submitError: String?
|
||||||
@FocusState private var titleFocused: Bool
|
@FocusState private var titleFocused: Bool
|
||||||
@@ -73,9 +62,6 @@ struct KanbanCreateSheet: View {
|
|||||||
assigneePicker
|
assigneePicker
|
||||||
workspaceField
|
workspaceField
|
||||||
priorityField
|
priorityField
|
||||||
if supportsKanbanDiagnostics {
|
|
||||||
maxRetriesField
|
|
||||||
}
|
|
||||||
skillsField
|
skillsField
|
||||||
if projectWorkspacePath == nil {
|
if projectWorkspacePath == nil {
|
||||||
tenantField
|
tenantField
|
||||||
@@ -128,63 +114,13 @@ struct KanbanCreateSheet: View {
|
|||||||
// MARK: - Fields
|
// MARK: - Fields
|
||||||
|
|
||||||
private var titleField: some View {
|
private var titleField: some View {
|
||||||
// v0.13 server tolerates multi-line titles. We keep the
|
|
||||||
// multi-line input rendering on for ALL versions of Hermes —
|
|
||||||
// visually a taller TextField is harmless on v0.12 — and decide
|
|
||||||
// at submit time whether to strip newlines (see `makeRequest`).
|
|
||||||
VStack(alignment: .leading, spacing: 4) {
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
ScarfSectionHeader("Title")
|
ScarfSectionHeader("Title")
|
||||||
TextField(
|
ScarfTextField("What needs doing?", text: $title)
|
||||||
"What needs doing?",
|
|
||||||
text: $title,
|
|
||||||
axis: .vertical
|
|
||||||
)
|
|
||||||
.lineLimit(1...4)
|
|
||||||
.textFieldStyle(.plain)
|
|
||||||
.scarfStyle(.body)
|
|
||||||
.padding(.horizontal, ScarfSpace.s3)
|
|
||||||
.padding(.vertical, ScarfSpace.s2)
|
|
||||||
.background(
|
|
||||||
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
|
|
||||||
.fill(ScarfColor.backgroundSecondary)
|
|
||||||
)
|
|
||||||
.overlay(
|
|
||||||
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
|
|
||||||
.strokeBorder(ScarfColor.borderStrong, lineWidth: 1)
|
|
||||||
)
|
|
||||||
.focused($titleFocused)
|
.focused($titleFocused)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// v0.13: per-task retry budget. Toggle gates whether `--max-retries`
|
|
||||||
/// is sent at all so the user can preserve "let Hermes pick the
|
|
||||||
/// default" semantics by leaving the toggle off.
|
|
||||||
private var maxRetriesField: some View {
|
|
||||||
VStack(alignment: .leading, spacing: 4) {
|
|
||||||
ScarfSectionHeader(
|
|
||||||
"Max retries",
|
|
||||||
subtitle: "0 = no retries. Defaults to 3."
|
|
||||||
)
|
|
||||||
HStack(spacing: ScarfSpace.s3) {
|
|
||||||
Toggle("Override default", isOn: $maxRetriesEnabled)
|
|
||||||
.toggleStyle(.switch)
|
|
||||||
.labelsHidden()
|
|
||||||
Stepper(value: $maxRetries, in: 0...20) {
|
|
||||||
Text("\(maxRetries)")
|
|
||||||
.scarfStyle(.bodyEmph)
|
|
||||||
.frame(minWidth: 24, alignment: .trailing)
|
|
||||||
.foregroundStyle(
|
|
||||||
maxRetriesEnabled
|
|
||||||
? ScarfColor.foregroundPrimary
|
|
||||||
: ScarfColor.foregroundFaint
|
|
||||||
)
|
|
||||||
}
|
|
||||||
.disabled(!maxRetriesEnabled)
|
|
||||||
Spacer()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private var descriptionField: some View {
|
private var descriptionField: some View {
|
||||||
VStack(alignment: .leading, spacing: 4) {
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
ScarfSectionHeader("Description", subtitle: "Markdown supported")
|
ScarfSectionHeader("Description", subtitle: "Markdown supported")
|
||||||
@@ -371,14 +307,7 @@ struct KanbanCreateSheet: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func makeRequest() -> KanbanCreateRequest {
|
private func makeRequest() -> KanbanCreateRequest {
|
||||||
var trimmedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines)
|
let trimmedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
// Pre-v0.13 hosts may truncate titles at the first `\n`. Strip
|
|
||||||
// newlines client-side when we know the connected Hermes hasn't
|
|
||||||
// shipped multi-line title support — replace with a space to
|
|
||||||
// keep the user's intent visible. v0.13+ keeps newlines verbatim.
|
|
||||||
if !supportsKanbanDiagnostics {
|
|
||||||
trimmedTitle = trimmedTitle.replacingOccurrences(of: "\n", with: " ")
|
|
||||||
}
|
|
||||||
let trimmedBody = bodyText.trimmingCharacters(in: .whitespacesAndNewlines)
|
let trimmedBody = bodyText.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
let trimmedAssignee = assignee.trimmingCharacters(in: .whitespacesAndNewlines)
|
let trimmedAssignee = assignee.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
let trimmedTenant = tenant.trimmingCharacters(in: .whitespacesAndNewlines)
|
let trimmedTenant = tenant.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
@@ -401,14 +330,6 @@ struct KanbanCreateSheet: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Belt-and-suspenders: the `maxRetriesField` is only rendered
|
|
||||||
// when `supportsKanbanDiagnostics` is true, but gate again here
|
|
||||||
// so a programmatic state change can't smuggle the flag onto a
|
|
||||||
// pre-v0.13 host (where the verb would error).
|
|
||||||
let resolvedMaxRetries: Int? = (supportsKanbanDiagnostics && maxRetriesEnabled)
|
|
||||||
? maxRetries
|
|
||||||
: nil
|
|
||||||
|
|
||||||
return KanbanCreateRequest(
|
return KanbanCreateRequest(
|
||||||
title: trimmedTitle,
|
title: trimmedTitle,
|
||||||
body: trimmedBody.isEmpty ? nil : trimmedBody,
|
body: trimmedBody.isEmpty ? nil : trimmedBody,
|
||||||
@@ -421,8 +342,7 @@ struct KanbanCreateSheet: View {
|
|||||||
idempotencyKey: nil,
|
idempotencyKey: nil,
|
||||||
maxRuntimeSeconds: nil,
|
maxRuntimeSeconds: nil,
|
||||||
createdBy: nil,
|
createdBy: nil,
|
||||||
skills: parsedSkills,
|
skills: parsedSkills
|
||||||
maxRetries: resolvedMaxRetries
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,16 +8,6 @@ import ScarfDesign
|
|||||||
struct KanbanInspectorPane: View {
|
struct KanbanInspectorPane: View {
|
||||||
@State private var viewModel: KanbanTaskDetailViewModel
|
@State private var viewModel: KanbanTaskDetailViewModel
|
||||||
let availableAssignees: [HermesKanbanAssignee]
|
let availableAssignees: [HermesKanbanAssignee]
|
||||||
/// True when the connected Hermes is on v0.13+ — gates the
|
|
||||||
/// hallucination banner, max_retries chip, diagnostics block,
|
|
||||||
/// and auto-blocked reason banner. Pre-v0.13 hosts see the v2.7.5
|
|
||||||
/// inspector unchanged.
|
|
||||||
let supportsKanbanDiagnostics: Bool
|
|
||||||
/// Resolves an effective hallucination gate — the board VM owns the
|
|
||||||
/// optimistic-override merge so the banner disappears immediately on
|
|
||||||
/// Verify before the polled state confirms the new gate. Falls back
|
|
||||||
/// to the wire-level value when no override is in flight.
|
|
||||||
let effectiveHallucinationGate: (HermesKanbanTask) -> KanbanHallucinationGate?
|
|
||||||
let onClose: () -> Void
|
let onClose: () -> Void
|
||||||
let onClaim: () -> Void
|
let onClaim: () -> Void
|
||||||
let onComplete: () -> Void
|
let onComplete: () -> Void
|
||||||
@@ -25,8 +15,6 @@ struct KanbanInspectorPane: View {
|
|||||||
let onUnblock: () -> Void
|
let onUnblock: () -> Void
|
||||||
let onArchive: () -> Void
|
let onArchive: () -> Void
|
||||||
let onReassign: (String?) -> Void
|
let onReassign: (String?) -> Void
|
||||||
let onVerifyHallucination: () -> Void
|
|
||||||
let onRejectHallucination: () -> Void
|
|
||||||
|
|
||||||
@State private var selectedTab: DetailTab = .comments
|
@State private var selectedTab: DetailTab = .comments
|
||||||
|
|
||||||
@@ -42,22 +30,16 @@ struct KanbanInspectorPane: View {
|
|||||||
service: KanbanService,
|
service: KanbanService,
|
||||||
taskId: String,
|
taskId: String,
|
||||||
availableAssignees: [HermesKanbanAssignee] = [],
|
availableAssignees: [HermesKanbanAssignee] = [],
|
||||||
supportsKanbanDiagnostics: Bool = false,
|
|
||||||
effectiveHallucinationGate: @escaping (HermesKanbanTask) -> KanbanHallucinationGate? = { _ in nil },
|
|
||||||
onClose: @escaping () -> Void,
|
onClose: @escaping () -> Void,
|
||||||
onClaim: @escaping () -> Void,
|
onClaim: @escaping () -> Void,
|
||||||
onComplete: @escaping () -> Void,
|
onComplete: @escaping () -> Void,
|
||||||
onBlock: @escaping () -> Void,
|
onBlock: @escaping () -> Void,
|
||||||
onUnblock: @escaping () -> Void,
|
onUnblock: @escaping () -> Void,
|
||||||
onArchive: @escaping () -> Void,
|
onArchive: @escaping () -> Void,
|
||||||
onReassign: @escaping (String?) -> Void = { _ in },
|
onReassign: @escaping (String?) -> Void = { _ in }
|
||||||
onVerifyHallucination: @escaping () -> Void = {},
|
|
||||||
onRejectHallucination: @escaping () -> Void = {}
|
|
||||||
) {
|
) {
|
||||||
_viewModel = State(initialValue: KanbanTaskDetailViewModel(service: service, taskId: taskId))
|
_viewModel = State(initialValue: KanbanTaskDetailViewModel(service: service, taskId: taskId))
|
||||||
self.availableAssignees = availableAssignees
|
self.availableAssignees = availableAssignees
|
||||||
self.supportsKanbanDiagnostics = supportsKanbanDiagnostics
|
|
||||||
self.effectiveHallucinationGate = effectiveHallucinationGate
|
|
||||||
self.onClose = onClose
|
self.onClose = onClose
|
||||||
self.onClaim = onClaim
|
self.onClaim = onClaim
|
||||||
self.onComplete = onComplete
|
self.onComplete = onComplete
|
||||||
@@ -65,8 +47,6 @@ struct KanbanInspectorPane: View {
|
|||||||
self.onUnblock = onUnblock
|
self.onUnblock = onUnblock
|
||||||
self.onArchive = onArchive
|
self.onArchive = onArchive
|
||||||
self.onReassign = onReassign
|
self.onReassign = onReassign
|
||||||
self.onVerifyHallucination = onVerifyHallucination
|
|
||||||
self.onRejectHallucination = onRejectHallucination
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
@@ -179,16 +159,6 @@ struct KanbanInspectorPane: View {
|
|||||||
ScarfBadge(workspace, kind: .neutral)
|
ScarfBadge(workspace, kind: .neutral)
|
||||||
.fixedSize()
|
.fixedSize()
|
||||||
}
|
}
|
||||||
// v0.13: max_retries chip. Read-only — Hermes
|
|
||||||
// has no `update --max-retries` verb. The
|
|
||||||
// `if let` guards pre-v0.13 hosts (always nil)
|
|
||||||
// and the explicit capability gate adds
|
|
||||||
// belt-and-suspenders.
|
|
||||||
if supportsKanbanDiagnostics, let maxRetries = task.maxRetries {
|
|
||||||
ScarfBadge("retries: \(maxRetries)", kind: .neutral)
|
|
||||||
.fixedSize()
|
|
||||||
.help("Max retries set at create time. Hermes has no update verb — re-create the task to change this.")
|
|
||||||
}
|
|
||||||
if let tenant = task.tenant, !tenant.isEmpty {
|
if let tenant = task.tenant, !tenant.isEmpty {
|
||||||
ScarfBadge(tenant, kind: .brand)
|
ScarfBadge(tenant, kind: .brand)
|
||||||
.fixedSize()
|
.fixedSize()
|
||||||
@@ -281,18 +251,13 @@ struct KanbanInspectorPane: View {
|
|||||||
// MARK: - Body
|
// MARK: - Body
|
||||||
|
|
||||||
/// Inline health banner shown above the task body when something
|
/// Inline health banner shown above the task body when something
|
||||||
/// requires user attention. Stack vertically (multiple can apply at
|
/// requires user attention. Two conditions trigger today:
|
||||||
/// once on a v0.13 task — e.g. unassigned + hallucination pending +
|
/// 1. Task is in `ready`/`todo` with no assignee — explains that
|
||||||
/// last-run-blocked).
|
/// the dispatcher silently skips unassigned tasks.
|
||||||
/// Order top-to-bottom:
|
/// 2. The most recent run ended in a non-success outcome
|
||||||
/// 1. **Hallucination gate (v0.13+)** — pending worker-created card.
|
/// (`stale_lock`/`crashed`/`gave_up`/`timed_out`/`spawn_failed`/
|
||||||
/// User must verify or reject before any other action makes sense.
|
/// `reclaimed`/`failed`) — surfaces the error so the user
|
||||||
/// 2. **Auto-blocked reason (v0.13+)** — server-supplied reason
|
/// doesn't have to dig into the Runs tab to discover it.
|
||||||
/// overrides the generic "Last run: blocked" banner.
|
|
||||||
/// 3. Task is in `ready`/`todo` with no assignee — explains that the
|
|
||||||
/// dispatcher silently skips unassigned tasks.
|
|
||||||
/// 4. The most recent run ended in a non-success outcome — surfaces
|
|
||||||
/// the error so the user doesn't have to dig into the Runs tab.
|
|
||||||
@ViewBuilder
|
@ViewBuilder
|
||||||
private func healthBanner(for task: HermesKanbanTask) -> some View {
|
private func healthBanner(for task: HermesKanbanTask) -> some View {
|
||||||
let status = KanbanStatus.from(task.status)
|
let status = KanbanStatus.from(task.status)
|
||||||
@@ -327,38 +292,6 @@ struct KanbanInspectorPane: View {
|
|||||||
// Also suppress for `done` (terminal success).
|
// Also suppress for `done` (terminal success).
|
||||||
let suppressFailureBanner = (status == .running) || (status == .done)
|
let suppressFailureBanner = (status == .running) || (status == .done)
|
||||||
|
|
||||||
// v0.13: hallucination-gate state. Read through the VM's
|
|
||||||
// optimistic-aware accessor so a Verify click takes effect
|
|
||||||
// before the polled state confirms. Belt-and-suspenders gate
|
|
||||||
// on capability flag.
|
|
||||||
let hallucination: KanbanHallucinationGate? = supportsKanbanDiagnostics
|
|
||||||
? effectiveHallucinationGate(task)
|
|
||||||
: nil
|
|
||||||
// v0.13: structured auto-blocked reason. Renders the server's
|
|
||||||
// string verbatim; takes precedence over the generic "Last run:
|
|
||||||
// blocked" banner.
|
|
||||||
let autoBlockedReason: String? = (supportsKanbanDiagnostics
|
|
||||||
&& status == .blocked
|
|
||||||
&& (task.autoBlockedReason?.isEmpty == false))
|
|
||||||
? task.autoBlockedReason
|
|
||||||
: nil
|
|
||||||
// Suppress the generic last-run banner when the more specific
|
|
||||||
// server-side reason supersedes it.
|
|
||||||
let suppressGenericFailure = autoBlockedReason != nil
|
|
||||||
|
|
||||||
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
|
|
||||||
if hallucination == .pending {
|
|
||||||
hallucinationBanner
|
|
||||||
}
|
|
||||||
if let reason = autoBlockedReason {
|
|
||||||
bannerRow(
|
|
||||||
icon: "exclamationmark.octagon.fill",
|
|
||||||
tint: ScarfColor.danger,
|
|
||||||
title: "Auto-blocked",
|
|
||||||
// Verbatim — Hermes-side message is the source of truth.
|
|
||||||
message: reason
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if needsAssignee {
|
if needsAssignee {
|
||||||
bannerRow(
|
bannerRow(
|
||||||
icon: "exclamationmark.triangle.fill",
|
icon: "exclamationmark.triangle.fill",
|
||||||
@@ -366,9 +299,7 @@ struct KanbanInspectorPane: View {
|
|||||||
title: "Won't run automatically",
|
title: "Won't run automatically",
|
||||||
message: "Unassigned tasks are silently skipped by Hermes's dispatcher. Add an assignee to get this scheduled."
|
message: "Unassigned tasks are silently skipped by Hermes's dispatcher. Add an assignee to get this scheduled."
|
||||||
)
|
)
|
||||||
}
|
} else if hadFailedEndedRun, let lastEndedRun, !suppressFailureBanner {
|
||||||
if hadFailedEndedRun, let lastEndedRun,
|
|
||||||
!suppressFailureBanner, !suppressGenericFailure {
|
|
||||||
let label = (lastEndedRun.outcome ?? lastEndedRun.status).lowercased()
|
let label = (lastEndedRun.outcome ?? lastEndedRun.status).lowercased()
|
||||||
let detail = lastEndedRun.error ?? lastEndedRun.summary ?? "no details"
|
let detail = lastEndedRun.error ?? lastEndedRun.summary ?? "no details"
|
||||||
bannerRow(
|
bannerRow(
|
||||||
@@ -378,84 +309,6 @@ struct KanbanInspectorPane: View {
|
|||||||
message: detail
|
message: detail
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
// v0.13: cross-run diagnostics on the task header.
|
|
||||||
if supportsKanbanDiagnostics, !task.diagnostics.isEmpty {
|
|
||||||
diagnosticsBlock(task.diagnostics)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// v0.13 hallucination-gate banner — Verify / Reject affordances for
|
|
||||||
/// worker-created cards waiting on user verification.
|
|
||||||
private var hallucinationBanner: some View {
|
|
||||||
HStack(alignment: .top, spacing: ScarfSpace.s2) {
|
|
||||||
Image(systemName: "questionmark.diamond.fill")
|
|
||||||
.foregroundStyle(ScarfColor.warning)
|
|
||||||
.font(.system(size: 13, weight: .semibold))
|
|
||||||
VStack(alignment: .leading, spacing: 4) {
|
|
||||||
Text("Created by a worker — verify before running")
|
|
||||||
.scarfStyle(.captionStrong)
|
|
||||||
.foregroundStyle(ScarfColor.foregroundPrimary)
|
|
||||||
Text("A worker claimed it created this card; Hermes hasn't confirmed the underlying work exists. Verify the card matches a real follow-up, or reject if it's a hallucinated reference.")
|
|
||||||
.scarfStyle(.caption)
|
|
||||||
.foregroundStyle(ScarfColor.foregroundMuted)
|
|
||||||
HStack(spacing: ScarfSpace.s2) {
|
|
||||||
Button("Verify", action: onVerifyHallucination)
|
|
||||||
.buttonStyle(ScarfPrimaryButton())
|
|
||||||
Button("Reject", action: onRejectHallucination)
|
|
||||||
.buttonStyle(ScarfDestructiveButton())
|
|
||||||
}
|
|
||||||
.padding(.top, 2)
|
|
||||||
}
|
|
||||||
Spacer(minLength: 0)
|
|
||||||
}
|
|
||||||
.padding(ScarfSpace.s2)
|
|
||||||
.background(
|
|
||||||
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
|
|
||||||
.fill(ScarfColor.warning.opacity(0.10))
|
|
||||||
)
|
|
||||||
.overlay(
|
|
||||||
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
|
|
||||||
.strokeBorder(ScarfColor.warning.opacity(0.4), lineWidth: 1)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// v0.13 diagnostics block — renders a list of distress signals.
|
|
||||||
/// Used both at the task-header level (cross-run signals) and per
|
|
||||||
/// run on the Runs tab (in-flight signals). Wraps in a horizontal
|
|
||||||
/// scroll so a long diag list doesn't blow out inspector width.
|
|
||||||
private func diagnosticsBlock(_ diags: [HermesKanbanDiagnostic]) -> some View {
|
|
||||||
VStack(alignment: .leading, spacing: 4) {
|
|
||||||
Text("Diagnostics")
|
|
||||||
.scarfStyle(.captionUppercase)
|
|
||||||
.foregroundStyle(ScarfColor.foregroundFaint)
|
|
||||||
ScrollView(.horizontal, showsIndicators: false) {
|
|
||||||
HStack(spacing: 4) {
|
|
||||||
ForEach(diags) { diag in
|
|
||||||
diagnosticBadge(diag)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.padding(.top, 4)
|
|
||||||
}
|
|
||||||
|
|
||||||
@ViewBuilder
|
|
||||||
private func diagnosticBadge(_ diag: HermesKanbanDiagnostic) -> some View {
|
|
||||||
let kind = KanbanDiagnosticKind.from(diag.kind)
|
|
||||||
let badgeKind: ScarfBadgeKind = {
|
|
||||||
switch kind.severity {
|
|
||||||
case .danger: return .danger
|
|
||||||
case .warning: return .warning
|
|
||||||
case .neutral: return .neutral
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
// Render the raw kind string — view code stays in sync with
|
|
||||||
// whatever future kinds Hermes ships. The typed mirror picks
|
|
||||||
// the badge tint and tooltip glyph; the verbatim wire string
|
|
||||||
// is the user-facing label.
|
|
||||||
ScarfBadge(diag.kind, kind: badgeKind)
|
|
||||||
.help(diag.message ?? diag.kind)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private func bannerRow(
|
private func bannerRow(
|
||||||
@@ -709,9 +562,6 @@ struct KanbanInspectorPane: View {
|
|||||||
private func runRow(_ run: HermesKanbanRun) -> some View {
|
private func runRow(_ run: HermesKanbanRun) -> some View {
|
||||||
VStack(alignment: .leading, spacing: 2) {
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
HStack(spacing: ScarfSpace.s2) {
|
HStack(spacing: ScarfSpace.s2) {
|
||||||
// Render the wire-side outcome / status string verbatim so
|
|
||||||
// v0.13's richer outcome strings ("zombied — reclaimed by
|
|
||||||
// reaper", etc.) surface unchanged.
|
|
||||||
ScarfBadge(run.outcome ?? run.status, kind: outcomeKind(run.outcome ?? run.status))
|
ScarfBadge(run.outcome ?? run.status, kind: outcomeKind(run.outcome ?? run.status))
|
||||||
if let profile = run.profile {
|
if let profile = run.profile {
|
||||||
Text(profile)
|
Text(profile)
|
||||||
@@ -735,12 +585,6 @@ struct KanbanInspectorPane: View {
|
|||||||
.foregroundStyle(ScarfColor.danger)
|
.foregroundStyle(ScarfColor.danger)
|
||||||
.frame(maxWidth: .infinity, alignment: .leading)
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
}
|
}
|
||||||
// v0.13: per-run diagnostics. Gated on capability so a future
|
|
||||||
// server-side change can't accidentally surface partial UX
|
|
||||||
// on a pre-v0.13 host.
|
|
||||||
if supportsKanbanDiagnostics, !run.diagnostics.isEmpty {
|
|
||||||
diagnosticsBlock(run.diagnostics)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
.padding(ScarfSpace.s2)
|
.padding(ScarfSpace.s2)
|
||||||
.background(
|
.background(
|
||||||
@@ -775,14 +619,6 @@ struct KanbanInspectorPane: View {
|
|||||||
@ViewBuilder
|
@ViewBuilder
|
||||||
private var primaryAction: some View {
|
private var primaryAction: some View {
|
||||||
if let task = viewModel.detail?.task {
|
if let task = viewModel.detail?.task {
|
||||||
// v0.13: when the hallucination gate is pending, suppress the
|
|
||||||
// primary action — the banner provides Verify / Reject as the
|
|
||||||
// gate. Showing "Start" alongside the banner would let the
|
|
||||||
// user dispatch a card Hermes hasn't confirmed exists.
|
|
||||||
if supportsKanbanDiagnostics,
|
|
||||||
effectiveHallucinationGate(task) == .pending {
|
|
||||||
EmptyView()
|
|
||||||
} else {
|
|
||||||
switch KanbanStatus.from(task.status) {
|
switch KanbanStatus.from(task.status) {
|
||||||
case .ready, .todo:
|
case .ready, .todo:
|
||||||
Button("Start", action: onClaim)
|
Button("Start", action: onClaim)
|
||||||
@@ -803,7 +639,6 @@ struct KanbanInspectorPane: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
@ViewBuilder
|
@ViewBuilder
|
||||||
private var secondaryActions: some View {
|
private var secondaryActions: some View {
|
||||||
|
|||||||
+140
@@ -0,0 +1,140 @@
|
|||||||
|
import Foundation
|
||||||
|
import ScarfCore
|
||||||
|
import os
|
||||||
|
|
||||||
|
/// View-model for the v0.13 Messaging Gateway behavior subsection composed
|
||||||
|
/// into each per-platform setup view. Owns the four v0.13 controls
|
||||||
|
/// (allowlist + three behavior toggles) so the existing per-platform VMs
|
||||||
|
/// don't grow another set of fields.
|
||||||
|
///
|
||||||
|
/// Capability-gated. Pre-v0.13 hosts skip the entire subsection (the
|
||||||
|
/// owning view returns `EmptyView` when none of the v0.13 flags is on),
|
||||||
|
/// so this VM never has its `save()` called against a host that can't
|
||||||
|
/// honor it.
|
||||||
|
@Observable
|
||||||
|
@MainActor
|
||||||
|
final class GatewayBehaviorViewModel {
|
||||||
|
private static let logger = Logger(subsystem: "com.scarf", category: "GatewayBehavior")
|
||||||
|
|
||||||
|
let platform: String
|
||||||
|
let context: ServerContext
|
||||||
|
let capabilities: HermesCapabilities
|
||||||
|
/// Allowlist kind for this platform, or `nil` for platforms without
|
||||||
|
/// an allowlist surface (Discord, Signal, etc. — `GatewayBehaviorSection`
|
||||||
|
/// short-circuits before instantiating this VM in that case, but the
|
||||||
|
/// field is `nil` for safety).
|
||||||
|
let kind: GatewayAllowlistKind?
|
||||||
|
|
||||||
|
// Allowlist
|
||||||
|
var items: [String] = []
|
||||||
|
|
||||||
|
// Behavior toggles
|
||||||
|
var busyAckEnabled: Bool = true
|
||||||
|
var gatewayRestartNotification: Bool = false
|
||||||
|
var slashCommandNoticeTTLSeconds: Int = 0
|
||||||
|
|
||||||
|
var message: String?
|
||||||
|
var isSaving: Bool = false
|
||||||
|
|
||||||
|
init(
|
||||||
|
platform: String,
|
||||||
|
capabilities: HermesCapabilities,
|
||||||
|
context: ServerContext = .local
|
||||||
|
) {
|
||||||
|
self.platform = platform
|
||||||
|
self.capabilities = capabilities
|
||||||
|
self.context = context
|
||||||
|
self.kind = GatewayAllowlistKind.kind(for: platform)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hydrate from `~/.hermes/config.yaml`. Called from the section's
|
||||||
|
/// `.onAppear`. Empty when the platform has no `gateway:` block in
|
||||||
|
/// the file — defaults match v0.13 server-side defaults so the form
|
||||||
|
/// looks identical to a fresh-install host.
|
||||||
|
func load() {
|
||||||
|
let cfg = HermesFileService(context: context).loadConfig()
|
||||||
|
let block = cfg.gatewayPlatforms[platform] ?? .empty
|
||||||
|
if let kind {
|
||||||
|
switch kind {
|
||||||
|
case .channels: items = block.allowedChannels
|
||||||
|
case .chats: items = block.allowedChats
|
||||||
|
case .rooms: items = block.allowedRooms
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
items = []
|
||||||
|
}
|
||||||
|
busyAckEnabled = block.busyAckEnabled
|
||||||
|
gatewayRestartNotification = block.gatewayRestartNotification
|
||||||
|
slashCommandNoticeTTLSeconds = block.slashCommandNoticeTTLSeconds
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Persist edits in two phases:
|
||||||
|
///
|
||||||
|
/// 1. **Allowlist write** via `GatewayConfigWriter.saveList` — direct
|
||||||
|
/// YAML edit, since `hermes config set` can't write list values.
|
||||||
|
/// Skipped when the platform has no `kind` (no allowlist surface)
|
||||||
|
/// or the host doesn't advertise `hasGatewayAllowlists`.
|
||||||
|
/// 2. **Scalar saves** via `PlatformSetupHelpers.saveForm` for the
|
||||||
|
/// three v0.13 behavior toggles. Each gated on its own capability
|
||||||
|
/// flag; the TTL field rides on the `hasGatewayBusyAckToggle ‖
|
||||||
|
/// hasGatewayRestartNotification` proxy (see WS-5 plan §Open Questions
|
||||||
|
/// Q5 + WS-1 Decision F).
|
||||||
|
func save() {
|
||||||
|
isSaving = true
|
||||||
|
defer {
|
||||||
|
isSaving = false
|
||||||
|
DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in
|
||||||
|
self?.message = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 1: list write via direct YAML edit. Detached so the SCP
|
||||||
|
// round-trip on remote hosts doesn't block MainActor — local
|
||||||
|
// writes are still cheap, but the same posture works for both.
|
||||||
|
if let kind, capabilities.hasGatewayAllowlists {
|
||||||
|
let trimmed = items
|
||||||
|
.map { $0.trimmingCharacters(in: .whitespaces) }
|
||||||
|
.filter { !$0.isEmpty }
|
||||||
|
let ok = GatewayConfigWriter.saveList(
|
||||||
|
context: context,
|
||||||
|
platform: platform,
|
||||||
|
key: kind.yamlKey,
|
||||||
|
items: trimmed
|
||||||
|
)
|
||||||
|
if !ok {
|
||||||
|
Self.logger.warning("GatewayConfigWriter.saveList failed for \(self.platform, privacy: .public)")
|
||||||
|
message = "Failed to write allowlist to config.yaml"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2: scalar saves via `hermes config set`.
|
||||||
|
var configKV: [String: String] = [:]
|
||||||
|
let prefix = "gateway.platforms.\(platform)."
|
||||||
|
if capabilities.hasGatewayBusyAckToggle {
|
||||||
|
configKV[prefix + "busy_ack_enabled"] =
|
||||||
|
PlatformSetupHelpers.envBool(busyAckEnabled)
|
||||||
|
}
|
||||||
|
if capabilities.hasGatewayRestartNotification {
|
||||||
|
configKV[prefix + "gateway_restart_notification"] =
|
||||||
|
PlatformSetupHelpers.envBool(gatewayRestartNotification)
|
||||||
|
}
|
||||||
|
// TTL field rides on either of the v0.13 toggles being available —
|
||||||
|
// proxy gating per WS-1 Decision F + WS-5 Q5. // TODO(WS-5-Q5)
|
||||||
|
if capabilities.hasGatewayBusyAckToggle
|
||||||
|
|| capabilities.hasGatewayRestartNotification {
|
||||||
|
configKV[prefix + "slash_command_notice_ttl_seconds"] =
|
||||||
|
String(slashCommandNoticeTTLSeconds)
|
||||||
|
}
|
||||||
|
|
||||||
|
if configKV.isEmpty {
|
||||||
|
message = "Allowlist saved — restart gateway to apply"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = PlatformSetupHelpers.saveForm(
|
||||||
|
context: context, envPairs: [:], configKV: configKV
|
||||||
|
)
|
||||||
|
message = result
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import SwiftUI
|
||||||
|
import ScarfCore
|
||||||
|
import ScarfDesign
|
||||||
|
|
||||||
|
/// Reusable list-of-strings editor for v0.13 cross-platform allowlists.
|
||||||
|
/// Shape: a vertical stack of rows, each with a delete glyph; an "Add row"
|
||||||
|
/// button at the bottom appends an empty entry.
|
||||||
|
///
|
||||||
|
/// Stateless — binds to the parent VM's `items` array. The VM owns
|
||||||
|
/// persistence and change tracking; this view is pure presentation.
|
||||||
|
struct AllowlistEditor: View {
|
||||||
|
@Binding var items: [String]
|
||||||
|
let kind: GatewayAllowlistKind
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
|
||||||
|
HStack {
|
||||||
|
Text("Allowed \(kind.pluralNoun)")
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||||
|
Spacer()
|
||||||
|
Text(itemsCountLabel)
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
|
}
|
||||||
|
|
||||||
|
if items.isEmpty {
|
||||||
|
Text("No restrictions — agent responds in any \(kind.noun).")
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
|
.padding(.vertical, ScarfSpace.s2)
|
||||||
|
} else {
|
||||||
|
VStack(spacing: 4) {
|
||||||
|
ForEach(Array(items.enumerated()), id: \.offset) { idx, _ in
|
||||||
|
AllowlistRow(
|
||||||
|
value: Binding(
|
||||||
|
get: { items[safe: idx] ?? "" },
|
||||||
|
set: { newValue in
|
||||||
|
guard idx < items.count else { return }
|
||||||
|
items[idx] = newValue
|
||||||
|
}
|
||||||
|
),
|
||||||
|
placeholder: kind.inputPlaceholder,
|
||||||
|
onDelete: {
|
||||||
|
guard idx < items.count else { return }
|
||||||
|
items.remove(at: idx)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
HStack {
|
||||||
|
Button {
|
||||||
|
items.append("")
|
||||||
|
} label: {
|
||||||
|
Label("Add \(kind.noun)", systemImage: "plus.circle")
|
||||||
|
.font(.caption)
|
||||||
|
}
|
||||||
|
.buttonStyle(.borderless)
|
||||||
|
Spacer()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.horizontal, ScarfSpace.s3)
|
||||||
|
.padding(.vertical, ScarfSpace.s2)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var itemsCountLabel: String {
|
||||||
|
let nonEmpty = items.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }.count
|
||||||
|
if nonEmpty == 0 { return "0 \(kind.pluralNoun)" }
|
||||||
|
if nonEmpty == 1 { return "1 \(kind.noun)" }
|
||||||
|
return "\(nonEmpty) \(kind.pluralNoun)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct AllowlistRow: View {
|
||||||
|
@Binding var value: String
|
||||||
|
let placeholder: String
|
||||||
|
let onDelete: () -> Void
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HStack(spacing: ScarfSpace.s2) {
|
||||||
|
TextField(placeholder, text: $value)
|
||||||
|
.textFieldStyle(.roundedBorder)
|
||||||
|
.font(ScarfFont.monoSmall)
|
||||||
|
Button {
|
||||||
|
onDelete()
|
||||||
|
} label: {
|
||||||
|
Image(systemName: "minus.circle.fill")
|
||||||
|
.foregroundStyle(ScarfColor.danger)
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.help("Remove")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private extension Array {
|
||||||
|
subscript(safe index: Int) -> Element? {
|
||||||
|
guard index >= 0, index < count else { return nil }
|
||||||
|
return self[index]
|
||||||
|
}
|
||||||
|
}
|
||||||
+96
@@ -0,0 +1,96 @@
|
|||||||
|
import SwiftUI
|
||||||
|
import ScarfCore
|
||||||
|
import ScarfDesign
|
||||||
|
|
||||||
|
/// v0.13 Messaging Gateway behavior subsection composed into each per-
|
||||||
|
/// platform setup view (Slack, Mattermost, Telegram, WhatsApp, Matrix,
|
||||||
|
/// Google Chat). Owns its own `@State` view-model so the existing per-
|
||||||
|
/// platform VMs don't grow another set of fields.
|
||||||
|
///
|
||||||
|
/// **Capability gating.** Hides itself entirely on pre-v0.13 hosts
|
||||||
|
/// (returns `EmptyView` when none of the three v0.13 flags is on). Each
|
||||||
|
/// internal control gates on its own flag, so a host that gains, say,
|
||||||
|
/// `hasGatewayAllowlists` but not `hasGatewayBusyAckToggle` still gets
|
||||||
|
/// the allowlist editor with the toggles hidden.
|
||||||
|
struct GatewayBehaviorSection: View {
|
||||||
|
let platform: String
|
||||||
|
let capabilities: HermesCapabilities
|
||||||
|
let context: ServerContext
|
||||||
|
|
||||||
|
@State private var viewModel: GatewayBehaviorViewModel
|
||||||
|
|
||||||
|
init(platform: String, capabilities: HermesCapabilities, context: ServerContext) {
|
||||||
|
self.platform = platform
|
||||||
|
self.capabilities = capabilities
|
||||||
|
self.context = context
|
||||||
|
_viewModel = State(initialValue: GatewayBehaviorViewModel(
|
||||||
|
platform: platform,
|
||||||
|
capabilities: capabilities,
|
||||||
|
context: context
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
// Pre-v0.13 host — hide the entire subsection so the existing
|
||||||
|
// platform forms look unchanged. Critical regression invariant
|
||||||
|
// per WS-5 plan §"How to test" #1.
|
||||||
|
if !capabilities.hasGatewayAllowlists
|
||||||
|
&& !capabilities.hasGatewayBusyAckToggle
|
||||||
|
&& !capabilities.hasGatewayRestartNotification {
|
||||||
|
EmptyView()
|
||||||
|
} else {
|
||||||
|
content
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var content: some View {
|
||||||
|
VStack(alignment: .leading, spacing: ScarfSpace.s3) {
|
||||||
|
SettingsSection(title: "Gateway behavior (v0.13+)", icon: "dot.radiowaves.left.and.right") {
|
||||||
|
if capabilities.hasGatewayAllowlists,
|
||||||
|
let kind = viewModel.kind {
|
||||||
|
AllowlistEditor(
|
||||||
|
items: $viewModel.items,
|
||||||
|
kind: kind
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if capabilities.hasGatewayBusyAckToggle {
|
||||||
|
ToggleRow(
|
||||||
|
label: "Send 'Agent is working…' ack",
|
||||||
|
isOn: viewModel.busyAckEnabled
|
||||||
|
) { viewModel.busyAckEnabled = $0 }
|
||||||
|
}
|
||||||
|
if capabilities.hasGatewayRestartNotification {
|
||||||
|
ToggleRow(
|
||||||
|
label: "Post 'Gateway restarted' notice on boot",
|
||||||
|
isOn: viewModel.gatewayRestartNotification
|
||||||
|
) { viewModel.gatewayRestartNotification = $0 }
|
||||||
|
}
|
||||||
|
// TTL field rides on either v0.13 toggle being available
|
||||||
|
// — proxy gating per WS-1 Decision F. // TODO(WS-5-Q5)
|
||||||
|
if capabilities.hasGatewayBusyAckToggle
|
||||||
|
|| capabilities.hasGatewayRestartNotification {
|
||||||
|
StepperRow(
|
||||||
|
label: "Auto-delete slash-command notices (s)",
|
||||||
|
value: viewModel.slashCommandNoticeTTLSeconds,
|
||||||
|
range: 0...3600,
|
||||||
|
step: 5
|
||||||
|
) { viewModel.slashCommandNoticeTTLSeconds = $0 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
HStack {
|
||||||
|
if let msg = viewModel.message {
|
||||||
|
Label(msg, systemImage: "checkmark.circle.fill")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.green)
|
||||||
|
}
|
||||||
|
Spacer()
|
||||||
|
Button("Save behavior") { viewModel.save() }
|
||||||
|
.buttonStyle(ScarfPrimaryButton())
|
||||||
|
.controlSize(.small)
|
||||||
|
.disabled(viewModel.isSaving)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.onAppear { viewModel.load() }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,13 @@ import ScarfDesign
|
|||||||
|
|
||||||
struct MatrixSetupView: View {
|
struct MatrixSetupView: View {
|
||||||
@State private var viewModel: MatrixSetupViewModel
|
@State private var viewModel: MatrixSetupViewModel
|
||||||
init(context: ServerContext) { _viewModel = State(initialValue: MatrixSetupViewModel(context: context)) }
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
let context: ServerContext
|
||||||
|
|
||||||
|
init(context: ServerContext) {
|
||||||
|
self.context = context
|
||||||
|
_viewModel = State(initialValue: MatrixSetupViewModel(context: context))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
@@ -45,6 +51,13 @@ struct MatrixSetupView: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
saveBar
|
saveBar
|
||||||
|
|
||||||
|
// v0.13 Messaging Gateway behavior — self-hides on pre-v0.13.
|
||||||
|
GatewayBehaviorSection(
|
||||||
|
platform: "matrix",
|
||||||
|
capabilities: capabilitiesStore?.capabilities ?? .empty,
|
||||||
|
context: context
|
||||||
|
)
|
||||||
}
|
}
|
||||||
.onAppear { viewModel.load() }
|
.onAppear { viewModel.load() }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,13 @@ import ScarfDesign
|
|||||||
|
|
||||||
struct MattermostSetupView: View {
|
struct MattermostSetupView: View {
|
||||||
@State private var viewModel: MattermostSetupViewModel
|
@State private var viewModel: MattermostSetupViewModel
|
||||||
init(context: ServerContext) { _viewModel = State(initialValue: MattermostSetupViewModel(context: context)) }
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
let context: ServerContext
|
||||||
|
|
||||||
|
init(context: ServerContext) {
|
||||||
|
self.context = context
|
||||||
|
_viewModel = State(initialValue: MattermostSetupViewModel(context: context))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
@@ -28,6 +34,13 @@ struct MattermostSetupView: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
saveBar
|
saveBar
|
||||||
|
|
||||||
|
// v0.13 Messaging Gateway behavior — self-hides on pre-v0.13.
|
||||||
|
GatewayBehaviorSection(
|
||||||
|
platform: "mattermost",
|
||||||
|
capabilities: capabilitiesStore?.capabilities ?? .empty,
|
||||||
|
context: context
|
||||||
|
)
|
||||||
}
|
}
|
||||||
.onAppear { viewModel.load() }
|
.onAppear { viewModel.load() }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,13 @@ import ScarfDesign
|
|||||||
|
|
||||||
struct SlackSetupView: View {
|
struct SlackSetupView: View {
|
||||||
@State private var viewModel: SlackSetupViewModel
|
@State private var viewModel: SlackSetupViewModel
|
||||||
init(context: ServerContext) { _viewModel = State(initialValue: SlackSetupViewModel(context: context)) }
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
let context: ServerContext
|
||||||
|
|
||||||
|
init(context: ServerContext) {
|
||||||
|
self.context = context
|
||||||
|
_viewModel = State(initialValue: SlackSetupViewModel(context: context))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
@@ -30,6 +36,13 @@ struct SlackSetupView: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
saveBar
|
saveBar
|
||||||
|
|
||||||
|
// v0.13 Messaging Gateway behavior — self-hides on pre-v0.13.
|
||||||
|
GatewayBehaviorSection(
|
||||||
|
platform: "slack",
|
||||||
|
capabilities: capabilitiesStore?.capabilities ?? .empty,
|
||||||
|
context: context
|
||||||
|
)
|
||||||
}
|
}
|
||||||
.onAppear { viewModel.load() }
|
.onAppear { viewModel.load() }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,13 @@ import ScarfDesign
|
|||||||
|
|
||||||
struct TelegramSetupView: View {
|
struct TelegramSetupView: View {
|
||||||
@State private var viewModel: TelegramSetupViewModel
|
@State private var viewModel: TelegramSetupViewModel
|
||||||
init(context: ServerContext) { _viewModel = State(initialValue: TelegramSetupViewModel(context: context)) }
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
let context: ServerContext
|
||||||
|
|
||||||
|
init(context: ServerContext) {
|
||||||
|
self.context = context
|
||||||
|
_viewModel = State(initialValue: TelegramSetupViewModel(context: context))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
@@ -29,6 +35,13 @@ struct TelegramSetupView: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
saveBar
|
saveBar
|
||||||
|
|
||||||
|
// v0.13 Messaging Gateway behavior — self-hides on pre-v0.13.
|
||||||
|
GatewayBehaviorSection(
|
||||||
|
platform: "telegram",
|
||||||
|
capabilities: capabilitiesStore?.capabilities ?? .empty,
|
||||||
|
context: context
|
||||||
|
)
|
||||||
}
|
}
|
||||||
.onAppear { viewModel.load() }
|
.onAppear { viewModel.load() }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,13 @@ import ScarfDesign
|
|||||||
|
|
||||||
struct WhatsAppSetupView: View {
|
struct WhatsAppSetupView: View {
|
||||||
@State private var viewModel: WhatsAppSetupViewModel
|
@State private var viewModel: WhatsAppSetupViewModel
|
||||||
init(context: ServerContext) { _viewModel = State(initialValue: WhatsAppSetupViewModel(context: context)) }
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
let context: ServerContext
|
||||||
|
|
||||||
|
init(context: ServerContext) {
|
||||||
|
self.context = context
|
||||||
|
_viewModel = State(initialValue: WhatsAppSetupViewModel(context: context))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
@@ -29,6 +35,14 @@ struct WhatsAppSetupView: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
saveBar
|
saveBar
|
||||||
|
|
||||||
|
// v0.13 Messaging Gateway behavior — self-hides on pre-v0.13.
|
||||||
|
GatewayBehaviorSection(
|
||||||
|
platform: "whatsapp",
|
||||||
|
capabilities: capabilitiesStore?.capabilities ?? .empty,
|
||||||
|
context: context
|
||||||
|
)
|
||||||
|
|
||||||
Divider()
|
Divider()
|
||||||
pairingSection
|
pairingSection
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,33 @@ import ScarfDesign
|
|||||||
struct PlatformsView: View {
|
struct PlatformsView: View {
|
||||||
@State private var viewModel: PlatformsViewModel
|
@State private var viewModel: PlatformsViewModel
|
||||||
@Environment(HermesFileWatcher.self) private var fileWatcher
|
@Environment(HermesFileWatcher.self) private var fileWatcher
|
||||||
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
|
||||||
|
/// Capabilities resolved at view-eval time. Defaults to `.empty` outside
|
||||||
|
/// the per-server `ContextBoundRoot`. Used to filter `KnownPlatforms.all`
|
||||||
|
/// for v0.13-only entries (Google Chat) — see `visiblePlatforms` for
|
||||||
|
/// the deliberate asymmetry: pre-v0.12 hosts still see Yuanbao + Teams
|
||||||
|
/// unfiltered, by design.
|
||||||
|
private var capabilities: HermesCapabilities {
|
||||||
|
capabilitiesStore?.capabilities ?? .empty
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Capability-filtered platform list. Today only **Google Chat** is
|
||||||
|
/// gated — Yuanbao and Microsoft Teams stay unfiltered to avoid
|
||||||
|
/// changing v0.12 host UX in a v0.13 work-stream (WS-5 plan §Q4).
|
||||||
|
/// If we later decide to gate the v0.12 platforms too, add their
|
||||||
|
/// flags here; the `default: true` arm keeps every other platform
|
||||||
|
/// visible.
|
||||||
|
private var visiblePlatforms: [HermesToolPlatform] {
|
||||||
|
KnownPlatforms.all.filter { p in
|
||||||
|
switch p.name {
|
||||||
|
case "google-chat", "googlechat":
|
||||||
|
return capabilities.hasGoogleChatPlatform
|
||||||
|
default:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
init(context: ServerContext) {
|
init(context: ServerContext) {
|
||||||
_viewModel = State(initialValue: PlatformsViewModel(context: context))
|
_viewModel = State(initialValue: PlatformsViewModel(context: context))
|
||||||
@@ -40,12 +67,12 @@ struct PlatformsView: View {
|
|||||||
List(selection: Binding(
|
List(selection: Binding(
|
||||||
get: { viewModel.selected.name },
|
get: { viewModel.selected.name },
|
||||||
set: { name in
|
set: { name in
|
||||||
if let p = viewModel.platforms.first(where: { $0.name == name }) {
|
if let p = visiblePlatforms.first(where: { $0.name == name }) {
|
||||||
viewModel.selected = p
|
viewModel.selected = p
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)) {
|
)) {
|
||||||
ForEach(viewModel.platforms) { platform in
|
ForEach(visiblePlatforms) { platform in
|
||||||
HStack(spacing: 8) {
|
HStack(spacing: 8) {
|
||||||
Image(systemName: KnownPlatforms.icon(for: platform.name))
|
Image(systemName: KnownPlatforms.icon(for: platform.name))
|
||||||
.frame(width: 20)
|
.frame(width: 20)
|
||||||
@@ -149,6 +176,7 @@ struct PlatformsView: View {
|
|||||||
case "webhook": WebhookSetupView(context: ctx)
|
case "webhook": WebhookSetupView(context: ctx)
|
||||||
case "yuanbao": yuanbaoPanel
|
case "yuanbao": yuanbaoPanel
|
||||||
case "microsoft-teams": microsoftTeamsPanel
|
case "microsoft-teams": microsoftTeamsPanel
|
||||||
|
case "google-chat", "googlechat": googleChatPanel
|
||||||
default:
|
default:
|
||||||
SettingsSection(title: LocalizedStringKey(viewModel.selected.displayName), icon: KnownPlatforms.icon(for: viewModel.selected.name)) {
|
SettingsSection(title: LocalizedStringKey(viewModel.selected.displayName), icon: KnownPlatforms.icon(for: viewModel.selected.name)) {
|
||||||
ReadOnlyRow(label: "Setup", value: "No setup form for this platform yet.")
|
ReadOnlyRow(label: "Setup", value: "No setup form for this platform yet.")
|
||||||
@@ -180,6 +208,27 @@ struct PlatformsView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Hermes v0.13 — Google Chat is the 20th gateway platform. Like
|
||||||
|
/// Yuanbao + Microsoft Teams, the auth dance is OAuth-style and
|
||||||
|
/// lives outside Scarf, so the panel surfaces the setup verb rather
|
||||||
|
/// than a per-field form. The `GatewayBehaviorSection` below it picks
|
||||||
|
/// up the v0.13 allowlist + behavior toggles, capability-gated.
|
||||||
|
@ViewBuilder
|
||||||
|
private var googleChatPanel: some View {
|
||||||
|
VStack(alignment: .leading, spacing: ScarfSpace.s3) {
|
||||||
|
SettingsSection(title: "Google Chat", icon: KnownPlatforms.icon(for: "google-chat")) {
|
||||||
|
ReadOnlyRow(label: "Type", value: "Generic env-driven gateway adapter (v0.13+)")
|
||||||
|
ReadOnlyRow(label: "Setup", value: "Run `hermes setup` and select Google Chat to walk the OAuth flow.")
|
||||||
|
ReadOnlyRow(label: "Configured", value: viewModel.hasConfigBlock(for: viewModel.selected) ? "Yes" : "No")
|
||||||
|
}
|
||||||
|
GatewayBehaviorSection(
|
||||||
|
platform: "google-chat",
|
||||||
|
capabilities: capabilities,
|
||||||
|
context: viewModel.context
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private var cliPanel: some View {
|
private var cliPanel: some View {
|
||||||
SettingsSection(title: "CLI", icon: "terminal") {
|
SettingsSection(title: "CLI", icon: "terminal") {
|
||||||
ReadOnlyRow(label: "Scope", value: "Local terminal sessions")
|
ReadOnlyRow(label: "Scope", value: "Local terminal sessions")
|
||||||
|
|||||||
@@ -307,6 +307,16 @@ struct SkillsView: View {
|
|||||||
case .missing(let hint) = designMdNpxStatus {
|
case .missing(let hint) = designMdNpxStatus {
|
||||||
designMdNpxBanner(hint: hint)
|
designMdNpxBanner(hint: hint)
|
||||||
}
|
}
|
||||||
|
// v0.13 `[[as_document]]` directive — informational
|
||||||
|
// only. Rendered when the skill body contains the
|
||||||
|
// marker AND the host advertises Google Chat support
|
||||||
|
// (cheap proxy: the directive shipped in v0.13
|
||||||
|
// alongside Google Chat — see WS-5 plan §Q5/Q6).
|
||||||
|
if (capabilitiesStore?.capabilities.hasGoogleChatPlatform ?? false),
|
||||||
|
skillContentMentionsAsDocument {
|
||||||
|
asDocumentInfoRow
|
||||||
|
}
|
||||||
|
|
||||||
// v2.5 SKILL.md frontmatter chips. Render only the
|
// v2.5 SKILL.md frontmatter chips. Render only the
|
||||||
// sections that are populated — old skills without
|
// sections that are populated — old skills without
|
||||||
// this metadata show no extra rows.
|
// this metadata show no extra rows.
|
||||||
@@ -402,6 +412,39 @@ struct SkillsView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns true when the loaded skill body contains the v0.13
|
||||||
|
/// `[[as_document]]` directive. Substring scan over `skillContent`
|
||||||
|
/// — `[[as_document]]` is a literal token Hermes pattern-matches at
|
||||||
|
/// runtime, not a frontmatter key, so the body is the right place
|
||||||
|
/// to look. // TODO(WS-5-Q6): if Hermes ever moves the directive
|
||||||
|
/// into frontmatter, switch to `SkillFrontmatterParser` instead.
|
||||||
|
private var skillContentMentionsAsDocument: Bool {
|
||||||
|
viewModel.skillContent.contains("[[as_document]]")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compact informational row about the `[[as_document]]` directive.
|
||||||
|
/// Does not block any action — it's a label so users understand why
|
||||||
|
/// images in the skill might land as document attachments on certain
|
||||||
|
/// platforms (Google Chat, Microsoft Teams) rather than inline.
|
||||||
|
private var asDocumentInfoRow: some View {
|
||||||
|
HStack(alignment: .top, spacing: 8) {
|
||||||
|
Image(systemName: "doc.badge.gearshape")
|
||||||
|
.foregroundStyle(.blue)
|
||||||
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
|
Text("Document-attachment directive present (v0.13+)")
|
||||||
|
.font(.caption.bold())
|
||||||
|
Text("Media in this skill marked with `[[as_document]]` is sent as document attachments instead of inline images on platforms that distinguish (Google Chat, Microsoft Teams).")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(10)
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
.background(.blue.opacity(0.08))
|
||||||
|
.clipShape(RoundedRectangle(cornerRadius: 8))
|
||||||
|
}
|
||||||
|
|
||||||
/// Yellow banner surfaced on the design-md skill detail when the
|
/// Yellow banner surfaced on the design-md skill detail when the
|
||||||
/// host's `npx` probe came back missing. Reuses the same color
|
/// host's `npx` probe came back missing. Reuses the same color
|
||||||
/// language as the missing-config banner.
|
/// language as the missing-config banner.
|
||||||
|
|||||||
Reference in New Issue
Block a user