Compare commits

..

26 Commits

Author SHA1 Message Date
Alan Wizemann a8cdb3e663 feat(ios): v0.13 read-only catch-up — goal pill, queue chip, Kanban diagnostics, Curator archived, Platforms (WS-9)
Mirrors the v0.13 surfaces from WS-2 (Persistent Goals + ACP /queue),
WS-3 (Kanban diagnostics + hallucination gate), WS-4 (Curator archive),
and WS-5 (Google Chat platform + cross-platform allowlists + behavior
toggles) onto ScarfGo. Per Phase H precedent, every iOS surface is
strictly read-only — write verbs (Verify / Reject, /goal --clear, queue
send, allowlist editing, archive Restore / Prune) live on Mac in v2.8.0
and are deferred to v2.8.x.

Five iOS additions, all capability-gated so pre-v0.13 hosts see the
v2.7.5 layout unchanged:

1. Chat — goal pill ("Goal: <text>") and queue chip ("N queued") render
   inside `projectContextBar` whenever a project, goal, or queue is
   present. The bar is no longer project-only; goal/queue chips render
   even outside a project chat. Goal text scales with Dynamic Type
   (semantic `.subheadline`); the full untruncated text rides VoiceOver
   via the chip's accessibility label.
2. Kanban — `ScarfGoKanbanDetailSheet` gains a `retries: N` chip in the
   header `FlowLayout`, a yellow "Worker-created — verify on Mac" badge
   for `pending` hallucination state, a red "Auto-blocked" banner with
   the server-supplied `auto_blocked_reason`, and tappable diagnostics
   chip-lists (task-level + per-run) that present a new
   `DiagnosticDetailSheet` with kind / severity / message / timestamp.
   No Verify or Reject buttons; the badge copy points users to the Mac
   app.
3. Curator — `CuratorView` appends a read-only "Archived" section that
   loads via `viewModel.loadArchive()` on appear and pull-to-refresh.
   Per-row name + category badge + reason + archived-at + size; footer
   signposts users to the Mac app for Restore / Prune.
4. Settings → Platforms — adds a Google Chat status row (configured /
   not configured), busy-ack and restart-notification rows summarized
   across `gatewayPlatforms` (yes / no / mixed (N platforms)), and
   collapsed DisclosureGroups for allowed channels / chats / rooms with
   monospaced "platform: id" entries when expanded. No editor.
5. Settings — green "v0.13 features active" `ScarfBadge` above the
   quick-edits section when `caps.isV013OrLater`. Tap presents a new
   `V013FeaturesSheet` listing the six v0.13 surfaces with one-sentence
   summaries; the section footer is explicit that editing lives on Mac.

Implements WS-9 of Scarf v2.8.0 (Hermes v0.13.0 catch-up).
Plan: scarf/docs/v2.8/WS-9-ios-v0.13-plan.md (on coordination/v2.8.0-plans).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 19:25:16 +02:00
Alan Wizemann 441d11404f Merge remote-tracking branch 'origin/ws-8-ux-v0.13' into integration/v2.8.0
# Conflicts:
#	scarf/scarf/Features/Chat/Views/ChatTranscriptPane.swift
#	scarf/scarf/Features/Chat/Views/SessionInfoBar.swift
2026-05-09 19:12:15 +02:00
Alan Wizemann 6e8480411a Merge remote-tracking branch 'origin/ws-7-settings-v0.13' into integration/v2.8.0
# Conflicts:
#	scarf/Packages/ScarfCore/Sources/ScarfCore/Models/HermesConfig.swift
#	scarf/Packages/ScarfCore/Sources/ScarfCore/Parsing/HermesConfig+YAML.swift
2026-05-09 19:11:29 +02:00
Alan Wizemann 3a764e81e0 Merge remote-tracking branch 'origin/ws-6-providers-v0.13' into integration/v2.8.0
# Conflicts:
#	scarf/Packages/ScarfCore/Sources/ScarfCore/Models/HermesConfig.swift
#	scarf/Packages/ScarfCore/Sources/ScarfCore/Parsing/HermesConfig+YAML.swift
2026-05-09 19:10:43 +02:00
Alan Wizemann 6e90741a17 Merge remote-tracking branch 'origin/ws-5-gateway-v0.13' into integration/v2.8.0 2026-05-09 19:09:38 +02:00
Alan Wizemann 93a3b40a67 Merge remote-tracking branch 'origin/ws-4-curator-archive' into integration/v2.8.0 2026-05-09 19:09:38 +02:00
Alan Wizemann 52f0ddb36c Merge remote-tracking branch 'origin/ws-3-kanban-v0.13' into integration/v2.8.0 2026-05-09 19:09:38 +02:00
Alan Wizemann cedee04f2a feat(kanban): v0.13 diagnostics + recovery UX (WS-3)
Layers Hermes v0.13's reliability + recovery affordances on top of the
v2.7.5 Kanban v3 board. New surface — gated end-to-end on
`HermesCapabilities.hasKanbanDiagnostics` (>= v0.13.0):

- **Hallucination gate.** Worker-created cards land in `pending` until
  the user verifies the underlying work exists. Inspector renders a
  yellow Verify / Reject banner above the body; cards dim to 0.6 with
  a question-mark glyph. Verify is optimistic — banner clears
  immediately, polling confirms. Reject routes through
  `comment` + `archive` so there's an audit trail.
- **Generic diagnostics engine.** `HermesKanbanDiagnostic` (new model +
  typed-mirror enum `KanbanDiagnosticKind`) renders cross-run signals
  on the inspector header and per-run signals under each Runs row.
  Card footer gains a stethoscope dot when any signal is attached.
- **`max_retries` create-time field + inspector chip.** Toggle-gated
  Stepper in the create sheet sends `--max-retries N`; chip on the
  inspector header reads it back read-only with a tooltip explaining
  there's no update verb.
- **Multi-line title input.** Create sheet's title becomes a
  `TextField(axis: .vertical, lineLimit: 1...4)`. Newlines are stripped
  client-side on pre-v0.13 hosts (which truncate at the first `\n`).
- **Auto-blocked reason banner.** When `task.auto_blocked_reason` is
  set, replaces the generic "Last run: blocked" with a red banner
  rendering the server reason verbatim. Card footer shows a 1-line
  truncated copy in red.
- **Tolerant decode contract.** Every new field is `Optional` with
  `decodeIfPresent`; diagnostics arrays use `try?` so a single
  malformed entry doesn't poison the row. v0.12 hosts decode unchanged.

Implements WS-3 of Scarf v2.8.0 (Hermes v0.13.0 catch-up).
Plan: scarf/docs/v2.8/WS-3-kanban-v0.13-plan.md (on
coordination/v2.8.0-plans).

TODOs marked inline pending integration against a live v0.13 binary:
WS-3-Q1 (verify verb name), WS-3-Q2 (diagnostics envelope vs task),
WS-3-Q4 (failure_count placement), WS-3-Q5 (darwin-zombie kind
string), WS-3-Q6 (max_retries default).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 19:06:38 +02:00
Alan Wizemann b4482e5ee7 feat(gateway): Google Chat platform + cross-platform allowlists + behavior toggles (WS-5)
Catches the Mac Messaging Gateway and Platforms surfaces up to Hermes
v0.13.0. Adds Google Chat as the 20th platform under Settings → Platforms,
gated on `hasGoogleChatPlatform`. Adds a per-platform "Gateway behavior"
subsection to the six platforms Hermes added v0.13 allowlist support to
(Slack, Mattermost, Google Chat, Telegram, WhatsApp, Matrix) — each
exposes the `allowed_channels` / `allowed_chats` / `allowed_rooms` editor
plus three new toggles (`busy_ack_enabled`, `gateway_restart_notification`,
`slash_command_notice_ttl_seconds`). The Messaging Gateway page header
gains a one-line cross-profile digest sourced from `hermes gateway list
--json`. SkillsView surfaces an informational row on skills whose body
contains the v0.13 `[[as_document]]` directive.

New ScarfCore types: `GatewayAllowlistKind` (channels/chats/rooms +
platform mapping), `GatewayPlatformSettings` (per-platform v0.13 bundle),
`GatewayConfigWriter` (pure YAML list-block editor — `hermes config set`
can't write lists; tested with 15 cases incl. round-trip + idempotence +
quoting + scalar-sibling preservation), `HermesGatewayListService`
(`hermes gateway list --json` parser tolerant of unknown keys + alt
field names; 13 tests), `HermesConfig.gatewayPlatforms` field. Mac VM
renamed to `MessagingGatewayViewModel` (single-feature local rename;
CLAUDE.md "the SidebarSection.gateway enum case stays" invariant
upheld). All 22 new tests pass; full ScarfCore suite green except 3
pre-existing `RemoteSQLiteBackendTests` failures unrelated to WS-5.

Capability-gated end-to-end. Pre-v0.13 hosts see no Google Chat row,
no cross-profile digest, no v0.13 toggles, and no `[[as_document]]`
info row — the v2.7.5 surface is byte-for-byte unchanged. Q1-Q3 wire-
shape unknowns (Google Chat identifier, YAML key path,
`gateway list --json` shape) are marked with `// TODO(WS-5-Q<N>)` and
defended by tolerant parsers + dual-spelling lookups.

Implements WS-5 of Scarf v2.8.0 (Hermes v0.13.0 catch-up).
Plan: scarf/docs/v2.8/WS-5-gateway-v0.13-plan.md (on coordination/v2.8.0-plans).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 19:05:55 +02:00
Alan Wizemann 4757b5ae49 feat(curator): archive + prune + list-archived (WS-4)
Catches the Curator surface up to Hermes v0.13's new write-side verbs
(`archive <skill>`, `prune`, `list-archived`, synchronous `run`). Adds
a new `CuratorService` actor in ScarfCore mirroring `KanbanService`'s
pattern (Sendable, pure I/O, `Task.detached(priority: .utility)` per
verb), tolerantly-decoded `HermesCuratorArchivedSkill` /
`CuratorPruneSummary` models, and `CuratorError` for inline-banner
surfacing.

Mac UX gains an "Archived" section between the leaderboards and the
last-report block (per-row Restore button), an "archivebox" button on
every active-skill leaderboard row to manually archive, a destructive
"Prune Archived…" confirm sheet enumerating each skill (template-
uninstall pattern — Cancel owns `.defaultAction`, Prune is on the red
`ScarfDestructiveButton`), and a synchronous-with-progress "Run Now"
on v0.13+ hosts (600s timeout, `ProgressView` while in-flight).
Failure path routes through a yellow inline error banner instead of a
modal alert. The legacy `CuratorRestoreSheet` stays accessible from
the overflow menu but only on pre-v0.13 hosts; on v0.13+ the per-row
Restore in the new Archived section replaces it.

All new surfaces gate on `HermesCapabilities.hasCuratorArchive` —
pre-v0.13 hosts see the v2.7.x layout unchanged. iOS picks up the new
`runNow(synchronous:)` signature with the v0.13 capability flag; the
read-only Archived section + WS-9 marker is left for the next stream.
14 new parser tests in `HermesCuratorParserTests` cover the JSON
happy path, the `{"archived": [...]}` envelope, the text fallback
(`--json` not supported), `"no archived skills"` sentinel folding,
prune-dry-run with both wrapper + bare-array shapes, and zero-skill
prune. All 369 ScarfCore tests pass; `xcodebuild` for the `scarf`
scheme succeeds.

Wire-shape unknowns (CLI flag presence on real v0.13) carry
`// TODO(WS-4-Q<N>)` markers in `CuratorService` and fall back
defensively when a flag isn't recognized. Implements WS-4 of Scarf
v2.8.0 (Hermes v0.13.0 catch-up). Plan:
scarf/docs/v2.8/WS-4-curator-archive-plan.md (on
coordination/v2.8.0-plans).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 19:03:13 +02:00
Alan Wizemann 0070441243 feat(profiles): add --no-skills toggle to create-profile sheet
Adds an "Empty profile (no skills)" toggle to the Mac create-profile
sheet, gated on `hasProfileNoSkills` (v0.13+). When ON, the create
flow appends `--no-skills` to `hermes profile create`. The toggle is
disabled (greyed out) when "Full copy of active profile" is on, per
WS-7 plan Decision H — a full clone copies skills wholesale, so
`--no-skills` would be a contradiction at the UX layer. The wire
itself stays permissive: a user can stack `--clone --no-skills` to
clone config but skip skills, which is a plausible workflow.

Defensive write-strip: even though the toggle is hidden on pre-v0.13
hosts, the call site reads `createNoSkills` through the capability
gate so a stale state value can't sneak `--no-skills` past argparse
on a CLI that doesn't know it.

iOS Profiles is read-only (per CLAUDE.md "v0.12 iOS catch-up
Phase H") so no toggle there.

TODO marker (WS-7-Q8) flags the assumed `--clone-all` interaction —
verify Hermes's behaviour with both flags during integration.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 19:03:06 +02:00
Alan Wizemann 57a6340985 feat(providers): catalog refresh + image_gen.model + OpenRouter caching (WS-6)
Surfaces the v0.13 provider catalog work in Scarf v2.8.0. Five new model IDs
(deepseek/deepseek-v4-pro, x-ai/grok-4.3, openrouter/owl-alpha,
tencent/hy3-preview, arcee/trinity-large-thinking) flow through
models_dev_cache.json on next refresh — no manual catalog entries
needed; the picker reaches them automatically. The grok-4.20-beta →
grok-4.20 rename is handled via a new ModelCatalogService.modelAliases
map plus resolveModelAlias() helper, called from validateModel(),
model(_:_:), and provider(for:) at read time. Lossless: stored configs
are never rewritten.

Vercel AI Gateway is demoted to the bottom of the picker via a new
demotedProviders set + sort-comparator axis (between subscription-gated
and alphabetical). Always-on, no capability gate — sort-order
consistency across Hermes versions.

image_gen.model (top-level v0.13 YAML key) and
openrouter.response_cache.enabled (provisional key shape per
TODO(WS-6-Q1)) are surfaced as new SettingsSection rows in
AuxiliaryTab, capability-gated on hasImageGenModel +
hasOpenRouterResponseCache so pre-v0.13 hosts hide them. Image-gen
picker has a curated 7-entry allowlist (HermesImageGenModel) plus
free-form Custom model ID entry.

CLAUDE.md gains two schema-drift bullets next to the existing
overlayOnlyProviders requirement (modelAliases + demotedProviders
mirror with hermes_cli/providers.py).

Tests: 4 new M0cServicesTests (sort axis, alias resolution + cross-
provider isolation, image-gen allowlist, demoted-set sentinel) and 2
new M6ConfigCronTests (YAML round-trip + empty-default).

Implements WS-6 of Scarf v2.8.0 (Hermes v0.13.0 catch-up).
Plan: scarf/docs/v2.8/WS-6-providers-v0.13-plan.md
(on coordination/v2.8.0-plans).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 19:02:45 +02:00
Alan Wizemann 0f78856e6e feat(settings): v0.13 polish — redaction hint, display.language picker, xAI cloning badge (WS-8)
Three Settings-tab surfaces tracking v0.13 release notes:

- **Redaction default-flip awareness** (Advanced → Caching & Redaction):
  inline hint below the existing toggle whose copy depends on
  `HermesCapabilities.isV013OrLater`. v0.13 flipped the server-side
  default from OFF (v0.12) to ON, but Scarf's parser still treats
  "absent key" as `false`. Hint disambiguates so users on v0.13 hosts
  understand redaction is on server-side even when the toggle reads OFF.

- **`display.language` picker** (General → Locale): 8-option enum (`""`
  default + en/zh/ja/de/es/fr/uk/tr) capability-gated on
  `hasDisplayLanguage`. Persists via `hermes config set
  display.language <code>`. Empty string preserves "no key" semantics
  (Hermes-default English); explicit `en` pins it. Required a small
  `optionLabel:` overload on `PickerRow` so non-English labels
  (中文 / 日本語 / etc.) render alongside their codes.

- **xAI Custom Voices badge** (Voice → Text-to-Speech): adds `xai`
  to the TTS provider picker (un-gated — xAI TTS shipped earlier),
  exposes Voice ID + Model fields, and renders a "Cloning supported"
  ScarfBadge gated on `hasXAIVoiceCloning`. Hint copy points at
  `hermes voice` for cloned-voice management since Scarf has no
  in-app surface for that yet (out-of-scope for v2.8).

Capability gates: `isV013OrLater` (hint discriminator),
`hasDisplayLanguage` (picker), `hasXAIVoiceCloning` (badge). Pre-v0.13
hosts see the v2.7.5 layout unchanged.

`TODO(WS-8-Q2)` flags the assumed xAI YAML keys (`tts.xai.voice_id` /
`tts.xai.model` mirroring elevenlabs) for grep-verify against
`~/.hermes/hermes-agent/hermes_cli/voice/tts.py`.

iOS deferred to v2.9 (Q4): `Scarf iOS` Settings is read-mostly and
doesn't have a write surface for either the language picker or the
xAI fields.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 18:59:38 +02:00
Alan Wizemann 5877bf6519 feat(updater): forward-compat HermesUpdaterCommandBuilder for hermes update --yes (WS-8)
Pure-function helper that builds argv arrays for `hermes update`,
gated on `HermesCapabilities`. Pre-v0.12 → bare `update`; v0.12+
honors `--check`; v0.13+ honors `--yes` for unattended runs.

No in-app "Update Hermes" affordance ships in v2.7.5 — Sparkle handles
Scarf-self-update and `hermes update` is invoked by users in their
terminal. This is forward-compat plumbing so the eventual UI surface
shares flag selection across Mac / iOS / remote without re-deriving
from scratch.

Test matrix in `M0eUpdaterTests` covers all six combinations
(pre-v0.12, v0.12 ± unattended ± check, v0.13 ± unattended ± check)
plus an empty-capabilities fallback.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 18:59:12 +02:00
Alan Wizemann f19f19cd56 feat(chat): surface v0.13 compression count + bracket-aware slash hint (WS-8)
Two small chat-surface additions tracking Hermes v0.13:

- Plumb a `compressionCount` field through `ACPPromptResult` and
  `RichChatViewModel.acpCompressionCount` so `SessionInfoBar` can render
  a `🗜 ×N` chip next to the token counter when the agent has performed
  context compactions. Capability-gated on
  `HermesCapabilities.hasContextCompressionCount` and `count > 0` so
  pre-v0.13 hosts (which always emit 0) and fresh sessions never see
  the chip. Wire decode tolerates camelCase + snake_case;
  `TODO(WS-8-Q1)` flags the assumption that the field rides on
  `usage` — if v0.13 emits via a separate `session/update` notification
  the bigger fix is described in the WS-8 plan.

- Slash-menu argument hint is now bracket-aware: hints starting with
  `<` or `[` pass through verbatim, others wrap as `<hint>`. v0.13's
  `/new [name]` ships through unchanged without rendering as
  `<[name]>`. No flag check at the renderer — agent payload is the
  source of truth.

Coordination with WS-2: both WSes touch `SessionInfoBar`. WS-2 owns
the queue chip on the left half; this WS owns the compression chip on
the right half. The added `capabilities` parameter is shared — kept
additive so WS-2's later merge produces no file-level conflict.

Tests: extends `M0dViewModelsTests` (compression count tracking +
reset semantics) and `ScarfCoreSmokeTests` (decode default + explicit
v0.13 init path).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 18:58:58 +02:00
Alan Wizemann 6c96fcfa43 feat(settings): add Web Tools tab with v0.13 search/extract split
Adds a new "Web Tools" Settings tab (between Browser and Voice) with
two distinct shapes that share the same chrome:

- Pre-v0.13: a single "Backend" picker writing the legacy
  `web_tools.backend` key (so v0.12 users still configure web tools).
- v0.13+: two pickers — Search backend writes
  `web_tools.search.backend` (SearXNG appears here only — Hermes
  registers it as a search-only dispatch), Extract backend writes
  `web_tools.extract.backend`.

Capability gate: `hasWebToolsBackendSplit` chooses which shape
renders. The tab itself is always visible — pre-v0.13 users would
otherwise lose access to the legacy combined-backend picker.

Model layer:
- `HermesConfig.webToolsBackend` / `webToolsSearchBackend` /
  `webToolsExtractBackend` — three fields, each round-tripping its
  own YAML key. Defaults: `duckduckgo` / `duckduckgo` / `reader`.
- YAML parser reads all three keys via the existing `str(...)`
  helper. Pre-v0.13 hosts populate only `webToolsBackend`; the
  split keys default to the same backend so the picker shows the
  same value the user already had.

TODO markers (WS-7-Q6/Q7) flag the inline backend lists + legacy
fallback semantics — verify against `~/.hermes/hermes-agent/
hermes_cli/web_tools.py` during integration.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 18:56:08 +02:00
Alan Wizemann edac142d08 feat(chat): add /goal and /queue slash commands (WS-2)
Adds Hermes v0.13's Persistent Goals and ACP /queue surfaces to the
rich-chat composer. /goal <text> locks the agent on a target across
turns (rendered as an info-tinted "Goal locked" pill in the chat
header, with a context-menu Clear action that dispatches /goal --clear);
/queue <text> queues a prompt to run after the current turn (rendered
as a warning-tinted chip with a popover listing queued prompts +
relative timestamps). Both ride .acpNonInterruptive so the chat keeps
"Agent working…" off, and both surface a 4-second transient toast
mirroring /steer's existing UX.

Capability-gated end-to-end: the rich-chat slash menu reads through
RichChatViewModel.capabilitiesGate (a new @ObservationIgnored field
fed by ChatViewModel.attachCapabilitiesStore on Mac and a parallel
.task(id:) on iOS), so pre-v0.13 hosts never see /goal or /queue.
/steer is greyed-out on idle sessions when hasACPSteerOnIdle is off
(pre-v0.13 hosts only). The "Clear all" queue-popover button is
intentionally absent in v2.8.0 — Hermes' wire-shape for /queue --clear
isn't verified yet, so a button that lies about server-side state is
worse than no button (per WS-2 plan Q2 decision).

Optimistic-only: there is no authoritative read-back path for the
active goal in v2.8.0. The pill paints synchronously off the
optimistic write the moment the user sends /goal …; cross-session
resume won't re-paint it until the user types /goal again. A
TODO(WS-2-Q1) marker in RichChatViewModel.recordActiveGoal points at
the read-back hook for v2.8.1; TODO(WS-2-Q5) flags the verbatim
/queue argument shape for coordinator wire-verification; TODO(WS-2-Q7)
flags the /goal non-interruptive classification. TODO(v2.8.1) in
handlePromptComplete is the deferred "auto-resumed from checkpoint"
indicator (WS-2 plan Q3 decision).

iOS surfaces no UI yet (deferred to WS-9), but the iOS controller's
_sendImpl mirrors the dispatch so the shared RichChatViewModel state
stays aligned across platforms — otherwise an iOS user who ran /goal
then opened the same session on Mac would see an empty pill.

Tests: extends M9SlashCommandTests with 13 new cases covering the
non-interruptive list contents, capability-gated availableCommands
filtering on v0.12 vs v0.13, parseGoalArgument variants, optimistic
mutators (recordActiveGoal / recordQueuedPrompt / popQueuedPrompt),
isNonInterruptiveSlash recognition, and reset() drainage.

Implements WS-2 of Scarf v2.8.0 (Hermes v0.13.0 catch-up).
Plan: scarf/docs/v2.8/WS-2-goals-and-queue-plan.md (on coordination/v2.8.0-plans).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 18:55:54 +02:00
Alan Wizemann fd33b714e3 feat(cron): add --no-agent watchdog toggle gated on hasCronNoAgent
Adds a "Run script only (no agent call)" toggle to the cron job
editor. When ON, the prompt + skills sections dim + disable
visually but stay rendered (no layout shift mid-edit), the
script field stays fully active, and the form passes
`noAgent: true` to `createJob`/`updateJob`. The toggle is hidden
on pre-v0.13 hosts via `supportsNoAgent: hasCronNoAgent` and
defensively stripped at the call site (`hasCronNoAgent ?
form.noAgent : false` on create, `: nil` on edit) — same shape
as the v0.12 `workdir` strip.

Read-side: `HermesCronJob.noAgent: Bool?` is decoded via
`decodeIfPresent` so pre-v0.13 jobs.json files round-trip
unchanged. The display rule `job.noAgent == true` treats
`nil` and `false` identically — a script-only job must opt in.

Write-side:
- `createJob` appends `--no-agent` and passes an empty positional
  prompt (per WS-7-Q5) to keep argparse happy when the prompt is
  the trailing positional.
- `updateJob` sends `--no-agent` / `--agent` to flip the flag in
  edit mode (per WS-7-Q4 — verify the toggle-off spelling on
  integration; if Hermes is one-way, disable the toggle in edit
  mode with a tooltip).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 18:43:03 +02:00
Alan Wizemann c81a8a56e8 feat(mcp): add SSE transport support gated on hasMCPSSETransport
Extends MCPTransport with a third .sse case (alongside stdio + http),
plumbed through the YAML parser, add-server form, list view, detail
view, and editor. The add-server form filters .sse out of the segmented
picker on pre-v0.13 hosts (capability-gated on hasMCPSSETransport) so
Hermes never sees a transport flag it can't parse. The editor renders
a third numeric "SSE read timeout" field only for .sse servers.

YAML layer:
- HermesMCPServer.sseReadTimeout: Int? — defaulted in init, decoded
  from `sse_read_timeout` scalar.
- parseMCPServersBlock: 3-way transport discriminator — `transport: sse`
  scalar wins, then url-bearing entries default to .http (v0.12 shape),
  command-bearing to .stdio. Pre-v0.13 entries are byte-for-byte
  unaffected.
- HermesFileService.addMCPServerSSE writes via `hermes mcp add --url
  <u> --transport sse [--sse-read-timeout <t>]`.
- HermesFileService.setMCPServerSSETimeout patches the scalar via the
  same surgical patcher used by setMCPServerTimeouts.

TODO markers (WS-7-Q1/Q2/Q3) flag the wire-format unknowns the plan
called out — verify against a v0.13 Hermes install during integration.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 18:34:27 +02:00
Alan Wizemann 3e470c7155 Merge pull request #80 from awizemann/ws-1-capabilities-v0.13
feat(capabilities): add Hermes v0.13 capability flags + version bump (WS-1)
2026-05-09 18:17:51 +02:00
Alan Wizemann 963d0e1a5c feat(capabilities): add isV013OrLater convenience predicate
Surfaces a v0.12 → v0.13 boundary check that doesn't proxy through any
specific feature flag. Used by WS-8 (redaction default-state hint copy,
"v0.13 features active" Settings badge in iOS WS-9) where the call site
isn't actually about a specific feature — it's about whether the host is
on the v0.13 line.

Equivalent to any individual v0.13 flag (e.g. `hasGoals`); both resolve
to the same `>= 0.13.0` threshold. Convenience exists to keep call sites
honest: `caps.isV013OrLater` reads better than `caps.hasGoals` when the
context isn't goal-related.

Tests: 4 new fixtures covering v0.13 host (true), v0.12 host (false),
empty/undetected (false), and v0.14 host (true). 19 total tests in the
suite, all passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 18:08:14 +02:00
Alan Wizemann 52c802676f feat(capabilities): add Hermes v0.13 capability flags + version bump
Adds 22 new capability flags grouped under a v0.13 (v2026.5.7) MARK
section in HermesCapabilities, covering Persistent Goals, ACP /queue
+ /steer-on-idle, Kanban diagnostics + recovery UX, Curator archive
+ prune, Google Chat (20th platform), cross-platform allowlists,
MCP SSE transport, Cron --no-agent, Web Tools backend split, Profiles
--no-skills, context compression count, /new <name>, OpenRouter cache,
image_gen.model, display.language, xAI voice cloning, video_analyze,
and the transform_llm_output plugin hook.

Each flag gates on >= 0.13.0 so v0.13 patch releases (0.13.4 etc.)
still light up every flag. Existing v0.12 flags unchanged. Test suite
extends with v0.13.0/2026.5.7 fixtures, a v0.13.4 patch-release case,
explicit "v0.13 flags off on v0.12 host" coverage, and updates the
future-version test to v0.14.0.

CLAUDE.md target line bumps to v2026.5.7 (v0.13.0); a new v2026.5.7
section mirrors the v0.12 / v0.11 scaffolding describing the Scarf-
relevant subset. The v0.12 + v0.11 historical sections remain intact
since pre-v0.13 hosts still consume those flags.

Foundation for the v2.8.0 Scarf release — every subsequent work-stream
(WS-2 through WS-9) consumes flags added here.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 17:31:51 +02:00
Alan Wizemann 5d8873d305 chore: Bump version to 2.7.5 2026-05-08 13:59:21 +02:00
Alan Wizemann 49bc4efe83 fix(kanban): enrich LocalTransport subprocess env so kanban dispatcher can spawn workers
GUI-launched Scarf inherits macOS's launch-services PATH
(`/usr/bin:/bin:/usr/sbin:/sbin`). Scarf itself finds `hermes` via
absolute-path resolution in `HermesPathSet.hermesBinaryCandidates`,
but when the kanban dispatcher (a child of Scarf) tries to spawn a
worker, the worker inherits the same stripped PATH and Hermes's spawn
machinery prints `\`hermes\` executable not found on PATH. Install
Hermes Agent or activate its venv before running the kanban
dispatcher.` — recording `outcome=spawn_failed` on the run.

`LocalTransport` now mirrors `SSHTransport.environmentEnricher`:
adds an `environmentEnricher: (() -> [String: String])?` static, and
applies it to every subprocess. `scarfApp.swift` wires it at launch
to the same `HermesFileService.enrichedEnvironment()` login-shell
probe (`zsh -l -i` → `zsh -l` fallback) the SSH transport already
uses, so subprocesses see `~/.local/bin`, `/opt/homebrew/bin`, and
the user's credential env vars.

Defense-in-depth: `subprocessEnvironment(forExecutable:)` always
prepends the executable's own directory to PATH if missing — covers
early-startup paths and test harnesses where the enricher hasn't
been wired yet.

Two new tests in `KanbanModelsTests` lock in:
1. The fallback (no enricher → executable's dir lands on PATH)
2. The enricher win for PATH + the empty-string-aware copy semantics
   for credential env vars (process env happens to set
   `ANTHROPIC_API_KEY=""` as an empty string in some environments;
   the enricher's non-empty value must still take effect)

Release notes for v2.7.5 updated to document the fix.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 13:59:21 +02:00
Alan Wizemann adcc984091 feat(kanban): full read/write board with per-project tenants
Lifts Scarf's Kanban surface from the v2.6 read-only list to a
drag-and-drop board with the complete Hermes v0.12 mutation surface
wired up, plus per-project boards bound to a Scarf-minted tenant slug
and a read-only board on iOS.

Why now: the v2.6 list was a placeholder shipped while upstream Kanban
collab was still mid-rework. v0.12 stabilized the 27-verb CLI; this
release makes Scarf a real GUI client for it. Driving real tasks
end-to-end exposed and closed a connected bug pattern (claim vs
dispatch, silent skipped_unassigned, integer-vs-ISO timestamps,
parser-leaked "(no" sentinel) that would have shipped as latent UX
papercuts otherwise.

ScarfCore: KanbanService actor (Sendable, pure I/O) wrapping every
verb; KanbanTenantReader cross-platform manifest projection; eight
new model types (TaskDetail, Comment, Event, Run, Stats, Assignee,
CreateRequest, Filters); KanbanError; pure transition planner that
maps drag-drop column changes to verb sequences, tested against
canonical Hermes JSON fixtures.

Mac: KanbanBoardView orchestrator with five-column drag-drop layout,
optimistic-merge state, KanbanInspectorPane side-pane (Comments /
Events / Runs / Log tabs, Log streams worker stdout every 2s while
running), inline assignee picker, health banner for unassigned and
last-failed-run states. New Task sheet defaults to active profile
and auto-fires kanban dispatch on submit. Sidebar moved Kanban from
Manage to Monitor. Read-only KanbanListView preserved as Board|List
toggle for narrow windows / accessibility.

Per-project: DashboardTab.kanban tab on every project gated on
hasKanban; KanbanTenantResolver mints scarf:<slug> tenants on first
interaction and persists to .scarf/manifest.json (immutable across
rename); ProjectAgentContextService surfaces the tenant in the
AGENTS.md scarf-managed block so agents pass --tenant <slug> on
kanban create. New kanban_summary dashboard widget; vocabulary
mirrored in tools/widget-schema.json and site/widgets.js.

iOS: read-only board on the project tab via paged single-column
Picker, modal detail sheet with Comments / Events / Runs. Mutations
+ drag-drop deferred to v2.8.

Tests: 19 new pure-logic tests covering decoding, planner verb
mapping, argv assembly, glance string formatting, and parser
rejection of the kanban assignees empty-state sentinel. All 348
ScarfCore tests pass.

Constraints documented in CLAUDE.md: no within-column reorder
(Hermes has no update --priority verb); no live watch streaming
yet (5s polling for board, 2s for log); no bulk re-tag for legacy
NULL-tenant tasks. Pre-v0.12 Hermes hosts gracefully hide the
surface end-to-end.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 13:59:21 +02:00
Alan Wizemann fd80f4f95a Create FUNDING.yml 2026-05-07 12:55:53 +02:00
124 changed files with 13104 additions and 403 deletions
+15
View File
@@ -0,0 +1,15 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: awizemann
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+61 -3
View File
@@ -113,9 +113,29 @@ Public documentation lives in the GitHub wiki at https://github.com/awizemann/sc
## Hermes Version
Targets Hermes v2026.4.30 (v0.12.0). Log lines may carry an optional `[session_id]` tag between the level and logger name — `HermesLogService.parseLine` treats the session tag as an optional capture group, so older untagged lines still parse.
Targets Hermes v2026.5.7 (v0.13.0). Log lines may carry an optional `[session_id]` tag between the level and logger name — `HermesLogService.parseLine` treats the session tag as an optional capture group, so older untagged lines still parse.
**Capability gating.** Scarf detects the target's Hermes version once per server connection via [HermesCapabilities](scarf/Packages/ScarfCore/Sources/ScarfCore/Services/HermesCapabilities.swift) (`hermes --version` → semver + `YYYY.M.D` parse). The resulting `HermesCapabilitiesStore` is injected on `ContextBoundRoot` (Mac) and `ScarfGoTabRoot` (iOS) via `.environment(_:)` and `.hermesCapabilities(_:)`; UI that depends on a v0.12+ surface (Curator, Kanban, ACP image input, `auxiliary.curator`, `prompt_caching.cache_ttl`, Piper TTS, Vercel terminal) reads it through the typed environment key. Pre-v0.12 hosts gracefully hide the new affordances rather than throwing on unknown CLI subcommands. Add a new flag at the top of `HermesCapabilities` whenever Scarf gains a release-gated UI surface.
**Capability gating.** Scarf detects the target's Hermes version once per server connection via [HermesCapabilities](scarf/Packages/ScarfCore/Sources/ScarfCore/Services/HermesCapabilities.swift) (`hermes --version` → semver + `YYYY.M.D` parse). The resulting `HermesCapabilitiesStore` is injected on `ContextBoundRoot` (Mac) and `ScarfGoTabRoot` (iOS) via `.environment(_:)` and `.hermesCapabilities(_:)`; UI that depends on a release-gated surface reads it through the typed environment key. Pre-target hosts gracefully hide the new affordances rather than throwing on unknown CLI subcommands. Add a new flag at the top of `HermesCapabilities` whenever Scarf gains a release-gated UI surface — group flags by the Hermes release that introduced them (`MARK: v0.13 (v2026.5.7) flags`, etc.).
**v2026.5.7 (v0.13.0)** added (Scarf-relevant subset; full v2.8.0 implementation lands across WS-2 through WS-9):
- **Persistent Goals** — `/goal <text>` slash command locks the agent onto a target across turns. Checkpoints v2 single-store rewrite + auto-resume after gateway restart. Surfaced in Scarf chat as a non-interruptive command + a "🎯 Goal locked: <text>" pill in the chat header. Gated on `HermesCapabilities.hasGoals`.
- **ACP `/queue` slash command** — queues a prompt to run after the current turn completes. Joins `/steer` in `RichChatViewModel.nonInterruptiveCommands` with a transient "Queued" toast. Gated on `hasACPQueue`. `/steer` now also runs as a regular prompt on idle sessions (`hasACPSteerOnIdle`).
- **Kanban v0.13 reliability + recovery UX** — hallucination gate on worker-created cards, generic diagnostics engine (per-task distress signals), per-task `max_retries` override, multiline title/body create, `auto_blocked_reason` rendered in the inspector banner, darwin zombie detection, unify failure counter across spawn/timeout/crash. New fields decode through tolerant `HermesKanbanRun` / `HermesKanbanTaskDetail` extensions; pre-v0.13 hosts ignore unknown keys. Gated on `hasKanbanDiagnostics`.
- **Curator archive + prune** — `hermes curator archive <skill>` + `prune` + `list-archived` subcommands. The synchronous manual `hermes curator run` blocks until done (pre-v0.13 returned immediately). Surfaced as an "Archived" tab in CuratorView with per-row Restore + Prune actions and a destructive prune-confirm sheet. Gated on `hasCuratorArchive`.
- **Messaging Gateway expansion** — Google Chat (20th platform; `hasGoogleChatPlatform`), cross-platform allowlists (`allowed_channels` / `allowed_chats` / `allowed_rooms` per platform; `hasGatewayAllowlists`), per-platform `gateway_restart_notification` (`hasGatewayRestartNotification`), `busy_ack_enabled` toggle (`hasGatewayBusyAckToggle`), slash-command auto-delete TTL, `[[as_document]]` skill media routing directive, `hermes gateway list` cross-profile status verb (`hasGatewayList`).
- **Provider catalog refresh** — new models on Nous Portal + OpenRouter: `deepseek/deepseek-v4-pro`, `x-ai/grok-4.3`, `openrouter/owl-alpha` (free), `tencent/hy3-preview`, `arcee/trinity-large-thinking` (with temperature + compression overrides). `x-ai/grok-4.20-beta` renamed to `x-ai/grok-4.20` — keep alias map. Vercel AI Gateway demoted to bottom of the picker. `image_gen.model` from `config.yaml` now honored by Hermes (was advertised but ignored pre-v0.13); surfaced in `Settings → Auxiliary` (`hasImageGenModel`). OpenRouter response caching toggle (`hasOpenRouterResponseCache`).
- **MCP SSE transport** — MCP servers can be configured with SSE transport + `sse_read_timeout`. Surfaced in MCPServersView add-server flow alongside stdio/pipe. Gated on `hasMCPSSETransport`.
- **Cron `--no-agent` mode** — script-only watchdog jobs that skip the AI call. Surfaced in CronView edit sheet. Gated on `hasCronNoAgent`.
- **Web Tools per-capability backends** — `web_search` and `web_extract` can use distinct backends; SearXNG joined as a search-only backend. Surfaced in the Web Tools settings tab. Gated on `hasWebToolsBackendSplit`.
- **Profiles `--no-skills`** — `hermes profile create --no-skills` for empty-profile creation. Surfaced as a toggle in the create-profile flow. Gated on `hasProfileNoSkills`.
- **CLI / UX additions** — context compression count in the status feed (rendered next to the token count in chat status bar; `hasContextCompressionCount`), `/new <name>` slash-command argument (`hasNewWithSessionName`), `hermes update --yes` non-interactive (`hasUpdateNonInteractive`), `display.language` static-message translation (zh / ja / de / es / fr / uk / tr; `hasDisplayLanguage`), xAI Custom Voices (voice-cloning badge next to xAI TTS provider; `hasXAIVoiceCloning`).
- **Server-side defaults flipped** — secret redaction defaults back to ON in v0.13 (was off by default in v0.12). The Settings redaction toggle remains for opt-out; the default-state hint reflects the v0.13 semantics when the host advertises v0.13+.
- **`video_analyze` tool** — native video understanding on Gemini-class models. Hermes handles transparently inside the agent loop; Scarf has no UI surface yet but `hasVideoAnalyze` is reserved for future widget gating.
- **`transform_llm_output` plugin hook** — plugin-author concern; surfaced indirectly through PluginsView when a plugin advertises the hook. `hasTransformLLMOutputHook` gates the metadata badge.
- **Schema is unchanged from v0.11/v0.12** — same state.db columns. No migration needed.
**v2026.4.30 (v0.12.0)** added (Scarf-relevant subset):
**v2026.4.30 (v0.12.0)** added (Scarf-relevant subset):
@@ -124,7 +144,7 @@ Targets Hermes v2026.4.30 (v0.12.0). Log lines may carry an optional `[session_i
- **`flush_memories` aux task removed (server side)** — `auxiliary.flush_memories` is gone from v0.12 Hermes config but remains alive on pre-v0.12 hosts. Scarf preserves `AuxiliarySettings.flushMemories: AuxiliaryModel`, the YAML reader still emits an `aux("flush_memories")` row, and `AuxiliaryTab` only renders the row when `HermesCapabilities.hasFlushMemoriesAux` is `true` (inverse semantics — pre-v0.12 only). v0.12 users never see the row; v0.11 users keep their edit surface.
- **`auxiliary.curator` aux task added** — Curator's review model is configurable independently of the main model. Surfaced in `Settings → Auxiliary` next to the other aux rows.
- **Multimodal ACP `session/prompt`** — ACP advertises and forwards image content blocks. Scarf chat composers (Mac drag/drop + paste; iOS PhotosPicker) attach images that flow through `ACPClient.sendPrompt(sessionId:text:images:)` as `[{"type":"text","text":...}, {"type":"image","data":"<base64>","mimeType":"image/jpeg"}]` — wire shape matches `acp.schema.ImageContentBlock`. `ImageEncoder` downsamples to 1568px long-edge JPEG q=0.85 detached (never blocks MainActor). Gated on `HermesCapabilities.hasACPImagePrompts`.
- **CLI additions:** `hermes -z <prompt>` (non-interactive one-shot), `hermes update --check` (preflight), `hermes fallback` (manage fallback providers), `hermes curator` (status / run / pause / resume / pin / unpin / restore), `hermes kanban` (full task-board CLI; multi-profile collab was reverted upstream so Scarf ships a read-only Kanban view only). All capability-gated.
- **CLI additions:** `hermes -z <prompt>` (non-interactive one-shot), `hermes update --check` (preflight), `hermes fallback` (manage fallback providers), `hermes curator` (status / run / pause / resume / pin / unpin / restore), `hermes kanban` (full 27-verb task-board CLI). All capability-gated. **v2.7.5 lifts Kanban from a read-only list to a full drag-and-drop board.** See the dedicated [Kanban v3](#kanban-v3-drag-and-drop-board--per-project-tenants-v275) section below for the complete architecture.
- **Skills surface:** `hermes skills install <https-url>` direct-URL install (SkillsView "Install from URL…" toolbar button), reload via `hermes skills audit` (Skills "Reload" button — equivalent to the `/reload-skills` slash command for non-ACP contexts), enabled/disabled state read from `skills.disabled` in config.yaml (rendered as strikethrough + "OFF" pill), Curator pin badge from `~/.hermes/skills/.curator_state` (rendered as a pin glyph). The disable-toggle write path is deferred to v2.7 — Hermes only exposes `hermes skills config` as an interactive verb, and Scarf prefers reading accurately to risking a clobbered list.
- **Two new gateway platforms:** Microsoft Teams (19th, plugin-shipped) + Tencent 元宝 / Yuanbao (18th, native). Surfaced in the Mac Platforms tab.
- **Cron upgrades:** per-job `--workdir <abs-path>` (project-aware cwd that pulls AGENTS.md / CLAUDE.md / .cursorrules) is exposed in the editor sheet, gated on `HermesCapabilities.hasCronWorkdir` so pre-v0.12 hosts don't see the field (and a defensive override in `CronView` strips the value before calling `createJob`/`updateJob` even if it was hydrated from a pre-existing job). Pass an empty string on edit to clear an existing workdir, mirroring the `--script` shape. Hermes also added a `context_from` field for chaining cron outputs but only via YAML so far — Scarf reads it (HermesCronJob.contextFrom) but doesn't write it.
@@ -153,6 +173,44 @@ 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.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)
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.
**Sidebar move.** `.kanban` moved from *Manage**Monitor* in `SidebarView` (between `.activity` and the remaining Monitor entries). Kanban is runtime work-in-progress, not configuration. Position kept inside the same enum case — only the section bucket changed.
**Hermes constraints that drive design.**
1. **No `update` verb.** `priority`, `title`, `body`, `tenant` are write-once at `kanban create`. Mutations after create are state transitions (`assign` / `claim` / `complete` / `block` / `unblock` / `archive`) or new comments. Inline-edit on a card title is impossible at the wire level.
2. **No `project_id` column.** Hermes Kanban is one global SQLite DB at `~/.hermes/kanban.db`. Closest namespace is the optional `tenant TEXT` column. Scarf hijacks it: each project gets a `scarf:<slug>` tenant minted on first kanban interaction.
3. **No within-column position field.** Drag-to-reorder inside a column has no Hermes persistence path and is **disabled** in v2.7.5. Sort key is `priority DESC, created_at DESC` — matches dispatcher's actual run order. Cross-column drag is the only persisted gesture.
4. **No file-watch / webhooks.** Polling at 5s while foregrounded; live `watch` streaming deferred to a later release (a `hasKanbanWatch` flag will gate it).
5. **Status enum has 7 values, board collapses to 5 columns:** Triage / **Up Next** (`todo` + `ready`) / Running / Blocked / Done. Triage hides when empty; Archived hides behind a toolbar toggle.
**Service layer.** [KanbanService](scarf/Packages/ScarfCore/Sources/ScarfCore/Services/KanbanService.swift) is a Sendable `actor` in ScarfCore — pure I/O, no UI state. Wraps every v0.12 verb (`list / show / runs / stats / assignees / create / assign / claim / comment / complete / block / unblock / archive / dispatch / link / unlink`). Every method dispatches its CLI invocation through `Task.detached(priority: .utility)`, matching the existing `KanbanViewModel.load` pattern (re: Swift 6 rules in `~/.claude/CLAUDE.md`). Errors land in [KanbanError](scarf/Packages/ScarfCore/Sources/ScarfCore/Models/KanbanError.swift) and surface as inline banners (not modal alerts) since the board is high-frequency. The "no matching tasks" stdout sentinel is normalized to `[]`.
**Drag-drop transition planner.** `KanbanService.plan(for: KanbanTransition)` is a pure function that maps `(from, to)` columns to the right verb sequence — `(.upNext, .running) → [.claim]`, `(.blocked, .running) → [.unblock, .claim]`, etc. Disallowed transitions throw `KanbanError.forbiddenTransition` with a user-facing reason: drop on Done from anywhere triggers "Done is terminal — create a follow-up task to continue work."; drop on Triage from outside triggers "Triage tasks are promoted by a specifier agent." The view's drop handler short-circuits forbidden transitions with red-stroke target feedback.
**Per-project tenant.** [KanbanTenantResolver](scarf/scarf/Core/Services/KanbanTenantResolver.swift) (Mac) mints `scarf:<slug>` on first kanban interaction inside a project, persisting to `<project>/.scarf/manifest.json`'s new optional `kanbanTenant: String?` field. Tenants are **immutable across rename** (existing tasks already carry the old slug). Bare projects (no manifest) get a sentinel manifest written with `id: scarf/<project-id>` + `version: 0.0.0` + just the `kanbanTenant` set; `ProjectAgentContextService` recognizes the sentinel and refuses to surface it as a "Template" line. The cross-platform read-only counterpart is [KanbanTenantReader](scarf/Packages/ScarfCore/Sources/ScarfCore/Services/KanbanTenantReader.swift) in ScarfCore — iOS uses it to filter the per-project board without linking the full manifest model.
**Agent-side tenant injection.** `ProjectAgentContextService.renderBlock` adds a "Kanban tenant" line to the AGENTS.md scarf-managed block whenever a tenant exists. Since `ChatViewModel.startACPSession` calls `refresh(for:)` before opening every project chat, the agent sees the tenant on every session start and is told to pass `--tenant scarf:<slug>` on `hermes kanban create`. Agents are imperfect at flag discipline; misuse just sends the task to the global "Untagged" group on the global board, which is acceptable v2.7.5 behavior. A dedicated retag UX is a follow-up.
**View model.** [KanbanBoardViewModel](scarf/scarf/Features/Kanban/ViewModels/KanbanBoardViewModel.swift) is `@MainActor + @Observable`, holds the column-grouped task array, and applies optimistic-merge logic around drag-drops: an in-flight move records `optimisticOverrides[taskId] = newStatus`, mutates the local array immediately, and clears the override only when the polled response confirms the new status. Without this, a stale poll response can clobber a card the user just dragged. On CLI failure the override is removed and an error message lands in the inline banner.
**Mac surface.** [KanbanBoardView](scarf/scarf/Features/Kanban/Views/KanbanBoardView.swift) is the orchestrator (header + columns + side-pane inspector + create/block/complete sheets). [KanbanColumnView](scarf/scarf/Features/Kanban/Views/KanbanColumnView.swift) owns its `dropDestination(for: KanbanTaskRef.self)`. [KanbanCardView](scarf/scarf/Features/Kanban/Views/KanbanCardView.swift) handles the `.draggable` source, status-specific chrome (running edge accent + shimmer; blocked warning glyph; done dim 0.7/0.55), and a custom drag preview. [KanbanInspectorPane](scarf/scarf/Features/Kanban/Views/KanbanInspectorPane.swift) is a 420pt side-pane (not modal) so the user can keep dragging cards after inspecting one. [KanbanCreateSheet](scarf/scarf/Features/Kanban/Views/KanbanCreateSheet.swift) maps form state to a `KanbanCreateRequest`; the Workspace picker locks to "Project Dir" on per-project boards. [KanbanBlockReasonSheet](scarf/scarf/Features/Kanban/Views/KanbanBlockReasonSheet.swift) and [KanbanCompleteResultSheet](scarf/scarf/Features/Kanban/Views/KanbanCompleteResultSheet.swift) prompt for optional `--reason` / `--result` text on those transitions.
**Per-project surface.** New `DashboardTab.kanban` case in `ProjectsView.swift`, dispatched to [ProjectKanbanTab](scarf/scarf/Features/Projects/Views/ProjectKanbanTab.swift) which mints the tenant on appearance and wraps `KanbanBoardView` with `tenantFilter` + `projectPath` pre-applied. Capability-gated on `HermesCapabilities.hasKanban` so pre-v0.12 hosts don't see a broken destination. Plus a new `kanban_summary` widget — top 3 tasks by priority across `running` + `blocked` + `todo` for the project's tenant, with stats glance footer. Mirror in `tools/widget-schema.json`, `tools/build-catalog.py`, and `site/widgets.js`. Templates can reference it as `{ kind: kanban_summary, max_rows: 3 }` in dashboard.json.
**iOS surface.** Read-only board on the project Kanban tab ([ScarfGoKanbanView](Scarf%20iOS/Kanban/ScarfGoKanbanView.swift) + [ScarfGoKanbanDetailSheet](Scarf%20iOS/Kanban/ScarfGoKanbanDetailSheet.swift)). Renders the 5 columns as a horizontally-paged `Picker` of single-column lists — HIG-friendly on iPhone. No mutations, no drag-drop in v2.7.5 (deferred to a later release). Card titles use semantic `.headline` (not `ScarfFont`) so Dynamic Type works; chrome (badges) keeps `ScarfBadge` for fixed visual weight. Gated on `HermesCapabilities.hasKanban`; pre-v0.12 hosts don't see the segment.
**Capability gating.** Kept the single `HermesCapabilities.hasKanban` flag (`>= 0.12.0`). All 27 verbs shipped together; finer-grained gating is YAGNI. A `hasKanbanWatch` flag will land in a later release if `watch` semantics drift between point releases.
**Don't:** introduce within-column reorder via a client-side ordering sidecar — sort order would diverge from dispatcher's actual run order, which is worse than no manual order. Use `priority` on `kanban create` to set initial order; revisit when Hermes ships an `update --priority` verb. Don't try to mutate `priority` / `title` / `body` post-create — there's no verb. Don't drop cards from `done` into anything — Done is terminal. Don't call `transport.runProcess` directly from view bodies; route through `KanbanService` (the actor) so polling and writes share the same concurrency model.
## Project Templates
Scarf ships a `.scarftemplate` format (v1 as of 2.2.0) for sharing pre-packaged projects across users and machines. A bundle is a zip containing:
+83
View File
@@ -0,0 +1,83 @@
## What's in 2.7.5
A feature release that lifts Scarf's Kanban surface from a read-only list (the v2.6 placeholder shipped while upstream Kanban was still mid-rework) to a full drag-and-drop board with the complete Hermes v0.12 mutation surface wired up — plus per-project boards bound to a Scarf-minted tenant slug, and a read-only board on iOS for at-a-glance status from your phone. No data migrations, no schema changes; pre-v0.12 hosts gracefully hide the surface.
### New features
#### Mac
- **Drag-and-drop Kanban board** ([scarf/Features/Kanban/Views/KanbanBoardView.swift](scarf/scarf/Features/Kanban/Views/KanbanBoardView.swift)). Five visible columns — Triage / Up Next (`todo` + `ready`) / Running / Blocked / Done — collapsing Hermes's seven status values into a layout that doesn't waste space on `ready`, which the dispatcher only ever holds for a few seconds. Triage hides itself when empty; archived hides behind a header toggle. Drop a card onto a column and Scarf maps the gesture to the right Hermes verbs through a pure transition planner: drop-on-Running fires `kanban dispatch` (the dispatcher then spawns a worker), drop-on-Blocked opens a sheet asking for a reason and calls `kanban block`, drop-on-Done opens a result sheet and calls `kanban complete`, blocked → running chains `unblock` + `dispatch`. Forbidden transitions (anything dropped on Done; anything dragged out of Triage) reject with a red drop-target stroke and a tooltip explaining why — Done is terminal, Triage is promoted by a specifier worker, neither has a CLI verb that maps cleanly. Optimistic local updates apply on drop and revert on CLI failure with a toast, so the UI feels instant.
- **Side-pane inspector** ([KanbanInspectorPane.swift](scarf/scarf/Features/Kanban/Views/KanbanInspectorPane.swift)). Click a card and a 420 px pane slides in from the trailing edge. Not a modal sheet — modal would block triaging the next card after closing. Header carries the status, an inline assignee menu (more on that below), workspace kind, and tenant; below that, four tabs render `hermes kanban show <id>` data: **Comments** (with an inline composer that calls `kanban comment`), **Events** (the `task_events` log with per-kind glyphs), **Runs** (one row per attempt with outcome badge + summary + error), and **Log** — the worker's captured stdout/stderr from `hermes kanban log <id>`, polled every 2 s while the task is running with a "● streaming" indicator and auto-scroll to the latest line, snapshot-only with a refresh button when the task is in a terminal state. The action bar at the bottom has all the per-status verbs — Start (which is `claim` rebranded as a user-visible action), Complete, Block, Unblock, Archive — every one with a help tooltip explaining what it does and what Hermes verb it invokes. The "Archive" tooltip explicitly notes Hermes has no hard-delete: archived tasks remain in `~/.hermes/kanban.db` and are recoverable via the "Show archived" toggle until `hermes kanban gc` runs.
- **Inspector auto-refresh.** While the inspector is open, the detail (header, action buttons, comments, events, runs) re-fetches every 5 s on the same cadence as the board itself, so a worker transition (e.g. running → done elsewhere) is reflected without the user having to close + reopen. The Log tab's 2 s poll runs separately and self-cancels the moment the task transitions out of `running`.
- **Inline assignee picker on the inspector header.** The assignee badge is a clickable menu — set means a `.brand` (rust) chip, unassigned means a `.warning` (yellow) chip so the eye catches it instantly. Tapping opens a menu of every known profile (union of `~/.hermes/profiles/`, current task assignees, and the active local profile from `HermesProfileResolver`) plus an "Unassigned" option. Selection routes through `kanban assign` and immediately follows with `kanban dispatch` so the task gets picked up promptly. Solves the "I assigned a profile but nothing happened" gap end-to-end without the user touching a terminal.
- **Health banner in the inspector.** Surfaces two conditions that previously left users staring at a stuck task with no explanation. **Yellow** when the task is unassigned in `ready` / `todo`: *"Won't run automatically — Hermes's dispatcher silently skips tasks with no assignee."* The dispatcher's own `--json` output literally lists these under `skipped_unassigned`; we now surface that to the human. **Red** when the most-recently-completed run ended in a non-success outcome (`stale_lock` / `crashed` / `gave_up` / `timed_out` / `spawn_failed` / `reclaimed` / `failed`): banner displays the outcome label + the raw `error` field from the run record, so you don't have to dig into the Runs tab to discover it. The red banner is suppressed while a fresh attempt is running — once status flips back to `running`, the previous outcome is stale signal and the Log tab's live stream is the right thing to look at.
- **Card-level signals.** Cards in `running` get a 2 px `ScarfColor.info` left edge + a subtle title shimmer so live work is obvious at a glance. Blocked cards get a 2 px `ScarfColor.warning` left edge + a ⚠ glyph next to the title. Done cards dim to 0.7 opacity in light mode, 0.55 in dark, with a green ✓ in the title row. Cards in `ready` / `todo` with no assignee get a yellow ⚠ glyph in the title row with a tooltip explaining the dispatcher won't pick them up — same signal as the inspector banner, just at the board level so triage is one keypress away.
- **`Board | List` toggle at the top of the route.** The v2.6 read-only list view is preserved in `KanbanListView.swift` and surfaced via a segmented picker, so users on narrow windows or anyone who prefers a flat sortable list can opt in. Choice persists across launches via `@AppStorage`.
- **New Task sheet** ([KanbanCreateSheet.swift](scarf/scarf/Features/Kanban/Views/KanbanCreateSheet.swift)). Title, body (markdown supported), assignee (defaults to `HermesProfileResolver.activeProfileName()` so newly-created tasks actually run), workspace kind (segmented `Scratch / Worktree / Project Dir`; locked to Project Dir on per-project boards), priority slider, comma-separated skills with autocomplete from `~/.hermes/skills/`, optional tenant (hidden on per-project boards — the slug is implicit), and a "Send to triage" toggle. Submit fires `kanban create --json` and immediately follows with `kanban dispatch` so an assigned task transitions `ready``running` within seconds rather than waiting for the gateway dispatcher's internal cycle.
- **Kanban moved from Manage → Monitor in the sidebar.** It's runtime work-in-progress, not configuration. Sits between Activity and the rest of Manage so users see "what's happening right now" at a glance.
#### Per-project Kanban
- **`DashboardTab.kanban` on every project**, capability-gated on `HermesCapabilities.hasKanban`. Renders a project-scoped `KanbanBoardView` filtered to the project's tenant slug. Workspace defaults in the New Task sheet are pre-pinned to `dir:<project.path>`. Empty state explains the project doesn't have any tasks yet and offers a "New Task" CTA — the empty board IS the discovery surface.
- **Tenant minting via [KanbanTenantResolver](scarf/scarf/Core/Services/KanbanTenantResolver.swift).** Each Scarf project gets a stable `scarf:<slug>` tenant minted on first kanban interaction and persisted to `<project>/.scarf/manifest.json` (new optional `kanbanTenant` field on `ProjectTemplateManifest`). Slug rules: lowercased, hyphenated, ≤ 48 chars, `scarf:` prefix to avoid collision with hand-typed tenants. Once minted, the tenant is **immutable across rename** — tasks already on the board carry the original slug, so renaming the project doesn't orphan them. Bare projects (no manifest) get a sentinel manifest written with `id: scarf/<project-id>` + `version: 0.0.0` + just the `kanbanTenant` set; the `ProjectAgentContextService` reader recognizes the sentinel and refuses to surface it as a "Template" line in the AGENTS.md block, so the project doesn't suddenly start advertising a fake template to the agent.
- **Agent-side tenant injection.** [ProjectAgentContextService.renderBlock](scarf/scarf/Core/Services/ProjectAgentContextService.swift) emits a "Kanban tenant" line inside the `<!-- scarf-project -->` markers in `<project>/AGENTS.md` whenever a tenant exists, instructing the agent to pass `--tenant scarf:<slug>` on `hermes kanban create`. `ChatViewModel.startACPSession` already calls `refresh(for:)` before opening every project chat, so the agent reads a fresh tenant on every session start with no extra wiring. Agents are imperfect at flag discipline; a forgotten `--tenant` lands the task in the global "Untagged" group rather than failing — acceptable v2.7.5 behavior.
- **`kanban_summary` dashboard widget** ([KanbanSummaryWidgetView.swift](scarf/scarf/Features/Projects/Views/Widgets/KanbanSummaryWidgetView.swift)). New widget kind for project dashboards: shows the top three `running` / `blocked` / `todo` tasks for the project's tenant by priority, plus a glance footer (`"12 todo · 3 running · 5 blocked"`) sourced from `kanban stats`. Polls every 10 s while the dashboard is foregrounded. Widget vocabulary registered in [tools/widget-schema.json](tools/widget-schema.json) and rendered on the catalog site via [site/widgets.js](site/widgets.js); template authors can drop a `{ kind: kanban_summary, max_rows: 3 }` block into `dashboard.json`.
#### iOS / iPadOS
- **Read-only Kanban tab on `ProjectDetailView`** ([Scarf iOS/Kanban/ScarfGoKanbanView.swift](scarf/Scarf%20iOS/Kanban/ScarfGoKanbanView.swift)). Same five-column collapse rendered as a horizontally-paged segmented `Picker` of single-column lists — HIG-friendly on iPhone where a 5-column grid forces unreadable card widths. Pulls live status, assignee, workspace, skills, priority chips. Tap a card → modal `NavigationStack` detail sheet ([ScarfGoKanbanDetailSheet.swift](scarf/Scarf%20iOS/Kanban/ScarfGoKanbanDetailSheet.swift)) with the same Comments / Events / Runs tabs the Mac inspector has. Read-only in v2.7.5 — mutations + drag-drop on iPad land in v2.8 once the Mac flow is fully shaken out. Card titles use semantic `.headline` (not `ScarfFont`) so Dynamic Type works; chrome (badges) stays on `ScarfBadge` for fixed visual weight per the project's iOS conventions.
#### ScarfCore
- **`KanbanService` actor** ([Packages/ScarfCore/Sources/ScarfCore/Services/KanbanService.swift](scarf/Packages/ScarfCore/Sources/ScarfCore/Services/KanbanService.swift)) — pure-I/O Sendable actor wrapping every Hermes v0.12 verb (`list / show / runs / stats / assignees / create / assign / claim / comment / complete / block / unblock / archive / dispatch / link / unlink / log`). Dispatches each CLI invocation through `Task.detached(priority: .utility)` matching the existing concurrency conventions. Errors land in [KanbanError](scarf/Packages/ScarfCore/Sources/ScarfCore/Models/KanbanError.swift) and surface as inline banners (not modal alerts) since the board is high-frequency. The "no matching tasks" stdout sentinel is normalized to `[]` rather than thrown.
- **Pure transition planner.** `KanbanService.plan(for: KanbanTransition)` is a synchronous function that maps a `(from, to)` column pair to the right verb sequence — `(.upNext, .running) → [.dispatch]`, `(.blocked, .running) → [.unblock, .dispatch]`, etc. Disallowed transitions throw `KanbanError.forbiddenTransition` with a user-actionable reason. The planner is fully tested in `KanbanModelsTests.swift`. Critically: `dispatch` (not `claim`) is the verb used for Up-Next → Running. Hermes's `claim` is documented as "manual alternative to the dispatcher" and assumes the caller spawns the worker themselves — Scarf doesn't, so calling `claim` from drag-drop reserved tasks but never spawned work, and the dispatcher reclaimed them ~15 minutes later (`stale_lock`). `dispatch` is the right primitive for a GUI client.
- **Cross-platform [KanbanTenantReader](scarf/Packages/ScarfCore/Sources/ScarfCore/Services/KanbanTenantReader.swift).** Read-only projection over `<project>/.scarf/manifest.json`'s `kanbanTenant` field. The full `ProjectTemplateManifest` type lives in the Mac target; this lightweight reader gives iOS a way to filter the per-project board by tenant without linking the full manifest model.
- **Timestamp decoding tolerates both shapes.** Hermes emits `created_at` / `started_at` / `completed_at` / `last_heartbeat_at` etc. as Unix integer seconds (its SQLite columns are INTEGER), but earlier wire docs implied ISO-8601 strings. The decoder now accepts either an integer or a string and normalizes to ISO-8601 so downstream code only handles one type. Locked in by `decodeUnixIntegerTimestamps` in `KanbanModelsTests`.
- **`KanbanBoardViewModel` optimistic merge.** Holds `optimisticOverrides: [taskId: status]` for in-flight drags; the polled response merges with optimistic state until the server confirms the new status, so a stale poll arriving milliseconds after a drop can't snap the card back to its old column. On CLI failure the override is removed and the message lands in the inline banner.
### Dispatch + assignee fixes
A diagnostic round driving real tasks end-to-end exposed a connected bug pattern that the polish pass closed:
- **Hermes's dispatcher silently skips unassigned tasks** — its `kanban dispatch --json` output literally lists them under a `skipped_unassigned` key and moves on. Tasks created without an assignee sat in `ready` indefinitely and the user had no signal anything was wrong. The New Task sheet now defaults to the active Hermes profile, the inspector header shows a yellow "Unassigned" chip + warning banner, every `ready` / `todo` card without an assignee gets a ⚠ glyph + tooltip, and the inspector's inline assignee picker fixes it in one click.
- **Drag-to-Running used to call `claim`**, which is a manual alternative to the dispatcher. Status flipped to `running`, but no worker spawned (Scarf doesn't host workers), and 15 minutes later the dispatcher reclaimed the task with a `stale_lock` outcome. Replaced with `dispatch` end-to-end so the gateway-running dispatcher actually does the spawning.
- **`hermes kanban assignees` empty-state was leaking into the picker.** The CLI prints a literal sentinel `(no assignees — create a profile with hermes -p <name> setup)` when the table is empty; the parser was tokenizing it on whitespace and offering `(no` as a profile in the menu. Parser now skips the sentinel, validates each candidate against `^[a-zA-Z0-9_-]+$`, and falls back cleanly to the active local profile when the table is empty.
- **`spawn_failed` from "executable not found on PATH"** — most subtle of the lot. macOS GUI apps inherit a launch-services PATH (`/usr/bin:/bin:/usr/sbin:/sbin`) that doesn't include `~/.local/bin` (where pipx installs `hermes`) or `/opt/homebrew/bin`. Scarf was finding `hermes` for its own invocation via the absolute-path resolver in `HermesPathSet.hermesBinaryCandidates`, but when the dispatcher then spawned a worker process, that worker inherited Scarf's GUI PATH and couldn't find `hermes` by name — recording an `outcome=spawn_failed` run with the exact "executable not found on PATH" message. `LocalTransport` now grows an `environmentEnricher` static (mirroring `SSHTransport.environmentEnricher`) wired by `scarfApp.swift` to the same `HermesFileService.enrichedEnvironment()` login-shell probe the SSH transport uses. Every local subprocess Scarf spawns now sees the user's full PATH and credential env, so a spawned-from-Scarf hermes can spawn its children by name without reaching for absolute paths. Defense-in-depth: `subprocessEnvironment(forExecutable:)` also unconditionally prepends the executable's parent directory to PATH, so the fix works even if the enricher hasn't been wired (early startup, tests).
### Migrating from 2.7.1
Sparkle will offer the update automatically. No config migration, no schema changes — `~/.hermes/kanban.db` is shared across all Hermes clients and Scarf only reads/writes through the documented CLI surface. Existing Scarf projects pick up the new project Kanban tab on first open; the tenant slug is minted lazily on first kanban interaction inside the project, so projects with no kanban activity stay byte-identical until the user opens the tab.
If you have an existing project with a Scarf-managed `manifest.json`, the new optional `kanbanTenant` field is added on next mint and lives alongside any template-author config schema without touching it. Templates do not ship `kanbanTenant` (it's user-machine-scoped state); the export pipeline strips it.
If you've been running tasks via the v2.6 read-only list and your Hermes host already runs the gateway dispatcher, your existing kanban tasks should appear on the board automatically — there's no migration step. Tasks created without an assignee in v2.6 will now show the yellow "Unassigned" warning until you fix them through the inline picker.
### Known limitations
- **Within-column reorder is not supported.** Hermes has no `update` verb and no `position` column on the tasks table — `priority` is write-once at create time. Sort order inside each column is `priority DESC, created_at DESC`, matching the dispatcher's actual run order. We considered a client-side ordering sidecar; rejected because the on-screen order would diverge from what runs next, which is worse than no manual order. Will revisit if Hermes ships an `update --priority` verb.
- **No live `watch` streaming yet.** The board polls every 5 s; the inspector polls detail on the same cadence and the Log tab on a 2 s cadence while running. `hermes kanban watch --json` event streaming + reconnect-with-backoff lands in v2.8 along with iOS write surfaces.
- **No bulk re-tag for legacy NULL-tenant tasks.** Tasks created before this release (assignee or no assignee) appear in the global "Untagged" group on the global board. Hermes has no `tenant` mutation verb post-create, so retagging would be archive + recreate — too destructive to ship in this release.
### Acknowledgements
- Driven end-to-end against a fresh local Hermes v0.12.0 install with the gateway dispatcher running. Real bug surface mostly came from doing instead of speculating: the `claim` vs `dispatch` distinction, the silent `skipped_unassigned` behavior, the `(no` parse leak, the integer-vs-ISO timestamp shape, and the stale "Last run" banner during a fresh attempt all surfaced from driving real tasks and watching what actually happened.
@@ -311,6 +311,14 @@ public actor ACPClient {
let result = try await sendRequest(method: "session/prompt", params: params)
let dict = result?.dictValue ?? [:]
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"
return ACPPromptResult(
@@ -318,7 +326,8 @@ public actor ACPClient {
inputTokens: usage["inputTokens"] as? Int ?? 0,
outputTokens: usage["outputTokens"] 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 thoughtTokens: 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(
stopReason: String,
inputTokens: Int,
outputTokens: Int,
thoughtTokens: Int,
cachedReadTokens: Int
cachedReadTokens: Int,
compressionCount: Int = 0
) {
self.stopReason = stopReason
self.inputTokens = inputTokens
self.outputTokens = outputTokens
self.thoughtTokens = thoughtTokens
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 toolPreviewLength: Int
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(
@@ -46,7 +53,8 @@ public struct DisplaySettings: Sendable, Equatable {
inlineDiffs: Bool,
toolProgressCommand: Bool,
toolPreviewLength: Int,
busyInputMode: String
busyInputMode: String,
language: String = ""
) {
self.skin = skin
self.compact = compact
@@ -56,6 +64,7 @@ public struct DisplaySettings: Sendable, Equatable {
self.toolProgressCommand = toolProgressCommand
self.toolPreviewLength = toolPreviewLength
self.busyInputMode = busyInputMode
self.language = language
}
public nonisolated static let empty = DisplaySettings(
skin: "default",
@@ -65,7 +74,8 @@ public struct DisplaySettings: Sendable, Equatable {
inlineDiffs: true,
toolProgressCommand: false,
toolPreviewLength: 0,
busyInputMode: "interrupt"
busyInputMode: "interrupt",
language: ""
)
}
@@ -190,6 +200,15 @@ public struct VoiceSettings: Sendable, Equatable {
public var ttsOpenAIVoice: String
public var ttsNeuTTSModel: 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
public var sttEnabled: Bool
@@ -217,7 +236,9 @@ public struct VoiceSettings: Sendable, Equatable {
sttLocalModel: String,
sttLocalLanguage: String,
sttOpenAIModel: String,
sttMistralModel: String
sttMistralModel: String,
ttsXAIVoiceID: String = "",
ttsXAIModel: String = ""
) {
self.recordKey = recordKey
self.maxRecordingSeconds = maxRecordingSeconds
@@ -230,6 +251,8 @@ public struct VoiceSettings: Sendable, Equatable {
self.ttsOpenAIVoice = ttsOpenAIVoice
self.ttsNeuTTSModel = ttsNeuTTSModel
self.ttsNeuTTSDevice = ttsNeuTTSDevice
self.ttsXAIVoiceID = ttsXAIVoiceID
self.ttsXAIModel = ttsXAIModel
self.sttEnabled = sttEnabled
self.sttProvider = sttProvider
self.sttLocalModel = sttLocalModel
@@ -254,7 +277,9 @@ public struct VoiceSettings: Sendable, Equatable {
sttLocalModel: "base",
sttLocalLanguage: "",
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;
/// useful for cost auditing and screen-recording demos.
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
public var display: DisplaySettings
@@ -747,11 +814,23 @@ public struct HermesConfig: Sendable {
homeAssistant: HomeAssistantSettings,
cacheTTL: String = "5m",
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.redactionEnabled = redactionEnabled
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.provider = provider
self.maxTurns = maxTurns
@@ -28,6 +28,12 @@ public struct HermesCronJob: Identifiable, Sendable, Codable {
/// job's prompt. YAML-only field today (no `--context-from` CLI
/// flag yet) Scarf displays it but doesn't write it.
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 {
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 workdir
case contextFrom = "context_from"
case noAgent = "no_agent"
}
/// Memberwise init. Swift doesn't synthesize one for us because
@@ -66,7 +73,8 @@ public struct HermesCronJob: Identifiable, Sendable, Codable {
timeoutSeconds: Int? = nil,
silent: Bool? = nil,
workdir: String? = nil,
contextFrom: [String]? = nil
contextFrom: [String]? = nil,
noAgent: Bool? = nil
) {
self.id = id
self.name = name
@@ -88,6 +96,7 @@ public struct HermesCronJob: Identifiable, Sendable, Codable {
self.silent = silent
self.workdir = workdir
self.contextFrom = contextFrom
self.noAgent = noAgent
}
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.workdir = try c.decodeIfPresent(String.self, forKey: .workdir)
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 {
@@ -136,6 +146,7 @@ public struct HermesCronJob: Identifiable, Sendable, Codable {
try c.encodeIfPresent(silent, forKey: .silent)
try c.encodeIfPresent(workdir, forKey: .workdir)
try c.encodeIfPresent(contextFrom, forKey: .contextFrom)
try c.encodeIfPresent(noAgent, forKey: .noAgent)
}
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))
}
}
@@ -0,0 +1,32 @@
import Foundation
/// One row from `hermes kanban assignees --json`. The output is the
/// union of profiles configured on the host (`~/.hermes/profiles/`)
/// and any names appearing in the live board's `assignee` column
/// covers the case where a profile was renamed but historical tasks
/// still reference the old name.
public struct HermesKanbanAssignee: Sendable, Equatable, Identifiable, Codable {
public var id: String { profile }
public let profile: String
public let activeCount: Int
public let totalCount: Int
public init(profile: String, activeCount: Int = 0, totalCount: Int = 0) {
self.profile = profile
self.activeCount = activeCount
self.totalCount = totalCount
}
enum CodingKeys: String, CodingKey {
case profile
case activeCount = "active"
case totalCount = "total"
}
public init(from decoder: any Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
self.profile = try c.decode(String.self, forKey: .profile)
self.activeCount = try c.decodeIfPresent(Int.self, forKey: .activeCount) ?? 0
self.totalCount = try c.decodeIfPresent(Int.self, forKey: .totalCount) ?? 0
}
}
@@ -0,0 +1,51 @@
import Foundation
/// One comment from `hermes kanban show <id> --json` or appended via
/// `hermes kanban comment <id> <text>`. Comments are append-only there's
/// no edit/delete verb.
public struct HermesKanbanComment: Sendable, Equatable, Identifiable, Codable {
public let id: Int
public let taskId: String
public let author: String
public let body: String
public let createdAt: String
public init(
id: Int,
taskId: String,
author: String,
body: String,
createdAt: String
) {
self.id = id
self.taskId = taskId
self.author = author
self.body = body
self.createdAt = createdAt
}
enum CodingKeys: String, CodingKey {
case id
case taskId = "task_id"
case author
case body
case createdAt = "created_at"
}
public init(from decoder: any Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
self.id = try c.decode(Int.self, forKey: .id)
self.taskId = try c.decodeIfPresent(String.self, forKey: .taskId) ?? ""
self.author = try c.decodeIfPresent(String.self, forKey: .author) ?? ""
self.body = try c.decodeIfPresent(String.self, forKey: .body) ?? ""
// Hermes emits Unix integer timestamps from its SQLite columns;
// accept both ints and ISO strings.
if let unix = try? c.decodeIfPresent(Double.self, forKey: .createdAt) {
let f = ISO8601DateFormatter()
f.formatOptions = [.withInternetDateTime]
self.createdAt = f.string(from: Date(timeIntervalSince1970: unix))
} else {
self.createdAt = (try? c.decodeIfPresent(String.self, forKey: .createdAt)) ?? ""
}
}
}
@@ -0,0 +1,158 @@
import Foundation
/// A structured signal Hermes emits when it observes worker / task
/// distress. Hermes v0.13 introduced a generic diagnostics engine that
/// attaches these to a task (cross-run signals) and/or a run (per-attempt
/// signals). Pre-v0.13 hosts never emit diagnostics so the array decodes
/// empty and downstream UI no-ops.
///
/// **Wire shape (best inference from release notes verify against live
/// JSON during integration):** an array of objects with `kind`, optional
/// `message`, optional `detected_at` (ISO-8601 string OR Unix integer,
/// matching the rest of `HermesKanbanTask`'s timestamp tolerance).
///
/// **Forward compat:** `kind` stays a `String` so a future Hermes can
/// add new diagnostic kinds without a Scarf release. `KanbanDiagnosticKind`
/// is the typed mirror it falls back to `.unknown` for unrecognized
/// kinds and renders the raw string verbatim.
public struct HermesKanbanDiagnostic: Sendable, Equatable, Identifiable, Codable {
/// Synthetic id not on the wire. Lets SwiftUI `ForEach` over a
/// diagnostic array without forcing a deterministic id from the
/// server (Hermes doesn't currently mint one).
public let id: UUID
/// Wire-side `kind` string. Compared case-insensitively via
/// `KanbanDiagnosticKind.from(_:)`.
public let kind: String
/// Human-friendly elaboration ("no heartbeat for 4m20s", "exit code
/// 0 with no complete call", etc.). May be nil; render the raw
/// `kind` then.
public let message: String?
/// ISO-8601 string. Decoder accepts Unix integer seconds (Hermes's
/// SQLite-backed shape) and converts to ISO-8601 so consumers see
/// one type same pattern as `HermesKanbanTask.decodeFlexibleTimestamp`.
public let detectedAt: String?
public init(
kind: String,
message: String? = nil,
detectedAt: String? = nil
) {
self.id = UUID()
self.kind = kind
self.message = message
self.detectedAt = detectedAt
}
enum CodingKeys: String, CodingKey {
case kind
case message
case detectedAt = "detected_at"
}
public init(from decoder: any Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
self.id = UUID()
self.kind = try c.decodeIfPresent(String.self, forKey: .kind) ?? "unknown"
self.message = try c.decodeIfPresent(String.self, forKey: .message)
// Flexible timestamp decode mirrors HermesKanbanTask's pattern.
if !c.contains(.detectedAt) {
self.detectedAt = nil
} else if let unix = try? c.decodeIfPresent(Double.self, forKey: .detectedAt) {
let date = Date(timeIntervalSince1970: unix)
self.detectedAt = Self.isoFormatter.string(from: date)
} else {
self.detectedAt = try c.decodeIfPresent(String.self, forKey: .detectedAt)
}
}
public func encode(to encoder: any Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
try c.encode(kind, forKey: .kind)
try c.encodeIfPresent(message, forKey: .message)
try c.encodeIfPresent(detectedAt, forKey: .detectedAt)
}
public static func == (lhs: HermesKanbanDiagnostic, rhs: HermesKanbanDiagnostic) -> Bool {
// Compare on wire fields, not synthetic id round-trip decoding
// mints fresh ids.
lhs.kind == rhs.kind
&& lhs.message == rhs.message
&& lhs.detectedAt == rhs.detectedAt
}
private static let isoFormatter: ISO8601DateFormatter = {
let f = ISO8601DateFormatter()
f.formatOptions = [.withInternetDateTime]
return f
}()
}
// MARK: - Typed mirror
/// Typed view of `HermesKanbanDiagnostic.kind`. Models keep the raw
/// string for forward compatibility; UI helpers read this enum to pick
/// the right glyph + tint without string-matching at every callsite.
///
/// `unknown` is the fallback for any kind a future Hermes adds that
/// Scarf doesn't recognize. Views render the raw string verbatim in
/// that case so the user still sees what Hermes flagged.
// TODO(WS-3-Q5): The exact `kind` string for darwin-zombie detection is
// inferred from the v0.13 release notes ("Detect darwin zombie workers");
// confirm against live `hermes kanban show --json` output during
// integration. Same for `worker_exit_no_complete` and the heartbeat-stalled
// kinds typed mirror falls through to `.unknown` if the wire string
// drifts, and the raw string is still rendered.
public enum KanbanDiagnosticKind: String, Sendable, CaseIterable {
case heartbeatStalled = "heartbeat_stalled"
case toolErrorLoop = "tool_error_loop"
case retryCapHit = "retry_cap_hit"
case unboundedRetry = "unbounded_retry"
case darwinZombieDetected = "darwin_zombie_detected"
case spawnFailure = "spawn_failure"
case workerExitNoComplete = "worker_exit_no_complete"
case unknown
/// Map a wire string (case-insensitive) to a typed kind. Unknown
/// values fall through to `.unknown` so callers can still surface
/// the raw string.
public static func from(_ raw: String) -> KanbanDiagnosticKind {
KanbanDiagnosticKind(rawValue: raw.lowercased()) ?? .unknown
}
/// SF Symbol name to render alongside the diagnostic. View code
/// reaches through the typed enum so glyph choices live in one
/// place.
public var glyphName: String {
switch self {
case .heartbeatStalled: return "waveform.path.badge.minus"
case .toolErrorLoop: return "arrow.triangle.2.circlepath.exclamationmark"
case .retryCapHit: return "nosign"
case .unboundedRetry: return "arrow.clockwise.circle.fill"
case .darwinZombieDetected: return "apple.logo"
case .spawnFailure: return "bolt.slash"
case .workerExitNoComplete: return "figure.walk.departure"
case .unknown: return "stethoscope"
}
}
/// Severity tier for this kind drives badge tint. `.danger` for
/// terminal-class signals (retry cap hit, zombie, spawn failure);
/// `.warning` for recoverable signals (heartbeat stalled, tool
/// error loop); `.neutral` only for unknown / forward-compat kinds.
public var severity: DiagnosticSeverity {
switch self {
case .retryCapHit, .darwinZombieDetected, .spawnFailure:
return .danger
case .heartbeatStalled, .toolErrorLoop, .unboundedRetry, .workerExitNoComplete:
return .warning
case .unknown:
return .neutral
}
}
public enum DiagnosticSeverity: Sendable {
case warning
case danger
case neutral
}
}
@@ -0,0 +1,175 @@
import Foundation
/// One event from the `task_events` log emitted by `hermes kanban show`
/// (within a `HermesKanbanTaskDetail`) and streamed live by
/// `hermes kanban watch --json`. Event kinds are open-ended on the Hermes
/// side; v0.12 emits a small known set listed in `KanbanEventKind`. Unknown
/// kinds map to `.unknown` so new Hermes builds don't break decoding.
public struct HermesKanbanEvent: Sendable, Equatable, Identifiable, Codable {
public let id: Int
public let taskId: String
public let runId: Int?
/// Wire string for the event kind. Use `kindEnum` to interpret.
public let kind: String
public let createdAt: String
/// Opaque diagnostics payload from the `task_events.payload` column.
/// Stored as a JSON string so callers that don't need it pay no
/// decoding cost; callers that do can re-parse.
public let payloadJSON: String?
public init(
id: Int,
taskId: String,
runId: Int? = nil,
kind: String,
createdAt: String,
payloadJSON: String? = nil
) {
self.id = id
self.taskId = taskId
self.runId = runId
self.kind = kind
self.createdAt = createdAt
self.payloadJSON = payloadJSON
}
public var kindEnum: KanbanEventKind { KanbanEventKind.from(kind) }
enum CodingKeys: String, CodingKey {
case id
case taskId = "task_id"
case runId = "run_id"
case kind
case createdAt = "created_at"
case payload
}
public init(from decoder: any Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
self.id = try c.decodeIfPresent(Int.self, forKey: .id) ?? 0
self.taskId = try c.decodeIfPresent(String.self, forKey: .taskId) ?? ""
self.runId = try c.decodeIfPresent(Int.self, forKey: .runId)
self.kind = try c.decodeIfPresent(String.self, forKey: .kind) ?? "unknown"
if let unix = try? c.decodeIfPresent(Double.self, forKey: .createdAt) {
let f = ISO8601DateFormatter()
f.formatOptions = [.withInternetDateTime]
self.createdAt = f.string(from: Date(timeIntervalSince1970: unix))
} else {
self.createdAt = (try? c.decodeIfPresent(String.self, forKey: .createdAt)) ?? ""
}
// payload may be absent, a JSON object, or already a string.
if let raw = try? c.decodeIfPresent(String.self, forKey: .payload) {
self.payloadJSON = raw
} else if c.contains(.payload) {
// Re-encode arbitrary JSON into a string so we can carry it
// around without committing to a typed shape.
let nested = try c.decode(JSONAny.self, forKey: .payload)
let data = try JSONEncoder().encode(nested)
self.payloadJSON = String(data: data, encoding: .utf8)
} else {
self.payloadJSON = nil
}
}
public func encode(to encoder: any Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
try c.encode(id, forKey: .id)
try c.encode(taskId, forKey: .taskId)
try c.encodeIfPresent(runId, forKey: .runId)
try c.encode(kind, forKey: .kind)
try c.encode(createdAt, forKey: .createdAt)
try c.encodeIfPresent(payloadJSON, forKey: .payload)
}
}
/// Known event kinds emitted by Hermes v0.12+. New kinds are surfaced
/// as `.unknown` until the model catches up; UI defaults to a generic
/// rendering for those.
public enum KanbanEventKind: String, Sendable, CaseIterable {
case created
case claimed
case released
case started
case completed
case blocked
case unblocked
case commented
case archived
case heartbeat
case statusChange = "status_change"
case error
case crashed
case timedOut = "timed_out"
case spawnFailed = "spawn_failed"
case unknown
public static func from(_ raw: String) -> KanbanEventKind {
KanbanEventKind(rawValue: raw.lowercased()) ?? .unknown
}
}
// MARK: - JSON-any helper
/// Minimal type-erased JSON wrapper used for opaque event payloads. We
/// don't commit to a typed shape because Hermes treats payload as
/// diagnostics and may evolve it freely. Used only inside Codable
/// init/encode (a single decodere-encodestring pass), so the `Any`
/// payload never crosses an actor boundary `@unchecked Sendable`
/// is the appropriate seal here.
struct JSONAny: Codable, @unchecked Sendable {
let raw: Any
init(from decoder: any Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
self.raw = NSNull()
} else if let b = try? container.decode(Bool.self) {
self.raw = b
} else if let i = try? container.decode(Int64.self) {
self.raw = i
} else if let d = try? container.decode(Double.self) {
self.raw = d
} else if let s = try? container.decode(String.self) {
self.raw = s
} else if let arr = try? container.decode([JSONAny].self) {
self.raw = arr.map(\.raw)
} else if let dict = try? container.decode([String: JSONAny].self) {
self.raw = dict.mapValues(\.raw)
} else {
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Unsupported JSON value"
)
}
}
func encode(to encoder: any Encoder) throws {
var c = encoder.singleValueContainer()
switch raw {
case is NSNull:
try c.encodeNil()
case let b as Bool:
try c.encode(b)
case let i as Int64:
try c.encode(i)
case let i as Int:
try c.encode(Int64(i))
case let d as Double:
try c.encode(d)
case let s as String:
try c.encode(s)
case let arr as [Any]:
try c.encode(arr.map { JSONAny(unsafeRaw: $0) })
case let dict as [String: Any]:
try c.encode(dict.mapValues { JSONAny(unsafeRaw: $0) })
default:
throw EncodingError.invalidValue(
raw,
EncodingError.Context(codingPath: encoder.codingPath, debugDescription: "Unsupported")
)
}
}
private init(unsafeRaw: Any) { self.raw = unsafeRaw }
}
@@ -0,0 +1,170 @@
import Foundation
/// One attempt to execute a kanban task `hermes kanban runs <id> --json`
/// returns an array of these per task. Each run records the worker
/// profile that claimed the task, the outcome, and a structured
/// metadata blob the worker handed back.
public struct HermesKanbanRun: Sendable, Equatable, Identifiable, Codable {
public let id: Int
public let taskId: String
public let profile: String?
public let stepKey: String?
public let status: String // running | done | blocked | crashed | timed_out | failed | released
public let claimLock: String? // "host:pid" at spawn time
public let claimExpires: Int?
public let workerPid: Int?
public let maxRuntimeSeconds: Int?
public let lastHeartbeatAt: String?
public let startedAt: String
public let endedAt: String?
public let outcome: String? // completed | blocked | crashed | timed_out | spawn_failed | gave_up | reclaimed
public let summary: String?
public let error: String?
/// `metadata` is an opaque JSON dict from the worker. Carried as a
/// raw string so we don't lock the typed shape.
public let metadataJSON: String?
// v0.13 (v2026.5.7) fields. Both Optional / empty-default so a v0.12
// host's run row decodes without error.
/// Per-attempt distress signals. Cross-run signals (retry cap hit,
/// etc.) hang off `HermesKanbanTask.diagnostics`; in-flight signals
/// (heartbeat stalled, darwin zombie detected) attach here.
public let diagnostics: [HermesKanbanDiagnostic]
/// Server-side unified failure counter (renamed from three separate
/// spawn / timeout / crash counters in v0.13). Optional when nil,
/// callers fall back to counting failed runs in the runs array.
// TODO(WS-3-Q4): Verify whether v0.13 exposes this field on the per-run
// shape OR only at the task level. Tolerant decode handles either.
public let failureCount: Int?
public init(
id: Int,
taskId: String,
profile: String? = nil,
stepKey: String? = nil,
status: String,
claimLock: String? = nil,
claimExpires: Int? = nil,
workerPid: Int? = nil,
maxRuntimeSeconds: Int? = nil,
lastHeartbeatAt: String? = nil,
startedAt: String,
endedAt: String? = nil,
outcome: String? = nil,
summary: String? = nil,
error: String? = nil,
metadataJSON: String? = nil,
diagnostics: [HermesKanbanDiagnostic] = [],
failureCount: Int? = nil
) {
self.id = id
self.taskId = taskId
self.profile = profile
self.stepKey = stepKey
self.status = status
self.claimLock = claimLock
self.claimExpires = claimExpires
self.workerPid = workerPid
self.maxRuntimeSeconds = maxRuntimeSeconds
self.lastHeartbeatAt = lastHeartbeatAt
self.startedAt = startedAt
self.endedAt = endedAt
self.outcome = outcome
self.summary = summary
self.error = error
self.metadataJSON = metadataJSON
self.diagnostics = diagnostics
self.failureCount = failureCount
}
enum CodingKeys: String, CodingKey {
case id
case taskId = "task_id"
case profile
case stepKey = "step_key"
case status
case claimLock = "claim_lock"
case claimExpires = "claim_expires"
case workerPid = "worker_pid"
case maxRuntimeSeconds = "max_runtime_seconds"
case lastHeartbeatAt = "last_heartbeat_at"
case startedAt = "started_at"
case endedAt = "ended_at"
case outcome
case summary
case error
case metadata
case diagnostics
case failureCount = "failure_count"
}
public init(from decoder: any Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
self.id = try c.decodeIfPresent(Int.self, forKey: .id) ?? 0
self.taskId = try c.decodeIfPresent(String.self, forKey: .taskId) ?? ""
self.profile = try c.decodeIfPresent(String.self, forKey: .profile)
self.stepKey = try c.decodeIfPresent(String.self, forKey: .stepKey)
self.status = try c.decodeIfPresent(String.self, forKey: .status) ?? "unknown"
self.claimLock = try c.decodeIfPresent(String.self, forKey: .claimLock)
self.claimExpires = try c.decodeIfPresent(Int.self, forKey: .claimExpires)
self.workerPid = try c.decodeIfPresent(Int.self, forKey: .workerPid)
self.maxRuntimeSeconds = try c.decodeIfPresent(Int.self, forKey: .maxRuntimeSeconds)
let f = ISO8601DateFormatter()
f.formatOptions = [.withInternetDateTime]
if let unix = try? c.decodeIfPresent(Double.self, forKey: .lastHeartbeatAt) {
self.lastHeartbeatAt = f.string(from: Date(timeIntervalSince1970: unix))
} else {
self.lastHeartbeatAt = try c.decodeIfPresent(String.self, forKey: .lastHeartbeatAt)
}
if let unix = try? c.decodeIfPresent(Double.self, forKey: .startedAt) {
self.startedAt = f.string(from: Date(timeIntervalSince1970: unix))
} else {
self.startedAt = (try? c.decodeIfPresent(String.self, forKey: .startedAt)) ?? ""
}
if let unix = try? c.decodeIfPresent(Double.self, forKey: .endedAt) {
self.endedAt = f.string(from: Date(timeIntervalSince1970: unix))
} else {
self.endedAt = try c.decodeIfPresent(String.self, forKey: .endedAt)
}
self.outcome = try c.decodeIfPresent(String.self, forKey: .outcome)
self.summary = try c.decodeIfPresent(String.self, forKey: .summary)
self.error = try c.decodeIfPresent(String.self, forKey: .error)
if let raw = try? c.decodeIfPresent(String.self, forKey: .metadata) {
self.metadataJSON = raw
} else if c.contains(.metadata) {
let nested = try c.decode(JSONAny.self, forKey: .metadata)
let data = try JSONEncoder().encode(nested)
self.metadataJSON = String(data: data, encoding: .utf8)
} else {
self.metadataJSON = nil
}
// v0.13 diagnostics array `try?` so a malformed entry doesn't
// poison the whole run row. Empty default for pre-v0.13 hosts.
self.diagnostics = (try? c.decodeIfPresent([HermesKanbanDiagnostic].self, forKey: .diagnostics)) ?? []
self.failureCount = try c.decodeIfPresent(Int.self, forKey: .failureCount)
}
public func encode(to encoder: any Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
try c.encode(id, forKey: .id)
try c.encode(taskId, forKey: .taskId)
try c.encodeIfPresent(profile, forKey: .profile)
try c.encodeIfPresent(stepKey, forKey: .stepKey)
try c.encode(status, forKey: .status)
try c.encodeIfPresent(claimLock, forKey: .claimLock)
try c.encodeIfPresent(claimExpires, forKey: .claimExpires)
try c.encodeIfPresent(workerPid, forKey: .workerPid)
try c.encodeIfPresent(maxRuntimeSeconds, forKey: .maxRuntimeSeconds)
try c.encodeIfPresent(lastHeartbeatAt, forKey: .lastHeartbeatAt)
try c.encode(startedAt, forKey: .startedAt)
try c.encodeIfPresent(endedAt, forKey: .endedAt)
try c.encodeIfPresent(outcome, forKey: .outcome)
try c.encodeIfPresent(summary, forKey: .summary)
try c.encodeIfPresent(error, forKey: .error)
try c.encodeIfPresent(metadataJSON, forKey: .metadata)
try c.encode(diagnostics, forKey: .diagnostics)
try c.encodeIfPresent(failureCount, forKey: .failureCount)
}
}
@@ -0,0 +1,68 @@
import Foundation
/// Output of `hermes kanban stats --json`. Drives the toolbar glance
/// ("12 todo · 3 running · 5 blocked"), the per-project Kanban summary
/// widget, and the column-count badges on the board header.
public struct HermesKanbanStats: Sendable, Equatable, Codable {
public let byStatus: [String: Int]
public let byAssignee: [String: Int]
public let byTenant: [String: Int]
/// Age in seconds of the oldest task currently in the `ready` status.
/// `nil` when no tasks are ready. Helps surface a stuck dispatcher.
public let oldestReadyAgeSeconds: Double?
public init(
byStatus: [String: Int],
byAssignee: [String: Int] = [:],
byTenant: [String: Int] = [:],
oldestReadyAgeSeconds: Double? = nil
) {
self.byStatus = byStatus
self.byAssignee = byAssignee
self.byTenant = byTenant
self.oldestReadyAgeSeconds = oldestReadyAgeSeconds
}
public static let empty = HermesKanbanStats(byStatus: [:])
enum CodingKeys: String, CodingKey {
case byStatus = "by_status"
case byAssignee = "by_assignee"
case byTenant = "by_tenant"
case oldestReadyAgeSeconds = "oldest_ready_age_seconds"
}
public init(from decoder: any Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
self.byStatus = try c.decodeIfPresent([String: Int].self, forKey: .byStatus) ?? [:]
self.byAssignee = try c.decodeIfPresent([String: Int].self, forKey: .byAssignee) ?? [:]
self.byTenant = try c.decodeIfPresent([String: Int].self, forKey: .byTenant) ?? [:]
self.oldestReadyAgeSeconds = try c.decodeIfPresent(Double.self, forKey: .oldestReadyAgeSeconds)
}
/// "12 todo · 3 running · 5 blocked" formatted glance string. Skips
/// empty buckets and never includes archived. Returns an empty
/// string when there's nothing to show so callers can hide chrome.
public var glanceString: String {
let order: [(String, String)] = [
("todo", "todo"),
("ready", "ready"),
("running", "running"),
("blocked", "blocked"),
("done", "done")
]
let parts = order.compactMap { (key, label) -> String? in
guard let n = byStatus[key], n > 0 else { return nil }
return "\(n) \(label)"
}
return parts.joined(separator: " · ")
}
/// Active task count across the board (everything except archived
/// and done). Used as a badge on the sidebar / project tab.
public var activeCount: Int {
["triage", "todo", "ready", "running", "blocked"]
.map { byStatus[$0] ?? 0 }
.reduce(0, +)
}
}
@@ -2,11 +2,16 @@ import Foundation
/// One task from `hermes kanban list --json` (v0.12+).
///
/// Hermes ships a SQLite-backed task board under `~/.hermes/kanban.db`
/// multi-profile collaboration was reverted upstream while the
/// design is reworked, so Scarf v2.6 surfaces this as a read-only
/// list. Create / claim / dispatch / dependency-link UI is deferred
/// until upstream stabilizes.
/// Hermes ships a SQLite-backed task board under `~/.hermes/kanban.db`.
/// v2.6 surfaced this as a read-only list; v2.7.5 lifts it to a full
/// drag-and-drop board with the complete write surface (`create`,
/// `claim`, `complete`, `block`, `unblock`, `archive`, `assign`,
/// `link`/`unlink`, `comment`, `dispatch`).
///
/// Hermes has no `update` verb `priority` / `title` / `body` /
/// `tenant` / `max_retries` are write-once at create time. Mutations
/// after that are expressed as state transitions (status, assignee) or
/// new comments.
public struct HermesKanbanTask: Sendable, Equatable, Identifiable, Codable {
public let id: String
public let title: String
@@ -24,6 +29,35 @@ public struct HermesKanbanTask: Sendable, Equatable, Identifiable, Codable {
public let result: String?
public let skills: [String]
// v2.7.5 fields exposed by `kanban show --json` and `kanban watch`.
public let idempotencyKey: String?
public let lastHeartbeatAt: String?
public let maxRuntimeSeconds: Int?
public let currentRunId: Int?
// v0.13 (v2026.5.7) reliability + recovery fields. All Optional with
// `nil` decoded for pre-v0.13 hosts so the v2.7.5 surface keeps
// rendering unchanged when the connected Hermes hasn't shipped them.
/// Per-task retry budget set at create time via `--max-retries N`.
/// Hermes pattern is write-once no `set_max_retries` verb. Scarf
/// surfaces this read-only on the inspector header.
public let maxRetries: Int?
/// Server-supplied reason a task was auto-blocked (e.g. "worker
/// exited (code 0) without calling `kanban complete`"). Surfaced
/// verbatim in the inspector banner.
public let autoBlockedReason: String?
/// `pending` / `verified` / `rejected` / nil. Pending means a worker
/// claimed it created this card but Hermes hasn't confirmed the
/// underlying work exists. Read through `KanbanHallucinationGate.from`
/// to map to a typed mirror kept as a String at the wire level so
/// Hermes can add new gate states (e.g. `quarantined`) without a
/// Scarf release.
public let hallucinationGateStatus: String?
/// Cross-run distress signals (retry cap hit, etc.). Per-run signals
/// hang off `HermesKanbanRun.diagnostics`. Empty array for pre-v0.13
/// hosts AND for tasks the diagnostics engine hasn't flagged.
public let diagnostics: [HermesKanbanDiagnostic]
public init(
id: String,
title: String,
@@ -39,7 +73,15 @@ public struct HermesKanbanTask: Sendable, Equatable, Identifiable, Codable {
startedAt: String? = nil,
completedAt: String? = nil,
result: String? = nil,
skills: [String] = []
skills: [String] = [],
idempotencyKey: String? = nil,
lastHeartbeatAt: String? = nil,
maxRuntimeSeconds: Int? = nil,
currentRunId: Int? = nil,
maxRetries: Int? = nil,
autoBlockedReason: String? = nil,
hallucinationGateStatus: String? = nil,
diagnostics: [HermesKanbanDiagnostic] = []
) {
self.id = id
self.title = title
@@ -56,6 +98,14 @@ public struct HermesKanbanTask: Sendable, Equatable, Identifiable, Codable {
self.completedAt = completedAt
self.result = result
self.skills = skills
self.idempotencyKey = idempotencyKey
self.lastHeartbeatAt = lastHeartbeatAt
self.maxRuntimeSeconds = maxRuntimeSeconds
self.currentRunId = currentRunId
self.maxRetries = maxRetries
self.autoBlockedReason = autoBlockedReason
self.hallucinationGateStatus = hallucinationGateStatus
self.diagnostics = diagnostics
}
enum CodingKeys: String, CodingKey {
@@ -67,6 +117,14 @@ public struct HermesKanbanTask: Sendable, Equatable, Identifiable, Codable {
case startedAt = "started_at"
case completedAt = "completed_at"
case result, skills
case idempotencyKey = "idempotency_key"
case lastHeartbeatAt = "last_heartbeat_at"
case maxRuntimeSeconds = "max_runtime_seconds"
case currentRunId = "current_run_id"
case maxRetries = "max_retries"
case autoBlockedReason = "auto_blocked_reason"
case hallucinationGateStatus = "hallucination_gate_status"
case diagnostics
}
public init(from decoder: any Decoder) throws {
@@ -81,10 +139,144 @@ public struct HermesKanbanTask: Sendable, Equatable, Identifiable, Codable {
self.workspaceKind = try c.decodeIfPresent(String.self, forKey: .workspaceKind)
self.workspacePath = try c.decodeIfPresent(String.self, forKey: .workspacePath)
self.createdBy = try c.decodeIfPresent(String.self, forKey: .createdBy)
self.createdAt = try c.decodeIfPresent(String.self, forKey: .createdAt)
self.startedAt = try c.decodeIfPresent(String.self, forKey: .startedAt)
self.completedAt = try c.decodeIfPresent(String.self, forKey: .completedAt)
// Hermes emits timestamps as Unix integer seconds for tasks
// returned from `create`/`show`/`list` (its SQLite columns are
// INTEGER) but ISO-8601 strings in some other paths. Normalize
// both shapes into ISO-8601 strings so UI code only deals with
// one type.
self.createdAt = try Self.decodeFlexibleTimestamp(c, forKey: .createdAt)
self.startedAt = try Self.decodeFlexibleTimestamp(c, forKey: .startedAt)
self.completedAt = try Self.decodeFlexibleTimestamp(c, forKey: .completedAt)
self.result = try c.decodeIfPresent(String.self, forKey: .result)
self.skills = try c.decodeIfPresent([String].self, forKey: .skills) ?? []
self.idempotencyKey = try c.decodeIfPresent(String.self, forKey: .idempotencyKey)
self.lastHeartbeatAt = try Self.decodeFlexibleTimestamp(c, forKey: .lastHeartbeatAt)
self.maxRuntimeSeconds = try c.decodeIfPresent(Int.self, forKey: .maxRuntimeSeconds)
self.currentRunId = try c.decodeIfPresent(Int.self, forKey: .currentRunId)
// v0.13 fields every one is `decodeIfPresent` so a v0.12 host's
// task row decodes successfully with these all nil/empty. The
// tolerant-decode contract is pinned by KanbanModelsTests.
self.maxRetries = try c.decodeIfPresent(Int.self, forKey: .maxRetries)
self.autoBlockedReason = try c.decodeIfPresent(String.self, forKey: .autoBlockedReason)
self.hallucinationGateStatus = try c.decodeIfPresent(String.self, forKey: .hallucinationGateStatus)
// Wrap diagnostics decode in `try?` so a single malformed entry
// (or the whole array being the wrong shape) doesn't poison the
// task row the rest of the decoder still produces a usable
// task. Empty default matches the `skills` pattern.
self.diagnostics = (try? c.decodeIfPresent([HermesKanbanDiagnostic].self, forKey: .diagnostics)) ?? []
}
/// Decode a timestamp that may arrive as a Unix integer or an
/// ISO-8601 string. Returns the ISO-8601 string form so downstream
/// code only deals with one type.
static func decodeFlexibleTimestamp(
_ container: KeyedDecodingContainer<CodingKeys>,
forKey key: CodingKeys
) throws -> String? {
if !container.contains(key) { return nil }
// Try the SQLite-style integer first (most common from Hermes).
if let unix = try? container.decodeIfPresent(Double.self, forKey: key) {
let date = Date(timeIntervalSince1970: unix)
return Self.isoFormatter.string(from: date)
}
// Fall back to a plain string.
return try container.decodeIfPresent(String.self, forKey: key)
}
static let isoFormatter: ISO8601DateFormatter = {
let f = ISO8601DateFormatter()
f.formatOptions = [.withInternetDateTime]
return f
}()
}
// MARK: - Status enum (typed view of the wire string)
/// Typed mirror of Hermes's status enum. Models keep `status: String` for
/// forward compatibility with new statuses Hermes might add; UI code uses
/// `KanbanStatus.from(_:)` to map known values into typed categories and
/// fall back to `.unknown` for anything new.
public enum KanbanStatus: String, Sendable, CaseIterable, Identifiable {
case triage
case todo
case ready
case running
case blocked
case done
case archived
case unknown
public var id: String { rawValue }
public static func from(_ raw: String) -> KanbanStatus {
KanbanStatus(rawValue: raw.lowercased()) ?? .unknown
}
/// Coarse 5-column board grouping. `triage` is a column; `todo` and
/// `ready` collapse to one ("Up Next"); everything else maps 1:1.
/// `archived` lives outside the board (toggle).
public var boardColumn: KanbanBoardColumn {
switch self {
case .triage: return .triage
case .todo, .ready, .unknown: return .upNext
case .running: return .running
case .blocked: return .blocked
case .done: return .done
case .archived: return .archived
}
}
}
public enum KanbanBoardColumn: String, Sendable, CaseIterable, Identifiable {
case triage
case upNext
case running
case blocked
case done
case archived
public var id: String { rawValue }
public var displayName: String {
switch self {
case .triage: return "Triage"
case .upNext: return "Up Next"
case .running: return "Running"
case .blocked: return "Blocked"
case .done: return "Done"
case .archived: return "Archived"
}
}
/// Visible columns in the default board layout. `archived` appears
/// only when the "Show archived" toggle is on. `triage` is shown
/// only when the board has at least one triage task (collapsed
/// otherwise to keep the default layout focused).
public static let defaultVisible: [KanbanBoardColumn] = [
.triage, .upNext, .running, .blocked, .done
]
}
// MARK: - Hallucination gate (v0.13)
/// Typed mirror of Hermes v0.13's hallucination-gate state. Worker-created
/// cards land in `pending` until something verifies the underlying work
/// exists; Scarf surfaces a Verify / Reject UX above the task body so the
/// user can act as the verification gate.
///
/// Kept separate from `KanbanStatus` because hallucination state is
/// orthogonal to the lifecycle a card can be `ready` *and* `pending`,
/// for example.
public enum KanbanHallucinationGate: String, Sendable, CaseIterable {
case pending
case verified
case rejected
/// Map a raw `hallucination_gate_status` string (case-insensitive) to
/// a typed gate. Returns nil for empty/nil/unknown values so callers
/// can short-circuit "no gate" branches with `if let gate = `.
public static func from(_ raw: String?) -> KanbanHallucinationGate? {
guard let raw, !raw.isEmpty else { return nil }
return KanbanHallucinationGate(rawValue: raw.lowercased())
}
}
@@ -0,0 +1,89 @@
import Foundation
/// Output of `hermes kanban show <id> --json`. Wraps a task with its full
/// audit trail: comments + events + parent results. Loaded on-demand
/// when the user opens the inspector pane; the board itself only carries
/// the lightweight `HermesKanbanTask` rows.
public struct HermesKanbanTaskDetail: Sendable, Equatable, Codable {
public let task: HermesKanbanTask
public let comments: [HermesKanbanComment]
public let events: [HermesKanbanEvent]
/// Parent-task results keyed by parent task id. Hermes hands these
/// to the worker as upstream context; surfacing them in the
/// inspector is useful for understanding why a task started.
public let parentResults: [String: String]
/// Envelope-level diagnostics array (sibling to `task`, not nested
/// inside it). Defensive Hermes v0.13's wire shape may attach
/// diagnostics to the task itself OR to the envelope.
/// `allDiagnostics` dedupes both sources by `(kind, detected_at)`.
// TODO(WS-3-Q2): Confirm against live `hermes kanban show --json`
// whether diagnostics live on the task envelope, the inner task, or
// both. Current decode is tolerant of either.
public let envelopeDiagnostics: [HermesKanbanDiagnostic]?
public init(
task: HermesKanbanTask,
comments: [HermesKanbanComment] = [],
events: [HermesKanbanEvent] = [],
parentResults: [String: String] = [:],
envelopeDiagnostics: [HermesKanbanDiagnostic]? = nil
) {
self.task = task
self.comments = comments
self.events = events
self.parentResults = parentResults
self.envelopeDiagnostics = envelopeDiagnostics
}
enum CodingKeys: String, CodingKey {
case task
case comments
case events
case parentResults = "parent_results"
case envelopeDiagnostics = "diagnostics"
}
public init(from decoder: any Decoder) throws {
// Hermes emits `kanban show --json` either as a nested
// {task: {...}, comments: [...], events: [...]} object or
// as a flat task object with extra `comments`/`events`
// keys at top level. Try the nested form first; fall
// back to top-level decode.
let container = try decoder.container(keyedBy: CodingKeys.self)
if let nested = try? container.decode(HermesKanbanTask.self, forKey: .task) {
self.task = nested
} else {
let single = try decoder.singleValueContainer()
self.task = try single.decode(HermesKanbanTask.self)
}
self.comments = (try? container.decodeIfPresent([HermesKanbanComment].self, forKey: .comments)) ?? []
self.events = (try? container.decodeIfPresent([HermesKanbanEvent].self, forKey: .events)) ?? []
self.parentResults = (try? container.decodeIfPresent([String: String].self, forKey: .parentResults)) ?? [:]
// Same `try?` shield as the rest a malformed envelope
// diagnostics array shouldn't reject the whole show response.
self.envelopeDiagnostics = try? container.decodeIfPresent([HermesKanbanDiagnostic].self, forKey: .envelopeDiagnostics)
}
public func encode(to encoder: any Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
try c.encode(task, forKey: .task)
try c.encode(comments, forKey: .comments)
try c.encode(events, forKey: .events)
try c.encode(parentResults, forKey: .parentResults)
try c.encodeIfPresent(envelopeDiagnostics, forKey: .envelopeDiagnostics)
}
/// Unified diagnostics view for the inspector. Combines `task.diagnostics`
/// with envelope-level diagnostics (when present) and dedupes on the
/// `(kind, detectedAt)` tuple. Wire-side dupes are unlikely but cheap to
/// filter. Empty for pre-v0.13 hosts.
public var allDiagnostics: [HermesKanbanDiagnostic] {
let onTask = task.diagnostics
let onEnvelope = envelopeDiagnostics ?? []
var seen = Set<String>()
return (onTask + onEnvelope).filter { diag in
let key = "\(diag.kind)|\(diag.detectedAt ?? "")"
return seen.insert(key).inserted
}
}
}
@@ -3,6 +3,10 @@ import Foundation
public enum MCPTransport: String, Sendable, Equatable, CaseIterable, Identifiable {
case stdio
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 }
@@ -11,6 +15,7 @@ public enum MCPTransport: String, Sendable, Equatable, CaseIterable, Identifiabl
switch self {
case .stdio: return "Local (stdio)"
case .http: return "Remote (HTTP)"
case .sse: return "Remote (SSE)"
}
}
#endif
@@ -33,6 +38,12 @@ public struct HermesMCPServer: Identifiable, Sendable, Equatable {
public let resourcesEnabled: Bool
public let promptsEnabled: 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(
@@ -51,7 +62,8 @@ public struct HermesMCPServer: Identifiable, Sendable, Equatable {
toolsExclude: [String],
resourcesEnabled: Bool,
promptsEnabled: Bool,
hasOAuthToken: Bool
hasOAuthToken: Bool,
sseReadTimeout: Int? = nil
) {
self.name = name
self.transport = transport
@@ -69,6 +81,7 @@ public struct HermesMCPServer: Identifiable, Sendable, Equatable {
self.resourcesEnabled = resourcesEnabled
self.promptsEnabled = promptsEnabled
self.hasOAuthToken = hasOAuthToken
self.sseReadTimeout = sseReadTimeout
}
public var id: String { name }
@@ -79,6 +92,8 @@ public struct HermesMCPServer: Identifiable, Sendable, Equatable {
return (command ?? "") + argString
case .http:
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.
HermesToolPlatform(name: "yuanbao", displayName: "Yuanbao 元宝", icon: "bubble.left.and.bubble.right.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 {
@@ -79,6 +90,7 @@ public enum KnownPlatforms {
case "imessage": return "message.fill"
case "yuanbao": return "bubble.left.and.bubble.right.fill"
case "microsoft-teams": return "person.2.fill"
case "google-chat", "googlechat": return "bubble.left.fill"
default: return "bubble.left"
}
}
@@ -0,0 +1,134 @@
import Foundation
/// Swift-side parameter struct that maps 1:1 onto `hermes kanban create`
/// flags. Constructing one then handing it to `KanbanService.create`
/// keeps the CLI argv assembly in one place VMs build a `KanbanCreateRequest`
/// from form state and never assemble argv directly.
public struct KanbanCreateRequest: Sendable, Equatable {
public var title: String
public var body: String?
public var assignee: String?
public var parentIds: [String]
public var workspace: KanbanWorkspaceSpec?
public var tenant: String?
public var priority: Int?
public var triage: Bool
public var idempotencyKey: String?
public var maxRuntimeSeconds: Int?
public var createdBy: String?
public var skills: [String]
/// v0.13: per-task retry budget. `--max-retries N` is write-once at
/// create time no `set_max_retries` verb. Pass `nil` to let Hermes
/// pick its built-in default (3 as of v0.13.0). Capability-gated in
/// the create sheet on `hasKanbanDiagnostics`.
// TODO(WS-3-Q6): Confirm Hermes's global default for `max_retries`
// (v0.13 release notes don't enumerate it). The create sheet defaults
// the field to 3; if Hermes config exposes a different default, mirror
// it.
public var maxRetries: Int?
public init(
title: String,
body: String? = nil,
assignee: String? = nil,
parentIds: [String] = [],
workspace: KanbanWorkspaceSpec? = nil,
tenant: String? = nil,
priority: Int? = nil,
triage: Bool = false,
idempotencyKey: String? = nil,
maxRuntimeSeconds: Int? = nil,
createdBy: String? = nil,
skills: [String] = [],
maxRetries: Int? = nil
) {
self.title = title
self.body = body
self.assignee = assignee
self.parentIds = parentIds
self.workspace = workspace
self.tenant = tenant
self.priority = priority
self.triage = triage
self.idempotencyKey = idempotencyKey
self.maxRuntimeSeconds = maxRuntimeSeconds
self.createdBy = createdBy
self.skills = skills
self.maxRetries = maxRetries
}
/// Build the argv suffix this request maps to (everything after
/// `["kanban", "create"]`). Public for tests; consumers should
/// call `KanbanService.create` instead of building argv directly.
public func argv() -> [String] {
var args: [String] = []
if let body, !body.isEmpty {
args.append(contentsOf: ["--body", body])
}
if let assignee, !assignee.isEmpty {
args.append(contentsOf: ["--assignee", assignee])
}
for parent in parentIds {
args.append(contentsOf: ["--parent", parent])
}
if let workspace {
args.append(contentsOf: ["--workspace", workspace.cliValue])
}
if let tenant, !tenant.isEmpty {
args.append(contentsOf: ["--tenant", tenant])
}
if let priority {
args.append(contentsOf: ["--priority", String(priority)])
}
if triage {
args.append("--triage")
}
if let idempotencyKey, !idempotencyKey.isEmpty {
args.append(contentsOf: ["--idempotency-key", idempotencyKey])
}
if let maxRuntimeSeconds {
args.append(contentsOf: ["--max-runtime", "\(maxRuntimeSeconds)s"])
}
if let maxRetries {
args.append(contentsOf: ["--max-retries", String(maxRetries)])
}
if let createdBy, !createdBy.isEmpty {
args.append(contentsOf: ["--created-by", createdBy])
}
for skill in skills {
args.append(contentsOf: ["--skill", skill])
}
args.append("--json")
// Title is the positional argument appended last so flags
// can't be confused for it.
args.append(title)
return args
}
}
/// Typed mirror of Hermes's `--workspace` flag. `scratch` and `worktree`
/// are bare strings on the wire; `dir:<absolute path>` is a colon-prefixed
/// path. We keep them typed in Swift so callers can't typo "scrach".
public enum KanbanWorkspaceSpec: Sendable, Equatable {
case scratch
case worktree
case directory(String)
public var cliValue: String {
switch self {
case .scratch: return "scratch"
case .worktree: return "worktree"
case .directory(let p): return "dir:\(p)"
}
}
/// "scratch" / "worktree" / "dir" the kind segment, suitable
/// for badge labels.
public var displayKind: String {
switch self {
case .scratch: return "scratch"
case .worktree: return "worktree"
case .directory: return "dir"
}
}
}
@@ -0,0 +1,52 @@
import Foundation
/// Errors thrown by `KanbanService`. Each case carries enough detail
/// to render a user-actionable message VMs surface these inline in
/// the board's error banner rather than blocking with alerts, since
/// kanban interactions are high-frequency.
public enum KanbanError: Error, LocalizedError, Sendable {
/// `hermes` binary couldn't be located (local) or the remote
/// `hermesBinaryHint` is unset (SSH).
case cliMissing
/// Subprocess returned non-zero exit. `stderr` may be empty if the
/// transport itself failed; carries a synthetic message in that case.
case nonZeroExit(code: Int32, stderr: String)
/// JSON decoding failed. Underlying `Error` is wrapped for
/// diagnostics; the user-facing message is generic.
case decoding(message: String)
/// `hermes kanban list --json` printed the literal string
/// "no matching tasks" instead of `[]`. Treated as a successful
/// empty result by callers but exposed here so VMs can distinguish
/// it from "transport error" if they want to.
case noMatchingTasks
/// Verb is not supported by this Hermes version (gated upstream
/// by `HermesCapabilities.hasKanban` + reasoned-about feature
/// drift). Carries the verb name + a hint.
case notSupported(verb: String, reason: String)
/// Disallowed transition the UI tried to perform (e.g. dragging a
/// `done` card back to `todo`). Caller surfaces a tooltip; this is
/// thrown only when a programmatic transition is requested instead
/// of being filtered out at the drag-target gate.
case forbiddenTransition(from: String, to: String, reason: String)
public var errorDescription: String? {
switch self {
case .cliMissing:
return "Hermes CLI couldn't be found. Install Hermes v0.12+ and ensure it's on your PATH."
case .nonZeroExit(let code, let stderr):
let trimmed = stderr.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty {
return "Hermes exited with code \(code)."
}
return trimmed
case .decoding(let message):
return "Couldn't decode Hermes output: \(message)"
case .noMatchingTasks:
return "No matching tasks."
case .notSupported(let verb, let reason):
return "`hermes kanban \(verb)` isn't available: \(reason)"
case .forbiddenTransition(let from, let to, let reason):
return "Can't move a \(from) task to \(to): \(reason)"
}
}
}
@@ -0,0 +1,146 @@
import Foundation
/// Filter options for `hermes kanban list --json`. Empty filter (default)
/// returns all non-archived tasks across all tenants.
public struct KanbanListFilter: Sendable, Equatable {
public var status: KanbanStatus?
public var assignee: String?
/// `nil` = all tenants. Empty string "untagged" (NULL tenant)
/// Hermes treats `--tenant ""` as "no tenant".
public var tenant: String?
public var includeArchived: Bool
/// Show only my profile's tasks (`--mine`).
public var mineOnly: Bool
public init(
status: KanbanStatus? = nil,
assignee: String? = nil,
tenant: String? = nil,
includeArchived: Bool = false,
mineOnly: Bool = false
) {
self.status = status
self.assignee = assignee
self.tenant = tenant
self.includeArchived = includeArchived
self.mineOnly = mineOnly
}
public static let all = KanbanListFilter()
/// Build the argv suffix after `["kanban", "list"]`.
public func argv() -> [String] {
var args: [String] = ["--json"]
if mineOnly {
args.append("--mine")
}
if let status, status != .unknown {
args.append(contentsOf: ["--status", status.rawValue])
}
if let assignee, !assignee.isEmpty {
args.append(contentsOf: ["--assignee", assignee])
}
if let tenant {
args.append(contentsOf: ["--tenant", tenant])
}
if includeArchived {
args.append("--archived")
}
return args
}
}
/// Filter options for `hermes kanban watch --json` (live event stream).
public struct KanbanWatchFilter: Sendable, Equatable {
public var assignee: String?
public var tenant: String?
public var kinds: [KanbanEventKind]
public var intervalSeconds: Double
public init(
assignee: String? = nil,
tenant: String? = nil,
kinds: [KanbanEventKind] = [],
intervalSeconds: Double = 0.5
) {
self.assignee = assignee
self.tenant = tenant
self.kinds = kinds
self.intervalSeconds = intervalSeconds
}
public static let all = KanbanWatchFilter()
public func argv() -> [String] {
var args: [String] = []
if let assignee, !assignee.isEmpty {
args.append(contentsOf: ["--assignee", assignee])
}
if let tenant, !tenant.isEmpty {
args.append(contentsOf: ["--tenant", tenant])
}
if !kinds.isEmpty {
let joined = kinds.map(\.rawValue).joined(separator: ",")
args.append(contentsOf: ["--kinds", joined])
}
if intervalSeconds > 0 && intervalSeconds != 0.5 {
args.append(contentsOf: ["--interval", String(format: "%.2f", intervalSeconds)])
}
return args
}
}
/// Summary of one `hermes kanban dispatch` pass. Used by the optional
/// "Dispatch now" button to show what happened.
public struct KanbanDispatchSummary: Sendable, Equatable, Codable {
public let promoted: Int
public let failed: Int
public let dryRun: Bool
public let perTask: [DispatchedTask]
public init(
promoted: Int = 0,
failed: Int = 0,
dryRun: Bool = false,
perTask: [DispatchedTask] = []
) {
self.promoted = promoted
self.failed = failed
self.dryRun = dryRun
self.perTask = perTask
}
public struct DispatchedTask: Sendable, Equatable, Codable, Identifiable {
public var id: String { taskId }
public let taskId: String
public let decision: String // "promoted" | "skipped" | "failed"
public let reason: String?
public init(taskId: String, decision: String, reason: String? = nil) {
self.taskId = taskId
self.decision = decision
self.reason = reason
}
enum CodingKeys: String, CodingKey {
case taskId = "task_id"
case decision
case reason
}
}
enum CodingKeys: String, CodingKey {
case promoted
case failed
case dryRun = "dry_run"
case perTask = "per_task"
}
public init(from decoder: any Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
self.promoted = try c.decodeIfPresent(Int.self, forKey: .promoted) ?? 0
self.failed = try c.decodeIfPresent(Int.self, forKey: .failed) ?? 0
self.dryRun = try c.decodeIfPresent(Bool.self, forKey: .dryRun) ?? false
self.perTask = try c.decodeIfPresent([DispatchedTask].self, forKey: .perTask) ?? []
}
}
@@ -225,6 +225,58 @@ public extension HermesConfig {
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(
model: str("model.default", default: "unknown"),
provider: str("model.provider", default: "unknown"),
@@ -284,7 +336,26 @@ public extension HermesConfig {
homeAssistant: homeAssistant,
cacheTTL: str("prompt_caching.cache_ttl", default: "5m"),
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)'"
}
}
@@ -8,9 +8,13 @@ import os
///
/// Scarf tracks Hermes feature releases by date-version + semver. v0.12 added
/// a dozen surfaces (Curator, Kanban, multimodal ACP, ...) and removed a few
/// (`flush_memories` aux task). UI that branches on these surfaces calls
/// the boolean accessors here so older Hermes installs degrade silently
/// instead of throwing on an unknown CLI subcommand.
/// (`flush_memories` aux task); v0.13 added Persistent Goals, ACP `/queue`,
/// Kanban diagnostics + recovery UX, Curator archive/prune, Google Chat (20th
/// platform), cross-platform allowlists, MCP SSE transport, Cron `no_agent`
/// mode, Web Tools per-capability backends, Profiles `--no-skills`, and a
/// handful of UX additions. UI that branches on these surfaces calls the
/// boolean accessors here so older Hermes installs degrade silently instead
/// of throwing on an unknown CLI subcommand.
///
/// Pure value type no side effects. The async detection lives in
/// `HermesCapabilitiesStore`.
@@ -45,8 +49,11 @@ public struct HermesCapabilities: Sendable, Equatable {
// MARK: - Capability flags
//
// Add a new flag here when Scarf gains UI that conditionally branches on
// a Hermes capability. Keep the comparison conservative: `>= 0.12.0`
// covers users still on the 0.12 line who haven't upgraded to 0.13 yet.
// a Hermes capability. Keep the comparison conservative: a flag introduced
// in v0.13.0 should gate on `>= 0.13.0`, not `>= 0.13.5`, so users on
// an early 0.13 patch still see the surface.
// MARK: v0.12 (v2026.4.30) flags
/// `hermes curator` autonomous skill maintenance (v0.12+).
public var hasCurator: Bool { atLeastSemver(0, 12, 0) }
@@ -96,9 +103,123 @@ public struct HermesCapabilities: Sendable, Equatable {
public var hasPromptCacheTTL: Bool { atLeastSemver(0, 12, 0) }
/// `redaction.enabled` is now off by default in v0.12 Scarf surfaces
/// the toggle so users can flip it back on.
/// the toggle so users can flip it back on. v0.13 flips the server-side
/// default back to ON; the toggle remains so users on v0.13 can opt out.
public var hasRedactionToggle: Bool { atLeastSemver(0, 12, 0) }
// MARK: v0.13 (v2026.5.7) flags
/// `/goal` slash command + Persistent Goals + Checkpoints v2 single-store
/// (v0.13+). Used by RichChatViewModel to add `/goal` to the
/// non-interruptive command list and to render the "Goal locked" pill in
/// the chat header.
public var hasGoals: Bool { atLeastSemver(0, 13, 0) }
/// `/queue` slash command in the ACP adapter (v0.13+). Queues a prompt
/// to run after the current turn completes without interrupting.
public var hasACPQueue: Bool { atLeastSemver(0, 13, 0) }
/// `/steer` runs as a regular prompt on idle ACP sessions (v0.13+). Pre-
/// v0.13 hosts silently no-op `/steer` when no turn is in flight; with
/// this flag on, Scarf can surface `/steer` even when the agent isn't
/// mid-turn without confusing UX.
public var hasACPSteerOnIdle: Bool { atLeastSemver(0, 13, 0) }
/// Kanban v0.13 reliability surface: hallucination gate on worker-created
/// cards, generic diagnostics engine, per-task `max_retries`, multiline
/// title/body create, `auto_blocked_reason` on blocked tasks, darwin
/// zombie detection. All read through the `kanban show` JSON surface.
public var hasKanbanDiagnostics: Bool { atLeastSemver(0, 13, 0) }
/// `hermes curator archive`, `prune`, and `list-archived` subcommands
/// (v0.13+). The synchronous manual `hermes curator run` lives behind
/// this flag too pre-v0.13 `run` returns immediately and the work
/// happens in the background.
public var hasCuratorArchive: Bool { atLeastSemver(0, 13, 0) }
/// Google Chat 20th messaging-gateway platform (v0.13+).
public var hasGoogleChatPlatform: Bool { atLeastSemver(0, 13, 0) }
/// Cross-platform allowlist keys: `allowed_channels` (Slack / Mattermost
/// / Google Chat), `allowed_chats` (Telegram / WhatsApp), `allowed_rooms`
/// (Matrix / DingTalk). Settable per platform in `config.yaml` (v0.13+).
public var hasGatewayAllowlists: Bool { atLeastSemver(0, 13, 0) }
/// `busy_ack_enabled` config to suppress per-message "agent is working"
/// acks across platforms (v0.13+).
public var hasGatewayBusyAckToggle: Bool { atLeastSemver(0, 13, 0) }
/// Per-platform `gateway_restart_notification` flag controls whether the
/// platform posts a "Gateway restarted" notice on boot (v0.13+).
public var hasGatewayRestartNotification: Bool { atLeastSemver(0, 13, 0) }
/// `hermes gateway list` cross-profile status verb (v0.13+). Lets Scarf
/// show which profile is currently running which platform.
public var hasGatewayList: Bool { atLeastSemver(0, 13, 0) }
/// MCP servers can use SSE transport (v0.13+). Adds an `sse_read_timeout`
/// knob alongside the existing stdio/pipe transports.
public var hasMCPSSETransport: Bool { atLeastSemver(0, 13, 0) }
/// Cron `--no-agent` mode for script-only watchdog jobs (v0.13+). Skips
/// the AI call entirely useful for keep-alive / periodic-check jobs.
public var hasCronNoAgent: Bool { atLeastSemver(0, 13, 0) }
/// Web Tools split into per-capability backend selection: `web_search`
/// and `web_extract` can now use distinct backends (v0.13+). SearXNG
/// joined as a search-only backend.
public var hasWebToolsBackendSplit: Bool { atLeastSemver(0, 13, 0) }
/// `hermes profile create --no-skills` flag for empty profiles (v0.13+).
public var hasProfileNoSkills: Bool { atLeastSemver(0, 13, 0) }
/// Context compression count surfaced in the status feed (v0.13+). Scarf
/// renders it next to the token count in the chat status bar.
public var hasContextCompressionCount: Bool { atLeastSemver(0, 13, 0) }
/// `/new` slash command accepts an optional session-name argument (v0.13+).
public var hasNewWithSessionName: Bool { atLeastSemver(0, 13, 0) }
/// `hermes update --yes` / `-y` skips interactive prompts (v0.13+). Used
/// by Scarf's "Update Hermes" affordance to run unattended.
public var hasUpdateNonInteractive: Bool { atLeastSemver(0, 13, 0) }
/// OpenRouter response caching toggle in `config.yaml` (v0.13+).
public var hasOpenRouterResponseCache: Bool { atLeastSemver(0, 13, 0) }
/// `image_gen.model` honored from `config.yaml` (v0.13+). Pre-v0.13 the
/// value was advertised but ignored at runtime.
public var hasImageGenModel: Bool { atLeastSemver(0, 13, 0) }
/// `display.language` config key for static-message translation: zh / ja /
/// de / es / fr / uk / tr (v0.13+).
public var hasDisplayLanguage: Bool { atLeastSemver(0, 13, 0) }
/// xAI Custom Voices voice cloning support (v0.13+). Exposed in Scarf
/// as a "Cloning supported" badge next to the xAI TTS provider entry.
public var hasXAIVoiceCloning: Bool { atLeastSemver(0, 13, 0) }
/// `video_analyze` tool native video understanding on Gemini and
/// compatible models (v0.13+). Hermes handles this transparently inside
/// the agent loop; Scarf has no UI surface yet, but the flag lets future
/// dashboards / activity views light up video-tool annotations.
public var hasVideoAnalyze: Bool { atLeastSemver(0, 13, 0) }
/// `transform_llm_output` plugin hook for shaping LLM output before the
/// conversation receives it (v0.13+). Plugin-author concern; Scarf's
/// PluginsView surfaces it as a documented hook in plugin metadata.
public var hasTransformLLMOutputHook: Bool { atLeastSemver(0, 13, 0) }
// MARK: Convenience predicates
/// Whether the connected host is on the v0.13 line or newer. Convenience
/// for UI copy that needs to switch on the v0.12 v0.13 boundary without
/// proxying through a feature-specific flag (e.g. "v0.13 features active"
/// badges, redaction default-state hints). Equivalent to any individual
/// v0.13 flag; prefer this when the call site isn't actually about a
/// specific feature.
public var isV013OrLater: Bool { atLeastSemver(0, 13, 0) }
private func atLeastSemver(_ major: Int, _ minor: Int, _ patch: Int) -> Bool {
guard let s = semver else { return false }
return s >= SemVer(major: major, minor: minor, patch: patch)
@@ -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
}
}
@@ -0,0 +1,558 @@
import Foundation
#if canImport(os)
import os
#endif
/// Async, transport-aware client for `hermes kanban `. Wraps every CLI
/// verb the v0.12 board exposes in a typed Swift surface.
///
/// **Concurrency.** This is a pure-I/O `actor` no UI state. View models
/// (`@MainActor` `@Observable`) hold a service reference and `await`
/// methods. Each public method serializes through the actor, but the
/// underlying CLI invocation runs on a `Task.detached(priority: .utility)`
/// so two concurrent reads from different VMs don't queue end-to-end on
/// a single thread.
///
/// **Hermes constraints surfaced as Swift constraints:**
/// - There is no `update` verb, so there's no `update(taskId:title:body:)`.
/// Mutations after create are state transitions (assign / claim /
/// complete / block / unblock / archive / comment) or new comments.
/// - The board is global with optional `tenant` namespacing pass a
/// tenant via `KanbanListFilter.tenant` for project-scoped views.
/// - The CLI prints `"no matching tasks"` instead of `[]` when nothing
/// matches a filter. We fold that into `[]` rather than throwing.
public actor KanbanService {
#if canImport(os)
private static let logger = Logger(subsystem: "com.scarf", category: "KanbanService")
#endif
private let context: ServerContext
public init(context: ServerContext) {
self.context = context
}
// MARK: - Reads
public func list(_ filter: KanbanListFilter = .all) async throws -> [HermesKanbanTask] {
var args = ["kanban", "list"]
args.append(contentsOf: filter.argv())
let (code, stdout, stderr) = await runHermes(args: args, timeout: 20)
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "list")
// Empty filter on an empty board prints "no matching tasks" instead
// of `[]`. Treat as empty rather than letting the JSON decode fail.
if stdout.contains("no matching tasks") {
return []
}
guard let data = stdout.data(using: .utf8) else {
throw KanbanError.decoding(message: "non-UTF8 stdout")
}
do {
return try JSONDecoder().decode([HermesKanbanTask].self, from: data)
} catch {
throw KanbanError.decoding(message: error.localizedDescription)
}
}
public func show(taskId: String) async throws -> HermesKanbanTaskDetail {
let args = ["kanban", "show", taskId, "--json"]
let (code, stdout, stderr) = await runHermes(args: args, timeout: 15)
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "show")
guard let data = stdout.data(using: .utf8) else {
throw KanbanError.decoding(message: "non-UTF8 stdout")
}
do {
return try JSONDecoder().decode(HermesKanbanTaskDetail.self, from: data)
} catch {
throw KanbanError.decoding(message: error.localizedDescription)
}
}
public func runs(taskId: String) async throws -> [HermesKanbanRun] {
let args = ["kanban", "runs", taskId, "--json"]
let (code, stdout, stderr) = await runHermes(args: args, timeout: 15)
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "runs")
guard let data = stdout.data(using: .utf8) else {
throw KanbanError.decoding(message: "non-UTF8 stdout")
}
do {
return try JSONDecoder().decode([HermesKanbanRun].self, from: data)
} catch {
// Some Hermes builds emit a `{"runs": [...]}` envelope.
struct Wrapper: Decodable { let runs: [HermesKanbanRun] }
if let wrapped = try? JSONDecoder().decode(Wrapper.self, from: data) {
return wrapped.runs
}
throw KanbanError.decoding(message: error.localizedDescription)
}
}
public func stats() async throws -> HermesKanbanStats {
let args = ["kanban", "stats", "--json"]
let (code, stdout, stderr) = await runHermes(args: args, timeout: 15)
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "stats")
guard let data = stdout.data(using: .utf8) else {
throw KanbanError.decoding(message: "non-UTF8 stdout")
}
do {
return try JSONDecoder().decode(HermesKanbanStats.self, from: data)
} catch {
throw KanbanError.decoding(message: error.localizedDescription)
}
}
/// Print the captured worker log for a task `hermes kanban log
/// <id>`. Returns whatever `$HERMES_HOME/kanban/logs/<id>` contains.
/// Empty string when the worker hasn't written anything yet (or
/// the task has never been claimed). Pass `tailBytes` to cap the
/// returned size (useful when polling at high cadence).
public func log(taskId: String, tailBytes: Int? = nil) async throws -> String {
var args = ["kanban", "log"]
if let tailBytes {
args.append(contentsOf: ["--tail", String(tailBytes)])
}
args.append(taskId)
let (code, stdout, stderr) = await runHermes(args: args, timeout: 15)
// `kanban log` exits with code 0 even when no log file exists
// it just prints "No log file." or similar to stdout. Tolerate
// non-zero codes too: some Hermes versions emit a warning to
// stderr and exit 1 when the log dir is missing.
if code != 0 {
let combined = stderr.isEmpty ? stdout : stderr
// Treat "no log" sentinels as empty rather than as errors.
let lower = combined.lowercased()
if lower.contains("no log") || lower.contains("not found") {
return ""
}
throw KanbanError.nonZeroExit(code: code, stderr: combined)
}
return stdout
}
public func assignees() async throws -> [HermesKanbanAssignee] {
// The `assignees` verb doesn't take `--json` consistently across
// 0.12.x pass it anyway and fall back to a tab-delimited parse
// if Hermes printed a human table.
let args = ["kanban", "assignees"]
let (code, stdout, stderr) = await runHermes(args: args, timeout: 15)
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "assignees")
if let data = stdout.data(using: .utf8),
let arr = try? JSONDecoder().decode([HermesKanbanAssignee].self, from: data) {
return arr
}
// Fallback: each non-blank line of the form
// "<profile>\t<active>\t<total>"
// OR "<profile> <active> <total>" (whitespace separated).
return parseAssigneeTable(stdout)
}
private nonisolated func parseAssigneeTable(_ text: String) -> [HermesKanbanAssignee] {
var result: [HermesKanbanAssignee] = []
// Profile names follow the same convention as `hermes -p <name>`
// letters, digits, hyphen, underscore. Anything else is
// chrome (header rows, Rich box-drawing, fallback messages
// like "(no assignees create a profile with `hermes -p
// <name> setup`)") and gets skipped.
for raw in text.split(separator: "\n") {
let line = raw.trimmingCharacters(in: .whitespaces)
if line.isEmpty { continue }
// Skip the column header row.
if line.lowercased().hasPrefix("profile") { continue }
// Skip the empty-state sentinel without trying to tokenize
// it (used to leak "(no" into the picker).
if line.lowercased().contains("no assignees") { continue }
// Skip Rich box-drawing separators (only + whitespace).
if line.unicodeScalars.allSatisfy({ $0.value == 0x2500 || $0.properties.isWhitespace }) {
continue
}
// Strip the active marker `` (U+25C6) some `hermes`
// commands prefix to the active profile.
var working = line
if working.hasPrefix("") {
working = String(working.dropFirst()).trimmingCharacters(in: .whitespaces)
}
let parts = working
.split(whereSeparator: { $0 == "\t" || $0 == " " })
.map { String($0) }
.filter { !$0.isEmpty }
guard let profile = parts.first else { continue }
// Validate: must look like a real profile slug, not a word
// out of an English sentence.
guard profile.range(of: "^[a-zA-Z0-9_-]+$", options: .regularExpression) != nil else {
continue
}
let active = (parts.count > 1) ? Int(parts[1]) ?? 0 : 0
let total = (parts.count > 2) ? Int(parts[2]) ?? 0 : active
result.append(HermesKanbanAssignee(profile: profile, activeCount: active, totalCount: total))
}
return result
}
// MARK: - Writes
public func create(_ request: KanbanCreateRequest) async throws -> HermesKanbanTask {
var args = ["kanban", "create"]
args.append(contentsOf: request.argv())
let (code, stdout, stderr) = await runHermes(args: args, timeout: 30)
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "create")
guard let data = stdout.data(using: .utf8) else {
throw KanbanError.decoding(message: "non-UTF8 stdout")
}
// Hermes returns the full task object when --json is set.
do {
return try JSONDecoder().decode(HermesKanbanTask.self, from: data)
} catch {
// Some builds emit just the new id on stdout. Fall back to a
// follow-up `show` so the caller always gets a typed task.
let trimmed = stdout.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmed.isEmpty, !trimmed.contains("\n"), !trimmed.contains("{") {
let detail = try await show(taskId: trimmed)
return detail.task
}
throw KanbanError.decoding(message: error.localizedDescription)
}
}
public func assign(taskId: String, profile: String?) async throws {
let target = (profile?.isEmpty ?? true) ? "none" : profile!
let args = ["kanban", "assign", taskId, target]
let (code, _, stderr) = await runHermes(args: args, timeout: 15)
try ensureSuccess(code: code, stdout: "", stderr: stderr, verb: "assign")
}
@discardableResult
public func claim(taskId: String, ttlSeconds: Int = 900) async throws -> String {
let args = ["kanban", "claim", taskId, "--ttl", String(ttlSeconds)]
let (code, stdout, stderr) = await runHermes(args: args, timeout: 20)
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "claim")
// claim prints the resolved workspace path on stdout.
return stdout.trimmingCharacters(in: .whitespacesAndNewlines)
}
public func comment(taskId: String, text: String, author: String? = nil) async throws {
var args = ["kanban", "comment"]
if let author, !author.isEmpty {
args.append(contentsOf: ["--author", author])
}
args.append(taskId)
args.append(text)
let (code, _, stderr) = await runHermes(args: args, timeout: 15)
try ensureSuccess(code: code, stdout: "", stderr: stderr, verb: "comment")
}
public func complete(
taskIds: [String],
result: String? = nil,
summary: String? = nil,
metadataJSON: String? = nil
) async throws {
guard !taskIds.isEmpty else { return }
var args = ["kanban", "complete"]
if let result, !result.isEmpty {
args.append(contentsOf: ["--result", result])
}
if let summary, !summary.isEmpty {
args.append(contentsOf: ["--summary", summary])
}
if let metadataJSON, !metadataJSON.isEmpty {
args.append(contentsOf: ["--metadata", metadataJSON])
}
args.append(contentsOf: taskIds)
let (code, _, stderr) = await runHermes(args: args, timeout: 30)
try ensureSuccess(code: code, stdout: "", stderr: stderr, verb: "complete")
}
public func block(taskId: String, reason: String? = nil) async throws {
var args = ["kanban", "block", taskId]
if let reason, !reason.trimmingCharacters(in: .whitespaces).isEmpty {
// Hermes accepts free-form trailing words as the reason.
args.append(contentsOf: reason.split(separator: " ").map(String.init))
}
let (code, _, stderr) = await runHermes(args: args, timeout: 15)
try ensureSuccess(code: code, stdout: "", stderr: stderr, verb: "block")
}
public func unblock(taskIds: [String]) async throws {
guard !taskIds.isEmpty else { return }
var args = ["kanban", "unblock"]
args.append(contentsOf: taskIds)
let (code, _, stderr) = await runHermes(args: args, timeout: 15)
try ensureSuccess(code: code, stdout: "", stderr: stderr, verb: "unblock")
}
public func archive(taskIds: [String]) async throws {
guard !taskIds.isEmpty else { return }
var args = ["kanban", "archive"]
args.append(contentsOf: taskIds)
let (code, _, stderr) = await runHermes(args: args, timeout: 15)
try ensureSuccess(code: code, stdout: "", stderr: stderr, verb: "archive")
}
@discardableResult
public func dispatch(maxTasks: Int? = nil, dryRun: Bool = false) async throws -> KanbanDispatchSummary {
var args = ["kanban", "dispatch", "--json"]
if dryRun { args.append("--dry-run") }
if let maxTasks { args.append(contentsOf: ["--max", String(maxTasks)]) }
let (code, stdout, stderr) = await runHermes(args: args, timeout: 60)
try ensureSuccess(code: code, stdout: stdout, stderr: stderr, verb: "dispatch")
guard let data = stdout.data(using: .utf8) else {
throw KanbanError.decoding(message: "non-UTF8 stdout")
}
do {
return try JSONDecoder().decode(KanbanDispatchSummary.self, from: data)
} catch {
// Older builds may print human output. Return a stub summary.
return KanbanDispatchSummary(promoted: 0, failed: 0, dryRun: dryRun, perTask: [])
}
}
public func link(parent: String, child: String) async throws {
let args = ["kanban", "link", parent, child]
let (code, _, stderr) = await runHermes(args: args, timeout: 15)
try ensureSuccess(code: code, stdout: "", stderr: stderr, verb: "link")
}
public func unlink(parent: String, child: String) async throws {
let args = ["kanban", "unlink", parent, child]
let (code, _, stderr) = await runHermes(args: args, timeout: 15)
try ensureSuccess(code: code, stdout: "", stderr: stderr, verb: "unlink")
}
// MARK: - Hallucination gate (v0.13)
/// Mark a worker-created card as user-verified flips
/// `hallucination_gate_status` from `pending` to `verified` so the
/// dispatcher can pick it up. The polling loop picks up the new
/// state on the next tick (and the VM optimistically clears the
/// pending banner immediately on the click).
///
/// **Pre-v0.13 hosts:** the verb doesn't exist; callers MUST gate
/// on `HermesCapabilities.hasKanbanDiagnostics` before invoking this.
/// A pre-v0.13 binary will surface the failure as
/// `KanbanError.nonZeroExit` with stderr containing "unknown command".
// TODO(WS-3-Q1): Confirm the exact CLI verb name for the
// hallucination-gate verify path against a v0.13 binary (`hermes
// kanban --help`). The v0.13 release notes describe "hallucination
// gate + recovery UX" but don't enumerate the verb name. This
// implementation assumes `hermes kanban verify <id>`. If Hermes ships
// it as `hermes kanban gate verify <id>`, `hermes kanban hallucination
// verify <id>`, or another name, update the args here. The Reject
// path does NOT depend on this verb (it routes through
// `archive` + a comment), so the recovery UX stays functional even
// if Verify is a stub for an early v0.13.x.
public func verify(taskId: String) async throws {
let args = ["kanban", "verify", taskId]
let (code, _, stderr) = await runHermes(args: args, timeout: 15)
try ensureSuccess(code: code, stdout: "", stderr: stderr, verb: "verify")
}
/// Reject a worker-created card as a hallucinated reference. There
/// is no dedicated `kanban reject` verb in v0.13; the right action
/// per the v0.13 release notes is to archive the card (the work
/// doesn't exist) with a comment recording the rejection reason for
/// the audit trail. Routing this through the existing `comment` +
/// `archive` verbs keeps the wire shape stable across versions.
///
/// If a future Hermes adds a dedicated `kanban reject` verb, swap
/// the body here the public surface stays "reject" returning Void.
public func rejectHallucinated(taskId: String) async throws {
// Best-effort comment first so the audit trail records the
// rejection. A failure here shouldn't block the archive log
// and continue.
do {
try await comment(
taskId: taskId,
text: "Rejected as hallucinated (no underlying work).",
author: nil
)
} catch {
#if canImport(os)
Self.logger.warning("kanban reject: comment failed, proceeding to archive (\(error.localizedDescription, privacy: .public))")
#endif
}
try await archive(taskIds: [taskId])
}
// MARK: - Drag-drop transition mapper
/// Map a board-level column transition to the right Hermes verb call.
/// Returns the list of CLI invocations the caller should run in order.
/// Pure no I/O. Called from VMs to build an action plan; the VM
/// then either prompts the user (e.g. for a block reason) or calls
/// the matching `KanbanService` methods.
///
/// Forbidden transitions throw `KanbanError.forbiddenTransition`
/// rather than returning an empty plan, so callers can surface the
/// reason to the user.
public nonisolated static func plan(
for transition: KanbanTransition
) throws -> KanbanTransitionPlan {
let from = transition.from
let to = transition.to
if from == to {
return KanbanTransitionPlan(steps: [])
}
// "Done" is terminal Hermes has no `reopen` verb.
if from == .done {
throw KanbanError.forbiddenTransition(
from: from.displayName,
to: to.displayName,
reason: "Done is terminal — create a follow-up task to continue work."
)
}
// Triage promotion isn't a CLI verb in v0.12 it happens via
// a specifier worker. UI should disallow drag from triage.
if from == .triage {
throw KanbanError.forbiddenTransition(
from: from.displayName,
to: to.displayName,
reason: "Triage tasks are promoted by a specifier agent. Use the specifier worker pipeline."
)
}
// Archive lives outside the board only via context menu.
if to == .archived {
return KanbanTransitionPlan(steps: [.archive])
}
switch (from, to) {
case (.upNext, .running):
return KanbanTransitionPlan(steps: [.dispatch])
case (.upNext, .blocked):
return KanbanTransitionPlan(steps: [.block(reasonRequired: true)])
case (.upNext, .done):
// Direct tododone is unusual but allowed (manual checkoff).
return KanbanTransitionPlan(steps: [.complete(resultRequired: false)])
case (.running, .blocked):
return KanbanTransitionPlan(steps: [.block(reasonRequired: true)])
case (.running, .done):
return KanbanTransitionPlan(steps: [.complete(resultRequired: false)])
case (.running, .upNext):
// Release back to ready no direct verb. Closest is unblock,
// which only works for blocked tasks. Forbid for now.
throw KanbanError.forbiddenTransition(
from: from.displayName,
to: to.displayName,
reason: "Use the inspector's Comment + Unassign actions to hand a running task back."
)
case (.blocked, .upNext):
return KanbanTransitionPlan(steps: [.unblock])
case (.blocked, .running):
return KanbanTransitionPlan(steps: [.unblock, .dispatch])
case (.blocked, .done):
return KanbanTransitionPlan(steps: [.unblock, .complete(resultRequired: false)])
default:
throw KanbanError.forbiddenTransition(
from: from.displayName,
to: to.displayName,
reason: "No CLI path exists for this transition."
)
}
}
// 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 transport = context.makeTransport()
let executable = context.paths.hermesBinary
do {
let result = try transport.runProcess(
executable: executable,
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)
}
}.value
}
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 KanbanError.cliMissing
}
let combined = stderr.isEmpty ? stdout : stderr
#if canImport(os)
Self.logger.warning("kanban \(verb) exit=\(code, privacy: .public) stderr=\(combined, privacy: .public)")
#endif
throw KanbanError.nonZeroExit(code: code, stderr: combined)
}
}
// MARK: - Transition planning
/// Source/destination columns for a single drag-drop. Comparable to
/// SwiftUI's `.dropDestination` payload but kept Sendable + Hashable
/// so it can also drive iOS context-menu "Move to" actions.
public struct KanbanTransition: Sendable, Hashable {
public let from: KanbanBoardColumn
public let to: KanbanBoardColumn
public init(from: KanbanBoardColumn, to: KanbanBoardColumn) {
self.from = from
self.to = to
}
}
/// One Hermes verb call produced by `KanbanService.plan(for:)`. The VM
/// resolves any user-input requirements (block reason, completion
/// result) before invoking the corresponding actor method.
///
/// **Why `.dispatch` and not `.claim`.** `hermes kanban claim` reserves
/// a task atomically and prints the workspace path but it's a
/// "manual alternative to the dispatcher" that assumes the caller will
/// spawn the worker themselves. Scarf is not a worker host; the
/// gateway-running dispatcher is. Calling `claim` from drag-drop
/// flipped status to `running` without spawning any work, and the
/// task got reclaimed (stale_lock) ~15 minutes later. The right
/// verb is `dispatch`, which causes the dispatcher to spawn workers
/// for every assigned `ready` task in one pass.
public enum KanbanTransitionStep: Sendable, Equatable {
/// Force a dispatcher pass so the gateway spawns workers for
/// assigned `ready` tasks. Requires the task have an assignee
/// the dispatcher silently skips unassigned tasks.
case dispatch
case unblock
case block(reasonRequired: Bool)
case complete(resultRequired: Bool)
case archive
}
public struct KanbanTransitionPlan: Sendable, Equatable {
public let steps: [KanbanTransitionStep]
public init(steps: [KanbanTransitionStep]) {
self.steps = steps
}
public var requiresBlockReason: Bool {
steps.contains { if case .block(true) = $0 { return true } else { return false } }
}
public var requiresCompleteResult: Bool {
steps.contains { if case .complete(true) = $0 { return true } else { return false } }
}
}
@@ -0,0 +1,39 @@
import Foundation
/// Cross-platform read-only helper for `<project>/.scarf/manifest.json`'s
/// `kanbanTenant` field. The full `ProjectTemplateManifest` Codable
/// type lives in the Mac app target (with all the install/export
/// machinery); iOS doesn't link it, so this lightweight projection
/// gives both targets a way to read just the tenant slug without
/// duplicating the entire manifest model.
public struct KanbanTenantReader: Sendable {
public let context: ServerContext
public nonisolated init(context: ServerContext) {
self.context = context
}
/// Read the project's Kanban tenant slug, or `nil` if the manifest
/// doesn't exist or doesn't carry one. Cheap single JSON parse
/// of a tiny projection.
public nonisolated func tenant(forProjectPath projectPath: String) -> String? {
let manifestPath = projectPath + "/.scarf/manifest.json"
let transport = context.makeTransport()
guard transport.fileExists(manifestPath),
let data = try? transport.readFile(manifestPath)
else {
return nil
}
return Self.tenant(fromManifestData: data)
}
/// Pure-input variant for tests + tooling that already have the
/// JSON bytes in hand. Returns `nil` when the bytes don't decode
/// or the field isn't present.
public nonisolated static func tenant(fromManifestData data: Data) -> String? {
struct Projection: Decodable {
let kanbanTenant: String?
}
return (try? JSONDecoder().decode(Projection.self, from: data))?.kanbanTenant
}
}
@@ -155,9 +155,20 @@ public struct ModelCatalogService: Sendable {
)
}
return byID.values.sorted { lhs, rhs in
// Subscription-gated first (Nous Portal).
if lhs.subscriptionGated != rhs.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
}
}
@@ -235,7 +246,10 @@ public struct ModelCatalogService: Sendable {
public func provider(for modelID: String) -> HermesProviderInfo? {
guard let catalog = loadCatalog() else { return nil }
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(
providerID: 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
/// catalog (e.g., free-typed custom model).
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(),
let provider = catalog[providerID],
let raw = provider.models?[modelID] else { return nil }
let raw = provider.models?[resolved] else { return nil }
return HermesModelInfo(
providerID: providerID,
providerName: provider.name ?? providerID,
modelID: modelID,
modelName: raw.name ?? modelID,
modelID: resolved,
modelName: raw.name ?? resolved,
contextWindow: raw.limit?.context,
maxOutput: raw.limit?.output,
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.
public func validateModel(_ modelID: String, for providerID: String) -> ModelValidation {
ScarfMon.measure(.diskIO, "modelCatalog.validateModel") {
let trimmed = modelID.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else {
let raw = modelID.trimmingCharacters(in: .whitespacesAndNewlines)
guard !raw.isEmpty else {
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
// OAuth, ) serve their own catalogs that aren't mirrored to
@@ -433,6 +454,78 @@ public struct ModelCatalogService: Sendable {
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
/// 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
/// `hermes_cli/providers.py`. Describes a provider that isn't in the
/// models.dev catalog.
@@ -25,6 +25,63 @@ public struct LocalTransport: ServerTransport {
self.contextID = contextID
}
// MARK: - Environment enrichment
/// Injection point for local-subprocess environment enrichment.
/// Mirrors `SSHTransport.environmentEnricher` the Mac app wires
/// this at launch to `HermesFileService.enrichedEnvironment()`,
/// which probes the user's login shell for PATH + credential env
/// vars. Without it, GUI-launched Scarf hands subprocesses a
/// stripped `/usr/bin:/bin:/usr/sbin:/sbin` PATH and child
/// `hermes` invocations from inside spawned workers fail with
/// `executable not found on PATH`.
///
/// Set once at app launch (startup is single-threaded). Tests may
/// inject a stub. iOS leaves this `nil` because LocalTransport
/// doesn't run subprocesses there.
nonisolated(unsafe) public static var environmentEnricher: (@Sendable () -> [String: String])?
/// Build the environment dict for a single subprocess. Process
/// env wins for keys it has; the enricher fills gaps + always
/// owns PATH (which is the whole point of running it). The
/// executable's parent directory is appended as a final fallback
/// so `runProcess` works even before the enricher has been wired
/// (during very early startup, in tests, etc.).
nonisolated static func subprocessEnvironment(forExecutable executable: String) -> [String: String] {
var env = ProcessInfo.processInfo.environment
if let enricher = Self.environmentEnricher {
let extra = enricher()
for (key, value) in extra where !value.isEmpty {
if key == "PATH" {
// Enricher always wins for PATH that's the
// whole reason the enricher exists. The GUI
// process PATH is the broken thing we're
// replacing.
env[key] = value
} else if (env[key] ?? "").isEmpty {
// For other keys (credential env, locale, etc.)
// an explicit non-empty value in the GUI
// environment wins; an empty or absent value
// gets filled by the shell-harvested copy.
env[key] = value
}
}
}
// Always make sure the executable's own directory is on PATH
// covers the case where the enricher hasn't been wired (tests,
// pre-launch helpers) but a child process still tries to spawn
// its sibling tools by bare name.
let dir = (executable as NSString).deletingLastPathComponent
if !dir.isEmpty {
let currentPATH = env["PATH"] ?? "/usr/bin:/bin:/usr/sbin:/sbin"
let parts = currentPATH.split(separator: ":").map(String.init)
if !parts.contains(dir) {
env["PATH"] = "\(dir):\(currentPATH)"
}
}
return env
}
// MARK: - Files
public func readFile(_ path: String) throws -> Data {
@@ -116,6 +173,17 @@ public struct LocalTransport: ServerTransport {
let proc = Process()
proc.executableURL = URL(fileURLWithPath: executable)
proc.arguments = args
// Hand subprocesses an environment that includes the user's
// login-shell PATH. Without this, `hermes` (pipx-installed at
// `~/.local/bin/hermes`) ends up running with macOS's GUI
// launch-services PATH (`/usr/bin:/bin:/usr/sbin:/sbin`), and
// when Hermes itself shells out to spawn a worker (e.g. the
// kanban dispatcher invoking `hermes` by name from a Python
// subprocess), it returns "executable not found on PATH" and
// the run records `outcome=spawn_failed`. Mirrors the SSH
// transport's environmentEnricher hook and is wired by
// `scarfApp.swift` at launch.
proc.environment = Self.subprocessEnvironment(forExecutable: executable)
let stdoutPipe = Pipe()
let stderrPipe = Pipe()
let stdinPipe = Pipe()
@@ -4,17 +4,19 @@ import Observation
import os
#endif
/// Mac + iOS view model for the v0.12 Curator surface.
/// Mac + iOS view model for the Curator surface (v0.12 base + v0.13
/// archive/prune additions).
///
/// Drives `hermes curator status / run / pause / resume / pin / unpin /
/// restore` plus a parsed view of `~/.hermes/skills/.curator_state`
/// JSON. The CLI doesn't ship a `--json` flag for `status`, so we
/// text-parse stdout (HermesCuratorStatusParser) and use the state
/// file for richer last-run metadata.
/// restore` plus (v0.13+) `archive`, `prune`, `list-archived`. All CLI
/// invocations route through `CuratorService` (the actor) so polling
/// and writes share the same concurrency model and a single error path.
///
/// Capability-gated: callers should construct this only when
/// `HermesCapabilities.hasCurator` is true. The view model does not
/// gate itself the gate happens at sidebar/tab routing time.
/// `HermesCapabilities.hasCurator` is true. Archive-aware UI surfaces
/// (Archive button, Archived section, Prune) gate independently on
/// `hasCuratorArchive`. The view model itself doesn't gate it exposes
/// every method and the View decides what to render.
@Observable
@MainActor
public final class CuratorViewModel {
@@ -27,20 +29,50 @@ public final class CuratorViewModel {
public private(set) var status: HermesCuratorStatus = .empty
public private(set) var isLoading = false
public private(set) var lastReportMarkdown: String?
// Archive state (v0.13+ only populated by `loadArchive()` on hosts
// where `hasCuratorArchive` is true).
public private(set) var archivedSkills: [HermesCuratorArchivedSkill] = []
public private(set) var isLoadingArchive = false
// Prune state `pruneSummary` non-nil while the confirm sheet is
// mid-flight; `isPruning` flips during the destructive step.
public private(set) var pruneSummary: CuratorPruneSummary?
public private(set) var isPruning = false
// Track which active-skill row is currently being archived so the
// row chrome can show an inline spinner without blocking the rest.
public private(set) var pendingArchiveName: String?
/// Happy-path success toast ("Pinned X", "Resumed", "Archived
/// legacy-helper"). Auto-clears 3s after assignment.
public var transientMessage: String?
/// Failure path populated by every CLI verb when it throws. Shown
/// as an inline yellow banner above the status summary so users
/// don't have to dismiss a modal alert during a high-frequency
/// surface like the leaderboard. Manually dismissed via the View's
/// "x" button (sets to nil).
public var errorMessage: String?
@ObservationIgnored
private let service: CuratorService
public init(context: ServerContext) {
self.context = context
self.service = CuratorService(context: context)
}
// MARK: - Loads
public func load() async {
isLoading = true
defer { isLoading = false }
let context = self.context
// v2.8 instrumented. Curator load fires `hermes curator
// status` (CLI subprocess) plus 1-2 file reads; on remote
// each is a separate SSH RTT. Visibility lets future captures
// show how often the report file is missing or oversized.
// status` (CLI subprocess) plus 1-2 file reads; on remote each
// is a separate SSH RTT. Visibility lets future captures show
// how often the report file is missing or oversized.
let parsed = await ScarfMon.measureAsync(.diskIO, "curator.load") {
await Task.detached(priority: .userInitiated) { () -> (HermesCuratorStatus, String?) in
let textResult = Self.runCuratorStatus(context: context)
@@ -69,46 +101,156 @@ public final class CuratorViewModel {
self.lastReportMarkdown = parsed.1
}
public func runNow() async {
await runAndReload(args: ["curator", "run"], successMessage: "Curator run started")
/// Refresh the archived-skills list. No-op on hosts without
/// `hasCuratorArchive` the caller gates the call.
public func loadArchive() async {
isLoadingArchive = true
defer { isLoadingArchive = false }
do {
archivedSkills = try await service.listArchived()
} catch {
archivedSkills = []
errorMessage = (error as? LocalizedError)?.errorDescription
?? error.localizedDescription
}
}
// MARK: - Writes (v0.12)
/// Run the curator manually. On v0.13+ hosts this blocks for the
/// duration of the run (default 600s timeout); pre-v0.13 returns
/// immediately. Caller passes the capability-decided flag.
public func runNow(synchronous: Bool, timeout: TimeInterval = 600) async {
await runWithReload(
verb: "run",
successMessage: synchronous ? "Curator run complete" : "Curator run started"
) {
try await self.service.runNow(synchronous: synchronous, timeout: timeout)
}
}
public func pause() async {
await runAndReload(args: ["curator", "pause"], successMessage: "Curator paused")
await runWithReload(verb: "pause", successMessage: "Curator paused") {
try await self.service.pause()
}
}
public func resume() async {
await runAndReload(args: ["curator", "resume"], successMessage: "Curator resumed")
await runWithReload(verb: "resume", successMessage: "Curator resumed") {
try await self.service.resume()
}
}
public func pin(_ skill: String) async {
await runAndReload(args: ["curator", "pin", skill], successMessage: "Pinned \(skill)")
await runWithReload(verb: "pin", successMessage: "Pinned \(skill)") {
try await self.service.pin(skill)
}
}
public func unpin(_ skill: String) async {
await runAndReload(args: ["curator", "unpin", skill], successMessage: "Unpinned \(skill)")
await runWithReload(verb: "unpin", successMessage: "Unpinned \(skill)") {
try await self.service.unpin(skill)
}
}
public func restore(_ skill: String) async {
await runAndReload(args: ["curator", "restore", skill], successMessage: "Restored \(skill)")
await runWithReload(verb: "restore", successMessage: "Restored \(skill)") {
try await self.service.restore(skill)
}
// Restore drops the entry from the archived list refresh it
// so the row disappears immediately.
await loadArchive()
}
private func runAndReload(args: [String], successMessage: String) async {
let context = self.context
let exitCode = await Task.detached(priority: .userInitiated) {
Self.runHermes(context: context, args: args).exitCode
}.value
transientMessage = exitCode == 0 ? successMessage : "Command failed"
await load()
// Auto-clear toast after 3s.
// MARK: - Writes (v0.13)
public func archive(_ skill: String) async {
pendingArchiveName = skill
await runWithReload(verb: "archive", successMessage: "Archived \(skill)") {
try await self.service.archive(skill)
}
pendingArchiveName = nil
await loadArchive()
}
/// Stage 1 of the bulk-prune flow. Calls `prune --dry-run` and
/// populates `pruneSummary`; the View binds its confirm sheet to
/// the non-nil presence of this property.
public func planPrune() async {
do {
pruneSummary = try await service.prune(dryRun: true)
} catch {
errorMessage = (error as? LocalizedError)?.errorDescription
?? error.localizedDescription
pruneSummary = nil
}
}
/// Stage 2 of the bulk-prune flow. Destructive removes everything
/// currently archived. Clears `pruneSummary` regardless of outcome
/// so the confirm sheet dismisses.
public func confirmPrune() async {
isPruning = true
do {
_ = try await service.prune(dryRun: false)
transientMessage = "Pruned archived skills"
errorMessage = nil
await loadArchive()
await load()
scheduleTransientClear()
} catch {
errorMessage = (error as? LocalizedError)?.errorDescription
?? error.localizedDescription
}
isPruning = false
pruneSummary = nil
}
/// Cancel the in-flight prune-confirm flow without running.
public func cancelPrune() {
pruneSummary = nil
}
/// User-driven dismissal of the inline error banner.
public func dismissError() {
errorMessage = nil
}
// MARK: - Helpers
/// Run a service call, route success `transientMessage`, failure
/// `errorMessage`, and reload `status` either way. Mirrors the
/// previous `runAndReload` helper but goes through the typed
/// service surface.
private func runWithReload(
verb: String,
successMessage: String,
body: @escaping @Sendable () async throws -> Void
) async {
do {
try await body()
transientMessage = successMessage
errorMessage = nil
await load()
scheduleTransientClear()
} catch {
let message = (error as? LocalizedError)?.errorDescription
?? error.localizedDescription
errorMessage = message
transientMessage = nil
await load()
}
}
private func scheduleTransientClear() {
Task { @MainActor [weak self] in
try? await Task.sleep(nanoseconds: 3_000_000_000)
self?.transientMessage = nil
}
}
/// Wrap the transport-level `runProcess` so the call sites don't
/// have to reach for it directly. Combined stdout+stderr.
// MARK: - Legacy sync helpers (kept for `load`'s detached path)
nonisolated private static func runHermes(
context: ServerContext,
args: [String]
@@ -229,6 +229,12 @@ public final class RichChatViewModel {
public private(set) var acpOutputTokens = 0
public private(set) var acpThoughtTokens = 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`.
public private(set) var acpCommands: [HermesSlashCommand] = []
@@ -248,15 +254,73 @@ public final class RichChatViewModel {
/// Hermes v2026.4.23+ but listed here unconditionally so older
/// hosts that don't advertise it still surface the trigger; the
/// agent will respond appropriately or no-op gracefully.
///
/// v2.8 / Hermes v0.13 adds `/goal` (lock the agent on a target
/// across turns) and `/queue` (queue a prompt for after the current
/// turn). Both ride the same `.acpNonInterruptive` source Hermes
/// parses them server-side, the wire shape is plain
/// `session/prompt`, and the chat UI keeps the "Agent working"
/// indicator off when they're sent. They're listed unconditionally
/// here; capability filtering happens in `availableCommands` so
/// pre-v0.13 hosts don't see `/goal` or `/queue` in the slash menu.
// TODO(WS-2-Q7): verify against a real v0.13 ACP host that `/goal`
// is in fact non-interruptive on the wire. If Hermes treats it as a
// regular prompt that flips "Agent working", drop it from this
// list and route it through the standard send path (the pill
// bookkeeping in `recordActiveGoal` is independent of the
// interruptive classification).
public static let nonInterruptiveCommands: [HermesSlashCommand] = [
HermesSlashCommand(
name: "steer",
description: "Nudge the agent mid-run (applies after the next tool call)",
argumentHint: "<guidance>",
source: .acpNonInterruptive
),
HermesSlashCommand(
name: "goal",
description: "Lock the agent on a goal that persists across turns",
argumentHint: "<text>",
source: .acpNonInterruptive
),
HermesSlashCommand(
name: "queue",
description: "Queue a prompt to run after the current turn",
argumentHint: "<text>",
source: .acpNonInterruptive
)
]
/// Capability snapshot the chat surface uses to filter
/// `availableCommands`. Set by the chat controller (Mac
/// `ChatViewModel`, iOS `ChatController`) at session-start time and
/// kept fresh via the `HermesCapabilitiesStore` env binding. Default
/// `.empty` means "no v0.13 surfaces" pre-v0.13 hosts and harness
/// scenarios (Previews, smoke tests) never expose `/goal` or
/// `/queue` until the controller publishes a real capabilities
/// value. `@ObservationIgnored` so capability refreshes don't trash
/// the streaming-message render budget; controllers call
/// `publishCapabilities(_:)` once per refresh tick.
@ObservationIgnored
public var capabilitiesGate: HermesCapabilities = .empty
/// Optimistic local mirror of the agent's currently-locked goal.
/// Set by `recordActiveGoal(text:)` the moment the user sends
/// `/goal `; cleared on `/goal --clear` or `reset()`. Pre-v0.13
/// hosts can't reach this code path (the slash menu hides `/goal`),
/// but a typed-out `/goal foo` against an older host would still
/// land here briefly until Hermes' "unknown command" reply lands
/// see WS-2 plan "Inconsistency caveat".
public private(set) var activeGoal: HermesActiveGoal?
/// Optimistic mirror of prompts the user has queued via `/queue `
/// while a turn is in flight. Hermes is the authoritative owner
/// server-side; this list drives the chat-header chip + popover and
/// drains FIFO via `popQueuedPrompt()` when a turn completes.
/// Best-effort: if Hermes' server-side queue gets out of sync
/// (deferred prompt aborted, dropped on disconnect) the user sees a
/// stale chip until their next interaction.
public private(set) var queuedPrompts: [HermesQueuedPrompt] = []
/// Transient hint shown above the composer, e.g. "Guidance queued
/// applies after the next tool call." for `/steer`. The chat view
/// auto-clears it after a short delay (handled in the view); the
@@ -318,12 +382,94 @@ public final class RichChatViewModel {
!acpNames.contains($0.name) && !projectNames.contains($0.name)
}
let occupied = acpNames.union(projectNames).union(Set(quicks.map(\.name)))
let nonInterruptive = Self.nonInterruptiveCommands.filter {
!occupied.contains($0.name)
// Capability gate: `/goal` and `/queue` are v0.13+ surfaces;
// hide them when the connected host is older. `/steer` is
// surfaced unconditionally it works on v0.11+ during an
// active turn; idle-session greying for pre-v0.13 hosts is
// the input bar's concern (it reads `hasACPSteerOnIdle`).
let supported: [HermesSlashCommand] = Self.nonInterruptiveCommands.filter { cmd in
switch cmd.name {
case "goal": return capabilitiesGate.hasGoals
case "queue": return capabilitiesGate.hasACPQueue
case "steer": return true
default: return true
}
}
let nonInterruptive = supported.filter { !occupied.contains($0.name) }
return acpCommands + projectAsHermes + quicks + nonInterruptive
}
/// Publish a fresh capabilities snapshot from the controller.
/// Called whenever `HermesCapabilitiesStore.capabilities` changes
/// (initial detection, post-refresh, server switch). The chat input
/// bar's slash menu re-reads `availableCommands` lazily, so this is
/// just a stored-value swap no observable churn.
public func publishCapabilities(_ caps: HermesCapabilities) {
capabilitiesGate = caps
}
/// Optimistic write triggered when the user sends `/goal <text>`.
/// Pass `nil` (or empty) to clear (the `/goal --clear` path). The
/// pill renders synchronously off this state; there is no
/// authoritative server read-back in v2.8.0 see WS-2 plan Q1.
// TODO(WS-2-Q1): hook a Hermes-supplied goal-state read-back path
// here once we know whether v0.13 exposes goal state via an ACP
// session-startup notification, a session-sidecar JSON field, or a
// `/goal --status` reply. Until then `activeGoal` is purely
// user-set and does not survive a session resume.
public func recordActiveGoal(text: String?) {
if let text, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
activeGoal = HermesActiveGoal(
text: text.trimmingCharacters(in: .whitespacesAndNewlines),
setAt: Date()
)
} else {
activeGoal = nil
}
}
/// Append an optimistically-queued prompt to the local mirror
/// (driven by `/queue <text>`). No-op for empty / whitespace input.
public func recordQueuedPrompt(text: String) {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
queuedPrompts.append(HermesQueuedPrompt(text: trimmed))
}
/// Drain the next queued prompt off the local mirror, FIFO. Called
/// from `handlePromptComplete` once a turn settles Hermes runs
/// the actual queued prompt server-side; popping here keeps the
/// header chip count honest. Returns the popped prompt for any
/// caller that wants to log it; the chat UI ignores the return.
@discardableResult
public func popQueuedPrompt() -> HermesQueuedPrompt? {
queuedPrompts.isEmpty ? nil : queuedPrompts.removeFirst()
}
/// Parse the argument slug from a `/goal ` invocation. Pure
/// function exposed for unit tests. The chat dispatch reads this
/// to decide whether to set, clear, or no-op the optimistic pill.
public enum GoalCommandArgument: Equatable {
case set(String)
case clear
/// User typed `/goal` with no argument Hermes will reply
/// with usage; Scarf shows a neutral hint and doesn't touch
/// the pill state.
case empty
}
public static func parseGoalArgument(_ raw: String) -> GoalCommandArgument {
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty { return .empty }
// Accept `--clear`, `clear`, and case-insensitive variants so
// typos don't accidentally lock the goal text to literal
// "Clear". `--clear` is the canonical form (matches Hermes
// CLI flag style).
let lowered = trimmed.lowercased()
if lowered == "--clear" || lowered == "clear" { return .clear }
return .set(trimmed)
}
/// True when `text` is a non-interruptive command that should NOT
/// flip `isAgentWorking` to true on send. Used by the Mac/iOS chat
/// view models to skip the "agent working" overlay change for
@@ -468,12 +614,21 @@ public final class RichChatViewModel {
acpErrorHint = nil
acpErrorDetails = nil
acpCachedReadTokens = 0
acpCompressionCount = 0
acpCommands = []
projectScopedCommands = []
currentTurnStart = nil
turnDurations = [:]
transientHint = nil
pendingPermission = nil
// v2.8 / Hermes v0.13 drop optimistic v0.13 surfaces on
// session reset so a fresh chat (or a resume into a different
// session) doesn't paint stale goal / queue state from the
// previous one. The capabilities gate stays on whatever the
// controller most recently published; it's a host-level value
// that doesn't change with session boundaries.
activeGoal = nil
queuedPrompts = []
loadQuickCommands()
}
@@ -811,7 +966,30 @@ public final class RichChatViewModel {
acpOutputTokens += response.outputTokens
acpThoughtTokens += response.thoughtTokens
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
// v2.8 / Hermes v0.13 Hermes runs the next `/queue`-deferred
// prompt server-side now that this turn has settled. Drain the
// local mirror FIFO so the header chip count matches what the
// user staged. Best-effort: if Hermes' authoritative queue
// diverged (deferred prompt aborted, dropped on disconnect),
// the chip is one tick stale until the user's next interaction.
if !queuedPrompts.isEmpty {
popQueuedPrompt()
}
// TODO(v2.8.1): when this completes after an auto-resumed
// checkpoint (Hermes v0.13's "Auto-resume interrupted sessions
// after gateway restart"), surface a one-shot "Auto-resumed
// from checkpoint" indicator. Wire-shape unknown until a v0.13
// dogfooding pass confirms whether the resume lands as a
// visible ACP event or is purely server-side. Deferred from
// v2.8.0 per WS-2 plan Q3.
buildMessageGroups()
// Final position after the prompt settles. Catches fast responses
// (slash commands, short replies) where `.defaultScrollAnchor(.bottom)`
@@ -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"])
}
}
@@ -9,6 +9,13 @@ import Foundation
// MARK: - Version line parsing
@Test func parseV013ReleaseLine() {
let caps = HermesCapabilities.parseLine("Hermes Agent v0.13.0 (2026.5.7)")
#expect(caps.semver == HermesCapabilities.SemVer(major: 0, minor: 13, patch: 0))
#expect(caps.dateVersion == HermesCapabilities.DateVersion(year: 2026, month: 5, day: 7))
#expect(caps.detected)
}
@Test func parseV012ReleaseLine() {
let caps = HermesCapabilities.parseLine("Hermes Agent v0.12.0 (2026.4.30)")
#expect(caps.semver == HermesCapabilities.SemVer(major: 0, minor: 12, patch: 0))
@@ -75,8 +82,42 @@ import Foundation
// MARK: - Capability flags
@Test func v013FlagsAllOn() {
let caps = HermesCapabilities.parseLine("Hermes Agent v0.13.0 (2026.5.7)")
// v0.12 surfaces remain on.
#expect(caps.hasCurator)
#expect(caps.hasKanban)
#expect(caps.hasACPImagePrompts)
#expect(!caps.hasFlushMemoriesAux)
// v0.13 surfaces light up.
#expect(caps.hasGoals)
#expect(caps.hasACPQueue)
#expect(caps.hasACPSteerOnIdle)
#expect(caps.hasKanbanDiagnostics)
#expect(caps.hasCuratorArchive)
#expect(caps.hasGoogleChatPlatform)
#expect(caps.hasGatewayAllowlists)
#expect(caps.hasGatewayBusyAckToggle)
#expect(caps.hasGatewayRestartNotification)
#expect(caps.hasGatewayList)
#expect(caps.hasMCPSSETransport)
#expect(caps.hasCronNoAgent)
#expect(caps.hasWebToolsBackendSplit)
#expect(caps.hasProfileNoSkills)
#expect(caps.hasContextCompressionCount)
#expect(caps.hasNewWithSessionName)
#expect(caps.hasUpdateNonInteractive)
#expect(caps.hasOpenRouterResponseCache)
#expect(caps.hasImageGenModel)
#expect(caps.hasDisplayLanguage)
#expect(caps.hasXAIVoiceCloning)
#expect(caps.hasVideoAnalyze)
#expect(caps.hasTransformLLMOutputHook)
}
@Test func v012FlagsAllOn() {
let caps = HermesCapabilities.parseLine("Hermes Agent v0.12.0 (2026.4.30)")
// v0.12 surfaces on.
#expect(caps.hasCurator)
#expect(caps.hasFallbackCommand)
#expect(caps.hasKanban)
@@ -94,6 +135,22 @@ import Foundation
#expect(caps.hasRedactionToggle)
// flush_memories was REMOVED in v0.12 flag inverts.
#expect(!caps.hasFlushMemoriesAux)
// v0.13 surfaces stay off on a v0.12 host.
#expect(!caps.hasGoals)
#expect(!caps.hasACPQueue)
#expect(!caps.hasKanbanDiagnostics)
#expect(!caps.hasCuratorArchive)
#expect(!caps.hasGoogleChatPlatform)
#expect(!caps.hasGatewayAllowlists)
#expect(!caps.hasMCPSSETransport)
#expect(!caps.hasCronNoAgent)
#expect(!caps.hasWebToolsBackendSplit)
#expect(!caps.hasProfileNoSkills)
#expect(!caps.hasContextCompressionCount)
#expect(!caps.hasOpenRouterResponseCache)
#expect(!caps.hasImageGenModel)
#expect(!caps.hasDisplayLanguage)
#expect(!caps.hasXAIVoiceCloning)
}
@Test func v011FlagsAllOff() {
@@ -126,11 +183,45 @@ import Foundation
}
@Test func futureVersionRetainsCapabilities() {
// A v0.13 (hypothetical) should still see all v0.12 capabilities on.
let caps = HermesCapabilities.parseLine("Hermes Agent v0.13.0 (2026.6.1)")
// A v0.14 (hypothetical) should still see all v0.12 + v0.13 capabilities on.
let caps = HermesCapabilities.parseLine("Hermes Agent v0.14.0 (2026.7.1)")
#expect(caps.hasCurator)
#expect(caps.hasACPImagePrompts)
#expect(caps.hasGoals)
#expect(caps.hasKanbanDiagnostics)
#expect(caps.hasCuratorArchive)
// And flush_memories stays gone.
#expect(!caps.hasFlushMemoriesAux)
}
@Test func v0_13_patchReleaseStillEnablesAllFlags() {
// A v0.13.4 patch release should still enable every v0.13 flag.
let caps = HermesCapabilities.parseLine("Hermes Agent v0.13.4 (2026.5.20)")
#expect(caps.hasGoals)
#expect(caps.hasACPQueue)
#expect(caps.hasKanbanDiagnostics)
#expect(caps.hasGoogleChatPlatform)
}
// MARK: - isV013OrLater convenience predicate
@Test func isV013OrLater_v013HostTrue() {
let caps = HermesCapabilities.parseLine("Hermes Agent v0.13.0 (2026.5.7)")
#expect(caps.isV013OrLater)
}
@Test func isV013OrLater_v012HostFalse() {
let caps = HermesCapabilities.parseLine("Hermes Agent v0.12.0 (2026.4.30)")
#expect(!caps.isV013OrLater)
}
@Test func isV013OrLater_emptyFalse() {
let caps = HermesCapabilities.empty
#expect(!caps.isV013OrLater)
}
@Test func isV013OrLater_v014HostTrue() {
let caps = HermesCapabilities.parseLine("Hermes Agent v0.14.0 (2026.7.1)")
#expect(caps.isV013OrLater)
}
}
@@ -151,4 +151,169 @@ import Foundation
#expect(parsed?.patchCount == 2)
#expect(parsed?.lastActivityLabel == "2026-04-25")
}
// MARK: - v0.13 list-archived / prune fixtures (WS-4)
/// Empty JSON array `[]`. Locks in the happy-path no-archives shape.
@Test func listArchivedEmpty() throws {
let result = try CuratorService.parseListArchived(stdout: "[]")
#expect(result.isEmpty)
}
/// Three archives with full optional fields. Asserts each
/// optional value decodes through `decodeIfPresent` and that
/// the computed labels resolve.
@Test func listArchivedThreeSkills() throws {
let json = """
[
{
"name": "legacy-helper",
"category": "templates",
"archived_at": "2026-04-22T03:14:09Z",
"reason": "stale: 91d unused",
"size_bytes": 4521,
"path": "/Users/u/.hermes/skills/.archived/legacy-helper"
},
{
"name": "old-translator",
"category": "user",
"archived_at": "2026-04-23T10:00:00Z",
"reason": "consolidated with translator",
"size_bytes": 8192
},
{
"name": "minimal"
}
]
"""
let result = try CuratorService.parseListArchived(stdout: json)
#expect(result.count == 3)
#expect(result[0].name == "legacy-helper")
#expect(result[0].category == "templates")
#expect(result[0].reason == "stale: 91d unused")
#expect(result[0].sizeBytes == 4521)
#expect(result[0].archivedAtLabel == "2026-04-22")
#expect(result[0].path == "/Users/u/.hermes/skills/.archived/legacy-helper")
// Tolerant: only `name` set on the third row.
#expect(result[2].name == "minimal")
#expect(result[2].category == nil)
#expect(result[2].reason == nil)
#expect(result[2].archivedAtLabel == "")
#expect(result[2].sizeLabel == "")
}
/// `{"archived": [...]}` envelope is also accepted.
@Test func listArchivedEnvelope() throws {
let json = """
{"archived": [
{"name": "envelope-skill", "size_bytes": 1024}
]}
"""
let result = try CuratorService.parseListArchived(stdout: json)
#expect(result.count == 1)
#expect(result[0].name == "envelope-skill")
}
/// Text fallback when `--json` isn't supported. Each row carries
/// the name in column 1 plus k=v chips for the optional fields.
@Test func listArchivedTextFallback() {
let text = """
legacy-helper archived=2026-04-22 size=4521 reason=stale
old-translator archived=2026-04-23 size=8192
minimal-row
"""
let result = CuratorService.parseListArchivedText(text)
#expect(result.count == 3)
#expect(result[0].name == "legacy-helper")
#expect(result[0].archivedAt == "2026-04-22")
#expect(result[0].sizeBytes == 4521)
#expect(result[0].reason == "stale")
#expect(result[2].name == "minimal-row")
#expect(result[2].sizeBytes == nil)
}
/// Empty-state sentinel folds to `[]` (parallel to KanbanService's
/// `"no matching tasks"` handling).
@Test func listArchivedNoArchivedSentinel() throws {
let result = try CuratorService.parseListArchived(stdout: "no archived skills\n")
#expect(result.isEmpty)
}
/// Whitespace-only stdout also folds to empty.
@Test func listArchivedWhitespaceFoldsToEmpty() throws {
let result = try CuratorService.parseListArchived(stdout: " \n\n")
#expect(result.isEmpty)
}
/// Decode failure (clearly non-JSON, non-text) throws. We accept
/// JSON, the envelope, the empty sentinel, or text rows; anything
/// else surfaces as a `CuratorError.decoding`.
@Test func listArchivedNonsenseThrows() throws {
do {
_ = try CuratorService.parseListArchived(stdout: "{garbage")
Issue.record("expected decoding throw")
} catch let error as CuratorError {
if case .decoding = error {
// expected
} else {
Issue.record("unexpected error \(error)")
}
}
}
/// Prune-dry-run JSON with `would_remove` + `total_bytes`.
@Test func pruneDryRunHappyPath() {
let json = """
{
"would_remove": [
{"name": "stale-a", "size_bytes": 1000},
{"name": "stale-b", "size_bytes": 2000}
],
"total_bytes": 3000
}
"""
let summary = CuratorService.parsePruneDryRun(json)
#expect(summary.totalCount == 2)
#expect(summary.totalBytes == 3000)
#expect(summary.wouldRemove.first?.name == "stale-a")
}
/// Zero-skill prune is a valid dry-run (no archives).
@Test func pruneDryRunZeroSkills() {
let json = """
{"would_remove": [], "total_bytes": 0}
"""
let summary = CuratorService.parsePruneDryRun(json)
#expect(summary.totalCount == 0)
#expect(summary.totalBytes == 0)
#expect(summary.totalBytesLabel == "")
}
/// Bare-array fallback: some Hermes builds may print just the
/// would-remove list when the wrapper is missing.
@Test func pruneDryRunBareArrayFallback() {
let json = """
[{"name": "lonely", "size_bytes": 500}]
"""
let summary = CuratorService.parsePruneDryRun(json)
#expect(summary.totalCount == 1)
#expect(summary.totalBytes == 500)
}
/// Empty / whitespace stdout zero summary (no decoding throw).
@Test func pruneDryRunEmptyStaysSafe() {
let summary = CuratorService.parsePruneDryRun(" \n")
#expect(summary.totalCount == 0)
#expect(summary.totalBytes == 0)
}
/// Verify the size label uses the byte formatter (not raw bytes).
@Test func archivedSkillSizeLabelFormats() {
let big = HermesCuratorArchivedSkill(name: "x", sizeBytes: 1_500_000)
// ByteCountFormatter produces a localized label; just verify
// it's non-empty and not raw "1500000".
#expect(!big.sizeLabel.isEmpty)
#expect(big.sizeLabel != "1500000")
}
}
@@ -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")
}
}
@@ -0,0 +1,522 @@
import Testing
import Foundation
@testable import ScarfCore
/// Pure-logic tests for the v2.7.5 Kanban model layer. The actor-based
/// `KanbanService` is exercised separately under integration tests
/// since it spawns `hermes kanban ` subprocesses; this suite covers
/// the wire-shape contracts and the synchronous transition planner.
@Suite struct KanbanModelsTests {
// MARK: - HermesKanbanTask decoding
@Test func decodeListRow() throws {
let json = """
{
"id": "t_9f2a",
"title": "Investigate flaky test",
"body": "Repro on CI but not local.",
"assignee": "researcher",
"status": "running",
"priority": 50,
"tenant": "scarf:demo",
"workspace_kind": "scratch",
"workspace_path": "/Users/alan/.hermes/kanban/workspaces/t_9f2a",
"created_by": "user",
"created_at": "2026-05-06T12:00:00Z",
"started_at": "2026-05-06T12:01:00Z",
"skills": ["debugging"],
"idempotency_key": "abc",
"last_heartbeat_at": "2026-05-06T12:05:00Z",
"max_runtime_seconds": 1800,
"current_run_id": 1
}
"""
let task = try JSONDecoder().decode(HermesKanbanTask.self, from: Data(json.utf8))
#expect(task.id == "t_9f2a")
#expect(task.assignee == "researcher")
#expect(task.status == "running")
#expect(task.tenant == "scarf:demo")
#expect(task.workspaceKind == "scratch")
#expect(task.skills == ["debugging"])
#expect(task.idempotencyKey == "abc")
#expect(task.maxRuntimeSeconds == 1800)
#expect(task.currentRunId == 1)
}
// MARK: - Assignee table parsing
//
// `hermes kanban assignees` prints either a JSON array (when
// `--json` is honored) OR a Rich-style human table OR an
// empty-state sentinel "(no assignees create a profile with
// `hermes -p <name> setup`)". The first iteration of the parser
// tokenized the sentinel and emitted `(no` as a profile name,
// which surfaced in the Mac inspector's assignee dropdown.
// MARK: - LocalTransport subprocess environment
@Test func localTransportSubprocessEnvIncludesExecutableDir() {
// GUI-launched Scarf would otherwise hand subprocesses
// `/usr/bin:/bin:/usr/sbin:/sbin`, which doesn't include
// `~/.local/bin` so when Hermes's kanban dispatcher
// spawns a worker by bare name, it fails with
// `executable not found on PATH` and the run records
// `outcome=spawn_failed`. Unblock by always making sure
// the directory of the executable we're launching is on
// PATH for the child.
let previous = LocalTransport.environmentEnricher
defer { LocalTransport.environmentEnricher = previous }
LocalTransport.environmentEnricher = nil
let env = LocalTransport.subprocessEnvironment(
forExecutable: "/Users/alanwizemann/.local/bin/hermes"
)
let path = env["PATH"] ?? ""
#expect(path.contains("/Users/alanwizemann/.local/bin"))
}
@Test func localTransportSubprocessEnvLetsEnricherWinPATH() {
let previous = LocalTransport.environmentEnricher
defer { LocalTransport.environmentEnricher = previous }
LocalTransport.environmentEnricher = {
// Simulate a login-shell probe returning a fuller PATH +
// some credential env. The enricher's PATH must override
// the GUI-process PATH.
return [
"PATH": "/opt/homebrew/bin:/usr/local/bin:/Users/me/.local/bin",
"ANTHROPIC_API_KEY": "sk-test-fake"
]
}
let env = LocalTransport.subprocessEnvironment(
forExecutable: "/usr/local/bin/hermes"
)
// Enricher's PATH wins (PATH is the whole point of running it).
#expect(env["PATH"]?.contains("/opt/homebrew/bin") == true)
// Credential env is forwarded (process env didn't have it).
#expect(env["ANTHROPIC_API_KEY"] == "sk-test-fake")
}
@Test func parseAssigneeTableSkipsNoAssigneesSentinel() {
// Use the same parser via its public stand-in: round-trip
// through a fixture that decodes via JSON would skip the
// table parser, so we test the fallback indirectly by
// constructing the same decoder pipeline. The parser is
// private to KanbanService; this test asserts the visible
// contract (no garbage profile names appear in the picker)
// by verifying the decode path on the real CLI fixture
// returns an empty array rather than a `(no` row.
let fixture = "(no assignees — create a profile with `hermes -p <name> setup`)"
// Through the public surface: we know `KanbanService.assignees`
// would consume this stdout when --json fails. The validator
// we care about is the regex check; reproduce inline:
let pattern = "^[a-zA-Z0-9_-]+$"
let firstToken = fixture
.split(whereSeparator: { $0 == "\t" || $0 == " " })
.first.map(String.init) ?? ""
// Confirms the parser's regex would reject "(no".
#expect(firstToken.range(of: pattern, options: .regularExpression) == nil)
}
@Test func decodeUnixIntegerTimestamps() throws {
// Real `hermes kanban create --json` output uses Unix integer
// seconds for created_at / started_at its SQLite columns are
// INTEGER. The decoder must normalize them into ISO-8601 strings
// so downstream code works with one type.
let json = """
{
"id": "t_2a0be199",
"title": "smoke",
"status": "ready",
"priority": 50,
"created_at": 1778160614,
"started_at": null,
"skills": []
}
"""
let task = try JSONDecoder().decode(HermesKanbanTask.self, from: Data(json.utf8))
#expect(task.id == "t_2a0be199")
// Should have been converted from Unix int to an ISO-8601 string
// exact format is platform-stable.
#expect(task.createdAt?.contains("2026") == true)
#expect(task.startedAt == nil)
}
@Test func decodeMissingOptionalsBecomesNil() throws {
// Hermes emits a minimal task object when many fields are
// absent; the decoder must tolerate it.
let json = """
{ "id": "t_x", "title": "ok", "status": "todo" }
"""
let task = try JSONDecoder().decode(HermesKanbanTask.self, from: Data(json.utf8))
#expect(task.id == "t_x")
#expect(task.assignee == nil)
#expect(task.priority == nil)
#expect(task.tenant == nil)
#expect(task.skills.isEmpty)
}
// MARK: - Status / column projection
@Test func statusToColumnMapping() {
#expect(KanbanStatus.from("triage").boardColumn == .triage)
#expect(KanbanStatus.from("todo").boardColumn == .upNext)
#expect(KanbanStatus.from("ready").boardColumn == .upNext)
#expect(KanbanStatus.from("running").boardColumn == .running)
#expect(KanbanStatus.from("blocked").boardColumn == .blocked)
#expect(KanbanStatus.from("done").boardColumn == .done)
#expect(KanbanStatus.from("archived").boardColumn == .archived)
#expect(KanbanStatus.from("WHATEVER").boardColumn == .upNext) // unknown upNext
}
// MARK: - KanbanCreateRequest argv assembly
@Test func createRequestArgvIncludesAllFields() {
let req = KanbanCreateRequest(
title: "Translate doc",
body: "Spanish, please",
assignee: "researcher",
parentIds: ["t_parent"],
workspace: .directory("/tmp/proj"),
tenant: "scarf:demo",
priority: 75,
triage: true,
idempotencyKey: "key-1",
maxRuntimeSeconds: 1800,
createdBy: "alan",
skills: ["translation", "github-code-review"]
)
let argv = req.argv()
#expect(argv.contains("--body"))
#expect(argv.contains("--assignee"))
#expect(argv.contains("--parent"))
#expect(argv.contains("--workspace"))
#expect(argv.contains("dir:/tmp/proj"))
#expect(argv.contains("--tenant"))
#expect(argv.contains("scarf:demo"))
#expect(argv.contains("--priority"))
#expect(argv.contains("75"))
#expect(argv.contains("--triage"))
#expect(argv.contains("--idempotency-key"))
#expect(argv.contains("--max-runtime"))
#expect(argv.contains("--created-by"))
#expect(argv.contains("--skill"))
#expect(argv.last == "Translate doc") // positional title is last
#expect(argv.contains("--json"))
}
@Test func createRequestArgvOmitsAbsent() {
let req = KanbanCreateRequest(title: "minimal")
let argv = req.argv()
#expect(argv.contains("--json"))
#expect(argv.last == "minimal")
#expect(!argv.contains("--body"))
#expect(!argv.contains("--assignee"))
#expect(!argv.contains("--triage"))
}
// MARK: - KanbanListFilter argv
@Test func listFilterEmptyOnlyJSON() {
let argv = KanbanListFilter.all.argv()
#expect(argv == ["--json"])
}
@Test func listFilterStatusFlag() {
let argv = KanbanListFilter(status: .running).argv()
#expect(argv.contains("--status"))
#expect(argv.contains("running"))
}
@Test func listFilterTenantPasses() {
let argv = KanbanListFilter(tenant: "scarf:demo").argv()
#expect(argv.contains("--tenant"))
#expect(argv.contains("scarf:demo"))
}
@Test func listFilterArchivedAndMine() {
let argv = KanbanListFilter(includeArchived: true, mineOnly: true).argv()
#expect(argv.contains("--mine"))
#expect(argv.contains("--archived"))
}
// MARK: - Transition planning
@Test func planUpNextToRunningDispatches() throws {
// `dispatch`, not `claim`. See KanbanTransitionStep doc for the
// rationale claim doesn't spawn a worker; the dispatcher does.
let plan = try KanbanService.plan(
for: KanbanTransition(from: .upNext, to: .running)
)
#expect(plan.steps == [.dispatch])
}
@Test func planRunningToBlockedRequiresReason() throws {
let plan = try KanbanService.plan(
for: KanbanTransition(from: .running, to: .blocked)
)
#expect(plan.requiresBlockReason)
}
@Test func planBlockedToRunningChainsTwoVerbs() throws {
let plan = try KanbanService.plan(
for: KanbanTransition(from: .blocked, to: .running)
)
// unblock then dispatch
#expect(plan.steps.count == 2)
if case .unblock = plan.steps.first {} else {
Issue.record("expected first step .unblock, got \(plan.steps)")
}
if case .dispatch = plan.steps.last {} else {
Issue.record("expected last step .dispatch, got \(plan.steps)")
}
}
@Test func planDoneToAnythingForbidden() {
do {
_ = try KanbanService.plan(
for: KanbanTransition(from: .done, to: .upNext)
)
Issue.record("expected error")
} catch let err as KanbanError {
if case .forbiddenTransition = err {
// ok
} else {
Issue.record("wrong error: \(err)")
}
} catch {
Issue.record("unexpected error: \(error)")
}
}
@Test func planTriageToUpNextForbidden() {
do {
_ = try KanbanService.plan(
for: KanbanTransition(from: .triage, to: .upNext)
)
Issue.record("expected error")
} catch let err as KanbanError {
if case .forbiddenTransition = err {
// ok
} else {
Issue.record("wrong error: \(err)")
}
} catch {
Issue.record("unexpected error: \(error)")
}
}
@Test func planNoOpProducesEmptyPlan() throws {
let plan = try KanbanService.plan(
for: KanbanTransition(from: .running, to: .running)
)
#expect(plan.steps.isEmpty)
}
// MARK: - Stats glance
@Test func glanceStringJoinsNonEmptyBuckets() {
let stats = HermesKanbanStats(
byStatus: ["todo": 12, "running": 3, "blocked": 5, "done": 0]
)
#expect(stats.glanceString == "12 todo · 3 running · 5 blocked")
#expect(stats.activeCount == 12 + 3 + 5)
}
@Test func glanceStringEmptyWhenZero() {
let stats = HermesKanbanStats(byStatus: [:])
#expect(stats.glanceString.isEmpty)
#expect(stats.activeCount == 0)
}
// MARK: - v0.13 (Hermes 2026.5.7) tolerant decode
//
// The contract these tests pin: a v0.13 host's task / run / detail
// JSON decodes successfully WITH the new fields populated, AND a
// pre-v0.13 (v0.12) host's task / run / detail JSON decodes
// successfully WITHOUT the new fields (everything resolves to nil
// or empty). Drift from this pair = a regression that bites every
// user not yet on Hermes v0.13.
@Test func decodeV013TaskFields() throws {
let json = """
{
"id": "t_v013",
"title": "v0.13 task",
"status": "blocked",
"max_retries": 5,
"auto_blocked_reason": "worker exited without `kanban complete`",
"hallucination_gate_status": "pending",
"diagnostics": [
{"kind": "worker_exit_no_complete", "message": "exit code 0 with no complete call", "detected_at": 1778160614},
{"kind": "darwin_zombie_detected", "detected_at": "2026-05-09T12:00:00Z"}
]
}
"""
let task = try JSONDecoder().decode(HermesKanbanTask.self, from: Data(json.utf8))
#expect(task.maxRetries == 5)
#expect(task.autoBlockedReason?.contains("kanban complete") == true)
#expect(task.hallucinationGateStatus == "pending")
#expect(task.diagnostics.count == 2)
#expect(task.diagnostics.first?.kind == "worker_exit_no_complete")
#expect(task.diagnostics.last?.detectedAt?.contains("2026") == true)
}
@Test func decodeV012TaskHasNoNewFields() throws {
// The most damaging failure mode is a v0.12 user upgrading Scarf
// and having the board stop loading because a v0.13-only field
// is required. Pin the contract.
let json = """
{"id": "t_legacy", "title": "v0.12 task", "status": "ready"}
"""
let task = try JSONDecoder().decode(HermesKanbanTask.self, from: Data(json.utf8))
#expect(task.maxRetries == nil)
#expect(task.autoBlockedReason == nil)
#expect(task.hallucinationGateStatus == nil)
#expect(task.diagnostics.isEmpty)
}
@Test func decodeMalformedDiagnosticTolerated() throws {
// If Hermes emits a malformed diagnostics value, the rest of the
// task should still decode. We use try? on the diagnostics decode
// so a single bad entry doesn't reject the whole row.
let json = """
{
"id": "t_x",
"title": "x",
"status": "ready",
"diagnostics": "not-an-array"
}
"""
let task = try JSONDecoder().decode(HermesKanbanTask.self, from: Data(json.utf8))
#expect(task.id == "t_x")
// Diagnostics field couldn't decode treat as empty.
#expect(task.diagnostics.isEmpty)
}
@Test func hallucinationGateMirrorMapsKnownValues() {
#expect(KanbanHallucinationGate.from("pending") == .pending)
#expect(KanbanHallucinationGate.from("verified") == .verified)
#expect(KanbanHallucinationGate.from("REJECTED") == .rejected) // case-insensitive
#expect(KanbanHallucinationGate.from(nil) == nil)
#expect(KanbanHallucinationGate.from("") == nil)
// Unknown wire values fall through to nil so the banner stays
// hidden; future Hermes versions can add `quarantined` etc.
// without a Scarf release.
#expect(KanbanHallucinationGate.from("quarantined") == nil)
}
@Test func diagnosticKindMirrorMapsKnownValues() {
#expect(KanbanDiagnosticKind.from("heartbeat_stalled") == .heartbeatStalled)
#expect(KanbanDiagnosticKind.from("DARWIN_ZOMBIE_DETECTED") == .darwinZombieDetected)
// Unknown kinds fall through to .unknown so views can render
// the raw string verbatim.
#expect(KanbanDiagnosticKind.from("future_kind_v014") == .unknown)
}
@Test func diagnosticSeverityMapping() {
#expect(KanbanDiagnosticKind.retryCapHit.severity == .danger)
#expect(KanbanDiagnosticKind.darwinZombieDetected.severity == .danger)
#expect(KanbanDiagnosticKind.heartbeatStalled.severity == .warning)
#expect(KanbanDiagnosticKind.workerExitNoComplete.severity == .warning)
#expect(KanbanDiagnosticKind.unknown.severity == .neutral)
}
@Test func createRequestArgvIncludesMaxRetries() {
let req = KanbanCreateRequest(title: "t", maxRetries: 5)
let argv = req.argv()
#expect(argv.contains("--max-retries"))
#expect(argv.contains("5"))
}
@Test func createRequestArgvOmitsMaxRetriesWhenAbsent() {
let req = KanbanCreateRequest(title: "t")
let argv = req.argv()
#expect(!argv.contains("--max-retries"))
}
@Test func decodeRunWithDiagnostics() throws {
let json = """
{
"id": 1,
"task_id": "t_x",
"status": "failed",
"started_at": 1778160000,
"ended_at": 1778160300,
"outcome": "crashed",
"error": "OOM",
"diagnostics": [
{"kind": "retry_cap_hit", "message": "3/3 retries exhausted"}
],
"failure_count": 3
}
"""
let run = try JSONDecoder().decode(HermesKanbanRun.self, from: Data(json.utf8))
#expect(run.diagnostics.count == 1)
#expect(run.diagnostics.first?.kind == "retry_cap_hit")
#expect(run.failureCount == 3)
}
@Test func decodeRunWithoutDiagnostics() throws {
// v0.12 run row no diagnostics, no failure_count, must still
// decode cleanly.
let json = """
{"id": 1, "task_id": "t_x", "status": "running", "started_at": 1778160000}
"""
let run = try JSONDecoder().decode(HermesKanbanRun.self, from: Data(json.utf8))
#expect(run.diagnostics.isEmpty)
#expect(run.failureCount == nil)
}
@Test func taskDetailMergesEnvelopeAndTaskDiagnostics() throws {
// Hermes's wire shape may put diagnostics on the task envelope OR
// on the inner task. `allDiagnostics` dedupes by (kind, detected_at)
// so a server emitting both sides doesn't surface dupes.
let json = """
{
"task": {
"id": "t_y",
"title": "y",
"status": "blocked",
"diagnostics": [
{"kind": "heartbeat_stalled", "detected_at": "2026-05-09T12:00:00Z"}
]
},
"comments": [],
"events": [],
"diagnostics": [
{"kind": "heartbeat_stalled", "detected_at": "2026-05-09T12:00:00Z"},
{"kind": "retry_cap_hit"}
]
}
"""
let detail = try JSONDecoder().decode(HermesKanbanTaskDetail.self, from: Data(json.utf8))
let merged = detail.allDiagnostics
#expect(merged.count == 2)
#expect(merged.contains(where: { $0.kind == "heartbeat_stalled" }))
#expect(merged.contains(where: { $0.kind == "retry_cap_hit" }))
}
@Test func taskDetailWithoutEnvelopeDiagnosticsDecodes() throws {
// Pre-v0.13 task detail no envelope diagnostics. Must decode.
let json = """
{
"task": {"id": "t_z", "title": "z", "status": "ready"},
"comments": [],
"events": []
}
"""
let detail = try JSONDecoder().decode(HermesKanbanTaskDetail.self, from: Data(json.utf8))
#expect(detail.envelopeDiagnostics == nil)
#expect(detail.allDiagnostics.isEmpty)
}
@Test func diagnosticDecodesUnixTimestamp() throws {
let json = """
{"kind": "spawn_failure", "detected_at": 1778160614}
"""
let diag = try JSONDecoder().decode(HermesKanbanDiagnostic.self, from: Data(json.utf8))
#expect(diag.kind == "spawn_failure")
// Decoder normalizes Unix int ISO-8601 string.
#expect(diag.detectedAt?.contains("2026") == true)
}
}
@@ -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
@Test func projectDashboardServiceRegistryRoundTrip() throws {
@@ -162,6 +162,47 @@ import Foundation
// start false.
#expect(vm.supportsCompress == 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() {
@@ -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.compression.enabled == true)
#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() {
@@ -228,6 +249,87 @@ import Foundation
#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() {
let s = CronSchedule(
kind: "cron",
@@ -241,6 +241,150 @@ import Foundation
#expect(a == b)
}
// MARK: - v0.13 non-interruptive commands (WS-2 / Persistent Goals + /queue)
@Test func nonInterruptiveListIncludesGoalAndQueue() {
let names = RichChatViewModel.nonInterruptiveCommands.map(\.name)
#expect(names.contains("steer"))
#expect(names.contains("goal"))
#expect(names.contains("queue"))
}
@MainActor
@Test func availableCommandsHidesGoalWhenCapabilityOff() {
let vm = RichChatViewModel(context: .local)
vm.publishCapabilities(.empty)
let names = vm.availableCommands.map(\.name)
#expect(!names.contains("goal"))
}
@MainActor
@Test func availableCommandsHidesQueueWhenCapabilityOff() {
let vm = RichChatViewModel(context: .local)
vm.publishCapabilities(.empty)
let names = vm.availableCommands.map(\.name)
#expect(!names.contains("queue"))
}
@MainActor
@Test func availableCommandsExposesAllThreeOnV013() {
let vm = RichChatViewModel(context: .local)
let caps = HermesCapabilities.parseLine("Hermes Agent v0.13.0 (2026.5.7)")
vm.publishCapabilities(caps)
let names = vm.availableCommands.map(\.name)
#expect(names.contains("steer"))
#expect(names.contains("goal"))
#expect(names.contains("queue"))
}
@MainActor
@Test func availableCommandsExposesSteerButHidesV013OnV012() {
let vm = RichChatViewModel(context: .local)
let caps = HermesCapabilities.parseLine("Hermes Agent v0.12.0 (2026.4.30)")
vm.publishCapabilities(caps)
let names = vm.availableCommands.map(\.name)
#expect(names.contains("steer"))
#expect(!names.contains("goal"))
#expect(!names.contains("queue"))
}
@Test func parseGoalArgumentRecognizesClearVariants() {
#expect(RichChatViewModel.parseGoalArgument("--clear") == .clear)
#expect(RichChatViewModel.parseGoalArgument("clear") == .clear)
#expect(RichChatViewModel.parseGoalArgument("Clear") == .clear)
#expect(RichChatViewModel.parseGoalArgument(" --clear ") == .clear)
}
@Test func parseGoalArgumentReturnsSetForArbitraryText() {
#expect(
RichChatViewModel.parseGoalArgument("finish v2.8 on time")
== .set("finish v2.8 on time")
)
// Whitespace around set text is trimmed.
#expect(
RichChatViewModel.parseGoalArgument(" ship it ")
== .set("ship it")
)
}
@Test func parseGoalArgumentReturnsEmptyForBlank() {
#expect(RichChatViewModel.parseGoalArgument("") == .empty)
#expect(RichChatViewModel.parseGoalArgument(" ") == .empty)
#expect(RichChatViewModel.parseGoalArgument("\n\t") == .empty)
}
@MainActor
@Test func recordActiveGoalSetsAndClears() {
let vm = RichChatViewModel(context: .local)
#expect(vm.activeGoal == nil)
vm.recordActiveGoal(text: "ship v2.8")
let goal = vm.activeGoal
#expect(goal?.text == "ship v2.8")
vm.recordActiveGoal(text: nil)
#expect(vm.activeGoal == nil)
// Empty / whitespace also clears.
vm.recordActiveGoal(text: "x")
vm.recordActiveGoal(text: " ")
#expect(vm.activeGoal == nil)
}
@MainActor
@Test func recordQueuedPromptAppendsAndPopsFIFO() {
let vm = RichChatViewModel(context: .local)
vm.recordQueuedPrompt(text: "first")
vm.recordQueuedPrompt(text: "second")
vm.recordQueuedPrompt(text: "third")
#expect(vm.queuedPrompts.count == 3)
let popped = vm.popQueuedPrompt()
#expect(popped?.text == "first")
#expect(vm.queuedPrompts.count == 2)
let next = vm.popQueuedPrompt()
#expect(next?.text == "second")
#expect(vm.queuedPrompts.first?.text == "third")
}
@MainActor
@Test func recordQueuedPromptIgnoresBlank() {
let vm = RichChatViewModel(context: .local)
vm.recordQueuedPrompt(text: "")
vm.recordQueuedPrompt(text: " ")
#expect(vm.queuedPrompts.isEmpty)
}
@MainActor
@Test func popQueuedPromptOnEmptyReturnsNil() {
let vm = RichChatViewModel(context: .local)
#expect(vm.popQueuedPrompt() == nil)
}
@Test func isNonInterruptiveSlashRecognizesGoalAndQueue() {
// Non-MainActor: the helper itself isn't MainActor-isolated;
// construct a VM on MainActor and read through it on the test
// actor to keep the assertion focused on classification.
Task { @MainActor in
let vm = RichChatViewModel(context: .local)
#expect(vm.isNonInterruptiveSlash("/goal finish v2.8"))
#expect(vm.isNonInterruptiveSlash("/queue summarize"))
#expect(vm.isNonInterruptiveSlash("/queue"))
#expect(vm.isNonInterruptiveSlash("/steer be careful"))
#expect(!vm.isNonInterruptiveSlash("hello"))
#expect(!vm.isNonInterruptiveSlash("/compress"))
}
}
@MainActor
@Test func resetClearsGoalAndQueue() {
let vm = RichChatViewModel(context: .local)
vm.recordActiveGoal(text: "x")
vm.recordQueuedPrompt(text: "a")
vm.recordQueuedPrompt(text: "b")
#expect(vm.activeGoal != nil)
#expect(vm.queuedPrompts.count == 2)
vm.reset()
#expect(vm.activeGoal == nil)
#expect(vm.queuedPrompts.isEmpty)
}
// MARK: - Helpers
static func makeTempProject() throws -> String {
@@ -242,6 +242,15 @@ import Foundation
thoughtTokens: 20, cachedReadTokens: 10
)
#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() {
+188 -36
View File
@@ -44,6 +44,19 @@ struct ChatView: View {
private var supportsImagePrompts: Bool {
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
/// `.focused(...)`; cleared by the scroll-to-dismiss gesture on
/// 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 {
// Dashboard row taps set `pendingResumeSessionID`, Project
// Detail's "New Chat" sets `pendingProjectChat`. Both fire
@@ -830,37 +854,47 @@ struct ChatView: View {
/// informational.
@ViewBuilder
private var projectContextBar: some View {
if let projectName = controller.currentProjectName,
!projectName.isEmpty
{
// v2.8.0 (WS-9): the bar is no longer project-only a non-empty
// 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) {
Image(systemName: "folder.fill")
.foregroundStyle(.tint)
.font(.caption)
VStack(alignment: .leading, spacing: 1) {
Text("Project chat")
.font(.caption2)
.foregroundStyle(ScarfColor.foregroundMuted)
HStack(spacing: 6) {
Text(projectName)
.font(.callout.weight(.medium))
.foregroundStyle(.primary)
.lineLimit(1)
.truncationMode(.tail)
if let branch = controller.currentGitBranch, !branch.isEmpty {
Label(branch, systemImage: "arrow.triangle.branch")
.font(.caption2)
.foregroundStyle(.tint)
.labelStyle(.titleAndIcon)
.padding(.horizontal, 5)
.padding(.vertical, 1)
.background(.tint.opacity(0.15), in: Capsule())
if hasProject {
Image(systemName: "folder.fill")
.foregroundStyle(.tint)
.font(.caption)
VStack(alignment: .leading, spacing: 1) {
Text("Project chat")
.font(.caption2)
.foregroundStyle(ScarfColor.foregroundMuted)
HStack(spacing: 6) {
Text(projectName)
.font(.callout.weight(.medium))
.foregroundStyle(.primary)
.lineLimit(1)
.truncationMode(.tail)
if let branch = controller.currentGitBranch, !branch.isEmpty {
Label(branch, systemImage: "arrow.triangle.branch")
.font(.caption2)
.foregroundStyle(.tint)
.labelStyle(.titleAndIcon)
.padding(.horizontal, 5)
.padding(.vertical, 1)
.background(.tint.opacity(0.15), in: Capsule())
.lineLimit(1)
}
}
}
}
if hasGoal { goalChip }
if hasQueue { queueChip }
Spacer()
if !controller.vm.projectScopedCommands.isEmpty {
if hasProject && !controller.vm.projectScopedCommands.isEmpty {
Button {
showSlashCommandsSheet = true
} label: {
@@ -882,6 +916,8 @@ struct ChatView: View {
.padding(.vertical, 6)
.frame(maxWidth: .infinity, alignment: .leading)
.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) {
ProjectSlashCommandsBrowser(
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
/// `hermes acp` + creating the ACP session. Typically ~0.51.5 s
/// 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.
vm.addUserMessage(text: "[image attached]")
}
// /steer is non-interruptive the agent is still on its
// current turn; the guidance applies after the next tool call.
// Surface a transient toast confirming the guidance was
// received. v2.5 / Hermes v2026.4.23+.
if vm.isNonInterruptiveSlash(text) {
vm.transientHint = "Guidance queued — applies after the next tool call."
Task { @MainActor [weak vm] in
try? await Task.sleep(nanoseconds: 4_000_000_000)
if vm?.transientHint == "Guidance queued — applies after the next tool call." {
vm?.transientHint = nil
}
// Non-interruptive slash commands: keep the chat working
// indicator off and surface a transient toast confirming the
// command was accepted. v2.5 added `/steer`; v2.8 / Hermes
// v0.13 adds `/goal` (lock the agent on a target across
// turns) and `/queue` (queue a prompt for after the current
// turn). Each gets its own optimistic side-effect on the VM
// so the (Mac-rendered) chat header pill / queue chip update
// synchronously. iOS doesn't surface those affordances yet
// (WS-9), but mirroring the dispatch keeps the shared VM
// state aligned across platforms otherwise an iOS user who
// ran `/goal` then opened the same session on Mac would see
// an empty pill until they typed `/goal` again.
let parsedSlash = Self.parseSlashName(text)
switch parsedSlash.name {
case "goal":
// TODO(WS-2-Q7): verify on a real v0.13 host.
let arg = RichChatViewModel.parseGoalArgument(parsedSlash.args)
switch arg {
case .set(let goalText):
vm.recordActiveGoal(text: goalText)
vm.transientHint = "Goal locked: \(Self.truncatedToastGoal(goalText))"
case .clear:
vm.recordActiveGoal(text: nil)
vm.transientHint = "Goal cleared."
case .empty:
vm.transientHint = "Sent /goal — see the agent reply for current goal."
}
scheduleTransientHintClear(snapshot: vm.transientHint)
case "queue":
// TODO(WS-2-Q5): verify the verbatim wire shape on a
// real v0.13 ACP host.
let queuedText = parsedSlash.args.trimmingCharacters(in: .whitespacesAndNewlines)
if !queuedText.isEmpty {
vm.recordQueuedPrompt(text: queuedText)
}
vm.transientHint = "Queued — runs after current turn."
scheduleTransientHintClear(snapshot: vm.transientHint)
case "steer" where vm.isNonInterruptiveSlash(text):
vm.transientHint = "Guidance queued — applies after the next tool call."
scheduleTransientHintClear(snapshot: vm.transientHint)
default:
break
}
// Project-scoped slash commands expand client-side: the user
// 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.
/// `/<name> args` matching a loaded project-scoped command is
/// expanded; everything else is sent literally.
+82 -2
View File
@@ -13,11 +13,21 @@ import ScarfDesign
/// `HermesCapabilities.hasCurator` is true.
struct CuratorView: View {
@State private var viewModel: CuratorViewModel
@Environment(\.hermesCapabilities) private var capabilitiesStore
init(context: ServerContext) {
_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 {
List {
Section {
@@ -78,18 +88,88 @@ struct CuratorView: View {
.textSelection(.enabled)
}
}
if archiveAvailable {
archivedSection
}
}
.navigationTitle("Curator")
.navigationBarTitleDisplayMode(.large)
.refreshable {
await viewModel.load()
if archiveAvailable {
await viewModel.loadArchive()
}
}
.overlay(alignment: .bottom) {
if let toast = viewModel.transientMessage {
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 {
@@ -115,7 +195,7 @@ struct CuratorView: View {
private var actionFooter: some View {
HStack(spacing: 8) {
Button {
Task { await viewModel.runNow() }
Task { await viewModel.runNow(synchronous: archiveAvailable, timeout: 600) }
} label: {
Label("Run now", systemImage: "play.fill")
}
@@ -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
}
}
}
@@ -0,0 +1,364 @@
import SwiftUI
import ScarfCore
import ScarfDesign
/// Read-only Kanban task detail sheet for iOS. Mirrors the Mac
/// inspector's 3-tab layout (Comments | Events | Runs) but routes
/// through a `NavigationStack` for iOS-native chrome and dismisses
/// to the parent kanban view, not to the board.
///
/// No mutations in v2.7.5 write actions land on iOS in a later
/// release via a bottom action bar with explicit verb buttons (no
/// drag-drop).
struct ScarfGoKanbanDetailSheet: View {
let taskId: String
let context: ServerContext
@Environment(\.dismiss) private var dismiss
@Environment(\.hermesCapabilities) private var capabilitiesStore
@State private var detail: HermesKanbanTaskDetail?
@State private var runs: [HermesKanbanRun] = []
@State private var isLoading = true
@State private var error: String?
@State private var selectedTab: DetailTab = .comments
@State private var selectedDiagnostic: HermesKanbanDiagnostic?
enum DetailTab: String, CaseIterable, Identifiable {
case comments = "Comments"
case events = "Events"
case runs = "Runs"
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 {
NavigationStack {
content
.navigationTitle(detail?.task.title ?? "Task")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button("Done") { dismiss() }
}
}
}
.task(id: taskId) { await load() }
.sheet(item: $selectedDiagnostic) { diag in
DiagnosticDetailSheet(diagnostic: diag)
}
}
@ViewBuilder
private var content: some View {
if isLoading && detail == nil {
ProgressView("Loading…")
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else if let error {
ContentUnavailableView {
Label("Couldn't load task", systemImage: "exclamationmark.triangle")
} description: {
Text(error)
} actions: {
Button("Try Again") {
Task { await load() }
}
}
} else if let detail {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
headerCard(detail.task)
hallucinationBadge(detail.task)
autoBlockedBanner(detail.task)
if let body = detail.task.body, !body.isEmpty {
if let attributed = try? AttributedString(markdown: body) {
Text(attributed)
.font(.body)
} else {
Text(body)
.font(.body)
}
}
if diagnosticsAvailable, !detail.task.diagnostics.isEmpty {
diagnosticsBlock(detail.task.diagnostics, label: "Diagnostics")
}
Picker("Section", selection: $selectedTab) {
ForEach(DetailTab.allCases) { tab in
Text(tab.rawValue).tag(tab)
}
}
.pickerStyle(.segmented)
switch selectedTab {
case .comments: commentsSection(detail.comments)
case .events: eventsSection(detail.events)
case .runs: runsSection
}
}
.padding()
}
}
}
private func headerCard(_ task: HermesKanbanTask) -> some View {
VStack(alignment: .leading, spacing: 8) {
// 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))
if let assignee = task.assignee, !assignee.isEmpty {
ScarfBadge(assignee, kind: .neutral)
}
if let workspace = task.workspaceKind {
ScarfBadge(workspace, kind: .neutral)
}
if let tenant = task.tenant, !tenant.isEmpty {
ScarfBadge(tenant, kind: .brand)
}
if diagnosticsAvailable, let maxRetries = task.maxRetries {
ScarfBadge("retries: \(maxRetries)", kind: .neutral)
.accessibilityLabel("Max retries \(maxRetries)")
}
}
if let priority = task.priority {
Text("Priority \(priority)")
.font(.caption)
.foregroundStyle(.secondary)
}
}
}
/// 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 {
VStack(alignment: .leading, spacing: 8) {
if comments.isEmpty {
Text("No comments yet.")
.font(.callout)
.foregroundStyle(.tertiary)
} else {
ForEach(comments) { comment in
VStack(alignment: .leading, spacing: 2) {
HStack {
Text(comment.author)
.font(.subheadline)
.bold()
Text(comment.createdAt)
.font(.caption2)
.foregroundStyle(.tertiary)
}
Text(comment.body)
.font(.body)
.foregroundStyle(.secondary)
}
.padding(8)
.background(ScarfColor.backgroundSecondary.opacity(0.5))
.clipShape(RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous))
}
}
}
}
private func eventsSection(_ events: [HermesKanbanEvent]) -> some View {
VStack(alignment: .leading, spacing: 6) {
if events.isEmpty {
Text("No events yet.")
.font(.callout)
.foregroundStyle(.tertiary)
} else {
ForEach(events) { event in
HStack(alignment: .top) {
VStack(alignment: .leading, spacing: 2) {
Text(event.kind)
.font(.subheadline)
.bold()
Text(event.createdAt)
.font(.caption2)
.foregroundStyle(.tertiary)
}
Spacer()
}
.padding(.vertical, 4)
}
}
}
}
private var runsSection: some View {
VStack(alignment: .leading, spacing: 8) {
if runs.isEmpty {
Text("No runs yet.")
.font(.callout)
.foregroundStyle(.tertiary)
} else {
ForEach(runs) { run in
VStack(alignment: .leading, spacing: 2) {
HStack {
ScarfBadge(run.outcome ?? run.status, kind: outcomeKind(run.outcome ?? run.status))
if let profile = run.profile {
Text(profile)
.font(.subheadline)
}
Spacer()
Text(run.startedAt)
.font(.caption2)
.foregroundStyle(.tertiary)
}
if let summary = run.summary, !summary.isEmpty {
Text(summary)
.font(.caption)
.foregroundStyle(.secondary)
}
if let err = run.error, !err.isEmpty {
Text(err)
.font(.caption)
.foregroundStyle(.red)
}
if diagnosticsAvailable, !run.diagnostics.isEmpty {
diagnosticsBlock(run.diagnostics, label: "Run diagnostics")
.padding(.top, 4)
}
}
.padding(8)
.background(ScarfColor.backgroundSecondary.opacity(0.4))
.clipShape(RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous))
}
}
}
}
private func badgeKind(for status: String) -> ScarfBadgeKind {
switch KanbanStatus.from(status) {
case .running, .ready: return .info
case .done: return .success
case .blocked: return .warning
default: return .neutral
}
}
private func outcomeKind(_ outcome: String) -> ScarfBadgeKind {
switch outcome.lowercased() {
case "completed", "done": return .success
case "blocked": return .warning
case "crashed", "timed_out", "spawn_failed", "failed": return .danger
case "running": return .info
default: return .neutral
}
}
// MARK: - Loading
private func load() async {
isLoading = true
defer { isLoading = false }
let svc = KanbanService(context: context)
do {
async let detailLoaded = svc.show(taskId: taskId)
async let runsLoaded = svc.runs(taskId: taskId)
self.detail = try await detailLoaded
self.runs = (try? await runsLoaded) ?? []
self.error = nil
} catch let err as KanbanError {
self.error = err.errorDescription
} catch {
self.error = error.localizedDescription
}
}
}
@@ -0,0 +1,236 @@
import SwiftUI
import ScarfCore
import ScarfDesign
/// Read-only Kanban surface for iOS / iPadOS, scoped to one project's
/// tenant. Renders the 5 standard board columns as a horizontally-
/// paged `TabView` of single-column lists HIG-friendly on iPhone
/// where a 5-column grid would force unreadable card widths.
///
/// Mutations + drag-drop are deferred to a later release per
/// CLAUDE.md's iOS catch-up policy. Tap a card to open a read-only
/// detail sheet that surfaces the same comments / events / runs the
/// Mac inspector shows. iPad gets the same view (no drag-drop yet)
/// same UI for both form factors keeps the future mutation path
/// straightforward.
struct ScarfGoKanbanView: View {
let project: ProjectEntry
let context: ServerContext
@State private var tasks: [HermesKanbanTask] = []
@State private var stats: HermesKanbanStats = .empty
@State private var isLoading = true
@State private var error: String?
@State private var selectedColumn: KanbanBoardColumn = .upNext
@State private var inspectorTaskId: String?
@State private var pollTask: Task<Void, Never>?
private var resolvedTenant: String? {
KanbanTenantReader(context: context).tenant(forProjectPath: project.path)
}
var body: some View {
VStack(spacing: 0) {
if !stats.glanceString.isEmpty {
Text(stats.glanceString)
.font(.caption)
.foregroundStyle(.secondary)
.padding(.vertical, 4)
}
columnPicker
.padding(.horizontal)
.padding(.bottom, 4)
Divider()
content
}
.background(ScarfColor.backgroundPrimary)
.task(id: project.id) {
await refresh()
startPolling()
}
.onDisappear { pollTask?.cancel() }
.sheet(item: Binding(
get: { inspectorTaskId.map { TaskIDBox(id: $0) } },
set: { inspectorTaskId = $0?.id }
)) { box in
ScarfGoKanbanDetailSheet(
taskId: box.id,
context: context
)
}
}
private var columnPicker: some View {
Picker("Column", selection: $selectedColumn) {
ForEach(visibleColumns, id: \.self) { column in
Text("\(column.displayName) (\(taskCount(in: column)))").tag(column)
}
}
.pickerStyle(.segmented)
}
@ViewBuilder
private var content: some View {
if let error {
errorView(error)
} else if isLoading && tasks.isEmpty {
ProgressView()
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
taskList
}
}
private var taskList: some View {
let rows = tasks(in: selectedColumn)
return Group {
if rows.isEmpty {
ContentUnavailableView(
emptyTitle(for: selectedColumn),
systemImage: "rectangle.split.3x1",
description: Text(emptyCopy(for: selectedColumn))
)
} else {
List(rows) { task in
Button {
inspectorTaskId = task.id
} label: {
cardRow(task)
}
.buttonStyle(.plain)
}
.listStyle(.plain)
.refreshable {
await refresh()
}
}
}
}
private func cardRow(_ task: HermesKanbanTask) -> some View {
VStack(alignment: .leading, spacing: 4) {
Text(task.title)
.font(.headline)
.foregroundStyle(.primary)
.lineLimit(2)
HStack(spacing: 8) {
if let assignee = task.assignee, !assignee.isEmpty {
Label(assignee, systemImage: "person.fill")
.labelStyle(.titleAndIcon)
.font(.caption)
.foregroundStyle(.secondary)
}
if let workspace = task.workspaceKind {
ScarfBadge(workspace, kind: .neutral)
}
if let priority = task.priority, priority >= 70 {
ScarfBadge("p\(priority)", kind: priority >= 90 ? .danger : .warning)
}
Spacer()
}
if !task.skills.isEmpty {
Text(task.skills.prefix(2).joined(separator: ", ") + (task.skills.count > 2 ? " +\(task.skills.count - 2)" : ""))
.font(.caption2)
.foregroundStyle(.tertiary)
.lineLimit(1)
}
}
.padding(.vertical, 4)
}
private func errorView(_ message: String) -> some View {
ContentUnavailableView {
Label("Couldn't load tasks", systemImage: "exclamationmark.triangle")
} description: {
Text(message)
} actions: {
Button("Try Again") {
Task { await refresh() }
}
}
}
// MARK: - Loading
private func startPolling() {
pollTask?.cancel()
pollTask = Task {
while !Task.isCancelled {
try? await Task.sleep(nanoseconds: 5_000_000_000)
if Task.isCancelled { break }
await refresh()
}
}
}
private func refresh() async {
isLoading = true
defer { isLoading = false }
guard let tenant = resolvedTenant, !tenant.isEmpty else {
tasks = []
error = "No Kanban tenant has been minted for this project yet. Open the Kanban tab on the Mac app to mint one."
return
}
let svc = KanbanService(context: context)
let filter = KanbanListFilter(tenant: tenant)
do {
let polled = try await svc.list(filter)
tasks = polled
stats = (try? await svc.stats()) ?? .empty
error = nil
} catch let err as KanbanError {
error = err.errorDescription
} catch {
self.error = error.localizedDescription
}
}
// MARK: - Column projection
private var visibleColumns: [KanbanBoardColumn] {
var cols: [KanbanBoardColumn] = []
if !tasks(in: .triage).isEmpty { cols.append(.triage) }
cols.append(contentsOf: [.upNext, .running, .blocked, .done])
return cols
}
private func taskCount(in column: KanbanBoardColumn) -> Int {
tasks(in: column).count
}
private func tasks(in column: KanbanBoardColumn) -> [HermesKanbanTask] {
tasks.filter { KanbanStatus.from($0.status).boardColumn == column }
.sorted { lhs, rhs in
let lp = lhs.priority ?? 0
let rp = rhs.priority ?? 0
if lp != rp { return lp > rp }
return (lhs.createdAt ?? "") > (rhs.createdAt ?? "")
}
}
private func emptyTitle(for column: KanbanBoardColumn) -> String {
switch column {
case .triage: return "Triage empty"
case .upNext: return "Queue empty"
case .running: return "No live workers"
case .blocked: return "Nothing blocked"
case .done: return "No completions yet"
case .archived: return "No archived tasks"
}
}
private func emptyCopy(for column: KanbanBoardColumn) -> String {
switch column {
case .triage: return "No tasks waiting on a specifier."
case .upNext: return "Drop a task on the Mac board, or create one with `hermes kanban create`."
case .running: return "No workers are running tasks for this project right now."
case .blocked: return "Nothing is blocked. When a worker hits a block, it'll show up here."
case .done: return "Recent completions will land here."
case .archived: return "Archived tasks are hidden by default."
}
}
}
private struct TaskIDBox: Identifiable {
let id: String
}
@@ -19,6 +19,7 @@ struct ProjectDetailView: View {
let config: IOSServerConfig
@Environment(\.scarfGoCoordinator) private var coordinator
@Environment(\.hermesCapabilities) private var capabilitiesStore
private static let sharedContextID: ServerID = ServerID(
uuidString: "00000000-0000-0000-0000-0000000000A2"
@@ -35,7 +36,7 @@ struct ProjectDetailView: View {
@State private var lastDashboardMtime: Date?
enum DetailTab: Hashable {
case dashboard, site, sessions
case dashboard, site, sessions, kanban
}
private var serverContext: ServerContext {
@@ -55,6 +56,9 @@ struct ProjectDetailView: View {
var tabs: [DetailTab] = [.dashboard]
if siteWidget != nil { tabs.append(.site) }
tabs.append(.sessions)
if capabilitiesStore?.capabilities.hasKanban ?? false {
tabs.append(.kanban)
}
return tabs
}
@@ -111,6 +115,7 @@ struct ProjectDetailView: View {
case .dashboard: return "Dashboard"
case .site: return "Site"
case .sessions: return "Sessions"
case .kanban: return "Kanban"
}
}
@@ -129,6 +134,8 @@ struct ProjectDetailView: View {
}
case .sessions:
ProjectSessionsView_iOS(project: project)
case .kanban:
ScarfGoKanbanView(project: project, context: serverContext)
}
}
+154
View File
@@ -13,6 +13,7 @@ struct SettingsView: View {
@State private var vm: IOSSettingsViewModel
@State private var showRawYAML = false
@State private var editingSpec: SettingSpec?
@State private var showV013FeaturesSheet = false
/// v2.7 Scarf-local opt-in to bulk-fetch tool result CONTENT
/// when resuming past chats. Default off; the shared
/// `RichChatViewModel` reads this same UserDefaults key on
@@ -21,6 +22,16 @@ struct SettingsView: View {
@AppStorage(RichChatViewModel.loadHistoricalToolResultsKey)
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(
uuidString: "00000000-0000-0000-0000-0000000000A1"
)!
@@ -40,6 +51,10 @@ struct SettingsView: View {
}
}
if caps.isV013OrLater {
v013ActiveBadgeSection
}
if !vm.isLoading || vm.config.model != "unknown" {
quickEditsSection
modelSection
@@ -79,6 +94,35 @@ struct SettingsView: View {
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
@@ -284,9 +328,119 @@ struct SettingsView: View {
yesNoRow("Telegram: require mention", vm.config.telegram.requireMention)
LabeledContent("Slack: reply mode", value: vm.config.slack.replyToMode)
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
/// `quickEditsSection` flow because it doesn't touch config.yaml
/// it controls the in-process ScarfMon backend set instead. Off
@@ -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)
}
}
+20 -20
View File
@@ -529,7 +529,7 @@
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = "Scarf iOS/Scarf_iOS.entitlements";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 33;
CURRENT_PROJECT_VERSION = 34;
DEVELOPMENT_TEAM = 3Q6X2L86C4;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
@@ -546,7 +546,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 2.7.1;
MARKETING_VERSION = 2.7.5;
PRODUCT_BUNDLE_IDENTIFIER = com.scarfgo.app;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@@ -571,7 +571,7 @@
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = "Scarf iOS/Scarf_iOS.entitlements";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 33;
CURRENT_PROJECT_VERSION = 34;
DEVELOPMENT_TEAM = 3Q6X2L86C4;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
@@ -588,7 +588,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 2.7.1;
MARKETING_VERSION = 2.7.5;
PRODUCT_BUNDLE_IDENTIFIER = com.scarfgo.app;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@@ -612,7 +612,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 33;
CURRENT_PROJECT_VERSION = 34;
DEVELOPMENT_TEAM = 3Q6X2L86C4;
GENERATE_INFOPLIST_FILE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 26.2;
@@ -635,7 +635,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 33;
CURRENT_PROJECT_VERSION = 34;
DEVELOPMENT_TEAM = 3Q6X2L86C4;
GENERATE_INFOPLIST_FILE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 26.2;
@@ -658,7 +658,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 33;
CURRENT_PROJECT_VERSION = 34;
DEVELOPMENT_TEAM = 3Q6X2L86C4;
GENERATE_INFOPLIST_FILE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 26.2;
@@ -680,7 +680,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 33;
CURRENT_PROJECT_VERSION = 34;
DEVELOPMENT_TEAM = 3Q6X2L86C4;
GENERATE_INFOPLIST_FILE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 26.2;
@@ -834,7 +834,7 @@
CODE_SIGN_ENTITLEMENTS = scarf/scarf.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 33;
CURRENT_PROJECT_VERSION = 34;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3Q6X2L86C4;
ENABLE_APP_SANDBOX = NO;
@@ -848,7 +848,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 14.6;
MARKETING_VERSION = 2.7.1;
MARKETING_VERSION = 2.7.5;
PRODUCT_BUNDLE_IDENTIFIER = com.scarf.app;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
@@ -870,7 +870,7 @@
CODE_SIGN_ENTITLEMENTS = scarf/scarf.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 33;
CURRENT_PROJECT_VERSION = 34;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3Q6X2L86C4;
ENABLE_APP_SANDBOX = NO;
@@ -884,7 +884,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 14.6;
MARKETING_VERSION = 2.7.1;
MARKETING_VERSION = 2.7.5;
PRODUCT_BUNDLE_IDENTIFIER = com.scarf.app;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
@@ -902,12 +902,12 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 33;
CURRENT_PROJECT_VERSION = 34;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3Q6X2L86C4;
GENERATE_INFOPLIST_FILE = YES;
MACOSX_DEPLOYMENT_TARGET = 26.2;
MARKETING_VERSION = 2.7.1;
MARKETING_VERSION = 2.7.5;
PRODUCT_BUNDLE_IDENTIFIER = com.scarfTests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
@@ -924,12 +924,12 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 33;
CURRENT_PROJECT_VERSION = 34;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3Q6X2L86C4;
GENERATE_INFOPLIST_FILE = YES;
MACOSX_DEPLOYMENT_TARGET = 26.2;
MARKETING_VERSION = 2.7.1;
MARKETING_VERSION = 2.7.5;
PRODUCT_BUNDLE_IDENTIFIER = com.scarfTests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
@@ -945,11 +945,11 @@
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 33;
CURRENT_PROJECT_VERSION = 34;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3Q6X2L86C4;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 2.7.1;
MARKETING_VERSION = 2.7.5;
PRODUCT_BUNDLE_IDENTIFIER = com.scarfUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
@@ -965,11 +965,11 @@
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 33;
CURRENT_PROJECT_VERSION = 34;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3Q6X2L86C4;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 2.7.1;
MARKETING_VERSION = 2.7.5;
PRODUCT_BUNDLE_IDENTIFIER = com.scarfUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = NO;
@@ -31,6 +31,16 @@ struct ProjectTemplateManifest: Codable, Sendable, Equatable {
/// optional-field decoding keeps them working unchanged.
let config: TemplateConfigSchema?
/// Per-project Kanban tenant slug (manifest schemaVersion 3+, v2.7.5).
/// Minted by `KanbanTenantResolver` on first kanban interaction
/// inside this project. Templates never set this it's
/// user-machine-scoped state but Codable's optional decoding
/// means template manifests stay valid alongside user-minted ones.
/// Once minted, immutable across renames so existing tasks stay
/// attributable to the project. Read by `ProjectAgentContextService`
/// to surface the tenant to the agent in the AGENTS.md block.
var kanbanTenant: String? = nil
/// Filesystem-safe slug derived from `id` (`"owner/name"` `"owner-name"`).
/// Used for the install directory name, skills namespace, and cron-job tag.
nonisolated var slug: String {
@@ -84,7 +84,11 @@ struct HermesFileService: Sendable {
inlineDiffs: bool("display.inline_diffs", default: true),
toolProgressCommand: bool("display.tool_progress_command", default: false),
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(
@@ -131,7 +135,12 @@ struct HermesFileService: Sendable {
sttLocalModel: str("stt.local.model", default: "base"),
sttLocalLanguage: str("stt.local.language"),
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 {
@@ -254,6 +263,47 @@ struct HermesFileService: Sendable {
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(
model: str("model.default", default: "unknown"),
provider: str("model.provider", default: "unknown"),
@@ -313,7 +363,8 @@ struct HermesFileService: Sendable {
homeAssistant: homeAssistant,
cacheTTL: str("prompt_caching.cache_ttl", default: "5m"),
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,
resourcesEnabled: server.resourcesEnabled,
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")
}
/// 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
nonisolated func setMCPServerArgs(name: String, args: [String]) -> Bool {
patchMCPServerField(name: name) { entryLines in
@@ -812,11 +895,23 @@ struct HermesFileService: Sendable {
func flush() {
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 enabled = enabledStr != "false"
let timeout = fields["timeout"].flatMap(Int.init)
let connectTimeout = fields["connect_timeout"].flatMap(Int.init)
let sseReadTimeout = fields["sse_read_timeout"].flatMap(Int.init)
let server = HermesMCPServer(
name: name,
transport: transport,
@@ -833,7 +928,8 @@ struct HermesFileService: Sendable {
toolsExclude: excludeList,
resourcesEnabled: resources,
promptsEnabled: prompts,
hasOAuthToken: false
hasOAuthToken: false,
sseReadTimeout: sseReadTimeout
)
servers.append(server)
@@ -0,0 +1,184 @@
import Foundation
import os
import ScarfCore
/// Resolves and mints per-project Kanban tenant slugs.
///
/// Hermes Kanban has no `project_id` column the closest namespace
/// primitive is the optional `tenant TEXT` column on `tasks`. Scarf
/// uses it as a surrogate project key: each Scarf project gets a
/// stable `scarf:<slug>` tenant minted on first kanban interaction
/// and persisted to `<project>/.scarf/manifest.json`.
///
/// **Invariants:**
/// - Once minted, the tenant is immutable across renames. Tasks
/// already on the board carry the original slug; renaming the
/// project would orphan them.
/// - The `scarf:` prefix prevents collisions with hand-typed
/// tenants from CLI users.
/// - Bare projects (no manifest) get a minimal `manifest.json`
/// with only `kanbanTenant` set on first mint.
struct KanbanTenantResolver: Sendable {
private static let logger = Logger(subsystem: "com.scarf", category: "KanbanTenantResolver")
/// Prefix that distinguishes Scarf-minted tenants from hand-typed
/// ones. Public for callers that group "scarf-managed" projects in
/// the global tenant filter.
static let prefix = "scarf:"
let context: ServerContext
nonisolated init(context: ServerContext = .local) {
self.context = context
}
// MARK: - Public
/// Returns the existing tenant for a project, or `nil` if none has
/// been minted yet. Read-only never writes.
nonisolated func tenant(for project: ProjectEntry) -> String? {
readManifest(for: project)?.kanbanTenant
}
/// Returns the existing tenant or mints a new one if absent. Writes
/// the new tenant back to the project's manifest.json. Idempotent
/// calling twice on a fresh project returns the same value.
nonisolated func resolveOrMint(for project: ProjectEntry) throws -> String {
if let existing = tenant(for: project), !existing.isEmpty {
return existing
}
let candidate = Self.makeSlug(for: project.name)
let unique = uniquify(candidate, against: project)
try persist(tenant: unique, for: project)
Self.logger.info("minted kanban tenant '\(unique, privacy: .public)' for project '\(project.name, privacy: .public)'")
return unique
}
// MARK: - Slug generation (pure)
/// Build a `scarf:<slug>` tenant from a project name. Lowercased,
/// hyphenated, 48 chars after the prefix. Public for tests.
nonisolated static func makeSlug(for name: String) -> String {
let lower = name.lowercased()
let mapped = lower.unicodeScalars.map { scalar -> Character in
let c = Character(scalar)
if c.isLetter || c.isNumber { return c }
return "-"
}
let collapsed = String(mapped)
.split(separator: "-", omittingEmptySubsequences: true)
.joined(separator: "-")
let trimmed = collapsed.isEmpty ? "project" : collapsed
let bounded = String(trimmed.prefix(48))
return prefix + bounded
}
// MARK: - Private
/// Disambiguate against tenants already used by other projects on
/// this host. Reads every project's manifest; `O(projects)` fine
/// for typical project counts (handful to dozens). Suffixes `-2`,
/// `-3`, until unique.
nonisolated private func uniquify(_ candidate: String, against project: ProjectEntry) -> String {
let used = Set(allMintedTenants(excluding: project))
if !used.contains(candidate) { return candidate }
var n = 2
while n < 1000 {
let next = candidate + "-\(n)"
if !used.contains(next) { return next }
n += 1
}
// Defensive should never hit. Fall back to a UUID suffix.
return candidate + "-" + UUID().uuidString.prefix(6).lowercased()
}
/// Collect every Scarf-minted tenant currently on disk, excluding
/// the given project. Used to dedup new mints.
nonisolated private func allMintedTenants(excluding project: ProjectEntry) -> [String] {
let registryPath = context.paths.home + "/scarf/projects.json"
guard let data = context.readData(registryPath),
let registry = try? JSONDecoder().decode(ProjectRegistry.self, from: data)
else {
return []
}
return registry.projects.compactMap { other in
guard other.id != project.id else { return nil }
return readManifest(for: other)?.kanbanTenant
}
}
nonisolated private func readManifest(for project: ProjectEntry) -> ProjectTemplateManifest? {
let path = manifestPath(for: project)
let transport = context.makeTransport()
guard transport.fileExists(path),
let data = try? transport.readFile(path)
else {
return nil
}
return try? JSONDecoder().decode(ProjectTemplateManifest.self, from: data)
}
/// Write the tenant back to `<project>/.scarf/manifest.json`. If
/// the file doesn't exist yet (bare project), create a minimal
/// manifest with just the kanbanTenant set. The remaining
/// manifest fields use sentinel values that the
/// `ProjectAgentContextService` reader tolerates: id stays at the
/// project's slug-form, version stays "0.0.0", and contents claims
/// nothing none of which the reader requires for the Kanban
/// tenant line.
nonisolated private func persist(tenant: String, for project: ProjectEntry) throws {
let path = manifestPath(for: project)
let transport = context.makeTransport()
// Ensure .scarf/ exists.
let scarfDir = project.scarfDir
if !transport.fileExists(scarfDir) {
try transport.createDirectory(scarfDir)
}
let updated: ProjectTemplateManifest
if let existing = readManifest(for: project) {
// Mutate the existing manifest in place. var fields permit
// this; let fields are preserved.
var copy = existing
copy.kanbanTenant = tenant
updated = copy
} else {
updated = ProjectTemplateManifest(
schemaVersion: 3,
id: "scarf/\(project.id)",
name: project.name,
version: "0.0.0",
minScarfVersion: nil,
minHermesVersion: nil,
author: nil,
description: "",
category: nil,
tags: nil,
icon: nil,
screenshots: nil,
contents: TemplateContents(
dashboard: false,
agentsMd: false,
instructions: nil,
skills: nil,
cron: nil,
memory: nil,
config: nil,
slashCommands: nil
),
config: nil,
kanbanTenant: tenant
)
}
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data = try encoder.encode(updated)
try transport.writeFile(path, data: data)
}
nonisolated private func manifestPath(for project: ProjectEntry) -> String {
project.scarfDir + "/manifest.json"
}
}
@@ -130,6 +130,7 @@ struct ProjectAgentContextService: Sendable {
let configFieldsLine = renderConfigFieldsLine(for: project)
let cronLines = renderCronLines(for: project, templateId: templateInfo?.id)
let slashCommandNames = readSlashCommandNames(for: project)
let kanbanTenant = readKanbanTenant(for: project)
let lockFilePresent = context.makeTransport().fileExists(
project.path + "/.scarf/template.lock.json"
)
@@ -164,6 +165,10 @@ struct ProjectAgentContextService: Sendable {
lines.append("- **Project slash commands:** \(formatted). The user invokes these via the chat slash menu; you'll see the expanded prompt as a normal user message preceded by `<!-- scarf-slash:<name> -->`.")
}
if let tenant = kanbanTenant, !tenant.isEmpty {
lines.append("- **Kanban tenant:** `\(tenant)` — when creating Hermes Kanban tasks for this project, always pass `--tenant \(tenant)` to `hermes kanban create` so the tasks land on this project's board instead of the global \"Untagged\" pile.")
}
if lockFilePresent {
lines.append("- **Uninstall manifest:** `\(project.path)/.scarf/template.lock.json` (tracks files written by template install)")
}
@@ -202,9 +207,31 @@ struct ProjectAgentContextService: Sendable {
guard transport.fileExists(manifestPath) else { return nil }
guard let data = try? transport.readFile(manifestPath) else { return nil }
guard let manifest = try? JSONDecoder().decode(ProjectTemplateManifest.self, from: data) else { return nil }
// Bare-project manifests minted by KanbanTenantResolver carry
// a sentinel id of "scarf/<project-id>" and version "0.0.0".
// Don't surface those as a template the template line is
// for actual installed templates only.
if manifest.id.hasPrefix("scarf/") && manifest.version == "0.0.0" {
return nil
}
return (id: manifest.id, version: manifest.version)
}
/// Read `<project>/.scarf/manifest.json` for the Scarf-minted Kanban
/// tenant. Nil when no tenant has been minted yet (no kanban
/// interaction has happened for this project).
nonisolated private func readKanbanTenant(for project: ProjectEntry) -> String? {
let manifestPath = project.path + "/.scarf/manifest.json"
let transport = context.makeTransport()
guard transport.fileExists(manifestPath),
let data = try? transport.readFile(manifestPath),
let manifest = try? JSONDecoder().decode(ProjectTemplateManifest.self, from: data)
else {
return nil
}
return manifest.kanbanTenant
}
/// Build the "Configuration fields" bullet's tail. Returns a
/// comma-joined list of backticked field names with inline type
/// hints (`(secret)`), or the literal string "(none)" when the
@@ -77,6 +77,27 @@ final class ChatViewModel {
let richChatViewModel: RichChatViewModel
private var coordinator: Coordinator?
/// Capability store the chat surface reads from. Set by `ChatView`
/// at body-evaluation time via `attachCapabilitiesStore(_:)`
/// `@ObservationIgnored` so capability refreshes don't force a
/// full chat re-render. Forwards into
/// `RichChatViewModel.capabilitiesGate` whenever the published
/// snapshot changes; the slash menu reads through that. v2.8 /
/// Hermes v0.13 gates `/goal` + `/queue` slash menu rows.
@ObservationIgnored
var capabilitiesStore: HermesCapabilitiesStore?
/// Wire the Mac chat view's environment-injected capabilities store
/// into both this VM and its child rich-chat VM. Idempotent on the
/// pointer (re-attaching the same store is a no-op); always
/// re-publishes the latest snapshot so a refresh that fired before
/// the chat view became visible still lands.
@MainActor
func attachCapabilitiesStore(_ store: HermesCapabilitiesStore?) {
capabilitiesStore = store
richChatViewModel.publishCapabilities(store?.capabilities ?? .empty)
}
/// `callId` of the tool call currently surfaced in the chat
/// inspector pane, or nil when nothing is focused. Set by
/// `ToolCallCard` taps in the transcript; cleared by the inspector's
@@ -321,6 +342,47 @@ final class ChatViewModel {
richChatViewModel.clearACPErrorState()
}
/// Auto-clear the chat composer's transient hint after 4 s. Shared
/// helper for `/steer`, `/goal`, and `/queue` so the toast lifetime
/// stays consistent across non-interruptive commands.
@MainActor
private func scheduleHintClear() {
let snapshot = richChatViewModel.transientHint
Task { @MainActor [weak self] in
try? await Task.sleep(nanoseconds: 4_000_000_000)
if self?.richChatViewModel.transientHint == snapshot {
self?.richChatViewModel.transientHint = nil
}
}
}
/// Pull the slash command name + raw argument tail out of the
/// composer text. Returns `(name: nil, args: "")` for non-slash
/// input. Mirrors the parser shape `RichChatViewModel.parseGoalArgument`
/// expects; kept on `ChatViewModel` (not promoted to ScarfCore)
/// because the Mac and iOS chat surfaces compose this with their
/// own per-platform send paths.
static func parseSlashName(_ text: String) -> (name: String?, args: String) {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard trimmed.hasPrefix("/") else { return (nil, "") }
let withoutSlash = trimmed.dropFirst()
if let space = withoutSlash.firstIndex(of: " ") {
return (
name: String(withoutSlash[..<space]),
args: String(withoutSlash[withoutSlash.index(after: space)...])
)
}
return (name: String(withoutSlash), args: "")
}
/// Cap goal text in transient toasts so a 1 KB user-typed goal
/// doesn't blow out the hint pill. The header pill applies its
/// own 33-char cap; the toast is shorter so the hint stays
/// glanceable.
static func truncatedToastGoal(_ text: String) -> String {
text.count <= 60 ? text : String(text.prefix(57)) + ""
}
@MainActor
private func recordACPFailure(_ error: Error, client: ACPClient?, context: String) async {
logger.error("\(context): \(error.localizedDescription)")
@@ -575,22 +637,59 @@ final class ChatViewModel {
// and Hermes-version-independent. v2.5.
let wireText = expandIfProjectScoped(text)
// /steer is non-interruptive the agent is still on its
// current turn; the guidance applies after the next tool
// call. Don't change the "Agent working..." status (it's
// already on); show a transient toast so the user knows the
// guidance was accepted. v2.5 / Hermes v2026.4.23+.
let isSteer = richChatViewModel.isNonInterruptiveSlash(text)
if isSteer {
richChatViewModel.transientHint = "Guidance queued — applies after the next tool call."
Task { @MainActor [weak self] in
try? await Task.sleep(nanoseconds: 4_000_000_000)
if self?.richChatViewModel.transientHint == "Guidance queued — applies after the next tool call." {
self?.richChatViewModel.transientHint = nil
}
// Non-interruptive slash commands keep the "Agent working"
// indicator off and surface a transient toast confirming the
// command was accepted. v2.5 added `/steer`; v2.8 / Hermes
// v0.13 adds `/goal` (lock the agent on a target across turns)
// and `/queue` (queue a prompt for after the current turn).
// Each gets its own optimistic side-effect on RichChatViewModel
// so the chat header pill / queue chip update synchronously
// without waiting for a server round-trip.
let isNonInterruptive = richChatViewModel.isNonInterruptiveSlash(text)
let parsed = Self.parseSlashName(text)
switch parsed.name {
case "goal":
// TODO(WS-2-Q7): once a v0.13 host confirms the
// wire-shape, this branch fires only when the host
// advertises `hasGoals`; pre-v0.13 hosts hide the menu
// row, but a power-user typing `/goal` directly still
// lands here. We keep the optimistic write so the pill
// appears synchronously the agent's "unknown command"
// reply on a pre-v0.13 host paints the inconsistency in
// user-visible chat content (acceptable v1 behavior;
// see WS-2 plan "Inconsistency caveat").
let arg = RichChatViewModel.parseGoalArgument(parsed.args)
switch arg {
case .set(let goalText):
richChatViewModel.recordActiveGoal(text: goalText)
richChatViewModel.transientHint = "Goal locked: \(Self.truncatedToastGoal(goalText))"
case .clear:
richChatViewModel.recordActiveGoal(text: nil)
richChatViewModel.transientHint = "Goal cleared."
case .empty:
richChatViewModel.transientHint = "Sent /goal — see the agent reply for current goal."
}
} else {
acpStatus = ACPPhase.agentWorking
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."
scheduleHintClear()
default:
// Regular interruptive prompt (or an unrecognized slash).
// Don't flip "Agent working" for any other
// non-interruptive command (defensive; matches the
// legacy contract).
if !isNonInterruptive { acpStatus = ACPPhase.agentWorking }
}
acpPromptTask = Task { @MainActor in
do {
@@ -608,7 +707,7 @@ final class ChatViewModel {
// notifier handles the foreground/disabled gating;
// we just hand it the latest assistant text and
// session title for the body line.
if !isSteer {
if !isNonInterruptive {
let preview = richChatViewModel.messages
.last(where: { $0.isAssistant })?
.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
var onSend: (String, [ChatImageAttachment]) -> Void
var isEnabled: Bool
@Environment(\.hermesCapabilities) private var capabilitiesStore
var body: some View {
VStack(spacing: 0) {
@@ -20,8 +21,13 @@ struct ChatTranscriptPane: View {
acpInputTokens: richChat.acpInputTokens,
acpOutputTokens: richChat.acpOutputTokens,
acpThoughtTokens: richChat.acpThoughtTokens,
acpCompressionCount: richChat.acpCompressionCount,
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()
@@ -58,7 +64,8 @@ struct ChatTranscriptPane: View {
onSend: onSend,
isEnabled: isEnabled,
commands: richChat.availableCommands,
showCompressButton: richChat.supportsCompress && !richChat.hasBroaderCommandMenu
showCompressButton: richChat.supportsCompress && !richChat.hasBroaderCommandMenu,
isAgentWorking: richChat.isAgentWorking
)
.id(richChat.sessionId ?? "scarf.chat.no-session")
}
@@ -5,6 +5,12 @@ struct ChatView: View {
@Environment(ChatViewModel.self) private var viewModel
@Environment(HermesFileWatcher.self) private var fileWatcher
@Environment(AppCoordinator.self) private var coordinator
/// Capabilities store for the active server (injected on
/// `ContextBoundRoot`). Forwarded into `ChatViewModel` so the
/// rich-chat slash menu can gate v0.13 surfaces (`/goal`, `/queue`,
/// `/steer` on idle). Nil during harness scenarios; treated the
/// same as `.empty` capabilities.
@Environment(\.hermesCapabilities) private var capabilitiesStore
@State private var showErrorDetails = false
/// Side-pane visibility toggles (issue #58). Drive the new
@@ -45,6 +51,15 @@ struct ChatView: View {
.navigationTitle(
viewModel.currentProjectName.map { "Chat · \($0)" } ?? "Chat"
)
// Forward the env-injected capabilities store into the chat VM
// on every refresh tick so the rich-chat slash menu picks up
// v0.13 surfaces the moment the host advertises them. The id
// value is the capabilities-line string a stable identity
// that flips exactly when the detector fires. Nil store
// `.empty` capabilities, which is what the VM defaults to.
.task(id: capabilitiesStore?.capabilities.versionLine ?? "") {
viewModel.attachCapabilitiesStore(capabilitiesStore)
}
.task {
await viewModel.loadRecentSessions()
viewModel.refreshCredentialPreflight()
@@ -16,6 +16,11 @@ struct RichChatInputBar: View {
let isEnabled: Bool
var commands: [HermesSlashCommand] = []
var showCompressButton: Bool = false
/// Whether the agent is currently mid-turn. Used to grey-out
/// `/steer` in the slash menu on idle pre-v0.13 hosts (where the
/// command silently no-ops). v0.13+ hosts allow `/steer` on idle
/// and the row stays interactive regardless of `isAgentWorking`.
var isAgentWorking: Bool = false
@Environment(\.hermesCapabilities) private var capabilitiesStore
@@ -52,6 +57,8 @@ struct RichChatInputBar: View {
SlashCommandMenu(
commands: filteredCommands,
agentHasCommands: !commands.isEmpty,
disabledCommandNames: disabledMenuCommandNames,
disabledReason: disabledMenuReason,
selectedIndex: $selectedIndex,
onSelect: insertCommand
)
@@ -392,6 +399,27 @@ struct RichChatInputBar: View {
SlashCommandMenu.filter(commands: commands, query: menuQuery)
}
/// Names of menu rows that should render greyed-out + ignore taps.
/// v2.8 / Hermes v0.13: `/steer` is greyed only when the connected
/// host is pre-v0.13 AND the session is idle. Pre-v0.13 hosts
/// silently no-op `/steer` outside an active turn surfacing the
/// row as "use during a turn" is friendlier than letting the user
/// click and see nothing happen. v0.13+ hosts allow steer-on-idle
/// (the command just sends as a regular prompt) so the row stays
/// interactive there.
private var disabledMenuCommandNames: Set<String> {
let hasSteerOnIdle = capabilitiesStore?.capabilities.hasACPSteerOnIdle ?? false
if !isAgentWorking && !hasSteerOnIdle {
return ["steer"]
}
return []
}
private var disabledMenuReason: String? {
guard !disabledMenuCommandNames.isEmpty else { return nil }
return "Use `/steer` while the agent is working — your Hermes version doesn't support steering on idle sessions."
}
private func updateMenuState() {
let shouldShow = shouldShowMenu
@@ -9,6 +9,11 @@ struct SessionInfoBar: View {
var acpInputTokens: Int = 0
var acpOutputTokens: 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
/// applicable. Nil for plain global chats. Drives the folder-chip
/// 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
/// git repos.
var gitBranch: String? = nil
/// Active locked goal (Hermes v0.13 `/goal`). Nil hides the pill.
/// Optimistic set by `RichChatViewModel.recordActiveGoal(text:)`
/// when the user sends `/goal `.
var activeGoal: HermesActiveGoal? = nil
/// Invoked when the user picks "Clear goal" from the goal pill's
/// context menu. Caller dispatches `/goal --clear` so the optimistic
/// pill clear and the server-side authoritative state stay in sync.
var onClearGoal: (() -> Void)? = nil
/// Local mirror of prompts queued via `/queue ` (Hermes v0.13).
/// Empty list hides the chip.
var queuedPrompts: [HermesQueuedPrompt] = []
/// 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
/// 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) {
Circle()
.fill(isWorking ? ScarfColor.success : ScarfColor.foregroundFaint)
@@ -96,6 +152,21 @@ struct SessionInfoBar: View {
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 {
let formattedCost = cost.formatted(.currency(code: "USD").precision(.fractionLength(4)))
Label(session.costIsActual ? formattedCost : "\(formattedCost) est.", systemImage: "dollarsign.circle")
@@ -134,4 +205,11 @@ struct SessionInfoBar: View {
private func formatTokens(_ count: Int) -> String {
count.formatted(.number.notation(.compactName).precision(.fractionLength(0...1)))
}
/// Cap goal text in the chip to keep the SessionInfoBar from
/// wrapping when the user locks a long goal. Full goal text is
/// available in the tooltip via `.help(...)`.
static func truncatedGoal(_ text: String) -> String {
text.count <= 36 ? text : String(text.prefix(33)) + ""
}
}
@@ -11,6 +11,13 @@ struct SlashCommandMenu: View {
/// Whether the agent advertised any commands at all. Lets us distinguish
/// "agent hasn't sent commands yet" from "filter matched nothing".
let agentHasCommands: Bool
/// Names that render greyed-out + ignore taps. v2.8 uses this only
/// for `/steer` on pre-v0.13 idle sessions; v0.13 hosts allow steer
/// on idle and the set is empty.
var disabledCommandNames: Set<String> = []
/// Tooltip shown on disabled rows. Reused per-row in v2.8 only
/// one disabled case ships, so a single shared string is enough.
var disabledReason: String? = nil
@Binding var selectedIndex: Int
var onSelect: (HermesSlashCommand) -> Void
@@ -50,13 +57,17 @@ struct SlashCommandMenu: View {
ScrollView {
LazyVStack(spacing: 0) {
ForEach(Array(commands.enumerated()), id: \.element.id) { index, command in
let isDisabled = disabledCommandNames.contains(command.name)
SlashCommandRow(
command: command,
isSelected: index == selectedIndex
isSelected: index == selectedIndex,
isDisabled: isDisabled,
disabledReason: isDisabled ? disabledReason : nil
)
.id(index)
.contentShape(Rectangle())
.onTapGesture {
guard !isDisabled else { return }
selectedIndex = index
onSelect(command)
}
@@ -77,6 +88,8 @@ struct SlashCommandMenu: View {
private struct SlashCommandRow: View {
let command: HermesSlashCommand
let isSelected: Bool
var isDisabled: Bool = false
var disabledReason: String? = nil
var body: some View {
HStack(alignment: .firstTextBaseline, spacing: 8) {
@@ -87,7 +100,16 @@ private struct SlashCommandRow: View {
.fontWeight(.semibold)
.foregroundStyle(isSelected ? ScarfColor.accentActive : ScarfColor.foregroundPrimary)
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)
.foregroundStyle(ScarfColor.foregroundFaint)
}
@@ -107,11 +129,19 @@ private struct SlashCommandRow: View {
.foregroundStyle(ScarfColor.foregroundMuted)
.lineLimit(2)
}
if isDisabled, let reason = disabledReason {
Text(reason)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundFaint)
.lineLimit(2)
}
}
Spacer(minLength: 0)
}
.padding(.horizontal, ScarfSpace.s3)
.padding(.vertical, ScarfSpace.s2)
.background(isSelected ? ScarfColor.accentTint : Color.clear)
.opacity(isDisabled ? 0.55 : 1.0)
.help(isDisabled ? (disabledReason ?? "") : "")
}
}
@@ -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"]
if !name.isEmpty { args += ["--name", name] }
if !deliver.isEmpty { args += ["--deliver", deliver] }
@@ -158,12 +158,25 @@ final class CronViewModel {
// know the flag argparse rejects unknown args, so the form
// omits the flag when the field is empty.
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)
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")
}
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]
if let schedule, !schedule.isEmpty { args += ["--schedule", schedule] }
if let prompt, !prompt.isEmpty { args += ["--prompt", prompt] }
@@ -180,6 +193,16 @@ final class CronViewModel {
// = user cleared an existing workdir; Hermes documents `--workdir ""`
// on edit as the explicit clear gesture, mirroring the `--script` shape.
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")
}
+37 -4
View File
@@ -25,6 +25,10 @@ struct CronView: View {
capabilitiesStore?.capabilities.hasCronWorkdir ?? false
}
private var hasCronNoAgent: Bool {
capabilitiesStore?.capabilities.hasCronNoAgent ?? false
}
var body: some View {
VStack(spacing: 0) {
pageHeader
@@ -47,7 +51,7 @@ struct CronView: View {
// polling timer. Same wiring ActivityView uses.
.onChange(of: fileWatcher.lastChangeDate) { viewModel.load() }
.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(
schedule: form.schedule,
prompt: form.prompt,
@@ -56,7 +60,12 @@ struct CronView: View {
skills: form.skills,
script: form.script,
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
} onCancel: {
@@ -64,7 +73,7 @@ struct CronView: View {
}
}
.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(
id: job.id,
schedule: form.schedule,
@@ -75,7 +84,8 @@ struct CronView: View {
newSkills: form.skills,
clearSkills: form.clearSkills,
script: form.script,
workdir: hasCronWorkdir ? form.workdir : nil
workdir: hasCronWorkdir ? form.workdir : nil,
noAgent: hasCronNoAgent ? form.noAgent : nil
)
viewModel.editingJob = nil
} onCancel: {
@@ -643,6 +653,9 @@ struct CronJobEditor: View {
/// v0.12+ workdir flag fills `--workdir <path>`. Empty string
/// preserves the v0.11 behaviour of running with no cwd hint.
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
@@ -650,6 +663,10 @@ struct CronJobEditor: View {
/// 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`.
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 onCancel: () -> Void
@@ -681,12 +698,25 @@ struct CronJobEditor: View {
)
.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("Repeat", text: $form.repeatCount, placeholder: "Optional count")
formField("Script path", text: $form.script, placeholder: "Python script whose stdout is injected", mono: true)
if supportsWorkdir {
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 {
VStack(alignment: .leading, spacing: 4) {
Text("Skills")
@@ -723,6 +753,8 @@ struct CronJobEditor: View {
.tint(ScarfColor.accent)
}
}
.opacity(form.noAgent ? 0.4 : 1.0)
.disabled(form.noAgent)
}
HStack {
Spacer()
@@ -746,6 +778,7 @@ struct CronJobEditor: View {
form.skills = job.skills ?? []
form.script = job.preRunScript ?? ""
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 ScarfDesign
/// Modal that lists archived skills (state active) and exposes a
/// one-click "Restore" action per row. v0.12 archives are recoverable
/// `hermes curator restore <name>` brings the skill back into
/// `~/.hermes/skills/<category>/<name>/` and re-marks it active.
/// Legacy v0.12 fallback for restoring an archived skill by typed
/// name. Hermes v0.12 didn't ship `curator list-archived`, so the only
/// way to restore was to remember the skill name and pass it through
/// `hermes curator restore <name>`.
///
/// The Curator's `status` text doesn't enumerate archived skills with
/// names; we surface what's available (counts + pinned list) and rely
/// on the user knowing the names. Hermes ergo does an interactive
/// `--name` arg if missing but Scarf prefers explicit selection so
/// users don't have to remember names. For v2.6 we render a free-form
/// text field; once Hermes ships a `curator list-archived` (tracked
/// upstream), swap to a pickable list.
/// **v0.13+ flow (preferred):** `CuratorArchivedSection` renders a
/// per-skill list with a one-click Restore button per row no typing
/// required. This sheet stays reachable from the overflow menu only on
/// pre-v0.13 hosts (gated by `!hasCuratorArchive`). Don't delete this
/// file even after WS-4 ships; v0.12 hosts still depend on it.
struct CuratorRestoreSheet: View {
let viewModel: CuratorViewModel
@@ -2,57 +2,52 @@ import SwiftUI
import ScarfCore
import ScarfDesign
/// Mac UI for Hermes v0.12's autonomous skill curator.
/// Mac UI for Hermes's autonomous skill curator (v0.12 base + v0.13
/// archive/prune surface).
///
/// Surfaces the running state (enabled / paused / disabled), last-run
/// metadata, agent-created skill counts, and the most/least-active /
/// least-recently-active leaderboards. Pin-and-restore actions hit
/// `hermes curator pin/unpin/restore` via CuratorViewModel.
/// metadata, agent-created skill counts, the most/least-active /
/// least-recently-active leaderboards, and on v0.13+ hosts the new
/// archived-skills section + per-row Archive button on each leaderboard
/// entry. Pin / unpin / restore / archive / prune route through
/// CuratorViewModel CuratorService.
///
/// Capability-gated upstream: AppCoordinator only wires the sidebar
/// item when `HermesCapabilities.hasCurator` is true. This view assumes
/// it's reachable on a v0.12+ host.
/// item when `HermesCapabilities.hasCurator` is true. Archive surfaces
/// gate independently on `hasCuratorArchive`; pre-v0.13 hosts see the
/// v2.7.x layout unchanged (legacy `CuratorRestoreSheet` reachable from
/// the overflow menu, no Archive section, fire-and-forget Run Now).
struct CuratorView: View {
@State private var viewModel: CuratorViewModel
@State private var showRestoreSheet = false
@Environment(\.hermesCapabilities) private var capabilitiesStore
init(context: ServerContext) {
_viewModel = State(initialValue: CuratorViewModel(context: context))
}
/// Single source of truth for "v0.13 archive surface visible". Read
/// once in `body` and threaded into sub-views. Defensive default to
/// `false` so previews / smoke tests behave like a pre-v0.13 host.
private var archiveAvailable: Bool {
capabilitiesStore?.capabilities.hasCuratorArchive ?? false
}
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: ScarfSpace.s4) {
ScarfPageHeader(
"Curator",
subtitle: "Autonomous skill maintenance — Hermes v0.12+"
subtitle: archiveAvailable
? "Autonomous skill maintenance — archive, prune, restore"
: "Autonomous skill maintenance — Hermes v0.12+"
) {
HStack(spacing: ScarfSpace.s2) {
if viewModel.isLoading {
ProgressView().controlSize(.small)
}
Button("Run Now") {
Task { await viewModel.runNow() }
}
.buttonStyle(ScarfPrimaryButton())
.disabled(viewModel.isLoading)
Menu {
switch viewModel.status.state {
case .paused:
Button("Resume") { Task { await viewModel.resume() } }
case .enabled:
Button("Pause") { Task { await viewModel.pause() } }
default:
EmptyView()
}
Button("Restore Archived…") {
showRestoreSheet = true
}
.disabled(viewModel.status.archivedSkills == 0)
} label: {
Image(systemName: "ellipsis.circle")
}
}
headerActions
}
if let errorMessage = viewModel.errorMessage {
errorBanner(errorMessage)
}
if let toast = viewModel.transientMessage {
@@ -64,6 +59,19 @@ struct CuratorView: View {
pinnedSection
activityTables
if archiveAvailable {
CuratorArchivedSection(
archived: viewModel.archivedSkills,
isLoading: viewModel.isLoadingArchive,
onRestore: { name in
Task { await viewModel.restore(name) }
},
onPruneAll: {
Task { await viewModel.planPrune() }
}
)
}
if let report = viewModel.lastReportMarkdown {
lastReportSection(markdown: report)
}
@@ -71,10 +79,84 @@ struct CuratorView: View {
.padding(ScarfSpace.s4)
}
.background(ScarfColor.backgroundPrimary)
.task { await viewModel.load() }
.task {
await viewModel.load()
if archiveAvailable {
await viewModel.loadArchive()
}
}
.sheet(isPresented: $showRestoreSheet) {
CuratorRestoreSheet(viewModel: viewModel)
}
.sheet(
isPresented: Binding(
get: { viewModel.pruneSummary != nil },
set: { isShown in
if !isShown { viewModel.cancelPrune() }
}
)
) {
if let summary = viewModel.pruneSummary {
CuratorPruneConfirmSheet(
summary: summary,
isPruning: viewModel.isPruning,
onConfirm: {
Task { await viewModel.confirmPrune() }
},
onCancel: {
viewModel.cancelPrune()
}
)
}
}
}
@ViewBuilder
private var headerActions: some View {
HStack(spacing: ScarfSpace.s2) {
if viewModel.isLoading {
ProgressView().controlSize(.small)
}
Button("Run Now") {
Task {
await viewModel.runNow(
synchronous: archiveAvailable,
timeout: 600
)
}
}
.buttonStyle(ScarfPrimaryButton())
.disabled(viewModel.isLoading)
.help(archiveAvailable
? "Curator runs synchronously on Hermes v0.13+. Usually 1090s."
: "Trigger a curator run. Returns immediately on pre-v0.13 hosts.")
Menu {
switch viewModel.status.state {
case .paused:
Button("Resume") { Task { await viewModel.resume() } }
case .enabled:
Button("Pause") { Task { await viewModel.pause() } }
default:
EmptyView()
}
if archiveAvailable {
Divider()
Button("Prune Archived…", role: .destructive) {
Task { await viewModel.planPrune() }
}
.disabled(viewModel.archivedSkills.isEmpty && !viewModel.isLoadingArchive)
} else {
Button("Restore Archived…") {
showRestoreSheet = true
}
.disabled(viewModel.status.archivedSkills == 0)
}
} label: {
Image(systemName: "ellipsis.circle")
}
}
}
private var statusSummary: some View {
@@ -206,6 +288,10 @@ struct CuratorView: View {
}
.buttonStyle(.plain)
.help(viewModel.status.pinnedNames.contains(row.name) ? "Pinned" : "Pin skill")
if archiveAvailable {
archiveButton(for: row.name)
}
}
.padding(.vertical, 2)
}
@@ -213,6 +299,25 @@ struct CuratorView: View {
}
}
@ViewBuilder
private func archiveButton(for name: String) -> some View {
if viewModel.pendingArchiveName == name {
ProgressView()
.controlSize(.small)
.frame(width: 14, height: 14)
} else {
Button {
Task { await viewModel.archive(name) }
} label: {
Image(systemName: "archivebox")
.font(.system(size: 12))
}
.buttonStyle(.plain)
.help("Archive (move out of active set)")
.disabled(viewModel.pendingArchiveName != nil)
}
}
private func counterChip(label: String, value: Int) -> some View {
Text("\(label) \(value)")
.font(ScarfFont.monoSmall)
@@ -277,6 +382,35 @@ struct CuratorView: View {
.background(ScarfColor.accentTint)
.clipShape(RoundedRectangle(cornerRadius: ScarfRadius.md))
}
/// Inline yellow banner for CLI failures. Non-blocking sits above
/// the status summary and dismisses with the "x" so users can keep
/// interacting with the leaderboard. Mirrors the pattern in
/// KanbanBoardView.
private func errorBanner(_ message: String) -> some View {
HStack(alignment: .top, spacing: ScarfSpace.s2) {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(ScarfColor.warning)
Text(message)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundPrimary)
.frame(maxWidth: .infinity, alignment: .leading)
Button {
viewModel.dismissError()
} label: {
Image(systemName: "xmark.circle.fill")
.foregroundStyle(ScarfColor.foregroundMuted)
}
.buttonStyle(.plain)
.help("Dismiss")
}
.padding(.horizontal, ScarfSpace.s3)
.padding(.vertical, ScarfSpace.s2)
.background(
RoundedRectangle(cornerRadius: ScarfRadius.md)
.fill(ScarfColor.warning.opacity(0.12))
)
}
}
/// Simple `FlowLayout` for the pinned-skill chips. Custom layout
@@ -1,7 +1,13 @@
import Foundation
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 state: String
let exitReason: String?
@@ -37,32 +43,48 @@ struct PendingPairing: Identifiable {
}
@Observable
final class GatewayViewModel {
@MainActor
final class MessagingGatewayViewModel {
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.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 pendingPairings: [PendingPairing] = []
var isLoading = false
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() {
isLoading = true
let ctx = context
let caps = capabilities
Task.detached { [weak self] in
// Two sync transport calls + two CLI invocations substantial
// remote latency. Detach the whole load and commit at the end.
let status = Self.fetchGatewayStatus(context: ctx)
let pairing = Self.fetchPairing(context: ctx)
let listSnap = caps.hasGatewayList
? HermesGatewayListService.fetch(context: ctx)
: nil
await MainActor.run { [weak self] in
guard let self else { return }
self.gateway = status
self.approvedUsers = pairing.approved
self.pendingPairings = pairing.pending
self.gatewayList = listSnap
self.isLoading = false
}
}
@@ -70,7 +92,7 @@ final class GatewayViewModel {
/// Static form of the gateway-status walk so the detached load can call
/// 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)
var pid: Int?
var state = "unknown"
@@ -102,7 +124,7 @@ final class GatewayViewModel {
let isLoaded = statusOutput.contains("service is loaded")
let isStale = statusOutput.contains("stale")
return GatewayInfo(
return MessagingGatewayInfo(
pid: pid, state: state, exitReason: exitReason,
startTime: startTime, updatedAt: updatedAt,
platforms: platforms, isLoaded: isLoaded, isStale: isStale
@@ -2,12 +2,24 @@ import SwiftUI
import ScarfCore
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 {
@State private var viewModel: GatewayViewModel
@State private var viewModel: MessagingGatewayViewModel
@Environment(HermesFileWatcher.self) private var fileWatcher
@Environment(\.hermesCapabilities) private var capabilitiesStore
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) {
ScarfPageHeader(
"Messaging Gateway",
subtitle: "Outbound channel bridge — Discord, Telegram, Slack, etc."
subtitle: "Outbound channel bridge — Discord, Telegram, Slack, Google Chat, etc."
)
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
platformsSection
pairingSection
@@ -29,14 +46,58 @@ struct GatewayView: View {
}
.background(ScarfColor.backgroundPrimary)
.navigationTitle("Messaging Gateway")
.onAppear { viewModel.load() }
.onAppear {
attachCapabilitiesIfNeeded()
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
private var serviceSection: some View {
VStack(alignment: .leading, spacing: 12) {
VStack(alignment: .leading, spacing: ScarfSpace.s3) {
HStack {
Text("Service")
.font(.headline)
@@ -46,15 +107,20 @@ struct GatewayView: View {
.font(.caption)
.foregroundStyle(.secondary)
}
HStack(spacing: 8) {
HStack(spacing: ScarfSpace.s2) {
Button("Start") { viewModel.startGateway() }
.buttonStyle(ScarfPrimaryButton())
.controlSize(.small)
Button("Stop") { viewModel.stopGateway() }
.buttonStyle(ScarfSecondaryButton())
.controlSize(.small)
Button("Restart") { viewModel.restartGateway() }
.buttonStyle(ScarfSecondaryButton())
.controlSize(.small)
}
.controlSize(.small)
}
HStack(spacing: 16) {
HStack(spacing: ScarfSpace.s3) {
StatusBadge(
label: viewModel.gateway.state,
isActive: viewModel.gateway.state == "running"
@@ -97,7 +163,7 @@ struct GatewayView: View {
// MARK: - Platforms
private var platformsSection: some View {
VStack(alignment: .leading, spacing: 8) {
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
Text("Platforms")
.font(.headline)
if viewModel.gateway.platforms.isEmpty {
@@ -105,7 +171,7 @@ struct GatewayView: View {
.font(.caption)
.foregroundStyle(.secondary)
} else {
HStack(spacing: 12) {
HStack(spacing: ScarfSpace.s3) {
ForEach(viewModel.gateway.platforms) { platform in
VStack(spacing: 6) {
Image(systemName: platform.icon)
@@ -119,9 +185,9 @@ struct GatewayView: View {
)
}
.frame(maxWidth: .infinity)
.padding(12)
.padding(ScarfSpace.s3)
.background(.quaternary.opacity(0.5))
.clipShape(RoundedRectangle(cornerRadius: 8))
.clipShape(RoundedRectangle(cornerRadius: ScarfRadius.md))
}
}
}
@@ -131,12 +197,12 @@ struct GatewayView: View {
// MARK: - Pairing
private var pairingSection: some View {
VStack(alignment: .leading, spacing: 12) {
VStack(alignment: .leading, spacing: ScarfSpace.s3) {
Text("Paired Users")
.font(.headline)
if !viewModel.pendingPairings.isEmpty {
VStack(alignment: .leading, spacing: 8) {
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
Label("Pending Approvals", systemImage: "clock.badge.questionmark")
.font(.caption.bold())
.foregroundStyle(.orange)
@@ -150,12 +216,12 @@ struct GatewayView: View {
viewModel.approvePairing(platform: pending.platform, code: pending.code)
}
.controlSize(.small)
.buttonStyle(.borderedProminent)
.buttonStyle(ScarfPrimaryButton())
}
.font(.caption)
.padding(8)
.padding(ScarfSpace.s2)
.background(.orange.opacity(0.1))
.clipShape(RoundedRectangle(cornerRadius: 6))
.clipShape(RoundedRectangle(cornerRadius: ScarfRadius.sm))
}
}
}
@@ -182,9 +248,9 @@ struct GatewayView: View {
}
.controlSize(.small)
}
.padding(8)
.padding(ScarfSpace.s2)
.background(.quaternary.opacity(0.3))
.clipShape(RoundedRectangle(cornerRadius: 6))
.clipShape(RoundedRectangle(cornerRadius: ScarfRadius.sm))
}
}
}
@@ -0,0 +1,492 @@
import Foundation
import Observation
import ScarfCore
import os
/// Drives the drag-and-drop Kanban board. Holds the column-grouped task
/// state, polls Hermes every 5s while foregrounded, and applies
/// optimistic updates around drag-drops so the UI feels instant.
///
/// **Optimistic merge.** When the user drops a card on a new column,
/// the VM records the in-flight task id + intended status, mutates the
/// local array immediately, and fires the corresponding CLI verb. Until
/// the next poll response confirms the new status, polled rows for
/// in-flight tasks are merged with the optimistic state preventing a
/// stale poll from snapping the card back to its old column. On CLI
/// failure, the optimistic mutation is reverted and an error message
/// is surfaced.
@Observable
@MainActor
final class KanbanBoardViewModel {
private let logger = Logger(subsystem: "com.scarf", category: "KanbanBoardViewModel")
let context: ServerContext
let service: KanbanService
/// When non-nil, the board filters list/watch calls to this tenant
/// and `New Task` pre-fills the tenant field. Used by per-project
/// boards; global board leaves it nil.
var tenantFilter: String?
/// When non-nil, `New Task` pre-fills the workspace to
/// `dir:<projectPath>` and locks it so project-scoped task
/// creation always lands inside the project tree.
let projectPath: String?
init(
context: ServerContext = .local,
tenantFilter: String? = nil,
projectPath: String? = nil
) {
self.context = context
self.service = KanbanService(context: context)
self.tenantFilter = tenantFilter
self.projectPath = projectPath
}
// MARK: - State
var tasks: [HermesKanbanTask] = []
var stats: HermesKanbanStats = .empty
var assignees: [HermesKanbanAssignee] = []
var isLoading = false
var lastError: String?
var lastPollAt: Date?
/// Filters above the board.
var assigneeFilter: String? // nil = all assignees
var showArchived: Bool = false
/// Optimistic in-flight overrides keyed by task id; cleared when the
/// polled response confirms the new state.
/// - Status side: drag-drop column moves.
/// - Hallucination-gate side (v0.13): Verify clicks flip `pending`
/// `verified` locally so the banner disappears immediately.
/// The override entry is dropped from the dictionary entirely once
/// both sides are nil (no override needed).
private struct OptimisticOverride {
var status: String?
var hallucinationGate: KanbanHallucinationGate?
var isEmpty: Bool {
status == nil && hallucinationGate == nil
}
}
private var optimisticOverrides: [String: OptimisticOverride] = [:]
/// Tasks dropped into invalid columns produce a transient "denied"
/// banner. Stored as an explicit error to support the Cmd-Z style
/// undo we don't ship in v2.7.5 but want to leave room for.
var transientNotice: String?
// MARK: - Polling
private var pollTask: Task<Void, Never>?
func startPolling() {
stopPolling()
pollTask = Task { [weak self] in
while !Task.isCancelled {
await self?.refresh()
try? await Task.sleep(nanoseconds: 5_000_000_000)
}
}
}
func stopPolling() {
pollTask?.cancel()
pollTask = nil
}
// MARK: - Loading
/// One-shot refresh. Polling drives the auto-refresh; this is
/// exposed for explicit user-triggered reloads (e.g. the toolbar
/// refresh button).
func refresh() async {
isLoading = true
defer { isLoading = false }
do {
let filter = KanbanListFilter(
assignee: assigneeFilter,
tenant: tenantFilter,
includeArchived: showArchived
)
let polled = try await service.list(filter)
mergePolledTasks(polled)
lastPollAt = Date()
lastError = nil
// Stats refresh is best-effort failure here doesn't
// poison the board, just leaves the glance string stale.
if let stats = try? await service.stats() {
self.stats = stats
}
} catch let err as KanbanError {
lastError = err.errorDescription
} catch {
lastError = error.localizedDescription
}
}
/// Refresh the assignee picker. Cheap; called once on appear.
func refreshAssignees() async {
if let list = try? await service.assignees() {
assignees = list
}
}
// MARK: - Column projection
/// Group tasks into the 5-column board layout. Triage column
/// hides itself when empty; archived only appears when
/// `showArchived` is on.
func tasks(in column: KanbanBoardColumn) -> [HermesKanbanTask] {
let raw = tasks.filter { effectiveColumn($0) == column }
return sortColumn(raw)
}
/// Visible columns for the current state. Triage hidden when
/// empty; archived hidden unless toggle is on.
var visibleColumns: [KanbanBoardColumn] {
var cols: [KanbanBoardColumn] = []
if !tasks(in: .triage).isEmpty {
cols.append(.triage)
}
cols.append(contentsOf: [.upNext, .running, .blocked, .done])
if showArchived {
cols.append(.archived)
}
return cols
}
// MARK: - Drag-drop
/// Apply an optimistic move and fire the matching Hermes verbs.
/// Returns immediately; the CLI calls run in the background.
/// Inputs the drag layer must collect upstream:
/// - `blockReason` when the destination is `.blocked`
/// - `completeResult` when the destination is `.done`
func attemptMove(
taskId: String,
to destination: KanbanBoardColumn,
blockReason: String? = nil,
completeResult: String? = nil
) {
guard let task = tasks.first(where: { $0.id == taskId }) else { return }
let source = effectiveColumn(task)
if source == destination { return }
let plan: KanbanTransitionPlan
do {
plan = try KanbanService.plan(
for: KanbanTransition(from: source, to: destination)
)
} catch let err as KanbanError {
transientNotice = err.errorDescription
return
} catch {
transientNotice = error.localizedDescription
return
}
// Optimistic mutation flip the local row's status to a
// value within the destination column's range. We pick a
// representative status per column.
let optimisticStatusValue = optimisticStatus(for: destination)
var override = optimisticOverrides[taskId] ?? OptimisticOverride()
override.status = optimisticStatusValue
optimisticOverrides[taskId] = override
let svc = service
Task {
do {
for step in plan.steps {
try await applyStep(step, taskId: taskId, blockReason: blockReason, completeResult: completeResult, service: svc)
}
// Refresh once on success so the polled state catches up
// without waiting for the 5s tick.
await refresh()
} catch let err as KanbanError {
clearStatusOverride(for: taskId)
lastError = err.errorDescription
logger.warning("kanban move failed: \(err.errorDescription ?? "", privacy: .public)")
} catch {
clearStatusOverride(for: taskId)
lastError = error.localizedDescription
}
}
}
/// Archive via context menu (not drag).
func archive(taskId: String) {
Task {
do {
try await service.archive(taskIds: [taskId])
await refresh()
} catch let err as KanbanError {
lastError = err.errorDescription
} catch {
lastError = error.localizedDescription
}
}
}
/// Reassign a task to a different profile (or clear the assignee
/// when `profile` is nil/empty). Fires a dispatcher pass after a
/// successful assignment so the task transitions promptly when
/// the gateway dispatcher's own cycle is slow. Best-effort:
/// failures surface in `lastError`. Used by the inspector's
/// inline assignee picker.
func reassignTask(taskId: String, to profile: String?) {
Task {
do {
let normalized = (profile?.isEmpty ?? true) ? nil : profile
try await service.assign(taskId: taskId, profile: normalized)
if normalized != nil {
// Best-effort nudge.
_ = try? await service.dispatch(maxTasks: nil, dryRun: false)
}
await refresh()
} catch let err as KanbanError {
lastError = err.errorDescription
} catch {
lastError = error.localizedDescription
}
}
}
/// Append a comment from the inspector pane.
func comment(taskId: String, text: String) {
Task {
do {
try await service.comment(taskId: taskId, text: text, author: nil)
await refresh()
} catch let err as KanbanError {
lastError = err.errorDescription
} catch {
lastError = error.localizedDescription
}
}
}
/// Create a new task wired up to the New Task sheet.
/// Fires a dispatcher pass immediately after successful creation
/// so an assigned task transitions from `ready` `running`
/// promptly without waiting for whatever cadence the gateway's
/// internal dispatcher loop runs at.
func createTask(_ request: KanbanCreateRequest) async throws -> HermesKanbanTask {
let task = try await service.create(request)
if let assignee = task.assignee, !assignee.isEmpty {
// Best-effort: failure here is non-fatal the task still
// exists, the user just won't see it transition to running
// until the next gateway dispatcher tick.
_ = try? await service.dispatch(maxTasks: nil, dryRun: false)
}
await refresh()
return task
}
// MARK: - Hallucination gate (v0.13)
/// User confirmed the worker-created card is real. Optimistically
/// flip the gate to `verified` so the banner disappears immediately;
/// the polling loop confirms the new state on the next tick. On
/// failure (e.g. the verb name is wrong on this v0.13.x build), the
/// override is cleared and the error surfaces in `lastError`.
func verifyHallucination(taskId: String) {
var override = optimisticOverrides[taskId] ?? OptimisticOverride()
override.hallucinationGate = .verified
optimisticOverrides[taskId] = override
Task {
do {
try await service.verify(taskId: taskId)
await refresh()
} catch let err as KanbanError {
clearHallucinationOverride(for: taskId)
lastError = err.errorDescription
logger.warning("kanban verify failed: \(err.errorDescription ?? "", privacy: .public)")
} catch {
clearHallucinationOverride(for: taskId)
lastError = error.localizedDescription
}
}
}
/// User rejected the worker-created card as a hallucinated reference.
/// Routes through `comment` + `archive` per `KanbanService.rejectHallucinated`
/// so there's an audit trail for why the card disappeared.
func rejectHallucination(taskId: String) {
Task {
do {
try await service.rejectHallucinated(taskId: taskId)
await refresh()
} catch let err as KanbanError {
lastError = err.errorDescription
} catch {
lastError = error.localizedDescription
}
}
}
// MARK: - Private helpers
private func mergePolledTasks(_ polled: [HermesKanbanTask]) {
// Filter polled rows to the requested tenant if one is set
// belt-and-suspenders against Hermes versions that ignore
// an empty `--tenant ""` argument.
let filtered: [HermesKanbanTask]
if let tenant = tenantFilter, !tenant.isEmpty {
filtered = polled.filter { $0.tenant == tenant }
} else {
filtered = polled
}
let presentIds = Set(filtered.map(\.id))
// Drop optimistic overrides for tasks Hermes confirmed. Two
// independent sides clear them separately so a Verify click
// still in-flight survives a status-side poll confirmation, and
// vice versa.
for (id, override) in optimisticOverrides {
guard let row = filtered.first(where: { $0.id == id }) else {
if !presentIds.contains(id) {
// Task no longer in the polled set (archived, deleted,
// or filtered out). Drop the override entirely.
optimisticOverrides.removeValue(forKey: id)
}
continue
}
// Status side optimistic move confirmed.
if let optStatus = override.status,
columnFromStatus(optStatus) == columnFromStatus(row.status) {
optimisticOverrides[id]?.status = nil
}
// Hallucination-gate side optimistic verify/reject confirmed.
if let optGate = override.hallucinationGate,
KanbanHallucinationGate.from(row.hallucinationGateStatus) == optGate {
optimisticOverrides[id]?.hallucinationGate = nil
}
if optimisticOverrides[id]?.isEmpty ?? true {
optimisticOverrides.removeValue(forKey: id)
}
}
tasks = filtered
}
/// Drop the status side of a task's override (preserving any
/// in-flight hallucination-gate optimistic state).
private func clearStatusOverride(for taskId: String) {
guard var override = optimisticOverrides[taskId] else { return }
override.status = nil
if override.isEmpty {
optimisticOverrides.removeValue(forKey: taskId)
} else {
optimisticOverrides[taskId] = override
}
}
/// Drop the hallucination-gate side of a task's override (preserving
/// any in-flight status-side drag-drop).
private func clearHallucinationOverride(for taskId: String) {
guard var override = optimisticOverrides[taskId] else { return }
override.hallucinationGate = nil
if override.isEmpty {
optimisticOverrides.removeValue(forKey: taskId)
} else {
optimisticOverrides[taskId] = override
}
}
/// Effective hallucination gate for a task the optimistic override
/// wins if one is in flight; otherwise the polled value. View code
/// reads through this so the banner / dim state matches the moment-
/// after-click experience.
func effectiveHallucinationGate(_ task: HermesKanbanTask) -> KanbanHallucinationGate? {
if let override = optimisticOverrides[task.id]?.hallucinationGate {
return override
}
return KanbanHallucinationGate.from(task.hallucinationGateStatus)
}
/// Return the effective board column for a task the optimistic
/// override wins if one is in flight; otherwise the polled status.
private func effectiveColumn(_ task: HermesKanbanTask) -> KanbanBoardColumn {
if let overrideStatus = optimisticOverrides[task.id]?.status {
return columnFromStatus(overrideStatus)
}
return columnFromStatus(task.status)
}
private nonisolated func columnFromStatus(_ status: String) -> KanbanBoardColumn {
KanbanStatus.from(status).boardColumn
}
private nonisolated func optimisticStatus(for column: KanbanBoardColumn) -> String {
switch column {
case .triage: return "triage"
case .upNext: return "todo"
case .running: return "running"
case .blocked: return "blocked"
case .done: return "done"
case .archived: return "archived"
}
}
/// Within-column ordering. Hermes has no `position` field, so we
/// derive ordering from `priority` (descending) then `created_at`
/// (descending). This matches the dispatcher's actual run order
/// what shows up first is what runs next.
private nonisolated func sortColumn(_ rows: [HermesKanbanTask]) -> [HermesKanbanTask] {
rows.sorted { lhs, rhs in
let lp = lhs.priority ?? 0
let rp = rhs.priority ?? 0
if lp != rp { return lp > rp }
return (lhs.createdAt ?? "") > (rhs.createdAt ?? "")
}
}
private func applyStep(
_ step: KanbanTransitionStep,
taskId: String,
blockReason: String?,
completeResult: String?,
service: KanbanService
) async throws {
switch step {
case .dispatch:
// The dispatcher silently skips tasks without an assignee.
// Refusing here, with a user-actionable message, beats
// letting Hermes lock the task into a 15-minute zombie
// state until stale_lock reclaim kicks in.
if let task = tasks.first(where: { $0.id == taskId }),
(task.assignee?.isEmpty ?? true) {
throw KanbanError.forbiddenTransition(
from: "Up Next",
to: "Running",
reason: "This task has no assignee. Hermes's dispatcher only spawns workers for assigned tasks. Open the task and assign a profile, or recreate it with an assignee."
)
}
_ = try await service.dispatch(maxTasks: nil, dryRun: false)
case .unblock:
try await service.unblock(taskIds: [taskId])
case .block(let reasonRequired):
let reason = (blockReason?.isEmpty ?? true) ? nil : blockReason
if reasonRequired && reason == nil {
throw KanbanError.forbiddenTransition(
from: "",
to: "Blocked",
reason: "A reason is required to mark a task blocked."
)
}
try await service.block(taskId: taskId, reason: reason)
case .complete(let resultRequired):
let result = (completeResult?.isEmpty ?? true) ? nil : completeResult
if resultRequired && result == nil {
throw KanbanError.forbiddenTransition(
from: "",
to: "Done",
reason: "A result summary is required to complete this task."
)
}
try await service.complete(taskIds: [taskId], result: result, summary: nil, metadataJSON: nil)
case .archive:
try await service.archive(taskIds: [taskId])
}
}
}
@@ -0,0 +1,137 @@
import Foundation
import Observation
import ScarfCore
import os
/// Drives the inspector pane for a single Kanban task. Loads the full
/// `kanban show` detail (comments + events + parent results) and the
/// run history (`kanban runs`). Mutations route back through the
/// shared `KanbanService` so the board's optimistic merge picks them
/// up on the next poll tick.
@Observable
@MainActor
final class KanbanTaskDetailViewModel {
private let logger = Logger(subsystem: "com.scarf", category: "KanbanTaskDetailViewModel")
let service: KanbanService
let taskId: String
var detail: HermesKanbanTaskDetail?
var runs: [HermesKanbanRun] = []
var isLoading = false
var lastError: String?
var commentDraft: String = ""
// MARK: - Worker log
/// Captured worker stdout/stderr from `hermes kanban log <id>`.
/// Empty until the first poll completes; updates every ~2s while
/// the task is running.
var log: String = ""
var isLogStreaming: Bool = false
private var logPollTask: Task<Void, Never>?
private var detailPollTask: Task<Void, Never>?
init(service: KanbanService, taskId: String) {
self.service = service
self.taskId = taskId
}
// No deinit-side cancellation: `logPollTask` is MainActor-isolated
// and `deinit` is nonisolated; relying on the Task's `[weak self]`
// capture is enough, and the inspector calls `stopLogPolling()`
// from `onDisappear` for predictable cleanup.
/// Start polling task detail (header / comments / events / runs)
/// every 5s while the inspector is open. Same cadence as the board
/// so a worker transition (e.g. running done) is reflected in
/// the inspector header + primary-action button without the user
/// having to close and reopen. Idempotent. The first iteration
/// runs immediately so the initial fetch matches one-shot
/// `load()` semantics.
func startDetailPolling() {
guard detailPollTask == nil else { return }
detailPollTask = Task { [weak self] in
while !Task.isCancelled {
guard let self else { return }
await self.load()
try? await Task.sleep(nanoseconds: 5_000_000_000)
}
}
}
func stopDetailPolling() {
detailPollTask?.cancel()
detailPollTask = nil
}
func load() async {
isLoading = true
defer { isLoading = false }
do {
async let detail = service.show(taskId: taskId)
async let runs = service.runs(taskId: taskId)
self.detail = try await detail
self.runs = (try? await runs) ?? []
lastError = nil
} catch let err as KanbanError {
lastError = err.errorDescription
} catch {
lastError = error.localizedDescription
}
}
/// One-shot log refresh. Use when the user opens the Log tab and
/// the task isn't running (so we don't want to start a poll loop).
func refreshLogOnce() async {
do {
let text = try await service.log(taskId: taskId, tailBytes: nil)
self.log = text
} catch let err as KanbanError {
lastError = err.errorDescription
} catch {
lastError = error.localizedDescription
}
}
/// Start polling the worker log every 2s. Called when the Log tab
/// is opened on a running task. Idempotent: a second call is a
/// no-op while the previous loop is alive.
func startLogPolling() {
guard logPollTask == nil else { return }
isLogStreaming = true
logPollTask = Task { [weak self] in
while !Task.isCancelled {
guard let self else { return }
await self.refreshLogOnce()
try? await Task.sleep(nanoseconds: 2_000_000_000)
// Auto-stop when the task transitions out of running.
if let status = self.detail?.task.status,
KanbanStatus.from(status) != .running {
self.isLogStreaming = false
self.logPollTask = nil
return
}
}
}
}
func stopLogPolling() {
logPollTask?.cancel()
logPollTask = nil
isLogStreaming = false
}
func submitComment() async {
let text = commentDraft.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty else { return }
do {
try await service.comment(taskId: taskId, text: text, author: nil)
commentDraft = ""
await load()
} catch let err as KanbanError {
lastError = err.errorDescription
} catch {
lastError = error.localizedDescription
}
}
}
@@ -0,0 +1,55 @@
import SwiftUI
import ScarfCore
import ScarfDesign
/// Modal sheet that prompts for an optional "reason" string before
/// firing `kanban block`. Used by the drag-drop layer when a card
/// lands on the Blocked column.
struct KanbanBlockReasonSheet: View {
@Environment(\.dismiss) private var dismiss
let taskTitle: String
let onSubmit: (String?) -> Void
@State private var reason: String = ""
@FocusState private var fieldFocused: Bool
var body: some View {
VStack(alignment: .leading, spacing: ScarfSpace.s3) {
VStack(alignment: .leading, spacing: 4) {
Text("Block task")
.scarfStyle(.title3)
.foregroundStyle(ScarfColor.foregroundPrimary)
Text(taskTitle)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
.lineLimit(2)
}
ScarfTextField("Reason (optional)", text: $reason)
.focused($fieldFocused)
Text("Reasons appear as a comment on the task and feed into the worker's context if it's later unblocked.")
.scarfStyle(.footnote)
.foregroundStyle(ScarfColor.foregroundFaint)
HStack {
Spacer()
Button("Cancel") {
dismiss()
}
.keyboardShortcut(.cancelAction)
.buttonStyle(ScarfSecondaryButton())
Button("Block") {
onSubmit(reason.trimmingCharacters(in: .whitespacesAndNewlines))
dismiss()
}
.keyboardShortcut(.defaultAction)
.buttonStyle(ScarfPrimaryButton())
}
}
.padding(ScarfSpace.s5)
.frame(width: 420)
.onAppear { fieldFocused = true }
}
}
@@ -0,0 +1,361 @@
import SwiftUI
import ScarfCore
import ScarfDesign
/// Full drag-and-drop Kanban board. Renders the visible columns side
/// by side, supports drag-drop for column transitions, and slides in
/// a side-pane inspector when a card is tapped.
///
/// Two flavors:
/// - **Global**: pass `tenantFilter: nil` and `projectPath: nil`.
/// - **Per-project**: pass the project's `kanbanTenant` slug + the
/// project path so the New Task sheet pre-fills the workspace and
/// tenant.
struct KanbanBoardView: View {
@State private var viewModel: KanbanBoardViewModel
@Environment(\.hermesCapabilities) private var capabilitiesStore
/// When non-nil, a project board hosts this view. Drives header
/// chrome (subtitle, hidden tenant filter) and create-sheet
/// defaults.
let projectName: String?
init(
context: ServerContext,
tenantFilter: String? = nil,
projectPath: String? = nil,
projectName: String? = nil
) {
_viewModel = State(initialValue: KanbanBoardViewModel(
context: context,
tenantFilter: tenantFilter,
projectPath: projectPath
))
self.projectName = projectName
}
/// Convenience read for the v0.13 diagnostics flag gates the
/// max_retries field, hallucination banner, diagnostics rendering,
/// and the auto-blocked reason banner. Pre-v0.13 hosts get the
/// v2.7.5 surface unchanged. Treats a missing store as "off" so
/// harness contexts (Previews) don't accidentally surface gated UI.
private var supportsKanbanDiagnostics: Bool {
capabilitiesStore?.capabilities.hasKanbanDiagnostics ?? false
}
@State private var inspectorTaskId: String?
@State private var showingCreateSheet = false
@State private var blockSheetTaskId: String?
@State private var blockSheetTitle: String = ""
@State private var blockSheetDestination: KanbanBoardColumn = .blocked
@State private var completeSheetTaskId: String?
@State private var completeSheetTitle: String = ""
var body: some View {
VStack(spacing: 0) {
header
ScarfDivider()
if let err = viewModel.lastError {
errorBanner(err)
}
if let notice = viewModel.transientNotice {
noticeBanner(notice)
}
HStack(spacing: 0) {
boardArea
if inspectorTaskId != nil {
ScarfDivider()
.frame(width: 1)
inspectorPane
.transition(.move(edge: .trailing).combined(with: .opacity))
}
}
}
.background(ScarfColor.backgroundPrimary)
.onAppear {
viewModel.startPolling()
Task { await viewModel.refreshAssignees() }
}
.onDisappear { viewModel.stopPolling() }
.sheet(isPresented: $showingCreateSheet) {
KanbanCreateSheet(
assignees: viewModel.assignees,
tenantPrefill: viewModel.tenantFilter,
projectWorkspacePath: viewModel.projectPath,
supportsKanbanDiagnostics: supportsKanbanDiagnostics
) { request in
_ = try await viewModel.createTask(request)
}
}
.sheet(isPresented: blockSheetBinding) {
KanbanBlockReasonSheet(taskTitle: blockSheetTitle) { reason in
if let taskId = blockSheetTaskId {
viewModel.attemptMove(
taskId: taskId,
to: blockSheetDestination,
blockReason: reason
)
}
blockSheetTaskId = nil
}
}
.sheet(isPresented: completeSheetBinding) {
KanbanCompleteResultSheet(taskTitle: completeSheetTitle) { result in
if let taskId = completeSheetTaskId {
viewModel.attemptMove(
taskId: taskId,
to: .done,
completeResult: result
)
}
completeSheetTaskId = nil
}
}
}
// MARK: - Header
private var header: some View {
ScarfPageHeader(
"Kanban",
subtitle: subtitle
) {
HStack(spacing: ScarfSpace.s2) {
glanceText
if viewModel.tenantFilter == nil {
assigneeFilterMenu
}
Toggle("Show archived", isOn: $viewModel.showArchived)
.toggleStyle(.switch)
.labelsHidden()
.help("Show archived tasks")
Button {
Task { await viewModel.refresh() }
} label: {
Image(systemName: "arrow.clockwise")
}
.buttonStyle(ScarfGhostButton())
.help("Refresh now")
Button {
showingCreateSheet = true
} label: {
Label("New Task", systemImage: "plus")
}
.buttonStyle(ScarfPrimaryButton())
}
}
}
private var subtitle: String {
if let projectName, let tenant = viewModel.tenantFilter, !tenant.isEmpty {
return "\(projectName) · tenant \(tenant)"
}
return "Hermes task board"
}
private var glanceText: some View {
let text = viewModel.stats.glanceString
return Text(text.isEmpty ? " " : text)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
.frame(minWidth: 60)
}
private var assigneeFilterMenu: some View {
Menu {
Button("All assignees") { viewModel.assigneeFilter = nil }
if !viewModel.assignees.isEmpty {
Divider()
ForEach(viewModel.assignees) { row in
Button(row.profile) { viewModel.assigneeFilter = row.profile }
}
}
} label: {
HStack(spacing: 4) {
Image(systemName: "line.3.horizontal.decrease.circle")
Text(viewModel.assigneeFilter ?? "All")
.scarfStyle(.caption)
}
}
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
}
// MARK: - Board area
private var boardArea: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: ScarfSpace.s4) {
ForEach(viewModel.visibleColumns, id: \.self) { column in
KanbanColumnView(
column: column,
tasks: viewModel.tasks(in: column),
isLive: column == .running && isLive,
readyPillCount: column == .upNext ? readyCount : 0,
onTaskTap: { task in
inspectorTaskId = task.id
},
onCreate: { showingCreateSheet = true },
onDrop: { ref in
handleDrop(ref.id, on: column)
},
canCreate: column == .upNext || column == .triage,
supportsKanbanDiagnostics: supportsKanbanDiagnostics,
effectiveHallucinationGate: { viewModel.effectiveHallucinationGate($0) }
)
}
Spacer(minLength: ScarfSpace.s4)
}
.padding(ScarfSpace.s4)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
// MARK: - Inspector
@ViewBuilder
private var inspectorPane: some View {
if let taskId = inspectorTaskId,
let task = viewModel.tasks.first(where: { $0.id == taskId }) {
KanbanInspectorPane(
service: viewModel.service,
taskId: taskId,
availableAssignees: viewModel.assignees,
supportsKanbanDiagnostics: supportsKanbanDiagnostics,
effectiveHallucinationGate: { viewModel.effectiveHallucinationGate($0) },
onClose: { inspectorTaskId = nil },
onClaim: {
viewModel.attemptMove(taskId: taskId, to: .running)
inspectorTaskId = nil
},
onComplete: {
completeSheetTaskId = taskId
completeSheetTitle = task.title
},
onBlock: {
blockSheetTaskId = taskId
blockSheetTitle = task.title
blockSheetDestination = .blocked
},
onUnblock: {
viewModel.attemptMove(taskId: taskId, to: .upNext)
inspectorTaskId = nil
},
onArchive: {
viewModel.archive(taskId: taskId)
inspectorTaskId = nil
},
onReassign: { profile in
viewModel.reassignTask(taskId: taskId, to: profile)
},
onVerifyHallucination: {
viewModel.verifyHallucination(taskId: taskId)
},
onRejectHallucination: {
viewModel.rejectHallucination(taskId: taskId)
// Card vanishes from active board after archive close
// the inspector so it doesn't dangle on a deleted task.
inspectorTaskId = nil
}
)
}
}
// MARK: - Drop handling
private func handleDrop(_ taskId: String, on destination: KanbanBoardColumn) {
guard let task = viewModel.tasks.first(where: { $0.id == taskId }) else { return }
// Sheets first when the transition needs user input.
switch destination {
case .blocked:
blockSheetTaskId = taskId
blockSheetTitle = task.title
blockSheetDestination = .blocked
case .done:
// Manual checkoffs from running don't strictly need a result,
// but we offer the sheet anyway so users can record one
// when relevant. The move fires regardless on submit.
if KanbanStatus.from(task.status) == .running {
completeSheetTaskId = taskId
completeSheetTitle = task.title
} else {
viewModel.attemptMove(taskId: taskId, to: destination)
}
default:
viewModel.attemptMove(taskId: taskId, to: destination)
}
}
private var blockSheetBinding: Binding<Bool> {
Binding(
get: { blockSheetTaskId != nil },
set: { if !$0 { blockSheetTaskId = nil } }
)
}
private var completeSheetBinding: Binding<Bool> {
Binding(
get: { completeSheetTaskId != nil },
set: { if !$0 { completeSheetTaskId = nil } }
)
}
// MARK: - Helpers
private var isLive: Bool {
guard let lastPoll = viewModel.lastPollAt else { return false }
return Date().timeIntervalSince(lastPoll) < 6
}
/// Tasks currently in `ready` (a Hermes status that the dispatcher
/// will promote to `running` next tick). Surfaced as a pill on the
/// To Do column header.
private var readyCount: Int {
viewModel.tasks.filter { KanbanStatus.from($0.status) == .ready }.count
}
private func errorBanner(_ message: String) -> some View {
HStack(spacing: 6) {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(ScarfColor.warning)
Text(message)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundPrimary)
Spacer()
Button {
viewModel.lastError = nil
Task { await viewModel.refresh() }
} label: {
Text("Retry")
.scarfStyle(.caption)
}
.buttonStyle(ScarfGhostButton())
}
.padding(.horizontal, ScarfSpace.s3)
.padding(.vertical, 8)
.frame(maxWidth: .infinity, alignment: .leading)
.background(ScarfColor.warning.opacity(0.12))
}
private func noticeBanner(_ message: String) -> some View {
HStack(spacing: 6) {
Image(systemName: "info.circle")
.foregroundStyle(ScarfColor.info)
Text(message)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundPrimary)
Spacer()
Button {
viewModel.transientNotice = nil
} label: {
Image(systemName: "xmark")
.font(.system(size: 10))
}
.buttonStyle(ScarfGhostButton())
}
.padding(.horizontal, ScarfSpace.s3)
.padding(.vertical, 8)
.frame(maxWidth: .infinity, alignment: .leading)
.background(ScarfColor.info.opacity(0.12))
}
}
@@ -0,0 +1,371 @@
import SwiftUI
import ScarfCore
import ScarfDesign
import CoreTransferable
/// Transferable wrapper for a kanban task id. We tunnel the payload
/// through `String` via `ProxyRepresentation` (no custom UTI needed)
/// because SwiftUI's drag-drop with custom-UTI `CodableRepresentation`
/// requires a registered exported type in Info.plist to round-trip
/// reliably; the proxy form skips that ceremony and consistently lands
/// drops in v15 / 26.
struct KanbanTaskRef: Transferable {
let id: String
static var transferRepresentation: some TransferRepresentation {
ProxyRepresentation(
exporting: { (ref: KanbanTaskRef) in ref.id },
importing: { (id: String) in KanbanTaskRef(id: id) }
)
}
}
/// Single Kanban card. Variant chrome differs by status:
/// - **Running** gets a blue left-edge accent + live shimmer
/// - **Blocked** gets a warning left-edge accent + glyph
/// - **Done** dims to 0.7 opacity (0.55 in dark mode)
/// - **Hallucination-gate pending** (v0.13+) dims to 0.6 + glyph and
/// shows a one-line auto-blocked reason in the footer when present.
struct KanbanCardView: View {
let task: HermesKanbanTask
let onTap: () -> Void
/// True when the connected Hermes is on v0.13+ gates the
/// hallucination dim/glyph, auto-block sub-line, and diagnostics
/// dot on the card. Pre-v0.13 hosts see the v2.7.5 chrome unchanged.
let supportsKanbanDiagnostics: Bool
/// Optimistic-aware accessor. Pre-v0.13 always nil. Otherwise delegates
/// to the board VM so a Verify click un-dims the card immediately.
let effectiveHallucinationGate: (HermesKanbanTask) -> KanbanHallucinationGate?
init(
task: HermesKanbanTask,
supportsKanbanDiagnostics: Bool = false,
effectiveHallucinationGate: @escaping (HermesKanbanTask) -> KanbanHallucinationGate? = { _ in nil },
onTap: @escaping () -> Void
) {
self.task = task
self.supportsKanbanDiagnostics = supportsKanbanDiagnostics
self.effectiveHallucinationGate = effectiveHallucinationGate
self.onTap = onTap
}
@Environment(\.colorScheme) private var colorScheme
/// Cached gate read derived once per body eval rather than recomputed
/// in each subview helper.
private var hallucinationGate: KanbanHallucinationGate? {
guard supportsKanbanDiagnostics else { return nil }
return effectiveHallucinationGate(task)
}
var body: some View {
Button(action: onTap) {
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
titleRow
if hasMetaRow1 {
metaRow1
}
if !task.skills.isEmpty {
skillsRow
}
footerRow
}
.padding(ScarfSpace.s3)
.frame(maxWidth: .infinity, alignment: .leading)
.background(
RoundedRectangle(cornerRadius: ScarfRadius.lg, style: .continuous)
.fill(ScarfColor.backgroundPrimary)
)
.overlay(
RoundedRectangle(cornerRadius: ScarfRadius.lg, style: .continuous)
.stroke(ScarfColor.border, lineWidth: 1)
)
.overlay(alignment: .leading) {
if let edgeColor {
Rectangle()
.fill(edgeColor)
.frame(width: 2)
.clipShape(
RoundedRectangle(cornerRadius: 1, style: .continuous)
)
.padding(.vertical, 4)
}
}
}
.buttonStyle(.plain)
.scarfShadow(.sm)
// v0.13: hallucination-pending cards dim to 0.6 to signal "needs
// verification before running" without making them unreadable.
// Done cards stay at the established doneOpacity (0.7 / 0.55).
.opacity(cardOpacity)
.draggable(KanbanTaskRef(id: task.id)) {
// Drag preview the live card with a heavier shadow.
self.dragPreview
}
}
private var cardOpacity: Double {
if task.isDone { return doneOpacity }
if hallucinationGate == .pending { return 0.6 }
return 1.0
}
private var titleRow: some View {
HStack(alignment: .top, spacing: ScarfSpace.s2) {
statusGlyph
Text(task.title)
.scarfStyle(.bodyEmph)
.foregroundStyle(ScarfColor.foregroundPrimary)
.lineLimit(2)
.multilineTextAlignment(.leading)
Spacer(minLength: 0)
// v0.13 hallucination glyph takes precedence over the
// unassigned glyph the hallucination state is the more
// specific signal (a worker created this card; verify it).
if hallucinationGate == .pending {
Image(systemName: "questionmark.diamond.fill")
.foregroundStyle(ScarfColor.warning)
.font(.system(size: 11, weight: .semibold))
.help("Worker-created — verify before running")
} else if needsAssignmentWarning {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(ScarfColor.warning)
.font(.system(size: 11, weight: .semibold))
.help("Unassigned — Hermes's dispatcher silently skips tasks with no assignee, so this task will never run automatically. Open the task and add an assignee, or recreate it with one set.")
}
}
}
/// Cards in `todo` or `ready` with no `assignee` are about to land
/// in a silent zombie state Hermes's dispatcher's `--json`
/// output literally lists them under `skipped_unassigned` and
/// moves on. Surfacing this on the card itself (vs. only inside
/// the inspector) is the only way the user has a chance to notice
/// before they sit there confused.
private var needsAssignmentWarning: Bool {
let column = KanbanStatus.from(task.status).boardColumn
guard column == .upNext || column == .triage else { return false }
return (task.assignee?.isEmpty ?? true)
}
@ViewBuilder
private var statusGlyph: some View {
switch KanbanStatus.from(task.status) {
case .blocked:
Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(ScarfColor.warning)
.font(.system(size: 11, weight: .semibold))
.padding(.top, 2)
case .done:
Image(systemName: "checkmark.circle.fill")
.foregroundStyle(ScarfColor.success)
.font(.system(size: 11, weight: .semibold))
.padding(.top, 2)
case .running:
// No leading glyph the left-edge accent + shimmer
// already encodes the live state.
EmptyView()
default:
EmptyView()
}
}
private var hasMetaRow1: Bool {
task.assignee?.isEmpty == false || task.workspaceKind != nil
}
private var metaRow1: some View {
HStack(spacing: ScarfSpace.s2) {
if let assignee = task.assignee, !assignee.isEmpty {
assigneeChip(assignee)
} else {
unassignedChip
}
if let workspace = task.workspaceKind {
ScarfBadge(workspace, kind: .neutral)
}
Spacer(minLength: 0)
}
}
private func assigneeChip(_ name: String) -> some View {
HStack(spacing: 4) {
Text(initials(of: name))
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(ScarfColor.accentActive)
.frame(width: 16, height: 16)
.background(ScarfColor.accentTint)
.clipShape(Circle())
Text(name)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
}
}
private var unassignedChip: some View {
Text("Unassigned")
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundFaint)
.padding(.horizontal, 6)
.padding(.vertical, 2)
.overlay(
RoundedRectangle(cornerRadius: ScarfRadius.sm, style: .continuous)
.stroke(
ScarfColor.borderStrong,
style: StrokeStyle(lineWidth: 1, dash: [2, 2])
)
)
}
private var skillsRow: some View {
HStack(spacing: 4) {
let visible = task.skills.prefix(2)
ForEach(Array(visible.enumerated()), id: \.offset) { _, skill in
ScarfBadge(skill, kind: .brand)
}
if task.skills.count > 2 {
ScarfBadge("+\(task.skills.count - 2)", kind: .neutral)
}
Spacer(minLength: 0)
}
}
private var footerRow: some View {
VStack(alignment: .leading, spacing: 2) {
// v0.13: server-supplied auto-blocked reason. Renders verbatim
// (truncated to one line; full reason in the inspector).
// Pre-v0.13 hosts always have task.autoBlockedReason == nil.
if supportsKanbanDiagnostics,
KanbanStatus.from(task.status) == .blocked,
let reason = task.autoBlockedReason, !reason.isEmpty {
Text(reason)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.danger)
.lineLimit(1)
.truncationMode(.tail)
.help(reason)
}
HStack(spacing: ScarfSpace.s2) {
Text(relativeTimeLabel)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundFaint)
Spacer(minLength: 0)
// v0.13: diagnostics dot small stethoscope glyph when
// any cross-run distress signal is attached. Matches the
// chip count in the inspector.
if supportsKanbanDiagnostics, !task.diagnostics.isEmpty {
Image(systemName: "stethoscope")
.font(.system(size: 9))
.foregroundStyle(ScarfColor.warning)
.help("\(task.diagnostics.count) diagnostic signal\(task.diagnostics.count == 1 ? "" : "s")")
}
if let priority = task.priority, priority >= 70 {
priorityIndicator(priority)
}
}
}
}
private func priorityIndicator(_ priority: Int) -> some View {
let color: Color = priority >= 90 ? ScarfColor.danger : ScarfColor.warning
return RoundedRectangle(cornerRadius: 2, style: .continuous)
.fill(color)
.frame(width: 8, height: 8)
.help("Priority \(priority)")
}
private var dragPreview: some View {
VStack(alignment: .leading, spacing: 2) {
Text(task.title)
.scarfStyle(.bodyEmph)
.foregroundStyle(ScarfColor.foregroundPrimary)
.lineLimit(1)
if let assignee = task.assignee, !assignee.isEmpty {
Text(assignee)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
}
}
.padding(.horizontal, ScarfSpace.s2)
.padding(.vertical, 6)
.background(ScarfColor.backgroundPrimary)
.overlay(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.stroke(ScarfColor.accent, lineWidth: 1)
)
.scarfShadow(.lg)
}
// MARK: - Helpers
private var edgeColor: Color? {
switch KanbanStatus.from(task.status) {
case .running: return ScarfColor.info
case .blocked: return ScarfColor.warning
default: return nil
}
}
private var doneOpacity: Double {
colorScheme == .dark ? 0.55 : 0.7
}
/// Display string for the footer's relative time slot. The "since"
/// reference depends on status running tasks show how long
/// they've been running; blocked show how long blocked, etc.
private var relativeTimeLabel: String {
switch KanbanStatus.from(task.status) {
case .running:
if let started = task.startedAt, let label = relativeShort(from: started) {
return "running \(label)"
}
return "running"
case .blocked:
// Hermes doesn't expose blocked-since separately; fall
// back to created_at as a coarse signal.
if let created = task.createdAt, let label = relativeShort(from: created) {
return "blocked \(label)"
}
return "blocked"
case .done:
if let completed = task.completedAt, let label = relativeShort(from: completed) {
return "done \(label) ago"
}
return "done"
default:
if let created = task.createdAt, let label = relativeShort(from: created) {
return "\(label) ago"
}
return ""
}
}
private func relativeShort(from iso: String) -> String? {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
if let date = formatter.date(from: iso) {
return Self.relativeFormatter.localizedString(for: date, relativeTo: Date())
}
formatter.formatOptions = [.withInternetDateTime]
if let date = formatter.date(from: iso) {
return Self.relativeFormatter.localizedString(for: date, relativeTo: Date())
}
return nil
}
private static let relativeFormatter: RelativeDateTimeFormatter = {
let f = RelativeDateTimeFormatter()
f.unitsStyle = .abbreviated
return f
}()
private func initials(of name: String) -> String {
let parts = name.split(whereSeparator: { !$0.isLetter && !$0.isNumber })
let letters = parts.prefix(2).compactMap { $0.first.map(String.init) }
return letters.joined().uppercased()
}
}
private extension HermesKanbanTask {
var isDone: Bool { KanbanStatus.from(status) == .done }
}
@@ -0,0 +1,170 @@
import SwiftUI
import ScarfCore
import ScarfDesign
/// One column of the Kanban board. Owns its drop target, header chrome,
/// scroll viewport, and per-column empty state. Cards are rendered via
/// `KanbanCardView`.
struct KanbanColumnView: View {
let column: KanbanBoardColumn
let tasks: [HermesKanbanTask]
/// Live indicator for the Running column true when polling has
/// ticked within the last 6 seconds.
let isLive: Bool
/// "ready: N " pill on the To Do column.
let readyPillCount: Int
let onTaskTap: (HermesKanbanTask) -> Void
let onCreate: () -> Void
let onDrop: (KanbanTaskRef) -> Void
let canCreate: Bool
/// True when the connected Hermes is on v0.13+. Forwarded to each
/// `KanbanCardView` so the hallucination dim/glyph + diagnostics dot
/// + auto-block sub-line gate uniformly.
let supportsKanbanDiagnostics: Bool
/// Optimistic-aware accessor forwarded to cards. Default is
/// "no override" so Previews and harness contexts still render
/// without wiring up a board VM.
let effectiveHallucinationGate: (HermesKanbanTask) -> KanbanHallucinationGate?
init(
column: KanbanBoardColumn,
tasks: [HermesKanbanTask],
isLive: Bool,
readyPillCount: Int,
onTaskTap: @escaping (HermesKanbanTask) -> Void,
onCreate: @escaping () -> Void,
onDrop: @escaping (KanbanTaskRef) -> Void,
canCreate: Bool,
supportsKanbanDiagnostics: Bool = false,
effectiveHallucinationGate: @escaping (HermesKanbanTask) -> KanbanHallucinationGate? = { _ in nil }
) {
self.column = column
self.tasks = tasks
self.isLive = isLive
self.readyPillCount = readyPillCount
self.onTaskTap = onTaskTap
self.onCreate = onCreate
self.onDrop = onDrop
self.canCreate = canCreate
self.supportsKanbanDiagnostics = supportsKanbanDiagnostics
self.effectiveHallucinationGate = effectiveHallucinationGate
}
@State private var isTargeted = false
var body: some View {
VStack(spacing: 0) {
header
.padding(.horizontal, ScarfSpace.s3)
.padding(.vertical, ScarfSpace.s2)
.background(ScarfColor.backgroundSecondary.opacity(0.001))
.background(.ultraThinMaterial)
Divider()
.opacity(0.5)
ScrollView {
LazyVStack(spacing: ScarfSpace.s2) {
if tasks.isEmpty {
emptyState
.padding(.top, ScarfSpace.s4)
} else {
ForEach(tasks) { task in
KanbanCardView(
task: task,
supportsKanbanDiagnostics: supportsKanbanDiagnostics,
effectiveHallucinationGate: effectiveHallucinationGate
) {
onTaskTap(task)
}
}
}
}
.padding(ScarfSpace.s3)
}
}
.frame(minWidth: 240, idealWidth: 300, maxWidth: 360)
.frame(maxHeight: .infinity)
.background(
RoundedRectangle(cornerRadius: ScarfRadius.xl, style: .continuous)
.fill(ScarfColor.backgroundSecondary.opacity(0.6))
)
.overlay(
RoundedRectangle(cornerRadius: ScarfRadius.xl, style: .continuous)
.stroke(borderColor, lineWidth: isTargeted ? 2 : 1)
)
.animation(.easeInOut(duration: 0.12), value: isTargeted)
.dropDestination(for: KanbanTaskRef.self) { items, _ in
if let ref = items.first {
onDrop(ref)
return true
}
return false
} isTargeted: { targeted in
isTargeted = targeted
}
}
// MARK: - Header
private var header: some View {
HStack(spacing: ScarfSpace.s2) {
Text(column.displayName.uppercased())
.scarfStyle(.captionUppercase)
.foregroundStyle(ScarfColor.foregroundMuted)
ScarfBadge(String(tasks.count), kind: .neutral)
if column == .upNext, readyPillCount > 0 {
Text("ready: \(readyPillCount)")
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.info)
}
if column == .running, isLive {
liveIndicator
}
Spacer(minLength: 0)
if canCreate {
Button(action: onCreate) {
Image(systemName: "plus")
.font(.system(size: 12, weight: .semibold))
}
.buttonStyle(ScarfGhostButton())
.help("New task in \(column.displayName)")
}
}
}
private var liveIndicator: some View {
HStack(spacing: 4) {
Circle()
.fill(ScarfColor.success)
.frame(width: 6, height: 6)
Text("live")
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
}
}
private var borderColor: Color {
isTargeted ? ScarfColor.accent : ScarfColor.border
}
// MARK: - Empty state
private var emptyState: some View {
Text(emptyCopy)
.scarfStyle(.footnote)
.foregroundStyle(ScarfColor.foregroundFaint)
.multilineTextAlignment(.center)
.frame(maxWidth: .infinity)
.padding(.vertical, ScarfSpace.s4)
}
private var emptyCopy: String {
switch column {
case .triage: return "Nothing waiting on you."
case .upNext: return "Empty queue. Drop a task here."
case .running: return "No live workers."
case .blocked: return "Nothing blocked."
case .done: return "Recent completions appear here."
case .archived: return "No archived tasks."
}
}
}
@@ -0,0 +1,56 @@
import SwiftUI
import ScarfCore
import ScarfDesign
/// Modal sheet that prompts for an optional "result summary" before
/// firing `kanban complete`. Optional leaving it blank still
/// completes the task; the field captures the most useful Hermes
/// flag for downstream child tasks.
struct KanbanCompleteResultSheet: View {
@Environment(\.dismiss) private var dismiss
let taskTitle: String
let onSubmit: (String?) -> Void
@State private var result: String = ""
@FocusState private var fieldFocused: Bool
var body: some View {
VStack(alignment: .leading, spacing: ScarfSpace.s3) {
VStack(alignment: .leading, spacing: 4) {
Text("Complete task")
.scarfStyle(.title3)
.foregroundStyle(ScarfColor.foregroundPrimary)
Text(taskTitle)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
.lineLimit(2)
}
ScarfTextField("Result summary (optional)", text: $result)
.focused($fieldFocused)
Text("If this task has child tasks, the result is handed to them as upstream context. Leave blank for a quiet completion.")
.scarfStyle(.footnote)
.foregroundStyle(ScarfColor.foregroundFaint)
HStack {
Spacer()
Button("Cancel") {
dismiss()
}
.keyboardShortcut(.cancelAction)
.buttonStyle(ScarfSecondaryButton())
Button("Complete") {
onSubmit(result.trimmingCharacters(in: .whitespacesAndNewlines))
dismiss()
}
.keyboardShortcut(.defaultAction)
.buttonStyle(ScarfPrimaryButton())
}
}
.padding(ScarfSpace.s5)
.frame(width: 460)
.onAppear { fieldFocused = true }
}
}
@@ -0,0 +1,428 @@
import SwiftUI
import ScarfCore
import ScarfDesign
/// New Task sheet creates a Kanban task via `hermes kanban create`.
/// Workspace defaults to the project directory when shown from a per-
/// project board (locked); on the global board defaults to scratch.
struct KanbanCreateSheet: View {
@Environment(\.dismiss) private var dismiss
let assignees: [HermesKanbanAssignee]
/// Pre-filled tenant on per-project boards. Empty on global board.
let tenantPrefill: String?
/// Pre-filled project workspace path on per-project boards. When
/// non-nil, the workspace picker is locked to "Project Dir".
let projectWorkspacePath: String?
/// True when the connected Hermes is on v0.13+ gates the
/// `--max-retries` field and decides whether to strip newlines from
/// the title at submit time. Pre-v0.13 hosts may truncate at the
/// first `\n`; we keep the multi-line input rendering on either way
/// since a taller `TextField` is harmless on v0.12.
let supportsKanbanDiagnostics: Bool
/// Closure invoked when the user submits VM owner constructs the
/// `KanbanService.create` call.
let onSubmit: (KanbanCreateRequest) async throws -> Void
@State private var title: String = ""
@State private var bodyText: String = ""
/// Default assignee on first appearance. Hermes's dispatcher
/// silently skips unassigned tasks (`skipped_unassigned` field on
/// `kanban dispatch --json` output) so leaving this empty produces
/// tasks that never run. We preselect the active Hermes profile
/// and let the user opt out if they really want unassigned (which
/// is rarely useful typically only when they plan to assign
/// later via CLI or another flow).
@State private var assignee: String = HermesProfileResolver.activeProfileName()
@State private var workspaceKind: WorkspaceKind = .scratch
@State private var priority: Double = 50
@State private var skillsInput: String = ""
@State private var tenant: String = ""
@State private var sendToTriage: Bool = false
/// v0.13: per-task retry budget. Toggle-gated so the user can opt
/// into "send the flag" vs. "let Hermes pick its default" (the
/// release notes default to 3 see TODO in KanbanCreateRequest).
@State private var maxRetriesEnabled: Bool = false
@State private var maxRetries: Int = 3
@State private var isSubmitting: Bool = false
@State private var submitError: String?
@FocusState private var titleFocused: Bool
enum WorkspaceKind: String, CaseIterable, Identifiable {
case scratch
case worktree
case projectDir
var id: String { rawValue }
var label: String {
switch self {
case .scratch: return "Scratch"
case .worktree: return "Worktree"
case .projectDir: return "Project Dir"
}
}
}
var body: some View {
VStack(alignment: .leading, spacing: ScarfSpace.s3) {
header
ScarfDivider()
ScrollView {
VStack(alignment: .leading, spacing: ScarfSpace.s4) {
titleField
descriptionField
assigneePicker
workspaceField
priorityField
if supportsKanbanDiagnostics {
maxRetriesField
}
skillsField
if projectWorkspacePath == nil {
tenantField
}
triageToggle
}
.padding(.vertical, ScarfSpace.s2)
}
if let error = submitError {
errorBanner(error)
}
ScarfDivider()
footerButtons
}
.padding(ScarfSpace.s5)
.frame(width: 540, height: 660)
.onAppear {
if let path = projectWorkspacePath, !path.isEmpty {
workspaceKind = .projectDir
}
if let prefill = tenantPrefill, !prefill.isEmpty {
tenant = prefill
}
titleFocused = true
}
}
// MARK: - Header
private var header: some View {
HStack {
VStack(alignment: .leading, spacing: 2) {
Text("New task")
.scarfStyle(.title3)
.foregroundStyle(ScarfColor.foregroundPrimary)
if let prefill = tenantPrefill, !prefill.isEmpty {
Text("Tenant: `\(prefill)`")
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
} else {
Text("Adds to the global Kanban board")
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
}
}
Spacer()
}
}
// MARK: - Fields
private var titleField: some View {
// v0.13 server tolerates multi-line titles. We keep the
// multi-line input rendering on for ALL versions of Hermes
// visually a taller TextField is harmless on v0.12 and decide
// at submit time whether to strip newlines (see `makeRequest`).
VStack(alignment: .leading, spacing: 4) {
ScarfSectionHeader("Title")
TextField(
"What needs doing?",
text: $title,
axis: .vertical
)
.lineLimit(1...4)
.textFieldStyle(.plain)
.scarfStyle(.body)
.padding(.horizontal, ScarfSpace.s3)
.padding(.vertical, ScarfSpace.s2)
.background(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.fill(ScarfColor.backgroundSecondary)
)
.overlay(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.strokeBorder(ScarfColor.borderStrong, lineWidth: 1)
)
.focused($titleFocused)
}
}
/// v0.13: per-task retry budget. Toggle gates whether `--max-retries`
/// is sent at all so the user can preserve "let Hermes pick the
/// default" semantics by leaving the toggle off.
private var maxRetriesField: some View {
VStack(alignment: .leading, spacing: 4) {
ScarfSectionHeader(
"Max retries",
subtitle: "0 = no retries. Defaults to 3."
)
HStack(spacing: ScarfSpace.s3) {
Toggle("Override default", isOn: $maxRetriesEnabled)
.toggleStyle(.switch)
.labelsHidden()
Stepper(value: $maxRetries, in: 0...20) {
Text("\(maxRetries)")
.scarfStyle(.bodyEmph)
.frame(minWidth: 24, alignment: .trailing)
.foregroundStyle(
maxRetriesEnabled
? ScarfColor.foregroundPrimary
: ScarfColor.foregroundFaint
)
}
.disabled(!maxRetriesEnabled)
Spacer()
}
}
}
private var descriptionField: some View {
VStack(alignment: .leading, spacing: 4) {
ScarfSectionHeader("Description", subtitle: "Markdown supported")
TextEditor(text: $bodyText)
.scrollContentBackground(.hidden)
.padding(ScarfSpace.s2)
.frame(minHeight: 120, maxHeight: 200)
.background(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.fill(ScarfColor.backgroundSecondary)
)
.overlay(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.strokeBorder(ScarfColor.borderStrong, lineWidth: 1)
)
.scarfStyle(.body)
}
}
private var assigneePicker: some View {
VStack(alignment: .leading, spacing: 4) {
ScarfSectionHeader("Assignee")
Menu {
Button("Unassigned") { assignee = "" }
if !assignees.isEmpty {
Divider()
ForEach(assignees) { profile in
Button(profile.profile) { assignee = profile.profile }
}
}
} label: {
HStack {
Text(assignee.isEmpty ? "Unassigned" : assignee)
.scarfStyle(.body)
.foregroundStyle(ScarfColor.foregroundPrimary)
Spacer()
Image(systemName: "chevron.up.chevron.down")
.font(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
}
.padding(.horizontal, ScarfSpace.s3)
.padding(.vertical, ScarfSpace.s2)
.background(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.fill(ScarfColor.backgroundSecondary)
)
.overlay(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.strokeBorder(ScarfColor.borderStrong, lineWidth: 1)
)
}
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
}
}
private var workspaceField: some View {
VStack(alignment: .leading, spacing: 4) {
ScarfSectionHeader("Workspace")
Picker("", selection: $workspaceKind) {
ForEach(allowedWorkspaces) { kind in
Text(kind.label).tag(kind)
}
}
.pickerStyle(.segmented)
.disabled(projectWorkspacePath != nil)
if projectWorkspacePath != nil {
Text("Locked to project directory.")
.scarfStyle(.footnote)
.foregroundStyle(ScarfColor.foregroundFaint)
}
}
}
private var allowedWorkspaces: [WorkspaceKind] {
// Project Dir is only meaningful when we have a path.
if projectWorkspacePath == nil {
return [.scratch, .worktree]
}
return WorkspaceKind.allCases
}
private var priorityField: some View {
VStack(alignment: .leading, spacing: 4) {
ScarfSectionHeader("Priority", subtitle: "0100; higher runs first")
HStack(spacing: ScarfSpace.s3) {
Slider(value: $priority, in: 0...100, step: 1)
Text("\(Int(priority))")
.scarfStyle(.bodyEmph)
.frame(width: 32, alignment: .trailing)
.foregroundStyle(ScarfColor.foregroundPrimary)
}
HStack {
Text("low").scarfStyle(.caption).foregroundStyle(ScarfColor.foregroundFaint)
Spacer()
Text("normal").scarfStyle(.caption).foregroundStyle(ScarfColor.foregroundFaint)
Spacer()
Text("high").scarfStyle(.caption).foregroundStyle(ScarfColor.foregroundFaint)
}
}
}
private var skillsField: some View {
VStack(alignment: .leading, spacing: 4) {
ScarfSectionHeader("Skills", subtitle: "Comma-separated names from ~/.hermes/skills/")
ScarfTextField("e.g. translation, github-code-review", text: $skillsInput)
}
}
private var tenantField: some View {
VStack(alignment: .leading, spacing: 4) {
ScarfSectionHeader("Tenant", subtitle: "Optional namespace")
ScarfTextField("(none)", text: $tenant)
}
}
private var triageToggle: some View {
HStack(alignment: .top, spacing: ScarfSpace.s2) {
Toggle("Send to triage", isOn: $sendToTriage)
.toggleStyle(.switch)
Spacer()
}
.padding(.top, 4)
}
private func errorBanner(_ message: String) -> some View {
HStack(spacing: ScarfSpace.s2) {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(ScarfColor.warning)
Text(message)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundPrimary)
}
.padding(.horizontal, ScarfSpace.s3)
.padding(.vertical, ScarfSpace.s2)
.frame(maxWidth: .infinity, alignment: .leading)
.background(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.fill(ScarfColor.warning.opacity(0.12))
)
}
private var footerButtons: some View {
HStack {
Spacer()
Button("Cancel") { dismiss() }
.keyboardShortcut(.cancelAction)
.buttonStyle(ScarfSecondaryButton())
Button {
submit()
} label: {
if isSubmitting {
ProgressView()
.controlSize(.small)
} else {
Text("Create task")
}
}
.keyboardShortcut(.defaultAction)
.buttonStyle(ScarfPrimaryButton())
.disabled(title.trimmingCharacters(in: .whitespaces).isEmpty || isSubmitting)
}
}
// MARK: - Submit
private func submit() {
let request = makeRequest()
isSubmitting = true
submitError = nil
Task {
do {
try await onSubmit(request)
isSubmitting = false
dismiss()
} catch let err as KanbanError {
isSubmitting = false
submitError = err.errorDescription
} catch {
isSubmitting = false
submitError = error.localizedDescription
}
}
}
private func makeRequest() -> KanbanCreateRequest {
var trimmedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines)
// Pre-v0.13 hosts may truncate titles at the first `\n`. Strip
// newlines client-side when we know the connected Hermes hasn't
// shipped multi-line title support replace with a space to
// keep the user's intent visible. v0.13+ keeps newlines verbatim.
if !supportsKanbanDiagnostics {
trimmedTitle = trimmedTitle.replacingOccurrences(of: "\n", with: " ")
}
let trimmedBody = bodyText.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedAssignee = assignee.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedTenant = tenant.trimmingCharacters(in: .whitespacesAndNewlines)
let parsedSkills = skillsInput
.split(separator: ",")
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
let workspace: KanbanWorkspaceSpec?
switch workspaceKind {
case .scratch:
workspace = .scratch
case .worktree:
workspace = .worktree
case .projectDir:
if let path = projectWorkspacePath, !path.isEmpty {
workspace = .directory(path)
} else {
workspace = .scratch
}
}
// Belt-and-suspenders: the `maxRetriesField` is only rendered
// when `supportsKanbanDiagnostics` is true, but gate again here
// so a programmatic state change can't smuggle the flag onto a
// pre-v0.13 host (where the verb would error).
let resolvedMaxRetries: Int? = (supportsKanbanDiagnostics && maxRetriesEnabled)
? maxRetries
: nil
return KanbanCreateRequest(
title: trimmedTitle,
body: trimmedBody.isEmpty ? nil : trimmedBody,
assignee: trimmedAssignee.isEmpty ? nil : trimmedAssignee,
parentIds: [],
workspace: workspace,
tenant: trimmedTenant.isEmpty ? nil : trimmedTenant,
priority: Int(priority),
triage: sendToTriage,
idempotencyKey: nil,
maxRuntimeSeconds: nil,
createdBy: nil,
skills: parsedSkills,
maxRetries: resolvedMaxRetries
)
}
}
@@ -0,0 +1,851 @@
import SwiftUI
import ScarfCore
import ScarfDesign
/// Side-pane inspector for one Kanban task. Rendered alongside the board
/// (not modally) so the user can drag another card immediately after
/// closing this one. 420pt wide; slides in from the trailing edge.
struct KanbanInspectorPane: View {
@State private var viewModel: KanbanTaskDetailViewModel
let availableAssignees: [HermesKanbanAssignee]
/// True when the connected Hermes is on v0.13+ gates the
/// hallucination banner, max_retries chip, diagnostics block,
/// and auto-blocked reason banner. Pre-v0.13 hosts see the v2.7.5
/// inspector unchanged.
let supportsKanbanDiagnostics: Bool
/// Resolves an effective hallucination gate the board VM owns the
/// optimistic-override merge so the banner disappears immediately on
/// Verify before the polled state confirms the new gate. Falls back
/// to the wire-level value when no override is in flight.
let effectiveHallucinationGate: (HermesKanbanTask) -> KanbanHallucinationGate?
let onClose: () -> Void
let onClaim: () -> Void
let onComplete: () -> Void
let onBlock: () -> Void
let onUnblock: () -> Void
let onArchive: () -> Void
let onReassign: (String?) -> Void
let onVerifyHallucination: () -> Void
let onRejectHallucination: () -> Void
@State private var selectedTab: DetailTab = .comments
enum DetailTab: String, CaseIterable, Identifiable {
case comments = "Comments"
case events = "Events"
case runs = "Runs"
case log = "Log"
var id: String { rawValue }
}
init(
service: KanbanService,
taskId: String,
availableAssignees: [HermesKanbanAssignee] = [],
supportsKanbanDiagnostics: Bool = false,
effectiveHallucinationGate: @escaping (HermesKanbanTask) -> KanbanHallucinationGate? = { _ in nil },
onClose: @escaping () -> Void,
onClaim: @escaping () -> Void,
onComplete: @escaping () -> Void,
onBlock: @escaping () -> Void,
onUnblock: @escaping () -> Void,
onArchive: @escaping () -> Void,
onReassign: @escaping (String?) -> Void = { _ in },
onVerifyHallucination: @escaping () -> Void = {},
onRejectHallucination: @escaping () -> Void = {}
) {
_viewModel = State(initialValue: KanbanTaskDetailViewModel(service: service, taskId: taskId))
self.availableAssignees = availableAssignees
self.supportsKanbanDiagnostics = supportsKanbanDiagnostics
self.effectiveHallucinationGate = effectiveHallucinationGate
self.onClose = onClose
self.onClaim = onClaim
self.onComplete = onComplete
self.onBlock = onBlock
self.onUnblock = onUnblock
self.onArchive = onArchive
self.onReassign = onReassign
self.onVerifyHallucination = onVerifyHallucination
self.onRejectHallucination = onRejectHallucination
}
var body: some View {
VStack(spacing: 0) {
header
ScarfDivider()
if let detail = viewModel.detail {
ScrollView {
VStack(alignment: .leading, spacing: ScarfSpace.s3) {
healthBanner(for: detail.task)
bodySection(detail.task)
Picker("", selection: $selectedTab) {
ForEach(DetailTab.allCases) { tab in
Text(tab.rawValue).tag(tab)
}
}
.pickerStyle(.segmented)
switch selectedTab {
case .comments: commentsSection(detail.comments)
case .events: eventsSection(detail.events)
case .runs: runsSection
case .log: logSection(for: detail.task)
}
}
.padding(ScarfSpace.s4)
}
} else if viewModel.isLoading {
ProgressView()
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else if let err = viewModel.lastError {
errorState(err)
} else {
ProgressView()
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
ScarfDivider()
actionBar
}
.frame(width: 420)
.frame(maxHeight: .infinity)
.background(ScarfColor.backgroundPrimary)
.task {
// Start the 5s detail-poll loop. First iteration runs the
// initial fetch so the user sees the same load latency as
// the previous one-shot `viewModel.load()` did.
viewModel.startDetailPolling()
}
.onChange(of: viewModel.taskId) { _, _ in
viewModel.stopLogPolling()
viewModel.stopDetailPolling()
viewModel.startDetailPolling()
}
.onChange(of: selectedTab) { _, newTab in
handleTabChange(newTab)
}
.onChange(of: viewModel.detail?.task.status ?? "") { _, _ in
// If the task transitions to running while the log tab is
// open, start polling. If it transitions out, the polling
// loop self-cancels.
if selectedTab == .log {
handleTabChange(.log)
}
}
.onDisappear {
viewModel.stopLogPolling()
viewModel.stopDetailPolling()
}
}
private func handleTabChange(_ tab: DetailTab) {
guard tab == .log else {
viewModel.stopLogPolling()
return
}
let isRunning = (viewModel.detail?.task.status).flatMap {
KanbanStatus.from($0)
} == .running
if isRunning {
viewModel.startLogPolling()
} else {
// Static fetch for terminal-state tasks (done/blocked/etc).
viewModel.stopLogPolling()
Task { await viewModel.refreshLogOnce() }
}
}
// MARK: - Header
private var header: some View {
HStack(alignment: .top, spacing: ScarfSpace.s2) {
VStack(alignment: .leading, spacing: 4) {
if let task = viewModel.detail?.task {
Text(task.title)
.scarfStyle(.title3)
.foregroundStyle(ScarfColor.foregroundPrimary)
.lineLimit(2)
// Horizontal scroll lets the chip row degrade
// gracefully on narrow inspectors (or with long
// profile / tenant names) instead of wrapping
// chips onto a second visual line, which looked
// broken when a single name pushed past the
// available width.
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 4) {
ScarfBadge(task.status.lowercased(), kind: badgeKind(for: task.status))
.fixedSize()
assigneeMenu(for: task)
.fixedSize()
if let workspace = task.workspaceKind {
ScarfBadge(workspace, kind: .neutral)
.fixedSize()
}
// v0.13: max_retries chip. Read-only Hermes
// has no `update --max-retries` verb. The
// `if let` guards pre-v0.13 hosts (always nil)
// and the explicit capability gate adds
// belt-and-suspenders.
if supportsKanbanDiagnostics, let maxRetries = task.maxRetries {
ScarfBadge("retries: \(maxRetries)", kind: .neutral)
.fixedSize()
.help("Max retries set at create time. Hermes has no update verb — re-create the task to change this.")
}
if let tenant = task.tenant, !tenant.isEmpty {
ScarfBadge(tenant, kind: .brand)
.fixedSize()
}
}
}
} else {
Text("Loading…")
.scarfStyle(.title3)
.foregroundStyle(ScarfColor.foregroundMuted)
}
}
Spacer()
Button(action: onClose) {
Image(systemName: "xmark")
.font(.system(size: 12, weight: .semibold))
}
.buttonStyle(ScarfGhostButton())
.keyboardShortcut(.cancelAction)
}
.padding(ScarfSpace.s4)
}
/// Inline assignee picker. Renders as a clickable badge styled to
/// match neighboring chips: `.brand` when set, `.warning` when
/// unassigned (so the user immediately sees the signal). Menu
/// items list every known profile + "Unassigned"; selection
/// routes through `onReassign`, which on the board side calls
/// `kanban assign <id> <profile>` and then `kanban dispatch`.
private func assigneeMenu(for task: HermesKanbanTask) -> some View {
let current = task.assignee?.isEmpty == false ? task.assignee : nil
let options = mergedAssigneeOptions(currentAssignee: current)
let label = current ?? "Unassigned"
let kind: ScarfBadgeKind = (current == nil) ? .warning : .brand
return Menu {
Button("Unassigned") { onReassign(nil) }
if !options.isEmpty {
Divider()
ForEach(options, id: \.self) { profile in
Button(profile) { onReassign(profile) }
}
}
} label: {
HStack(spacing: 4) {
ScarfBadge(label, kind: kind)
Image(systemName: "chevron.down")
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(ScarfColor.foregroundMuted)
}
.fixedSize() // prevent chevron + badge from wrapping
}
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
.help(current == nil
? "Assign a profile so the dispatcher can spawn a worker."
: "Reassign this task. Hermes's dispatcher only runs assigned tasks.")
}
/// Build the assignee dropdown list. Sources, in order:
/// 1. The board's known-assignees list (passed in via init
/// union of `~/.hermes/profiles/` and current task assignees).
/// 2. The active local Hermes profile.
/// 3. The task's current assignee (so reassigning back is one tap).
/// Deduped, sorted for stability.
private func mergedAssigneeOptions(currentAssignee: String?) -> [String] {
var set = Set<String>()
for entry in availableAssignees {
set.insert(entry.profile)
}
let active = HermesProfileResolver.activeProfileName()
if !active.isEmpty {
set.insert(active)
}
if let currentAssignee {
set.insert(currentAssignee)
}
return set.sorted()
}
private func badgeKind(for status: String) -> ScarfBadgeKind {
switch KanbanStatus.from(status) {
case .running, .ready: return .info
case .done: return .success
case .blocked: return .warning
case .archived: return .neutral
default: return .neutral
}
}
// MARK: - Body
/// Inline health banner shown above the task body when something
/// requires user attention. Stack vertically (multiple can apply at
/// once on a v0.13 task e.g. unassigned + hallucination pending +
/// last-run-blocked).
/// Order top-to-bottom:
/// 1. **Hallucination gate (v0.13+)** pending worker-created card.
/// User must verify or reject before any other action makes sense.
/// 2. **Auto-blocked reason (v0.13+)** server-supplied reason
/// overrides the generic "Last run: blocked" banner.
/// 3. Task is in `ready`/`todo` with no assignee explains that the
/// dispatcher silently skips unassigned tasks.
/// 4. The most recent run ended in a non-success outcome surfaces
/// the error so the user doesn't have to dig into the Runs tab.
@ViewBuilder
private func healthBanner(for task: HermesKanbanTask) -> some View {
let status = KanbanStatus.from(task.status)
let column = status.boardColumn
let isUnassigned = (task.assignee?.isEmpty ?? true)
let needsAssignee = (column == .upNext || column == .triage) && isUnassigned
// Pick the most recent **completed** run by id descending
// skipping any in-flight run so a fresh worker doesn't show
// up here. The previous reclaimed/crashed run is only
// user-relevant *until* the next attempt actually starts;
// the moment status flips to running, the Log tab's live
// stream is the right signal and a stale banner just adds
// noise.
let lastEndedRun = viewModel.runs
.filter { $0.endedAt != nil }
.max(by: { $0.id < $1.id })
let failureOutcomes: Set<String> = [
"stale_lock", "reclaimed", "crashed",
"timed_out", "spawn_failed", "gave_up", "failed"
]
let hadFailedEndedRun = lastEndedRun
.flatMap { (run: HermesKanbanRun) -> String? in
run.outcome ?? run.status
}
.map { failureOutcomes.contains($0.lowercased()) }
?? false
// Suppress the failure banner during an active attempt once
// status is `running` again, the previous outcome is stale.
// Also suppress for `done` (terminal success).
let suppressFailureBanner = (status == .running) || (status == .done)
// v0.13: hallucination-gate state. Read through the VM's
// optimistic-aware accessor so a Verify click takes effect
// before the polled state confirms. Belt-and-suspenders gate
// on capability flag.
let hallucination: KanbanHallucinationGate? = supportsKanbanDiagnostics
? effectiveHallucinationGate(task)
: nil
// v0.13: structured auto-blocked reason. Renders the server's
// string verbatim; takes precedence over the generic "Last run:
// blocked" banner.
let autoBlockedReason: String? = (supportsKanbanDiagnostics
&& status == .blocked
&& (task.autoBlockedReason?.isEmpty == false))
? task.autoBlockedReason
: nil
// Suppress the generic last-run banner when the more specific
// server-side reason supersedes it.
let suppressGenericFailure = autoBlockedReason != nil
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
if hallucination == .pending {
hallucinationBanner
}
if let reason = autoBlockedReason {
bannerRow(
icon: "exclamationmark.octagon.fill",
tint: ScarfColor.danger,
title: "Auto-blocked",
// Verbatim Hermes-side message is the source of truth.
message: reason
)
}
if needsAssignee {
bannerRow(
icon: "exclamationmark.triangle.fill",
tint: ScarfColor.warning,
title: "Won't run automatically",
message: "Unassigned tasks are silently skipped by Hermes's dispatcher. Add an assignee to get this scheduled."
)
}
if hadFailedEndedRun, let lastEndedRun,
!suppressFailureBanner, !suppressGenericFailure {
let label = (lastEndedRun.outcome ?? lastEndedRun.status).lowercased()
let detail = lastEndedRun.error ?? lastEndedRun.summary ?? "no details"
bannerRow(
icon: "exclamationmark.octagon.fill",
tint: ScarfColor.danger,
title: "Last run: \(label)",
message: detail
)
}
// v0.13: cross-run diagnostics on the task header.
if supportsKanbanDiagnostics, !task.diagnostics.isEmpty {
diagnosticsBlock(task.diagnostics)
}
}
}
/// v0.13 hallucination-gate banner Verify / Reject affordances for
/// worker-created cards waiting on user verification.
private var hallucinationBanner: some View {
HStack(alignment: .top, spacing: ScarfSpace.s2) {
Image(systemName: "questionmark.diamond.fill")
.foregroundStyle(ScarfColor.warning)
.font(.system(size: 13, weight: .semibold))
VStack(alignment: .leading, spacing: 4) {
Text("Created by a worker — verify before running")
.scarfStyle(.captionStrong)
.foregroundStyle(ScarfColor.foregroundPrimary)
Text("A worker claimed it created this card; Hermes hasn't confirmed the underlying work exists. Verify the card matches a real follow-up, or reject if it's a hallucinated reference.")
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
HStack(spacing: ScarfSpace.s2) {
Button("Verify", action: onVerifyHallucination)
.buttonStyle(ScarfPrimaryButton())
Button("Reject", action: onRejectHallucination)
.buttonStyle(ScarfDestructiveButton())
}
.padding(.top, 2)
}
Spacer(minLength: 0)
}
.padding(ScarfSpace.s2)
.background(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.fill(ScarfColor.warning.opacity(0.10))
)
.overlay(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.strokeBorder(ScarfColor.warning.opacity(0.4), lineWidth: 1)
)
}
/// v0.13 diagnostics block renders a list of distress signals.
/// Used both at the task-header level (cross-run signals) and per
/// run on the Runs tab (in-flight signals). Wraps in a horizontal
/// scroll so a long diag list doesn't blow out inspector width.
private func diagnosticsBlock(_ diags: [HermesKanbanDiagnostic]) -> some View {
VStack(alignment: .leading, spacing: 4) {
Text("Diagnostics")
.scarfStyle(.captionUppercase)
.foregroundStyle(ScarfColor.foregroundFaint)
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 4) {
ForEach(diags) { diag in
diagnosticBadge(diag)
}
}
}
}
.padding(.top, 4)
}
@ViewBuilder
private func diagnosticBadge(_ diag: HermesKanbanDiagnostic) -> some View {
let kind = KanbanDiagnosticKind.from(diag.kind)
let badgeKind: ScarfBadgeKind = {
switch kind.severity {
case .danger: return .danger
case .warning: return .warning
case .neutral: return .neutral
}
}()
// Render the raw kind string view code stays in sync with
// whatever future kinds Hermes ships. The typed mirror picks
// the badge tint and tooltip glyph; the verbatim wire string
// is the user-facing label.
ScarfBadge(diag.kind, kind: badgeKind)
.help(diag.message ?? diag.kind)
}
private func bannerRow(
icon: String,
tint: Color,
title: String,
message: String
) -> some View {
HStack(alignment: .top, spacing: ScarfSpace.s2) {
Image(systemName: icon)
.foregroundStyle(tint)
.font(.system(size: 13, weight: .semibold))
VStack(alignment: .leading, spacing: 2) {
Text(title)
.scarfStyle(.captionStrong)
.foregroundStyle(ScarfColor.foregroundPrimary)
Text(message)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
}
Spacer(minLength: 0)
}
.padding(ScarfSpace.s2)
.background(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.fill(tint.opacity(0.10))
)
.overlay(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.strokeBorder(tint.opacity(0.4), lineWidth: 1)
)
}
@ViewBuilder
private func bodySection(_ task: HermesKanbanTask) -> some View {
if let body = task.body, !body.isEmpty {
if let attributed = try? AttributedString(markdown: body) {
Text(attributed)
.scarfStyle(.body)
.foregroundStyle(ScarfColor.foregroundPrimary)
.frame(maxWidth: .infinity, alignment: .leading)
} else {
Text(body)
.scarfStyle(.body)
.foregroundStyle(ScarfColor.foregroundPrimary)
.frame(maxWidth: .infinity, alignment: .leading)
}
} else {
Text("No description.")
.scarfStyle(.footnote)
.foregroundStyle(ScarfColor.foregroundFaint)
}
}
private func commentsSection(_ comments: [HermesKanbanComment]) -> some View {
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
if comments.isEmpty {
Text("No comments yet.")
.scarfStyle(.footnote)
.foregroundStyle(ScarfColor.foregroundFaint)
} else {
ForEach(comments) { comment in
commentRow(comment)
}
}
commentComposer
}
}
private func commentRow(_ comment: HermesKanbanComment) -> some View {
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: ScarfSpace.s2) {
Text(comment.author)
.scarfStyle(.captionStrong)
.foregroundStyle(ScarfColor.foregroundPrimary)
Text(comment.createdAt)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundFaint)
}
Text(comment.body)
.scarfStyle(.body)
.foregroundStyle(ScarfColor.foregroundMuted)
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(ScarfSpace.s2)
.background(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.fill(ScarfColor.backgroundSecondary.opacity(0.5))
)
}
private var commentComposer: some View {
VStack(alignment: .leading, spacing: 4) {
ScarfTextField("Add a comment…", text: Binding(
get: { viewModel.commentDraft },
set: { viewModel.commentDraft = $0 }
))
HStack {
Spacer()
Button("Comment") {
Task { await viewModel.submitComment() }
}
.buttonStyle(ScarfPrimaryButton())
.disabled(viewModel.commentDraft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
}
.padding(.top, ScarfSpace.s2)
}
private func eventsSection(_ events: [HermesKanbanEvent]) -> some View {
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
if events.isEmpty {
Text("No events yet.")
.scarfStyle(.footnote)
.foregroundStyle(ScarfColor.foregroundFaint)
} else {
ForEach(events) { event in
eventRow(event)
}
}
}
}
private func eventRow(_ event: HermesKanbanEvent) -> some View {
HStack(alignment: .top, spacing: ScarfSpace.s2) {
Image(systemName: glyphForEventKind(event.kindEnum))
.foregroundStyle(colorForEventKind(event.kindEnum))
.frame(width: 16)
VStack(alignment: .leading, spacing: 2) {
Text(event.kind)
.scarfStyle(.captionStrong)
.foregroundStyle(ScarfColor.foregroundPrimary)
Text(event.createdAt)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundFaint)
}
Spacer(minLength: 0)
}
}
private func glyphForEventKind(_ kind: KanbanEventKind) -> String {
switch kind {
case .created: return "plus.circle"
case .claimed: return "hand.raised"
case .started: return "play.circle"
case .completed: return "checkmark.circle.fill"
case .blocked: return "exclamationmark.triangle.fill"
case .unblocked: return "arrow.uturn.backward"
case .commented: return "text.bubble"
case .archived: return "archivebox"
case .heartbeat: return "waveform.path"
case .crashed, .timedOut, .spawnFailed, .error: return "xmark.octagon.fill"
case .statusChange, .released, .unknown: return "arrow.right"
}
}
private func colorForEventKind(_ kind: KanbanEventKind) -> Color {
switch kind {
case .completed: return ScarfColor.success
case .blocked, .crashed, .timedOut, .spawnFailed, .error: return ScarfColor.warning
case .claimed, .started, .unblocked: return ScarfColor.info
default: return ScarfColor.foregroundMuted
}
}
@ViewBuilder
private func logSection(for task: HermesKanbanTask) -> some View {
let isRunning = KanbanStatus.from(task.status) == .running
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
HStack(spacing: 6) {
if isRunning && viewModel.isLogStreaming {
Circle()
.fill(ScarfColor.success)
.frame(width: 6, height: 6)
Text("streaming")
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
} else if isRunning {
Text("waiting for first poll…")
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundFaint)
} else {
Text("snapshot from `hermes kanban log \(task.id)`")
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundFaint)
}
Spacer()
Button {
Task { await viewModel.refreshLogOnce() }
} label: {
Image(systemName: "arrow.clockwise")
.font(.system(size: 11))
}
.buttonStyle(ScarfGhostButton())
.help("Refresh worker log")
}
if viewModel.log.isEmpty {
Text(isRunning
? "No output yet. The worker may not have written anything to stdout / stderr."
: "No log captured for this task.")
.scarfStyle(.footnote)
.foregroundStyle(ScarfColor.foregroundFaint)
.padding(.vertical, ScarfSpace.s2)
} else {
ScrollViewReader { proxy in
ScrollView {
Text(viewModel.log)
.font(.system(size: 11, weight: .regular, design: .monospaced))
.foregroundStyle(ScarfColor.foregroundPrimary)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(ScarfSpace.s2)
// Invisible anchor pinned to the bottom so we
// can `scrollTo(.bottom)` whenever the log
// grows during a poll tick.
Color.clear.frame(height: 1).id("log-bottom-anchor")
}
.onChange(of: viewModel.log) { _, _ in
withAnimation(.linear(duration: 0.1)) {
proxy.scrollTo("log-bottom-anchor", anchor: .bottom)
}
}
}
.frame(maxHeight: 280)
.background(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.fill(ScarfColor.backgroundSecondary.opacity(0.5))
)
.overlay(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.strokeBorder(ScarfColor.border, lineWidth: 1)
)
}
}
}
private var runsSection: some View {
VStack(alignment: .leading, spacing: ScarfSpace.s2) {
if viewModel.runs.isEmpty {
Text("No runs yet.")
.scarfStyle(.footnote)
.foregroundStyle(ScarfColor.foregroundFaint)
} else {
ForEach(viewModel.runs) { run in
runRow(run)
}
}
}
}
private func runRow(_ run: HermesKanbanRun) -> some View {
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: ScarfSpace.s2) {
// Render the wire-side outcome / status string verbatim so
// v0.13's richer outcome strings ("zombied reclaimed by
// reaper", etc.) surface unchanged.
ScarfBadge(run.outcome ?? run.status, kind: outcomeKind(run.outcome ?? run.status))
if let profile = run.profile {
Text(profile)
.scarfStyle(.captionStrong)
.foregroundStyle(ScarfColor.foregroundPrimary)
}
Spacer()
Text(run.startedAt)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundFaint)
}
if let summary = run.summary, !summary.isEmpty {
Text(summary)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
.frame(maxWidth: .infinity, alignment: .leading)
}
if let error = run.error, !error.isEmpty {
Text(error)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.danger)
.frame(maxWidth: .infinity, alignment: .leading)
}
// v0.13: per-run diagnostics. Gated on capability so a future
// server-side change can't accidentally surface partial UX
// on a pre-v0.13 host.
if supportsKanbanDiagnostics, !run.diagnostics.isEmpty {
diagnosticsBlock(run.diagnostics)
}
}
.padding(ScarfSpace.s2)
.background(
RoundedRectangle(cornerRadius: ScarfRadius.md, style: .continuous)
.fill(ScarfColor.backgroundSecondary.opacity(0.4))
)
}
private func outcomeKind(_ outcome: String) -> ScarfBadgeKind {
switch outcome.lowercased() {
case "completed", "done": return .success
case "blocked": return .warning
case "crashed", "timed_out", "spawn_failed", "failed": return .danger
case "running": return .info
default: return .neutral
}
}
// MARK: - Action bar
@ViewBuilder
private var actionBar: some View {
HStack(spacing: ScarfSpace.s2) {
primaryAction
secondaryActions
Spacer()
archiveAction
}
.padding(ScarfSpace.s3)
}
@ViewBuilder
private var primaryAction: some View {
if let task = viewModel.detail?.task {
// v0.13: when the hallucination gate is pending, suppress the
// primary action the banner provides Verify / Reject as the
// gate. Showing "Start" alongside the banner would let the
// user dispatch a card Hermes hasn't confirmed exists.
if supportsKanbanDiagnostics,
effectiveHallucinationGate(task) == .pending {
EmptyView()
} else {
switch KanbanStatus.from(task.status) {
case .ready, .todo:
Button("Start", action: onClaim)
.buttonStyle(ScarfPrimaryButton())
.help("Atomically claim this task and start the worker. Moves it to Running.")
case .running:
Button("Complete", action: onComplete)
.buttonStyle(ScarfPrimaryButton())
.help("Mark this task as Done. You'll be prompted for an optional result summary.")
case .blocked:
Button("Unblock", action: onUnblock)
.buttonStyle(ScarfPrimaryButton())
.help("Return this task to the Up Next queue so the dispatcher can pick it up again.")
case .triage:
EmptyView()
default:
EmptyView()
}
}
}
}
@ViewBuilder
private var secondaryActions: some View {
if let task = viewModel.detail?.task {
switch KanbanStatus.from(task.status) {
case .ready, .todo, .running:
Button("Block", action: onBlock)
.buttonStyle(ScarfSecondaryButton())
.help("Mark this task blocked with a reason. The reason is appended as a comment.")
default:
EmptyView()
}
}
}
@ViewBuilder
private var archiveAction: some View {
if let task = viewModel.detail?.task,
KanbanStatus.from(task.status) != .archived {
Button("Archive", action: onArchive)
.buttonStyle(ScarfDestructiveButton())
.help("Hide this task from the active board. Hermes has no hard-delete; archived tasks remain in `~/.hermes/kanban.db` and are recoverable via the \"Show archived\" toggle until `hermes kanban gc` runs.")
}
}
// MARK: - Error
private func errorState(_ message: String) -> some View {
VStack(spacing: ScarfSpace.s2) {
Image(systemName: "exclamationmark.triangle")
.font(.system(size: 28))
.foregroundStyle(ScarfColor.warning)
Text(message)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
.multilineTextAlignment(.center)
Button("Retry") {
Task { await viewModel.load() }
}
.buttonStyle(ScarfSecondaryButton())
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding(ScarfSpace.s4)
}
}
@@ -0,0 +1,168 @@
import SwiftUI
import ScarfCore
import ScarfDesign
/// The v2.6 read-only list view, preserved as a presentation fallback
/// alongside the v2.7.5 drag-and-drop board. Reuses the existing
/// `KanbanViewModel` (status-filter polling) so the list stays
/// independent of the board's optimistic-merge state.
struct KanbanListView: View {
@State private var viewModel: KanbanViewModel
init(context: ServerContext) {
_viewModel = State(initialValue: KanbanViewModel(context: context))
}
var body: some View {
VStack(spacing: 0) {
ScarfPageHeader(
"Kanban",
subtitle: "Hermes v0.12+ task board (list view)"
) {
HStack(spacing: ScarfSpace.s2) {
Picker("Status", selection: $viewModel.statusFilter) {
ForEach(KanbanViewModel.StatusFilter.allCases) { f in
Text(f.label).tag(f)
}
}
.pickerStyle(.menu)
.frame(width: 120)
Button {
Task { await viewModel.load() }
} label: {
Label("Refresh", systemImage: "arrow.clockwise")
}
.buttonStyle(ScarfGhostButton())
}
}
Divider()
if let err = viewModel.lastError {
errorBanner(err)
}
ScrollView {
if viewModel.tasks.isEmpty && !viewModel.isLoading {
emptyState
} else {
taskTable
}
}
}
.background(ScarfColor.backgroundPrimary)
.onChange(of: viewModel.statusFilter) { _, _ in
Task { await viewModel.load() }
}
.onAppear { viewModel.startPolling() }
.onDisappear { viewModel.stopPolling() }
}
private var taskTable: some View {
VStack(spacing: 0) {
ForEach(viewModel.tasks) { task in
taskRow(task)
Divider()
}
}
.padding(ScarfSpace.s3)
}
private func taskRow(_ task: HermesKanbanTask) -> some View {
HStack(alignment: .top, spacing: ScarfSpace.s3) {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: ScarfSpace.s2) {
statusBadge(for: task.status)
Text(task.title)
.scarfStyle(.bodyEmph)
.foregroundStyle(ScarfColor.foregroundPrimary)
.lineLimit(1)
}
HStack(spacing: 12) {
metaChip(systemImage: "number", value: String(task.id.prefix(8)))
if let assignee = task.assignee, !assignee.isEmpty {
metaChip(systemImage: "person.fill", value: assignee)
}
if let workspace = task.workspaceKind {
metaChip(systemImage: "folder", value: workspace)
}
if let tenant = task.tenant, !tenant.isEmpty {
metaChip(systemImage: "tag", value: tenant)
}
if !task.skills.isEmpty {
metaChip(systemImage: "lightbulb", value: task.skills.joined(separator: ", "))
}
Spacer(minLength: 0)
}
}
Spacer(minLength: 0)
VStack(alignment: .trailing, spacing: 2) {
if let createdAt = task.createdAt {
Text(createdAt)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundFaint)
}
if let priority = task.priority {
Text("p\(priority)")
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
}
}
}
.padding(.vertical, ScarfSpace.s2)
}
private func statusBadge(for status: String) -> some View {
let kind: ScarfBadgeKind
switch status.lowercased() {
case "done": kind = .success
case "running": kind = .info
case "ready": kind = .info
case "blocked": kind = .warning
case "archived": kind = .neutral
default: kind = .neutral
}
return ScarfBadge(status, kind: kind)
}
private func metaChip(systemImage: String, value: String) -> some View {
HStack(spacing: 3) {
Image(systemName: systemImage)
.font(.system(size: 10))
Text(value)
.font(ScarfFont.monoSmall)
}
.foregroundStyle(ScarfColor.foregroundMuted)
}
private var emptyState: some View {
VStack(spacing: 12) {
Image(systemName: "rectangle.split.3x1")
.font(.system(size: 36))
.foregroundStyle(ScarfColor.foregroundFaint)
Text("No kanban tasks")
.scarfStyle(.headline)
.foregroundStyle(ScarfColor.foregroundPrimary)
Text("Create one with `hermes kanban create \"task title\"`. Tasks dispatched by the gateway show up here automatically.")
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
.multilineTextAlignment(.center)
.frame(maxWidth: 460)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding(.vertical, 60)
}
private func errorBanner(_ message: String) -> some View {
HStack(spacing: 6) {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(ScarfColor.warning)
Text(message)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundPrimary)
}
.padding(.horizontal, ScarfSpace.s3)
.padding(.vertical, 8)
.frame(maxWidth: .infinity, alignment: .leading)
.background(ScarfColor.warning.opacity(0.12))
}
}
@@ -2,166 +2,49 @@ import SwiftUI
import ScarfCore
import ScarfDesign
/// Mac UI for `hermes kanban list` (v0.12+). Read-only create / claim
/// / dispatch / dependency-link UI is deferred until upstream
/// stabilizes the multi-profile collaboration design.
/// Top-level Mac Kanban surface toggles between the v2.7.5 board view
/// (drag-and-drop, full read/write) and the legacy v2.6 read-only list.
/// Kept as a single AppCoordinator route so users can switch between
/// presentations without leaving the route, and so accessibility users
/// (or anyone with a narrow window) keep a usable list fallback.
///
/// Capability-gated upstream: AppCoordinator only routes to this view
/// when `HermesCapabilities.hasKanban` is true.
/// Capability-gated upstream: `SidebarView` only lists this route when
/// `HermesCapabilities.hasKanban` is true.
struct KanbanView: View {
@State private var viewModel: KanbanViewModel
let context: ServerContext
init(context: ServerContext) {
_viewModel = State(initialValue: KanbanViewModel(context: context))
@AppStorage("kanban.viewMode") private var rawMode: String = ViewMode.board.rawValue
enum ViewMode: String {
case board
case list
}
var body: some View {
VStack(spacing: 0) {
ScarfPageHeader(
"Kanban",
subtitle: "Hermes v0.12+ task board (read-only)"
) {
HStack(spacing: ScarfSpace.s2) {
Picker("Status", selection: $viewModel.statusFilter) {
ForEach(KanbanViewModel.StatusFilter.allCases) { f in
Text(f.label).tag(f)
}
}
.pickerStyle(.menu)
.frame(width: 120)
Button {
Task { await viewModel.load() }
} label: {
Label("Refresh", systemImage: "arrow.clockwise")
}
.buttonStyle(ScarfGhostButton())
}
}
Divider()
if let err = viewModel.lastError {
errorBanner(err)
}
ScrollView {
if viewModel.tasks.isEmpty && !viewModel.isLoading {
emptyState
} else {
taskTable
}
modeBar
ScarfDivider()
switch ViewMode(rawValue: rawMode) ?? .board {
case .board:
KanbanBoardView(context: context)
case .list:
KanbanListView(context: context)
}
}
.background(ScarfColor.backgroundPrimary)
.onChange(of: viewModel.statusFilter) { _, _ in
Task { await viewModel.load() }
}
.onAppear { viewModel.startPolling() }
.onDisappear { viewModel.stopPolling() }
}
private var taskTable: some View {
VStack(spacing: 0) {
ForEach(viewModel.tasks) { task in
taskRow(task)
Divider()
private var modeBar: some View {
HStack(spacing: ScarfSpace.s2) {
Spacer()
Picker("View", selection: $rawMode) {
Text("Board").tag(ViewMode.board.rawValue)
Text("List").tag(ViewMode.list.rawValue)
}
}
.padding(ScarfSpace.s3)
}
private func taskRow(_ task: HermesKanbanTask) -> some View {
HStack(alignment: .top, spacing: ScarfSpace.s3) {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: ScarfSpace.s2) {
statusBadge(for: task.status)
Text(task.title)
.scarfStyle(.bodyEmph)
.foregroundStyle(ScarfColor.foregroundPrimary)
.lineLimit(1)
}
HStack(spacing: 12) {
metaChip(systemImage: "number", value: task.id.prefix(8) + "")
if let assignee = task.assignee, !assignee.isEmpty {
metaChip(systemImage: "person.fill", value: assignee)
}
if let workspace = task.workspaceKind {
metaChip(systemImage: "folder", value: workspace)
}
if !task.skills.isEmpty {
metaChip(systemImage: "lightbulb", value: task.skills.joined(separator: ", "))
}
Spacer(minLength: 0)
}
}
Spacer(minLength: 0)
VStack(alignment: .trailing, spacing: 2) {
if let createdAt = task.createdAt {
Text(createdAt)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundFaint)
}
if let priority = task.priority {
Text("p\(priority)")
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
}
}
}
.padding(.vertical, ScarfSpace.s2)
}
private func statusBadge(for status: String) -> some View {
let kind: ScarfBadgeKind
switch status.lowercased() {
case "done": kind = .success
case "running": kind = .info
case "ready": kind = .info
case "blocked": kind = .warning
case "archived": kind = .neutral
default: kind = .neutral
}
return ScarfBadge(status, kind: kind)
}
private func metaChip(systemImage: String, value: String) -> some View {
HStack(spacing: 3) {
Image(systemName: systemImage)
.font(.system(size: 10))
Text(value)
.font(ScarfFont.monoSmall)
}
.foregroundStyle(ScarfColor.foregroundMuted)
}
private var emptyState: some View {
VStack(spacing: 12) {
Image(systemName: "rectangle.split.3x1")
.font(.system(size: 36))
.foregroundStyle(ScarfColor.foregroundFaint)
Text("No kanban tasks")
.scarfStyle(.headline)
.foregroundStyle(ScarfColor.foregroundPrimary)
Text("Create one with `hermes kanban create \"task title\"`. Tasks dispatched by the gateway show up here automatically.")
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundMuted)
.multilineTextAlignment(.center)
.frame(maxWidth: 460)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding(.vertical, 60)
}
private func errorBanner(_ message: String) -> some View {
HStack(spacing: 6) {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(ScarfColor.warning)
Text(message)
.scarfStyle(.caption)
.foregroundStyle(ScarfColor.foregroundPrimary)
.pickerStyle(.segmented)
.frame(width: 160)
}
.padding(.horizontal, ScarfSpace.s3)
.padding(.vertical, 8)
.frame(maxWidth: .infinity, alignment: .leading)
.background(ScarfColor.warning.opacity(0.12))
.padding(.vertical, ScarfSpace.s2)
}
}
@@ -21,6 +21,9 @@ final class MCPServerEditorViewModel {
var promptsEnabled: Bool
var timeoutDraft: 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 isSaving: Bool = false
var saveError: String?
@@ -37,6 +40,7 @@ final class MCPServerEditorViewModel {
self.promptsEnabled = server.promptsEnabled
self.timeoutDraft = server.timeout.map { String($0) } ?? ""
self.connectTimeoutDraft = server.connectTimeout.map { String($0) } ?? ""
self.sseReadTimeoutDraft = server.sseReadTimeout.map { String($0) } ?? ""
}
func appendEnvRow() {
@@ -69,6 +73,8 @@ final class MCPServerEditorViewModel {
let exclude = excludeDraft.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
let timeoutValue = Int(timeoutDraft.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 transport = server.transport
@@ -87,6 +93,11 @@ final class MCPServerEditorViewModel {
if !service.setMCPServerEnv(name: name, env: envMap) { ok = false }
case .http:
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(
name: name,
@@ -42,6 +42,10 @@ final class MCPServersViewModel {
filteredServers.filter { $0.transport == .http }
}
var sseServers: [HermesMCPServer] {
filteredServers.filter { $0.transport == .sse }
}
var selectedServer: HermesMCPServer? {
guard let name = selectedServerName else { return nil }
return servers.first(where: { $0.name == name })
@@ -167,6 +171,11 @@ final class MCPServersViewModel {
url: preset.url ?? "",
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 {
await MainActor.run {
@@ -196,6 +205,11 @@ final class MCPServersViewModel {
result = fileService.addMCPServerStdio(name: name, command: command, args: args)
case .http:
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 {
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() {
let fileService = self.fileService
Task.detached {
@@ -6,12 +6,26 @@ struct MCPServerAddCustomView: View {
let viewModel: MCPServersViewModel
@Environment(\.dismiss) private var dismiss
@Environment(\.hermesCapabilities) private var capabilitiesStore
@State private var name: String = ""
@State private var transport: MCPTransport = .stdio
@State private var command: String = "npx"
@State private var argsText: String = ""
@State private var url: String = ""
@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 {
VStack(spacing: 0) {
@@ -44,17 +58,20 @@ struct MCPServerAddCustomView: View {
}
sectionBox(title: "Transport") {
Picker("", selection: $transport) {
ForEach(MCPTransport.allCases) { t in
ForEach(availableTransports) { t in
Text(t.displayName).tag(t)
}
}
.pickerStyle(.segmented)
.labelsHidden()
}
if transport == .stdio {
switch transport {
case .stdio:
stdioSection
} else {
case .http:
httpSection
case .sse:
sseSection
}
Text("Env vars, headers, and tool filters can be edited after the server is added.")
.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 {
let trimmedName = name.trimmingCharacters(in: .whitespaces)
guard !trimmedName.isEmpty else { return false }
@@ -120,6 +159,8 @@ struct MCPServerAddCustomView: View {
return !command.trimmingCharacters(in: .whitespaces).isEmpty
case .http:
return !url.trimmingCharacters(in: .whitespaces).isEmpty
case .sse:
return !url.trimmingCharacters(in: .whitespaces).isEmpty
}
}
@@ -130,14 +171,25 @@ struct MCPServerAddCustomView: View {
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
let resolvedAuth: String? = (auth == "none") ? nil : auth
viewModel.addCustom(
name: trimmedName,
transport: transport,
command: command.trimmingCharacters(in: .whitespaces),
args: args,
url: url.trimmingCharacters(in: .whitespaces),
auth: resolvedAuth
)
switch transport {
case .stdio, .http:
viewModel.addCustom(
name: trimmedName,
transport: transport,
command: command.trimmingCharacters(in: .whitespaces),
args: args,
url: url.trimmingCharacters(in: .whitespaces),
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()
}
@@ -127,6 +127,11 @@ struct MCPServerDetailView: View {
if let auth = server.auth, !auth.isEmpty {
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)
@@ -186,6 +186,16 @@ struct MCPServerEditorView: View {
.textFieldStyle(.roundedBorder)
.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()
}
}
@@ -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 {
Section {
Text("No servers configured yet")
@@ -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]
}
}
@@ -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 {
@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 {
@@ -45,6 +51,13 @@ struct MatrixSetupView: View {
}
saveBar
// v0.13 Messaging Gateway behavior self-hides on pre-v0.13.
GatewayBehaviorSection(
platform: "matrix",
capabilities: capabilitiesStore?.capabilities ?? .empty,
context: context
)
}
.onAppear { viewModel.load() }
}
@@ -4,7 +4,13 @@ import ScarfDesign
struct MattermostSetupView: View {
@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 {
@@ -28,6 +34,13 @@ struct MattermostSetupView: View {
}
saveBar
// v0.13 Messaging Gateway behavior self-hides on pre-v0.13.
GatewayBehaviorSection(
platform: "mattermost",
capabilities: capabilitiesStore?.capabilities ?? .empty,
context: context
)
}
.onAppear { viewModel.load() }
}

Some files were not shown because too many files have changed in this diff Show More