mirror of
https://github.com/awizemann/scarf.git
synced 2026-05-10 18:44:45 +00:00
Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a8cdb3e663 | |||
| 441d11404f | |||
| 6e8480411a | |||
| 3a764e81e0 | |||
| 6e90741a17 | |||
| 93a3b40a67 | |||
| 52f0ddb36c | |||
| b4482e5ee7 | |||
| 4757b5ae49 | |||
| 0070441243 | |||
| 57a6340985 | |||
| 0f78856e6e | |||
| 5877bf6519 | |||
| f19f19cd56 | |||
| 6c96fcfa43 | |||
| edac142d08 | |||
| fd33b714e3 | |||
| c81a8a56e8 |
@@ -173,6 +173,10 @@ v0.10.0 introduced the **Tool Gateway** — paid Nous Portal subscribers route w
|
|||||||
|
|
||||||
**Keep `ModelCatalogService.overlayOnlyProviders` in sync** with `HERMES_OVERLAYS` in `~/.hermes/hermes-agent/hermes_cli/providers.py`. When Hermes adds a new overlay-only provider, mirror the entry (display name, base URL, auth type, subscription-gated flag, doc URL) or the picker won't reach it.
|
**Keep `ModelCatalogService.overlayOnlyProviders` in sync** with `HERMES_OVERLAYS` in `~/.hermes/hermes-agent/hermes_cli/providers.py`. When Hermes adds a new overlay-only provider, mirror the entry (display name, base URL, auth type, subscription-gated flag, doc URL) or the picker won't reach it.
|
||||||
|
|
||||||
|
**Keep `ModelCatalogService.modelAliases` in sync** with Hermes's deprecated-model-ID map (currently release-notes-only upstream; the canonical successor lives in `hermes_cli/providers.py` if/when upstream tracks it in code). Drift here means a user's old model ID stops resolving in the picker even though Hermes still accepts it at runtime.
|
||||||
|
|
||||||
|
**Keep `ModelCatalogService.demotedProviders` in sync** with the deprioritized-provider list in `hermes-agent/hermes_cli/providers.py`. Drift means Vercel AI Gateway (or any future demoted provider) sorts in the wrong position in Scarf's picker.
|
||||||
|
|
||||||
## Kanban v3: drag-and-drop board + per-project tenants (v2.7.5)
|
## Kanban v3: drag-and-drop board + per-project tenants (v2.7.5)
|
||||||
|
|
||||||
Scarf v2.7.5 promotes Kanban from a read-only list to a full board with drag-and-drop, every Hermes write verb wired up, and per-project boards bound to a Scarf-minted tenant slug. The list view is preserved as a `Board | List` toggle for accessibility / narrow-window fallback.
|
Scarf v2.7.5 promotes Kanban from a read-only list to a full board with drag-and-drop, every Hermes write verb wired up, and per-project boards bound to a Scarf-minted tenant slug. The list view is preserved as a `Board | List` toggle for accessibility / narrow-window fallback.
|
||||||
|
|||||||
@@ -311,6 +311,14 @@ public actor ACPClient {
|
|||||||
let result = try await sendRequest(method: "session/prompt", params: params)
|
let result = try await sendRequest(method: "session/prompt", params: params)
|
||||||
let dict = result?.dictValue ?? [:]
|
let dict = result?.dictValue ?? [:]
|
||||||
let usage = dict["usage"] as? [String: Any] ?? [:]
|
let usage = dict["usage"] as? [String: Any] ?? [:]
|
||||||
|
// TODO(WS-8-Q1): Confirm wire field name once v0.13 Hermes is
|
||||||
|
// available. We tolerate camelCase + snake_case to match the rest
|
||||||
|
// of the ACP payload's mixed conventions; if Hermes routes the
|
||||||
|
// count through a `session/update` notification instead, this
|
||||||
|
// decode is a no-op and the ACPEvent path takes over.
|
||||||
|
let compression = (usage["compressionCount"] as? Int)
|
||||||
|
?? (usage["compression_count"] as? Int)
|
||||||
|
?? 0
|
||||||
|
|
||||||
statusMessage = "Ready"
|
statusMessage = "Ready"
|
||||||
return ACPPromptResult(
|
return ACPPromptResult(
|
||||||
@@ -318,7 +326,8 @@ public actor ACPClient {
|
|||||||
inputTokens: usage["inputTokens"] as? Int ?? 0,
|
inputTokens: usage["inputTokens"] as? Int ?? 0,
|
||||||
outputTokens: usage["outputTokens"] as? Int ?? 0,
|
outputTokens: usage["outputTokens"] as? Int ?? 0,
|
||||||
thoughtTokens: usage["thoughtTokens"] as? Int ?? 0,
|
thoughtTokens: usage["thoughtTokens"] as? Int ?? 0,
|
||||||
cachedReadTokens: usage["cachedReadTokens"] as? Int ?? 0
|
cachedReadTokens: usage["cachedReadTokens"] as? Int ?? 0,
|
||||||
|
compressionCount: compression
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -243,19 +243,32 @@ public struct ACPPromptResult: Sendable {
|
|||||||
public let outputTokens: Int
|
public let outputTokens: Int
|
||||||
public let thoughtTokens: Int
|
public let thoughtTokens: Int
|
||||||
public let cachedReadTokens: Int
|
public let cachedReadTokens: Int
|
||||||
|
/// Number of automatic context compactions Hermes has performed on this
|
||||||
|
/// session so far. v0.13+ — older Hermes hosts always return 0, which
|
||||||
|
/// the chat status bar treats as "hide chip". Optional in the wire
|
||||||
|
/// payload; folded into a non-optional `Int` here with a 0 default so
|
||||||
|
/// the rest of the pipeline doesn't need to nil-check.
|
||||||
|
// TODO(WS-8-Q1): Verify that v0.13 Hermes emits the count on
|
||||||
|
// `session/prompt`'s `usage` blob (assumed here). If it lands on a
|
||||||
|
// separate `session/update` notification instead, this becomes a new
|
||||||
|
// ACPEvent case + a branch in RichChatViewModel.handleACPEvent — wire
|
||||||
|
// shape is documented in the WS-8 plan as the bigger fix path.
|
||||||
|
public let compressionCount: Int
|
||||||
|
|
||||||
public init(
|
public init(
|
||||||
stopReason: String,
|
stopReason: String,
|
||||||
inputTokens: Int,
|
inputTokens: Int,
|
||||||
outputTokens: Int,
|
outputTokens: Int,
|
||||||
thoughtTokens: Int,
|
thoughtTokens: Int,
|
||||||
cachedReadTokens: Int
|
cachedReadTokens: Int,
|
||||||
|
compressionCount: Int = 0
|
||||||
) {
|
) {
|
||||||
self.stopReason = stopReason
|
self.stopReason = stopReason
|
||||||
self.inputTokens = inputTokens
|
self.inputTokens = inputTokens
|
||||||
self.outputTokens = outputTokens
|
self.outputTokens = outputTokens
|
||||||
self.thoughtTokens = thoughtTokens
|
self.thoughtTokens = thoughtTokens
|
||||||
self.cachedReadTokens = cachedReadTokens
|
self.cachedReadTokens = cachedReadTokens
|
||||||
|
self.compressionCount = compressionCount
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Errors thrown by `CuratorService`. Each case carries enough detail
|
||||||
|
/// to render a user-actionable message — the view model surfaces these
|
||||||
|
/// inline as a banner above the leaderboard rather than blocking with a
|
||||||
|
/// modal alert.
|
||||||
|
public enum CuratorError: Error, LocalizedError, Sendable {
|
||||||
|
/// `hermes` binary couldn't be located.
|
||||||
|
case cliMissing
|
||||||
|
/// Subprocess returned non-zero exit. `stderr` may carry a synthetic
|
||||||
|
/// message when the transport itself failed.
|
||||||
|
case nonZeroExit(verb: String, code: Int32, stderr: String)
|
||||||
|
/// JSON decoding failed. Underlying message wrapped for diagnostics.
|
||||||
|
case decoding(verb: String, message: String)
|
||||||
|
/// Generic transport error — process couldn't start, IO failed, etc.
|
||||||
|
case transport(message: String)
|
||||||
|
|
||||||
|
public var errorDescription: String? {
|
||||||
|
switch self {
|
||||||
|
case .cliMissing:
|
||||||
|
return "Hermes CLI couldn't be found. Install Hermes v0.13+ and ensure it's on your PATH."
|
||||||
|
case .nonZeroExit(let verb, let code, let stderr):
|
||||||
|
let trimmed = stderr.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
if trimmed.isEmpty {
|
||||||
|
return "`hermes curator \(verb)` exited with code \(code)."
|
||||||
|
}
|
||||||
|
return trimmed
|
||||||
|
case .decoding(let verb, let message):
|
||||||
|
return "Couldn't decode `hermes curator \(verb)` output: \(message)"
|
||||||
|
case .transport(let message):
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Optimistic local mirror of the agent's currently-locked goal (set via
|
||||||
|
/// the `/goal <text>` slash command, Hermes v0.13+). Scarf records this
|
||||||
|
/// the moment the user sends `/goal …` so the chat header pill appears
|
||||||
|
/// synchronously, without waiting for a server round-trip. There is no
|
||||||
|
/// authoritative read-back path in v2.8.0 — see WS-2 plan Q1.
|
||||||
|
///
|
||||||
|
/// Plain value type, no mutation API. Drives the goal pill in
|
||||||
|
/// `SessionInfoBar` and the inspector contextual menu.
|
||||||
|
public struct HermesActiveGoal: Sendable, Equatable, Identifiable {
|
||||||
|
/// The user's verbatim goal text (post-trim).
|
||||||
|
public let text: String
|
||||||
|
/// When Scarf observed the `/goal` send. Local clock — not the
|
||||||
|
/// server's authoritative timestamp.
|
||||||
|
public let setAt: Date
|
||||||
|
|
||||||
|
public var id: String {
|
||||||
|
text + "@" + ISO8601DateFormatter().string(from: setAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
public init(text: String, setAt: Date) {
|
||||||
|
self.text = text
|
||||||
|
self.setAt = setAt
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -36,6 +36,13 @@ public struct DisplaySettings: Sendable, Equatable {
|
|||||||
public var toolProgressCommand: Bool
|
public var toolProgressCommand: Bool
|
||||||
public var toolPreviewLength: Int
|
public var toolPreviewLength: Int
|
||||||
public var busyInputMode: String // e.g. "interrupt"
|
public var busyInputMode: String // e.g. "interrupt"
|
||||||
|
/// Static-message translation language. v0.13+. Empty string means
|
||||||
|
/// "follow Hermes default" — the picker collapses both empty-string
|
||||||
|
/// and `"en"` to "English" in display, but only writes a value when
|
||||||
|
/// the user explicitly picks one. Persisted via
|
||||||
|
/// `hermes config set display.language <code>`. Supported values per
|
||||||
|
/// v0.13 release notes: `en`, `zh`, `ja`, `de`, `es`, `fr`, `uk`, `tr`.
|
||||||
|
public var language: String
|
||||||
|
|
||||||
|
|
||||||
public init(
|
public init(
|
||||||
@@ -46,7 +53,8 @@ public struct DisplaySettings: Sendable, Equatable {
|
|||||||
inlineDiffs: Bool,
|
inlineDiffs: Bool,
|
||||||
toolProgressCommand: Bool,
|
toolProgressCommand: Bool,
|
||||||
toolPreviewLength: Int,
|
toolPreviewLength: Int,
|
||||||
busyInputMode: String
|
busyInputMode: String,
|
||||||
|
language: String = ""
|
||||||
) {
|
) {
|
||||||
self.skin = skin
|
self.skin = skin
|
||||||
self.compact = compact
|
self.compact = compact
|
||||||
@@ -56,6 +64,7 @@ public struct DisplaySettings: Sendable, Equatable {
|
|||||||
self.toolProgressCommand = toolProgressCommand
|
self.toolProgressCommand = toolProgressCommand
|
||||||
self.toolPreviewLength = toolPreviewLength
|
self.toolPreviewLength = toolPreviewLength
|
||||||
self.busyInputMode = busyInputMode
|
self.busyInputMode = busyInputMode
|
||||||
|
self.language = language
|
||||||
}
|
}
|
||||||
public nonisolated static let empty = DisplaySettings(
|
public nonisolated static let empty = DisplaySettings(
|
||||||
skin: "default",
|
skin: "default",
|
||||||
@@ -65,7 +74,8 @@ public struct DisplaySettings: Sendable, Equatable {
|
|||||||
inlineDiffs: true,
|
inlineDiffs: true,
|
||||||
toolProgressCommand: false,
|
toolProgressCommand: false,
|
||||||
toolPreviewLength: 0,
|
toolPreviewLength: 0,
|
||||||
busyInputMode: "interrupt"
|
busyInputMode: "interrupt",
|
||||||
|
language: ""
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,6 +200,15 @@ public struct VoiceSettings: Sendable, Equatable {
|
|||||||
public var ttsOpenAIVoice: String
|
public var ttsOpenAIVoice: String
|
||||||
public var ttsNeuTTSModel: String
|
public var ttsNeuTTSModel: String
|
||||||
public var ttsNeuTTSDevice: String
|
public var ttsNeuTTSDevice: String
|
||||||
|
/// xAI TTS voice identifier. v0.13+ — xAI shipped TTS earlier but the
|
||||||
|
/// custom-voice / cloning surface is the v0.13 add-on.
|
||||||
|
// TODO(WS-8-Q2): Confirm key name vs `tts.xai.voice` /
|
||||||
|
// `tts.xai.voice_id` / a top-level `tts.xai_voice` once a v0.13
|
||||||
|
// host is on hand. The setter / YAML reader follow whatever this
|
||||||
|
// field name implies.
|
||||||
|
public var ttsXAIVoiceID: String
|
||||||
|
/// xAI TTS model identifier. v0.13+. Mirrors the elevenlabs shape.
|
||||||
|
public var ttsXAIModel: String
|
||||||
|
|
||||||
// STT
|
// STT
|
||||||
public var sttEnabled: Bool
|
public var sttEnabled: Bool
|
||||||
@@ -217,7 +236,9 @@ public struct VoiceSettings: Sendable, Equatable {
|
|||||||
sttLocalModel: String,
|
sttLocalModel: String,
|
||||||
sttLocalLanguage: String,
|
sttLocalLanguage: String,
|
||||||
sttOpenAIModel: String,
|
sttOpenAIModel: String,
|
||||||
sttMistralModel: String
|
sttMistralModel: String,
|
||||||
|
ttsXAIVoiceID: String = "",
|
||||||
|
ttsXAIModel: String = ""
|
||||||
) {
|
) {
|
||||||
self.recordKey = recordKey
|
self.recordKey = recordKey
|
||||||
self.maxRecordingSeconds = maxRecordingSeconds
|
self.maxRecordingSeconds = maxRecordingSeconds
|
||||||
@@ -230,6 +251,8 @@ public struct VoiceSettings: Sendable, Equatable {
|
|||||||
self.ttsOpenAIVoice = ttsOpenAIVoice
|
self.ttsOpenAIVoice = ttsOpenAIVoice
|
||||||
self.ttsNeuTTSModel = ttsNeuTTSModel
|
self.ttsNeuTTSModel = ttsNeuTTSModel
|
||||||
self.ttsNeuTTSDevice = ttsNeuTTSDevice
|
self.ttsNeuTTSDevice = ttsNeuTTSDevice
|
||||||
|
self.ttsXAIVoiceID = ttsXAIVoiceID
|
||||||
|
self.ttsXAIModel = ttsXAIModel
|
||||||
self.sttEnabled = sttEnabled
|
self.sttEnabled = sttEnabled
|
||||||
self.sttProvider = sttProvider
|
self.sttProvider = sttProvider
|
||||||
self.sttLocalModel = sttLocalModel
|
self.sttLocalModel = sttLocalModel
|
||||||
@@ -254,7 +277,9 @@ public struct VoiceSettings: Sendable, Equatable {
|
|||||||
sttLocalModel: "base",
|
sttLocalModel: "base",
|
||||||
sttLocalLanguage: "",
|
sttLocalLanguage: "",
|
||||||
sttOpenAIModel: "whisper-1",
|
sttOpenAIModel: "whisper-1",
|
||||||
sttMistralModel: "voxtral-mini-latest"
|
sttMistralModel: "voxtral-mini-latest",
|
||||||
|
ttsXAIVoiceID: "",
|
||||||
|
ttsXAIModel: ""
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -666,6 +691,48 @@ public struct HermesConfig: Sendable {
|
|||||||
/// final reply (provider/model/cost/turn count). Off by default;
|
/// final reply (provider/model/cost/turn count). Off by default;
|
||||||
/// useful for cost auditing and screen-recording demos.
|
/// useful for cost auditing and screen-recording demos.
|
||||||
public var runtimeMetadataFooter: Bool
|
public var runtimeMetadataFooter: Bool
|
||||||
|
/// Pre-v0.13: single combined Web Tools backend at `web_tools.backend`.
|
||||||
|
/// v0.13 split this into per-capability keys (see below). Kept readable
|
||||||
|
/// for round-trip compatibility on hosts that never migrated; v0.13+
|
||||||
|
/// hosts ignore this scalar and read the split keys instead.
|
||||||
|
public var webToolsBackend: String
|
||||||
|
/// v0.13+: `web_tools.search.backend`. SearXNG is search-only and
|
||||||
|
/// can land here. Pre-v0.13 hosts default to the same value as the
|
||||||
|
/// combined backend.
|
||||||
|
public var webToolsSearchBackend: String
|
||||||
|
/// v0.13+: `web_tools.extract.backend`. Pre-v0.13 hosts default to
|
||||||
|
/// the same value as the combined backend.
|
||||||
|
public var webToolsExtractBackend: String
|
||||||
|
|
||||||
|
// -- 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]
|
||||||
|
|
||||||
|
/// `image_gen.model` (v0.13+) — overrides the per-provider default
|
||||||
|
/// image-gen model. Empty string means "let Hermes pick the
|
||||||
|
/// provider default". Hermes v0.12 advertised this key but ignored
|
||||||
|
/// it; Scarf's `AuxiliaryTab` only renders the picker when
|
||||||
|
/// `HermesCapabilities.hasImageGenModel` is `true`.
|
||||||
|
public var imageGenModel: String
|
||||||
|
|
||||||
|
/// `openrouter.response_cache.enabled` (v0.13+) — when true, Hermes
|
||||||
|
/// asks OpenRouter to cache responses for repeat prompts within a
|
||||||
|
/// session. Off by default in Scarf's parser per WS-6 plan
|
||||||
|
/// recommendation. UI gated on
|
||||||
|
/// `HermesCapabilities.hasOpenRouterResponseCache`.
|
||||||
|
// TODO(WS-6-Q1): the exact YAML key shape is provisional. Verify
|
||||||
|
// against a v0.13 host's `hermes config check` output before
|
||||||
|
// shipping (see WS-6-plan §Open Questions #1). Candidate alternative
|
||||||
|
// shapes: `providers.openrouter.response_cache_enabled` or
|
||||||
|
// `prompt_caching.openrouter.enabled`.
|
||||||
|
public var openrouterResponseCacheEnabled: Bool
|
||||||
|
|
||||||
// Grouped blocks
|
// Grouped blocks
|
||||||
public var display: DisplaySettings
|
public var display: DisplaySettings
|
||||||
@@ -747,11 +814,23 @@ 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] = [:],
|
||||||
|
imageGenModel: String = "",
|
||||||
|
openrouterResponseCacheEnabled: Bool = false,
|
||||||
|
webToolsBackend: String = "duckduckgo",
|
||||||
|
webToolsSearchBackend: String = "duckduckgo",
|
||||||
|
webToolsExtractBackend: String = "reader"
|
||||||
) {
|
) {
|
||||||
self.cacheTTL = cacheTTL
|
self.cacheTTL = cacheTTL
|
||||||
self.redactionEnabled = redactionEnabled
|
self.redactionEnabled = redactionEnabled
|
||||||
self.runtimeMetadataFooter = runtimeMetadataFooter
|
self.runtimeMetadataFooter = runtimeMetadataFooter
|
||||||
|
self.gatewayPlatforms = gatewayPlatforms
|
||||||
|
self.imageGenModel = imageGenModel
|
||||||
|
self.openrouterResponseCacheEnabled = openrouterResponseCacheEnabled
|
||||||
|
self.webToolsBackend = webToolsBackend
|
||||||
|
self.webToolsSearchBackend = webToolsSearchBackend
|
||||||
|
self.webToolsExtractBackend = webToolsExtractBackend
|
||||||
self.model = model
|
self.model = model
|
||||||
self.provider = provider
|
self.provider = provider
|
||||||
self.maxTurns = maxTurns
|
self.maxTurns = maxTurns
|
||||||
|
|||||||
@@ -28,6 +28,12 @@ public struct HermesCronJob: Identifiable, Sendable, Codable {
|
|||||||
/// job's prompt. YAML-only field today (no `--context-from` CLI
|
/// job's prompt. YAML-only field today (no `--context-from` CLI
|
||||||
/// flag yet) — Scarf displays it but doesn't write it.
|
/// flag yet) — Scarf displays it but doesn't write it.
|
||||||
public nonisolated let contextFrom: [String]?
|
public nonisolated let contextFrom: [String]?
|
||||||
|
/// Hermes v0.13+ — script-only watchdog mode. When `true` the
|
||||||
|
/// pre-run script runs but the AI turn is skipped. `nil` means the
|
||||||
|
/// jobs.json file is pre-v0.13 (treat as `false`); `false` is the
|
||||||
|
/// explicit v0.13+ default. Capability-gated on `hasCronNoAgent`
|
||||||
|
/// at all write call sites.
|
||||||
|
public nonisolated let noAgent: Bool?
|
||||||
|
|
||||||
public enum CodingKeys: String, CodingKey {
|
public enum CodingKeys: String, CodingKey {
|
||||||
case id, name, prompt, skills, model, schedule, enabled, state, deliver, silent
|
case id, name, prompt, skills, model, schedule, enabled, state, deliver, silent
|
||||||
@@ -41,6 +47,7 @@ public struct HermesCronJob: Identifiable, Sendable, Codable {
|
|||||||
case timeoutSeconds = "timeout_seconds"
|
case timeoutSeconds = "timeout_seconds"
|
||||||
case workdir
|
case workdir
|
||||||
case contextFrom = "context_from"
|
case contextFrom = "context_from"
|
||||||
|
case noAgent = "no_agent"
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Memberwise init. Swift doesn't synthesize one for us because
|
/// Memberwise init. Swift doesn't synthesize one for us because
|
||||||
@@ -66,7 +73,8 @@ public struct HermesCronJob: Identifiable, Sendable, Codable {
|
|||||||
timeoutSeconds: Int? = nil,
|
timeoutSeconds: Int? = nil,
|
||||||
silent: Bool? = nil,
|
silent: Bool? = nil,
|
||||||
workdir: String? = nil,
|
workdir: String? = nil,
|
||||||
contextFrom: [String]? = nil
|
contextFrom: [String]? = nil,
|
||||||
|
noAgent: Bool? = nil
|
||||||
) {
|
) {
|
||||||
self.id = id
|
self.id = id
|
||||||
self.name = name
|
self.name = name
|
||||||
@@ -88,6 +96,7 @@ public struct HermesCronJob: Identifiable, Sendable, Codable {
|
|||||||
self.silent = silent
|
self.silent = silent
|
||||||
self.workdir = workdir
|
self.workdir = workdir
|
||||||
self.contextFrom = contextFrom
|
self.contextFrom = contextFrom
|
||||||
|
self.noAgent = noAgent
|
||||||
}
|
}
|
||||||
|
|
||||||
public nonisolated init(from decoder: any Decoder) throws {
|
public nonisolated init(from decoder: any Decoder) throws {
|
||||||
@@ -112,6 +121,7 @@ public struct HermesCronJob: Identifiable, Sendable, Codable {
|
|||||||
self.silent = try c.decodeIfPresent(Bool.self, forKey: .silent)
|
self.silent = try c.decodeIfPresent(Bool.self, forKey: .silent)
|
||||||
self.workdir = try c.decodeIfPresent(String.self, forKey: .workdir)
|
self.workdir = try c.decodeIfPresent(String.self, forKey: .workdir)
|
||||||
self.contextFrom = try c.decodeIfPresent([String].self, forKey: .contextFrom)
|
self.contextFrom = try c.decodeIfPresent([String].self, forKey: .contextFrom)
|
||||||
|
self.noAgent = try c.decodeIfPresent(Bool.self, forKey: .noAgent)
|
||||||
}
|
}
|
||||||
|
|
||||||
public nonisolated func encode(to encoder: any Encoder) throws {
|
public nonisolated func encode(to encoder: any Encoder) throws {
|
||||||
@@ -136,6 +146,7 @@ public struct HermesCronJob: Identifiable, Sendable, Codable {
|
|||||||
try c.encodeIfPresent(silent, forKey: .silent)
|
try c.encodeIfPresent(silent, forKey: .silent)
|
||||||
try c.encodeIfPresent(workdir, forKey: .workdir)
|
try c.encodeIfPresent(workdir, forKey: .workdir)
|
||||||
try c.encodeIfPresent(contextFrom, forKey: .contextFrom)
|
try c.encodeIfPresent(contextFrom, forKey: .contextFrom)
|
||||||
|
try c.encodeIfPresent(noAgent, forKey: .noAgent)
|
||||||
}
|
}
|
||||||
|
|
||||||
public nonisolated var stateIcon: String {
|
public nonisolated var stateIcon: String {
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// One entry in the `hermes curator list-archived` output. Decoded
|
||||||
|
/// tolerantly via `decodeIfPresent` so a stripped-down host (or a future
|
||||||
|
/// Hermes that drops one of the optional columns) doesn't crash the view.
|
||||||
|
///
|
||||||
|
/// Only `name` is required — every other field is optional and the
|
||||||
|
/// computed `*Label` accessors render `"—"` for missing values.
|
||||||
|
public struct HermesCuratorArchivedSkill: Sendable, Equatable, Identifiable, Codable {
|
||||||
|
public var id: String { name }
|
||||||
|
public let name: String
|
||||||
|
public let category: String?
|
||||||
|
public let archivedAt: String?
|
||||||
|
public let reason: String?
|
||||||
|
public let sizeBytes: Int?
|
||||||
|
public let path: String?
|
||||||
|
|
||||||
|
public init(
|
||||||
|
name: String,
|
||||||
|
category: String? = nil,
|
||||||
|
archivedAt: String? = nil,
|
||||||
|
reason: String? = nil,
|
||||||
|
sizeBytes: Int? = nil,
|
||||||
|
path: String? = nil
|
||||||
|
) {
|
||||||
|
self.name = name
|
||||||
|
self.category = category
|
||||||
|
self.archivedAt = archivedAt
|
||||||
|
self.reason = reason
|
||||||
|
self.sizeBytes = sizeBytes
|
||||||
|
self.path = path
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum CodingKeys: String, CodingKey {
|
||||||
|
case name
|
||||||
|
case category
|
||||||
|
case archivedAt = "archived_at"
|
||||||
|
case reason
|
||||||
|
case sizeBytes = "size_bytes"
|
||||||
|
case path
|
||||||
|
}
|
||||||
|
|
||||||
|
public init(from decoder: Decoder) throws {
|
||||||
|
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
|
self.name = try c.decode(String.self, forKey: .name)
|
||||||
|
self.category = try c.decodeIfPresent(String.self, forKey: .category)
|
||||||
|
self.archivedAt = try c.decodeIfPresent(String.self, forKey: .archivedAt)
|
||||||
|
self.reason = try c.decodeIfPresent(String.self, forKey: .reason)
|
||||||
|
self.sizeBytes = try c.decodeIfPresent(Int.self, forKey: .sizeBytes)
|
||||||
|
self.path = try c.decodeIfPresent(String.self, forKey: .path)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func encode(to encoder: Encoder) throws {
|
||||||
|
var c = encoder.container(keyedBy: CodingKeys.self)
|
||||||
|
try c.encode(name, forKey: .name)
|
||||||
|
try c.encodeIfPresent(category, forKey: .category)
|
||||||
|
try c.encodeIfPresent(archivedAt, forKey: .archivedAt)
|
||||||
|
try c.encodeIfPresent(reason, forKey: .reason)
|
||||||
|
try c.encodeIfPresent(sizeBytes, forKey: .sizeBytes)
|
||||||
|
try c.encodeIfPresent(path, forKey: .path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "4.4 KB" / "1.2 MB" / "—" for nil. Uses the SI byte formatter so
|
||||||
|
/// the labels match what Finder shows.
|
||||||
|
public var sizeLabel: String {
|
||||||
|
guard let bytes = sizeBytes else { return "—" }
|
||||||
|
let formatter = ByteCountFormatter()
|
||||||
|
formatter.allowedUnits = [.useAll]
|
||||||
|
formatter.countStyle = .file
|
||||||
|
return formatter.string(fromByteCount: Int64(bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `2026-04-22` (ISO date prefix) / "—". Hermes returns full ISO
|
||||||
|
/// timestamps with seconds + Z; the date prefix is what the user
|
||||||
|
/// actually wants in the archived list.
|
||||||
|
public var archivedAtLabel: String {
|
||||||
|
guard let iso = archivedAt, !iso.isEmpty else { return "—" }
|
||||||
|
// Trim to date prefix if it looks like a full ISO timestamp.
|
||||||
|
if let tIdx = iso.firstIndex(of: "T") {
|
||||||
|
return String(iso[..<tIdx])
|
||||||
|
}
|
||||||
|
return iso
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result of `hermes curator prune --dry-run` — what would be removed
|
||||||
|
/// if the user confirms. The view derives `totalCount` from
|
||||||
|
/// `wouldRemove.count` so the wire shape stays flat.
|
||||||
|
public struct CuratorPruneSummary: Sendable, Equatable, Codable {
|
||||||
|
public let wouldRemove: [HermesCuratorArchivedSkill]
|
||||||
|
public let totalBytes: Int
|
||||||
|
public var totalCount: Int { wouldRemove.count }
|
||||||
|
|
||||||
|
public init(wouldRemove: [HermesCuratorArchivedSkill], totalBytes: Int) {
|
||||||
|
self.wouldRemove = wouldRemove
|
||||||
|
self.totalBytes = totalBytes
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum CodingKeys: String, CodingKey {
|
||||||
|
case wouldRemove = "would_remove"
|
||||||
|
case totalBytes = "total_bytes"
|
||||||
|
}
|
||||||
|
|
||||||
|
public init(from decoder: Decoder) throws {
|
||||||
|
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
|
self.wouldRemove = try c.decodeIfPresent([HermesCuratorArchivedSkill].self, forKey: .wouldRemove) ?? []
|
||||||
|
self.totalBytes = try c.decodeIfPresent(Int.self, forKey: .totalBytes) ?? 0
|
||||||
|
}
|
||||||
|
|
||||||
|
public func encode(to encoder: Encoder) throws {
|
||||||
|
var c = encoder.container(keyedBy: CodingKeys.self)
|
||||||
|
try c.encode(wouldRemove, forKey: .wouldRemove)
|
||||||
|
try c.encode(totalBytes, forKey: .totalBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "12.3 KB" / "—" for empty. Convenience for the confirm sheet header.
|
||||||
|
public var totalBytesLabel: String {
|
||||||
|
guard totalBytes > 0 else { return "—" }
|
||||||
|
let formatter = ByteCountFormatter()
|
||||||
|
formatter.allowedUnits = [.useAll]
|
||||||
|
formatter.countStyle = .file
|
||||||
|
return formatter.string(fromByteCount: Int64(totalBytes))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,10 @@ import Foundation
|
|||||||
public enum MCPTransport: String, Sendable, Equatable, CaseIterable, Identifiable {
|
public enum MCPTransport: String, Sendable, Equatable, CaseIterable, Identifiable {
|
||||||
case stdio
|
case stdio
|
||||||
case http
|
case http
|
||||||
|
/// Server-Sent Events transport. Hermes v0.13+ only.
|
||||||
|
// TODO(WS-7-Q1): Verify Hermes uses the literal `sse` transport name
|
||||||
|
// (vs. `streamable-http`/`http-sse`/etc.) once a v0.13 host is on hand.
|
||||||
|
case sse
|
||||||
|
|
||||||
public var id: String { rawValue }
|
public var id: String { rawValue }
|
||||||
|
|
||||||
@@ -11,6 +15,7 @@ public enum MCPTransport: String, Sendable, Equatable, CaseIterable, Identifiabl
|
|||||||
switch self {
|
switch self {
|
||||||
case .stdio: return "Local (stdio)"
|
case .stdio: return "Local (stdio)"
|
||||||
case .http: return "Remote (HTTP)"
|
case .http: return "Remote (HTTP)"
|
||||||
|
case .sse: return "Remote (SSE)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@@ -33,6 +38,12 @@ public struct HermesMCPServer: Identifiable, Sendable, Equatable {
|
|||||||
public let resourcesEnabled: Bool
|
public let resourcesEnabled: Bool
|
||||||
public let promptsEnabled: Bool
|
public let promptsEnabled: Bool
|
||||||
public let hasOAuthToken: Bool
|
public let hasOAuthToken: Bool
|
||||||
|
/// Hermes-side keepalive interval (seconds) for SSE transport. `nil`
|
||||||
|
/// when the YAML doesn't specify `sse_read_timeout` (Hermes default
|
||||||
|
/// applies). Pre-v0.13 hosts always have this as `nil`.
|
||||||
|
// TODO(WS-7-Q2): Default is assumed to be 300s per WS-7 plan; placeholder
|
||||||
|
// copy uses that. Verify against `~/.hermes/hermes-agent/hermes_cli/mcp.py`.
|
||||||
|
public let sseReadTimeout: Int?
|
||||||
|
|
||||||
|
|
||||||
public init(
|
public init(
|
||||||
@@ -51,7 +62,8 @@ public struct HermesMCPServer: Identifiable, Sendable, Equatable {
|
|||||||
toolsExclude: [String],
|
toolsExclude: [String],
|
||||||
resourcesEnabled: Bool,
|
resourcesEnabled: Bool,
|
||||||
promptsEnabled: Bool,
|
promptsEnabled: Bool,
|
||||||
hasOAuthToken: Bool
|
hasOAuthToken: Bool,
|
||||||
|
sseReadTimeout: Int? = nil
|
||||||
) {
|
) {
|
||||||
self.name = name
|
self.name = name
|
||||||
self.transport = transport
|
self.transport = transport
|
||||||
@@ -69,6 +81,7 @@ public struct HermesMCPServer: Identifiable, Sendable, Equatable {
|
|||||||
self.resourcesEnabled = resourcesEnabled
|
self.resourcesEnabled = resourcesEnabled
|
||||||
self.promptsEnabled = promptsEnabled
|
self.promptsEnabled = promptsEnabled
|
||||||
self.hasOAuthToken = hasOAuthToken
|
self.hasOAuthToken = hasOAuthToken
|
||||||
|
self.sseReadTimeout = sseReadTimeout
|
||||||
}
|
}
|
||||||
public var id: String { name }
|
public var id: String { name }
|
||||||
|
|
||||||
@@ -79,6 +92,8 @@ public struct HermesMCPServer: Identifiable, Sendable, Equatable {
|
|||||||
return (command ?? "") + argString
|
return (command ?? "") + argString
|
||||||
case .http:
|
case .http:
|
||||||
return url ?? ""
|
return url ?? ""
|
||||||
|
case .sse:
|
||||||
|
return url ?? ""
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// One queued prompt the user has staged via `/queue <text>` (Hermes
|
||||||
|
/// v0.13+ ACP `/queue` slash command). Hermes is the authoritative owner
|
||||||
|
/// of the actual queue server-side — Scarf maintains this mirror so the
|
||||||
|
/// chat header chip + popover can show "what's pending" without an
|
||||||
|
/// extra round-trip. The mirror drains best-effort when a turn
|
||||||
|
/// completes (`RichChatViewModel.popQueuedPrompt`).
|
||||||
|
///
|
||||||
|
/// `id` is a Scarf-side UUID minted at queue-time — Hermes' wire
|
||||||
|
/// protocol does not expose a per-queue-entry id, so we never round-trip
|
||||||
|
/// an entry-level identifier. See WS-2 plan Q5.
|
||||||
|
public struct HermesQueuedPrompt: Sendable, Equatable, Identifiable {
|
||||||
|
public let id: UUID
|
||||||
|
public let text: String
|
||||||
|
public let queuedAt: Date
|
||||||
|
|
||||||
|
public init(id: UUID = UUID(), text: String, queuedAt: Date = Date()) {
|
||||||
|
self.id = id
|
||||||
|
self.text = text
|
||||||
|
self.queuedAt = queuedAt
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,26 @@ 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,
|
||||||
|
// -- v0.13 additions -------------------------------------
|
||||||
|
// TODO(WS-6-Q1): the `openrouter.response_cache.enabled`
|
||||||
|
// key shape is provisional pending verification against a
|
||||||
|
// v0.13 `hermes config check`. If upstream uses a different
|
||||||
|
// path (e.g. `providers.openrouter.response_cache_enabled`
|
||||||
|
// or nested under `prompt_caching`), update this single
|
||||||
|
// line + the matching `setSetting` key in
|
||||||
|
// `SettingsViewModel.setOpenRouterResponseCache`. Default
|
||||||
|
// is `false` per WS-6-plan §Open Questions #2.
|
||||||
|
imageGenModel: str("image_gen.model", default: ""),
|
||||||
|
openrouterResponseCacheEnabled: bool("openrouter.response_cache.enabled", default: false),
|
||||||
|
// Pre-v0.13 hosts wrote a single `web_tools.backend`. v0.13 split
|
||||||
|
// it into per-capability keys. Read all three so the round-trip
|
||||||
|
// never loses a value the user already set; the WebTools tab
|
||||||
|
// chooses which to render based on `hasWebToolsBackendSplit`.
|
||||||
|
webToolsBackend: str("web_tools.backend", default: "duckduckgo"),
|
||||||
|
webToolsSearchBackend: str("web_tools.search.backend", default: "duckduckgo"),
|
||||||
|
webToolsExtractBackend: str("web_tools.extract.backend", default: "reader")
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,358 @@
|
|||||||
|
import Foundation
|
||||||
|
#if canImport(os)
|
||||||
|
import os
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/// Async, transport-aware client for `hermes curator …`. Wraps the v0.12
|
||||||
|
/// verbs (`status / run / pause / resume / pin / unpin / restore`) plus
|
||||||
|
/// the v0.13 archive surface (`archive / prune / list-archived` and a
|
||||||
|
/// synchronous-blocking `run`).
|
||||||
|
///
|
||||||
|
/// **Concurrency.** Pure-I/O `actor` — no UI state. View models hold a
|
||||||
|
/// service reference and `await` methods. Each public method dispatches
|
||||||
|
/// the underlying CLI invocation through `Task.detached(priority:
|
||||||
|
/// .utility)` so two concurrent reads from the VM don't queue end-to-end
|
||||||
|
/// on a single thread. Mirrors `KanbanService` shape exactly.
|
||||||
|
///
|
||||||
|
/// **Capability gating happens at the call site, not in the service.**
|
||||||
|
/// `runNow(synchronous:timeout:)` takes a flag from the VM (the VM reads
|
||||||
|
/// `HermesCapabilities.hasCuratorArchive` to decide). The service stays
|
||||||
|
/// version-agnostic — only the timeout differs in practice.
|
||||||
|
public actor CuratorService {
|
||||||
|
#if canImport(os)
|
||||||
|
private static let logger = Logger(subsystem: "com.scarf", category: "CuratorService")
|
||||||
|
#endif
|
||||||
|
|
||||||
|
private let context: ServerContext
|
||||||
|
|
||||||
|
public init(context: ServerContext) {
|
||||||
|
self.context = context
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Reads
|
||||||
|
|
||||||
|
/// Run `hermes curator status` and parse stdout via
|
||||||
|
/// `HermesCuratorStatusParser`. Combines the text output with the
|
||||||
|
/// on-disk `.curator_state` JSON for richer last-run metadata.
|
||||||
|
/// Never throws — a transport failure resolves to `.empty` so the
|
||||||
|
/// view always has something to render.
|
||||||
|
public func status() async -> HermesCuratorStatus {
|
||||||
|
let context = self.context
|
||||||
|
return await Task.detached(priority: .utility) { () -> HermesCuratorStatus in
|
||||||
|
let textResult = Self.runHermesSync(context: context, args: ["curator", "status"], timeout: 30)
|
||||||
|
let stateData = context.readData(context.paths.curatorStateFile)
|
||||||
|
return HermesCuratorStatusParser.parse(text: textResult.output, stateFileJSON: stateData)
|
||||||
|
}.value
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `hermes curator list-archived [--json]`. Prefers JSON; falls back
|
||||||
|
/// to a defensive text parser. Empty / "no archived skills" sentinel
|
||||||
|
/// folds to `[]`.
|
||||||
|
public func listArchived() async throws -> [HermesCuratorArchivedSkill] {
|
||||||
|
// TODO(WS-4-Q2): confirm `--json` is supported on v0.13
|
||||||
|
// `list-archived`. If not, drop the flag and rely on the text
|
||||||
|
// parser path. Until then we pass `--json` and parse the output
|
||||||
|
// tolerantly.
|
||||||
|
let args = ["curator", "list-archived", "--json"]
|
||||||
|
let (code, stdout, stderr) = await runHermes(args: args, timeout: 30)
|
||||||
|
|
||||||
|
// If --json isn't recognized, the CLI typically emits
|
||||||
|
// "unrecognized arguments: --json" or similar to stderr and
|
||||||
|
// exits non-zero. Retry without the flag and parse text.
|
||||||
|
if code != 0 {
|
||||||
|
let lower = (stderr + stdout).lowercased()
|
||||||
|
if lower.contains("unrecognized") || lower.contains("unknown") || lower.contains("no such option") {
|
||||||
|
let (c2, out2, err2) = await runHermes(args: ["curator", "list-archived"], timeout: 30)
|
||||||
|
try ensureSuccess(code: c2, stdout: out2, stderr: err2, verb: "list-archived")
|
||||||
|
return Self.parseListArchivedText(out2)
|
||||||
|
}
|
||||||
|
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "list-archived")
|
||||||
|
}
|
||||||
|
|
||||||
|
let trimmed = stdout.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
if trimmed.isEmpty || trimmed.lowercased().contains("no archived skills") {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
// Try JSON first — may also be a text dump if Hermes ignored `--json`.
|
||||||
|
if let data = trimmed.data(using: .utf8),
|
||||||
|
let arr = try? JSONDecoder().decode([HermesCuratorArchivedSkill].self, from: data) {
|
||||||
|
return arr
|
||||||
|
}
|
||||||
|
// Some builds wrap in `{"archived": [...]}` envelope.
|
||||||
|
struct Wrapper: Decodable { let archived: [HermesCuratorArchivedSkill] }
|
||||||
|
if let data = trimmed.data(using: .utf8),
|
||||||
|
let wrapped = try? JSONDecoder().decode(Wrapper.self, from: data) {
|
||||||
|
return wrapped.archived
|
||||||
|
}
|
||||||
|
// Text fallback — defensive parse.
|
||||||
|
return Self.parseListArchivedText(stdout)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Writes (legacy v0.12 verbs; service form)
|
||||||
|
|
||||||
|
public func runNow(synchronous: Bool, timeout: TimeInterval) async throws {
|
||||||
|
// TODO(WS-4-Q4): default 600s for v0.13 sync runs. No Cancel
|
||||||
|
// button in v2.8 (transport.cancel parity not guaranteed across
|
||||||
|
// LocalTransport / SSHTransport).
|
||||||
|
let resolvedTimeout = synchronous ? timeout : 30
|
||||||
|
let (code, stdout, stderr) = await runHermes(args: ["curator", "run"], timeout: resolvedTimeout)
|
||||||
|
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "run")
|
||||||
|
}
|
||||||
|
|
||||||
|
public func pause() async throws {
|
||||||
|
let (code, stdout, stderr) = await runHermes(args: ["curator", "pause"], timeout: 15)
|
||||||
|
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "pause")
|
||||||
|
}
|
||||||
|
|
||||||
|
public func resume() async throws {
|
||||||
|
let (code, stdout, stderr) = await runHermes(args: ["curator", "resume"], timeout: 15)
|
||||||
|
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "resume")
|
||||||
|
}
|
||||||
|
|
||||||
|
public func pin(_ name: String) async throws {
|
||||||
|
let (code, stdout, stderr) = await runHermes(args: ["curator", "pin", name], timeout: 15)
|
||||||
|
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "pin")
|
||||||
|
}
|
||||||
|
|
||||||
|
public func unpin(_ name: String) async throws {
|
||||||
|
let (code, stdout, stderr) = await runHermes(args: ["curator", "unpin", name], timeout: 15)
|
||||||
|
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "unpin")
|
||||||
|
}
|
||||||
|
|
||||||
|
public func restore(_ name: String) async throws {
|
||||||
|
let (code, stdout, stderr) = await runHermes(args: ["curator", "restore", name], timeout: 30)
|
||||||
|
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "restore")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Writes (new in v0.13)
|
||||||
|
|
||||||
|
/// `hermes curator archive <name>` — non-destructive; moves the
|
||||||
|
/// skill from the active set to the archived set. No `--json` is
|
||||||
|
/// expected; the verb's success channel is the exit code.
|
||||||
|
public func archive(_ name: String) async throws {
|
||||||
|
let (code, stdout, stderr) = await runHermes(args: ["curator", "archive", name], timeout: 30)
|
||||||
|
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "archive")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `hermes curator prune [--dry-run]`. Destructive when `dryRun`
|
||||||
|
/// is `false` — removes everything currently archived from disk.
|
||||||
|
/// Returns a `CuratorPruneSummary` describing what was (or would be)
|
||||||
|
/// removed. On `dryRun=false`, the wire shape may not include the
|
||||||
|
/// `would_remove` list — the caller should not depend on it; the
|
||||||
|
/// archived list is empty after a successful destructive prune.
|
||||||
|
@discardableResult
|
||||||
|
public func prune(dryRun: Bool) async throws -> CuratorPruneSummary {
|
||||||
|
// TODO(WS-4-Q1): confirm v0.13 ships `--dry-run`. If not, fall
|
||||||
|
// back to enumerating via `list-archived` and treat any prune
|
||||||
|
// call as destructive. The retry-without-flag path below covers
|
||||||
|
// the "unrecognized argument" case automatically.
|
||||||
|
var args = ["curator", "prune"]
|
||||||
|
if dryRun { args.append("--dry-run") }
|
||||||
|
// `--json` requested for the dry-run path so we can parse the
|
||||||
|
// would-remove list. Destructive mode runs without --json since
|
||||||
|
// we only need the exit code.
|
||||||
|
if dryRun { args.append("--json") }
|
||||||
|
|
||||||
|
let (code, stdout, stderr) = await runHermes(args: args, timeout: 60)
|
||||||
|
|
||||||
|
// Detect "unrecognized --dry-run" / "unknown --json" gracefully.
|
||||||
|
if code != 0 {
|
||||||
|
let lower = (stderr + stdout).lowercased()
|
||||||
|
let unrecognized = lower.contains("unrecognized") || lower.contains("unknown") || lower.contains("no such option")
|
||||||
|
if dryRun && unrecognized {
|
||||||
|
// Q1 fallback: enumerate via list-archived. Caller still
|
||||||
|
// uses this summary for confirm-sheet display.
|
||||||
|
let archived = try await listArchived()
|
||||||
|
let total = archived.compactMap { $0.sizeBytes }.reduce(0, +)
|
||||||
|
return CuratorPruneSummary(wouldRemove: archived, totalBytes: total)
|
||||||
|
}
|
||||||
|
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "prune")
|
||||||
|
}
|
||||||
|
|
||||||
|
if dryRun {
|
||||||
|
return Self.parsePruneDryRun(stdout)
|
||||||
|
}
|
||||||
|
return CuratorPruneSummary(wouldRemove: [], totalBytes: 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Pure parsers (nonisolated; safe to call from VMs without awaits)
|
||||||
|
|
||||||
|
/// Parse a `list-archived --json` payload. Tolerates the bare-array
|
||||||
|
/// shape, the `{"archived": [...]}` envelope, and "no archived
|
||||||
|
/// skills" / empty-string sentinels. Returns `[]` for any of the
|
||||||
|
/// empty cases. Throws `CuratorError.decoding` only when the input
|
||||||
|
/// is non-empty and clearly not JSON.
|
||||||
|
public nonisolated static func parseListArchived(stdout: String) throws -> [HermesCuratorArchivedSkill] {
|
||||||
|
let trimmed = stdout.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
if trimmed.isEmpty || trimmed.lowercased().contains("no archived skills") {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
guard let data = trimmed.data(using: .utf8) else {
|
||||||
|
throw CuratorError.decoding(verb: "list-archived", message: "non-UTF8 stdout")
|
||||||
|
}
|
||||||
|
if let arr = try? JSONDecoder().decode([HermesCuratorArchivedSkill].self, from: data) {
|
||||||
|
return arr
|
||||||
|
}
|
||||||
|
struct Wrapper: Decodable { let archived: [HermesCuratorArchivedSkill] }
|
||||||
|
if let wrapped = try? JSONDecoder().decode(Wrapper.self, from: data) {
|
||||||
|
return wrapped.archived
|
||||||
|
}
|
||||||
|
// Last resort: text fallback.
|
||||||
|
let parsed = parseListArchivedText(stdout)
|
||||||
|
if !parsed.isEmpty {
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
|
throw CuratorError.decoding(verb: "list-archived", message: "stdout was neither JSON nor a recognised text list")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Defensive text parser for `list-archived` output when `--json`
|
||||||
|
/// isn't supported. Format inferred from `curator status`: one row
|
||||||
|
/// per non-blank line, leading whitespace, name in column 1, then
|
||||||
|
/// optional `archived=YYYY-MM-DD`, `size=NNNN`, `reason=...` k/v
|
||||||
|
/// pairs. Blank lines, header lines, and the empty-state sentinel
|
||||||
|
/// are skipped.
|
||||||
|
public nonisolated static func parseListArchivedText(_ text: String) -> [HermesCuratorArchivedSkill] {
|
||||||
|
var rows: [HermesCuratorArchivedSkill] = []
|
||||||
|
for raw in text.split(separator: "\n") {
|
||||||
|
let line = raw.trimmingCharacters(in: .whitespaces)
|
||||||
|
if line.isEmpty { continue }
|
||||||
|
let lower = line.lowercased()
|
||||||
|
// Skip header / sentinel lines.
|
||||||
|
if lower.hasPrefix("name") && lower.contains("archived") { continue }
|
||||||
|
if lower.contains("no archived skills") { continue }
|
||||||
|
if line.unicodeScalars.allSatisfy({ $0.value == 0x2500 || $0.properties.isWhitespace }) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Skip lines that look like JSON / non-row chrome — `{`,
|
||||||
|
// `}`, `[`, `]` at the start or quotes / colons mean we're
|
||||||
|
// parsing a malformed JSON dump, not a row table.
|
||||||
|
if let first = line.first, "{[}]\":,".contains(first) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Find the first whitespace-separated token as the name; if
|
||||||
|
// the name carries an `=` it's a header chip we should skip.
|
||||||
|
let parts = line.split(whereSeparator: { $0 == "\t" || $0 == " " }).map(String.init)
|
||||||
|
guard let name = parts.first, !name.contains("=") else { continue }
|
||||||
|
// Reject names that look like punctuation / JSON fragments.
|
||||||
|
if name.contains("\"") || name.contains(":") || name.contains("{") || name.contains("}") || name.contains("[") || name.contains("]") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Pull k=v pairs from the remainder.
|
||||||
|
var archivedAt: String?
|
||||||
|
var sizeBytes: Int?
|
||||||
|
var reason: String?
|
||||||
|
var category: String?
|
||||||
|
var path: String?
|
||||||
|
for token in parts.dropFirst() {
|
||||||
|
guard let eq = token.firstIndex(of: "=") else { continue }
|
||||||
|
let key = String(token[..<eq])
|
||||||
|
let value = String(token[token.index(after: eq)...])
|
||||||
|
switch key {
|
||||||
|
case "archived", "archived_at":
|
||||||
|
archivedAt = value
|
||||||
|
case "size", "size_bytes":
|
||||||
|
sizeBytes = Int(value)
|
||||||
|
case "reason":
|
||||||
|
reason = value
|
||||||
|
case "category":
|
||||||
|
category = value
|
||||||
|
case "path":
|
||||||
|
path = value
|
||||||
|
default:
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows.append(
|
||||||
|
HermesCuratorArchivedSkill(
|
||||||
|
name: name,
|
||||||
|
category: category,
|
||||||
|
archivedAt: archivedAt,
|
||||||
|
reason: reason,
|
||||||
|
sizeBytes: sizeBytes,
|
||||||
|
path: path
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return rows
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse a `prune --dry-run --json` payload. Tolerates an empty
|
||||||
|
/// payload (returns a zero summary) and the `{would_remove: [],
|
||||||
|
/// total_bytes: N}` shape.
|
||||||
|
public nonisolated static func parsePruneDryRun(_ stdout: String) -> CuratorPruneSummary {
|
||||||
|
let trimmed = stdout.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard !trimmed.isEmpty else {
|
||||||
|
return CuratorPruneSummary(wouldRemove: [], totalBytes: 0)
|
||||||
|
}
|
||||||
|
if let data = trimmed.data(using: .utf8),
|
||||||
|
let summary = try? JSONDecoder().decode(CuratorPruneSummary.self, from: data) {
|
||||||
|
return summary
|
||||||
|
}
|
||||||
|
// Tolerate a bare-array fallback (some Hermes builds may print
|
||||||
|
// just the would-remove list when --json is missing the wrapper).
|
||||||
|
if let data = trimmed.data(using: .utf8),
|
||||||
|
let arr = try? JSONDecoder().decode([HermesCuratorArchivedSkill].self, from: data) {
|
||||||
|
let total = arr.compactMap { $0.sizeBytes }.reduce(0, +)
|
||||||
|
return CuratorPruneSummary(wouldRemove: arr, totalBytes: total)
|
||||||
|
}
|
||||||
|
// Last-resort text parse for "would remove N skills (X bytes)".
|
||||||
|
return CuratorPruneSummary(wouldRemove: [], totalBytes: 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - CLI invocation
|
||||||
|
|
||||||
|
private nonisolated func runHermes(
|
||||||
|
args: [String],
|
||||||
|
timeout: TimeInterval
|
||||||
|
) async -> (exitCode: Int32, stdout: String, stderr: String) {
|
||||||
|
let context = self.context
|
||||||
|
return await Task.detached(priority: .utility) { () -> (Int32, String, String) in
|
||||||
|
let result = Self.runHermesSync(context: context, args: args, timeout: timeout)
|
||||||
|
return (result.exitCode, result.output, result.stderr)
|
||||||
|
}.value
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Synchronous, transport-level invocation. `output` is stdout; the
|
||||||
|
/// caller usually only reads `output` for parser input but sometimes
|
||||||
|
/// needs `stderr` (e.g. to detect "unrecognized argument" patterns).
|
||||||
|
private nonisolated static func runHermesSync(
|
||||||
|
context: ServerContext,
|
||||||
|
args: [String],
|
||||||
|
timeout: TimeInterval
|
||||||
|
) -> (exitCode: Int32, output: String, stderr: String) {
|
||||||
|
let transport = context.makeTransport()
|
||||||
|
do {
|
||||||
|
let result = try transport.runProcess(
|
||||||
|
executable: context.paths.hermesBinary,
|
||||||
|
args: args,
|
||||||
|
stdin: nil,
|
||||||
|
timeout: timeout
|
||||||
|
)
|
||||||
|
return (result.exitCode, result.stdoutString, result.stderrString)
|
||||||
|
} catch let error as TransportError {
|
||||||
|
let message = error.diagnosticStderr.isEmpty
|
||||||
|
? (error.errorDescription ?? "transport error")
|
||||||
|
: error.diagnosticStderr
|
||||||
|
return (-1, "", message)
|
||||||
|
} catch {
|
||||||
|
return (-1, "", error.localizedDescription)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private nonisolated func ensureSuccess(
|
||||||
|
code: Int32,
|
||||||
|
stdout: String,
|
||||||
|
stderr: String,
|
||||||
|
verb: String
|
||||||
|
) throws {
|
||||||
|
guard code != 0 else { return }
|
||||||
|
if code == -1 && stderr.lowercased().contains("hermes binary not found") {
|
||||||
|
throw CuratorError.cliMissing
|
||||||
|
}
|
||||||
|
let combined = stderr.isEmpty ? stdout : stderr
|
||||||
|
#if canImport(os)
|
||||||
|
Self.logger.warning("curator \(verb) exit=\(code, privacy: .public) stderr=\(combined, privacy: .public)")
|
||||||
|
#endif
|
||||||
|
throw CuratorError.nonZeroExit(verb: verb, code: code, stderr: combined)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Pure helpers that build argv arrays for `hermes update` invocations.
|
||||||
|
///
|
||||||
|
/// Lives in ScarfCore so the eventual UI surface (Mac / iOS / remote)
|
||||||
|
/// shares flag selection. There is no in-app "Update Hermes" affordance
|
||||||
|
/// in v2.7.5 — Sparkle handles Scarf-self-update and `hermes update` is
|
||||||
|
/// invoked by users in their terminal — but capability-gated flag logic
|
||||||
|
/// is forward-compat plumbing that the future affordance will call. Each
|
||||||
|
/// helper is a `nonisolated static` pure function: no transport, no
|
||||||
|
/// MainActor, no mocking surface required.
|
||||||
|
public enum HermesUpdaterCommandBuilder {
|
||||||
|
/// Argv for an `hermes update` invocation, capability-gated.
|
||||||
|
///
|
||||||
|
/// Pre-v0.12 hosts only had `update` (no flags). v0.12+ accepts
|
||||||
|
/// `--check` for preflight. v0.13+ accepts `--yes` / `-y` for
|
||||||
|
/// unattended runs (skips the interactive confirmation prompt).
|
||||||
|
/// Flags are silently dropped when the connected host can't honor
|
||||||
|
/// them so callers don't need to branch on capabilities themselves.
|
||||||
|
public static func updateArgv(
|
||||||
|
capabilities: HermesCapabilities,
|
||||||
|
unattended: Bool,
|
||||||
|
checkOnly: Bool
|
||||||
|
) -> [String] {
|
||||||
|
var args: [String] = ["update"]
|
||||||
|
if checkOnly && capabilities.hasUpdateCheck {
|
||||||
|
args.append("--check")
|
||||||
|
}
|
||||||
|
if unattended && capabilities.hasUpdateNonInteractive {
|
||||||
|
args.append("--yes")
|
||||||
|
}
|
||||||
|
return args
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -155,9 +155,20 @@ public struct ModelCatalogService: Sendable {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
return byID.values.sorted { lhs, rhs in
|
return byID.values.sorted { lhs, rhs in
|
||||||
|
// Subscription-gated first (Nous Portal).
|
||||||
if lhs.subscriptionGated != rhs.subscriptionGated {
|
if lhs.subscriptionGated != rhs.subscriptionGated {
|
||||||
return lhs.subscriptionGated
|
return lhs.subscriptionGated
|
||||||
}
|
}
|
||||||
|
// Demoted last (Vercel AI Gateway, per Hermes v0.13). The
|
||||||
|
// axis is unconditional — we don't gate on the Hermes
|
||||||
|
// version because "Vercel mid-alphabet on v0.12, bottom on
|
||||||
|
// v0.13" would be more confusing than the consistent
|
||||||
|
// "Vercel last" treatment for everyone.
|
||||||
|
let lDemoted = Self.demotedProviders.contains(lhs.providerID)
|
||||||
|
let rDemoted = Self.demotedProviders.contains(rhs.providerID)
|
||||||
|
if lDemoted != rDemoted {
|
||||||
|
return !lDemoted
|
||||||
|
}
|
||||||
return lhs.providerName.localizedCaseInsensitiveCompare(rhs.providerName) == .orderedAscending
|
return lhs.providerName.localizedCaseInsensitiveCompare(rhs.providerName) == .orderedAscending
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -235,7 +246,10 @@ public struct ModelCatalogService: Sendable {
|
|||||||
public func provider(for modelID: String) -> HermesProviderInfo? {
|
public func provider(for modelID: String) -> HermesProviderInfo? {
|
||||||
guard let catalog = loadCatalog() else { return nil }
|
guard let catalog = loadCatalog() else { return nil }
|
||||||
for (providerID, p) in catalog {
|
for (providerID, p) in catalog {
|
||||||
if p.models?[modelID] != nil {
|
// Resolve any model-rename alias for this provider before
|
||||||
|
// checking the catalog — see `modelAliases` for rationale.
|
||||||
|
let resolved = resolveModelAlias(providerID: providerID, modelID: modelID)
|
||||||
|
if p.models?[resolved] != nil {
|
||||||
return HermesProviderInfo(
|
return HermesProviderInfo(
|
||||||
providerID: providerID,
|
providerID: providerID,
|
||||||
providerName: p.name ?? providerID,
|
providerName: p.name ?? providerID,
|
||||||
@@ -299,14 +313,17 @@ public struct ModelCatalogService: Sendable {
|
|||||||
/// Look up a specific model by provider + ID. Returns nil if not in the
|
/// Look up a specific model by provider + ID. Returns nil if not in the
|
||||||
/// catalog (e.g., free-typed custom model).
|
/// catalog (e.g., free-typed custom model).
|
||||||
public func model(providerID: String, modelID: String) -> HermesModelInfo? {
|
public func model(providerID: String, modelID: String) -> HermesModelInfo? {
|
||||||
|
// Resolve any model-rename alias for this provider before
|
||||||
|
// checking the catalog — see `modelAliases` for rationale.
|
||||||
|
let resolved = resolveModelAlias(providerID: providerID, modelID: modelID)
|
||||||
guard let catalog = loadCatalog(),
|
guard let catalog = loadCatalog(),
|
||||||
let provider = catalog[providerID],
|
let provider = catalog[providerID],
|
||||||
let raw = provider.models?[modelID] else { return nil }
|
let raw = provider.models?[resolved] else { return nil }
|
||||||
return HermesModelInfo(
|
return HermesModelInfo(
|
||||||
providerID: providerID,
|
providerID: providerID,
|
||||||
providerName: provider.name ?? providerID,
|
providerName: provider.name ?? providerID,
|
||||||
modelID: modelID,
|
modelID: resolved,
|
||||||
modelName: raw.name ?? modelID,
|
modelName: raw.name ?? resolved,
|
||||||
contextWindow: raw.limit?.context,
|
contextWindow: raw.limit?.context,
|
||||||
maxOutput: raw.limit?.output,
|
maxOutput: raw.limit?.output,
|
||||||
costInput: raw.cost?.input,
|
costInput: raw.cost?.input,
|
||||||
@@ -344,10 +361,14 @@ public struct ModelCatalogService: Sendable {
|
|||||||
/// HTTP 404 at runtime. Catch that at save time, not 6 hours later.
|
/// HTTP 404 at runtime. Catch that at save time, not 6 hours later.
|
||||||
public func validateModel(_ modelID: String, for providerID: String) -> ModelValidation {
|
public func validateModel(_ modelID: String, for providerID: String) -> ModelValidation {
|
||||||
ScarfMon.measure(.diskIO, "modelCatalog.validateModel") {
|
ScarfMon.measure(.diskIO, "modelCatalog.validateModel") {
|
||||||
let trimmed = modelID.trimmingCharacters(in: .whitespacesAndNewlines)
|
let raw = modelID.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
guard !trimmed.isEmpty else {
|
guard !raw.isEmpty else {
|
||||||
return .invalid(providerName: providerID, suggestions: [])
|
return .invalid(providerName: providerID, suggestions: [])
|
||||||
}
|
}
|
||||||
|
// Resolve any model-rename alias before lookup so configs
|
||||||
|
// referencing a deprecated ID (e.g. `x-ai/grok-4.20-beta`)
|
||||||
|
// validate against the canonical successor.
|
||||||
|
let trimmed = resolveModelAlias(providerID: providerID, modelID: raw)
|
||||||
|
|
||||||
// Overlay-only providers (Nous Portal, OpenAI Codex, Qwen
|
// Overlay-only providers (Nous Portal, OpenAI Codex, Qwen
|
||||||
// OAuth, …) serve their own catalogs that aren't mirrored to
|
// OAuth, …) serve their own catalogs that aren't mirrored to
|
||||||
@@ -433,6 +454,78 @@ public struct ModelCatalogService: Sendable {
|
|||||||
let output: Int?
|
let output: Int?
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Model aliases (model rename resolution)
|
||||||
|
|
||||||
|
/// Hermes deprecates model IDs across releases. When a stored config
|
||||||
|
/// `model.default` references a deprecated ID, resolve to its
|
||||||
|
/// canonical successor. Lossless — we never rewrite the user's
|
||||||
|
/// `config.yaml`; the alias just lets `validateModel` /
|
||||||
|
/// `model(providerID:modelID:)` / `provider(for:)` succeed against
|
||||||
|
/// the new ID.
|
||||||
|
///
|
||||||
|
/// Keys are slash-joined `providerID/modelID` to disambiguate
|
||||||
|
/// across providers — even if `vercel` later adds a `grok-4.20-beta`
|
||||||
|
/// alias on its own, the openrouter resolution shouldn't fire.
|
||||||
|
/// Values are the bare resolved model ID (no provider prefix).
|
||||||
|
///
|
||||||
|
/// **Schema is Swift-primary.** Mirror new entries into Hermes's
|
||||||
|
/// upstream deprecation map in `hermes_cli/providers.py` if/when
|
||||||
|
/// upstream tracks renames in code (today they're release-notes
|
||||||
|
/// only).
|
||||||
|
public static let modelAliases: [String: String] = [
|
||||||
|
// v0.13: x-ai dropped the `-beta` suffix once Grok 4.20 GA'd.
|
||||||
|
// The model is the same one served at the same OpenRouter slot;
|
||||||
|
// only the marketing identifier changed.
|
||||||
|
// TODO(WS-6-Q4): verify whether OpenRouter retired the
|
||||||
|
// `x-ai/grok-4.20-beta` slot entirely. Either way the alias is
|
||||||
|
// correct (cosmetic if old slot stays live, load-bearing if it
|
||||||
|
// 404s).
|
||||||
|
"openrouter/x-ai/grok-4.20-beta": "x-ai/grok-4.20",
|
||||||
|
"xai/grok-4.20-beta": "grok-4.20",
|
||||||
|
"vercel/xai/grok-4.20-beta": "xai/grok-4.20",
|
||||||
|
]
|
||||||
|
|
||||||
|
/// Resolve a stored model identifier through the alias map. Returns
|
||||||
|
/// the input unchanged when no alias exists. Pure function — used at
|
||||||
|
/// read time everywhere a config'd model ID is rendered, validated,
|
||||||
|
/// or sent to Hermes.
|
||||||
|
public func resolveModelAlias(providerID: String, modelID: String) -> String {
|
||||||
|
let composite = "\(providerID)/\(modelID)"
|
||||||
|
return Self.modelAliases[composite] ?? modelID
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Demoted providers (sort tail)
|
||||||
|
|
||||||
|
/// Provider IDs that Hermes v0.13 explicitly deprioritizes in the
|
||||||
|
/// picker. `loadProviders()` sorts these to the tail of the list,
|
||||||
|
/// after the alphabetical group, so users who haven't manually
|
||||||
|
/// chosen Vercel as their gateway don't end up there by default.
|
||||||
|
/// Mirrors Hermes's deprioritized-provider list in
|
||||||
|
/// `hermes-agent/hermes_cli/providers.py`.
|
||||||
|
public static let demotedProviders: Set<String> = [
|
||||||
|
"vercel",
|
||||||
|
]
|
||||||
|
|
||||||
|
// MARK: - Image-generation model allowlist (curated)
|
||||||
|
|
||||||
|
/// Known image-generation models, used to pre-populate the
|
||||||
|
/// `image_gen.model` picker on the Auxiliary tab. The list is
|
||||||
|
/// curated — `models_dev_cache.json` doesn't tag image-capable
|
||||||
|
/// models, so we maintain this by hand on Hermes version bumps.
|
||||||
|
/// Always free-form-typeable on the picker too, so missing entries
|
||||||
|
/// don't block users with non-listed image providers.
|
||||||
|
///
|
||||||
|
/// Order: most-likely-to-be-chosen first.
|
||||||
|
public static let imageGenModels: [HermesImageGenModel] = [
|
||||||
|
.init(modelID: "openai/gpt-image-1", display: "OpenAI · gpt-image-1", providerHint: "openai"),
|
||||||
|
.init(modelID: "google/imagen-4", display: "Google · Imagen 4", providerHint: "google-vertex"),
|
||||||
|
.init(modelID: "google/imagen-3", display: "Google · Imagen 3", providerHint: "google-vertex"),
|
||||||
|
.init(modelID: "stability/stable-image-ultra", display: "Stability · Stable Image Ultra", providerHint: "stability"),
|
||||||
|
.init(modelID: "fal-ai/flux-pro-1.1", display: "fal · FLUX 1.1 Pro", providerHint: "fal"),
|
||||||
|
.init(modelID: "black-forest-labs/flux-1.1-pro", display: "Black Forest Labs · FLUX 1.1 Pro", providerHint: "openrouter"),
|
||||||
|
.init(modelID: "openai/dall-e-3", display: "OpenAI · DALL·E 3", providerHint: "openai"),
|
||||||
|
]
|
||||||
|
|
||||||
// MARK: - Hermes overlay providers
|
// MARK: - Hermes overlay providers
|
||||||
|
|
||||||
/// The 11 providers Hermes surfaces via `hermes model` that have no
|
/// The 11 providers Hermes surfaces via `hermes model` that have no
|
||||||
@@ -538,6 +631,27 @@ public struct ModelCatalogService: Sendable {
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Curated entry for the `image_gen.model` picker on the Auxiliary
|
||||||
|
/// tab. Hermes v0.13 honors a top-level `image_gen.model` key but the
|
||||||
|
/// models.dev catalog has no `image: true` tag, so we maintain a
|
||||||
|
/// short hand-curated allowlist keyed by display order. The picker
|
||||||
|
/// always allows free-form-typing too, so any provider's model ID
|
||||||
|
/// works regardless of whether it appears here.
|
||||||
|
public struct HermesImageGenModel: Sendable, Identifiable, Hashable {
|
||||||
|
public let modelID: String
|
||||||
|
public let display: String
|
||||||
|
/// Hint at which provider serves this model — surfaced as a
|
||||||
|
/// "Configure provider X first" advisory but never enforced.
|
||||||
|
public let providerHint: String?
|
||||||
|
public var id: String { modelID }
|
||||||
|
|
||||||
|
public init(modelID: String, display: String, providerHint: String?) {
|
||||||
|
self.modelID = modelID
|
||||||
|
self.display = display
|
||||||
|
self.providerHint = providerHint
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Scarf-side mirror of `HermesOverlay` from hermes-agent's
|
/// Scarf-side mirror of `HermesOverlay` from hermes-agent's
|
||||||
/// `hermes_cli/providers.py`. Describes a provider that isn't in the
|
/// `hermes_cli/providers.py`. Describes a provider that isn't in the
|
||||||
/// models.dev catalog.
|
/// models.dev catalog.
|
||||||
|
|||||||
@@ -4,17 +4,19 @@ import Observation
|
|||||||
import os
|
import os
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
/// Mac + iOS view model for the v0.12 Curator surface.
|
/// Mac + iOS view model for the Curator surface (v0.12 base + v0.13
|
||||||
|
/// archive/prune additions).
|
||||||
///
|
///
|
||||||
/// Drives `hermes curator status / run / pause / resume / pin / unpin /
|
/// Drives `hermes curator status / run / pause / resume / pin / unpin /
|
||||||
/// restore` plus a parsed view of `~/.hermes/skills/.curator_state`
|
/// restore` plus (v0.13+) `archive`, `prune`, `list-archived`. All CLI
|
||||||
/// JSON. The CLI doesn't ship a `--json` flag for `status`, so we
|
/// invocations route through `CuratorService` (the actor) so polling
|
||||||
/// text-parse stdout (HermesCuratorStatusParser) and use the state
|
/// and writes share the same concurrency model and a single error path.
|
||||||
/// file for richer last-run metadata.
|
|
||||||
///
|
///
|
||||||
/// Capability-gated: callers should construct this only when
|
/// Capability-gated: callers should construct this only when
|
||||||
/// `HermesCapabilities.hasCurator` is true. The view model does not
|
/// `HermesCapabilities.hasCurator` is true. Archive-aware UI surfaces
|
||||||
/// gate itself — the gate happens at sidebar/tab routing time.
|
/// (Archive button, Archived section, Prune…) gate independently on
|
||||||
|
/// `hasCuratorArchive`. The view model itself doesn't gate — it exposes
|
||||||
|
/// every method and the View decides what to render.
|
||||||
@Observable
|
@Observable
|
||||||
@MainActor
|
@MainActor
|
||||||
public final class CuratorViewModel {
|
public final class CuratorViewModel {
|
||||||
@@ -27,20 +29,50 @@ public final class CuratorViewModel {
|
|||||||
public private(set) var status: HermesCuratorStatus = .empty
|
public private(set) var status: HermesCuratorStatus = .empty
|
||||||
public private(set) var isLoading = false
|
public private(set) var isLoading = false
|
||||||
public private(set) var lastReportMarkdown: String?
|
public private(set) var lastReportMarkdown: String?
|
||||||
|
|
||||||
|
// Archive state (v0.13+ only — populated by `loadArchive()` on hosts
|
||||||
|
// where `hasCuratorArchive` is true).
|
||||||
|
public private(set) var archivedSkills: [HermesCuratorArchivedSkill] = []
|
||||||
|
public private(set) var isLoadingArchive = false
|
||||||
|
|
||||||
|
// Prune state — `pruneSummary` non-nil while the confirm sheet is
|
||||||
|
// mid-flight; `isPruning` flips during the destructive step.
|
||||||
|
public private(set) var pruneSummary: CuratorPruneSummary?
|
||||||
|
public private(set) var isPruning = false
|
||||||
|
|
||||||
|
// Track which active-skill row is currently being archived so the
|
||||||
|
// row chrome can show an inline spinner without blocking the rest.
|
||||||
|
public private(set) var pendingArchiveName: String?
|
||||||
|
|
||||||
|
/// Happy-path success toast ("Pinned X", "Resumed", "Archived
|
||||||
|
/// legacy-helper"). Auto-clears 3s after assignment.
|
||||||
public var transientMessage: String?
|
public var transientMessage: String?
|
||||||
|
|
||||||
|
/// Failure path — populated by every CLI verb when it throws. Shown
|
||||||
|
/// as an inline yellow banner above the status summary so users
|
||||||
|
/// don't have to dismiss a modal alert during a high-frequency
|
||||||
|
/// surface like the leaderboard. Manually dismissed via the View's
|
||||||
|
/// "x" button (sets to nil).
|
||||||
|
public var errorMessage: String?
|
||||||
|
|
||||||
|
@ObservationIgnored
|
||||||
|
private let service: CuratorService
|
||||||
|
|
||||||
public init(context: ServerContext) {
|
public init(context: ServerContext) {
|
||||||
self.context = context
|
self.context = context
|
||||||
|
self.service = CuratorService(context: context)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Loads
|
||||||
|
|
||||||
public func load() async {
|
public func load() async {
|
||||||
isLoading = true
|
isLoading = true
|
||||||
defer { isLoading = false }
|
defer { isLoading = false }
|
||||||
let context = self.context
|
let context = self.context
|
||||||
// v2.8 — instrumented. Curator load fires `hermes curator
|
// v2.8 — instrumented. Curator load fires `hermes curator
|
||||||
// status` (CLI subprocess) plus 1-2 file reads; on remote
|
// status` (CLI subprocess) plus 1-2 file reads; on remote each
|
||||||
// each is a separate SSH RTT. Visibility lets future captures
|
// is a separate SSH RTT. Visibility lets future captures show
|
||||||
// show how often the report file is missing or oversized.
|
// how often the report file is missing or oversized.
|
||||||
let parsed = await ScarfMon.measureAsync(.diskIO, "curator.load") {
|
let parsed = await ScarfMon.measureAsync(.diskIO, "curator.load") {
|
||||||
await Task.detached(priority: .userInitiated) { () -> (HermesCuratorStatus, String?) in
|
await Task.detached(priority: .userInitiated) { () -> (HermesCuratorStatus, String?) in
|
||||||
let textResult = Self.runCuratorStatus(context: context)
|
let textResult = Self.runCuratorStatus(context: context)
|
||||||
@@ -69,46 +101,156 @@ public final class CuratorViewModel {
|
|||||||
self.lastReportMarkdown = parsed.1
|
self.lastReportMarkdown = parsed.1
|
||||||
}
|
}
|
||||||
|
|
||||||
public func runNow() async {
|
/// Refresh the archived-skills list. No-op on hosts without
|
||||||
await runAndReload(args: ["curator", "run"], successMessage: "Curator run started")
|
/// `hasCuratorArchive` — the caller gates the call.
|
||||||
|
public func loadArchive() async {
|
||||||
|
isLoadingArchive = true
|
||||||
|
defer { isLoadingArchive = false }
|
||||||
|
do {
|
||||||
|
archivedSkills = try await service.listArchived()
|
||||||
|
} catch {
|
||||||
|
archivedSkills = []
|
||||||
|
errorMessage = (error as? LocalizedError)?.errorDescription
|
||||||
|
?? error.localizedDescription
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Writes (v0.12)
|
||||||
|
|
||||||
|
/// Run the curator manually. On v0.13+ hosts this blocks for the
|
||||||
|
/// duration of the run (default 600s timeout); pre-v0.13 returns
|
||||||
|
/// immediately. Caller passes the capability-decided flag.
|
||||||
|
public func runNow(synchronous: Bool, timeout: TimeInterval = 600) async {
|
||||||
|
await runWithReload(
|
||||||
|
verb: "run",
|
||||||
|
successMessage: synchronous ? "Curator run complete" : "Curator run started"
|
||||||
|
) {
|
||||||
|
try await self.service.runNow(synchronous: synchronous, timeout: timeout)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public func pause() async {
|
public func pause() async {
|
||||||
await runAndReload(args: ["curator", "pause"], successMessage: "Curator paused")
|
await runWithReload(verb: "pause", successMessage: "Curator paused") {
|
||||||
|
try await self.service.pause()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public func resume() async {
|
public func resume() async {
|
||||||
await runAndReload(args: ["curator", "resume"], successMessage: "Curator resumed")
|
await runWithReload(verb: "resume", successMessage: "Curator resumed") {
|
||||||
|
try await self.service.resume()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public func pin(_ skill: String) async {
|
public func pin(_ skill: String) async {
|
||||||
await runAndReload(args: ["curator", "pin", skill], successMessage: "Pinned \(skill)")
|
await runWithReload(verb: "pin", successMessage: "Pinned \(skill)") {
|
||||||
|
try await self.service.pin(skill)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public func unpin(_ skill: String) async {
|
public func unpin(_ skill: String) async {
|
||||||
await runAndReload(args: ["curator", "unpin", skill], successMessage: "Unpinned \(skill)")
|
await runWithReload(verb: "unpin", successMessage: "Unpinned \(skill)") {
|
||||||
|
try await self.service.unpin(skill)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public func restore(_ skill: String) async {
|
public func restore(_ skill: String) async {
|
||||||
await runAndReload(args: ["curator", "restore", skill], successMessage: "Restored \(skill)")
|
await runWithReload(verb: "restore", successMessage: "Restored \(skill)") {
|
||||||
|
try await self.service.restore(skill)
|
||||||
|
}
|
||||||
|
// Restore drops the entry from the archived list — refresh it
|
||||||
|
// so the row disappears immediately.
|
||||||
|
await loadArchive()
|
||||||
}
|
}
|
||||||
|
|
||||||
private func runAndReload(args: [String], successMessage: String) async {
|
// MARK: - Writes (v0.13)
|
||||||
let context = self.context
|
|
||||||
let exitCode = await Task.detached(priority: .userInitiated) {
|
public func archive(_ skill: String) async {
|
||||||
Self.runHermes(context: context, args: args).exitCode
|
pendingArchiveName = skill
|
||||||
}.value
|
await runWithReload(verb: "archive", successMessage: "Archived \(skill)") {
|
||||||
transientMessage = exitCode == 0 ? successMessage : "Command failed"
|
try await self.service.archive(skill)
|
||||||
|
}
|
||||||
|
pendingArchiveName = nil
|
||||||
|
await loadArchive()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stage 1 of the bulk-prune flow. Calls `prune --dry-run` and
|
||||||
|
/// populates `pruneSummary`; the View binds its confirm sheet to
|
||||||
|
/// the non-nil presence of this property.
|
||||||
|
public func planPrune() async {
|
||||||
|
do {
|
||||||
|
pruneSummary = try await service.prune(dryRun: true)
|
||||||
|
} catch {
|
||||||
|
errorMessage = (error as? LocalizedError)?.errorDescription
|
||||||
|
?? error.localizedDescription
|
||||||
|
pruneSummary = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stage 2 of the bulk-prune flow. Destructive — removes everything
|
||||||
|
/// currently archived. Clears `pruneSummary` regardless of outcome
|
||||||
|
/// so the confirm sheet dismisses.
|
||||||
|
public func confirmPrune() async {
|
||||||
|
isPruning = true
|
||||||
|
do {
|
||||||
|
_ = try await service.prune(dryRun: false)
|
||||||
|
transientMessage = "Pruned archived skills"
|
||||||
|
errorMessage = nil
|
||||||
|
await loadArchive()
|
||||||
await load()
|
await load()
|
||||||
// Auto-clear toast after 3s.
|
scheduleTransientClear()
|
||||||
|
} catch {
|
||||||
|
errorMessage = (error as? LocalizedError)?.errorDescription
|
||||||
|
?? error.localizedDescription
|
||||||
|
}
|
||||||
|
isPruning = false
|
||||||
|
pruneSummary = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel the in-flight prune-confirm flow without running.
|
||||||
|
public func cancelPrune() {
|
||||||
|
pruneSummary = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
/// User-driven dismissal of the inline error banner.
|
||||||
|
public func dismissError() {
|
||||||
|
errorMessage = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Helpers
|
||||||
|
|
||||||
|
/// Run a service call, route success → `transientMessage`, failure
|
||||||
|
/// → `errorMessage`, and reload `status` either way. Mirrors the
|
||||||
|
/// previous `runAndReload` helper but goes through the typed
|
||||||
|
/// service surface.
|
||||||
|
private func runWithReload(
|
||||||
|
verb: String,
|
||||||
|
successMessage: String,
|
||||||
|
body: @escaping @Sendable () async throws -> Void
|
||||||
|
) async {
|
||||||
|
do {
|
||||||
|
try await body()
|
||||||
|
transientMessage = successMessage
|
||||||
|
errorMessage = nil
|
||||||
|
await load()
|
||||||
|
scheduleTransientClear()
|
||||||
|
} catch {
|
||||||
|
let message = (error as? LocalizedError)?.errorDescription
|
||||||
|
?? error.localizedDescription
|
||||||
|
errorMessage = message
|
||||||
|
transientMessage = nil
|
||||||
|
await load()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func scheduleTransientClear() {
|
||||||
Task { @MainActor [weak self] in
|
Task { @MainActor [weak self] in
|
||||||
try? await Task.sleep(nanoseconds: 3_000_000_000)
|
try? await Task.sleep(nanoseconds: 3_000_000_000)
|
||||||
self?.transientMessage = nil
|
self?.transientMessage = nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Wrap the transport-level `runProcess` so the call sites don't
|
// MARK: - Legacy sync helpers (kept for `load`'s detached path)
|
||||||
/// have to reach for it directly. Combined stdout+stderr.
|
|
||||||
nonisolated private static func runHermes(
|
nonisolated private static func runHermes(
|
||||||
context: ServerContext,
|
context: ServerContext,
|
||||||
args: [String]
|
args: [String]
|
||||||
|
|||||||
@@ -229,6 +229,12 @@ public final class RichChatViewModel {
|
|||||||
public private(set) var acpOutputTokens = 0
|
public private(set) var acpOutputTokens = 0
|
||||||
public private(set) var acpThoughtTokens = 0
|
public private(set) var acpThoughtTokens = 0
|
||||||
public private(set) var acpCachedReadTokens = 0
|
public private(set) var acpCachedReadTokens = 0
|
||||||
|
/// Running count of context compactions Hermes has performed on this
|
||||||
|
/// session. Surfaced as the `🗜 ×N` chip in `SessionInfoBar` when > 0
|
||||||
|
/// and `HermesCapabilities.hasContextCompressionCount` is true. Each
|
||||||
|
/// `session/prompt` response carries the latest server-side total, so
|
||||||
|
/// we replace (with a `max` guard) rather than accumulate.
|
||||||
|
public private(set) var acpCompressionCount = 0
|
||||||
|
|
||||||
/// Slash commands advertised by the ACP server via `available_commands_update`.
|
/// Slash commands advertised by the ACP server via `available_commands_update`.
|
||||||
public private(set) var acpCommands: [HermesSlashCommand] = []
|
public private(set) var acpCommands: [HermesSlashCommand] = []
|
||||||
@@ -248,15 +254,73 @@ public final class RichChatViewModel {
|
|||||||
/// Hermes v2026.4.23+ but listed here unconditionally so older
|
/// Hermes v2026.4.23+ but listed here unconditionally so older
|
||||||
/// hosts that don't advertise it still surface the trigger; the
|
/// hosts that don't advertise it still surface the trigger; the
|
||||||
/// agent will respond appropriately or no-op gracefully.
|
/// agent will respond appropriately or no-op gracefully.
|
||||||
|
///
|
||||||
|
/// v2.8 / Hermes v0.13 adds `/goal` (lock the agent on a target
|
||||||
|
/// across turns) and `/queue` (queue a prompt for after the current
|
||||||
|
/// turn). Both ride the same `.acpNonInterruptive` source — Hermes
|
||||||
|
/// parses them server-side, the wire shape is plain
|
||||||
|
/// `session/prompt`, and the chat UI keeps the "Agent working…"
|
||||||
|
/// indicator off when they're sent. They're listed unconditionally
|
||||||
|
/// here; capability filtering happens in `availableCommands` so
|
||||||
|
/// pre-v0.13 hosts don't see `/goal` or `/queue` in the slash menu.
|
||||||
|
// TODO(WS-2-Q7): verify against a real v0.13 ACP host that `/goal`
|
||||||
|
// is in fact non-interruptive on the wire. If Hermes treats it as a
|
||||||
|
// regular prompt that flips "Agent working…", drop it from this
|
||||||
|
// list and route it through the standard send path (the pill
|
||||||
|
// bookkeeping in `recordActiveGoal` is independent of the
|
||||||
|
// interruptive classification).
|
||||||
public static let nonInterruptiveCommands: [HermesSlashCommand] = [
|
public static let nonInterruptiveCommands: [HermesSlashCommand] = [
|
||||||
HermesSlashCommand(
|
HermesSlashCommand(
|
||||||
name: "steer",
|
name: "steer",
|
||||||
description: "Nudge the agent mid-run (applies after the next tool call)",
|
description: "Nudge the agent mid-run (applies after the next tool call)",
|
||||||
argumentHint: "<guidance>",
|
argumentHint: "<guidance>",
|
||||||
source: .acpNonInterruptive
|
source: .acpNonInterruptive
|
||||||
|
),
|
||||||
|
HermesSlashCommand(
|
||||||
|
name: "goal",
|
||||||
|
description: "Lock the agent on a goal that persists across turns",
|
||||||
|
argumentHint: "<text>",
|
||||||
|
source: .acpNonInterruptive
|
||||||
|
),
|
||||||
|
HermesSlashCommand(
|
||||||
|
name: "queue",
|
||||||
|
description: "Queue a prompt to run after the current turn",
|
||||||
|
argumentHint: "<text>",
|
||||||
|
source: .acpNonInterruptive
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
|
|
||||||
|
/// Capability snapshot the chat surface uses to filter
|
||||||
|
/// `availableCommands`. Set by the chat controller (Mac
|
||||||
|
/// `ChatViewModel`, iOS `ChatController`) at session-start time and
|
||||||
|
/// kept fresh via the `HermesCapabilitiesStore` env binding. Default
|
||||||
|
/// `.empty` means "no v0.13 surfaces" — pre-v0.13 hosts and harness
|
||||||
|
/// scenarios (Previews, smoke tests) never expose `/goal` or
|
||||||
|
/// `/queue` until the controller publishes a real capabilities
|
||||||
|
/// value. `@ObservationIgnored` so capability refreshes don't trash
|
||||||
|
/// the streaming-message render budget; controllers call
|
||||||
|
/// `publishCapabilities(_:)` once per refresh tick.
|
||||||
|
@ObservationIgnored
|
||||||
|
public var capabilitiesGate: HermesCapabilities = .empty
|
||||||
|
|
||||||
|
/// Optimistic local mirror of the agent's currently-locked goal.
|
||||||
|
/// Set by `recordActiveGoal(text:)` the moment the user sends
|
||||||
|
/// `/goal …`; cleared on `/goal --clear` or `reset()`. Pre-v0.13
|
||||||
|
/// hosts can't reach this code path (the slash menu hides `/goal`),
|
||||||
|
/// but a typed-out `/goal foo` against an older host would still
|
||||||
|
/// land here briefly until Hermes' "unknown command" reply lands —
|
||||||
|
/// see WS-2 plan "Inconsistency caveat".
|
||||||
|
public private(set) var activeGoal: HermesActiveGoal?
|
||||||
|
|
||||||
|
/// Optimistic mirror of prompts the user has queued via `/queue …`
|
||||||
|
/// while a turn is in flight. Hermes is the authoritative owner
|
||||||
|
/// server-side; this list drives the chat-header chip + popover and
|
||||||
|
/// drains FIFO via `popQueuedPrompt()` when a turn completes.
|
||||||
|
/// Best-effort: if Hermes' server-side queue gets out of sync
|
||||||
|
/// (deferred prompt aborted, dropped on disconnect) the user sees a
|
||||||
|
/// stale chip until their next interaction.
|
||||||
|
public private(set) var queuedPrompts: [HermesQueuedPrompt] = []
|
||||||
|
|
||||||
/// Transient hint shown above the composer, e.g. "Guidance queued —
|
/// Transient hint shown above the composer, e.g. "Guidance queued —
|
||||||
/// applies after the next tool call." for `/steer`. The chat view
|
/// applies after the next tool call." for `/steer`. The chat view
|
||||||
/// auto-clears it after a short delay (handled in the view); the
|
/// auto-clears it after a short delay (handled in the view); the
|
||||||
@@ -318,12 +382,94 @@ public final class RichChatViewModel {
|
|||||||
!acpNames.contains($0.name) && !projectNames.contains($0.name)
|
!acpNames.contains($0.name) && !projectNames.contains($0.name)
|
||||||
}
|
}
|
||||||
let occupied = acpNames.union(projectNames).union(Set(quicks.map(\.name)))
|
let occupied = acpNames.union(projectNames).union(Set(quicks.map(\.name)))
|
||||||
let nonInterruptive = Self.nonInterruptiveCommands.filter {
|
// Capability gate: `/goal` and `/queue` are v0.13+ surfaces;
|
||||||
!occupied.contains($0.name)
|
// hide them when the connected host is older. `/steer` is
|
||||||
|
// surfaced unconditionally — it works on v0.11+ during an
|
||||||
|
// active turn; idle-session greying for pre-v0.13 hosts is
|
||||||
|
// the input bar's concern (it reads `hasACPSteerOnIdle`).
|
||||||
|
let supported: [HermesSlashCommand] = Self.nonInterruptiveCommands.filter { cmd in
|
||||||
|
switch cmd.name {
|
||||||
|
case "goal": return capabilitiesGate.hasGoals
|
||||||
|
case "queue": return capabilitiesGate.hasACPQueue
|
||||||
|
case "steer": return true
|
||||||
|
default: return true
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
let nonInterruptive = supported.filter { !occupied.contains($0.name) }
|
||||||
return acpCommands + projectAsHermes + quicks + nonInterruptive
|
return acpCommands + projectAsHermes + quicks + nonInterruptive
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Publish a fresh capabilities snapshot from the controller.
|
||||||
|
/// Called whenever `HermesCapabilitiesStore.capabilities` changes
|
||||||
|
/// (initial detection, post-refresh, server switch). The chat input
|
||||||
|
/// bar's slash menu re-reads `availableCommands` lazily, so this is
|
||||||
|
/// just a stored-value swap — no observable churn.
|
||||||
|
public func publishCapabilities(_ caps: HermesCapabilities) {
|
||||||
|
capabilitiesGate = caps
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Optimistic write triggered when the user sends `/goal <text>`.
|
||||||
|
/// Pass `nil` (or empty) to clear (the `/goal --clear` path). The
|
||||||
|
/// pill renders synchronously off this state; there is no
|
||||||
|
/// authoritative server read-back in v2.8.0 — see WS-2 plan Q1.
|
||||||
|
// TODO(WS-2-Q1): hook a Hermes-supplied goal-state read-back path
|
||||||
|
// here once we know whether v0.13 exposes goal state via an ACP
|
||||||
|
// session-startup notification, a session-sidecar JSON field, or a
|
||||||
|
// `/goal --status` reply. Until then `activeGoal` is purely
|
||||||
|
// user-set and does not survive a session resume.
|
||||||
|
public func recordActiveGoal(text: String?) {
|
||||||
|
if let text, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
|
||||||
|
activeGoal = HermesActiveGoal(
|
||||||
|
text: text.trimmingCharacters(in: .whitespacesAndNewlines),
|
||||||
|
setAt: Date()
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
activeGoal = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Append an optimistically-queued prompt to the local mirror
|
||||||
|
/// (driven by `/queue <text>`). No-op for empty / whitespace input.
|
||||||
|
public func recordQueuedPrompt(text: String) {
|
||||||
|
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard !trimmed.isEmpty else { return }
|
||||||
|
queuedPrompts.append(HermesQueuedPrompt(text: trimmed))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drain the next queued prompt off the local mirror, FIFO. Called
|
||||||
|
/// from `handlePromptComplete` once a turn settles — Hermes runs
|
||||||
|
/// the actual queued prompt server-side; popping here keeps the
|
||||||
|
/// header chip count honest. Returns the popped prompt for any
|
||||||
|
/// caller that wants to log it; the chat UI ignores the return.
|
||||||
|
@discardableResult
|
||||||
|
public func popQueuedPrompt() -> HermesQueuedPrompt? {
|
||||||
|
queuedPrompts.isEmpty ? nil : queuedPrompts.removeFirst()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse the argument slug from a `/goal …` invocation. Pure
|
||||||
|
/// function — exposed for unit tests. The chat dispatch reads this
|
||||||
|
/// to decide whether to set, clear, or no-op the optimistic pill.
|
||||||
|
public enum GoalCommandArgument: Equatable {
|
||||||
|
case set(String)
|
||||||
|
case clear
|
||||||
|
/// User typed `/goal` with no argument — Hermes will reply
|
||||||
|
/// with usage; Scarf shows a neutral hint and doesn't touch
|
||||||
|
/// the pill state.
|
||||||
|
case empty
|
||||||
|
}
|
||||||
|
|
||||||
|
public static func parseGoalArgument(_ raw: String) -> GoalCommandArgument {
|
||||||
|
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
if trimmed.isEmpty { return .empty }
|
||||||
|
// Accept `--clear`, `clear`, and case-insensitive variants so
|
||||||
|
// typos don't accidentally lock the goal text to literal
|
||||||
|
// "Clear". `--clear` is the canonical form (matches Hermes
|
||||||
|
// CLI flag style).
|
||||||
|
let lowered = trimmed.lowercased()
|
||||||
|
if lowered == "--clear" || lowered == "clear" { return .clear }
|
||||||
|
return .set(trimmed)
|
||||||
|
}
|
||||||
|
|
||||||
/// True when `text` is a non-interruptive command that should NOT
|
/// True when `text` is a non-interruptive command that should NOT
|
||||||
/// flip `isAgentWorking` to true on send. Used by the Mac/iOS chat
|
/// flip `isAgentWorking` to true on send. Used by the Mac/iOS chat
|
||||||
/// view models to skip the "agent working" overlay change for
|
/// view models to skip the "agent working" overlay change for
|
||||||
@@ -468,12 +614,21 @@ public final class RichChatViewModel {
|
|||||||
acpErrorHint = nil
|
acpErrorHint = nil
|
||||||
acpErrorDetails = nil
|
acpErrorDetails = nil
|
||||||
acpCachedReadTokens = 0
|
acpCachedReadTokens = 0
|
||||||
|
acpCompressionCount = 0
|
||||||
acpCommands = []
|
acpCommands = []
|
||||||
projectScopedCommands = []
|
projectScopedCommands = []
|
||||||
currentTurnStart = nil
|
currentTurnStart = nil
|
||||||
turnDurations = [:]
|
turnDurations = [:]
|
||||||
transientHint = nil
|
transientHint = nil
|
||||||
pendingPermission = nil
|
pendingPermission = nil
|
||||||
|
// v2.8 / Hermes v0.13 — drop optimistic v0.13 surfaces on
|
||||||
|
// session reset so a fresh chat (or a resume into a different
|
||||||
|
// session) doesn't paint stale goal / queue state from the
|
||||||
|
// previous one. The capabilities gate stays on whatever the
|
||||||
|
// controller most recently published; it's a host-level value
|
||||||
|
// that doesn't change with session boundaries.
|
||||||
|
activeGoal = nil
|
||||||
|
queuedPrompts = []
|
||||||
loadQuickCommands()
|
loadQuickCommands()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -811,7 +966,30 @@ public final class RichChatViewModel {
|
|||||||
acpOutputTokens += response.outputTokens
|
acpOutputTokens += response.outputTokens
|
||||||
acpThoughtTokens += response.thoughtTokens
|
acpThoughtTokens += response.thoughtTokens
|
||||||
acpCachedReadTokens += response.cachedReadTokens
|
acpCachedReadTokens += response.cachedReadTokens
|
||||||
|
// Compression count is a session-wide running total emitted by
|
||||||
|
// Hermes; each prompt response carries the latest value, so we
|
||||||
|
// replace rather than accumulate. The `max` guard tolerates
|
||||||
|
// pre-v0.13 hosts (which emit 0) being upgraded server-side
|
||||||
|
// mid-session — once a real number lands the count resumes from
|
||||||
|
// there rather than snapping back to 0.
|
||||||
|
acpCompressionCount = max(acpCompressionCount, response.compressionCount)
|
||||||
isAgentWorking = false
|
isAgentWorking = false
|
||||||
|
// v2.8 / Hermes v0.13 — Hermes runs the next `/queue`-deferred
|
||||||
|
// prompt server-side now that this turn has settled. Drain the
|
||||||
|
// local mirror FIFO so the header chip count matches what the
|
||||||
|
// user staged. Best-effort: if Hermes' authoritative queue
|
||||||
|
// diverged (deferred prompt aborted, dropped on disconnect),
|
||||||
|
// the chip is one tick stale until the user's next interaction.
|
||||||
|
if !queuedPrompts.isEmpty {
|
||||||
|
popQueuedPrompt()
|
||||||
|
}
|
||||||
|
// TODO(v2.8.1): when this completes after an auto-resumed
|
||||||
|
// checkpoint (Hermes v0.13's "Auto-resume interrupted sessions
|
||||||
|
// after gateway restart"), surface a one-shot "Auto-resumed
|
||||||
|
// from checkpoint" indicator. Wire-shape unknown until a v0.13
|
||||||
|
// dogfooding pass confirms whether the resume lands as a
|
||||||
|
// visible ACP event or is purely server-side. Deferred from
|
||||||
|
// v2.8.0 per WS-2 plan Q3.
|
||||||
buildMessageGroups()
|
buildMessageGroups()
|
||||||
// Final position after the prompt settles. Catches fast responses
|
// Final position after the prompt settles. Catches fast responses
|
||||||
// (slash commands, short replies) where `.defaultScrollAnchor(.bottom)`
|
// (slash commands, short replies) where `.defaultScrollAnchor(.bottom)`
|
||||||
|
|||||||
@@ -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"])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -151,4 +151,169 @@ import Foundation
|
|||||||
#expect(parsed?.patchCount == 2)
|
#expect(parsed?.patchCount == 2)
|
||||||
#expect(parsed?.lastActivityLabel == "2026-04-25")
|
#expect(parsed?.lastActivityLabel == "2026-04-25")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - v0.13 list-archived / prune fixtures (WS-4)
|
||||||
|
|
||||||
|
/// Empty JSON array → `[]`. Locks in the happy-path no-archives shape.
|
||||||
|
@Test func listArchivedEmpty() throws {
|
||||||
|
let result = try CuratorService.parseListArchived(stdout: "[]")
|
||||||
|
#expect(result.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Three archives with full optional fields. Asserts each
|
||||||
|
/// optional value decodes through `decodeIfPresent` and that
|
||||||
|
/// the computed labels resolve.
|
||||||
|
@Test func listArchivedThreeSkills() throws {
|
||||||
|
let json = """
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"name": "legacy-helper",
|
||||||
|
"category": "templates",
|
||||||
|
"archived_at": "2026-04-22T03:14:09Z",
|
||||||
|
"reason": "stale: 91d unused",
|
||||||
|
"size_bytes": 4521,
|
||||||
|
"path": "/Users/u/.hermes/skills/.archived/legacy-helper"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "old-translator",
|
||||||
|
"category": "user",
|
||||||
|
"archived_at": "2026-04-23T10:00:00Z",
|
||||||
|
"reason": "consolidated with translator",
|
||||||
|
"size_bytes": 8192
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "minimal"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
"""
|
||||||
|
let result = try CuratorService.parseListArchived(stdout: json)
|
||||||
|
#expect(result.count == 3)
|
||||||
|
#expect(result[0].name == "legacy-helper")
|
||||||
|
#expect(result[0].category == "templates")
|
||||||
|
#expect(result[0].reason == "stale: 91d unused")
|
||||||
|
#expect(result[0].sizeBytes == 4521)
|
||||||
|
#expect(result[0].archivedAtLabel == "2026-04-22")
|
||||||
|
#expect(result[0].path == "/Users/u/.hermes/skills/.archived/legacy-helper")
|
||||||
|
|
||||||
|
// Tolerant: only `name` set on the third row.
|
||||||
|
#expect(result[2].name == "minimal")
|
||||||
|
#expect(result[2].category == nil)
|
||||||
|
#expect(result[2].reason == nil)
|
||||||
|
#expect(result[2].archivedAtLabel == "—")
|
||||||
|
#expect(result[2].sizeLabel == "—")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `{"archived": [...]}` envelope is also accepted.
|
||||||
|
@Test func listArchivedEnvelope() throws {
|
||||||
|
let json = """
|
||||||
|
{"archived": [
|
||||||
|
{"name": "envelope-skill", "size_bytes": 1024}
|
||||||
|
]}
|
||||||
|
"""
|
||||||
|
let result = try CuratorService.parseListArchived(stdout: json)
|
||||||
|
#expect(result.count == 1)
|
||||||
|
#expect(result[0].name == "envelope-skill")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text fallback when `--json` isn't supported. Each row carries
|
||||||
|
/// the name in column 1 plus k=v chips for the optional fields.
|
||||||
|
@Test func listArchivedTextFallback() {
|
||||||
|
let text = """
|
||||||
|
legacy-helper archived=2026-04-22 size=4521 reason=stale
|
||||||
|
old-translator archived=2026-04-23 size=8192
|
||||||
|
minimal-row
|
||||||
|
"""
|
||||||
|
let result = CuratorService.parseListArchivedText(text)
|
||||||
|
#expect(result.count == 3)
|
||||||
|
#expect(result[0].name == "legacy-helper")
|
||||||
|
#expect(result[0].archivedAt == "2026-04-22")
|
||||||
|
#expect(result[0].sizeBytes == 4521)
|
||||||
|
#expect(result[0].reason == "stale")
|
||||||
|
#expect(result[2].name == "minimal-row")
|
||||||
|
#expect(result[2].sizeBytes == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Empty-state sentinel folds to `[]` (parallel to KanbanService's
|
||||||
|
/// `"no matching tasks"` handling).
|
||||||
|
@Test func listArchivedNoArchivedSentinel() throws {
|
||||||
|
let result = try CuratorService.parseListArchived(stdout: "no archived skills\n")
|
||||||
|
#expect(result.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whitespace-only stdout also folds to empty.
|
||||||
|
@Test func listArchivedWhitespaceFoldsToEmpty() throws {
|
||||||
|
let result = try CuratorService.parseListArchived(stdout: " \n\n")
|
||||||
|
#expect(result.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode failure (clearly non-JSON, non-text) throws. We accept
|
||||||
|
/// JSON, the envelope, the empty sentinel, or text rows; anything
|
||||||
|
/// else surfaces as a `CuratorError.decoding`.
|
||||||
|
@Test func listArchivedNonsenseThrows() throws {
|
||||||
|
do {
|
||||||
|
_ = try CuratorService.parseListArchived(stdout: "{garbage")
|
||||||
|
Issue.record("expected decoding throw")
|
||||||
|
} catch let error as CuratorError {
|
||||||
|
if case .decoding = error {
|
||||||
|
// expected
|
||||||
|
} else {
|
||||||
|
Issue.record("unexpected error \(error)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Prune-dry-run JSON with `would_remove` + `total_bytes`.
|
||||||
|
@Test func pruneDryRunHappyPath() {
|
||||||
|
let json = """
|
||||||
|
{
|
||||||
|
"would_remove": [
|
||||||
|
{"name": "stale-a", "size_bytes": 1000},
|
||||||
|
{"name": "stale-b", "size_bytes": 2000}
|
||||||
|
],
|
||||||
|
"total_bytes": 3000
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
let summary = CuratorService.parsePruneDryRun(json)
|
||||||
|
#expect(summary.totalCount == 2)
|
||||||
|
#expect(summary.totalBytes == 3000)
|
||||||
|
#expect(summary.wouldRemove.first?.name == "stale-a")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Zero-skill prune is a valid dry-run (no archives).
|
||||||
|
@Test func pruneDryRunZeroSkills() {
|
||||||
|
let json = """
|
||||||
|
{"would_remove": [], "total_bytes": 0}
|
||||||
|
"""
|
||||||
|
let summary = CuratorService.parsePruneDryRun(json)
|
||||||
|
#expect(summary.totalCount == 0)
|
||||||
|
#expect(summary.totalBytes == 0)
|
||||||
|
#expect(summary.totalBytesLabel == "—")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bare-array fallback: some Hermes builds may print just the
|
||||||
|
/// would-remove list when the wrapper is missing.
|
||||||
|
@Test func pruneDryRunBareArrayFallback() {
|
||||||
|
let json = """
|
||||||
|
[{"name": "lonely", "size_bytes": 500}]
|
||||||
|
"""
|
||||||
|
let summary = CuratorService.parsePruneDryRun(json)
|
||||||
|
#expect(summary.totalCount == 1)
|
||||||
|
#expect(summary.totalBytes == 500)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Empty / whitespace stdout → zero summary (no decoding throw).
|
||||||
|
@Test func pruneDryRunEmptyStaysSafe() {
|
||||||
|
let summary = CuratorService.parsePruneDryRun(" \n")
|
||||||
|
#expect(summary.totalCount == 0)
|
||||||
|
#expect(summary.totalBytes == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verify the size label uses the byte formatter (not raw bytes).
|
||||||
|
@Test func archivedSkillSizeLabelFormats() {
|
||||||
|
let big = HermesCuratorArchivedSkill(name: "x", sizeBytes: 1_500_000)
|
||||||
|
// ByteCountFormatter produces a localized label; just verify
|
||||||
|
// it's non-empty and not raw "1500000".
|
||||||
|
#expect(!big.sizeLabel.isEmpty)
|
||||||
|
#expect(big.sizeLabel != "1500000")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -310,6 +310,74 @@ import Foundation
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - ModelCatalogService — WS-6 (v0.13)
|
||||||
|
|
||||||
|
@Test func vercelAIGatewayDemotedToBottom() throws {
|
||||||
|
// Build a minimal catalog with vercel + alphabetically-later
|
||||||
|
// providers, then assert vercel sorts after them. Locks the
|
||||||
|
// demoted-axis sort comparator added in WS-6.
|
||||||
|
let json = """
|
||||||
|
{
|
||||||
|
"anthropic": { "name": "Anthropic", "models": {} },
|
||||||
|
"vercel": { "name": "Vercel AI Gateway", "models": {} },
|
||||||
|
"zonk": { "name": "Zonk Provider", "models": {} }
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
let tmp = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("scarf-models-\(UUID().uuidString).json")
|
||||||
|
try json.write(to: tmp, atomically: true, encoding: .utf8)
|
||||||
|
defer { try? FileManager.default.removeItem(at: tmp) }
|
||||||
|
let svc = ModelCatalogService(path: tmp.path)
|
||||||
|
let providers = svc.loadProviders().filter { !$0.isOverlay }
|
||||||
|
let names = providers.map(\.providerName)
|
||||||
|
// anthropic first (alpha), zonk next (alpha), vercel last
|
||||||
|
// (demoted) — even though `vercel` < `zonk` alphabetically.
|
||||||
|
#expect(names.last == "Vercel AI Gateway")
|
||||||
|
let vercelIdx = names.firstIndex(of: "Vercel AI Gateway") ?? -1
|
||||||
|
let zonkIdx = names.firstIndex(of: "Zonk Provider") ?? -1
|
||||||
|
#expect(vercelIdx > zonkIdx)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func grok420BetaAliasResolvesToGrok420() {
|
||||||
|
let svc = ModelCatalogService(path: "/tmp/scarf-nonexistent-\(UUID().uuidString).json")
|
||||||
|
// OpenRouter's old `-beta` ID resolves to the GA name.
|
||||||
|
#expect(svc.resolveModelAlias(providerID: "openrouter", modelID: "x-ai/grok-4.20-beta")
|
||||||
|
== "x-ai/grok-4.20")
|
||||||
|
// xAI direct provider keeps the same shape minus prefix.
|
||||||
|
#expect(svc.resolveModelAlias(providerID: "xai", modelID: "grok-4.20-beta")
|
||||||
|
== "grok-4.20")
|
||||||
|
// Non-aliased ID passes through unchanged.
|
||||||
|
#expect(svc.resolveModelAlias(providerID: "anthropic", modelID: "claude-4.7-opus")
|
||||||
|
== "claude-4.7-opus")
|
||||||
|
// Cross-provider isolation: same modelID on a different
|
||||||
|
// provider isn't aliased — composite key in `modelAliases`
|
||||||
|
// disambiguates by providerID.
|
||||||
|
#expect(svc.resolveModelAlias(providerID: "fictional", modelID: "x-ai/grok-4.20-beta")
|
||||||
|
== "x-ai/grok-4.20-beta")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func imageGenModelAllowlistShape() {
|
||||||
|
// Lock the curated list size + a few sentinel entries so
|
||||||
|
// unintentional edits get caught in review. Free-form-typing
|
||||||
|
// bypasses the allowlist, so additions/removals here are
|
||||||
|
// purely UX (which models surface as picker rows).
|
||||||
|
let models = ModelCatalogService.imageGenModels
|
||||||
|
#expect(models.count >= 5)
|
||||||
|
#expect(models.contains(where: { $0.modelID == "openai/gpt-image-1" }))
|
||||||
|
#expect(models.contains(where: { $0.modelID == "google/imagen-4" }))
|
||||||
|
// Every entry has a non-empty display + a non-empty modelID.
|
||||||
|
for m in models {
|
||||||
|
#expect(!m.modelID.isEmpty)
|
||||||
|
#expect(!m.display.isEmpty)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func demotedProvidersContainsVercel() {
|
||||||
|
// Minimal lock-in for the demoted-providers static set. Mirrors
|
||||||
|
// Hermes's deprioritized-provider list in providers.py.
|
||||||
|
#expect(ModelCatalogService.demotedProviders.contains("vercel"))
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - ProjectDashboardService
|
// MARK: - ProjectDashboardService
|
||||||
|
|
||||||
@Test func projectDashboardServiceRegistryRoundTrip() throws {
|
@Test func projectDashboardServiceRegistryRoundTrip() throws {
|
||||||
|
|||||||
@@ -162,6 +162,47 @@ import Foundation
|
|||||||
// start → false.
|
// start → false.
|
||||||
#expect(vm.supportsCompress == false)
|
#expect(vm.supportsCompress == false)
|
||||||
#expect(vm.hasBroaderCommandMenu == false)
|
#expect(vm.hasBroaderCommandMenu == false)
|
||||||
|
// v0.13: compression count starts at 0 so the SessionInfoBar chip
|
||||||
|
// stays hidden on fresh sessions.
|
||||||
|
#expect(vm.acpCompressionCount == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test @MainActor func richChatTracksCompressionCountFromPromptResults() {
|
||||||
|
let vm = RichChatViewModel(context: .local)
|
||||||
|
let response = ACPPromptResult(
|
||||||
|
stopReason: "end_turn",
|
||||||
|
inputTokens: 100, outputTokens: 50,
|
||||||
|
thoughtTokens: 20, cachedReadTokens: 10,
|
||||||
|
compressionCount: 3
|
||||||
|
)
|
||||||
|
vm.handleACPEvent(.promptComplete(sessionId: "s", response: response))
|
||||||
|
#expect(vm.acpCompressionCount == 3)
|
||||||
|
|
||||||
|
// Subsequent prompts overwrite (with a max guard) — the server
|
||||||
|
// emits a session-wide running total, not a per-prompt delta.
|
||||||
|
let next = ACPPromptResult(
|
||||||
|
stopReason: "end_turn",
|
||||||
|
inputTokens: 0, outputTokens: 0,
|
||||||
|
thoughtTokens: 0, cachedReadTokens: 0,
|
||||||
|
compressionCount: 5
|
||||||
|
)
|
||||||
|
vm.handleACPEvent(.promptComplete(sessionId: "s", response: next))
|
||||||
|
#expect(vm.acpCompressionCount == 5)
|
||||||
|
|
||||||
|
// A pre-v0.13 host mid-session emits 0; the max-guard keeps the
|
||||||
|
// last real value rather than snapping back.
|
||||||
|
let stale = ACPPromptResult(
|
||||||
|
stopReason: "end_turn",
|
||||||
|
inputTokens: 0, outputTokens: 0,
|
||||||
|
thoughtTokens: 0, cachedReadTokens: 0,
|
||||||
|
compressionCount: 0
|
||||||
|
)
|
||||||
|
vm.handleACPEvent(.promptComplete(sessionId: "s", response: stale))
|
||||||
|
#expect(vm.acpCompressionCount == 5)
|
||||||
|
|
||||||
|
// reset() clears the counter so a fresh session starts clean.
|
||||||
|
vm.reset()
|
||||||
|
#expect(vm.acpCompressionCount == 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test @MainActor func messageGroupDerivedProperties() {
|
@Test @MainActor func messageGroupDerivedProperties() {
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
@testable import ScarfCore
|
||||||
|
|
||||||
|
/// Pure-function matrix for `HermesUpdaterCommandBuilder.updateArgv`. The
|
||||||
|
/// builder degrades flags silently when the connected host can't honor
|
||||||
|
/// them, so the "is the right flag emitted on the right version?" matrix
|
||||||
|
/// is the meaningful test surface.
|
||||||
|
@Suite struct M0eUpdaterTests {
|
||||||
|
|
||||||
|
// MARK: - Helpers
|
||||||
|
|
||||||
|
private func caps(_ versionLine: String?) -> HermesCapabilities {
|
||||||
|
guard let line = versionLine else { return .empty }
|
||||||
|
return HermesCapabilities.parseLine(line)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Pre-v0.12 (no flags supported)
|
||||||
|
|
||||||
|
@Test func preV012_returnsBareUpdateRegardlessOfFlags() {
|
||||||
|
let pre = caps("Hermes Agent v0.11.0 (2026.4.23)")
|
||||||
|
#expect(HermesUpdaterCommandBuilder.updateArgv(
|
||||||
|
capabilities: pre, unattended: false, checkOnly: false
|
||||||
|
) == ["update"])
|
||||||
|
#expect(HermesUpdaterCommandBuilder.updateArgv(
|
||||||
|
capabilities: pre, unattended: true, checkOnly: false
|
||||||
|
) == ["update"])
|
||||||
|
#expect(HermesUpdaterCommandBuilder.updateArgv(
|
||||||
|
capabilities: pre, unattended: true, checkOnly: true
|
||||||
|
) == ["update"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func unknownVersion_returnsBareUpdate() {
|
||||||
|
// No detected version means we can't guarantee any flag is
|
||||||
|
// honored; defensively emit the bare verb.
|
||||||
|
#expect(HermesUpdaterCommandBuilder.updateArgv(
|
||||||
|
capabilities: .empty, unattended: true, checkOnly: true
|
||||||
|
) == ["update"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - v0.12 (--check supported, --yes is not)
|
||||||
|
|
||||||
|
@Test func v012_checkOnly_emitsCheckFlag() {
|
||||||
|
let v012 = caps("Hermes Agent v0.12.0 (2026.4.30)")
|
||||||
|
#expect(HermesUpdaterCommandBuilder.updateArgv(
|
||||||
|
capabilities: v012, unattended: false, checkOnly: true
|
||||||
|
) == ["update", "--check"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func v012_unattended_dropsYesFlag() {
|
||||||
|
// v0.12 doesn't honor --yes; the helper degrades silently.
|
||||||
|
let v012 = caps("Hermes Agent v0.12.0 (2026.4.30)")
|
||||||
|
#expect(HermesUpdaterCommandBuilder.updateArgv(
|
||||||
|
capabilities: v012, unattended: true, checkOnly: false
|
||||||
|
) == ["update"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func v012_checkOnlyAndUnattended_emitsOnlyCheck() {
|
||||||
|
let v012 = caps("Hermes Agent v0.12.0 (2026.4.30)")
|
||||||
|
#expect(HermesUpdaterCommandBuilder.updateArgv(
|
||||||
|
capabilities: v012, unattended: true, checkOnly: true
|
||||||
|
) == ["update", "--check"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - v0.13 (full flag support)
|
||||||
|
|
||||||
|
@Test func v013_unattended_emitsYesFlag() {
|
||||||
|
let v013 = caps("Hermes Agent v0.13.0 (2026.5.7)")
|
||||||
|
#expect(HermesUpdaterCommandBuilder.updateArgv(
|
||||||
|
capabilities: v013, unattended: true, checkOnly: false
|
||||||
|
) == ["update", "--yes"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func v013_checkOnlyAndUnattended_emitsBothFlags() {
|
||||||
|
let v013 = caps("Hermes Agent v0.13.0 (2026.5.7)")
|
||||||
|
#expect(HermesUpdaterCommandBuilder.updateArgv(
|
||||||
|
capabilities: v013, unattended: true, checkOnly: true
|
||||||
|
) == ["update", "--check", "--yes"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func v013_neither_emitsBareUpdate() {
|
||||||
|
let v013 = caps("Hermes Agent v0.13.0 (2026.5.7)")
|
||||||
|
#expect(HermesUpdaterCommandBuilder.updateArgv(
|
||||||
|
capabilities: v013, unattended: false, checkOnly: false
|
||||||
|
) == ["update"])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -92,6 +92,27 @@ import Foundation
|
|||||||
#expect(c.security.redactSecrets == true)
|
#expect(c.security.redactSecrets == true)
|
||||||
#expect(c.compression.enabled == true)
|
#expect(c.compression.enabled == true)
|
||||||
#expect(c.voice.ttsProvider == "edge")
|
#expect(c.voice.ttsProvider == "edge")
|
||||||
|
// v0.13 additions default to empty / off when the YAML omits
|
||||||
|
// them — pre-v0.13 hosts produce this exact shape.
|
||||||
|
#expect(c.imageGenModel == "")
|
||||||
|
#expect(c.openrouterResponseCacheEnabled == false)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func parsesImageGenAndOpenRouterCache() {
|
||||||
|
// WS-6: round-trip the two new top-level v0.13 keys. If the
|
||||||
|
// OpenRouter key shape changes upstream (see TODO(WS-6-Q1)),
|
||||||
|
// this test is the single touchpoint that pins the parser
|
||||||
|
// line + setter key + UI binding to a single shape.
|
||||||
|
let yaml = """
|
||||||
|
image_gen:
|
||||||
|
model: openai/gpt-image-1
|
||||||
|
openrouter:
|
||||||
|
response_cache:
|
||||||
|
enabled: true
|
||||||
|
"""
|
||||||
|
let c = HermesConfig(yaml: yaml)
|
||||||
|
#expect(c.imageGenModel == "openai/gpt-image-1")
|
||||||
|
#expect(c.openrouterResponseCacheEnabled == true)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func parsesTopLevelModel() {
|
@Test func parsesTopLevelModel() {
|
||||||
@@ -228,6 +249,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",
|
||||||
|
|||||||
@@ -241,6 +241,150 @@ import Foundation
|
|||||||
#expect(a == b)
|
#expect(a == b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - v0.13 non-interruptive commands (WS-2 / Persistent Goals + /queue)
|
||||||
|
|
||||||
|
@Test func nonInterruptiveListIncludesGoalAndQueue() {
|
||||||
|
let names = RichChatViewModel.nonInterruptiveCommands.map(\.name)
|
||||||
|
#expect(names.contains("steer"))
|
||||||
|
#expect(names.contains("goal"))
|
||||||
|
#expect(names.contains("queue"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func availableCommandsHidesGoalWhenCapabilityOff() {
|
||||||
|
let vm = RichChatViewModel(context: .local)
|
||||||
|
vm.publishCapabilities(.empty)
|
||||||
|
let names = vm.availableCommands.map(\.name)
|
||||||
|
#expect(!names.contains("goal"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func availableCommandsHidesQueueWhenCapabilityOff() {
|
||||||
|
let vm = RichChatViewModel(context: .local)
|
||||||
|
vm.publishCapabilities(.empty)
|
||||||
|
let names = vm.availableCommands.map(\.name)
|
||||||
|
#expect(!names.contains("queue"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func availableCommandsExposesAllThreeOnV013() {
|
||||||
|
let vm = RichChatViewModel(context: .local)
|
||||||
|
let caps = HermesCapabilities.parseLine("Hermes Agent v0.13.0 (2026.5.7)")
|
||||||
|
vm.publishCapabilities(caps)
|
||||||
|
let names = vm.availableCommands.map(\.name)
|
||||||
|
#expect(names.contains("steer"))
|
||||||
|
#expect(names.contains("goal"))
|
||||||
|
#expect(names.contains("queue"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func availableCommandsExposesSteerButHidesV013OnV012() {
|
||||||
|
let vm = RichChatViewModel(context: .local)
|
||||||
|
let caps = HermesCapabilities.parseLine("Hermes Agent v0.12.0 (2026.4.30)")
|
||||||
|
vm.publishCapabilities(caps)
|
||||||
|
let names = vm.availableCommands.map(\.name)
|
||||||
|
#expect(names.contains("steer"))
|
||||||
|
#expect(!names.contains("goal"))
|
||||||
|
#expect(!names.contains("queue"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func parseGoalArgumentRecognizesClearVariants() {
|
||||||
|
#expect(RichChatViewModel.parseGoalArgument("--clear") == .clear)
|
||||||
|
#expect(RichChatViewModel.parseGoalArgument("clear") == .clear)
|
||||||
|
#expect(RichChatViewModel.parseGoalArgument("Clear") == .clear)
|
||||||
|
#expect(RichChatViewModel.parseGoalArgument(" --clear ") == .clear)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func parseGoalArgumentReturnsSetForArbitraryText() {
|
||||||
|
#expect(
|
||||||
|
RichChatViewModel.parseGoalArgument("finish v2.8 on time")
|
||||||
|
== .set("finish v2.8 on time")
|
||||||
|
)
|
||||||
|
// Whitespace around set text is trimmed.
|
||||||
|
#expect(
|
||||||
|
RichChatViewModel.parseGoalArgument(" ship it ")
|
||||||
|
== .set("ship it")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func parseGoalArgumentReturnsEmptyForBlank() {
|
||||||
|
#expect(RichChatViewModel.parseGoalArgument("") == .empty)
|
||||||
|
#expect(RichChatViewModel.parseGoalArgument(" ") == .empty)
|
||||||
|
#expect(RichChatViewModel.parseGoalArgument("\n\t") == .empty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func recordActiveGoalSetsAndClears() {
|
||||||
|
let vm = RichChatViewModel(context: .local)
|
||||||
|
#expect(vm.activeGoal == nil)
|
||||||
|
vm.recordActiveGoal(text: "ship v2.8")
|
||||||
|
let goal = vm.activeGoal
|
||||||
|
#expect(goal?.text == "ship v2.8")
|
||||||
|
vm.recordActiveGoal(text: nil)
|
||||||
|
#expect(vm.activeGoal == nil)
|
||||||
|
// Empty / whitespace also clears.
|
||||||
|
vm.recordActiveGoal(text: "x")
|
||||||
|
vm.recordActiveGoal(text: " ")
|
||||||
|
#expect(vm.activeGoal == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func recordQueuedPromptAppendsAndPopsFIFO() {
|
||||||
|
let vm = RichChatViewModel(context: .local)
|
||||||
|
vm.recordQueuedPrompt(text: "first")
|
||||||
|
vm.recordQueuedPrompt(text: "second")
|
||||||
|
vm.recordQueuedPrompt(text: "third")
|
||||||
|
#expect(vm.queuedPrompts.count == 3)
|
||||||
|
let popped = vm.popQueuedPrompt()
|
||||||
|
#expect(popped?.text == "first")
|
||||||
|
#expect(vm.queuedPrompts.count == 2)
|
||||||
|
let next = vm.popQueuedPrompt()
|
||||||
|
#expect(next?.text == "second")
|
||||||
|
#expect(vm.queuedPrompts.first?.text == "third")
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func recordQueuedPromptIgnoresBlank() {
|
||||||
|
let vm = RichChatViewModel(context: .local)
|
||||||
|
vm.recordQueuedPrompt(text: "")
|
||||||
|
vm.recordQueuedPrompt(text: " ")
|
||||||
|
#expect(vm.queuedPrompts.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func popQueuedPromptOnEmptyReturnsNil() {
|
||||||
|
let vm = RichChatViewModel(context: .local)
|
||||||
|
#expect(vm.popQueuedPrompt() == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func isNonInterruptiveSlashRecognizesGoalAndQueue() {
|
||||||
|
// Non-MainActor: the helper itself isn't MainActor-isolated;
|
||||||
|
// construct a VM on MainActor and read through it on the test
|
||||||
|
// actor to keep the assertion focused on classification.
|
||||||
|
Task { @MainActor in
|
||||||
|
let vm = RichChatViewModel(context: .local)
|
||||||
|
#expect(vm.isNonInterruptiveSlash("/goal finish v2.8"))
|
||||||
|
#expect(vm.isNonInterruptiveSlash("/queue summarize"))
|
||||||
|
#expect(vm.isNonInterruptiveSlash("/queue"))
|
||||||
|
#expect(vm.isNonInterruptiveSlash("/steer be careful"))
|
||||||
|
#expect(!vm.isNonInterruptiveSlash("hello"))
|
||||||
|
#expect(!vm.isNonInterruptiveSlash("/compress"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func resetClearsGoalAndQueue() {
|
||||||
|
let vm = RichChatViewModel(context: .local)
|
||||||
|
vm.recordActiveGoal(text: "x")
|
||||||
|
vm.recordQueuedPrompt(text: "a")
|
||||||
|
vm.recordQueuedPrompt(text: "b")
|
||||||
|
#expect(vm.activeGoal != nil)
|
||||||
|
#expect(vm.queuedPrompts.count == 2)
|
||||||
|
vm.reset()
|
||||||
|
#expect(vm.activeGoal == nil)
|
||||||
|
#expect(vm.queuedPrompts.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Helpers
|
// MARK: - Helpers
|
||||||
|
|
||||||
static func makeTempProject() throws -> String {
|
static func makeTempProject() throws -> String {
|
||||||
|
|||||||
@@ -242,6 +242,15 @@ import Foundation
|
|||||||
thoughtTokens: 20, cachedReadTokens: 10
|
thoughtTokens: 20, cachedReadTokens: 10
|
||||||
)
|
)
|
||||||
#expect(prompt.stopReason == "end_turn")
|
#expect(prompt.stopReason == "end_turn")
|
||||||
|
// v0.13: compressionCount has a 0 default for legacy callers.
|
||||||
|
#expect(prompt.compressionCount == 0)
|
||||||
|
|
||||||
|
let v013Prompt = ACPPromptResult(
|
||||||
|
stopReason: "end_turn", inputTokens: 0, outputTokens: 0,
|
||||||
|
thoughtTokens: 0, cachedReadTokens: 0,
|
||||||
|
compressionCount: 7
|
||||||
|
)
|
||||||
|
#expect(v013Prompt.compressionCount == 7)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func projectDashboardInitChain() {
|
@Test func projectDashboardInitChain() {
|
||||||
|
|||||||
@@ -44,6 +44,19 @@ struct ChatView: View {
|
|||||||
private var supportsImagePrompts: Bool {
|
private var supportsImagePrompts: Bool {
|
||||||
capabilitiesStore?.capabilities.hasACPImagePrompts ?? false
|
capabilitiesStore?.capabilities.hasACPImagePrompts ?? false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// v0.13 `/goal` capability — drives the goal pill in `projectContextBar`.
|
||||||
|
/// Read-only on iOS in v2.8.0; users send `/goal` from the Mac. The pill
|
||||||
|
/// drops automatically when `vm.activeGoal` clears.
|
||||||
|
private var supportsActiveGoal: Bool {
|
||||||
|
capabilitiesStore?.capabilities.hasGoals ?? false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// v0.13 ACP `/queue` capability — drives the queue-count chip. Tap is a
|
||||||
|
/// no-op in v2.8.0 (no popover); previews live on the Mac app.
|
||||||
|
private var supportsACPQueue: Bool {
|
||||||
|
capabilitiesStore?.capabilities.hasACPQueue ?? false
|
||||||
|
}
|
||||||
/// Drives the composer's keyboard. Bound to the TextField via
|
/// Drives the composer's keyboard. Bound to the TextField via
|
||||||
/// `.focused(...)`; cleared by the scroll-to-dismiss gesture on
|
/// `.focused(...)`; cleared by the scroll-to-dismiss gesture on
|
||||||
/// the message list AND by an explicit keyboard-toolbar button.
|
/// the message list AND by an explicit keyboard-toolbar button.
|
||||||
@@ -109,6 +122,17 @@ struct ChatView: View {
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
// Forward the env-injected capabilities snapshot into the
|
||||||
|
// shared `RichChatViewModel` whenever it changes. Drives the
|
||||||
|
// capability gate `RichChatViewModel.availableCommands` reads.
|
||||||
|
// Mirrors the Mac `ChatView` plumbing — the iOS chat surface
|
||||||
|
// doesn't render `/goal` / `/queue` UI yet (deferred to WS-9),
|
||||||
|
// but the VM-side state has to stay aligned across platforms
|
||||||
|
// so the Mac surface is correct after a cross-device session
|
||||||
|
// resume.
|
||||||
|
.task(id: capabilitiesStore?.capabilities.versionLine ?? "") {
|
||||||
|
controller.vm.publishCapabilities(capabilitiesStore?.capabilities ?? .empty)
|
||||||
|
}
|
||||||
.task {
|
.task {
|
||||||
// Dashboard row taps set `pendingResumeSessionID`, Project
|
// Dashboard row taps set `pendingResumeSessionID`, Project
|
||||||
// Detail's "New Chat" sets `pendingProjectChat`. Both fire
|
// Detail's "New Chat" sets `pendingProjectChat`. Both fire
|
||||||
@@ -830,10 +854,17 @@ struct ChatView: View {
|
|||||||
/// informational.
|
/// informational.
|
||||||
@ViewBuilder
|
@ViewBuilder
|
||||||
private var projectContextBar: some View {
|
private var projectContextBar: some View {
|
||||||
if let projectName = controller.currentProjectName,
|
// v2.8.0 (WS-9): the bar is no longer project-only — a non-empty
|
||||||
!projectName.isEmpty
|
// active goal OR a non-empty queue mirror also light it up. Project
|
||||||
{
|
// chip, goal pill, and queue chip render independently and the bar
|
||||||
|
// shows when ANY of them is present.
|
||||||
|
let projectName = controller.currentProjectName ?? ""
|
||||||
|
let hasProject = !projectName.isEmpty
|
||||||
|
let hasGoal = supportsActiveGoal && controller.vm.activeGoal != nil
|
||||||
|
let hasQueue = supportsACPQueue && !controller.vm.queuedPrompts.isEmpty
|
||||||
|
if hasProject || hasGoal || hasQueue {
|
||||||
HStack(spacing: 8) {
|
HStack(spacing: 8) {
|
||||||
|
if hasProject {
|
||||||
Image(systemName: "folder.fill")
|
Image(systemName: "folder.fill")
|
||||||
.foregroundStyle(.tint)
|
.foregroundStyle(.tint)
|
||||||
.font(.caption)
|
.font(.caption)
|
||||||
@@ -859,8 +890,11 @@ struct ChatView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
if hasGoal { goalChip }
|
||||||
|
if hasQueue { queueChip }
|
||||||
Spacer()
|
Spacer()
|
||||||
if !controller.vm.projectScopedCommands.isEmpty {
|
if hasProject && !controller.vm.projectScopedCommands.isEmpty {
|
||||||
Button {
|
Button {
|
||||||
showSlashCommandsSheet = true
|
showSlashCommandsSheet = true
|
||||||
} label: {
|
} label: {
|
||||||
@@ -882,6 +916,8 @@ struct ChatView: View {
|
|||||||
.padding(.vertical, 6)
|
.padding(.vertical, 6)
|
||||||
.frame(maxWidth: .infinity, alignment: .leading)
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
.background(.tint.opacity(0.1))
|
.background(.tint.opacity(0.1))
|
||||||
|
.animation(.spring(response: 0.3, dampingFraction: 0.75), value: hasGoal)
|
||||||
|
.animation(.spring(response: 0.3, dampingFraction: 0.75), value: hasQueue)
|
||||||
.sheet(isPresented: $showSlashCommandsSheet) {
|
.sheet(isPresented: $showSlashCommandsSheet) {
|
||||||
ProjectSlashCommandsBrowser(
|
ProjectSlashCommandsBrowser(
|
||||||
projectName: projectName,
|
projectName: projectName,
|
||||||
@@ -891,6 +927,55 @@ struct ChatView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// v0.13 goal pill — purely informational mirror of the agent's
|
||||||
|
/// currently-locked `/goal`. Read-only on iOS; `/goal --clear` lives on
|
||||||
|
/// the Mac app and the pill drops on the next VM update. Semantic
|
||||||
|
/// `.subheadline` font so the goal text scales with Dynamic Type
|
||||||
|
/// (it's content the user reads, not chrome). VoiceOver gets the full
|
||||||
|
/// untruncated text via the accessibility label.
|
||||||
|
@ViewBuilder
|
||||||
|
private var goalChip: some View {
|
||||||
|
if let goal = controller.vm.activeGoal {
|
||||||
|
Label(truncatedGoalText(goal.text), systemImage: "scope")
|
||||||
|
.labelStyle(.titleAndIcon)
|
||||||
|
.font(.subheadline)
|
||||||
|
.foregroundStyle(ScarfColor.info)
|
||||||
|
.padding(.horizontal, 8)
|
||||||
|
.padding(.vertical, 3)
|
||||||
|
.background(ScarfColor.info.opacity(0.16), in: Capsule())
|
||||||
|
.lineLimit(1)
|
||||||
|
.accessibilityLabel("Goal locked: \(goal.text)")
|
||||||
|
.transition(.opacity.combined(with: .scale(scale: 0.92)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// v0.13 queue chip — read-only count of prompts queued via `/queue`.
|
||||||
|
/// Tap is a no-op in v2.8.0 (no popover); the source of truth lives on
|
||||||
|
/// the Mac app. Defaults to one fixed pill regardless of count.
|
||||||
|
@ViewBuilder
|
||||||
|
private var queueChip: some View {
|
||||||
|
let count = controller.vm.queuedPrompts.count
|
||||||
|
if count > 0 {
|
||||||
|
Label("\(count) queued", systemImage: "tray.full")
|
||||||
|
.labelStyle(.titleAndIcon)
|
||||||
|
.font(.caption.weight(.medium))
|
||||||
|
.foregroundStyle(.tint)
|
||||||
|
.padding(.horizontal, 8)
|
||||||
|
.padding(.vertical, 3)
|
||||||
|
.background(.tint.opacity(0.18), in: Capsule())
|
||||||
|
.lineLimit(1)
|
||||||
|
.accessibilityLabel("\(count) prompt\(count == 1 ? "" : "s") queued — manage on the Mac app")
|
||||||
|
.transition(.opacity.combined(with: .scale(scale: 0.92)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Trim long goal text to fit a chip beside the project name on iPhone
|
||||||
|
/// portrait. The full text rides VoiceOver via the chip's accessibility
|
||||||
|
/// label.
|
||||||
|
private func truncatedGoalText(_ text: String) -> String {
|
||||||
|
text.count <= 28 ? text : String(text.prefix(25)) + "…"
|
||||||
|
}
|
||||||
|
|
||||||
/// Shown while we're opening the SSH exec channel + spawning
|
/// Shown while we're opening the SSH exec channel + spawning
|
||||||
/// `hermes acp` + creating the ACP session. Typically ~0.5–1.5 s
|
/// `hermes acp` + creating the ACP session. Typically ~0.5–1.5 s
|
||||||
/// on a warm network — silent before this overlay existed, which
|
/// on a warm network — silent before this overlay existed, which
|
||||||
@@ -1307,18 +1392,48 @@ final class ChatController {
|
|||||||
// even when they didn't type any caption.
|
// even when they didn't type any caption.
|
||||||
vm.addUserMessage(text: "[image attached]")
|
vm.addUserMessage(text: "[image attached]")
|
||||||
}
|
}
|
||||||
// /steer is non-interruptive — the agent is still on its
|
// Non-interruptive slash commands: keep the chat working
|
||||||
// current turn; the guidance applies after the next tool call.
|
// indicator off and surface a transient toast confirming the
|
||||||
// Surface a transient toast confirming the guidance was
|
// command was accepted. v2.5 added `/steer`; v2.8 / Hermes
|
||||||
// received. v2.5 / Hermes v2026.4.23+.
|
// v0.13 adds `/goal` (lock the agent on a target across
|
||||||
if vm.isNonInterruptiveSlash(text) {
|
// turns) and `/queue` (queue a prompt for after the current
|
||||||
|
// turn). Each gets its own optimistic side-effect on the VM
|
||||||
|
// so the (Mac-rendered) chat header pill / queue chip update
|
||||||
|
// synchronously. iOS doesn't surface those affordances yet
|
||||||
|
// (WS-9), but mirroring the dispatch keeps the shared VM
|
||||||
|
// state aligned across platforms — otherwise an iOS user who
|
||||||
|
// ran `/goal` then opened the same session on Mac would see
|
||||||
|
// an empty pill until they typed `/goal` again.
|
||||||
|
let parsedSlash = Self.parseSlashName(text)
|
||||||
|
switch parsedSlash.name {
|
||||||
|
case "goal":
|
||||||
|
// TODO(WS-2-Q7): verify on a real v0.13 host.
|
||||||
|
let arg = RichChatViewModel.parseGoalArgument(parsedSlash.args)
|
||||||
|
switch arg {
|
||||||
|
case .set(let goalText):
|
||||||
|
vm.recordActiveGoal(text: goalText)
|
||||||
|
vm.transientHint = "Goal locked: \(Self.truncatedToastGoal(goalText))"
|
||||||
|
case .clear:
|
||||||
|
vm.recordActiveGoal(text: nil)
|
||||||
|
vm.transientHint = "Goal cleared."
|
||||||
|
case .empty:
|
||||||
|
vm.transientHint = "Sent /goal — see the agent reply for current goal."
|
||||||
|
}
|
||||||
|
scheduleTransientHintClear(snapshot: vm.transientHint)
|
||||||
|
case "queue":
|
||||||
|
// TODO(WS-2-Q5): verify the verbatim wire shape on a
|
||||||
|
// real v0.13 ACP host.
|
||||||
|
let queuedText = parsedSlash.args.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
if !queuedText.isEmpty {
|
||||||
|
vm.recordQueuedPrompt(text: queuedText)
|
||||||
|
}
|
||||||
|
vm.transientHint = "Queued — runs after current turn."
|
||||||
|
scheduleTransientHintClear(snapshot: vm.transientHint)
|
||||||
|
case "steer" where vm.isNonInterruptiveSlash(text):
|
||||||
vm.transientHint = "Guidance queued — applies after the next tool call."
|
vm.transientHint = "Guidance queued — applies after the next tool call."
|
||||||
Task { @MainActor [weak vm] in
|
scheduleTransientHintClear(snapshot: vm.transientHint)
|
||||||
try? await Task.sleep(nanoseconds: 4_000_000_000)
|
default:
|
||||||
if vm?.transientHint == "Guidance queued — applies after the next tool call." {
|
break
|
||||||
vm?.transientHint = nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// Project-scoped slash commands expand client-side: the user
|
// Project-scoped slash commands expand client-side: the user
|
||||||
// bubble shows the literal `/<name> args` they typed (above);
|
// bubble shows the literal `/<name> args` they typed (above);
|
||||||
@@ -1341,6 +1456,43 @@ final class ChatController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Pull `(name, argTail)` out of a `/<name> [args]` invocation.
|
||||||
|
/// Mirror of `ChatViewModel.parseSlashName` on Mac. Returns
|
||||||
|
/// `(nil, "")` for non-slash input.
|
||||||
|
static func parseSlashName(_ text: String) -> (name: String?, args: String) {
|
||||||
|
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard trimmed.hasPrefix("/") else { return (nil, "") }
|
||||||
|
let withoutSlash = trimmed.dropFirst()
|
||||||
|
if let space = withoutSlash.firstIndex(of: " ") {
|
||||||
|
return (
|
||||||
|
name: String(withoutSlash[..<space]),
|
||||||
|
args: String(withoutSlash[withoutSlash.index(after: space)...])
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (name: String(withoutSlash), args: "")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cap goal text in transient toasts so a 1 KB user-typed goal
|
||||||
|
/// doesn't blow out the hint pill. Mirror of
|
||||||
|
/// `ChatViewModel.truncatedToastGoal`.
|
||||||
|
static func truncatedToastGoal(_ text: String) -> String {
|
||||||
|
text.count <= 60 ? text : String(text.prefix(57)) + "…"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Auto-clear the chat composer's transient hint after 4s. Mirror
|
||||||
|
/// of `ChatViewModel.scheduleHintClear` — uses a value snapshot
|
||||||
|
/// rather than identity so a later toast that reuses the same
|
||||||
|
/// string still triggers the clear once the latest value matches.
|
||||||
|
@MainActor
|
||||||
|
private func scheduleTransientHintClear(snapshot: String?) {
|
||||||
|
Task { @MainActor [weak vm] in
|
||||||
|
try? await Task.sleep(nanoseconds: 4_000_000_000)
|
||||||
|
if vm?.transientHint == snapshot {
|
||||||
|
vm?.transientHint = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Mirror of `ChatViewModel.expandIfProjectScoped(_:)` on Mac.
|
/// Mirror of `ChatViewModel.expandIfProjectScoped(_:)` on Mac.
|
||||||
/// `/<name> args` matching a loaded project-scoped command is
|
/// `/<name> args` matching a loaded project-scoped command is
|
||||||
/// expanded; everything else is sent literally.
|
/// expanded; everything else is sent literally.
|
||||||
|
|||||||
@@ -13,11 +13,21 @@ import ScarfDesign
|
|||||||
/// `HermesCapabilities.hasCurator` is true.
|
/// `HermesCapabilities.hasCurator` is true.
|
||||||
struct CuratorView: View {
|
struct CuratorView: View {
|
||||||
@State private var viewModel: CuratorViewModel
|
@State private var viewModel: CuratorViewModel
|
||||||
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
|
||||||
init(context: ServerContext) {
|
init(context: ServerContext) {
|
||||||
_viewModel = State(initialValue: CuratorViewModel(context: context))
|
_viewModel = State(initialValue: CuratorViewModel(context: context))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// v0.13 capability gate. Drives both the synchronous `runNow`
|
||||||
|
/// blocking-with-spinner behavior AND the read-only Archived
|
||||||
|
/// section. Pre-v0.13 hosts skip the archive load entirely so we
|
||||||
|
/// don't spam `hermes curator list-archived` against a binary that
|
||||||
|
/// would error out.
|
||||||
|
private var archiveAvailable: Bool {
|
||||||
|
capabilitiesStore?.capabilities.hasCuratorArchive ?? false
|
||||||
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
List {
|
List {
|
||||||
Section {
|
Section {
|
||||||
@@ -78,18 +88,88 @@ struct CuratorView: View {
|
|||||||
.textSelection(.enabled)
|
.textSelection(.enabled)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if archiveAvailable {
|
||||||
|
archivedSection
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.navigationTitle("Curator")
|
.navigationTitle("Curator")
|
||||||
.navigationBarTitleDisplayMode(.large)
|
.navigationBarTitleDisplayMode(.large)
|
||||||
.refreshable {
|
.refreshable {
|
||||||
await viewModel.load()
|
await viewModel.load()
|
||||||
|
if archiveAvailable {
|
||||||
|
await viewModel.loadArchive()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.overlay(alignment: .bottom) {
|
.overlay(alignment: .bottom) {
|
||||||
if let toast = viewModel.transientMessage {
|
if let toast = viewModel.transientMessage {
|
||||||
toastView(toast)
|
toastView(toast)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.task { await viewModel.load() }
|
.task {
|
||||||
|
await viewModel.load()
|
||||||
|
if archiveAvailable {
|
||||||
|
await viewModel.loadArchive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// v0.13 read-only Archived list. iOS doesn't expose Restore /
|
||||||
|
/// Prune-this / Prune-all — that's a Mac-only surface in v2.8.0.
|
||||||
|
/// The footer signposts the user to the Mac app when there are
|
||||||
|
/// rows to act on.
|
||||||
|
@ViewBuilder
|
||||||
|
private var archivedSection: some View {
|
||||||
|
Section {
|
||||||
|
if viewModel.archivedSkills.isEmpty {
|
||||||
|
Text("No archived skills — Curator will move stale skills here after the next review cycle.")
|
||||||
|
.font(.callout)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
} else {
|
||||||
|
ForEach(viewModel.archivedSkills) { skill in
|
||||||
|
archivedRow(skill)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} header: {
|
||||||
|
Text("Archived")
|
||||||
|
} footer: {
|
||||||
|
if !viewModel.archivedSkills.isEmpty {
|
||||||
|
Text("Restore or prune archived skills from the Mac app.")
|
||||||
|
.font(.caption)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@ViewBuilder
|
||||||
|
private func archivedRow(_ skill: HermesCuratorArchivedSkill) -> some View {
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
HStack {
|
||||||
|
Text(skill.name)
|
||||||
|
.font(.body)
|
||||||
|
.lineLimit(1)
|
||||||
|
Spacer()
|
||||||
|
if let category = skill.category, !category.isEmpty {
|
||||||
|
ScarfBadge(category, kind: .neutral)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
HStack(spacing: 6) {
|
||||||
|
if let reason = skill.reason, !reason.isEmpty {
|
||||||
|
Text(reason)
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
.lineLimit(2)
|
||||||
|
}
|
||||||
|
Spacer()
|
||||||
|
Text(skill.archivedAtLabel)
|
||||||
|
.font(.caption2)
|
||||||
|
.foregroundStyle(.tertiary)
|
||||||
|
}
|
||||||
|
if let size = skill.sizeBytes, size > 0 {
|
||||||
|
Text(skill.sizeLabel)
|
||||||
|
.font(.caption2)
|
||||||
|
.foregroundStyle(.tertiary)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var statusRow: some View {
|
private var statusRow: some View {
|
||||||
@@ -115,7 +195,7 @@ struct CuratorView: View {
|
|||||||
private var actionFooter: some View {
|
private var actionFooter: some View {
|
||||||
HStack(spacing: 8) {
|
HStack(spacing: 8) {
|
||||||
Button {
|
Button {
|
||||||
Task { await viewModel.runNow() }
|
Task { await viewModel.runNow(synchronous: archiveAvailable, timeout: 600) }
|
||||||
} label: {
|
} label: {
|
||||||
Label("Run now", systemImage: "play.fill")
|
Label("Run now", systemImage: "play.fill")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import SwiftUI
|
||||||
|
import ScarfCore
|
||||||
|
import ScarfDesign
|
||||||
|
|
||||||
|
/// iOS substitute for the Mac inspector's `.help()` tooltip on a Kanban
|
||||||
|
/// diagnostic chip. iOS doesn't have hover, so each diagnostic chip in
|
||||||
|
/// the detail sheet is tappable; tap presents this sheet with the kind,
|
||||||
|
/// severity, server-supplied message, and detection timestamp.
|
||||||
|
///
|
||||||
|
/// Read-only — there are no recovery actions on iOS in v2.8.0. The
|
||||||
|
/// surface is deliberately small (one screen, no scroll padding) so it
|
||||||
|
/// reads as a fast peek rather than a full editor.
|
||||||
|
struct DiagnosticDetailSheet: View {
|
||||||
|
let diagnostic: HermesKanbanDiagnostic
|
||||||
|
|
||||||
|
@Environment(\.dismiss) private var dismiss
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
NavigationStack {
|
||||||
|
List {
|
||||||
|
Section {
|
||||||
|
LabeledContent("Kind") {
|
||||||
|
Text(diagnostic.kind)
|
||||||
|
.font(.body.monospaced())
|
||||||
|
.foregroundStyle(.primary)
|
||||||
|
}
|
||||||
|
LabeledContent("Severity") {
|
||||||
|
ScarfBadge(severityLabel, kind: severityBadgeKind)
|
||||||
|
}
|
||||||
|
if let detectedAt = diagnostic.detectedAt, !detectedAt.isEmpty {
|
||||||
|
LabeledContent("Detected at") {
|
||||||
|
Text(detectedAt)
|
||||||
|
.font(.caption.monospaced())
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} header: {
|
||||||
|
Text("Diagnostic")
|
||||||
|
}
|
||||||
|
|
||||||
|
if let message = diagnostic.message, !message.isEmpty {
|
||||||
|
Section {
|
||||||
|
Text(message)
|
||||||
|
.font(.body)
|
||||||
|
.textSelection(.enabled)
|
||||||
|
} header: {
|
||||||
|
Text("Message")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Section {
|
||||||
|
Label("Recovery actions live on the Mac app — open this task there to verify, reject, or unblock.", systemImage: "info.circle")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.scrollContentBackground(.hidden)
|
||||||
|
.background(ScarfColor.backgroundPrimary)
|
||||||
|
.navigationTitle("Diagnostic")
|
||||||
|
.navigationBarTitleDisplayMode(.inline)
|
||||||
|
.toolbar {
|
||||||
|
ToolbarItem(placement: .topBarTrailing) {
|
||||||
|
Button("Done") { dismiss() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var severityLabel: String {
|
||||||
|
let kind = KanbanDiagnosticKind.from(diagnostic.kind)
|
||||||
|
switch kind.severity {
|
||||||
|
case .danger: return "danger"
|
||||||
|
case .warning: return "warning"
|
||||||
|
case .neutral: return "neutral"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var severityBadgeKind: ScarfBadgeKind {
|
||||||
|
let kind = KanbanDiagnosticKind.from(diagnostic.kind)
|
||||||
|
switch kind.severity {
|
||||||
|
case .danger: return .danger
|
||||||
|
case .warning: return .warning
|
||||||
|
case .neutral: return .neutral
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,12 +15,14 @@ struct ScarfGoKanbanDetailSheet: View {
|
|||||||
let context: ServerContext
|
let context: ServerContext
|
||||||
|
|
||||||
@Environment(\.dismiss) private var dismiss
|
@Environment(\.dismiss) private var dismiss
|
||||||
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
|
||||||
@State private var detail: HermesKanbanTaskDetail?
|
@State private var detail: HermesKanbanTaskDetail?
|
||||||
@State private var runs: [HermesKanbanRun] = []
|
@State private var runs: [HermesKanbanRun] = []
|
||||||
@State private var isLoading = true
|
@State private var isLoading = true
|
||||||
@State private var error: String?
|
@State private var error: String?
|
||||||
@State private var selectedTab: DetailTab = .comments
|
@State private var selectedTab: DetailTab = .comments
|
||||||
|
@State private var selectedDiagnostic: HermesKanbanDiagnostic?
|
||||||
|
|
||||||
enum DetailTab: String, CaseIterable, Identifiable {
|
enum DetailTab: String, CaseIterable, Identifiable {
|
||||||
case comments = "Comments"
|
case comments = "Comments"
|
||||||
@@ -29,6 +31,13 @@ struct ScarfGoKanbanDetailSheet: View {
|
|||||||
var id: String { rawValue }
|
var id: String { rawValue }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// v0.13 capability gate. Defensive default `false` when no
|
||||||
|
/// capabilities store is present (preview / smoke harness) so the
|
||||||
|
/// sheet renders the v2.7.5 layout unchanged.
|
||||||
|
private var diagnosticsAvailable: Bool {
|
||||||
|
capabilitiesStore?.capabilities.hasKanbanDiagnostics ?? false
|
||||||
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
NavigationStack {
|
NavigationStack {
|
||||||
content
|
content
|
||||||
@@ -41,6 +50,9 @@ struct ScarfGoKanbanDetailSheet: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
.task(id: taskId) { await load() }
|
.task(id: taskId) { await load() }
|
||||||
|
.sheet(item: $selectedDiagnostic) { diag in
|
||||||
|
DiagnosticDetailSheet(diagnostic: diag)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ViewBuilder
|
@ViewBuilder
|
||||||
@@ -62,6 +74,8 @@ struct ScarfGoKanbanDetailSheet: View {
|
|||||||
ScrollView {
|
ScrollView {
|
||||||
VStack(alignment: .leading, spacing: 16) {
|
VStack(alignment: .leading, spacing: 16) {
|
||||||
headerCard(detail.task)
|
headerCard(detail.task)
|
||||||
|
hallucinationBadge(detail.task)
|
||||||
|
autoBlockedBanner(detail.task)
|
||||||
if let body = detail.task.body, !body.isEmpty {
|
if let body = detail.task.body, !body.isEmpty {
|
||||||
if let attributed = try? AttributedString(markdown: body) {
|
if let attributed = try? AttributedString(markdown: body) {
|
||||||
Text(attributed)
|
Text(attributed)
|
||||||
@@ -71,6 +85,9 @@ struct ScarfGoKanbanDetailSheet: View {
|
|||||||
.font(.body)
|
.font(.body)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if diagnosticsAvailable, !detail.task.diagnostics.isEmpty {
|
||||||
|
diagnosticsBlock(detail.task.diagnostics, label: "Diagnostics")
|
||||||
|
}
|
||||||
Picker("Section", selection: $selectedTab) {
|
Picker("Section", selection: $selectedTab) {
|
||||||
ForEach(DetailTab.allCases) { tab in
|
ForEach(DetailTab.allCases) { tab in
|
||||||
Text(tab.rawValue).tag(tab)
|
Text(tab.rawValue).tag(tab)
|
||||||
@@ -90,7 +107,9 @@ struct ScarfGoKanbanDetailSheet: View {
|
|||||||
|
|
||||||
private func headerCard(_ task: HermesKanbanTask) -> some View {
|
private func headerCard(_ task: HermesKanbanTask) -> some View {
|
||||||
VStack(alignment: .leading, spacing: 8) {
|
VStack(alignment: .leading, spacing: 8) {
|
||||||
HStack(spacing: 6) {
|
// Wrap chips in FlowLayout so the new v0.13 `retries` chip
|
||||||
|
// doesn't push the row over the iPhone-portrait width budget.
|
||||||
|
FlowLayout(spacing: 6) {
|
||||||
ScarfBadge(task.status.lowercased(), kind: badgeKind(for: task.status))
|
ScarfBadge(task.status.lowercased(), kind: badgeKind(for: task.status))
|
||||||
if let assignee = task.assignee, !assignee.isEmpty {
|
if let assignee = task.assignee, !assignee.isEmpty {
|
||||||
ScarfBadge(assignee, kind: .neutral)
|
ScarfBadge(assignee, kind: .neutral)
|
||||||
@@ -101,6 +120,10 @@ struct ScarfGoKanbanDetailSheet: View {
|
|||||||
if let tenant = task.tenant, !tenant.isEmpty {
|
if let tenant = task.tenant, !tenant.isEmpty {
|
||||||
ScarfBadge(tenant, kind: .brand)
|
ScarfBadge(tenant, kind: .brand)
|
||||||
}
|
}
|
||||||
|
if diagnosticsAvailable, let maxRetries = task.maxRetries {
|
||||||
|
ScarfBadge("retries: \(maxRetries)", kind: .neutral)
|
||||||
|
.accessibilityLabel("Max retries \(maxRetries)")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if let priority = task.priority {
|
if let priority = task.priority {
|
||||||
Text("Priority \(priority)")
|
Text("Priority \(priority)")
|
||||||
@@ -110,6 +133,100 @@ struct ScarfGoKanbanDetailSheet: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// v0.13 hallucination gate. Worker-created cards land in the
|
||||||
|
/// `pending` state until a human verifies — Mac surfaces a Verify /
|
||||||
|
/// Reject button pair; iOS in v2.8.0 stays read-only and points
|
||||||
|
/// the user to the Mac app via the badge copy.
|
||||||
|
@ViewBuilder
|
||||||
|
private func hallucinationBadge(_ task: HermesKanbanTask) -> some View {
|
||||||
|
if diagnosticsAvailable,
|
||||||
|
KanbanHallucinationGate.from(task.hallucinationGateStatus) == .pending {
|
||||||
|
HStack(spacing: 6) {
|
||||||
|
Image(systemName: "questionmark.diamond.fill")
|
||||||
|
.foregroundStyle(ScarfColor.warning)
|
||||||
|
Text("Worker-created — verify on Mac")
|
||||||
|
.font(.subheadline)
|
||||||
|
.foregroundStyle(ScarfColor.warning)
|
||||||
|
}
|
||||||
|
.padding(.horizontal, 10)
|
||||||
|
.padding(.vertical, 6)
|
||||||
|
.background(
|
||||||
|
ScarfColor.warning.opacity(0.10),
|
||||||
|
in: RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
|
||||||
|
)
|
||||||
|
.overlay(
|
||||||
|
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
|
||||||
|
.strokeBorder(ScarfColor.warning.opacity(0.4), lineWidth: 1)
|
||||||
|
)
|
||||||
|
.accessibilityHint("Open this task on the Mac app to verify or reject the worker's claim.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// v0.13 auto-blocked banner. Surfaces `auto_blocked_reason` verbatim
|
||||||
|
/// when Hermes auto-blocks a task (retry cap hit, repeated tool
|
||||||
|
/// errors, etc.). Server-supplied copy — render verbatim.
|
||||||
|
@ViewBuilder
|
||||||
|
private func autoBlockedBanner(_ task: HermesKanbanTask) -> some View {
|
||||||
|
if diagnosticsAvailable,
|
||||||
|
KanbanStatus.from(task.status) == .blocked,
|
||||||
|
let reason = task.autoBlockedReason, !reason.isEmpty {
|
||||||
|
HStack(alignment: .top, spacing: 8) {
|
||||||
|
Image(systemName: "exclamationmark.octagon.fill")
|
||||||
|
.foregroundStyle(ScarfColor.danger)
|
||||||
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
|
Text("Auto-blocked")
|
||||||
|
.font(.subheadline.weight(.semibold))
|
||||||
|
.foregroundStyle(ScarfColor.danger)
|
||||||
|
Text(reason)
|
||||||
|
.font(.subheadline)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(10)
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
.background(
|
||||||
|
ScarfColor.danger.opacity(0.08),
|
||||||
|
in: RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tap-target diagnostic chip list. iOS substitute for the Mac
|
||||||
|
/// inspector's `.help()` tooltip — chips are tappable, tap presents
|
||||||
|
/// `DiagnosticDetailSheet` with the full message + timestamp.
|
||||||
|
@ViewBuilder
|
||||||
|
private func diagnosticsBlock(_ diags: [HermesKanbanDiagnostic], label: String) -> some View {
|
||||||
|
VStack(alignment: .leading, spacing: 6) {
|
||||||
|
Text(label)
|
||||||
|
.font(.caption.weight(.semibold))
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
FlowLayout(spacing: 6) {
|
||||||
|
ForEach(diags) { diag in
|
||||||
|
Button {
|
||||||
|
selectedDiagnostic = diag
|
||||||
|
} label: {
|
||||||
|
ScarfBadge(diag.kind, kind: diagnosticBadgeKind(diag))
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.accessibilityLabel(diag.message ?? diag.kind)
|
||||||
|
.accessibilityHint("Tap to see the full diagnostic message and timestamp.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Maps the typed `KanbanDiagnosticKind.severity` enum into the
|
||||||
|
/// `ScarfBadgeKind` palette. Mirrors the Mac inspector's
|
||||||
|
/// `diagnosticBadge` helper so the two surfaces tint identically.
|
||||||
|
private func diagnosticBadgeKind(_ diag: HermesKanbanDiagnostic) -> ScarfBadgeKind {
|
||||||
|
switch KanbanDiagnosticKind.from(diag.kind).severity {
|
||||||
|
case .danger: return .danger
|
||||||
|
case .warning: return .warning
|
||||||
|
case .neutral: return .neutral
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private func commentsSection(_ comments: [HermesKanbanComment]) -> some View {
|
private func commentsSection(_ comments: [HermesKanbanComment]) -> some View {
|
||||||
VStack(alignment: .leading, spacing: 8) {
|
VStack(alignment: .leading, spacing: 8) {
|
||||||
if comments.isEmpty {
|
if comments.isEmpty {
|
||||||
@@ -194,6 +311,10 @@ struct ScarfGoKanbanDetailSheet: View {
|
|||||||
.font(.caption)
|
.font(.caption)
|
||||||
.foregroundStyle(.red)
|
.foregroundStyle(.red)
|
||||||
}
|
}
|
||||||
|
if diagnosticsAvailable, !run.diagnostics.isEmpty {
|
||||||
|
diagnosticsBlock(run.diagnostics, label: "Run diagnostics")
|
||||||
|
.padding(.top, 4)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.padding(8)
|
.padding(8)
|
||||||
.background(ScarfColor.backgroundSecondary.opacity(0.4))
|
.background(ScarfColor.backgroundSecondary.opacity(0.4))
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ struct SettingsView: View {
|
|||||||
@State private var vm: IOSSettingsViewModel
|
@State private var vm: IOSSettingsViewModel
|
||||||
@State private var showRawYAML = false
|
@State private var showRawYAML = false
|
||||||
@State private var editingSpec: SettingSpec?
|
@State private var editingSpec: SettingSpec?
|
||||||
|
@State private var showV013FeaturesSheet = false
|
||||||
/// v2.7 — Scarf-local opt-in to bulk-fetch tool result CONTENT
|
/// v2.7 — Scarf-local opt-in to bulk-fetch tool result CONTENT
|
||||||
/// when resuming past chats. Default off; the shared
|
/// when resuming past chats. Default off; the shared
|
||||||
/// `RichChatViewModel` reads this same UserDefaults key on
|
/// `RichChatViewModel` reads this same UserDefaults key on
|
||||||
@@ -21,6 +22,16 @@ struct SettingsView: View {
|
|||||||
@AppStorage(RichChatViewModel.loadHistoricalToolResultsKey)
|
@AppStorage(RichChatViewModel.loadHistoricalToolResultsKey)
|
||||||
private var loadHistoricalToolResults: Bool = false
|
private var loadHistoricalToolResults: Bool = false
|
||||||
|
|
||||||
|
/// Drives v0.13 read-only surfaces (features-active badge,
|
||||||
|
/// platforms-section additions). Defensive `?? .empty` resolves
|
||||||
|
/// every gate to `false` outside `ContextBoundRoot` (preview /
|
||||||
|
/// smoke harness) so the v2.7.5 layout is the unconditional
|
||||||
|
/// fallback.
|
||||||
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
private var caps: HermesCapabilities {
|
||||||
|
capabilitiesStore?.capabilities ?? .empty
|
||||||
|
}
|
||||||
|
|
||||||
private static let sharedContextID: ServerID = ServerID(
|
private static let sharedContextID: ServerID = ServerID(
|
||||||
uuidString: "00000000-0000-0000-0000-0000000000A1"
|
uuidString: "00000000-0000-0000-0000-0000000000A1"
|
||||||
)!
|
)!
|
||||||
@@ -40,6 +51,10 @@ struct SettingsView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if caps.isV013OrLater {
|
||||||
|
v013ActiveBadgeSection
|
||||||
|
}
|
||||||
|
|
||||||
if !vm.isLoading || vm.config.model != "unknown" {
|
if !vm.isLoading || vm.config.model != "unknown" {
|
||||||
quickEditsSection
|
quickEditsSection
|
||||||
modelSection
|
modelSection
|
||||||
@@ -79,6 +94,35 @@ struct SettingsView: View {
|
|||||||
onDismiss: {}
|
onDismiss: {}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
.sheet(isPresented: $showV013FeaturesSheet) {
|
||||||
|
V013FeaturesSheet()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// v0.13 features-active badge. Only shown when the connected host
|
||||||
|
/// is on the v0.13 line; tap presents `V013FeaturesSheet`. Read-only
|
||||||
|
/// — there's no settings change behind the badge, just a
|
||||||
|
/// what's-new affordance.
|
||||||
|
@ViewBuilder
|
||||||
|
private var v013ActiveBadgeSection: some View {
|
||||||
|
Section {
|
||||||
|
Button {
|
||||||
|
showV013FeaturesSheet = true
|
||||||
|
} label: {
|
||||||
|
HStack(spacing: 8) {
|
||||||
|
ScarfBadge("v0.13 features active", kind: .success)
|
||||||
|
Spacer()
|
||||||
|
Text("Learn more")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.tint)
|
||||||
|
Image(systemName: "chevron.right")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.tertiary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
}
|
||||||
|
.listRowBackground(ScarfColor.success.opacity(0.06))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ViewBuilder
|
@ViewBuilder
|
||||||
@@ -284,7 +328,117 @@ struct SettingsView: View {
|
|||||||
yesNoRow("Telegram: require mention", vm.config.telegram.requireMention)
|
yesNoRow("Telegram: require mention", vm.config.telegram.requireMention)
|
||||||
LabeledContent("Slack: reply mode", value: vm.config.slack.replyToMode)
|
LabeledContent("Slack: reply mode", value: vm.config.slack.replyToMode)
|
||||||
yesNoRow("Matrix: require mention", vm.config.matrix.requireMention)
|
yesNoRow("Matrix: require mention", vm.config.matrix.requireMention)
|
||||||
|
|
||||||
|
// v0.13 additions: each is independently capability-gated
|
||||||
|
// and read-only on iOS in v2.8.0. Editing lives on Mac.
|
||||||
|
if caps.hasGoogleChatPlatform {
|
||||||
|
LabeledContent("Google Chat", value: googleChatStatusLabel)
|
||||||
}
|
}
|
||||||
|
if caps.hasGatewayBusyAckToggle {
|
||||||
|
gatewayBusyAckRow
|
||||||
|
}
|
||||||
|
if caps.hasGatewayRestartNotification {
|
||||||
|
gatewayRestartNotificationRow
|
||||||
|
}
|
||||||
|
if caps.hasGatewayAllowlists {
|
||||||
|
gatewayAllowlistsRows
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// v0.13 Google Chat status. Whether the platform shows up at all
|
||||||
|
/// is driven by whether `gateway.platforms.google-chat.*` exists in
|
||||||
|
/// config.yaml on the remote — if absent, we render "Not configured".
|
||||||
|
/// Hermes accepts either `google-chat` or `googlechat` as the
|
||||||
|
/// identifier; check both spellings defensively.
|
||||||
|
private var googleChatStatusLabel: String {
|
||||||
|
if vm.config.gatewayPlatforms["google-chat"] != nil
|
||||||
|
|| vm.config.gatewayPlatforms["googlechat"] != nil {
|
||||||
|
return "configured"
|
||||||
|
}
|
||||||
|
return "not configured"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// v0.13 cross-platform busy-ack toggle. We summarize per platform
|
||||||
|
/// so users on iOS get a faithful read of the per-platform flag —
|
||||||
|
/// "off on slack, on elsewhere" is a real configuration shape.
|
||||||
|
/// Empty `gatewayPlatforms` shows "default".
|
||||||
|
@ViewBuilder
|
||||||
|
private var gatewayBusyAckRow: some View {
|
||||||
|
let value = summariseGatewayBool(\GatewayPlatformSettings.busyAckEnabled, defaultLabel: "on")
|
||||||
|
LabeledContent("Gateway: busy ack", value: value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@ViewBuilder
|
||||||
|
private var gatewayRestartNotificationRow: some View {
|
||||||
|
let value = summariseGatewayBool(\GatewayPlatformSettings.gatewayRestartNotification, defaultLabel: "off")
|
||||||
|
LabeledContent("Gateway: restart notification", value: value)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Render a per-key summary across `gatewayPlatforms`. When all
|
||||||
|
/// configured platforms agree on the same value we show a single
|
||||||
|
/// "yes" / "no". When they disagree we show "mixed (N platforms)"
|
||||||
|
/// to nudge the user to the Mac app for the per-platform detail.
|
||||||
|
private func summariseGatewayBool(
|
||||||
|
_ keyPath: KeyPath<GatewayPlatformSettings, Bool>,
|
||||||
|
defaultLabel: String
|
||||||
|
) -> String {
|
||||||
|
let values = vm.config.gatewayPlatforms.values.map { $0[keyPath: keyPath] }
|
||||||
|
guard !values.isEmpty else { return defaultLabel + " (default)" }
|
||||||
|
let allTrue = values.allSatisfy { $0 }
|
||||||
|
let allFalse = values.allSatisfy { !$0 }
|
||||||
|
if allTrue { return "yes" }
|
||||||
|
if allFalse { return "no" }
|
||||||
|
return "mixed (\(values.count) platforms)"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// v0.13 cross-platform allowlist summaries. Each kind
|
||||||
|
/// (channels / chats / rooms) renders as a DisclosureGroup with the
|
||||||
|
/// total count in the label and a flat list of "platform: id" rows
|
||||||
|
/// when expanded. iPhone-friendly: collapsed by default so the
|
||||||
|
/// section stays compact.
|
||||||
|
@ViewBuilder
|
||||||
|
private var gatewayAllowlistsRows: some View {
|
||||||
|
gatewayAllowlistDisclosure(kind: .channels)
|
||||||
|
gatewayAllowlistDisclosure(kind: .chats)
|
||||||
|
gatewayAllowlistDisclosure(kind: .rooms)
|
||||||
|
}
|
||||||
|
|
||||||
|
@ViewBuilder
|
||||||
|
private func gatewayAllowlistDisclosure(kind: GatewayAllowlistKind) -> some View {
|
||||||
|
let entries = gatewayAllowlistEntries(kind: kind)
|
||||||
|
if !entries.isEmpty {
|
||||||
|
DisclosureGroup {
|
||||||
|
ForEach(entries, id: \.self) { entry in
|
||||||
|
Text(entry)
|
||||||
|
.font(.caption.monospaced())
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
.lineLimit(1)
|
||||||
|
.truncationMode(.middle)
|
||||||
|
}
|
||||||
|
} label: {
|
||||||
|
LabeledContent("Allowed \(kind.pluralNoun)") {
|
||||||
|
Text("\(entries.count)")
|
||||||
|
.font(.callout)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Flatten the per-platform allowlists for `kind` across every
|
||||||
|
/// configured platform. Each entry is rendered as
|
||||||
|
/// `"platformName: id"` so the user sees which platform the id
|
||||||
|
/// belongs to without an extra DisclosureGroup level.
|
||||||
|
private func gatewayAllowlistEntries(kind: GatewayAllowlistKind) -> [String] {
|
||||||
|
var out: [String] = []
|
||||||
|
for (platform, settings) in vm.config.gatewayPlatforms.sorted(by: { $0.key < $1.key }) {
|
||||||
|
guard GatewayAllowlistKind.kind(for: platform) == kind else { continue }
|
||||||
|
for item in settings.items(for: kind) where !item.isEmpty {
|
||||||
|
out.append("\(platform): \(item)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Diagnostics → Performance entry point. Hidden from the
|
/// Diagnostics → Performance entry point. Hidden from the
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import SwiftUI
|
||||||
|
import ScarfDesign
|
||||||
|
|
||||||
|
/// "Learn more" sheet behind the v0.13 features-active badge in
|
||||||
|
/// `SettingsView`. Text-only summary of what shipped in Hermes v0.13
|
||||||
|
/// (Persistent Goals, ACP /queue, Kanban diagnostics, hallucination
|
||||||
|
/// gate, Curator archive, Google Chat platform). Every row spells out
|
||||||
|
/// where the editing lives — Mac for v2.8.0; iOS write surfaces are
|
||||||
|
/// deferred to v2.8.x.
|
||||||
|
///
|
||||||
|
/// No deep-linking from rows in v2.8.0 — that's a v2.8.x polish.
|
||||||
|
struct V013FeaturesSheet: View {
|
||||||
|
@Environment(\.dismiss) private var dismiss
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
NavigationStack {
|
||||||
|
List {
|
||||||
|
Section {
|
||||||
|
featureRow(
|
||||||
|
icon: "scope",
|
||||||
|
title: "Persistent goals",
|
||||||
|
description: "Type /goal <text> in chat to lock the agent on a target across turns. Send and clear from the Mac app in v2.8."
|
||||||
|
)
|
||||||
|
featureRow(
|
||||||
|
icon: "tray.full",
|
||||||
|
title: "ACP /queue",
|
||||||
|
description: "Queue prompts to run after the current turn finishes. Send and manage from the Mac app in v2.8."
|
||||||
|
)
|
||||||
|
featureRow(
|
||||||
|
icon: "stethoscope",
|
||||||
|
title: "Kanban diagnostics",
|
||||||
|
description: "Worker distress signals (heartbeat stalls, retry caps, zombies) surface on the task detail."
|
||||||
|
)
|
||||||
|
featureRow(
|
||||||
|
icon: "questionmark.diamond.fill",
|
||||||
|
title: "Hallucination gate",
|
||||||
|
description: "Worker-created cards are flagged for verify or reject. Verify on the Mac app."
|
||||||
|
)
|
||||||
|
featureRow(
|
||||||
|
icon: "archivebox",
|
||||||
|
title: "Curator archive",
|
||||||
|
description: "Stale skills move to an Archived list. Restore or prune from the Mac app."
|
||||||
|
)
|
||||||
|
featureRow(
|
||||||
|
icon: "bubble.left.and.bubble.right",
|
||||||
|
title: "Google Chat platform",
|
||||||
|
description: "New messaging-gateway target. Configure on the Mac app."
|
||||||
|
)
|
||||||
|
} header: {
|
||||||
|
Text("What's new in v0.13")
|
||||||
|
} footer: {
|
||||||
|
Text("This iOS release surfaces v0.13 features read-only. Editing lives in the Mac app for v2.8.")
|
||||||
|
.font(.caption)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.scrollContentBackground(.hidden)
|
||||||
|
.background(ScarfColor.backgroundPrimary)
|
||||||
|
.navigationTitle("v0.13 features")
|
||||||
|
.navigationBarTitleDisplayMode(.inline)
|
||||||
|
.toolbar {
|
||||||
|
ToolbarItem(placement: .topBarTrailing) {
|
||||||
|
Button("Done") { dismiss() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func featureRow(icon: String, title: String, description: String) -> some View {
|
||||||
|
HStack(alignment: .top, spacing: 12) {
|
||||||
|
Image(systemName: icon)
|
||||||
|
.foregroundStyle(.tint)
|
||||||
|
.font(.title3)
|
||||||
|
.frame(width: 28)
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
Text(title).font(.body.weight(.semibold))
|
||||||
|
Text(description)
|
||||||
|
.font(.callout)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.vertical, 4)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -84,7 +84,11 @@ struct HermesFileService: Sendable {
|
|||||||
inlineDiffs: bool("display.inline_diffs", default: true),
|
inlineDiffs: bool("display.inline_diffs", default: true),
|
||||||
toolProgressCommand: bool("display.tool_progress_command", default: false),
|
toolProgressCommand: bool("display.tool_progress_command", default: false),
|
||||||
toolPreviewLength: int("display.tool_preview_length", default: 0),
|
toolPreviewLength: int("display.tool_preview_length", default: 0),
|
||||||
busyInputMode: str("display.busy_input_mode", default: "interrupt")
|
busyInputMode: str("display.busy_input_mode", default: "interrupt"),
|
||||||
|
// v0.13: empty default means "key absent — agent uses its own
|
||||||
|
// default" (English). The picker writes a real value when the
|
||||||
|
// user explicitly chooses one.
|
||||||
|
language: str("display.language", default: "")
|
||||||
)
|
)
|
||||||
|
|
||||||
let terminal = TerminalSettings(
|
let terminal = TerminalSettings(
|
||||||
@@ -131,7 +135,12 @@ struct HermesFileService: Sendable {
|
|||||||
sttLocalModel: str("stt.local.model", default: "base"),
|
sttLocalModel: str("stt.local.model", default: "base"),
|
||||||
sttLocalLanguage: str("stt.local.language"),
|
sttLocalLanguage: str("stt.local.language"),
|
||||||
sttOpenAIModel: str("stt.openai.model", default: "whisper-1"),
|
sttOpenAIModel: str("stt.openai.model", default: "whisper-1"),
|
||||||
sttMistralModel: str("stt.mistral.model", default: "voxtral-mini-latest")
|
sttMistralModel: str("stt.mistral.model", default: "voxtral-mini-latest"),
|
||||||
|
// TODO(WS-8-Q2): Verify key names. Mirroring the elevenlabs
|
||||||
|
// shape (`<provider>.voice_id` + `<provider>.model`); v0.13
|
||||||
|
// source might use `tts.xai.voice` or `tts.xai.model_id`.
|
||||||
|
ttsXAIVoiceID: str("tts.xai.voice_id"),
|
||||||
|
ttsXAIModel: str("tts.xai.model")
|
||||||
)
|
)
|
||||||
|
|
||||||
func aux(_ name: String) -> AuxiliaryModel {
|
func aux(_ name: String) -> AuxiliaryModel {
|
||||||
@@ -254,6 +263,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 +363,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
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -599,7 +650,8 @@ struct HermesFileService: Sendable {
|
|||||||
toolsExclude: server.toolsExclude,
|
toolsExclude: server.toolsExclude,
|
||||||
resourcesEnabled: server.resourcesEnabled,
|
resourcesEnabled: server.resourcesEnabled,
|
||||||
promptsEnabled: server.promptsEnabled,
|
promptsEnabled: server.promptsEnabled,
|
||||||
hasOAuthToken: hasToken
|
hasOAuthToken: hasToken,
|
||||||
|
sseReadTimeout: server.sseReadTimeout
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -630,6 +682,37 @@ struct HermesFileService: Sendable {
|
|||||||
return runHermesCLI(args: cliArgs, timeout: 45, stdinInput: "y\ny\ny\n")
|
return runHermesCLI(args: cliArgs, timeout: 45, stdinInput: "y\ny\ny\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Adds an SSE-transport MCP server. v0.13+ only — caller is responsible
|
||||||
|
/// for capability-gating; pre-v0.13 hosts will reject the `--transport`
|
||||||
|
/// flag at argparse time. The optional `sseReadTimeout` is passed via
|
||||||
|
/// `--sse-read-timeout <int>` and persisted as `sse_read_timeout: <int>`
|
||||||
|
/// in the YAML entry.
|
||||||
|
// TODO(WS-7-Q3): Verify exact CLI flag spelling against `hermes mcp add --help`
|
||||||
|
// on a v0.13 install. Plan assumes `--transport sse` + `--sse-read-timeout`;
|
||||||
|
// alternatives could be `--sse` (boolean) + `--read-timeout`.
|
||||||
|
@discardableResult
|
||||||
|
nonisolated func addMCPServerSSE(name: String, url: String, sseReadTimeout: Int?) -> (exitCode: Int32, output: String) {
|
||||||
|
var cliArgs: [String] = ["mcp", "add", name, "--url", url, "--transport", "sse"]
|
||||||
|
if let timeout = sseReadTimeout {
|
||||||
|
cliArgs.append(contentsOf: ["--sse-read-timeout", String(timeout)])
|
||||||
|
}
|
||||||
|
return runHermesCLI(args: cliArgs, timeout: 45, stdinInput: "y\ny\ny\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Updates the `sse_read_timeout` scalar in-place via the same surgical
|
||||||
|
/// patcher used by `setMCPServerTimeouts`. Pass `nil` to remove the
|
||||||
|
/// scalar entirely (Hermes default applies).
|
||||||
|
@discardableResult
|
||||||
|
nonisolated func setMCPServerSSETimeout(name: String, sseReadTimeout: Int?) -> Bool {
|
||||||
|
patchMCPServerField(name: name) { entryLines in
|
||||||
|
if let timeout = sseReadTimeout {
|
||||||
|
Self.replaceOrInsertScalar(key: "sse_read_timeout", value: String(timeout), in: &entryLines)
|
||||||
|
} else {
|
||||||
|
Self.removeScalar(key: "sse_read_timeout", in: &entryLines)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@discardableResult
|
@discardableResult
|
||||||
nonisolated func setMCPServerArgs(name: String, args: [String]) -> Bool {
|
nonisolated func setMCPServerArgs(name: String, args: [String]) -> Bool {
|
||||||
patchMCPServerField(name: name) { entryLines in
|
patchMCPServerField(name: name) { entryLines in
|
||||||
@@ -812,11 +895,23 @@ struct HermesFileService: Sendable {
|
|||||||
|
|
||||||
func flush() {
|
func flush() {
|
||||||
guard let name = currentName else { return }
|
guard let name = currentName else { return }
|
||||||
let transport: MCPTransport = fields["url"] != nil ? .http : .stdio
|
// 3-way transport discriminator: an explicit `transport: sse` scalar
|
||||||
|
// wins (Hermes v0.13+ emits it for SSE servers); otherwise URL-bearing
|
||||||
|
// entries fall back to .http (v0.12 shape) and command-bearing entries
|
||||||
|
// to .stdio. This preserves byte-for-byte round-trip on existing files
|
||||||
|
// — pre-v0.13 entries have no `transport:` key so they parse identically.
|
||||||
|
// TODO(WS-7-Q1): Verify Hermes v0.13 actually emits `transport: sse`
|
||||||
|
// (vs. inferring from the schema/url shape) once a v0.13 host is on hand.
|
||||||
|
let transport: MCPTransport = {
|
||||||
|
if fields["transport"]?.lowercased() == "sse" { return .sse }
|
||||||
|
if fields["url"] != nil { return .http }
|
||||||
|
return .stdio
|
||||||
|
}()
|
||||||
let enabledStr = fields["enabled"]?.lowercased()
|
let enabledStr = fields["enabled"]?.lowercased()
|
||||||
let enabled = enabledStr != "false"
|
let enabled = enabledStr != "false"
|
||||||
let timeout = fields["timeout"].flatMap(Int.init)
|
let timeout = fields["timeout"].flatMap(Int.init)
|
||||||
let connectTimeout = fields["connect_timeout"].flatMap(Int.init)
|
let connectTimeout = fields["connect_timeout"].flatMap(Int.init)
|
||||||
|
let sseReadTimeout = fields["sse_read_timeout"].flatMap(Int.init)
|
||||||
let server = HermesMCPServer(
|
let server = HermesMCPServer(
|
||||||
name: name,
|
name: name,
|
||||||
transport: transport,
|
transport: transport,
|
||||||
@@ -833,7 +928,8 @@ struct HermesFileService: Sendable {
|
|||||||
toolsExclude: excludeList,
|
toolsExclude: excludeList,
|
||||||
resourcesEnabled: resources,
|
resourcesEnabled: resources,
|
||||||
promptsEnabled: prompts,
|
promptsEnabled: prompts,
|
||||||
hasOAuthToken: false
|
hasOAuthToken: false,
|
||||||
|
sseReadTimeout: sseReadTimeout
|
||||||
)
|
)
|
||||||
servers.append(server)
|
servers.append(server)
|
||||||
|
|
||||||
|
|||||||
@@ -77,6 +77,27 @@ final class ChatViewModel {
|
|||||||
let richChatViewModel: RichChatViewModel
|
let richChatViewModel: RichChatViewModel
|
||||||
private var coordinator: Coordinator?
|
private var coordinator: Coordinator?
|
||||||
|
|
||||||
|
/// Capability store the chat surface reads from. Set by `ChatView`
|
||||||
|
/// at body-evaluation time via `attachCapabilitiesStore(_:)` —
|
||||||
|
/// `@ObservationIgnored` so capability refreshes don't force a
|
||||||
|
/// full chat re-render. Forwards into
|
||||||
|
/// `RichChatViewModel.capabilitiesGate` whenever the published
|
||||||
|
/// snapshot changes; the slash menu reads through that. v2.8 /
|
||||||
|
/// Hermes v0.13 — gates `/goal` + `/queue` slash menu rows.
|
||||||
|
@ObservationIgnored
|
||||||
|
var capabilitiesStore: HermesCapabilitiesStore?
|
||||||
|
|
||||||
|
/// Wire the Mac chat view's environment-injected capabilities store
|
||||||
|
/// into both this VM and its child rich-chat VM. Idempotent on the
|
||||||
|
/// pointer (re-attaching the same store is a no-op); always
|
||||||
|
/// re-publishes the latest snapshot so a refresh that fired before
|
||||||
|
/// the chat view became visible still lands.
|
||||||
|
@MainActor
|
||||||
|
func attachCapabilitiesStore(_ store: HermesCapabilitiesStore?) {
|
||||||
|
capabilitiesStore = store
|
||||||
|
richChatViewModel.publishCapabilities(store?.capabilities ?? .empty)
|
||||||
|
}
|
||||||
|
|
||||||
/// `callId` of the tool call currently surfaced in the chat
|
/// `callId` of the tool call currently surfaced in the chat
|
||||||
/// inspector pane, or nil when nothing is focused. Set by
|
/// inspector pane, or nil when nothing is focused. Set by
|
||||||
/// `ToolCallCard` taps in the transcript; cleared by the inspector's
|
/// `ToolCallCard` taps in the transcript; cleared by the inspector's
|
||||||
@@ -321,6 +342,47 @@ final class ChatViewModel {
|
|||||||
richChatViewModel.clearACPErrorState()
|
richChatViewModel.clearACPErrorState()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Auto-clear the chat composer's transient hint after 4 s. Shared
|
||||||
|
/// helper for `/steer`, `/goal`, and `/queue` so the toast lifetime
|
||||||
|
/// stays consistent across non-interruptive commands.
|
||||||
|
@MainActor
|
||||||
|
private func scheduleHintClear() {
|
||||||
|
let snapshot = richChatViewModel.transientHint
|
||||||
|
Task { @MainActor [weak self] in
|
||||||
|
try? await Task.sleep(nanoseconds: 4_000_000_000)
|
||||||
|
if self?.richChatViewModel.transientHint == snapshot {
|
||||||
|
self?.richChatViewModel.transientHint = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pull the slash command name + raw argument tail out of the
|
||||||
|
/// composer text. Returns `(name: nil, args: "")` for non-slash
|
||||||
|
/// input. Mirrors the parser shape `RichChatViewModel.parseGoalArgument`
|
||||||
|
/// expects; kept on `ChatViewModel` (not promoted to ScarfCore)
|
||||||
|
/// because the Mac and iOS chat surfaces compose this with their
|
||||||
|
/// own per-platform send paths.
|
||||||
|
static func parseSlashName(_ text: String) -> (name: String?, args: String) {
|
||||||
|
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard trimmed.hasPrefix("/") else { return (nil, "") }
|
||||||
|
let withoutSlash = trimmed.dropFirst()
|
||||||
|
if let space = withoutSlash.firstIndex(of: " ") {
|
||||||
|
return (
|
||||||
|
name: String(withoutSlash[..<space]),
|
||||||
|
args: String(withoutSlash[withoutSlash.index(after: space)...])
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (name: String(withoutSlash), args: "")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cap goal text in transient toasts so a 1 KB user-typed goal
|
||||||
|
/// doesn't blow out the hint pill. The header pill applies its
|
||||||
|
/// own 33-char cap; the toast is shorter so the hint stays
|
||||||
|
/// glanceable.
|
||||||
|
static func truncatedToastGoal(_ text: String) -> String {
|
||||||
|
text.count <= 60 ? text : String(text.prefix(57)) + "…"
|
||||||
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
private func recordACPFailure(_ error: Error, client: ACPClient?, context: String) async {
|
private func recordACPFailure(_ error: Error, client: ACPClient?, context: String) async {
|
||||||
logger.error("\(context): \(error.localizedDescription)")
|
logger.error("\(context): \(error.localizedDescription)")
|
||||||
@@ -575,22 +637,59 @@ final class ChatViewModel {
|
|||||||
// and Hermes-version-independent. v2.5.
|
// and Hermes-version-independent. v2.5.
|
||||||
let wireText = expandIfProjectScoped(text)
|
let wireText = expandIfProjectScoped(text)
|
||||||
|
|
||||||
// /steer is non-interruptive — the agent is still on its
|
// Non-interruptive slash commands keep the "Agent working…"
|
||||||
// current turn; the guidance applies after the next tool
|
// indicator off and surface a transient toast confirming the
|
||||||
// call. Don't change the "Agent working..." status (it's
|
// command was accepted. v2.5 added `/steer`; v2.8 / Hermes
|
||||||
// already on); show a transient toast so the user knows the
|
// v0.13 adds `/goal` (lock the agent on a target across turns)
|
||||||
// guidance was accepted. v2.5 / Hermes v2026.4.23+.
|
// and `/queue` (queue a prompt for after the current turn).
|
||||||
let isSteer = richChatViewModel.isNonInterruptiveSlash(text)
|
// Each gets its own optimistic side-effect on RichChatViewModel
|
||||||
if isSteer {
|
// so the chat header pill / queue chip update synchronously
|
||||||
|
// without waiting for a server round-trip.
|
||||||
|
let isNonInterruptive = richChatViewModel.isNonInterruptiveSlash(text)
|
||||||
|
let parsed = Self.parseSlashName(text)
|
||||||
|
switch parsed.name {
|
||||||
|
case "goal":
|
||||||
|
// TODO(WS-2-Q7): once a v0.13 host confirms the
|
||||||
|
// wire-shape, this branch fires only when the host
|
||||||
|
// advertises `hasGoals`; pre-v0.13 hosts hide the menu
|
||||||
|
// row, but a power-user typing `/goal` directly still
|
||||||
|
// lands here. We keep the optimistic write so the pill
|
||||||
|
// appears synchronously — the agent's "unknown command"
|
||||||
|
// reply on a pre-v0.13 host paints the inconsistency in
|
||||||
|
// user-visible chat content (acceptable v1 behavior;
|
||||||
|
// see WS-2 plan "Inconsistency caveat").
|
||||||
|
let arg = RichChatViewModel.parseGoalArgument(parsed.args)
|
||||||
|
switch arg {
|
||||||
|
case .set(let goalText):
|
||||||
|
richChatViewModel.recordActiveGoal(text: goalText)
|
||||||
|
richChatViewModel.transientHint = "Goal locked: \(Self.truncatedToastGoal(goalText))"
|
||||||
|
case .clear:
|
||||||
|
richChatViewModel.recordActiveGoal(text: nil)
|
||||||
|
richChatViewModel.transientHint = "Goal cleared."
|
||||||
|
case .empty:
|
||||||
|
richChatViewModel.transientHint = "Sent /goal — see the agent reply for current goal."
|
||||||
|
}
|
||||||
|
scheduleHintClear()
|
||||||
|
case "queue":
|
||||||
|
// TODO(WS-2-Q5): verify against a real v0.13 ACP host
|
||||||
|
// that the verbatim "/queue <text>" wire shape is what
|
||||||
|
// Hermes accepts (versus a structured arg shape). The
|
||||||
|
// optimistic mirror logic below assumes verbatim text.
|
||||||
|
let queuedText = parsed.args.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
if !queuedText.isEmpty {
|
||||||
|
richChatViewModel.recordQueuedPrompt(text: queuedText)
|
||||||
|
}
|
||||||
|
richChatViewModel.transientHint = "Queued — runs after current turn."
|
||||||
|
scheduleHintClear()
|
||||||
|
case "steer" where isNonInterruptive:
|
||||||
richChatViewModel.transientHint = "Guidance queued — applies after the next tool call."
|
richChatViewModel.transientHint = "Guidance queued — applies after the next tool call."
|
||||||
Task { @MainActor [weak self] in
|
scheduleHintClear()
|
||||||
try? await Task.sleep(nanoseconds: 4_000_000_000)
|
default:
|
||||||
if self?.richChatViewModel.transientHint == "Guidance queued — applies after the next tool call." {
|
// Regular interruptive prompt (or an unrecognized slash).
|
||||||
self?.richChatViewModel.transientHint = nil
|
// Don't flip "Agent working…" for any other
|
||||||
}
|
// non-interruptive command (defensive; matches the
|
||||||
}
|
// legacy contract).
|
||||||
} else {
|
if !isNonInterruptive { acpStatus = ACPPhase.agentWorking }
|
||||||
acpStatus = ACPPhase.agentWorking
|
|
||||||
}
|
}
|
||||||
acpPromptTask = Task { @MainActor in
|
acpPromptTask = Task { @MainActor in
|
||||||
do {
|
do {
|
||||||
@@ -608,7 +707,7 @@ final class ChatViewModel {
|
|||||||
// notifier handles the foreground/disabled gating;
|
// notifier handles the foreground/disabled gating;
|
||||||
// we just hand it the latest assistant text and
|
// we just hand it the latest assistant text and
|
||||||
// session title for the body line.
|
// session title for the body line.
|
||||||
if !isSteer {
|
if !isNonInterruptive {
|
||||||
let preview = richChatViewModel.messages
|
let preview = richChatViewModel.messages
|
||||||
.last(where: { $0.isAssistant })?
|
.last(where: { $0.isAssistant })?
|
||||||
.content ?? ""
|
.content ?? ""
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import SwiftUI
|
||||||
|
import ScarfCore
|
||||||
|
import ScarfDesign
|
||||||
|
|
||||||
|
/// Header chip that surfaces prompts the user has queued via
|
||||||
|
/// `/queue …` (Hermes v0.13). Tap → popover listing the queued
|
||||||
|
/// prompt previews + their relative timestamps.
|
||||||
|
///
|
||||||
|
/// The chip is OPTIMISTIC — it's a Scarf-side mirror of what the user
|
||||||
|
/// typed. Hermes owns the authoritative queue server-side. The popover
|
||||||
|
/// header makes that explicit so the user understands per-entry
|
||||||
|
/// removal isn't supported (Hermes has no remove-by-id verb), and the
|
||||||
|
/// v2.8.0 plan removed the "Clear all" button rather than ship one
|
||||||
|
/// that would lie about its effect on server-side state. See WS-2 plan
|
||||||
|
/// Q2 for the wire-shape question that drove that decision.
|
||||||
|
struct ChatQueueIndicator: View {
|
||||||
|
let queuedPrompts: [HermesQueuedPrompt]
|
||||||
|
@State private var isPopoverShown = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
if queuedPrompts.isEmpty {
|
||||||
|
EmptyView()
|
||||||
|
} else {
|
||||||
|
chipButton
|
||||||
|
.popover(isPresented: $isPopoverShown, arrowEdge: .bottom) {
|
||||||
|
queuePopover
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var chipButton: some View {
|
||||||
|
Button {
|
||||||
|
isPopoverShown = true
|
||||||
|
} label: {
|
||||||
|
HStack(spacing: 4) {
|
||||||
|
Image(systemName: "tray.full")
|
||||||
|
Text("\(queuedPrompts.count) queued")
|
||||||
|
}
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.padding(.horizontal, ScarfSpace.s2)
|
||||||
|
.padding(.vertical, 2)
|
||||||
|
.background(Capsule().fill(ScarfColor.warning.opacity(0.16)))
|
||||||
|
.foregroundStyle(ScarfColor.warning)
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.help("Prompts waiting to run after the current turn finishes")
|
||||||
|
}
|
||||||
|
|
||||||
|
@ViewBuilder
|
||||||
|
private var queuePopover: some View {
|
||||||
|
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
|
||||||
|
Text("Queued prompts")
|
||||||
|
.scarfStyle(.headline)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundPrimary)
|
||||||
|
Text("Local view — Hermes manages the actual queue server-side. The next prompt runs automatically when the current turn finishes.")
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
ScarfDivider()
|
||||||
|
ScrollView {
|
||||||
|
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
|
||||||
|
ForEach(Array(queuedPrompts.enumerated()), id: \.element.id) { index, prompt in
|
||||||
|
queueRow(prompt, position: index + 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.vertical, 2)
|
||||||
|
}
|
||||||
|
.frame(maxHeight: 220)
|
||||||
|
}
|
||||||
|
.padding(ScarfSpace.s4)
|
||||||
|
.frame(width: 360)
|
||||||
|
}
|
||||||
|
|
||||||
|
@ViewBuilder
|
||||||
|
private func queueRow(_ prompt: HermesQueuedPrompt, position: Int) -> some View {
|
||||||
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
|
HStack(alignment: .firstTextBaseline, spacing: ScarfSpace.s2) {
|
||||||
|
Text("#\(position)")
|
||||||
|
.scarfStyle(.captionUppercase)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
|
Text(prompt.queuedAt, style: .relative)
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
|
.monospacedDigit()
|
||||||
|
}
|
||||||
|
Text(prompt.text)
|
||||||
|
.scarfStyle(.body)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundPrimary)
|
||||||
|
.lineLimit(3)
|
||||||
|
.truncationMode(.tail)
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
}
|
||||||
|
.padding(.vertical, 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ struct ChatTranscriptPane: View {
|
|||||||
@Bindable var chatViewModel: ChatViewModel
|
@Bindable var chatViewModel: ChatViewModel
|
||||||
var onSend: (String, [ChatImageAttachment]) -> Void
|
var onSend: (String, [ChatImageAttachment]) -> Void
|
||||||
var isEnabled: Bool
|
var isEnabled: Bool
|
||||||
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(spacing: 0) {
|
VStack(spacing: 0) {
|
||||||
@@ -20,8 +21,13 @@ struct ChatTranscriptPane: View {
|
|||||||
acpInputTokens: richChat.acpInputTokens,
|
acpInputTokens: richChat.acpInputTokens,
|
||||||
acpOutputTokens: richChat.acpOutputTokens,
|
acpOutputTokens: richChat.acpOutputTokens,
|
||||||
acpThoughtTokens: richChat.acpThoughtTokens,
|
acpThoughtTokens: richChat.acpThoughtTokens,
|
||||||
|
acpCompressionCount: richChat.acpCompressionCount,
|
||||||
projectName: chatViewModel.currentProjectName,
|
projectName: chatViewModel.currentProjectName,
|
||||||
gitBranch: chatViewModel.currentGitBranch
|
gitBranch: chatViewModel.currentGitBranch,
|
||||||
|
activeGoal: richChat.activeGoal,
|
||||||
|
onClearGoal: { chatViewModel.sendText("/goal --clear") },
|
||||||
|
queuedPrompts: richChat.queuedPrompts,
|
||||||
|
capabilities: capabilitiesStore?.capabilities ?? .empty
|
||||||
)
|
)
|
||||||
Divider()
|
Divider()
|
||||||
|
|
||||||
@@ -58,7 +64,8 @@ struct ChatTranscriptPane: View {
|
|||||||
onSend: onSend,
|
onSend: onSend,
|
||||||
isEnabled: isEnabled,
|
isEnabled: isEnabled,
|
||||||
commands: richChat.availableCommands,
|
commands: richChat.availableCommands,
|
||||||
showCompressButton: richChat.supportsCompress && !richChat.hasBroaderCommandMenu
|
showCompressButton: richChat.supportsCompress && !richChat.hasBroaderCommandMenu,
|
||||||
|
isAgentWorking: richChat.isAgentWorking
|
||||||
)
|
)
|
||||||
.id(richChat.sessionId ?? "scarf.chat.no-session")
|
.id(richChat.sessionId ?? "scarf.chat.no-session")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,12 @@ struct ChatView: View {
|
|||||||
@Environment(ChatViewModel.self) private var viewModel
|
@Environment(ChatViewModel.self) private var viewModel
|
||||||
@Environment(HermesFileWatcher.self) private var fileWatcher
|
@Environment(HermesFileWatcher.self) private var fileWatcher
|
||||||
@Environment(AppCoordinator.self) private var coordinator
|
@Environment(AppCoordinator.self) private var coordinator
|
||||||
|
/// Capabilities store for the active server (injected on
|
||||||
|
/// `ContextBoundRoot`). Forwarded into `ChatViewModel` so the
|
||||||
|
/// rich-chat slash menu can gate v0.13 surfaces (`/goal`, `/queue`,
|
||||||
|
/// `/steer` on idle). Nil during harness scenarios; treated the
|
||||||
|
/// same as `.empty` capabilities.
|
||||||
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
@State private var showErrorDetails = false
|
@State private var showErrorDetails = false
|
||||||
|
|
||||||
/// Side-pane visibility toggles (issue #58). Drive the new
|
/// Side-pane visibility toggles (issue #58). Drive the new
|
||||||
@@ -45,6 +51,15 @@ struct ChatView: View {
|
|||||||
.navigationTitle(
|
.navigationTitle(
|
||||||
viewModel.currentProjectName.map { "Chat · \($0)" } ?? "Chat"
|
viewModel.currentProjectName.map { "Chat · \($0)" } ?? "Chat"
|
||||||
)
|
)
|
||||||
|
// Forward the env-injected capabilities store into the chat VM
|
||||||
|
// on every refresh tick so the rich-chat slash menu picks up
|
||||||
|
// v0.13 surfaces the moment the host advertises them. The id
|
||||||
|
// value is the capabilities-line string — a stable identity
|
||||||
|
// that flips exactly when the detector fires. Nil store ↔
|
||||||
|
// `.empty` capabilities, which is what the VM defaults to.
|
||||||
|
.task(id: capabilitiesStore?.capabilities.versionLine ?? "") {
|
||||||
|
viewModel.attachCapabilitiesStore(capabilitiesStore)
|
||||||
|
}
|
||||||
.task {
|
.task {
|
||||||
await viewModel.loadRecentSessions()
|
await viewModel.loadRecentSessions()
|
||||||
viewModel.refreshCredentialPreflight()
|
viewModel.refreshCredentialPreflight()
|
||||||
|
|||||||
@@ -16,6 +16,11 @@ struct RichChatInputBar: View {
|
|||||||
let isEnabled: Bool
|
let isEnabled: Bool
|
||||||
var commands: [HermesSlashCommand] = []
|
var commands: [HermesSlashCommand] = []
|
||||||
var showCompressButton: Bool = false
|
var showCompressButton: Bool = false
|
||||||
|
/// Whether the agent is currently mid-turn. Used to grey-out
|
||||||
|
/// `/steer` in the slash menu on idle pre-v0.13 hosts (where the
|
||||||
|
/// command silently no-ops). v0.13+ hosts allow `/steer` on idle
|
||||||
|
/// and the row stays interactive regardless of `isAgentWorking`.
|
||||||
|
var isAgentWorking: Bool = false
|
||||||
|
|
||||||
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
|
||||||
@@ -52,6 +57,8 @@ struct RichChatInputBar: View {
|
|||||||
SlashCommandMenu(
|
SlashCommandMenu(
|
||||||
commands: filteredCommands,
|
commands: filteredCommands,
|
||||||
agentHasCommands: !commands.isEmpty,
|
agentHasCommands: !commands.isEmpty,
|
||||||
|
disabledCommandNames: disabledMenuCommandNames,
|
||||||
|
disabledReason: disabledMenuReason,
|
||||||
selectedIndex: $selectedIndex,
|
selectedIndex: $selectedIndex,
|
||||||
onSelect: insertCommand
|
onSelect: insertCommand
|
||||||
)
|
)
|
||||||
@@ -392,6 +399,27 @@ struct RichChatInputBar: View {
|
|||||||
SlashCommandMenu.filter(commands: commands, query: menuQuery)
|
SlashCommandMenu.filter(commands: commands, query: menuQuery)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Names of menu rows that should render greyed-out + ignore taps.
|
||||||
|
/// v2.8 / Hermes v0.13: `/steer` is greyed only when the connected
|
||||||
|
/// host is pre-v0.13 AND the session is idle. Pre-v0.13 hosts
|
||||||
|
/// silently no-op `/steer` outside an active turn — surfacing the
|
||||||
|
/// row as "use during a turn" is friendlier than letting the user
|
||||||
|
/// click and see nothing happen. v0.13+ hosts allow steer-on-idle
|
||||||
|
/// (the command just sends as a regular prompt) so the row stays
|
||||||
|
/// interactive there.
|
||||||
|
private var disabledMenuCommandNames: Set<String> {
|
||||||
|
let hasSteerOnIdle = capabilitiesStore?.capabilities.hasACPSteerOnIdle ?? false
|
||||||
|
if !isAgentWorking && !hasSteerOnIdle {
|
||||||
|
return ["steer"]
|
||||||
|
}
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
|
||||||
|
private var disabledMenuReason: String? {
|
||||||
|
guard !disabledMenuCommandNames.isEmpty else { return nil }
|
||||||
|
return "Use `/steer` while the agent is working — your Hermes version doesn't support steering on idle sessions."
|
||||||
|
}
|
||||||
|
|
||||||
private func updateMenuState() {
|
private func updateMenuState() {
|
||||||
let shouldShow = shouldShowMenu
|
let shouldShow = shouldShowMenu
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,11 @@ struct SessionInfoBar: View {
|
|||||||
var acpInputTokens: Int = 0
|
var acpInputTokens: Int = 0
|
||||||
var acpOutputTokens: Int = 0
|
var acpOutputTokens: Int = 0
|
||||||
var acpThoughtTokens: Int = 0
|
var acpThoughtTokens: Int = 0
|
||||||
|
/// Number of context compactions Hermes has run on this session. v0.13+
|
||||||
|
/// surface — capability-gated by the bar so pre-v0.13 hosts never see
|
||||||
|
/// the chip even if a stale value somehow trickles through. Defaults
|
||||||
|
/// to 0 so existing callers and previews don't need to be updated.
|
||||||
|
var acpCompressionCount: Int = 0
|
||||||
/// Name of the Scarf project this session is attributed to, when
|
/// Name of the Scarf project this session is attributed to, when
|
||||||
/// applicable. Nil for plain global chats. Drives the folder-chip
|
/// applicable. Nil for plain global chats. Drives the folder-chip
|
||||||
/// indicator rendered before the session title. Resolved by
|
/// indicator rendered before the session title. Resolved by
|
||||||
@@ -20,6 +25,21 @@ struct SessionInfoBar: View {
|
|||||||
/// name. Nil for non-project chats and for projects that aren't
|
/// name. Nil for non-project chats and for projects that aren't
|
||||||
/// git repos.
|
/// git repos.
|
||||||
var gitBranch: String? = nil
|
var gitBranch: String? = nil
|
||||||
|
/// Active locked goal (Hermes v0.13 `/goal`). Nil hides the pill.
|
||||||
|
/// Optimistic — set by `RichChatViewModel.recordActiveGoal(text:)`
|
||||||
|
/// when the user sends `/goal …`.
|
||||||
|
var activeGoal: HermesActiveGoal? = nil
|
||||||
|
/// Invoked when the user picks "Clear goal" from the goal pill's
|
||||||
|
/// context menu. Caller dispatches `/goal --clear` so the optimistic
|
||||||
|
/// pill clear and the server-side authoritative state stay in sync.
|
||||||
|
var onClearGoal: (() -> Void)? = nil
|
||||||
|
/// Local mirror of prompts queued via `/queue …` (Hermes v0.13).
|
||||||
|
/// Empty list hides the chip.
|
||||||
|
var queuedPrompts: [HermesQueuedPrompt] = []
|
||||||
|
/// Capability snapshot for v0.13+ surfaces. Defaulted so previews and
|
||||||
|
/// pre-v0.13 hosts render the v2.7.5 layout unchanged. Coordinated
|
||||||
|
/// with WS-2 — both WSes add `capabilities` to this view.
|
||||||
|
var capabilities: HermesCapabilities = .empty
|
||||||
|
|
||||||
/// Active Hermes profile name (issue #50). Resolved on each body
|
/// Active Hermes profile name (issue #50). Resolved on each body
|
||||||
/// re-evaluation; the resolver caches for 5s so this is cheap.
|
/// re-evaluation; the resolver caches for 5s so this is cheap.
|
||||||
@@ -62,6 +82,42 @@ struct SessionInfoBar: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Goal pill (v2.8 / Hermes v0.13). `.info` keeps it
|
||||||
|
// visually decodable from the rust accent (project /
|
||||||
|
// branch) and the warning amber (queue chip). The
|
||||||
|
// pill renders only when `activeGoal` is non-nil —
|
||||||
|
// pre-v0.13 hosts can't reach the `/goal` send path
|
||||||
|
// through the slash menu (it's filtered out in
|
||||||
|
// `availableCommands`), so the pill stays absent there
|
||||||
|
// by transitive impossibility.
|
||||||
|
if let activeGoal {
|
||||||
|
HStack(spacing: 4) {
|
||||||
|
Image(systemName: "scope")
|
||||||
|
Text(Self.truncatedGoal(activeGoal.text))
|
||||||
|
}
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.padding(.horizontal, ScarfSpace.s2)
|
||||||
|
.padding(.vertical, 2)
|
||||||
|
.background(Capsule().fill(ScarfColor.info.opacity(0.16)))
|
||||||
|
.foregroundStyle(ScarfColor.info)
|
||||||
|
.help("Goal locked: \(activeGoal.text)")
|
||||||
|
.contextMenu {
|
||||||
|
if let onClearGoal {
|
||||||
|
Button("Clear goal", role: .destructive, action: onClearGoal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Queue chip (v2.8 / Hermes v0.13). Local mirror only —
|
||||||
|
// Hermes is the authoritative owner of the actual
|
||||||
|
// queue. Per-entry deletion isn't exposed (Hermes has
|
||||||
|
// no remove-by-id verb), and the v2.8.0 plan drops the
|
||||||
|
// global "Clear all" button to avoid lying about
|
||||||
|
// server-side state. The popover is read-only.
|
||||||
|
if !queuedPrompts.isEmpty {
|
||||||
|
ChatQueueIndicator(queuedPrompts: queuedPrompts)
|
||||||
|
}
|
||||||
|
|
||||||
HStack(spacing: 4) {
|
HStack(spacing: 4) {
|
||||||
Circle()
|
Circle()
|
||||||
.fill(isWorking ? ScarfColor.success : ScarfColor.foregroundFaint)
|
.fill(isWorking ? ScarfColor.success : ScarfColor.foregroundFaint)
|
||||||
@@ -96,6 +152,21 @@ struct SessionInfoBar: View {
|
|||||||
Label("\(formatTokens(reasonToks)) reasoning", systemImage: "brain")
|
Label("\(formatTokens(reasonToks)) reasoning", systemImage: "brain")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// v0.13: Hermes surfaces a running count of automatic
|
||||||
|
// context compactions. Render only when the host is on
|
||||||
|
// v0.13+ AND the count is non-zero, so a pre-v0.13 host
|
||||||
|
// (which always reports 0) sees no chip, and a v0.13 host
|
||||||
|
// sees the chip the first time the agent compacts.
|
||||||
|
if capabilities.hasContextCompressionCount && acpCompressionCount > 0 {
|
||||||
|
Label(
|
||||||
|
"×\(acpCompressionCount)",
|
||||||
|
systemImage: "arrow.down.right.and.arrow.up.left"
|
||||||
|
)
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||||
|
.help("Hermes auto-compacted this session's context \(acpCompressionCount) time\(acpCompressionCount == 1 ? "" : "s")")
|
||||||
|
}
|
||||||
|
|
||||||
if let cost = session.displayCostUSD {
|
if let cost = session.displayCostUSD {
|
||||||
let formattedCost = cost.formatted(.currency(code: "USD").precision(.fractionLength(4)))
|
let formattedCost = cost.formatted(.currency(code: "USD").precision(.fractionLength(4)))
|
||||||
Label(session.costIsActual ? formattedCost : "\(formattedCost) est.", systemImage: "dollarsign.circle")
|
Label(session.costIsActual ? formattedCost : "\(formattedCost) est.", systemImage: "dollarsign.circle")
|
||||||
@@ -134,4 +205,11 @@ struct SessionInfoBar: View {
|
|||||||
private func formatTokens(_ count: Int) -> String {
|
private func formatTokens(_ count: Int) -> String {
|
||||||
count.formatted(.number.notation(.compactName).precision(.fractionLength(0...1)))
|
count.formatted(.number.notation(.compactName).precision(.fractionLength(0...1)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Cap goal text in the chip to keep the SessionInfoBar from
|
||||||
|
/// wrapping when the user locks a long goal. Full goal text is
|
||||||
|
/// available in the tooltip via `.help(...)`.
|
||||||
|
static func truncatedGoal(_ text: String) -> String {
|
||||||
|
text.count <= 36 ? text : String(text.prefix(33)) + "…"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,13 @@ struct SlashCommandMenu: View {
|
|||||||
/// Whether the agent advertised any commands at all. Lets us distinguish
|
/// Whether the agent advertised any commands at all. Lets us distinguish
|
||||||
/// "agent hasn't sent commands yet" from "filter matched nothing".
|
/// "agent hasn't sent commands yet" from "filter matched nothing".
|
||||||
let agentHasCommands: Bool
|
let agentHasCommands: Bool
|
||||||
|
/// Names that render greyed-out + ignore taps. v2.8 uses this only
|
||||||
|
/// for `/steer` on pre-v0.13 idle sessions; v0.13 hosts allow steer
|
||||||
|
/// on idle and the set is empty.
|
||||||
|
var disabledCommandNames: Set<String> = []
|
||||||
|
/// Tooltip shown on disabled rows. Reused per-row in v2.8 — only
|
||||||
|
/// one disabled case ships, so a single shared string is enough.
|
||||||
|
var disabledReason: String? = nil
|
||||||
@Binding var selectedIndex: Int
|
@Binding var selectedIndex: Int
|
||||||
var onSelect: (HermesSlashCommand) -> Void
|
var onSelect: (HermesSlashCommand) -> Void
|
||||||
|
|
||||||
@@ -50,13 +57,17 @@ struct SlashCommandMenu: View {
|
|||||||
ScrollView {
|
ScrollView {
|
||||||
LazyVStack(spacing: 0) {
|
LazyVStack(spacing: 0) {
|
||||||
ForEach(Array(commands.enumerated()), id: \.element.id) { index, command in
|
ForEach(Array(commands.enumerated()), id: \.element.id) { index, command in
|
||||||
|
let isDisabled = disabledCommandNames.contains(command.name)
|
||||||
SlashCommandRow(
|
SlashCommandRow(
|
||||||
command: command,
|
command: command,
|
||||||
isSelected: index == selectedIndex
|
isSelected: index == selectedIndex,
|
||||||
|
isDisabled: isDisabled,
|
||||||
|
disabledReason: isDisabled ? disabledReason : nil
|
||||||
)
|
)
|
||||||
.id(index)
|
.id(index)
|
||||||
.contentShape(Rectangle())
|
.contentShape(Rectangle())
|
||||||
.onTapGesture {
|
.onTapGesture {
|
||||||
|
guard !isDisabled else { return }
|
||||||
selectedIndex = index
|
selectedIndex = index
|
||||||
onSelect(command)
|
onSelect(command)
|
||||||
}
|
}
|
||||||
@@ -77,6 +88,8 @@ struct SlashCommandMenu: View {
|
|||||||
private struct SlashCommandRow: View {
|
private struct SlashCommandRow: View {
|
||||||
let command: HermesSlashCommand
|
let command: HermesSlashCommand
|
||||||
let isSelected: Bool
|
let isSelected: Bool
|
||||||
|
var isDisabled: Bool = false
|
||||||
|
var disabledReason: String? = nil
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
HStack(alignment: .firstTextBaseline, spacing: 8) {
|
HStack(alignment: .firstTextBaseline, spacing: 8) {
|
||||||
@@ -87,7 +100,16 @@ private struct SlashCommandRow: View {
|
|||||||
.fontWeight(.semibold)
|
.fontWeight(.semibold)
|
||||||
.foregroundStyle(isSelected ? ScarfColor.accentActive : ScarfColor.foregroundPrimary)
|
.foregroundStyle(isSelected ? ScarfColor.accentActive : ScarfColor.foregroundPrimary)
|
||||||
if let hint = command.argumentHint {
|
if let hint = command.argumentHint {
|
||||||
Text("<\(hint)>")
|
// v0.13: Hermes may emit hints already wrapped in
|
||||||
|
// brackets (e.g. `[name]` for the optional `/new
|
||||||
|
// <name>` argument exposed by `hasNewWithSessionName`).
|
||||||
|
// Avoid double-wrapping — bracketed hints pass through
|
||||||
|
// verbatim while older `guidance`-style hints (no
|
||||||
|
// brackets) still render as `<guidance>`.
|
||||||
|
let display = hint.hasPrefix("<") || hint.hasPrefix("[")
|
||||||
|
? hint
|
||||||
|
: "<\(hint)>"
|
||||||
|
Text(display)
|
||||||
.font(ScarfFont.monoSmall)
|
.font(ScarfFont.monoSmall)
|
||||||
.foregroundStyle(ScarfColor.foregroundFaint)
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
}
|
}
|
||||||
@@ -107,11 +129,19 @@ private struct SlashCommandRow: View {
|
|||||||
.foregroundStyle(ScarfColor.foregroundMuted)
|
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||||
.lineLimit(2)
|
.lineLimit(2)
|
||||||
}
|
}
|
||||||
|
if isDisabled, let reason = disabledReason {
|
||||||
|
Text(reason)
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
|
.lineLimit(2)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Spacer(minLength: 0)
|
Spacer(minLength: 0)
|
||||||
}
|
}
|
||||||
.padding(.horizontal, ScarfSpace.s3)
|
.padding(.horizontal, ScarfSpace.s3)
|
||||||
.padding(.vertical, ScarfSpace.s2)
|
.padding(.vertical, ScarfSpace.s2)
|
||||||
.background(isSelected ? ScarfColor.accentTint : Color.clear)
|
.background(isSelected ? ScarfColor.accentTint : Color.clear)
|
||||||
|
.opacity(isDisabled ? 0.55 : 1.0)
|
||||||
|
.help(isDisabled ? (disabledReason ?? "") : "")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -146,7 +146,7 @@ final class CronViewModel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func createJob(schedule: String, prompt: String, name: String, deliver: String, skills: [String], script: String, repeatCount: String, workdir: String = "") {
|
func createJob(schedule: String, prompt: String, name: String, deliver: String, skills: [String], script: String, repeatCount: String, workdir: String = "", noAgent: Bool = false) {
|
||||||
var args = ["cron", "create"]
|
var args = ["cron", "create"]
|
||||||
if !name.isEmpty { args += ["--name", name] }
|
if !name.isEmpty { args += ["--name", name] }
|
||||||
if !deliver.isEmpty { args += ["--deliver", deliver] }
|
if !deliver.isEmpty { args += ["--deliver", deliver] }
|
||||||
@@ -158,12 +158,25 @@ final class CronViewModel {
|
|||||||
// know the flag — argparse rejects unknown args, so the form
|
// know the flag — argparse rejects unknown args, so the form
|
||||||
// omits the flag when the field is empty.
|
// omits the flag when the field is empty.
|
||||||
if !workdir.isEmpty { args += ["--workdir", workdir] }
|
if !workdir.isEmpty { args += ["--workdir", workdir] }
|
||||||
|
// v0.13+: --no-agent runs the pre-run script and skips the AI turn.
|
||||||
|
// Caller (CronView) strips this on pre-v0.13 hosts so the flag is
|
||||||
|
// never emitted to a Hermes that can't parse it.
|
||||||
|
if noAgent { args.append("--no-agent") }
|
||||||
args.append(schedule)
|
args.append(schedule)
|
||||||
if !prompt.isEmpty { args.append(prompt) }
|
// TODO(WS-7-Q5): When --no-agent is set Hermes ignores the prompt arg,
|
||||||
|
// but argparse still wants positional args to line up with the
|
||||||
|
// schedule. The plan recommends passing an empty string explicitly so
|
||||||
|
// the positional parser doesn't treat the prompt as missing — verify
|
||||||
|
// this behaviour against `hermes cron create --help` on a v0.13 host.
|
||||||
|
if noAgent {
|
||||||
|
args.append("")
|
||||||
|
} else if !prompt.isEmpty {
|
||||||
|
args.append(prompt)
|
||||||
|
}
|
||||||
runAndReload(args, success: "Job created")
|
runAndReload(args, success: "Job created")
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateJob(id: String, schedule: String?, prompt: String?, name: String?, deliver: String?, repeatCount: String?, newSkills: [String]?, clearSkills: Bool, script: String?, workdir: String? = nil) {
|
func updateJob(id: String, schedule: String?, prompt: String?, name: String?, deliver: String?, repeatCount: String?, newSkills: [String]?, clearSkills: Bool, script: String?, workdir: String? = nil, noAgent: Bool? = nil) {
|
||||||
var args = ["cron", "edit", id]
|
var args = ["cron", "edit", id]
|
||||||
if let schedule, !schedule.isEmpty { args += ["--schedule", schedule] }
|
if let schedule, !schedule.isEmpty { args += ["--schedule", schedule] }
|
||||||
if let prompt, !prompt.isEmpty { args += ["--prompt", prompt] }
|
if let prompt, !prompt.isEmpty { args += ["--prompt", prompt] }
|
||||||
@@ -180,6 +193,16 @@ final class CronViewModel {
|
|||||||
// = user cleared an existing workdir; Hermes documents `--workdir ""`
|
// = user cleared an existing workdir; Hermes documents `--workdir ""`
|
||||||
// on edit as the explicit clear gesture, mirroring the `--script` shape.
|
// on edit as the explicit clear gesture, mirroring the `--script` shape.
|
||||||
if let workdir { args += ["--workdir", workdir] }
|
if let workdir { args += ["--workdir", workdir] }
|
||||||
|
// TODO(WS-7-Q4): The toggle-off shape of `--no-agent` on edit is
|
||||||
|
// unverified. Plan assumes Hermes accepts `--agent` to flip the flag
|
||||||
|
// back; if the CLI is one-way (`--no-agent` only), the edit-mode
|
||||||
|
// toggle should disable itself with a tooltip explaining the
|
||||||
|
// limitation. Send the flag in the assumed shape for now and adjust
|
||||||
|
// post-integration.
|
||||||
|
if let noAgent {
|
||||||
|
if noAgent { args.append("--no-agent") }
|
||||||
|
else { args.append("--agent") }
|
||||||
|
}
|
||||||
runAndReload(args, success: "Updated")
|
runAndReload(args, success: "Updated")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,6 +25,10 @@ struct CronView: View {
|
|||||||
capabilitiesStore?.capabilities.hasCronWorkdir ?? false
|
capabilitiesStore?.capabilities.hasCronWorkdir ?? false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private var hasCronNoAgent: Bool {
|
||||||
|
capabilitiesStore?.capabilities.hasCronNoAgent ?? false
|
||||||
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(spacing: 0) {
|
VStack(spacing: 0) {
|
||||||
pageHeader
|
pageHeader
|
||||||
@@ -47,7 +51,7 @@ struct CronView: View {
|
|||||||
// polling timer. Same wiring ActivityView uses.
|
// polling timer. Same wiring ActivityView uses.
|
||||||
.onChange(of: fileWatcher.lastChangeDate) { viewModel.load() }
|
.onChange(of: fileWatcher.lastChangeDate) { viewModel.load() }
|
||||||
.sheet(isPresented: $viewModel.showCreateSheet) {
|
.sheet(isPresented: $viewModel.showCreateSheet) {
|
||||||
CronJobEditor(mode: .create, availableSkills: viewModel.availableSkills, supportsWorkdir: hasCronWorkdir) { form in
|
CronJobEditor(mode: .create, availableSkills: viewModel.availableSkills, supportsWorkdir: hasCronWorkdir, supportsNoAgent: hasCronNoAgent) { form in
|
||||||
viewModel.createJob(
|
viewModel.createJob(
|
||||||
schedule: form.schedule,
|
schedule: form.schedule,
|
||||||
prompt: form.prompt,
|
prompt: form.prompt,
|
||||||
@@ -56,7 +60,12 @@ struct CronView: View {
|
|||||||
skills: form.skills,
|
skills: form.skills,
|
||||||
script: form.script,
|
script: form.script,
|
||||||
repeatCount: form.repeatCount,
|
repeatCount: form.repeatCount,
|
||||||
workdir: hasCronWorkdir ? form.workdir : ""
|
workdir: hasCronWorkdir ? form.workdir : "",
|
||||||
|
// Mirrors the workdir strip-on-pre-version pattern: pre-v0.13
|
||||||
|
// hosts get a hard `false`, so a stale form value (or a
|
||||||
|
// hand-edited jobs.json round-tripped through edit-mode)
|
||||||
|
// can't sneak `--no-agent` into a CLI that doesn't grok it.
|
||||||
|
noAgent: hasCronNoAgent ? form.noAgent : false
|
||||||
)
|
)
|
||||||
viewModel.showCreateSheet = false
|
viewModel.showCreateSheet = false
|
||||||
} onCancel: {
|
} onCancel: {
|
||||||
@@ -64,7 +73,7 @@ struct CronView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
.sheet(item: $viewModel.editingJob) { job in
|
.sheet(item: $viewModel.editingJob) { job in
|
||||||
CronJobEditor(mode: .edit(job), availableSkills: viewModel.availableSkills, supportsWorkdir: hasCronWorkdir) { form in
|
CronJobEditor(mode: .edit(job), availableSkills: viewModel.availableSkills, supportsWorkdir: hasCronWorkdir, supportsNoAgent: hasCronNoAgent) { form in
|
||||||
viewModel.updateJob(
|
viewModel.updateJob(
|
||||||
id: job.id,
|
id: job.id,
|
||||||
schedule: form.schedule,
|
schedule: form.schedule,
|
||||||
@@ -75,7 +84,8 @@ struct CronView: View {
|
|||||||
newSkills: form.skills,
|
newSkills: form.skills,
|
||||||
clearSkills: form.clearSkills,
|
clearSkills: form.clearSkills,
|
||||||
script: form.script,
|
script: form.script,
|
||||||
workdir: hasCronWorkdir ? form.workdir : nil
|
workdir: hasCronWorkdir ? form.workdir : nil,
|
||||||
|
noAgent: hasCronNoAgent ? form.noAgent : nil
|
||||||
)
|
)
|
||||||
viewModel.editingJob = nil
|
viewModel.editingJob = nil
|
||||||
} onCancel: {
|
} onCancel: {
|
||||||
@@ -643,6 +653,9 @@ struct CronJobEditor: View {
|
|||||||
/// v0.12+ workdir flag — fills `--workdir <path>`. Empty string
|
/// v0.12+ workdir flag — fills `--workdir <path>`. Empty string
|
||||||
/// preserves the v0.11 behaviour of running with no cwd hint.
|
/// preserves the v0.11 behaviour of running with no cwd hint.
|
||||||
var workdir: String = ""
|
var workdir: String = ""
|
||||||
|
/// v0.13+ `--no-agent` flag — script-only watchdog mode. Hermes
|
||||||
|
/// runs the pre-run script and skips the AI turn.
|
||||||
|
var noAgent: Bool = false
|
||||||
}
|
}
|
||||||
|
|
||||||
let mode: Mode
|
let mode: Mode
|
||||||
@@ -650,6 +663,10 @@ struct CronJobEditor: View {
|
|||||||
/// Pass `false` on pre-v0.12 hosts; the `--workdir` field is hidden and
|
/// Pass `false` on pre-v0.12 hosts; the `--workdir` field is hidden and
|
||||||
/// the form's value is dropped when the parent calls `createJob`/`updateJob`.
|
/// the form's value is dropped when the parent calls `createJob`/`updateJob`.
|
||||||
let supportsWorkdir: Bool
|
let supportsWorkdir: Bool
|
||||||
|
/// Pass `false` on pre-v0.13 hosts; the `--no-agent` toggle is hidden
|
||||||
|
/// and the parent strips the form's value before calling
|
||||||
|
/// `createJob`/`updateJob`. Mirrors the `supportsWorkdir` pattern.
|
||||||
|
let supportsNoAgent: Bool
|
||||||
let onSave: (FormState) -> Void
|
let onSave: (FormState) -> Void
|
||||||
let onCancel: () -> Void
|
let onCancel: () -> Void
|
||||||
|
|
||||||
@@ -681,12 +698,25 @@ struct CronJobEditor: View {
|
|||||||
)
|
)
|
||||||
.scrollContentBackground(.hidden)
|
.scrollContentBackground(.hidden)
|
||||||
}
|
}
|
||||||
|
.opacity(form.noAgent ? 0.4 : 1.0)
|
||||||
|
.disabled(form.noAgent)
|
||||||
formField("Deliver", text: $form.deliver, placeholder: "origin | local | discord:CHANNEL | telegram:CHAT", mono: true)
|
formField("Deliver", text: $form.deliver, placeholder: "origin | local | discord:CHANNEL | telegram:CHAT", mono: true)
|
||||||
formField("Repeat", text: $form.repeatCount, placeholder: "Optional count")
|
formField("Repeat", text: $form.repeatCount, placeholder: "Optional count")
|
||||||
formField("Script path", text: $form.script, placeholder: "Python script whose stdout is injected", mono: true)
|
formField("Script path", text: $form.script, placeholder: "Python script whose stdout is injected", mono: true)
|
||||||
if supportsWorkdir {
|
if supportsWorkdir {
|
||||||
formField("Workdir", text: $form.workdir, placeholder: "Absolute path; pulls AGENTS.md/CLAUDE.md context", mono: true)
|
formField("Workdir", text: $form.workdir, placeholder: "Absolute path; pulls AGENTS.md/CLAUDE.md context", mono: true)
|
||||||
}
|
}
|
||||||
|
if supportsNoAgent {
|
||||||
|
Toggle("Run script only (no agent call)", isOn: $form.noAgent)
|
||||||
|
.scarfStyle(.body)
|
||||||
|
.tint(ScarfColor.accent)
|
||||||
|
if form.noAgent {
|
||||||
|
Text("Watchdog mode — Hermes runs the pre-run script and skips the AI turn. Prompt + skills are ignored.")
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||||
|
.padding(.leading, ScarfSpace.s3)
|
||||||
|
}
|
||||||
|
}
|
||||||
if !availableSkills.isEmpty {
|
if !availableSkills.isEmpty {
|
||||||
VStack(alignment: .leading, spacing: 4) {
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
Text("Skills")
|
Text("Skills")
|
||||||
@@ -723,6 +753,8 @@ struct CronJobEditor: View {
|
|||||||
.tint(ScarfColor.accent)
|
.tint(ScarfColor.accent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.opacity(form.noAgent ? 0.4 : 1.0)
|
||||||
|
.disabled(form.noAgent)
|
||||||
}
|
}
|
||||||
HStack {
|
HStack {
|
||||||
Spacer()
|
Spacer()
|
||||||
@@ -746,6 +778,7 @@ struct CronJobEditor: View {
|
|||||||
form.skills = job.skills ?? []
|
form.skills = job.skills ?? []
|
||||||
form.script = job.preRunScript ?? ""
|
form.script = job.preRunScript ?? ""
|
||||||
form.workdir = job.workdir ?? ""
|
form.workdir = job.workdir ?? ""
|
||||||
|
form.noAgent = job.noAgent ?? false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import SwiftUI
|
||||||
|
import ScarfCore
|
||||||
|
import ScarfDesign
|
||||||
|
|
||||||
|
/// Mac sub-view rendered between the active-skill leaderboards and the
|
||||||
|
/// last-report block on Hermes v0.13+ hosts. Lists everything currently
|
||||||
|
/// archived (`hermes curator list-archived`) with per-row Restore + a
|
||||||
|
/// bulk Prune affordance routed through the parent's confirm sheet.
|
||||||
|
///
|
||||||
|
/// Empty-state copy explains what archive means — useful when the
|
||||||
|
/// curator hasn't run yet on a fresh install (no archives ≠ a problem).
|
||||||
|
struct CuratorArchivedSection: View {
|
||||||
|
let archived: [HermesCuratorArchivedSkill]
|
||||||
|
let isLoading: Bool
|
||||||
|
let onRestore: (String) -> Void
|
||||||
|
let onPruneAll: () -> Void
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
ScarfCard {
|
||||||
|
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
|
||||||
|
header
|
||||||
|
if isLoading && archived.isEmpty {
|
||||||
|
loadingRow
|
||||||
|
} else if archived.isEmpty {
|
||||||
|
emptyState
|
||||||
|
} else {
|
||||||
|
rows
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var header: some View {
|
||||||
|
HStack(alignment: .firstTextBaseline) {
|
||||||
|
ScarfSectionHeader("Archived")
|
||||||
|
Spacer()
|
||||||
|
Text("\(archived.count) skill\(archived.count == 1 ? "" : "s")")
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||||
|
if !archived.isEmpty {
|
||||||
|
Button("Prune All…") {
|
||||||
|
onPruneAll()
|
||||||
|
}
|
||||||
|
.buttonStyle(ScarfDestructiveButton())
|
||||||
|
.help("Remove every archived skill from disk. Cannot be undone.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var loadingRow: some View {
|
||||||
|
HStack(spacing: ScarfSpace.s2) {
|
||||||
|
ProgressView().controlSize(.small)
|
||||||
|
Text("Loading archived skills…")
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||||
|
Spacer()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var emptyState: some View {
|
||||||
|
VStack(alignment: .leading, spacing: ScarfSpace.s1) {
|
||||||
|
Text("No archived skills.")
|
||||||
|
.scarfStyle(.body)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||||
|
Text("The curator moves stale or redundant skills here on its weekly review. Until then, this list stays empty.")
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var rows: some View {
|
||||||
|
VStack(alignment: .leading, spacing: ScarfSpace.s1) {
|
||||||
|
ForEach(archived) { skill in
|
||||||
|
ArchivedSkillRow(
|
||||||
|
skill: skill,
|
||||||
|
onRestore: { onRestore(skill.name) }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct ArchivedSkillRow: View {
|
||||||
|
let skill: HermesCuratorArchivedSkill
|
||||||
|
let onRestore: () -> Void
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HStack(alignment: .center, spacing: ScarfSpace.s2) {
|
||||||
|
Image(systemName: "archivebox.fill")
|
||||||
|
.font(.system(size: 12))
|
||||||
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
|
Text(skill.name)
|
||||||
|
.scarfStyle(.body)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundPrimary)
|
||||||
|
.lineLimit(1)
|
||||||
|
if let reason = skill.reason, !reason.isEmpty {
|
||||||
|
Text(reason)
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||||
|
.lineLimit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
Text(skill.archivedAtLabel)
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
|
.frame(width: 96, alignment: .trailing)
|
||||||
|
Text(skill.sizeLabel)
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
|
.frame(width: 72, alignment: .trailing)
|
||||||
|
Button("Restore") {
|
||||||
|
onRestore()
|
||||||
|
}
|
||||||
|
.buttonStyle(ScarfPrimaryButton())
|
||||||
|
.controlSize(.small)
|
||||||
|
.help("Restore \(skill.name) to the active skill set")
|
||||||
|
}
|
||||||
|
.padding(.vertical, 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import SwiftUI
|
||||||
|
import ScarfCore
|
||||||
|
import ScarfDesign
|
||||||
|
|
||||||
|
/// Destructive-confirm sheet for `hermes curator prune` (bulk).
|
||||||
|
///
|
||||||
|
/// Pattern matches `TemplateUninstallSheet`: enumerate every entry that
|
||||||
|
/// will be removed, surface the total count + bytes, and require an
|
||||||
|
/// explicit click on a red `ScarfDestructiveButton` ("Prune
|
||||||
|
/// permanently") before kicking off the destructive call. Cancel owns
|
||||||
|
/// the keyboard default action so an accidental Enter-press doesn't
|
||||||
|
/// nuke the archive.
|
||||||
|
struct CuratorPruneConfirmSheet: View {
|
||||||
|
@Environment(\.dismiss) private var dismiss
|
||||||
|
let summary: CuratorPruneSummary
|
||||||
|
let isPruning: Bool
|
||||||
|
let onConfirm: () -> Void
|
||||||
|
let onCancel: () -> Void
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 0) {
|
||||||
|
header
|
||||||
|
.padding(.bottom, ScarfSpace.s2)
|
||||||
|
ScarfDivider()
|
||||||
|
ScrollView {
|
||||||
|
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
|
||||||
|
ForEach(summary.wouldRemove) { skill in
|
||||||
|
row(skill: skill)
|
||||||
|
}
|
||||||
|
if summary.wouldRemove.isEmpty {
|
||||||
|
Text("Nothing currently archived. Nothing to prune.")
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||||
|
.padding(.vertical, ScarfSpace.s2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.vertical, ScarfSpace.s2)
|
||||||
|
}
|
||||||
|
ScarfDivider()
|
||||||
|
footer
|
||||||
|
.padding(.top, ScarfSpace.s2)
|
||||||
|
}
|
||||||
|
.frame(minWidth: 520, minHeight: 380)
|
||||||
|
.padding(ScarfSpace.s4)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var header: some View {
|
||||||
|
VStack(alignment: .leading, spacing: ScarfSpace.s1) {
|
||||||
|
HStack(alignment: .firstTextBaseline) {
|
||||||
|
Text("Prune Archived Skills")
|
||||||
|
.scarfStyle(.title2)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundPrimary)
|
||||||
|
Spacer()
|
||||||
|
if summary.totalCount > 0 {
|
||||||
|
ScarfBadge("\(summary.totalCount)", kind: .danger)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Text("This permanently deletes every archived skill from disk. Restoring an archived skill is no longer possible after pruning.")
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
if summary.totalBytes > 0 {
|
||||||
|
Text("Total to remove: \(summary.totalBytesLabel)")
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func row(skill: HermesCuratorArchivedSkill) -> some View {
|
||||||
|
HStack(spacing: ScarfSpace.s2) {
|
||||||
|
Image(systemName: "minus.circle")
|
||||||
|
.foregroundStyle(ScarfColor.danger)
|
||||||
|
.font(.caption)
|
||||||
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
|
Text(skill.name)
|
||||||
|
.scarfStyle(.body)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundPrimary)
|
||||||
|
.lineLimit(1)
|
||||||
|
if let reason = skill.reason, !reason.isEmpty {
|
||||||
|
Text(reason)
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||||
|
.lineLimit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer()
|
||||||
|
Text(skill.archivedAtLabel)
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
|
.frame(width: 96, alignment: .trailing)
|
||||||
|
Text(skill.sizeLabel)
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
|
.frame(width: 72, alignment: .trailing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var footer: some View {
|
||||||
|
HStack {
|
||||||
|
Button("Cancel") {
|
||||||
|
onCancel()
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
.buttonStyle(ScarfGhostButton())
|
||||||
|
// Cancel owns .defaultAction so accidental Enter-presses
|
||||||
|
// don't trigger the destructive button (template-uninstall
|
||||||
|
// pattern recommended in the WS-4 plan).
|
||||||
|
.keyboardShortcut(.defaultAction)
|
||||||
|
.disabled(isPruning)
|
||||||
|
Spacer()
|
||||||
|
if isPruning {
|
||||||
|
ProgressView().controlSize(.small)
|
||||||
|
}
|
||||||
|
Button("Prune permanently") {
|
||||||
|
onConfirm()
|
||||||
|
}
|
||||||
|
.buttonStyle(ScarfDestructiveButton())
|
||||||
|
.disabled(isPruning || summary.wouldRemove.isEmpty)
|
||||||
|
.accessibilityIdentifier("curatorPrune.confirm")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,18 +2,16 @@ import SwiftUI
|
|||||||
import ScarfCore
|
import ScarfCore
|
||||||
import ScarfDesign
|
import ScarfDesign
|
||||||
|
|
||||||
/// Modal that lists archived skills (state ≠ active) and exposes a
|
/// Legacy v0.12 fallback for restoring an archived skill by typed
|
||||||
/// one-click "Restore" action per row. v0.12 archives are recoverable —
|
/// name. Hermes v0.12 didn't ship `curator list-archived`, so the only
|
||||||
/// `hermes curator restore <name>` brings the skill back into
|
/// way to restore was to remember the skill name and pass it through
|
||||||
/// `~/.hermes/skills/<category>/<name>/` and re-marks it active.
|
/// `hermes curator restore <name>`.
|
||||||
///
|
///
|
||||||
/// The Curator's `status` text doesn't enumerate archived skills with
|
/// **v0.13+ flow (preferred):** `CuratorArchivedSection` renders a
|
||||||
/// names; we surface what's available (counts + pinned list) and rely
|
/// per-skill list with a one-click Restore button per row — no typing
|
||||||
/// on the user knowing the names. Hermes ergo does an interactive
|
/// required. This sheet stays reachable from the overflow menu only on
|
||||||
/// `--name` arg if missing — but Scarf prefers explicit selection so
|
/// pre-v0.13 hosts (gated by `!hasCuratorArchive`). Don't delete this
|
||||||
/// users don't have to remember names. For v2.6 we render a free-form
|
/// file even after WS-4 ships; v0.12 hosts still depend on it.
|
||||||
/// text field; once Hermes ships a `curator list-archived` (tracked
|
|
||||||
/// upstream), swap to a pickable list.
|
|
||||||
struct CuratorRestoreSheet: View {
|
struct CuratorRestoreSheet: View {
|
||||||
let viewModel: CuratorViewModel
|
let viewModel: CuratorViewModel
|
||||||
|
|
||||||
|
|||||||
@@ -2,57 +2,52 @@ import SwiftUI
|
|||||||
import ScarfCore
|
import ScarfCore
|
||||||
import ScarfDesign
|
import ScarfDesign
|
||||||
|
|
||||||
/// Mac UI for Hermes v0.12's autonomous skill curator.
|
/// Mac UI for Hermes's autonomous skill curator (v0.12 base + v0.13
|
||||||
|
/// archive/prune surface).
|
||||||
///
|
///
|
||||||
/// Surfaces the running state (enabled / paused / disabled), last-run
|
/// Surfaces the running state (enabled / paused / disabled), last-run
|
||||||
/// metadata, agent-created skill counts, and the most/least-active /
|
/// metadata, agent-created skill counts, the most/least-active /
|
||||||
/// least-recently-active leaderboards. Pin-and-restore actions hit
|
/// least-recently-active leaderboards, and on v0.13+ hosts the new
|
||||||
/// `hermes curator pin/unpin/restore` via CuratorViewModel.
|
/// archived-skills section + per-row Archive button on each leaderboard
|
||||||
|
/// entry. Pin / unpin / restore / archive / prune route through
|
||||||
|
/// CuratorViewModel → CuratorService.
|
||||||
///
|
///
|
||||||
/// Capability-gated upstream: AppCoordinator only wires the sidebar
|
/// Capability-gated upstream: AppCoordinator only wires the sidebar
|
||||||
/// item when `HermesCapabilities.hasCurator` is true. This view assumes
|
/// item when `HermesCapabilities.hasCurator` is true. Archive surfaces
|
||||||
/// it's reachable on a v0.12+ host.
|
/// gate independently on `hasCuratorArchive`; pre-v0.13 hosts see the
|
||||||
|
/// v2.7.x layout unchanged (legacy `CuratorRestoreSheet` reachable from
|
||||||
|
/// the overflow menu, no Archive section, fire-and-forget Run Now).
|
||||||
struct CuratorView: View {
|
struct CuratorView: View {
|
||||||
@State private var viewModel: CuratorViewModel
|
@State private var viewModel: CuratorViewModel
|
||||||
@State private var showRestoreSheet = false
|
@State private var showRestoreSheet = false
|
||||||
|
|
||||||
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
|
||||||
init(context: ServerContext) {
|
init(context: ServerContext) {
|
||||||
_viewModel = State(initialValue: CuratorViewModel(context: context))
|
_viewModel = State(initialValue: CuratorViewModel(context: context))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Single source of truth for "v0.13 archive surface visible". Read
|
||||||
|
/// once in `body` and threaded into sub-views. Defensive default to
|
||||||
|
/// `false` so previews / smoke tests behave like a pre-v0.13 host.
|
||||||
|
private var archiveAvailable: Bool {
|
||||||
|
capabilitiesStore?.capabilities.hasCuratorArchive ?? false
|
||||||
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
ScrollView {
|
ScrollView {
|
||||||
VStack(alignment: .leading, spacing: ScarfSpace.s4) {
|
VStack(alignment: .leading, spacing: ScarfSpace.s4) {
|
||||||
ScarfPageHeader(
|
ScarfPageHeader(
|
||||||
"Curator",
|
"Curator",
|
||||||
subtitle: "Autonomous skill maintenance — Hermes v0.12+"
|
subtitle: archiveAvailable
|
||||||
|
? "Autonomous skill maintenance — archive, prune, restore"
|
||||||
|
: "Autonomous skill maintenance — Hermes v0.12+"
|
||||||
) {
|
) {
|
||||||
HStack(spacing: ScarfSpace.s2) {
|
headerActions
|
||||||
if viewModel.isLoading {
|
|
||||||
ProgressView().controlSize(.small)
|
|
||||||
}
|
|
||||||
Button("Run Now") {
|
|
||||||
Task { await viewModel.runNow() }
|
|
||||||
}
|
|
||||||
.buttonStyle(ScarfPrimaryButton())
|
|
||||||
.disabled(viewModel.isLoading)
|
|
||||||
Menu {
|
|
||||||
switch viewModel.status.state {
|
|
||||||
case .paused:
|
|
||||||
Button("Resume") { Task { await viewModel.resume() } }
|
|
||||||
case .enabled:
|
|
||||||
Button("Pause") { Task { await viewModel.pause() } }
|
|
||||||
default:
|
|
||||||
EmptyView()
|
|
||||||
}
|
|
||||||
Button("Restore Archived…") {
|
|
||||||
showRestoreSheet = true
|
|
||||||
}
|
|
||||||
.disabled(viewModel.status.archivedSkills == 0)
|
|
||||||
} label: {
|
|
||||||
Image(systemName: "ellipsis.circle")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let errorMessage = viewModel.errorMessage {
|
||||||
|
errorBanner(errorMessage)
|
||||||
}
|
}
|
||||||
|
|
||||||
if let toast = viewModel.transientMessage {
|
if let toast = viewModel.transientMessage {
|
||||||
@@ -64,6 +59,19 @@ struct CuratorView: View {
|
|||||||
pinnedSection
|
pinnedSection
|
||||||
activityTables
|
activityTables
|
||||||
|
|
||||||
|
if archiveAvailable {
|
||||||
|
CuratorArchivedSection(
|
||||||
|
archived: viewModel.archivedSkills,
|
||||||
|
isLoading: viewModel.isLoadingArchive,
|
||||||
|
onRestore: { name in
|
||||||
|
Task { await viewModel.restore(name) }
|
||||||
|
},
|
||||||
|
onPruneAll: {
|
||||||
|
Task { await viewModel.planPrune() }
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
if let report = viewModel.lastReportMarkdown {
|
if let report = viewModel.lastReportMarkdown {
|
||||||
lastReportSection(markdown: report)
|
lastReportSection(markdown: report)
|
||||||
}
|
}
|
||||||
@@ -71,10 +79,84 @@ struct CuratorView: View {
|
|||||||
.padding(ScarfSpace.s4)
|
.padding(ScarfSpace.s4)
|
||||||
}
|
}
|
||||||
.background(ScarfColor.backgroundPrimary)
|
.background(ScarfColor.backgroundPrimary)
|
||||||
.task { await viewModel.load() }
|
.task {
|
||||||
|
await viewModel.load()
|
||||||
|
if archiveAvailable {
|
||||||
|
await viewModel.loadArchive()
|
||||||
|
}
|
||||||
|
}
|
||||||
.sheet(isPresented: $showRestoreSheet) {
|
.sheet(isPresented: $showRestoreSheet) {
|
||||||
CuratorRestoreSheet(viewModel: viewModel)
|
CuratorRestoreSheet(viewModel: viewModel)
|
||||||
}
|
}
|
||||||
|
.sheet(
|
||||||
|
isPresented: Binding(
|
||||||
|
get: { viewModel.pruneSummary != nil },
|
||||||
|
set: { isShown in
|
||||||
|
if !isShown { viewModel.cancelPrune() }
|
||||||
|
}
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
if let summary = viewModel.pruneSummary {
|
||||||
|
CuratorPruneConfirmSheet(
|
||||||
|
summary: summary,
|
||||||
|
isPruning: viewModel.isPruning,
|
||||||
|
onConfirm: {
|
||||||
|
Task { await viewModel.confirmPrune() }
|
||||||
|
},
|
||||||
|
onCancel: {
|
||||||
|
viewModel.cancelPrune()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@ViewBuilder
|
||||||
|
private var headerActions: some View {
|
||||||
|
HStack(spacing: ScarfSpace.s2) {
|
||||||
|
if viewModel.isLoading {
|
||||||
|
ProgressView().controlSize(.small)
|
||||||
|
}
|
||||||
|
Button("Run Now") {
|
||||||
|
Task {
|
||||||
|
await viewModel.runNow(
|
||||||
|
synchronous: archiveAvailable,
|
||||||
|
timeout: 600
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.buttonStyle(ScarfPrimaryButton())
|
||||||
|
.disabled(viewModel.isLoading)
|
||||||
|
.help(archiveAvailable
|
||||||
|
? "Curator runs synchronously on Hermes v0.13+. Usually 10–90s."
|
||||||
|
: "Trigger a curator run. Returns immediately on pre-v0.13 hosts.")
|
||||||
|
|
||||||
|
Menu {
|
||||||
|
switch viewModel.status.state {
|
||||||
|
case .paused:
|
||||||
|
Button("Resume") { Task { await viewModel.resume() } }
|
||||||
|
case .enabled:
|
||||||
|
Button("Pause") { Task { await viewModel.pause() } }
|
||||||
|
default:
|
||||||
|
EmptyView()
|
||||||
|
}
|
||||||
|
|
||||||
|
if archiveAvailable {
|
||||||
|
Divider()
|
||||||
|
Button("Prune Archived…", role: .destructive) {
|
||||||
|
Task { await viewModel.planPrune() }
|
||||||
|
}
|
||||||
|
.disabled(viewModel.archivedSkills.isEmpty && !viewModel.isLoadingArchive)
|
||||||
|
} else {
|
||||||
|
Button("Restore Archived…") {
|
||||||
|
showRestoreSheet = true
|
||||||
|
}
|
||||||
|
.disabled(viewModel.status.archivedSkills == 0)
|
||||||
|
}
|
||||||
|
} label: {
|
||||||
|
Image(systemName: "ellipsis.circle")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var statusSummary: some View {
|
private var statusSummary: some View {
|
||||||
@@ -206,6 +288,10 @@ struct CuratorView: View {
|
|||||||
}
|
}
|
||||||
.buttonStyle(.plain)
|
.buttonStyle(.plain)
|
||||||
.help(viewModel.status.pinnedNames.contains(row.name) ? "Pinned" : "Pin skill")
|
.help(viewModel.status.pinnedNames.contains(row.name) ? "Pinned" : "Pin skill")
|
||||||
|
|
||||||
|
if archiveAvailable {
|
||||||
|
archiveButton(for: row.name)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.padding(.vertical, 2)
|
.padding(.vertical, 2)
|
||||||
}
|
}
|
||||||
@@ -213,6 +299,25 @@ struct CuratorView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ViewBuilder
|
||||||
|
private func archiveButton(for name: String) -> some View {
|
||||||
|
if viewModel.pendingArchiveName == name {
|
||||||
|
ProgressView()
|
||||||
|
.controlSize(.small)
|
||||||
|
.frame(width: 14, height: 14)
|
||||||
|
} else {
|
||||||
|
Button {
|
||||||
|
Task { await viewModel.archive(name) }
|
||||||
|
} label: {
|
||||||
|
Image(systemName: "archivebox")
|
||||||
|
.font(.system(size: 12))
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.help("Archive (move out of active set)")
|
||||||
|
.disabled(viewModel.pendingArchiveName != nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private func counterChip(label: String, value: Int) -> some View {
|
private func counterChip(label: String, value: Int) -> some View {
|
||||||
Text("\(label) \(value)")
|
Text("\(label) \(value)")
|
||||||
.font(ScarfFont.monoSmall)
|
.font(ScarfFont.monoSmall)
|
||||||
@@ -277,6 +382,35 @@ struct CuratorView: View {
|
|||||||
.background(ScarfColor.accentTint)
|
.background(ScarfColor.accentTint)
|
||||||
.clipShape(RoundedRectangle(cornerRadius: ScarfRadius.md))
|
.clipShape(RoundedRectangle(cornerRadius: ScarfRadius.md))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Inline yellow banner for CLI failures. Non-blocking — sits above
|
||||||
|
/// the status summary and dismisses with the "x" so users can keep
|
||||||
|
/// interacting with the leaderboard. Mirrors the pattern in
|
||||||
|
/// KanbanBoardView.
|
||||||
|
private func errorBanner(_ message: String) -> some View {
|
||||||
|
HStack(alignment: .top, spacing: ScarfSpace.s2) {
|
||||||
|
Image(systemName: "exclamationmark.triangle.fill")
|
||||||
|
.foregroundStyle(ScarfColor.warning)
|
||||||
|
Text(message)
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundPrimary)
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
Button {
|
||||||
|
viewModel.dismissError()
|
||||||
|
} label: {
|
||||||
|
Image(systemName: "xmark.circle.fill")
|
||||||
|
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.help("Dismiss")
|
||||||
|
}
|
||||||
|
.padding(.horizontal, ScarfSpace.s3)
|
||||||
|
.padding(.vertical, ScarfSpace.s2)
|
||||||
|
.background(
|
||||||
|
RoundedRectangle(cornerRadius: ScarfRadius.md)
|
||||||
|
.fill(ScarfColor.warning.opacity(0.12))
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Simple `FlowLayout` for the pinned-skill chips. Custom layout
|
/// Simple `FlowLayout` for the pinned-skill chips. Custom layout
|
||||||
|
|||||||
@@ -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))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,9 @@ final class MCPServerEditorViewModel {
|
|||||||
var promptsEnabled: Bool
|
var promptsEnabled: Bool
|
||||||
var timeoutDraft: String
|
var timeoutDraft: String
|
||||||
var connectTimeoutDraft: String
|
var connectTimeoutDraft: String
|
||||||
|
/// SSE-only — renders as a third numeric on `.sse` servers. Empty string
|
||||||
|
/// means "use Hermes default" (writer drops the scalar).
|
||||||
|
var sseReadTimeoutDraft: String
|
||||||
var showSecrets: Bool = false
|
var showSecrets: Bool = false
|
||||||
var isSaving: Bool = false
|
var isSaving: Bool = false
|
||||||
var saveError: String?
|
var saveError: String?
|
||||||
@@ -37,6 +40,7 @@ final class MCPServerEditorViewModel {
|
|||||||
self.promptsEnabled = server.promptsEnabled
|
self.promptsEnabled = server.promptsEnabled
|
||||||
self.timeoutDraft = server.timeout.map { String($0) } ?? ""
|
self.timeoutDraft = server.timeout.map { String($0) } ?? ""
|
||||||
self.connectTimeoutDraft = server.connectTimeout.map { String($0) } ?? ""
|
self.connectTimeoutDraft = server.connectTimeout.map { String($0) } ?? ""
|
||||||
|
self.sseReadTimeoutDraft = server.sseReadTimeout.map { String($0) } ?? ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func appendEnvRow() {
|
func appendEnvRow() {
|
||||||
@@ -69,6 +73,8 @@ final class MCPServerEditorViewModel {
|
|||||||
let exclude = excludeDraft.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
|
let exclude = excludeDraft.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
|
||||||
let timeoutValue = Int(timeoutDraft.trimmingCharacters(in: .whitespaces))
|
let timeoutValue = Int(timeoutDraft.trimmingCharacters(in: .whitespaces))
|
||||||
let connectValue = Int(connectTimeoutDraft.trimmingCharacters(in: .whitespaces))
|
let connectValue = Int(connectTimeoutDraft.trimmingCharacters(in: .whitespaces))
|
||||||
|
let trimmedSSE = sseReadTimeoutDraft.trimmingCharacters(in: .whitespaces)
|
||||||
|
let sseTimeoutValue: Int? = trimmedSSE.isEmpty ? nil : Int(trimmedSSE)
|
||||||
|
|
||||||
let service = fileService
|
let service = fileService
|
||||||
let transport = server.transport
|
let transport = server.transport
|
||||||
@@ -87,6 +93,11 @@ final class MCPServerEditorViewModel {
|
|||||||
if !service.setMCPServerEnv(name: name, env: envMap) { ok = false }
|
if !service.setMCPServerEnv(name: name, env: envMap) { ok = false }
|
||||||
case .http:
|
case .http:
|
||||||
if !service.setMCPServerHeaders(name: name, headers: headerMap) { ok = false }
|
if !service.setMCPServerHeaders(name: name, headers: headerMap) { ok = false }
|
||||||
|
case .sse:
|
||||||
|
// SSE servers carry headers like .http does, plus an
|
||||||
|
// optional sse_read_timeout written below.
|
||||||
|
if !service.setMCPServerHeaders(name: name, headers: headerMap) { ok = false }
|
||||||
|
if !service.setMCPServerSSETimeout(name: name, sseReadTimeout: sseTimeoutValue) { ok = false }
|
||||||
}
|
}
|
||||||
if !service.updateMCPToolFilters(
|
if !service.updateMCPToolFilters(
|
||||||
name: name,
|
name: name,
|
||||||
|
|||||||
@@ -42,6 +42,10 @@ final class MCPServersViewModel {
|
|||||||
filteredServers.filter { $0.transport == .http }
|
filteredServers.filter { $0.transport == .http }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var sseServers: [HermesMCPServer] {
|
||||||
|
filteredServers.filter { $0.transport == .sse }
|
||||||
|
}
|
||||||
|
|
||||||
var selectedServer: HermesMCPServer? {
|
var selectedServer: HermesMCPServer? {
|
||||||
guard let name = selectedServerName else { return nil }
|
guard let name = selectedServerName else { return nil }
|
||||||
return servers.first(where: { $0.name == name })
|
return servers.first(where: { $0.name == name })
|
||||||
@@ -167,6 +171,11 @@ final class MCPServersViewModel {
|
|||||||
url: preset.url ?? "",
|
url: preset.url ?? "",
|
||||||
auth: preset.auth
|
auth: preset.auth
|
||||||
)
|
)
|
||||||
|
case .sse:
|
||||||
|
// No SSE-transport presets ship today; the preset picker
|
||||||
|
// only surfaces stdio/http servers. Treat as a no-op
|
||||||
|
// failure if a preset somehow declares .sse.
|
||||||
|
addResult = (exitCode: 1, output: "SSE-transport presets are not supported.")
|
||||||
}
|
}
|
||||||
guard addResult.exitCode == 0 else {
|
guard addResult.exitCode == 0 else {
|
||||||
await MainActor.run {
|
await MainActor.run {
|
||||||
@@ -196,6 +205,11 @@ final class MCPServersViewModel {
|
|||||||
result = fileService.addMCPServerStdio(name: name, command: command, args: args)
|
result = fileService.addMCPServerStdio(name: name, command: command, args: args)
|
||||||
case .http:
|
case .http:
|
||||||
result = fileService.addMCPServerHTTP(name: name, url: url, auth: auth)
|
result = fileService.addMCPServerHTTP(name: name, url: url, auth: auth)
|
||||||
|
case .sse:
|
||||||
|
// Routed through addCustomSSE; this branch is unreachable from
|
||||||
|
// the add-server form (which dispatches per-transport in submit())
|
||||||
|
// but kept so the switch is exhaustive without `@unknown default`.
|
||||||
|
result = (exitCode: 1, output: "SSE servers must be added via addCustomSSE.")
|
||||||
}
|
}
|
||||||
await MainActor.run {
|
await MainActor.run {
|
||||||
if result.exitCode == 0 {
|
if result.exitCode == 0 {
|
||||||
@@ -211,6 +225,28 @@ final class MCPServersViewModel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// v0.13+ SSE-transport server creation. Caller is responsible for
|
||||||
|
/// capability-gating; the form filters `.sse` out of `availableTransports`
|
||||||
|
/// when `hasMCPSSETransport` is false, so this method is unreachable
|
||||||
|
/// from the UI on pre-v0.13 hosts.
|
||||||
|
func addCustomSSE(name: String, url: String, sseReadTimeout: Int?) {
|
||||||
|
let fileService = self.fileService
|
||||||
|
Task.detached {
|
||||||
|
let result = fileService.addMCPServerSSE(name: name, url: url, sseReadTimeout: sseReadTimeout)
|
||||||
|
await MainActor.run {
|
||||||
|
if result.exitCode == 0 {
|
||||||
|
self.flashStatus("Added \(name)")
|
||||||
|
self.load()
|
||||||
|
self.selectedServerName = name
|
||||||
|
self.showRestartBanner = true
|
||||||
|
self.showAddCustom = false
|
||||||
|
} else {
|
||||||
|
self.activeError = "Add failed: \(result.output)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func restartGateway() {
|
func restartGateway() {
|
||||||
let fileService = self.fileService
|
let fileService = self.fileService
|
||||||
Task.detached {
|
Task.detached {
|
||||||
|
|||||||
@@ -6,12 +6,26 @@ struct MCPServerAddCustomView: View {
|
|||||||
let viewModel: MCPServersViewModel
|
let viewModel: MCPServersViewModel
|
||||||
|
|
||||||
@Environment(\.dismiss) private var dismiss
|
@Environment(\.dismiss) private var dismiss
|
||||||
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
@State private var name: String = ""
|
@State private var name: String = ""
|
||||||
@State private var transport: MCPTransport = .stdio
|
@State private var transport: MCPTransport = .stdio
|
||||||
@State private var command: String = "npx"
|
@State private var command: String = "npx"
|
||||||
@State private var argsText: String = ""
|
@State private var argsText: String = ""
|
||||||
@State private var url: String = ""
|
@State private var url: String = ""
|
||||||
@State private var auth: String = "none"
|
@State private var auth: String = "none"
|
||||||
|
@State private var sseReadTimeout: String = ""
|
||||||
|
|
||||||
|
/// `.sse` is a v0.13+ surface; pre-v0.13 hosts only see stdio + http.
|
||||||
|
/// Iterating `MCPTransport.allCases` directly would render the SSE
|
||||||
|
/// segment unconditionally and Hermes would reject the resulting CLI
|
||||||
|
/// invocation at argparse time.
|
||||||
|
private var availableTransports: [MCPTransport] {
|
||||||
|
var t: [MCPTransport] = [.stdio, .http]
|
||||||
|
if capabilitiesStore?.capabilities.hasMCPSSETransport ?? false {
|
||||||
|
t.append(.sse)
|
||||||
|
}
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(spacing: 0) {
|
VStack(spacing: 0) {
|
||||||
@@ -44,17 +58,20 @@ struct MCPServerAddCustomView: View {
|
|||||||
}
|
}
|
||||||
sectionBox(title: "Transport") {
|
sectionBox(title: "Transport") {
|
||||||
Picker("", selection: $transport) {
|
Picker("", selection: $transport) {
|
||||||
ForEach(MCPTransport.allCases) { t in
|
ForEach(availableTransports) { t in
|
||||||
Text(t.displayName).tag(t)
|
Text(t.displayName).tag(t)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.pickerStyle(.segmented)
|
.pickerStyle(.segmented)
|
||||||
.labelsHidden()
|
.labelsHidden()
|
||||||
}
|
}
|
||||||
if transport == .stdio {
|
switch transport {
|
||||||
|
case .stdio:
|
||||||
stdioSection
|
stdioSection
|
||||||
} else {
|
case .http:
|
||||||
httpSection
|
httpSection
|
||||||
|
case .sse:
|
||||||
|
sseSection
|
||||||
}
|
}
|
||||||
Text("Env vars, headers, and tool filters can be edited after the server is added.")
|
Text("Env vars, headers, and tool filters can be edited after the server is added.")
|
||||||
.font(.caption)
|
.font(.caption)
|
||||||
@@ -112,6 +129,28 @@ struct MCPServerAddCustomView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private var sseSection: some View {
|
||||||
|
sectionBox(title: "Endpoint (SSE)") {
|
||||||
|
VStack(alignment: .leading, spacing: 8) {
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
Text("URL").font(.caption.bold())
|
||||||
|
TextField("https://.../sse", text: $url)
|
||||||
|
.textFieldStyle(.roundedBorder)
|
||||||
|
.font(.system(.body, design: .monospaced))
|
||||||
|
}
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
Text("SSE Read Timeout (seconds)").font(.caption.bold())
|
||||||
|
TextField("default 300", text: $sseReadTimeout)
|
||||||
|
.textFieldStyle(.roundedBorder)
|
||||||
|
.frame(maxWidth: 140)
|
||||||
|
Text("Hermes-side keepalive interval. Leave blank to use the default.")
|
||||||
|
.font(.caption2)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private var canSubmit: Bool {
|
private var canSubmit: Bool {
|
||||||
let trimmedName = name.trimmingCharacters(in: .whitespaces)
|
let trimmedName = name.trimmingCharacters(in: .whitespaces)
|
||||||
guard !trimmedName.isEmpty else { return false }
|
guard !trimmedName.isEmpty else { return false }
|
||||||
@@ -120,6 +159,8 @@ struct MCPServerAddCustomView: View {
|
|||||||
return !command.trimmingCharacters(in: .whitespaces).isEmpty
|
return !command.trimmingCharacters(in: .whitespaces).isEmpty
|
||||||
case .http:
|
case .http:
|
||||||
return !url.trimmingCharacters(in: .whitespaces).isEmpty
|
return !url.trimmingCharacters(in: .whitespaces).isEmpty
|
||||||
|
case .sse:
|
||||||
|
return !url.trimmingCharacters(in: .whitespaces).isEmpty
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,6 +171,8 @@ struct MCPServerAddCustomView: View {
|
|||||||
.map { $0.trimmingCharacters(in: .whitespaces) }
|
.map { $0.trimmingCharacters(in: .whitespaces) }
|
||||||
.filter { !$0.isEmpty }
|
.filter { !$0.isEmpty }
|
||||||
let resolvedAuth: String? = (auth == "none") ? nil : auth
|
let resolvedAuth: String? = (auth == "none") ? nil : auth
|
||||||
|
switch transport {
|
||||||
|
case .stdio, .http:
|
||||||
viewModel.addCustom(
|
viewModel.addCustom(
|
||||||
name: trimmedName,
|
name: trimmedName,
|
||||||
transport: transport,
|
transport: transport,
|
||||||
@@ -138,6 +181,15 @@ struct MCPServerAddCustomView: View {
|
|||||||
url: url.trimmingCharacters(in: .whitespaces),
|
url: url.trimmingCharacters(in: .whitespaces),
|
||||||
auth: resolvedAuth
|
auth: resolvedAuth
|
||||||
)
|
)
|
||||||
|
case .sse:
|
||||||
|
let trimmedTimeout = sseReadTimeout.trimmingCharacters(in: .whitespaces)
|
||||||
|
let parsedTimeout: Int? = trimmedTimeout.isEmpty ? nil : Int(trimmedTimeout)
|
||||||
|
viewModel.addCustomSSE(
|
||||||
|
name: trimmedName,
|
||||||
|
url: url.trimmingCharacters(in: .whitespaces),
|
||||||
|
sseReadTimeout: parsedTimeout
|
||||||
|
)
|
||||||
|
}
|
||||||
dismiss()
|
dismiss()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -127,6 +127,11 @@ struct MCPServerDetailView: View {
|
|||||||
if let auth = server.auth, !auth.isEmpty {
|
if let auth = server.auth, !auth.isEmpty {
|
||||||
summaryRow(label: "Auth", value: auth)
|
summaryRow(label: "Auth", value: auth)
|
||||||
}
|
}
|
||||||
|
case .sse:
|
||||||
|
summaryRow(label: "URL", value: server.url ?? "—")
|
||||||
|
if let timeout = server.sseReadTimeout {
|
||||||
|
summaryRow(label: "Read TO", value: "\(timeout)s")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.padding(ScarfSpace.s3)
|
.padding(ScarfSpace.s3)
|
||||||
|
|||||||
@@ -186,6 +186,16 @@ struct MCPServerEditorView: View {
|
|||||||
.textFieldStyle(.roundedBorder)
|
.textFieldStyle(.roundedBorder)
|
||||||
.frame(maxWidth: 140)
|
.frame(maxWidth: 140)
|
||||||
}
|
}
|
||||||
|
if viewModel.server.transport == .sse {
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
Text("SSE read timeout")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
TextField("default 300", text: $viewModel.sseReadTimeoutDraft)
|
||||||
|
.textFieldStyle(.roundedBorder)
|
||||||
|
.frame(maxWidth: 140)
|
||||||
|
}
|
||||||
|
}
|
||||||
Spacer()
|
Spacer()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -132,6 +132,14 @@ struct MCPServersView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if !viewModel.sseServers.isEmpty {
|
||||||
|
Section("Remote (SSE)") {
|
||||||
|
ForEach(viewModel.sseServers) { server in
|
||||||
|
serverRow(server)
|
||||||
|
.tag(server.name as String?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if viewModel.servers.isEmpty && !viewModel.isLoading {
|
if viewModel.servers.isEmpty && !viewModel.isLoading {
|
||||||
Section {
|
Section {
|
||||||
Text("No servers configured yet")
|
Text("No servers configured yet")
|
||||||
|
|||||||
+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")
|
||||||
|
|||||||
@@ -112,10 +112,17 @@ final class ProfilesViewModel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func create(name: String, cloneConfig: Bool, cloneAll: Bool) {
|
func create(name: String, cloneConfig: Bool, cloneAll: Bool, noSkills: Bool = false) {
|
||||||
var args = ["profile", "create", name]
|
var args = ["profile", "create", name]
|
||||||
if cloneAll { args.append("--clone-all") }
|
if cloneAll { args.append("--clone-all") }
|
||||||
else if cloneConfig { args.append("--clone") }
|
else if cloneConfig { args.append("--clone") }
|
||||||
|
// v0.13+: Empty-profile creation. The wire is independent of
|
||||||
|
// --clone / --clone-all per the v0.13 release notes — the user
|
||||||
|
// can stack `--clone --no-skills` to clone config but skip
|
||||||
|
// skills, which is a plausible workflow. The UI still disables
|
||||||
|
// the toggle under --clone-all (Decision H, see ProfilesView)
|
||||||
|
// but the wire is permissive.
|
||||||
|
if noSkills { args.append("--no-skills") }
|
||||||
runAndReload(args, success: "Profile '\(name)' created")
|
runAndReload(args, success: "Profile '\(name)' created")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,12 @@ struct ProfilesView: View {
|
|||||||
@State private var createName = ""
|
@State private var createName = ""
|
||||||
@State private var createCloneConfig = true
|
@State private var createCloneConfig = true
|
||||||
@State private var createCloneAll = false
|
@State private var createCloneAll = false
|
||||||
|
/// v0.13+ `--no-skills` toggle. Mutually exclusive with `--clone-all`
|
||||||
|
/// at the UX layer (Decision H from the WS-7 plan): a full clone
|
||||||
|
/// copies skills wholesale — `--no-skills` would be a contradiction.
|
||||||
|
@State private var createNoSkills = false
|
||||||
@State private var showRename = false
|
@State private var showRename = false
|
||||||
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
|
||||||
init(context: ServerContext) {
|
init(context: ServerContext) {
|
||||||
_viewModel = State(initialValue: ProfilesViewModel(context: context))
|
_viewModel = State(initialValue: ProfilesViewModel(context: context))
|
||||||
@@ -123,7 +128,7 @@ struct ProfilesView: View {
|
|||||||
}
|
}
|
||||||
Spacer()
|
Spacer()
|
||||||
Button {
|
Button {
|
||||||
createName = ""; createCloneConfig = true; createCloneAll = false
|
createName = ""; createCloneConfig = true; createCloneAll = false; createNoSkills = false
|
||||||
showCreate = true
|
showCreate = true
|
||||||
} label: {
|
} label: {
|
||||||
Label("Create", systemImage: "plus")
|
Label("Create", systemImage: "plus")
|
||||||
@@ -300,11 +305,31 @@ struct ProfilesView: View {
|
|||||||
Toggle("Clone config, .env, SOUL.md from active profile", isOn: $createCloneConfig)
|
Toggle("Clone config, .env, SOUL.md from active profile", isOn: $createCloneConfig)
|
||||||
.disabled(createCloneAll)
|
.disabled(createCloneAll)
|
||||||
Toggle("Full copy of active profile (all state)", isOn: $createCloneAll)
|
Toggle("Full copy of active profile (all state)", isOn: $createCloneAll)
|
||||||
|
// TODO(WS-7-Q8): Decision H — disable --no-skills when --clone-all
|
||||||
|
// is on. A full clone copies skills wholesale; --no-skills would
|
||||||
|
// be a contradiction. Verify Hermes's behaviour with both flags
|
||||||
|
// (argparse mutual exclusion vs. last-flag-wins vs. clone-but-
|
||||||
|
// skip-skills) and relax the disabled state if Hermes does
|
||||||
|
// something useful with the combination.
|
||||||
|
if capabilitiesStore?.capabilities.hasProfileNoSkills ?? false {
|
||||||
|
Toggle("Empty profile (no skills)", isOn: $createNoSkills)
|
||||||
|
.disabled(createCloneAll)
|
||||||
|
}
|
||||||
HStack {
|
HStack {
|
||||||
Spacer()
|
Spacer()
|
||||||
Button("Cancel") { showCreate = false }
|
Button("Cancel") { showCreate = false }
|
||||||
Button("Create") {
|
Button("Create") {
|
||||||
viewModel.create(name: createName, cloneConfig: createCloneConfig, cloneAll: createCloneAll)
|
viewModel.create(
|
||||||
|
name: createName,
|
||||||
|
cloneConfig: createCloneConfig,
|
||||||
|
cloneAll: createCloneAll,
|
||||||
|
// Defensive: if the toggle isn't visible (pre-v0.13)
|
||||||
|
// the state is always `false`, but read it through
|
||||||
|
// the capability gate anyway so a stale state value
|
||||||
|
// can't sneak `--no-skills` to a CLI that doesn't
|
||||||
|
// know it.
|
||||||
|
noSkills: (capabilitiesStore?.capabilities.hasProfileNoSkills ?? false) ? createNoSkills : false
|
||||||
|
)
|
||||||
showCreate = false
|
showCreate = false
|
||||||
}
|
}
|
||||||
.buttonStyle(.borderedProminent)
|
.buttonStyle(.borderedProminent)
|
||||||
|
|||||||
@@ -29,8 +29,31 @@ final class SettingsViewModel {
|
|||||||
// that no-ops on older hosts is low compared to gating overhead.
|
// that no-ops on older hosts is low compared to gating overhead.
|
||||||
var terminalBackends = ["local", "docker", "singularity", "modal", "daytona", "ssh", "vercel"]
|
var terminalBackends = ["local", "docker", "singularity", "modal", "daytona", "ssh", "vercel"]
|
||||||
var browserBackends = ["browseruse", "firecrawl", "local"]
|
var browserBackends = ["browseruse", "firecrawl", "local"]
|
||||||
var ttsProviders = ["edge", "elevenlabs", "openai", "minimax", "mistral", "neutts", "piper"]
|
// v0.13: `xai` joins the TTS provider list. xAI shipped TTS earlier
|
||||||
|
// (v0.12) but the v0.13 add-on is custom voice cloning — see
|
||||||
|
// `HermesCapabilities.hasXAIVoiceCloning` and the badge in VoiceTab.
|
||||||
|
// The provider option itself is ungated so pre-v0.13 hosts with xAI
|
||||||
|
// keys can still pick it.
|
||||||
|
var ttsProviders = ["edge", "elevenlabs", "openai", "minimax", "mistral", "neutts", "piper", "xai"]
|
||||||
var sttProviders = ["local", "groq", "openai", "mistral"]
|
var sttProviders = ["local", "groq", "openai", "mistral"]
|
||||||
|
/// Static-message translation languages honored by Hermes v0.13's
|
||||||
|
/// `display.language` key. The first row's empty value writes no
|
||||||
|
/// key — equivalent to "Hermes default" — while explicit `en` writes
|
||||||
|
/// the code so users who care about determinism can pin it. Keep the
|
||||||
|
/// label list in sync with the Hermes v0.13 release notes; new
|
||||||
|
/// languages should be appended in alphabetical order by display
|
||||||
|
/// label so the picker stays scannable.
|
||||||
|
var displayLanguages: [(code: String, label: String)] = [
|
||||||
|
("", "English (default)"),
|
||||||
|
("en", "English"),
|
||||||
|
("zh", "中文 (Chinese)"),
|
||||||
|
("ja", "日本語 (Japanese)"),
|
||||||
|
("de", "Deutsch (German)"),
|
||||||
|
("es", "Español (Spanish)"),
|
||||||
|
("fr", "Français (French)"),
|
||||||
|
("uk", "Українська (Ukrainian)"),
|
||||||
|
("tr", "Türkçe (Turkish)"),
|
||||||
|
]
|
||||||
var memoryProviders = ["", "honcho", "openviking", "mem0", "hindsight", "holographic", "retaindb", "byterover", "supermemory"]
|
var memoryProviders = ["", "honcho", "openviking", "mem0", "hindsight", "holographic", "retaindb", "byterover", "supermemory"]
|
||||||
var saveMessage: String?
|
var saveMessage: String?
|
||||||
var isLoading = false
|
var isLoading = false
|
||||||
@@ -104,6 +127,10 @@ final class SettingsViewModel {
|
|||||||
func setToolProgressCommand(_ value: Bool) { setSetting("display.tool_progress_command", value: value ? "true" : "false") }
|
func setToolProgressCommand(_ value: Bool) { setSetting("display.tool_progress_command", value: value ? "true" : "false") }
|
||||||
func setToolPreviewLength(_ value: Int) { setSetting("display.tool_preview_length", value: String(value)) }
|
func setToolPreviewLength(_ value: Int) { setSetting("display.tool_preview_length", value: String(value)) }
|
||||||
func setBusyInputMode(_ value: String) { setSetting("display.busy_input_mode", value: value) }
|
func setBusyInputMode(_ value: String) { setSetting("display.busy_input_mode", value: value) }
|
||||||
|
/// v0.13: `display.language` for static-message translations. Empty
|
||||||
|
/// string writes "" via `hermes config set` which Hermes treats as
|
||||||
|
/// "use default"; explicit codes pin the language.
|
||||||
|
func setDisplayLanguage(_ value: String) { setSetting("display.language", value: value) }
|
||||||
|
|
||||||
// MARK: - Agent
|
// MARK: - Agent
|
||||||
|
|
||||||
@@ -143,6 +170,16 @@ final class SettingsViewModel {
|
|||||||
func setBrowserAllowPrivateURLs(_ value: Bool) { setSetting("browser.allow_private_urls", value: value ? "true" : "false") }
|
func setBrowserAllowPrivateURLs(_ value: Bool) { setSetting("browser.allow_private_urls", value: value ? "true" : "false") }
|
||||||
func setCamofoxManagedPersistence(_ value: Bool) { setSetting("browser.camofox.managed_persistence", value: value ? "true" : "false") }
|
func setCamofoxManagedPersistence(_ value: Bool) { setSetting("browser.camofox.managed_persistence", value: value ? "true" : "false") }
|
||||||
|
|
||||||
|
// MARK: - Web Tools
|
||||||
|
|
||||||
|
/// Pre-v0.13 combined backend. Pre-v0.13 hosts read this; v0.13+
|
||||||
|
/// hosts read it for back-compat but the WebToolsTab gates writes
|
||||||
|
/// on `hasWebToolsBackendSplit` so the tab only writes the split
|
||||||
|
/// keys on v0.13.
|
||||||
|
func setWebToolsBackend(_ value: String) { setSetting("web_tools.backend", value: value) }
|
||||||
|
func setWebToolsSearchBackend(_ value: String) { setSetting("web_tools.search.backend", value: value) }
|
||||||
|
func setWebToolsExtractBackend(_ value: String) { setSetting("web_tools.extract.backend", value: value) }
|
||||||
|
|
||||||
// MARK: - Voice / TTS / STT
|
// MARK: - Voice / TTS / STT
|
||||||
|
|
||||||
func setAutoTTS(_ value: Bool) { setSetting("voice.auto_tts", value: value ? "true" : "false") }
|
func setAutoTTS(_ value: Bool) { setSetting("voice.auto_tts", value: value ? "true" : "false") }
|
||||||
@@ -158,6 +195,10 @@ final class SettingsViewModel {
|
|||||||
func setTTSOpenAIVoice(_ value: String) { setSetting("tts.openai.voice", value: value) }
|
func setTTSOpenAIVoice(_ value: String) { setSetting("tts.openai.voice", value: value) }
|
||||||
func setTTSNeuTTSModel(_ value: String) { setSetting("tts.neutts.model", value: value) }
|
func setTTSNeuTTSModel(_ value: String) { setSetting("tts.neutts.model", value: value) }
|
||||||
func setTTSNeuTTSDevice(_ value: String) { setSetting("tts.neutts.device", value: value) }
|
func setTTSNeuTTSDevice(_ value: String) { setSetting("tts.neutts.device", value: value) }
|
||||||
|
// v0.13: xAI TTS / Custom Voices. TODO(WS-8-Q2): grep-verify key
|
||||||
|
// names against `~/.hermes/hermes-agent/hermes_cli/voice/tts.py`.
|
||||||
|
func setTTSXAIVoiceID(_ value: String) { setSetting("tts.xai.voice_id", value: value) }
|
||||||
|
func setTTSXAIModel(_ value: String) { setSetting("tts.xai.model", value: value) }
|
||||||
func setSTTEnabled(_ value: Bool) { setSetting("stt.enabled", value: value ? "true" : "false") }
|
func setSTTEnabled(_ value: Bool) { setSetting("stt.enabled", value: value ? "true" : "false") }
|
||||||
func setSTTProvider(_ value: String) { setSetting("stt.provider", value: value) }
|
func setSTTProvider(_ value: String) { setSetting("stt.provider", value: value) }
|
||||||
func setSTTLocalModel(_ value: String) { setSetting("stt.local.model", value: value) }
|
func setSTTLocalModel(_ value: String) { setSetting("stt.local.model", value: value) }
|
||||||
@@ -195,6 +236,24 @@ final class SettingsViewModel {
|
|||||||
setSetting("auxiliary.\(task).timeout", value: String(value))
|
setSetting("auxiliary.\(task).timeout", value: String(value))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Image generation (v0.13+)
|
||||||
|
|
||||||
|
/// `image_gen.model` — overrides the per-provider default image
|
||||||
|
/// model (Hermes v0.13+). Empty string clears the override.
|
||||||
|
/// Capability-gated in `AuxiliaryTab` so pre-v0.13 hosts never
|
||||||
|
/// invoke this setter.
|
||||||
|
func setImageGenModel(_ value: String) { setSetting("image_gen.model", value: value) }
|
||||||
|
|
||||||
|
/// `openrouter.response_cache.enabled` — toggles OpenRouter
|
||||||
|
/// response caching for repeat prompts (Hermes v0.13+).
|
||||||
|
/// Capability-gated in `AuxiliaryTab` so pre-v0.13 hosts never
|
||||||
|
/// invoke this setter.
|
||||||
|
// TODO(WS-6-Q1): the YAML key path is provisional — keep in lockstep
|
||||||
|
// with `HermesConfig+YAML.swift`'s parser line.
|
||||||
|
func setOpenRouterResponseCache(_ value: Bool) {
|
||||||
|
setSetting("openrouter.response_cache.enabled", value: value ? "true" : "false")
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Security / Privacy
|
// MARK: - Security / Privacy
|
||||||
|
|
||||||
func setRedactSecrets(_ value: Bool) { setSetting("security.redact_secrets", value: value ? "true" : "false") }
|
func setRedactSecrets(_ value: Bool) { setSetting("security.redact_secrets", value: value ? "true" : "false") }
|
||||||
|
|||||||
@@ -152,8 +152,23 @@ struct PickerRow: View {
|
|||||||
let label: String
|
let label: String
|
||||||
let selection: String
|
let selection: String
|
||||||
let options: [String]
|
let options: [String]
|
||||||
|
let optionLabel: ((String) -> String)?
|
||||||
let onChange: (String) -> Void
|
let onChange: (String) -> Void
|
||||||
|
|
||||||
|
init(
|
||||||
|
label: String,
|
||||||
|
selection: String,
|
||||||
|
options: [String],
|
||||||
|
optionLabel: ((String) -> String)? = nil,
|
||||||
|
onChange: @escaping (String) -> Void
|
||||||
|
) {
|
||||||
|
self.label = label
|
||||||
|
self.selection = selection
|
||||||
|
self.options = options
|
||||||
|
self.optionLabel = optionLabel
|
||||||
|
self.onChange = onChange
|
||||||
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
HStack {
|
HStack {
|
||||||
SettingsRowLabel(label: label)
|
SettingsRowLabel(label: label)
|
||||||
@@ -162,7 +177,7 @@ struct PickerRow: View {
|
|||||||
set: { onChange($0) }
|
set: { onChange($0) }
|
||||||
)) {
|
)) {
|
||||||
ForEach(options, id: \.self) { option in
|
ForEach(options, id: \.self) { option in
|
||||||
Text(option.isEmpty ? "(none)" : option).tag(option)
|
Text(displayLabel(for: option)).tag(option)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.frame(maxWidth: 250)
|
.frame(maxWidth: 250)
|
||||||
@@ -170,6 +185,13 @@ struct PickerRow: View {
|
|||||||
}
|
}
|
||||||
.settingsRowChrome()
|
.settingsRowChrome()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private func displayLabel(for option: String) -> String {
|
||||||
|
if let mapper = optionLabel {
|
||||||
|
return mapper(option)
|
||||||
|
}
|
||||||
|
return option.isEmpty ? "(none)" : option
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ToggleRow: View {
|
struct ToggleRow: View {
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ struct SettingsView: View {
|
|||||||
case agent = "Agent"
|
case agent = "Agent"
|
||||||
case terminal = "Terminal"
|
case terminal = "Terminal"
|
||||||
case browser = "Browser"
|
case browser = "Browser"
|
||||||
|
case webTools = "Web Tools"
|
||||||
case voice = "Voice"
|
case voice = "Voice"
|
||||||
case memory = "Memory"
|
case memory = "Memory"
|
||||||
case auxiliary = "Aux Models"
|
case auxiliary = "Aux Models"
|
||||||
@@ -41,6 +42,7 @@ struct SettingsView: View {
|
|||||||
case .agent: return "Agent"
|
case .agent: return "Agent"
|
||||||
case .terminal: return "Terminal"
|
case .terminal: return "Terminal"
|
||||||
case .browser: return "Browser"
|
case .browser: return "Browser"
|
||||||
|
case .webTools: return "Web Tools"
|
||||||
case .voice: return "Voice"
|
case .voice: return "Voice"
|
||||||
case .memory: return "Memory"
|
case .memory: return "Memory"
|
||||||
case .auxiliary: return "Aux Models"
|
case .auxiliary: return "Aux Models"
|
||||||
@@ -56,6 +58,7 @@ struct SettingsView: View {
|
|||||||
case .agent: return "brain.head.profile"
|
case .agent: return "brain.head.profile"
|
||||||
case .terminal: return "terminal"
|
case .terminal: return "terminal"
|
||||||
case .browser: return "globe"
|
case .browser: return "globe"
|
||||||
|
case .webTools: return "globe.americas"
|
||||||
case .voice: return "mic"
|
case .voice: return "mic"
|
||||||
case .memory: return "memorychip"
|
case .memory: return "memorychip"
|
||||||
case .auxiliary: return "sparkles.rectangle.stack"
|
case .auxiliary: return "sparkles.rectangle.stack"
|
||||||
@@ -171,6 +174,7 @@ struct SettingsView: View {
|
|||||||
case .agent: AgentTab(viewModel: viewModel)
|
case .agent: AgentTab(viewModel: viewModel)
|
||||||
case .terminal: TerminalTab(viewModel: viewModel)
|
case .terminal: TerminalTab(viewModel: viewModel)
|
||||||
case .browser: BrowserTab(viewModel: viewModel)
|
case .browser: BrowserTab(viewModel: viewModel)
|
||||||
|
case .webTools: WebToolsTab(viewModel: viewModel)
|
||||||
case .voice: VoiceTab(viewModel: viewModel)
|
case .voice: VoiceTab(viewModel: viewModel)
|
||||||
case .memory: MemoryTab(viewModel: viewModel)
|
case .memory: MemoryTab(viewModel: viewModel)
|
||||||
case .auxiliary: AuxiliaryTab(viewModel: viewModel)
|
case .auxiliary: AuxiliaryTab(viewModel: viewModel)
|
||||||
|
|||||||
@@ -131,6 +131,8 @@ struct AdvancedTab: View {
|
|||||||
isOn: viewModel.config.redactionEnabled
|
isOn: viewModel.config.redactionEnabled
|
||||||
) { viewModel.setSetting("redaction.enabled", value: $0 ? "true" : "false") }
|
) { viewModel.setSetting("redaction.enabled", value: $0 ? "true" : "false") }
|
||||||
|
|
||||||
|
redactionDefaultsHint
|
||||||
|
|
||||||
ToggleRow(
|
ToggleRow(
|
||||||
label: "Runtime metadata footer",
|
label: "Runtime metadata footer",
|
||||||
isOn: viewModel.config.runtimeMetadataFooter
|
isOn: viewModel.config.runtimeMetadataFooter
|
||||||
@@ -138,6 +140,30 @@ struct AdvancedTab: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Inline hint below the redaction toggle. The server-side default
|
||||||
|
/// flipped from OFF (v0.12) to ON (v0.13), but Scarf's parser still
|
||||||
|
/// reads "absent key" as `false` — meaning a v0.13 host with no
|
||||||
|
/// explicit key in `config.yaml` shows the toggle OFF while the
|
||||||
|
/// agent treats redaction as ON. Hint copy disambiguates so users
|
||||||
|
/// can tell what's actually happening server-side.
|
||||||
|
@ViewBuilder
|
||||||
|
private var redactionDefaultsHint: some View {
|
||||||
|
let isV013 = capabilitiesStore?.capabilities.isV013OrLater ?? false
|
||||||
|
HStack {
|
||||||
|
Text("")
|
||||||
|
.font(.caption)
|
||||||
|
.frame(width: 160, alignment: .trailing)
|
||||||
|
Text(isV013
|
||||||
|
? "Recommended: ON. Hermes v0.13+ defaults to redacting secrets unless you opt out."
|
||||||
|
: "Default OFF in Hermes v0.12. Toggle ON to redact secrets in logs and shares.")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
Spacer()
|
||||||
|
}
|
||||||
|
.padding(.horizontal, 12)
|
||||||
|
.padding(.vertical, 4)
|
||||||
|
}
|
||||||
|
|
||||||
private var backupSection: some View {
|
private var backupSection: some View {
|
||||||
SettingsSection(title: "Backup & Restore", icon: "externaldrive") {
|
SettingsSection(title: "Backup & Restore", icon: "externaldrive") {
|
||||||
HStack {
|
HStack {
|
||||||
|
|||||||
@@ -139,6 +139,23 @@ struct AuxiliaryTab: View {
|
|||||||
auxRows(for: task.key)
|
auxRows(for: task.key)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// -- Hermes v0.13 additions ---------------------------------
|
||||||
|
// Image-gen model picker. Hermes v0.13 honors `image_gen.model`
|
||||||
|
// as a top-level YAML key; pre-v0.13 hosts ignore it silently.
|
||||||
|
// Hide the section on pre-v0.13 hosts to spare users a
|
||||||
|
// "I set this and nothing happened" trap.
|
||||||
|
if capabilitiesStore?.capabilities.hasImageGenModel ?? false {
|
||||||
|
SettingsSection(title: "Image Generation", icon: "photo") {
|
||||||
|
imageGenRow
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// OpenRouter response caching toggle (v0.13+). Same hide-on-
|
||||||
|
// pre-v0.13 rationale: the toggle no-ops on older Hermes hosts.
|
||||||
|
if capabilitiesStore?.capabilities.hasOpenRouterResponseCache ?? false {
|
||||||
|
SettingsSection(title: "OpenRouter", icon: "shippingbox") {
|
||||||
|
openRouterResponseCacheRow
|
||||||
|
}
|
||||||
|
}
|
||||||
// Unknown / unrecognised aux tasks present in config.yaml.
|
// Unknown / unrecognised aux tasks present in config.yaml.
|
||||||
// Shown only when at least one such key is present so the
|
// Shown only when at least one such key is present so the
|
||||||
// typical user with a clean config never sees this section.
|
// typical user with a clean config never sees this section.
|
||||||
@@ -225,6 +242,60 @@ struct AuxiliaryTab: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - v0.13 surfaces
|
||||||
|
|
||||||
|
/// Image-gen model picker — curated allowlist + free-form custom
|
||||||
|
/// entry. Capability-gated by the caller; this view assumes the
|
||||||
|
/// host honors `image_gen.model` (Hermes v0.13+).
|
||||||
|
@ViewBuilder
|
||||||
|
private var imageGenRow: some View {
|
||||||
|
let value = viewModel.config.imageGenModel
|
||||||
|
Picker("Model", selection: Binding(
|
||||||
|
get: { value },
|
||||||
|
set: { viewModel.setImageGenModel($0) }
|
||||||
|
)) {
|
||||||
|
Text("Provider default").tag("")
|
||||||
|
Divider()
|
||||||
|
ForEach(ModelCatalogService.imageGenModels) { model in
|
||||||
|
Text(model.display).tag(model.modelID)
|
||||||
|
}
|
||||||
|
// User has set a custom value not in the curated list;
|
||||||
|
// preserve it as a tagged option so the picker renders the
|
||||||
|
// actual selection rather than collapsing to "Provider
|
||||||
|
// default".
|
||||||
|
if !value.isEmpty
|
||||||
|
&& !ModelCatalogService.imageGenModels.contains(where: { $0.modelID == value }) {
|
||||||
|
Divider()
|
||||||
|
Text(value + " (custom)").tag(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.pickerStyle(.menu)
|
||||||
|
EditableTextField(label: "Custom model ID", value: value) { newValue in
|
||||||
|
viewModel.setImageGenModel(newValue.trimmingCharacters(in: .whitespaces))
|
||||||
|
}
|
||||||
|
Text("Used for image generation calls. Leave as Provider default unless your provider documents a specific model ID for image-gen.")
|
||||||
|
.font(.caption2)
|
||||||
|
.foregroundStyle(.tertiary)
|
||||||
|
.padding(.horizontal, 12)
|
||||||
|
.padding(.bottom, 4)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// OpenRouter response-caching toggle (Hermes v0.13+). Off by
|
||||||
|
/// default; surfaced for users with highly repeated prompts who
|
||||||
|
/// want OpenRouter to cache identical-prompt responses.
|
||||||
|
@ViewBuilder
|
||||||
|
private var openRouterResponseCacheRow: some View {
|
||||||
|
let isOn = viewModel.config.openrouterResponseCacheEnabled
|
||||||
|
ToggleRow(label: "Response caching", isOn: isOn) { newValue in
|
||||||
|
viewModel.setOpenRouterResponseCache(newValue)
|
||||||
|
}
|
||||||
|
Text("OpenRouter caches identical prompts within a session to reduce token costs. Off by default — enable when your workload has highly repeated prompts.")
|
||||||
|
.font(.caption2)
|
||||||
|
.foregroundStyle(.tertiary)
|
||||||
|
.padding(.horizontal, 12)
|
||||||
|
.padding(.bottom, 4)
|
||||||
|
}
|
||||||
|
|
||||||
private func auxModel(for key: String) -> AuxiliaryModel {
|
private func auxModel(for key: String) -> AuxiliaryModel {
|
||||||
switch key {
|
switch key {
|
||||||
case "vision": return viewModel.config.auxiliary.vision
|
case "vision": return viewModel.config.auxiliary.vision
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import ScarfCore
|
|||||||
struct GeneralTab: View {
|
struct GeneralTab: View {
|
||||||
@Bindable var viewModel: SettingsViewModel
|
@Bindable var viewModel: SettingsViewModel
|
||||||
@Environment(AppCoordinator.self) private var coordinator
|
@Environment(AppCoordinator.self) private var coordinator
|
||||||
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
SettingsSection(title: "Model", icon: "cpu") {
|
SettingsSection(title: "Model", icon: "cpu") {
|
||||||
@@ -39,6 +40,20 @@ struct GeneralTab: View {
|
|||||||
|
|
||||||
SettingsSection(title: "Locale", icon: "globe.americas") {
|
SettingsSection(title: "Locale", icon: "globe.americas") {
|
||||||
EditableTextField(label: "Timezone (IANA)", value: viewModel.config.timezone) { viewModel.setTimezone($0) }
|
EditableTextField(label: "Timezone (IANA)", value: viewModel.config.timezone) { viewModel.setTimezone($0) }
|
||||||
|
// v0.13: `display.language` picker. Hidden on pre-v0.13 hosts
|
||||||
|
// because writing the key would no-op silently. Two "English"
|
||||||
|
// entries by design — empty string preserves "no key" semantics
|
||||||
|
// (Hermes-default), explicit `en` pins it.
|
||||||
|
if capabilitiesStore?.capabilities.hasDisplayLanguage == true {
|
||||||
|
PickerRow(
|
||||||
|
label: "Display language",
|
||||||
|
selection: viewModel.config.display.language,
|
||||||
|
options: viewModel.displayLanguages.map(\.code),
|
||||||
|
optionLabel: { code in
|
||||||
|
viewModel.displayLanguages.first { $0.code == code }?.label ?? code
|
||||||
|
}
|
||||||
|
) { viewModel.setDisplayLanguage($0) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
UpdatesSection()
|
UpdatesSection()
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
import ScarfCore
|
import ScarfCore
|
||||||
|
import ScarfDesign
|
||||||
|
|
||||||
/// Voice tab — push-to-talk + TTS + STT provider settings.
|
/// Voice tab — push-to-talk + TTS + STT provider settings.
|
||||||
struct VoiceTab: View {
|
struct VoiceTab: View {
|
||||||
@Bindable var viewModel: SettingsViewModel
|
@Bindable var viewModel: SettingsViewModel
|
||||||
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
SettingsSection(title: "Push-to-Talk", icon: "mic") {
|
SettingsSection(title: "Push-to-Talk", icon: "mic") {
|
||||||
@@ -28,6 +30,16 @@ struct VoiceTab: View {
|
|||||||
case "neutts":
|
case "neutts":
|
||||||
EditableTextField(label: "Model", value: viewModel.config.voice.ttsNeuTTSModel) { viewModel.setTTSNeuTTSModel($0) }
|
EditableTextField(label: "Model", value: viewModel.config.voice.ttsNeuTTSModel) { viewModel.setTTSNeuTTSModel($0) }
|
||||||
PickerRow(label: "Device", selection: viewModel.config.voice.ttsNeuTTSDevice, options: ["cpu", "cuda"]) { viewModel.setTTSNeuTTSDevice($0) }
|
PickerRow(label: "Device", selection: viewModel.config.voice.ttsNeuTTSDevice, options: ["cpu", "cuda"]) { viewModel.setTTSNeuTTSDevice($0) }
|
||||||
|
case "xai":
|
||||||
|
// v0.13: xAI TTS surface. Voice ID + Model are always
|
||||||
|
// visible (xAI TTS shipped earlier); the cloning-supported
|
||||||
|
// badge is gated on `hasXAIVoiceCloning` so pre-v0.13 hosts
|
||||||
|
// see the input rows but no cloning advertisement.
|
||||||
|
EditableTextField(label: "Voice ID", value: viewModel.config.voice.ttsXAIVoiceID) { viewModel.setTTSXAIVoiceID($0) }
|
||||||
|
EditableTextField(label: "Model", value: viewModel.config.voice.ttsXAIModel) { viewModel.setTTSXAIModel($0) }
|
||||||
|
if capabilitiesStore?.capabilities.hasXAIVoiceCloning == true {
|
||||||
|
xaiCloningBadge
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
EmptyView()
|
EmptyView()
|
||||||
}
|
}
|
||||||
@@ -49,4 +61,24 @@ struct VoiceTab: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Inline hint chip+caption shown below xAI's Voice ID + Model fields
|
||||||
|
/// on v0.13+. References `hermes voice` because Scarf doesn't manage
|
||||||
|
/// cloned voices in-app yet — the badge is discovery-only. Out-of-scope
|
||||||
|
/// for v2.8: an in-app cloned-voice manager (would be its own feature).
|
||||||
|
@ViewBuilder
|
||||||
|
private var xaiCloningBadge: some View {
|
||||||
|
HStack(alignment: .center, spacing: 8) {
|
||||||
|
Text("")
|
||||||
|
.font(.caption)
|
||||||
|
.frame(width: 160, alignment: .trailing)
|
||||||
|
ScarfBadge("Cloning supported", kind: .info)
|
||||||
|
Text("Manage cloned voices in your terminal: `hermes voice` (xAI subcommands).")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
Spacer()
|
||||||
|
}
|
||||||
|
.padding(.horizontal, 12)
|
||||||
|
.padding(.vertical, 4)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import SwiftUI
|
||||||
|
import ScarfCore
|
||||||
|
import ScarfDesign
|
||||||
|
|
||||||
|
/// Web Tools tab — search + extract backend pickers. Pre-v0.13 hosts
|
||||||
|
/// see a single "Combined backend" row writing to the legacy
|
||||||
|
/// `web_tools.backend` key. v0.13+ hosts see two rows writing to the
|
||||||
|
/// per-capability split keys (`web_tools.search.backend` +
|
||||||
|
/// `web_tools.extract.backend`); SearXNG appears in the search picker
|
||||||
|
/// only because Hermes registers it as a search-only backend.
|
||||||
|
struct WebToolsTab: View {
|
||||||
|
@Bindable var viewModel: SettingsViewModel
|
||||||
|
@Environment(\.hermesCapabilities) private var capabilitiesStore
|
||||||
|
|
||||||
|
private var split: Bool {
|
||||||
|
capabilitiesStore?.capabilities.hasWebToolsBackendSplit ?? false
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO(WS-7-Q6): Backend lists are curated inline based on the v0.13
|
||||||
|
// release notes ("SearXNG joined search-only"). The exact dispatch
|
||||||
|
// table lives in `~/.hermes/hermes-agent/hermes_cli/web_tools.py` —
|
||||||
|
// verify during integration. A wrong entry just produces a
|
||||||
|
// `hermes config set` failure on save (recoverable, not silent).
|
||||||
|
private static let searchBackends: [String] = [
|
||||||
|
"duckduckgo", "tavily", "brave", "exa", "you", "searxng"
|
||||||
|
]
|
||||||
|
private static let extractBackends: [String] = [
|
||||||
|
"reader", "browserless", "trafilatura", "firecrawl"
|
||||||
|
]
|
||||||
|
/// v0.12 combined-backend list — superset of the v0.13 search list
|
||||||
|
/// minus SearXNG (which only dispatches as search) plus the v0.13
|
||||||
|
/// extract-only entries that pre-v0.13 hosts handled under the
|
||||||
|
/// combined key.
|
||||||
|
private static let combinedBackends: [String] = [
|
||||||
|
"duckduckgo", "tavily", "brave", "exa", "you",
|
||||||
|
"reader", "browserless", "trafilatura", "firecrawl"
|
||||||
|
]
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
if split {
|
||||||
|
SettingsSection(title: "Web Tools", icon: "globe.americas") {
|
||||||
|
PickerRow(
|
||||||
|
label: "Search backend",
|
||||||
|
selection: viewModel.config.webToolsSearchBackend,
|
||||||
|
options: Self.searchBackends
|
||||||
|
) { viewModel.setWebToolsSearchBackend($0) }
|
||||||
|
PickerRow(
|
||||||
|
label: "Extract backend",
|
||||||
|
selection: viewModel.config.webToolsExtractBackend,
|
||||||
|
options: Self.extractBackends
|
||||||
|
) { viewModel.setWebToolsExtractBackend($0) }
|
||||||
|
}
|
||||||
|
Text("SearXNG joined v0.13 as a search-only backend. Backend-specific tuning (host URLs, API keys) lives in the raw YAML editor for now.")
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundMuted)
|
||||||
|
.padding(.horizontal, ScarfSpace.s4)
|
||||||
|
} else {
|
||||||
|
// TODO(WS-7-Q7): Pre-v0.13 hosts fall back to the legacy single
|
||||||
|
// backend. v0.13 may or may not honour `web_tools.backend` as a
|
||||||
|
// fallback when the split keys are absent — verify with Hermes
|
||||||
|
// and consider a one-time migration prompt in a follow-up if
|
||||||
|
// upgrading from v0.12 silently resets the user's backend.
|
||||||
|
SettingsSection(title: "Web Tools", icon: "globe.americas") {
|
||||||
|
PickerRow(
|
||||||
|
label: "Backend",
|
||||||
|
selection: viewModel.config.webToolsBackend,
|
||||||
|
options: Self.combinedBackends
|
||||||
|
) { viewModel.setWebToolsBackend($0) }
|
||||||
|
}
|
||||||
|
Text("Hermes v0.13 splits search and extract into separate backends. Update Hermes to access the per-capability picker.")
|
||||||
|
.scarfStyle(.caption)
|
||||||
|
.foregroundStyle(ScarfColor.foregroundFaint)
|
||||||
|
.padding(.horizontal, ScarfSpace.s4)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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