diff --git a/.agents/skills/delete-comment/SKILL.md b/.agents/skills/delete-comment/SKILL.md new file mode 100644 index 000000000..f86d64f0e --- /dev/null +++ b/.agents/skills/delete-comment/SKILL.md @@ -0,0 +1,68 @@ +--- +name: delete-comment +description: Classify the Swift comments still in the baseline, record what they were holding, and delete them. +disable-model-invocation: true +--- + +# Delete comments + +Swift source in this repo carries no comments. `ci/check_comments.py` enforces it with a +ratchet: `ci/comment_baseline.txt` lists each file that still has comments and how many +lines, and that number only goes down. This skill walks it down. + +Scope is the paths given after `/delete-comment`, otherwise every file in the baseline. + +## Steps + +1. **List.** `python3 ci/check_comments.py --list ` prints each comment block as a + JSON line (`file`, `first`, `last`, `text`). Done when you hold the full list for the + scope. +2. **Classify** every block as exactly one category below, reading the code around it. + Done when every listed block has a category. +3. **Record** what deletion would lose. Each Decision Record goes into `docs/adr/` + (format in `docs/adr/README.md`): extend the ADR that already holds that decision, + otherwise add the next number. Each Excuse becomes one plain line for the maintainer: + the symbol, the shortcut it takes, the proper fix. Done when every Decision Record's + file is listed under an ADR section's `Lives in` and every Excuse has its line. +4. **Delete.** `python3 ci/check_comments.py --strip ` removes every comment in + those files, so strip only files whose blocks are all classified and recorded, and + leave out a file that holds a Keep. Then + `python3 ci/check_comments.py --update`. Done when `python3 ci/check_comments.py` + passes and `git diff` on Swift files shows comment lines removed and nothing else. +5. **Report** the count per category, the lines shed, and the Excuse list. The + maintainer picks which Excuses become issues (`docs/agents/issue-tracker.md` § Bulk + Findings); file those with the `improve` label. + +For more than a few hundred blocks, split the list into shards of about 340 blocks and +give each to a read-only classifier that writes verdicts to a file outside the worktree. +Write the ADRs and run `--strip` yourself, so no two agents edit the same file. + +## Categories + +**Tautology.** Restates what the code says or does: a summary of the function or type +below it, a parameter description, a `// MARK:`, a file header, a test scenario in words, +a step label. Product-language summaries count when the names and body show the same +thing. This is the default. + +**Stale.** A claim the code contradicts, or a name that no longer exists. `grep` names +the surrounding code does not show. Stale wins over Decision Record. + +**Excuse.** Cover for an implementation this repo should fix: `TODO`, `FIXME`, "for +now", "until X lands"; an admission the behavior is wrong, approximate, or racy; a +justification for `@unchecked Sendable`, `nonisolated(unsafe)`, a force unwrap or cast +where a safe design exists; a fixed delay or retry papering over a race; two places +"kept in sync by hand"; a shim the comment says should go. + +**Decision Record.** All three hold: it gives a reason the code cannot show (a server +contract quirk, an iOS or SwiftUI behavior, a past bug, a performance, privacy, or +security rule, an ordering dependency); an engineer reading only the code could +plausibly simplify it and bring back a user-visible bug; and this repo cannot fix the +cause (that would be an Excuse). A comment that says what happens and cites an issue +number is a Tautology. About one block in ten clears this bar. + +**Keep.** A third-party license or attribution notice no file in +`HermesMobile/Resources/ThirdPartyNotices/` covers. It stays in the baseline until the +notice moves there; say so in the report. + +A `// test-wait: ` annotation is read by `ci/check_test_waits.py`. The checker +neither lists nor strips it. diff --git a/.agents/skills/delete-comment/agents/openai.yaml b/.agents/skills/delete-comment/agents/openai.yaml new file mode 100644 index 000000000..5b1f887a9 --- /dev/null +++ b/.agents/skills/delete-comment/agents/openai.yaml @@ -0,0 +1,2 @@ +policy: + allow_implicit_invocation: false diff --git a/.claude/skills b/.claude/skills new file mode 120000 index 000000000..2b7a412b8 --- /dev/null +++ b/.claude/skills @@ -0,0 +1 @@ +../.agents/skills \ No newline at end of file diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.yml index 63b038d55..3579a2a91 100644 --- a/.github/workflows/pr-ci.yml +++ b/.github/workflows/pr-ci.yml @@ -226,6 +226,10 @@ jobs: python3 -m unittest discover -s scripts/tests python3 -m unittest discover -s ci -p 'test_*.py' python3 ci/check_test_waits.py + if [[ -n "${GITHUB_BASE_REF:-}" ]]; then + git fetch --no-tags --depth=1 origin "+refs/heads/${GITHUB_BASE_REF}:refs/remotes/origin/${GITHUB_BASE_REF}" + fi + python3 ci/check_comments.py ruby ci/select_testflight_build_number_test.rb gate: diff --git a/.gitignore b/.gitignore index 0a8fc8729..91c2bab71 100644 --- a/.gitignore +++ b/.gitignore @@ -30,12 +30,15 @@ UPDATES.md .obsidian/ docs/research/ -# Local agent tooling (per-machine caches, skills, session state) +# Local agent tooling (per-machine caches, session state). Repo skills are +# tracked in .agents/skills; .claude/skills links to them. node_modules/ .codex-tmp/ -.agents/ +.agents/* +!.agents/skills/ .sc/ -.claude/ +.claude/* +!.claude/skills .codex/ .cursor/ # App Store Connect credentials, release metadata, checkpoints, and tester exports diff --git a/AGENTS.md b/AGENTS.md index d6abaea52..f6fb674b4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,7 +77,7 @@ The most common defect in this repo is a change that works on the path you teste - **Reverse states.** If you added a way in, add the way out and the way to see it. Archive needs restore. Pin needs unpin. Start needs stop. Optimistic mutation needs rollback. A one-way door is a bug. - **Connection modes.** `localhost`, Tailscale, and tunnel behave differently; Cloudflare closes quiet streams. Backgrounding, reconnecting, and reattaching to a live stream instead of resending the message are real cases. - **Native quality.** Dynamic Type, VoiceOver labels, Reduce Motion, light and dark appearance, keyboard focus, and localization. Read `docs/agents/i18n.md` before touching the String Catalog, plurals, casing, or RTL. -- **Docs.** Agent conventions live in `docs/agents/`; new vocabulary in `CONTEXT.md`; build and simulator mechanics in `DEVELOPMENT.md`; Hermes connection, reconnect, and feature detection in `docs/agents/hermes-server.md`; webui parity in `docs/agents/feature-gap-index.md`, and what a Hermes host still lacks against webui in #1668; Kanban contract and behavior rules in `docs/agents/kanban.md`. Push components, keys, and relay data in `docs/agents/push.md`; usage report contract, consent, and collector in `docs/agents/usage-reports.md`. Performance rules and their guards in `docs/agents/performance.md`. `CHANGELOG.md` is written at release time, not per PR. +- **Docs.** Agent conventions live in `docs/agents/`; decisions the code cannot show in `docs/adr/`; new vocabulary in `CONTEXT.md`; build and simulator mechanics in `DEVELOPMENT.md`; Hermes connection, reconnect, and feature detection in `docs/agents/hermes-server.md`; webui parity in `docs/agents/feature-gap-index.md`, and what a Hermes host still lacks against webui in #1668; Kanban contract and behavior rules in `docs/agents/kanban.md`. Push components, keys, and relay data in `docs/agents/push.md`; usage report contract, consent, and collector in `docs/agents/usage-reports.md`. Performance rules and their guards in `docs/agents/performance.md`. `CHANGELOG.md` is written at release time, not per PR. ## Working with the server @@ -125,7 +125,7 @@ A live server is not a test fixture. Unit tests run against `URLProtocol` mocks, - Do not commit implementation plans, research notes, or agent scratch files. Keep temporary working material outside the worktree. - Track active maintainer work in the GitHub issue that owns it. Issue, label, and staged-versus-express conventions live in `docs/agents/issue-tracker.md` and `docs/agents/triage-labels.md`. External proposals follow `CONTRIBUTING.md`. -- Put durable architecture, constraints, and decisions in the checked-in docs (`docs/agents/`, `CONTEXT.md`, `DEVELOPMENT.md`). Update those docs when the product changes so agents find current facts instead of abandoned intentions. +- Put durable architecture, constraints, and decisions in the checked-in docs (`docs/agents/`, `docs/adr/`, `CONTEXT.md`, `DEVELOPMENT.md`). Update those docs when the product changes so agents find current facts instead of abandoned intentions. - A merged PR is the implementation record. Close or update its issue when the work lands; do not preserve a second checklist in the repository. ## How it works @@ -156,7 +156,7 @@ Canonical vocabulary: `CONTEXT.md`. - Make async ownership explicit. Cancellation, stale results, reconnects, and duplicate events are normal mobile conditions; never mutate state after the owning view or task is gone. - Optimistic UI only when failure has a clear rollback. Never show success before the server says the operation succeeded. - Destructive and privacy-sensitive actions stay deliberate: file writes, Git operations, server administration, and credential changes get copy that states the real consequence. -- Comments describe how a thing is used, and move when the code moves. To be used mostly to describe functions, not to annotate every line of behavior. +- Swift source carries no comments; `ci/check_comments.py` fails a file that gains one. Names and types say what the code does. A decision the code cannot show (a server quirk, an iOS behavior, a past bug) goes in `docs/adr/`, and changes in the same PR as the code it covers. - Our users drive agents from a phone all day and notice a dropped frame, a lying spinner, and a stale label. The intended feel is dense, calm, and operator-grade. No continuously repainting animations; every animation respects Reduce Motion. - The look is compact and glass-forward: a Liquid-Glass composer with the runtime controls in its bottom row, dense native pickers rather than marketing pages, and no third-party UI packages to get there. - The target builds in Swift 5 language mode with targeted concurrency. Fix what the build flags, not what strict Swift 6 would. diff --git a/HermesLiveActivityWidget/AgentRunLiveActivityWidget.swift b/HermesLiveActivityWidget/AgentRunLiveActivityWidget.swift index fcccbe9e8..1e198984f 100644 --- a/HermesLiveActivityWidget/AgentRunLiveActivityWidget.swift +++ b/HermesLiveActivityWidget/AgentRunLiveActivityWidget.swift @@ -49,17 +49,12 @@ struct AgentRunLiveActivityWidget: Widget { .agentRunPalette(on: .host) } .widgetURL(AgentRunTapTarget.url(attributes: context.attributes, sessionID: context.presentedState.sessionID, activityID: context.activityID)) - // The keyline only rings the iPhone's black Island, so it keeps the dark hues. .keylineTint(AgentRunPalette.dark.status(context.presentedState.status, isStale: context.presentedState.isStale)) } .supplementalActivityFamilies([.small]) } } -/// The activity's content view for every family: the two-line small layout on the -/// Apple Watch Smart Stack and CarPlay (#1400), the Lock Screen card everywhere else. -/// The family is read here because ActivityConfiguration's builder closures get no -/// environment. private struct AgentRunActivityContent: View { let context: ActivityViewContext @Environment(\.activityFamily) private var family @@ -73,9 +68,6 @@ private struct AgentRunActivityContent: View { } } -/// Title first, then state (#1400): the full ask or outcome title, the elapsed timer -/// while working, or the latest-status wording for stale work. Stale asks stay asks. -/// No excerpt, chips or pill: the card has to make sense at a glance without a tap. private struct AgentRunSmallView: View { let state: AgentRunActivityAttributes.ContentState let isBot: Bool @@ -90,7 +82,6 @@ private struct AgentRunSmallView: View { .font(.footnote.weight(.bold)) .foregroundStyle(palette.status(state.status, isStale: state.isStale)) .widgetAccentable() - // Working has no status words on the second line, so the glyph names the phase. .accessibilityLabel(state.status.title) .accessibilityHidden(presentation != .working) @@ -135,13 +126,10 @@ private struct AgentRunExpandedIslandBottomView: View { let isBot: Bool @Environment(\.agentRunPalette) private var palette - /// One line without reply text: what the agent is doing, then its counts. private var countsLine: String { AgentRunStaleBotPresentation.expandedCountsLine(state: state, isBot: isBot) } - /// A stale approval or clarification keeps its ask in this line. Every other - /// state still yields the line to reply text. private var showsStaleWaitingAnswer: Bool { AgentRunStaleBotPresentation.prefersWaitingAnswer(state: state, isBot: isBot) } @@ -177,13 +165,9 @@ private struct AgentRunLockScreenView: View { VStack(alignment: .leading, spacing: 10) { header activityRow - // A stale ask stays on the chips, including its answer action, even when - // reply text would otherwise take this row. Counts stay counts. if isBot, (showsStaleWaitingAnswer || context.presentedState.responseExcerpt.isEmpty), !botChips.isEmpty { AgentRunChipRow(chips: botChips.map(AgentRunDetailChip.text), isDimmed: context.presentedState.isStale) } else if !isBot, context.presentedState.responseExcerpt.isEmpty { - // No reply text to show: the relay's counts and freshness, or nothing - // at all rather than filler (#644). let chips = context.presentedState.detailChips if !chips.isEmpty { AgentRunChipRow(chips: chips, isDimmed: false) } } else { @@ -203,7 +187,6 @@ private struct AgentRunLockScreenView: View { } if context.presentedState.isStale { - // Stale webui names the card as stale. A disconnected Bot is handled above. return String(localized: "Latest status shown") } @@ -214,7 +197,6 @@ private struct AgentRunLockScreenView: View { return context.presentedState.currentActivity } - /// The bot's counts. A stale activity adds one action: answer, or reconnect. private var botChips: [String] { AgentRunStaleBotPresentation.lockScreenChips(state: context.presentedState, isBot: isBot) } @@ -288,8 +270,6 @@ private struct AgentRunLockScreenView: View { } } -/// Bounded detail chips: a bot's counts, or a webui run's counts and freshness (#644). -/// Only the system-drawn relative time moves; the app never repaints this row. private struct AgentRunChipRow: View { let chips: [AgentRunDetailChip] let isDimmed: Bool @@ -323,8 +303,6 @@ private extension AgentRunDetailChip { var isCount: Bool { if case .text = self { true } else { false } } } -/// The bot's avatar with its status as a corner badge, or the plain status dot for a -/// session and for a bot whose avatar file is missing. private struct AgentRunLeadingMark: View { let bot: AgentRunActivityBot? let status: AgentRunActivityStatus @@ -405,8 +383,6 @@ private struct AgentRunIslandStatusView: View { } } -/// The compact leading and minimal glyph. It names the working phase on its own, so -/// it carries the full status for VoiceOver (#1398). private struct AgentRunIslandCompactMark: View { let state: AgentRunActivityAttributes.ContentState let isBot: Bool @@ -429,8 +405,6 @@ private struct AgentRunIslandCompactMark: View { .accessibilityLabel(accessibilityLabel) } - /// "Hermex, Thinking". Stale work says it shows the latest status, or for a Bot - /// that it is disconnected; a stale Bot also says how to recover (#584). private var accessibilityLabel: String { let compact = AgentRunCompactPresentation(state: state) let stale = AgentRunStaleBotPresentation.presentation(state: state, isBot: isBot) @@ -447,9 +421,6 @@ private struct AgentRunIslandCompactMark: View { } } -/// Compact trailing: empty while working, one short word for an ask, an outcome, or -/// stale work (#1398). The leading mark already reads the full status, so VoiceOver -/// skips the word. private struct AgentRunCompactTrailingView: View { let state: AgentRunActivityAttributes.ContentState @Environment(\.agentRunPalette) private var palette @@ -535,12 +506,6 @@ private struct AgentRunElapsedTimerText: View { let startedAt: Date var alignment: TextAlignment = .trailing - // `Text(timerInterval:)` reserves layout width for the largest value its range - // could ever show, then draws the shorter live value leading-aligned inside that - // leftover slack — which left-shifted the digits in the Dynamic Island and the - // Lock Screen pill (#247). Bounding the range keeps an MM:SS-sized box, and an - // explicit `multilineTextAlignment` pins the digits to the edge each call site - // wants (trailing under the Dynamic Island status, centered in the pill). private static let maxDisplayInterval: TimeInterval = 99 * 60 + 59 var body: some View { @@ -555,30 +520,19 @@ private struct AgentRunElapsedTimerText: View { } } -/// Every color the Live Activity draws, chosen from the surface under it and from how the -/// system renders it (#1399). `agentRunPalette(on:)` builds one per surface; views read it -/// from the environment. Status glyphs and words carry status in every treatment. struct AgentRunPalette { - /// What the activity draws on. enum Surface { - /// The fixed near-black card: dark whatever the system appearance. case darkCard - /// System material or a host's own background (the iPhone Island, a Mac menu - /// bar): light or dark per the environment's `colorScheme`. case host - /// iOS 26 and later asks for system material; iOS 18–25 keeps the dark card. static var lockScreen: Surface { if #available(iOS 26, *) { .host } else { .darkCard } } - /// nil asks for the system default material. var backgroundTint: Color? { self == .darkCard ? AgentRunPalette.darkCardBackground : nil } var actionForeground: Color? { self == .darkCard ? .white : nil } } - /// Today's look: the dark card in full color. The environment default, and the - /// Island keyline's colors. static let dark = AgentRunPalette(surface: .darkCard, colorScheme: .dark, renderingMode: .fullColor, isLuminanceReduced: false, increasedContrast: false) @@ -587,18 +541,11 @@ struct AgentRunPalette { let primaryText: Color let secondaryText: Color let stroke: Color - /// Chip and timer pill fill: kept faint so the background shows through. let fill: Color - /// Rings the avatar's status badge so it reads as cut out of the background. let avatarOutline: Color private let isDark: Bool - /// Replaces every status hue: secondary when luminance is reduced (Always-On), - /// primary when the system tints or desaturates the activity. private let statusOverride: Color? - /// Rules in order: reduced luminance mutes status, accented or vibrant rendering - /// draws in hierarchical primary and secondary, and full color contrasts with the - /// actual background, which is always dark for the dark card. init(surface: Surface, colorScheme: ColorScheme, renderingMode: WidgetRenderingMode, isLuminanceReduced: Bool, increasedContrast: Bool) { isDark = surface == .darkCard || colorScheme == .dark @@ -625,14 +572,12 @@ struct AgentRunPalette { return isDark ? hue.dark : hue.light } - /// The working dot beside the timer. var liveDot: Color { statusOverride ?? (isDark ? Color(red: 0.35, green: 0.95, blue: 0.7) : Color(red: 0.06, green: 0.5, blue: 0.32)) } private static let neutral = (dark: Color.white.opacity(0.54), light: Color.black.opacity(0.45)) - /// Bright hues for dark backgrounds, darker variants of the same hue for light ones. private static func hue(for status: AgentRunActivityStatus) -> (dark: Color, light: Color) { switch status { case .starting, .thinking, .responding: @@ -660,13 +605,9 @@ struct AgentRunPalette { } extension EnvironmentValues { - /// Set by `agentRunPalette(on:)`; defaults to the dark card. @Entry var agentRunPalette = AgentRunPalette.dark } -/// Reads how the system draws this view and hands the matching palette down. The reads -/// live in a view modifier because ActivityConfiguration's builder closures get no -/// environment. private struct AgentRunPaletteScope: ViewModifier { let surface: AgentRunPalette.Surface @Environment(\.colorScheme) private var colorScheme diff --git a/HermesLiveActivityWidget/BotWidget.swift b/HermesLiveActivityWidget/BotWidget.swift index 22704eedb..04225fdab 100644 --- a/HermesLiveActivityWidget/BotWidget.swift +++ b/HermesLiveActivityWidget/BotWidget.swift @@ -2,11 +2,6 @@ import AppIntents import SwiftUI import WidgetKit -/// Bots on the Home Screen (#1643): a face and title per bot, each tap opening that bot's chat on -/// its own server. A small widget holds one bot (one tap target is all a small widget gets); a -/// medium holds a row of 4 and a large two rows of 4, in the order the user chose. Each instance -/// is configured from the app's snapshot (`BotWidgetSnapshot`); nothing here reads the network or -/// the Keychain, and each face is the PNG the app rendered. struct BotWidget: Widget { var body: some WidgetConfiguration { AppIntentConfiguration(kind: BotWidgetSnapshot.widgetKind, intent: BotWidgetConfigurationIntent.self, @@ -22,15 +17,11 @@ struct BotWidget: Widget { } struct BotWidgetEntry: TimelineEntry { - /// One bot's place on the widget. enum Slot: Equatable { - /// No bot chosen for it yet. case empty - /// The chosen bot or its server is no longer in the snapshot. case unavailable case bot(title: String, light: URL?, dark: URL?, destination: BotWidgetDestination) - /// Nil unless the bot is in the snapshot, so any other slot's tap opens the app as it is. var destination: URL? { if case .bot(_, _, _, let destination) = self { destination.url } else { nil } } @@ -39,8 +30,6 @@ struct BotWidgetEntry: TimelineEntry { let date: Date let slots: [Slot] - /// The entry for a configuration in `family`, read against the app's snapshot: one slot on a - /// small widget, else 4 per row, with unchosen slots left empty so the layout never reflows. init(date: Date, configuration: BotWidgetConfigurationIntent, family: WidgetFamily, file: BotWidgetSnapshotFile? = .shared) { self.date = date @@ -73,9 +62,6 @@ struct BotWidgetEntry: TimelineEntry { } } -/// A single entry: the snapshot only changes when the app writes it, and that reloads the widget. An -/// entry with an unavailable bot asks again hourly, since before the first unlock after a restart -/// the snapshot can't be read and every bot looks gone. struct BotWidgetTimeline: AppIntentTimelineProvider { func placeholder(in context: Context) -> BotWidgetEntry { let hermes = BotWidgetEntry.Slot.bot(title: String(localized: "Hermes"), light: nil, dark: nil, @@ -115,15 +101,12 @@ private struct BotWidgetView: View { } } - /// One bot of a row; a bot's own link, so each opens its own chat. @ViewBuilder private func cell(_ slot: BotWidgetEntry.Slot) -> some View { let view = BotWidgetSlotView(slot: slot, faceSize: 58, isSingle: false).frame(maxWidth: .infinity) if let url = slot.destination { Link(destination: url) { view } } else { view } } } -/// A slot's face and title. A small widget's single slot gets two title lines and a hint under an -/// empty or unavailable face; a row's slots get one line. private struct BotWidgetSlotView: View { @Environment(\.colorScheme) private var colorScheme let slot: BotWidgetEntry.Slot @@ -201,8 +184,6 @@ private struct BotWidgetSlotView: View { } } -/// A gray face: the fallback before the app renders a bot's avatar, and, with flat eyes, the -/// unavailable state. private struct BotWidgetPlainFace: View { let isFlat: Bool diff --git a/HermesLiveActivityWidget/ProviderLimitsWidget.swift b/HermesLiveActivityWidget/ProviderLimitsWidget.swift index 6824581be..f6aa581bc 100644 --- a/HermesLiveActivityWidget/ProviderLimitsWidget.swift +++ b/HermesLiveActivityWidget/ProviderLimitsWidget.swift @@ -1,11 +1,6 @@ import SwiftUI import WidgetKit -/// Provider limits on the Home Screen and Lock Screen (#1409), drawn from the snapshot the app -/// writes when Usage loads on a Hermes server (`ProviderLimitsSnapshot`). It makes no network or -/// Keychain call: opening Usage is the only refresh. Each window shows its percentage until the -/// earlier of its reset and an hour after its measurement, then asks to open Hermex; the timeline -/// has an entry at each of those instants rather than trusting WidgetKit to reload on time. struct ProviderLimitsWidget: Widget { var body: some WidgetConfiguration { StaticConfiguration(kind: ProviderLimitsSnapshot.widgetKind, provider: ProviderLimitsTimeline()) { entry in @@ -33,8 +28,6 @@ struct ProviderLimitsTimeline: TimelineProvider { completion(ProviderLimitsEntry(date: Date(), snapshot: ProviderLimitsSnapshotFile.shared?.read())) } - /// An entry now and one at every later instant a window expires, so each percentage goes on - /// time even when the system reloads late. func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) { let now = Date() let snapshot = ProviderLimitsSnapshotFile.shared?.read() @@ -45,11 +38,9 @@ struct ProviderLimitsTimeline: TimelineProvider { } } -/// One window as an entry draws it. private struct LimitReading { let provider: ProviderLimitsSnapshot.Provider let window: ProviderLimitsSnapshot.Window - /// Nil once the window expired. let percent: Double? init(_ provider: ProviderLimitsSnapshot.Provider, _ window: ProviderLimitsSnapshot.Window, at now: Date) { @@ -82,8 +73,6 @@ private struct ProviderLimitsWidgetView: View { } } - /// The window with the least left that still shows a percentage, else the one with the least - /// left when it was measured, shown as expired. private func tightest(in snapshot: ProviderLimitsSnapshot) -> LimitReading? { let readings = snapshot.providers.flatMap { provider in provider.windows.map { LimitReading(provider, $0, at: entry.date) } @@ -126,7 +115,6 @@ private struct SmallLimit: View { } } -/// Up to two providers side by side, two windows each. private struct MediumLimits: View { let snapshot: ProviderLimitsSnapshot let now: Date @@ -138,7 +126,6 @@ private struct MediumLimits: View { HStack { ProfileLabel(profile: snapshot.profile) Spacer(minLength: 8) - // The oldest measurement shown: a newer publication never makes it look fresh. if let measured = providers.compactMap(\.updatedAt).min() { Text("Updated \(shortMoment(measured, now: now))") .font(.caption2) @@ -199,7 +186,6 @@ private struct MediumRow: View { } } -/// The Lock Screen's rectangle: the tightest window, in the system's one-color rendering. private struct RectangularLimit: View { let reading: LimitReading let profile: String @@ -280,7 +266,6 @@ private struct WindowTitle: View { } } -/// The reset, or for a stale value still showing, when it was measured. private struct WindowFootnote: View { let reading: LimitReading let now: Date @@ -335,7 +320,6 @@ private struct ProfileLabel: View { } } -/// The remaining share, unanimated: it changes only between timeline entries. private struct LimitBar: View { @Environment(\.widgetRenderingMode) private var renderingMode @Environment(\.isLuminanceReduced) private var isLuminanceReduced @@ -359,9 +343,6 @@ private struct LimitBar: View { } } -/// The Usage card's tiers (`providerLimitTint`): accent, orange at 25% or less, red at 10% or -/// less, in full color only. Tinted and vibrant rendering draw it in primary and Always-On in -/// secondary, so the number and bar carry it alone. private struct LimitTint { let percent: Double let renderingMode: WidgetRenderingMode @@ -378,12 +359,10 @@ private struct LimitTint { private func clamped(_ percent: Double) -> Double { min(max(percent, 0), 100) } -/// "12%" for the small widget's large figure. private func percentText(_ percent: Double) -> String { (clamped(percent).rounded() / 100).formatted(.percent.precision(.fractionLength(0))) } -/// "3:40 PM" today, "Thu" within the week, "Nov 12" beyond. private func shortMoment(_ date: Date, now: Date) -> String { if Calendar.current.isDate(date, inSameDayAs: now) { return date.formatted(date: .omitted, time: .shortened) diff --git a/HermesMobile/AppIntents/HermexAppIntents.swift b/HermesMobile/AppIntents/HermexAppIntents.swift index 310121805..4cf525dd7 100644 --- a/HermesMobile/AppIntents/HermexAppIntents.swift +++ b/HermesMobile/AppIntents/HermexAppIntents.swift @@ -1,38 +1,20 @@ import AppIntents import Foundation -/// Bridges App Intents (which run outside the SwiftUI view tree) into the app's existing -/// deep-link router. An intent writes a `hermes-agent://…` URL here; `ContentView` observes -/// `pendingDeepLink` and feeds it through the same `handleOpenURL` path as an external URL, -/// so intent navigation reuses the share/session deep-link plumbing rather than inventing a -/// parallel one (issue #337). A shared singleton is the standard bridge because the intent -/// has no reference to the live view hierarchy. @MainActor @Observable final class AppIntentRouter { static let shared = AppIntentRouter() - /// Set by an App Intent, drained by `ContentView`. Holding it (rather than acting - /// immediately) lets the view consume it whether the intent fired before the view - /// appeared (cold launch) or after (warm launch). var pendingDeepLink: URL? private init() {} - /// Records a deep link for the view layer to route. No-op on a nil URL so callers can - /// pass the optional `HermesDeepLink` builders without unwrapping. func requestDeepLink(_ url: URL?) { guard let url else { return } pendingDeepLink = url } - /// Opens a new chat on `server`, in `profile` or the one its New Session uses, with `text` in - /// the composer for the user to review; nothing is sent (#1402). The text and its destination - /// wait in the app group's share inbox first, so a cold launch, a server switch or a sign-in - /// can't lose them, and only the bare share link travels as the deep link. Each call is its - /// own chat text, even for the same text. The Hermes home adds it to that Profile's new - /// session draft, after any unsent text, then opens it with a review notice naming `origin`. - /// Callers: the New Chat with Content intent, and About's Troubleshoot with Hermes (#1476). func openNewChat(prefilling text: String, server: URL, profile: String?, origin: ImportedTextOrigin = .shortcut, inbox: URL? = HermesShareDraft.containerURL(), now: Date = Date()) throws { guard let inbox else { throw NewChatWithContentError.storage } @@ -53,14 +35,10 @@ final class AppIntentRouter { } } -/// "New Chat" — opens Hermex on the New Chat composer, mirroring the in-app "+" button -/// (no server session is created until the first message). Available to the Action button, -/// Shortcuts, Spotlight, and Siri via `HermexShortcuts`. struct NewChatIntent: AppIntent { static var title: LocalizedStringResource = "New Chat" static var description = IntentDescription("Open Hermex on a new, empty chat.") - /// Foregrounds the app so the navigation can run in-process. static var openAppWhenRun: Bool = true @MainActor @@ -71,17 +49,10 @@ struct NewChatIntent: AppIntent { } } -/// "New Chat with Voice" — opens Hermex on the New Chat composer and auto-starts voice -/// dictation, so an Action-button press starts a hands-free chat (no second tap on the mic). -/// Routes through the same `AppIntentRouter`/deep-link plumbing as `NewChatIntent`, but on a -/// distinct host so the composer knows to begin listening once it's on screen (issue #338). -/// Mic/speech permission is handled by the existing dictation path: if access is undetermined -/// the system prompt appears, and if it's denied the composer shows a clear error instead. struct NewChatVoiceIntent: AppIntent { static var title: LocalizedStringResource = "New Chat with Voice" static var description = IntentDescription("Open Hermex on a new chat and start voice dictation.") - /// Foregrounds the app so the navigation — and the microphone — can run in-process. static var openAppWhenRun: Bool = true @MainActor @@ -92,17 +63,10 @@ struct NewChatVoiceIntent: AppIntent { } } -/// "New Chat in " — opens Hermex on a new chat pinned to a specific server profile -/// the user picks when configuring the Shortcut/Siri phrase (issue #339). The chosen -/// `ProfileEntity` is carried through the same `AppIntentRouter`/deep-link plumbing as the -/// other New Chat intents, on its own host (`new-chat-profile`) with the profile name as a -/// query item, so `PendingNewChatView` can create the session pinned to it. A Hermes server's -/// Profile (#1180) adds its server, and opens a new Hermes session there. struct NewChatInProfileIntent: AppIntent { static var title: LocalizedStringResource = "New Chat in Profile" static var description = IntentDescription("Open Hermex on a new chat pinned to a specific profile.") - /// Foregrounds the app so the navigation can run in-process. static var openAppWhenRun: Bool = true @Parameter(title: "Profile") @@ -123,14 +87,10 @@ struct NewChatInProfileIntent: AppIntent { } } -/// "New Chat with Content" — opens Hermex on a new chat with the Shortcut's text in the composer, -/// never sent (#1402): on a Hermes server's Profile, or the active Hermes server's New Session -/// Profile. A webui Profile can't take it. struct NewChatWithContentIntent: AppIntent { static var title: LocalizedStringResource = "New Chat with Content" static var description = IntentDescription("Open Hermex on a new chat with this text in the composer. Nothing is sent until you send it.") - /// Foregrounds the app so the user can review the text. static var openAppWhenRun: Bool = true @Parameter(title: "Content", inputOptions: String.IntentInputOptions(multiline: true)) @@ -154,7 +114,6 @@ struct NewChatWithContentIntent: AppIntent { return .result() } - /// The chosen Hermes Profile, else the active server when it is a Hermes server. static func destination(profile: ProfileEntity?, active: URL?, servers: [ServerAccount]) throws -> (server: URL, profile: String?) { if let profile { @@ -168,7 +127,6 @@ struct NewChatWithContentIntent: AppIntent { } } -/// Why New Chat with Content opened nothing; Shortcuts shows the message. enum NewChatWithContentError: Error, Equatable, CustomLocalizedStringResourceConvertible { case empty case tooLong @@ -187,10 +145,6 @@ enum NewChatWithContentError: Error, Equatable, CustomLocalizedStringResourceCon } } -/// Registers Hermex's App Shortcuts. iOS discovers this conformance automatically at build -/// time — it does not need to be referenced from the `App` struct. Exposing the intent here -/// is what makes "New Chat" appear in the Shortcuts app, Spotlight, and Siri, and assignable -/// to the iPhone Action button. struct HermexShortcuts: AppShortcutsProvider { static var appShortcuts: [AppShortcut] { AppShortcut( @@ -236,29 +190,21 @@ struct HermexShortcuts: AppShortcutsProvider { } extension SharedShortcutDestination { - /// The new chat for this text on the Hermes server it names; nil once that server is gone. func newChat(in servers: [ServerAccount]) -> HermesNewChatDestination? { servers.lazy.filter { $0.kind == .hermes }.compactMap { URL(string: $0.id) }.first(where: opens(on:)) .map { HermesNewChatDestination(server: $0, profile: profile) } } } -/// A new Hermes session a Shortcut asked for (#1180): New Chat or New Chat with Voice on the -/// active Hermes server, or New Chat in Profile on a Hermes server's Profile. `ContentView` -/// holds it until its server is active and signed in; that server's Sessions list then opens it. struct HermesNewChatDestination: Hashable { let server: URL - /// The Profile to start in; nil takes the one the Sessions list's New Session uses. let profile: String? var autoStartsVoiceInput = false - /// Fresh per request, so running the same Shortcut again opens another chat. let id = UUID() enum Route: Equatable { - /// The server isn't a configured Hermes server: the app opens as it is. case ignore case waitForSignIn - /// Make the server active first; the rebuilt home takes the held request. case switchServer(ServerAccount) case open } @@ -269,8 +215,6 @@ struct HermesNewChatDestination: Hashable { self.autoStartsVoiceInput = autoStartsVoiceInput } - /// Parses a Hermes Profile's `new-chat-profile?server=…&profile=…`. Nil for any other link, - /// including a bare `new-chat-profile?profile=…`, which keeps its webui route (#971). init?(url: URL) { guard HermesDeepLink.isNewChatInProfileURL(url), let raw = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems? @@ -280,16 +224,12 @@ struct HermesNewChatDestination: Hashable { self.init(server: server, profile: profile) } - /// The server a Hermes Profile's id or link names: an absolute `http(s)` URL, as the registry - /// stores it. static func server(_ raw: String) -> URL? { guard let url = URL(string: raw), ["http", "https"].contains(url.scheme?.lowercased() ?? ""), url.host?.isEmpty == false else { return nil } return url } - /// New Chat and New Chat with Voice on the active server when it is a Hermes server, signed in - /// or not; nil on a webui server, whose New Chat is unchanged. @MainActor static func onActiveServer(state: AuthManager.State, servers: [ServerAccount], autoStartsVoiceInput: Bool) -> Self? { guard let active = state.server, @@ -297,7 +237,6 @@ struct HermesNewChatDestination: Hashable { return Self(server: active, profile: nil, autoStartsVoiceInput: autoStartsVoiceInput) } - /// Decided by the registry and auth state alone, as a session link is (`HermesSessionLinkRouter`). @MainActor func route(state: AuthManager.State, servers: [ServerAccount]) -> Route { guard let account = servers.first(where: { $0.id == server.absoluteString }), account.kind == .hermes else { return .ignore @@ -307,9 +246,6 @@ struct HermesNewChatDestination: Hashable { return .waitForSignIn } - /// The chat `entry`'s Sessions list opens: in this request's Profile, else `listed`, the one - /// its New Session uses. Nil for another server's list, and until the list `isLive`, having - /// read the host and showing no offline cache, whatever Profile the request names. @MainActor func chat(on entry: HermesSessionListEntry, listed: String?, isLive: Bool) -> HermesSessionChat? { guard entry.server == server, isLive, let profile = profile ?? listed else { return nil } return HermesSessionChat(server: server, connection: entry.connection, target: .new(profile: profile), diff --git a/HermesMobile/AppIntents/ProfileEntity.swift b/HermesMobile/AppIntents/ProfileEntity.swift index a353fdc2c..3eecd2d98 100644 --- a/HermesMobile/AppIntents/ProfileEntity.swift +++ b/HermesMobile/AppIntents/ProfileEntity.swift @@ -1,19 +1,9 @@ import AppIntents import Foundation -/// An App Intents value standing in for a server profile, so an intent can take "which -/// profile" as a parameter the user picks while configuring a Shortcut / Siri phrase -/// (issue #339). This is the *shared* entity issue #8 (profile widgets) reuses — whichever -/// of #339/#8 ships first owns it, the other reuses it, so the picker plumbing isn't -/// duplicated. struct ProfileEntity: AppEntity, Identifiable, Equatable { - /// A webui profile's server name (e.g. `default`, `dev`): the stable identifier the deep link - /// and `createSession(profile:)` use to pin a new chat to this profile. A Hermes server's - /// Profile is `|` (#1180), so the same name on two servers is two choices. let id: String - /// Human-facing label, mirroring `ProfileSummary.displayName` (so `default` → "Default"). let name: String - /// Optional one-line subtitle for the picker (model · provider), best-effort. let subtitle: String? static var typeDisplayRepresentation: TypeDisplayRepresentation { @@ -31,9 +21,6 @@ struct ProfileEntity: AppEntity, Identifiable, Equatable { } extension ProfileEntity { - /// A Hermes server's Profile (#1180), titled by the name its Bots roster last showed, with the - /// Profile's own name and its `model` (#1679) under it; one the roster never named is titled - /// by its own name alone. init(hermesServer server: URL, profile: String, title: String?, model: String? = nil) { let shown = title?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" let model = model?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" @@ -43,8 +30,6 @@ extension ProfileEntity { subtitle = details.isEmpty ? nil : details.joined(separator: " · ") } - /// The new Hermes session this Profile opens (#1180); nil for a webui profile's bare id, which - /// keeps the webui route a Shortcut saved before #1180 has (#971). var hermesNewChat: HermesNewChatDestination? { guard let bar = id.firstIndex(of: "|"), let server = HermesNewChatDestination.server(String(id[.. [ProfileEntity] { await ProfileEntityProvider.entities(for: identifiers) } - /// One server's choices are one untitled section. func suggestedEntities() async throws -> IntentItemCollection { let sections = await ProfileEntityProvider.sections() guard sections.count > 1 else { return IntentItemCollection(items: sections.first?.profiles ?? []) } @@ -89,22 +65,13 @@ struct ProfileEntityQuery: EntityQuery { } } -/// One server's part of the Profile picker (#1180), titled by the server's name. struct ProfileEntitySection: Equatable { let title: String let profiles: [ProfileEntity] } -/// Resolves the current profile list for App Intents, live-first with a cached fallback. -/// Kept separate from the `EntityQuery` so the fetch/cache policy is reusable (e.g. by #8). enum ProfileEntityProvider { - /// The webui server's profiles (`profileServer`), live-first with a cached fallback. static func currentEntities() async -> [ProfileEntity] { - // A successful fetch always mirrors into the cache: a non-empty result is stored and - // returned, while an empty result clears the cache (the server genuinely has no - // profiles) so a stale list can't linger. A *failed* fetch (nil) leaves the cache - // untouched, so a transient network/auth blip falls back to the last-known profiles - // instead of emptying the picker. if let live = try? await fetchLiveProfiles() { ProfileEntityCache.shared.save(live) if !live.isEmpty { return live.compactMap(ProfileEntity.init) } @@ -112,11 +79,6 @@ enum ProfileEntityProvider { return ProfileEntityCache.shared.loadEntities() } - /// The picker's sections, one per configured server in the registry's order (#1180): a - /// Hermes server's Profiles as its public `/api/status` names them (no sign-in from here), - /// else as its Bots roster last cached them, and the webui server `profileServer` picks, - /// whose bare ids New Chat in Profile opens wherever they always have. Every server is read - /// at once; one with nothing to list has no section. @MainActor static func sections( servers: [ServerAccount] = ServerRegistry.shared.servers, active: URL? = savedServerURL(), names: HermesProfileNameCache = .shared, @@ -154,11 +116,6 @@ enum ProfileEntityProvider { } } - /// Saved Shortcuts' Profiles. A Hermes id resolves from the id itself while its server is - /// configured, titled from the cached roster without reading the host; a bare id resolves - /// against the webui list as it always has (#971), or while a webui server's move to Hermes - /// named it, even after that server is removed (#1217). Running it then decides where it goes - /// (`MovedWebuiRoute.newChat`), and opens nothing where more than one place could take it. @MainActor static func entities( for identifiers: [String], servers: [ServerAccount] = ServerRegistry.shared.servers, names: HermesProfileNameCache = .shared, webui: () async -> [ProfileEntity] = { await currentEntities() } @@ -176,8 +133,6 @@ enum ProfileEntityProvider { } } - /// The Profile names a Hermes server's public `/api/status` reports, read with the Connection - /// Headers its saved sign-in carries, as every request to it does. Nil when it can't be read. @MainActor static func liveProfileNames(of account: ServerAccount, probe: BotHostStatusProbe = BotHostStatusProbe()) async -> [String]? { guard let server = URL(string: account.urlString) else { return nil } @@ -186,22 +141,11 @@ enum ProfileEntityProvider { return status.profiles } - /// The server's name as its avatar's switcher shows it: its display name, else its host. private static func name(of account: ServerAccount) -> String { let name = account.displayName.trimmingCharacters(in: .whitespacesAndNewlines) return name.isEmpty ? URL(string: account.urlString)?.host ?? account.urlString : name } - /// Best-effort live fetch against the saved server. Returns `[]` (not an error) when no - /// server is configured; a network/auth failure throws so the caller falls back to cache. - /// - /// Runs out-of-process (App Intents), where `CustomHeaderStore.shared` — which - /// `AuthManager` hydrates only on a foreground launch — is empty. So we read the server's - /// custom headers straight from the Keychain (reachable cross-process) and pass them - /// explicitly; otherwise a reverse proxy that authenticates on a header rejects this fetch - /// and the picker can never refresh live. (The session cookie is also absent out-of-process, - /// so a cookie-auth server still falls back to the cache — this just stops the ad-hoc client - /// from silently dropping the headers every other client in the app carries.) private static func fetchLiveProfiles() async throws -> [ProfileSummary] { guard let server = profileServer(active: savedServerURL(), servers: ServerRegistry.shared.servers) else { return [] } let headers = customHeaders(for: server) @@ -209,19 +153,12 @@ enum ProfileEntityProvider { return response.profiles ?? [] } - /// The webui server whose Profiles Shortcuts lists: the active one, or while a Hermes - /// server is active the first webui server, which New Chat in Profile switches to. - /// Nil when no webui server is configured. A webui server that moved to Hermes still lists - /// here; running its Profile's Shortcut follows the move (`MovedWebuiRoute.newChat`, #1217). static func profileServer(active: URL?, servers: [ServerAccount]) -> URL? { guard let active else { return nil } guard servers.first(where: { $0.id == active.absoluteString })?.kind == .hermes else { return active } return servers.first { $0.kind == .webui }.flatMap { URL(string: $0.urlString) } } - /// Loads the server's stored custom headers (scoped key first, then the pre-#16 global - /// blob) without mutating the Keychain — mirrors `AuthManager.hydrateCustomHeaders`, but - /// read-only since this runs in the App Intents process. private static func customHeaders(for server: URL) -> [CustomHeader] { let keychain = KeychainStore() let stored: String? @@ -243,15 +180,6 @@ enum ProfileEntityProvider { @MainActor private static var didRefreshAppShortcutsThisLaunch = false - /// Nudges the system to re-read `suggestedEntities()` so a freshly loaded profile list - /// surfaces (or updates) the parameterized "New Chat in " App Shortcut. iOS only - /// indexes a parameterized App Shortcut once its suggested values exist, so without this - /// call the shortcut never appears — the parameter-less New Chat shortcuts show, but this - /// one doesn't until the system re-queries (#339). - /// - /// Fires on the first profile load of each app launch (so the shortcut re-registers after - /// an app reinstall / index reset, even when the profile list itself is unchanged) and on - /// any later change — but not on every redundant reload, to avoid needless re-indexing. @MainActor static func refreshAppShortcuts(changed: Bool) { guard changed || !didRefreshAppShortcutsThisLaunch else { return } @@ -260,26 +188,16 @@ enum ProfileEntityProvider { } } -/// Persists the last-known profile list to the app-group container so an App Intents query -/// (and #8's widgets, which run out-of-process) can populate their picker without a live, -/// authenticated server call. The app refreshes this on every foreground profiles load. struct ProfileEntityCache { static let shared = ProfileEntityCache() private let defaults: UserDefaults? - // `.v2`: bumped from v1 when the App Shortcut refresh nudge was added, so the first load - // on an upgraded install reads an empty cache and is treated as a change — which fires - // `updateAppShortcutParameters()` once even though the profile list itself is unchanged. private let storageKey = "cachedProfileEntities.v2" init(defaults: UserDefaults? = UserDefaults(suiteName: HermesShareDraft.appGroupIdentifier)) { self.defaults = defaults } - /// Mirrors the profiles into the cache: writes a compact snapshot when non-empty, clears - /// the entry when empty so a stale list can't linger after the server reports none. - /// Returns whether the stored snapshot actually changed, so the caller can avoid - /// re-indexing App Shortcuts when nothing moved. @discardableResult func save(_ profiles: [ProfileSummary]) -> Bool { guard let defaults else { return false } @@ -310,8 +228,6 @@ struct ProfileEntityCache { } } -/// Minimal codable snapshot of a profile for the cache — deliberately decoupled from the -/// server model so an upstream shape change can't break a cached read. private struct CachedProfile: Codable, Equatable { let id: String let name: String @@ -329,16 +245,10 @@ private struct CachedProfile: Codable, Equatable { } } -/// The Profile names, and models (#1679), each Hermes server's Bots roster last showed (#1180), in the app-group -/// container, so the Shortcuts picker titles a host's Profiles as the app does and still lists -/// them while the host can't be read or is signed out. One entry per server, keyed by a digest of -/// its URL so the app group holds no server URL, written on every roster read and deleted with -/// the server. struct HermesProfileNameCache { struct Name: Codable, Equatable { let profile: String let title: String - /// The Profile's model (#1679); optional, so an entry saved before it still decodes. var model: String? = nil } @@ -350,8 +260,6 @@ struct HermesProfileNameCache { self.defaults = defaults } - /// Replaces `server`'s names, an empty roster clearing them, and returns whether they changed, - /// so the caller re-indexes App Shortcuts only then. @discardableResult func save(_ names: [Name], for server: URL) -> Bool { guard let defaults, names != self.names(for: server) else { return false } diff --git a/HermesMobile/Auth/AppLock.swift b/HermesMobile/Auth/AppLock.swift index ade84eb6d..97f473a59 100644 --- a/HermesMobile/Auth/AppLock.swift +++ b/HermesMobile/Auth/AppLock.swift @@ -1,7 +1,6 @@ import Foundation import LocalAuthentication -/// What the device can unlock Hermex with right now. struct AppLockCapability: Equatable { enum Method: Equatable { case faceID @@ -9,45 +8,18 @@ struct AppLockCapability: Equatable { case passcode } - /// What the Settings label and the Unlock button name. var method: Method - /// iOS can't authenticate at all without a device passcode. var hasPasscode: Bool } -/// Face ID, Touch ID or the device passcode. `AppLock` asks through this so tests can fake it. @MainActor protocol AppLockAuthenticator { func capability() -> AppLockCapability - /// Prompts once; true only when the device owner authenticated. func authenticate(reason: String) async -> Bool } -/// The optional app lock (#885): one Settings toggle, off by default, app-wide rather than -/// per server, so it lives in `UserDefaults`. `AppLockSceneDelegate` feeds it the scene's -/// phases and shows its window whenever `showsLockWindow` is true. -/// -/// - With the lock on, a cold launch is locked, and so is becoming active more than -/// `relockDelay` after entering the background. The time runs on `ContinuousClock`, so the -/// phone sleeping counts and changing the clock doesn't. Inactive and back (Control -/// Center, the Face ID sheet) never locks. -/// - While on, the scene is covered whenever it isn't active, so the app switcher snapshot -/// and Control Center show the app icon instead of a chat. The lock's own Face ID or -/// passcode sheet doesn't cover. -/// - When locked, it prompts once by itself as the scene becomes active; after a cancel or -/// failure only the Unlock button tries again. -/// - Turning the lock on or off needs a successful authentication. It can't be turned on -/// without a device passcode. If the passcode is removed while it's on, the lock says so and -/// Continue turns it off: it never opens silently. -/// - It is a cover, not a gate: the app stays mounted behind it, so streams, Live Activities -/// and reconnects keep running, and deep links, App Intents, notification taps and share -/// handoffs land behind it. While locked, keyboard commands are off, "New Chat with Voice" -/// holds dictation, and push presence reports no chat on screen. -/// - It can't cover other processes: notifications, Live Activities and the share sheet still -/// show their content, as the Settings footer says. @MainActor @Observable final class AppLock { static let shared = AppLock() static let enabledKey = "appLockEnabled" - /// Background time after which becoming active locks again. static let relockDelay: Duration = .seconds(60) private enum Phase { @@ -58,7 +30,6 @@ struct AppLockCapability: Equatable { private(set) var isEnabled: Bool private(set) var isLocked: Bool - /// The lock is on but the device has no passcode, so nothing can unlock it. private(set) var isPasscodeMissing = false private(set) var isAuthenticating = false private(set) var capability: AppLockCapability @@ -69,8 +40,6 @@ struct AppLockCapability: Equatable { @ObservationIgnored private var backgroundedAt: ContinuousClock.Instant? @ObservationIgnored private var didPromptForThisLock = false private var phase = Phase.inactive - /// A prompt of ours may be holding the scene inactive: set when one starts, cleared once - /// the scene is active with no prompt running, or in the background. private var promptHoldsScene = false init( @@ -85,11 +54,9 @@ struct AppLockCapability: Equatable { self.now = now self.isEnabled = isEnabled isLocked = isEnabled - // With the lock off, Settings asks when it appears; nothing touches LocalAuthentication at launch. capability = isEnabled ? authenticator.capability() : AppLockCapability(method: .passcode, hasPasscode: true) } - /// The scene isn't active and the lock is on. var isCovered: Bool { guard isEnabled else { return false } switch phase { @@ -111,8 +78,6 @@ struct AppLockCapability: Equatable { backgroundedAt = now() } - /// Locks if the scene was in the background too long, then prompts if this lock hasn't yet. - /// Returns that prompt so tests can wait for it. @discardableResult func sceneDidBecomeActive() -> Task? { phase = .active @@ -125,14 +90,12 @@ struct AppLockCapability: Equatable { guard isLocked, !isAuthenticating else { return nil } refreshCapability() - // Checked on every return, so a passcode set again brings the lock back. isPasscodeMissing = !capability.hasPasscode guard !isPasscodeMissing, !didPromptForThisLock else { return nil } didPromptForThisLock = true return Task { await unlock() } } - /// The Unlock button, and the automatic prompt. func unlock() async { guard isLocked, !isPasscodeMissing, !isAuthenticating else { return } didPromptForThisLock = true @@ -144,18 +107,15 @@ struct AppLockCapability: Equatable { } } - /// Continue on the "can't lock" note: the passcode is gone, so the lock turns off. func continueWithoutPasscode() { guard isPasscodeMissing else { return } store(enabled: false) } - /// The Settings toggle. Authenticates first, and leaves the lock as it was on failure. func setEnabled(_ enabled: Bool) async { guard enabled != isEnabled, !isAuthenticating else { return } refreshCapability() guard capability.hasPasscode else { - // Nothing can authenticate without a passcode, and only the owner can remove one. if !enabled { store(enabled: false) } return } @@ -189,8 +149,6 @@ struct AppLockCapability: Equatable { } } -/// `LocalAuthentication` with a fresh `LAContext` per call, so one attempt's result never -/// carries into the next. struct DeviceAppLockAuthenticator: AppLockAuthenticator { func capability() -> AppLockCapability { let context = LAContext() @@ -200,7 +158,6 @@ struct DeviceAppLockAuthenticator: AppLockAuthenticator { var passcodeError: NSError? let hasPasscode = context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &passcodeError) || passcodeError?.code != LAError.passcodeNotSet.rawValue - // Without a passcode biometry can't be enrolled, so name the hardware, as iOS Settings does. guard canUseBiometry || !hasPasscode else { return AppLockCapability(method: .passcode, hasPasscode: hasPasscode) } @@ -212,7 +169,6 @@ struct DeviceAppLockAuthenticator: AppLockAuthenticator { return AppLockCapability(method: method, hasPasscode: hasPasscode) } - /// Face ID or Touch ID, falling back to the passcode. func authenticate(reason: String) async -> Bool { let context = LAContext() return await withCheckedContinuation { continuation in diff --git a/HermesMobile/Auth/AppLockWindow.swift b/HermesMobile/Auth/AppLockWindow.swift index dbb190976..bec6cdc5b 100644 --- a/HermesMobile/Auth/AppLockWindow.swift +++ b/HermesMobile/Auth/AppLockWindow.swift @@ -1,21 +1,11 @@ import SwiftUI import UIKit -/// Puts `AppLock`'s window on the app's one window scene (#885). `PushAppDelegate` names -/// this class in the scene configuration; SwiftUI still creates and owns the app window and -/// forwards the scene's lifecycle calls here. -/// -/// The window sits above alerts, so it also covers sheets, full-screen covers, alerts and -/// menus, which an overlay on `ContentView` would sit under. It appears in the same call -/// that reports the phase, before the first frame of a cold launch and before the app -/// switcher snapshot, with no animation. @MainActor final class AppLockSceneDelegate: NSObject, UIWindowSceneDelegate { private let lock = AppLock.shared private var lockWindow: UIWindow? private var lockHost: UIHostingController? - /// The app window that was key when the lock appeared; it is key again when the lock goes. private weak var coveredKeyWindow: UIWindow? - /// The text input that last had the keyboard behind the lock; it gets it back after. private weak var coveredTextInput: UIResponder? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { @@ -28,7 +18,6 @@ import UIKit host.view.backgroundColor = .appCanvas window.tintColor = .appAccent window.rootViewController = host - // VoiceOver reads only the lock while it is up. window.accessibilityViewIsModal = true lockWindow = window lockHost = host @@ -57,7 +46,6 @@ import UIKit update() } - /// Follows changes that don't come with a scene call: an unlock, Continue, or the toggle. private func followLock() { withObservationTracking { _ = lock.showsLockWindow @@ -69,12 +57,8 @@ import UIKit } } - /// Something behind the lock took the keyboard after it appeared, such as the composer of - /// a new chat an App Intent or share opened: it goes until the lock does, like one that was - /// focused before, so no keys (⌘↩ included) reach the hidden app. @objc private func textInputDidBeginEditing(_ notification: Notification) { guard let window = lockWindow, !window.isHidden, let input = notification.object as? UIResponder else { return } - // On the next turn: resigning inside the begin-editing call leaves UIKit half done. Task { @MainActor [weak self, weak input] in guard let self, let input, input.isFirstResponder, let window = lockWindow, !window.isHidden else { return } @@ -89,18 +73,15 @@ import UIKit if lock.showsLockWindow { if window.isHidden { coveredKeyWindow = scene.keyWindow - // The keyboard sits above every window, so it goes until the lock does. if let input = UIResponder.currentFirstResponder, input is UIKeyInput { coveredTextInput = input input.resignFirstResponder() } - // The icon can change in Settings, which SwiftUI doesn't observe. lockHost?.rootView = AppLockView(lock: lock, icon: .current) window.overrideUserInterfaceStyle = Self.themeStyle window.isHidden = false UIAccessibility.post(notification: .screenChanged, argument: nil) } - // SwiftUI may make its own window key after ours appears on a cold launch. if !window.isKeyWindow { window.makeKey() } } else if !window.isHidden { window.isHidden = true @@ -116,7 +97,6 @@ import UIKit } } - /// The Color Scheme setting, which the app window gets through `preferredColorScheme`. private static var themeStyle: UIUserInterfaceStyle { switch AppTheme.storedValue(UserDefaults.standard.string(forKey: AppTheme.storageKey) ?? "") { case .system: .unspecified @@ -129,7 +109,6 @@ import UIKit private extension UIResponder { private static weak var found: UIResponder? - /// The key window's first responder, found by sending an action to no target. static var currentFirstResponder: UIResponder? { found = nil UIApplication.shared.sendAction(#selector(hermexRecordFirstResponder), to: nil, from: nil, for: nil) @@ -141,13 +120,8 @@ private extension UIResponder { } } -/// The lock window's content: the lock or the "can't lock" note while the scene is active, and -/// the app icon alone whenever it's covered, locked or not, so the app switcher never shows the -/// Unlock button. The icon stays in the same spot, so switching needs no motion. -/// Static: nothing animates or repaints. struct AppLockView: View { let lock: AppLock - /// The user's chosen app icon, read each time the window appears. let icon: AppIconChoice @Environment(\.dynamicTypeSize) private var dynamicTypeSize @@ -158,7 +132,6 @@ struct AppLockView: View { VStack(spacing: 0) { AppLockIcon(choice: icon) - // Covered, it's the icon alone. if !lock.isCovered { if lock.isPasscodeMissing { passcodeMissing @@ -218,7 +191,6 @@ struct AppLockView: View { } extension AppLockCapability.Method { - /// The glyph beside Unlock and on the Settings toggle. var systemImage: String { switch self { case .faceID: "faceid" @@ -228,7 +200,6 @@ extension AppLockCapability.Method { } } -/// The user's chosen app icon, as the Settings icon picker previews it. private struct AppLockIcon: View { let choice: AppIconChoice @@ -252,7 +223,6 @@ private struct AppLockIcon: View { } } -/// Settings' button look, sized to its title rather than the full width. private struct AppLockButton: View { let title: String let systemImage: String? diff --git a/HermesMobile/Auth/AuthManager+MoveToHermes.swift b/HermesMobile/Auth/AuthManager+MoveToHermes.swift index e2c6105a0..37dc9a092 100644 --- a/HermesMobile/Auth/AuthManager+MoveToHermes.swift +++ b/HermesMobile/Auth/AuthManager+MoveToHermes.swift @@ -1,48 +1,17 @@ import Foundation -/// Move to Hermes's commit point (#1215, part of #707): one acknowledged Keychain write that -/// adds or adopts the Hermes destination and records which webui server moved there. -/// -/// The record lives on the destination's registry entry (`ServerAccount.movedWebuiServers`), so -/// it survives removing the webui entry, survives signing out of the destination, and goes when -/// the destination is removed: `removeServer` and `signOut` need nothing of their own for it. -/// The commit never switches the active server (the guided flow does that at Done, #1218) and -/// never reads or writes a push pairing: `MovePushPairing.carry` is the runner's first step -/// after it (#1216). extension AuthManager { enum MoveCommitError: Error, Equatable { - /// The source isn't a configured webui server. case sourceNotWebui - /// The destination has the source's address. That host moved in place, which - /// `replaceWebuiServer` handles (#1027). case sameAddress - /// A webui server is configured at the destination's address. case destinationNotHermes - /// The destination is configured but signed out, so the move couldn't run on it. case destinationSignedOut - /// Another Hermes server already holds this webui server's record. case sourceAlreadyMoved(destinationID: String) - /// No Profile was mapped, or one webui Profile was mapped twice. case invalidMapping - /// No Hermes server holds a record for this webui server. case recordMissing - /// The Keychain didn't save the change, so nothing was committed. case saveFailed } - /// Commits a move of `source` to the Hermes server at `connection`'s address, with the - /// Profile mappings chosen at Review, and returns the destination's entry. - /// - /// - A Hermes server already configured there is adopted: it gains the record, and its - /// own sign-in, name, initials, color, headers, preferences and pairing stay as they - /// are. `connection` is ignored, and the server must have a saved sign-in. - /// - Otherwise a new Hermes server is added with `connection` as its sign-in and the - /// source's name, initials and color. Webui custom headers are never copied. - /// - /// Calling it again for a move this destination already holds returns the entry and - /// changes nothing. When the Keychain refuses either write, it throws and leaves the - /// registry and `servers` as they were, and puts back what was saved at a new server's - /// address (`restoreSignIn`). @discardableResult func commitMove(from source: ServerAccount, to connection: BotConnection, profiles: [MovedWebuiProfile]) throws -> ServerAccount { @@ -62,8 +31,6 @@ extension AuthManager { guard (try? bots.load(server: destinationURL)) != nil else { throw MoveCommitError.destinationSignedOut } } - // A new server's sign-in is saved before its entry, so a committed entry always has - // one. If the entry isn't saved, whatever was saved at that address is put back. let previousSignIn = adopting ? nil : try? bots.load(server: destinationURL) if !adopting { do { try bots.save(connection, server: destinationURL) } catch { throw MoveCommitError.saveFailed } @@ -73,7 +40,6 @@ extension AuthManager { let committed: ServerAccount do { committed = try serverRegistry.commit { servers, now in - // Checked again under the registry's lock, against what it holds now. try Self.checkMove(of: source.id, to: destinationID, in: servers) if let index = servers.firstIndex(where: { $0.id == destinationID }) { guard !servers[index].movedWebuiServers.contains(where: { $0.sourceServerID == source.id }) else { @@ -83,7 +49,6 @@ extension AuthManager { servers[index].updatedAt = now return servers[index] } - // The source's identity as the registry holds it, not as a screen last read it. let identity = servers.first { $0.id == source.id } ?? source let added = ServerAccount( id: destinationID, urlString: destinationID, @@ -104,8 +69,6 @@ extension AuthManager { return committed } - /// The Hermes server holding `sourceID`'s move record, with the record, or nil when - /// that webui server never moved or its destination was removed. func moveRecord(forSource sourceID: String) -> (destination: ServerAccount, record: MovedWebuiServer)? { for server in servers { if let record = server.movedWebuiServers.first(where: { $0.sourceServerID == sourceID }) { @@ -115,9 +78,6 @@ extension AuthManager { return nil } - /// Changes `sourceID`'s move record, such as its completion or report, with the same - /// acknowledged write as the commit. Throws, changing nothing, when no Hermes server - /// holds the record or the Keychain didn't save it. The record's source can't change. func updateMoveRecord(forSource sourceID: String, _ change: (inout MovedWebuiServer) -> Void) throws { do { try serverRegistry.commit { servers, now in @@ -133,16 +93,8 @@ extension AuthManager { refreshServers() } - // MARK: The one-time question (#1267) - - /// Whether the one-time question is due: the signed-in active server is a webui server that - /// was never asked, has no move record and isn't being removed, and no move sheet has shown - /// this launch. Another webui server waits for a launch with it active. The root asks once - /// nothing else is presented (`askAboutMoveIfDue`). var isMoveQuestionDue: Bool { dueMoveQuestionSource != nil } - /// Asks the question when it is due. Asking marks the server asked, so its banner follows - /// and a quit mid-question doesn't ask again. func askAboutMoveIfDue() { guard let source = dueMoveQuestionSource, let sourceURL = URL(string: source.id) else { return } askedAboutMoveThisLaunch = true @@ -159,16 +111,12 @@ extension AuthManager { return active } - /// Whether `serverID`'s chat list shows "Move to Hermes": a webui server asked but - /// not dismissed, with no move record, whose Paused, Finished and Moved banners speak instead. func showsMoveInvite(for serverID: String) -> Bool { guard let server = servers.first(where: { $0.id == serverID }), server.kind == .webui, server.moveToHermesPrompt == .asked else { return false } return moveRecord(forSource: serverID) == nil } - /// Moves `sourceID`'s question forward to `prompt`; never back, so a dismissed banner stays - /// dismissed. Best effort: a refused Keychain write leaves the server as it was. func noteMovePrompt(_ prompt: MoveToHermesPrompt, forSource sourceID: String) { guard let server = servers.first(where: { $0.id == sourceID && $0.kind == .webui }), server.moveToHermesPrompt != prompt, server.moveToHermesPrompt != .dismissed else { return } @@ -179,14 +127,10 @@ extension AuthManager { refreshServers() } - /// Why `sourceID` can't move to `destinationID` given `servers`, or nothing when it can. - /// A record this destination already holds is not a conflict: the commit returns it. private static func checkMove(of sourceID: String, to destinationID: String, in servers: [ServerAccount]) throws { guard servers.contains(where: { $0.id == sourceID && $0.kind == .webui }) else { throw MoveCommitError.sourceNotWebui } - // A webui id keeps its host's case and a Hermes address lowercases it, so compare them - // the way a Hermes address is normalized. func asHermesAddress(_ id: String) -> String { (try? BotConnection.address(id))?.absoluteString ?? id } guard asHermesAddress(sourceID) != destinationID else { throw MoveCommitError.sameAddress } if servers.contains(where: { $0.kind != .hermes && asHermesAddress($0.id) == destinationID }) { @@ -199,10 +143,6 @@ extension AuthManager { } } - /// Puts back the sign-in saved at `server` before a failed commit wrote its own, or - /// removes it when there was none. Best effort: `server` has no registry entry here, so - /// whatever a failed rollback leaves is read by nothing, and adding the server later - /// replaces it. private func restoreSignIn(_ previous: BotConnection?, at server: URL) { let bots = BotConnectionStore(keychain: keychain) if let previous { diff --git a/HermesMobile/Auth/AuthManager.swift b/HermesMobile/Auth/AuthManager.swift index caf7a4818..d473128bd 100644 --- a/HermesMobile/Auth/AuthManager.swift +++ b/HermesMobile/Auth/AuthManager.swift @@ -9,8 +9,6 @@ final class AuthManager { case loggedOut(server: URL) case loggedIn(server: URL) - /// The server this state refers to, if any — used to scope sign-out and - /// session-expiry to the active server (#16). `unconfigured` has none. var server: URL? { switch self { case .unconfigured: return nil @@ -19,34 +17,17 @@ final class AuthManager { } } - /// Shown when a server has auth on but explicitly reports password auth off, - /// i.e. it signs in with passkeys (which we can't do yet). See issue #255. nonisolated static let passkeyOnlyMessage = String(localized: "This server signs in with passkeys, which Hermex doesn't support yet.") - /// Single sign-on. Hermex cannot run the OIDC redirect flow yet, and an - /// external browser's session is not shared with the app. nonisolated static let oidcOnlyMessage = String(localized: "This server signs in with single sign-on, which Hermex doesn't support yet.") - /// Trusted-header mode where the proxy did *not* authenticate this request, - /// so the server reports the mode but not a session. nonisolated static let trustedAuthNotSignedInMessage = String(localized: "This server signs in through an identity proxy, which didn't authorize this request. Open the server in a browser, or check the custom headers.") - /// Why the app can't complete sign-in on its own, or nil when it can — - /// either there's no auth, the server already signed this client in, or a - /// password login is available. - /// - /// Replaces the "auth on and password auth off ⇒ passkeys" inference that - /// used to live in three places. `is_auth_enabled()` upstream - /// (`api/auth.py:563`) also covers OIDC and trusted-header, so that - /// inference locked out working deployments and told them the wrong reason - /// (#3). nonisolated static func unsupportedSignInMessage(for status: AuthStatusResponse) -> String? { guard status.authEnabled == true, !status.isAlreadySignedIn else { return nil } - // A missing value means an older server that doesn't report it; fall - // through to the password path rather than block a working user. guard status.passwordAuthEnabled == false else { return nil } if status.oidcEnabled == true { return oidcOnlyMessage } @@ -55,55 +36,32 @@ final class AuthManager { } private(set) var state: State = .unconfigured { - // The shared Bot connection signs in with the active server's saved credentials. didSet { if let old = oldValue.server, old != state.server { hermesConnections.retire(server: old) } - // The Limits widget shows only the signed-in active server's Usage (#1409). if case .loggedIn = oldValue, oldValue != state { limitsPublisher.invalidate() } dropStaleMoveSheets() } } private(set) var lastErrorMessage: String? - /// Observable snapshot of every configured server, mirrored from the - /// `ServerRegistry` (the persistent source of truth) after each mutation so - /// the Settings server list updates reactively (#17). The active server is the - /// one whose `id` matches `state.server?.absoluteString`. private(set) var servers: [ServerAccount] = [] - /// Servers `removeServer` is part way through removing. A Move to Hermes runner treats its - /// destination as gone from the start, before the removal's first await (#1216). @ObservationIgnored private(set) var removingServerIDs: Set = [] - /// "Bring your chats" after signing in to a Hermes server (#1266), which the root presents; - /// nil once it is answered, no webui server is left to move, or `dropStaleMoveSheets` ends it. - /// Showing one takes this launch's move sheet from the one-time question. var moveOffer: MoveToHermesOffer? { didSet { if moveOffer != nil { askedAboutMoveThisLaunch = true } } } - /// The one-time "Move to Hermes" question (#1267), which the root presents; set by - /// `askAboutMoveIfDue`, nil once closed or `dropStaleMoveSheets` ends it. var moveQuestion: MoveToHermesQuestion? - /// One move sheet a launch: the question or the offer, whichever showed first. @ObservationIgnored var askedAboutMoveThisLaunch = false - // `keychain`, `serverRegistry` and `refreshServers` are internal for - // `AuthManager+MoveToHermes`; nothing outside this type and that extension uses them. let keychain: any KeychainStoring private let clientFactory: (URL) -> any AuthAPIClient - /// Builds a client bound to explicit headers (not the shared `CustomHeaderStore`) - /// — used by `addServer` to probe a new server without disturbing the active - /// server's live headers (#17). private let probeClientFactory: (URL, [CustomHeader]) -> any AuthAPIClient private let headerStore: CustomHeaderStore private let logoutTimeout: Duration let serverRegistry: ServerRegistry private let hermesConnections: HermesConnections - /// Where a removed server's Profile choice and model lists are cleared. private let preferences: UserDefaults - /// Hands back a server's Bot Screen holds. Tests record it. var handBackScreenHolds: (URL) -> Void = { server in Task { await ScreenHolds.handBackAll(server: server) } } - /// Tears down a server's push pairing when it is signed out of or removed. private let forgetPush: @MainActor (URL) async -> Void - /// The Limits widget's snapshot, emptied when its server or connection stops being in use. private let limitsPublisher: ProviderLimitsPublisher init( @@ -140,30 +98,19 @@ final class AuthManager { } } - /// The active server's id (its normalized URL string), or nil when - /// unconfigured. Used by the Settings list to mark which row is active. var activeServerID: String? { state.server?.absoluteString } - /// The active server's registry entry, or nil when unconfigured. var activeServer: ServerAccount? { servers.first { $0.id == activeServerID } } - /// What `server` is. A URL missing from the registry reads as webui, the only kind - /// before #899. func kind(of server: URL) -> ServerKind { servers.first { $0.id == server.absoluteString }?.kind ?? .webui } - /// Re-reads the registry into the observable `servers` snapshot. Called after - /// every registry mutation routed through this manager. func refreshServers() { servers = serverRegistry.servers dropStaleMoveSheets() } - /// Ends `moveOffer` and `moveQuestion`, closing their sheets and any move they started (which - /// pauses, as closing does), once the server they show over isn't the signed-in active server - /// (the offer's destination, the question's webui server), or either server is gone, is being - /// removed, or changed kind. Called after every state, registry and removal change. private func dropStaleMoveSheets() { let active: String? = if case .loggedIn(let server) = state { server.absoluteString } else { nil } func kindOf(_ id: String) -> ServerKind? { servers.first { $0.id == id }?.kind } @@ -177,8 +124,6 @@ final class AuthManager { } } - /// The headers currently in effect — used to prefill the editor on the connect - /// and Settings screens. var currentCustomHeaders: [CustomHeader] { headerStore.snapshot() } @@ -187,9 +132,6 @@ final class AuthManager { serverURLString: String, customHeaders: [CustomHeader]? = nil ) async throws -> AuthStatusResponse { - // Apply the in-progress headers before the very first probe so the health - // and auth-status calls already traverse the proxy. Passing nil leaves the - // current headers untouched (#255). if let customHeaders { headerStore.replace(with: customHeaders.sanitizedForStorage()) } @@ -222,7 +164,6 @@ final class AuthManager { do { let serverURL = try Self.normalizedServerURL(from: serverURLString) - // A webui server and a Hermes server never share a URL (#899). guard kind(of: serverURL) == .webui else { lastErrorMessage = String(localized: "This server is already configured.") return @@ -235,9 +176,6 @@ final class AuthManager { return } - // `logged_in` means the server already authenticated this client — - // trusted-header mode does it at the proxy — so there is nothing to - // log in with and the server is saved as signed in (#3). if authStatus.authEnabled == true, !authStatus.isAlreadySignedIn { guard !password.isEmpty else { lastErrorMessage = String(localized: "Enter the server password.") @@ -252,14 +190,8 @@ final class AuthManager { } } - // Persist only on success: the server URL and the headers that reached it. try keychain.save(serverURL.absoluteString, forKey: .serverURL) - // Record (or re-activate) this server in the multi-server registry, - // shadowing the Keychain `server_url` write above (#15). Dedupes by - // normalized URL. serverRegistry.activate(url: serverURL) - // Persist the headers that reached this server under its own scoped key - // so they never apply to a different server (#16). persistCustomHeaders(for: serverURL) refreshServers() state = .loggedIn(server: serverURL) @@ -268,27 +200,12 @@ final class AuthManager { } } - /// Outcome of `addServer`, so the in-app add-server flow can reveal the - /// password field only when the server actually needs one (#17). `serverAnswered` - /// says the webui answered its status read before the add failed, so the failure - /// is the webui's own (#1395). enum AddServerOutcome: Equatable { case added(URL) case needsPassword case failed(serverAnswered: Bool) } - /// Adds (and switches to) another server from the in-app add-server flow. - /// - /// Unlike `configure` (the onboarding path), this NEVER mutates the active - /// server's state or its live header store until the add fully succeeds: the - /// new server is probed through a client bound to *its own* headers (via - /// `probeClientFactory`), not the shared `CustomHeaderStore`. So a typo or an - /// unreachable server can't bounce the user out of a working session, and the - /// active server's concurrent requests (polling / SSE reconnect) never pick up - /// the new server's headers during the async probe window. Rejects a URL that's - /// already configured (no duplicate normalized URLs). On success the new server - /// becomes active and its headers are persisted under its own scoped key (#16). @discardableResult func addServer( serverURLString: String, @@ -311,8 +228,6 @@ final class AuthManager { } let newHeaders = customHeaders.sanitizedForStorage() - // Probe with a client scoped to the NEW server's headers, leaving the live - // header store (and the active server's in-flight/SSE requests) untouched. let client = probeClientFactory(serverURL, newHeaders) var serverAnswered = false @@ -327,7 +242,6 @@ final class AuthManager { if authStatus.authEnabled == true, !authStatus.isAlreadySignedIn { guard !password.isEmpty else { - // Not an error — the UI reveals the password field and retries. return .needsPassword } @@ -338,20 +252,12 @@ final class AuthManager { } } - // Commit only now that the add succeeded: the new server becomes - // active, so its headers move into the live store and persist under its - // own scoped key (#16). The previous active server's headers were never - // disturbed, and stay safe in their own scoped Keychain entry. - // - // Do the throwing Keychain write first so a write failure leaves the - // live header store (and the active server) completely untouched. try keychain.save(serverURL.absoluteString, forKey: .serverURL) headerStore.replace(with: newHeaders) handBackScreens(leavingFor: serverURL) serverRegistry.activate(url: serverURL) persistCustomHeaders(for: serverURL) refreshServers() - // As on a switch: the App Intents cache holds the previous server's profiles (#339). ProfileEntityCache.shared.save([]) state = .loggedIn(server: serverURL) return .added(serverURL) @@ -361,16 +267,6 @@ final class AuthManager { } } - /// Adds (and switches to) a Hermes server (#899): `connection` is a sign-in the - /// connection form or dev sign-in has already verified, and becomes the server's own - /// record, saved under its address, which is also the server's id. Refuses an address - /// already in the registry, as `addServer` does, so a webui server and a Hermes server - /// never share a URL (`replaceWebuiServer` swaps one for the other). Returns whether it - /// was added. - /// - /// Switching to it offers to move a webui server there (`moveOffer`). A sign-in opened - /// from Move to Hermes passes `activating: false`: the server is only added, so the move's - /// sheet stays up and scans it next, and the move's Done switches (#1266). @discardableResult func addHermesServer(_ connection: BotConnection, activating: Bool = true) -> Bool { lastErrorMessage = nil @@ -394,19 +290,12 @@ final class AuthManager { handBackScreens(leavingFor: server) serverRegistry.activate(url: server, kind: .hermes, serverVersion: connection.hermesVersion) refreshServers() - // The Shortcuts Profile list belonged to the server this replaces as active (#339). ProfileEntityCache.shared.save([]) enterActiveServer(server) moveOffer = MoveToHermesOffer(destinationID: server.absoluteString, servers: servers) return true } - /// Replaces the webui server saved at `connection`'s address with a Hermes server, for a - /// host that moved from hermes-webui to the dashboard (#1027). `connection` is a sign-in - /// already verified, as for `addHermesServer`. The webui server goes as `removeServer` - /// takes it (its sign-in, cache and drafts on this iPhone), and the Hermes server keeps - /// its name, initials and color. Refuses unless a webui server is saved there. Returns - /// whether the Hermes server was added. func replaceWebuiServer(with connection: BotConnection) async -> Bool { lastErrorMessage = nil let server = (try? BotConnection.address(connection.address.absoluteString)) ?? connection.address @@ -414,8 +303,6 @@ final class AuthManager { lastErrorMessage = String(localized: "This server is already configured.") return false } - // No suspension between the removal's last step and the add, so no screen ever - // shows the server the removal falls back to. await removeServer(webui) guard addHermesServer(connection), let added = activeServer else { return false } updateServerIdentity(added, displayName: webui.displayName, initials: webui.initials, @@ -423,18 +310,11 @@ final class AuthManager { return true } - /// A Hermes sign-in a webui server keeps for its Bots, which the connect form offers - /// to copy into a new Hermes server at the same address (#900). struct SavedHermesSignIn: Equatable { - /// The webui server that keeps it, named as Settings → Servers names it. let serverName: String let connection: BotConnection } - /// The sign-ins configured webui servers keep for exactly `address`, each saved address - /// parsed by `BotConnection.address(_:)` as the typed one was. Never matched by - /// `install_id`: it comes from the public `/api/status`, so any host could report - /// another's and be offered its saved password. func savedHermesSignIns(at address: URL) -> [SavedHermesSignIn] { let store = BotConnectionStore(keychain: keychain) return servers.compactMap { account in @@ -446,24 +326,12 @@ final class AuthManager { } } - /// The host refused the active Hermes server's saved username or password at the - /// login step, or its browser sign-in's refresh token (`failure`, from - /// `HermesConnections.onSignInRejected`), including the one silent re-sign-in a - /// signed-in 401 starts. Shows that server's sign-in form, with `failure`'s advice, - /// where no Bot screen exists to send the refused credential again. Any other server, and a webui - /// server's own Hermes connection, which keeps its per-screen flag (#884), stays as it is. func hermesSignInRejected(server: URL, failure: BotFailure = .rejected(401)) { guard state == .loggedIn(server: server), kind(of: server) == .hermes else { return } lastErrorMessage = BotConnectionAdvice.message(for: failure, address: server) state = .loggedOut(server: server) } - /// The Hermes connection form saved `server`'s sign-in. Records the release the host - /// reported, and signs the server back in when it is the active Hermes server waiting - /// on its sign-in form. A sign-in to the active Hermes server, from that form or from its - /// Settings while already signed in, offers to move a webui server there (`moveOffer`) - /// unless the sign-in continues a move (`offersMove: false`). Token refreshes never call - /// this. A no-op for a webui server. func hermesSignInSaved(server: URL, offersMove: Bool = true) { guard var account = servers.first(where: { $0.id == server.absoluteString }), account.kind == .hermes, let saved = try? BotConnectionStore(keychain: keychain).load(server: server) else { return } @@ -481,9 +349,6 @@ final class AuthManager { } } - /// `server`'s shared connection signed in and reached `gateway` (`HermesConnections.onSignedIn`). - /// Records it on a Hermes server's entry for the usage report (#1724) when it changed; a webui - /// server's own Hermes connection changes nothing. func hermesSignedIn(server: URL, gateway: HermesGatewayKind) { guard var account = servers.first(where: { $0.id == server.absoluteString }), account.kind == .hermes, account.hermesGateway != gateway else { return } @@ -492,9 +357,6 @@ final class AuthManager { refreshServers() } - /// An update from Settings installed `version` on the Hermes server `server` (#1075). - /// Records it on the server's saved sign-in and its registry entry, where a sign-in would - /// have, and changes nothing else: a server waiting on its sign-in form stays there. func hermesServerUpdated(server: URL, to version: String) { let store = BotConnectionStore(keychain: keychain) if var saved = try? store.load(server: server), saved.hermesVersion != version { @@ -508,31 +370,15 @@ final class AuthManager { refreshServers() } - /// Updates the in-effect headers from the Settings editor while signed in. The - /// in-memory snapshot always updates immediately (so live requests pick them - /// up), but the Keychain write is opt-in: the editor refreshes on every - /// keystroke (`persist: false`, cheap) and persists once on dismiss - /// (`persist: true`), since Keychain writes are slow enough to stutter typing - /// (#255). func updateCustomHeaders(_ headers: [CustomHeader], persist: Bool = true) { headerStore.replace(with: headers.sanitizedForStorage()) - // Persist under the active server's scoped key. The Settings editor is only - // reachable while signed in, so a server is always present here; if somehow - // unconfigured there's nothing to scope to, so we skip the write (#16). if persist, let server = state.server { persistCustomHeaders(for: server) } } - /// Signs out of the **active** server: best-effort server-side logout, then - /// drops it locally and auto-switches to the next remaining server — returning - /// to onboarding only when none remain (#17). A single-server install behaves - /// exactly as before (sign out → onboarding). A Hermes server stays configured: its - /// record, Bot data and push pairing are deleted and its sign-in form shows, with its - /// address (#899). func signOut() async { guard let active = state.server else { - // Defensive: nothing is active. Safe full reset to onboarding. clearLocalAuth(for: nil) state = .unconfigured return @@ -544,10 +390,7 @@ final class AuthManager { await ChatDraftStore.shared.discardBotDrafts(server: active) await forgetPush(active) removeBotConnection(for: active) - // Only once the record's removal has retired the shared connection: a Bots inbox - // still on screen can save a roster it reads during the awaits above (#1403). await BotRosterCache.shared.remove(server: active) - // The awaits above can outlast a switch to another server, which stays on screen. guard state.server == active else { return } lastErrorMessage = nil state = .loggedOut(server: active) @@ -563,16 +406,10 @@ final class AuthManager { await ChatDraftStore.shared.discardBotDrafts(server: active) await forgetPush(active) advanceAfterRemoving(activeServer: active) - // After the Bot record and its connection are gone, as in the Hermes branch above. await BotRosterCache.shared.remove(server: active) - // This sign-out removed the server, so its Bot widget rows go too (#1643). BotWidgetPublisher.shared.remove(server: active) } - /// Removes a configured server. When it's the active one this behaves like - /// `signOut` (best-effort server logout + auto-switch / onboarding). A - /// non-active server is just dropped locally — its registry row, scoped - /// headers, and cookies — leaving the active server's auth untouched (#17). func removeServer(_ account: ServerAccount) async { guard let serverURL = URL(string: account.urlString) else { return } removingServerIDs.insert(account.id) @@ -580,11 +417,9 @@ final class AuthManager { limitsPublisher.invalidate(server: serverURL) dropStaleMoveSheets() await ScreenHolds.handBackAll(server: serverURL) - // A move committed during the awaits below leaves an orphan journal, which `MoveToHermesPending.all` deletes. let movedSources = (servers.first { $0.id == account.id } ?? account).movedWebuiServers.map(\.sourceServerID) try? await BotHistoryCache.shared.removeServer(serverURL, activeConnectionID: (try? BotConnectionStore(keychain: keychain).load(server: serverURL))?.id) SessionUnreadStore().remove(for: serverURL) - // Kept through a sign-out, which the Shortcuts picker still lists the server's Profiles across (#1180). HermesProfileNameCache.shared.remove(server: serverURL) await ChatDraftStore.shared.discardBotDrafts(server: serverURL) await forgetPush(serverURL) @@ -600,20 +435,11 @@ final class AuthManager { serverRegistry.remove(id: account.id) refreshServers() } - // After the Bot record and its connection are gone, as in `signOut`. await BotRosterCache.shared.remove(server: serverURL) - // Here too, so a roster read during the awaits can't write the rows back. A Hermes sign-out - // keeps them, so a Bot widget still opens its bot after the next sign-in (#1643). BotWidgetPublisher.shared.remove(server: serverURL) - // After the entry is gone, so a running Move finds no record and writes nothing more (#1216). MoveToHermesJournal.discard(sources: movedSources, destinationID: account.id) } - /// Switches the active server to an already-registered one (the Settings - /// switcher). Mirrors the cold-launch path: persist the URL, set it active, and - /// enter it (`enterActiveServer`): a webui server optimistically `.loggedIn` with - /// its scoped headers, a stale cookie demoted by the first request's 401 - /// (`handleAPIError`), exactly like a relaunch — so no extra round-trip here. func switchActiveServer(to account: ServerAccount) { guard account.id != state.server?.absoluteString, let serverURL = URL(string: account.urlString) else { return } @@ -622,18 +448,11 @@ final class AuthManager { serverRegistry.setActive(id: account.id) refreshServers() try? keychain.save(serverURL.absoluteString, forKey: .serverURL) - // Drop the App Intents profile picker cache (#339): it holds the previous server's - // profiles, which would leak into Shortcuts / Siri if the new server's fetch is - // delayed or fails. The new server's profiles reload on the next foreground fetch. ProfileEntityCache.shared.save([]) lastErrorMessage = nil enterActiveServer(serverURL) } - /// Updates a server's per-server identity (display name, initials, Header Logo - /// Color). When `account` is the active server the registry mirrors the new - /// identity into the global identity defaults, so the avatar / header tint - /// update live (#17). func updateServerIdentity( _ account: ServerAccount, displayName: String, @@ -648,16 +467,9 @@ final class AuthManager { refreshServers() } - /// Drops the active server locally + from the registry, then auto-switches to - /// the next remaining server, or returns to onboarding when none remain. The - /// shared core of `signOut` and active-server `removeServer` (#17). private func advanceAfterRemoving(activeServer server: URL) { - // Always drop any pre-#16 global header remnant on a sign-out path. try? keychain.delete(.customHeaders) clearLocalArtifacts(for: server) - // Drop the App Intents profile picker cache (#339): the cached profiles belong to the - // server being removed, so they're stale whether we switch to another server (its - // profiles reload on the next foreground fetch) or return to onboarding. ProfileEntityCache.shared.save([]) let nextActive = serverRegistry.remove(id: server.absoluteString) @@ -674,30 +486,17 @@ final class AuthManager { } } - /// Deletes one server's local auth artifacts — its scoped custom headers, its - /// Bot connection with that connection's cached avatars, shared sign-in and remembered - /// Hermes Profile, and its cookies — without touching the registry or the global - /// `server_url` key. Its push pairing lives in the shared Keychain access group and is torn down by - /// `PushRegistrar.forget`, which the removal paths above await first. A Hermes - /// server's sign-in never uses the shared cookie jar, so the cookies of a webui - /// server on the same host stay. private func clearLocalArtifacts(for server: URL) { try? keychain.delete(.customHeaders, scope: server.absoluteString) removeBotConnection(for: server) if kind(of: server) == .webui { clearSessionCookies(for: server) } } - /// Any Bot Screen takeover on the server being left goes back to its bot. It runs on a connection - /// of its own, so the logged-in tree's rebuild can't cut it off. private func handBackScreens(leavingFor next: URL) { guard let departing = state.server, departing != next else { return } handBackScreenHolds(departing) } - /// Deletes `server`'s Bot connection record with that connection's cached avatars, - /// which also retires its shared sign-in (`BotConnectionStore.remove`), the Profile its - /// New Session remembers (#1015), whether its Sessions list shows every Profile (#709), - /// the Profile that list last read, its favorite and recent models and remembered Thinking and Fast, and its Bot Screen switch. private func removeBotConnection(for server: URL) { BotScreenSettings.remove(for: server, in: preferences) ScreenHoldStore(keychain: keychain).removeAll(server: server) @@ -714,17 +513,8 @@ final class AuthManager { try? bots.remove(server: server) } - /// Tells the server to end the session, but never lets an unreachable or - /// slow server block local sign-out. The request is best-effort and bounded - /// by `logoutTimeout`; on failure, timeout, or cancellation we just move on - /// so the caller can always clear local auth and return to onboarding. - /// - /// Order matters: this runs while the session cookie still exists, so a - /// reachable server is logged out server-side before `clearLocalAuth()` - /// deletes the cookie. See issue #249. private func attemptBestEffortServerLogout(server: URL) async { let client = clientFactory(server) - // Copy to a local so the timeout task captures only the value, not `self`. let timeout = logoutTimeout let logoutTask = Task { @MainActor in @@ -743,17 +533,12 @@ final class AuthManager { guard case APIError.unauthorized = error else { return } - // A webui 401 is never about a Hermes server's own sign-in: a late reply from a - // webui screen a switch left behind must not sign the Hermes server out (#899). if let server = state.server, kind(of: server) == .hermes { return } lastErrorMessage = String(localized: "Your session expired. Sign in again.") switch state { case .loggedIn(let server), .loggedOut(let server): - // The server is still valid; only the session cookie is stale. Keep the - // Keychain entry so re-login is a one-field affair, and clear only this - // server's cookies so other configured servers stay signed in (#16). clearSessionCookies(for: server) state = .loggedOut(server: server) case .unconfigured: @@ -761,20 +546,8 @@ final class AuthManager { } } - /// Clears local auth for `server` (a full per-server sign-out): forgets that - /// server's saved URL, its scoped custom headers, and its cookies, leaving any - /// other configured server untouched (#16). (Session-expiry via - /// `handleAPIError` keeps the URL + headers so re-login behind a proxy is a - /// one-field affair — see #255.) - /// - /// When `server` is nil (a 401 while unconfigured) there's no active server to - /// scope to, so we fall back to clearing the global remnants and the whole - /// cookie jar as a safe reset. private func clearLocalAuth(for server: URL?) { - // The legacy single-server URL key is global; always clear it on sign-out. try? keychain.delete(.serverURL) - // Drop any pre-#16 global header blob too, so it can't linger or be - // re-migrated after the user has signed out. try? keychain.delete(.customHeaders) if let server { @@ -784,18 +557,12 @@ final class AuthManager { clearAllSessionCookies() } - // Forget the active server in the registry (leaves other servers intact). serverRegistry.forgetActiveServer() refreshServers() headerStore.replace(with: []) - // Drop the App Intents profile picker cache (#339) so a signed-out user doesn't see - // the previous server's profiles lingering in Shortcuts / Siri. ProfileEntityCache.shared.save([]) } - /// Mirrors the in-memory header snapshot to `server`'s scoped Keychain entry: - /// writes it when non-empty, deletes it when empty so no stale list lingers for - /// that server (#16). private func persistCustomHeaders(for server: URL) { let scope = server.absoluteString let headers = headerStore.snapshot() @@ -806,12 +573,6 @@ final class AuthManager { } } - /// Loads `server`'s custom headers into the live snapshot before any client is - /// built, so the first request after launch already carries them (#255). On the - /// first launch after the per-server split there's no scoped entry yet, so we - /// migrate the pre-#16 global blob in place — write it under the scoped key and - /// drop the global remnant — and use it. One scoped Keychain read on the - /// steady-state path (#16). private func hydrateCustomHeaders(for server: URL) { let scope = server.absoluteString let stored: String? @@ -827,21 +588,11 @@ final class AuthManager { headerStore.replace(with: [CustomHeader].decodeFromStorage(stored)) } - /// Deletes only the cookies that would be sent to `server` (matched by host, - /// path, and security via `HTTPCookieStorage.cookies(for:)`), so signing out of - /// or expiring one server leaves other servers' cookies intact (#16). - /// - /// Different-host servers are fully isolated this way. Two servers that share a - /// host but differ only by port still share a cookie jar (cookies aren't - /// port-scoped) — a documented limitation; closing it would need the per-server - /// cookie snapshot/restore deferred to the #17 switcher. private func clearSessionCookies(for server: URL) { let storage = HTTPCookieStorage.shared storage.cookies(for: server)?.forEach { storage.deleteCookie($0) } } - /// Clears the entire shared cookie jar. Used only as a fallback when there's no - /// active server to scope to (a 401 while unconfigured). private func clearAllSessionCookies() { HTTPCookieStorage.shared.cookies?.forEach { HTTPCookieStorage.shared.deleteCookie($0) @@ -853,26 +604,15 @@ final class AuthManager { let savedValue = try? keychain.load(.serverURL), let savedURL = URL(string: savedValue) else { - // No saved server: nothing is active, so no scoped headers apply. state = .unconfigured return } - // One-time migration of the saved single server into the multi-server - // registry (#15). Idempotent: an already-registered server is just - // re-activated, and its per-server identity is only seeded on first - // insert, so #17 edits survive relaunch. serverRegistry.activate(url: savedURL) refreshServers() enterActiveServer(savedURL) } - /// Enters `server`, already active in the registry. A webui server's headers are - /// hydrated (migrating the pre-#16 global blob on the first launch after the split) - /// before any client is built, so its first request carries them (#255/#16), and it - /// enters `.loggedIn` optimistically: a stale cookie is demoted by the first 401 - /// (`handleAPIError`). A Hermes server sends no webui headers and is signed in only - /// while its own record exists; without one its sign-in form shows (#899). private func enterActiveServer(_ server: URL) { guard kind(of: server) == .hermes else { hydrateCustomHeaders(for: server) diff --git a/HermesMobile/Auth/KeychainStore.swift b/HermesMobile/Auth/KeychainStore.swift index 17448f9d0..4e72ced3f 100644 --- a/HermesMobile/Auth/KeychainStore.swift +++ b/HermesMobile/Auth/KeychainStore.swift @@ -6,10 +6,6 @@ protocol KeychainStoring { func load(_ key: KeychainStore.Key) throws -> String? func delete(_ key: KeychainStore.Key) throws - // Per-server-scoped variants (#16): the same logical key namespaced by a - // stable server identifier (the normalized server URL), so secrets like the - // custom request headers are stored separately per configured server and one - // server's credentials are never read or cleared for another. func save(_ value: String, forKey key: KeychainStore.Key, scope: String) throws func load(_ key: KeychainStore.Key, scope: String) throws -> String? func delete(_ key: KeychainStore.Key, scope: String) throws @@ -18,20 +14,10 @@ protocol KeychainStoring { struct KeychainStore: KeychainStoring { enum Key: String { case serverURL = "server_url" - // JSON-encoded [{name, value}] of user-supplied request headers (#255). - // Values may be secrets, so the list lives in the Keychain, not defaults. case customHeaders = "custom_headers" - // JSON-encoded multi-server registry (server list + active id). The server - // URL is treated as a credential, so the registry - // lives in the Keychain, not UserDefaults (#15). case servers = "servers" case botConnection = "bot_connection" - // Per-server push pairing (relay URL, install key, preview key). Unlike - // every other key here it lives in a shared Keychain access group so the - // Notification Service Extension can read it; see `PushPairing.swift`. case pushPairing = "push_pairing" - // Per-server JSON of the Bot Screen takeovers this iPhone holds (#1567). The viewer id in - // each is a capability on the host. case screenHolds = "screen_holds" } @@ -70,10 +56,6 @@ struct KeychainStore: KeychainStoring { try keychain.remove(Self.scopedKey(key, scope: scope)) } - /// Namespaces a logical key by a server scope. `::` can't appear in a key's - /// raw value (they're lowercase identifiers), so it's an unambiguous separator - /// and the legacy unscoped account (`custom_headers`) never collides with a - /// scoped one (`custom_headers::https://host`). static func scopedKey(_ key: Key, scope: String) -> String { "\(key.rawValue)::\(scope)" } diff --git a/HermesMobile/Config/AppColor.swift b/HermesMobile/Config/AppColor.swift index 0c58454a3..fababb3c0 100644 --- a/HermesMobile/Config/AppColor.swift +++ b/HermesMobile/Config/AppColor.swift @@ -1,8 +1,6 @@ import SwiftUI import UIKit -/// Settings > Appearance's themes. Each has a light and a dark palette, and a user can pick a -/// different theme for each mode. Default is the app's system colors, untouched. enum ColorTheme: String, CaseIterable, Identifiable { case `default` case paper @@ -26,7 +24,6 @@ enum ColorTheme: String, CaseIterable, Identifiable { } } - /// Text color for drawing outside the view hierarchy, where no trait reaches, such as math images. func resolvedText(isDark: Bool) -> UIColor { palette(isDark: isDark).text.resolvedColor(with: UITraitCollection(userInterfaceStyle: isDark ? .dark : .light)) } @@ -50,14 +47,12 @@ enum ColorTheme: String, CaseIterable, Identifiable { } } -/// One theme's colors in one mode. A class, because every token read passes one through the trait. final class ThemePalette { let canvas, surface, raised, groupedCanvas, groupedSurface, groupedRaised: UIColor let text, textSecondary, textTertiary, placeholder: UIColor let separator, fill, fillSecondary, fillTertiary: UIColor let accent, onAccent, link, code, inlineCode, userBubble: UIColor - /// Today's colors. Dynamic, so one palette serves both modes and elevated sheets. static let system = ThemePalette( canvas: .systemBackground, surface: .secondarySystemBackground, raised: .tertiarySystemBackground, groupedCanvas: .systemGroupedBackground, groupedSurface: .secondarySystemGroupedBackground, @@ -112,9 +107,6 @@ final class ThemePalette { self.userBubble = userBubble } - /// A theme's palette, from the seven colors that define it. The rest follow the same rules - /// in every theme, with fill strengths matching iOS's own. Tertiary text and placeholders are - /// the muted color at full strength: anything fainter misses the contrast floor. private convenience init(isDark: Bool, canvas: Int, surface: Int, text: Int, muted: Int, border: Int, accent: Int, code: Int) { let canvas = UIColor(rgb: canvas) let surface = UIColor(rgb: surface) @@ -134,7 +126,6 @@ final class ThemePalette { ) } - /// This palette with a user's accent, moved just far enough to stay readable on it. func withAccent(_ accent: UIColor, isDark: Bool) -> ThemePalette { let traits = UITraitCollection(userInterfaceStyle: isDark ? .dark : .light) let readable = accent.adjustedForContrast( @@ -152,14 +143,11 @@ final class ThemePalette { } } -/// The theme and accent a user picked. It's the value of one trait on the window scene, so a -/// change recolors SwiftUI, UIKit, sheets and the app lock without re-running view bodies. struct AppAppearance: Equatable { static let `default` = AppAppearance(lightTheme: .default, darkTheme: .default, accentHex: nil) let lightTheme: ColorTheme let darkTheme: ColorTheme - /// Nil uses each theme's own accent. let accentHex: String? private let lightPalette: ThemePalette private let darkPalette: ThemePalette @@ -177,7 +165,6 @@ struct AppAppearance: Equatable { func palette(isDark: Bool) -> ThemePalette { isDark ? darkPalette : lightPalette } - /// For caches of baked images, which a new theme or accent has to redraw. var cacheKey: String { "\(lightTheme.rawValue)|\(darkTheme.rawValue)|\(accentHex ?? "")" } func theme(for colorScheme: ColorScheme) -> ColorTheme { colorScheme == .dark ? darkTheme : lightTheme } @@ -211,13 +198,9 @@ extension EnvironmentValues { set { self[AppAppearanceKey.self] = newValue } } - /// Whether this mode shows a theme, rather than Default's system colors. Only for what a - /// color token can't do alone, such as hiding a list's own background. var isAppThemed: Bool { appAppearance.theme(for: colorScheme) != .default } } -/// Where Settings > Appearance keeps its theme and accent, for all servers. Applied like -/// `AppTextSize`: when a scene connects, before its first frame, and when the setting changes. enum AppAppearanceSettings { static let lightThemeKey = "appearance.lightTheme" static let darkThemeKey = "appearance.darkTheme" @@ -242,9 +225,6 @@ enum AppAppearanceSettings { } } -/// The app's color tokens. Each follows the scene's theme, accent and mode wherever it's drawn. -/// In SwiftUI: `Color(.appCanvas)`. Status colors and syntax highlighting aren't tokens: they -/// stay fixed in every theme. extension UIColor { static let appCanvas = token { $0.canvas } static let appSurface = token { $0.surface } @@ -261,13 +241,9 @@ extension UIColor { static let appFillSecondary = token { $0.fillSecondary } static let appFillTertiary = token { $0.fillTertiary } static let appAccent = token { $0.accent } - /// Text and icons on a solid `appAccent` fill. static let appOnAccent = token { $0.onAccent } - /// Links in Markdown replies. static let appLink = token { $0.link } - /// Behind code blocks. static let appCode = token { $0.code } - /// Behind inline code in prose. static let appInlineCode = token { $0.inlineCode } static let appUserBubble = token { $0.userBubble } @@ -287,7 +263,6 @@ extension UIColor { ) } - /// Nil unless `rawValue` is a six-digit hex color. convenience init?(hexRGB rawValue: String) { guard let hex = HeaderLogoColor.normalizedHex(rawValue), let value = Int(hex.dropFirst(), radix: 16) else { return nil } @@ -295,7 +270,6 @@ extension UIColor { } } -/// WCAG contrast, which the themes and any accent pick must meet. enum ColorContrast { static let minimum = 4.5 @@ -317,12 +291,10 @@ private extension UIColor { return 0.2126 * linear(red) + 0.7152 * linear(green) + 0.0722 * linear(blue) } - /// White or black, whichever reads better on this color. The better one always clears 4.5:1. var readableForeground: UIColor { ColorContrast.ratio(.white, self) >= ColorContrast.ratio(.black, self) ? .white : .black } - /// This color, mixed toward `target` in small steps until it reaches `minimum` on every background. func adjustedForContrast(_ minimum: Double, on backgrounds: [UIColor], toward target: UIColor) -> UIColor { var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) @@ -343,10 +315,6 @@ private extension UIColor { } } -/// Text levels for SwiftUI: `.foregroundStyle(.appSecondary)`. On Default these are SwiftUI's own -/// levels, which keep their vibrancy on glass. On a theme they're its text colors, which meet the -/// contrast floor where iOS's translucent levels don't. Text with no style of its own stays iOS's -/// label color: a foreground style set at the app root would also repaint every button's label. struct AppTextStyle: ShapeStyle { enum Level { case primary, secondary, tertiary } @@ -368,16 +336,11 @@ extension ShapeStyle where Self == AppTextStyle { static var appTertiary: AppTextStyle { AppTextStyle(level: .tertiary) } } -/// What a themed list draws behind its rows. enum ThemedListRows { - /// Cards on the canvas, as in an inset grouped list. case grouped - /// Rows directly on the canvas. case plain } -/// A `List` that follows the theme. On Default it's an ordinary `List`: nothing here applies, so -/// rows keep iOS's own backgrounds and highlights. Rows never draw dividers between them. struct AppList: View { var rows = ThemedListRows.grouped @ViewBuilder let content: Content @@ -388,7 +351,6 @@ struct AppList: View { } } -/// `AppList` for a `Form`. struct AppForm: View { @ViewBuilder let content: Content @@ -398,8 +360,6 @@ struct AppForm: View { } } -/// Gives every row the theme's background and hides its separators. A row with its own -/// `listRowBackground` keeps it. private struct ThemedListContent: View { let rows: ThemedListRows let content: Content @@ -429,8 +389,6 @@ private struct ThemedScrollBackground: ViewModifier { } } -/// `.borderedProminent` with a readable label. iOS always draws it white, which a theme's light -/// dark-mode accent can't carry, so a theme or accent pick uses `appOnAccent`. struct AppProminentButtonStyle: PrimitiveButtonStyle { func makeBody(configuration: Configuration) -> some View { Prominent(configuration: configuration) @@ -455,8 +413,6 @@ extension PrimitiveButtonStyle where Self == AppProminentButtonStyle { static var appProminent: AppProminentButtonStyle { AppProminentButtonStyle() } } -/// A material on Default. A theme draws its surface instead: iOS's materials wash its colors out -/// to gray. `.background(.appMaterial(.bar))`. struct AppMaterialStyle: ShapeStyle { let material: Material @@ -470,9 +426,6 @@ extension ShapeStyle where Self == AppMaterialStyle { } extension View { - /// Fills a page, pushed or in a sheet, with the theme's canvas. iOS paints a page with no - /// background of its own in the system color, and nothing above the page can change that. - /// Draws nothing on Default. func themedPageBackground() -> some View { modifier(ThemedPageBackground()) } diff --git a/HermesMobile/Config/AppConfig.swift b/HermesMobile/Config/AppConfig.swift index 5c7e6d1fc..f441f9c4e 100644 --- a/HermesMobile/Config/AppConfig.swift +++ b/HermesMobile/Config/AppConfig.swift @@ -4,14 +4,9 @@ enum AppConfig { static let tipURL = URL(staticString: "https://buymeacoffee.com/callmeuzi") static let membershipURL = URL(staticString: "https://buymeacoffee.com/callmeuzi/membership") static let writeReviewURL = URL(staticString: "https://apps.apple.com/app/id6767006319?action=write-review") - /// Handed to iOS, so the GitHub app opens it when installed. static let repositoryURL = URL(staticString: "https://github.com/uzairansaruzi/hermex") - /// GitHub's issue template chooser: Report a Problem's fallback when the app can't prefill the bug form. static let reportProblemURL = URL(staticString: "https://github.com/uzairansaruzi/hermex/issues/new/choose") - /// The bug report form; `SupportReport.issueURL` fills in its version inputs. static let bugReportURL = URL(staticString: "https://github.com/uzairansaruzi/hermex/issues/new?template=bug_report.yml") - /// The playbook a user's Hermes agent follows to triage a Hermex problem (#1477). Read from - /// `master` by the agent, so triage improves without an app release. static let triagePlaybookURL = URL(staticString: "https://raw.githubusercontent.com/uzairansaruzi/hermex/master/.github/triage/PLAYBOOK.md") static let privacyPolicyURL = URL(staticString: "https://hermexapp.com/privacy") static let supportURL = URL(staticString: "https://www.uzairansar.com/hermes-mobile") diff --git a/HermesMobile/Config/AppFont.swift b/HermesMobile/Config/AppFont.swift index 7190f5d20..5ee7e3e26 100644 --- a/HermesMobile/Config/AppFont.swift +++ b/HermesMobile/Config/AppFont.swift @@ -2,7 +2,6 @@ import MarkdownUI import SwiftUI import UIKit -/// Settings > Appearance's Font, one choice for the whole app across every server. enum AppFontFamily: String, CaseIterable, Identifiable { case sanFrancisco case sfRounded @@ -14,7 +13,6 @@ enum AppFontFamily: String, CaseIterable, Identifiable { var id: String { rawValue } - /// Proper names, the same in every language. var title: String { switch self { case .sanFrancisco: "San Francisco" @@ -27,7 +25,6 @@ enum AppFontFamily: String, CaseIterable, Identifiable { } } - /// The family name of a non-system font. DM Sans and Lora are bundled (`Resources/Fonts`). fileprivate var customName: String? { switch self { case .sanFrancisco, .sfRounded, .sfMono: nil @@ -38,7 +35,6 @@ enum AppFontFamily: String, CaseIterable, Identifiable { } } - /// The design of a system font. Nil asks for the plain system font, exactly as `.body` does. fileprivate var design: Font.Design? { switch self { case .sfRounded: .rounded @@ -48,9 +44,6 @@ enum AppFontFamily: String, CaseIterable, Identifiable { } } -/// The stored font choice. A trait can't swap a SwiftUI `Font`, so tokens read this instead: -/// a view body that calls one depends on `family` through Observation, wherever it's hosted, -/// and only a change of font re-runs those bodies. @Observable final class AppFontSettings { static let storageKey = "appearance.fontFamily" static let shared = AppFontSettings() @@ -64,8 +57,6 @@ enum AppFontFamily: String, CaseIterable, Identifiable { } } -/// Typography tokens: use these in place of `.body`, `.caption` and friends so text follows the -/// Font setting. San Francisco resolves to the same fonts as the system styles. enum AppFont { static func largeTitle(weight: Font.Weight? = nil) -> Font { font(.largeTitle, weight: weight) } static func title(weight: Font.Weight? = nil) -> Font { font(.title, weight: weight) } @@ -79,7 +70,6 @@ enum AppFont { static func caption(weight: Font.Weight? = nil) -> Font { font(.caption, weight: weight) } static func caption2(weight: Font.Weight? = nil) -> Font { font(.caption2, weight: weight) } - /// Text at a size that ignores Text Size, like `.system(size:)`. Glyphs keep `.system(size:)`. static func fixed(size: CGFloat, weight: Font.Weight? = nil) -> Font { let family = AppFontSettings.shared.family guard let name = family.customName else { @@ -89,28 +79,22 @@ enum AppFont { return weight.map(custom.weight) ?? custom } - /// Code stays monospaced whatever the Font setting is. static func mono(style: Font.TextStyle = .body, weight: Font.Weight? = nil) -> Font { .system(style, design: .monospaced, weight: weight) } - /// Monospaced tool output: `customSize` points when set (`CodeDisplaySettings`), else `style`. static func code(style: Font.TextStyle, customSize: Double?) -> Font { customSize.map { .system(size: $0, design: .monospaced) } ?? mono(style: style) } - /// The default for text with no font of its own, set at each window's root. Nil on San - /// Francisco, which leaves every control's own default alone. static var root: Font? { AppFontSettings.shared.family == .sanFrancisco ? nil : body() } - /// A list's section footer. Nil on San Francisco, which keeps the list's own default. static var sectionFooter: Font? { AppFontSettings.shared.family == .sanFrancisco ? nil : footnote() } - /// The family a Markdown reply's text uses. static var markdownFamily: FontProperties.Family { let family = AppFontSettings.shared.family return family.customName.map(FontProperties.Family.custom) ?? .system(family.design ?? .default) @@ -122,11 +106,9 @@ enum AppFont { return .system(style, design: family.design, weight: weight) } let custom = Font.custom(name, size: standardSize(of: style), relativeTo: style) - // `relativeTo:` borrows only the scaling, and a headline is semibold by nature. return (weight ?? (style == .headline ? .semibold : nil)).map(custom.weight) ?? custom } - /// The style's point size at the standard text size. private static func standardSize(of style: Font.TextStyle) -> CGFloat { switch style { case .largeTitle: 34 @@ -144,7 +126,6 @@ enum AppFont { } extension View { - /// Sets `AppFont.root` here, in a modifier of its own so a font change re-runs only this. func appRootFont() -> some View { modifier(AppRootFont()) } } @@ -159,8 +140,6 @@ private struct AppRootFont: ViewModifier { } } -/// `AppFont.root` also replaces the smaller default a list gives its section footers, so a section -/// with a footer uses `appFooter:` to get it back. Reads like SwiftUI's `footer:` initializers. struct AppSectionFooterFont: ViewModifier { func body(content: Content) -> some View { content.font(AppFont.sectionFooter) @@ -184,17 +163,12 @@ extension Section where Parent: View, Content: View { } } -/// Navigation bar titles are UIKit's and read no SwiftUI font. The proxy covers bars made later, -/// and bars already on screen are set directly. San Francisco clears both. @MainActor enum AppBarFont { - /// Called from the app's `init`, because SwiftUI makes its first bar before a scene delegate - /// hears about the scene. Nil traits follow the iPhone's text size. static func applyAtLaunch() { let size = AppTextSize.size(atStop: UserDefaults.standard.integer(forKey: AppTextSize.storageKey)) setProxy(traits: size.map { UITraitCollection(preferredContentSizeCategory: UIContentSizeCategory($0)) }) } - /// Called when the font or the text size changes. static func apply() { for case let scene as UIWindowScene in UIApplication.shared.connectedScenes { let (title, largeTitle) = setProxy(traits: scene.traitCollection) @@ -236,10 +210,7 @@ extension Section where Parent: View, Content: View { } } -// UIKit text. The caller re-reads these when the font changes: `updateUIView` is observed, and -// anything that bakes the text into an image puts `family` in the image's cache key. extension UIFont { - /// The app's font at a fixed size. static func app(size: CGFloat, weight: UIFont.Weight = .regular) -> UIFont { let family = AppFontSettings.shared.family if let name = family.customName { @@ -256,7 +227,6 @@ extension UIFont { return UIFont(descriptor: descriptor, size: size) } - /// The app's font for `style` at `size`, which scales with `adjustsFontForContentSizeCategory`. static func app(forTextStyle style: TextStyle, at size: DynamicTypeSize) -> UIFont { app(forTextStyle: style, compatibleWith: UITraitCollection(preferredContentSizeCategory: UIContentSizeCategory(size))) } diff --git a/HermesMobile/Config/AppTheme.swift b/HermesMobile/Config/AppTheme.swift index 2e5dc9cde..c619b96c9 100644 --- a/HermesMobile/Config/AppTheme.swift +++ b/HermesMobile/Config/AppTheme.swift @@ -6,17 +6,13 @@ import UserNotifications import UIKit #endif -// Device-wide engagement and tip preferences, shared across every configured server. enum TipJar { - /// The release (major.minor) on which "Not now" was last tapped. static let dismissedReleaseKey = "tipJar.dismissedRelease" static let linkOpenedKey = "tipJar.linkOpened" static let completedResponseCountKey = "engagement.completedResponseCount" } -// Device-wide preferences for the "Star Hermex on GitHub" card. enum GitHubStar { - /// The release (major.minor) on which "Not now" was last tapped. static let dismissedReleaseKey = "githubStar.dismissedRelease" static let linkOpenedKey = "githubStar.linkOpened" } @@ -63,31 +59,24 @@ enum AppTheme: String, CaseIterable, Identifiable { } } -/// Settings > Appearance's Text Size, app-wide on this iPhone and across every server. Set once -/// as a scene trait override, so SwiftUI, UIKit, sheets and the app lock all follow it. The share -/// extension and Live Activity are separate processes and keep following the iPhone. enum AppTextSize { static let storageKey = "appearance.textSizeStop" - /// The slider's stops. The first follows the iPhone. Stored by position, so only append. static let stops: [DynamicTypeSize?] = [ nil, .xSmall, .small, .medium, .large, .xLarge, .xxLarge, .xxxLarge, .accessibility1, .accessibility2, .accessibility3, .accessibility4, .accessibility5 ] - /// The stop's size, or nil to follow the iPhone. An unknown position follows the iPhone too. static func size(atStop stop: Int) -> DynamicTypeSize? { stops.indices.contains(stop) ? stops[stop] : nil } - /// The stop as a percentage of the standard size, which reads the same in every language. static func percentage(of size: DynamicTypeSize) -> Double { let standard = UIFont.preferredFont(forTextStyle: .body, at: .large).pointSize return UIFont.preferredFont(forTextStyle: .body, at: size).pointSize / standard } - /// Called when a scene connects, before its first frame. @MainActor static func applyStoredSize(to scene: UIWindowScene) { let size = self.size(atStop: UserDefaults.standard.integer(forKey: storageKey)) if let size { @@ -97,7 +86,6 @@ enum AppTextSize { } } - /// Called when the setting changes. @MainActor static func applyStoredSizeToConnectedScenes() { for case let scene as UIWindowScene in UIApplication.shared.connectedScenes { applyStoredSize(to: scene) @@ -106,8 +94,6 @@ enum AppTextSize { } extension UIFont { - /// The style's font at `size`. Plain `preferredFont(forTextStyle:)` reads the iPhone's - /// setting, which misses `AppTextSize`. static func preferredFont(forTextStyle style: TextStyle, at size: DynamicTypeSize) -> UIFont { preferredFont( forTextStyle: style, @@ -116,17 +102,13 @@ extension UIFont { } } -/// Settings > Appearance's Code section, which covers chat code, tool output, source files and diffs. enum CodeDisplaySettings { - /// Named for its first home in chat; kept so a stored choice survives. static let wrapsLinesKey = "chatTranscript.wrapsCodeBlockLines" private static let legacySourceWrapsLinesKey = "workspace.sourceViewer.wrapsLines" - /// Points. Unset, code follows Text Size. static let customSizeKey = "appearance.customCodeSize" static let customSizeRange: ClosedRange = 10...28 - /// Source files and diffs had their own wrap setting. Either one being on stays on. static func migrateWrapSetting(defaults: UserDefaults = .standard) { guard defaults.object(forKey: legacySourceWrapsLinesKey) != nil else { return } if defaults.bool(forKey: legacySourceWrapsLinesKey) { @@ -252,23 +234,13 @@ extension Color { } } -/// User-facing switch (issue #261) for tinting the primary actions — the -/// "New Chat" button and the composer "Send" button — with the chosen accent, or -/// the server's Header Logo Color if there is none, instead of the default -/// monochrome fill. Defaults to off (opt-in); -/// a control keeps its muted/monochrome look while disabled so a tinted-but-dead -/// button never reads as interactive. enum PrimaryActionTintSettings { static let isEnabledKey = "appearance.tintsPrimaryActionsWithThemeColor" - /// A primary action adopts the theme color only when the user enabled the - /// setting *and* the control is currently interactive. static func usesThemeColor(isEnabled: Bool, controlIsEnabled: Bool) -> Bool { isEnabled && controlIsEnabled } - /// A tinted primary action's fill and label: the accent at its readable color if one is - /// chosen, otherwise the server's color. static func colors(accentHex: String?, serverHex: String) -> (fill: Color, label: Color) { if accentHex.flatMap(HeaderLogoColor.normalizedHex) != nil { return (Color(.appAccent), Color(.appOnAccent)) @@ -282,8 +254,6 @@ enum PrimaryActionTintSettings { enum AppHaptics { static let isEnabledKey = "appHaptics.isEnabled" - /// Opt-in selection tick while assistant text streams. Off by default and - /// only honored when `isEnabledKey` is also on. static let streamingPulseIsEnabledKey = "appHaptics.streamingPulse.isEnabled" } @@ -296,8 +266,6 @@ enum AgentRunLiveActivityPrivacy { static let showsResponseExcerptsKey = "agentRunLiveActivity.showsResponseExcerpts" } -/// Settings → Chat "Thinking & Tools" (#1254): whether a chat shows thinking and tool -/// cards, and whether they start open. enum ThinkingAndToolCards: String, CaseIterable, Identifiable { case hidden case collapsed @@ -320,15 +288,10 @@ enum ThinkingAndToolCards: String, CaseIterable, Identifiable { enum ChatTranscriptDisplaySettings { static let thinkingAndToolCardsKey = "chatTranscript.thinkingAndToolCards" - /// The three toggles the Thinking & Tools picker replaced (#1254). Read only by - /// `migrateThinkingAndToolCards`. private static let legacyShowsCardsKey = "chatTranscript.showsThinkingAndToolCards" private static let legacyThinkingExpandedKey = "chatTranscript.thinkingCardsStartExpanded" private static let legacyToolsExpandedKey = "chatTranscript.toolCardsStartExpanded" - /// Carries the three old toggles into the picker once, at launch: cards off is Hidden, - /// either expand toggle on is Expanded, otherwise Collapsed. Afterwards it finds no old - /// keys and does nothing. static func migrateThinkingAndToolCards(in defaults: UserDefaults = .standard) { let legacyKeys = [legacyShowsCardsKey, legacyThinkingExpandedKey, legacyToolsExpandedKey] guard legacyKeys.contains(where: { defaults.object(forKey: $0) != nil }) else { return } @@ -347,36 +310,17 @@ enum ChatTranscriptDisplaySettings { } static let hidesAttachmentPathsKey = "chatTranscript.hidesAttachmentPaths" - /// Settings → Chat "Message Timestamps": the time under each user message - /// and each finished reply. The key name predates the move under the - /// message and stays so a stored choice keeps working. static let showsAssistantTurnTimestampsKey = "chatTranscript.showsAssistantTurnTimestamps" static let defaultShowsTimestamps = true static let showsResponseSpeedKey = "chatTranscript.showsResponseSpeed" - /// Settings → Chat "Fold Finished Turns": settled turns collapse their - /// thinking, tool rows, and interim replies behind one elapsed-time row. static let foldsSettledTurnsKey = "chatTranscript.foldsSettledTurns" - /// Backs the Settings → Chat "Right-to-Left Chat Layout" toggle (issue #259). - /// Local-only: there is no server settings object to mirror an `rtl` flag - /// through today, so the reporter's optional `settings.rtl` server sync is - /// deferred rather than guessed at (project hard rule: never invent API shapes). static let rtlChatLayoutEnabledKey = "chatTranscript.rtlChatLayoutEnabled" - /// The chat-canvas layout direction for a given toggle state. The toggle is a - /// manual override that persists once tapped; its *default* follows the - /// device language (see `rtlChatLayoutDefaultEnabled`). static func chatLayoutDirection(rtlEnabled: Bool) -> LayoutDirection { rtlEnabled ? .rightToLeft : .leftToRight } - /// Whether the user's primary preferred language reads right-to-left - /// (Arabic/Hebrew/Persian/Urdu/…). Read from the device language *preference* - /// — not the app's resolved UI direction — so it still fires for an RTL user - /// even though Hermex isn't translated into their language yet: the app text - /// falls back to English (LTR), but the chat layout should not. Only the - /// primary preference counts (a German-first user with Arabic further down - /// the list is "using German"). `preferredLanguages` is injectable for tests. static func isRightToLeftLanguage( preferredLanguages: [String] = Locale.preferredLanguages ) -> Bool { @@ -384,15 +328,10 @@ enum ChatTranscriptDisplaySettings { return Locale.Language(identifier: primary).characterDirection == .rightToLeft } - /// Default state of the RTL chat toggle: on for RTL-language users so the chat - /// mirrors automatically, off otherwise. Used as the `@AppStorage` default, so - /// a user's explicit toggle still overrides it and persists (#259). static var rtlChatLayoutDefaultEnabled: Bool { isRightToLeftLanguage() } - /// A card's expansion follows the start-expanded preference until the user - /// taps it; the per-card tap override then wins for the rest of the session. static func isCardExpanded(userToggled: Bool?, startsExpanded: Bool) -> Bool { userToggled ?? startsExpanded } @@ -409,11 +348,6 @@ enum ChatTranscriptDisplaySettings { messageID == streamingAssistantMessageID } - /// Whether to draw the `glyph + speed` header above an assistant reply. It - /// only exists to carry Response Speed, so it is limited to real assistant - /// turns with visible text and a measured speed — never user bubbles, - /// system/marker cards, tool-call cards, or empty/tool-only assistant rows. - /// The reply's time lives under the message (`ChatMessageMetaRow`). static func showsAssistantTurnHeader( role: String?, hasTextContent: Bool, @@ -427,11 +361,6 @@ enum ChatTranscriptDisplaySettings { } } -/// Visibility of the optional navigation entries, so a user can hide the parts of -/// the app they never use (issue #189): the session-list utility rows and the -/// chat's Files and Git controls. These buttons are the only way into those -/// screens, so hiding one takes it out of reach until the toggle goes back on. -/// Purely a display preference — nothing stops loading or syncing. enum SectionVisibilitySettings { static let tasksKey = "sectionVisibility.tasks" static let kanbanKey = "sectionVisibility.kanban" @@ -444,12 +373,6 @@ enum SectionVisibilitySettings { static let chatGitKey = "sectionVisibility.chatGit" } -/// App-wide preview gate for Bot Mode (#496): the Bots row on a webui server's main -/// screen. Default off. Not per-server: it hides screens, it is not user data, and Bot -/// connections and drafts stay in the Keychain while it is off. Hermes servers never -/// need it: adding one, moving a webui server to one (#712), its Bots side and its bot -/// links all work with it off. Nor is the Hermes connection screen behind it (#557): -/// that login is what push pairing needs, and push serves a server's webui sessions too. enum BotModeGate { static let isEnabledKey = "botMode.isEnabled" @@ -458,22 +381,11 @@ enum BotModeGate { } } -/// Pure helpers for the few *physical* layout values SwiftUI does not mirror on -/// its own under right-to-left layout (issue #294 — app-wide RTL). Semantic edges -/// (`.leading`/`.trailing`) and toolbar placements flip automatically; these cover -/// the exceptions: a manual `.offset(x:)` and a rotating disclosure chevron. enum RTLLayout { - /// Mirror a physical horizontal offset so a corner-anchored overlay stays on - /// the same visual side as its `.topTrailing`/`.topLeading` anchor: a positive - /// (rightward) offset becomes leftward under RTL. static func horizontalOffset(_ x: CGFloat, isRightToLeft: Bool) -> CGFloat { isRightToLeft ? -x : x } - /// Expand-rotation (degrees) for a disclosure chevron drawn with a mirroring - /// base glyph (`chevron.forward`): collapsed, the glyph already points toward - /// the reveal direction, so the rotation must reverse under RTL for the - /// expanded state to still point *down* rather than up. static func disclosureChevronRotationDegrees(isExpanded: Bool, isRightToLeft: Bool) -> Double { guard isExpanded else { return 0 } return isRightToLeft ? -90 : 90 @@ -487,7 +399,6 @@ enum ChatActiveRunStatusKind: Equatable { case reconnecting case waitingForNetwork case stopping - /// A Hermes session is parked on one of its host's requests (#1011). case waitingForUser var label: String { @@ -529,14 +440,9 @@ enum ChatActiveRunStatusKind: Equatable { } } -/// What the run-status pill above the composer shows. An active run with a -/// start date counts its elapsed time, like the transcript's "Working for" row. struct ChatActiveRunStatusPresentation: Equatable { let kind: ChatActiveRunStatusKind - /// Start of the active run, or nil when the pill shows no time. Only - /// `.active` keeps it; every other kind drops it, so only an active run ticks. let startedAt: Date? - /// The host is compacting the session's context (#1734). Only `.active` keeps it. let isCompacting: Bool init(kind: ChatActiveRunStatusKind, startedAt: Date? = nil, isCompacting: Bool = false) { @@ -545,8 +451,6 @@ struct ChatActiveRunStatusPresentation: Equatable { self.isCompacting = kind == .active && isCompacting } - /// "Hermes is working · 2m 13s" while `startedAt` is set, or the tail row's "Compacting - /// context · 2m 13s" while the host compacts; else the kind's label. func label(now: Date) -> String { guard let startedAt else { return kind.label } if isCompacting { return ChatWorkingRowLabel.text(startedAt: startedAt, now: now, isCompacting: true) } @@ -555,7 +459,6 @@ struct ChatActiveRunStatusPresentation: Equatable { ) } - /// The spoken form of `label(now:)`, matching the tail row's VoiceOver label. func accessibilityLabel(now: Date) -> String { guard let startedAt else { return kind.accessibilityLabel } if isCompacting { @@ -568,11 +471,6 @@ struct ChatActiveRunStatusPresentation: Equatable { } enum ChatActiveRunStatusPolicy { - /// The pill's state while the transcript is scrolled away from its bottom, - /// or nil when it hides. `activeRunStartedAt` is the tail row's start date - /// (`ChatWorkingRowPolicy.startedAt`), so both count from the same start - /// and drop the time in the same cases. `isWaitingForUser` is a Hermes - /// session parked on a host request; `isCompacting`, its host compacting context. static func presentation( isStartingChat: Bool, hasActiveStream: Bool, @@ -614,9 +512,6 @@ enum ChatActiveRunStatusPolicy { } enum ChatWorkingRowPolicy { - /// Start date for the transcript's "Working for" tail row, or nil when the - /// row stays hidden: no active run, the run is being stopped, or the agent - /// is waiting on a clarification or approval answer rather than working. static func startedAt( activeRunStartedAt: Date?, isCancellingStream: Bool, @@ -629,8 +524,6 @@ enum ChatWorkingRowPolicy { } } -/// The words of the transcript's tail row: "Working for 1m 3s", or "Compacting context · 1m 3s" -/// while the host compacts (#1734), which the run-status pill shows too. enum ChatWorkingRowLabel { static func text(startedAt: Date, now: Date, isCompacting: Bool) -> String { let elapsed = ChatWorkingElapsedFormatter.label(startedAt: startedAt, now: now) @@ -646,23 +539,19 @@ enum ChatWorkingRowLabel { } enum ChatWorkingElapsedFormatter { - /// Compact elapsed time for the tail row: `12s`, `1m 4s`, `1h 2m 3s`. static func label(startedAt: Date, now: Date) -> String { label(seconds: now.timeIntervalSince(startedAt)) } - /// Spelled-out elapsed time for VoiceOver: `1 minute, 4 seconds`. static func spokenLabel(startedAt: Date, now: Date) -> String { spokenLabel(seconds: now.timeIntervalSince(startedAt)) } - /// Compact form of a finished span, shared with the settled-turn fold row. static func label(seconds: TimeInterval) -> String { Duration.seconds(wholeSeconds(seconds)) .formatted(.units(allowed: [.hours, .minutes, .seconds], width: .narrow)) } - /// Spelled-out form of a finished span, for VoiceOver. static func spokenLabel(seconds: TimeInterval) -> String { Duration.seconds(wholeSeconds(seconds)) .formatted(.units(allowed: [.hours, .minutes, .seconds], width: .wide)) @@ -674,13 +563,10 @@ enum ChatWorkingElapsedFormatter { } } -/// How a run ended, as far as a local alert cares (#862). A run someone stopped -/// never alerts, because they already know, so it has no case. enum ResponseCompletionOutcome: Equatable { case completed case failed - /// A finalized Live Activity's outcome; nil for a cancelled or still-running one. init?(_ status: AgentRunActivityStatus) { switch status { case .complete: self = .completed @@ -689,7 +575,6 @@ enum ResponseCompletionOutcome: Equatable { } } - /// A chat run's recorded ending; nil for a stopped one. init?(ending: TranscriptTurnRunOutcome.Ending) { switch ending { case .completed: self = .completed @@ -698,7 +583,6 @@ enum ResponseCompletionOutcome: Equatable { } } - /// The Live Activity's own end line, so the alert matches the Lock Screen. var body: String { switch self { case .completed: String(localized: "Response complete") @@ -708,14 +592,6 @@ enum ResponseCompletionOutcome: Equatable { } enum ResponseCompletionNotificationPolicy { - /// Fire a run-ended notification when the user almost certainly isn't watching: - /// notifications are enabled + permitted and the scene is not active when the run - /// ends. Deliberately does NOT depend on any "was streaming" / "was backgrounded - /// during the stream" memory — those in-memory flags were wiped on - /// suspend→cold-relaunch, which is exactly when the stuck-mid-response reports - /// happened (#248). Every in-session run end funnels through one chokepoint, so - /// scene-not-active is the only gate needed. A stopped run never gets here: - /// `ResponseCompletionOutcome` cannot represent it. static func shouldSchedule( preferenceEnabled: Bool, authorizationStatus: UNAuthorizationStatus, @@ -731,22 +607,13 @@ enum ResponseCompletionNotificationPolicy { } } -/// One local alert for a run that ended while the app was not in the foreground. -/// Titled with the chat, bodied with the outcome, and keyed by server and session: -/// the same session ID on two servers never collides, and a newer alert for the -/// same chat replaces the one before it (#862). Its `userInfo` is read back by -/// `destination(userInfo:servers:)` when the alert is tapped. struct ResponseCompletionNotificationRequest: Equatable { static let source = "local" let sessionID: String? let server: URL - /// The chat title when the alert is scheduled, trimmed the way the Live Activity - /// trims it, falling back to "Hermes session". let title: String let outcome: ResponseCompletionOutcome - /// A Hermes chat's Profile, with `sessionID` its stored key (#1177): the tap opens the - /// session link, which looks the session up there. Nil for a webui chat. let hermesProfile: String? init(sessionID: String?, server: URL, title: String, outcome: ResponseCompletionOutcome, hermesProfile: String? = nil) { @@ -759,16 +626,12 @@ struct ResponseCompletionNotificationRequest: Equatable { var body: String { outcome.body } - /// Stable per chat, so a new alert replaces the delivered one. var identifier: String { "run-alert-\(Self.serverHash(server).prefix(16))-\(sessionID ?? "")" } - /// Groups the chat's alerts apart from every other chat's. var threadIdentifier: String { identifier } - /// A hash rather than the URL: iOS keeps delivered alerts, and server URLs are - /// credential-like. No `install_hash`, so it is never read as a relay push (#653). var userInfo: [String: String] { var info = ["server_hash": Self.serverHash(server), "source": Self.source] info["session_id"] = sessionID @@ -776,14 +639,10 @@ struct ResponseCompletionNotificationRequest: Equatable { return info } - /// Lowercase hex SHA-256 of the server's normalized URL. static func serverHash(_ server: URL) -> String { SHA256.hash(data: Data(server.absoluteString.utf8)).map { String(format: "%02x", $0) }.joined() } - /// The link to the chat a tapped local alert names, on a server that is still configured: - /// a Hermes session link when it names a Profile, else the webui session. Nil for a relay - /// push, a removed server, or a missing session, so the tap only opens the app. static func destination(userInfo: [AnyHashable: Any], servers: [URL]) -> URL? { guard userInfo["source"] as? String == source, let hash = userInfo["server_hash"] as? String, @@ -802,9 +661,6 @@ struct ResponseCompletionNotificationCompletionContext: Equatable { let sceneIsActive: Bool } -/// Consumes `ChatViewModel.runEndTrigger`, which bumps once for every run that ends -/// completed or failed, and holds the background task open until that run's alert -/// has been handled. struct ResponseCompletionNotificationTracker { private var lastHandledRunEndTrigger = 0 @@ -812,9 +668,6 @@ struct ResponseCompletionNotificationTracker { runEndTrigger <= lastHandledRunEndTrigger } - /// Returns the context exactly once per run-end trigger, so a run is handled a - /// single time even if the trigger is observed repeatedly. The scene state when - /// the run ends is the only gate the policy needs. mutating func completionContext( runEndTrigger: Int, sceneIsActive: Bool @@ -882,15 +735,10 @@ enum ResponseCompletionNotificationService { struct EnableResult: Equatable { let isEnabled: Bool - /// The permission once any prompt was answered. let authorizationStatus: UNAuthorizationStatus - /// Why the alerts stayed off, for Settings to show; nil when they are on. let message: String? } - /// Turns Response Complete Alerts on, asking iOS for permission only if Hermex never - /// has. Settings' toggle and the chat's one-time offer (#863) both call it, so the - /// prompt, the asked-once flag and the stored preference always agree. @MainActor static func enable( defaults: UserDefaults = .standard, @@ -923,7 +771,6 @@ enum ResponseCompletionNotificationService { return EnableResult(isEnabled: isEnabled, authorizationStatus: status, message: message) } - /// The permission line Settings shows under Response Complete Alerts. static func permissionLabel(_ status: UNAuthorizationStatus) -> String { switch status { case .authorized, .provisional, .ephemeral: @@ -937,9 +784,6 @@ enum ResponseCompletionNotificationService { } } - /// Both the chat's run end and cold-launch Live Activity reconciliation use this. - /// `isCurrent` says whether this is still the chat's latest run end: a newer one - /// schedules under the same identifier, and this older alert must not replace it. @MainActor @discardableResult static func scheduleRunEndedIfAllowed( _ outcome: ResponseCompletionOutcome, @@ -954,8 +798,6 @@ enum ResponseCompletionNotificationService { scheduler: any ResponseCompletionNotificationScheduling = UserNotificationResponseCompletionScheduler() ) async -> Bool { let status = await authorizationStatus(scheduler: scheduler) - // Read after the permission await: a newer run end or a pairing can arrive - // while it is suspended. A paired server's relay alerts for it instead. guard isCurrent() else { return false } if isPushPaired(server) { return false } guard ResponseCompletionNotificationPolicy.shouldSchedule( @@ -985,9 +827,6 @@ private extension UNAuthorizationStatus { } } -/// What a Sessions send does while a response is running. Settings stores the -/// default a tap on Send uses; a long-press on Send picks one for a single -/// message (`ChatComposerSendButton`). enum StreamingSendBehavior: String, CaseIterable, Identifiable, SendChoice { case steer case interrupt @@ -997,7 +836,6 @@ enum StreamingSendBehavior: String, CaseIterable, Identifiable, SendChoice { var id: String { rawValue } - /// The send-choice card's row title and VoiceOver action name. var title: String { switch self { case .steer: @@ -1009,7 +847,6 @@ enum StreamingSendBehavior: String, CaseIterable, Identifiable, SendChoice { } } - /// The same symbols as the Bot card's rows (`BotPromptMode.systemImage`). var systemImage: String { switch self { case .steer: diff --git a/HermesMobile/Config/DevAutoLogin.swift b/HermesMobile/Config/DevAutoLogin.swift index 202bb0b87..7ab53f5f1 100644 --- a/HermesMobile/Config/DevAutoLogin.swift +++ b/HermesMobile/Config/DevAutoLogin.swift @@ -1,30 +1,11 @@ #if DEBUG import Foundation -/// Debug-only sign-in from launch environment variables, so an agent driving a -/// simulator is never blocked on the login screen. `scripts/sim-login ` -/// reads the credentials from the macOS Keychain and passes them through -/// `SIMCTL_CHILD_*`; see `DEVELOPMENT.md`. Both logins go through the normal -/// paths, so credentials land in the simulator's Keychain as a manual login would. -/// -/// - `HERMEX_DEV_SERVER_URL`, `HERMEX_DEV_PASSWORD`: the webui server. -/// - `HERMEX_DEV_BOT_ADDRESS`, `HERMEX_DEV_BOT_USERNAME`, `HERMEX_DEV_BOT_PASSWORD`: -/// the Bot connection saved under that server. Also turns Bot Mode on. -/// - `HERMEX_DEV_HERMES_SERVER=1` (`scripts/sim-login --hermes`): also adds a Hermes -/// server at the Bot address with the same sign-in, and opens it once per launch. @MainActor enum DevAutoLogin { - /// The sign-in under way, if any. It is owned here rather than by the calling - /// view task, because the root view is rebuilt during launch and a cancelled - /// view task would cancel the login requests with it. private static var inFlight: Task? - /// Set once this launch has opened the Hermes server, so switching away from it - /// afterwards sticks. private static var didOpenHermesServer = false - /// Called from the root view's `.task(id: authManager.state)`, so an expired - /// session signs back in. Concurrent calls share one attempt. A failed login - /// leaves the state unchanged and is therefore not retried. static func run( authManager: AuthManager, environment: [String: String] = ProcessInfo.processInfo.environment @@ -40,14 +21,12 @@ enum DevAutoLogin { guard let serverText = environment["HERMEX_DEV_SERVER_URL"], let server = try? AuthManager.normalizedServerURL(from: serverText) else { return } - // The Bot connection is saved first so the Bots inbox finds it on first load. await connectBot(server: server, environment: environment) switch authManager.state { case .loggedIn: break case .loggedOut(let active) where authManager.kind(of: active) == .hermes: - // A signed-out Hermes server keeps its own sign-in form; the webui login never replaces it. break case .loggedOut, .unconfigured: await authManager.configure( @@ -65,8 +44,6 @@ enum DevAutoLogin { } } - /// Switches to the Hermes server at the Bot address, adding it first with a fresh sign-in - /// when it isn't configured yet. private static func openHermesServer(authManager: AuthManager, environment: [String: String]) async { guard let addressText = environment["HERMEX_DEV_BOT_ADDRESS"], let username = environment["HERMEX_DEV_BOT_USERNAME"], @@ -88,7 +65,6 @@ enum DevAutoLogin { if !authManager.addHermesServer(connection) { NSLog("DevAutoLogin: adding the Hermes server failed: %@", authManager.lastErrorMessage ?? "Bot Mode is off") } - // A scripted sign-in isn't the user's, so it doesn't cover the screen with the move offer. authManager.moveOffer = nil } catch { NSLog("DevAutoLogin: Hermes server login failed: %@", String(describing: error)) @@ -100,7 +76,6 @@ enum DevAutoLogin { guard let addressText = environment["HERMEX_DEV_BOT_ADDRESS"], let username = environment["HERMEX_DEV_BOT_USERNAME"], let password = environment["HERMEX_DEV_BOT_PASSWORD"] else { return } - // Turning Bot Mode off keeps the saved connection, so the gate is restored either way. if (try? store.load(server: server)) != nil { UserDefaults.standard.set(true, forKey: BotModeGate.isEnabledKey) return @@ -109,7 +84,6 @@ enum DevAutoLogin { let address = try BotConnection.address(addressText) var connection = BotConnection(id: UUID(), name: address.host ?? "Hermes", address: address, username: username, password: password) - // Not saved yet, so it signs in on its own cookie jar, like the connection form. let wire = BotClient(connection: connection) defer { wire.close() } try await wire.connect() diff --git a/HermesMobile/Config/HitchMeter.swift b/HermesMobile/Config/HitchMeter.swift index 319b999ea..abb8282e2 100644 --- a/HermesMobile/Config/HitchMeter.swift +++ b/HermesMobile/Config/HitchMeter.swift @@ -2,19 +2,12 @@ import QuartzCore import SwiftUI -/// Rolling one-second hitch statistics from display-link frames. A frame is a -/// hitch when it arrives more than half a frame late: the gap since the previous -/// frame exceeds 1.5 × the duration that frame promised -/// (`targetTimestamp − timestamp`). The late time is how far past that promise -/// it landed. struct HitchAccumulator { struct Reading: Equatable { let hitchMillisecondsPerSecond: Double let hitchCount: Int - /// The refresh rate the display link reports, not the delivered frame rate. let hertz: Double - /// `33.3 ms/s · 1 hitch · 60 Hz` var summary: String { let hitches = hitchCount == 1 ? "hitch" : "hitches" let milliseconds = String(format: "%.1f", hitchMillisecondsPerSecond) @@ -33,8 +26,6 @@ struct HitchAccumulator { private var frames: [Frame] = [] private var previous: (timestamp: CFTimeInterval, targetTimestamp: CFTimeInterval)? - /// Adds one display-link callback: `timestamp` is when the last frame was - /// shown, `targetTimestamp` when the next one should be. mutating func record(timestamp: CFTimeInterval, targetTimestamp: CFTimeInterval) { var lateness: CFTimeInterval? if let previous { @@ -63,13 +54,9 @@ struct HitchAccumulator { } } -/// Feeds `HitchAccumulator` from a `CADisplayLink` in `.common` mode, so it keeps -/// measuring while a scroll view is tracking, and publishes a readout at most -/// twice a second so the meter never repaints every frame. @MainActor @Observable final class HitchMeter: NSObject { - /// Launch with `--hitch-meter` to show the overlay (`DEVELOPMENT.md`). static let isEnabled = ProcessInfo.processInfo.arguments.contains("--hitch-meter") private(set) var readout = HitchAccumulator().reading.summary @@ -85,7 +72,6 @@ final class HitchMeter: NSObject { displayLink = link } - /// Invalidates the display link, which also releases its hold on `self`. func stop() { displayLink?.invalidate() displayLink = nil @@ -103,9 +89,6 @@ final class HitchMeter: NSObject { } } -/// The debug readout pinned to the top-leading safe area. It never takes a -/// touch and VoiceOver skips it. It stops while the scene is not active, so time -/// in the background never counts as a hitch. struct HitchMeterOverlay: View { @Environment(\.scenePhase) private var scenePhase @State private var meter = HitchMeter() diff --git a/HermesMobile/Config/NotificationOffer.swift b/HermesMobile/Config/NotificationOffer.swift index 03a2eb9ec..8660f6d3c 100644 --- a/HermesMobile/Config/NotificationOffer.swift +++ b/HermesMobile/Config/NotificationOffer.swift @@ -1,27 +1,14 @@ import SwiftUI import UserNotifications -/// The one-time question after the first run started from the phone (#863): "Want a -/// notification when it’s done?" Asked once per install, never per server. #769's -/// offer after the first Hermes connection checks and sets the same flag, so whichever -/// surface asks first silences the other. enum NotificationOffer { enum Offer: Equatable { - /// Turns on Response Complete Alerts, asking iOS for permission if Hermex never has. case localAlerts - /// Opens Settings → Notifications, where push setup runs behind its own confirmation. case push } - /// Standard `UserDefaults`, per install: a bool is not credential-like. static let hasOfferedKey = "notificationOffer.hasOffered" - /// What to offer, or nil when there is nothing worth asking: already asked, local - /// alerts already on, iOS permission refused, or the active server already paired. - /// `canPair` means this build can push and the active server has a saved Hermes - /// connection to set it up with. Both are Keychain reads, so they are evaluated only - /// when they can still change the answer: never on a denied install, and `canPair` - /// never on a paired server. static func decide( hasOffered: Bool, localAlertsEnabled: Bool, @@ -33,10 +20,6 @@ enum NotificationOffer { return canPair() ? .push : .localAlerts } - /// The offer for a run that just started on `server`, marked as made before it is - /// returned, so a crash or kill can never show it twice. Nil leaves the flag unset, - /// so a later run can still ask. `isCurrent` is read after the permission check: a - /// chat that closed meanwhile shows nothing, so it must not use the offer up. @MainActor static func claim( server: URL, @@ -48,8 +31,6 @@ enum NotificationOffer { }, scheduler: any ResponseCompletionNotificationScheduling = UserNotificationResponseCompletionScheduler() ) async -> Offer? { - // Every send after the offer, or with alerts on, ends here before any permission - // or Keychain read. Denied and paired installs still check permission each send. guard !defaults.bool(forKey: hasOfferedKey), !defaults.bool(forKey: ResponseCompletionNotifications.isEnabledKey) else { return nil } let authorization = await scheduler.authorizationStatus() @@ -67,14 +48,10 @@ enum NotificationOffer { } extension View { - /// Presents a claimed offer as one system alert. Only the offer's own button acts; - /// "Not now" changes no setting and no permission. func notificationOfferAlert(_ offer: Binding) -> some View { modifier(NotificationOfferAlertModifier(offer: offer)) } - /// Publishes `handler` as every descendant chat's way to Settings → Notifications, - /// without invalidating those chats when the caller rebuilds the closure. func openNotificationSettings(perform handler: @escaping () -> Void) -> some View { modifier(OpenNotificationSettingsModifier(handler: handler)) } @@ -115,10 +92,6 @@ private struct NotificationOfferAlertModifier: ViewModifier { } } -/// Opens Settings at Notifications with the push section expanded. `SessionListView` -/// installs it, so every chat it hosts inherits it: opened from the list, a new chat, -/// a fork, or Archived Sessions. A reference, like `ChatDisclosureToggleAction`: a -/// closure rebuilt on every list pass would invalidate every chat reading it. final class OpenNotificationSettingsAction { var handler: () -> Void = {} @@ -136,8 +109,6 @@ extension EnvironmentValues { } } -// The stable instance lives in the modifier's own state, not the caller's, so the -// handler capturing the caller cannot form a cycle that outlives the screen. private struct OpenNotificationSettingsModifier: ViewModifier { let handler: () -> Void @State private var action = OpenNotificationSettingsAction() diff --git a/HermesMobile/Config/PerformanceSignposts.swift b/HermesMobile/Config/PerformanceSignposts.swift index 6de2009e4..6d2c03fda 100644 --- a/HermesMobile/Config/PerformanceSignposts.swift +++ b/HermesMobile/Config/PerformanceSignposts.swift @@ -1,30 +1,10 @@ import OSLog -/// Signpost intervals on the paths users feel most, for Instruments' `os_signpost` -/// instrument: filter by the app's subsystem and category `Performance` -/// (`DEVELOPMENT.md` § Launch arguments and profiling). The intervals are -/// `Launch`, `Session Open`, `Load Earlier`, `Transcript Apply`, `Markdown Parse`, -/// `Stream Batch Apply`, `Cache Read`, and `Cache Write`. `Stream Batch Apply` covers -/// both a stream's reveal ticks (`forced=0`) and the flushes that skip the tick on -/// completion, cancel, error, interim reply and snapshot (`forced=1`). -/// -/// Compiled into every build, because Instruments profiles Release builds and an -/// idle signposter costs almost nothing until a recording turns it on. -/// -/// Privacy: names are static strings and metadata is integers only (counts), -/// marked `.public`. Never put prompt or message text, titles, paths, URLs, -/// session IDs, or model names into a name or its metadata; a trace leaves the -/// device with whoever records it. let performanceSignposter = OSSignposter( subsystem: Bundle.main.bundleIdentifier ?? "HermesMobile", category: "Performance" ) -/// The one `Launch` interval: from the app's `init` to the first frame after a home list -/// (webui's or a Hermes server's) holds session rows, cached or read. Rows in a collapsed group, -/// such as webui's scheduled sessions, count. Pre-main work -/// (dyld, static initializers) is outside it. A launch that never shows rows (onboarding, -/// an empty list) leaves it open; it is never emitted twice. @MainActor enum LaunchSignpost { private static var state: OSSignpostIntervalState? @@ -34,7 +14,6 @@ enum LaunchSignpost { state = performanceSignposter.beginInterval("Launch", id: performanceSignposter.makeSignpostID()) } - /// Ends the interval on the next main-queue turn, so it includes the rows' layout. static func end(rows: Int) { guard !ended, rows > 0, let state else { return } ended = true @@ -44,19 +23,10 @@ enum LaunchSignpost { } } -/// The one open `Session Open` interval: from a session-list open -/// (`SessionListView.startOpeningSession`, so taps and keyboard opens alike, or a Hermes -/// list pushing its chat, which also covers its links and shares) to the first transcript -/// frame in `ChatView`. Webui deep links, App Intents, and notification taps are not measured. -/// -/// The session ID (a Hermes chat's `HermesSessionChat.id`) only matches an end to its begin -/// and is never emitted. @MainActor enum SessionOpenSignpost { private static var pending: (sessionID: String, state: OSSignpostIntervalState)? - /// Starts timing an open. An earlier open that has not finished ends here - /// first, so no interval is left dangling. static func begin(sessionID: String?) { if let pending { performanceSignposter.endInterval("Session Open", pending.state) @@ -67,9 +37,6 @@ enum SessionOpenSignpost { pending = (sessionID, state) } - /// Ends the open of `sessionID` with its transcript size, or with no metadata - /// when `messages` is nil because the open failed before a chat showed. Does - /// nothing for any other session, or once that open has ended. static func end(sessionID: String?, messages: Int?) { guard let pending, pending.sessionID == sessionID else { return } self.pending = nil diff --git a/HermesMobile/Config/RatingPromptState.swift b/HermesMobile/Config/RatingPromptState.swift index 4b15e5309..d01479f65 100644 --- a/HermesMobile/Config/RatingPromptState.swift +++ b/HermesMobile/Config/RatingPromptState.swift @@ -1,6 +1,5 @@ import Foundation -/// Only completed main-app replies count. Later requests require both cooldowns. struct RatingPromptPolicy { static let day: TimeInterval = 24 * 60 * 60 @@ -30,7 +29,6 @@ enum RatingPromptMoment { case returnedToSessionList } -/// Persists engagement across servers; launch guards and weak stream owners stay in memory. @MainActor final class RatingPromptState { static let shared: RatingPromptState = { @@ -49,7 +47,6 @@ final class RatingPromptState { } private let defaults: UserDefaults - /// Also counts each completed response for the week's usage report, when reports are allowed. private let usage: UsageReports? private var streamOwners: [StreamOwner] = [] private(set) var isFirstLaunch: Bool @@ -78,7 +75,6 @@ final class RatingPromptState { usage?.recordCompletedResponse(now: now) } - /// A webui stream or a Hermes chat on `server`; a running turn holds the request back. func register(_ coordinator: any ChatTurnCoordinating, server: URL) { streamOwners.removeAll { $0.coordinator == nil } streamOwners.append(StreamOwner(coordinator: coordinator, server: server)) @@ -88,9 +84,6 @@ final class RatingPromptState { streamOwners.contains { $0.server == server && $0.coordinator?.activeStreamID != nil } } - // The list checks card eligibility before rating requests and records display here, - // so dismissing a card cannot allow a rating request, or the other card, later in the - // same launch. func recordCardShown(_ card: SessionListCard) { if cardShownThisLaunch == nil { cardShownThisLaunch = card } } @@ -99,8 +92,6 @@ final class RatingPromptState { !isFirstLaunch && cardShownThisLaunch == nil && policy.isEligible(at: now) } - /// Check all server sessions, including rows hidden by sidebar filters. Recheck - /// local ownership and navigation after the await; failure simply skips this moment. func requestWhenQuiet( moment: RatingPromptMoment, server: URL, @@ -121,11 +112,9 @@ final class RatingPromptState { request: request ) } catch { - // An optional prompt never turns a connection failure into a user-facing error. } } - /// Record the attempt before invoking StoreKit; Apple may choose not to show anything. @discardableResult func requestIfEligible( moment: RatingPromptMoment, @@ -152,7 +141,6 @@ final class RatingPromptState { cardShownThisLaunch = nil } - /// Launch-only override for exercising the real navigation and stream guards. private func prepareForTesting(now: Date = Date()) { reset(now: now.addingTimeInterval(-4 * RatingPromptPolicy.day)) defaults.set(10, forKey: TipJar.completedResponseCountKey) diff --git a/HermesMobile/Config/RenderProbe.swift b/HermesMobile/Config/RenderProbe.swift index 87bd31fff..37329c30c 100644 --- a/HermesMobile/Config/RenderProbe.swift +++ b/HermesMobile/Config/RenderProbe.swift @@ -1,23 +1,8 @@ -/// Counts SwiftUI body evaluations of the transcript's heavy views, so a test can -/// check that a stream tick re-renders only the row it changed -/// (`ChatTranscriptRenderBudgetTests`). Each probed view calls `hit` once at the -/// top of its `body` (or, for `ResponseTextSelection`, its host update), and -/// `ChatTranscriptMessageBlock.==` counts each comparison and each that finds a change. -/// -/// Debug builds keep the counts in memory only, by name and by transcript row -/// `renderID`; nothing is logged or sent anywhere. Release builds compile `hit` to an -/// empty inlined function and keep no storage. Inspect the counts from lldb, for -/// example `po RenderProbe.snapshot`, after `RenderProbe.reset()` and a stream. @MainActor enum RenderProbe { - /// The probed bodies. Static names only: a row's identity is a separate key. enum Name: String { case transcriptMessageBlock = "ChatTranscriptMessageBlock" - /// A `ChatTranscriptMessageBlock.==` that returned false: a row whose inputs - /// changed, as opposed to an equal row SwiftUI re-ran anyway. case transcriptMessageBlockUnequal = "ChatTranscriptMessageBlock.unequal" - /// Every `ChatTranscriptMessageBlock.==` call. Zero while rows re-render means - /// SwiftUI never consulted the rows' `.equatable()` comparison. case transcriptMessageBlockCompared = "ChatTranscriptMessageBlock.compared" case messageBubble = "MessageBubbleView" case markdownRenderer = "MarkdownRenderer" @@ -30,7 +15,6 @@ enum RenderProbe { private static var counts: [Name: Int] = [:] private static var renderIDCounts: [String: Int] = [:] - /// Records one evaluation of `name`, and of the transcript row `renderID` when given. static func hit(_ name: Name, renderID: String? = nil) { counts[name, default: 0] += 1 if let renderID { @@ -38,7 +22,6 @@ enum RenderProbe { } } - /// Clears every count; call before the window you want to measure. static func reset() { counts = [:] renderIDCounts = [:] @@ -48,12 +31,10 @@ enum RenderProbe { counts[name] ?? 0 } - /// Evaluations of the transcript row with this `renderID` since the last reset. static func count(renderID: String) -> Int { renderIDCounts[renderID] ?? 0 } - /// Every named total since the last reset, keyed by static name. static var snapshot: [String: Int] { Dictionary(uniqueKeysWithValues: counts.map { ($0.key.rawValue, $0.value) }) } diff --git a/HermesMobile/Config/SessionListCardState.swift b/HermesMobile/Config/SessionListCardState.swift index 945b9c43d..d59303c7e 100644 --- a/HermesMobile/Config/SessionListCardState.swift +++ b/HermesMobile/Config/SessionListCardState.swift @@ -1,27 +1,19 @@ import Foundation -/// The prompt cards that share the slot at the top of the session list. enum SessionListCard: CaseIterable { - /// Asks once whether to send usage reports (#1662), and again when the report gains fields. case usageReports case tip, star - /// The card to show. At most one per launch: once a card has shown, the others wait for a - /// later launch. When several are eligible, the first in `allCases` wins. static func choose(eligible: Set, shownThisLaunch: SessionListCard?) -> SessionListCard? { if let shownThisLaunch { return eligible.contains(shownThisLaunch) ? shownThisLaunch : nil } return allCases.first(where: eligible.contains) } - /// The card a session list shows now, on the device's standard defaults. The caller passes - /// the stored counter, dismissed releases and usage report answers from its `@AppStorage`, - /// so reading them subscribes its view and an answer hides a card at once. @MainActor static func current(completedResponses: Int, tipDismissedRelease: String?, starDismissedRelease: String?, usageReportConsent: UsageReportConsent, forcesUsageReportsCard: Bool = false, hasSharedImport: Bool) -> SessionListCard? { #if DEBUG - // Settings › Developer: skip every guard while the question is unanswered. if forcesUsageReportsCard, usageReportConsent.question() != nil { return .usageReports } #endif let ratingPolicy = RatingPromptState.shared.policy @@ -41,8 +33,6 @@ enum SessionListCard: CaseIterable { return choose(eligible: eligible, shownThisLaunch: RatingPromptState.shared.cardShownThisLaunch) } - /// `current` on the stored values, for a check outside a view's body, such as a rating - /// request recording the card the list shows. @MainActor static func current(hasSharedImport: Bool) -> SessionListCard? { let defaults = UserDefaults.standard @@ -54,8 +44,6 @@ enum SessionListCard: CaseIterable { hasSharedImport: hasSharedImport) } - /// The usage reports card waits for 5 completed responses and an unanswered question, under - /// the same share and rating guards as the other cards. It has no X: only an answer hides it. static func usageReportsEligible(question: UsageReportConsent.Question?, completedResponses: Int, hasSharedImport: Bool, ratingPolicy: RatingPromptPolicy, now: Date = Date()) -> Bool { question != nil && completedResponses >= Self.usageReports.minimumResponses && !hasSharedImport && ratingPolicy.allowsSessionListCard(at: now) @@ -69,7 +57,6 @@ enum SessionListCard: CaseIterable { } } - /// The tip and star cards' stored answers; the usage reports card keeps its own in `UsageReports`. fileprivate var promptKeys: (dismissedRelease: String, linkOpened: String)? { switch self { case .usageReports: return nil @@ -79,16 +66,11 @@ enum SessionListCard: CaseIterable { } } -/// The tip or star card's device-wide preferences: opening its link records intent (not a -/// payment or a star, which the app cannot see) and hides the card for good. "Not now" hides it -/// until the next feature release. struct SessionListCardState { let card: SessionListCard let defaults: UserDefaults - /// The installed marketing version; tests inject one. var appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "" - /// Major.minor, so a patch update never brings a dismissed card back. var release: String { appVersion.split(separator: ".").prefix(2).joined(separator: ".") } @@ -107,22 +89,18 @@ struct SessionListCardState { defaults.set(release, forKey: keys.dismissedRelease) } - /// Settings › About's rows call this directly; the card's own button goes through - /// `openLinkFromCard`, which also tallies it. func recordLinkOpened() { guard let keys = card.promptKeys else { return } defaults.set(true, forKey: keys.linkOpened) dismiss() } - /// The card's own button: hides it for good and tallies `link_opened`, not `dismissed`. @MainActor func openLinkFromCard(usage: UsageReports? = nil, now: Date = Date()) { recordLinkOpened() (usage ?? .shared).record(card, \.linkOpened, now: now) } - /// The card's X. @MainActor func dismissFromCard(usage: UsageReports? = nil) { dismiss() @@ -130,8 +108,6 @@ struct SessionListCardState { } } -/// One welcome per launch, then a short gesture every 3.5 seconds while visible. Whichever -/// session list card is showing owns the task; there are no frame updates during neutral pauses. @MainActor final class SessionListCardGreeting { static let shared = SessionListCardGreeting() @@ -139,8 +115,6 @@ final class SessionListCardGreeting { enum Phase { case neutral, blink, hop, glanceDown, curious, happy } - /// The view owns cancellation. Each awaited pause must finish successfully and - /// still belong to an active task before another expression can be displayed. func play( reduceMotion: Bool, wait: (Duration) async throws -> Void = { try await Task.sleep(for: $0) }, @@ -184,12 +158,10 @@ final class SessionListCardGreeting { try await wait(gesture.hold) try Task.checkCancellation() display(.neutral) - // Measure the cadence from one gesture's start to the next. pause = .milliseconds(3500) - gesture.hold } } } catch { - // Dismissal, navigation, backgrounding or Reduce Motion stops the sequence. } } } diff --git a/HermesMobile/Config/UsageReports.swift b/HermesMobile/Config/UsageReports.swift index a84ef13d1..77aee6501 100644 --- a/HermesMobile/Config/UsageReports.swift +++ b/HermesMobile/Config/UsageReports.swift @@ -2,8 +2,6 @@ import Foundation import StoreKit import UIKit -/// Something the user did during the week (#1662). The raw values are the report's -/// `features` keys; `docs/agents/usage-reports.md` lists where each is observed. enum UsageFeature: String, CaseIterable, Codable, CodingKey { case workspace, tasks, skills, memory, insights, kanban, bots case shareExtension = "share_extension" @@ -13,7 +11,6 @@ enum UsageFeature: String, CaseIterable, Codable, CodingKey { case appIntents = "app_intents" } -/// One prompt card's week: on screen, closed with its X, its own button opened. struct UsageCardTally: Codable, Equatable { var shown = false var dismissed = false @@ -25,7 +22,6 @@ struct UsageCardTally: Codable, Equatable { } } -/// A UTC ISO week, named by its Monday at 00:00 UTC. struct UsageWeekID: Codable, Hashable { let monday: Date @@ -41,7 +37,6 @@ struct UsageWeekID: Codable, Hashable { var previous: UsageWeekID { UsageWeekID(containing: monday.addingTimeInterval(-24 * 60 * 60)) } - /// `YYYY-Www`, as the report names it. var id: String { let parts = Self.calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: monday) return String(format: "%04d-W%02d", parts.yearForWeekOfYear ?? 0, parts.weekOfYear ?? 0) @@ -51,23 +46,19 @@ struct UsageWeekID: Codable, Hashable { Self.calendar.isDate(monday, equalTo: other.monday, toGranularity: .month) } - /// `YYYY-MM-DD` in UTC. static func day(_ date: Date) -> String { date.formatted(Date.ISO8601FormatStyle(timeZone: .gmt).year().month().day()) } } -/// The local tallies for one week. Callers only ever hand in booleans and counts. struct UsageTallies: Codable, Equatable { var week: UsageWeekID - /// UTC days (`YYYY-MM-DD`) in which the app came to the foreground. var activeDays: Set = [] var completedResponses = 0 var features: Set = [] var tip = UsageCardTally() var star = UsageCardTally() - /// The before-consent preview's weekly values: plausible, and labelled as samples. static func sample(week: UsageWeekID) -> UsageTallies { UsageTallies(week: week, activeDays: Set((0..<5).map { UsageWeekID.day(week.monday.addingTimeInterval(Double($0) * 86_400)) }), completedResponses: 42, features: [.workspace, .insights, .bots, .liveActivity], @@ -75,8 +66,6 @@ struct UsageTallies: Codable, Equatable { } } -/// What this phone is, read when a report is built. Makes no request beyond StoreKit's -/// local app transaction, which only tells TestFlight from the App Store. struct UsageDevice: Equatable { var channel: UsageReport.Channel var appVersion: String @@ -91,13 +80,11 @@ struct UsageDevice: Equatable { appVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0.0", osVersion: UIDevice.current.systemVersion, deviceModel: hardwareModel, - // The app's display language, which can differ from the device's. language: String((Bundle.main.preferredLocalizations.first ?? "en").prefix(16)), region: region(Locale.current.region?.identifier) ) } - /// TestFlight installs carry a sandbox app transaction; anything unreadable counts as the App Store. private static func channel() async -> UsageReport.Channel { guard let result = try? await AppTransaction.shared else { return .appstore } switch result { @@ -106,7 +93,6 @@ struct UsageDevice: Equatable { } } - /// The hardware identifier, such as `iPhone17,2`; a simulator reports the model it simulates. private static var hardwareModel: String { if let simulated = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] { return simulated } var info = utsname() @@ -114,22 +100,15 @@ struct UsageDevice: Equatable { return withUnsafeBytes(of: &info.machine) { bytes in String(decoding: bytes.prefix { $0 != 0 }, as: UTF8.self) } } - /// Two capital letters or three digits, as the collector accepts; `ZZ` (unknown) otherwise. static func region(_ identifier: String?) -> String { guard let identifier, identifier.wholeMatch(of: /[A-Z]{2}|[0-9]{3}/) != nil else { return "ZZ" } return identifier } } -/// The weekly usage report, exactly as it goes on the wire (#1659): every key required and -/// every value inside the collector's limits. `UsageReports` builds it, and the preview shows -/// the same value the sender encodes. It has no field that could hold a URL or a name. struct UsageReport: Encodable, Equatable { - /// The newest format this build can encode. Each user's reports use the version they accepted. static let currentVersion = 2 - /// The fields each later format added, which the re-prompt names. Version 2 added each - /// server's `gateway`. static func fieldsAdded(after version: Int) -> [String] { version < 2 ? [String(localized: "whether each Hermes server is a Webapp or a dashboard")] : [] } @@ -145,12 +124,9 @@ struct UsageReport: Encodable, Equatable { struct Version: Encodable, Equatable { var kind: ServerKind var version: String - /// From format 2; nil, and so absent from the JSON, in format 1. var gateway: Gateway? } - /// What a server's last sign-in reached; `unknown` for a webui server or a Hermes server - /// not signed in since this was recorded. enum Gateway: String, Encodable { case webapp, dashboard, unknown } struct Features: Encodable, Equatable { @@ -205,8 +181,6 @@ struct UsageReport: Encodable, Equatable { case completedResponses = "completed_responses" } - /// The one builder the preview and the sender share. It reads only each server's kind and - /// known release, and makes no request. init(version: Int, tallies: UsageTallies, firstReportOfMonth: Bool, installDate: Date, device: UsageDevice, servers: [ServerAccount], settings: Settings) { v = version @@ -234,8 +208,6 @@ struct UsageReport: Encodable, Equatable { cards = Cards(tip: tallies.tip, star: tallies.star) } - /// A plain release number, `other` for any other string, or `unknown` when the app knows - /// none: a webui server stores no version. static func reportedVersion(of server: ServerAccount) -> String { guard server.kind == .hermes, let version = server.serverVersion else { return "unknown" } return version.wholeMatch(of: /[0-9]+(\.[0-9]+){1,3}/) != nil ? version : "other" @@ -256,22 +228,15 @@ struct UsageReport: Encodable, Equatable { } } -/// The device's answer about usage reports. One answer covers every server. struct UsageReportConsent: Equatable { - /// The format the user allowed; nil while reports are off. var acceptedVersion: Int? - /// The newest format the user said No thanks to, or turned reports off at. var declinedVersion: Int? enum Question: Equatable { - /// The first ask. case allow - /// The report gained fields since the version the user allowed. case moreFields([String]) } - /// What the session list card asks now, if anything. No thanks and turning reports off are - /// both permanent for that format. func question(currentVersion: Int = UsageReport.currentVersion) -> Question? { guard (declinedVersion ?? 0) < currentVersion else { return nil } guard let acceptedVersion else { return declinedVersion == nil ? .allow : nil } @@ -279,14 +244,11 @@ struct UsageReportConsent: Equatable { } } -/// Consent, the week's tallies and the weekly send (#1662), device-wide in `UserDefaults`. -/// Nothing is tallied unless reports are allowed and at least one server is configured. @MainActor final class UsageReports { static let shared = UsageReports(defaults: .standard) static let collectorURL = URL(staticString: "https://hermex-stats.uzairansar.com/v1/report") - /// Debug builds never send. nonisolated static var buildSends: Bool { #if DEBUG false @@ -299,10 +261,8 @@ final class UsageReports { static let acceptedVersion = "usageReports.acceptedVersion" static let declinedVersion = "usageReports.declinedVersion" static let week = "usageReports.week" - /// Last week's tallies, waiting for the next foreground to send them. static let endedWeek = "usageReports.endedWeek" static let lastAttemptedWeek = "usageReports.lastAttemptedWeek" - /// Debug builds: Settings › Developer shows the card past its guards until answered. static let debugForcesCard = "usageReports.debugForcesCard" } @@ -330,8 +290,6 @@ final class UsageReports { self.currentVersion = currentVersion } - // MARK: - Consent - var consent: UsageReportConsent { UsageReportConsent(acceptedVersion: defaults.object(forKey: Keys.acceptedVersion) as? Int, declinedVersion: defaults.object(forKey: Keys.declinedVersion) as? Int) @@ -339,19 +297,15 @@ final class UsageReports { var isAllowed: Bool { consent.acceptedVersion != nil } - /// Allow, on the card or in Settings: reports use the newest format, and today counts as active. func allow(now: Date = Date()) { defaults.set(currentVersion, forKey: Keys.acceptedVersion) recordActiveDay(now) } - /// No thanks: the card never asks again for this format. On the re-prompt, reports keep - /// going in the format already allowed. func decline() { defaults.set(currentVersion, forKey: Keys.declinedVersion) } - /// Settings off: stops sending and erases the tallies. Reports already sent stay sent. func turnOff() { defaults.removeObject(forKey: Keys.acceptedVersion) defaults.set(currentVersion, forKey: Keys.declinedVersion) @@ -360,7 +314,6 @@ final class UsageReports { } #if DEBUG - /// Settings › Developer's toggle: forgets the answer and the week so the card asks again. func forgetAnswerForTesting() { for key in [Keys.acceptedVersion, Keys.declinedVersion, Keys.week, Keys.endedWeek] { defaults.removeObject(forKey: key) @@ -368,11 +321,8 @@ final class UsageReports { } #endif - // MARK: - Tallies - private var isRecording: Bool { isAllowed && !servers().isEmpty } - /// This week's tallies so far; nil before anything is recorded. var thisWeek: UsageTallies? { load(Keys.week) } func record(_ feature: UsageFeature, now: Date = Date()) { @@ -383,7 +333,6 @@ final class UsageReports { update(now) { $0.completedResponses += 1 } } - /// A tip or star card event seen at the card itself; Settings › About's matching rows never count. func record(_ card: SessionListCard, _ event: WritableKeyPath, now: Date = Date()) { switch card { case .tip: update(now) { $0.tip[keyPath: event] = true } @@ -403,8 +352,6 @@ final class UsageReports { save(tallies, forKey: Keys.week) } - /// Sets aside tallies from the week that just ended for the next send, discards anything - /// older, and returns this week's. private func rollOver(_ now: Date) -> UsageTallies { let week = UsageWeekID(containing: now) if let stored: UsageTallies = load(Keys.week), stored.week != week { @@ -417,11 +364,6 @@ final class UsageReports { return load(Keys.week) ?? UsageTallies(week: week) } - // MARK: - Reports - - /// Each foreground: counts today, which first sets aside the week that just ended, then - /// sends that week once. The attempt is recorded before posting, and a failure is never - /// retried, even after a relaunch. func appBecameActive(now: Date = Date()) async { recordActiveDay(now) await sendEndedWeek(now: now) @@ -432,9 +374,6 @@ final class UsageReports { _ = rollOver(now) guard defaults.data(forKey: Keys.endedWeek) != nil else { return } let device = await device() - // Read the tallies only after the await, so turning reports off meanwhile, even - // if they're turned on again, leaves nothing to send. From here to the request - // nothing waits, so consent is checked just before it. guard let ended: UsageTallies = load(Keys.endedWeek) else { return } defaults.removeObject(forKey: Keys.endedWeek) guard lastAttemptedWeek != ended.week else { return } @@ -450,14 +389,11 @@ final class UsageReports { _ = try? await session.data(for: request) } - /// The report for the week in progress, as it would be sent; the example before consent. - /// `asking` builds it in the newest format, as the consent card's re-prompt asks for it. func preview(now: Date = Date(), asking: Bool = false) async -> UsageReport { let week = UsageWeekID(containing: now) guard let accepted = consent.acceptedVersion else { return build(version: currentVersion, tallies: .sample(week: week), firstOfMonth: true, device: await device()) } - // Roll over before the await: resuming in a later week with this `now` would discard that week's tallies. let tallies = rollOver(now) return build(version: asking ? currentVersion : accepted, tallies: tallies, firstOfMonth: isFirstReport(ofMonthOf: week), device: await device()) } @@ -473,13 +409,11 @@ final class UsageReports { (defaults.object(forKey: Keys.lastAttemptedWeek) as? Date).map(UsageWeekID.init(containing:)) } - /// True until a report for another week whose Monday is in the same UTC month was attempted. private func isFirstReport(ofMonthOf week: UsageWeekID) -> Bool { guard let last = lastAttemptedWeek, last != week else { return true } return !last.isInSameMonth(as: week) } - /// Push is on when any configured server has a pairing; App Lock is the device setting. static func liveSettings(servers: [ServerAccount]) -> UsageReport.Settings { let paired = Set(((try? KeychainPushPairingStore()?.allPairings()) ?? [:]).keys.map(\.absoluteString)) return UsageReport.Settings(pushEnabled: servers.contains { paired.contains($0.id) }, @@ -496,7 +430,6 @@ final class UsageReports { } extension URLSessionConfiguration { - /// No cookies, cache, credentials or custom headers: the report body is the whole request. static var usageReports: URLSessionConfiguration { let configuration = URLSessionConfiguration.ephemeral configuration.httpCookieStorage = nil diff --git a/HermesMobile/ContentView.swift b/HermesMobile/ContentView.swift index c06bfab4f..a16005426 100644 --- a/HermesMobile/ContentView.swift +++ b/HermesMobile/ContentView.swift @@ -18,32 +18,23 @@ struct ContentView: View { guard !didCheckInitialPendingShare else { return } didCheckInitialPendingShare = true importPendingSharedDraftIfAvailable() - // Cold launch: an App Intent may have queued a deep link before this - // view appeared (e.g. Action button "New Chat"). Drain it now (#337). drainPendingIntentDeepLink() await UsageReports.shared.appBecameActive() } .onChange(of: intentRouter.pendingDeepLink) { - // Warm launch: the intent set the deep link after the view appeared. drainPendingIntentDeepLink() } .onChange(of: authManager.state) { - // A held conversation link resolves again once sign-in or a server switch - // changes what it can reach. switchServer(pendingLinks.reroute(state: authManager.state, servers: authManager.servers, isBotModeEnabled: isBotModeEnabled)) - // The home went, and a Shortcut text's chat with it. shares.endReview() switchServer(shares.shortcutRoute(state: authManager.state, servers: authManager.servers)) } - // A Shortcut's text opens only on the server it named (#1402), which may not be active. .onChange(of: shares.pending?.reservationID) { switchServer(shares.shortcutRoute(state: authManager.state, servers: authManager.servers)) } .alert((unopenableShortcut?.sharedImport.shortcut?.origin ?? .shortcut).cantOpenTitle, isPresented: Binding(get: { unopenableShortcut != nil }, set: { isPresented in - // Dismissed without a button (Escape, VoiceOver's escape) is Not Now. A button's - // action may run after this, so the release waits a turn and skips a settled text. guard !isPresented, let share = unopenableShortcut else { return } Task { @MainActor in if shares.pending?.reservationID == share.reservationID { releasePendingSharedImport(share) } @@ -55,41 +46,23 @@ struct ContentView: View { Text("The server for this text was removed from Hermex, so it can’t open.") } .task { - // #246: on cold launch, end any Live Activity left "running" by a - // run that finished while the app was terminated. #248: this is also - // the one pass allowed to alert for a recent run that completed or - // failed, since a relaunch means it ended while not active. await reconcileOrphanedLiveActivities(notifiesOnCompletion: true) - // #489: a bot activity has no server status to reconcile against. - // #566: a finished webui activity releases its relay registration. - // #1179: an unpaired Hermes session's is checked once against its host. await AgentLiveActivityManager.shared.settleActivitiesFromPreviousLaunch(checking: hermesRunCheck()) } .onChange(of: scenePhase) { - // Closes the shared Bot socket cleanly on background; Control Center and - // banners (`.inactive`) keep it. Each Bot screen also suspends on - // background; the chat, inbox, rooms and editor reconnect on `.active`, - // and the creators on their next Create (#902). if scenePhase == .background { HermesConnections.shared.closeForBackground() } guard scenePhase == .active else { return } - // Sends last week's usage report once, when reports are allowed (#1662). Task { await UsageReports.shared.appBecameActive() } importPendingSharedDraftIfAvailable() - // #248: the foreground pass stays silent — the in-session run-end - // paths own notifications while the app is alive. Task { await reconcileOrphanedLiveActivities(notifiesOnCompletion: false) } } .onChange(of: NetworkPathMonitor.shared.changeCount) { - // A handover can leave the shared Bot socket open but dead; one probe checks it - // for every Bot screen (#1372). The background already closed it. guard scenePhase != .background, NetworkPathMonitor.shared.isSatisfied else { return } HermesConnections.shared.networkPathDidChange() } } private func reconcileOrphanedLiveActivities(notifiesOnCompletion: Bool) async { - // Only webui runs can be reconciled against a server. A Hermes session's activity - // (#1014) has no stream status to ask, and orphanedActivities() skips it. guard case let .loggedIn(server) = authManager.state, authManager.kind(of: server) == .webui else { return } await LiveActivityReconciler.reconcileOrphanedActivities( server: server, @@ -98,9 +71,6 @@ struct ContentView: View { ) } - /// The signed-in active Hermes server's one `session.active_list` read for cold launch - /// (#1179), over its saved connection; nil on a webui server or without a sign-in. The read is - /// made only if an unpaired Hermes session's activity needs it. private func hermesRunCheck() -> AgentLiveActivityManager.HermesRunCheck? { guard case let .loggedIn(server) = authManager.state, authManager.kind(of: server) == .hermes, let connection = try? BotConnectionStore().load(server: server) else { return nil } @@ -144,11 +114,6 @@ struct ContentView: View { pendingBotDestination: $pendingLinks.bot, pendingWebuiPush: $pendingLinks.webuiPush ) - // Switching the active server keeps us in `.loggedIn`, so without a - // per-server identity SwiftUI would reuse the same SessionListView (and - // its server-bound view model), leaving stale sessions/chat on screen. - // Keying on the server tears the whole stack down and rebuilds it - // against the newly active server (#17). .id(server) } } @@ -165,26 +130,16 @@ struct ContentView: View { return } - // A fresh request each time (new `id`) so a repeat invocation re-triggers navigation - // even if the previous one's value still lingers downstream. The voice variant carries - // `autoStartsVoiceInput` so the composer begins dictation once it appears (#338). if HermesDeepLink.isNewChatVoiceURL(url) { openNewChat(autoStartsVoiceInput: true) return } - // A Hermes server's Profile opens a new session on that server (#1180), switching to it - // or waiting for its sign-in first. if let destination = HermesNewChatDestination(url: url) { switchServer(pendingLinks.open(destination, state: authManager.state, servers: authManager.servers)) return } - // The profile variant carries the chosen profile name, so the composer creates the - // session pinned to it (#339). A malformed link with no profile falls back to a - // plain new chat (server's active profile) rather than failing; one naming a server - // that didn't parse above opens nothing. A webui server that moved sends its Profile - // where Review mapped it, unless another place could take it too (#1217). if HermesDeepLink.isWebuiNewChatInProfileURL(url) { let profile = HermesDeepLink.profileName(fromNewChatInProfile: url) switch MovedWebuiRoute.newChat(inProfile: profile, active: authManager.state.server, @@ -204,16 +159,12 @@ struct ContentView: View { return } - // A bot link carries its own server, Bot connection and Profile, so it may - // have to switch servers or wait for sign-in before it can open (#554). if let destination = HermesDeepLink.botDestination(from: url) { switchServer(pendingLinks.route(destination, state: authManager.state, servers: authManager.servers, isBotModeEnabled: isBotModeEnabled)) return } - // A Bot widget names its server by digest and its bot by Profile only (#1643), so it finds - // the server's current Bot connection, or waits for a signed-out Hermes server's sign-in. if let destination = BotWidgetDestination(url: url) { UsageReports.shared.record(.homeWidget) switchServer(pendingLinks.open(destination, state: authManager.state, servers: authManager.servers, @@ -221,23 +172,17 @@ struct ContentView: View { return } - // A Limits widget's tap opens Usage only on the signed-in active server and connection its - // limits were read through (#1409), never switching servers; anything else opens the app as is. if let usage = HermesUsageDestination(url: url) { UsageReports.shared.record(.homeWidget) if usage.opens(state: authManager.state, servers: authManager.servers) { pendingLinks.hermesUsage = usage } return } - // A session link that names its server opens there, Hermes or webui, or nowhere when that - // server isn't usable (#1176); one that doesn't keeps the webui route it always had. if let destination = HermesSessionDestination(url: url) { switchServer(pendingLinks.open(destination, state: authManager.state, servers: authManager.servers)) return } - // A bare session link names no server: once a webui server moved, it opens only where it - // can't be another server's (#1217). if let sessionID = HermesDeepLink.sessionID(from: url) { switch MovedWebuiRoute.bareSession(sessionID, active: authManager.state.server, servers: authManager.servers) { case .webui(let route): @@ -257,13 +202,10 @@ struct ContentView: View { importPendingSharedDraftIfAvailable() } - /// Activates the server a held link's route asked for; the rebuilt tree takes the link. private func switchServer(_ account: ServerAccount?) { if let account { authManager.switchActiveServer(to: account) } } - /// New Chat and New Chat with Voice: a new Hermes session on an active Hermes server, in - /// the Profile its New Session uses (#1180), else the webui New Chat composer. private func openNewChat(autoStartsVoiceInput: Bool) { if let hermes = HermesNewChatDestination.onActiveServer(state: authManager.state, servers: authManager.servers, autoStartsVoiceInput: autoStartsVoiceInput) { @@ -273,17 +215,10 @@ struct ContentView: View { } } - /// Readies a webui-only entry point (a webui Profile's New Chat in Profile, a legacy - /// session link) and returns whether it can go ahead. While a Hermes server is active it - /// switches to the first webui server, as a webui push tap does, and the rebuilt - /// session list takes the held request. With no webui server it opens nothing: a Hermes-only - /// user is never asked to add one (#1181). On a webui server, or with nothing configured, - /// there is nothing to do. private func reachWebuiServer() -> Bool { enter(WebuiEntryRoute.resolve(active: authManager.state.server, servers: authManager.servers)) } - /// Takes `route` and returns whether the webui entry point can go ahead. private func enter(_ route: WebuiEntryRoute) -> Bool { switch route { case .stay: @@ -296,15 +231,10 @@ struct ContentView: View { } } - /// Keeps a share the Hermes home can't open queued (it has no saved connection, or the list - /// left before the user discarded a share its draft couldn't take), to be offered again on - /// the next launch or return to the app. private func releasePendingSharedImport(_ reservation: SharedImportReservation) { shares.release(reservation, in: HermesShareDraft.containerURL()) } - /// Routes a deep link queued by an App Intent through the same `handleOpenURL` parser - /// used for external URLs, then clears it so it routes exactly once (#337). private func drainPendingIntentDeepLink() { guard let url = intentRouter.pendingDeepLink else { return } intentRouter.pendingDeepLink = nil @@ -316,7 +246,6 @@ struct ContentView: View { } private func consumePendingSharedImport(_ reservation: SharedImportReservation) { - // A share from the share extension; a Shortcut's queued text has a destination instead. if reservation.sharedImport.shortcut == nil { UsageReports.shared.record(.shareExtension) } shares.consume(reservation, in: HermesShareDraft.containerURL(), active: authManager.state.server, servers: authManager.servers) @@ -326,8 +255,6 @@ struct ContentView: View { shares.openNext(in: HermesShareDraft.containerURL(), active: authManager.state.server, servers: authManager.servers) } - /// The Shortcut texts behind the one a Hermes chat shows (#1402), for the Sessions list and that - /// chat. private var shortcutReview: ShortcutTextReview { ShortcutTextReview( chat: shares.reviewing, hasWaiting: shares.hasWaitingShortcutText, @@ -344,26 +271,14 @@ struct ContentView: View { } } -/// The shares waiting in the app group, handed to the active server's home one at a time -/// (#1181): the one reserved for it or being moved into a Hermes draft, whether more wait, and -/// whether one was routed since the last Open Next. A Shortcut's text (#1402) waits only while -/// another one's chat is shown, for that chat's Open Next or Discard or for it to close. -/// `ContentView` owns it; a nil directory (no app group) reserves nothing. struct SharedImportQueue { - /// The reserved share the active home is opening. var pending: SharedImportReservation? - /// More shares wait behind it, which a webui session list offers in its Open Next banner. private(set) var hasWaiting = false - /// The Hermes chat showing a Shortcut's text, which later Shortcut texts wait behind. private(set) var reviewing: UUID? - /// A Shortcut text waits, which the reviewing chat offers with Open Next and Discard. private(set) var hasWaitingShortcutText = false private var hasRouted = false - /// The share a Hermes list is moving into its draft (`claim`), offered to no home meanwhile. private var moving: SharedImportReservation? - /// Reserves the next waiting share when the active home opens it now (`SharedImportGate`), or - /// Shortcut text while no chat shows one. mutating func reserveNext(in directory: URL?, active: URL?, servers: [ServerAccount]) { guard pending == nil, moving == nil, let directory else { return } var kinds: SharedImportKinds = reviewing == nil ? .shortcutTexts : [] @@ -379,9 +294,6 @@ struct SharedImportQueue { } } - /// The home routed `reservation`, or the user discarded it after it failed (#1196), so it - /// leaves the queue, and a Hermes home, which has no Open Next banner, takes the next share - /// at once. mutating func consume(_ reservation: SharedImportReservation, in directory: URL?, active: URL?, servers: [ServerAccount]) { hasRouted = true @@ -390,7 +302,6 @@ struct SharedImportQueue { do { try HermesShareDraft.consume(reservation, from: directory) } catch { - // Keep the share recoverable if acknowledgement fails after routing. try? HermesShareDraft.release(reservation, in: directory) return refreshWaiting(in: directory) } @@ -398,8 +309,6 @@ struct SharedImportQueue { reserveNext(in: directory, active: active, servers: servers) } - /// Keeps a share the Hermes home can't open queued, to be offered again on the next launch - /// or return to the app. mutating func release(_ reservation: SharedImportReservation, in directory: URL?) { settle(reservation) guard let directory else { return } @@ -407,9 +316,6 @@ struct SharedImportQueue { refreshWaiting(in: directory) } - /// A Hermes list starts moving `reservation` into a draft: no home is offered it again until - /// the move ends in `consume`, `release` or `abandon`, so a server switch mid-move can't open - /// it in a second server's draft. False when it isn't the pending share. mutating func claim(_ reservation: SharedImportReservation) -> Bool { guard pending?.reservationID == reservation.reservationID else { return false } moving = pending @@ -417,50 +323,37 @@ struct SharedImportQueue { return true } - /// The move was cut short before the draft took the share, so whichever home is active - /// opens it again. mutating func abandon(_ reservation: SharedImportReservation) { guard moving?.reservationID == reservation.reservationID else { return } pending = moving moving = nil } - /// A webui session list's Open Next. mutating func openNext(in directory: URL?, active: URL?, servers: [ServerAccount]) { hasWaiting = false hasRouted = false reserveNext(in: directory, active: active, servers: servers) } - /// The Hermes list is moving a Shortcut's text into `chat`, which shows it next: later texts - /// wait behind it. mutating func beginReview(in chat: UUID) { reviewing = chat } - /// `chat` no longer shows its Shortcut's text (it closed, its Open Next, or the text never got - /// there), so the next waiting text opens. A chat that isn't the reviewing one changes nothing. mutating func endReview(in chat: UUID, directory: URL?, active: URL?, servers: [ServerAccount]) { guard reviewing == chat else { return } reviewing = nil reserveNext(in: directory, active: active, servers: servers) } - /// The reviewing `chat` gave way to `replacement` in its place, as a Profile change in an - /// empty chat does with its draft: the review goes with it. A chat that isn't the reviewing - /// one changes nothing. mutating func moveReview(from chat: UUID, to replacement: UUID) { guard reviewing == chat else { return } reviewing = replacement } - /// The home that showed the reviewing chat went (a server switch or sign-out). Waiting texts - /// open on the next reservation, not at once, so the switch isn't undone for another server's. mutating func endReview() { reviewing = nil } - /// The reviewing chat's Discard: the next waiting Shortcut text is deleted unopened. mutating func discardNextShortcutText(in directory: URL?) { guard let directory else { return } if let next = try? HermesShareDraft.reserveNextPendingImport(from: directory, kinds: .shortcutTexts) { @@ -469,14 +362,11 @@ struct SharedImportQueue { refreshWaiting(in: directory) } - /// The pending reservation for `server`'s home: a share opens on any home, a Shortcut's text - /// only on the server it named (#1402). func offered(to server: URL) -> SharedImportReservation? { guard let shortcut = pending?.sharedImport.shortcut else { return pending } return shortcut.opens(on: server) ? pending : nil } - /// The server to make active for the pending Shortcut text, when it names one that isn't (#1402). @MainActor func shortcutRoute(state: AuthManager.State, servers: [ServerAccount]) -> ServerAccount? { guard let shortcut = pending?.sharedImport.shortcut, case .switchServer(let account) = shortcut.newChat(in: servers)?.route(state: state, servers: servers) @@ -484,8 +374,6 @@ struct SharedImportQueue { return account } - /// The Shortcut text waiting for a server that is no longer configured (#1402): it opens - /// nowhere else unasked, so the user discards it or keeps it for later. func unopenableShortcut(servers: [ServerAccount]) -> SharedImportReservation? { guard let shortcut = pending?.sharedImport.shortcut, shortcut.newChat(in: servers) == nil else { return nil } return pending @@ -503,12 +391,7 @@ struct SharedImportQueue { } } -/// The Shortcut texts waiting behind the one a Hermes chat shows (#1402). The Sessions list -/// begins a review as it moves a text into its chat, moves it to a chat that replaces that one -/// in place, and ends it when the chat closes; the chat offers Open Next and Discard while one -/// waits. `ContentView` makes it from its queue. struct ShortcutTextReview { - /// The chat showing a Shortcut's text. var chat: UUID? var hasWaiting = false var begin: (UUID) -> Void = { _ in } @@ -516,24 +399,17 @@ struct ShortcutTextReview { var end: (UUID) -> Void = { _ in } var discardNext: () -> Void = {} - /// What chat `id` offers: nil unless it is the reviewing chat and a text waits behind it. func waiting(in id: UUID) -> WaitingShortcutText? { guard chat == id, hasWaiting else { return nil } return WaitingShortcutText(openNext: { end(id) }, discard: discardNext) } } -/// Where a webui-only entry point goes when the active server may be a Hermes server (#899). enum WebuiEntryRoute: Equatable { - /// The active server is a webui server, or nothing is configured: proceed as before. case stay - /// A Hermes server is active: make the first webui server in the registry active. case switchServer(ServerAccount) - /// A Hermes server is active and no webui server is configured. case unavailable - /// `moved` are webui servers an entry point mustn't take (`MovedWebuiRoute`): one that is - /// active is left like a Hermes server, for the first webui server not among them. static func resolve(active: URL?, servers: [ServerAccount], moved: Set = []) -> WebuiEntryRoute { guard let active, servers.first(where: { $0.id == active.absoluteString })?.kind == .hermes || moved.contains(active.absoluteString) else { return .stay } @@ -542,44 +418,23 @@ enum WebuiEntryRoute: Equatable { } } -/// Where a webui server's old entry points go once it moved to Hermes (#707, #1217). The Hermes -/// server it moved to holds its move record (`ServerAccount.movedWebuiServers`), which outlives -/// the webui entry and goes with the destination; without records every route is today's. -/// -/// - A webui session link naming a moved server opens on its destination, looked up in every -/// Profile, so it finds where the session actually is rather than where Review mapped its -/// Profile. Only when every Profile was read and none has it does the Sessions list open it on -/// the webui server, while that is configured (`movedFrom`). A link about a run on the webui -/// server (`WebuiPushDestination.opensOnSource`) opens there while it is configured. -/// - A bare `session?id=` link or webui Profile Shortcut names no server. Once a move could own -/// it, it opens only where every candidate agrees, counting each webui server that didn't move, -/// and otherwise opens nothing: the active server never breaks the tie. enum MovedWebuiRoute { - /// What a bare link or webui Profile Shortcut does. enum Outcome: Equatable { - /// No move could own it: the webui route, among webui servers that didn't move. case webui(WebuiEntryRoute) case hermes(Destination) - /// More than one place could take it, or the one place can't. case refuse } private struct Move { - /// The Hermes server holding the record, and the webui server it names, as registry ids. let destination: String let source: String let record: MovedWebuiServer } - /// The Hermes server holding `source`'s move record; nil when it never moved or its - /// destination was removed. static func destination(of source: URL, in servers: [ServerAccount]) -> ServerAccount? { servers.first { $0.kind == .hermes && $0.movedWebuiServers.contains { $0.sourceServerID == source.absoluteString } } } - /// `link` as a session link on the Hermes server its webui server moved to, falling back to - /// that webui server while it is configured; nil when it didn't move, or when `link` is about - /// a run on it and it is still configured. static func session(_ link: WebuiPushDestination, servers: [ServerAccount]) -> HermesSessionDestination? { let isConfigured = servers.contains { $0.id == link.server.absoluteString && $0.kind == .webui } guard !(link.opensOnSource && isConfigured), @@ -589,15 +444,10 @@ enum MovedWebuiRoute { movedFrom: isConfigured ? link.server : nil) } - /// The link the Sessions list opens when no Profile has `link`'s key: the session on the webui - /// server it moved from, which opens there and never comes back here. Nil for any other link. static func fallback(for link: HermesSessionDestination) -> URL? { link.movedFrom.flatMap { WebuiPushDestination(server: $0, sessionID: link.key, opensOnSource: true).url } } - /// A bare `session?id=` link, which any moved server could own. With any move recorded it - /// opens only when every move went to one Hermes server, at most one of them is still - /// configured to fall back to, and no webui server stayed unmoved. static func bareSession(_ key: String, active: URL?, servers: [ServerAccount]) -> Outcome { let moves = moves(in: servers) guard !moves.isEmpty else { return .webui(WebuiEntryRoute.resolve(active: active, servers: servers)) } @@ -609,11 +459,6 @@ enum MovedWebuiRoute { movedFrom: retained.first.flatMap(URL.init(string:)))) } - /// A webui Profile's New Chat in Profile, which names no server. Each move whose Review named - /// `profile` sends it where it was mapped: a Hermes Profile, or the webui server it was kept - /// on, which can't open it once removed. With any such move it opens only where they and every - /// unmoved webui server agree. With none, the webui route among unmoved webui servers, so a - /// moved server whose Review didn't name the Profile never takes it. static func newChat(inProfile profile: String?, active: URL?, servers: [ServerAccount]) -> Outcome { enum Place: Hashable { @@ -644,8 +489,6 @@ enum MovedWebuiRoute { } } - /// Whether a move's Review named webui Profile `profile`, so a Shortcut saved with it still - /// resolves after its webui server is removed, and `newChat` decides where it goes. static func names(profile: String, in servers: [ServerAccount]) -> Bool { moves(in: servers).contains { $0.record.destination(ofProfile: profile) != nil } } @@ -662,25 +505,12 @@ enum MovedWebuiRoute { } } -/// Whether the next share waiting in the app group opens now. A webui session list opens the -/// first and offers each later one in its Open Next banner, so a draft in progress is never -/// replaced; a Hermes home has no banner and opens each as it arrives (#1181). enum SharedImportGate { static func opensNext(afterRouting hasRouted: Bool, active: URL?, servers: [ServerAccount]) -> Bool { !hasRouted || servers.first(where: { $0.id == active?.absoluteString })?.kind == .hermes } } -/// A signed-in Hermes server's whole app (#899, #709): a sidebar and detail at regular width, -/// or one navigation stack where compact-width chats push, on either side of the home switch. Each -/// side leads with the session list's header, whose avatar opens Settings on a tap and switches -/// servers on a hold, and takes the home's bar (`HermesHomeChrome`). The home keeps both sides' -/// state, open chat included, so a switch or a size-class change shows the last roster, rows or -/// chat at once while they refresh. It opens on the side last shown, Sessions at first, and a Bot -/// link (a push tap, a search hit) turns it to Bots, where the inbox opens it. A session link (#1176), a Shortcut's new session (#1180), a share -/// (#1181) or a Limits widget's Usage link (#1409) turns it to Sessions, where the list opens it. -/// Settings opens as a sheet beside a split and pushes at compact width. A sheet stays one when the -/// width changes: pushing it above an open chat (a fold) would clear both. enum HermesSettingsPresentation { case sheet, pushed @@ -702,11 +532,6 @@ struct HermesServerHome: View { @Binding var pendingSessionDestination: HermesSessionDestination? @Binding var pendingNewChat: HermesNewChatDestination? @Binding var pendingUsage: HermesUsageDestination? - /// The share `ContentView` reserved; the list claims it as it starts moving it into its new - /// session's draft and routes it once the draft holds it, or once the user discards it after - /// that move failed. The home declines it without a saved connection, and the list when it - /// goes before the user discards a failed one, which keeps it queued; a move cut short - /// abandons it to whichever home is active. let pendingShare: SharedImportReservation? let claimShare: (SharedImportReservation) -> Bool let didRouteShare: (SharedImportReservation) -> Void @@ -715,8 +540,6 @@ struct HermesServerHome: View { let shortcutReview: ShortcutTextReview @SceneStorage("hermesHome.tab") private var tab = HermesHomeTab.sessions @State private var inbox: BotInbox - /// The Sessions side's list on the saved Bot connection, read again each time a side shows, - /// so a sign-in changed in Settings or the inbox gets a fresh list. @State private var sessions: HermesSessionsSide? @State private var settings: HermesSettingsPresentation? @State private var isPresentingAddServer = false @@ -760,7 +583,6 @@ struct HermesServerHome: View { } } } - // Outside the branches, so the sheet outlives the switch between them. .sheet(isPresented: isPresenting(.sheet), onDismiss: readConnection) { NavigationStack { SettingsView(authManager: authManager, server: server) @@ -772,43 +594,30 @@ struct HermesServerHome: View { } } .onChange(of: usesSplit, initial: true) { settings = settings?.afterWidthChange(usesSplit: usesSplit) } - // A Hermes chat's Update sign-in (#942) signs the server out to its sign-in form, which - // keeps the saved values and focuses the password; saving signs it back in. .modifier(HermesUpdateSignInModifier { authManager.hermesSignInRejected(server: server) }) - // A connection the inbox's sheet saved or changed closes no screen, so the switch reads too. - // At compact width a route turning the home leaves the side it left on its root, so a - // later return doesn't push that side's old chat again. .onChange(of: tab) { readConnection() guard !usesSplit else { return } if tab == .sessions { inbox.selection = BotInboxSelection() } else { sessions?.navigation.covers.bringForward() } } - // A bot route lands on the inbox, so Settings (and an Archived screen pushed from it, #1146) - // closes first, as a Sessions list's pushed screens do when its tab goes. .onChange(of: pendingBotDestination, initial: true) { if pendingBotDestination != nil { tab = .bots; settings = nil } } - // A session link lands on the Sessions list the same way, with Add Server closed too, and - // the list closes what covers its rows; without a saved connection there is no list to - // open it. .onChange(of: pendingSessionDestination, initial: true) { guard pendingSessionDestination != nil else { return } if sessions == nil { pendingSessionDestination = nil; return } tab = .sessions; settings = nil; isPresentingAddServer = false } - // So does a Shortcut's new session (#1180), which the list opens. .onChange(of: pendingNewChat, initial: true) { guard pendingNewChat != nil else { return } if sessions == nil { pendingNewChat = nil; return } tab = .sessions; settings = nil; isPresentingAddServer = false } - // So does a Limits widget's Usage link (#1409), only on the connection it was read through. .onChange(of: pendingUsage, initial: true) { guard let pendingUsage else { return } if sessions?.entry.connection.id != pendingUsage.connectionID { self.pendingUsage = nil; return } tab = .sessions; settings = nil; isPresentingAddServer = false } - // And a share (#1181), which stays queued while there is no list to open it. .onChange(of: pendingShare?.reservationID, initial: true) { guard let pendingShare else { return } if sessions == nil { didDeclineShare(pendingShare); return } @@ -829,7 +638,6 @@ struct HermesServerHome: View { @ViewBuilder private func homeContent(_ home: HermesHome) -> some View { Group { - // Without a saved connection the inbox's welcome sets one up. if tab == .sessions, let sessions { HermesSessionListView(entry: sessions.entry, model: sessions.model, home: home, navigation: sessions.navigation, @@ -847,8 +655,6 @@ struct HermesServerHome: View { .onAppear(perform: readConnection) } - /// A new list only when the saved record changed: a sign-in changed in Settings keeps its UUID. - /// The old list's chats go with it, so one reviewing a Shortcut's text (#1402) lets the next open. private func readConnection() { let saved = try? BotConnectionStore().load(server: server) guard saved != sessions?.entry.connection else { return } @@ -870,10 +676,6 @@ struct HermesServerHome: View { } } -/// Opens the Hermes server's sign-in form after its host refused the saved password (#942). -/// `HermesServerHome` installs it, so every Hermes chat under it inherits it: opened from the -/// Sessions list, a pushed branch or Archived Sessions. A bot's chat takes the inbox's (#1146). A reference, like -/// `OpenNotificationSettingsAction`, so a pass of the home invalidates no chat reading it. final class HermesUpdateSignInAction { var handler: () -> Void = {} @@ -891,8 +693,6 @@ extension EnvironmentValues { } } -/// The stable action lives in this modifier's state, so the handler capturing the home cannot -/// form a cycle that outlives it. The Bots inbox installs its own for the bot chats it opens. struct HermesUpdateSignInModifier: ViewModifier { let handler: () -> Void @State private var action = HermesUpdateSignInAction() @@ -903,8 +703,6 @@ struct HermesUpdateSignInModifier: ViewModifier { } } -/// The Hermes home's Sessions side: its list, opening on the server's pick, and the view model -/// and open chat the home keeps across its switch and size-class changes. @MainActor private struct HermesSessionsSide { let entry: HermesSessionListEntry let model: SessionListViewModel @@ -916,10 +714,6 @@ struct HermesUpdateSignInModifier: ViewModifier { } } -/// A Hermes server whose sign-in record is missing or was refused (#899): its connection -/// form is the whole screen, with the address locked and the password focused. The -/// server's avatar is the way out, as on the home: a tap opens Settings, a hold switches -/// servers. Saving a sign-in signs the server back in. struct HermesServerSignIn: View { @Bindable var authManager: AuthManager let server: URL @@ -957,8 +751,6 @@ struct HermesServerSignIn: View { } } -/// How a Hermes server names itself on its screens: its display name, or its host -/// when it has none, and its initials. private struct HermesServerIdentity { let title: String let host: String @@ -977,8 +769,6 @@ private struct HermesServerIdentity { } -/// The active Hermes server's avatar, as on the webui home (#283): a tap opens Settings, -/// a hold opens the same server switcher. private struct HermesServerAvatarButton: View { @Bindable var authManager: AuthManager let server: URL @@ -1002,7 +792,6 @@ private struct HermesServerAvatarButton: View { .frame(width: 32, height: 32) .background(HeaderLogoColor.color(for: identity.colorHex), in: Circle()) .overlay(Circle().stroke(.white.opacity(0.18), lineWidth: 1)) - // On the label, so the initials are never read out as a control of their own. .accessibilityLabel("Settings") .accessibilityHint("Opens Settings. Long press to switch servers.") } primaryAction: { @@ -1011,56 +800,34 @@ private struct HermesServerAvatarButton: View { } } -/// The links `ContentView` holds until their server is active and signed in, and the routing -/// that decides each one's fate: drop it, hold it across a sign-in, or ask for its server first. -/// A route returns the server to activate; `ContentView` switches to it and the rebuilt tree -/// takes the held link. The session list and Hermes home clear a link once they open it. struct PendingLinks { var deepLinkedSessionID: String? var newChatRequest: NewChatRequest? var webuiPush: WebuiPushDestination? - /// The bot a deep link named. The session list flips to the Bots inbox, which resolves it - /// against the live roster (#554). var bot: BotDestination? - /// The Hermes session a link named (#1176). The Hermes home turns to Sessions, whose list - /// looks it up. var hermesSession: HermesSessionDestination? - /// The new Hermes session a Shortcut asked for (#1180). The Hermes home turns to Sessions, - /// whose list opens it. var hermesNewChat: HermesNewChatDestination? - /// The Usage screen a Limits widget's tap asked for (#1409). The Hermes home turns to Sessions, - /// whose list opens it. Never routed to another server: a change of server drops it. var hermesUsage: HermesUsageDestination? - /// The bot a Bot widget's tap named on a signed-out Hermes server (#1643), held by server digest - /// and Profile until its sign-in saves a new Bot connection, which `reroute` turns into `bot`. var botWidget: BotWidgetDestination? - /// A webui conversation link replaces whatever other link was waiting. @MainActor mutating func open(_ destination: WebuiPushDestination, state: AuthManager.State, servers: [ServerAccount]) -> ServerAccount? { self = PendingLinks() return route(destination, state: state, servers: servers) } - /// So does a Hermes session link, so a sign-in it waits for never routes an older link to a - /// server it doesn't name first (#1176). @MainActor mutating func open(_ destination: HermesSessionDestination, state: AuthManager.State, servers: [ServerAccount]) -> ServerAccount? { self = PendingLinks() return route(destination, state: state, servers: servers) } - /// So does a Shortcut's new Hermes session (#1180). @MainActor mutating func open(_ destination: HermesNewChatDestination, state: AuthManager.State, servers: [ServerAccount]) -> ServerAccount? { self = PendingLinks() return route(destination, state: state, servers: servers) } - /// So does a Bot widget's tap (#1643). With a saved Bot connection it becomes a bot link, routed - /// as one; a signed-out Hermes server is made active so its sign-in form shows, and the link - /// waits for it. A digest no configured server has, or a webui server with no Bot connection, - /// opens the app as it is. @MainActor mutating func open( _ destination: BotWidgetDestination, state: AuthManager.State, servers: [ServerAccount], isBotModeEnabled: Bool, botConnectionID: @MainActor (URL) -> UUID? = BotDeepLinkRouter.savedConnectionID @@ -1078,8 +845,6 @@ struct PendingLinks { return state.server == server ? nil : account } - /// Routes every held conversation link again once a sign-in or server switch changes what - /// it can reach. @MainActor mutating func reroute( state: AuthManager.State, servers: [ServerAccount], isBotModeEnabled: Bool, botConnectionID: @MainActor (URL) -> UUID? = BotDeepLinkRouter.savedConnectionID @@ -1098,8 +863,6 @@ struct PendingLinks { return account } - /// A held Bot widget tap: routed as a bot link once its server has a Bot connection again, kept - /// while that server stays active and signed out, and dropped once another server is active. @MainActor private mutating func reroute( _ destination: BotWidgetDestination, state: AuthManager.State, servers: [ServerAccount], isBotModeEnabled: Bool, botConnectionID: @MainActor (URL) -> UUID? @@ -1114,7 +877,6 @@ struct PendingLinks { state: state, servers: servers, isBotModeEnabled: isBotModeEnabled, botConnectionID: botConnectionID) } - /// A new Hermes session: dropped when its server is gone, else held while it signs in or activates. @MainActor private mutating func route(_ destination: HermesNewChatDestination, state: AuthManager.State, servers: [ServerAccount]) -> ServerAccount? { switch destination.route(state: state, servers: servers) { @@ -1129,8 +891,6 @@ struct PendingLinks { return nil } - /// A webui conversation link, or, when its server moved to Hermes, that server's session link - /// (`MovedWebuiRoute`). @MainActor private mutating func route(_ destination: WebuiPushDestination, state: AuthManager.State, servers: [ServerAccount]) -> ServerAccount? { if let moved = MovedWebuiRoute.session(destination, servers: servers) { @@ -1149,8 +909,6 @@ struct PendingLinks { return nil } - /// A bot link: dropped when nothing can be opened (Bot Mode off, server removed, connection - /// replaced), else held while its server signs in or activates. @MainActor mutating func route( _ destination: BotDestination, state: AuthManager.State, servers: [ServerAccount], isBotModeEnabled: Bool, botConnectionID: @MainActor (URL) -> UUID? = BotDeepLinkRouter.savedConnectionID @@ -1168,9 +926,6 @@ struct PendingLinks { return nil } - /// A Hermes session link: dropped, handed to a webui server's push route, or held while its - /// server signs in or activates. A link naming a webui server removed after it moved to Hermes - /// takes the push route, which sends it to its destination (#1217). @MainActor private mutating func route(_ destination: HermesSessionDestination, state: AuthManager.State, servers: [ServerAccount]) -> ServerAccount? { switch HermesSessionLinkRouter.resolve(destination, state: state, servers: servers) { diff --git a/HermesMobile/Features/Bots/BotArtifact.swift b/HermesMobile/Features/Bots/BotArtifact.swift index dd126f82c..a8b73b678 100644 --- a/HermesMobile/Features/Bots/BotArtifact.swift +++ b/HermesMobile/Features/Bots/BotArtifact.swift @@ -1,6 +1,5 @@ import Foundation -/// Captured with the transcript, never reconstructed from the currently selected server. struct BotArtifactContext: Hashable { let connectionID: UUID let profile: String @@ -8,8 +7,6 @@ struct BotArtifactContext: Hashable { let generation: Int } -/// `folder` is a download the host refused because the path is a folder, as a symlinked folder -/// the workspace listing shows as a file is (#1112); it reads as `unavailable` anywhere else. enum BotArtifactFailure: Error, LocalizedError { case unavailable, tooLarge, invalidReference, folder @@ -22,22 +19,17 @@ enum BotArtifactFailure: Error, LocalizedError { } } -/// Paths stay server-side. In particular, relative paths and ~ are resolved by -/// fs/download using the originating session and Profile, never by Foundation on iOS. enum BotArtifactReference { static func path(_ raw: String, address: URL) throws -> String { let value = raw.trimmingCharacters(in: .whitespacesAndNewlines) guard !value.isEmpty, !value.contains("\0"), !value.hasPrefix("//") else { throw BotArtifactFailure.invalidReference } - // A Windows host's `C:\…` would otherwise parse as a URL with scheme `C`. if BotAttachmentUpload.isHostAbsolute(value) { return value } if let url = URL(string: value), let scheme = url.scheme { if scheme.lowercased() == "file", url.host == nil || url.host == "" || url.host == "localhost" { return url.path(percentEncoded: false) } - // Desktop may emit an authenticated download URL. Extract only its - // path; never carry its token, Profile override, or session override forward. if ["https", "http"].contains(scheme.lowercased()), url.scheme == address.scheme, url.host == address.host, url.port == address.port, ["/api/fs/download", "/api/files/download", "/api/media", "/api/fs/read-data-url"].contains(url.path), diff --git a/HermesMobile/Features/Bots/BotArtifactPreview.swift b/HermesMobile/Features/Bots/BotArtifactPreview.swift index cdec64db4..acd40d4c5 100644 --- a/HermesMobile/Features/Bots/BotArtifactPreview.swift +++ b/HermesMobile/Features/Bots/BotArtifactPreview.swift @@ -3,13 +3,7 @@ import Observation import SwiftUI import UniformTypeIdentifiers -/// The preview owns its temporary file and the bytes written to it. Quick Look -/// and Share read the file; Save to Files writes the same bytes, so exporting -/// never downloads again. Dismissal invalidates late completions and removes -/// only the directory this presentation created. @MainActor @Observable final class BotArtifactPreviewModel { - /// What Save to Files writes: the downloaded bytes under the temporary file's - /// sanitized name, typed by its extension, or `.data` without one. struct Export { let data: Data let filename: String @@ -18,12 +12,10 @@ import UniformTypeIdentifiers private var loaded: (file: QuickLookTemporaryFile, data: Data)? var fileURL: URL? { loaded?.file.url } - /// The page, decoded once, when `load` was asked to render an HTML report (#1623). private(set) var html: String? private(set) var errorMessage: String? private var generation = 0 - /// Nil while loading, on error and after cleanup, when there are no bytes to save. var export: Export? { guard let loaded else { return nil } let url = loaded.file.url @@ -43,7 +35,6 @@ import UniformTypeIdentifiers try Task.checkCancellation() guard owner == generation else { return } let written = try await QuickLookTemporaryFile.write(data: data, name: name) - // Returning drops a late write, which deletes its directory. guard !Task.isCancelled, owner == generation else { return } loaded = (written, data) if decodesHTML { html = String(decoding: data, as: UTF8.self) } @@ -61,11 +52,8 @@ import UniformTypeIdentifiers } -/// A Hermes chat's sent file or artifact in Quick Look, or an HTML report in its own web view. -/// Once loaded, Save to Files and Share sit beside Done and act on the bytes already downloaded. struct BotArtifactPreview: View { let reference: TranscriptMediaReference - /// The title and saved file name; the reference's file name when nil. var title: String? = nil let download: () async throws -> Data @Environment(\.dismiss) private var dismiss diff --git a/HermesMobile/Features/Bots/BotAtAutocompleteView.swift b/HermesMobile/Features/Bots/BotAtAutocompleteView.swift index 6597b3ab3..4f93b4afb 100644 --- a/HermesMobile/Features/Bots/BotAtAutocompleteView.swift +++ b/HermesMobile/Features/Bots/BotAtAutocompleteView.swift @@ -1,15 +1,9 @@ import SwiftUI -/// What a Hermes chat's one `@` panel draws, in order: this connection's bots, -/// then this conversation's workspace files. enum BotAtPanelSection { case bots([BotMentions.Completion]) case files([ComposerFilePathSearch.Match]) - /// The sections in drawing order. A group with nothing to show is absent, - /// so a connection with no roster shows files alone and a failed or empty - /// file lookup leaves the Bots section standing. A lookup still in flight - /// shows the Files section with no rows yet. static func sections( botCompletions: [BotMentions.Completion], fileMatches: [ComposerFilePathSearch.Match], @@ -22,11 +16,6 @@ enum BotAtPanelSection { } } -/// A Hermes chat's `@` panel: roster rows above workspace file rows, on the -/// slash panel's glass. Section headers are the only chrome. -/// -/// Rooms use `BotMentionAutocompleteView` directly and never reach this panel, -/// so their mentions stay members-only. struct BotAtAutocompleteView: View { let botCompletions: [BotMentions.Completion] let avatars: [String: UIImage] @@ -46,8 +35,6 @@ struct BotAtAutocompleteView: View { ) } - /// Tracks Dynamic Type and the rows actually drawn, like the two panels it - /// combines. The loading row counts as the file group's one row. private var panelHeight: CGFloat { var height = CGFloat(sections.count) * headerHeight for section in sections { @@ -71,7 +58,6 @@ struct BotAtAutocompleteView: View { } } .composerPanelHeight(panelHeight) - // Clip the scrolling content before Liquid Glass composites the surface. .clipShape(RoundedRectangle(cornerRadius: ChatComposerMetrics.cardCornerRadius, style: .continuous)) .adaptiveGlass(.regular, fallbackMaterial: .ultraThinMaterial, in: RoundedRectangle(cornerRadius: ChatComposerMetrics.cardCornerRadius, style: .continuous)) diff --git a/HermesMobile/Features/Bots/BotAvatarGeneration.swift b/HermesMobile/Features/Bots/BotAvatarGeneration.swift index b52c048c3..484964c96 100644 --- a/HermesMobile/Features/Bots/BotAvatarGeneration.swift +++ b/HermesMobile/Features/Bots/BotAvatarGeneration.swift @@ -2,13 +2,8 @@ import Foundation import Observation import SwiftUI -/// "Describe It": one avatar from the host's model, through `prompt.btw`, which denies every tool -/// at dispatch. A real turn is not safe here: `prompt.submit` runs terminal and file tools with no -/// approval request, a dropped socket does not stop it, and `session.resume` can auto-continue it. enum BotAvatarGeneration { enum Failure: LocalizedError, Equatable { - /// `said` is the host's own words when it answered with no JSON at all, such as a provider - /// rejecting the bot's API key. `unreadable` is a JSON answer that failed the checks. case host(String), said(String), timedOut, disconnected, unreadable([String]) var errorDescription: String? { @@ -18,20 +13,15 @@ enum BotAvatarGeneration { case .said(let message): return message case .timedOut: return String(localized: "The host took too long to answer.") case .disconnected: return String(localized: "The connection dropped before the host answered.") - // The problems are English, for the repair prompt, so they stay off the screen. case .unreadable: return String(localized: "The answer was not a usable avatar.") } } } - /// How long to wait for the answer. A slow model can reason for minutes. static let answerDeadline: Duration = .seconds(420) private static let deleteAttempts = 4 - /// How long a closing draft gets before its row is deleted again. Tests shorten it. static var deleteRetryDelay: Duration = .seconds(2) - /// Adapted from Open Bot Avatar's design prompt (Dominik Scholz, MIT): flat, with a path - /// grammar the app parses itself, and short enough for a small model to answer quickly. static let designPrompt = """ You design one small flat avatar: a soft, chunky silhouette of an object or creature with two eyes on it. It is shown at about 44 points on a phone. Give geometry only; the app adds the color, the eye shape and the motion. @@ -67,8 +57,6 @@ enum BotAvatarGeneration { + problems.map { "- \($0)" } + ["", "Last answer:", answer]).joined(separator: "\n") } - /// Turns a description into a checked avatar. A bad avatar gets one repair try. An answer with no - /// JSON at all is the host saying why it can't, so it goes straight to the user. static func avatar(description: String, send: (String) async throws -> String) async throws -> BotGeneratedAvatar { let first = try await send(prompt(description: description)) guard case .failure(.unreadable(let problems)) = BotGeneratedAvatar.read(answer: first) else { @@ -78,14 +66,6 @@ enum BotAvatarGeneration { return try BotGeneratedAvatar.read(answer: try await send(repairPrompt(answer: first, problems: problems))).get() } - /// One tool-free model call in a hidden draft session under `profile`. The draft is closed and - /// its empty stored row deleted afterwards, even when the caller stopped waiting, unless the - /// socket itself has gone. Reads the shared socket's events for its own task only. - /// - /// The calls run in their own task: cancelling a call that isn't cancellation-safe ends the - /// screen's whole connection, so stopping only stops the waiting. One runs at a time: a call - /// nobody is waiting for may still hold the socket's handlers until its reply lands, even after - /// its sheet has closed, so the next starts once it has let them go. @MainActor static func ask(_ prompt: String, profile: String, transport: any BotTransport, validateDispatch: (() throws -> Void)?) async throws -> String { let waiter = AnswerWaiter() @@ -106,7 +86,6 @@ enum BotAvatarGeneration { @MainActor private static func run(_ prompt: String, profile: String, transport: any BotTransport, waiter: AnswerWaiter, validateDispatch: (() throws -> Void)?) async throws -> String { - // Stopped while waiting its turn: nothing goes to the host. guard !waiter.isFinished else { return try await waiter.answer(within: answerDeadline) } let draft = try await transport.call(.sessionDraft(profile: profile), validateDispatch: validateDispatch) guard let runtime = draft["session_id"].text else { throw BotFailure.unsupported } @@ -119,21 +98,18 @@ enum BotAvatarGeneration { transport.onEvent = priorEvent transport.onDisconnect = priorDisconnect Task { @MainActor in - // A canonical draft has no runtime to close: one fenced delete removes it (#1603). if transport.speaksCanonicalProtocol { _ = try? await transport.mutateStoredSession(profile: profile, key: stored ?? runtime, .delete) return } _ = try? await transport.call(.sessionClose(runtime: runtime), validateDispatch: nil) guard let stored else { return } - // The host refuses to delete a session it is still closing, so this tries a few times. for attempt in 1...deleteAttempts { if (try? await transport.call(.sessionDelete(profile: profile, storedKey: stored), validateDispatch: nil)) != nil { return } if attempt < deleteAttempts { try? await Task.sleep(for: deleteRetryDelay) } } } } - // Stopped while the draft was opening: nothing more goes to the host. guard !waiter.isFinished else { return try await waiter.answer(within: answerDeadline) } let accepted = try await transport.call(.promptBtw(sessionID: runtime, text: prompt), validateDispatch: validateDispatch) guard let task = accepted["task_id"].text else { throw BotFailure.unsupported } @@ -141,8 +117,6 @@ enum BotAvatarGeneration { return try await waiter.answer(within: answerDeadline) } - /// Holds the one continuation an answer resolves. Everything runs on the main actor, and only - /// the first of the answer, the deadline, a disconnect or a cancel takes effect. @MainActor private final class AnswerWaiter { var runtime: String? private var taskID: String? @@ -157,7 +131,6 @@ enum BotAvatarGeneration { if let text = early[task] { finish(text) } } - /// `prompt.btw` can answer before its own reply is read, so an early answer is kept. func receive(_ event: BotJSON) { guard event["type"].text == "btw.complete", event["session_id"].text == runtime, let task = event["payload"]["task_id"].text else { return } @@ -169,7 +142,6 @@ enum BotAvatarGeneration { } } - /// The host reports a failed side question as text starting `error:`. private func finish(_ text: String) { if text.hasPrefix("error:") { finish(throwing: Failure.host(String(text.dropFirst(6)).trimmingCharacters(in: .whitespaces))) @@ -200,8 +172,6 @@ enum BotAvatarGeneration { } } -/// The sheet's state. The result reaches the editor or creator as a draft, so nothing is on the -/// host until its own Save. Closing stops the waiting, but the host's model call can't be stopped. @MainActor @Observable final class BotAvatarDescriber { enum State: Equatable { case idle, running, failed(String), finished } @@ -237,7 +207,6 @@ enum BotAvatarGeneration { } } -/// Describes an avatar for the host's model to draw. @MainActor struct BotAvatarDescribeSheet: View { @State private var describer: BotAvatarDescriber @State private var description = "" @@ -281,14 +250,10 @@ enum BotAvatarGeneration { .presentationDetents([.medium]) .onChange(of: describer.state) { if describer.state == .finished { dismiss() } } .onDisappear { describer.stopWaiting() } - // The editor closes its connection in the background, so no answer can arrive. .onChange(of: scenePhase) { if scenePhase == .background { describer.stopWaiting() } } } } -/// Every shape a bot can take, in a compact sideways grid: a generated avatar first when the draft -/// has one, then the classics, then the ready-made avatars. Faces are plain vector drawings, so a -/// tile draws at once. struct BotAvatarShapePicker: View { let name: String let appearance: BotProfileAppearance @@ -322,7 +287,6 @@ struct BotAvatarShapePicker: View { private func tile(selected: Bool, name: String, @ViewBuilder face: () -> Face) -> some View { face() - // Wide enough that the next column peeks in, which shows the grid scrolls. .frame(width: 64, height: 50) .overlay { if selected { RoundedRectangle(cornerRadius: 12).stroke(.secondary, lineWidth: 2) } diff --git a/HermesMobile/Features/Bots/BotAvatarLibrary.swift b/HermesMobile/Features/Bots/BotAvatarLibrary.swift index 796e2cf9b..6eb537d26 100644 --- a/HermesMobile/Features/Bots/BotAvatarLibrary.swift +++ b/HermesMobile/Features/Bots/BotAvatarLibrary.swift @@ -1,8 +1,3 @@ -// Silhouettes and eye positions from Open Bot Avatar, (c) Dominik Scholz, MIT license, at -// 3a5119877844165eebafe57d3100da475f67d0a8. Curves are normalized to absolute M, L, Q, C and Z. - -/// Where a face's eyes sit in the 100 by 100 box. `x` and `y` are the center of the pair and -/// `spacing` runs center to center. At scale 1 each eye is 4 wide and 11 tall. struct BotAvatarEyes: Equatable, Sendable { var x: Double var y: Double @@ -11,8 +6,6 @@ struct BotAvatarEyes: Equatable, Sendable { } extension BotAvatarShape { - /// The stored path and eyes of a ready-made avatar; nil for the eight classic shapes, which - /// draw from `BotAvatarBody` with their own leaning eyes. var readyMade: (path: String, eyes: BotAvatarEyes)? { switch self { case .circle, .blob, .squircle, .pill, .triangle, .hexagon, .cloud, .drop: return nil diff --git a/HermesMobile/Features/Bots/BotAvatarStore.swift b/HermesMobile/Features/Bots/BotAvatarStore.swift index ec28b68cb..8fcc9cd78 100644 --- a/HermesMobile/Features/Bots/BotAvatarStore.swift +++ b/HermesMobile/Features/Bots/BotAvatarStore.swift @@ -2,28 +2,18 @@ import ImageIO import UniformTypeIdentifiers import UIKit -/// Decoded Desktop avatars for the Bots inbox, read through `profiles.get_asset`. -/// Keyed by connection UUID plus Profile name so equal Profile names on two hosts -/// never share an image. Entries exist only for the current connection's roster -/// and drop when the connection is replaced or removed; nothing is written to disk. -/// Desktop's copies of a drawn face are skipped (`decode`), so the face stays live. @MainActor final class BotAvatarStore { static let shared = BotAvatarStore() - /// Longest decoded edge in pixels: the 48pt row tile at 3x with headroom. nonisolated static let maxPixelSize = 192 - /// Largest data URL accepted from the host. The server caps assets at 2 MB before base64. nonisolated static let maxPayloadBytes = 3_000_000 private struct Key: Hashable { let connectionID: UUID; let profile: String } - /// A nil image is Desktop's face copy, kept so an unchanged revision does not - /// fetch it again. Unreadable assets are not kept and retry on the next refresh. private struct Entry { let revision: Int?; let image: UIImage? } private var entries: [Key: Entry] = [:] init() {} - /// Images for one connection's roster, keyed by Profile name. func images(connectionID: UUID) -> [String: UIImage] { var result: [String: UIImage] = [:] for (key, entry) in entries where key.connectionID == connectionID { result[key.profile] = entry.image } @@ -34,21 +24,12 @@ import UIKit entries = entries.filter { $0.key.connectionID != connectionID } } - /// Applies an acknowledged editor write immediately. Keeping the current - /// look revision is intentional: replacing only the asset does not advance - /// UI metadata, so a later roster refresh must retain this new thumbnail. func setImage(_ image: UIImage?, connectionID: UUID, profile: String, revision: Int?) { let key = Key(connectionID: connectionID, profile: profile) if let image { entries[key] = Entry(revision: revision, image: image) } else { entries.removeValue(forKey: key) } } - /// Brings the store in line with a fresh roster for one connection. Every other - /// connection's images and rows no longer flagged `has_avatar` drop first, then - /// `onUpdate` fires so cached images paint before any fetch. Images whose look - /// revision is unchanged are kept; the rest, including entries without a - /// revision, are fetched one at a time and `onUpdate` fires after each decode. - /// The first failed call ends the pass silently: the roster never depends on it. func refresh(_ profiles: [BotProfile], connectionID: UUID, using transport: any BotTransport, validateDispatch: (() throws -> Void)? = nil, onUpdate: () -> Void) async { let wanted = Set(profiles.filter(\.hasAvatar).map(\.id)) @@ -68,7 +49,6 @@ import UIKit } } - /// Bounds a picked image to the same size the store keeps for fetched assets. nonisolated static func thumbnail(_ image: UIImage) -> UIImage? { let longest = max(image.size.width * image.scale, image.size.height * image.scale) guard longest > CGFloat(maxPixelSize) else { return image } @@ -78,20 +58,13 @@ import UIKit return UIGraphicsImageRenderer(size: size, format: format).image { _ in image.draw(in: CGRect(origin: .zero, size: size)) } } - /// A readable asset: a picture to show, or Desktop's still copy of a drawn face. enum Asset { case image(UIImage), faceCopy var image: UIImage? { if case .image(let image) = self { image } else { nil } } } - /// Decodes a `profiles.get_asset` reply into a bounded thumbnail; nil means the row draws its face. nonisolated static func decode(_ reply: BotJSON, photo: Bool) -> UIImage? { asset(reply, photo: photo)?.image } - /// Reads a `profiles.get_asset` reply. Anything other than a found, base64 image - /// data URL within the size cap is nil, so a later fetch retries it. Unless the - /// look says `photo`, a 160x160 PNG is `faceCopy`: Desktop uploads a still copy of - /// its own drawing at that size for any bot without an asset, and draws the face - /// over it the same way (`isBackfilledFacePng`). nonisolated static func asset(_ reply: BotJSON, photo: Bool) -> Asset? { guard reply["found"].flag == true, let text = reply["data"].text, text.utf8.count <= maxPayloadBytes, text.hasPrefix("data:image/"), let comma = text.firstIndex(of: ","), diff --git a/HermesMobile/Features/Bots/BotChatControls.swift b/HermesMobile/Features/Bots/BotChatControls.swift index bd5cc624b..0b62cb1cb 100644 --- a/HermesMobile/Features/Bots/BotChatControls.swift +++ b/HermesMobile/Features/Bots/BotChatControls.swift @@ -1,10 +1,6 @@ import Foundation import Observation -/// One Hermes chat's model, effort and Fast controls (`HermesChatSettings`). Every read, -/// confirmation and socket write belongs to one connection generation and runtime; -/// disconnect invalidates them together. On a canonical host (#1604) the model goes out as the -/// session's fenced `model` edit (`mutate`), and a confirmation resends the host's own token. @MainActor @Observable final class BotChatControls { struct Context: Equatable { let connectionID: UUID @@ -24,40 +20,24 @@ import Observation struct Confirmation: Identifiable { let action: Action let message: String - /// A canonical host's token for exactly this selection; nil on the dashboard, which takes - /// `confirm_expensive_model`. var token: String? = nil var id: UUID { action.id } } - /// Sends one fenced edit of the session, checked at the write; a canonical host's model goes this way. typealias Mutate = (HermesCall.SessionMutation.Operation, @escaping () throws -> Void) async throws -> BotJSON private(set) var catalog = HermesModelCatalog(.null) private(set) var effort: String? private(set) var fast: Bool? private(set) var pendingModel: ModelCatalogOption? - /// Called once for a pick of this chat's the host runs: from inside the pick's `apply` when - /// the host runs it at once (or once confirmed), and for a deferred pick (`deferredPick`) from - /// the first catalog read that shows it live. A caller that sends more defers it. @ObservationIgnored var onPickedModelActive: ((ModelCatalogOption) -> Void)? - /// A pick the host deferred past the running response (#1771), with the model it ran when the - /// pick went out, kept apart from `pendingModel` (a display state `session.info` clears). A - /// canonical host commits it at the claim boundary right after the response, a dashboard when - /// the next turn starts. It ends when a catalog read shows it live (`settleDeferredPick`) or - /// shows a third model, when the host asks to confirm it, refuses or drops it, when a newer - /// pick is answered, or on another runtime. private var deferredPick: (model: ModelCatalogOption, from: ModelCatalogOption?)? - /// The host's ask to confirm `deferredPick` that a reattach replayed before these controls - /// reconnected; shown once they do, on the same chat. private var heldConfirmation: BotJSON? private(set) var confirmation: Confirmation? private(set) var errorMessage: String? private(set) var isApplying = false private(set) var isLoading = false private(set) var context: Context? - /// Methods this chat stopped calling after a 403 or an unusable reply. A method the - /// host lacks (-32601) is the connection's to remember, for every chat on it. private var refused: Set = [] private var readTask: Task? private var readAgain = false @@ -77,14 +57,12 @@ import Observation guard let active = catalog.active else { return false } return catalog.capabilities[active.favoriteKey]?["reasoning"].flag != false } - /// Methods this chat won't call: its own refusals and the connection's missing methods. private var unavailable: Set { refused.union(wire?.unavailableMethods ?? []) } var mayChangeEffort: Bool { mayChangeModel && supportsEffort } var mayChangeFast: Bool { mayChangeModel && showsFast } var mayChangeModel: Bool { context != nil && !isApplying && !isLoading && !unavailable.contains("model.options") && !unavailable.contains("config.set") && catalog.active != nil } - /// `mutate` is set on a canonical host, whose model is a session edit rather than `config.set`. func connect(_ context: Context, wire: any BotTransport, mutate: Mutate? = nil) async { disconnect() if lastContext?.connectionID != context.connectionID || lastContext?.profile != context.profile { @@ -101,7 +79,6 @@ import Observation } } - /// Drops a refused or unconfirmed pick's error once the user moves on; a no-op when clear. func clearError() { if errorMessage != nil { errorMessage = nil } } @@ -116,17 +93,12 @@ import Observation consumed.removeAll() } - /// A `session.info`'s effort and Fast mode. func snapshot(_ info: BotJSON) { effort = info["reasoning_effort"].text fast = info["fast"].flag if let pendingModel, let reported = info["model"].text, reported != pendingModel.id { - // Desktop may replace/cancel the queued choice, or the next turn may - // resolve an alias to a canonical model. Do not keep an obsolete badge. self.pendingModel = nil } - // `info.model` can be the queued choice. Only model.options reads the live - // agent's model/provider; never use the display mirror for the active tick. } func refresh() { @@ -165,33 +137,22 @@ import Observation } } catch { guard context == owner, revision == readRevision, !Task.isCancelled else { return } - // A -32601 needs nothing here: the connection has recorded it. A lost connection is - // the conversation's to report, and its reattach reads the catalog again. if isRefused(error) { refused.insert(call.method) } else if !isUnsupported(error), error as? BotFailure != .transport { errorMessage = error.localizedDescription } } } - /// Whether `model`, as a `session.info` names it, is the deferred pick still waiting to run: - /// the frame that may report it running is a reason to read the catalog again. func awaitsDeferredPick(named model: String?) -> Bool { model != nil && model == deferredPick?.model.id } - /// The host dropped the pick it deferred: a dashboard's `model_switch.dropped` notice at the - /// next turn's start. func dropDeferredPick() { deferredPick = nil } - /// A canonical `session.updated` about the deferred pick that arrived around a rebuild: a - /// refusal ends the wait at once, and an ask to confirm it is held for the reattach's `connect`, - /// which would clear a confirmation shown now. Any other edit leaves a held ask alone. func holdDeferredPickUpdate(_ payload: BotJSON) { if receiveDeferredPickRefusal(payload) { return } if deferredPick != nil, payload["status"].text == "confirmation_required" { heldConfirmation = payload } } - /// Ends the wait when `payload`, a canonical `session.updated`, refused the deferred pick, and - /// says whether it did. private func receiveDeferredPickRefusal(_ payload: BotJSON) -> Bool { guard payload["operation"].text == "model", payload["status"].text == "refused", let refused = payload["target_model"].text, refused == deferredPick?.model.id else { return false } @@ -199,9 +160,6 @@ import Observation return true } - /// Ends the deferred pick once the catalog, read with nothing else in flight, shows it live - /// (telling `onPickedModelActive`) or shows a model that is neither it nor the one it replaces. - /// Called as each read, read loop and write ends; one still running skips it. private func settleDeferredPick() { guard let pick = deferredPick, context != nil, readTask == nil, !isLoading, !isApplying, let active = catalog.active else { return } @@ -224,25 +182,18 @@ import Observation await confirm(pending) } - /// Resends `pending`'s pick confirmed, with its token on a canonical host. The sheet captures - /// `pending` before dismissing, which clears `confirmation`. func confirm(_ pending: Confirmation) async { guard allowed(pending.action.change) else { return } confirmation = nil await apply(pending.action, confirmed: true, token: pending.token) } - /// A canonical host's `session.updated` about the pick it deferred. At the end of the running - /// response it may ask to confirm it (a `confirmation_required` model edit, #1604): the sheet - /// asks for it as it would have at once, its token kept for the confirmed resend. Or it - /// refused it (`status: refused` naming it as `target_model`), which ends the wait. func receiveDeferredPickUpdate(_ payload: BotJSON) { if receiveDeferredPickRefusal(payload) { return } guard let context else { if deferredPick != nil { heldConfirmation = payload } return } - // The event is the edit's own answer plus `payload`, the selection it deferred. guard let option = deferredPick?.model, payload["status"].text == "confirmation_required", let token = payload["confirm"].text, !token.isEmpty, payload["payload"]["model"].text == option.id else { return } @@ -252,7 +203,6 @@ import Observation token: token) } - /// `token` is a canonical host's confirmation token for this exact selection, resent once. func apply(_ action: Action, confirmed: Bool = false, token: String? = nil) async { guard action.context == context, let wire, allowed(action.change), !consumed.contains(action.id) else { return } let (runtime, profile) = (action.context.runtime, action.context.profile) @@ -276,7 +226,6 @@ import Observation call = .configSet(sessionID: runtime, profile: profile, setting: .fast(enabled)) } errorMessage = nil; confirmation = nil; isApplying = true; activeAction = action.id - // A read started before this write must not overwrite its authoritative response. readRevision += 1; isLoading = false var dispatched = false defer { @@ -295,12 +244,9 @@ import Observation else { result = try await wire.call(call, validateDispatch: check) } guard context == action.context, activeAction == action.id, !Task.isCancelled else { return } readRevision += 1; isLoading = false - // The host answered a newer pick: it replaced the one it deferred, or asks first. if case .model = action.change { deferredPick = nil } switch action.change { case .model(let option) where canonicalModel != nil: - // Nothing applied until the confirmed resend carries this token; a token another - // change made stale is answered with a fresh one, asked again. if result["status"].text == "confirmation_required", let token = result["confirm"].text, !token.isEmpty { consumed.remove(action.id) confirmation = Confirmation(action: action, message: result["confirm_message"].text @@ -309,7 +255,6 @@ import Observation pendingModel = result["status"].text == "deferred" ? option : nil deferredPick = pendingModel.map { ($0, action.expectedModel) } await reload() - // The applied edit's receipt carries no `status`; `deferred` waits for the turn. if result["status"] == .null { announce(option, for: action) } } else { throw BotSettingFailure.unknownOutcome } case .model(let option): @@ -335,7 +280,6 @@ import Observation guard context == action.context, activeAction == action.id, !Task.isCancelled else { return } if isRefused(error) { refused.insert(call.method) } if error is HermesFenceRefusal { - // The session changed first; nothing applied, and the next pick carries its new fences. errorMessage = String(localized: "This chat changed on the server. Reopen it and try again.") } else if case BotSettingFailure.rejected = error { errorMessage = error.localizedDescription } else if !dispatched || isUnsupported(error) { errorMessage = error.localizedDescription } @@ -343,7 +287,6 @@ import Observation } } - /// Tells `onPickedModelActive` about `option` when the catalog read after its reply shows it live. private func announce(_ option: ModelCatalogOption, for action: Action) { guard context == action.context, activeAction == action.id, catalog.active?.matchesSelection(modelID: option.id, providerID: option.providerID) == true else { return } @@ -357,13 +300,11 @@ import Observation case .fast: return mayChangeFast } } - /// The host can't do this here: it refused (`isRefused`) or lacks the method (-32601). private func isUnsupported(_ error: Error) -> Bool { if isRefused(error) || error as? BotFailure == .rejected(-32601) { return true } if case BotSettingFailure.rejected(-32601, _) = error { return true } return false } - /// A 403 or an unusable reply, which turns the method off for this chat alone. private func isRefused(_ error: Error) -> Bool { if case BotSettingFailure.rejected(403, _) = error { return true } return error as? BotFailure == .unsupported diff --git a/HermesMobile/Features/Bots/BotChatSettings.swift b/HermesMobile/Features/Bots/BotChatSettings.swift index fd6ac0cfd..94d6cdb91 100644 --- a/HermesMobile/Features/Bots/BotChatSettings.swift +++ b/HermesMobile/Features/Bots/BotChatSettings.swift @@ -39,7 +39,6 @@ struct BotSessionControl: Identifiable, Equatable { } } -/// Kept separate from connection failures so a rejected setting preserves the host's explanation. enum BotSettingFailure: Error, LocalizedError { case rejected(Int, String), unknownOutcome var errorDescription: String? { diff --git a/HermesMobile/Features/Bots/BotConnection.swift b/HermesMobile/Features/Bots/BotConnection.swift index 2473c91e3..e77026844 100644 --- a/HermesMobile/Features/Bots/BotConnection.swift +++ b/HermesMobile/Features/Bots/BotConnection.swift @@ -7,62 +7,29 @@ struct BotConnection: Codable, Equatable, Identifiable { let address: URL let username: String var password: String - /// Release string `/api/status` reported at the last successful connect. Nil for - /// records saved before the pin existed or when the host omits `version`. var hermesVersion: String? - /// The host's `install_id` from `/api/status`: one per Hermes root, shared by every - /// Profile and every address that reaches it. Nil for records saved before it existed - /// or while the host has never reported one. Only a connect that saves a new UUID - /// replaces it; a response that omits it never clears it. var installID: String? - /// Connection Headers for a proxy in front of this host, such as a Cloudflare Access - /// service token, sent with every request to `address` and nowhere else - /// (`HermesHeaders`). Saved as the form admitted them; nil when there are none, - /// including records saved before they existed. Never the webui's custom headers. var headers: [CustomHeader]? - /// Set when this connection signs in through the host's browser sign-in rather than a - /// password (#708). Its `username` is then the host's user id and its `password` empty. - /// Nil for a password connection, including records saved before it existed. var oauth: HermesOAuth? - /// Saved for a dashboard with no sign-in (`HermesSignInMethod.open`, #1314): no username - /// and no browser sign-in, so anyone who reaches `address` reaches the agent too. var hasNoCredentials: Bool { username.isEmpty && oauth == nil } - /// The `install_id` a `/api/status` reply reports, or nil when it is omitted. The host - /// omits it, rather than sending null, whenever it cannot read or persist the id. static func installID(in status: BotJSON) -> String? { guard let value = status["install_id"].text, !value.isEmpty else { return nil } return value } - /// Called with the live `install_id` before any password is sent, or, on a gateway's Webapp, - /// which names it only once signed in, right after sign-in and before anything loads (#1606). - /// Throws `.differentHost` only when both ids are known and differ; a record without one, - /// or a host that omits it this time, connects as before (trust on first use). The id is - /// public on a dashboard, so this catches an address that now reaches another host, not an - /// impostor. func requireSameInstall(_ live: String?) throws { if let installID, let live, installID != live { throw BotFailure.differentHost } } - /// First path segments a browser, config file or curl command adds to the dashboard's - /// root: the pages the root redirects to, sign-in, and the API and gateway socket. private static let dashboardPaths: Set = ["login", "auth", "api", "chat", "sessions"] - /// Parses the connection form's text into the dashboard root every request is built - /// from, so a saved address never has a path, query or fragment. A pasted link is - /// reduced to its root: `ws`/`wss` become `http`/`https`, the query and fragment are - /// dropped, and a path starting with a `dashboardPaths` segment is cleared. Any other - /// path throws `BotAddressError.path`; credentials, other schemes and bad hosts or - /// ports throw `.invalid`. A missing scheme becomes HTTPS, or HTTP for private and - /// local hosts. The form's preview and dev auto-login parse through here too. static func address(_ text: String) throws -> URL { var value = text.trimmingCharacters(in: .whitespacesAndNewlines) guard !value.isEmpty, !value.contains(where: \.isWhitespace) else { throw BotAddressError.invalid } let hasScheme = value.contains("://") if !hasScheme { - // A bare IPv6 literal needs brackets; bracketed literals may include a port. if IPv6Address(value) != nil { value = "[\(value)]" } value = "https://" + value } @@ -95,7 +62,6 @@ struct BotConnection: Codable, Equatable, Identifiable { return url } - /// Infer a scheme only for an omitted one, never as a retry after TLS fails. private static func defaultsToHTTP(_ host: String) -> Bool { if let address = IPv4Address(host) { return privateIPv4(Array(address.rawValue)) } if let address = IPv6Address(host) { @@ -119,33 +85,19 @@ struct BotConnection: Codable, Equatable, Identifiable { } } -/// The account and refresh token of a connection signed in through the host's browser -/// sign-in (#708). The host rotates `refreshToken` on every refresh, so the live -/// `HermesConnection` holds the current one and saves it here -/// (`BotConnectionStore.saveRotatedRefreshToken`) before using the access token it came -/// with; an in-memory copy of this record can hold a token the host has since replaced. struct HermesOAuth: Codable, Equatable { - /// The host's provider name, such as `nous`, sent with every refresh. let provider: String let userID: String var refreshToken: String } -/// Why the connection form's address can't be used. Thrown only by -/// `BotConnection.address(_:)`, so typing mistakes stay apart from `BotFailure` -/// connection failures and never reach the inbox's retry rules. enum BotAddressError: LocalizedError, Equatable { - /// A path that isn't a dashboard page, as typed without trailing slashes. Usually a - /// reverse-proxy prefix, which Hermex can't use yet. case path(String) - /// No usable HTTP or HTTPS host, or the address carries a username or password. case invalid var errorDescription: String? { switch self { case .path(let path): - // A first-strong isolate lays the path out left to right on its own, so its - // leading "/" stays in front of it inside right-to-left translations. let shown = "\u{2068}\(path)\u{2069}" return String(localized: "Remove “\(shown)” from the address. Hermex needs the dashboard's main address, like https://example.com:9119, and can't use a dashboard served under a path yet.") case .invalid: @@ -154,12 +106,6 @@ enum BotAddressError: LocalizedError, Equatable { } } -/// One credential record per configured webui server. Replacing an endpoint or -/// account mints a new identity even when Profile names happen to match, unless the -/// host reports the record's stored `install_id` (`BotConnectionSetup.connect`). -/// Saving other credentials or headers, or removing them, retires the server's shared -/// `HermesConnection` at once; a rename or an install id backfill keeps it. Saving another -/// connection, or removing it, also empties a Limits widget read through the old one (#1409). @MainActor struct BotConnectionStore { var keychain: any KeychainStoring = KeychainStore() var limitsPublisher: ProviderLimitsPublisher = .shared @@ -173,10 +119,6 @@ enum BotAddressError: LocalizedError, Equatable { HermesConnections.shared.retire(server: server, unlessStill: connection) limitsPublisher.invalidate(server: server, unlessConnection: connection.id) } - /// Writes the refresh token the host just rotated into, only while `server`'s record is - /// still connection `id` holding `sent`, the token that connection last saw saved: a - /// record removed or signed in again meanwhile keeps what it has. It never retires the - /// live connection, which made the change. func saveRotatedRefreshToken(_ rotated: String, replacing sent: String, connection id: UUID, server: URL) throws { guard var saved = try load(server: server), saved.id == id, saved.oauth?.refreshToken == sent else { return } saved.oauth?.refreshToken = rotated @@ -190,45 +132,24 @@ enum BotAddressError: LocalizedError, Equatable { } } -/// One `profiles.list` row. Identity comes only from server fields: the Desktop -/// title, then the core `display_name`, then the Profile name (`default` reads as -/// Hermes, as in Desktop). Description follows the same Desktop-then-core order. -/// Pinned, hidden and the user section are Desktop's roster organization. Desktop -/// stamps each filed bot with the section's id and name (`sectionId`, -/// `sectionName`); its section list and order stay in Desktop's plugin storage. -/// `groups` are executable group rooms, not sections. struct BotProfile: Identifiable, Hashable { let id: String let name: String let title: String? let displayName: String? let description: String? - /// The Profile's model as the host names it, for the Shortcuts picker (#1679). let model: String? let preview: String? let lastActive: Date? - /// The canonical chat's root (`canonical_session.id`) and the compression tip - /// the roster read resolved (`resolved_id`). `BotLiveStatus` matches runtimes - /// against both; nil when the bot has no canonical chat. let canonicalID: String? let canonicalTipID: String? let pinned: Bool let hidden: Bool - /// Desktop's user section, trimmed; nil when unfiled. A bot with an id but no - /// name cannot be headed, so the inbox treats it as unfiled. let sectionID: String? let sectionName: String? - /// Desktop's `ui_meta["hermes-bots"]` object as received. A pin, hide or section - /// write sends it back whole with the changed fields applied, so Desktop-only - /// fields survive. let look: [String: BotJSON] - /// True when the host has an avatar asset, so the inbox fetches only rows that have one. let hasAvatar: Bool - /// Desktop's compare-and-swap revision for this bot's look - /// (`ui_meta_revisions["hermes-bots"]`). Nil when the host or bot has none; the - /// avatar is then refetched on every roster load instead of served from memory. let lookRevision: Int? - /// True when the look marks the asset as an uploaded photo (`imageKind`), not a copy of the face. var isPhoto: Bool { look["imageKind"]?.text == "photo" } init?(_ row: BotJSON) { @@ -262,13 +183,8 @@ struct BotProfile: Identifiable, Hashable { } } -/// A bot's live turn state from `session.active_list`, the host's list of live -/// runtimes in its own process. Only what the inbox shows: idle, a reaped -/// runtime, and any status this build does not know read as no status at all. enum BotLiveStatus: Int, Comparable { - /// A turn is running (`working`, `starting`, `streaming`). case working - /// The runtime has an open approval, question or other request for the user. case waiting init?(wire: String?) { @@ -281,11 +197,6 @@ enum BotLiveStatus: Int, Comparable { static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue } - /// Maps `session.active_list` items onto bots by `session_key`, which is the live - /// compression tip or, before the agent exists, the stored key; so it is matched - /// against both the canonical root and the tip the roster read. Items carry no - /// Profile, and stored ids can repeat across Profiles, so a key that names more - /// than one bot marks none of them. Several items on one bot: the most urgent wins. static func statuses(_ items: [BotJSON], profiles: [BotProfile]) -> [String: BotLiveStatus] { var owners: [String: Set] = [:] for profile in profiles { diff --git a/HermesMobile/Features/Bots/BotConnectionView.swift b/HermesMobile/Features/Bots/BotConnectionView.swift index cda604884..1cec5fe0e 100644 --- a/HermesMobile/Features/Bots/BotConnectionView.swift +++ b/HermesMobile/Features/Bots/BotConnectionView.swift @@ -13,21 +13,12 @@ import Observation @State private var copiedPrompt = false @State private var copiedAddress = false @State private var statusCheck: Task? - /// The form loads the saved record once: coming back from the pushed headers editor - /// reruns `.task`, which must not replace the edits in progress, and checks the - /// status again only if leaving cancelled that check. @State private var loaded = false @FocusState private var passwordFocused: Bool - /// Set when the host refused the saved password: the field opens focused with the - /// stored password kept, so typing replaces it and Connect alone retries as is. private let focusesPassword: Bool - /// True when the form is the whole screen, a signed-out Hermes server's sign-in, so - /// there is nothing for Done to close. private let isRoot: Bool - /// Runs once a sign-in is saved, even if the form closed while it connected. private let onSaved: () -> Void - /// `error` opens the form showing why it is needed, such as the host refusing the password. init(server: URL, focusesPassword: Bool = false, isRoot: Bool = false, error: String? = nil, onSaved: @escaping () -> Void = {}) { _setup = State(initialValue: BotConnectionSetup(server: server, error: error)) @@ -44,8 +35,6 @@ import Observation .listRowBackground(Color.clear) Section { if setup.isServerSignIn { - // A Hermes server's address is its identity: removing the server is how - // it changes, through Settings → Servers. Text(verbatim: setup.address).foregroundStyle(.appSecondary).textSelection(.enabled) .accessibilityLabel(Text("Hermes address")).accessibilityValue(setup.address) .accessibilityIdentifier("hermes-connection-address") @@ -79,7 +68,6 @@ import Observation } } appFooter: { VStack(alignment: .leading, spacing: 4) { - // Under the password, so the focused field's keyboard never covers it. if let error = setup.errorMessage { Label { Text(error) @@ -91,8 +79,6 @@ import Observation } if let attempt = setup.failedAttempt { ConnectionAttemptDetails(attempt: attempt) } if setup.offersStatusRetry { - // A signed-out server's status says whether it signs in through the - // browser; there is no status section to check it again from. Button("Check again") { statusCheck?.cancel() statusCheck = Task { await setup.checkStatus() } @@ -100,8 +86,6 @@ import Observation .accessibilityIdentifier("hermes-connection-check-status") } if !setup.isServerSignIn { - // The trailing mark keeps a URL ending in a neutral character, such as an - // IPv6 literal's "]", in one left-to-right run inside right-to-left text. if let preview = setup.addressPreview { Text("Will connect to \(preview.absoluteString + "\u{200E}")") .accessibilityIdentifier("hermes-connection-address-preview") @@ -191,8 +175,6 @@ import Observation private var browser: HermesBrowserSignIn.Presenter { HermesBrowserSignIn.Presenter(webAuthenticationSession) } - /// The Connection Headers row, which pushes the shared editor, and a footer that puts - /// a rejected header or a half Cloudflare Access pair above what headers are for. private var headersSection: some View { Section { NavigationLink { @@ -234,8 +216,6 @@ import Observation .disabled(setup.isConnecting) } - /// Read-only rows from the host's public status. Gateway rows appear only after - /// the host answered; the version falls back to the one stored at sign-in. @ViewBuilder private func statusSection(_ saved: BotConnection) -> some View { let live: BotHostStatus? = if case .reachable(let status) = setup.hostStatus { status } else { nil } Section { @@ -306,8 +286,6 @@ private extension BotConnectionSetup.HostStatus { } extension BotHostStatus { - /// Upstream reports a dead gateway process as `stopped`, `startup_failed` or a - /// watchdog `degraded`, so `gateway_running` decides whether scheduled Tasks run. var gatewayStopped: Bool { gatewayRunning == false || (gatewayRunning == nil && ["stopped", "startup_failed"].contains(gatewayState)) } @@ -325,9 +303,6 @@ extension BotHostStatus { } } - /// Only scheduled Tasks depend on the gateway: Bot chat and WebUI reply - /// notifications come from the process running the turn, so the copy never - /// claims those stop. var gatewayNote: String? { if gatewayStopped { let consequence = String(localized: "Scheduled Tasks won’t run until it starts.") @@ -339,43 +314,28 @@ extension BotHostStatus { } } -/// Owns one sign-in attempt. Parsing failures and late transport replies obey the -/// same lifetime, including attempts cancelled before a client was constructed. @MainActor @Observable final class BotConnectionSetup { let server: URL - /// True when `server` is a Hermes server and this record is its own sign-in (#899): the - /// address is the server's and can't change, and the record can't be removed here, only - /// with the server in Settings → Servers. let isServerSignIn: Bool var name = "" var address = "" { didSet { failedAttempt = nil } } var username = "" { didSet { failedAttempt = nil } } var password = "" { didSet { failedAttempt = nil } } - /// The Connection Headers being edited. Saved with the connection by `connect()`, - /// without blank rows. var headers: [CustomHeader] = [] { didSet { failedAttempt = nil } } private(set) var saved: BotConnection? private(set) var errorMessage: String? { didSet { failedAttempt = nil } } - /// What the failed Connect behind `errorMessage` observed, shown as its Details (#1395). Set - /// after the message it explains; a new message or an edit to what Connect sends drops it. private(set) var failedAttempt: HermesAttemptRecord? private(set) var isConnecting = false - /// The address whose host reported a different `install_id` on the last attempt. private(set) var differentHostAddress: URL? - /// The saved host's public status; nil while no connection is saved. private(set) var hostStatus: HostStatus? - /// The relay this server's notifications are paired with; nil when they are off. private(set) var notificationRelay: URL? @ObservationIgnored private let store: BotConnectionStore @ObservationIgnored private let makeWire: (BotConnection) -> any BotTransport @ObservationIgnored private let discard: (BotConnection) async -> Void - /// The offline cache, from the screen: a replaced or removed connection's Bot Chat - /// transcripts leave it too (#1144). @ObservationIgnored var offlineCache: ModelContext? @ObservationIgnored private var client: (any BotTransport)? @ObservationIgnored private let probe: (URL, HermesHeaders) async -> Result @ObservationIgnored private let relay: (URL) -> URL? - /// The URL session setup of a browser sign-in's own connection; tests script the host with it. @ObservationIgnored private let hermesConfiguration: () -> URLSessionConfiguration @ObservationIgnored private var attempt: UUID? @ObservationIgnored private var statusCheck: UUID? @@ -384,8 +344,6 @@ extension BotHostStatus { case checking, reachable(BotHostStatus), unreachable(BotHostProbeFailure) } - /// `isServerSignIn` defaults to whether the registry lists `server` as a Hermes server. - /// `error` is shown until the first Connect. init(server: URL, isServerSignIn: Bool? = nil, error: String? = nil, store: BotConnectionStore? = nil, makeWire: ((BotConnection) -> any BotTransport)? = nil, discard: ((BotConnection) async -> Void)? = nil, @@ -396,8 +354,6 @@ extension BotHostStatus { self.hermesConfiguration = hermesConfiguration self.isServerSignIn = isServerSignIn ?? ServerRegistry.shared.servers.contains { $0.id == server.absoluteString && $0.kind == .hermes } - // The candidate is not saved yet, so it signs in on its own cookie jar, never the - // server's shared one. self.makeWire = makeWire ?? { BotClient(connection: $0) } self.probe = probe ?? { await BotHostStatusProbe().check($0, headers: $1) } self.relay = relay ?? { PushRegistrar.shared?.pairing(for: $0)?.relayURL } @@ -414,8 +370,6 @@ extension BotHostStatus { errorMessage = error } - /// The root `connect()` would use for the typed text, or nil while it doesn't parse. - /// Parse errors wait for Connect so they never nag mid-word. var addressPreview: URL? { try? BotConnection.address(address) } var canConnect: Bool { @@ -425,10 +379,6 @@ extension BotHostStatus { && !username.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !password.isEmpty } - /// How this Hermes server's host offers to sign in, the default first: as its status says, - /// or, until the status answers, as its saved sign-in did, through the browser (#708) or - /// without credentials (#1314). Only a Hermes server's own sign-in; a webui server's Bots - /// connection keeps the password form. var offeredSignInMethods: [HermesSignInMethod] { guard isServerSignIn else { return [.password] } if case .reachable(let status) = hostStatus { return status.signInMethods } @@ -436,12 +386,8 @@ extension BotHostStatus { return saved?.hasNoCredentials == true ? [.open] : [.password] } - /// The Password | Browser picker's choice, while the host offers it. private var pickedSignInMethod: HermesSignInMethod? - /// How Connect signs in: the picked method, else the browser for a saved browser sign-in - /// on a host that offers both, else the host's default. Each saves only its own - /// credential, so switching leaves no stale one. var signInMethod: HermesSignInMethod { get { let offered = offeredSignInMethods @@ -456,18 +402,13 @@ extension BotHostStatus { } } - /// The Password | Browser picker, for a host that offers both. var offersSignInChoice: Bool { offeredSignInMethods.count > 1 } - /// Why the edited headers can't be sent to Hermes (`HermesHeaders`), shown under the - /// Connection Headers row; Connect stays off until it is fixed. Nil when they can. var headerRejection: String? { do { _ = try HermesHeaders(headers.sanitizedForStorage(), signsInWithBrowser: signInMethod == .browser); return nil } catch { return error.localizedDescription } } - /// The `headerRejection` that only a browser sign-in makes, an `Authorization` row, - /// which the form shows under the sign-in method instead. var browserHeaderRejection: String? { guard signInMethod == .browser else { return nil } do { _ = try HermesHeaders(headers.sanitizedForStorage(), signsInWithBrowser: true); return nil } @@ -475,20 +416,14 @@ extension BotHostStatus { catch { return nil } } - /// Shown under the Connection Headers row when only one of Cloudflare Access's two - /// service-token headers has a value. Access treats such a request as signed out, - /// but Connect stays on and sends what was entered. var accessPairWarning: String? { let filled = Set(headers.filter { !$0.sanitizedValue.isEmpty }.map { $0.sanitizedName.lowercased() }) guard filled.contains("cf-access-client-id") != filled.contains("cf-access-client-secret") else { return nil } return String(localized: "Cloudflare Access needs both CF-Access-Client-Id and CF-Access-Client-Secret.") } - /// Remove is offered for a saved side connection, never for a Hermes server's own sign-in. var offersRemoval: Bool { saved != nil && !isServerSignIn } - /// The replace action is offered only for the address that was refused, so editing - /// the address to the right one never leaves a data-clearing button behind. var offersHostReplacement: Bool { !isConnecting && differentHostAddress != nil && differentHostAddress == (try? BotConnection.address(address)) } @@ -496,7 +431,6 @@ extension BotHostStatus { func load() { do { saved = try store.load(server: server) - // A Hermes server signed out has no record, but its address is still its own. name = saved?.name ?? ""; address = isServerSignIn ? server.absoluteString : saved?.address.absoluteString ?? "" username = saved?.username ?? ""; password = saved?.password ?? "" headers = saved?.headers ?? [] @@ -504,15 +438,11 @@ extension BotHostStatus { notificationRelay = relay(server) } - /// A signed-out Hermes server's status read failed, so the form can't tell how it signs in: - /// the sign-in section offers to read it again, such as after the network or the Connection - /// Headers change. var offersStatusRetry: Bool { guard isServerSignIn, saved == nil, case .unreachable = hostStatus else { return false } return true } - /// The address whose status the form reads: the saved one, else a Hermes server's own. private var statusAddress: URL? { saved?.address ?? (isServerSignIn ? server : nil) } func cancel() { @@ -520,9 +450,6 @@ extension BotHostStatus { statusCheck = nil } - /// Reads the saved host's public status once, with its saved headers, or a signed-out - /// Hermes server's with the form's, which says how it signs in. - /// Nothing retries; a newer check, `cancel()` or a changed saved address drops a late reply. func checkStatus() async { guard let checked = statusAddress else { hostStatus = nil; return } let sent = saved.map(HermesHeaders.init(saved:)) ?? (try? HermesHeaders(headers.sanitizedForStorage())) ?? .none @@ -536,15 +463,6 @@ extension BotHostStatus { } } - /// Signs in with the form's headers and saves the connection with them. The UUID, and - /// with it drafts, cache and push pairing, is kept when the host reports the saved - /// `install_id`, when address and username are unchanged, or when a saved browser sign-in - /// switches to this one at its address, whatever the headers; otherwise the old - /// connection's data is discarded. An unchanged address must still - /// reach the saved install before the password is sent. `replacingHost` is the user's - /// answer to `.differentHost`: it drops that expectation and always starts a new connection. - /// A server that signs in through the browser shows its host's page with `browser` instead, - /// and one without sign-in saves no username or password. func connect(replacingHost: Bool = false, browser: HermesBrowserSignIn.Presenter = .unavailable) async -> Bool { guard !isConnecting, !Task.isCancelled else { return false } if signInMethod == .browser { return await connectThroughBrowser(browser, replacingHost: replacingHost) } @@ -568,8 +486,6 @@ extension BotHostStatus { guard attempt == id, !Task.isCancelled else { return false } let live = wire.serverInstallID let sameInstall = live != nil && live == saved?.installID - // A switch from the saved browser sign-in is the same connection: `wire.connect()` - // has already refused a host whose `install_id` contradicts the saved one. let sameAccount = saved?.address == url && (saved?.oauth != nil || saved?.username == account) let kept = replacingHost ? nil : (sameInstall || sameAccount ? saved : nil) let candidate = BotConnection(id: kept?.id ?? UUID(), name: label, address: url, username: account, @@ -581,8 +497,6 @@ extension BotHostStatus { } catch { guard attempt == id, !Task.isCancelled else { return false } if error as? BotFailure == .differentHost { differentHostAddress = attempted } - // Only the header policy and the address parse throw before `attempted` is set, - // with a `HermesHeaders.Rejection` or a `BotAddressError`. errorMessage = attempted.map { BotConnectionAdvice.message(for: error, address: $0) } ?? error.localizedDescription failedAttempt = client?.lastAttempt @@ -590,11 +504,6 @@ extension BotHostStatus { } } - /// A Hermes server's sign-in through its host's browser page (#708), shown by `browser`. - /// The UUID, and with it drafts, cache and push pairing, is kept when the host reports - /// the saved `install_id`, the same account signs in again, or a saved sign-in without the - /// browser switches to it at its address; otherwise the old connection's data is - /// discarded, as in `connect`. Closing the sheet shows no error. private func connectThroughBrowser(_ browser: HermesBrowserSignIn.Presenter, replacingHost: Bool) async -> Bool { let id = UUID(); attempt = id; isConnecting = true; errorMessage = nil; differentHostAddress = nil defer { if attempt == id { isConnecting = false; attempt = nil } } @@ -611,8 +520,6 @@ extension BotHostStatus { guard attempt == id, !Task.isCancelled else { return false } let signedIn = http.connection let sameInstall = http.serverInstallID != nil && http.serverInstallID == saved?.installID - // A switch to the browser is the same connection: the sign-in has already refused - // a host whose `install_id` contradicts the saved one. let sameAccount = saved?.address == server && (saved?.oauth.map { $0.provider == signedIn.oauth?.provider && $0.userID == signedIn.oauth?.userID } ?? true) @@ -630,9 +537,6 @@ extension BotHostStatus { } } - /// Saves `candidate`, the commit point, and then drops the data of the connection it - /// replaced, if another. Old-account cleanup must finish even if the sheet disappears - /// afterwards; a committed replacement is success. private func commit(_ candidate: BotConnection) async -> Bool { let old = saved do { try store.save(candidate, server: server) } catch { @@ -640,8 +544,6 @@ extension BotHostStatus { return false } saved = candidate - // The old host's status and any check still in flight describe a host - // this screen no longer shows. if old?.address != candidate.address { statusCheck = nil; hostStatus = nil } if let old, old.id != candidate.id { await discardData(of: old) @@ -667,8 +569,6 @@ extension BotHostStatus { } } - /// Drops what this phone kept for a connection replaced or removed. Its offline cache rows - /// go at once; the rest in a task the sheet's dismissal can't cancel. private func discardData(of old: BotConnection) async { if let offlineCache { try? CacheStore.removeHermesBotChats(serverURL: server, connectionID: old.id, in: offlineCache) @@ -677,8 +577,6 @@ extension BotHostStatus { await Task { await discard(old) }.value } - /// Generic instructions only: no credentials or configured host is copied. - /// The agent discovers its installed version instead of following pinned CLI recipes. static let prompt = """ Help me connect the Hermex iPhone app to my existing Hermes dashboard for Bots and notifications. Hermex already connects to hermes-webui, but this is a separate direct dashboard connection. @@ -692,8 +590,6 @@ extension BotHostStatus { """ } -/// The unconnected inbox uses the same drawn faces as the bot editor. Each short -/// playful bit returns to neutral, and covered/inactive screens render still faces. struct BotConnectionWelcomeView: View { let isCovered: Bool let onConnect: () -> Void @@ -736,7 +632,6 @@ struct BotConnectionWelcomeView: View { } } -/// The Password | Browser segment of a sign-in form whose host offers both (#1539). struct HermesSignInMethodPicker: View { @Binding var selection: HermesSignInMethod @@ -750,7 +645,6 @@ struct HermesSignInMethodPicker: View { } } -/// The warning shown wherever a Hermes dashboard with no password is signed in to or saved (#1314). struct OpenDashboardWarning: View { var body: some View { Label { @@ -762,9 +656,6 @@ struct OpenDashboardWarning: View { } } -/// The collapsed Details under a connect form's advice (#1395): each stage of the failed -/// attempt, then Copy Details (`HermesAttemptRecord.report`). Saved setup, onboarding and Add -/// Server show it under their error; its text takes the surrounding foreground style. struct ConnectionAttemptDetails: View { let attempt: HermesAttemptRecord @State private var isExpanded = false @@ -798,7 +689,6 @@ struct ConnectionAttemptDetails: View { } } .font(AppFont.footnote()) - // A newer attempt's record starts collapsed and uncopied. .onChange(of: attempt) { isExpanded = false; copied = false } } diff --git a/HermesMobile/Features/Bots/BotCreateView.swift b/HermesMobile/Features/Bots/BotCreateView.swift index 55f3058b8..bc2267852 100644 --- a/HermesMobile/Features/Bots/BotCreateView.swift +++ b/HermesMobile/Features/Bots/BotCreateView.swift @@ -1,16 +1,10 @@ import SwiftUI -/// The create and duplicate sheet: a live face, the name, an optional role, the -/// drawn look, the model and the credential choice, plus instructions and the -/// bundled-skills choice for a new bot, then one Create button. -/// After a partial create the same sheet shows each step's outcome and Try Again. @MainActor struct BotCreateView: View { @State private var creator: BotCreator @State private var showsModels = false @State private var showsExpressions = false @State private var showsDescribe = false - /// What the face should do about the last edit: a hop for a shape, a wobble - /// for a color, a glance down while the name is typed. @State private var cue: BotFaceCue? @Environment(\.dismiss) private var dismiss @Environment(\.scenePhase) private var scenePhase @@ -24,9 +18,6 @@ import SwiftUI BotInteractiveFaceView(name: creator.name, appearance: creator.draft.appearance, size: 150, cue: cue) .padding(.top, 24).padding(.bottom, 20) if creator.hasStarted { results } - // Once the Profile write has been dispatched these values are on the - // host; a retry only finishes the remaining steps, so editing them - // here would be a lie. Edit the bot afterwards instead. card { TextField("Name your bot", text: Binding(get: { creator.draft.title }, set: { creator.setTitle($0); cue = BotFaceCue(.glanceDown) })) .font(AppFont.title3()).multilineTextAlignment(.center) @@ -70,7 +61,6 @@ import SwiftUI : "The bot starts with no API keys. Add them in Hermes Desktop before it can answer.") .font(AppFont.caption2()).foregroundStyle(.appTertiary).padding(.horizontal, 12).padding(.top, 7) - // A duplicate copies the source's instructions and skills, so these are new-bot only. if !creator.isDuplicate { startingPoint.disabled(creator.hasStarted) } } .padding(.horizontal, 16) @@ -116,12 +106,9 @@ import SwiftUI .task { await creator.load() } .onDisappear { creator.close() } .onChange(of: scenePhase) { if scenePhase == .background { creator.close() } } - // A clean create closes on its own; one with leftovers stays up so the - // results and the note are read before Done. .onChange(of: creator.phase) { if creator.phase == .created, !creator.needsAttention { dismiss() } } } - /// The new bot's instructions and whether it starts with the bundled skills. @ViewBuilder private var startingPoint: some View { sectionLabel("Instructions") card { @@ -154,7 +141,6 @@ import SwiftUI : "The bot starts with every skill that ships with Hermes.") } - /// Footnote under a card, leading-aligned however short it is. private func caption(_ text: LocalizedStringKey) -> some View { Text(text).font(AppFont.caption2()).foregroundStyle(.appTertiary) .frame(maxWidth: .infinity, alignment: .leading) @@ -187,7 +173,6 @@ import SwiftUI } } - /// Per-step outcomes after an attempt, mirroring the editor's save results. private var results: some View { VStack(alignment: .leading, spacing: 10) { Text(creator.phase == .created ? (creator.needsAttention ? "Created, with a note" : "Created") : "Needs Attention").font(AppFont.headline()) diff --git a/HermesMobile/Features/Bots/BotCreator.swift b/HermesMobile/Features/Bots/BotCreator.swift index 692155875..d98d19671 100644 --- a/HermesMobile/Features/Bots/BotCreator.swift +++ b/HermesMobile/Features/Bots/BotCreator.swift @@ -1,9 +1,6 @@ import Foundation import Observation -/// Hermes Profile names as the host validates them: `[a-z0-9][a-z0-9_-]{0,63}`, -/// never `default` or another reserved word. The slug is derived from the display -/// name the user types, so the roster title and the folder name stay related. enum BotProfileName { static let reserved: Set = ["hermes", "default", "test", "tmp", "root", "sudo"] @@ -28,12 +25,6 @@ enum BotProfileName { } } -/// One bot creation or duplication for one connection. Setup is three host writes -/// in order: the Profile (`profiles.create`), its look (`profiles.configure`) and -/// its canonical "Bot Chat" (`session.create` + `session.title`). Each step records -/// its own outcome; Try Again repeats only the steps that are not done, and a -/// step whose reply was lost re-reads the host before writing again, so a retry -/// never mints a second Profile or a second chat. @MainActor @Observable final class BotCreator { enum Step: CaseIterable, Identifiable { case profile, look, chat @@ -54,30 +45,19 @@ enum BotProfileName { var role = "" var appearance = BotProfileAppearance(look: [:], fallbackTitle: "") var model: ModelCatalogOption? - /// On: `share_auth`, the new bot reads the host's saved sign-ins and keys in - /// place. Off: `mirror_credentials: false`, the bot starts with none. Values - /// never travel to the phone either way. var sharesCredentials = true - /// New bots only: becomes the Profile's `SOUL.md` when it has text; empty - /// keeps the host's default. A duplicate copies the source's instead. var instructions = "" - /// New bots only: `no_skills`, so the host seeds only its essential skills. - /// The host refuses it with `clone_from`, since a copy brings the source's skills. var skipsBundledSkills = false } let server: URL let connection: BotConnection - /// The bot being duplicated, whose config, skills and instructions the host clones. let source: BotProfile? private(set) var draft: Draft private(set) var phase = Phase.editing - /// True while the socket and model inventory are being opened; Create waits for it. private(set) var isLoading = false private(set) var outcomes: [Step: Outcome] = [:] private(set) var modelGroups: [ModelCatalogGroup] = [] - /// One-line note after a successful create when the host reports the bot - /// ended up without a model, so the user knows to finish setup. private(set) var note: String? private var taken: Set @@ -109,11 +89,8 @@ enum BotProfileName { self.draft = draft } - /// The Profile folder name the host will get; empty when the title yields none. var name: String { BotProfileName.slug(from: draft.title) } var nameIsTaken: Bool { taken.contains(name) } - /// True once a create attempt has written anything: the name is committed and - /// Try Again resumes the same bot instead of starting another. var hasStarted: Bool { !outcomes.isEmpty } var nameProblem: String? { let name = self.name @@ -128,8 +105,6 @@ enum BotProfileName { phase == .editing && !isLoading && BotProfileName.isValid(name) && (hasStarted || !nameIsTaken) } var isDuplicate: Bool { source != nil } - /// True after a create that finished with something left to do: a look that - /// did not save or a bot with no model. The sheet stays up to say so. var needsAttention: Bool { note != nil || outcomes.values.contains { $0 != .done } } func setTitle(_ value: String) { draft.title = value; draft.appearance.title = value } @@ -148,7 +123,6 @@ enum BotProfileName { } var holdsConnection: Bool { wire != nil } - /// "Describe It" under the default Profile: the new bot does not exist yet. func sendAvatarPrompt(_ prompt: String) async throws -> String { guard let client = wire else { throw BotFailure.stale } return try await BotAvatarGeneration.ask(prompt, profile: "default", transport: client, validateDispatch: validate(generation)) @@ -161,8 +135,6 @@ enum BotProfileName { draft.appearance.expression = expression == .neutral ? nil : expression.rawValue } - /// Opens the socket and reads the model inventory. A failure here leaves the - /// picker empty; the create itself reconnects if needed. func load() async { generation += 1 let owner = generation @@ -196,7 +168,6 @@ enum BotProfileName { } } - /// Runs the steps that are not done yet. Never called twice concurrently. func create() async { guard canCreate else { return } generation += 1 @@ -220,12 +191,8 @@ enum BotProfileName { phase = .created onCreated(name) } catch { - // A disconnect clears `wire` before the suspended call throws, so only the - // generation decides whether this attempt still owns the sheet. guard generation == owner else { return } if !(error is BotCreatorStop), let step = Step.allCases.first(where: { outcomes[$0] == nil }) { - // A dropped connection mid-write leaves that write's fate unknown; the - // next attempt re-reads the host before writing again. outcomes[step] = error as? BotFailure == .transport ? .uncertain : .failed(error.localizedDescription) } phase = .editing @@ -270,7 +237,6 @@ enum BotProfileName { } } - /// The look is cosmetic: a failure is reported but does not stop the chat step. private func configureLook(_ client: any BotTransport, owner: Int) async { if outcomes[.look] == .done { return } var look = draft.appearance @@ -287,8 +253,6 @@ enum BotProfileName { } } - /// Adopt-before-mint, as Desktop: an existing "Bot Chat" row is the bot's chat - /// and is never duplicated. Only a confirmed absence creates one. private func ensureChat(_ client: any BotTransport, owner: Int) async throws { if outcomes[.chat] == .done { return } if try await findChat(client, owner: owner) { outcomes[.chat] = .done; return } @@ -296,15 +260,11 @@ enum BotProfileName { let created = try await client.call(.sessionCreate(profile: name), validateDispatch: validate(owner)) try ensureOwner(owner, client) guard let runtime = created["session_id"].text, !runtime.isEmpty else { throw BotFailure.unsupported } - // A canonical create already titled and hid it (#1603), and has no `session.title`. if client.speaksCanonicalProtocol { outcomes[.chat] = .done; return } do { - // The created row is lazy; the title write persists it so the roster and - // the phone's exact-title lookup find it before any prompt. _ = try await client.call(.sessionTitle(sessionID: runtime), validateDispatch: validate(owner)) try ensureOwner(owner, client) } catch BotFailure.rejected(4022) { - // Another writer took the title in between; that chat is the bot's. try ensureOwner(owner, client) guard try await findChat(client, owner: owner) else { throw BotFailure.unsupported } } @@ -340,5 +300,4 @@ enum BotProfileName { } } -/// Ends a create after a step recorded its own failure message. private struct BotCreatorStop: Error {} diff --git a/HermesMobile/Features/Bots/BotDeepLink.swift b/HermesMobile/Features/Bots/BotDeepLink.swift index 121b450e0..510dae0ab 100644 --- a/HermesMobile/Features/Bots/BotDeepLink.swift +++ b/HermesMobile/Features/Bots/BotDeepLink.swift @@ -1,16 +1,10 @@ import Foundation -/// Where an external event — today a deep link, later a push or a Live Activity tap — -/// wants the app to land inside Bot Mode. Identity only, never a display name: the -/// configured server owns the Bot connection, the connection UUID survives password -/// and name edits, and the Profile name is the server's own key for that bot. -/// `conversation` is the bot's durable canonical root when the sender knows it (#554). struct BotDestination: Equatable, Hashable { let server: URL let connectionID: UUID let profile: String var conversation: String? - /// Also opens the bot's Screen, when the server's Bot Screen switch is on (#1567). var opensScreen = false } @@ -19,10 +13,6 @@ extension HermesDeepLink { private static let conversationQueryItem = "conversation" private static let screenQueryItem = "screen" - /// `hermes-agent://bot?server=…&connection=…&profile=…[&conversation=…][&screen=1]`, the one - /// bot route (scheme follows the active build, e.g. `-branch`). Every part rides as - /// a query item, like `newChatInProfileURL`, so a Profile name with spaces or - /// non-ASCII is percent-encoded rather than mangled into the host. static func botURL(for destination: BotDestination) -> URL? { let profile = destination.profile.trimmingCharacters(in: .whitespacesAndNewlines) guard !profile.isEmpty else { return nil } @@ -43,9 +33,6 @@ extension HermesDeepLink { return components.url } - /// Parses a bot route into its typed destination. Nil for any other kind of link and - /// for one missing the identity needed to route without guessing — a link is dropped - /// rather than opening the wrong bot. static func botDestination(from url: URL) -> BotDestination? { guard url.scheme?.lowercased() == scheme, url.host?.lowercased() == botHost else { return nil } @@ -55,8 +42,6 @@ extension HermesDeepLink { } guard let rawServer = value(serverQueryItem), - // The registry stores normalized URLs, so normalize here too: a link - // written with a trailing slash still matches its configured server. let server = try? AuthManager.normalizedServerURL(from: rawServer), let connectionID = value(connectionQueryItem).flatMap(UUID.init(uuidString:)), let profile = value(profileQueryItem) @@ -79,26 +64,13 @@ extension HermesDeepLink { } } -/// What the app should do with one bot deep link, decided before any navigation so -/// every outcome is testable without a view (#554). enum BotDeepLinkOutcome: Equatable { - /// Nothing to route: Bot Mode is off and the named server is a webui server, the - /// named server is gone, or its Bot connection was removed or replaced. The app - /// opens normally, with no error. case ignore - /// Hold the destination until the user is signed in, then resolve it again. case waitForSignIn(BotDestination) - /// Make the destination's server active first. That rebuilds the logged-in tree - /// against it, and the held destination routes there. case switchServer(ServerAccount, BotDestination) - /// The destination's server is already active: hand it to the Bots inbox. case open(BotDestination) } -/// Turns a bot deep link into an outcome, using only what the app already knows — -/// the Bot Mode gate, the server registry, the per-server Bot connection and the -/// auth state. The roster is not consulted here: an unknown Profile is resolved by -/// the inbox it lands on, so a link never waits on a socket to be routed. @MainActor enum BotDeepLinkRouter { static func resolve( _ destination: BotDestination, @@ -110,11 +82,7 @@ enum BotDeepLinkOutcome: Equatable { guard let account = servers.first(where: { $0.id == destination.server.absoluteString }) else { return .ignore } - // Bot Mode off: a webui server's session list opens and no Bot UI leaks through a - // link. A Hermes server is Bot UI throughout and opens either way (#899). guard isBotModeEnabled || account.kind == .hermes else { return .ignore } - // A replaced endpoint or account mints a new connection UUID, so this also - // covers "the link names a bot on a connection this server no longer has". guard botConnectionID(destination.server) == destination.connectionID else { return .ignore } switch state { @@ -127,23 +95,14 @@ enum BotDeepLinkOutcome: Equatable { } } - /// The server's saved Bot connection, from the per-server Keychain record the way every - /// other caller reads it. static func savedConnectionID(for server: URL) -> UUID? { (try? BotConnectionStore().load(server: server))?.id } - /// Whether an inbox in this state can answer a held link now. A live roster can. - /// A connecting or quietly retrying socket cannot yet, and the link waits rather - /// than being lost to a transient failure. An inbox that has settled with no Bot - /// connection at all never will, so the link is dropped instead of held forever. static func inboxCanAnswer(link: BotInbox.Link, hasConnection: Bool, hasSettled: Bool) -> Bool { link == .live || (hasSettled && !hasConnection) } - /// The bot a held destination names on the roster now on screen, or nil when the - /// connection was replaced under it or the server no longer has that Profile. - /// Equal Profile names on two connections never match each other. static func profile( for destination: BotDestination, connection: BotConnection?, @@ -154,11 +113,7 @@ enum BotDeepLinkOutcome: Equatable { } } -/// The inbox's presented chat and optional linked root. Resolving a link replaces -/// the whole selection, including when its Profile is no longer on the roster. struct BotInboxSelection { - // The inbox owns one destination on every width: picking a room replaces - // the bot (including a linked conversation), and picking a bot replaces the room. var profile: BotProfile? { didSet { if profile != nil { room = nil } @@ -173,10 +128,7 @@ struct BotInboxSelection { var conversation: String? { didSet { chatContinuity = ChatContinuity() } } - /// The open chat's, for the `ChatView` of whichever width is showing it (#1528). private(set) var chatContinuity = ChatContinuity() - /// New on every pick, the same bot or room again included, so a regular-width detail - /// re-roots and pops what it pushed, as a Sessions row does. private(set) var pick = UUID() @MainActor mutating func open( @@ -187,11 +139,6 @@ struct BotInboxSelection { conversation = profile == nil ? nil : destination.conversation } - /// The chat the selected bot opens (#1146): its canonical Bot Chat in the regular chat, the - /// one destination every bot route reaches (inbox row and tile, search, deep link, push and - /// Live Activity taps, a Sessions search hit, an Archived Bot Chat row). A link's root is - /// seeded, so a chat the host has since replaced opens the current one with its notice - /// (#1339). Nil with no bot selected. func chat(server: URL, connection: BotConnection) -> HermesSessionChat? { profile.map { HermesSessionChat(server: server, connection: connection, target: .canonicalChat(profile: $0.id), diff --git a/HermesMobile/Features/Bots/BotExpressionPickerView.swift b/HermesMobile/Features/Bots/BotExpressionPickerView.swift index cde9e03fa..287bd072e 100644 --- a/HermesMobile/Features/Bots/BotExpressionPickerView.swift +++ b/HermesMobile/Features/Bots/BotExpressionPickerView.swift @@ -1,8 +1,5 @@ import SwiftUI -/// Pushed from the editor's Expression row: a large live preview of the draft face -/// above the sixteen named rest expressions. Tapping a tile edits the draft only; -/// Save on the editor persists it. @MainActor struct BotExpressionPickerView: View { let editor: BotProfileEditor diff --git a/HermesMobile/Features/Bots/BotFaceMotion.swift b/HermesMobile/Features/Bots/BotFaceMotion.swift index 47d6b0c31..f2d739d58 100644 --- a/HermesMobile/Features/Bots/BotFaceMotion.swift +++ b/HermesMobile/Features/Bots/BotFaceMotion.swift @@ -1,27 +1,17 @@ import SwiftUI -/// How a drawn bot face moves. `.still` is one frozen frame, used by the picker -/// tiles, Reduce Motion and the extensions. `.idle` blinks on a sparse schedule. -/// `.working` is Desktop's lean-and-sway pose for the open bot while its turn is live: -/// it sways for one `BotWorkingSchedule.beat` from `since`, then holds a still lean -/// that only blinks, so a long turn never keeps a 15 fps loop running. enum BotFaceMotion: Equatable, Sendable { case still, idle case working(since: Date) - /// Reduce Motion collapses every mode to a still face. func honoring(reduceMotion: Bool) -> BotFaceMotion { reduceMotion ? .still : self } } -/// One frame of a face: gaze offset as a fraction of the mark size, head roll in -/// degrees and the lid factor applied to eye height (1 open, 0.06 shut). struct BotFacePose: Equatable, Sendable { var gazeX = 0.0 var gazeY = 0.0 var roll = 0.0 var lid = 1.0 - /// Vertical lift as a fraction of the mark size (positive is up) and the - /// squash-and-stretch scale, used only by the playful bits. var lift = 0.0 var scaleX = 1.0 var scaleY = 1.0 @@ -29,7 +19,6 @@ struct BotFacePose: Equatable, Sendable { static let rest = BotFacePose() static let blink = BotFacePose(lid: 0.06) - /// Desktop's `work` pose (`avatar.tsx` facePose), scaled from head degrees onto the mark. static func working(at t: Double) -> BotFacePose { let turn = -11 + sin(t * 0.48) * 8 let tilt = sin(t * 0.42) * 8 + sin(t * 1.1) * 1.6 @@ -38,14 +27,9 @@ struct BotFacePose: Equatable, Sendable { return BotFacePose(gazeX: turn * 0.0025, gazeY: -tilt * 0.0025, roll: roll, lid: blink ? 0.06 : 1) } - /// The working lean with the sway taken out: gaze held aside at the pose's - /// centre turn, no tilt or roll. Still reads "busy, looking at its work". static let settledWorking = BotFacePose(gazeX: -11 * 0.0025) } -/// A `TimelineView` schedule that fires only at blink edges: shut, then open 180 ms -/// later, every 3 to 5 seconds. The period and phase are seeded by the bot's name so -/// a list of faces never blinks in unison. Nothing repaints between entries. struct BotBlinkSchedule: TimelineSchedule, Equatable { static let shutDuration = 0.18 let period: Double @@ -57,11 +41,9 @@ struct BotBlinkSchedule: TimelineSchedule, Equatable { phase = Double((hash >> 20) % 5000) / 1000 } - /// Whether the eyes are shut at `date`; the same rule the entries are cut from. func isShut(at date: Date) -> Bool { let offset = (date.timeIntervalSinceReferenceDate - phase).truncatingRemainder(dividingBy: period) let position = offset < 0 ? offset + period : offset - // The open entry lands exactly at shutDuration; keep float error from reading it as shut. return position + 0.0001 < Self.shutDuration } @@ -69,8 +51,6 @@ struct BotBlinkSchedule: TimelineSchedule, Equatable { let period = period, shut = Self.shutDuration let base = start.timeIntervalSinceReferenceDate let firstShut = phase + (floor((base - phase) / period) + 1) * period - // Starting inside a blink still needs that blink's open edge, or the eyes - // would stay shut until the next cycle. let pendingOpen: Date? = isShut(at: start) ? Date(timeIntervalSinceReferenceDate: firstShut - period + shut) : nil return AnySequence { () -> AnyIterator in var index = -1 @@ -86,10 +66,6 @@ struct BotBlinkSchedule: TimelineSchedule, Equatable { } } -/// The working face's `TimelineView` schedule: 15 fps for `beat` seconds from `start`, -/// then only the bot's blink edges. `start` is when the current beat began (the turn -/// started working, or the app came back to the foreground mid-turn), so a two-hour -/// run stops repainting after the beat. A waiting face never uses it (#757). struct BotWorkingSchedule: TimelineSchedule, Equatable { static let beat = 30.0 static let frameInterval = 1.0 / 15 @@ -98,7 +74,6 @@ struct BotWorkingSchedule: TimelineSchedule, Equatable { private var end: Date { start.addingTimeInterval(Self.beat) } - /// The swaying pose inside the beat, then the settled lean with the blink's lid. func pose(at date: Date) -> BotFacePose { if date < end { return .working(at: date.timeIntervalSinceReferenceDate) } var pose = BotFacePose.settledWorking @@ -112,7 +87,6 @@ struct BotWorkingSchedule: TimelineSchedule, Equatable { let first = max(date, start), blink = blink return AnySequence { () -> AnyIterator in var frame = 0 - // The blink schedule's first entry is `end` itself, which paints the settled pose. let settled = blink.entries(from: end, mode: mode).makeIterator() return AnyIterator { let next = first.addingTimeInterval(Double(frame) * Self.frameInterval) @@ -124,20 +98,12 @@ struct BotWorkingSchedule: TimelineSchedule, Equatable { } } -/// A bot's chat turn as its title face reads it (`HermesChatTurnCoordinator.botTurn`): -/// `.unknown` while not connected, so a reconnect inside a turn starts no new beat. enum BotTurnState { case unknown, idle, running, needsAttention, interrupted } -/// When a bot's chat title face starts a working beat. A beat starts only when the turn -/// enters work after being seen not working (a new prompt, an answered approval) or -/// after the chat opened or came back to the foreground. A same-turn reconnect passes -/// through `.unknown`; that and an arriving approval never start one, so a long turn settles. struct BotWorkingBeat: Equatable { - /// `.distantPast` until the first beat, so a face that never saw work start holds the lean. private(set) var start = Date.distantPast private var armed = true - /// Called when the chat returns to the foreground; the next entry into work starts a beat. mutating func rearm() { armed = true } mutating func observe(_ turn: BotTurnState, at date: Date) { @@ -149,16 +115,12 @@ struct BotWorkingBeat: Equatable { } } -/// One short, self-ending piece of business for the hero face, after Bloub's state -/// catalogue: it starts and ends at rest so it can cut straight in and out of the -/// blink schedule. `pose(at:)` takes progress 0…1 and uses ease-outs, never springs. enum BotFaceBit: CaseIterable, Equatable, Sendable { case glanceLeft, glanceRight, glanceDown, doubleBlink, wobble, hop, spin var duration: Double { switch self { case .glanceLeft, .glanceRight: return 0.9 - // Long enough to cover a burst of typing; repeated cues never restart it. case .glanceDown: return 1.6 case .doubleBlink: return 0.5 case .wobble: return 0.7 @@ -168,10 +130,8 @@ enum BotFaceBit: CaseIterable, Equatable, Sendable { } func pose(at progress: Double) -> BotFacePose { - // The edges are exactly rest, so float noise never leaves a face a hair off. guard progress > 0, progress < 1 else { return .rest } let p = progress - // Out for the first third, hold, back over the last third. let hold = p < 0.3 ? Self.easeOut(p / 0.3) : p > 0.7 ? 1 - Self.easeOut((p - 0.7) / 0.3) : 1 switch self { case .glanceLeft: return BotFacePose(gazeX: -0.07 * hold) @@ -195,9 +155,6 @@ enum BotFaceBit: CaseIterable, Equatable, Sendable { private static func easeOut(_ t: Double) -> Double { 1 - pow(1 - t, 3) } } -/// When the hero face does something on its own: every 4 to 9 seconds, seeded by -/// the bot's name so two faces never move in step, one bit from the repertoire. -/// A spin is rare: it lands at most every tenth slot, so at least 40 seconds apart. struct BotPlayfulSchedule: Equatable { let seed: UInt64 @@ -205,7 +162,6 @@ struct BotPlayfulSchedule: Equatable { self.seed = seed.utf8.reduce(UInt64(1_469_598_103_934_665_603)) { ($0 ^ UInt64($1)) &* 1_099_511_628_211 } } - /// The wait before slot `index` and what plays there. func entry(_ index: Int) -> (delay: Double, bit: BotFaceBit) { var state = seed ^ (UInt64(index) &* 0x9E37_79B9_7F4A_7C15) state ^= state >> 30; state &*= 0xBF58_476D_1CE4_E5B9 @@ -218,22 +174,17 @@ struct BotPlayfulSchedule: Equatable { } } -/// A screen's request for one bit, such as a hop when a shape is picked. A new -/// identity replays the same bit once the previous run has finished. struct BotFaceCue: Equatable { let id = UUID() let bit: BotFaceBit init(_ bit: BotFaceBit) { self.bit = bit } } -/// A drawn face that moves per `motion`. The still and Reduce Motion paths render a -/// plain `BotAvatarMarkView` with no timeline at all. struct BotAnimatedFaceView: View { let name: String let appearance: BotProfileAppearance let size: CGFloat var motion: BotFaceMotion = .idle - /// Extra gaze, as a fraction of the mark size, layered onto the motion's pose. var gaze = CGSize.zero @Environment(\.accessibilityReduceMotion) private var reduceMotion @@ -263,14 +214,6 @@ struct BotAnimatedFaceView: View { } } -/// The hero face on the create and edit screens, after Bloub: it blinks on its own, -/// its eyes follow a finger dragged over it, a tap makes it squish and pull a -/// surprised face for a moment, and every few seconds it plays one short bit -/// (a glance, a double blink, a wobble, a hop, rarely a spin). The screen can cue -/// a bit for what the user just did. A bit runs its own short timeline and then -/// hands back to the blink schedule, so nothing repaints while the face is left -/// alone. Reduce Motion keeps the eyes still, plays no bits and drops the squish, -/// but still answers a tap with the expression. struct BotInteractiveFaceView: View { let name: String let appearance: BotProfileAppearance @@ -281,7 +224,6 @@ struct BotInteractiveFaceView: View { @State private var playing: (bit: BotFaceBit, start: Date)? @Environment(\.accessibilityReduceMotion) private var reduceMotion - /// How far the eyes travel, as a fraction of the mark, and the reaction's length. private static let reach = 0.07 private static let reactionDuration: Duration = .milliseconds(650) @@ -316,12 +258,9 @@ struct BotInteractiveFaceView: View { .animation(reduceMotion ? nil : .spring(duration: 0.3, bounce: 0.4), value: reaction > 0) .accessibilityHidden(true) .onChange(of: cue?.id) { if let cue { play(cue.bit) } } - // Reduce Motion is part of the identity so flipping it restarts, or stops, the idle loop. .task(id: "\(name)|\(reduceMotion)") { await playIdleBits() } } - /// Runs the seeded idle repertoire while the face is on screen. A slot whose - /// moment finds the face busy (a cue, a tap) is simply skipped. private func playIdleBits() async { guard !reduceMotion else { return } let schedule = BotPlayfulSchedule(seed: name) @@ -334,12 +273,8 @@ struct BotInteractiveFaceView: View { } } - /// A cue for the bit already on screen is ignored, so fast typing looks down - /// once for the whole burst instead of jittering with every letter. - /// The bit's pose at `date`, with a finger on the face still steering the eyes. private func bitPose(_ playing: (bit: BotFaceBit, start: Date), at date: Date) -> BotFacePose { var pose = playing.bit.pose(at: date.timeIntervalSince(playing.start) / playing.bit.duration) - // A glance plus a drag stays within the eyes' travel, so they never leave the body. pose.gazeX = max(-Self.reach, min(Self.reach, pose.gazeX + gaze.width)) pose.gazeY = max(-Self.reach, min(Self.reach, pose.gazeY + gaze.height)) return pose diff --git a/HermesMobile/Features/Bots/BotFilePathSearch.swift b/HermesMobile/Features/Bots/BotFilePathSearch.swift index 5563bbf35..7374d08b4 100644 --- a/HermesMobile/Features/Bots/BotFilePathSearch.swift +++ b/HermesMobile/Features/Bots/BotFilePathSearch.swift @@ -1,53 +1,24 @@ import Foundation -/// The file and folder rows the Bot composer's `@` panel draws, read from the -/// direct connection's `complete.path`. -/// -/// The host completes against the live session's working directory and does its -/// own ranking and capping, so the phone only translates rows and drops what a -/// `@path` reference cannot name. Template directives (`@diff`, `@url:…`) are -/// not files, and a path with whitespace or `..` could never read back as a -/// reference. enum BotFilePathSearch { - /// Which question one `complete.path` call asks the host. enum Word { - /// The `@` panel's search (`panelWord`): a name finds matches in any folder. case panel - /// One folder's entries starting with a name (`listingWord`), which is what - /// confirms a known `@path`. case listing } - /// The `@` panel's word for a query (#1388). A name of two or more characters - /// asks the host's fuzzy search over the whole working folder as `@file:name`, - /// which ranks files and folders alike and skips Profile mentions. A path with - /// `/`, a single character and the bare trigger keep the one-folder listing, so - /// `@src/` lists `src` and `@s` still offers the root's folders. static func panelWord(for query: String) -> String { guard searchesEveryFolder(query) else { return listingWord(for: query) } return "@file:" + query } - /// Whether `panelWord` asks the whole-folder search for `query`: a name of two or more - /// characters with no `/` or line break; spaces are fine. Files' workspace search (#1389) - /// asks the host only then. static func searchesEveryFolder(_ query: String) -> Bool { !query.contains("/") && !query.contains(where: \.isNewline) && query.trimmingCharacters(in: .whitespaces).count >= 2 } - /// A one-folder listing's word: the folder the query names, filtered to entries - /// starting with its last component. The host answers only a non-empty word, and - /// `.` is its own spelling for the root. static func listingWord(for query: String) -> String { query.isEmpty ? "." : query } - /// The panel rows from one `complete.path` reply. - /// - /// A listing word answers plain relative paths; the panel's fuzzy word answers - /// the same root-relative paths spelled `@file:` and `@folder:`. Directories end - /// in `/` and carry `meta: "dir"`. `browsing` keeps a path with whitespace, which - /// Files opens rather than inserts as a reference (#1389). static func matches(from reply: BotJSON, browsing: Bool = false) -> [ComposerFilePathSearch.Match] { guard let items = reply["items"].list else { return [] } diff --git a/HermesMobile/Features/Bots/BotGeneratedAvatar.swift b/HermesMobile/Features/Bots/BotGeneratedAvatar.swift index 6d79a91a1..7107b2abd 100644 --- a/HermesMobile/Features/Bots/BotGeneratedAvatar.swift +++ b/HermesMobile/Features/Bots/BotGeneratedAvatar.swift @@ -1,14 +1,9 @@ import Foundation import SwiftUI -/// An avatar the host's model drew from a description: one path, its eyes and a short name, -/// stored inline under a Hermex-owned key in `ui_meta["hermes-bots"]`, the way `expression` is. -/// Desktop and older Hermex builds ignore the key and keep drawing the stored `shape`. struct BotGeneratedAvatar: Equatable, Sendable { static let lookKey = "hermexAvatar" - /// How much of a host's plain-text answer the sheet shows. private static let maxSaidCharacters = 400 - /// The trailing line of the host's failure copy (`agent/turn_failure_copy.py`). private static let hostFailureMarkers = ["\n\nProvider said:", "\n\nDetails:"] var name: String @@ -19,7 +14,6 @@ struct BotGeneratedAvatar: Equatable, Sendable { self.name = name; self.path = path; self.eyes = eyes } - /// Reads a stored value, or a model's answer before `validate` checks it. Unknown fields are ignored. init?(json: BotJSON) { let eyes = json["eyes"] guard let path = json["path"].text, let x = eyes["x"].number, let y = eyes["y"].number, @@ -34,10 +28,7 @@ struct BotGeneratedAvatar: Equatable, Sendable { ]) } - /// Reads a model's answer, which may be wrapped in prose or a code fence. Returns the avatar, the - /// problems in words a repair prompt can act on, or what the host said if it sent no JSON. static func read(answer: String) -> Result { - // A failed call comes back as ordinary text, and its provider detail can hold JSON of its own. let isHostFailure = hostFailureMarkers.contains { answer.contains($0) } guard !isHostFailure, let open = answer.firstIndex(of: "{"), let close = answer.lastIndex(of: "}"), open < close else { let said = answer.trimmingCharacters(in: .whitespacesAndNewlines) @@ -57,15 +48,11 @@ struct BotGeneratedAvatar: Equatable, Sendable { return copy } - /// Whether the eye numbers are sane. A damaged or newer stored value that fails this draws - /// the bot's shape instead, and a save still writes the value back unchanged. var hasDrawableEyes: Bool { (0.6...1.8).contains(eyes.scale) && eyes.spacing >= 7 * eyes.scale && eyes.spacing <= 40 && (0...100).contains(eyes.x) && (0...100).contains(eyes.y) } - /// What stops this avatar drawing properly. The path must parse and fill most of the box's - /// safe area, and both neutral eyes must sit fully on the body. var problems: [String] { guard let body = BotAvatarPathData.path(path) else { return ["path must use only absolute M, L, Q, C and Z commands, at most \(BotAvatarPathData.maxSegments) segments"] @@ -89,8 +76,6 @@ struct BotGeneratedAvatar: Equatable, Sendable { } } -/// Stored avatar paths, parsed once. The grammar is deliberately small: absolute M, L, Q, C and Z, -/// which every ready-made path uses and the design prompt asks the model for. enum BotAvatarPathData { static let maxCharacters = 6000 static let maxSegments = 400 @@ -102,7 +87,6 @@ enum BotAvatarPathData { return cache }() - /// The path for `data`, or nil when it breaks the grammar. Safe from any thread. static func path(_ data: String) -> Path? { let key = data as NSString if let hit = cache.object(forKey: key) { return hit.path } diff --git a/HermesMobile/Features/Bots/BotGroupRoom.swift b/HermesMobile/Features/Bots/BotGroupRoom.swift index 496275721..a95230956 100644 --- a/HermesMobile/Features/Bots/BotGroupRoom.swift +++ b/HermesMobile/Features/Bots/BotGroupRoom.swift @@ -1,6 +1,5 @@ import Foundation -/// Room identity never borrows a display name or a hidden member session ID. struct BotRoomKey: Hashable, Identifiable { let server: URL let connectionID: UUID @@ -13,8 +12,6 @@ struct BotRoomCapabilities: Equatable { let authority: String? let pageLimit: Int let methods: Set - /// The Profiles a canonical host's `groups.create` will seat for this connection (#1605); nil - /// from a dashboard, which names none and seats whoever its roster lists. let seatableProfiles: Set? init(_ value: BotJSON) { let methods = Set(value["methods"].list?.compactMap(\.text) ?? []) @@ -97,8 +94,6 @@ struct BotRoomEvent: Identifiable, Equatable { } var isMessage: Bool { kind == "message.user" || kind == "message.member" } - /// True once the user or a member has said something. System rows such as - /// a rename don't count, so a room renamed before its first message is new. static func hasConversation(in events: some Sequence) -> Bool { events.contains { ["message.user", "message.member"].contains($0.kind) } } @@ -123,7 +118,6 @@ struct BotRoomEvent: Identifiable, Equatable { } } -/// A loaded projection, not a claim about the server's complete thread history. struct BotRoomThread: Identifiable, Equatable { let id: String let events: [BotRoomEvent] @@ -146,16 +140,12 @@ struct BotRoomThread: Identifiable, Equatable { } } -/// Pure replay seam. Invisible events still advance the cursor and occupy their -/// sequence number. An unchanged page leaves the visible transcript untouched. struct BotRoomLog { private(set) var cursor = 0 private(set) var earlierBoundary = 0 private(set) var events: [BotRoomEvent] = [] private var seen = Set() static func windowStart(before sequence: Int) -> Int { max(0, sequence - 200) } - /// Preserve system rows and the replay cursor without keeping an unbounded - /// seen-set or the entire paged history alive after leaving the room. func recentWindow() -> Self { var result = self result.events = Array(events.suffix(500)) @@ -169,8 +159,6 @@ struct BotRoomLog { self = Self(); cursor = Self.windowStart(before: latest); earlierBoundary = cursor } mutating func loadedEarlier(from start: Int) { earlierBoundary = start } - /// An acknowledgment can arrive ahead of unread log events. Insert its bubble - /// without skipping those events on the next log read. mutating func acknowledge(_ event: BotJSON) { let previous = cursor apply(.object(["events": .array([event])])) @@ -184,8 +172,6 @@ struct BotRoomLog { } } -/// Room identifier, text and name rules shared by the room screens and -/// `HermesCall`'s room admission. enum BotRoomRPC { static func validID(_ id: String) -> Bool { id.range(of: "\\A[A-Za-z0-9][A-Za-z0-9._:-]{0,127}\\z", options: .regularExpression) != nil @@ -205,7 +191,6 @@ struct BotRoomFailure: Error, LocalizedError { var errorDescription: String? { if expired { return String(localized: "This room’s history is no longer available.") } if code == 4123 { return String(localized: "Restart the Hermes gateway on your Mac, then reconnect.") } - // A canonical host refused a retry or discard because the task moved on (#1605). if reason == "stale_generation" { return String(localized: "This chat changed on the server. Reopen it and try again.") } return BotFailure.rejected(code).localizedDescription } diff --git a/HermesMobile/Features/Bots/BotHistoryCache.swift b/HermesMobile/Features/Bots/BotHistoryCache.swift index efbce7b4c..4f03170d0 100644 --- a/HermesMobile/Features/Bots/BotHistoryCache.swift +++ b/HermesMobile/Features/Bots/BotHistoryCache.swift @@ -1,9 +1,6 @@ import CryptoKit import Foundation -/// A bounded, disposable index of the room history this phone has loaded, which room -/// search reads; a bot's chat is the host's to search (#1146). All disk access and text -/// matching run on the actor, away from SwiftUI rendering. actor BotHistoryCache { nonisolated let recent = BotRecentTranscripts() struct Scope: Codable, Hashable, Sendable { @@ -25,13 +22,10 @@ actor BotHistoryCache { var sender: String? = nil var memberID: String? = nil var timestamp: Double? = nil - /// Optional server display hint (e.g. `"steer"`). Absent on snapshots - /// saved before steering hints existed; decodes as nil. var displayKind: String? = nil var threadID: String? = nil var eventID: String? = nil - /// Rebuild only the message projection, never cached commands or runtime state. var roomEvent: BotJSON? { guard let seq else { return nil } return .object(["seq": .number(Double(seq)), "kind": .string(role), @@ -45,7 +39,6 @@ actor BotHistoryCache { struct Snapshot: Codable, Equatable, Identifiable, Sendable { let id: UUID let scope: Scope - /// The room's name; the key predates rooms being the only snapshots. let profileName: String? let savedAt: Date let messages: [Message] @@ -53,8 +46,6 @@ actor BotHistoryCache { var cursor: Int? = nil var earlierBoundary: Int? = nil - /// Minimal identity for opening a saved room while its live list is unavailable. - /// Runtime authority, members and permissions always come from groups.state. var cachedRoom: BotGroupRoom? { guard let roomID else { return nil } return BotGroupRoom(.object(["room_id": .string(roomID), @@ -80,7 +71,6 @@ actor BotHistoryCache { static let maximumBytes = 8 * 1024 * 1024 static let maximumHits = 100 static let lifetime: TimeInterval = 30 * 24 * 60 * 60 - /// Longest a cursor-only room change stays unsaved while other writes are absent. static let cursorOnlySaveInterval: TimeInterval = 10 * 60 private let directory: URL? private var loaded = false @@ -95,10 +85,8 @@ actor BotHistoryCache { private var removed: Set = [] private var clearedAt: [String: Date] = [:] - /// A nil directory is an isolated memory cache, used by fixtures. init(directory: URL? = nil) { self.directory = directory } - /// Matches in `roomIDs`' saved history, newest first; nil searches every room. func search(_ query: String, scope: Scope, roomIDs: Set?, now: Date = Date()) throws -> [Hit] { try Task.checkCancellation() let query = query.trimmingCharacters(in: .whitespacesAndNewlines) @@ -125,8 +113,6 @@ actor BotHistoryCache { return hits } - /// Append overlapping replay pages by sequence. Coverage includes invisible events, - /// while the disk projection contains only bounded user/member message text. func appendRoom(key: BotRoomKey, room: BotGroupRoom, page: BotJSON, since: Int, receivedAt: Date = Date()) throws { try Task.checkCancellation() @@ -137,7 +123,6 @@ actor BotHistoryCache { let cursor = page["cursor"].integer, cursor >= since else { return } try load() let previous = snapshots.first { $0.scope == scope && $0.roomID == key.roomID } - // A gap cannot become a saved cursor: retain only the newly read window. let overlaps = previous.map { since <= ($0.cursor ?? 0) && cursor >= ($0.earlierBoundary ?? 0) } ?? false var rows = overlaps ? previous?.messages ?? [] : [] var seen = Set(rows.compactMap(\.seq)) @@ -165,10 +150,6 @@ actor BotHistoryCache { if cursorOnly, previous?.cursor == next.cursor { return } snapshots.removeAll { $0.scope == scope && $0.roomID == key.roomID } snapshots.append(next) - // Invisible events move only the cursor: keep it in memory and let the next real - // write persist it. After a kill, reopening re-reads from the older saved cursor - // and the overlap merge above absorbs the repeated pages. A periodic save keeps a - // long-running room's saved `savedAt` fresh so it cannot expire on relaunch. guard !cursorOnly || receivedAt.timeIntervalSince(lastRoomWriteAt) >= Self.cursorOnlySaveInterval else { return } try persist(prune(now: receivedAt)) lastRoomWriteAt = receivedAt @@ -184,7 +165,6 @@ actor BotHistoryCache { return snapshots.first { $0.scope == scope && $0.roomID == key.roomID } } - /// Room IDs are permanently retired by expiry/disband. Revoke late page writes too. func removeRoom(_ key: BotRoomKey) throws { recent.remove { $0 == .init(key) } let scope = Scope(server: key.server, connectionID: key.connectionID) @@ -194,7 +174,6 @@ actor BotHistoryCache { try persist() } - /// Call only with a complete authoritative room list, never a partial page. func retainRooms(_ ids: Set, scope: Scope) throws { recent.remove { $0.scope == scope && !ids.contains($0.roomID) } try load() @@ -208,8 +187,6 @@ actor BotHistoryCache { try persist() } - /// Removal revokes queued writes from the old connection. Cache clearing - /// allows later snapshots, but rejects writes captured before the clear. func remove(server: URL, connectionID: UUID? = nil, now: Date = Date()) throws { let key = Scope.key(server) recent.remove { $0.scope.serverKey == key && (connectionID == nil || $0.scope.connectionID == connectionID) } @@ -238,23 +215,17 @@ actor BotHistoryCache { let size = try file.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0 guard size <= Self.maximumBytes * 2 else { return } snapshots = try JSONDecoder().decode([Snapshot].self, from: Data(contentsOf: file)) - // Bot Chat's snapshots (no room) predate #1148; nothing reads them any more. let previousCount = snapshots.count snapshots.removeAll { $0.roomID == nil } - // The newest saved timestamp dates the last write, so a relaunch does not rewrite on its first cursor-only poll. lastRoomWriteAt = snapshots.map(\.savedAt).max() ?? .distantPast prune(now: Date()) persistPruning(previousCount: previousCount) } - /// Drops expired snapshots, then the oldest ones until the index fits the count and - /// byte budget. Returns the encoded index so `persist` does not encode it again. @discardableResult private func prune(now: Date) -> Data? { snapshots.removeAll { now.timeIntervalSince($0.savedAt) >= Self.lifetime } if snapshots.count > 100 { snapshots.removeFirst(snapshots.count - 100) } - // Use encoded bytes for the actual disk budget, including JSON escaping. - // Under budget this is the only encode; each eviction re-encodes once. while !snapshots.isEmpty { if let data = try? JSONEncoder().encode(snapshots), data.count <= Self.maximumBytes { return data } snapshots.removeFirst() @@ -262,8 +233,6 @@ actor BotHistoryCache { return nil } - /// Expiry cleanup must not prevent reading fresh messages when storage is - /// temporarily unwritable. Keep it pending so the next search retries it. private func persistPruning(previousCount: Int) { needsPrunePersistence = needsPrunePersistence || snapshots.count != previousCount guard needsPrunePersistence else { return } @@ -271,12 +240,9 @@ actor BotHistoryCache { try persist() needsPrunePersistence = false } catch { - // Fresh in-memory results remain usable; retry on the next access. } } - /// Writes the index atomically. Pass `encoded` only when it is `prune`'s - /// result for the current `snapshots`. private func persist(_ encoded: Data? = nil) throws { guard let directory else { return } try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) @@ -285,11 +251,6 @@ actor BotHistoryCache { } } -/// The last `profiles.list` rows each Bot connection read, so the inbox paints its roster -/// while it connects (#1403). One file per server digest and connection UUID under Caches, -/// main app only: rows, never live status, rooms or photos. A missing, oversized or -/// unreadable file is a miss, never a failure. Removal revokes every write whose roster -/// was read before it, so a late save cannot bring back a signed-out connection's rows. actor BotRosterCache { typealias Scope = BotHistoryCache.Scope @@ -298,11 +259,8 @@ actor BotRosterCache { static let maximumRows = 200 static let maximumBytes = 2 * 1024 * 1024 private let directory: URL - /// When each scope's saved roster was read, so a slower, older save never replaces a newer one. private var savedReadAt: [Scope: ContinuousClock.Instant] = [:] - /// Removals by server digest, and by `-` for one connection. private var removedAt: [String: ContinuousClock.Instant] = [:] - /// Runs as each load starts. Fixtures change the saved connection here, while an open waits on the load. private let willLoad: @Sendable () async -> Void init(directory: URL, willLoad: @escaping @Sendable () async -> Void = {}) { @@ -319,8 +277,6 @@ actor BotRosterCache { return rows } - /// Replaces `scope`'s rows with a complete roster read at `readAt`. An empty roster, or - /// one over the bounds, leaves no file, so the next open shows no stale bots. func save(_ rows: [BotJSON], scope: Scope, readAt: ContinuousClock.Instant) { let revoked = [removedAt[scope.serverKey], removedAt[name(scope)], savedReadAt[scope]].compactMap { $0 } guard revoked.allSatisfy({ $0 < readAt }) else { return } @@ -334,7 +290,6 @@ actor BotRosterCache { try? data.write(to: file(scope), options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) } - /// Deletes `server`'s rosters, or only `connectionID`'s, and revokes saves of rosters read before now. func remove(server: URL, connectionID: UUID? = nil, now: ContinuousClock.Instant = .now) { let key = Scope.key(server) let prefix = connectionID.map { name(.init(server: server, connectionID: $0)) } ?? key @@ -349,11 +304,6 @@ actor BotRosterCache { private func file(_ scope: Scope) -> URL { directory.appendingPathComponent(name(scope) + ".json") } } -/// Each recent room's rendered window, separate from the lossy on-disk search index, so -/// reopening a room draws its last window before the first poll. The lock covers every -/// access because screens read synchronously before their first frame, while the history -/// actor invalidates entries. Logs are value types: no clients, callbacks, approval state, -/// or credentials cross this boundary. final class BotRecentTranscripts: @unchecked Sendable { struct Key: Hashable { let scope: BotHistoryCache.Scope @@ -386,8 +336,6 @@ final class BotRecentTranscripts: @unchecked Sendable { } } - /// Claim writes when a screen starts recovery, not during SwiftUI construction. - /// A later owner or removal makes every older writer inert. func begin(_ key: Key) -> UUID { lock.withLock { let owner = UUID(); access &+= 1 diff --git a/HermesMobile/Features/Bots/BotInbox.swift b/HermesMobile/Features/Bots/BotInbox.swift index 77e6b6eb1..0703b1671 100644 --- a/HermesMobile/Features/Bots/BotInbox.swift +++ b/HermesMobile/Features/Bots/BotInbox.swift @@ -2,17 +2,9 @@ import Observation import SwiftData import UIKit -/// The Bots inbox for one configured server: the roster, Desktop's pin, hidden and -/// section organization, each bot's live turn state, device-local unread marks and -/// section order, and one live subscription that lasts while the inbox is visible. -/// `open()` owns the transport and `close()` ends it; every late reply is dropped by -/// the wire identity check, so a replaced or closed connection never writes into the screen. @MainActor @Observable final class BotInbox { enum Link: Equatable { case idle, connecting, live, disconnected } - /// The roster split the way Desktop draws it: pinned first, the rest in server - /// order, hidden bots apart and only when revealed or when a search names them. - /// The inbox list regroups these into `sections`; search reads them flat. struct Rows: Equatable { var pinned: [BotProfile] = [] var others: [BotProfile] = [] @@ -38,23 +30,17 @@ import UIKit } } - /// One of Desktop's named sections, as this roster names it. struct SectionName: Identifiable, Equatable { let id: String let name: String } - /// One block of the list under the tiles: a named section, or the final - /// unfiled block (`name == nil`) holding unfiled bots and every room. struct ChatSection: Identifiable { let id: String let name: String? let chats: [ChatRow] } - /// Everything except the pinned tiles, as sections in `sectionNames` order with - /// the unfiled block last. Each block is in `byAttention` order; an empty one is left out. - /// With no named sections this is one unfiled block, the flat list as before. var sections: [ChatSection] { let rows = rows(matching: "") var filed: [String: [ChatRow]] = [:] @@ -63,9 +49,6 @@ import UIKit if let id = profile.sectionID, profile.sectionName != nil { filed[id, default: []].append(.bot(profile)) } else { unfiled.append(.bot(profile)) } } - // Rooms are never sectioned: Desktop keeps a room's section on the machine - // that filed it. A hidden room lives in the revealed list whether or not it - // is also pinned, exactly as a hidden bot does, so it can always be unhidden. unfiled += visibleRooms.filter { isRoomHidden($0) ? showsHidden : !isRoomPinned($0) }.map(ChatRow.room) var blocks = sectionNames.compactMap { section in filed[section.id].map { ChatSection(id: "section:" + section.id, name: section.name, chats: byAttention($0)) } @@ -74,11 +57,6 @@ import UIKit return blocks } - /// Every named section on the roster, pinned and hidden members included, in - /// this phone's order: the ids the user placed first, the rest A–Z. A section - /// takes the name most of its members carry, ties going to the first member in - /// roster order, so a rename still being stamped across members reads calmly. - /// Also the "Move to Section" destinations, so a pinned-only section is offered. var sectionNames: [SectionName] { var tallies: [String: [(name: String, count: Int)]] = [:] var ids: [String] = [] @@ -90,23 +68,17 @@ import UIKit } let named = ids.map { id in let names = tallies[id]! - // Strictly greater keeps the earliest name on a tie. let winner = names.dropFirst().reduce(names[0]) { $1.count > $0.count ? $1 : $0 } return SectionName(id: id, name: winner.name) } return Self.ordered(named, placed: sectionOrder) } - /// The sections "Reorder Sections…" offers, in `sectionNames` order: only those - /// the list can head. A section of only pinned bots lives in the tiles, so it - /// has no header to move; a hidden-only one stays, since Show hidden draws it. var reorderableSectionNames: [SectionName] { let listed = Set(profiles.compactMap { $0.sectionName != nil && (!$0.pinned || $0.hidden) ? $0.sectionID : nil }) return sectionNames.filter { listed.contains($0.id) } } - /// Placed ids keep their position; unplaced sections follow A–Z by name (ties - /// by id). Placed ids the roster no longer has are ignored. static func ordered(_ sections: [SectionName], placed: [String]) -> [SectionName] { let byID = Dictionary(sections.map { ($0.id, $0) }) { first, _ in first } var used = Set() @@ -121,8 +93,6 @@ import UIKit return front + rest } - /// The tiles above the timeline: Desktop's pinned bots, then rooms pinned on - /// this phone, each group in `byAttention` order. var pinned: [ChatRow] { byAttention(rows(matching: "").pinned.map(ChatRow.bot)) + byAttention(visibleRooms.filter { isRoomPinned($0) && !isRoomHidden($0) }.map(ChatRow.room)) @@ -130,10 +100,6 @@ import UIKit private var visibleRooms: [BotGroupRoom] { roomCapabilities.enabled ? rooms : [] } - /// The one order inside every group (each tile group and each section): waiting, - /// then working, then unread, then newest, undated last and ties by id. Rooms - /// have no live status or unread mark, so they rank with idle bots. Only rows - /// inside a group move; `ChatRow.id` stays stable so a move never rebuilds a row. private func byAttention(_ rows: [ChatRow]) -> [ChatRow] { func rank(_ row: ChatRow) -> Int { guard case .bot(let profile) = row else { return 3 } @@ -160,78 +126,39 @@ import UIKit private(set) var rooms: [BotGroupRoom] = [] private var hasRoomList = false private(set) var roomCapabilities = BotRoomCapabilities(.null) - /// Rooms pinned or hidden on this phone. The host has no such fields for - /// rooms, so unlike a bot's pin these never reach Desktop. private(set) var roomFlags = BotRoomOrganizeStore.Flags() - /// Section ids in the order the user placed them on this phone; empty means A–Z. - /// Desktop keeps its own order locally and never sees this one. private(set) var sectionOrder: [String] = [] private(set) var avatars: [String: UIImage] = [:] private(set) var link = Link.idle private(set) var errorMessage: String? - /// True after the host refused the saved username or password (`.rejected(401)`). - /// The inbox offers the sign-in form instead of Reconnect, and `open()` never sends - /// that record again until it changes or the form saves a sign-in (#884). private(set) var needsSignIn = false - /// True after the address turned out to be a gateway's own listener (`.gatewayListener`), - /// which no reconnect fixes: the inbox offers a way to a new address instead (#1598). private(set) var needsAddress = false - /// What to check once an empty inbox has failed to reach the host - /// `routeFailuresBeforeAdvice` times in a row. The quiet retry goes on behind it, - /// and `open()` leaves it alone so it holds steady between attempts. private(set) var routeAdvice: String? - /// Outcome of the last pin, hide or section write when it did not apply. private(set) var notice: String? - /// Profiles with a look write in flight; their actions stay inert. private(set) var editing: Set = [] - /// Deletes whose reply was lost. The next roster read settles them: a bot that - /// is gone gets its local state purged then, one that is still there is kept. private var uncertainDeletions: Set = [] - /// Session-only reveal of hidden bots, as in Desktop. Never persisted. var showsHidden = false - /// The open bot or room. It lives here, not in the inbox view, so the Hermes home's - /// chat survives what rebuilds that view: a size-class change or the `[Bots | Sessions]` switch. var selection = BotInboxSelection() - /// Device-local watermarks for the current connection: the canonical - /// `last_active` the user last saw for each Profile. Never leaves the phone. private(set) var seen: [String: Double] = [:] - /// Live turn state per Profile from the newest `session.active_list` read on this - /// connection. A lost socket or a failed read keeps them as the last known ones - /// (`liveStatusesAreStale`); a refusal, a closed inbox or another connection empties - /// stale ones, so a row never claims work as current that nobody can vouch for. private(set) var liveStatuses: [String: BotLiveStatus] = [:] - /// True while `liveStatuses` are only the last ones known (#1374): kept through a lost - /// socket or a failed status read, until a current status reply replaces them. private(set) var liveStatusesAreStale = false - /// True from a lost socket that kept the roster on screen until a roster read on a new - /// socket succeeds (#1374). A refusal the user has to act on, a closed inbox or another - /// connection ends it instead. private(set) var isReconnecting = false - /// What the home's status line speaks for (#1374): a roster that no message already - /// explains, and whether the socket is coming back. var homeConnection: HomeConnectionStatus.Facts { HomeConnectionStatus.Facts(keepsRows: !profiles.isEmpty && errorMessage == nil && routeAdvice == nil, isReconnecting: isReconnecting) } private var wire: (any BotTransport)? - /// The quiet reconnect after a lost socket, on backoff while online and held while offline. private let reconnect: BotReconnectSchedule private let isNetworkAvailable: @MainActor () -> Bool - /// Bumped by every `teardown()`, which each `open()` starts with, so an open that - /// awaited the roster cache meanwhile stops before painting or connecting. private var openSerial = 0 private var routeFailures = 0 private static let routeFailuresBeforeAdvice = 3 private var reloadTask: Task? private var reloadWanted = false private var reloadSerial = 0 - /// False once the host answered `session.active_list` with "method not found"; - /// statuses stay hidden until the next socket. private var readsLiveStatus = true private var statusSerial = 0 - /// True after a status read failed while a bot was busy, so re-reads go on until - /// one succeeds instead of leaving that turn unmarked until the next event. private var retriesStatusRead = false private var statusPollTask: Task? private var returnedFrom: String? @@ -241,24 +168,13 @@ import UIKit private let sectionOrderStore: BotSectionOrderStore private let avatarStore: BotAvatarStore private let historyCache: BotHistoryCache - /// The last roster each connection read, painted while the next open connects (#1403). private let rosterCache: BotRosterCache - /// Where each roster read leaves the Profiles' names for the Shortcuts picker (#1180). private let profileNames: HermesProfileNameCache - /// Where each roster read leaves the bots for the Bot widget's picker (#1643). private let widgets: BotWidgetPublisher private let makeWire: @MainActor (BotConnection) -> any BotTransport - /// Drops this phone's drafts for one deleted bot. private let purgeLocalState: @MainActor (UUID, String) async -> Void - /// The offline cache, from the inbox's screen: a deleted bot's Bot Chat transcript leaves - /// it too (#1144). @ObservationIgnored var offlineCache: ModelContext? - /// Minimum gap between event-driven roster reads; the host already floors - /// `sessions.changed` at two seconds, this guards against a chattier one. private let reloadSpacing: Duration - /// Gap between status-only re-reads while some bot is busy. `sessions.changed` - /// can miss a turn's end (post-turn work writes nothing), so the inbox re-reads - /// on its own while it is open, connected, and a row shows Working or Waiting. private let statusPollInterval: Duration init(server: URL, store: BotConnectionStore? = nil, unread: BotUnreadStore = BotUnreadStore(), @@ -284,8 +200,6 @@ import UIKit self.purgeLocalState = purgeLocalState ?? { connectionID, profile in await ChatDraftStore.shared.discardBotDrafts(server: server, connectionID: connectionID, profile: profile) } - // Known before the first frame, so a saved connection draws the loading - // skeleton rather than flashing "Connect to Hermes" until `open()` runs. connection = try? self.store.load(server: server) } @@ -298,23 +212,13 @@ import UIKit hidden: showsHidden || !search.isEmpty ? matching.filter(\.hidden) : []) } - /// A bot whose Bot Chat matched a message search on the host (#1146). struct BotChatHit: Identifiable, Equatable { let profileID: String - /// The host's FTS snippet, with `>>>` and `<<<` around each match; nil for an id match. let snippet: String? - /// The matched message is the user's rather than the bot's; nil for an id match, which - /// names no message. let isFromUser: Bool? var id: String { profileID } } - /// Searches each roster bot's Bot Chat on the host for `query` (#1146), Profile by Profile, as - /// the Sessions list does (`HermesREST.sessionSearch`); a Profile's other sessions, its rooms' - /// and a replaced Bot Chat's included, are not hits, since a hit opens the bot's current chat. The host can neither filter for the Bot Chat nor page, so each - /// search asks for its maximum; a Bot Chat behind that many other matches is not found. Empty - /// while the inbox is not live. A reply that lands after the inbox closed or reconnected - /// throws `BotFailure.stale`. func searchBotChats(_ query: String) async throws -> [BotChatHit] { guard link == .live, let client = wire, !query.isEmpty else { return [] } var hits: [BotChatHit] = [] @@ -331,32 +235,22 @@ import UIKit return hits } - /// True when the canonical chat moved past what this device last showed. - /// A row without a watermark reads as seen: the first roster load seeds it. func isUnread(_ profile: BotProfile) -> Bool { guard let lastActive = profile.lastActive?.timeIntervalSince1970, let mark = seen[profile.id] else { return false } return lastActive > mark } - /// The user is entering this bot's chat: the row's activity is now seen. func markSeen(_ profile: BotProfile) { guard let lastActive = profile.lastActive?.timeIntervalSince1970, seen[profile.id] != lastActive else { return } seen[profile.id] = lastActive persistSeen() } - /// The user came back from this bot's chat. Whatever the next roster read - /// shows was on screen while they were there, so it is marked seen once and - /// normal tracking resumes after that. func noteReturn(from profile: BotProfile) { markSeen(profile) returnedFrom = profile.id } - /// Connects, reads the roster and avatars, and keeps the socket for live - /// `sessions.changed` reloads. Also the pull-to-refresh, Reconnect and foreground - /// path, so a rejected password stays unsent here until the saved record changes - /// or `signInSaved()` runs. func open() async { teardown(); hasRoomList = false var client: (any BotTransport)? @@ -368,8 +262,6 @@ import UIKit roomFlags = BotRoomOrganizeStore.Flags(); sectionOrder = []; setLiveStatuses([:]) setReconnecting(false) } - // The form can keep the UUID under a new address; advice for the old host - // and its failure streak do not carry over to the new one. if connection?.id != saved?.id || connection?.address != saved?.address { routeFailures = 0; routeAdvice = nil } @@ -379,16 +271,8 @@ import UIKit if seen.isEmpty { seen = unread.load(connectionID: saved.id) } if roomFlags == BotRoomOrganizeStore.Flags() { roomFlags = roomStore.load(connectionID: saved.id) } if sectionOrder.isEmpty { sectionOrder = sectionOrderStore.load(server: server, connectionID: saved.id) } - // Each resend spends one of the host's ten password logins a minute per client - // IP, which Desktop and the browser may share behind the same tunnel. guard !needsSignIn else { link = .disconnected; return } if profiles.isEmpty { - // The roster this connection last read paints while it connects (#1403). It - // claims nothing live and allows no server edit; the first read replaces it. - // The connection form may save or remove the record during the load without - // closing this inbox, so the record is re-read before painting or connecting. - // Another client of a browser sign-in may rotate its refresh token meanwhile - // (`saveRotatedRefreshToken`); that is still this connection, opened on the new token. let serial = openSerial let cached = await rosterCache.load(.init(server: server, connectionID: saved.id)) guard serial == openSerial, !Task.isCancelled, let fresh = try? store.load(server: server) else { return } @@ -414,30 +298,21 @@ import UIKit } try await opened.connect() guard wire === opened, !Task.isCancelled else { return } - // The host answered, so the route advice no longer holds, even though the - // roster and rooms have yet to load. routeFailures = 0; routeAdvice = nil recordInstallID(opened.serverInstallID, for: saved) guard await reload(opened) else { return } - // The status read runs beside rooms and avatars; nothing above waits for it. let statuses = statusPollTask await refreshRooms(opened) guard wire === opened, !Task.isCancelled else { return } link = .live reconnect.succeeded() await refreshAvatars(opened) - // A pull-to-refresh ends once the fresh statuses are in, too. await statuses?.value } catch { guard !Task.isCancelled else { return } if let client { - // The socket's own disconnect callback may already have dropped this - // client and scheduled the quiet retry; a second report would paint - // the message over it. if wire === client { drop(client, error: error) } } else { - // A saved-connection read can fail before any client exists; that is - // still a visible failure with the Reconnect path, not a stale roster. link = .disconnected; errorMessage = (error as? BotFailure ?? .transport).localizedDescription needsSignIn = error as? BotFailure == .rejected(401) needsAddress = error as? BotFailure == .gatewayListener @@ -446,12 +321,6 @@ import UIKit } } - /// Trust on first use: stores the host's `install_id` on a record that has none, so - /// every later connect can refuse an address that starts reaching another host. The - /// record is re-read rather than taken from `opened`, because the connection form may - /// have saved a new password or name under the same UUID while this inbox connected. - /// The in-memory `connection` gains the id too, because the chats, rooms, creator and - /// editor opened from this inbox build their clients from it. private func recordInstallID(_ live: String?, for opened: BotConnection) { guard let live else { return } if connection?.id == opened.id, connection?.address == opened.address, connection?.installID == nil { @@ -463,15 +332,8 @@ import UIKit try? store.save(fresh, server: server) } - /// The connection form signed in and saved. The next `open()` connects even when the - /// saved record is unchanged, because the fix may have been on the host. func signInSaved() { needsSignIn = false } - /// A chat or room opened from this inbox saw the host refuse `rejected` and is - /// handing off to the sign-in form. The inbox takes the same stop as its own 401, - /// so the `open()` that runs as it reappears sends nothing. A record that signs in - /// differently from the inbox's is ignored; an install id the inbox recorded after - /// the chat opened is not a difference. func noteRejectedSignIn(_ rejected: BotConnection) { guard let connection, rejected.id == connection.id, rejected.address == connection.address, rejected.username == connection.username, rejected.password == connection.password else { return } @@ -481,28 +343,19 @@ import UIKit needsSignIn = true; needsAddress = false } - /// The device's network path changed (#1372): a quiet reconnect waiting on its backoff runs - /// now if the network is back, or holds until it is. `BotsInboxView` calls it while on screen. - /// Offline, the statuses are only the last known ones, whatever the socket says (#1374). func networkPathDidChange() { if !isNetworkAvailable(), !liveStatuses.isEmpty { setLiveStatuses(liveStatuses, stale: true) } reconnect.networkPathDidChange() } - /// The user tapped "Reconnecting…" (#1374): the waiting reconnect runs now, past its backoff, - /// the way a network return runs it. Offline, or with no reconnect waiting, nothing happens. func reconnectNow() { reconnect.networkPathDidChange() } - /// The inbox left the screen, or the app went to the background: it stops reconnecting, and - /// statuses that were only the last known ones go, since nothing re-reads them meanwhile. func close() { teardown() setReconnecting(false) if liveStatusesAreStale { setLiveStatuses([:]) } } - /// Ends the socket and everything waiting on it. `open()` starts with it, so a reconnect - /// keeps the last known statuses and its reconnecting state. private func teardown() { openSerial += 1 reconnect.cancel() @@ -512,28 +365,20 @@ import UIKit link = .idle } - /// The host could not be reached at all: no answer, or a proxy or Cloudflare - /// answering for it. Repeated, these replace an empty inbox's skeleton with advice. private static func isRouteFailure(_ error: Error) -> Bool { if error is URLError { return true } guard case .rejected(let code)? = error as? BotFailure else { return false } return (502...504).contains(code) || (520...530).contains(code) } - /// True until the first roster lands: the inbox shows a skeleton instead of a - /// connection message while it connects, or quietly retries, with nothing to show. var isLoadingRoster: Bool { connection != nil && profiles.isEmpty && errorMessage == nil && routeAdvice == nil && link != .live } func mayEdit(_ profile: BotProfile) -> Bool { link == .live && !editing.contains(profile.id) } - /// The built-in Profile is the host itself; Hermes refuses to delete it. func mayDelete(_ profile: BotProfile) -> Bool { profile.id != "default" && mayEdit(profile) } - /// Deletes the Profile on the host, then this phone's state for it. A refused - /// delete leaves everything in place; a lost reply is reported as uncertain and - /// never retried on its own, because the next roster read settles it. func delete(_ profile: BotProfile) async { guard mayDelete(profile), let client = wire else { return } editing.insert(profile.id); notice = nil @@ -555,7 +400,6 @@ import UIKit } } - /// Drops everything this phone kept for a bot that no longer exists on the host. private func forget(_ profile: String) async { if selection.profile?.id == profile { selection = BotInboxSelection() } guard let connection else { return } @@ -570,16 +414,11 @@ import UIKit func setPinned(_ pinned: Bool, _ profile: BotProfile) async { await configure(profile, ["pinned": .bool(pinned)]) } func setHidden(_ hidden: Bool, _ profile: BotProfile) async { await configure(profile, ["hidden": .bool(hidden)]) } - /// Files the bot under a section already on the roster, stamping its id and the - /// name the inbox heads it with, as Desktop's "Move to section" does. func moveToSection(_ profile: BotProfile, _ section: SectionName) async { guard profile.sectionID != section.id || profile.sectionName != section.name else { return } await configure(profile, ["sectionId": .string(section.id), "sectionName": .string(section.name)]) } - /// Files the bot under a new section named `name`, trimmed. A blank name writes - /// nothing; a name that exactly matches a section on the roster joins that one - /// instead of making a twin. Desktop adopts the new id at the end of its own list. func moveToNewSection(_ profile: BotProfile, name: String) async { let name = name.trimmingCharacters(in: .whitespacesAndNewlines) guard !name.isEmpty else { return } @@ -587,25 +426,16 @@ import UIKit await configure(profile, ["sectionId": .string(Self.newSectionID()), "sectionName": .string(name)]) } - /// Back to unfiled. Explicit nulls, not missing keys: Desktop merges the host's - /// meta over its local copy, so a dropped key would keep its stale section alive. func removeFromSection(_ profile: BotProfile) async { await configure(profile, ["sectionId": .null, "sectionName": .null]) } - /// Desktop's section id format: `sec--<5 base-36 chars>`. static func newSectionID(now: Date = .now) -> String { let alphabet = Array("0123456789abcdefghijklmnopqrstuvwxyz") let millis = String(Int64(now.timeIntervalSince1970 * 1000), radix: 36) return "sec-\(millis)-" + String((0..<5).map { _ in alphabet.randomElement()! }) } - /// Writes Desktop look fields through `profiles.configure`, sending the whole - /// `hermes-bots` object back with `changes` applied so unrelated Desktop fields - /// survive, under the look revision the row was read at. Nothing is shown as done - /// until the host says it applied and the roster is re-read; a conflict means - /// Desktop wrote in between, so the fresh roster is shown and the user decides - /// whether to retry. private func configure(_ profile: BotProfile, _ changes: [String: BotJSON]) async { guard mayEdit(profile), let client = wire else { return } editing.insert(profile.id); notice = nil @@ -629,9 +459,6 @@ import UIKit } } - /// Coalesces `sessions.changed` bursts: one reload in flight, at most one - /// more queued, spaced by `reloadSpacing`. Avatars are not refreshed here - /// because the event follows session activity, and a look change never moves it. private func noteChange() { reloadWanted = true guard reloadTask == nil, let client = wire else { return } @@ -646,13 +473,9 @@ import UIKit } } - /// One `profiles.list` on the live socket, saved as the connection's cached roster, - /// then starts a live-status read against it without waiting for one. Only the newest - /// request's reply is applied, and only while `client` still owns the inbox. private func reload(_ client: any BotTransport) async -> Bool { reloadSerial += 1 let serial = reloadSerial - // The scope this read belongs to, and when it started, so a removal meanwhile revokes its save. let scope = connection.map { BotRosterCache.Scope(server: server, connectionID: $0.id) } let readAt = ContinuousClock.now do { @@ -675,11 +498,6 @@ import UIKit returnedFrom = nil if changed { persistSeen() } let present = Set(profiles.map(\.id)) - // A Profile the roster listed before and this fresh one omits was deleted elsewhere: - // its cached Bot Chat goes too. Done before the first `await` below, so a reopen or a - // newer reload cannot make `previous` forget it first. `profiles` starts as the cached - // roster when there is one (it lives in Caches and skips very large rosters), so a - // deletion made while the app was closed is caught only then. if let connection, let offlineCache { for name in previous.subtracting(present) { try? CacheStore.removeHermesBotChats(serverURL: server, connectionID: connection.id, profile: name, in: offlineCache) @@ -704,27 +522,16 @@ import UIKit } } - /// Replaces any status read or re-read in flight with one read, now or after - /// `delay`. `statusPollTask` always holds the newest one, so `close()`, a drop or - /// a newer read cancels it. private func startLiveStatusRead(_ client: any BotTransport, after delay: Duration? = nil) { statusPollTask?.cancel(); statusPollTask = nil guard readsLiveStatus else { return } statusPollTask = Task { [weak self] in if let delay, (try? await Task.sleep(for: delay)) == nil { return } - // A sleep that ended before its cancel still wakes; a cancelled read was replaced. guard !Task.isCancelled, let self, self.wire === client else { return } await self.readLiveStatuses(client) } } - /// One read-only `session.active_list`, mapped onto the current roster. A reply - /// applies only while `client` owns the inbox, the read was not cancelled, and no - /// newer status or roster read has started. A failed read keeps the statuses as the - /// last known ones, and never drops the socket: the roster owns the link. A host - /// without the method shows none. - /// While a bot is busy, or a read failed while one was, the next read is - /// scheduled `statusPollInterval` later; once every bot is idle it stops. private func readLiveStatuses(_ client: any BotTransport) async { statusSerial += 1 let serial = statusSerial, roster = reloadSerial @@ -750,13 +557,11 @@ import UIKit else { startLiveStatusRead(client, after: statusPollInterval) } } - /// `profiles.list` rows as the inbox lists them: unnamed rows dropped, the first of each Profile kept. private static func roster(_ rows: [BotJSON]) -> [BotProfile] { var ids = Set() return rows.compactMap(BotProfile.init).filter { ids.insert($0.id).inserted } } - /// Writes only a real change, so an unchanged re-read never invalidates the list. private func setLiveStatuses(_ statuses: [String: BotLiveStatus], stale: Bool = false) { if statuses != liveStatuses { liveStatuses = statuses } if stale != liveStatusesAreStale { liveStatusesAreStale = stale } @@ -770,7 +575,6 @@ import UIKit connection.map { BotRoomKey(server: server, connectionID: $0.id, roomID: room.id) } } - /// A failed room read is not an authoritative empty list, even if the Bot roster is live. var searchableRoomIDs: Set? { hasRoomList && link == .live ? Set(rooms.map(\.id)) : nil } @@ -782,8 +586,6 @@ import UIKit return searchableRoomIDs == nil ? saved : nil } - /// Admit a cached identity for navigation only while the live list is unavailable. - /// Search dismissal rechecks the room, so a fresh list or connection change still wins. func selectRoomSearchHit(_ hit: BotHistoryCache.Hit) -> BotGroupRoom? { guard let room = roomForSearch(hit) else { return nil } if !rooms.contains(where: { $0.id == room.id }) { rooms.append(room) } @@ -818,7 +620,6 @@ import UIKit func isRoomPinned(_ room: BotGroupRoom) -> Bool { roomFlags.pinned.contains(room.id) } func isRoomHidden(_ room: BotGroupRoom) -> Bool { roomFlags.hidden.contains(room.id) } - /// Phone-only, so these apply at once and need no host round trip. func setRoomPinned(_ pinned: Bool, _ room: BotGroupRoom) { if pinned { roomFlags.pinned.insert(room.id) } else { roomFlags.pinned.remove(room.id) } persistRoomFlags() @@ -828,17 +629,12 @@ import UIKit persistRoomFlags() } - /// Places the named sections in `ids` order on this phone only. Sections not in - /// `ids`, including ones Desktop adds later, follow A–Z after them. func setSectionOrder(_ ids: [String]) { guard let connection, ids != sectionOrder else { return } sectionOrder = ids sectionOrderStore.save(ids, server: server, connectionID: connection.id) } - /// Saves a drag in "Reorder Sections…", given the sheet's ids in their new order. - /// A placed section the sheet leaves out (pinned-only for now) keeps its slot, - /// so its placement survives until the list can head it again. func placeReorderableSections(_ ids: [String]) { let listed = Set(ids) var next = ids[...] @@ -848,12 +644,8 @@ import UIKit }) } - /// Back to A–Z: forgets every placement for this connection. func resetSectionOrder() { setSectionOrder([]) } - /// Rename and disband follow the room screen's gates: the host must offer the - /// method, the room must be this gateway's own, and no write for it may be in - /// flight. A room under another gateway's authority is read-only from here. func mayRenameRoom(_ room: BotGroupRoom) -> Bool { mayCommandRoom(room, "groups.rename") } func mayDisbandRoom(_ room: BotGroupRoom) -> Bool { mayCommandRoom(room, "groups.disband") } private func mayCommandRoom(_ room: BotGroupRoom, _ method: String) -> Bool { @@ -870,8 +662,6 @@ import UIKit } } - /// Nothing local is dropped until the host confirms the tombstone; a lost - /// reply is settled by the next room list, which prunes what is gone. func disbandRoom(_ room: BotGroupRoom) async { guard mayDisbandRoom(room), let client = wire, let key = roomKey(room) else { return } let disbanded = await commandRoom(room, .groupsDisband(roomID: room.id), client) { result in @@ -883,7 +673,6 @@ import UIKit if disbanded { try? await historyCache.removeRoom(key) } } - /// True when the host accepted the write and `accept` took it. @discardableResult private func commandRoom(_ room: BotGroupRoom, _ call: HermesCall, _ client: any BotTransport, accept: (BotJSON) throws -> Void) async -> Bool { @@ -908,8 +697,6 @@ import UIKit roomStore.save(roomFlags, connectionID: connection.id) } - /// Capabilities are re-read on every inbox open/refresh, never inferred from - /// a mutating probe. Unsupported hosts keep their ordinary Bot inbox. private func refreshRooms(_ client: any BotTransport) async { do { let value = try await client.call(.groupsCapabilities) @@ -939,7 +726,6 @@ import UIKit } catch { guard wire === client, !Task.isCancelled else { return } rooms = []; hasRoomList = false; roomCapabilities = BotRoomCapabilities(.null) - // Method absence is the expected gate on older Hermes hosts. if let failure = error as? BotRoomFailure, failure.code != -32601 { notice = failure.localizedDescription } @@ -951,18 +737,10 @@ import UIKit await avatarStore.refresh(profiles, connectionID: connection.id, using: client) { if wire === client { avatars = avatarStore.images(connectionID: connection.id) } } - // After the photos, so a configured Bot widget gets its bot's photo rather than its face. guard wire === client, !Task.isCancelled else { return } await widgets.renderAvatars(profiles, server: server, connectionID: connection.id, photos: avatars) } - /// A lost socket or a failed read is retried quietly, with growing delays, for as long as - /// the inbox stays open, and held while the device is offline; the roster and its last known - /// statuses stay on screen meanwhile, and `isReconnecting` says so. Only a refusal the user - /// has to act on (`BotConnectionAdvice.isRetryable`) clears the statuses and shows a message - /// and the Reconnect button (Update sign-in for a rejected password, a new address for a - /// gateway's own listener). An empty inbox shows - /// `routeAdvice` if the host stays unreachable. private func drop(_ client: any BotTransport, error: Error) { reloadTask?.cancel(); reloadTask = nil; reloadWanted = false statusPollTask?.cancel(); statusPollTask = nil @@ -993,10 +771,6 @@ import UIKit } } -/// Device-local record of the canonical activity the user last saw per bot, -/// keyed by connection UUID so equal Profile names on two hosts never share a -/// mark. Plain timestamps, so `UserDefaults` rather than the Keychain; the -/// values never leave the phone and Desktop has no matching state to sync. struct BotUnreadStore { var defaults: UserDefaults = .standard @@ -1015,9 +789,6 @@ struct BotUnreadStore { } } -/// Phone-local order of Desktop's named sections, keyed by configured server and -/// connection UUID. Desktop's own order lives in its plugin storage and is never -/// read or written from here, so this is plain `UserDefaults` like the unread marks. struct BotSectionOrderStore { var defaults: UserDefaults = .standard @@ -1039,9 +810,6 @@ struct BotSectionOrderStore { } } -/// Phone-local pin and hide marks for group rooms, keyed by connection UUID like -/// the unread marks. The host keeps no such state for rooms, so a pin made here -/// never shows in Desktop or on another phone. struct BotRoomOrganizeStore { struct Flags: Equatable { var pinned: Set = [] diff --git a/HermesMobile/Features/Bots/BotLiveActivity.swift b/HermesMobile/Features/Bots/BotLiveActivity.swift index 65ec43559..34a5f13a4 100644 --- a/HermesMobile/Features/Bots/BotLiveActivity.swift +++ b/HermesMobile/Features/Bots/BotLiveActivity.swift @@ -3,7 +3,6 @@ import SwiftUI import UIKit extension AgentRunActivityBot { - /// Nil for a destination that cannot be written as a link: no tap target, no activity. init?(_ destination: BotDestination, avatarFile: String? = nil) { guard let url = HermesDeepLink.botURL(for: destination) else { return nil } self.init(key: "bot:\(destination.connectionID.uuidString):\(destination.profile)", @@ -11,12 +10,7 @@ extension AgentRunActivityBot { } } -/// What a bot's chat (`HermesChatTurnCoordinator`) borrows for its Live Activity (#489): the -/// count chips and the avatar file. The coordinator starts and updates the shared -/// `AgentLiveActivityManager` itself. @MainActor enum BotLiveActivity { - /// A bot's count chips (#584): the plan's step while one is open, then the live workers - /// and the turn's tools. Counts only. nonisolated static func countChips(plan: HermesPlan?, workers: Int, tools: Int = 0) -> [String] { var chips: [String] = [] if let plan, !plan.isFinished { @@ -27,10 +21,6 @@ extension AgentRunActivityBot { return chips } - /// Renders the bot's avatar, photo or drawn face, to one PNG in the app group and - /// returns its file name. Only one activity exists at a time, so every other - /// file is dropped first. The name carries the connection, so equal Profile - /// names on two connections never share an image. static func writeAvatar(_ profile: BotProfile, _ destination: BotDestination) -> String? { guard let directory = AgentRunActivityAvatarFile.directory else { return nil } let files = FileManager.default @@ -49,7 +39,6 @@ extension AgentRunActivityBot { BotAvatarMarkView(name: profile.id, appearance: BotProfileAppearance(profile: profile), size: 40) } } - // The activity card is always dark, so the adaptive body color resolves for it. .environment(\.colorScheme, .dark)) renderer.scale = 3 let digest = SHA256.hash(data: Data(profile.id.utf8)).prefix(8).map { String(format: "%02x", $0) }.joined() diff --git a/HermesMobile/Features/Bots/BotMentionAutocompleteView.swift b/HermesMobile/Features/Bots/BotMentionAutocompleteView.swift index d168607dc..bf7fa524a 100644 --- a/HermesMobile/Features/Bots/BotMentionAutocompleteView.swift +++ b/HermesMobile/Features/Bots/BotMentionAutocompleteView.swift @@ -1,8 +1,5 @@ import SwiftUI -/// The slash panel's dense rows and glass surface, with connection-local bots. -/// A Hermes chat's combined `@` panel draws the same `BotMentionRow`; rooms keep -/// this members-only panel and never see files. struct BotMentionAutocompleteView: View { let completions: [BotMentions.Completion] let avatars: [String: UIImage] @@ -27,8 +24,6 @@ struct BotMentionAutocompleteView: View { } } -/// One roster row: avatar, `@tag`, display name. A Hermes chat and a group room -/// draw the same row. struct BotMentionRow: View { let item: BotMentions.Completion let avatars: [String: UIImage] diff --git a/HermesMobile/Features/Bots/BotMentions.swift b/HermesMobile/Features/Bots/BotMentions.swift index 7baec790e..ba57812e4 100644 --- a/HermesMobile/Features/Bots/BotMentions.swift +++ b/HermesMobile/Features/Bots/BotMentions.swift @@ -1,7 +1,5 @@ import UIKit -/// Identification only, using one connection's inbox roster. No delivery or relay -/// work belongs here; the annotated prompt follows the ordinary command path. struct BotMentions { struct Completion: Identifiable { let profile: BotProfile @@ -12,9 +10,6 @@ struct BotMentions { private let candidates: [Completion] private let byForm: [String: BotProfile] private static let reserved: Set = ["all", "everyone", "user", "default", "hermes"] - /// A handle runs possessively to its end and is not a mention when a path - /// continues it (`@docs/plan.md`, `@docs.md`), so the composer's file - /// references never resolve as a bot; trailing punctuation still does. private static let tokens = try! NSRegularExpression( pattern: #"(^|\s)@([a-z0-9][a-z0-9_-]*+)(?![/\\]|\.[a-z0-9_-])"#, options: .caseInsensitive ) @@ -53,8 +48,6 @@ struct BotMentions { bot.id.lowercased() == "default" ? "hermes" : bot.id } - /// Desktop's slug and collapsed forms; reserved words only block friendly - /// aliases, so the primary Profile still owns @hermes and @default. static func nameForms(_ value: String?) -> [String] { guard let name = value?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() else { return [] } let slug = name.replacingOccurrences(of: "[^a-z0-9_-]+", with: "-", options: .regularExpression) @@ -74,13 +67,10 @@ struct BotMentions { }.prefix(8)) } - /// Every unambiguous alias is available to the shared composer editor. func chipReferences(avatars: [String: UIImage]) -> [String: ComposerBotReference] { byForm.mapValues { ComposerBotReference(profile: $0, avatar: avatars[$0.id]) } } - /// Preserve UTF-16 offsets while masking code, so sending and chip display - /// resolve the same prose without shifting a chip onto unrelated text. static func proseMentions(in text: String) -> [(range: NSRange, form: String)] { let prose = NSMutableString(string: text) for regex in [fences, inlineCode] { @@ -111,8 +101,6 @@ struct BotMentions { return Self.notePrefix + lines + Self.noteSuffix } - /// Hide only a trailing identification note in user presentation. Drafts and - /// transport text retain their original bytes, including whitespace. static func displayText(_ text: String) -> String { guard let start = text.range(of: notePrefix, options: .backwards), text.hasSuffix(noteSuffix) else { return text } @@ -125,8 +113,6 @@ struct BotMentions { } } -/// Caret-local @ token. Uses the slash completion's UTF-16 replacement behavior -/// so text on either side and the editor's selection ownership are preserved. struct BotMentionTrigger { let range: NSRange let query: String diff --git a/HermesMobile/Features/Bots/BotMessageActions.swift b/HermesMobile/Features/Bots/BotMessageActions.swift index 456ccea9d..531f25a92 100644 --- a/HermesMobile/Features/Bots/BotMessageActions.swift +++ b/HermesMobile/Features/Bots/BotMessageActions.swift @@ -1,12 +1,8 @@ import SwiftUI import UIKit -/// The long-press actions a room message offers: Copy only, by the canonical-chat -/// policy settled in issue #481. The copied text is the Markdown source the -/// transcript rendered, so a code block pastes as a code block. @MainActor enum BotMessageActions { - /// `copy` is injectable so a test can read the text without a pasteboard. static func items( copyText: String?, isHapticsEnabled: Bool, diff --git a/HermesMobile/Features/Bots/BotPendingRequest.swift b/HermesMobile/Features/Bots/BotPendingRequest.swift index 26ba03783..8dddeb51a 100644 --- a/HermesMobile/Features/Bots/BotPendingRequest.swift +++ b/HermesMobile/Features/Bots/BotPendingRequest.swift @@ -1,15 +1,5 @@ import Foundation -/// A request that parks a bot's work until someone answers it. -/// -/// Requests arrive as server-request envelopes, live or restored from -/// `open_requests`; an approval can also come from the snapshot's -/// `pending_approval`. A connection operation is the one kind that is not a -/// server request: see `BotConnectionOperation`. -/// -/// Only `desktopTask` is unanswerable, and not for want of a credential path: the -/// answer is data only Hermes Desktop's own window holds, so no client without -/// that window can produce one. enum BotPendingRequest: Equatable { case approval(BotApprovalRequest) case question(BotQuestionRequest) @@ -17,8 +7,6 @@ enum BotPendingRequest: Equatable { case desktopTask(BotDesktopTaskRequest) case connection(BotConnectionOperation) - /// The host's id for this request: the envelope id, approval's queue id, or - /// a connection operation's `op_id`. var requestID: String { switch self { case .approval(let request): return request.requestID @@ -30,19 +18,11 @@ enum BotPendingRequest: Equatable { } } -/// A server request, received live or restored from `open_requests`. -/// Keep the envelope id separate from approval's underlying queue request id. -/// An unknown method keeps `pending` nil: the bot is still blocked, and the phone -/// never answers it, not even with -32601, because a reply from here would -/// pre-empt the Hermes Desktop window that can. `theme.apply` and `theme.pick` keep it nil -/// too: a Hermes chat answers them itself, before they join its requests (`HermesThemeRequest`). struct BotServerRequest: Equatable { let id: String let method: String let sessionID: String let pending: BotPendingRequest? - /// A canonical host's approval or clarify prompt's execution generation, which its answer - /// carries (`HermesCanonicalPrompts`, #1602); nil for a server request. let promptGeneration: Int? init?(_ frame: BotJSON) { @@ -77,34 +57,19 @@ struct BotServerRequest: Equatable { } } -/// One pending dangerous-command approval. The host precomputes `choices` from -/// its own smart-approval and permanent-allow policy, so the phone offers exactly -/// what the host offered rather than inventing a fifth option. struct BotApprovalRequest: Equatable { - /// The host's wire vocabulary for `approval.respond`'s `choice`. enum Choice: String, Equatable, CaseIterable { case once, session, always, deny } let requestID: String - /// The command as the host redacted it. Nil when the gate was not command-shaped. let command: String? - /// Why the host flagged this action, from `description`. let consequence: String? - /// The host may include the tool's own folder, which takes precedence over session.info. let workingDirectory: String? - /// Server order, `once` first and `deny` last. Never empty. let choices: [Choice] - /// What Allow session and Always allow would allowlist: `pattern_keys`, else - /// `[pattern_key]`. Empty when the host sent neither. let patternKeys: [String] - /// The gated tool, when the host names it. Absent at the pin, where a plugin - /// rule carries its tool in the key or the command instead. let toolName: String? - /// What Allow session and Always allow cover on this bot's Profile, or nil - /// when Allow session isn't offered (a smart-denied prompt, or a room - /// approval's once and deny). var scopeLine: AttributedString? { ApprovalScope.line( keys: patternKeys, description: consequence, command: command, toolName: toolName, @@ -112,8 +77,6 @@ struct BotApprovalRequest: Equatable { ) } - /// Nil when the payload carries no usable request id: without one the phone - /// cannot address `approval.respond` and must not guess FIFO order. init?(_ json: BotJSON) { guard let id = json["request_id"].text, !id.isEmpty else { return nil } requestID = id @@ -123,21 +86,14 @@ struct BotApprovalRequest: Equatable { let keys = (json["pattern_keys"].list ?? []).compactMap { Self.trimmed($0) } patternKeys = keys.isEmpty ? Self.trimmed(json["pattern_key"]).map { [$0] } ?? [] : keys toolName = Self.trimmed(json["tool_name"]) - // A present `choices` is the host speaking, and nothing may be added to - // what it offered. If a newer host renames the lot so none of it parses, - // Deny is the only thing left that is safe to offer: rebuilding here - // would invent an Always allow the host never sanctioned. let present = json.fields?["choices"] if let present, present.list == nil { - // Present but not a list (null, a string, an object): not an older host, - // so nothing is rebuilt and Deny is the only safe offer. choices = [.deny] } else if let list = present?.list { let offered = list.compactMap { $0.text.flatMap(Choice.init(rawValue:)) } if offered.isEmpty { choices = [.deny] } else { choices = offered.contains(.deny) ? offered : offered + [.deny] } } else { - // Only an absent `choices` is an older host; rebuild what it would send. var rebuilt: [Choice] = [.once] if json["smart_denied"].flag != true, json["allow_session"].flag != false { rebuilt.append(.session) @@ -153,13 +109,7 @@ struct BotApprovalRequest: Equatable { } } -/// One pending clarify request: either the single-question shape -/// (`question`/`choices`/`multi_select`) or the batch shape (`questions`), which -/// locks one answer per question id and carries the locked ones back on reconnect. struct BotQuestionRequest: Equatable { - /// One offered answer. `wireLabel` goes back to the host verbatim; the host - /// strips its own "(Recommended)" suffix, so presentation never leaks into - /// the answer and the phone never has to reconstruct a label. struct Choice: Identifiable, Equatable { static let recommendedSuffix = "(Recommended)" @@ -180,14 +130,10 @@ struct BotQuestionRequest: Equatable { } struct Question: Identifiable, Equatable { - /// The host's `qid`. Nil for the single-question shape, whose - /// single answer carries no `question_id`. let wireID: String? let prompt: String - /// Empty means open-ended: free text is the only answer. let choices: [Choice] let allowsMultipleChoices: Bool - /// An answer already locked on the host, replayed so a reconnect restores it. let lockedAnswer: String? var id: String { wireID ?? "" } @@ -197,12 +143,9 @@ struct BotQuestionRequest: Equatable { let requestID: String let questions: [Question] - /// Batch questions lock one answer per question id (`clarify.lock` on 0.21.2). var isBatch: Bool { questions.first?.wireID != nil } var unansweredCount: Int { questions.filter { !$0.isAnswered }.count } - /// Nil when the payload has no request id or no readable question, which is - /// how a host that carries the key but no content degrades to "no card". init?(_ json: BotJSON) { guard let id = json["request_id"].text, !id.isEmpty else { return nil } let locked = json["answers"] @@ -242,18 +185,10 @@ struct BotQuestionRequest: Equatable { } } -/// A value only the person can supply: the Mac's administrator password, or a -/// secret the bot asked for by name. Password-vault prompts (`vault.*`) are not -/// read: they stay open requests with no card, never answered from the phone (#1148). -/// -/// Answers carry `{value}` through `request.answer`. An empty value skips -/// without retaining a secret. struct BotCredentialRequest: Equatable { - /// The server request method. enum Kind: String, Equatable, CaseIterable { case sudo, secret - /// What skipping costs, so declining is an informed choice too. var skipConsequence: String { switch self { case .sudo: return String(localized: "Skip to let the command fail instead.") @@ -264,9 +199,7 @@ struct BotCredentialRequest: Equatable { let kind: Kind let requestID: String - /// `secret` only: the name the host stores the value under. let envVar: String? - /// `secret` only: the host's own words for what it wants. let prompt: String? var title: String { @@ -276,7 +209,6 @@ struct BotCredentialRequest: Equatable { } } - /// What the bot is asking for, preferring the host's wording when it sent any. var detail: String { switch kind { case .sudo: @@ -286,9 +218,6 @@ struct BotCredentialRequest: Equatable { } } - /// Where the value ends up, stated before it is typed. `sudo` is used for the - /// one command and never written down; `secret` is saved on the host under - /// `envVar`. Neither is ever stored by Hermex. var handling: String { switch kind { case .sudo: @@ -302,13 +231,7 @@ struct BotCredentialRequest: Equatable { } } -/// A request only Hermes Desktop can answer: work its own window performs and -/// answers by itself, serializing its terminal scrollback, the OS window beneath -/// it, its preview pane. Nobody types an answer to those, on the phone or at the -/// Mac; the host's deadline passes and the bot carries on, so the phone reports -/// the wait rather than sending anyone to a desk. struct BotDesktopTaskRequest: Equatable { - /// The server request method. enum Kind: String, Equatable, CaseIterable { case tour case terminalRead = "terminal.read" @@ -316,8 +239,6 @@ struct BotDesktopTaskRequest: Equatable { case previewRead = "preview.read" case previewAct = "preview.act" - /// What is happening, in the user's words rather than the wire name, naming the bot in - /// a bot's chat and Hermes in any other chat (#1141). func title(_ subject: HermesRequestSubject) -> String { switch (self, subject) { case (.terminalRead, .bot): return String(localized: "This bot is reading a terminal on the Mac.") @@ -347,28 +268,16 @@ struct BotDesktopTaskRequest: Equatable { let requestID: String } -/// A `manage_connections` operation: the bot asked to connect one or more apps, -/// and the host holds the tool until every row is connected or skipped, Continue -/// settles it, Stop interrupts it, or its deadline passes. -/// -/// It is an event plus an RPC, not a server request: `connection.request` opens -/// it, each `connection.update` carries the full snapshot again, the snapshot's -/// `pending_connection` restores it, and `connection.respond` answers it by -/// `op_id`. Nothing about it is cached. struct BotConnectionOperation: Equatable { - /// One value an MCP install still needs; the card draws a field for each. struct EnvField: Equatable, Identifiable { let name: String let isRequired: Bool let isSecret: Bool - /// The catalog's value for a non-secret field. The field starts with it, - /// as on Desktop, because the host never fills a default in by itself. let defaultValue: String? let prompt: String? var id: String { name } - /// What the field holds: the user's edit, else the default it starts with. func value(in values: [String: String]) -> String { values[name] ?? defaultValue ?? "" } @@ -376,7 +285,6 @@ struct BotConnectionOperation: Equatable { init?(_ json: BotJSON) { guard let name = json["name"].text?.trimmingCharacters(in: .whitespaces), !name.isEmpty else { return nil } self.name = name - // Absent means the host's own defaults: required, and masked to be safe. isRequired = json["required"].flag ?? true isSecret = json["secret"].flag ?? true defaultValue = isSecret ? nil : BotConnectionOperation.trimmed(json["default"]) @@ -384,8 +292,6 @@ struct BotConnectionOperation: Equatable { } } - /// One app the bot asked for. A value this build does not recognize keeps its - /// row readable but offers nothing, since the phone cannot tell what it permits. struct Target: Equatable, Identifiable { enum Kind: String { case connector, mcp } enum Action: String { case authorize, connect, enable, install, reconnect } @@ -419,38 +325,27 @@ struct BotConnectionOperation: Equatable { requiredEnv = (json["required_env"].list ?? []).compactMap(EnvField.init) } - /// The host lets the user skip any row still open: pending, started, - /// failed or expired. Connected and skipped rows are already resolved. var canSkip: Bool { guard kind != nil, action != nil, let state else { return false } return [.pending, .initiated, .failed, .expired].contains(state) } - /// A managed connector's vendor sign-in. It finishes in the browser and the - /// host notices the new account by itself, so the phone sends nothing back. - /// Only an https link opens: a failed or expired row's link is dead. var linkToOpen: URL? { guard kind == .connector, action != nil, state == .pending || state == .initiated, let connectURL, connectURL.scheme?.lowercased() == "https" else { return nil } return connectURL } - /// An MCP sign-in, which redirects to a listener on the host's own - /// loopback. A phone browser dead-ends there, so it never gets the link. var finishesOnTheMac: Bool { guard kind == .mcp, action == .authorize || connectURL != nil, let state else { return false } return [.pending, .initiated, .failed].contains(state) } - /// An MCP enable or install the phone approves, sending a value for each - /// `requiredEnv` field. A failed one runs again with the new values. var canConnect: Bool { kind == .mcp && (action == .enable || action == .install) && connectURL == nil && (state == .pending || state == .failed) } - /// The values Connect sends for what the fields hold: trimmed, and an - /// emptied field left out. func env(from values: [String: String]) -> [String: String] { requiredEnv.reduce(into: [:]) { env, field in let value = field.value(in: values).trimmingCharacters(in: .whitespacesAndNewlines) @@ -458,8 +353,6 @@ struct BotConnectionOperation: Equatable { } } - /// True when this row connects with `env`: every required field filled, - /// no field it did not declare, and no empty value. func accepts(_ env: [String: String]) -> Bool { guard canConnect else { return false } let declared = Set(requiredEnv.map(\.name)) @@ -468,14 +361,11 @@ struct BotConnectionOperation: Equatable { } } - /// One row's answer, or Continue, on its way to `connection.respond`. enum Answer: Equatable { case connect(target: String, env: [String: String]) case skip(target: String) - /// Settles the whole operation now; unresolved rows become `not_connected`. case continueWithout - /// True when the row on screen offers this answer, with every required value filled. func isOffered(by operation: BotConnectionOperation) -> Bool { switch self { case .continueWithout: return true @@ -485,7 +375,6 @@ struct BotConnectionOperation: Equatable { } } - /// The `result` object: one row per answer, or only `settled_by`. var result: BotJSON { switch self { case .connect(let name, let env): @@ -501,16 +390,11 @@ struct BotConnectionOperation: Equatable { } let opID: String - /// The host's write counter for this operation. A frame that is not newer is older. let seq: Int let deadline: Date let isSettled: Bool - /// Server order, one row per name. let targets: [Target] - /// Reads `connection.request`, a `connection.update` or `pending_connection`. - /// Nil without an id, a counter, a deadline or any readable row: there is - /// nothing a card could address, and the bot shows as blocked without one. init?(_ json: BotJSON) { guard let opID = json["op_id"].text, !opID.isEmpty, let seq = json["seq"].integer, let deadline = json["deadline_at"].number, deadline.isFinite, deadline > 0 else { return nil } @@ -524,15 +408,10 @@ struct BotConnectionOperation: Equatable { self.targets = targets } - /// This operation after `frame`: every frame is the full snapshot, so a newer - /// one replaces it whole. An older or equal counter, or another operation's - /// frame, changes nothing. func applying(_ frame: BotConnectionOperation) -> BotConnectionOperation { frame.opID == opID && frame.seq > seq ? frame : self } - /// Whole minutes left before the host's deadline, never below one: the card - /// stays until the settled frame, which the deadline itself produces. static func minutesLeft(until deadline: Date, now: Date) -> Int { max(1, Int((deadline.timeIntervalSince(now) / 60).rounded(.up))) } @@ -543,14 +422,10 @@ struct BotConnectionOperation: Equatable { } } -/// One question's answer on its way to the host. `questionID` is the -/// host's `qid` for a batch and nil for the single-question shape. struct BotQuestionAnswer: Equatable { let questionID: String? let text: String - /// Multi-select answers go over the wire as a JSON array string; the host - /// parses that, a bare array is not part of the contract. init(questionID: String?, selections: [String]) { self.questionID = questionID let data = try? JSONSerialization.data(withJSONObject: selections) @@ -563,27 +438,18 @@ struct BotQuestionAnswer: Equatable { } } -/// Why the request on screen can no longer be acted on, scoped to the request it -/// describes so a newer request never inherits an older verdict. struct BotRequestResolution: Equatable { enum Outcome: Equatable { - /// The host accepted the answer. The next snapshot removes the request. case answered - /// The host had nothing left to resolve: answered on another surface, or expired. case alreadyResolved - /// Delivery failed in a way that cannot distinguish sent from not sent. case uncertain } let requestID: String let outcome: Outcome - /// True while the request must stay inert. An uncertain outcome warns instead - /// of locking the user out: the phone never resends, but a deliberate second - /// answer after checking Desktop is the user's call, not a replay. var blocksFurtherAnswers: Bool { outcome != .uncertain } - /// What the card says, naming the bot in a bot's chat and Hermes Desktop in any other chat. func message(_ subject: HermesRequestSubject) -> String { switch (outcome, subject) { case (.answered, _): return String(localized: "Answer sent.") @@ -594,27 +460,16 @@ struct BotRequestResolution: Equatable { } } -/// A request the host withdrew while it was on screen, and why (#892). The chat -/// leaves `message` where the card stood, so the bot's next words make sense. -/// -/// Only the family and the host's reason are kept: nothing the request carried -/// outlives its card, and the note is never cached. struct BotRequestWithdrawal: Equatable { - /// A server request by the identity `request.cancel` names (#530): the - /// envelope id and method, never its params. struct Envelope: Equatable { let id: String let method: String } - /// Which card was withdrawn, told apart by its server-request method. enum Family: Equatable { case approval, question - /// sudo, secret and the password-manager prompts. case other - /// Nil for the Desktop renderer's own tasks: their card already says the - /// bot carries on without them, so their withdrawal is silent. init?(method: String) { switch method { case "approval": self = .approval @@ -625,17 +480,12 @@ struct BotRequestWithdrawal: Equatable { } } - /// Why the host withdrew it, from `request.cancel`'s `reason`. enum Reason: Equatable { case timeout - /// `interrupted` or `session_closed`: the work stopped. case stopped case shutdown - /// Any other wording; approval callers may pass their own. case other - /// Nil for `resolved`, an answer given on another surface, and for a - /// cancel that gives no reason: either way silence is the honest note. init?(_ wire: String?) { switch wire?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" { case "", "resolved": return nil @@ -655,14 +505,11 @@ struct BotRequestWithdrawal: Equatable { self.reason = reason } - /// Nil when this withdrawal leaves no note. init?(method: String, reason: String?) { guard let family = Family(method: method), let reason = Reason(reason) else { return nil } self.init(family: family, reason: reason) } - /// One whole sentence per family and reason, so every language translates it - /// intact. A timed-out approval says the one fact that matters: nothing ran. var message: String { switch (family, reason) { case (.approval, .timeout): return String(localized: "Approval timed out, so it didn't run.") diff --git a/HermesMobile/Features/Bots/BotPendingRequestCard.swift b/HermesMobile/Features/Bots/BotPendingRequestCard.swift index f6d938017..5067b2ec0 100644 --- a/HermesMobile/Features/Bots/BotPendingRequestCard.swift +++ b/HermesMobile/Features/Bots/BotPendingRequestCard.swift @@ -1,42 +1,21 @@ import SwiftUI import UIKit -/// The request blocking a bot, rendered in the transcript where its work -/// stopped, so the command sits under the tool row that asked for it. -/// -/// Placement is the only thing Bot-specific here: the surfaces, choice buttons, -/// decision buttons and copy are the Sessions approval and clarification -/// vocabulary. `isEnabled` false is a resolved, expired or in-flight request: -/// the card stays readable and stops acting. A Hermes chat's request slot shows -/// it too, with `subject` naming Hermes or the bot (#1141); the -/// Desktop-task and connection bodies are the Hermes chat's own -/// (`HermesRequestCards.swift`). -/// -/// Only the Desktop-task body has no input, because its answer is data only -/// Hermes Desktop holds. Everything else — approvals, questions, sudo and -/// secret prompts, connection operations — is answered from here. struct BotPendingRequestCard: View { static let cornerRadius: CGFloat = 14 let request: BotPendingRequest - /// Which bot on which connection is asking, so two hosts with equal Profile - /// names never produce an anonymous card. let identity: String let isEnabled: Bool - /// Stop is gated separately: a Desktop-only request is never answerable, but - /// stopping the work it blocks is exactly what the phone still owns. let canStop: Bool let isAnswering: Bool let resolution: BotRequestResolution? let onApprove: (BotApprovalRequest.Choice) -> Void let onAnswer: ([BotQuestionAnswer]) -> Void let onSkip: () -> Void - /// Sends a credential request's typed value. Empty is the host's skip. let onCredential: (String) -> Void let onStop: () -> Void - /// One row's answer, or Continue, for a connection operation. let onConnection: (BotConnectionOperation.Answer) -> Void - /// Who the copy says is waiting. var subject: HermesRequestSubject = .bot var summary: ApprovalSummaryPresentation? = nil @@ -58,8 +37,6 @@ struct BotPendingRequestCard: View { credential: credential, identity: identity, isEnabled: isEnabled, isAnswering: isAnswering, onCredential: onCredential ) - // A new request gets a fresh, empty field: a password typed for a - // timed-out sudo prompt must never ride along into a secret. .id(credential.requestID) case .desktopTask(let task): HermesDesktopTaskRequestBody(task: task, identity: identity, subject: subject, canStop: canStop, onStop: onStop) @@ -68,7 +45,6 @@ struct BotPendingRequestCard: View { operation: operation, identity: identity, subject: subject, isEnabled: isEnabled, isAnswering: isAnswering, onConnection: onConnection ) - // Typed setup values belong to one operation's rows. .id(operation.opID) } if let resolution { @@ -85,7 +61,6 @@ struct BotPendingRequestCard: View { .onChange(of: request.requestID, initial: true) { announce() } } - /// One announcement per request; re-renders and answers stay silent. private func announce() { guard UIAccessibility.isVoiceOverRunning else { return } let summary: String @@ -105,10 +80,6 @@ struct BotPendingRequestCard: View { } } -/// A command approval. Only the choices the host actually offered are shown: -/// a smart-denied or permanent-allow-blocked request legitimately has fewer. -/// The scope line under the command says what Allow session and Always allow -/// cover, and is absent when neither is offered. private struct BotApprovalRequestBody: View { let approval: BotApprovalRequest let identity: String @@ -130,8 +101,6 @@ private struct BotApprovalRequestBody: View { .fixedSize(horizontal: false, vertical: true) } if let command = approval.command { - // Horizontally scrollable and selectable, so a long command is - // readable in full before it is approved. ScrollView(.horizontal, showsIndicators: false) { Text(command) .font(.system(.footnote, design: .monospaced)) @@ -166,8 +135,6 @@ private struct BotApprovalRequestBody: View { } } - /// Two per row, in the host's order, so Allow once and Deny stay reachable - /// without the layout changing when a choice is withheld. private var rows: [[BotApprovalRequest.Choice]] { stride(from: 0, to: approval.choices.count, by: 2).map { Array(approval.choices[$0..] = [:] @State private var typed: [String: String] = [:] - /// True when one tap is the whole answer, so no Send control is needed. private var submitsOnTap: Bool { !question.isBatch && question.questions.first?.allowsMultipleChoices == false } @@ -227,9 +189,6 @@ private struct BotQuestionRequestBody: View { private var canSubmit: Bool { isEnabled && !isAnswering && hasAnswer } - /// Every outstanding question, not just one. A partial send would lock the - /// untouched questions as skipped, so Send waits for the whole batch and - /// Skip stays the deliberate way to decline all of it. private var hasAnswer: Bool { !unanswered.isEmpty && unanswered.allSatisfy { item in !(picked[item.id]?.isEmpty ?? true) @@ -330,8 +289,6 @@ private struct BotQuestionRequestBody: View { .pendingRequestFieldSurface() .disabled(!isEnabled || isAnswering) - // A batch or multi-select answer is sent by the Send control below, - // which speaks for every question at once. if submitsOnTap { PendingRequestSubmitButton(isBusy: isAnswering, canSubmit: canSubmit) { onAnswer(answers()) } .accessibilityLabel("Send answer") @@ -358,8 +315,6 @@ private struct BotQuestionRequestBody: View { picked[item.id] = selection } - /// One answer per question the host has not already locked. A blank one is a - /// deliberate skip for that question, which is what the host's tool reads it as. private func answers() -> [BotQuestionAnswer] { unanswered.map { item in let labels = item.choices.filter { picked[item.id]?.contains($0.id) == true }.map(\.wireLabel) @@ -372,12 +327,6 @@ private struct BotQuestionRequestBody: View { } } -/// A sudo password or a secret the bot asked for. Masked, sent straight to the -/// host and never held on the model, in a draft or anywhere else on the phone. -/// The field offers AutoFill for passwords, and its value belongs to one -/// request: the card keys this body by request id, so a replacement request -/// starts empty. Skip is a first-class answer: it releases the bot immediately -/// instead of leaving it parked until the host's deadline. private struct BotCredentialRequestBody: View { let credential: BotCredentialRequest let identity: String @@ -398,7 +347,6 @@ private struct BotCredentialRequestBody: View { .font(AppFont.subheadline()) .foregroundStyle(.appPrimary) .fixedSize(horizontal: false, vertical: true) - // A secret's storage name, so the user knows which of their keys to paste. if let envVar = credential.envVar { Text(verbatim: envVar) .font(.system(.footnote, design: .monospaced)) @@ -455,16 +403,11 @@ private struct BotCredentialRequestBody: View { private func submit() { guard canSubmit else { return } let outgoing = value - // Dropped from the view the moment it is handed over; the model never - // holds it either, so no layer of the phone keeps the value around. value = "" onCredential(outgoing) } } -/// The line left in the card's slot when the host withdrew the request on screen -/// (#892), in the room system line's style. Static: it appears and goes without -/// a transition, and VoiceOver hears it once. struct BotRequestWithdrawalNote: View { let withdrawal: BotRequestWithdrawal diff --git a/HermesMobile/Features/Bots/BotProfileAppearance.swift b/HermesMobile/Features/Bots/BotProfileAppearance.swift index b9577f1ee..630390b5e 100644 --- a/HermesMobile/Features/Bots/BotProfileAppearance.swift +++ b/HermesMobile/Features/Bots/BotProfileAppearance.swift @@ -1,27 +1,18 @@ import SwiftUI import UIKit -/// Static Bot Mode presentation shared with Hermes Desktop. The raw metadata -/// dictionary remains the source of truth; this projection only edits the keys -/// Hermex owns on the Profile screen. struct BotProfileAppearance: Equatable, Sendable { var title: String var shape: String? var color: String? var custom: Bool var imageKind: String? - /// A `BotAvatarExpression` raw value. Hermex-owned: Desktop keeps the key but renders its own eyes. var expression: String? - /// An avatar the host's model drew from a description. Hermex-owned, like `expression`. var generated: BotGeneratedAvatar? { didSet { storedGenerated = nil } } - /// The value as the host stored it, until the user picks a face. A save writes it back as it - /// was, so a newer build's fields, or a format this build can't read, are never lost. private var storedGenerated: BotJSON? init(profile: BotProfile) { self.init(look: profile.look, fallbackTitle: profile.name) } - /// Reads a look object directly, so the editor can rebuild its appearance from the - /// look it last saved instead of the roster row it was opened with. init(look: [String: BotJSON], fallbackTitle: String) { let storedTitle = look["title"]?.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" title = storedTitle.isEmpty ? fallbackTitle : storedTitle @@ -36,8 +27,6 @@ struct BotProfileAppearance: Equatable, Sendable { } } - /// Applies only the compatible static appearance fields while retaining - /// Desktop-owned organization, groups, timestamps and future fields. func merging(into received: [String: BotJSON]) -> [String: BotJSON] { var result = received Self.set(title, key: "title", in: &result) @@ -64,15 +53,11 @@ struct BotProfileAppearance: Equatable, Sendable { } } -/// The swatches the editor and the create sheet offer for a drawn face. The first, -/// stored as Desktop's `#ffffff`, is the adaptive one: white on a dark screen and -/// black on a light one, so it never disappears into the background. struct BotAvatarColor: Identifiable { let hex: String let name: LocalizedStringResource var id: String { hex } var localizedName: String { String(localized: name) } - /// What the swatch and the face paint for this entry. var swatch: Color { Color.botBody(hex) } static let adaptiveHex = "#ffffff" @@ -94,8 +79,6 @@ enum BotAvatarShape: String, CaseIterable, Identifiable, Sendable { case controller, barbell, mug, lightbulb, chat, sprout, wateringCan = "watering-can" var id: String { rawValue } - /// The original shapes. Name-seeded faces pick only from these, so adding an avatar never - /// changes a bot that nobody customized. static let classic: [BotAvatarShape] = [.circle, .blob, .squircle, .pill, .triangle, .hexagon, .cloud, .drop] var localizedName: String { @@ -144,7 +127,6 @@ enum BotAvatarExpression: String, CaseIterable, Identifiable, Sendable { struct Eye: Equatable { let width: Double; let height: Double; let tilt: Double } struct Geometry: Equatable { let left: Eye; let right: Eye; let split: Double } - /// An unknown or missing stored value reads as neutral rather than failing the row. static func resolve(_ raw: String?) -> BotAvatarExpression { raw.flatMap(BotAvatarExpression.init(rawValue:)) ?? .neutral } var geometry: Geometry { @@ -193,14 +175,11 @@ enum BotAvatarExpression: String, CaseIterable, Identifiable, Sendable { } } -/// One frame of Desktop's classic shape vocabulary. It has no clock of its own: -/// `BotAnimatedFaceView` supplies the pose, and tile grids draw it at rest. struct BotAvatarMarkView: View { let name: String let appearance: BotProfileAppearance let size: CGFloat var pose: BotFacePose = .rest - /// Replaces the shape's own eye placement, so a card's face keeps one set of eyes on any shape. var eyeLayout: BotAvatarEyeLayout? private var presentation: BotAvatarPresentation { @@ -226,8 +205,6 @@ struct BotAvatarMarkView: View { .accessibilityHidden(true) } - /// Bloub measures eyes against the body radius; the neutral eye maps onto the - /// layout's capsule, with its lean. private func eye(_ eye: BotAvatarExpression.Eye, _ layout: BotAvatarEyeLayout) -> some View { Capsule().fill(presentation.eyeColor) .frame(width: size * layout.width * eye.width / 0.186, height: size * layout.height * eye.height / 0.412 * pose.lid) @@ -235,13 +212,9 @@ struct BotAvatarMarkView: View { } } -/// What a bot's chat title face shows for the current turn (#757). Waiting and failed -/// override the pinned expression, since a pin is only the resting face; every other -/// surface keeps the pin. Only `.working` moves beyond a blink. enum BotTitleFace { case resting, working, waiting, failed - /// The eyes that replace the pinned expression, or nil to keep it. var expression: BotAvatarExpression? { switch self { case .waiting: return .curious @@ -250,13 +223,10 @@ enum BotTitleFace { } } - /// The motion for an active scene: only work sways (from `beatStart`); every other - /// face just blinks, so a pending approval never runs the 15 fps beat. func motion(beatStart: Date) -> BotFaceMotion { self == .working ? .working(since: beatStart) : .idle } - /// What VoiceOver adds after the bot's name; nil when the face shows no state. var accessibilityValue: String? { switch self { case .waiting: return String(localized: "Needs attention") @@ -266,9 +236,6 @@ enum BotTitleFace { } } -/// A bot's chat title (#757): its face and name in one pill beside Back, and the way into the -/// bot's profile. The face shows the turn's state (`BotTitleFace`) and stays hidden from -/// VoiceOver, which hears the state as the pill's value instead. struct BotChatTitlePill: View { let profile: BotProfile let avatar: UIImage? @@ -290,7 +257,6 @@ struct BotChatTitlePill: View { } } -/// Before iOS 26 the toolbar draws no glass of its own, so the pill supplies a material. struct BotChatTitlePillFallback: ViewModifier { @ViewBuilder func body(content: Content) -> some View { if #available(iOS 26, *) { @@ -302,10 +268,6 @@ struct BotChatTitlePillFallback: ViewModifier { } } -/// A bot's chat's pill in `ChatView` (#1145): `BotChatTitlePill` over the chat's turn. It owns -/// the working face's beat (#776), so only the pill redraws as the turn moves: one 30 s sway -/// when work starts or the chat returns from the background mid-turn, then a still lean, and -/// no motion while the scene is not active. struct HermesBotChatPill: View { let turn: HermesChatTurnCoordinator let onOpen: () -> Void @@ -323,21 +285,16 @@ struct HermesBotChatPill: View { face: face, onOpen: onOpen ) .onChange(of: turn.botTurn) { workingBeat.observe(turn.botTurn, at: Date()) } - // The background drops the socket, so the turn is seen again on return: a new beat. .onChange(of: scenePhase) { if scenePhase == .background { workingBeat.rearm() } } } } } -/// An asset wins over the compatible static mark. The fallback now honors the -/// same shape and color fields the editor writes instead of inventing a letter tile. struct BotAvatarView: View { let profile: BotProfile let avatar: UIImage? let size: CGFloat - /// Photos never move; a drawn face blinks unless the caller asks for a frozen frame. var motion: BotFaceMotion = .idle - /// Replaces the pinned expression on a drawn face, for a state the title shows; photos ignore it. var expression: BotAvatarExpression? = nil var body: some View { @@ -357,20 +314,15 @@ struct BotAvatarView: View { } } -/// Where a face's eyes sit, as fractions of the mark: center offset, neutral eye size, lean, -/// the gap between the eyes, and how much of a look's travel they take. struct BotAvatarEyeLayout: Equatable { let x: Double, y: Double, width: Double, height: Double, lean: Double, gap: Double, travel: Double - /// The classic mark's leaning eyes, off to one side. static let classic = BotAvatarEyeLayout(x: 0.12, y: -0.08, width: 0.075, height: 0.22, lean: -18, gap: 0.1, travel: 1) - /// The same eyes centered at a point, as fractions of the mark from its center. func centered(x: Double, y: Double) -> BotAvatarEyeLayout { BotAvatarEyeLayout(x: x, y: y, width: width, height: height, lean: lean, gap: gap, travel: travel) } - /// Upright eyes at a placement. A smaller travel keeps a look inside a narrow body. init(_ eyes: BotAvatarEyes) { let width = 0.04 * eyes.scale self.init(x: eyes.x / 100 - 0.5, y: eyes.y / 100 - 0.5, width: width, height: 0.11 * eyes.scale, lean: 0, @@ -386,7 +338,6 @@ private struct BotAvatarPresentation { let shape: BotAvatarShape let color: Color let eyeColor: Color - /// A generated avatar's body, parsed once. Nil for a bad stored path, which draws the shape. let generatedPath: Path? let eyeLayout: BotAvatarEyeLayout @@ -496,8 +447,6 @@ private struct BotAvatarBody: Shape { } extension Color { - /// The body color for a stored hex. Desktop's white is drawn adaptively here: - /// white in dark appearance, black in light. static func botBody(_ hex: String) -> Color { if hex.lowercased() == BotAvatarColor.adaptiveHex { return Color(uiColor: UIColor { $0.userInterfaceStyle == .dark ? .white : .black }) @@ -505,7 +454,6 @@ extension Color { return Color(botHex: hex) ?? .purple } - /// Eyes that contrast with `botBody(hex)` in both appearances. static func botEyes(on hex: String) -> Color { if hex.lowercased() == BotAvatarColor.adaptiveHex { return Color(uiColor: UIColor { $0.userInterfaceStyle == .dark diff --git a/HermesMobile/Features/Bots/BotProfileEditor.swift b/HermesMobile/Features/Bots/BotProfileEditor.swift index 1d04db292..d619cd9d3 100644 --- a/HermesMobile/Features/Bots/BotProfileEditor.swift +++ b/HermesMobile/Features/Bots/BotProfileEditor.swift @@ -48,9 +48,6 @@ struct BotProfileDetails: Equatable, Sendable { } } -/// One connection/Profile editor. The initial roster row contributes Desktop's -/// appearance revision; `profiles.describe` contributes Profile-scoped content. -/// Successful sections advance their own baseline, while failed sections remain dirty. @MainActor @Observable final class BotProfileEditor { enum LoadState: Equatable { case idle, loading, loaded, failed(String) } enum Field: String, CaseIterable, Hashable, Identifiable { @@ -135,8 +132,6 @@ struct BotProfileDetails: Equatable, Sendable { return fields } var canSave: Bool { state == .loaded && !isSaving && !dirtyFields.isEmpty } - /// True while the editor holds its client: from a load or Save until `close()`, - /// `suspend()`, a failed load or a lost socket. var holdsConnection: Bool { wire != nil } func load() async { @@ -154,8 +149,6 @@ struct BotProfileDetails: Equatable, Sendable { try ensureOwner(owner, client) let details = BotProfileDetails(detailsPayload, expectedName: profile.id) guard details.name == profile.id else { throw BotFailure.wrongIdentity } - // A bot chat's pill opens this with a bare row until its roster read answers. Saving - // that would claim revision 0 and read as a change made elsewhere, so read the real one. if lookRevision == nil, let roster = try? await client.call(.profilesList(includeSessions: false), validateDispatch: validate(owner)) { try ensureOwner(owner, client) if let row = roster["profiles"].list?.first(where: { $0["name"].text == profile.id }), let fresh = BotProfile(row) { @@ -169,8 +162,6 @@ struct BotProfileDetails: Equatable, Sendable { try ensureOwner(owner, client) modelGroups = [] } - // The look comes from what was last received or saved, not the roster row the - // editor opened with, so a foreground reload after a save keeps the saved look. let loaded = Draft(appearance: BotProfileAppearance(look: receivedLook, fallbackTitle: profile.name), description: details.description, instructions: details.instructions, model: details.model, skills: details.skills, @@ -191,9 +182,6 @@ struct BotProfileDetails: Equatable, Sendable { isSaving = false; confirmation = nil } - /// Backgrounding can make an in-flight write ambiguous. Preserve every - /// draft and make that uncertainty visible; the next deliberate Save opens - /// a fresh socket but never retries automatically. func suspend() { let fields = dirtyFields let wasSaving = isSaving @@ -219,7 +207,6 @@ struct BotProfileDetails: Equatable, Sendable { clearOutcome(.appearance); clearOutcome(.avatar) } - /// Takes an avatar the host's model drew. The stored `shape` stays, for Desktop and older builds. func setGenerated(_ generated: BotGeneratedAvatar) { if draft.appearance.shape.flatMap(BotAvatarShape.init(rawValue:)) == nil { draft.appearance.shape = BotAvatarShape.circle.rawValue @@ -231,7 +218,6 @@ struct BotProfileDetails: Equatable, Sendable { clearOutcome(.appearance); clearOutcome(.avatar) } - /// One tool-free model call under this bot, for "Describe It". func sendAvatarPrompt(_ prompt: String) async throws -> String { guard let client = wire else { throw BotFailure.stale } return try await BotAvatarGeneration.ask(prompt, profile: profile.id, transport: client, validateDispatch: validate(generation)) @@ -249,8 +235,6 @@ struct BotProfileDetails: Equatable, Sendable { clearOutcome(.avatar) } - /// Only the eyes change: an uploaded photo, the `custom` flag and the default - /// bot's fixed look are left alone, so the expression shows once no photo covers it. func setExpression(_ expression: BotAvatarExpression) { draft.appearance.expression = expression == .neutral ? nil : expression.rawValue clearOutcome(.appearance) @@ -303,8 +287,6 @@ struct BotProfileDetails: Equatable, Sendable { outcomes[.model] = .failed(String(localized: "Model confirmation was declined. Your selection is still unsaved.")) } - /// Refreshes only Desktop appearance after a compare-and-swap conflict. - /// Other unsaved Profile fields stay untouched. func reloadAppearance() async { guard let client = wire else { return } let owner = generation @@ -317,7 +299,6 @@ struct BotProfileDetails: Equatable, Sendable { let appearance = BotProfileAppearance(profile: fresh) baseline.appearance = appearance; draft.appearance = appearance avatarChange = .unchanged; outcomes.removeValue(forKey: .appearance); outcomes.removeValue(forKey: .avatar) - // One bot's asset only: a roster-wide refresh would drop every other bot's image. var image: UIImage? if fresh.hasAvatar { let reply = try await client.call(.profilesGetAsset(name: fresh.id), validateDispatch: validate(owner)) @@ -445,9 +426,7 @@ struct BotProfileDetails: Equatable, Sendable { let reply = try await client.call(.profilesSetAsset(name: profile.id, avatar: change), validateDispatch: validate(owner)) try ensureOwner(owner, client) guard reply["ok"].flag == true, reply["asset"].text == "avatar" else { throw BotFailure.unsupported } - // The shared store holds thumbnails only; the full picture stays with this editor. avatarStore.setImage(avatar.flatMap(BotAvatarStore.thumbnail), connectionID: connection.id, profile: profile.id, revision: lookRevision) - // The look revision stays, so the Bot widget's copy is current only until deleted here (#1643). BotWidgetPublisher.shared.forgetAvatar(server: server, profile: profile.id) avatarChange = .unchanged; outcomes[.avatar] = .saved } diff --git a/HermesMobile/Features/Bots/BotProfileEditorView.swift b/HermesMobile/Features/Bots/BotProfileEditorView.swift index 2ef4de734..b2e7ae829 100644 --- a/HermesMobile/Features/Bots/BotProfileEditorView.swift +++ b/HermesMobile/Features/Bots/BotProfileEditorView.swift @@ -10,7 +10,6 @@ import SwiftUI @State private var showsExpressions = false @State private var showsDescribe = false @State private var imageError: String? - /// What the face should do about the last edit; see `BotCreateView`. @State private var cue: BotFaceCue? @Environment(\.scenePhase) private var scenePhase @@ -54,8 +53,6 @@ import SwiftUI .task { if editor.state == .idle { await editor.load() } } .onDisappear { editor.close() } .onChange(of: scenePhase) { - // Control Center and banners (`.inactive`) keep the connection (#902); only an - // editor without one reloads, and never over unsaved edits. if scenePhase == .background { editor.suspend() } else if scenePhase == .active, !editor.holdsConnection, @@ -185,7 +182,6 @@ import SwiftUI .padding(.top, 26).padding(.bottom, 12) } - /// The Contacts-style badge on the hero avatar: the one place a photo is chosen or removed. private var photoMenu: some View { Menu { Button { showsPhotoPicker = true } label: { Label("Choose Photo", systemImage: "photo.on.rectangle") } diff --git a/HermesMobile/Features/Bots/BotPromptMode.swift b/HermesMobile/Features/Bots/BotPromptMode.swift index fac391131..1931d7bb2 100644 --- a/HermesMobile/Features/Bots/BotPromptMode.swift +++ b/HermesMobile/Features/Bots/BotPromptMode.swift @@ -1,9 +1,5 @@ import Foundation -/// Bot-only actions. Send is the only choice while the bot is idle; the other -/// three are offered when a send lands on a working bot. Queue explicitly -/// bypasses the host's configurable busy input behavior, which could otherwise -/// interrupt work started by Desktop. enum BotPromptMode: CaseIterable, Hashable, SendChoice { case send, steer, queue, redirect @@ -25,12 +21,8 @@ enum BotPromptMode: CaseIterable, Hashable, SendChoice { } } - /// Whether this mode starts a fresh turn. Only there will the host expand a - /// skill invocation, so it is also the only place the `/` panel opens. var startsTurn: Bool { self == .send || self == .queue } - /// Send and Queue both submit a queued prompt; see `HermesCall.promptSubmit`. `fence` goes - /// only to a canonical host (#1602), and so do `images` (#1644), which only those two carry. func call(runtime: String, text: String, fence: HermesCall.Fence? = nil, images: [BotUploadedImage] = [], titlePreview: String? = nil) -> HermesCall { switch self { @@ -40,13 +32,8 @@ enum BotPromptMode: CaseIterable, Hashable, SendChoice { } } - /// What the host's reply says about this prompt. A `canonical` host answers a send with an - /// admission receipt (#1602), `queued` even on an idle session, where it starts at once: - /// `turnRunning` tells a follow-up from a start. A reply naming no admission, or any other - /// receipt, claims nothing ran. func outcome(_ reply: BotJSON, turnRunning: Bool = false, canonical: Bool = false) -> BotPromptOutcome { if canonical, self == .send || self == .queue { - // A stop phrase in a voice chat ends voice mode and admits nothing. if reply["voice_stopped"].flag == true { return .voiceStopped } guard reply["admission_id"].text?.isEmpty == false else { return .unknown } switch reply["status"].text { @@ -63,15 +50,12 @@ enum BotPromptMode: CaseIterable, Hashable, SendChoice { case (.send, "streaming"), (.queue, "streaming"): return .started case (.steer, "rejected"), (.redirect, "rejected"): return .rejected default: - // The installed submit handler recognizes voice-stop phrases before - // starting a turn. That acknowledgment must not claim a prompt ran. if (self == .send || self == .queue), reply["voice_stopped"].flag == true { return .voiceStopped } return .unknown } } func definitelyRejected(_ error: Error) -> Bool { - // A newer turn refused it before anything took effect. if error is HermesFenceRefusal { return true } guard case BotFailure.rejected(let code) = error else { return false } if [401, 403, 4001, 4090, -32601, -32602].contains(code) { return true } @@ -79,9 +63,6 @@ enum BotPromptMode: CaseIterable, Hashable, SendChoice { } } -/// What the host said about a prompt. Only `rejected` and `unknown` change what -/// the app does; the rest confirm admission and clear the draft. Nothing here is -/// shown: the transcript's own activity is the receipt. enum BotPromptOutcome: Equatable { case guidanceQueued, redirected, redirectQueued, followUpQueued, started, voiceStopped, rejected, unknown } diff --git a/HermesMobile/Features/Bots/BotRoomAction.swift b/HermesMobile/Features/Bots/BotRoomAction.swift index feb9bbffd..3590cf20d 100644 --- a/HermesMobile/Features/Bots/BotRoomAction.swift +++ b/HermesMobile/Features/Bots/BotRoomAction.swift @@ -1,7 +1,5 @@ import Foundation -/// Preserve the exact approval identity. Unknown or incomplete actions remain -/// visible as Desktop attention, never as a partially addressable command. struct BotRoomAction: Equatable, Identifiable { struct Identity: Hashable { let kind: String @@ -13,12 +11,9 @@ struct BotRoomAction: Equatable, Identifiable { let id: Identity let approval: BotApprovalRequest? var isRetry: Bool { id.kind == "retry" && id.task.map(BotRoomRPC.validID) == true } - /// A canonical host's task whose outcome is unknown (#1605): it offers Discard, never Retry. var isDiscard: Bool { id.kind == "discard" && id.task.map(BotRoomRPC.validID) == true && attempt != nil } var isAnswerable: Bool { approval != nil || isRetry || isDiscard } - /// The method that answers it, which the room's capabilities must list. var method: String { isRetry ? "groups.retry" : isDiscard ? "groups.discard" : "groups.approve" } - /// The member and generation a canonical host fences this task by, when the action names both. private var attempt: HermesCall.RoomAttempt? { guard let member = id.member, let generation = id.generation else { return nil } let attempt = HermesCall.RoomAttempt(memberID: member, executionGeneration: generation) @@ -33,8 +28,6 @@ struct BotRoomAction: Equatable, Identifiable { let task = id.task, BotRoomRPC.validID(task), let generation = id.generation, generation > 0, let request = id.request, BotRoomRPC.validID(request), var body = value["approval"].fields { body["request_id"] = .string(request) - // Rooms offer only once/deny. An absent list is an older host's default; a present - // value that is not a list is malformed and keeps BotApprovalRequest's Deny-only rule. if let present = body["choices"] { if let list = present.list { body["choices"] = .array(list.filter { $0 == .string("once") || $0 == .string("deny") }) } } else { @@ -44,8 +37,6 @@ struct BotRoomAction: Equatable, Identifiable { } else { approval = nil } } - /// A retry or a confirmed discard without a choice, or an approval answered with a choice the - /// host offered. func call(roomID: String, choice: BotApprovalRequest.Choice?) -> HermesCall? { guard let task = id.task else { return nil } if isRetry, choice == nil { return .groupsRetry(roomID: roomID, taskID: task, attempt: attempt) } diff --git a/HermesMobile/Features/Bots/BotRoomComposerView.swift b/HermesMobile/Features/Bots/BotRoomComposerView.swift index adb9a069c..35a5ab7c6 100644 --- a/HermesMobile/Features/Bots/BotRoomComposerView.swift +++ b/HermesMobile/Features/Bots/BotRoomComposerView.swift @@ -1,6 +1,5 @@ import SwiftUI -/// The Bot editor and mention panel, with only the controls rooms support. struct BotRoomComposerView: View { @Bindable var reader: BotRoomReader var threadID: String? = nil @@ -39,7 +38,6 @@ struct BotRoomComposerView: View { text: Binding(get: { reader.draft(in: threadID) }, set: { reader.setDraft($0, in: threadID) }), selection: $selection, isFocused: $focused, inputHeight: $inputHeight, measuredHeight: $measuredHeight, isDisabled: !reader.mayEditDraft(in: threadID), isCollapsed: !focused, - // Send only: a room has no send choices, and its Stop halts every bot in it. keyboardCommands: ComposerKeyboardCommands(send: reader.maySend(in: threadID) ? .init(title: String(localized: "Send Message"), perform: send) : nil), verticalPadding: 12, chipSkills: [], chipFilePaths: [], quotes: [], @@ -86,8 +84,6 @@ struct BotRoomComposerView: View { private func send() { Task { await reader.send(threadID: threadID) } } } -/// Room handles are server routing keys. Friendly names only help searching; -/// unlike a bot's chat, room sends must never append an identification annotation. enum BotRoomMentions { static func completions(room: BotGroupRoom, query: String) -> [BotMentions.Completion] { let members = room.members.compactMap { member -> BotMentions.Completion? in @@ -109,8 +105,6 @@ enum BotRoomMentions { struct BotRoomActionCard: View { let reader: BotRoomReader let action: BotRoomAction - /// The action whose Discard is being confirmed, kept apart from `action`: the room's cards are - /// keyed by position, so a poll can hand this card another task while the sheet is open. @State private var confirmingDiscard: BotRoomAction? var body: some View { if let approval = action.approval { @@ -127,7 +121,6 @@ struct BotRoomActionCard: View { if action.isRetry { Button("Retry") { Task { await reader.act(action) } }.disabled(!reader.mayAct(action)) } else if action.isDiscard { - // A canonical host lost this task's reply in a restart (#1605); discarding is permanent. Text("Hermes restarted while this bot was replying, so its reply is lost.") .font(AppFont.callout()) Button("Discard", role: .destructive) { confirmingDiscard = action } @@ -155,27 +148,16 @@ struct BotRoomActionCard: View { } } -/// The one thing worth a pill above a room's composer, highest priority first. A -/// request outranks an error because it has somewhere to go; an error outranks -/// recovery because the user can read it. `ChatView` borrows `.updateSignIn` (#942). enum BotComposerPill: Equatable { - /// A blocking request with a card in the transcript to jump to. case request(String) - /// A blocking request the phone cannot show; the line is the whole message. case notice(String) case error(String) case reconnect - /// Reconnect's slot after the host refused the saved password: reconnecting - /// would only send it again, so the button opens the sign-in form instead. case updateSignIn case retrySend var errorText: String? { if case .error(let text) = self { return text }; return nil } - /// Rooms' host exposes no turn start time, so routine working/connecting states - /// stay quiet; requests and recovery remain reachable. `needsSignIn` holds Update - /// sign-in in place even while a background leaves the room idle, because the room - /// never signs in again with a rejected password. static func room(link: BotRoomReader.Link, blocked: Bool, hasActions: Bool, mayRetry: Bool, needsSignIn: Bool = false, errorText: String?) -> BotComposerPill? { if let errorText { return .error(errorText) } @@ -190,8 +172,6 @@ enum BotComposerPill: Equatable { } } -/// One centered capsule with material and no motion of its own. Request, Reconnect, -/// Update sign-in and Retry send are buttons; an error is tappable to dismiss. struct BotComposerPillView: View { let pill: BotComposerPill var onReconnect: () -> Void = {} diff --git a/HermesMobile/Features/Bots/BotRoomCreator.swift b/HermesMobile/Features/Bots/BotRoomCreator.swift index b9e9b2f51..2f587f9ed 100644 --- a/HermesMobile/Features/Bots/BotRoomCreator.swift +++ b/HermesMobile/Features/Bots/BotRoomCreator.swift @@ -1,15 +1,10 @@ import Foundation import Observation -/// One sheet owns one immutable create attempt. A deliberate retry uses the same -/// room ID and payload, including after backgrounding or losing the socket. @MainActor @Observable final class BotRoomCreator { let connection: BotConnection let server: URL let roster: [BotProfile] - /// The Profiles a canonical host can seat (`BotRoomCapabilities.seatableProfiles`, #1605); nil - /// on a dashboard, which seats its whole roster. No other bot is offered or sent. Create - /// refreshes it from the host's latest answer. private(set) var seatable: Set? private(set) var selected: [BotProfile] = [] var name = "Group Chat" @@ -36,11 +31,8 @@ import Observation var locked: Bool { attempt != nil } var mayContinue: Bool { (2...6).contains(selected.count) } var mayCreate: Bool { !busy && created == nil && mayContinue && BotRoomRPC.validName(name) } - /// Whether the host can seat `bot`. func seats(_ bot: BotProfile) -> Bool { seatable?.contains(bot.id) ?? true } - /// The host can't seat some bot the list would otherwise show, so the list says it left some out. var leavesOutBots: Bool { roster.contains { !$0.hidden && !seats($0) } } - /// Fewer than two bots can join, so no group can be made. var tooFewToSeat: Bool { seatable != nil && roster.filter(seats).count < 2 } var remaining: [BotProfile] { let filter = query.trimmingCharacters(in: .whitespacesAndNewlines) @@ -58,7 +50,6 @@ import Observation selected.removeAll { $0.id == bot.id } } static func member(_ bot: BotProfile) -> HermesCall.RoomMember { - // profiles.list at the compatibility pin exposes no separate handle. HermesCall.RoomMember(memberID: bot.id, profile: bot.id, handle: bot.id, displayName: bot.displayName) } var preview: BotGroupRoom { @@ -83,9 +74,6 @@ import Observation try check(owner, client) guard caps.enabled, caps.methods.contains("groups.create"), caps.authority != nil else { throw BotFailure.unsupported } authority = caps.authority - // Rechecked at create: a bot the host stopped seating since the sheet opened is never sent. - // The host refuses such a member before it looks for the room, so a Try Again reads the - // rooms instead: the room it made, or an unlocked choice when it made none. if let fresh = caps.seatableProfiles, !selected.allSatisfy({ fresh.contains($0.id) }) { if let attempt { let rooms = try await BotRoomList.read(client) { try self.check(owner, client) } @@ -117,13 +105,10 @@ import Observation do { let rooms = try await BotRoomList.read(client) { try self.check(owner, client) } try check(owner, client); onReconciled(rooms) - // Another client can rename the room between a lost create - // reply and retry. Its permanent ID and frozen members still - // identify our successful creation; the name may differ. if let attempt, let room = Self.room(made: attempt, in: rooms, authority: authority) { created = room; message = nil } - } catch { /* Keep the original rejection; a failed read is not success. */ } + } catch { } } } else { message = dispatched ? String(localized: "Outcome unknown. Try Again checks the same group creation; it will not create a second room.") : error.localizedDescription @@ -131,8 +116,6 @@ import Observation } } - /// The room `attempt` made, found in `rooms` by its permanent id, frozen members and authority; - /// its name may differ, since another client can rename it in between. private static func room(made attempt: HermesCall.RoomCreation, in rooms: [BotGroupRoom], authority: String?) -> BotGroupRoom? { guard let authority, let room = rooms.first(where: { $0.id == attempt.roomID }), room.authority == authority, room.members.count == attempt.members.count, @@ -152,8 +135,6 @@ import Observation } } -/// A complete active-room read is needed before deciding an uncertain disband -/// removed its room. One missing page must never look like successful deletion. enum BotRoomList { @MainActor static func read(_ client: any BotTransport, check: () throws -> Void) async throws -> [BotGroupRoom] { var rooms: [BotGroupRoom] = [], offset = 0 diff --git a/HermesMobile/Features/Bots/BotRoomProfileView.swift b/HermesMobile/Features/Bots/BotRoomProfileView.swift index c99b973e1..f1b6d7426 100644 --- a/HermesMobile/Features/Bots/BotRoomProfileView.swift +++ b/HermesMobile/Features/Bots/BotRoomProfileView.swift @@ -5,7 +5,6 @@ import SwiftUI @Bindable var reader: BotRoomReader let roster: [BotProfile] let avatars: [String: UIImage] - /// Leaves the room for the inbox's sign-in form, after the host refused the password. var onUpdateSignIn: () -> Void = {} @State private var name = "" @State private var confirmingDisband = false @@ -51,7 +50,6 @@ import SwiftUI if reader.finishingStop { Text("Finishing stop…").font(AppFont.callout()) } if reader.link == .stopped { if let error = reader.errorMessage { Text(error).font(AppFont.callout()) } - // Reconnecting would only send the refused password again (#884). if reader.needsSignIn { Button("Update sign-in", action: onUpdateSignIn) } else { @@ -84,8 +82,6 @@ import SwiftUI } .onChange(of: reader.room.name) { if !editingName { name = reader.room.name } } .onChange(of: scenePhase) { - // Control Center and banners (`.inactive`) keep the room live (#902); the - // background stops it (#533), and only a stopped room reopens. guard visible else { return } switch scenePhase { case .background: reader.leave(owner: owner) @@ -94,7 +90,6 @@ import SwiftUI } } .onDisappear { visible = false; reader.leave(owner: owner) } - // A lost room reconnects as the network returns rather than on its backoff (#1372). .onChange(of: NetworkPathMonitor.shared.changeCount) { if visible { reader.networkPathDidChange() } } } private func commitName() { diff --git a/HermesMobile/Features/Bots/BotRoomReader.swift b/HermesMobile/Features/Bots/BotRoomReader.swift index 936216209..d318a5820 100644 --- a/HermesMobile/Features/Bots/BotRoomReader.swift +++ b/HermesMobile/Features/Bots/BotRoomReader.swift @@ -2,10 +2,6 @@ import CryptoKit import Foundation import Observation -/// One visible room owns one socket. Closing invalidates replies before -/// cancelling transport; backgrounding keeps the loaded window but stops all reads. -/// A lost connection reconnects on its own a few times on backoff, at once when the network -/// returns, and never while offline (#1372); it never resends a message or command. @MainActor @Observable final class BotRoomReader { enum Link: Equatable { case idle, connecting, live, stopped } let key: BotRoomKey @@ -18,10 +14,6 @@ import Observation private(set) var status = BotRoomStatus(.null) private(set) var link = Link.idle private(set) var errorMessage: String? - /// True after the host refused the saved username or password (`.rejected(401)`). - /// The room offers Update sign-in instead of Reconnect. It stays set for this - /// reader's life, because the reader only signs in with the record it was built - /// from; the fix goes through the inbox, which opens the room with a new reader. private(set) var needsSignIn = false private(set) var hasEarlier = false private(set) var loadingEarlier = false @@ -43,9 +35,6 @@ import Observation private(set) var busy = false private(set) var awaitingStop = false private(set) var inactiveActions = Set() - /// The last send, Stop or approval the room accepted, for the view's haptic. - /// Rooms play no turn completion: polled state cannot say which member's - /// work just finished, or when. private(set) var feedback: BotFeedback? struct Send: Equatable { let text: String @@ -56,7 +45,6 @@ import Observation self.text = text; eventID = UUID().uuidString self.threadID = threadID ?? UUID().uuidString; contextThreadID = threadID } - /// Pinned gateway user_event_id: SHA256 of the client retry key. var serverEventID: String { "user:" + SHA256.hash(data: Data(eventID.utf8)).map { String(format: "%02x", $0) }.joined() } @@ -100,11 +88,6 @@ import Observation } } - /// Room and profile share state, but each visible screen claims async ownership. - /// Navigation callbacks can arrive in either order; the old screen cannot close the new socket. - /// Once the host has refused this reader's password, a reopen only restores the saved - /// history and stops: the reader signs in with the record it was built from, so it - /// never sends that password again (#884). func open(owner: UUID? = nil, preservingLoadedHistory: Bool = false) async { viewOwner = owner suspend() @@ -117,7 +100,6 @@ import Observation log = BotRoomLog(); events = []; threads = []; hasEarlier = false; hasRecentLog = false } recentOwner = cache.recent.begin(.init(key)) - // Checked before `makeWire`, which can retire a newer shared connection. if needsSignIn { await historyRemoval?.value let cached = try? await cache.roomHistory(key) @@ -177,7 +159,6 @@ import Observation } catch { fail(error, client) } } - /// Independently callable for scripted tests; the timer only schedules reads. func poll() async { guard let client = wire, link == .live else { return } do { @@ -210,8 +191,6 @@ import Observation viewOwner = nil } - /// The device's network path changed: a reconnect waiting on its backoff runs now if the - /// network is back, or holds until it is. The room's screens call it while on screen. func networkPathDidChange() { reconnect.networkPathDidChange() } func suspend() { @@ -239,8 +218,6 @@ import Observation link == .live && !uncertainDisband && !foreignAuthority && capabilities.authority != nil && room.authority == capabilities.authority } var showsComposer: Bool { !foreignAuthority } - /// A new room opens on its members instead of an empty transcript: live, with - /// no earlier history to load and no message from the user or a member yet. var showsWelcome: Bool { link == .live && !hasEarlier && !BotRoomEvent.hasConversation(in: events) } var showsStop: Bool { status.working || status.stopping > 0 || awaitingStop } var mayStop: Bool { allows("groups.stop") && !busy && !awaitingStop && status.stopping == 0 && status.stoppable > 0 } @@ -256,7 +233,6 @@ import Observation private func allows(_ method: String) -> Bool { canParticipate && capabilities.methods.contains(method) } func mayAct(_ action: BotRoomAction) -> Bool { !busy && isPendingAndAnswerable(action) } - /// Pending ownership outlives the temporary command lock on the room's buttons. private func isPendingAndAnswerable(_ action: BotRoomAction) -> Bool { action.isAnswerable && !inactiveActions.contains(action.id) && status.actions.contains(action) && allows(action.method) @@ -290,8 +266,6 @@ import Observation result["tombstone"]["disbanded_at"].number != nil else { throw BotFailure.unsupported } self.finishDisband() }) - // A disconnect may invalidate the write's continuation. Recover with reads - // only while still visible; background/close leaves link idle. if viewOwner == owner && uncertainDisband && link == .stopped { await open(owner: owner) } } @@ -307,8 +281,6 @@ import Observation return false } - /// Overview sends start a thread; detail replies continue its current discussion. - /// Only the dedicated retry button reuses an uncertain send's id and payload. func send(retry: Bool = false, threadID: String? = nil) async { guard retry ? mayResend(in: threadID) : maySend(in: threadID) else { return } let request = retry ? uncertainSend(in: threadID)! : Send(text: draft(in: threadID), threadID: threadID) @@ -375,8 +347,6 @@ import Observation }) } - /// Ownership and the pending tuple are checked in BotClient's actual socket - /// write closure. A lost reply never starts another command. private func command(_ call: HermesCall, validate: @escaping () throws -> Void, accept: (BotJSON) throws -> Void) async { guard let client = wire, allows(call.method), !busy else { sending = nil; return } @@ -400,7 +370,6 @@ import Observation commandMessage = rejection.localizedDescription if rejection.reason == "authority_conflict" { foreignAuthority = true } if rejection.expired { discardHistory(); close(); onExpired(); return } - // A rejected retry does not erase the uncertainty of the original send. } else if dispatched { if let sending { uncertainSends[sending.contextThreadID ?? ""] = sending } commandMessage = String(localized: "Outcome unknown. Reconnect to check the room. Commands are never resent automatically.") @@ -412,8 +381,6 @@ import Observation do { if try await reconcileDisband(client) { return } } catch { fail(error, client); return } } - // Read after every acknowledgment or rejection (including 5118/5119). - // Inactive tuples stay inert even if a stale server snapshot repeats them. await poll() } @@ -446,8 +413,6 @@ import Observation return updated.latestSeq } - /// History windows stop at their old boundary. Live/open replay drains all - /// pages, including pages containing only unknown kinds. Reject stalled cursors. private func readPages(_ client: any BotTransport, since: Int, through: Int? = nil) async throws -> [BotJSON] { var cursor = since var pages: [BotJSON] = [] @@ -463,9 +428,6 @@ import Observation guard next > cursor else { throw BotFailure.unsupported } cursor = next } - // Commit the complete contiguous window together. Saving earlier pages one - // at a time would temporarily leave a gap before the already-cached window. - // Storage is best-effort; failures never stop live reading. let projection = BotJSON.object([ "events": .array(pages.flatMap { $0["events"].list ?? [] }), "cursor": pages.last?["cursor"] ?? .number(Double(since)) @@ -486,7 +448,6 @@ import Observation return moved } - /// Shows the disk history when `open` found no recent window to restore. private func restore(_ cached: BotHistoryCache.Snapshot?) { guard let cached, !hasRecentLog else { return } var restored = BotRoomLog() @@ -496,8 +457,6 @@ import Observation } private func publishLog() { - // A poll can race the send acknowledgment. Do not publish our own pending - // message as sent until the RPC result has been validated. let pendingIDs = Set((Array(uncertainSends.values) + [sending].compactMap { $0 }).map(\.serverEventID)) let visible = log.events.filter { event in event.kind != "message.user" || !pendingIDs.contains(event.eventID ?? "") @@ -509,7 +468,6 @@ import Observation } private func saveRecentTranscript() { - // Pending send bubbles stay private until their acknowledgment is known. guard link == .live, !busy, !uncertainDisband, let recentOwner else { return } cache.recent.save(log.recentWindow(), for: .init(key), owner: recentOwner) } @@ -518,7 +476,6 @@ import Observation let cache = cache, key = key cache.recent.remove { $0 == .init(key) } recentOwner = nil - // Deletion intentionally outlives the screen; it never mutates view state. historyRemoval = Task { try? await cache.removeRoom(key) } } @@ -528,8 +485,6 @@ import Observation errorMessage = error.localizedDescription needsSignIn = error as? BotFailure == .rejected(401) if let failure = error as? BotRoomFailure, failure.expired { discardHistory(); close(); onExpired() } - // Only a lost connection or a passing refusal (a tunnel's 502, a rate limit) heals on - // its own; the screen that owns the room reopens it, keeping the loaded history. let heals = switch error as? BotFailure { case .transport: true case .rejected: BotConnectionAdvice.isRetryable(error) diff --git a/HermesMobile/Features/Bots/BotRoomView.swift b/HermesMobile/Features/Bots/BotRoomView.swift index 6a0fa8b0d..dd7166556 100644 --- a/HermesMobile/Features/Bots/BotRoomView.swift +++ b/HermesMobile/Features/Bots/BotRoomView.swift @@ -20,7 +20,6 @@ import SwiftUI private var followsLatest: Bool { followLatch.isFollowing } let roster: [BotProfile] let avatars: [String: UIImage] - /// Leaves the room for the inbox's sign-in form, after the host refused the password. let onUpdateSignIn: () -> Void init(reader: BotRoomReader, roster: [BotProfile], avatars: [String: UIImage], threadID: String? = nil, sequence: Int? = nil, onUpdateSignIn: @escaping () -> Void = {}) { @@ -35,15 +34,8 @@ import SwiftUI let hasHiddenEvents = start > 0 let showsWelcome = threadID == nil && reader.showsWelcome ScrollView { - // At least as tall as the visible transcript while a new room shows - // its welcome, which centres it; taller, and scrolling, only when - // the welcome is (at accessibility text sizes). ZStack { if showsWelcome { Color.clear.containerRelativeFrame(.vertical) } - // Eager over a bounded window: member replies are - // hosted selection documents, and a lazy stack places unbuilt rows - // from an estimate, so the jump to a search hit missed on a cold - // open (issue #553). The window keeps the build to the newest page. VStack(spacing: 16) { if !showsThreadOverview && (hasHiddenEvents || reader.hasEarlier) { Button("Load earlier") { loadEarlier(proxy: proxy) } @@ -60,7 +52,6 @@ import SwiftUI BotRoomTranscriptRow(event: $0, isOverview: threadID == nil) }) { row in let event = row.event - // Thread identity survives new replies and activity reordering. if threadID == nil, let thread = reader.threads.first(where: { $0.latest.seq == event.seq }) { Button { selectedThread = thread.id } label: { BotRoomThreadPreview(thread: thread, room: reader.room) @@ -92,7 +83,6 @@ import SwiftUI Color.clear.frame(height: 1).id("room-bottom") } .padding(16) - // Centred in the reading column; the scroll view stays full width. .frame(maxWidth: ChatReadingWidth.maximumWidth(horizontalPadding: 16)) .frame(maxWidth: .infinity) .background { @@ -119,8 +109,6 @@ import SwiftUI .task(id: threadID == nil ? nil : availableSearchSequence) { guard threadID != nil, let sequence = availableSearchSequence else { return } window.reveal(sequence, in: transcriptEvents, overview: showsThreadOverview) - // A pushed destination lays out after the overview's synchronous - // search callback. Wait for those materialized rows before jumping. await Task.yield() guard !Task.isCancelled else { return } handleFollowEvent(.userScrollBegin) @@ -192,8 +180,6 @@ import SwiftUI if scenePhase == .active { await reader.open(owner: owner, preservingLoadedHistory: true) } } .onChange(of: scenePhase) { - // Control Center and banners (`.inactive`) keep the room live (#902); the - // background stops it (#533), and only a stopped room reopens. guard visible else { return } switch scenePhase { case .background: reader.leave(owner: owner, preservingLoadedHistory: true) @@ -202,7 +188,6 @@ import SwiftUI } } .onDisappear { visible = false; reader.leave(owner: owner, preservingLoadedHistory: true) } - // A lost room reconnects as the network returns rather than on its backoff (#1372). .onChange(of: NetworkPathMonitor.shared.changeCount) { if visible { reader.networkPathDidChange() } } .onChange(of: reader.feedback) { _, feedback in if let feedback { ChatHaptics.botFeedback(feedback.event, isEnabled: isHapticsEnabled) } @@ -216,8 +201,6 @@ import SwiftUI private var showsThreadOverview: Bool { threadID == nil && !reader.threads.isEmpty } - /// Thread previews stand in for their latest event. Unthreaded history remains - /// readable, but never gains a fabricated reply target. private var transcriptEvents: [BotRoomEvent] { if let threadID { return reader.threads.first { $0.id == threadID }?.events ?? [] } return (reader.events.filter { $0.threadID == nil } + reader.threads.map(\.latest)) @@ -230,9 +213,6 @@ import SwiftUI private func seedWindow() { window.seed(transcriptEvents, live: reader.link == .live, overview: showsThreadOverview) } - /// Reveals a page of events already in memory, or fetches one from the room - /// when none are hidden. Chronological detail preserves its first row; - /// descending overview appends below the reader without changing the offset. private func loadEarlier(proxy: ScrollViewProxy) { handleFollowEvent(.userScrollBegin) let firstEvent = showsThreadOverview ? nil @@ -274,8 +254,6 @@ import SwiftUI } } -/// Stable thread identities in the overview, exact sequence identities in detail -/// and unthreaded history. A reply must not replace its overview row's identity. struct BotRoomTranscriptRow: Identifiable { enum ID: Hashable { case thread(String), event(Int) } let event: BotRoomEvent @@ -327,23 +305,11 @@ private struct BotRoomThreadPreview: View { } } -/// The room events BotRoomView builds: the newest page when the room opens, -/// anchored by sequence number because room history is prepended. History the -/// reader loads stays hidden until asked for, and new events always show, so -/// neither shifts what is on screen. Load earlier reveals hidden events in -/// pages before the room fetches more. struct BotRoomTranscriptWindow: Equatable { static let pageSize = 50 private var oldestShown: Int? - // Overview rows reorder when threads receive replies, so their expansion - // cannot be anchored to a latest-event sequence that can disappear. private var overviewCount = Self.pageSize - /// Index of the first shown event in `events`, which are sorted by sequence. - /// An anchor outside the events (a reconnect restored a trimmed transcript, - /// or the room restarted) falls back to the newest page. `keeping` widens the - /// window to a search hit that is present, so its row is built by the time - /// the jump runs (#553). func start(in events: [BotRoomEvent], keeping sequence: Int? = nil, overview: Bool = false) -> Int { let newestPage = max(0, events.count - Self.pageSize) let start = overview ? max(0, events.count - overviewCount) : oldestShown.flatMap { oldest in @@ -353,10 +319,6 @@ struct BotRoomTranscriptWindow: Equatable { return min(start, hit) } - /// Anchors the window on the newest page once the room is live, and again - /// after the room empties (closed) or its events no longer cover the anchor. - /// Until then `start` follows the newest page, so the open-time catch-up - /// after a stale cache restore is not built in full. mutating func seed(_ events: [BotRoomEvent], live: Bool, overview: Bool = false) { guard !events.isEmpty else { oldestShown = nil; overviewCount = Self.pageSize; return } guard !overview else { return } @@ -371,7 +333,6 @@ struct BotRoomTranscriptWindow: Equatable { return (first.seq...last.seq).contains(sequence) } - /// Keeps a search hit shown after its jump lands. mutating func reveal(_ sequence: Int, in events: [BotRoomEvent], overview: Bool = false) { guard !events.isEmpty else { return } if overview { @@ -381,7 +342,6 @@ struct BotRoomTranscriptWindow: Equatable { } } - /// Shows up to one more page of hidden events; false when none are hidden. mutating func showEarlier(in events: [BotRoomEvent], overview: Bool = false) -> Bool { let start = start(in: events, overview: overview) guard start > 0 else { return false } @@ -425,7 +385,6 @@ private struct BotRoomEventView: View { Text(event.sender(in: room)).font(AppFont.caption()).foregroundStyle(.appSecondary) ResponseTextSelection(identity: messageText, collectsGlyphs: responseIsVisible) { MarkdownRenderer(content: messageText) - // The bubble's fill is translucent, so no solid fade matches it. .environment(\.markdownTableEdgeFadeColor, nil) } .onGeometryChange(for: Bool.self) { geometry in @@ -438,8 +397,6 @@ private struct BotRoomEventView: View { Spacer(minLength: 20) } .accessibilityElement(children: .combine) - // Every member message is a finished reply, so each one is timed. - // Under the bubble, past the avatar, which stays level with the bubble. footer.padding(.leading, 34) } } else { @@ -450,7 +407,6 @@ private struct BotRoomEventView: View { private var messageText: String { event.payload["text"].text ?? "" } - /// Rooms take the shared meta row with the time only; Copy stays in the long-press menu. @ViewBuilder private var footer: some View { if showsTimestamps, let timestamp = event.timestamp, timestamp > 0, @@ -497,9 +453,6 @@ struct BotRoomMemberAvatar: View { } } -/// What a new room opens on: every member's face and name, then, when this -/// phone can write to the room, the invitation to speak. One VoiceOver element. -/// Faces stay still, like the room's other faces (#517). struct BotRoomWelcomeView: View { let room: BotGroupRoom let roster: [BotProfile] @@ -510,7 +463,6 @@ struct BotRoomWelcomeView: View { var body: some View { VStack(spacing: 20) { if dynamicTypeSize.isAccessibilitySize { - // Stacked, so full names fit at accessibility text sizes. VStack(alignment: .leading, spacing: 14) { ForEach(room.members) { member in HStack(spacing: 14) { @@ -550,7 +502,6 @@ struct BotRoomWelcomeView: View { : String(localized: "Group members: \(names).") } - /// Rows of up to three, balanced so four members make two rows of two. private static func rows(of members: [BotGroupRoom.Member]) -> [ArraySlice] { guard !members.isEmpty else { return [] } let rowCount = (members.count + 2) / 3 @@ -559,7 +510,6 @@ struct BotRoomWelcomeView: View { } } -/// Uses the inbox row's avatar/name/time layout; identity is supplied by its caller. struct BotRoomInboxRow: View { let room: BotGroupRoom let roster: [BotProfile] diff --git a/HermesMobile/Features/Bots/BotScreenCard.swift b/HermesMobile/Features/Bots/BotScreenCard.swift index 029c5b9b0..6718c2239 100644 --- a/HermesMobile/Features/Bots/BotScreenCard.swift +++ b/HermesMobile/Features/Bots/BotScreenCard.swift @@ -1,20 +1,12 @@ import SwiftUI -/// Whether a Hermes chat's latest turn used the bot's screen (#1632, #1633), from -/// `HermesChatTurnCoordinator.screenUse`. enum BotScreenUse: Equatable { - /// The running turn has called `computer_use`. case active - /// The turn that used it is over, or its stream dropped. case ended - /// The tool the host names on `tool.start` when the bot acts on its screen. A browser tool - /// doesn't count: it doesn't mean the screen is in use. static let toolName = "computer_use" } -/// Opens a chat's Screen from its card or ⌘⇧S, taking over once it is live when `takingOver`. A -/// reference, like `HermesUpdateSignInAction`, so a pass of the Bots home invalidates no chat. final class BotScreenOpener { var handler: (_ takingOver: Bool) -> Void = { _ in } @@ -22,12 +14,9 @@ final class BotScreenOpener { } extension EnvironmentValues { - /// Set by the Bots home only while its own Screen entries show, and for a session chat by - /// `SessionScreenModifier` behind the same gate, so nil hides the chat's card and header button. @Entry var openBotScreen: BotScreenOpener? = nil } -/// Installs `openBotScreen` for a bot's chat while `isOffered`, keeping one opener in state. struct BotScreenOpenerModifier: ViewModifier { let isOffered: Bool let handler: (_ takingOver: Bool) -> Void @@ -39,15 +28,9 @@ struct BotScreenOpenerModifier: ViewModifier { } } -/// A session chat's Screen (#1633): its own Profile's, on the chat's server and connection, never -/// the Bots home's selected bot. Applied where each session `ChatView(hermesSession:)` is built, -/// inside its `.id`, it installs `openBotScreen` behind the Bots home's gate (the server's switch, -/// and no -32601 on `display.*`) and presents the Screen. Turning the switch off closes it. struct SessionScreenModifier: ViewModifier { let chat: HermesSessionChat @AppStorage private var isScreenEnabled: Bool - /// The host answered `display.*` with -32601. The Bots home keeps its own, so the card may - /// show once more here before it hides. @State private var hostLacksScreen = false @State private var presentation: Presentation? @State private var opener = BotScreenOpener() @@ -79,30 +62,19 @@ struct SessionScreenModifier: ViewModifier { } } -/// ⌘⇧S's Screen (#1633): the chat on screen offers its card's opener here, and `HermexCommands` -/// reads it ahead of the scene's actions. A shared registry rather than a focused or environment -/// value, because a session pushed from a chat, from Archived or from Settings is a -/// `navigationDestination` no list's value reliably reaches. A Bot Chat offers the same Screen the -/// Bots home's own action would. @MainActor @Observable final class ScreenShortcut { static let shared = ScreenShortcut() private(set) var opener: BotScreenOpener? - /// A chat is on screen, with or without a Screen to open. While one is, the Bots home's - /// selected bot isn't what ⌘⇧S opens. private(set) var hasChat = false - /// The `ChatView` on screen: only it withdraws, so a chat popping back into view before the - /// pushed one leaves keeps its own. @ObservationIgnored private var owner: UUID? - /// The chat `owner` is on screen, offering `opener`, or nil while it has no Screen to open. func offer(_ opener: BotScreenOpener?, from owner: UUID) { self.owner = owner if !hasChat { hasChat = true } if self.opener !== opener { self.opener = opener } } - /// The chat `owner` left the screen. func withdraw(_ owner: UUID) { guard self.owner == owner else { return } self.owner = nil @@ -111,16 +83,12 @@ struct SessionScreenModifier: ViewModifier { } } -/// The line in a Hermes chat's transcript while the bot uses its screen and after (#1632, #1633), -/// with the Screen's two entries: watch it, or take it over. struct BotScreenCard: View { let use: BotScreenUse let open: () -> Void let takeOver: () -> Void var body: some View { - // One line while the label and both buttons fit whole; otherwise the buttons go under - // the label, so neither ever wraps inside a capsule. ViewThatFits(in: .horizontal) { HStack(spacing: 8) { label.fixedSize() diff --git a/HermesMobile/Features/Bots/BotSearchView.swift b/HermesMobile/Features/Bots/BotSearchView.swift index 2e567540b..e17aecae7 100644 --- a/HermesMobile/Features/Bots/BotSearchView.swift +++ b/HermesMobile/Features/Bots/BotSearchView.swift @@ -1,8 +1,5 @@ import SwiftUI -/// Search has its own presentation lifetime. Browsing the roster never opens a -/// conversation; only choosing a bot asks the inbox to navigate after dismissal. Messages in a -/// bot's chat are searched on the host (#1146); room messages come from this iPhone's cache. @MainActor struct BotSearchView: View { @Environment(\.scenePhase) private var scenePhase @Environment(\.dismiss) private var dismiss @@ -17,9 +14,7 @@ import SwiftUI @State private var botHits: [BotInbox.BotChatHit] = [] @State private var hitRequest: SearchRequest? @State private var searchError = false - /// Why the host's search of the bots' chats failed. @State private var botSearchError: String? - /// The saved-message search and the host's bot-chat search finish separately. @State private var isSearching = false @State private var isSearchingBots = false let cache: BotHistoryCache @@ -98,7 +93,6 @@ import SwiftUI onSelect(profile) dismiss() } label: { - // An id match names no message, so it shows as the bot. if let isFromUser = hit.isFromUser { botChatResult(hit, isFromUser: isFromUser, profile: profile) } else { @@ -108,7 +102,6 @@ import SwiftUI .buttonStyle(.plain) } } - // One "Searching…" at a time: the saved messages' first, then the host's. if isSearchingBots && !isSearching { status("Searching…") } else if let botSearchError, hitRequest == request { Text(verbatim: botSearchError).font(AppFont.callout()).foregroundStyle(.appSecondary) @@ -209,7 +202,6 @@ import SwiftUI .frame(maxWidth: .infinity, alignment: .leading).padding(20) } - /// A bot's chat the host matched (#1146): who wrote the message, and the host's snippet. private func botChatResult(_ hit: BotInbox.BotChatHit, isFromUser: Bool, profile: BotProfile) -> some View { HStack(spacing: 14) { BotAvatarView(profile: profile, avatar: inbox.avatars[profile.id], size: 44) @@ -252,9 +244,6 @@ import SwiftUI .contentShape(Rectangle()).accessibilityElement(children: .combine) } - /// Searches room messages saved on this iPhone, showing them as soon as the cache answers, then - /// each bot's chat on the host (#1146), whose hits and error arrive on their own. The cache's - /// bot rows are left out: a bot's chat is the host's to search. private func searchMessages() async { let captured = request hits = []; botHits = []; hitRequest = captured; searchError = false; botSearchError = nil diff --git a/HermesMobile/Features/Bots/BotSlashCommands.swift b/HermesMobile/Features/Bots/BotSlashCommands.swift index a6d685ca2..79c82cdb0 100644 --- a/HermesMobile/Features/Bots/BotSlashCommands.swift +++ b/HermesMobile/Features/Bots/BotSlashCommands.swift @@ -1,26 +1,11 @@ import Foundation -/// The `/name rest` a draft opens with. struct BotSlashInvocation: Equatable { let name: String let argument: String } -/// What a Bot connection's `commands.catalog` offers the composer, and how a -/// typed invocation is read back out of a draft. -/// -/// Skills only. The gateway never interprets a leading `/` in `prompt.submit`: -/// slash work lives in `slash.exec` and `command.dispatch`, and Bot Mode exposes -/// no general slash runner, so a command row would insert text nothing runs. enum BotSlashCatalog { - /// The skills in a `commands.catalog` reply, by name. - /// - /// The host answers in two halves: the `skills` keys say which entries are - /// skills, and the `pairs` rows carry every entry's description. A key that - /// also appears in `canon` or `commands` is dropped, because those are - /// registry, quick or plugin commands, which `command.dispatch` resolves - /// *ahead of* skills — and a `quick_commands` entry of type `exec` runs a - /// shell command on the host. Names are never invented from `pairs` alone. static func skills(from reply: BotJSON) -> [SkillSlashSuggestion] { guard let entries = reply["skills"].fields, !entries.isEmpty else { return [] } @@ -47,8 +32,6 @@ enum BotSlashCatalog { guard !name.isEmpty, name.rangeOfCharacter(from: .whitespacesAndNewlines) == nil, !shadowed.contains(key.lowercased()), !shadowed.contains(name.lowercased()) else { continue } - // Identity and the composer's chips both key off the slug, so a name - // without one, or a second name that slugs the same, cannot be drawn. let slug = SlashSkillFormatter.slug(for: name) guard !slug.isEmpty, seen.insert(slug).inserted else { continue } suggestions.append(SkillSlashSuggestion( @@ -58,7 +41,6 @@ enum BotSlashCatalog { return suggestions.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } } - /// The `/name rest` `draft` opens with, or `nil` when it opens with prose. static func invocation(in draft: String) -> BotSlashInvocation? { let draft = draft.trimmingCharacters(in: .whitespacesAndNewlines) guard draft.hasPrefix("/") else { return nil } diff --git a/HermesMobile/Features/Bots/BotsInboxView.swift b/HermesMobile/Features/Bots/BotsInboxView.swift index 4ade0893b..5d80351ae 100644 --- a/HermesMobile/Features/Bots/BotsInboxView.swift +++ b/HermesMobile/Features/Bots/BotsInboxView.swift @@ -1,10 +1,6 @@ import SwiftData import SwiftUI -/// The Bots inbox: pushed from a webui server's session list, or the Bots side of a Hermes -/// server's home (`HermesServerHome`), where it leads with the session list's header, whose -/// avatar replaces the Bot connection gear, and takes the home's bar (`HermesHomeChrome`): the -/// filter holds hidden bots and section order, and new chat makes a bot or a group chat. @MainActor struct BotsInboxView: View { @Environment(\.horizontalSizeClass) private var horizontalSizeClass @Environment(\.verticalSizeClass) private var verticalSizeClass @@ -13,15 +9,11 @@ import SwiftUI @AppStorage(HeaderLogoColor.storageKey) private var headerLogoColorHex = HeaderLogoColor.defaultHex let server: URL private let home: HermesHome? - /// The bot a deep link named, resolved here because this is where the live roster - /// is. Cleared once this inbox has settled, whether or not it matched (#554). @Binding private var pendingDestination: BotDestination? @State private var inbox: BotInbox @State private var showingSearch = false @State private var searchedProfile: (connectionID: UUID, profileID: String)? @State private var showingSetup = false - /// True while the form is open to replace a password the host refused; it opens - /// with the password field focused. @State private var updatingSignIn = false @State private var revision = UUID() @State private var editSelection: BotProfileEditSelection? @@ -32,26 +24,17 @@ import SwiftUI @State private var renamingRoom: BotGroupRoom? @State private var roomName = "" @State private var disbanding: BotGroupRoom? - /// The bot the "New Section" alert files, and the name being typed for it. @State private var filing: BotProfile? @State private var newSectionName = "" @State private var showingSectionOrder = false @State private var searchedRoom: BotRoomKey? @State private var searchedSequence: Int? @State private var roomSequence: Int? - /// One-line report for something that is no longer there: a disbanded room, or a - /// conversation a deep link named that the bot has since replaced. @State private var toast: String? - /// True once `open()` has returned at least once, so "no Bot connection" is a - /// settled answer to a held deep link rather than a not-loaded-yet one. @State private var hasSettled = false - /// The bot whose Screen is open (#1567), on the connection it opened with. @State private var screenTarget: BotScreenTarget? - /// The host answered a Screen's `display.*` with -32601, so the entries hide. @State private var hostLacksScreen = false - /// The server's Bot Screen switch. @AppStorage private var isScreenEnabled: Bool - /// The Profiles whose screen this iPhone still holds, for the banner. @State private var heldScreens: [String] = [] init( @@ -61,8 +44,6 @@ import SwiftUI self.init(server: server, pendingDestination: pendingDestination, home: nil, inbox: BotInbox(server: server)) } - /// A Hermes server's home, which keeps `inbox` across its switch, so a switch back shows the - /// roster at once (#709). Its sign-in form is reached through Settings there. init(server: URL, pendingDestination: Binding, home: HermesHome?, inbox: BotInbox) { self.server = server self.home = home @@ -71,7 +52,6 @@ import SwiftUI _isScreenEnabled = AppStorage(wrappedValue: false, BotScreenSettings.key(for: server)) } - /// An inbox the caller built, such as one on scripted wires. init(server: URL, inbox: BotInbox) { self.server = server home = nil @@ -168,12 +148,9 @@ import SwiftUI } } - /// The rows alone. The list, its sheets and its lifecycle each sit in their - /// own expression: together they were too much for the CI type-checker. private var list: some View { AppList(rows: .plain) { homeHeader - // Not gated on the switch: a hand-back that failed as it was turned off still needs a way out. if let connection = inbox.connection { ForEach(heldScreens, id: \.self) { profile in heldScreenRow(profile, connection) @@ -182,13 +159,9 @@ import SwiftUI if inbox.connection != nil { if let message = inbox.errorMessage ?? inbox.routeAdvice { Text(message).font(AppFont.callout()) - // Reconnecting would only send the refused password again (#884). if inbox.needsSignIn { Button("Update sign-in", action: updateSignIn) } else if inbox.needsAddress { - // Reconnecting reaches the same listener (#1598). A Hermes server's address - // is fixed, so its way out is another server; a webui's Bot connection - // edits its own. if let home { Button("Add Server", action: home.avatar.addServer) } else { @@ -198,8 +171,6 @@ import SwiftUI Button("Reconnect") { revision = UUID() } } } else if inbox.isLoadingRoster { - // The first row speaks for the set, so VoiceOver hears one - // "Loading bots" instead of nothing. ForEach(0..<4, id: \.self) { index in BotInboxSkeletonRow().listRowSeparator(.hidden).padding(.vertical, 12) .accessibilityElement(children: .ignore) @@ -214,18 +185,8 @@ import SwiftUI } let pinned = inbox.pinned if !pinned.isEmpty { - // Pinned chats sit above the list as large tiles: as many columns as - // there are pinned chats, up to three, so one or two sit centered and - // four or more wrap instead of being clipped away. - // Top-aligned, so a tile with a status line under its name keeps its avatar - // level with its neighbours'. LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8, alignment: .top), count: min(pinned.count, 3)), spacing: 24) { ForEach(pinned) { chat in - // The grid is one list row, and a row merges every - // `.contextMenu` inside it into one, so holding any tile - // lifted the whole grid with the first bot's menu. A Menu - // with a primary action is its own control: tap opens - // the chat, a hold shows this chat's menu. switch chat { case .bot(let profile): Menu { organizeMenu(profile) } label: { @@ -245,7 +206,6 @@ import SwiftUI .listRowSeparator(.hidden) } chatSections(inbox.sections) - // The home's filter holds this instead. if home == nil && inbox.hiddenCount > 0 { Button(inbox.showsHidden ? "Hide hidden" : "Show hidden (\(inbox.hiddenCount))") { inbox.showsHidden.toggle() @@ -254,18 +214,15 @@ import SwiftUI .listRowSeparator(.hidden) } } else { - // The welcome is an overlay, so it has no list separators or disabled rows. } } .listStyle(.plain) - // A split view's sidebar paints gray behind a plain List; only its rows cover it. .scrollContentBackground(.hidden) .background(Color(.appCanvas)) .overlay { if inbox.connection == nil { GeometryReader { geometry in ScrollView { - // The home's header stays, so Settings and the server switcher do too. VStack(spacing: 0) { homeHeader BotConnectionWelcomeView(isCovered: showingSetup) { showingSetup = true } @@ -279,8 +236,6 @@ import SwiftUI .modifier(chrome) } - /// The session list's header, leading the home's Bots side. Its search opens the inbox's - /// search sheet. @ViewBuilder private var homeHeader: some View { if let home { SessionsHeader(logoColor: HeaderLogoColor.color(for: headerLogoColorHex), avatar: home.avatar, @@ -291,13 +246,11 @@ import SwiftUI } } - /// The home's chrome, or the pushed inbox's own toolbar. private var chrome: some ViewModifier { BotsInboxChrome(home: home, isOffline: inbox.connection == nil, search: { showingSearch = true }, openSetup: { showingSetup = true }, filter: { filterMenu }, newChat: { newChatMenu }) } - /// New Bot and New Group Chat: the pushed inbox's + menu, and the home's new chat. private var newChatMenu: some View { Menu { Button("New Bot", systemImage: "plus.bubble") { creation = .new } @@ -316,7 +269,6 @@ import SwiftUI .disabled(inbox.link != .live) } - /// The home's filter: hidden bots and groups, and the order of Desktop's sections. private var filterMenu: some View { Menu { Toggle(isOn: $inbox.showsHidden) { @@ -331,16 +283,8 @@ import SwiftUI .disabled(inbox.connection == nil) } - /// Opens the bot a deep link named, once this inbox has a roster to resolve it - /// against. A connecting or retrying socket keeps the link pending, so a dropped - /// socket or a manual Reconnect still routes it. A replaced connection or a - /// Profile the server no longer has leaves the user on the inbox rather than - /// guessing (#554). private func openPendingDestination() { guard let destination = pendingDestination, destination.server == server else { return } - // A pushed screen closes the inbox socket. Return to the inbox before waiting - // for its roster, so its appearance task can reconnect and resolve the link, - // as when the Sessions list opens a Bot Chat it found (#1053). inbox.selection = BotInboxSelection() guard BotDeepLinkRouter.inboxCanAnswer( link: inbox.link, hasConnection: inbox.connection != nil, hasSettled: hasSettled @@ -350,8 +294,6 @@ import SwiftUI if destination.opensScreen, let profile = inbox.selection.profile { openScreen(profile) } } - /// Resolve the selection again after the sheet closes so a refreshed roster - /// or changed connection cannot open an old bot under a new identity. private func openSearchSelection() { defer { searchedProfile = nil; searchedRoom = nil; searchedSequence = nil } if let key = searchedRoom, key.connectionID == inbox.connection?.id, @@ -360,8 +302,6 @@ import SwiftUI inbox.selection.profile = inbox.profiles.first { $0.id == searched.profileID } } - /// The list under the tiles. Headers appear only when a named section is on - /// screen; without one the unfiled block reads as the flat list it always was. @ViewBuilder private func chatSections(_ sections: [BotInbox.ChatSection]) -> some View { let headed = sections.contains { $0.name != nil } ForEach(sections) { section in @@ -369,7 +309,6 @@ import SwiftUI Section { chatRows(section.chats) } header: { - // A Desktop name is the user's own text, never a catalog key. Group { if let name = section.name { Text(verbatim: name) } else { Text("Other chats") } } @@ -402,9 +341,6 @@ import SwiftUI .buttonStyle(.plain) .opacity(dimmed ? 0.5 : 1) .contextMenu { organizeMenu(profile) } - // The same writes the long-press menu offers, one swipe away. No full - // swipe: Delete confirms and Pin is a server write, so nothing should fire - // from a flick. .swipeActions(edge: .leading, allowsFullSwipe: false) { Button { Task { await inbox.setPinned(!profile.pinned, profile) } @@ -415,8 +351,6 @@ import SwiftUI .disabled(!inbox.mayEdit(profile)) } .swipeActions(edge: .trailing, allowsFullSwipe: false) { - // Hide sits at the edge and Delete behind it, so the first thing a - // short swipe reaches is the reversible one. Button { Task { await inbox.setHidden(!profile.hidden, profile) } } label: { @@ -434,24 +368,14 @@ import SwiftUI .padding(.vertical, 12) } - /// Opens the sign-in form for a password the host refused. A chat or room returns - /// here first: its client is bound to the rejected sign-in, and the inbox reloads the - /// record when the form closes. Its callback calls `noteRejectedSignIn` before it - /// pops, so the inbox's reappearing `open()` does not send that password again. private func updateSignIn() { updatingSignIn = true; showingSetup = true } - /// The selected bot's canonical Bot Chat in the regular chat (#1146), where every bot route - /// lands. A refused password comes back here to the inbox's sign-in form. @ViewBuilder private func chat(_ profile: BotProfile, _ connection: BotConnection) -> some View { if let chat = inbox.selection.chat(server: server, connection: connection) { ChatView(hermesSession: chat, continuity: inbox.selection.chatContinuity) .modifier(HermesUpdateSignInModifier { inbox.noteRejectedSignIn(connection); inbox.selection.profile = nil; updateSignIn() }) - // A composite rather than a concatenation: a Profile name and a - // conversation root are both arbitrary server strings, so joining them - // could let two destinations share one identity and keep the wrong - // conversation on screen. .id([profile.id, connection.id.uuidString, inbox.selection.conversation ?? ""]) .onAppear { inbox.markSeen(profile); UsageReports.shared.record(.bots) } .onDisappear { inbox.noteReturn(from: profile) } @@ -470,8 +394,6 @@ import SwiftUI } } - /// Kept as its own function with the flags read once: inlined in the list - /// builder, the row's menus and swipes were too much for the type-checker. private func roomRow(_ room: BotGroupRoom, key: BotRoomKey) -> some View { let pinned = inbox.isRoomPinned(room) let hidden = inbox.isRoomHidden(room) @@ -505,9 +427,6 @@ import SwiftUI roomSequence = nil; inbox.selection.room = key } - /// The hardware-keyboard commands (`HermexCommands`) on the home's Bots side, acting as its - /// New Bot, search, tiles and rows do. An inbox the webui list pushed publishes none, so that - /// list keeps its own. private var sceneActions: HermexSceneActions? { guard home != nil else { return nil } return HermexSceneActions( @@ -528,8 +447,6 @@ import SwiftUI ) } - /// A takeover that outlived its Screen view: the bot stays paused until someone hands back, so - /// it stays in sight here. The name opens the Screen. private func heldScreenRow(_ profile: String, _ connection: BotConnection) -> some View { let bot = inbox.profiles.first { $0.id == profile } return HStack { @@ -550,33 +467,26 @@ import SwiftUI } } - /// Whether the entries to a bot's Screen show: the server's switch is on, and the host hasn't - /// answered that it has no such method. private var canOpenScreen: Bool { isScreenEnabled && !hostLacksScreen } - /// Opens `profile`'s Screen; `takingOver` takes control once its picture is live (#1632). private func openScreen(_ profile: BotProfile, takingOver: Bool = false) { guard canOpenScreen, let connection = inbox.connection else { return } screenTarget = BotScreenTarget(profile: profile, connection: connection, takesOver: takingOver) } - /// The tiles, then the rows under them, as the list shows them, which it does only with a - /// connection. Read only on a key press, never in `body`. private var keyboardShortcutChats: [BotInbox.ChatRow] { guard inbox.connection != nil else { return [] } return inbox.pinned + inbox.sections.flatMap(\.chats) } - /// The open bot's or room's `ChatRow.id`, where Next and Previous Chat step from. private var selectedChatID: String? { if let profile = inbox.selection.profile { return BotInbox.ChatRow.bot(profile).id } guard let key = inbox.selection.room, let room = inbox.rooms.first(where: { $0.id == key.roomID }) else { return nil } return BotInbox.ChatRow.room(room).id } - /// Opens a tile or row as its tap does. private func open(_ chat: BotInbox.ChatRow) { switch chat { case .bot(let profile): inbox.selection.profile = profile @@ -584,9 +494,6 @@ import SwiftUI } } - /// Pin and hide are this phone's own marks and always apply; Rename and - /// Disband go to the host and stay inert until the inbox is live and the - /// host offers them for this room. @ViewBuilder private func roomOrganizeMenu(_ room: BotGroupRoom) -> some View { Button { roomName = room.name; renamingRoom = room @@ -610,9 +517,6 @@ import SwiftUI .disabled(!inbox.mayDisbandRoom(room)) } - /// Pin, hide and the section write Desktop's own roster fields; all stay inert - /// until the inbox is live and no write for this bot is in flight. Screen writes nothing, so - /// it sits outside them. @ViewBuilder private func organizeMenu(_ profile: BotProfile) -> some View { if canOpenScreen { Button { openScreen(profile) } label: { @@ -649,12 +553,9 @@ import SwiftUI .disabled(!inbox.mayEdit(profile)) } - /// Desktop's "Move to section": every named section on the roster (the bot's own - /// one inert), a new one through an alert, and Remove only while the bot is filed. private func sectionMenu(_ profile: BotProfile) -> some View { Menu { ForEach(inbox.sectionNames) { section in - // A Desktop name is the user's own text, never a catalog key. Button { Task { await inbox.moveToSection(profile, section) } } label: { Text(verbatim: section.name) } .disabled(section.id == profile.sectionID && profile.sectionName != nil) } @@ -673,8 +574,6 @@ import SwiftUI extension BotsInboxView { - /// The sheets, dialogs, navigation destinations and open/close lifecycle - /// the list carries. Split from `body` so the CI type-checker finishes. private func attachPresentations(to content: some View) -> some View { content .sheet(isPresented: Binding(get: { roomCreator != nil }, set: { if !$0 { roomCreator = nil } }), onDismiss: { @@ -757,7 +656,6 @@ extension BotsInboxView { deleting = nil renamingRoom = nil; disbanding = nil; filing = nil showingSectionOrder = false - // Another host answers for itself whether it has Screen. screenTarget = nil; hostLacksScreen = false } .sheet(isPresented: $showingSectionOrder) { @@ -779,8 +677,6 @@ extension BotsInboxView { } } } - // The subscription lives while the inbox is on screen and the app is not in the - // background; returning, refreshing and reconnecting all go through the same open(). .task(id: revision) { inbox.offlineCache = modelContext await inbox.open(); hasSettled = true; openPendingDestination() @@ -790,8 +686,6 @@ extension BotsInboxView { .onChange(of: pendingDestination) { openPendingDestination() } .refreshable { await inbox.open() } .onChange(of: scenePhase) { - // Control Center and banners (`.inactive`) keep the socket (#902); only an - // inbox the background closed reopens. switch scenePhase { case .background: inbox.close() case .active where inbox.link == .idle: revision = UUID() @@ -799,18 +693,12 @@ extension BotsInboxView { } } .onDisappear { inbox.close() } - // A quiet reconnect holds while offline and runs as the network returns (#1372). .onChange(of: NetworkPathMonitor.shared.changeCount) { inbox.networkPathDidChange() } } } -/// The inbox's title and toolbar. As a Hermes server's home it takes the home's bar. Pushed from -/// the session list's Bots row, the back button and the toolbar are the whole header, so the -/// pinned tiles sit at the top; the title still names the screen for VoiceOver and for a pushed -/// chat's back button, with only its visible text removed. private struct BotsInboxChrome: ViewModifier { let home: HermesHome? - /// No Bot connection is saved, so there is nothing to search. let isOffline: Bool let search: () -> Void let openSetup: () -> Void @@ -849,9 +737,6 @@ private struct BotsInboxChrome: ViewModifier { } } -/// Places Desktop's named sections for this phone's inbox. Every drag saves the -/// whole list at once; Reset to A–Z forgets the placement. The unfiled block is -/// not listed because it always stays last, nor is a section the list never heads. private struct BotSectionOrderView: View { @Environment(\.dismiss) private var dismiss let inbox: BotInbox @@ -886,14 +771,12 @@ private struct BotSectionOrderView: View { } } -/// What the create sheet is for: a fresh bot or a copy of one on this connection. private enum BotCreationIntent: Identifiable { case new, duplicate(BotProfile) var id: String { source?.id ?? "" } var source: BotProfile? { if case .duplicate(let profile) = self { return profile }; return nil } } -/// One open Screen: the bot, on the connection the entry saw, and whether the entry was Take Over. private struct BotScreenTarget: Identifiable { let profile: BotProfile let connection: BotConnection @@ -907,8 +790,6 @@ private struct BotProfileEditSelection: Identifiable, Hashable { var id: String { connectionID.uuidString + "|" + profileID } } -/// A pinned bot: the avatar large and centered with the name beneath it, and the -/// live status word under the name while it has one. private struct BotHeroTile: View { let profile: BotProfile let avatar: UIImage? @@ -923,10 +804,6 @@ private struct BotHeroTile: View { Text(profile.name).font(AppFont.body()).foregroundStyle(.appSecondary).lineLimit(1) if unread { BotUnreadDot() } } - // The longer status, hidden, holds the line's place at this text size whether a - // status shows or not: statuses arrive after the tiles, and a tile changing height - // moved the whole list under the pinned bots. Two lines, so a long translation at - // a large size still reads whole. BotLiveStatusLabel(status: .waiting, font: AppFont.footnote(weight: .semibold), isStale: false) .lineLimit(2).multilineTextAlignment(.center).hidden().accessibilityHidden(true) .overlay(alignment: .top) { @@ -942,7 +819,6 @@ private struct BotHeroTile: View { } } -/// A pinned room: the member avatars stacked large, the name beneath. private struct BotRoomHeroTile: View { let room: BotGroupRoom let roster: [BotProfile] @@ -958,10 +834,6 @@ private struct BotRoomHeroTile: View { } } -/// One roster row: avatar, name with an optional short Desktop description chip, -/// the live status or else the last activity, then the canonical preview with a -/// trailing unread mark. The avatar is decorative; VoiceOver reads the text as one -/// element, status included. private struct BotInboxRow: View { @Environment(\.dynamicTypeSize) private var dynamicTypeSize let profile: BotProfile @@ -969,8 +841,6 @@ private struct BotInboxRow: View { let unread: Bool let status: BotLiveStatus? let statusIsStale: Bool - /// A description short enough to read as a role sits beside the name; a - /// longer one only stands in for the preview when the chat has none. private var chip: String? { guard let description = profile.description, description.count <= 24, profile.preview?.isEmpty == false else { return nil } @@ -984,7 +854,6 @@ private struct BotInboxRow: View { HStack(spacing: 14) { BotAvatarView(profile: profile, avatar: avatar, size: 44) VStack(alignment: .leading, spacing: 4) { - // At accessibility sizes the slot moves under the name, as in Sessions. if dynamicTypeSize.isAccessibilitySize { HStack(alignment: .firstTextBaseline, spacing: 8) { nameAndChip } trailingSlot @@ -1015,8 +884,6 @@ private struct BotInboxRow: View { } } - /// One line, one meaning, as in Sessions: the live status while the bot has one, - /// otherwise the last activity. @ViewBuilder private var trailingSlot: some View { if let status { BotLiveStatusLabel(status: status, font: AppFont.subheadline(weight: .semibold), isStale: statusIsStale) @@ -1027,10 +894,6 @@ private struct BotInboxRow: View { } } -/// A bot's live status as a still, tinted word: the Live Activity's translated -/// "Working" and "Waiting for you" in the Sessions list's attention tints. It never -/// animates; the word carries the meaning without the color. A last known status -/// (#1374) is drawn secondary and read "Last known". private struct BotLiveStatusLabel: View { let status: BotLiveStatus let font: Font @@ -1046,8 +909,6 @@ private struct BotLiveStatusLabel: View { } } -/// Stand-in for a bot row while the first roster loads: the same avatar and text -/// footprint, redacted. Static, so it costs nothing on screen. private struct BotInboxSkeletonRow: View { var body: some View { HStack(spacing: 14) { @@ -1065,7 +926,6 @@ private struct BotInboxSkeletonRow: View { } } -/// Static unread mark. It never animates; VoiceOver reads it as "Unread". private struct BotUnreadDot: View { var body: some View { Circle().fill(Color.accentColor).frame(width: 10, height: 10) @@ -1073,8 +933,6 @@ private struct BotUnreadDot: View { } } -/// Last-activity label in the roster's style: the time today, the weekday within -/// the past week, otherwise the month and day. enum BotInboxDateLabel { static func text(for date: Date, now: Date = Date(), calendar: Calendar = .current, locale: Locale = .current) -> String { let style = Date.FormatStyle(locale: locale, calendar: calendar, timeZone: calendar.timeZone) diff --git a/HermesMobile/Features/Bots/HermexPushPairing.swift b/HermesMobile/Features/Bots/HermexPushPairing.swift index dabd16303..a27ea6db4 100644 --- a/HermesMobile/Features/Bots/HermexPushPairing.swift +++ b/HermesMobile/Features/Bots/HermexPushPairing.swift @@ -1,58 +1,29 @@ import Foundation -/// What the `hermex-push` plugin is called on a Hermes host, and how the pairing route -/// it mounts answers. The keys themselves are a `PushPairing`, stored once by -/// `PushRegistrar` in the Keychain access group the Notification Service Extension -/// reads; provisioning keeps no copy of its own. enum HermexPushPlugin { - /// The plugin's own vocabulary: the env var it reads, its installed directory name, - /// and the identifier hermes-agent resolves to the `plugin/` subfolder of the repo. static let relayURLEnvironmentKey = "HERMEX_PUSH_RELAY_URL" static let name = "hermex-push" static let installIdentifier = "https://github.com/uzairansaruzi/hermex-push.git/plugin" - /// The relay Hermex runs (hermex#556), used for a host that has never been set up. - /// It is not offered as a choice: a host that already names its own relay keeps it, - /// and self-hosting stays a server-side setting rather than a field on the phone. static let defaultRelayURL = URL(string: "https://hermex-relay.hermex-relay.workers.dev")! - /// The newest plugin this build knows (#851). A host that has anything older loaded is - /// offered an update in Settings → Notifications. Bump it in the app release that - /// follows a plugin release (TESTFLIGHT.md's release gates). static let newestVersion = HermexPushPluginVersion("0.7.0")! - /// The first plugin with `POST /api/plugins/hermex-push/restart` (#934). Settings offers - /// "Restart Hermes…" only while a plugin this new is loaded: an older one has no route to - /// call, so its card keeps asking for a restart on the host. static let restartVersion = HermexPushPluginVersion("0.4.0")! - /// Whether the dashboard running `loaded` can be restarted from the phone. static func canRestart(_ loaded: HermexPushPluginVersion?) -> Bool { loaded.map { $0 >= restartVersion } ?? false } - /// `plugin_version` from the pairing route: the code the dashboard process has loaded, - /// which lags the files on disk until that process restarts. Nil for a plugin older than - /// 0.2.0, which leaves it out, and for anything unparseable; both count as older than - /// every known version. Tolerant, unlike the keys beside it. static func loadedVersion(_ body: BotJSON) -> HermexPushPluginVersion? { body["plugin_version"].text.flatMap(HermexPushPluginVersion.init) } - /// Whether the plugins hub lists hermex-push, i.e. it is on the host's disk. Nil for a - /// reply without a plugins list, which says nothing either way. static func isOnDisk(hub body: BotJSON) -> Bool? { body["plugins"].list?.contains { $0["name"].text == name } } - /// The version on the host's disk: `plugin.yaml`'s, as `GET /api/dashboard/plugins/hub` - /// lists it per plugin. Nil when the plugin is not listed or its version doesn't parse. static func installedVersion(hub body: BotJSON) -> HermexPushPluginVersion? { body["plugins"].list?.first { $0["name"].text == name }?["version"].text.flatMap(HermexPushPluginVersion.init) } - /// Why the pairing route answered 404, from the body the dashboard sent (hermes-agent - /// ca678285, #1178). Its auth middleware answers "Plugin not found" for a plugin that is - /// off or not installed. The SPA catch-all answers "No such API endpoint" for a plugin - /// that is on but whose routes the dashboard never mounted, since it mounts them only at - /// startup; `hermes serve`'s headless catch-all means the same. Nil for any other body. static func missingRoute(_ body: BotJSON) -> HermexPushRouteMissing? { if body["detail"].text == "Plugin not found" { return .pluginOff } if body["detail"].text?.hasPrefix("No such API endpoint") == true @@ -60,10 +31,6 @@ enum HermexPushPlugin { return nil } - /// Decodes `GET /api/plugins/hermex-push/pairing`. Fields the plugin may add later - /// are ignored, but a key the relay could not use fails instead of pairing a phone - /// that can never receive a push: the install key is 64 lowercase hex characters and - /// the preview key is base64 of exactly 32 bytes (AES-256-GCM). static func pairing(_ body: BotJSON) throws -> PushPairing { guard let install = body["install_key"].text, let preview = body["preview_key"].text, Data(base64Encoded: preview)?.count == 32, @@ -74,9 +41,6 @@ enum HermexPushPlugin { return pairing } - /// Accepts the relay addresses the plugin itself accepts: https anywhere, plain http - /// only to loopback for a local capture. A host that answers with anything else is - /// refused rather than pairing a phone the relay could never reach. static func relayURL(_ text: String) -> URL? { guard var parts = URLComponents(string: text.trimmingCharacters(in: .whitespacesAndNewlines)), let host = parts.host, !host.isEmpty, @@ -87,18 +51,13 @@ enum HermexPushPlugin { guard scheme == "https" || (scheme == "http" && isLoopback) else { return nil } parts.scheme = scheme parts.host = host.lowercased() - // The relay refuses redirects, so a trailing slash must not become `//installs`. while parts.path.hasSuffix("/") { parts.path.removeLast() } return parts.url } } -/// Failures that belong to setting a Hermes host up for push rather than to the Hermes -/// gateway. Each one is shown next to the step that produced it, so the user knows what -/// to retry. enum HermexPushFailure: Error, Equatable, LocalizedError { case unusablePairing, pairingUnavailable, noConnection - /// A plugin update turned hermex-push off and could not turn it back on. case pluginLeftOff var errorDescription: String? { switch self { @@ -114,20 +73,12 @@ enum HermexPushFailure: Error, Equatable, LocalizedError { } } -/// What the hermex-push routes the dashboard has mounted, from -/// `GET /api/plugins/hermex-push/capabilities` (plugin 0.5.0, #1235). Each route is a method -/// and the path below the plugin's mount, as in `"GET /pairing"`. A feature that needs a -/// plugin route shows only where `supports` says the route is mounted, since a POST can't be -/// probed without running it. `closed` supports nothing: an older plugin, or one the -/// dashboard hasn't loaded since it was installed. Read per screen, never cached, so one -/// server's answer can't gate another's. struct HermexCompanionRoutes: Equatable, Sendable { static let closed = HermexCompanionRoutes(pluginVersion: nil, routes: []) let pluginVersion: HermexPushPluginVersion? let routes: Set - /// Fields the plugin may add later are ignored, and an entry that isn't a string is skipped. init(_ body: BotJSON) { self.init(pluginVersion: HermexPushPlugin.loadedVersion(body), routes: Set(body["routes"].list?.compactMap(\.text) ?? [])) @@ -141,12 +92,8 @@ struct HermexCompanionRoutes: Equatable, Sendable { func supports(_ route: String) -> Bool { routes.contains(route) } } -/// The pairing route's 404s that say what the host lacks (`HermexPushPlugin.missingRoute`). -/// `notMounted` never clears without a dashboard restart on the host. enum HermexPushRouteMissing: Error, Equatable { case pluginOff, notMounted } -/// A hermex-push version, compared number by number so 0.10.0 is newer than 0.9.0, and -/// 0.3 equals 0.3.0. Only dot-separated whole numbers parse. struct HermexPushPluginVersion: Comparable, Sendable, CustomStringConvertible { let description: String private let numbers: [Int] diff --git a/HermesMobile/Features/Bots/HermexPushProvisioner.swift b/HermesMobile/Features/Bots/HermexPushProvisioner.swift index 8fed01269..b5071fa6d 100644 --- a/HermesMobile/Features/Bots/HermexPushProvisioner.swift +++ b/HermesMobile/Features/Bots/HermexPushProvisioner.swift @@ -1,14 +1,7 @@ import Foundation import UserNotifications -/// Drives one server's push setup: point the Hermes host at a relay, install and enable -/// the `hermex-push` plugin, restart the gateway, read the pairing keys and register this -/// phone. Every step mutates the user's server, so nothing here runs implicitly — the view -/// calls `enable` only from a confirmed action. A failed run leaves nothing half-paired: -/// the keys are wiped again, and the host returns the same pair on the next attempt. @MainActor @Observable final class HermexPushProvisioner { - /// The enable sequence, in the order the host needs it, and the labels the progress - /// list shows. Disable has its own two steps; they are named where they can fail. enum Step: String, CaseIterable, Identifiable { case relayURL, install, restart, pair, device var id: String { rawValue } @@ -23,20 +16,14 @@ import UserNotifications } } - /// A step that did not finish, in the step's own words, so the user knows what to retry. struct Failure: Equatable { let title: String let message: String var remedy: Remedy = .none - /// What the section offers beside a failure (#851). `updatePlugin`: keys an old - /// plugin sent, which updating it fixes. `retryUpdate`: the update itself stopped, - /// so the plugin card shows it instead of the red row. `retryRestart`: the restart - /// stopped before it ran (#934), so the card offers it again the same way. enum Remedy { case none, updatePlugin, retryUpdate, retryRestart } } - /// The plugin update's host steps (#851), in order, and how the card names them. enum PluginUpdateStep: CaseIterable { case reinstall, restart, check var progress: String { @@ -55,37 +42,17 @@ import UserNotifications } } - /// Where this host's hermex-push stands against `HermexPushPlugin.newestVersion`, as the - /// host last answered (#851). Kept in memory only: the section asks again each time it - /// appears, so "restart needed" never rests on what this iPhone remembers. enum PluginUpdate: Equatable { - /// Behind the newest; `loaded` is nil for a plugin too old to report its version. case available(loaded: HermexPushPluginVersion?) - /// The newest is on disk, but the dashboard runs the old code, `loaded`, until it - /// restarts; nil when it has none loaded (#1235). With 0.4.0 or newer loaded, the - /// phone can restart it (#934). case restartNeeded(loaded: HermexPushPluginVersion?) - /// Setup reached a dashboard that hasn't loaded hermex-push (#1178): it was installed - /// after the dashboard started, or just now. A gateway restart doesn't load it; only - /// restarting `hermes dashboard` on the host does. "Check again" then finishes pairing. case setupNeedsRestart - /// Hermes didn't answer in time after a restart from the phone (#934). "Check again" - /// reads once; a restart is offered again only once the host answers. case restartTimedOut - /// An update or check just brought it to the newest. Shown until Settings closes. case upToDate(HermexPushPluginVersion) - /// The update or the restart changed the host, but reading its version failed; the - /// card offers the read again, never a second reinstall and restart. case checkFailed(Failure) } - /// The card at the top of the section: the plugin's standing, the update's or the - /// restart's progress, or where either stopped. enum PluginCard: Equatable { case status(PluginUpdate), updating(PluginUpdateStep), restarting, failed(Failure) } - /// `checkingPermission` covers the iOS prompt at the start of setup: it blocks re-entry - /// but names no host step, since none has run yet. `tested` holds the relay's answer to - /// the Settings test notification until the next action replaces it. enum Phase: Equatable { case idle, checkingPermission, enabling(Step), disabling, savingPreferences, refreshing, sendingTest case updatingPlugin(PluginUpdateStep), checkingPlugin, restartingHermes @@ -96,47 +63,24 @@ import UserNotifications let server: URL private(set) var pairing: PushPairing? private(set) var phase: Phase = .idle - /// Steps that finished in the current enable run, so the view can show what is done. private(set) var completed: Set = [] - /// Whether setup, rather than the plugin update or its check, made the last host run, - /// so a failure lists setup's steps only when setup is what stopped. private var setupRanLast = false - /// iOS notification permission for Hermex is denied, so nothing this server sends can - /// show. Raised when setup finds it (before any host call) and, on a paired server, - /// whenever the section checks; cleared once the user allows notifications again. private(set) var notificationsOff = false private(set) var pluginUpdate: PluginUpdate? - /// Whether the last plugin read reached a gateway's own Webapp, which hermex-push's restart - /// re-execs without the gateway's drain (uzairansaruzi/hermex-push#33, #1606). private(set) var servesWebapp = false - /// Deliberate plugin actions supersede passive reads, even after the action finishes. private var pluginCheckGeneration = 0 - /// The saved connection this host is reached with. The screen keeps it current so a - /// password edit made just above this section is the one provisioning signs in with. var connection: BotConnection? - /// Nil on a build with no Keychain access group to write to, which means push cannot - /// work at all; the section then reports the step it could not take. private let registrar: (any PushPairingEnabling)? private let notifications: any ResponseCompletionNotificationScheduling private let dashboard: @MainActor (BotConnection) -> BotDashboardClient - /// The connection this server still has saved, read at the moment state is committed. private let connectionID: @MainActor () -> UUID? - /// Posts Settings' test notification to this pairing's relay; injected so tests never - /// reach one. private let testSender: @MainActor (PushPairing) async -> PushRelayTestOutcome - /// Retries while the host is coming back from its restart; injected so tests never sleep. private let retryDelays: [Duration] - /// The wait for Hermes after a restart from the phone (#934): about 60 s in all, since a - /// whole dashboard starts, not just the gateway. private let restartDelays: [Duration] - /// The newest plugin this build knows, injectable so tests can load a plugin that has the - /// restart route and is still behind, which this build's own constants never pair. private let newestPlugin: HermexPushPluginVersion private let sleep: @Sendable (Duration) async throws -> Void - /// The main-actor collaborators are built here rather than in default arguments, - /// which Swift evaluates outside the actor. init(server: URL, connection: BotConnection?, registrar: (any PushPairingEnabling)? = nil, notifications: any ResponseCompletionNotificationScheduling = UserNotificationResponseCompletionScheduler(), @@ -170,8 +114,6 @@ import UserNotifications } } - /// A step's failure, or the test notification's. Both show in the same red row, except - /// the plugin update's own, which its card shows (`pluginCard`). var failure: Failure? { switch phase { case .failed(let failure): return failure @@ -191,18 +133,12 @@ import UserNotifications var testDelivered: Bool { phase == .tested(.delivered) } - /// The test needs a banner this iPhone can show: with Reply Notifications off the relay - /// skips it yet still answers accepted, and with iOS notifications off nothing shows. var canSendTest: Bool { !isWorking && !notificationsOff && pairing?.effectivePreferences.replies == true } func isRunning(_ step: Step) -> Bool { phase == .enabling(step) } - /// Whether the step list belongs on screen: while a host step runs, after setup fails, - /// and after a run that changed the host before stopping (permission revoked mid-run), so - /// those changes stay visible. Hidden while iOS asks for permission: nothing ran yet. - /// The plugin update's failures leave it hidden; its card and the red row name them. var showsSteps: Bool { switch phase { case .enabling: return true @@ -213,7 +149,6 @@ import UserNotifications } } - /// Re-reads local state when Settings returns from editing the connection. func reload() async { guard !isWorking else { return } phase = .refreshing @@ -221,7 +156,6 @@ import UserNotifications guard !Task.isCancelled else { return } connection = try? BotConnectionStore().load(server: server) pairing = registrar?.pairing(for: server) - // A removed connection leaves no host to update. if connection == nil { pluginUpdate = nil } phase = .idle if let pairing, pairing.preferencesNeedSync == true { @@ -245,10 +179,6 @@ import UserNotifications } } - /// The view cancels only its presentation of a preference write. The registrar - /// owns completing the durable transaction after this screen goes away. A test result - /// and a finished plugin update are cleared too; a test still in flight keeps the - /// phase, so it stays one request. func leaveSettings() { switch phase { case .savingPreferences, .refreshing, .tested: phase = .idle @@ -257,18 +187,12 @@ import UserNotifications if case .upToDate = pluginUpdate { pluginUpdate = nil } } - /// Settings' end-to-end check: one `reply` through this server's relay, to Apple, and - /// on to every iPhone paired with the host. One call is one request, and a second call - /// while it runs sends nothing. It says nothing about the host → relay leg. func sendTestNotification() async { guard canSendTest, let pairing else { return } phase = .sendingTest phase = .tested(await testSender(pairing)) } - /// Nil for delivered. Every other answer names what refused it: this iPhone's - /// connection, Apple, the relay, or the relay's hosting (#834 answered in Cloudflare's - /// words, not the relay's JSON). Never the Hermes host: the test does not touch it. private static func testFailure(for outcome: PushRelayTestOutcome) -> Failure? { let message: String switch outcome { @@ -292,27 +216,14 @@ import UserNotifications remedy: outcome == .unusablePairing ? .updatePlugin : .none) } - /// The whole setup. A host that already answers the pairing route has its relay set - /// and the plugin loaded, so it is paired as it stands: no install, and no restart - /// interrupting work. A plugin that is off or missing gets the full sequence, in the - /// order the host needs it — the relay address before the pairing route will answer, - /// and the plugin enabled before that route exists at all. A dashboard that hasn't - /// mounted a plugin on its disk ends in `.setupNeedsRestart` (#1178), the full sequence - /// included: only restarting the dashboard on the host loads it. Denied notification - /// permission stops the run before it signs in, so the host is never touched for a - /// phone that could not show what it sends. func enable() async { await setUp(mayInstall: true) } - /// `enable`, or with `mayInstall` false "Check again" on `.setupNeedsRestart`, which - /// pairs a host that now answers and never installs or restarts anything. private func setUp(mayInstall: Bool) async { guard !isWorking else { return } setupRanLast = true guard let connection else { return fail(Step.relayURL.title, HermexPushFailure.noConnection) } completed = [] phase = .checkingPermission - // Permission comes first: a phone that cannot show a notification must not get as - // far as reinstalling the plugin and restarting the gateway. notificationsOff = !(await notificationsAllowed()) guard !notificationsOff else { phase = .idle; return } var step = Step.relayURL @@ -332,8 +243,6 @@ import UserNotifications phase = .enabling(step) paired = configured case .relayUnset: - // The plugin is there and loaded; it only lacks somewhere to send to. The - // plugin re-reads the value, so this needs no reinstall and no restart. try await client.setEnvironmentValue(HermexPushPlugin.relayURLEnvironmentKey, HermexPushPlugin.defaultRelayURL.absoluteString) completed.formUnion([.relayURL, .install, .restart]) @@ -341,7 +250,6 @@ import UserNotifications phase = .enabling(step) paired = try await pairAfterRestart(client) case .notInstalled where !mayInstall: - // The plugin went off or away since setup; Check again changes nothing. return fail(Step.pair.title, HermexPushFailure.pairingUnavailable) case .notInstalled: try await client.setEnvironmentValue(HermexPushPlugin.relayURLEnvironmentKey, @@ -356,18 +264,12 @@ import UserNotifications } step = advance(from: step, to: .device) guard let registrar else { throw PushRegistrarError.unsupportedBuild } - // Asks for notification permission, mints a device token and registers it at - // this install's relay. It stores the keys only once the relay has accepted. do { try await registrar.enable(paired, for: server) } catch PushRegistrarError.permissionDenied { - // Permission was revoked while the host was being set up. pairing = registrar.pairing(for: server) notificationsOff = true phase = .idle return } - // A run outlives the screen, so the connection or its whole server can be - // removed while it works. Teardown wins: what was just stored goes again and - // this phone comes back off the relay. guard connectionID() == connection.id else { return await abandon() } completed.insert(.device) pairing = registrar.pairing(for: server) @@ -376,26 +278,15 @@ import UserNotifications } catch HermexPushRouteMissing.notMounted { awaitDashboardRestart() } catch { - // Nothing half-paired: the registrar undoes its own registration, and the host - // keeps the same key pair, so a retry gets it back. pairing = registrar?.pairing(for: server) fail(step.title, error) } } - /// Whether another entry for this server's host (a LAN and a tunnel address, say) uses - /// the same pairing, so turning this one off leaves the host and relay alone (#1178). An - /// unreadable Keychain reads as not shared here; `disable` asks again and stops on it. var sharesHostPairing: Bool { (try? registrar?.sharesRegistration(for: server)) == true } - /// Stops `disable`'s plugin write when another entry paired while it signed in. private struct HostPairingShared: Error {} - /// The way out: stop the host sending, then drop this phone at the relay and wipe its - /// keys. The host goes first so a failure at either step changes nothing the user has - /// to unpick — they can simply try again. While another entry shares the pairing, the - /// plugin stays on for it and only this entry's keys go. A Keychain that can't say - /// whether one does fails the run before anything changes. func disable() async { guard !isWorking, pairing != nil else { return } completed = [] @@ -405,8 +296,6 @@ import UserNotifications if let connection, try registrar?.sharesRegistration(for: server) != true { let client = dashboard(connection) do { try await signIn(client) } catch { return failSignIn(error) } - // Another entry can start registering its device or finish pairing during - // a sign-in; it then owns the plugin too, so the disable doesn't go out. do { try await client.setPlugin(HermexPushPlugin.name, enabled: false) { if try self.registrar?.sharesRegistration(for: self.server) == true { throw HostPairingShared() } @@ -416,30 +305,19 @@ import UserNotifications step = String(localized: "Remove this iPhone from the relay") try await registrar?.disable(for: server) pairing = registrar?.pairing(for: server) - // Its install enables the plugin again, so the update goes with the pairing. pluginUpdate = nil phase = .idle } catch { fail(step, error) } } - /// The section's one passive read (#851), each time it appears on a paired server: the - /// pairing route's `plugin_version`, then the hub only when that is behind. Reads alone, - /// so no confirmation; a host that doesn't answer leaves the card as it was. func checkPlugin() async { guard pairing != nil, let connection, !isUpdatingPlugin else { return } let generation = pluginCheckGeneration guard let standing = try? await pluginStanding(dashboard(connection)), !Task.isCancelled, pairing != nil, !isUpdatingPlugin, generation == pluginCheckGeneration else { return } - // A plugin already on the newest needs no card; only an update run says so. if case .upToDate = standing { pluginUpdate = nil } else { pluginUpdate = standing } } - /// "Check again" once the host has been restarted, after a failed read, or after a - /// restart Hermes didn't come back from: one read, whose answer replaces the card. A - /// failure goes to the red row and leaves the card standing, except on a card that is - /// itself a failed read, which takes the newer failure, and on "Hermes didn't come back": - /// a host that still doesn't answer leaves it as it is, and one that answers with an - /// error is a failed read. func checkPluginAgain() async { guard !isWorking, let connection else { return } if pluginUpdate == .setupNeedsRestart { return await setUp(mayInstall: false) } @@ -458,17 +336,6 @@ import UserNotifications phase = .idle } - /// Settings' plugin update (#851), from a confirmed tap only: turn hermex-push off, - /// reinstall it over itself (cloned again from `main`, which turns it back on), restart - /// the gateway, then read what the host has loaded. Current Hermes asks at a terminal - /// before it replaces an enabled plugin that declares Python packages, and refuses the - /// dashboard's reinstall; a disabled one skips that question, and enabling it runs - /// Hermes's own dependency admission. The keys stay in `plugin-data`, so a paired phone - /// stays paired; an update started from a pairing failure ends here too, since pairing - /// waits for its own tap. - /// The dashboard that serves the pairing route and runs Bot turns loads plugins only - /// when it starts, so "restart needed" is the usual end. Only a plugin that is already - /// 0.4.0 or newer can then restart it from the phone (`restartHermes`). func updatePlugin() async { guard !isWorking else { return } pluginCheckGeneration &+= 1 @@ -490,10 +357,6 @@ import UserNotifications turnedOff = true try await client.installPlugin(identifier: HermexPushPlugin.installIdentifier) } catch { - // Turning a plugin off only edits the host's config, so the running gateway keeps - // it; turning it back on keeps the next restart from dropping push. A disable that - // failed may still have landed, so it is undone too; enabling an enabled plugin is a - // no-op. Only a confirmed disable is reported as left off. let failure = error do { try await client.setPlugin(HermexPushPlugin.name, enabled: true) } catch { if turnedOff { throw HermexPushFailure.pluginLeftOff } @@ -509,7 +372,6 @@ import UserNotifications pluginUpdate = try await afterRestart { try await self.pluginStanding(client) } phase = .idle } catch where step == .check { - // The host already took the reinstall and the restart; only the read is left to retry. pluginUpdate = .checkFailed(Self.checkFailure(error)) phase = .idle } catch { @@ -517,27 +379,15 @@ import UserNotifications } } - /// Signs `client` in and notes whether that reached a gateway's Webapp. private func signIn(_ client: BotDashboardClient) async throws { try await client.signIn() servesWebapp = client.servesWebapp } - /// Whether "Restart Hermes…" is offered for the plugin `loaded`: one with the restart route, - /// on a host that isn't a gateway's Webapp. func canRestart(_ loaded: HermexPushPluginVersion?) -> Bool { HermexPushPlugin.canRestart(loaded) && !servesWebapp } - /// "Restart Hermes…" (#934), from a confirmed tap on a host whose loaded plugin has the - /// restart route: hermex-push answers 202 and re-execs the dashboard about a second later. - /// A connection dropped on that request counts as the restart. Then the public `/api/status` - /// is probed on `restartDelays` (`HermesRestartWait`), and whenever it answers the pairing route is read, until - /// the newest plugin is loaded. The old process can still answer just after the 202, so an - /// answer with the old plugin keeps waiting. When the schedule runs out the last answer - /// stands: the old plugin, offered the restart again; a new plugin that didn't load, which - /// leaves its routes unmounted, asked for a restart on the host; a host that answers but - /// whose read fails, a failed read; or silence, "Hermes didn't come back". Like the update, the run outlives Settings. func restartHermes() async { guard !isWorking, let connection, case .restartNeeded(let loaded)? = pluginUpdate, canRestart(loaded) else { return } @@ -547,13 +397,9 @@ import UserNotifications phase = .restartingHermes let client = dashboard(connection) do { try await signIn(client) } catch { return failSignIn(error, remedy: .retryRestart) } - // This sign-in can be the one that finds a Webapp, whose drain the restart skips: the card - // then asks for the restart on the host instead. guard canRestart(loaded) else { phase = .idle; return } do { try await client.restartHermes() } catch BotFailure.transport, is URLError { - // The host can go down before its answer arrives; that is the restart. } catch BotFailure.stale where client.servesWebapp { - // A sign-in on the way found a Webapp, so nothing was sent: as above. servesWebapp = true phase = .idle return @@ -590,11 +436,6 @@ import UserNotifications } } - /// Where the host's plugin stands. The hub is read only for a loaded plugin that is - /// behind: its on-disk version tells a copy waiting for a restart from one that still - /// needs updating. A host without the hub, or one that fails it, reads as the latter. - /// A dashboard that hasn't mounted the plugin has no version loaded, so the newest on - /// disk reads as waiting for a restart rather than a refused read (#1235). private func pluginStanding(_ client: BotDashboardClient) async throws -> PluginUpdate { let loaded: HermexPushPluginVersion? do { loaded = try await client.loadedPluginVersion() } catch HermexPushRouteMissing.notMounted { loaded = nil } @@ -606,10 +447,6 @@ import UserNotifications return .available(loaded: loaded) } - /// Clears the notifications-off state once the user has allowed notifications in iOS - /// Settings, and on a paired server also raises it, since a phone whose permission - /// was later denied silently stops showing this server's pushes. It never starts - /// setup itself: host changes stay behind the confirmation. func recheckNotificationPermission() async { guard pairing != nil || notificationsOff else { return } let denied = await notifications.authorizationStatus() == .denied @@ -617,8 +454,6 @@ import UserNotifications notificationsOff = denied } - /// Asks iOS only when the user has never been asked. A refusal, now or earlier, is final - /// here: iOS shows no second prompt, so only Settings can change it. private func notificationsAllowed() async -> Bool { switch await notifications.authorizationStatus() { case .notDetermined: return await notifications.requestAuthorization() @@ -628,14 +463,6 @@ import UserNotifications } } - /// What the pairing route says this host still needs. Only a plugin that is off or - /// missing, or an unset relay, mean "not set up yet": a timeout, a server error, a 404 - /// the host doesn't explain, or keys this build cannot read are thrown on instead, - /// because reinstalling and restarting on those would replace a self-hosted relay and - /// interrupt work over a failure that had nothing to do with setup. An unmounted route - /// is read against the plugins hub: with hermex-push on disk it throws - /// `HermexPushRouteMissing.notMounted`, since only a dashboard restart loads it; a hub - /// reply with no plugins list leaves the 404 unexplained. private enum HostState { case paired(PushPairing), relayUnset, notInstalled } private func hostState(_ client: BotDashboardClient) async throws -> HostState { @@ -652,17 +479,12 @@ import UserNotifications } } - /// Ends setup on "Restart Hermes to finish" rather than a failed step: the host has the - /// plugin, and the dashboard that serves the pairing route loads it only when it starts. private func awaitDashboardRestart() { pairing = registrar?.pairing(for: server) pluginUpdate = .setupNeedsRestart phase = .idle } - /// Finishes a run whose connection was removed under it: nothing is stored, and a - /// device registered moments ago is dropped again, so a removed connection never - /// leaves this phone on its relay. private func abandon() async { await registrar?.forget(for: server) pairing = nil @@ -670,14 +492,10 @@ import UserNotifications phase = .idle } - /// The restart drops the route for a moment, so a missing route, a relay address the - /// plugin has not read yet, and a refused connection are all retried. A route the - /// dashboard never mounted is not: the gateway restart can't mount it (#1178). private func pairAfterRestart(_ client: BotDashboardClient) async throws -> PushPairing { try await afterRestart { try await client.pairing() } } - /// Runs `read` until the host answers it or the retry schedule runs out. private func afterRestart(_ read: () async throws -> T) async throws -> T { var delays = retryDelays.makeIterator() while true { @@ -689,7 +507,6 @@ import UserNotifications } } - /// A host coming back from a restart: unreachable, or up without the plugin's routes yet. private static func isRestarting(_ error: Error) -> Bool { switch error { case BotFailure.rejected(404), BotFailure.rejected(409), HermexPushRouteMissing.pluginOff: return true @@ -697,8 +514,6 @@ import UserNotifications } } - /// No answer from Hermes itself: a dropped or refused connection, or a proxy in front of - /// a host that is down. private static func isUnreachable(_ error: Error) -> Bool { switch error { case BotFailure.rejected(502), BotFailure.rejected(503), BotFailure.transport: return true @@ -712,14 +527,11 @@ import UserNotifications return next } - /// A failure whose words send the user to update the plugin also offers that update. private func fail(_ step: String, _ error: Error) { phase = .failed(Failure(title: step, message: Self.message(for: error), remedy: Self.needsNewerPlugin(error) ? .updatePlugin : .none)) } - /// Keys an old plugin sent, the errors `message(for:)` answers with "Update the - /// hermex-push plugin." private static func needsNewerPlugin(_ error: Error) -> Bool { switch error { case HermexPushFailure.unusablePairing, PushRegistrarError.malformedPairing, @@ -728,8 +540,6 @@ import UserNotifications } } - /// Sign-in changes nothing on the host, so a connection that fails there really is - /// unreachable, unlike a later step that may still be finishing when it times out. private func failSignIn(_ error: Error, remedy: Failure.Remedy = .none) { let message = switch error { case BotFailure.transport, is URLError: @@ -739,10 +549,6 @@ import UserNotifications phase = .failed(Failure(title: String(localized: "Sign in to Hermes"), message: message, remedy: remedy)) } - /// Provisioning speaks for itself rather than borrowing the Bot chat's wording: a step - /// that failed says what answered — the host, the relay or iOS — because that is what - /// the user has to act on. The registrar's and relay's errors are switched exhaustively - /// so a new case cannot fall through to someone else's words. static func message(for error: Error) -> String { switch error { case let failure as HermexPushFailure: diff --git a/HermesMobile/Features/Bots/HermexPushSettingsPage.swift b/HermesMobile/Features/Bots/HermexPushSettingsPage.swift index 19f347873..44aee8a2d 100644 --- a/HermesMobile/Features/Bots/HermexPushSettingsPage.swift +++ b/HermesMobile/Features/Bots/HermexPushSettingsPage.swift @@ -1,7 +1,5 @@ import SwiftUI -/// Settings → Notifications (#1252): push for this server and device first, then the -/// sections the caller supplies for alerts that apply on this iPhone to every server. @MainActor struct HermexPushSettingsPage: View { let server: URL @Environment(\.scenePhase) private var scenePhase @@ -36,8 +34,6 @@ import SwiftUI await provisioner.reload() await provisioner.checkPlugin() } - // Runs on appear and on every return to the app, so allowing notifications in - // iOS Settings clears the notice without re-running setup. .task(id: scenePhase) { if scenePhase == .active { await provisioner.recheckNotificationPermission() } } @@ -47,8 +43,6 @@ import SwiftUI provisioner.leaveSettings() } .confirmationDialog("Set this Hermes host up for push?", isPresented: $isConfirmingEnable, titleVisibility: .visible) { - // Provisioning changes the host, so the existing owner finishes that - // transaction even if Settings closes before it returns. Button("Set up push") { Task { await provisioner.enable() } } } message: { Text("If this host is not set up yet, Hermex installs the hermex-push plugin on it and restarts its gateway, interrupting work running there. A host that is already set up is only paired. Nothing happens until you tap this.") @@ -61,16 +55,13 @@ import SwiftUI : String(localized: "This iPhone is removed from the relay, the plugin is disabled on your Hermes host, and the keys stored on this iPhone are deleted.")) } .confirmationDialog("Update the hermex-push plugin?", isPresented: $isConfirmingUpdate, titleVisibility: .visible) { - // Like setup, the run outlives the screen: the host has already been asked to change. Button("Update plugin") { Task { await provisioner.updatePlugin() } } } message: { - // An update offered by a pairing failure has no pairing to keep. Text(provisioner.pairing == nil ? String(localized: "Your Hermes host downloads hermex-push again from GitHub and restarts its gateway, interrupting work running there. To finish, you’ll likely need to restart Hermes on the host yourself.") : String(localized: "Your Hermes host downloads hermex-push again from GitHub and restarts its gateway, interrupting work running there. This iPhone stays paired. To finish, you’ll likely need to restart Hermes on the host yourself.")) } .confirmationDialog("Restart Hermes?", isPresented: $isConfirmingRestart, titleVisibility: .visible) { - // Like the update, the run outlives the screen: the host has already been asked to restart. Button("Restart", role: .destructive) { Task { await provisioner.restartHermes() } } } message: { Text("Bot turns running on this host stop. Hermex reconnects when Hermes is back.") @@ -125,8 +116,6 @@ import SwiftUI Text("The relay only ever sees encrypted text.") .font(AppFont.caption()).foregroundStyle(.appSecondary) } - // Also available after pairing, so an expired sign-in can be repaired - // without searching through the server's detail screen. NavigationLink(provisioner.connection == nil ? String(localized: "Connect Hermes…") : String(localized: "Hermes connection")) { BotConnectionView(server: server) } @@ -135,7 +124,7 @@ import SwiftUI switch failure.remedy { case .none: failureRow(failure) case .updatePlugin: failureCallout(failure, action: String(localized: "Update plugin…")) - case .retryUpdate, .retryRestart: EmptyView() // The plugin card at the top shows it. + case .retryUpdate, .retryRestart: EmptyView() } } } @@ -156,8 +145,6 @@ import SwiftUI .frame(minHeight: 44) } - /// Settings' end-to-end push check (#874). No spinner: the label says "Sending…" while - /// the one request runs. A failure shows in the red row at the bottom of the section. @ViewBuilder private func testNotificationRows(_ pairing: PushPairing) -> some View { Button(provisioner.phase == .sendingTest ? String(localized: "Sending…") : String(localized: "Send Test Notification")) { Task { await provisioner.sendTestNotification() } @@ -179,8 +166,6 @@ import SwiftUI } } - /// Progress without motion: a finished step is checked, the running one is named, and - /// the rest stay quiet. No spinner, so a slow host never repaints the screen. private func stepRow(_ step: HermexPushProvisioner.Step) -> some View { let isDone = provisioner.completed.contains(step) let isRunning = provisioner.isRunning(step) @@ -197,8 +182,6 @@ import SwiftUI : String(localized: "\(step.title): waiting")))) } - /// Denied iOS permission, kept apart from the red step failure because no host step - /// ran. The whole row opens Hermex's notification page in iOS Settings. @ViewBuilder private func notificationsOffRow(title: String?, message: String) -> some View { if let settingsURL = URL(string: UIApplication.openNotificationSettingsURLString) { Link(destination: settingsURL) { @@ -219,9 +202,6 @@ import SwiftUI } } - /// The plugin update (#851) and the restart that finishes it (#934) as design C's card at - /// the top of the section: one card for every state, in the notifications-off row's style. - /// No spinner: a dashed circle and the running step's name carry progress. @ViewBuilder private func pluginCallout(_ card: HermexPushProvisioner.PluginCard) -> some View { let newest = HermexPushPlugin.newestVersion.description switch card { @@ -233,13 +213,11 @@ import SwiftUI case .updating(let step): callout("circle.dashed", tint: Color(.appTextSecondary), title: Text("Updating the plugin…"), message: Text(step.progress)) case .status(.restartNeeded(let loaded)) where provisioner.canRestart(loaded): - // The loaded plugin has the restart route, so restarting is the card's one action. callout("arrow.clockwise.circle.fill", tint: .orange, title: Text("Restart Hermes to finish"), message: Text("Hermes loads the new plugin when it restarts."), action: String(localized: "Restart Hermes…")) { isConfirmingRestart = true } case .status(.restartNeeded), .status(.setupNeedsRestart): callout("arrow.clockwise.circle.fill", tint: .orange, title: Text("Restart Hermes to finish"), - // A gateway's Webapp is the gateway itself, not `hermes dashboard` (#1606). message: provisioner.servesWebapp ? Text("Restart the Hermes gateway on your host, then check again.") : Text("Restart `hermes dashboard` on your host, then check again."), action: provisioner.phase == .checkingPlugin ? String(localized: "Checking…") : String(localized: "Check again")) { @@ -267,9 +245,6 @@ import SwiftUI } } - /// A failure the plugin update answers (the update's own, or keys an old plugin sent) or - /// a restart that never ran. The action asks for that step's confirmation again before - /// the host changes. private func failureCallout(_ failure: HermexPushProvisioner.Failure, action: String) -> some View { callout("exclamationmark.triangle.fill", tint: .red, title: Text(failure.title), message: Text(failure.message), action: action) { @@ -277,8 +252,6 @@ import SwiftUI } } - /// The card itself. With an action, the whole card is the button, so it stays a - /// full-width target at every Dynamic Type size. @ViewBuilder private func callout(_ symbol: String, tint: Color, title: Text, message: Text, action: String? = nil, perform: @escaping () -> Void = {}) -> some View { let card = HStack(alignment: .firstTextBaseline, spacing: 10) { diff --git a/HermesMobile/Features/Chat/ApprovalRequestInset.swift b/HermesMobile/Features/Chat/ApprovalRequestInset.swift index 30c5b558a..471cd0d8b 100644 --- a/HermesMobile/Features/Chat/ApprovalRequestInset.swift +++ b/HermesMobile/Features/Chat/ApprovalRequestInset.swift @@ -1,14 +1,11 @@ import SwiftUI import UIKit -/// What an approval card shows. A webui server's approval always offers all four -/// choices; a Hermes session's offers only the ones its host computed (#1011). struct ApprovalRequestContent: Equatable { let description: String? let command: String? let scopeLine: AttributedString? let pendingCount: Int - /// In the host's order: `once` first, `deny` last. let choices: [ApprovalChoice] } @@ -20,7 +17,6 @@ extension ApprovalPromptState { } extension BotApprovalRequest { - /// This approval in a Hermes session's card, one of `pendingCount` open approvals. func requestContent(pendingCount: Int) -> ApprovalRequestContent { ApprovalRequestContent(description: consequence, command: command, scopeLine: scopeLine, pendingCount: max(pendingCount, 1), @@ -28,15 +24,8 @@ extension BotApprovalRequest { } } -/// A pending approval pinned above the composer, in the clarification's slot (#1584), so -/// the transcript stays readable while the agent waits. The warning-accented bar is the -/// permanent footprint: its height feeds the transcript's bottom inset. The expanded card -/// rises over it through the bar's clip window, scrolls once it is taller than the space -/// above the composer, and falls back to the bar when not even a line of it fits. A new -/// approval arrives expanded; ChatView gives each one its own identity. struct ApprovalRequestInset: View { let content: ApprovalRequestContent - /// Height between the chat's top safe edge and this inset's bottom edge. let maximumExpandedHeight: CGFloat let isResponding: Bool let isStopping: Bool @@ -47,7 +36,6 @@ struct ApprovalRequestInset: View { let onSkipAll: () -> Void let onStop: () -> Void let onDismissKeyboard: () -> Void - /// The bar's height, the only part of this view that takes layout space. let onFootprintChange: (CGFloat) -> Void @Environment(\.accessibilityReduceMotion) private var reduceMotion @@ -66,7 +54,6 @@ struct ApprovalRequestInset: View { onStop: onStop, kind: .approval(pendingCount: content.pendingCount) ) - // Hidden under the card, so its tinted edge never shows around the card's corners. .opacity(isExpanded ? 0 : 1) .accessibilityHidden(isExpanded) .onGeometryChange(for: CGFloat.self) { proxy in @@ -89,17 +76,14 @@ struct ApprovalRequestInset: View { .onAppear(perform: announceRequest) } - /// One line of what is being approved: the command's first line, else its description. static func barSummary(for content: ApprovalRequestContent) -> String { [content.command, content.description] .map { ClarificationRequestBar.summary(for: $0 ?? "") } .first { !$0.isEmpty } ?? "" } - /// Room for at least the card's header and a line of it. private var canFit: Bool { maximumExpandedHeight >= minimumCardHeight } - /// The card, scrolling once it is taller than the space left. Hidden until measured. private var card: some View { let shape = RoundedRectangle(cornerRadius: ChatComposerMetrics.cardCornerRadius, style: .continuous) return ScrollView { @@ -133,7 +117,6 @@ struct ApprovalRequestInset: View { } } - /// The card no longer takes over the screen, so VoiceOver hears that one arrived. private func announceRequest() { guard UIAccessibility.isVoiceOverRunning else { return } let announcement = String(localized: "Approval needed: \(Self.barSummary(for: content))") @@ -141,8 +124,6 @@ struct ApprovalRequestInset: View { } } -/// An approval's card: what will run, what each choice covers, the offered choices as -/// one-tap buttons, and Skip all. `ApprovalRequestInset` gives it its place and surface. struct ApprovalRequestCard: View { let content: ApprovalRequestContent let isResponding: Bool @@ -150,7 +131,6 @@ struct ApprovalRequestCard: View { let onChoice: (ApprovalChoice) -> Void let onSkipAll: () -> Void var summary: ApprovalSummaryPresentation? = nil - /// The header's collapse control; nil leaves it out. var onCollapse: (() -> Void)? = nil @AppStorage(ApprovalSummaries.enabledKey) private var explainsApprovals = ApprovalSummaries.enabledByDefault @ScaledMetric(relativeTo: .body) private var collapseButtonSize: CGFloat = 28 @@ -215,7 +195,6 @@ struct ApprovalRequestCard: View { .padding(10) .frame(maxWidth: .infinity, alignment: .leading) } - // Raised, since the card itself now sits on the surface color. .background(Color(uiColor: .appRaised), in: RoundedRectangle(cornerRadius: 8)) } @@ -266,8 +245,6 @@ struct ApprovalRequestCard: View { } } - /// Two per row in the offered order, so all four read as the familiar 2×2 and a withheld - /// choice never moves Allow once or Deny out of reach. private var rows: [[ApprovalChoice]] { stride(from: 0, to: content.choices.count, by: 2).map { Array(content.choices[$0.. String } -/// Optional model text, with no relationship to the approval controls' enabled state. -/// Mount it only while the switch is on. The request outlives this view: a remount (a -/// question taking the card's place, a room card moving up, a layout change) keeps it, -/// and only an accepted answer, a withdrawal, leaving, or the switch turning off ends it. struct ApprovalSummaryLine: View { let presentation: ApprovalSummaryPresentation @AppStorage(ApprovalSummaries.enabledKey) private var explainsApprovals = ApprovalSummaries.enabledByDefault @@ -42,7 +37,6 @@ struct ApprovalSummaryLine: View { } } -/// A single iPhone-wide opt-in switch, used by every direct-Hermes approval surface. struct ApprovalSummarySettingsSection: View { @AppStorage(ApprovalSummaries.enabledKey) private var explainsApprovals = ApprovalSummaries.enabledByDefault @@ -57,14 +51,11 @@ struct ApprovalSummarySettingsSection: View { } } -/// Memory-only state for one pending approval lifetime, not one presentation of its card. @MainActor @Observable final class ApprovalSummaries { static let shared = ApprovalSummaries() static let enabledKey = "chat.explainApprovalsInPlainWords" - /// Off until the user opts in: each summary is a model call on their server. static let enabledByDefault = false - /// The app's display language named in English, so the summary reads in the user's language. nonisolated static func language(_ identifier: String = Bundle.main.preferredLocalizations.first ?? "en") -> String { Locale(identifier: "en").localizedString(forIdentifier: identifier) ?? "English" } @@ -111,15 +102,12 @@ struct ApprovalSummarySettingsSection: View { } @ObservationIgnored private var requests: [Key: Request] = [:] - /// Leaving or turning the switch off ends unfinished work, but never - /// makes a still-pending approval eligible for a second model request. func cancel(_ key: Key) { guard let request = requests.removeValue(forKey: key) else { return } request.task.cancel() states[key] = .unavailable } - /// A single request the host explicitly settled or withdrew. func remove(_ key: Key) { cancel(key) states[key] = nil @@ -129,7 +117,6 @@ struct ApprovalSummarySettingsSection: View { for key in Array(requests.keys) where key.scope == scope { cancel(key) } } - /// Call only with a host-confirmed pending set, never a navigation/reset's empty UI. func retain(_ keys: Set, in scope: Scope) { for key in Array(states.keys) where key.scope == scope && !keys.contains(key) { remove(key) @@ -139,12 +126,9 @@ struct ApprovalSummarySettingsSection: View { func show(_ key: Key, load: @escaping @MainActor () async throws -> String) async { guard states[key] == nil, !Task.isCancelled else { return } states[key] = .loading - // Unstructured, so the presenting view's task ending doesn't cancel it. let request = Request(task: Task { try await load() }) requests[key] = request let result = await request.task.result - // Cancellation/pruning owns the state once it removes the request. A late reply - // must not repopulate a finished approval, even if its loader ignores cancellation. guard requests[key]?.token == request.token else { return } requests[key] = nil if !request.task.isCancelled, case .success(let value) = result { diff --git a/HermesMobile/Features/Chat/CameraPickerView.swift b/HermesMobile/Features/Chat/CameraPickerView.swift index 8a025a4c1..cd46cec29 100644 --- a/HermesMobile/Features/Chat/CameraPickerView.swift +++ b/HermesMobile/Features/Chat/CameraPickerView.swift @@ -107,9 +107,6 @@ final class HermexAttachmentCameraController: NSObject, ObservableObject, @unche sessionQueue.async { [weak self] in self?.captureRotationAngle = angle } } - /// Detaching a preview layer makes AVCaptureSession rebuild its graph and - /// wait for it to finish, which takes seconds on device. Run it on the - /// session queue so the main thread never blocks on it. func detachPreviewLayer(_ layer: AVCaptureVideoPreviewLayer) { sessionQueue.async { layer.session = nil @@ -555,7 +552,6 @@ private struct HermexAttachmentCameraPreview: UIViewRepresentable { } } -/// KVO callbacks may arrive off-main, but this view is only touched after hopping to main. private final class HermexAttachmentCameraPreviewView: UIView, @unchecked Sendable { override class var layerClass: AnyClass { AVCaptureVideoPreviewLayer.self } diff --git a/HermesMobile/Features/Chat/ChatActiveRunStatusView.swift b/HermesMobile/Features/Chat/ChatActiveRunStatusView.swift index 7d059f39f..7e6e547c9 100644 --- a/HermesMobile/Features/Chat/ChatActiveRunStatusView.swift +++ b/HermesMobile/Features/Chat/ChatActiveRunStatusView.swift @@ -1,10 +1,5 @@ import SwiftUI -/// Run-status pill above the composer, shown while the transcript is scrolled -/// away from its bottom. It never animates: a static dot marks it, and an -/// active run's elapsed time ticks once a second inside a `TimelineView` that -/// wraps only the label, so the tick re-renders nothing else and stops when -/// the pill hides. struct ChatActiveRunStatusView: View { let presentation: ChatActiveRunStatusPresentation @@ -42,9 +37,6 @@ struct ChatActiveRunStatusView: View { } } -/// Static status dot for run-status capsules: always in the pill, and in the -/// transcript's recovery chip under Reduce Motion. It stands in for a spinner -/// that would repaint for as long as the status shows. struct ChatRunStatusDot: View { var body: some View { Circle() @@ -80,8 +72,6 @@ private struct ChatActiveRunStatusPreviewStack: View { ChatActiveRunStatusPreviewStack() } -// The pill wraps to two or three lines here; ChatView measures its height for -// the transcript spacer instead of assuming one line. #Preview("Active Run Status · AX5") { ChatActiveRunStatusPreviewStack() .environment(\.dynamicTypeSize, .accessibility5) diff --git a/HermesMobile/Features/Chat/ChatAttachmentCoordinator.swift b/HermesMobile/Features/Chat/ChatAttachmentCoordinator.swift index 21b014474..5e85d35ce 100644 --- a/HermesMobile/Features/Chat/ChatAttachmentCoordinator.swift +++ b/HermesMobile/Features/Chat/ChatAttachmentCoordinator.swift @@ -31,7 +31,6 @@ final class ChatAttachmentCoordinator { private(set) var localAttachmentPreviews: [String: [String: Data]] = [:] private var activeUploadCount = 0 private var stagingIDs: Set = [] - /// Bytes of Hermes files still staging, so overlapping imports share the 50 MB total. private var stagingBytes = 0 private(set) var uploadStartGeneration = 0 @@ -50,14 +49,8 @@ final class ChatAttachmentCoordinator { private let draftStore: ChatDraftStore? private let attachmentLease: ChatDraftAttachmentLease? private var reservedUploadFilenames: Set = [] - /// Names held by pasted text still staging, so a paste that starts before the - /// last one lands takes the next name (#1381). private var stagingPasteNames: Set = [] - /// Long pastes still staging, so `cancelPastedTextStaging()` can stop them. private var pasteTasks: [UUID: Task] = [:] - /// A Hermes session (#1012): staging keeps only the local copy, under Bot Chat's - /// limits and image conversion, and Send or Queue uploads it - /// (`HermesChatTurnCoordinator`). A webui session uploads each file as it is staged. let uploadsOnSend: Bool init( @@ -88,10 +81,6 @@ final class ChatAttachmentCoordinator { } } - /// Saves a durable app-owned copy, uploads it, and appends the result to the - /// pending strip. Staging stops if the durable copy cannot be established, - /// so every attachment shown in the composer is restorable from its draft. - /// A Hermes session only stages the copy (`stageForSend`). @discardableResult func uploadAttachment(data: Data, filename: String, previewData: Data? = nil, isClipboardPaste: Bool = false) async -> PendingAttachment? { @@ -133,11 +122,6 @@ final class ChatAttachmentCoordinator { return attachment } - /// Starts staging a long paste as a text file under the next free `pasted-text` - /// name (#1381). The name is held before the task starts, against the strip and - /// every paste still staging, and the paste counts as an upload while the text is - /// encoded, so Send waits for it. The chat stops it with `cancelPastedTextStaging()` - /// as it goes away. @discardableResult func stagePastedText(_ text: String) -> Task { let filename = ComposerLargePaste.filename(avoiding: stagingPasteNames.union(pendingAttachments.map(\.name))) @@ -150,7 +134,6 @@ final class ChatAttachmentCoordinator { stagingPasteNames.remove(filename) pasteTasks[id] = nil } - // Measured before encoding, so a paste over the file limit never copies its text. let data = await Task.detached { text.utf8.count <= limit ? Data(text.utf8) : nil }.value activeUploadCount = max(activeUploadCount - 1, 0) guard !Task.isCancelled else { return nil } @@ -166,23 +149,16 @@ final class ChatAttachmentCoordinator { return task } - /// Stops every long paste still staging, so none lands after its chat is gone. func cancelPastedTextStaging() { pasteTasks.values.forEach { $0.cancel() } } - /// The text of a staged paste, read from its local copy for `StagedPasteSheet` (#1456). - /// Nil when the copy is gone or isn't UTF-8. func stagedPasteText(_ attachment: PendingAttachment) async -> StagedPasteText? { guard let file = attachment.draftFileName, let data = try? await draftAttachmentStore.data(named: file) else { return nil } return await Task.detached { StagedPasteText(data: data) }.value } - /// Puts edited text in place of a staged paste (#1456). The new copy is written first and - /// the draft saved before the old copy goes, so a failure at any step leaves the original - /// whole. The save counts as an upload, so Send waits for it. A tile removed or changed - /// meanwhile stays as it is. Returns why the edit did not save, or nil once it has. func replaceStagedPaste(_ attachment: PendingAttachment, with text: String) async -> String? { let isCurrent = { (staged: PendingAttachment, file: String?) in staged.id == attachment.id && staged.draftFileName == file } let notSaved = String(localized: "Your original text is unchanged. Try again shortly.") @@ -203,7 +179,6 @@ final class ChatAttachmentCoordinator { stagingBytes += data.count defer { stagingBytes -= data.count } - // A failure is reported in the sheet, so the composer's banner stays as it was. let banner = uploadAttachmentErrorMessage guard let file = await saveDraftCopy(data, filename: attachment.name, attachmentID: attachment.id, maximumBytes: limit) else { @@ -225,8 +200,6 @@ final class ChatAttachmentCoordinator { pendingAttachments[index] = edited let key = attachmentLease?.key if let key { draftStore?.replaceAttachmentRecord(ChatDraftAttachment(pending: edited), for: key) } - // Nothing else references the old copy now; an import freeing space must not take it - // before the save below decides whether the edit stands. attachmentLease?.files.insert(old) do { try await draftStore?.flush() @@ -243,16 +216,10 @@ final class ChatAttachmentCoordinator { return nil } - /// Re-uploads a restored draft attachment from its durable local copy, - /// preserving the draft record's identity so the restored pending - /// attachment reconciles with the persisted draft instead of duplicating - /// it. Failures stay quiet (no banner, no delegate error): the caller - /// reports them in aggregate and keeps the record for a later retry. @discardableResult func reuploadDraftAttachment(data: Data, draftAttachment: ChatDraftAttachment) async -> PendingAttachment? { if let file = draftAttachment.file { attachmentLease?.filesByAttachmentID[draftAttachment.id] = file } if uploadsOnSend { - // A Hermes send uploads it later; restoring only shows the local copy again. let attachment = PendingAttachment( id: draftAttachment.id, name: draftAttachment.name, path: "", mime: draftAttachment.mime, size: draftAttachment.size, isImage: draftAttachment.isImage, @@ -280,10 +247,6 @@ final class ChatAttachmentCoordinator { return attachment } - /// Keeps a durable local copy for a Hermes send to upload, under Bot Chat's rules: - /// eight files, 25 MB each and 50 MB in all; images re-encoded as JPEG, or PNG with - /// transparency (`BotAttachmentUpload.prepare`). Counts as an upload while it runs, so - /// the composer waits for it as it waits for a webui upload. private func stageForSend(data: Data, filename: String, isClipboardPaste: Bool) async -> PendingAttachment? { let stagingID = UUID() stagingIDs.insert(stagingID) @@ -312,7 +275,6 @@ final class ChatAttachmentCoordinator { defer { stagingBytes -= prepared.data.count } guard let file = await saveDraftCopy(prepared.data, filename: prepared.name, attachmentID: stagingID, maximumBytes: BotAttachmentUpload.maximumFileBytes) else { return nil } - // A cancelled import (a paste whose chat went away) keeps no copy and no tile. guard !Task.isCancelled else { await deleteDraftCopy(named: file, attachmentID: stagingID) return nil @@ -327,8 +289,6 @@ final class ChatAttachmentCoordinator { return attachment } - /// Saves the app-owned copy a staged attachment is restored from, or reports why it - /// could not and returns nil. private func saveDraftCopy(_ data: Data, filename: String, attachmentID: UUID, maximumBytes: Int = PendingAttachment.maximumUploadBytes) async -> String? { let draftFileName: String @@ -361,8 +321,6 @@ final class ChatAttachmentCoordinator { return draftFileName } - /// The staged files a Hermes Send or Queue uploads, in strip order, each read from its - /// local copy only when the send gets to it. func outgoingAttachments(_ attachments: [PendingAttachment]) -> [HermesChatTurnCoordinator.OutgoingAttachment] { attachments.map { attachment in HermesChatTurnCoordinator.OutgoingAttachment( @@ -377,7 +335,6 @@ final class ChatAttachmentCoordinator { } } - /// Removes files a send carried from the strip and deletes their local copies. func consumeSentAttachments(_ sent: [PendingAttachment]) async { let ids = Set(sent.map(\.id)) pendingAttachments.removeAll { ids.contains($0.id) } @@ -392,12 +349,6 @@ final class ChatAttachmentCoordinator { await ImagePreviewDownsampler.previewDataAsync(from: data, maxPixelSize: ImagePreviewDownsampler.attachmentMaxPixelSize) } - /// Uploads a single file and returns it as a `PendingAttachment` *without* - /// adding it to `pendingAttachments`. The voice-note flow uses this: the clip - /// is sent as the sole attachment of its own message, so it must not sweep up - /// the user's typed draft or other staged attachments — and it is never part - /// of a persisted draft. Failures surface via `uploadAttachmentErrorMessage` - /// and the method returns nil. func uploadStandaloneAttachment(data: Data, filename: String) async -> PendingAttachment? { await performUpload( data: data, @@ -512,7 +463,6 @@ final class ChatAttachmentCoordinator { await deleteUnreferencedCopy(fileName) } - /// Deletes a local copy unless a draft or a live owner still holds it. private func deleteUnreferencedCopy(_ fileName: String) async { if let draftStore { await draftStore.deleteAttachmentIfUnreferenced(fileName) @@ -535,8 +485,6 @@ final class ChatAttachmentCoordinator { } } - /// Raw attachment bytes with no image downsampling — used by the inline - /// audio player, which needs the original encoded audio data intact. func attachmentRawData(path: String) async -> Data? { guard let sessionID = delegate?.attachmentSessionID else { return nil } @@ -562,8 +510,6 @@ final class ChatAttachmentCoordinator { } } - /// Raw transcript media bytes for inline audio/video playback. Local paths - /// still require a real session ID so `/api/media` can authorize session media. func transcriptMediaData(for reference: TranscriptMediaReference) async -> Data? { guard let sessionID = delegate?.attachmentSessionID else { return nil } @@ -636,7 +582,6 @@ final class ChatAttachmentCoordinator { localAttachmentPreviews[messageID] = nil } - /// A Hermes prompt row's thumbnails, by file name: its chips carry no path (#1012). func keepLocalPreviews(of attachments: [PendingAttachment], forMessageID messageID: String) { var previews: [String: Data] = [:] for attachment in attachments { previews[attachment.name] = attachment.thumbnailData } diff --git a/HermesMobile/Features/Chat/ChatAttachmentPreviewView.swift b/HermesMobile/Features/Chat/ChatAttachmentPreviewView.swift index f53a1b845..6aa1fad1d 100644 --- a/HermesMobile/Features/Chat/ChatAttachmentPreviewView.swift +++ b/HermesMobile/Features/Chat/ChatAttachmentPreviewView.swift @@ -273,22 +273,16 @@ struct ChatAttachmentPreviewView: View { } } -/// What a staged paste's sheet shows: its text, or the start of a paste too long to edit. struct StagedPasteText: Equatable, Sendable { - /// Past this the sheet shows only the start, read-only. The largest size whose sheet - /// stayed responsive on a loaded iOS 27 simulator; at 512 KB, Done stopped responding. static let editableBytes = 256_000 static let sendingNotice = String(localized: "This text is being sent, so it can't be edited right now.") let text: String let totalBytes: Int - /// False when `text` is only the start of the file. let isWhole: Bool - /// Nil for bytes that aren't UTF-8, which would come back damaged if edited and saved. init?(data: Data) { var end = min(data.count, Self.editableBytes) - // A cut inside a character backs up to its first byte. while end > 0, end < data.count, data[data.startIndex + end] & 0xC0 == 0x80 { end -= 1 } guard let text = String(bytes: data.prefix(end), encoding: .utf8) else { return nil } self.text = text @@ -297,17 +291,12 @@ struct StagedPasteText: Equatable, Sendable { } } -/// Opens one staged paste. `isSending` is read as it opens: the sheet covers Send, and a -/// save checks again. struct StagedPasteItem: Identifiable { let attachment: PendingAttachment let isSending: Bool var id: UUID { attachment.id } } -/// Shows a staged paste and, unless a send holds it or it is too long, edits it (#1456). -/// Cancel and Save both close the sheet. The chat's `load` and `save` keep it free of the -/// attachment stores. struct StagedPasteSheet: View { private enum Content { case loading, unreadable @@ -316,7 +305,6 @@ struct StagedPasteSheet: View { let item: StagedPasteItem let load: () async -> StagedPasteText? - /// Returns why the edit did not save, or nil once it has. let save: (String) async -> String? @State private var content = Content.loading @@ -450,8 +438,6 @@ struct StagedPasteSheet: View { } } -/// Owns the sheet's text view, whose text stays there until Save. Only the flags below reach -/// SwiftUI, and only when they flip, so typing in a long paste redraws nothing and copies nothing. @MainActor @Observable final class StagedPasteBuffer: NSObject, UITextViewDelegate { @@ -462,8 +448,6 @@ final class StagedPasteBuffer: NSObject, UITextViewDelegate { var text: String? { textView?.text } - /// Starts editing where the user is reading: a selection stays, otherwise the caret goes - /// to the top of what's on screen, so the keyboard doesn't jump back to the first line. func beginEditing() { guard let textView else { return } isEditing = true @@ -480,7 +464,6 @@ final class StagedPasteBuffer: NSObject, UITextViewDelegate { textView.becomeFirstResponder() } - /// Off while a save runs, so nothing typed after Save is lost when the sheet closes. func setEditable(_ isEditable: Bool) { textView?.isEditable = isEditable } @@ -492,8 +475,6 @@ final class StagedPasteBuffer: NSObject, UITextViewDelegate { } } -/// The paste in a wrapping, selectable text view. Text-changing keyboard helpers stay off so -/// a log isn't altered as it's edited. private struct StagedPasteTextView: UIViewRepresentable { let text: String let name: String @@ -528,14 +509,9 @@ private struct StagedPasteTextView: UIViewRepresentable { return textView } - /// The text view keeps the text from here on (`StagedPasteBuffer`). func updateUIView(_ textView: UITextView, context: Context) {} } -/// An attachment that is already known to be an image opens in the full-bleed lightbox. -/// Text, audio, Quick Look documents, and anything without a preview keep -/// `ChatAttachmentPreviewView`, which only learns what it has once the server answers. -/// `page` ties it to its gallery's pager. struct ChatAttachmentImageLightbox: View { let onAPIError: (Error) -> Void @@ -622,8 +598,6 @@ final class ChatAttachmentPreviewViewModel { previewImage = if case let .image(file) = preview { UIImage(data: file.data) } else { nil } } } - /// An image preview decoded once, so a redraw hands the lightbox the same image and - /// keeps its zoom. private(set) var previewImage: UIImage? private(set) var isLoading = false private(set) var errorMessage: String? @@ -648,8 +622,6 @@ final class ChatAttachmentPreviewViewModel { } preview = nil - // A pathless item, such as a Hermes session's chip (#1012), shows its local copy - // and never needs the session. let trimmedPath = item.path?.trimmingCharacters(in: .whitespacesAndNewlines) guard let path = trimmedPath, !path.isEmpty else { preview = localFallbackPreview @@ -680,9 +652,6 @@ final class ChatAttachmentPreviewViewModel { preview = .unavailable(String(localized: "Could not decode this image.")) } } else if item.inferredIsAudio { - // Raw bytes (no downsampling) so AVAudioPlayer gets the original - // encoded audio; checked before the Quick Look list, which would - // otherwise take m4a/mp3/wav/flac away from the inline player. let data = try await apiClient.rawFileData(sessionID: sessionID, path: path) guard generation == loadGeneration, !Task.isCancelled else { return } preview = .audio(data) diff --git a/HermesMobile/Features/Chat/ChatComposerAttachmentStripView.swift b/HermesMobile/Features/Chat/ChatComposerAttachmentStripView.swift index 2c7b83a67..b9abca3e6 100644 --- a/HermesMobile/Features/Chat/ChatComposerAttachmentStripView.swift +++ b/HermesMobile/Features/Chat/ChatComposerAttachmentStripView.swift @@ -1,8 +1,6 @@ import SwiftUI import UIKit -/// A staged document's badge slot in the strip. Its Quick Look preview is made -/// at this size, and the pill's smaller tile draws the same image scaled down. private let documentBadgeSize = CGSize(width: 58, height: 68) struct ComposerAttachmentStripView: View { @@ -38,8 +36,6 @@ struct ComposerAttachmentStripView: View { } } -/// Pill-state summary of pending attachments: up to three 30 pt tiles plus a -/// `+N` chip, so nothing pending is ever out of sight while the editor is idle. struct ComposerAttachmentPillPreview: View { let attachments: [PendingAttachment] let onPreview: (PendingAttachment) -> Void @@ -108,10 +104,6 @@ struct ComposerAttachmentPillPreview: View { } } -/// Loads a staged document's Quick Look preview and hands it to `content`: -/// nil until it arrives, and for good when Quick Look can't draw one, so the -/// tile keeps its icon. A preview made earlier, by this tile or the other -/// composer state, draws in the first frame. The swap never animates. private struct ComposerDocumentThumbnail: View { let attachment: PendingAttachment @ViewBuilder let content: (UIImage?) -> Content @@ -218,8 +210,6 @@ private struct ComposerAttachmentThumbnailView: View { .scaledToFill() .frame(width: documentBadgeSize.width, height: documentBadgeSize.height) .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) - // Keeps a white page from dissolving into a light - // tile, and gives it an edge in dark mode. .overlay(previewBorder(cornerRadius: 10)) } else { fileBadge @@ -254,8 +244,6 @@ private struct ComposerAttachmentThumbnailView: View { .accessibilityLabel("File attachment \(attachment.name), \(fileDetailText)") } - /// The document's icon and extension, until (or unless) Quick Look draws - /// a preview in the same slot. private var fileBadge: some View { ZStack { RoundedRectangle(cornerRadius: 10, style: .continuous) diff --git a/HermesMobile/Features/Chat/ChatComposerConfigLoader.swift b/HermesMobile/Features/Chat/ChatComposerConfigLoader.swift index f8e891e7a..91cf913cb 100644 --- a/HermesMobile/Features/Chat/ChatComposerConfigLoader.swift +++ b/HermesMobile/Features/Chat/ChatComposerConfigLoader.swift @@ -7,11 +7,7 @@ struct ChatComposerConfigState: Equatable, Sendable { var currentProfile: String? var selectedProfileName: String? var selectedReasoningEffort: String? - /// Model-aware effort vocabulary (`supported_efforts`); `nil` on older - /// servers → composer falls back to the full static list (issue #18). var supportedReasoningEfforts: [String]? - /// `supports_reasoning_effort`; `false` hides the effort control, `nil` - /// (older servers) keeps it visible. var supportsReasoningEffort: Bool? var modelCatalogGroups: [ModelCatalogGroup] var agentCommands: [AgentCommand] @@ -65,13 +61,6 @@ struct ChatComposerConfigLoader { self.client = client } - /// Loads the composer's server config for a chat. Profiles (and a switch to - /// the session's profile) go first because `/api/models` and - /// `/api/workspaces` are profile-scoped upstream. After that, models, - /// workspaces, and commands load concurrently; only reasoning waits, for the - /// model it is scoped to. Errors keep the serial order's precedence - /// (profiles, models, reasoning, workspaces), and commands load even when the - /// rest fails. func loadConfiguration(from initialState: ChatComposerConfigState) async -> ChatComposerConfigLoadResult { var state = initialState var configurationError: Error? @@ -145,9 +134,6 @@ struct ChatComposerConfigLoader { ?? Self.uniqueProvider(for: state.currentModel, in: state.modelCatalogGroups) } - // Scope the query to the session's resolved model/provider so the - // gating fields are model-accurate (issue #18); the seeded effort is - // the server's already-coerced value for that model. let reasoningResponse = try await client.reasoning( model: Self.nonEmpty(state.currentModel), provider: Self.nonEmpty(state.currentModelProvider) diff --git a/HermesMobile/Features/Chat/ChatComposerPresentation.swift b/HermesMobile/Features/Chat/ChatComposerPresentation.swift index 4a05d36eb..d64610d47 100644 --- a/HermesMobile/Features/Chat/ChatComposerPresentation.swift +++ b/HermesMobile/Features/Chat/ChatComposerPresentation.swift @@ -1,20 +1,13 @@ import SwiftUI -/// Shared geometry for Sessions and the text-only Bot composer. enum ChatComposerMetrics { static let cardCornerRadius: CGFloat = 26 static let actionSize: CGFloat = 44 static let pillInset: CGFloat = 5 - /// The tallest a `/` or `@` suggestion panel grows on a roomy screen. static let panelMaximumHeight: CGFloat = 280 } extension View { - /// Sizes a `/` or `@` suggestion panel to its rows, but lets it shrink to - /// the room left above the composer, so a short viewport (iPhone Duo, - /// landscape, large text) keeps the text card and Send above the keyboard. - /// The panel scrolls, so a short one still reaches every row. The stack - /// that holds it gives it `.layoutPriority(-1)` so the composer sizes first. func composerPanelHeight(_ height: CGFloat) -> some View { frame(minHeight: 0, maxHeight: min(ChatComposerMetrics.panelMaximumHeight, height)) } @@ -68,18 +61,11 @@ struct ChatComposerActionAppearance { } } -/// A row the send-choice card can list. Bots list `BotPromptMode`; Sessions -/// list `StreamingSendBehavior`. protocol SendChoice: Hashable { var title: String { get } var systemImage: String { get } } -/// The send-choice card: the "+" picker's chrome (scrim, material panel, the -/// same present and dismiss motion) holding what a send can do to a running -/// turn. It sits bottom-trailing, by the Send button that opened it, and a -/// pick submits at once. Bot Chat opens it when a send lands on a working bot; -/// the Sessions composer opens it on a long-press of Send mid-run. struct SendChoiceCard: View { @Environment(\.accessibilityReduceMotion) private var reduceMotion @Environment(\.accessibilityReduceTransparency) private var reduceTransparency @@ -145,8 +131,6 @@ struct SendChoiceCard: View { private func dismiss() { finish(onDismiss) } - /// Fades the card out, then hands control back; a pick and a dismissal - /// leave the same way. private func finish(_ completion: @escaping () -> Void) { guard !isDismissing else { return } isDismissing = true diff --git a/HermesMobile/Features/Chat/ChatComposerSelectorControls.swift b/HermesMobile/Features/Chat/ChatComposerSelectorControls.swift index db8fb9986..460e38665 100644 --- a/HermesMobile/Features/Chat/ChatComposerSelectorControls.swift +++ b/HermesMobile/Features/Chat/ChatComposerSelectorControls.swift @@ -29,8 +29,6 @@ struct ComposerProfileSelectorMenu: View { let profileOptions: [ProfileSummary] let selectedProfileName: String? let selectedProfileTitle: String - /// Single-profile servers reject switches (#24), so the control is a plain - /// label: no chevron, no menu, no button trait. let isStatic: Bool let isDisabled: Bool let color: Color @@ -101,8 +99,6 @@ struct ComposerProfileSelectorMenu: View { } } -/// The composer's model label, which opens Model settings. Keyboard down it is only the -/// provider's logo and a chevron; keyboard up the title takes the row's spare width and truncates. struct ComposerModelLabelButton: View { let showsTitle: Bool let selection: ComposerModelEffortSelection @@ -149,18 +145,14 @@ struct ComposerModelLabelButton: View { } } -/// What Model settings' Approvals row shows and may change. struct ComposerApprovals: Equatable { let isYoloOn: Bool - /// A Hermes session's Profile has an approval mode. A webui session has only YOLO. let offersModes: Bool - /// The host's `approval_mode`, nil until it reports one. let mode: String? let mayTurnOffYolo: Bool let isChanging: Bool let errorMessage: String? - /// The state in effect: Off wins, then YOLO, then the mode. Nil when nothing is known. var value: String? { if mode == HermesApprovalMode.off.rawValue { return Self.title(for: .off) } if isYoloOn { return "YOLO" } @@ -168,11 +160,8 @@ struct ComposerApprovals: Equatable { return HermesApprovalMode(rawValue: mode).map(Self.title(for:)) ?? mode.capitalized } - /// YOLO is on and this chat can't turn it off: the mode or a `--yolo` launch holds it. var isYoloLocked: Bool { isYoloOn && !mayTurnOffYolo } - /// YOLO is on and this chat can turn it off. This stays open during a run: stopping a bypass - /// can't wait for the work it's letting through. var canTurnOffYolo: Bool { isYoloOn && mayTurnOffYolo } static func title(for mode: HermesApprovalMode) -> String { @@ -189,7 +178,6 @@ struct ComposerModelEffortSelection: Equatable, Sendable { let effort: String? let supportedEfforts: [String]? let supportsEffort: Bool? - /// The level a Hermes host sends when the model's route takes less than `effort` (#1016). var sentEffort: String? = nil var modelProviderID: String? { @@ -226,24 +214,20 @@ struct ComposerModelEffortSelection: Equatable, Sendable { var title: String { let modelLabel = ModelDisplayNames.displayLabel(for: model.id, displayName: model.displayName) - // No level reported yet: a placeholder word would only push the model's name out. guard committedEffort != nil, let effortTitle else { return modelLabel } return "\(modelLabel) · \(effortTitle)" } - /// `title` for VoiceOver, which reads a lowered level as a sentence rather than symbols. var accessibilityTitle: String { guard let effort = committedEffort, let lowered = loweredEffort else { return title } let picked = ReasoningEffortOption.title(for: effort), sent = ReasoningEffortOption.title(for: lowered) return String(localized: "\(ModelDisplayNames.displayLabel(for: model.id, displayName: model.displayName)), \(picked) effort, sent as \(sent)") } - /// The same model with `level` chosen, for a level still on its way to the host. func replacingEffort(with level: String) -> Self { Self(model: model, effort: level, supportedEfforts: supportedEfforts, supportsEffort: supportsEffort) } - /// `sentEffort` when it differs from the committed level. private var loweredEffort: String? { guard let effort = committedEffort, let sent = normalizedEffort(sentEffort), sent != effort else { return nil } return sent @@ -256,8 +240,6 @@ struct ComposerModelEffortSelection: Equatable, Sendable { } } -/// Quiet toolbar-row control: icon, one-line title, optional chevron, no pill -/// background, so the row reads as one surface. 44 pt tall for the hit target. struct ComposerInlineControlLabel: View { static let minimumHeight: CGFloat = 44 static let horizontalPadding: CGFloat = 6 @@ -295,7 +277,6 @@ struct ReasoningEffortOption: Identifiable, CaseIterable { let id: String let title: String - /// webui's static ladder, and the fallback when a server sends no vocabulary (#18). static let allCases: [ReasoningEffortOption] = [ ReasoningEffortOption(id: "none", title: String(localized: "None")), ReasoningEffortOption(id: "minimal", title: String(localized: "Minimal")), @@ -305,8 +286,6 @@ struct ReasoningEffortOption: Identifiable, CaseIterable { ReasoningEffortOption(id: "xhigh", title: String(localized: "XHigh")) ] - /// Every level with a title: webui's ladder plus the levels only a Hermes host offers - /// (#1016), which stay out of webui's fallback. private static let titled = allCases + [ ReasoningEffortOption(id: "max", title: String(localized: "Max")), ReasoningEffortOption(id: "ultra", title: String(localized: "Ultra")) @@ -317,7 +296,6 @@ struct ReasoningEffortOption: Identifiable, CaseIterable { ?? effort.capitalized } - /// `title`, shortened where eight of them share a line under the Thinking control. static func shortTitle(for effort: String) -> String { switch effort { case "minimal": String(localized: "Min") @@ -326,11 +304,6 @@ struct ReasoningEffortOption: Identifiable, CaseIterable { } } - /// Menu options for a server-provided effort vocabulary (issue #18). - /// `nil` or empty → the full static list (older servers / defensive fallback; - /// an empty list also means `supports_reasoning_effort == false`, which hides - /// the control before this is ever rendered). Unknown ids are kept with a - /// capitalized title so a newer server's vocabulary still works. static func options(forSupportedEfforts supportedEfforts: [String]?) -> [ReasoningEffortOption] { guard let supportedEfforts, !supportedEfforts.isEmpty else { return allCases } @@ -341,16 +314,11 @@ struct ReasoningEffortOption: Identifiable, CaseIterable { .map { id in ReasoningEffortOption(id: id, title: title(for: id)) } } - /// The lone effort when the server vocabulary leaves nothing to choose, so the - /// composer can render a static label instead of a one-item menu. static func singleOption(forSupportedEfforts supportedEfforts: [String]?) -> ReasoningEffortOption? { let options = options(forSupportedEfforts: supportedEfforts) return options.count == 1 ? options[0] : nil } - /// Whether the composer should show the effort control at all (issue #18). - /// `supports_reasoning_effort == false` hides it; older servers (both fields - /// absent) keep today's behavior and show it. static func showsEffortControl( supportsReasoningEffort: Bool?, supportedEfforts: [String]? diff --git a/HermesMobile/Features/Chat/ChatComposerSelectorSheets.swift b/HermesMobile/Features/Chat/ChatComposerSelectorSheets.swift index 5bb2b37f4..e69655e2d 100644 --- a/HermesMobile/Features/Chat/ChatComposerSelectorSheets.swift +++ b/HermesMobile/Features/Chat/ChatComposerSelectorSheets.swift @@ -1,11 +1,8 @@ import SwiftUI -/// Workspace, Profile and context for one chat, opened from the chat header. The -/// composer supplies the pickers so they keep the gates they have in the new-chat row. struct ChatSettingsSheet: View { let workspaceTitle: String let isWorkspaceDisabled: Bool - /// What choosing another Profile does, where that differs from changing this chat. let profileNote: String? let contextSnapshot: ContextWindowSnapshot? @ViewBuilder let workspacePicker: () -> WorkspacePicker @@ -64,7 +61,6 @@ struct ChatSettingsSheet: View { } } -/// The rows of Model settings that change a setting on the host. enum ModelSettingsRow: Equatable { case model case thinking @@ -72,14 +68,10 @@ enum ModelSettingsRow: Equatable { case approvals } -/// What a row shows beside its value once the host has answered the user's change. Nothing -/// shows while it is out, so the rows never shift under the finger. enum ModelSettingsRowStatus: Equatable { case failed(String) - /// The host took the change and applies it later, such as after the running response. case notice(String) - /// Only the row that asked hears the answer, and only since this sheet opened. static func resolve( row: ModelSettingsRow, lastChanged: ModelSettingsRow?, @@ -94,9 +86,6 @@ enum ModelSettingsRowStatus: Equatable { } } -/// The chat's model and how it runs, opened from the composer's model label. Each change -/// applies on its own, so there is no Save. Picking a model can raise the host's -/// expensive-model question, which the composer attaches over this sheet. struct ModelSettingsSheet: View { let selection: ComposerModelEffortSelection let providerName: String? @@ -106,17 +95,14 @@ struct ModelSettingsSheet: View { let isUpdating: Bool let errorMessage: String? let notice: String? - /// This chat's Fast mode; nil where the host reports none, which hides the row. let fastMode: Bool? let mayChangeFastMode: Bool - /// Nil hides the row, on a composer with no session. let approvals: ComposerApprovals? let onSelectModel: (ModelCatalogOption) -> Void let onSelectEffort: (String) async -> Bool let onSelectFastMode: (Bool) -> Void let onSetYolo: (Bool) -> Void let onSelectApprovalMode: (HermesApprovalMode) -> Void - /// All models, given the commit that keeps this sheet's status in step. let allModelsPicker: (@escaping (ModelCatalogOption) -> Void) -> AllModels @Environment(\.dismiss) private var dismiss @@ -124,7 +110,6 @@ struct ModelSettingsSheet: View { @State private var lastChanged: ModelSettingsRow? @State private var levelSender = ThinkingLevelSender() - /// The chat's state, with a Thinking level still on its way already showing. private var shownSelection: ComposerModelEffortSelection { levelSender.pendingLevel.map(selection.replacingEffort(with:)) ?? selection } @@ -190,12 +175,10 @@ struct ModelSettingsSheet: View { .font(AppFont.caption(weight: .semibold)) .foregroundStyle(.appTertiary) } - // Keeps the requested level and the one the host sends apart (#1016). Text(verbatim: [providerName, shownSelection.committedEffort == nil ? nil : shownSelection.effortTitle] .compactMap { $0 }.joined(separator: " · ")) .font(AppFont.caption()) .foregroundStyle(.appSecondary) - // One line, so a level's "sent as" never moves the rows below it. .lineLimit(1) statusLine(for: .model) } @@ -212,27 +195,22 @@ struct ModelSettingsSheet: View { LabeledContent("Thinking", value: only.title) } else { ThinkingControl(selection: shownSelection, isDisabled: isDisabled, isCovered: showsAllModels) { level in - // VoiceOver's adjustment arrives here past the hit test below. guard !isUpdating || levelSender.isSending else { return } lastChanged = .thinking levelSender.request(level, send: onSelectEffort) } - // The host refuses a level while another kind of change is out. Its own sends - // stay open, since the sender keeps the newest of them. .allowsHitTesting(!isUpdating || levelSender.isSending) } statusLine(for: .thinking) } } - /// Follows the chat's state, so the switch only stays moved once the host answers. private func fastRow(isOn: Bool) -> some View { VStack(alignment: .leading, spacing: 2) { Toggle("Fast", isOn: Binding(get: { isOn }, set: { enabled in lastChanged = .fast onSelectFastMode(enabled) })) - // While another change is out, `allowsHitTesting` holds it off without a flash of grey. .disabled(isDisabled || !(mayChangeFastMode || isUpdating)) .allowsHitTesting(!isUpdating) statusLine(for: .fast) @@ -325,7 +303,6 @@ struct ModelSettingsSheet: View { } } -/// A row's failed or later-applied line. private struct ModelSettingsStatusLine: View { let status: ModelSettingsRowStatus? @@ -341,9 +318,6 @@ private struct ModelSettingsStatusLine: View { } } -/// YOLO for this chat and, on Hermes, the mode for every chat in the Profile. The wording is -/// Official Hermes's; the section label is ours, because copy states the real consequence: the -/// host writes the mode to that Profile's config. Off asks first for the same reason. private struct ApprovalChoicesView: View { let approvals: ComposerApprovals let isDisabled: Bool @@ -421,18 +395,13 @@ private struct ApprovalChoicesView: View { } struct ComposerWorkspacePickerSheet: View { - /// Direct-Hermes validates a typed path itself; webui uses trusted suggestions. var allowsCustomPath = false let workspaceRoots: [WorkspaceRoot] let selectedWorkspacePath: String? let suggestions: [String] - /// Server base URL used to open the registry manager; nil hides the - /// Manage affordance (e.g. offline cached mode). var managementServer: URL? let onLoadSuggestions: (String) async -> Void let onSelect: (String) async -> Void - /// Called after the registry manager closes having changed the registry, - /// so the owner can refetch `workspaceRoots`. var onRegistryChanged: () async -> Void = {} @Environment(\.dismiss) private var dismiss diff --git a/HermesMobile/Features/Chat/ChatComposerSendGate.swift b/HermesMobile/Features/Chat/ChatComposerSendGate.swift index cbe35d41f..98ab980a1 100644 --- a/HermesMobile/Features/Chat/ChatComposerSendGate.swift +++ b/HermesMobile/Features/Chat/ChatComposerSendGate.swift @@ -1,9 +1,5 @@ import Foundation -/// Decides whether the composer's Send/Stop action button is disabled. -/// Send is allowed when the user typed something, added a quote, or staged at -/// least one attachment. Attachment-only sends synthesize their message text in -/// `PendingAttachment.chatMessageText`; a send block always disables. enum ChatComposerSendGate { static func showsStopButton( isWaitingForStream: Bool, @@ -23,18 +19,10 @@ enum ChatComposerSendGate { } } -/// How the chat's state limits its composer. A read-only session locks the draft and -/// every control. A chat showing its offline cache (#1375) keeps the draft editable and -/// holds Send and every control that reaches the host until it reconnects, except a Hermes -/// chat's plain-text Send, which waits as the transcript's waiting send (#1407). struct ChatComposerAccess: Equatable { - /// The status line's "Read-only"; it locks the editor. let readOnlyMessage: String? - /// The chat shows its offline cache, so Send waits for the reconnect. let isOffline: Bool - /// Offline, a plain-text Send waits for the reconnect instead of being held. let offersWaitingSend: Bool - /// A Send waits for the reconnect, so every other Send is held until it goes or comes back. let hasWaitingSend: Bool init(session: SessionSummary, isViewingCachedData: Bool, offersWaitingSend: Bool = false, hasWaitingSend: Bool = false) { @@ -46,26 +34,19 @@ struct ChatComposerAccess: Equatable { var allowsEditing: Bool { readOnlyMessage == nil } - /// Whether being offline holds Send for this draft: everything but plain text (no quotes, files - /// or `/` command) where a waiting send is offered. func holdsSendOffline(isPlainText: Bool) -> Bool { isOffline && !(offersWaitingSend && isPlainText) } - /// File and host-argument searches, dictation, voice notes, attachments, and - /// configuration, branch, and workspace changes all reach the host. var allowsHostControls: Bool { allowsEditing && !isOffline } } -/// Whether a chat still counts as new, with its settings above the composer rather than in -/// the header. The server's count keeps the row from flashing while an existing chat loads. enum ChatComposerNewChatPolicy { static func showsControls(hasMessages: Bool, serverMessageCount: Int?, isStreaming: Bool) -> Bool { !hasMessages && (serverMessageCount ?? 0) == 0 && !isStreaming } } -/// Which composer controls respond while work is in progress. struct ChatComposerControlGate { let access: ChatComposerAccess let isSending: Bool @@ -73,29 +54,21 @@ struct ChatComposerControlGate { let isWaitingForStream: Bool let isUpdatingConfiguration: Bool - /// `+` only opens the picker, and a pick waits in the draft like a paste, so no - /// work in progress holds it (#1436). var allowsAttaching: Bool { access.allowsHostControls } - /// Model, workspace, and Profile changes wait for the chat to settle. var allowsConfiguration: Bool { allowsConfigurationIgnoringUpdates && !isUpdatingConfiguration } - /// The same, for Model settings, whose rows hold off during a change without dimming. var allowsConfigurationIgnoringUpdates: Bool { access.allowsHostControls && !isSending && !isCompressingSession && !isWaitingForStream } - /// Whether the model label opens Model settings. During a run it still opens to turn YOLO off, - /// with every other row held. func allowsModelSettings(approvals: ComposerApprovals?) -> Bool { allowsConfiguration || (access.allowsHostControls && approvals?.canTurnOffYolo == true) } } -/// Work in progress that holds Send even with a draft to send. VoiceOver reads it -/// as a dimmed Send's value, so the user knows what they are waiting for. enum ChatComposerSendBlock: Equatable { case waitingForConnection case offline @@ -104,7 +77,6 @@ enum ChatComposerSendBlock: Equatable { case uploadingAttachment case updatingConfiguration - /// The first condition that holds Send, or nil when none does. init?(isWaitingForConnection: Bool = false, isOffline: Bool, isSending: Bool, isCompressingSession: Bool, isUploadingAttachment: Bool, isUpdatingConfiguration: Bool) { if isWaitingForConnection { @@ -124,7 +96,6 @@ enum ChatComposerSendBlock: Equatable { } } - /// The composer status line's wording for the same state. var accessibilityValue: String { switch self { case .waitingForConnection: String(localized: "Waiting for connection") @@ -137,21 +108,9 @@ enum ChatComposerSendBlock: Equatable { } } -/// The Sessions composer's trailing circle. Stop while a response runs and the -/// draft is empty; otherwise Send. Mid-run a tap on Send uses the Send While -/// Responding default, the glyph and VoiceOver label say which behavior that -/// is, and a long-press (or a VoiceOver action) picks any behavior for this one -/// message. Idle, Send is a plain send with no choices. struct ChatComposerSendButton: Equatable { let showsStop: Bool - /// What a tap on Send does to the running response; nil while idle or - /// while the circle is Stop. The composer dispatches exactly this, so the - /// glyph never says one behavior while a tap does another. let runningBehavior: StreamingSendBehavior? - /// A Hermes session with files staged (#1012): only a fresh turn takes them, so Steer - /// drops out and a Steer default queues them. Stop and send stays, text-only, and - /// leaves them staged. Files alone are a draft too (#1367): mid-run they queue under - /// every default, with nothing else to choose. let stagedFilesDropSteer: Bool private let queuesStagedFilesOnly: Bool @@ -167,8 +126,6 @@ struct ChatComposerSendButton: Equatable { self.stagedFilesDropSteer = stagedFilesDropSteer } - /// The circle's one SF Symbol: Stop, the running default's symbol, or the - /// plain arrow. var systemName: String { if showsStop { return "stop.fill" } return runningBehavior?.systemImage ?? "arrow.up" @@ -179,47 +136,33 @@ struct ChatComposerSendButton: Equatable { return runningBehavior?.settingsDescription ?? String(localized: "Send") } - /// The long-press choices, in the Bot card's order. On a webui session, staged - /// files keep Steer: a steer carries them as an attached-files note (#856). var choices: [StreamingSendBehavior] { guard runningBehavior != nil, !queuesStagedFilesOnly else { return [] } return stagedFilesDropSteer ? [.queue, .interrupt] : [.steer, .queue, .interrupt] } - /// ⌘⇧↩'s pick from `choices` (#1380): the first one Send does not already do. Never - /// Stop and send, so a key chord cannot end the run; nil while idle or when that - /// would be all that is left. var alternateBehavior: StreamingSendBehavior? { choices.first { $0 != runningBehavior && $0 != .interrupt } } } -/// Keeps a hold on Send from also counting as a tap. A hold that opens the -/// send-choice card marks its own release to be dropped. A new touch-down, the -/// dropped release, or the card closing after the finger lifted clears the mark. struct ChatComposerSendHold { private var holdOpenedChoices = false - /// A new touch-down on Send: any earlier hold is over. mutating func pressBegan() { holdOpenedChoices = false } - /// The hold timer fired and opened the card. mutating func openedChoices() { holdOpenedChoices = true } - /// The card closed. A finger still down keeps its release dropped; one - /// that lifted off the button never reached Send, so the mark goes. mutating func choicesClosed(isPressing: Bool) { if !isPressing { holdOpenedChoices = false } } - /// Send's Button action: a tap, a keyboard or assistive activation, or a - /// hold's release. Returns whether Send should act; a hold's release does not. mutating func activate() -> Bool { guard holdOpenedChoices else { return true } holdOpenedChoices = false @@ -227,10 +170,8 @@ struct ChatComposerSendHold { } } -/// Device-local presentation choices shared by Sessions servers, never Bot Chat. enum SessionChatPreferences { static let dismissKeyboardKey = "sessionChat.dismissKeyboardAfterSend" - /// Settings' Send with Return (#1655), read by every composer editor. Off by default. static let returnSendsKey = "sessionChat.returnSends" static let completionPositionKey = "sessionChat.completionPosition" @@ -251,7 +192,6 @@ enum SessionChatPreferences { } } -/// An asynchronous send must not overwrite a newer editing session or draft. enum ChatSendFocusPolicy { static func focusAfterSubmission( succeeded: Bool, dismissKeyboard: Bool, wasFocused: Bool, diff --git a/HermesMobile/Features/Chat/ChatComposerTextInputView.swift b/HermesMobile/Features/Chat/ChatComposerTextInputView.swift index 9f8cd7d70..51aa2c23f 100644 --- a/HermesMobile/Features/Chat/ChatComposerTextInputView.swift +++ b/HermesMobile/Features/Chat/ChatComposerTextInputView.swift @@ -2,21 +2,10 @@ import SwiftUI import UIKit import UniformTypeIdentifiers -/// The card editor's height, shared by the Sessions, Bot Chat and Bot room -/// composers. It grows with the text from `expandedMinimum` up to the text -/// view's 160 pt measure cap. Where height is limited (iPhone landscape, or a -/// short viewport above the keyboard) it holds a fixed minimum and scrolls inside, -/// so the transcript or the composer's own controls stay visible. A nil size -/// class counts as regular. enum ComposerTextInputHeight { - /// At least 72 pt of real text view, so a tap anywhere in the card lands - /// on the editor rather than dead space; about three lines at default size. static let expandedMinimum: CGFloat = 72 - /// The chat viewport below which a full composer can overflow behind the keyboard: iPhone - /// Duo's displays leave about 300 pt, where a size class still says regular. static let shortViewportHeight: CGFloat = 360 - /// About two lines, which keeps Send above the keyboard with an attachment in the card. static let shortViewportMinimum: CGFloat = 48 static func expanded(measured: CGFloat, verticalSizeClass: UserInterfaceSizeClass?, isViewportShort: Bool) -> CGFloat { @@ -26,8 +15,6 @@ enum ComposerTextInputHeight { } extension EnvironmentValues { - /// The chat viewport is below `ComposerTextInputHeight.shortViewportHeight`, so the composer - /// keeps to what it needs for sending. @Entry var composerViewportIsShort = false } @@ -38,28 +25,17 @@ struct ComposerTextInputView: View { @Binding var inputHeight: CGFloat @Binding var measuredHeight: CGFloat - /// Compact in iPhone landscape, where the card editor stops growing, as it does in a short viewport. @Environment(\.verticalSizeClass) private var verticalSizeClass @Environment(\.composerViewportIsShort) private var viewportIsShort @AppStorage(SessionChatPreferences.returnSendsKey) private var returnSends = false - /// The chips the editor has drawn. The collapsed pill draws this same set - /// rather than deriving its own, because a trailing chip whose space was - /// deleted stays a chip only in the editor's history. @State private var renderedChips: [ComposerChipToken] = [] let isDisabled: Bool - /// Pill mode: a single truncated line stands in for the editor and a tap - /// focuses it. The text view stays in the hierarchy (invisible) so focus and - /// the draft survive the pill-to-card morph without recreating it. let isCollapsed: Bool let keyboardCommands: ComposerKeyboardCommands let verticalPadding: CGFloat - /// The skills whose references the editor draws as chips. Empty until the - /// server's skill list has loaded, which leaves the draft as plain text. let chipSkills: [SkillSlashSuggestion] - /// The workspace files picked in this chat, whose `@path` references the - /// editor draws as chips. let chipFilePaths: Set var chipBots: [String: ComposerBotReference] = [:] let quotes: [ComposerQuote] @@ -67,21 +43,14 @@ struct ComposerTextInputView: View { let onPasteFileURLs: ([URL]) -> Void let onPasteImageProviders: ([NSItemProvider]) -> Void let onPasteImages: ([UIImage]) -> Void - /// A tap that landed on a chip's glyph. let onTapChip: (ComposerChipToken) -> Void let onTapQuote: (ComposerQuote) -> Void let onRemoveQuote: (UUID) -> Void - /// The chat's last sent message, for ↑ in an empty editor. Nil turns the - /// shortcut off. var recallLastSentText: (() -> String?)? = nil - /// Takes a paste past `ComposerLargePaste.threshold` as a file. Nil keeps - /// every paste inline and leaves Paste as Text out. var onPasteLargeText: ((String) -> Void)? = nil var placeholder = String(localized: "Ask anything...") - /// Text-only clients reject file/image paste and drop before invoking callbacks. var acceptsAttachments = true - /// The collapsed draft's side padding; a composer with controls beside the draft narrows it. var collapsedHorizontalPadding: CGFloat = 16 private let collapsedLineHeight: CGFloat = 22 @@ -112,8 +81,6 @@ struct ComposerTextInputView: View { acceptsAttachments: acceptsAttachments, accessibilityLabel: placeholder ) - // The card editor runs 72–160 pt with the text, and stays at 72 pt - // where height is limited, and the text scrolls inside it. .frame(height: isCollapsed ? collapsedLineHeight : ComposerTextInputHeight.expanded(measured: inputHeight, verticalSizeClass: verticalSizeClass, @@ -160,14 +127,6 @@ struct ComposerTextInputView: View { } } -/// The draft as the collapsed pill draws it: one truncating line, with the same -/// chips the editor bakes. -/// -/// The pill is a stand-in rather than the editor itself — the real text view is -/// still mounted but at `opacity(0)` — so it has to draw the references a second -/// time. Both go through `ComposerChipRenderer`, so the collapsed and expanded -/// composer cannot drift apart, and the renderer caches the picture so drawing -/// it from `body` costs nothing on a re-render. private struct ComposerCollapsedDraft: View { let draft: String let chips: [ComposerChipToken] @@ -188,9 +147,6 @@ private struct ComposerCollapsedDraft: View { .accessibilityLabel(Text(spokenDraft)) } - /// The chips still inside this draft. The editor reports them a beat after - /// it draws, so a set that no longer fits the text the pill was handed is - /// dropped rather than drawn in the wrong place. private var tokens: [ComposerChipToken] { ComposerChipTextLine.validTokens(chips, in: draft) } @@ -200,14 +156,10 @@ private struct ComposerCollapsedDraft: View { return ComposerChipTextLine.text(draft, tokens: tokens, style: chipStyle) } - /// VoiceOver reads a chip by its label, the way the editor's attachment does, - /// rather than announcing an image. private var spokenDraft: String { draft.isEmpty ? placeholder : ComposerChipTokenizer.spokenText(in: draft, tokens: tokens) } - /// Every trait a chip resolves a colour or a size from, or the pill asks the - /// cache for a picture drawn for someone else's settings. private var chipStyle: ComposerChipTextStyle { ComposerChipTextStyle( colorScheme: colorScheme, @@ -269,9 +221,6 @@ private struct ComposerTextView: UIViewRepresentable { textView.textContainerInset = .zero textView.textContainer.lineFragmentPadding = 0 textView.textContentType = .none - // The editor draws its own attachments and reads them back as draft - // text. Rich-text editing would let UIKit insert one it cannot read, - // which would reach the server as an object-replacement character. textView.allowsEditingTextAttributes = false textView.keyboardCommands = keyboardCommands textView.returnSends = returnSends @@ -296,11 +245,6 @@ private struct ComposerTextView: UIViewRepresentable { textView.refreshChipsIfNeeded() context.coordinator.reportHeight(for: textView) } - // Mirror the chat RTL toggle onto the text view itself (#259): SwiftUI's - // layoutDirection environment does not propagate into a wrapped UITextView, - // so set the base direction directly so the cursor/empty-field rests on the - // trailing edge. `.natural` keeps the LTR default untouched, and per-run - // bidi still resolves mixed Arabic+Latin/URL content within the line. let isRTL = context.environment.layoutDirection == .rightToLeft textView.applyPresentationStyle(isRightToLeft: isRTL, isDisabled: isDisabled) textView.acceptsAttachments = acceptsAttachments @@ -332,8 +276,6 @@ private struct ComposerTextView: UIViewRepresentable { context.coordinator.onDropImageProviders = onPasteImageProviders context.coordinator.applyBoundText(text, generation: selection.publishGeneration, to: textView) context.coordinator.syncSelection(selection, to: textView, expecting: text) - // Chips are redrawn last so they settle around the caret the composer - // just asked for rather than the one the edit happened to leave behind. context.coordinator.applyingBoundValue { textView.refreshChipsIfNeeded() } context.coordinator.publishRenderedChips(of: textView) context.coordinator.syncFocus(for: textView, shouldFocus: isFocused, isDisabled: isDisabled) @@ -353,12 +295,8 @@ private struct ComposerTextView: UIViewRepresentable { var onDropImageProviders: ([NSItemProvider]) -> Void = { _ in } private var pendingFocusTarget: Bool? private var pendingEditingTarget: Bool? - /// Set while we push a bound value into the editor, so the delegate - /// callbacks it provokes do not write the bindings back mid-update. private var isApplyingBoundValue = false private var appliedSelectionRevision = 0 - /// Publishes made to the bindings, matched against the generation the - /// bound value carries to spot one the parent has not caught up with. private var publishGeneration = 0 init( @@ -375,9 +313,6 @@ private struct ComposerTextView: UIViewRepresentable { self.onHeightChange = onHeightChange } - /// Reports the chips the editor settled on, so the collapsed pill draws - /// exactly what the expanded editor drew. Deferred, because a binding - /// cannot be written during a view update. func publishRenderedChips(of textView: ComposerChipTextView) { let chips = textView.renderedTokens guard renderedChips != chips else { return } @@ -393,17 +328,6 @@ private struct ComposerTextView: UIViewRepresentable { } } - /// Pushes a parent-side draft change into the editor as an *edit* rather - /// than a wholesale assignment, so the change lands on the editor's undo - /// stack and the caret follows the insertion. Accepting a slash - /// completion is the case that matters: undo puts back what was typed. - /// - /// While an IME composition is marked, assigning text commits it - /// half-formed and splits characters such as 자 into ㅈㅏ (#312). A - /// binding that simply has not seen the marked text yet is not a real - /// change, so it is ignored; a deliberate clear or replacement still - /// applies. `generation` is the publish count the bound value was built - /// from, which is what tells those two apart when the value is empty. func applyBoundText(_ text: String, generation: Int, to textView: ComposerChipTextView) { let current = textView.sourceText guard current != text else { return } @@ -423,9 +347,6 @@ private struct ComposerTextView: UIViewRepresentable { } applyingBoundValue { - // An empty editor has no typing attributes to insert with, so - // filling or emptying one stays a plain assignment; everything - // in between goes through the input system for its undo stack. if textView.isEditable, !current.isEmpty, !text.isEmpty, @@ -434,22 +355,12 @@ private struct ComposerTextView: UIViewRepresentable { textView.replace(range, withText: edit.replacement) } - // `replace` goes through the input system, which can normalize - // what it inserts, and a range that straddles a chip cannot be - // edited in place at all; rebuild rather than leave the editor - // out of sync. if textView.sourceText != text { textView.replaceDocument(with: text) } } } - /// Keeps the editor's caret and the composer's idea of it in step. - /// - /// A caret the composer asked for is applied once, keyed on its - /// revision, so a later update replaying the same value cannot yank the - /// caret away from where the user has since put it. Every other pass - /// leaves the editor's own caret alone and reports it back. func syncSelection( _ selection: ComposerSelection, to textView: ComposerChipTextView, @@ -461,13 +372,9 @@ private struct ComposerTextView: UIViewRepresentable { appliedSelectionRevision = selection.revision let clamped = Self.clamp(selection.range, toLengthOf: expectedText) - // Assigning `selectedRange` resets predictive text, so never - // assign a range the editor already holds. if textView.sourceSelection != clamped { applyingBoundValue { textView.sourceSelection = clamped } } - // A resigned editor does not follow its own caret, and dictation - // writes into one the user can't scroll. textView.scrollRangeToVisible(textView.selectedRange) return } @@ -475,8 +382,6 @@ private struct ComposerTextView: UIViewRepresentable { publishSelection(of: textView) } - /// Reports the caret the editor settled on. Deferred, because a binding - /// cannot be written during a view update. private func publishSelection(of textView: ComposerChipTextView) { let range = textView.sourceSelection guard selection.range != range else { return } @@ -512,9 +417,6 @@ private struct ComposerTextView: UIViewRepresentable { isApplyingBoundValue = wasApplying } - /// Disabling a focused UITextView can synchronously ask its SwiftUI - /// hosting view for the next responder. Do that after updateUIView has - /// returned, otherwise the responder lookup re-enters the active graph. func syncEditing(for textView: UITextView, isDisabled: Bool) { let editable = !isDisabled guard textView.isEditable != editable || textView.isSelectable != editable else { @@ -562,9 +464,6 @@ private struct ComposerTextView: UIViewRepresentable { guard self.isFocused, textView.isEditable, textView.window != nil else { return } textView.becomeFirstResponder() } else if !self.isFocused, textView.isFirstResponder { - // UIKit can begin a new editing session while this blur is - // queued. Recheck the binding, just as the focus path does, - // so an older request cannot dismiss the new session. textView.resignFirstResponder() } } @@ -588,10 +487,6 @@ private struct ComposerTextView: UIViewRepresentable { func textViewDidChange(_ textView: UITextView) { guard !isApplyingBoundValue, let textView = textView as? ComposerChipTextView else { return } - // Text and caret travel together: publishing them in one update is - // what keeps the two consistent when the composer maps the caret - // back onto the draft to find the slash trigger. The generation - // rides along so a later update can be dated against this one. publishGeneration &+= 1 text = textView.sourceText selection.range = textView.sourceSelection @@ -599,9 +494,6 @@ private struct ComposerTextView: UIViewRepresentable { reportHeight(for: textView) } - /// Publishes pure caret moves — a tap, an arrow key, a selection drag. - /// Edits are left to `textViewDidChange`, which carries both halves, and - /// a live IME composition is left alone entirely. func textViewDidChangeSelection(_ textView: UITextView) { guard !isApplyingBoundValue, textView.markedTextRange == nil else { return } guard let textView = textView as? ComposerChipTextView else { return } @@ -619,13 +511,10 @@ private struct ComposerTextView: UIViewRepresentable { shouldChangeTextIn range: NSRange, replacementText text: String ) -> Bool { - // Typing right after a chip would otherwise inherit the attachment's - // attributes and swallow the new characters into the image. (textView as? ComposerChipTextView)?.restoreTypingAttributes() return true } - /// Puts Paste as Text after Paste where the editor converts long pastes (#1381). func textView( _ textView: UITextView, editMenuForTextIn range: NSRange, @@ -646,12 +535,6 @@ private struct ComposerTextView: UIViewRepresentable { return UIMenu(children: actions) } - // MARK: - Drops - - /// Claims a drop only when the composer can route every item through the - /// attachment pipeline, so UIKit never inserts something the draft - /// cannot represent. Anything else is left to UIKit, which drops it in - /// as plain text. func textDroppableView( _ textDroppableView: UIView & UITextDroppable, proposalForDrop drop: UITextDropRequest @@ -699,19 +582,10 @@ private struct ComposerTextView: UIViewRepresentable { } } -/// How the composer routes a dropped set of items into the attachment pipeline. -/// -/// All or nothing: an item the pipeline cannot take means UIKit keeps the whole -/// drop, because a half-handled drop would leave the user with some of what they -/// dragged and no way to tell which half went missing. struct ComposerDropRoute { let files: [NSItemProvider] let images: [NSItemProvider] - /// `nil` when any provider is neither a file nor an image. - /// - /// A provider that is both counts as a file, the same order `paste` uses: a - /// dropped PNG is a file the user picked, not a screenshot on the clipboard. init?(providers: [NSItemProvider]) { guard !providers.isEmpty else { return nil } @@ -733,21 +607,14 @@ struct ComposerDropRoute { } } -/// Hermes pastes longer than Hermes Desktop's limit become a `pasted-text.txt` -/// attachment instead of filling the editor (#1381). ⌘⇧V and the edit menu's -/// Paste as Text keep one inline. enum ComposerLargePaste { - /// Desktop's limit, counted in UTF-16 units as JavaScript counts a string. static let threshold = 3_000 static let bypassTitle = String(localized: "Paste as Text") - /// Walks at most `threshold + 1` units, so a huge paste costs what a short one does. static func converts(_ text: String) -> Bool { !text.utf16.dropFirst(threshold).isEmpty } - /// `pasted-text.txt`, then `pasted-text-2.txt` and on: the first name `taken` - /// does not hold, compared without case. static func filename(avoiding taken: Set) -> String { let taken = Set(taken.map { $0.lowercased() }) var candidate = "pasted-text.txt" @@ -759,29 +626,19 @@ enum ComposerLargePaste { return candidate } - /// Whether a staged attachment opens in `StagedPasteSheet` (#1456). A draft records - /// nothing else about where a file came from, so a local file the user named this way - /// opens there too; only its app-owned copy can change. static func isStagedPaste(_ attachment: PendingAttachment) -> Bool { attachment.path.isEmpty && attachment.draftFileName != nil && !attachment.isImage && attachment.name.wholeMatch(of: /pasted-text(-\d+)?\.txt/) != nil } } -/// The hardware-keyboard commands the composer's editor offers (#1380), each titled by -/// what it does right now. A nil command leaves its key alone. The editor refuses every -/// one while it is locked or an IME composition is unfinished; each action rechecks its -/// own gate when it runs. struct ComposerKeyboardCommands { struct Command { let title: String let perform: () -> Void } - /// ⌘↩: Send as a tap on the circle would. Never Stop. var send: Command? - /// ⌘⇧↩: the send-choice card's safe alternate to Send's behavior. var alternateSend: Command? - /// Esc: closes an open panel or card, or stops the running response. var escape: Command? } diff --git a/HermesMobile/Features/Chat/ChatComposerView.swift b/HermesMobile/Features/Chat/ChatComposerView.swift index 818616c64..23bbdcaee 100644 --- a/HermesMobile/Features/Chat/ChatComposerView.swift +++ b/HermesMobile/Features/Chat/ChatComposerView.swift @@ -1,7 +1,6 @@ import SwiftUI import UIKit -/// A composer status line that offers Retry, such as "Couldn't steer". struct ComposerRetryableStatus { let message: String let onRetry: () -> Void @@ -12,19 +11,13 @@ private struct ComposerStatusView: View { let text: String let isError: Bool let onRetry: (() -> Void)? - /// Offers Copy fix prompt, which puts this text on the pasteboard (#955). let fixPrompt: String? - /// Offers Cancel, which stops a Hermes send's uploads (#1012). let onCancel: (() -> Void)? - /// Offers Fix on This Phone, which opens Serve Every Profile (#1611). let onFix: (() -> Void)? - /// Offers ✕, for an error that goes once read. let onDismiss: (() -> Void)? @State private var didCopyFixPrompt = false var body: some View { - // At accessibility sizes Copy fix prompt drops below the message, - // like the transcript log rows' stacked labels. let layout = fixPrompt != nil && dynamicTypeSize.isAccessibilitySize ? AnyLayout(VStackLayout(alignment: .leading, spacing: 6)) : AnyLayout(HStackLayout(alignment: .top, spacing: 8)) @@ -83,7 +76,6 @@ private struct ComposerStatusView: View { .onChange(of: text) { didCopyFixPrompt = false } } - /// Swaps to "Copied" without animation and announces it for VoiceOver. private func fixPromptButton(_ prompt: String) -> some View { Button { UIPasteboard.general.string = prompt @@ -99,8 +91,6 @@ private struct ComposerStatusView: View { } .font(AppFont.caption(weight: .semibold)) .buttonStyle(.borderless) - // Wraps like Retry would: a long translation shares the row with the - // message instead of squeezing it, and never overflows when stacked. .fixedSize(horizontal: false, vertical: true) .accessibilityLabel(didCopyFixPrompt ? Text("Fix prompt copied") : Text("Copy fix prompt")) .accessibilityHint(Text("Copies a prompt that asks your Hermes agent to restart Hermes WebUI.")) @@ -161,14 +151,9 @@ struct MessageComposerView: View { @ScaledMetric(relativeTo: .body) private var actionIconSize: CGFloat = 16 @ScaledMetric(relativeTo: .body) private var plusIconSize: CGFloat = 20 - /// t3code sizing: every circle in the composer is 44 pt, which is also the - /// minimum hit target, so no invisible hit padding is needed. private let circleSize = ChatComposerMetrics.actionSize private let pillInset = ChatComposerMetrics.pillInset - /// The draft. Pass the owner's plain `$state`, not a get/set binding: - /// SwiftUI re-runs the owner of a get/set binding on every keystroke. The - /// owner hears about edits through `onDraftEdit` instead. @Binding var draftMessage: String @Binding var quotes: [ComposerQuote] @Binding var isFocused: Bool @@ -176,13 +161,9 @@ struct MessageComposerView: View { let isCompressingSession: Bool let isWaitingForStream: Bool let isCancellingStream: Bool - /// A read-only session locks the editor; an offline chat holds only Send and host controls. let access: ChatComposerAccess let errorMessage: String? - /// Offered as Copy fix prompt on the `errorMessage` banner (#955). let errorFixPrompt: String? - /// Offered as Fix on This Phone on the `errorMessage` banner, for a Profile the Webapp - /// doesn't serve (#1611). let onFixError: (() -> Void)? let configurationErrorMessage: String? let contextWindowSnapshot: ContextWindowSnapshot? @@ -194,13 +175,9 @@ struct MessageComposerView: View { let workspaceRoots: [WorkspaceRoot] let selectedWorkspacePath: String? let workspaceSuggestions: [String] - /// Server base URL for the workspace-registry manager; nil hides the - /// Manage affordance in the workspace picker. let workspaceManagementServer: URL? let personalitySuggestions: [String] let skillSuggestions: [SkillSlashSuggestion] - /// Whether a skills request has succeeded, even an empty one. Lets the - /// mid-sentence close rule tell "still loading" from "loaded, none match". let hasLoadedSkillSuggestions: Bool let agentCommands: [AgentCommand] let profileOptions: [ProfileSummary] @@ -208,10 +185,8 @@ struct MessageComposerView: View { let selectedProfileName: String? let selectedProfileTitle: String let selectedReasoningEffort: String? - /// Model-aware effort vocabulary; `nil` → full static list (issue #18). let supportedReasoningEfforts: [String]? let supportsReasoningEffort: Bool? - /// When false the model has no effort setting, so the combined title omits it. let showsReasoningControl: Bool let isUpdatingConfiguration: Bool let pendingAttachments: [PendingAttachment] @@ -219,45 +194,23 @@ struct MessageComposerView: View { let attachmentUploadCount: Int let attachmentUploadGeneration: Int let isSendingVoiceNote: Bool - /// When true, dictation auto-starts once this composer appears with the app active — - /// the "New Chat with Voice" App Intent (#338). Defaults to false for normal composers. let autoStartsVoiceInput: Bool let apiClient: APIClient? - /// This chat's server-side session. Nil before the session exists. let sessionID: String? - /// The server whose favorite and recent models this composer lists. let server: URL - /// Loads one query's rows into `filePathSearch`: the chat's workspace listing, or a - /// Hermes chat's `complete.path` (#1113). Nil keeps the `@` panel closed. let searchFilePaths: ((String) async -> Void)? - /// The workspace files already picked in this chat. The editor draws their - /// `@path` references as chips; the view model owns the set so the sent - /// transcript can draw the same ones. let chipFilePaths: Set - /// A bot's chat's `@`mention roster (#1145): its bots lead the `@` panel and draw as chips in - /// the editor. Nil everywhere else. var botMentions: BotMentions? = nil - /// Those bots' avatars, keyed by Profile, from this connection only. var mentionAvatars: [String: UIImage] = [:] - /// The `@` panel's rows and its directory listings. Owned by the view model - /// so a folder listed to confirm a restored draft's references is not listed - /// again the first time the panel opens. let filePathSearch: ComposerFilePathSearch let uploadAttachmentErrorMessage: String? - /// "Couldn't steer" with Retry, after a steer didn't reach the run. let steerFailure: ComposerRetryableStatus? - /// The Send While Responding default: what a tap on Send does mid-run, and - /// the glyph and VoiceOver label that say so. let streamingSendBehavior: StreamingSendBehavior - /// Sends the draft. Mid-run it carries the behavior Send shows (tap and - /// Command-Return) or one picked for this message from the send-choice card - /// or a VoiceOver action; the default does not change. Nil while idle. let onSend: (StreamingSendBehavior?) -> Void let onSendVoiceNote: (Data, String) -> Void let onCancel: () -> Void let onSelectModel: (ModelCatalogOption) -> Void let onModelPickerOpen: () async -> Void - /// Sends a level; true once the host took it. let onSelectReasoningEffort: (String) async -> Bool let onLoadWorkspaceSuggestions: (String) async -> Void let onWorkspaceRegistryChanged: () async -> Void @@ -265,7 +218,6 @@ struct MessageComposerView: View { let onLoadSkillSuggestions: () async -> Void let onSelectWorkspace: (String) async -> Void let onSelectProfile: (ProfileSummary) -> Void - /// The composer's measured height, and whether that is its resting layout (`isResting`). let onHeightChange: (_ height: CGFloat, _ isResting: Bool) -> Void let onPhotoMediaSelected: ([HermexPickedMedia]) -> Void let onFileURLsSelected: ([URL]) -> Void @@ -276,109 +228,54 @@ struct MessageComposerView: View { let onRemoveAttachment: (UUID) -> Void let onPreviewAttachment: (PendingAttachment) -> Void let onDismissUploadAttachmentError: () -> Void - /// Clears `errorMessage` and `configurationErrorMessage` from their banner's ✕; nil hides it. let onDismissError: (() -> Void)? - /// A workspace file the user just picked, for the chip catalog. let onSelectFileReference: (String) -> Void - /// The draft, each time its finished `@…` references change (and once on - /// appear), so the owner can confirm which name workspace files. Scanned - /// here because this view already re-runs per keystroke; the owner never - /// has to read the draft in its own body. let onFileReferenceCandidatesChange: (String) async -> Void - /// Each edit the user makes to the draft here (typing, completions, - /// dictation), after it lands in `draftMessage`, for the owner to persist. let onDraftEdit: (String) -> Void - /// The chat's last sent message, for ↑ in an empty composer on a hardware - /// keyboard. A closure, so the transcript is scanned only when ↑ is pressed. var recallLastSentText: (() -> String?)? = nil - /// Takes a long paste as a file; a Hermes session's (#1381). Nil keeps pastes inline. var onPasteLargeText: ((String) -> Void)? = nil - /// A file chip the user tapped, by workspace-relative path. let onOpenFileReference: (String) -> Void let onSelectGitBranch: (GitCheckoutTarget) -> Void let onCreateGitBranch: (GitCheckoutTarget) -> Void let onRefreshGitBranches: () -> Void - /// False on a Hermes session (#1010): voice notes stay hidden until their phase lands, and - /// the workspace picker takes a typed path (#1117). The + menu, dictation, the context - /// indicator and the branch picker (#1116) stay. var showsSessionControls = true - /// The commands the `/` panel lists and runs: a Hermes chat's own and its host's (#1036). var slashScope = SlashCommandScope.webui - /// The host's suggestions for a host command's argument (#1036). var hostSlashCompletion: HermesSlashCompletion? - /// Asks the host to complete a host command's argument: the draft up to the caret, or nil - /// once the caret leaves one. Called again on each change; a newer call replaces it. var onCompleteHostSlashArgument: (String?) async -> Void = { _ in } - /// A Hermes session's model, folder and Profile chips (#1015, #1117), shown while the rest - /// of `showsSessionControls` stays hidden. Its folder picker takes a typed path, which the - /// host checks. var showsModelAndProfileControls = false - /// A configuration change that has not landed yet, such as a model the host applies - /// after the running response. Shown below any configuration error. var configurationNotice: String? - /// The effort a Hermes host sends when the model takes less than the one picked (#1016). var sentReasoningEffort: String? - /// A Hermes session's Fast mode (#1142); nil hides its row in Model settings. var fastMode: Bool? - /// Whether the host takes a Fast change now; the row shows disabled otherwise. var mayChangeFastMode = false - /// Asks the host for the other Fast mode. var onSelectFastMode: (Bool) -> Void = { _ in } - /// Chat settings, which the header opens. The composer presents it because its pickers - /// and their gates live here. var isChatSettingsPresented: Binding = .constant(false) - /// Model settings, which the model label opens. `ChatView` owns it so its own - /// expensive-model question can stand down while the sheet is up. var isModelSettingsPresented: Binding = .constant(false) - /// Where Model settings asks the host's expensive-model question. Nil outside Hermes. var modelConfirmationControls: BotChatControls? - /// Model settings' Approvals row; nil hides it. var approvals: ComposerApprovals? var onSetYolo: (Bool) -> Void = { _ in } var onSelectApprovalMode: (HermesApprovalMode) -> Void = { _ in } - /// Nothing is sent yet: workspace, branch, Profile and context sit above the composer. var showsNewChatControls = false - /// A Hermes session (#1012): staged files upload when they are sent, under Bot Chat's - /// rules. Up to eight, and Steer drops out while a response runs. var uploadsAttachmentsOnSend = false - /// Set while a send uploads its files, for the status line's Cancel. var onCancelAttachmentUpload: (() -> Void)? - /// A Hermes session's dictation transcriber: the host's speech-to-text for the chat's - /// Profile (#1071). Nil sends dictation to the webui's `/api/transcribe` through `apiClient`. var hermesTranscriber: ComposerTranscriber? @State private var textFieldHeight: CGFloat = 0 @State private var textInputHeight: CGFloat = 22 - /// Where the caret is in `draftMessage`, in UTF-16 units. Transient by - /// design: a restored draft starts with the caret at its end, not wherever - /// it was left last week. @State private var composerSelection = ComposerSelection() - /// Where Esc closed the `/` or `@` panel (#1380). It stays closed until the draft or - /// the caret moves, so the trigger it closed does not reopen it at once; the first move - /// clears it, so coming back to the same spot opens the panel again. @State private var dismissedSuggestionsAnchor: SuggestionAnchor? @State private var noticeMessage: String? @State private var showsWorkspaceSheet = false @State private var showsGitBranchPicker = false - /// Runs once Chat settings has closed: a change that may raise an alert from - /// `ChatView`, which can't appear over the sheet. @State private var afterChatSettingsDismiss: (() -> Void)? @State private var optimisticWorkspacePath: String? - /// Read on appear: the `server` they belong to isn't known to a property initializer. @State private var favoriteModelKeys: [ModelFavoriteKey] = [] @State private var recentModelKeys: [ModelFavoriteKey] = [] @State private var keyboardIsVisible = false - /// The card's shape and controls, which open with the keyboard rather than with focus. Focus - /// flips while UIKit takes first responder, which stalls the main thread, so a SwiftUI animation - /// started then jumps while the keyboard, on the render server, keeps moving smoothly. @State private var isCardOpen = false - /// Opens the card for a focus no keyboard answers, such as with a hardware keyboard. @State private var cardFallback: DispatchWorkItem? @State private var shouldRestoreFocusAfterPresentation = false @State private var selectedQuote: ComposerQuote? - /// True while the send-choice card is up after a hold on Send mid-run. @State private var choosingSendBehavior = false - /// Keeps the release of a hold that opened the card from also sending. @State private var sendHold = ChatComposerSendHold() @State private var sendHoldWorkItem: DispatchWorkItem? @GestureState private var isPressingSend = false @@ -388,11 +285,9 @@ struct MessageComposerView: View { @State private var presentFilesAfterMediaPickerDismisses = false @State private var showFileImporter = false @State private var voiceInput = ComposerVoiceInputController() - /// Whether the keyboard was up when dictation took it down, so it can return. @State private var restoresFocusAfterDictation = false @State private var voiceNoteRecorder = ComposerVoiceNoteRecorder() @State private var voiceNoteCancelArmed = false - /// A hold on the mic records until release; Voice note in `+` records until the bar's buttons. @State private var voiceNoteIsHeld = true @State private var didAutoStartVoiceInput = false @AppStorage(ComposerSTTProviderPreference.storageKey) private var sttProviderPreferenceRawValue = ComposerSTTProviderPreference.defaultValue.rawValue @@ -402,7 +297,6 @@ struct MessageComposerView: View { !access.allowsEditing } - /// Offline or read-only: nothing that reaches the host starts, open controls included. private var holdsHostControls: Bool { !access.allowsHostControls } @@ -413,8 +307,6 @@ struct MessageComposerView: View { case waitingForUploadsToFinish } - /// The `/…` the caret is sitting in, whether that is the start of the draft - /// or the middle of a sentence. private var slashTrigger: ComposerSlashTrigger? { guard !areSuggestionsDismissed else { return nil } return ComposerSlashTrigger.detect(in: draftMessage, selection: composerSelection.range, scope: slashScope) @@ -425,24 +317,16 @@ struct MessageComposerView: View { let caret: NSRange } - /// Dictation closes every panel: the draft is locked, and accepting a row would - /// edit it and drop the words still being recorded. private var areSuggestionsDismissed: Bool { isDictating || dismissedSuggestionsAnchor == SuggestionAnchor(draft: draftMessage, caret: composerSelection.range) } - /// The draft up to the caret while it is at a host command's argument (#1036), which the - /// host is asked to complete. private var hostSlashArgumentText: String? { guard !holdsHostControls, fileTrigger == nil, let trigger = slashTrigger, trigger.startsDraft, ParsedSlashQuery(query: trigger.text, scope: slashScope).isHostArgumentMode else { return nil } return trigger.text } - /// The `@…` the caret is sitting in, or `nil` when there is none. - /// - /// Needs `searchFilePaths`, since every path the panel offers comes from - /// the chat's own workspace. private var fileTrigger: ComposerFileTrigger? { guard !holdsHostControls, !areSuggestionsDismissed, searchFilePaths != nil || botMentions != nil else { return nil @@ -454,11 +338,6 @@ struct MessageComposerView: View { fileTrigger != nil } - /// What the panel filters on, or `nil` when it should be closed. - /// - /// The `@` panel wins when both triggers match: a `/` inside a path never - /// triggers at all (it follows a non-space), but an `@` inside a command's - /// free-form argument is still a file reference. private var slashQuery: String? { guard fileTrigger == nil else { return nil } return slashTrigger?.panelQuery(scope: slashScope, skills: skillSuggestions, @@ -469,22 +348,15 @@ struct MessageComposerView: View { slashQuery != nil } - /// Whether the panel may only offer skills. The send path runs a command - /// only when the trimmed draft starts with `/`, so past other text a - /// command row would be inserted text nothing executes. private var showsSlashAutocompleteSkillsOnly: Bool { !(slashTrigger?.startsDraft ?? true) } - /// Every write the user makes to the draft goes through here, so the owner - /// can persist it. private func editDraft(_ text: String) { draftMessage = text onDraftEdit(text) } - /// Swaps the `/…` at the caret for `replacement` and leaves the caret just - /// after it, so the rest of the draft survives accepting a row. private func applyCompletion(_ replacement: String) { guard let trigger = slashTrigger else { return } @@ -493,15 +365,11 @@ struct MessageComposerView: View { composerSelection = composerSelection.moved(to: completed.selection) } - /// A row the user tapped in the `/` panel: completes it with a selection tick. private func pickCompletion(_ replacement: String) { applyCompletion(replacement) ChatHaptics.autocompleteAccepted(isEnabled: isHapticsEnabled) } - /// A bot's chat's `@` panel (#1145), as Bot Chat draws it: this connection's other bots, then - /// the chat's workspace files. Its task asks for files, so the container stands while the - /// first answer is out; it shows once there is a row or a lookup in flight. private func botAutocomplete(_ trigger: ComposerFileTrigger, mentions: BotMentions) -> some View { let bots = mentions.completions(query: trigger.query) return Group { @@ -524,14 +392,6 @@ struct MessageComposerView: View { .task(id: trigger.query) { await searchFilePaths?(trigger.query) } } - /// Swaps the `@…` at the caret for the picked entry. - /// - /// A file finishes the reference: `@path` plus a space, recorded so the - /// editor draws it as a chip. A folder is a step on the way, so it inserts - /// with a trailing `/` and no space and the panel stays open listing what is - /// inside it. Only files are recorded, which is what keeps a folder - /// reference from becoming a chip that opens nothing. Either pick plays a - /// selection tick, so a folder tap that keeps the panel open still lands. private func applyFileCompletion(_ match: ComposerFilePathSearch.Match) { guard let trigger = fileTrigger else { return } @@ -575,9 +435,6 @@ struct MessageComposerView: View { } } - // No `GlassEffectContainer` around the composer: on device, after the card collapsed - // with the send, it kept taking taps where the card had been, above the pill, and the - // scroll-to-bottom arrow there stopped working. private var composerWithLifecycle: some View { VStack(spacing: 6) { if voiceNoteRecorder.isRecording { @@ -661,10 +518,8 @@ struct MessageComposerView: View { } .animation(ChatMotion.quickState(reduceMotion: reduceMotion), value: showsSlashAutocomplete) .animation(ChatMotion.quickState(reduceMotion: reduceMotion), value: showsFileAutocomplete) - // The panel takes only the room the composer leaves (`composerPanelHeight`). .layoutPriority(-1) - // Back when the keyboard goes and the viewport has room again. if showsNewChatControls, showsConfigurationControls, !viewportIsShort { newChatControlsRow .padding(.horizontal) @@ -673,7 +528,6 @@ struct MessageComposerView: View { composerSurface .padding(.horizontal) - // Above the toolbar row, whose solid background bleeds up under the card. .zIndex(1) if isExpanded { @@ -681,7 +535,6 @@ struct MessageComposerView: View { if isDictating { dictationRow.transition(.opacity) } else { - // Waits for the card to rise past where the row lands. toolbarRow.transition(.asymmetric( insertion: .opacity.animation(reduceMotion ? nil : .easeIn(duration: 0.12).delay(0.14)), removal: .opacity @@ -692,12 +545,6 @@ struct MessageComposerView: View { .padding(.horizontal) .padding(.top, 8) .frame(maxWidth: .infinity) - // Solid chat background behind the controls: the card - // above is glass on purpose, but transcript text - // scrolling under the row made the pills unreadable. - // Bleeds up into the gap under the card and down past - // the keyboard gap and the bottom safe area, so no strip - // of transcript shows around the row. .background( Color(.appCanvas) .padding(.top, -10) @@ -707,9 +554,6 @@ struct MessageComposerView: View { .transition(.opacity) } } - // Focus flips arrive from UIKit outside any withAnimation, so the - // morph and the row's insertion take their animation from here: the - // keyboard's curve going up, so they move as one. .animation(isExpanded ? ChatMotion.keyboard(reduceMotion: reduceMotion) : ChatMotion.composerChrome(reduceMotion: reduceMotion), value: isExpanded) .background( @@ -748,8 +592,6 @@ struct MessageComposerView: View { } .frame(width: 0, height: 0) } - // The same keyboard-retaining overlay as the "+" picker and the Bot - // composer's send-choice card, so the keyboard stays up. .background { HermexKeyboardRetainingOverlay(isPresented: choosingSendBehavior) { SendChoiceCard( @@ -760,8 +602,6 @@ struct MessageComposerView: View { } .frame(width: 0, height: 0) } - // The run ending, or Send turning into Stop, closes the card and drops - // a hold that has not opened it yet, as the Bot composer does. .onChange(of: sendChoices) { _, choices in guard choices.isEmpty else { return } cancelScheduledSendChoices() @@ -777,8 +617,6 @@ struct MessageComposerView: View { cancelScheduledSendChoices() } } - // The view model holds both list loads while offline; going online is - // part of each identity so the held load runs on reconnect. .task(id: [draftMayReferenceSkill, access.isOffline]) { await loadSkillSuggestionsForChipsIfNeeded() } @@ -792,10 +630,6 @@ struct MessageComposerView: View { await onCompleteHostSlashArgument(hostSlashArgumentText) } .task(id: AppLock.shared.isLocked) { - // Cold path: the composer appears already active (the usual case for the - // "New Chat with Voice" intent once its session is created) — start here. - // Runs again when the app lock changes, since dictation waits for it (#885); - // one modifier keeps this chain inside CI Xcode's type-checking budget. if AppLock.shared.isLocked { voiceInput.suspend() } else if scenePhase == .active { voiceInput.resume() } autoStartVoiceInputIfNeeded() @@ -810,26 +644,18 @@ struct MessageComposerView: View { .onChange(of: scenePhase) { _, newPhase in if newPhase != .active { voiceInput.suspend() - // Backgrounding stops the recorder's run-loop ticker, so cancel - // the in-flight recording rather than leave it silently stalled. cancelVoiceNote() } else { voiceInput.resume() - // An intent that opened this composer may have foregrounded the app - // a beat after it appeared; auto-start once we're active (#338). autoStartVoiceInputIfNeeded() } } .onChange(of: voiceNoteRecorder.elapsed) { _, elapsed in - // Enforce the max-duration cap: auto-stop and send (not cancel) once - // the clip hits the limit, mirroring a finger release. if voiceNoteRecorder.isRecording, elapsed >= ComposerVoiceNoteRecorder.maximumDuration { finishVoiceNote(translationHeight: 0) } } .onChange(of: showsGitBranchPicker) { _, isPresented in - // The New Branch alert takes the keyboard, so hand focus off up front - // and bring it back once the popover closes. if isPresented { prepareForComposerPresentation() } else { @@ -988,11 +814,6 @@ struct MessageComposerView: View { .animation(ChatMotion.keyboard(reduceMotion: reduceMotion), value: keyboardIsVisible) } - /// Pill while the editor is idle; card while it is focused. Controls in the pill - /// open their sheets without expanding it. `shouldRestoreFocus…` keeps a focused - /// card open while its sheet is up, until focus comes back. - /// Collapsed with no status or recording row above the card: the layout whose height a chat - /// can start from before its own composer is measured. private var isResting: Bool { !isExpanded && !voiceNoteRecorder.isRecording && voiceNoteStatus == nil && voiceStatus == nil && composerStatus == nil @@ -1005,15 +826,10 @@ struct MessageComposerView: View { || shouldRestoreFocusAfterPresentation } - /// Dictation locks the draft from the mic tap until its words have landed. private var isDictating: Bool { voiceInput.state != .idle } - /// The glass surface: one text view in both states so focus and the draft - /// survive the morph. Pill: `+`, text, thumbnails, provider logo, mic and - /// Stop/Send in a row. Card: strip above the editor, controls move to - /// `toolbarRow` below. private var composerSurface: some View { VStack(spacing: 0) { if isExpanded { @@ -1049,7 +865,6 @@ struct MessageComposerView: View { onPasteImageProviders: onPasteImageProviders, onPasteImages: onPasteImages, onTapChip: { token in - // A skill chip is inert; a file chip opens the file. guard let path = token.filePath else { return } onOpenFileReference(path) }, @@ -1057,7 +872,6 @@ struct MessageComposerView: View { onRemoveQuote: removeQuote, recallLastSentText: recallLastSentText, onPasteLargeText: onPasteLargeText, - // The pill's `+` and logo already inset the draft. collapsedHorizontalPadding: 4 ) .allowsHitTesting(!isDictating) @@ -1085,9 +899,6 @@ struct MessageComposerView: View { .modifier(ChatComposerSurfaceStyle(isExpanded: isExpanded)) } - /// Card-state row under the surface. It never scrolls: the model label takes the - /// spare width and truncates, which leaves room for #250's voice-mode button beside - /// the mic. Visual order is VoiceOver order. private var toolbarRow: some View { HStack(alignment: .center, spacing: 8) { plusButton(usesGlass: true) @@ -1104,8 +915,6 @@ struct MessageComposerView: View { } } - /// Above a chat with nothing sent yet, and gone after the first message: the header - /// holds these from then on. The labels truncate instead of scrolling. private var newChatControlsRow: some View { HStack(alignment: .center, spacing: 8) { workspaceSelector @@ -1118,13 +927,10 @@ struct MessageComposerView: View { } } - /// False only for a composer with no session to configure. private var showsConfigurationControls: Bool { showsSessionControls || showsModelAndProfileControls } - /// The same controls and gates as the new-chat row, plus the context details. Every change - /// waits for the sheet to close, since each can raise an alert from `ChatView`. private var chatSettingsSheet: some View { ChatSettingsSheet( workspaceTitle: workspaceTitle, @@ -1150,7 +956,6 @@ struct MessageComposerView: View { afterChatSettingsDismiss = nil } - /// `perform` runs a picked workspace. private func workspacePickerSheet( perform: @escaping (@escaping () -> Void) -> Void = { $0() } ) -> some View { @@ -1192,7 +997,6 @@ struct MessageComposerView: View { supportsVoiceNotes: showsSessionControls, onTap: toggleVoiceInput, onRecordingStart: { startVoiceNoteRecording() }, - // A note started from `+` ends at its bar's buttons, so a hold on the mic can't touch it. onRecordingDragChanged: { height in guard voiceNoteIsHeld else { return } voiceNoteCancelArmed = ComposerVoiceNoteGesture.isCancelArmed(dragTranslationHeight: height) @@ -1204,10 +1008,6 @@ struct MessageComposerView: View { ) } - /// One trailing circle in both states. Stop while a response streams and the - /// draft is empty; Send as soon as there is text (or, on Hermes, a staged - /// file). Mid-run a tap sends with the behavior its glyph shows, and a hold - /// opens the send-choice card for this one message (`ChatComposerSendButton`). private var actionButton: some View { Button(action: actionButtonPressed) { actionButtonLabel @@ -1222,7 +1022,6 @@ struct MessageComposerView: View { .accessibilityLabel(sendButton.accessibilityLabel) .accessibilityValue(blockedSendReason ?? "") .accessibilityActions { - // VoiceOver can't hold, so each choice is a named action. ForEach(sendChoices, id: \.self) { behavior in Button(behavior.title) { pickSendBehavior(behavior) } } @@ -1236,19 +1035,12 @@ struct MessageComposerView: View { .tint(actionButtonForeground) .scaleEffect(0.9) } else { - // Morphs between Stop and the default's Send glyph; instant - // with Reduce Motion. Image(systemName: sendButton.systemName) .font(.system(size: actionIconSize, weight: .semibold)) .contentTransition(reduceMotion ? .identity : .symbolEffect(.replace)) } } - /// Times a hold the way the mic does (`ComposerVoiceControlButton`): one - /// `DragGesture(minimumDistance: 0)` beside the button's own tap, where - /// touch-down schedules the card and lifting before the delay cancels it. - /// The gesture state resets on a cancelled touch too, so a hold can never - /// stay armed. private var sendHoldGesture: some Gesture { DragGesture(minimumDistance: 0) .updating($isPressingSend) { _, isPressing, _ in @@ -1265,7 +1057,6 @@ struct MessageComposerView: View { choosingSendBehavior = true } sendHoldWorkItem = item - // The mic's hold delay, so the composer's two holds feel alike. DispatchQueue.main.asyncAfter( deadline: .now() + ComposerVoiceNoteGesture.holdActivationDelay, execute: item @@ -1277,17 +1068,13 @@ struct MessageComposerView: View { sendHoldWorkItem = nil } - /// Closes the send-choice card. A hold still down keeps its release from - /// sending (or stopping); see `ChatComposerSendHold`. private func closeSendChoices() { choosingSendBehavior = false sendHold.choicesClosed(isPressing: isPressingSend) } - /// The card's rows and VoiceOver's named actions both land here. private func pickSendBehavior(_ behavior: StreamingSendBehavior) { closeSendChoices() - // A pick can outlive the run or the draft it was offered for. guard sendChoices.contains(behavior) else { return } if voiceInput.isListening { voiceInput.stopBeforeSubmittingDraft() @@ -1295,15 +1082,10 @@ struct MessageComposerView: View { onSend(behavior) } - /// Whether the draft holds anything that could be drawn as a skill chip. private var draftMayReferenceSkill: Bool { ComposerChipTokenizer.mayContainReference(draftMessage) } - /// A draft restored from the store can already name a skill, and chips are - /// only drawn for skills the app has heard of. Fetching the list the moment - /// the draft looks like it needs one keeps a reopened chat from showing raw - /// `/skill` text, without a skills request on every chat that never uses one. private func loadSkillSuggestionsForChipsIfNeeded() async { guard draftMayReferenceSkill, skillSuggestions.isEmpty else { return } await onLoadSkillSuggestions() @@ -1333,7 +1115,6 @@ struct MessageComposerView: View { } } - /// Glass in the card's row. The pill is already glass, so its `+` stays plain. private func plusButton(usesGlass: Bool) -> some View { Button { showMediaPicker = true @@ -1357,10 +1138,6 @@ struct MessageComposerView: View { .accessibilityLabel("Composer options") } - /// One "Git Actions" toggle covers every git control in chat (#189), so the branch chip goes - /// with the toolbar menu rather than lingering alone. A Hermes chat creates a branch only - /// through hermex-push (#1236), and nothing switches while another write holds the - /// repository's lock. @ViewBuilder private var gitBranchPicker: some View { if showsGitControls, gitViewModel.hasRepository, gitViewModel.supportsBranches { @@ -1414,7 +1191,6 @@ struct MessageComposerView: View { ) } - /// `showsTitle` is false in the pill, where the logo is the only model identity. private func modelEffortControl(showsTitle: Bool) -> some View { ComposerModelLabelButton( showsTitle: showsTitle, @@ -1436,7 +1212,6 @@ struct MessageComposerView: View { recents: ModelRecentsStore.visibleRecentOptions( in: modelGroups, recentKeys: recentModelKeys, favoriteKeys: favoriteModelKeys ), - // A change in flight blocks other rows without dimming them; see the sheet. isDisabled: !controlGate.allowsConfigurationIgnoringUpdates, isUpdating: isUpdatingConfiguration, errorMessage: configurationErrorMessage, @@ -1451,7 +1226,6 @@ struct MessageComposerView: View { onSelectApprovalMode: onSelectApprovalMode, allModelsPicker: allModelsPicker ) - // Over this sheet while it is up; `ChatView`'s own stands down until it closes. .modifier(HermesModelConfirmationModifier(controls: modelConfirmationControls)) } @@ -1469,7 +1243,6 @@ struct MessageComposerView: View { providerID: selectedModelProviderID ) }, - // The current model's row opens this while another change is still out. isSelectionDisabled: isConfigurationControlDisabled, onSelect: onSelect, onToggleFavorite: { option in @@ -1508,15 +1281,6 @@ struct MessageComposerView: View { return match } - // No catalog match: carry the RAW id as `displayName` too. A locally - // shortened title here ("claude-haiku-4-5") would differ from the id - // and so read to `ModelDisplayNames` as a server-provided name — it - // would render verbatim instead of prettifying to "Haiku 4.5". Only - // the webui transport's `name`/`label` is a server name; anything the - // client derives must keep `displayName == id` to stay prettifiable. - // Display only: `matchesSelection` and the group lookup below match - // on id/provider, never on this string. A blank id has nothing to - // prettify, so it keeps the placeholder title ("Model"). let fallbackID = selectedModelID ?? selectedModelTitle return ModelCatalogOption( id: fallbackID, @@ -1535,8 +1299,6 @@ struct MessageComposerView: View { if let readOnlyMessage = access.readOnlyMessage { return (readOnlyMessage, false, nil, nil, nil, nil, nil) } else if let errorMessage, let onFixError { - // A Profile the Webapp doesn't serve leaves the chat on its cached copy, so it would - // read as offline; say why, with the fix (#1611). Send stays held by `access`. return (errorMessage, true, nil, nil, nil, onFixError, nil) } else if access.isOffline { return (ChatComposerSendBlock.offline.accessibilityValue, false, nil, nil, nil, nil, nil) @@ -1565,7 +1327,6 @@ struct MessageComposerView: View { return nil } - /// Only errors: the dictation row shows progress while a capture runs. private var voiceStatus: ComposerVoiceStatus? { guard !isDictating, let errorMessage = voiceInput.errorMessage else { return nil } return ComposerVoiceStatus( @@ -1575,9 +1336,6 @@ struct MessageComposerView: View { ) } - /// Voice-note status shown above the composer when *not* actively recording - /// (the recording bar covers that case): the permission prompt and recorder - /// errors like a denied microphone. private var voiceNoteStatus: ComposerVoiceStatus? { if voiceNoteRecorder.isRequestingPermission { return ComposerVoiceStatus( @@ -1647,9 +1405,6 @@ struct MessageComposerView: View { || voiceInput.isRequestingPermission } - /// Whether a hold-to-record gesture is allowed to start a new voice note. - /// Recording mid-stream is fine (it queues like any send), so unlike dictation - /// this does not block on `isWaitingForStream`. private var isVoiceNoteRecordingDisabled: Bool { !showsSessionControls || holdsHostControls @@ -1693,7 +1448,6 @@ struct MessageComposerView: View { sendButton.showsStop } - /// What a hold on Send offers right now: nothing while Send is disabled. private var sendChoices: [StreamingSendBehavior] { isActionButtonDisabled ? [] : sendButton.choices } @@ -1728,23 +1482,17 @@ struct MessageComposerView: View { ) } - /// VoiceOver's value on a Send that has a draft but is held by work in - /// progress. Stop, a read-only chat and an empty draft explain themselves. private var blockedSendReason: String? { guard !isReadOnly, !showsStopButton, !trimmedDraftMessage.isEmpty || !quotes.isEmpty || !pendingAttachments.isEmpty else { return nil } return sendBlock?.accessibilityValue } - /// A tap on the circle. The release of a hold that opened the send-choice - /// card lands here too, and is dropped so the hold never also sends. private func actionButtonPressed() { guard sendHold.activate() else { return } actionButtonTapped() } - /// Stop, or Send with the behavior it shows. Keyboard sends come here too, so a - /// hold that arrived after the key was enabled still stops it. private func actionButtonTapped() { guard !isActionButtonDisabled else { return } if showsStopButton { @@ -1757,9 +1505,6 @@ struct MessageComposerView: View { } } - /// The hardware-keyboard commands (#1380), titled like the circle and the send-choice - /// card. ⌘↩ is Send, never Stop; ⌘⇧↩ is the card's safe alternate; Esc closes what is - /// open before it stops the run through the usual confirmation, keeping the draft. private var keyboardCommands: ComposerKeyboardCommands { let button = sendButton var commands = ComposerKeyboardCommands() @@ -1784,12 +1529,6 @@ struct MessageComposerView: View { return commands } - /// Starts dictation once for a composer opened by the "New Chat with Voice" intent (#338), - /// mirroring a mic tap. Gated so it fires a single time, only while the app is active and - /// unlocked (the scene stays active under the app lock, so the microphone never starts - /// behind it) and the mic is free; the reused tap path handles the mic/speech permission - /// prompt and surfaces a clear error if access is denied, so a denied/undetermined mic - /// degrades gracefully. @MainActor private func autoStartVoiceInputIfNeeded() { guard autoStartsVoiceInput, !didAutoStartVoiceInput else { return } @@ -1801,13 +1540,9 @@ struct MessageComposerView: View { @MainActor private func toggleVoiceInput() { - // A recording from `+` leaves the mic free to tap; dictation must not start over it. guard !voiceNoteRecorder.isRecording else { return } voiceInput.transcribe = hermesTranscriber ?? apiClient?.dictationTranscriber voiceInput.providerPreference = ComposerSTTProviderPreference.storedValue(sttProviderPreferenceRawValue) - // Resign now, not on the next update: a live composition or a pending - // autocorrection commits as the editor lets go, and dictation's baseline - // has to include that edit. restoresFocusAfterDictation = isFocused if isFocused { UIApplication.shared.sendAction(#selector(ComposerChipTextView.resignForDictation), to: nil, from: nil, for: nil) @@ -1820,7 +1555,6 @@ struct MessageComposerView: View { composerSelection = composerSelection.moved(to: update.caret) } ) - // A start that fails at once never leaves idle where SwiftUI can see it. Task { await start.value if !isDictating { restoreFocusAfterDictation() } @@ -1834,8 +1568,6 @@ struct MessageComposerView: View { isFocused = true } - /// Hold recognized, or Voice note picked in `+` → start recording a voice note. - /// Gated by the recording disabled conditions; stops dictation first if it's running. @MainActor private func startVoiceNoteRecording(isHeld: Bool = true) { guard !isVoiceNoteRecordingDisabled, !voiceNoteRecorder.isRecording else { return } @@ -1848,8 +1580,6 @@ struct MessageComposerView: View { Task { await voiceNoteRecorder.begin() } } - /// Finger lifted (or max duration hit). Cancels if slid up past the threshold, - /// otherwise stops and sends the clip. @MainActor private func finishVoiceNote(translationHeight: CGFloat) { let shouldCancel = ComposerVoiceNoteGesture.isCancelArmed(dragTranslationHeight: translationHeight) @@ -1937,7 +1667,6 @@ struct MessageComposerView: View { requestTextViewFocusIfPossible() } - /// The card stays open across this, so returning from a sheet never flashes the pill. private func requestTextViewFocusIfPossible() { guard canFocusTextView else { return } isCardOpen = true diff --git a/HermesMobile/Features/Chat/ChatComposerVoiceControls.swift b/HermesMobile/Features/Chat/ChatComposerVoiceControls.swift index 72987aa4d..775014fd3 100644 --- a/HermesMobile/Features/Chat/ChatComposerVoiceControls.swift +++ b/HermesMobile/Features/Chat/ChatComposerVoiceControls.swift @@ -32,9 +32,6 @@ struct ComposerVoiceStatusView: View { } } -/// The composer's bottom row while dictation runs, in place of the toolbar: -/// cancel, then the waveform and timer, then finish. The row has no Send: the -/// draft is locked until the words land, and Send comes back with the toolbar. struct ComposerDictationRow: View { let voiceInput: ComposerVoiceInputController let circleSize: CGFloat @@ -98,7 +95,6 @@ struct ComposerDictationRow: View { } } - /// What the capture is called to VoiceOver, or nil while nothing is recording. private var capture: String? { switch voiceInput.state { case .listening: String(localized: "Listening...") @@ -114,9 +110,6 @@ struct ComposerDictationRow: View { } } -/// Recent mic levels as bars, newest on the trailing edge. This view is the only -/// reader of `levels`, so each sample redraws these bars and nothing else. With -/// Reduce Motion the bars stay flat and it reads nothing at all. struct ComposerDictationWaveform: View { let meter: ComposerVoiceLevelMeter @@ -151,13 +144,6 @@ struct ComposerDictationWaveform: View { } } -/// The composer mic. A quick **tap** toggles on-device dictation (unchanged); a -/// **press-and-hold** records a server-transcribed voice note, releasing to send -/// and sliding up to cancel. Both paths run through a single -/// `DragGesture(minimumDistance: 0)`: touch-down schedules a `DispatchWorkItem` -/// after the hold threshold, and a release before it fires cancels the item and -/// counts as a tap → dictation. See `pressGesture` for why timing beats composing -/// `LongPressGesture`/`TapGesture`. struct ComposerVoiceControlButton: View { let isDisabled: Bool let color: Color @@ -179,13 +165,9 @@ struct ComposerVoiceControlButton: View { .gesture(pressGesture) .accessibilityAddTraits(.isButton) .accessibilityAction { - // VoiceOver synthesizes an activation rather than a real touch, - // so the gesture's tap path never fires for it. if !isDisabled { onTap() } } .accessibilityAction(named: Text("Record voice note")) { - // VoiceOver can't hold-to-talk, so this starts recording; the - // recording bar then exposes "Stop and send" / "Cancel" actions. onRecordingStart() } } else { @@ -220,12 +202,6 @@ struct ComposerVoiceControlButton: View { Text(isRecordingVoiceNote ? String(localized: "Recording voice note") : String(localized: "Voice input")) } - /// One `DragGesture(minimumDistance: 0)` distinguishes tap from hold by timing, - /// which is far more reliable than composing `LongPressGesture`/`TapGesture`/ - /// `highPriorityGesture` (those let the press keep claiming the touch so the tap - /// never wins). Touch-down schedules a delayed "start recording"; a release - /// before the delay cancels it and counts as a tap → dictation. A perfectly - /// still hold still records because the delay is timer-driven, not movement-driven. private var pressGesture: some Gesture { DragGesture(minimumDistance: 0) .onChanged { value in @@ -270,15 +246,9 @@ struct ComposerVoiceControlButton: View { } } -/// Telegram-style indicator shown above the composer while a voice note records: -/// a pulsing red dot, an `m:ss` timer, and a slide-to-cancel hint that turns red -/// once the cancel threshold is armed, or Cancel and Send buttons when no finger is -/// holding the mic. Exposes explicit VoiceOver actions because the hold-to-talk -/// gesture isn't reachable with VoiceOver on. struct ComposerVoiceRecordingBar: View { let elapsed: TimeInterval let isCancelArmed: Bool - /// False when nothing is holding the mic, so a release can't end the recording. var isHeld = true let onStop: () -> Void let onCancel: () -> Void diff --git a/HermesMobile/Features/Chat/ChatGitControlsVisibilityPolicy.swift b/HermesMobile/Features/Chat/ChatGitControlsVisibilityPolicy.swift index af3824ab4..c2f21d9b7 100644 --- a/HermesMobile/Features/Chat/ChatGitControlsVisibilityPolicy.swift +++ b/HermesMobile/Features/Chat/ChatGitControlsVisibilityPolicy.swift @@ -1,8 +1,3 @@ -/// Decides whether turn-end git controls belong in the chat transcript. -/// -/// The Settings toggle is checked here with the existing workspace and turn -/// conditions so every transcript git surface follows the same visibility rule. -/// A repository without writes keeps the read-only recap and hides the commit button. enum ChatGitControlsVisibilityPolicy { static func showsInlineCommitButton( showsGitControls: Bool, diff --git a/HermesMobile/Features/Chat/ChatGoalControls.swift b/HermesMobile/Features/Chat/ChatGoalControls.swift index 91c977f52..b93f1e5f7 100644 --- a/HermesMobile/Features/Chat/ChatGoalControls.swift +++ b/HermesMobile/Features/Chat/ChatGoalControls.swift @@ -3,18 +3,13 @@ import SwiftUI struct GoalControlsMenu: View { let currentGoal: SubmittedGoal? let isViewingCachedData: Bool - /// Disables Set Goal. let isSetGoalDisabled: Bool - /// Disables the commands: Status, Pause, Resume, Mark Done, Clear and Stop. let isActionDisabled: Bool let onSetGoal: () -> Void let onSubmitCommand: (String) -> Void - /// A Hermes session's loop and heartbeat (#1142), a section each below the goal's commands. let automations: [BotSessionControl] - /// Whether the host takes Pause and Resume for them; without it they only show their state. let allowsAutomationChanges: Bool let isAutomationDisabled: Bool - /// Asks for one's Pause or Resume, which the chat confirms before sending. let onChangeAutomation: (BotSessionControl) -> Void var body: some View { @@ -69,7 +64,6 @@ struct GoalControlsMenu: View { } } - /// "Loop · Active" over its Pause, or the state alone when nothing can change it. @ViewBuilder private func automationSection(_ control: BotSessionControl) -> some View { let status = switch control.status { @@ -77,7 +71,6 @@ struct GoalControlsMenu: View { case "paused": String(localized: "Paused") default: control.status } - // Both halves are localized already; the separator is not words. let title = Text(verbatim: "\(control.kind.title) · \(status)") if allowsAutomationChanges, control.action != nil { Section { diff --git a/HermesMobile/Features/Chat/ChatHaptics.swift b/HermesMobile/Features/Chat/ChatHaptics.swift index 19fe08075..587ad09dc 100644 --- a/HermesMobile/Features/Chat/ChatHaptics.swift +++ b/HermesMobile/Features/Chat/ChatHaptics.swift @@ -8,25 +8,18 @@ enum ChatHapticFeedback: Equatable { case warning } -/// A Bot Chat or room action the host confirmed, published by the model for its -/// view to play through `ChatHaptics.botFeedback`. Models set it only on a success -/// path that already passed their stale-reply checks. `id` grows with every event, -/// so two identical events in a row both reach the view's `onChange`. struct BotFeedback: Equatable { enum Event: Equatable { case sent case approved(BotApprovalRequest.Choice) - /// A clarify answer or skip, or a credential value or skip. case answered case stopped - /// A turn this screen watched go from busy to idle. case turnCompleted } let event: Event let id: Int - /// The event that follows `previous`, with a fresh id. init(_ event: Event, after previous: BotFeedback?) { self.event = event id = (previous?.id ?? 0) + 1 @@ -58,13 +51,10 @@ enum ChatHaptics { } } - /// The Sessions haptic for a confirmed Bot Chat or room event, so a bot feels - /// the same as a session. static func botFeedback(_ event: BotFeedback.Event, isEnabled: Bool, performer: Performer? = nil) { switch event { case .sent: messageSent(isEnabled: isEnabled, performer: performer) case .approved(let choice): - // Both enums spell the host's once/session/always/deny. guard let choice = ApprovalChoice(rawValue: choice.rawValue) else { return } approvalSubmitted(choice, isEnabled: isEnabled, performer: performer) case .answered: clarificationSubmitted(isEnabled: isEnabled, performer: performer) @@ -85,9 +75,6 @@ enum ChatHaptics { emit(.selection, isEnabled: isEnabled, performer: performer) } - /// A row the user tapped in a composer's autocomplete panel: a command, - /// skill, sub-argument, file, folder, bot or mention. Dismissing the panel - /// is not a pick and plays nothing. static func autocompleteAccepted(isEnabled: Bool, performer: Performer? = nil) { emit(.selection, isEnabled: isEnabled, performer: performer) } @@ -96,52 +83,40 @@ enum ChatHaptics { emit(.warning, isEnabled: isEnabled, performer: performer) } - /// Any transcript disclosure: tool cards, tool groups, reasoning, marker cards. static func disclosureToggled(isEnabled: Bool, performer: Performer? = nil) { emit(.selection, isEnabled: isEnabled, performer: performer) } - /// The scroll-to-latest button, a deliberate jump rather than a follow scroll. static func scrolledToLatest(isEnabled: Bool, performer: Performer? = nil) { emit(.selection, isEnabled: isEnabled, performer: performer) } - /// Every pasteboard write the user asks for: messages, code blocks, files, titles, links. static func copied(isEnabled: Bool, performer: Performer? = nil) { emit(.lightImpact, isEnabled: isEnabled, performer: performer) } - /// The `running → finished` edge of a Git action shown in the toast overlay. - /// Call it once per action outcome, never from a view body. static func gitActionFinished(succeeded: Bool, isEnabled: Bool, performer: Performer? = nil) { emit(succeeded ? .success : .warning, isEnabled: isEnabled, performer: performer) } - /// A line tapped or long-pressed on the review diff surface. static func diffLineSelected(isEnabled: Bool, performer: Performer? = nil) { emit(.selection, isEnabled: isEnabled, performer: performer) } - /// Selected diff lines dropped into the composer draft. static func addedToPrompt(isEnabled: Bool, performer: Performer? = nil) { emit(.lightImpact, isEnabled: isEnabled, performer: performer) } - /// One tick of the opt-in pulse while assistant text streams. Callers throttle - /// with `StreamingPulseThrottle`; this only honors the enabled flag. static func streamingPulse(isEnabled: Bool, performer: Performer? = nil) { emit(.selection, isEnabled: isEnabled, performer: performer) } - /// Rate limit for the streaming pulse: at most one tick per `interval`, so a - /// fast token stream feels like a faint ticker instead of a buzz. struct StreamingPulseThrottle: Equatable { static let defaultInterval: TimeInterval = 0.32 var interval: TimeInterval = StreamingPulseThrottle.defaultInterval private var lastPulseAt: TimeInterval? - /// Records a token arrival. Returns `true` when enough time has passed for a pulse. mutating func shouldPulse(at now: TimeInterval) -> Bool { if let lastPulseAt, now - lastPulseAt < interval { return false diff --git a/HermesMobile/Features/Chat/ChatMarkerMessageClassifier.swift b/HermesMobile/Features/Chat/ChatMarkerMessageClassifier.swift index 8b6b69715..4dd8c14b9 100644 --- a/HermesMobile/Features/Chat/ChatMarkerMessageClassifier.swift +++ b/HermesMobile/Features/Chat/ChatMarkerMessageClassifier.swift @@ -1,15 +1,8 @@ import Foundation -/// Marker messages the agent emits around context compaction. The server sends -/// them as plain role-based messages with no structured flag, so — like the web -/// UI (`_isContextCompactionMessage` / `_isPreservedCompressionTaskListMessage` -/// in `ui.js`) — we detect them by content prefix. enum ChatMarkerMessageKind: Equatable { case contextCompaction case preservedTaskList - /// Synthesized "Context compaction · Reference only" anchor card built from - /// session-level `compression_anchor_*` metadata — never produced by - /// `classify`, which only sees literal marker messages. case compressionReference var title: String { @@ -42,17 +35,11 @@ enum ChatMarkerMessageClassifier { return nil } - /// Mirrors the web UI's `_isContextCompactionText`: true when the text is - /// itself a literal compaction marker (used both for classification and to - /// gate the synthesized reference card). static func isContextCompactionText(_ text: String?) -> Bool { let trimmed = (text ?? "").trimmingCharacters(in: .whitespacesAndNewlines) return contextCompactionPrefixes.contains { hasCaseInsensitivePrefix(trimmed, $0) } } - /// The card body with the preserved-task-list marker line stripped, so the - /// preview/expanded text starts at the actual task list (mirrors the web - /// UI's `_preservedCompressionTaskListPreview`). static func cardBody(for kind: ChatMarkerMessageKind, content: String?) -> String { let text = (content ?? "").trimmingCharacters(in: .whitespacesAndNewlines) diff --git a/HermesMobile/Features/Chat/ChatMessageActions.swift b/HermesMobile/Features/Chat/ChatMessageActions.swift index 7dfd4d546..8c9ba2d95 100644 --- a/HermesMobile/Features/Chat/ChatMessageActions.swift +++ b/HermesMobile/Features/Chat/ChatMessageActions.swift @@ -12,8 +12,6 @@ struct SelectableTextPresentation: Identifiable, Equatable { } -/// One entry of the message action menu. The SwiftUI menu and the UIKit -/// context-menu interaction both build from this list so they never drift. struct ChatMessageActionItem: Identifiable { enum Kind: Hashable { case listen @@ -32,9 +30,6 @@ struct ChatMessageActionItem: Identifiable { var id: Kind { kind } } -/// The long-press menu is built from the item list alone, so any transcript -/// that can name its own actions — Sessions, a Bot chat, a group room — gets -/// the same UIKit menu without owning a chat view model. extension Array where Element == ChatMessageActionItem { @MainActor func uiMenu() -> UIMenu { @@ -75,9 +70,6 @@ struct ChatMessageActionMenu: View { } } - /// The actions for this message in display order. Mutating actions are - /// disabled while the transcript is cached or a stream is active, and absent - /// where the chat cannot rewrite its history (`MessageActionContext`). var items: [ChatMessageActionItem] { var items: [ChatMessageActionItem] = [] let offersHistoryActions = context.offersHistoryActions @@ -134,7 +126,6 @@ struct ChatMessageActionMenu: View { return items } - /// The same actions as a UIKit menu, for `ChatMessageContextMenuView`. func uiMenu() -> UIMenu { items.uiMenu() } @@ -178,9 +169,6 @@ struct SelectableTextView: UIViewRepresentable { textView.backgroundColor = .appCanvas textView.font = .app(forTextStyle: .body, at: context.environment.dynamicTypeSize) textView.adjustsFontForContentSizeCategory = true - // A wrapped UITextView does not inherit SwiftUI's layoutDirection; `.natural` - // lets each paragraph align by its own writing direction so RTL message text - // reads right-aligned while LTR stays left-aligned (issue #294). textView.textAlignment = .natural textView.textContainerInset = UIEdgeInsets(top: 16, left: 16, bottom: 32, right: 16) textView.textContainer.lineFragmentPadding = 0 diff --git a/HermesMobile/Features/Chat/ChatMessageContextMenuView.swift b/HermesMobile/Features/Chat/ChatMessageContextMenuView.swift index 963587bd7..57aee4207 100644 --- a/HermesMobile/Features/Chat/ChatMessageContextMenuView.swift +++ b/HermesMobile/Features/Chat/ChatMessageContextMenuView.swift @@ -1,20 +1,7 @@ import SwiftUI import UIKit -/// Attaches the message action menu to a transcript bubble through UIKit's -/// `UIContextMenuInteraction` instead of SwiftUI's `.contextMenu`. -/// -/// SwiftUI lifts a snapshot of the whole bubble before it can show the menu. -/// On a multi-screen reply that snapshot is slow and taller than the screen, -/// so the menu lands over the undimmed transcript and then jumps as UIKit -/// makes room. Here nothing is lifted: the transcript dims and the menu opens -/// beside the press in one motion, whatever the reply's length (issue #208). extension View { - /// Attach to the message content itself, not the full-width row, so the - /// menu opens only where there is something to act on. An empty list - /// leaves the view untouched. Pass `longPress: false` on selectable text: - /// the menu's long-press outranks text selection, so there the actions - /// stay reachable through VoiceOver only and selection supplies Copy. @ViewBuilder func chatMessageContextMenu(_ actions: [ChatMessageActionItem], longPress: Bool = true) -> some View { if actions.isEmpty { @@ -46,13 +33,6 @@ private struct ChatMessageContextMenuHost: UIViewRepresentable { } } -/// A clear, touch-transparent view behind one bubble. It only marks the -/// bubble's frame and menu for the coordinator on the transcript's scroll view. -/// -/// The interaction cannot live here: SwiftUI's text-selection long-press on -/// the hosting view outranks recognizers on child platform views, so a menu -/// attached to this view never fires. On the scroll view it wins, as it does -/// in a collection view. final class ChatMessageContextMenuView: UIView { var actions: [ChatMessageActionItem] = [] @@ -90,8 +70,6 @@ final class ChatMessageContextMenuView: UIView { } } -/// One context-menu interaction per transcript scroll view. Rows register -/// while on screen; a long-press resolves to the row under the touch. @MainActor final class ChatMessageContextMenuCoordinator: NSObject, UIContextMenuInteractionDelegate { private static let coordinators = NSMapTable( @@ -111,8 +89,6 @@ final class ChatMessageContextMenuCoordinator: NSObject, UIContextMenuInteractio private weak var scrollView: UIScrollView? private let rows = NSHashTable.weakObjects() - /// The row being presented and the press point inside it, which anchors - /// the menu. private weak var activeRow: ChatMessageContextMenuView? private var pressInRow: CGPoint = .zero @@ -165,9 +141,6 @@ final class ChatMessageContextMenuCoordinator: NSObject, UIContextMenuInteractio anchorPreview() } - /// An invisible preview at the press point. It gives UIKit something to - /// anchor the menu to without lifting any of the bubble; the bubble stays - /// in place under the dim like the rest of the transcript. private func anchorPreview() -> UITargetedPreview? { guard let activeRow else { return nil } let anchor = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) diff --git a/HermesMobile/Features/Chat/ChatMessageMeta.swift b/HermesMobile/Features/Chat/ChatMessageMeta.swift index fc641a4ca..89a7b8183 100644 --- a/HermesMobile/Features/Chat/ChatMessageMeta.swift +++ b/HermesMobile/Features/Chat/ChatMessageMeta.swift @@ -1,13 +1,10 @@ import SwiftUI -/// Timestamps belong to user messages and settled terminal replies. Actions -/// remain reachable on every actionable message, including a turn still streaming. enum TranscriptMessageMetaPolicy { static func showsRow(hasActions: Bool, hasTimestamp: Bool) -> Bool { hasActions || hasTimestamp } - /// Render IDs of the last bubble-bearing reply of each settled assistant turn. static func terminalReplyRenderIDs( transcriptMessages: [TranscriptMessage], messages: [ChatMessage], @@ -39,11 +36,6 @@ enum TranscriptMessageMetaPolicy { } } -/// The row under a message bubble: timestamp, copy, and completed-response actions. -/// User rows read `[accessory][time][copy]` against the trailing edge, assistant -/// rows `[copy][actions][accessory][time]` against the leading edge, so Copy -/// always sits at the outer edge and RTL mirrors both through the semantic -/// alignments. The accessory slot is optional; Sessions passes none. struct ChatMessageMetaRow: View { let isUserMessage: Bool let timeText: String? @@ -117,9 +109,6 @@ extension ChatMessageMetaRow where Accessory == EmptyView { } } -/// A copy button that answers with a checkmark for `feedbackDuration` after -/// each tap. The caller writes the pasteboard and fires the haptic; this only -/// owns the feedback state, and SwiftUI cancels the reset with the view. struct ChatCopyButton: View { static let feedbackDuration: Duration = .milliseconds(1200) @@ -161,11 +150,6 @@ struct ChatCopyButton: View { } } -// MARK: - Timestamp formatting - -/// Formats a message's unix `timestamp` as a short, locale-/24h-aware time -/// (e.g. `2:14 PM` or `14:14`). Returns `nil` for a missing or non-finite -/// timestamp so the meta row simply omits the time. enum ChatMessageTimestampFormatter { private static let sharedFormatter: DateFormatter = makeFormatter( locale: .autoupdatingCurrent, @@ -176,8 +160,6 @@ enum ChatMessageTimestampFormatter { format(timestamp, with: sharedFormatter) } - /// Test seam: format against an explicit locale/time zone so 12h/24h - /// assertions stay deterministic regardless of host device settings. static func shortTime( forUnixTimestamp timestamp: Double?, locale: Locale, diff --git a/HermesMobile/Features/Chat/ChatMotion.swift b/HermesMobile/Features/Chat/ChatMotion.swift index 877ed68ad..9bd70bd17 100644 --- a/HermesMobile/Features/Chat/ChatMotion.swift +++ b/HermesMobile/Features/Chat/ChatMotion.swift @@ -1,6 +1,5 @@ import SwiftUI -/// Chat animation curves. Reduce Motion always snaps (`nil`); do not substitute a shorter ease. enum ChatMotion { static func press(duration: Double, reduceMotion: Bool) -> Animation? { reduceMotion ? nil : .smooth(duration: duration, extraBounce: 0) @@ -18,8 +17,6 @@ enum ChatMotion { reduceMotion ? nil : .smooth(duration: 0.22, extraBounce: 0) } - /// The system keyboard's own curve, for what has to move with it. These spring values are the - /// widely used match for its private animation curve. static func keyboard(reduceMotion: Bool) -> Animation? { reduceMotion ? nil : .interpolatingSpring(mass: 3, stiffness: 1000, damping: 500) } @@ -28,9 +25,6 @@ enum ChatMotion { reduceMotion ? nil : .easeOut(duration: 0.20) } - /// Expanding or collapsing the clarification card above the composer. The - /// card slides its own height past the bar's bottom edge on one ease-out - /// clock, sized like the keyboard's; Reduce Motion snaps. static func clarificationToggle(reduceMotion: Bool) -> Animation? { reduceMotion ? nil : .easeOut(duration: 0.22) } @@ -43,12 +37,6 @@ enum ChatMotion { reduceMotion ? .opacity : .opacity.combined(with: .move(edge: .top)) } - /// Entrance for a transcript row born moments ago: user rows fade up, - /// assistant rows fade. The animation rides on the transition itself, so - /// the row animates without wrapping the message append in `withAnimation` - /// and without animating layout (the bottom anchor still snaps). Removal - /// stays instant so an optimistic rollback never lingers. Reduce Motion - /// disables the entrance entirely. static func freshRowTransition(isUserRow: Bool, reduceMotion: Bool) -> AnyTransition { guard !reduceMotion else { return .identity } let insertion: AnyTransition = isUserRow ? .opacity.combined(with: .offset(y: 8)) : .opacity diff --git a/HermesMobile/Features/Chat/ChatPendingActionCoordinator.swift b/HermesMobile/Features/Chat/ChatPendingActionCoordinator.swift index 4e0b31e96..b688f82c4 100644 --- a/HermesMobile/Features/Chat/ChatPendingActionCoordinator.swift +++ b/HermesMobile/Features/Chat/ChatPendingActionCoordinator.swift @@ -7,8 +7,6 @@ private let chatPendingActionCoordinatorLogger = Logger( category: "ChatPendingActionCoordinator" ) -/// Friendly stand-in for the server's 409 `{"stale": true}` respond rejection: -/// the prompt already expired, so the card is dismissed instead of erroring (issue #25). struct PendingPromptExpiredError: LocalizedError, Equatable { enum Prompt: Equatable { case approval @@ -44,12 +42,8 @@ final class ChatPendingActionCoordinator { private(set) var isRespondingToApproval = false private(set) var approvalErrorMessage: String? private(set) var isSessionApprovalBypassEnabled = false - /// A write from Model settings' YOLO switch in flight. private(set) var isChangingApprovalBypass = false - /// Why that switch's last write failed. Cleared by the next one. private(set) var approvalBypassErrorMessage: String? - /// Bumped as each bypass write starts and as it answers, so a read sent before the answer - /// can't overwrite it. private var approvalBypassWrites = 0 private(set) var clarificationPrompt: ClarificationPromptState? @@ -111,10 +105,8 @@ final class ChatPendingActionCoordinator { renderApprovalPromptForCurrentSession() } } catch { - // Approval bypass state is advisory UI; failures should not block chat. } - // A pending approval can outlive the chat stream, including across navigation. guard !Task.isCancelled, !isSessionApprovalBypassEnabled else { return } await refreshApprovalPending(sessionID: sessionID) } @@ -137,16 +129,6 @@ final class ChatPendingActionCoordinator { approvalID: prompt.pending.approvalId ) - // The protective refusals answer HTTP 200 with `{"ok": false}` - // (`_handle_approval_respond` → `j(handler, {"ok": ok, …})`, - // `api/routes.py:24549` @ 399cd7ab, and `j()` defaults to 200), so - // only a non-2xx status threw and a deliberate refusal read as - // success: the card was cleared, the user was told nothing, and the - // agent stayed blocked. `stale_cleared` is the one false that still - // means "this card is finished". - // - // Only an explicit success may clear a live card. A missing `ok` - // is unknown and must fail closed. guard response.ok == true || response.staleCleared == true else { approvalErrorMessage = String(localized: "The server did not accept that response. The request is still waiting.") await refreshApprovalPending(sessionID: prompt.sessionID) @@ -160,8 +142,6 @@ final class ChatPendingActionCoordinator { return true } catch { if (error as? APIError)?.indicatesExpiredPendingPrompt == true { - // The prompt already expired server-side: dismiss the stale card and - // explain, instead of leaving a stuck card behind a generic failure. approvalStateGeneration &+= 1 approvalPendingBySession[prompt.sessionID] = nil approvalPrompt = nil @@ -203,9 +183,6 @@ final class ChatPendingActionCoordinator { } } - /// Model settings' YOLO switch. Turning it on releases a waiting approval on the server. - /// Turning it off asks again for any approval the server holds and resumes watching, since - /// the empty update that released one also ended the monitoring. func setApprovalBypass(_ enabled: Bool) async { guard let sessionID = delegate?.pendingActionSessionID, !isChangingApprovalBypass, enabled != isSessionApprovalBypassEnabled else { return } @@ -244,8 +221,6 @@ final class ChatPendingActionCoordinator { } func stopMonitoringForStreamTransition(clearClarification: Bool) { - // A pending approval belongs to the server, not to the chat transport. - // The approval event can arrive after chat completion on its own SSE stream. if delegate?.pendingActionIsStreamConnectionSuspended == true { stopApprovalMonitoring(clearPrompt: false) } @@ -263,7 +238,6 @@ final class ChatPendingActionCoordinator { } else if update.pendingCount == 0 { approvalPendingBySession[sessionID] = nil } else { - // An unrecognized SSE payload is not a server-confirmed clear. return } @@ -309,8 +283,6 @@ final class ChatPendingActionCoordinator { return true } catch { if (error as? APIError)?.indicatesExpiredPendingPrompt == true { - // The prompt already expired server-side: dismiss the stale card and - // explain, instead of leaving a stuck card behind a generic failure. clarificationPendingBySession[prompt.sessionID] = nil clarificationPrompt = nil delegate?.pendingActionCoordinatorDidFailAction(PendingPromptExpiredError(prompt: .clarification)) @@ -400,8 +372,6 @@ final class ChatPendingActionCoordinator { else { break pollingLoop } await self.refreshApprovalPending(sessionID: sessionID) - // An empty snapshot cannot rule out a later approval. Keep - // polling while this chat is open if its SSE connection failed. } guard !Task.isCancelled else { break } @@ -422,7 +392,6 @@ final class ChatPendingActionCoordinator { approvalStateGeneration == generation else { return } applyApprovalUpdate(response, sessionID: sessionID) } catch { - // The web UI also ignores degraded-mode polling failures. chatPendingActionCoordinatorLogger.debug( "Approval polling failed category=\(APIError.privacySafeLogCategory(for: error), privacy: .public)" ) @@ -527,7 +496,6 @@ final class ChatPendingActionCoordinator { let response = try await client.clarifyPending(sessionID: sessionID) applyClarificationUpdate(response, sessionID: sessionID) } catch { - // The web UI also ignores degraded-mode polling failures. chatPendingActionCoordinatorLogger.debug( "Clarification polling failed category=\(APIError.privacySafeLogCategory(for: error), privacy: .public)" ) diff --git a/HermesMobile/Features/Chat/ChatScrollPolicy.swift b/HermesMobile/Features/Chat/ChatScrollPolicy.swift index db63c4ad1..d9eb5129c 100644 --- a/HermesMobile/Features/Chat/ChatScrollPolicy.swift +++ b/HermesMobile/Features/Chat/ChatScrollPolicy.swift @@ -2,34 +2,9 @@ import CoreGraphics import Foundation import SwiftUI -/// Pure decision rules for the chat transcript's auto-scroll behavior. -/// -/// Auto-follow is an explicit latch rather than a distance test. -/// -/// Follow switches **off** when a drag begins, when a live gesture moves the -/// offset, or when a scroll with no gesture carries the reader away from the -/// bottom (a status-bar tap, VoiceOver, or a hardware-keyboard scroll). -/// -/// Follow switches **on** when a scroll-to-bottom tap or a send resets it, when -/// a gesture settles at the true bottom, or when a non-gesture offset change -/// lands at the true bottom from nearby (a collapse near the end clamping the -/// offset). Landing at the bottom from far above is a relayout artifact, never -/// a reason to follow. -/// -/// Layout growth from streaming tokens and keyboard inset changes never flip -/// the latch on their own, so a reader parked above the end stays parked. The -/// distance thresholds below drive the scroll-to-bottom button, the -/// reading-older chrome, and how far a gesture-free scroll must carry the -/// reader before it counts as leaving. enum ChatScrollPolicy { - /// Existing transcripts should enter at their latest content as part of the - /// scroll view's first layout, before the destination becomes visible. static let initialTranscriptAnchor = UnitPoint.bottom - /// Rich Markdown can finish measuring after the scroll view's initial - /// layout. Keep those size changes bottom-pinned only while follow is - /// latched on and no disclosure toggle is settling; otherwise return nil so - /// the reader's offset, and the row they just tapped, stay where they are. static func sizeChangeAnchor( shouldFollowLatestMessage: Bool, isDisclosureSettling: Bool = false @@ -37,56 +12,26 @@ enum ChatScrollPolicy { shouldFollowLatestMessage && !isDisclosureSettling ? .bottom : nil } - /// Distance (pt) from the bottom within which the scroll-to-bottom button - /// stays hidden while idle. static let bottomDetectionThreshold: CGFloat = 80 - /// Looser bottom threshold while a response is streaming, so small layout - /// jitter from incoming tokens does not flash the scroll-to-bottom button. static let streamingBottomDetectionThreshold: CGFloat = 160 - /// Strict bottom tolerance (pt) that re-arms follow when a gesture ends there. static let followReArmThreshold: CGFloat = 12 - /// How long a finished drag waits for momentum to announce itself before the - /// release position is treated as final. Finger-lift velocity is not a - /// reliable signal: a gentle fling can report zero and still decelerate. static let dragSettleDelay: TimeInterval = 0.16 - /// Gap between momentum ticks that means deceleration has stopped. static let momentumSettleDelay: TimeInterval = 0.05 - /// How long follow scrolls and the bottom size-change anchor stay suspended - /// after a disclosure toggle. Covers the disclosure animation plus a frame. static let disclosureAnchorSuspension: TimeInterval = 0.25 - /// The offset pin armed by a disclosure toggle releases once the content - /// size has been quiet this long. Lazy rows can keep laying out well past - /// the animation, and SwiftUI re-applies the bottom anchor on each of those - /// size changes after a status-bar scroll, so a fixed window is not enough. static let disclosureHoldQuietPeriod: TimeInterval = 0.3 - /// Upper bound on the pin, so a transcript that never goes quiet (streaming - /// tokens) still returns to normal scrolling. static let disclosureHoldMaximum: TimeInterval = 2 - /// Scroll-gesture events that drive the follow latch. enum FollowEvent: Equatable { - /// An explicit jump to the latest content: scroll-to-bottom tap or send. case reset - /// The user started dragging the transcript. case userScrollBegin - /// The user's gesture settled: a drag with no momentum after - /// `dragSettleDelay`, or deceleration coming to rest. Re-arms at the - /// bottom; elsewhere it keeps whatever the latch already is, so a - /// send or scroll-to-bottom tap that landed while the gesture was - /// still settling is not undone by the late settle report. case userScrollEnd(isAtBottom: Bool) - /// The content offset changed for any other reason: streaming growth, - /// keyboard presentation, a programmatic scroll, or a live gesture. - /// `movedAwayFromBottom` marks a scroll with no gesture that carried - /// the reader away from the bottom (see `isScrollingAwayFromBottom`); - /// `wasNearBottom` is where the previous report left the reader. case contentScrolled( isAtBottom: Bool, isUserScrolling: Bool, @@ -95,7 +40,6 @@ enum ChatScrollPolicy { ) } - /// The scroll geometry one metrics report is derived from. struct ScrollGeometry: Equatable { var offsetY: CGFloat var contentHeight: CGFloat @@ -106,13 +50,6 @@ enum ChatScrollPolicy { } } - /// True when a report without a gesture shows the reader farther from the - /// bottom than the last one, past the streaming threshold, in the same - /// viewport. While follow is on the bottom anchor snaps every size change - /// back to zero distance, so only an actual scroll (status-bar tap, - /// VoiceOver, hardware keyboard) can move the reader out that far. Keyboard - /// insets change the viewport and are excluded; the scroll observer - /// suppresses the check while a disclosure pin holds the offset. static func isScrollingAwayFromBottom(previous: ScrollGeometry?, current: ScrollGeometry) -> Bool { guard let previous, previous.visibleHeight == current.visibleHeight else { return false } let distance = current.distanceFromBottom @@ -120,24 +57,15 @@ enum ChatScrollPolicy { && distance > streamingBottomDetectionThreshold } - /// The follow latch. `isFollowing` is the answer; the second flag lets an - /// explicit reset outlive a gesture that was still coasting when it landed. struct FollowLatch: Equatable { var isFollowing = true - /// Set by `.reset`. Until the gesture settles or a new drag begins, live - /// offset changes still flagged as user scrolling belong to momentum - /// that predates the explicit action and must not switch follow off. var ignoresCoastingGesture = false } - /// Whether a send while a response streams jumps the reader to the end (`.reset`). Steer - /// and Stop and send show the prompt as a transcript row; Queue holds it as a pending - /// bubble or composer receipt (#1379), so a reader up in history stays there. static func streamingSendReArmsFollow(_ behavior: StreamingSendBehavior) -> Bool { behavior != .queue } - /// Reduces one event onto the current latch state. static func resolveFollow(current: FollowLatch, event: FollowEvent) -> FollowLatch { var latch = current switch event { @@ -164,7 +92,6 @@ enum ChatScrollPolicy { return latch } - /// Proximity, not the follow latch, hides the arrow at the bottom. static func showsScrollToBottomButton(isNearBottom: Bool, isStreaming: Bool, isFollowing: Bool) -> Bool { !isNearBottom && (!isStreaming || !isFollowing) } @@ -181,24 +108,15 @@ enum ChatScrollPolicy { distanceFromBottom <= bottomThreshold(isStreaming: isStreaming) } - /// The reader's place in a row, kept through a rewrap (rotation, a narrower - /// window, a text-size change) that moves every row under the reader (#1414). - /// Approximate: the same share of the row's height, not the same glyph. struct ReflowAnchor: Equatable { - /// The row's `renderID`, or the key of a block between rows. let id: String - /// Share of the row's height above the reading line, 0...1. let fractionWithinRow: CGFloat } - /// Where a reflow or a rebuilt transcript keeps the reader (#1528). The top - /// is a place of its own: its offset changes with the bars' insets. enum ReadingPlace: Equatable { case top case row(ReflowAnchor) - /// Whether `id`'s new frame can move this place: the row's own, or any at the top, - /// where a frame moving means the bars' insets may have too. func dependsOnFrame(of id: String) -> Bool { switch self { case .top: true @@ -207,9 +125,6 @@ enum ChatScrollPolicy { } } - /// The row under `readingLineY`, all in the transcript content's coordinates. - /// A line in the gap after a row, or below the last one, keeps the end of the - /// row above it. Nil at the top and above the first row, which keep the top. static func reflowAnchor(readingLineY: CGFloat, isAtTop: Bool, rowFrames: [String: CGRect]) -> ReflowAnchor? { guard !isAtTop else { return nil } let row = rowFrames @@ -220,21 +135,11 @@ enum ChatScrollPolicy { return ReflowAnchor(id: row.key, fractionWithinRow: min(max(fraction, 0), 1)) } - /// Where the reading line belongs once the anchor's row has its new frame. static func reflowReadingLineY(anchor: ReflowAnchor, newFrame: CGRect) -> CGFloat { newFrame.minY + anchor.fractionWithinRow * newFrame.height } } -/// Transcript disclosure controls (reasoning blocks, tool cards, tool groups, -/// turn folds) call this right before they toggle so the transcript can pin -/// the reader's offset and suspend follow scrolls through the size change. -/// -/// A reference, not a closure: SwiftUI cannot compare closures, so a closure -/// rebuilt on each transcript pass (every stream tick and keystroke) would -/// invalidate every reader. `chatDisclosureToggled(perform:)` keeps one -/// instance and refreshes `handler` in place, which nothing observes, so -/// readers see the same value on every pass. final class ChatDisclosureToggleAction: Equatable { var handler: () -> Void = {} @@ -254,11 +159,6 @@ extension EnvironmentValues { } } -/// Routes link taps through one `OpenURLAction` that outlives body passes, for -/// the same reason as `ChatDisclosureToggleAction`. The screen's `handler` sees -/// each link first and returns nil for links it does not own; of those, web -/// pages go to `SafariView` (their app, else the in-app browser) and the rest -/// go to the system. final class TranscriptLinkRouter { enum Decision { case host(OpenURLAction.Result) @@ -275,7 +175,6 @@ final class TranscriptLinkRouter { self?.route(url) ?? .systemAction } - /// What a tap on `url` does, given the screen handler's result for it. static func decision(for url: URL, hostResult: OpenURLAction.Result?) -> Decision { if let hostResult { return .host(hostResult) } return InAppBrowserPolicy.opensInApp(url) ? .inAppBrowser : .system @@ -295,32 +194,20 @@ final class TranscriptLinkRouter { } extension View { - /// Publishes `handler` to the transcript's disclosure controls without - /// invalidating them when the caller rebuilds the closure. func chatDisclosureToggled(perform handler: @escaping () -> Void) -> some View { modifier(ChatDisclosureToggledModifier(handler: handler)) } - /// Routes every link tap below this view through `handler` first, without - /// invalidating link readers when the caller rebuilds the closure. Links - /// the handler returns nil for open web pages in the app that claims them, - /// else in an in-app Safari sheet over whatever is on screen (`SafariView`); - /// other links go to the system. func transcriptLinks(perform handler: @escaping (URL) -> OpenURLAction.Result?) -> some View { modifier(TranscriptLinksModifier()) .modifier(TranscriptLinkHandlerModifier(handler: handler)) } - /// `transcriptLinks(perform:)` for a screen with no links of its own. func transcriptLinks() -> some View { transcriptLinks { _ in nil } } } -// The stable instances live in these modifiers' own state, not the caller's. -// Handlers usually capture the calling view, whose state would otherwise hold -// the instance that holds the handler: a cycle that outlives the screen. - private struct ChatDisclosureToggledModifier: ViewModifier { let handler: () -> Void @State private var action = ChatDisclosureToggleAction() @@ -331,8 +218,6 @@ private struct ChatDisclosureToggledModifier: ViewModifier { } } -/// Owns the router and refreshes its handler on every pass, publishing only the -/// router itself: a reference that compares equal, as with `chatDisclosureToggled`. private struct TranscriptLinkHandlerModifier: ViewModifier { let handler: (URL) -> OpenURLAction.Result? @State private var router = TranscriptLinkRouter() @@ -343,10 +228,6 @@ private struct TranscriptLinkHandlerModifier: ViewModifier { } } -/// Publishes the enclosing router's `openURL`. It takes no inputs and its one -/// dependency never changes, so owner passes skip its body and `openURL` is -/// written once: re-written on every pass, iOS 26 could treat it as changed -/// and re-run every link reader (ChatTranscriptEnvironmentStabilityTests). private struct TranscriptLinksModifier: ViewModifier { @Environment(\.transcriptLinkRouter) private var router @@ -366,11 +247,7 @@ private extension EnvironmentValues { } } -/// A run keeps reader ownership even after an explicit latest/send re-arms follow. -/// Only an owned successful completion can consume this one-shot permission. struct ChatCompletionScrollPolicy { - /// Use the final visible row of the current turn, never an older reply or - /// an interim bubble. Render identity remains stable through hydration. static func finalResponseRenderID( in messages: [TranscriptMessage], terminalReplyRenderIDs: Set ) -> String? { diff --git a/HermesMobile/Features/Chat/ChatStreamCoordinator.swift b/HermesMobile/Features/Chat/ChatStreamCoordinator.swift index 9a8aa5be8..50cc0cdc8 100644 --- a/HermesMobile/Features/Chat/ChatStreamCoordinator.swift +++ b/HermesMobile/Features/Chat/ChatStreamCoordinator.swift @@ -13,8 +13,6 @@ struct ChatStreamCoordinatorTiming: Equatable { let reconnectInterval: TimeInterval let runningToolReconnectInterval: TimeInterval let statusPollCooldown: TimeInterval - // Transport quieter than this is treated as provably alive; must sit above - // the server's ~5s SSE heartbeat cadence and below reconnectInterval (#227). let transportFreshInterval: TimeInterval static let standard = ChatStreamCoordinatorTiming( @@ -26,12 +24,9 @@ struct ChatStreamCoordinatorTiming: Equatable { ) } -/// Delays between reconnect status probes. Production sleeps; tests inject a no-op -/// so the retry loop can be asserted without waiting (#537). typealias ChatStreamReconnectDelay = @Sendable (TimeInterval) async throws -> Void enum ChatStreamReconnectBackoff { - /// Delays after the initial probe: three retries at 1s, 2s, and 4s. static let delays: [TimeInterval] = [1, 2, 4] static let maxProbeAttempts = delays.count + 1 @@ -55,7 +50,6 @@ struct ChatStreamSnapshotRestoreResult: Equatable { ) } -/// Span of a finished run and how it ended; the view model keys it to a turn. struct ChatRunEnding: Equatable { let startedAt: Date let endedAt: Date @@ -110,13 +104,6 @@ protocol ChatStreamCoordinatorDelegate: AnyObject { func streamCoordinatorEnqueuePendingSteerLeftover(_ text: String) -> Bool } -/// The run lifecycle `ChatViewModel` reads and drives whichever backend runs the chat's -/// turns: a webui server's SSE streams (`ChatStreamCoordinator`) or a Hermes session on -/// the gateway socket (`HermesChatTurnCoordinator`, #1010). Both feed the same -/// `ChatStreamCoordinatorDelegate`, so transcript building, pacing and run endings stay -/// shared. `activeStreamID` names the running turn: a webui stream id, or a Hermes turn -/// identity. Starting, cancelling and reconciling a webui session load stay on -/// `ChatStreamCoordinator`, since they speak its REST contract. @MainActor protocol ChatTurnCoordinating: AnyObject { var activeStreamID: String? { get } @@ -126,9 +113,7 @@ protocol ChatTurnCoordinating: AnyObject { var successfulResponseCompletion: ChatStreamCoordinator.SuccessfulResponseCompletion? { get } var liveTokensPerSecond: Double? { get } var hasCompletedCurrentResponse: Bool { get } - /// The chat left or backgrounded mid-turn; `reconnectIfNeeded` resumes it. var isConnectionSuspended: Bool { get } - /// Events may repeat text the transcript already holds, so appends deduplicate. var isReplayConnection: Bool { get } func attach(delegate: any ChatStreamCoordinatorDelegate) @@ -153,13 +138,9 @@ final class ChatStreamCoordinator { private let ratingPromptState: RatingPromptState private let timing: ChatStreamCoordinatorTiming private let reconnectDelay: ChatStreamReconnectDelay - /// Whether the device has a network. False parks recovery in - /// `.waitingForNetwork` without probing; tests pass a fake. private let isNetworkAvailable: @MainActor () -> Bool private var showsLiveActivityResponseExcerpts: Bool - /// Retains hydration requirements through transport teardown, which can arrive - /// before SwiftUI observes the successful completion. struct SuccessfulResponseCompletion { let streamID: String let needsTranscriptRefresh: Bool @@ -175,29 +156,12 @@ final class ChatStreamCoordinator { } } } - /// When the run behind the current stream started. Seeded by the caller from - /// the server's `pending_started_at` (session load and `/api/chat/start`), - /// then the latest user message's timestamp, and only failing both from the - /// local moment this coordinator discovered the stream. Keyed to stream - /// identity, so a same-stream reattach keeps counting from the same instant - /// instead of restarting "Working for" on every return to the session. private(set) var activeRunStartedAt: Date? - /// The last run's span and how it ended, recorded the moment the run stops - /// counting (`done` or teardown) so the delegate can key it to a turn. - /// Cleared when the next run starts, so a stale ending never outlives it. private(set) var latestRunEnding: ChatRunEnding? private(set) var recoveryState: ActiveStreamRecoveryState = .idle private(set) var isConnectionSuspended = false private(set) var hasCompletedCurrentResponse = false - /// Terminal-content fence (#288 review): set when the response completes and - /// NOT cleared by finishStream, so content queued after `done → streamEnd` - /// still cannot reach the transcript. Cleared only by the next run start / - /// new-response preparation / session load. @ObservationIgnored private var isTerminalContentFenceActive = false - /// Per-run one-shot teardown owner. The first caller of finishStream owns - /// teardown; later terminal events are ignored so delegate finish, snapshot - /// cleanup, queue drain, and title-refresh side effects cannot repeat. - /// Reset wherever the content fence disarms. @ObservationIgnored private var isTransportFinished = false @ObservationIgnored private(set) var lastEventID: String? @ObservationIgnored private(set) var lastProgressDate: Date? @@ -206,10 +170,6 @@ final class ChatStreamCoordinator { @ObservationIgnored private var lastRecoveryStatusCheckDate: Date? @ObservationIgnored private var hasInMemorySnapshotForActiveStream = false private(set) var isReplayConnection = false - // Foreground activation and view appearance can both request recovery for the - // same suspended stream. Share one recovery task so callers cannot duplicate - // status checks or transcript loads. Identity and generation fence late work - // from a replacement run. private var reconnectTask: ( id: UUID, streamID: String, @@ -218,9 +178,6 @@ final class ChatStreamCoordinator { task: Task )? private var reconnectTranscriptLoadTaskID: UUID? - // Bumped whenever the active run starts or finalizes. Captured before an async - // transcript load so a concurrent cancel/completion during the load can't be - // double-finalized (PR #266 review #2). private var runGeneration = 0 init( @@ -275,16 +232,10 @@ final class ChatStreamCoordinator { isTransportFinished } - /// Test seam for the clock-skew clamp: production callers always seed with - /// the current instant, which tests cannot advance. func seedActiveRunStartForTesting(_ startedAt: Date?, now: Date) { seedActiveRunStart(startedAt, now: now) } - /// `runStartedAt` is the run's real start when the caller knows it — the - /// server's `pending_started_at` from `/api/chat/start`, else the local send - /// time. Reconnects and replays pass nil: they rejoin the same stream, whose - /// start is already recorded. func start( streamID: String, replayAfterSeq: Int? = nil, @@ -366,10 +317,6 @@ final class ChatStreamCoordinator { return false } - // A same-stream `start()` (foreground reconnect / replay) bumps - // `runGeneration` without replacing the server run. Stream identity is - // the successor fence; generation would treat that restart as a new - // authority and drop the uncached optimistic row. guard activeStreamID == activeStreamIDBeforeLoad else { return false } @@ -379,10 +326,6 @@ final class ChatStreamCoordinator { return loadedActiveStreamID == activeStreamIDBeforeLoad } - /// `runStartedAt` is when the loaded session says its in-flight turn started - /// (`pending_started_at`, else the latest user message's timestamp). Adopting - /// a running stream counts from there instead of from this load, so returning - /// to a session never restarts its "Working for" counter. func reconcileSessionLoad( loadedActiveStreamID rawLoadedActiveStreamID: String?, preparation: ChatStreamLoadPreparation, @@ -469,10 +412,6 @@ final class ChatStreamCoordinator { await task.value } - /// The open chat calls this when the device's network path changes (#869). - /// A suspended stream retries at once through the single-flight reconnect, - /// so a flapping path joins one attempt. A live stream that was waiting - /// drops back to idle, and the stale-stream loop decides whether to probe. func networkPathDidChange(modelContext: ModelContext? = nil) async { if isConnectionSuspended { await reconnectIfNeeded(modelContext: modelContext) @@ -492,8 +431,6 @@ final class ChatStreamCoordinator { streamID: streamID, runGeneration: runGeneration ) else { return } - // Offline: end the attempt uncounted and stay suspended; the - // network's return starts a fresh one. guard networkAllowsStatusProbe() else { return } let runStartedAt = activeRunStartedAt @@ -522,12 +459,6 @@ final class ChatStreamCoordinator { if delegate?.streamCoordinatorStreamingAssistantMessageID == nil { delegate?.streamCoordinatorStreamingAssistantMessageID = delegate?.streamCoordinatorLatestAssistantMessageID() } - // Resume from the last event this process rendered (#599): a - // cursorless attach can replay the run from the start and - // duplicate text already on screen. A cold process with no - // snapshot asks the journal for the whole run so the loaded - // partial transcript fills in before `done`. A snapshot or an - // unparseable cursor keeps an ordinary connection. let replayAfterSeq: Int? if response.replayAvailable != true { replayAfterSeq = nil @@ -558,9 +489,6 @@ final class ChatStreamCoordinator { canFinalizeRunAfterLoad(streamID: streamID, capturedGeneration: runGeneration) else { return } - // #246: the server reports the run is over. Finalize it (and end - // the Live Activity) instead of re-arming and leaving it dangling - // on "running" when no assistant reply surfaced. finalizeInactiveStream(streamID: streamID, runStartedAt: runStartedAt) } return @@ -587,8 +515,6 @@ final class ChatStreamCoordinator { } let isTransientFailure = Self.isTransientReconnectFailure(error) - // The probe failed because the network went away: wait for it - // instead of spending the rest of the budget on an error (#869). if isTransientFailure, !isNetworkAvailable() { if reconnectTaskIsCurrent( reconnectTaskID: reconnectTaskID, @@ -621,8 +547,6 @@ final class ChatStreamCoordinator { } } - /// Transient tunnel/connectivity failures that are worth retrying inside the - /// reconnect budget. Auth, decoding, and ordinary HTTP errors surface once (#537). nonisolated static func isTransientReconnectFailure(_ error: Error) -> Bool { switch error { case APIError.network(let underlying): @@ -656,9 +580,6 @@ final class ChatStreamCoordinator { } } - /// Finishes the run from the server's transcript when the server says it - /// ended and its reply is saved; otherwise leaves the live SSE to finish it. - /// Used by the foreground refresh and by a steer that found the run ended. func refreshTranscriptIfCompleted( streamID expectedStreamID: String, modelContext: ModelContext? = nil @@ -673,16 +594,9 @@ final class ChatStreamCoordinator { guard response.active == false else { return } await delegate?.streamCoordinatorLoadMessages(modelContext: modelContext) - // Bail if a concurrent completion/cancel/new run finalized or replaced - // this run during the load (see canFinalizeRunAfterLoad). guard canFinalizeRunAfterLoad(streamID: expectedStreamID, capturedGeneration: generation) else { return } guard delegate?.streamCoordinatorLatestServerLoadHadAssistantResponseAfterLatestUser == true else { - // Foreground safety net: the live SSE is still connected and owns - // completion, so a status poll that briefly reports inactive must - // not finalize the run — keep waiting for the real `.done`. (This - // is why #246's finalize-on-reopen fix deliberately excludes this - // path; see finalizeInactiveStream.) activeStreamID = expectedStreamID isConnectionSuspended = false return @@ -690,8 +604,6 @@ final class ChatStreamCoordinator { completeResponseFromRefreshedTranscriptAndFinishStream(streamID: expectedStreamID) } catch { - // This is a foreground safety net. The primary SSE path owns visible - // stream errors; a failed status poll should not interrupt it. chatStreamCoordinatorLogger.warning( "Active stream status refresh failed category=\(APIError.privacySafeLogCategory(for: error), privacy: .public)" ) @@ -745,10 +657,6 @@ final class ChatStreamCoordinator { let transportElapsed = now.timeIntervalSince(lastTransportActivityDate ?? lastProgressDate) guard transportElapsed >= timing.transportFreshInterval else { - // #227: heartbeats prove the connection is alive during a - // semantically quiet window (model thinking / slow tool call), so - // stay idle and skip status polls. A genuinely silent transport - // still escalates below once past transportFreshInterval. setRecoveryStateIfChanged(.idle) return } @@ -800,12 +708,6 @@ final class ChatStreamCoordinator { } private func handle(_ event: SSEEvent) { - // Terminal-content fence (#288): once the response has completed, late - // content must never reach the transcript. The fence survives streamEnd - // (finishStream resets hasCompletedCurrentResponse but not the fence), - // closing the done → streamEnd → token ordering. Title and metering are - // session metadata and still pass; a settled completion is never - // re-ended by late error/cancel (#288 review). if isTerminalContentFenceActive { switch event { case .title(let payload): @@ -820,17 +722,10 @@ final class ChatStreamCoordinator { setLiveTokensPerSecondIfChanged(payload.displayableTokensPerSecond) return case .done: - // Duplicate done after completion — already finalized; ignore. return case .heartbeat, .ignored: break case .transportError, .cancelled, .error, .streamEnd: - // Settled completion wins: tear down exactly once without - // publishing a second Live Activity end or repeating delegate - // finish/drain/title-refresh side effects. transportError after - // done must still finish (snapshot cleanup, queued-slash drain, - // completed-title refresh) — it previously fell through to the - // pre-change handleTransportError path (PR #295 re-gate). finishStream() return case .token, .interimAssistant, .reasoning, .toolStarted, .toolCompleted, @@ -916,10 +811,6 @@ final class ChatStreamCoordinator { handleTransportError(message) case .heartbeat: delegate?.streamCoordinatorDidConfirmRecovery() - // #227: a heartbeat proves the transport is alive without carrying - // semantic progress — drop an already-shown "Checking stream" state - // immediately. Never demote .reconnecting; that chip is owned by - // the reconnect flow until real progress lands. if recoveryState == .checking { setRecoveryStateIfChanged(.idle) } @@ -929,8 +820,6 @@ final class ChatStreamCoordinator { } private func handleTransportError(_ message: String) { - // webui closes the socket right after `cancel` or `error`, and the SSE - // library reports that close; a finished run has nothing left to fail. guard !isTransportFinished else { return } setLiveTokensPerSecondIfChanged(nil) guard activeStreamID != nil, !hasCompletedCurrentResponse else { @@ -956,9 +845,6 @@ final class ChatStreamCoordinator { } } - /// Parks recovery in `.waitingForNetwork` and returns false while the - /// device is offline, so no status probe is sent (#869). Online, it lifts - /// an earlier wait so a failing probe can't leave that label behind. private func networkAllowsStatusProbe() -> Bool { guard isNetworkAvailable() else { setRecoveryStateIfChanged(.waitingForNetwork) @@ -992,9 +878,6 @@ final class ChatStreamCoordinator { if response.active == false { await delegate?.streamCoordinatorLoadMessages(modelContext: modelContext) - // Same generation/clobber guard as the reconnect and refresh paths; - // the extra `!isConnectionSuspended` keeps the reconnect path owning - // a stream that was suspended mid-load. (PR #266 review #3) guard canFinalizeRunAfterLoad(streamID: expectedStreamID, capturedGeneration: generation), !isConnectionSuspended else { return } @@ -1002,11 +885,6 @@ final class ChatStreamCoordinator { return } - // PR #238 review: recoveryState was set to .checking before this - // await. If it changed mid-flight (a heartbeat or real progress - // demoted it to .idle), the transport just proved itself alive — - // don't resurrect the chip or churn a live connection; the next - // recovery tick re-evaluates from scratch. guard recoveryState == .checking, forceReconnect else { return } reconnectStaleStream( @@ -1028,8 +906,6 @@ final class ChatStreamCoordinator { return } - // Same mid-flight demotion guard as the success path (PR #238 - // review): only a still-.checking state may escalate. guard recoveryState == .checking, forceReconnect, activeStreamID == expectedStreamID, @@ -1084,39 +960,16 @@ final class ChatStreamCoordinator { } private func completeResponseFromRefreshedTranscriptAndFinishStream(streamID completedStreamID: String?) { - // The owned transcript load may have reconciled activeStreamID to nil. completeCurrentResponse(needsTranscriptRefresh: false, completedStreamID: completedStreamID) delegate?.streamCoordinatorRemoveSnapshot(streamID: completedStreamID) finishStream() } - /// Whether `self` may still finalize the run captured before an awaited - /// transcript load. Returns false (bail) when a concurrent completion / cancel - /// / new run bumped the generation — finalizing would double-finalize — or when - /// a *different* run is now active — finalizing would clobber the newer stream. - /// A run reconciled to `nil` during the load still passes: it should be - /// finalized from the refreshed transcript so its Live Activity can't dangle on - /// "running" (#246). Shared by all three post-load finalize paths - /// (reconnect-after-suspend, foreground refresh, stale recovery) so they stay in - /// lockstep — recoverStaleStream previously used a stricter, hand-rolled guard. - /// (PR #266 review #3) private func canFinalizeRunAfterLoad(streamID: String, capturedGeneration: Int) -> Bool { guard runGeneration == capturedGeneration else { return false } return activeStreamID == nil || activeStreamID == streamID } - /// The server reports this stream is no longer active. Complete from the - /// just-refreshed transcript when an assistant reply surfaced, otherwise - /// finalize as failed. Either branch ends the Live Activity, so it can never - /// dangle on "running" after the run is over (#246). Shared by the two paths - /// with no live SSE behind them — reconnect-after-suspend and stale recovery. - /// The foreground transcript-refresh safety net deliberately keeps waiting - /// instead, because its live SSE still owns completion. - /// - /// `runStartedAt` is the run's start captured before the awaited transcript - /// load. A load that finds the stream gone clears the live run start, so a - /// failure is recorded against the captured one and the chat still alerts for - /// it, the way the Live Activity says "Response failed" (#862). private func finalizeInactiveStream(streamID: String?, runStartedAt: Date?) { if delegate?.streamCoordinatorLatestServerLoadHadAssistantResponseAfterLatestUser == true { completeResponseFromRefreshedTranscriptAndFinishStream(streamID: streamID) @@ -1156,24 +1009,12 @@ final class ChatStreamCoordinator { } } - /// Adopts a server-known start for the run that is now active, replacing the - /// local stamp `activeStreamID`'s observer laid down. Every seed a caller can - /// supply is stable across re-entry, so applying one on a same-stream - /// reattach sharpens the counter rather than restarting it; a nil seed leaves - /// the discovery stamp alone. A future-dated seed (clock skew between phone - /// and server) is clamped to `now` so the label never counts backwards, and - /// the earliest start known for this stream wins: a re-seed can only move the - /// start earlier, never forward onto a fresh `now`, which would restart - /// "Working for" on every reload of a session a skewed server is running. private func seedActiveRunStart(_ startedAt: Date?, now: Date = Date()) { guard activeStreamID != nil, let startedAt else { return } let clamped = min(startedAt, now) activeRunStartedAt = min(activeRunStartedAt ?? clamped, clamped) } - /// Records the run's span once. `completeCurrentResponse` already cleared - /// the run start for a normal completion, so a later teardown event (a - /// `streamEnd` or `cancelled` after `done`) cannot overwrite that ending. private func recordRunEndingIfRunning(_ ending: TranscriptTurnRunOutcome.Ending) { guard let activeRunStartedAt else { return } latestRunEnding = ChatRunEnding(startedAt: activeRunStartedAt, endedAt: Date(), ending: ending) @@ -1199,10 +1040,6 @@ final class ChatStreamCoordinator { await delegate?.streamCoordinatorLoadMessages(modelContext: modelContext) guard reconnectTranscriptLoadTaskID == reconnectTaskID else { return false } - // The transport-error path can begin recovery without persistence - // access. If a foreground caller supplied it while that nil-context - // load was in flight, repeat the shared load once so optimistic - // messages and the cache participate in reconciliation. if modelContext == nil, recoveryModelContext(for: reconnectTaskID) != nil { continue } @@ -1294,9 +1131,6 @@ final class ChatStreamCoordinator { delegate?.streamCoordinatorDidResetRecoveryState() } - /// Called right after `seedActiveRunStart`, so the widget's system elapsed - /// timer starts from the same instant as the in-app "Working for" label - /// rather than from the moment this process attached to the stream (#406). private func startLiveActivity(streamID: String) { guard let sessionID = delegate?.streamCoordinatorSessionID else { return } @@ -1309,9 +1143,6 @@ final class ChatStreamCoordinator { ) } - /// Restores `streamID`'s snapshot while a session load adopts it. Adopting a - /// different stream first drops the previous stream's resume cursor, so its - /// seq is never sent as `after_seq` for the new run (#599). private func restoreLoadedStreamSnapshot(streamID: String, preparation: ChatStreamLoadPreparation) { guard preparation.activeStreamIDBeforeLoad != streamID else { restoreSnapshotIfAvailable(streamID: streamID) diff --git a/HermesMobile/Features/Chat/ChatTactileButtonStyle.swift b/HermesMobile/Features/Chat/ChatTactileButtonStyle.swift index 0ad375226..59f6ccab2 100644 --- a/HermesMobile/Features/Chat/ChatTactileButtonStyle.swift +++ b/HermesMobile/Features/Chat/ChatTactileButtonStyle.swift @@ -294,7 +294,6 @@ private struct ChatMinimumHitTargetModifier: ViewModifier { let shape: HitShape func body(content: Content) -> some View { - // Expand the hit shape without making compact composer controls consume row space. content .padding(.horizontal, horizontalPadding) .padding(.vertical, verticalPadding) diff --git a/HermesMobile/Features/Chat/ChatTimelineAccessorySurface.swift b/HermesMobile/Features/Chat/ChatTimelineAccessorySurface.swift index 30837ddc8..04f457f8b 100644 --- a/HermesMobile/Features/Chat/ChatTimelineAccessorySurface.swift +++ b/HermesMobile/Features/Chat/ChatTimelineAccessorySurface.swift @@ -64,8 +64,6 @@ extension View { ) } - /// Shape-based entry point for accessories that are not a rounded rectangle, - /// such as the one-line run-status capsule. func chatTimelineAccessorySurface( fallbackMaterial: Material, in shape: some Shape diff --git a/HermesMobile/Features/Chat/ChatTranscriptSupportingViews.swift b/HermesMobile/Features/Chat/ChatTranscriptSupportingViews.swift index 16dcf61ec..d2551d074 100644 --- a/HermesMobile/Features/Chat/ChatTranscriptSupportingViews.swift +++ b/HermesMobile/Features/Chat/ChatTranscriptSupportingViews.swift @@ -4,15 +4,9 @@ import UIKit struct ChatScrollMetrics: Equatable { let distanceFromBottom: CGFloat let isUserInteracting: Bool - /// A scroll with no gesture carried the reader away from the bottom since - /// the last delivered report; see `ChatScrollPolicy.isScrollingAwayFromBottom`. let movedAwayFromBottom: Bool } -/// Reports the transcript's scroll geometry and the gesture events that drive -/// the follow latch (`ChatScrollPolicy.FollowEvent`). Metrics arrive on every -/// offset or size change; follow events arrive only when a drag begins and when -/// the gesture, including any momentum, has settled. struct ChatScrollObserver: UIViewRepresentable { let isStreaming: Bool let scrollPositionController: ChatScrollPositionController? @@ -110,23 +104,15 @@ struct ChatScrollObserver: UIViewRepresentable { var onFollowEvent: @MainActor (ChatScrollPolicy.FollowEvent) -> Void private weak var scrollView: UIScrollView? - /// The observer view itself: it backs the transcript content, so its - /// origin is the content's origin in the scroll view. private weak var contentView: UIView? private weak var observedPanGesture: UIPanGestureRecognizer? private var observations: [NSKeyValueObservation] = [] private var metricContext: MetricContext private var lastMetrics: ChatScrollMetrics? private var pendingMetrics: ChatScrollMetrics? - /// Geometry behind the last report the transcript received. Reports - /// coalesce per run loop, so the away-from-bottom check compares - /// delivered states, not every intermediate KVO tick. private var deliveredGeometry: ChatScrollPolicy.ScrollGeometry? private var pendingGeometry: ChatScrollPolicy.ScrollGeometry? private var hasScheduledMetricDelivery = false - /// True from the first drag movement until the gesture, including any - /// momentum, comes to rest. Mirrors the "user scroll session" the follow - /// latch reasons about. private var isUserScrollSessionActive = false private var settleWorkItem: DispatchWorkItem? var scrollPositionController: ChatScrollPositionController? { @@ -205,8 +191,6 @@ struct ChatScrollObserver: UIViewRepresentable { scrollView = nil } - // MARK: Follow latch events - @objc private func handlePanGesture(_ gesture: UIPanGestureRecognizer) { switch gesture.state { case .began: @@ -215,13 +199,9 @@ struct ChatScrollObserver: UIViewRepresentable { onFollowEvent(.userScrollBegin) case .ended, .cancelled, .failed: guard isUserScrollSessionActive, let scrollView else { return } - // Remember where the finger lifted: streaming growth during the - // momentum-detection window must not turn a release at the live - // edge into an opt-out from follow. let releaseIsAtBottom = isAtBottom(scrollView) scheduleSettle(after: ChatScrollPolicy.dragSettleDelay) { [weak self] in guard let self, let scrollView = self.scrollView else { return } - // Momentum announced itself; its ticks now own the session. if scrollView.isDecelerating { return } self.finishUserScrollSession(isAtBottom: releaseIsAtBottom) } @@ -230,8 +210,6 @@ struct ChatScrollObserver: UIViewRepresentable { } } - /// Each momentum tick pushes the settle check out; the check that - /// survives runs once deceleration has stopped moving the content. private func trackMomentum(_ scrollView: UIScrollView) { guard isUserScrollSessionActive, scrollView.isDecelerating else { return } scheduleSettle(after: ChatScrollPolicy.momentumSettleDelay) { [weak self] in @@ -241,8 +219,6 @@ struct ChatScrollObserver: UIViewRepresentable { private func finishUserScrollSessionIfSettled() { guard isUserScrollSessionActive, let scrollView else { return } - // A finger back on the glass either becomes a new drag (pan .began) - // or lifts without one (pan .failed); both paths re-enter above. if scrollView.isDragging || scrollView.isTracking { return } if scrollView.isDecelerating { scheduleSettle(after: ChatScrollPolicy.momentumSettleDelay) { [weak self] in @@ -306,8 +282,6 @@ struct ChatScrollObserver: UIViewRepresentable { guard let geometry = geometry(of: scrollView) else { return } let isUserInteracting = scrollView.isDragging || scrollView.isTracking || scrollView.isDecelerating - // While a disclosure pin holds the offset, a toggled row growing - // below the reader increases the distance without anyone scrolling. let isPinned = scrollPositionController?.isHoldingPosition == true let metrics = ChatScrollMetrics( distanceFromBottom: geometry.distanceFromBottom, @@ -376,33 +350,17 @@ struct ChatScrollObserver: UIViewRepresentable { } } -/// What one open chat keeps when a size-class change rebuilds its screen (#1528). An iPad window -/// crossing compact and regular width, or an iPhone Duo folding, swaps the navigation stack for -/// the split view, and SwiftUI makes a new `ChatView` in the other branch. Whoever says -/// which chat is open holds one of these for as long as it is, and hands it to the `ChatView` of -/// either branch. The new view takes the old one's model, with its loaded history, its stream and -/// its follow latch, and the reader's place in the transcript. -/// -/// SwiftUI gives no order to the swap: the new view can appear before or after the old one leaves, -/// and a split view can build an extra `ChatView` that appears and leaves while another stays on -/// screen. So this counts the views on screen rather than naming one owner. @MainActor final class ChatContinuity: Equatable { - /// The model of the view on screen, for its successor. Set as a view appears, since SwiftUI - /// can init a `ChatView` it never shows. private(set) var model: ChatViewModel? - /// The transcript load finished, so a successor must not load again: that would replace the - /// older pages the reader loaded with the newest one. var didLoadMessages = false private var viewsOnScreen: [(id: UUID, returnsWaitingSend: (String, HermesWaitingSend.Return) -> Void)] = [] private var transcriptsOnScreen: [ChatScrollPositionController] = [] - /// The transcript that left with none on screen, whose place the next one takes. private var lastTranscript: ChatScrollPositionController? nonisolated init() {} nonisolated static func == (lhs: ChatContinuity, rhs: ChatContinuity) -> Bool { lhs === rhs } - /// `returnsWaitingSend` puts a waiting send that came back into this view's composer. func viewAppeared(_ view: UUID, model: ChatViewModel, returnsWaitingSend: @escaping (String, HermesWaitingSend.Return) -> Void) { viewsOnScreen.removeAll { $0.id == view } @@ -411,17 +369,12 @@ struct ChatScrollObserver: UIViewRepresentable { model.onWaitingSendReturned = returnsWaitingSend } - /// True once no view of this chat is on screen, when the chat really left and its model stops - /// its work. The next view to appear starts it again, as when a pushed screen pops. func viewDisappeared(_ view: UUID) -> Bool { viewsOnScreen.removeAll { $0.id == view } - // An extra view that appeared last took the composer's place; the one staying takes it back. if let staying = viewsOnScreen.last { model?.onWaitingSendReturned = staying.returnsWaitingSend } return viewsOnScreen.isEmpty } - /// A transcript of this chat appeared. One that replaces another keeps its reader's place, - /// unless the reader is following: a new transcript already opens at the live edge. func transcriptAppeared(_ controller: ChatScrollPositionController, isFollowing: Bool) { let previous = transcriptsOnScreen.last ?? lastTranscript if let previous, previous !== controller, !isFollowing, let place = previous.readingPlace { @@ -437,63 +390,22 @@ struct ChatScrollObserver: UIViewRepresentable { } } -/// Keeps the reader's exact vertical position through a layout change SwiftUI -/// would otherwise move them for. Three cases: -/// -/// - **Prepend.** Older rows are inserted above the reader; the offset shifts -/// by the net content-height growth. `ScrollViewProxy.scrollTo(_:anchor:)` -/// can only align a row to a coarse anchor, which loses the gap formerly -/// occupied by the Load Older button and causes a visible hop. -/// - **Hold.** A disclosure toggle grows or shrinks a row below the reader; -/// the offset must not move at all. SwiftUI can re-apply a default anchor on -/// that size change (seen at the exact top after a status-bar scroll); that -/// shows up as an offset change in the same run-loop turn as a size change -/// and is put back. Any other offset change is someone scrolling on purpose -/// (VoiceOver, a hardware keyboard, a follow scroll) and releases the hold. -/// - **Reflow.** The column width or text size changed, so every row rewraps -/// and the raw offset lands on another passage (#1414). Rows, and the plan -/// and compression card between them, report their frames -/// (`rowFrameChanged`) under the layout they were measured in; the -/// first frame of a new layout captures the reader's place from the old -/// layout's frames, and the anchor row's new frames put it back. A reader -/// at the top stays at the top, through any change in the bars' insets, and -/// undoes SwiftUI like a hold, with its resync (#1528). A reader following -/// the live edge is left alone, as is any prepend or hold already in flight. -/// Otherwise ends like a hold, without its resync. -/// - **Handoff.** A size-class change rebuilt the transcript (`ChatContinuity`). -/// The new controller keeps the old one's reading place as a reflow does, and -/// undoes the bottom anchor SwiftUI opens a new transcript at. -/// -/// The controller snapshots the UIKit scroll geometry, then corrects during -/// the following layout passes for a bounded window. Corrections are -/// deliberately non-animated: they preserve an existing position rather than -/// navigating to a new one. Any user movement releases the hold. @MainActor final class ChatScrollPositionController { private enum Mode { - /// Offset follows the net content-height growth. case prepend - /// Offset stays put; SwiftUI-driven offset changes are reverted. case hold - /// Offset keeps `reflowPlace` at the reading line; otherwise like `hold`. case reflow } - /// What a row's wrapping depends on: the capped column width and the text - /// size. A change to either is a reflow. struct Layout: Equatable { let contentWidth: CGFloat let dynamicTypeSize: DynamicTypeSize } private weak var scrollView: UIScrollView? - /// The transcript content's view, for converting row frames (measured in the - /// content's coordinate space) to UIKit scroll content coordinates. private weak var contentView: UIView? private var mode = Mode.prepend - /// Set by `capture()`, cleared by anything that replaces the baseline, so - /// a hold armed while the older-message request is in flight cannot be - /// mistaken for the prepend capture when the request lands. private var hasPrependCapture = false private var baselineContentHeight: CGFloat? private var baselineOffsetY: CGFloat? @@ -502,33 +414,16 @@ final class ChatScrollPositionController { private var completionTask: Task? private var quietReleaseTask: Task? private var isApplyingCompensation = false - /// Set when a hold had to undo an offset SwiftUI applied. SwiftUI's own - /// notion of the offset is then stale, and lazy rows it believes are - /// off-screen stop hit-testing until a scroll it performed itself resyncs - /// it; `resyncAfterHold` is that scroll. private var didRevertSwiftUIOffset = false private var resyncAfterHold: (() -> Void)? - /// True from a content-size change until the end of the same run-loop - /// turn: an offset change in that window is SwiftUI re-anchoring, not a - /// scroll. `lastObservedContentHeight` covers the offset change UIKit - /// makes from inside the content-size setter, before that callback runs. private var contentSizeChangedThisTurn = false private var lastObservedContentHeight: CGFloat? - /// Row frames in the content's coordinate space, under `rowFramesLayout`. - /// Plain storage, written only when a row's frame changes; never per scroll. private var rowFrames: [String: CGRect] = [:] private var rowFramesLayout: Layout? private var reflowPlace: ChatScrollPolicy.ReadingPlace? - /// Puts back an offset change riding on a size change in the same turn: - /// SwiftUI re-applying a default anchor. Off for a row's reflow, where no - /// size-change anchor applies and that change is the reader's. private var undoesSwiftUIAnchors = false - /// A place handed over before this controller had a scroll view. private var pendingPlace: ChatScrollPolicy.ReadingPlace? - /// Where the reader was when last asked, for a successor's handoff after the scroll view or - /// the rows left, in whichever order they go. An anchor survives the rows moving under it. private var lastPlace: ChatScrollPolicy.ReadingPlace? - /// A SwiftUI scroll to the transcript's top: how keeping the top resyncs. var resyncToTop: (() -> Void)? var isHoldingPosition: Bool { @@ -546,11 +441,6 @@ final class ChatScrollPositionController { } } - /// A row's frame changed; `id` is its `renderID`, or a stable key for a - /// block drawn between rows (a plan, a compression card). The first frame - /// under a new `layout` arms a reflow from the frames still stored for the - /// old one; a reflow already running keeps its anchor through further - /// layouts (a second rotation). func rowFrameChanged(id: String, frame: CGRect, layout: Layout, isFollowing: Bool) { if let previous = rowFramesLayout, previous != layout { if mode == .reflow, reflowPlace != nil { @@ -567,7 +457,6 @@ final class ChatScrollPositionController { } } - /// A row left the transcript. func forgetRow(id: String) { rowFrames[id] = nil } @@ -585,8 +474,6 @@ final class ChatScrollPositionController { keep(place, in: scrollView, undoesSwiftUIAnchors: place == .top) } - /// The reader's place in `scrollView`, from the frames of the layout it was - /// last measured in. Nil with no rows to place it among. private func place(in scrollView: UIScrollView) -> ChatScrollPolicy.ReadingPlace? { guard !rowFrames.isEmpty else { return nil } let topInset = scrollView.adjustedContentInset.top @@ -611,20 +498,15 @@ final class ChatScrollPositionController { scheduleQuietRelease() } - /// Where the reader is now, or was when last known. A reflow running keeps the place it took - /// before the rows moved. var readingPlace: ChatScrollPolicy.ReadingPlace? { reflowPlace ?? scrollView.flatMap(place(in:)) ?? lastPlace } - /// The reader's gesture came to rest. Once per gesture, never per scroll. func readerSettled() { lastPlace = readingPlace } - /// Keeps the reader at a place the previous transcript of this chat reported. func restore(_ place: ChatScrollPolicy.ReadingPlace) { - // A transcript that leaves before it has a scroll view still passes this on. lastPlace = place guard let scrollView else { pendingPlace = place @@ -654,11 +536,6 @@ final class ChatScrollPositionController { return true } - /// Arms compensation before SwiftUI performs the prepend layout. Returns - /// false when the user moved the scroll view while the request was in - /// flight, or a disclosure hold replaced the capture meanwhile, leaving the - /// caller free to use its coarse fallback instead of overriding movement it - /// does not own. @discardableResult func restoreAfterPrepend() -> Bool { guard hasPrependCapture, @@ -674,18 +551,10 @@ final class ChatScrollPositionController { return false } - // Text and attachment layout can settle over several run-loop passes. - // Keep applying the same net-height correction for a short bounded - // window, then release ownership back to normal scrolling. beginPreservation(mode: .prepend, scrollView: scrollView, window: 1) return true } - /// Pins the current offset: a disclosure toggle is about to change a row's - /// height below the reader. The pin releases once the content size has been - /// quiet for `ChatScrollPolicy.disclosureHoldQuietPeriod`, or after - /// `disclosureHoldMaximum` at the latest. No-op while the user is moving the - /// transcript; their gesture owns the position. func holdPosition(resync: @escaping () -> Void) { cancelPreservation() guard let scrollView, @@ -703,9 +572,6 @@ final class ChatScrollPositionController { scheduleQuietRelease() } - /// Hold or reflow ran to completion (quiet or capped): let go, then resync - /// SwiftUI if a hold had to fight it. A hold ended by a gesture or a deliberate - /// scroll needs no resync; that scroll does it. private func finishHold() { applyCompensation() let minimumOffsetY = scrollView.map { -$0.adjustedContentInset.top } @@ -718,10 +584,6 @@ final class ChatScrollPositionController { resync?() } - /// The resync is a SwiftUI scroll to the transcript's top, so it only - /// describes the held position when that position is the top. Anchor - /// re-application has only been seen there (after a status-bar scroll); - /// anywhere else, leave SwiftUI alone rather than hop. nonisolated static func shouldResync( didRevertSwiftUIOffset: Bool, heldOffsetY: CGFloat?, @@ -731,16 +593,11 @@ final class ChatScrollPositionController { return heldOffsetY <= minimumOffsetY + 0.5 } - /// Ends a disclosure pin or reflow early: the transcript is about to scroll - /// on purpose (follow, scroll-to-bottom, keyboard). A prepend preservation - /// is left alone. func releaseHold() { guard mode != .prepend else { return } cancelPreservation() } - /// Ends a fling still coasting, so a deliberate jump (the scroll-to-bottom - /// arrow) is not overridden by leftover momentum. func stopMomentum() { scrollView?.stopScrollingAndZooming() } @@ -817,7 +674,6 @@ final class ChatScrollPositionController { } private func handleContentSizeChange(_ scrollView: UIScrollView) { - // A callback that outlived a detach must not touch the new attachment. guard scrollView === self.scrollView else { return } applyCompensation() @@ -852,10 +708,6 @@ final class ChatScrollPositionController { } } - /// User movement releases the preservation. In hold and reflow modes an - /// offset change UIKit makes inside the content-size setter is put back, and - /// with `undoesSwiftUIAnchors` so is one riding on a size change in the same - /// turn. Any other offset change is a deliberate scroll and releases it. private func handleOffsetChange(_ scrollView: UIScrollView) { guard !isApplyingCompensation, scrollView === self.scrollView else { return } @@ -925,15 +777,6 @@ final class ChatScrollPositionController { } } -/// Pins a subtree to left-to-right regardless of the surrounding chat layout -/// direction, so code, math, data tables, tool-call bodies, file paths, and -/// images never render mirrored inside an RTL message (issue #259). A fixed -/// `layoutDirection` also isolates the subtree's bidi resolution from the parent -/// paragraph direction. -/// -/// An RTL parent still places this view by its own leading edge, on the right. -/// Don't remap the alignment guides for it: flipping them here lines siblings up -/// edge to edge, which stretches the column off-screen (#1068). private struct ForcedLeftToRightModifier: ViewModifier { @Environment(\.layoutDirection) private var parentDirection let isForced: Bool @@ -944,19 +787,10 @@ private struct ForcedLeftToRightModifier: ViewModifier { } extension View { - /// Lays the view out left to right inside an RTL transcript, keeping its - /// leading edge where the transcript's is. `false` leaves the direction alone. func forcedLeftToRight(_ isForced: Bool = true) -> some View { modifier(ForcedLeftToRightModifier(isForced: isForced)) } - /// Calls `admit` with `id` the first time this media leaf is on screen, so opening - /// a chat loads only the media the user can see: the transcript is an eager stack, - /// so every row mounts at open. The leaf keeps the admitted id in its own `@State` - /// and keys its load `.task` by it. - /// - /// Admission latches per `id`. Scrolling away never withdraws it, so a load in - /// flight keeps running; a new `id` waits until the leaf is on screen again. func loadsOnceVisible(id: ID, admit: @escaping (ID) -> Void) -> some View { modifier(LoadsOnceVisibleModifier(id: id, admit: admit)) } @@ -981,9 +815,6 @@ private struct LoadsOnceVisibleModifier: ViewModifier { } } - /// A settled reply's selection host is a separate SwiftUI graph that can't see the - /// transcript's scroll view, so its media follows the whole reply's visibility. - /// Anywhere else without a scroll view, such as a preview sheet, counts as visible. private var isVisible: Bool { switch placement { case .unmeasured: false @@ -1005,9 +836,6 @@ struct ChatVerticalScrollAxisGuard: UIViewRepresentable { } func updateUIView(_ uiView: ChatVerticalScrollAxisGuardView, context: Context) { - // The transcript flips wholesale under the chat RTL toggle (#259); read - // the resolved direction here so the guard pins the horizontal offset to - // the layout-direction-aware leading edge (folds in #139). uiView.isRightToLeft = context.environment.layoutDirection == .rightToLeft uiView.attachToNearestScrollViewIfNeeded() } @@ -1022,8 +850,6 @@ final class ChatVerticalScrollAxisGuardView: UIView { private weak var guardedScrollView: UIScrollView? private var observations: [NSKeyValueObservation] = [] - /// Whether the guarded transcript is laid out right-to-left (#259). Drives - /// which physical edge the horizontal offset rests against; re-clamps on change. var isRightToLeft = false { didSet { guard oldValue != isRightToLeft else { return } @@ -1078,9 +904,6 @@ final class ChatVerticalScrollAxisGuardView: UIView { scrollView.observe(\.bounds, options: [.new]) { [weak self] _, _ in Self.clampObservedHorizontalOffset(for: self) }, - // Under RTL the pinned rest offset depends on contentSize.width, so a - // width change (a wide table/streaming code block loading) must re-clamp - // immediately instead of waiting for the next offset/bounds change (#259). scrollView.observe(\.contentSize, options: [.new]) { [weak self] _, _ in Self.clampObservedHorizontalOffset(for: self) } @@ -1115,16 +938,6 @@ final class ChatVerticalScrollAxisGuardView: UIView { scrollView.setContentOffset(offset, animated: false) } - /// The horizontal content offset the transcript should rest at, pinned to the - /// layout-direction-aware *leading* edge so the vertical-only transcript never - /// drifts sideways (#130) under either direction (#139/#259). - /// - /// LTR leading is the physical left, so it rests at `-left inset` exactly as - /// before — this branch is byte-for-byte the prior behavior. RTL leading is - /// the physical right, so it rests at the content's trailing edge - /// (`contentSize.width + right inset - viewport width`), clamped to never fall - /// below the LTR minimum. When the transcript has no horizontal overflow and - /// no horizontal inset — its normal case — both branches resolve to `0`. nonisolated static func pinnedHorizontalOffsetX( isRightToLeft: Bool, adjustedInset: UIEdgeInsets, @@ -1154,11 +967,6 @@ final class ChatVerticalScrollAxisGuardView: UIView { } } -/// Transcript tail row for the active run: three static dots and a -/// "Working for" counter that ticks once a second from the run's start date, -/// reading "Compacting context" while the host compacts (#1734). The -/// `TimelineView` scopes each tick to this row, so message rows above it are -/// not re-evaluated. struct ChatWorkingRowView: View { let startedAt: Date let isCompacting: Bool @@ -1193,10 +1001,6 @@ struct ChatWorkingRowView: View { } } -/// Transcript chip shown while the active stream is being checked, -/// reconnected, or waiting for the network. It spins while work is under way, -/// or shows a static dot under Reduce Motion. Waiting for the network always -/// shows the dot: nothing happens until the network returns. struct StreamRecoveryStatusView: View { let state: ActiveStreamRecoveryState @@ -1397,10 +1201,6 @@ struct ChatOfflineCacheBanner: View { } } -/// Notices pinned above the composer during a run, such as the goal-set -/// confirmation. Each card stops at two lines so a long goal never hides the -/// live transcript (#772); VoiceOver reads every notice in full, and the run's -/// end flushes them whole into the transcript. struct PinnedLocalNoticeStack: View { let notices: [String] @@ -1434,8 +1234,6 @@ struct PinnedLocalNoticeStack: View { .accessibilityLabel(notices.map(Self.plainText).joined(separator: "\n")) } - /// A notice without the code fences a host command's output comes in (#1036): the card - /// is plain text, and the transcript renders the fences once the run ends. static func plainText(_ notice: String) -> String { notice.split(separator: "\n", omittingEmptySubsequences: false) .filter { !$0.hasPrefix("```") } @@ -1443,14 +1241,8 @@ struct PinnedLocalNoticeStack: View { } } -/// The newest of the host's notices on a Hermes session (#1746), above the composer like -/// `ShortcutTextNotice`: a level symbol and tint, the host's text as sent with its links tappable, -/// and a close button. A notice with `detail` shows two lines and the full `detail` on a tap; one -/// without shows up to six lines, since nothing else would reveal the rest. VoiceOver reads -/// the level, the whole text, and how many more notices wait behind it. struct HostNoticeRow: View { let notice: HermesHostNotices.Notice - /// How many notices wait behind this one. let waitingCount: Int let dismiss: () -> Void @State private var showsDetail = false @@ -1499,9 +1291,6 @@ struct HostNoticeRow: View { let text = Text(notice.linkedText) .font(AppFont.footnote()) .foregroundStyle(.appPrimary) - // Two lines when a tap opens the full `detail`; otherwise the text is all there is, so - // it gets room for a host warning's hint, bounded so a long one never pushes the - // composer off screen. .lineLimit(notice.detail == nil ? 6 : 2) .fixedSize(horizontal: false, vertical: true) if notice.detail != nil { @@ -1543,10 +1332,6 @@ struct HostNoticeRow: View { } } -/// Characters that can hide or reorder what a prompt says to the agent without showing in the -/// composer (#1402): bidi embeddings, overrides and isolates, zero-width space, word joiner, -/// byte-order mark and Unicode tags. Joiners and marks text needs to read right (emoji ZWJ, -/// ZWNJ, LRM/RLM) are not among them. enum HiddenPromptCharacters { static func isHidden(_ scalar: Unicode.Scalar) -> Bool { switch scalar.value { @@ -1559,7 +1344,6 @@ enum HiddenPromptCharacters { text.unicodeScalars.contains(where: isHidden) } - /// `text` without them, every other character as it was. static func removing(from text: String) -> String { var kept = String.UnicodeScalarView() kept.append(contentsOf: text.unicodeScalars.lazy.filter { !isHidden($0) }) @@ -1568,7 +1352,6 @@ enum HiddenPromptCharacters { } extension ImportedTextOrigin { - /// The title of the alert for a queued text that can't open where it was bound. var cantOpenTitle: Text { switch self { case .shortcut: Text("Shortcut Can’t Open") @@ -1577,20 +1360,12 @@ extension ImportedTextOrigin { } } -/// Another queued text waiting behind the one a chat shows (#1402): Open Next opens it in that -/// chat's place, Discard deletes it unopened. struct WaitingShortcutText { let openNext: () -> Void let discard: () -> Void } -/// The composer's note that its text came from Shortcuts (#1402) or Troubleshoot with Hermes -/// (#1476), above it until the user dismisses it or sends. Hidden characters make it a warning -/// with Remove Hidden Characters; after a removal it offers Undo until the next edit. While another -/// queued text waits, it offers Open Next and Discard, which stay after the note itself is -/// dismissed or sent. struct ShortcutTextNotice: View { - /// Where the composer's added text came from; nil once its note is dismissed or sent. let origin: ImportedTextOrigin? let hasHiddenCharacters: Bool let canUndoRemoval: Bool diff --git a/HermesMobile/Features/Chat/ChatTranscriptView.swift b/HermesMobile/Features/Chat/ChatTranscriptView.swift index edae1d56b..dc479a22e 100644 --- a/HermesMobile/Features/Chat/ChatTranscriptView.swift +++ b/HermesMobile/Features/Chat/ChatTranscriptView.swift @@ -1,20 +1,13 @@ import SwiftUI import UIKit -/// The readable column for chat screens (Sessions chat, Bot Chat, Bot rooms). -/// A phone fills it edge to edge less its padding; iPad and iPhone landscape -/// stop at `maximum` and centre it, so lines stay short enough to read. The -/// composer caps at the same column so their edges line up. enum ChatReadingWidth { static let maximum: CGFloat = 768 - /// Width of the transcript column inside `horizontalPadding` on each side. static func contentWidth(viewportWidth: CGFloat, horizontalPadding: CGFloat) -> CGFloat { min(max(0, viewportWidth - 2 * horizontalPadding), maximum) } - /// `maxWidth` for a view that carries `horizontalPadding` on each side of - /// its own, so what sits inside that padding lines up with the column. static func maximumWidth(horizontalPadding: CGFloat) -> CGFloat { maximum + 2 * horizontalPadding } @@ -24,54 +17,38 @@ struct ChatTranscriptView: View { @Environment(\.accessibilityReduceMotion) private var reduceMotion @Environment(\.dynamicTypeSize) private var dynamicTypeSize @State private var scrollPositionController = ChatScrollPositionController() - /// The stream recovery chip, shown 400 ms after recovery starts and held - /// at least 400 ms, so quick recoveries don't flash (#1373). @State private var recoveryChip = DelayedStatusDriver() let isLoading: Bool let errorMessage: String? - /// False hides the error's Try Again, for a failure retrying can't fix. var errorMayRetry = true - /// The host's own words for `errorMessage`, behind a disclosure under it (#1611). var errorHostReason: String? - /// Opens Serve Every Profile when the error is a Profile the Webapp doesn't serve (#1611). var onServeEveryProfile: (() -> Void)? let messages: [ChatMessage] let displayedTranscriptMessages: [TranscriptMessage] let compressionReferenceCard: CompressionReferenceCard? - /// Reasoning cards by anchor message ID; nil holds the unanchored cards. let reasoningGroupsByAnchorID: [String?: [ReasoningGroup]] let completedToolCallGroupsForAnchor: (String?) -> [ToolCallGroup] let liveReasoningText: String let reasoningAnchorMessageID: String? let liveToolCalls: [ToolCall] - /// True while a reattached stream replays; live tool rows draw in place. let isReplayingLiveToolCalls: Bool let toolCallAnchorMessageID: String? let streamingAssistantMessageID: String? let liveTokensPerSecond: Double? let activeStreamRecoveryState: ActiveStreamRecoveryState - /// The pending clarification's id. The card itself is pinned above the - /// composer by `ChatView`; the transcript only follows its arrival. let clarificationPromptID: String? let hidesRunStatusAccessibility: Bool let showsThinkingAndToolCards: Bool - /// Start date for the "Working for" tail row; nil hides the row. let workingRowStartedAt: Date? - /// The host is compacting context: the tail row says so (#1734). let isCompacting: Bool - /// The note a Hermes session's withdrawn request leaves at the transcript's end (#1011). let requestWithdrawal: BotRequestWithdrawal? let showsScrollToBottomButton: Bool let shouldFollowLatestMessage: Bool - /// True while a disclosure toggle animates; suspends the bottom size-change - /// anchor and follow-driven scrolls so the tapped row stays stationary. let isDisclosureSettling: Bool let latestTranscriptMessageRole: String? let isScrolledNearBottom: Bool let activeStreamID: String? - /// Reads the stream's coalesced scroll trigger. Only `StreamingFollowTrigger` - /// calls it, so a bump re-runs that leaf rather than this view and its owner. let streamingScrollTrigger: () -> Int let transcriptRelayoutScrollToken: Int let completedResponseRenderID: String? @@ -88,7 +65,6 @@ struct ChatTranscriptView: View { let isEditingMessage: Bool let isForkingMessage: Bool let loadAttachmentImage: (String) async -> Data? - /// Where attachment rows get their inline audio; nil shows audio as file cells. let attachmentAudio: AttachmentAudioSource? let loadTranscriptMediaImage: (TranscriptMediaReference) async -> Data? let loadTranscriptMediaData: (TranscriptMediaReference) async -> Data? @@ -100,9 +76,7 @@ struct ChatTranscriptView: View { let onUpdateScrollMetrics: (ChatScrollMetrics) -> Void let onFollowEvent: (ChatScrollPolicy.FollowEvent) -> Void let onDisclosureToggle: () -> Void - /// Settled-turn folds derived by the owner; `.none` when folding is off. let turnFolds: TranscriptTurnFolds - /// Rows that close a settled turn and so carry the time + copy row. let terminalReplyRenderIDs: Set let expandedTurnKeys: Set let onToggleTurnFold: (String) -> Void @@ -118,51 +92,29 @@ struct ChatTranscriptView: View { let onEdit: (MessageActionContext) -> Void let onFork: (MessageActionContext) -> Void let onCopy: (MessageActionContext) -> Void - /// Non-nil shows the inline "Commit & Push" button under the latest assistant turn - /// (issue #315, Slice C, surface B). Nil hides it (non-git chats, no changes, etc.). var inlineCommitContext: ChatInlineCommitContext? = nil var onInlineCommit: () -> Void = {} - /// Non-nil shows the turn-end "File changes" recap card under the latest assistant turn - /// (issue #316, Slice D, surface B). Nil hides it (non-git chats, no changes, streaming). var turnChangesSummary: TurnFileChangeSummary? = nil var onOpenTurnDiff: () -> Void = {} var onOpenTurnFileDiff: (GitFile) -> Void = { _ in } - /// Non-nil draws the "Forked from" row above everything else (#873). var forkOrigin: ForkOrigin? = nil var onOpenForkParent: () -> Void = {} - /// A Hermes chat's settled plan (#1139), drawn right after the row - /// `settledPlanAfterRenderID` names: the prompt that opens the plan's turn. var settledPlan: HermesPlan? = nil var settledPlanAfterRenderID: String? = nil - /// How a Hermes chat's last turn ended (#1139), under that turn. var turnOutcome: HermesTurnOutcomeRow? = nil - /// A Bot Chat's bot is using, or just used, its screen (#1632), under its live reply. var screenCard: BotScreenCard? = nil - /// A Hermes chat's queued prompts (`ChatViewModel.queuedPromptMessages`, #1379, #1602), drawn - /// last in the host's order as pending bubbles whose only action is `onCopyQueuedPrompt`. var queuedPrompts: [ChatMessage] = [] - /// A turn a canonical host lost across its restart (`ChatViewModel.lostTurn`, #1602), drawn - /// ahead of the queued prompts it holds, with `onDiscardLostTurn`. var lostTurn: ChatLostTurn? = nil var onDiscardLostTurn: () -> Void = {} - /// A Hermes scheduled task's run (#1413), whose prompt rows show as `CronRunPromptCard`s. var isCronRun = false var onCopyQueuedPrompt: (String) -> Void = { _ in } - /// A Hermes chat's Send waiting for the reconnect (`ChatViewModel.waitingSendMessage`, #1407), - /// drawn last as a pending bubble whose only action is `onCancelWaitingSend`. var waitingSend: ChatMessage? = nil var onCancelWaitingSend: () -> Void = {} - /// Carries the reader's place from a transcript a size-class change replaced (#1528). var continuity: ChatContinuity? = nil - /// The session's live workers, nil on the offline cache's copy. The preview observes roster - /// changes itself, so this view only redraws when the count does. var delegatedWork: HermesDelegatedWork? = nil var onOpenDelegatedWork: () -> Void = {} - /// What stands in for a transcript with no rows. Nil draws the transcript when a Hermes - /// turn's outcome, a queued prompt, a waiting send or live workers still need to show before - /// rows were saved (#1139, #1379, #1407). enum Placeholder: Equatable { case loading case loadFailed(String) @@ -211,23 +163,18 @@ struct ChatTranscriptView: View { } } case .startPrompt?: - // An overlay takes no layout: above a keyboard on a short display (iPhone Duo), the - // prompt's height would stretch the screen and push the composer behind the keyboard. Color.clear.overlay { ContentUnavailableView { Image(systemName: "bubble.left.and.bubble.right") } description: { Text("Send a message to start the conversation.") } - // Centered above the composer, whose new-chat row would otherwise cover it. .padding(.bottom, transcriptBottomInsetHeight) } .contentShape(Rectangle()) .onTapGesture { onDismissKeyboard() } - // A fork can be empty (upstream allows `keep_count: 0`, and an edit of - // the first message truncates to nothing); it still links to its parent. .overlay(alignment: .top) { if let forkOrigin { ForkOriginRowView(origin: forkOrigin, onOpen: onOpenForkParent) @@ -311,12 +258,8 @@ struct ChatTranscriptView: View { } .task(id: completedResponseRenderID) { guard let renderID = completedResponseRenderID else { return } - // Let hydration's layout/pin pass settle before moving the - // viewport. A new run or reader action cancels this task. await Task.yield() guard !Task.isCancelled else { return } - // No animation or accessibility-focus move: only the viewport - // changes, and Reduce Motion is respected automatically. releasingHold { proxy.scrollTo(renderID, anchor: .top) } } .onChange(of: messages.count) { @@ -329,11 +272,6 @@ struct ChatTranscriptView: View { } } .onChange(of: transcriptRelayoutScrollToken) { - // The transcript just changed height without gaining a message — - // the server render replacing the cache-first one (#289), or sent - // references becoming chips (#388). A reader at the live edge is - // put back there (no animation); a reader up in history keeps the - // offset they were reading at, the way a disclosure toggle does. guard isFollowingLatestContent else { pinReader(proxy: proxy) return @@ -341,16 +279,12 @@ struct ChatTranscriptView: View { releasingHold { onScrollToLatestContent(proxy, false) } } .onChange(of: queuedPrompts.map(\.content) + [lostTurn.map { _ in "lost" }, waitingSend?.content]) { - // A pending bubble came, grew with a merged prompt, or went. followLiveEndChange(proxy: proxy) } .onChange(of: delegatedWork?.activeCount) { - // The worker preview came, gained or lost a row, or went. followLiveEndChange(proxy: proxy) } .onChange(of: clarificationPromptID) { - // The bar above the composer just grew the bottom inset; keep - // the latest content above it for a reader who was following. guard clarificationPromptID != nil, isFollowingLatestContent else { return } releasingHold { onScrollToBottom(proxy) } } @@ -360,7 +294,6 @@ struct ChatTranscriptView: View { } } .onAppear { - // Stored past this view: the ID alone, so `continuity` can't keep the view's closures. scrollPositionController.resyncToTop = { [transcriptContentID] in proxy.scrollTo(transcriptContentID, anchor: .top) } @@ -371,8 +304,6 @@ struct ChatTranscriptView: View { } } - /// A row at the live end changed height without the transcript gaining a message: follow it - /// only from the live edge, and leave a reader up in history where they are. private func followLiveEndChange(proxy: ScrollViewProxy) { guard isFollowingLatestContent else { pinReader(proxy: proxy) @@ -381,34 +312,22 @@ struct ChatTranscriptView: View { releasingHold { onScrollToLatestContent(proxy, false) } } - /// Follow-driven scrolls run only while the latch is on and no disclosure - /// toggle is mid-animation. private var isFollowingLatestContent: Bool { shouldFollowLatestMessage && !isDisclosureSettling } - /// Identifies the whole transcript content so a scroll to its top can be - /// expressed through SwiftUI. private let transcriptContentID = "chat-transcript-content" fileprivate static let contentCoordinateSpace = "chat-transcript-content-space" - /// Frame keys for the blocks drawn between rows, distinct from any `renderID`. private static let planRowID = "hermes-plan" private static let compressionCardFrameID = "compression-reference-card" - /// A tapped row is about to grow or shrink below the reader. Pin the offset - /// so a default anchor SwiftUI re-applies on the size change (seen at the - /// exact top after a status-bar scroll) cannot move them. If the pin had to - /// undo SwiftUI, finish with a SwiftUI-driven scroll to the same place so - /// its own offset model, and hit-testing of the visible rows, catch up. private func pinReader(proxy: ScrollViewProxy) { scrollPositionController.holdPosition { proxy.scrollTo(transcriptContentID, anchor: .top) } } - /// Deliberate scrolls end a disclosure pin first. The pin exists only to - /// stop SwiftUI moving the reader on its own after a toggle. private func releasingHold(_ scroll: () -> Void) { scrollPositionController.releaseHold() scroll() @@ -419,7 +338,6 @@ struct ChatTranscriptView: View { viewportWidth: CGFloat, contentWidth: CGFloat ) -> some View { - // One clock read per body pass; each row compares its timestamp to it. let now = Date() let layout = ChatScrollPositionController.Layout(contentWidth: contentWidth, dynamicTypeSize: dynamicTypeSize) let isFollowing = isFollowingLatestContent @@ -437,11 +355,6 @@ struct ChatTranscriptView: View { } ForEach(displayedTranscriptMessages) { transcriptMessage in - // Scope live-streaming state to the row that actually displays it. - // Non-anchor / non-streaming rows receive stable empty/nil values so - // their inputs don't change on every ~16ms flush; combined with the - // `.equatable()` wrapper below, SwiftUI then skips re-evaluating their - // (markdown-heavy) bodies while a response streams in. let isReasoningAnchor = reasoningAnchorMessageID == transcriptMessage.anchorID let isToolCallAnchor = toolCallAnchorMessageID == transcriptMessage.anchorID let isStreamingRow = streamingAssistantMessageID != nil @@ -458,7 +371,6 @@ struct ChatTranscriptView: View { foldState: foldState, isTerminalReply: terminalReplyRenderIDs.contains(transcriptMessage.renderID), onToggleTurnFold: { turnKey in - // Turn folds toggle in ChatView, so arm the pin here. pinReader(proxy: proxy) onToggleTurnFold(turnKey) }, @@ -516,8 +428,6 @@ struct ChatTranscriptView: View { transcriptLooseBlocks liveResponseBlocks - // Only with workers to list: an empty preview is still a row to the stack, whose - // spacing moved the transcript up as the host's rows replaced the cached copy. if let delegatedWork, delegatedWork.activeCount > 0 { HermesDelegatedWorkInlineView(work: delegatedWork, onOpen: onOpenDelegatedWork) .equatable() @@ -554,8 +464,6 @@ struct ChatTranscriptView: View { .padding(.top, 16) .frame(width: contentWidth, alignment: .leading) .padding(.horizontal, transcriptHorizontalPadding) - // The scroll view stays full width, so its indicator stays at the - // screen edge and swipes in the margins still scroll. .frame(width: viewportWidth, alignment: .center) .clipped() .chatDisclosureToggled { @@ -566,14 +474,11 @@ struct ChatTranscriptView: View { let state = activeStreamRecoveryState await recoveryChip.run( target: state == .idle ? nil : state, - // Offline needs no confirming: nothing resumes until the network does. immediately: state == .waitingForNetwork, animation: ChatMotion.quickState(reduceMotion: reduceMotion) ) } .id(transcriptContentID) - // Row frames are measured here; `ChatScrollObserver`, in this view's - // background, gives the controller the same origin in UIKit. .coordinateSpace(.named(Self.contentCoordinateSpace)) .background { ZStack { @@ -591,9 +496,6 @@ struct ChatTranscriptView: View { } } - /// Only rows created moments ago animate in. Cached history, reloads, and - /// reattached transcripts carry old timestamps and keep `.identity`, so - /// they never replay an entrance. private func rowEntryTransition(for message: ChatMessage, now: Date) -> AnyTransition { guard ChatTranscriptRowFreshness.isFresh(timestamp: message.timestamp, now: now) else { return .identity @@ -675,8 +577,6 @@ struct ChatTranscriptView: View { } } - // Outside the stream check, so a chip held past the stream's end stays - // until its hold ends. DelayedStatusView(driver: recoveryChip) { state in StreamRecoveryStatusView(state: state) .frame(maxWidth: .infinity, alignment: .leading) @@ -747,12 +647,6 @@ struct ChatTranscriptView: View { } } -/// Runs `onFire` each time the stream's scroll trigger bumps. -/// -/// The trigger bumps once per drain tick while a reply streams and feeds only -/// this scroll. Reading it in a leaf keeps each bump from re-running the chat -/// screen's content (transcript derivations, every row's equality check, the -/// composer) just to scroll. struct StreamingFollowTrigger: View { let trigger: () -> Int let onFire: () -> Void @@ -769,13 +663,9 @@ struct ChatTranscriptMessageBlock: View, Equatable { let transcriptMessage: TranscriptMessage let transcriptSpacing: CGFloat let showsThinkingAndToolCards: Bool - /// Nil outside a settled-turn fold. Otherwise says whether this row draws - /// the fold row and which of its parts are hidden right now. let foldState: TranscriptTurnFoldRowState? - /// Whether this row is the reply that closes a settled turn. let isTerminalReply: Bool let onToggleTurnFold: (String) -> Void - /// This row's own reasoning cards. let reasoningGroups: [ReasoningGroup] let toolCallGroups: [ToolCallGroup] let liveReasoningText: String @@ -808,16 +698,8 @@ struct ChatTranscriptMessageBlock: View, Equatable { let onEdit: (MessageActionContext) -> Void let onFork: (MessageActionContext) -> Void let onCopy: (MessageActionContext) -> Void - /// A scheduled task's run (#1413): a row opening on the host's cron hint is its card. var isCronRun = false - // Equality over the value inputs only. The closures are pure functions of - // these values (e.g. `actionContext` is determined by `transcriptMessage`, - // and in a Hermes session by the observed set of rows that can rewind, whose - // change invalidates the row itself), so two blocks that compare equal - // render identically. - // This lets `.equatable()` skip re-evaluating rows whose data is unchanged - // even though their closure props are recreated on every parent body pass. static func == (lhs: ChatTranscriptMessageBlock, rhs: ChatTranscriptMessageBlock) -> Bool { let isEqual = lhs.transcriptMessage == rhs.transcriptMessage && lhs.transcriptSpacing == rhs.transcriptSpacing && @@ -858,8 +740,6 @@ struct ChatTranscriptMessageBlock: View, Equatable { foldState: foldState, showsThinkingAndToolCards: showsThinkingAndToolCards ) - // Yield nothing when every part is folded away, so the outer stack adds - // no spacing for an empty row. if hasVisibleContent || !foldedQuestions.isEmpty { VStack(alignment: .leading, spacing: transcriptSpacing) { if let fold = foldState?.fold { @@ -895,8 +775,6 @@ struct ChatTranscriptMessageBlock: View, Equatable { } } - /// Only folded rows animate in and out; ordinary rows keep no transition - /// so streaming appends stay instant. private var foldTransition: AnyTransition { foldState == nil ? .identity : ChatMotion.disclosureTransition(reduceMotion: reduceMotion) } @@ -916,9 +794,6 @@ struct ChatTranscriptMessageBlock: View, Equatable { return hasArchivedActivity || shouldRenderLiveReasoningBlock || shouldRenderLiveToolActivityGroup } - /// The answered questions a folded turn keeps in view while it hides a - /// row's tool rows. Empty when the row's activity shows, since its clarify - /// rows already show the answers, and when thinking and tool cards are off. static func foldedQuestionLines( in toolCallGroups: [ToolCallGroup], foldState: TranscriptTurnFoldRowState?, @@ -1027,16 +902,12 @@ struct ChatTranscriptMessageBlock: View, Equatable { } } -/// A Hermes session's queued prompt at the transcript's end (#1379): a dimmed user bubble -/// whose meta reads "Queued" in place of a time, with Copy its only action. It loads no -/// attachment media, and its turn's start replaces it with the real row. private struct ChatQueuedPromptRow: View { let message: ChatMessage let onCopy: (String) -> Void var body: some View { VStack(alignment: .trailing, spacing: 4) { - // VoiceOver reads the bubble's own labels (text, chips, attachment names), then "Queued". MessageBubbleView(message: message, transcriptMediaCacheNamespace: "", isQueued: true) .accessibilityElement(children: .combine) .accessibilityValue(Text("Queued")) @@ -1046,15 +917,11 @@ private struct ChatQueuedPromptRow: View { } } -/// A turn a canonical host lost across its restart (#1602), for `ChatLostTurnRow`. `prompt` is its -/// bubble, nil when the transcript already ends on that prompt. struct ChatLostTurn: Equatable { static let rowID = "hermes-lost-turn" let prompt: ChatMessage? } -/// The lost turn's row: its prompt when the transcript lacks it, then "Lost during restart" and -/// Discard, built like `ChatWaitingSendRow`, and why the queue waits. Static: nothing animates. private struct ChatLostTurnRow: View { let turn: ChatLostTurn let onDiscard: () -> Void @@ -1084,9 +951,6 @@ private struct ChatLostTurnRow: View { } } -/// A Hermes chat's Send waiting for the reconnect (#1407): the queued prompt's dimmed bubble, with -/// "Waiting for connection" in place of a time and Cancel, which puts the text back in the composer. -/// Static: nothing animates while it waits. private struct ChatWaitingSendRow: View { let message: ChatMessage let onCancel: () -> Void @@ -1144,18 +1008,11 @@ private struct ChatTranscriptMessageRow: View { let isCronRun: Bool var body: some View { - // Compaction marker messages render as collapsible cards (matching the - // web UI), never as user bubbles — and without bubble actions, which - // don't apply to system-emitted markers. if let markerKind = ChatMarkerMessageClassifier.classify(message) { MarkerMessageCardView(kind: markerKind, content: message.content) } else if let completion = HermesDelegationCompletion(message) { - // A Hermes chat's async-delegation delivery (#1140): the host's turn, never a - // user bubble, with the full report one tap away. HermesDelegationCompletionCard(completion: completion) } else if isCronRun, let prompt = CronRunPrompt(message) { - // A scheduled task's prompt (#1413): the host's runbook, not the user's words. Its - // card is the row's only action; the time keeps its place below. VStack(alignment: .trailing, spacing: metaRowSpacing) { CronRunPromptCard(prompt: prompt, onCopy: actionContext.map { context in { onCopy(context) } }) if let metaTimeText { @@ -1184,14 +1041,10 @@ private struct ChatTranscriptMessageRow: View { message.role == "user" } - /// A reply's footer leaves the same visible gap below it as the turn's fold row - /// leaves above it. The footer's controls draw 13 pt glyphs centred in 28 pt - /// frames (`ChatCopyButton`), so their tops already sit 7.5 pt inside the row. private var metaRowSpacing: CGFloat { isUserMessage ? 4 : transcriptSpacing - (28 - 13) / 2 } - /// Keep actions reachable for every actionable reply, including active turns. private var showsMetaRow: Bool { TranscriptMessageMetaPolicy.showsRow( hasActions: actionContext != nil, hasTimestamp: metaTimeText != nil @@ -1199,7 +1052,6 @@ private struct ChatTranscriptMessageRow: View { } private var metaTimeText: String? { - // Steer rows carry their own caption; no timestamp or copy actions. guard !message.isSteerMessage else { return nil } guard showsTimestamps, isUserMessage || (isTerminalReply && !isStreaming) else { return nil } return ChatMessageTimestampFormatter.shortTime(forUnixTimestamp: message.timestamp) @@ -1279,8 +1131,6 @@ struct ChatScrollToBottomButton: View { } } -/// The capsule that reveals earlier transcript rows, shared by the Sessions -/// and Bot transcripts so paging back reads the same in both. struct LoadOlderMessagesButton: View { let isLoading: Bool let onTap: () -> Void @@ -1319,15 +1169,9 @@ struct LoadOlderMessagesButton: View { } } -/// Decides whether a transcript row is new enough to earn an entrance. enum ChatTranscriptRowFreshness { - /// Rows younger than this animate in; older ones render in place. static let window: TimeInterval = 3 - /// `timestamp` is epoch seconds, as `ChatMessage.timestamp` is. Missing or - /// non-finite values are never fresh. The check is symmetric so a server - /// clock running ahead cannot make reconciled history look freshly born; - /// rows the app creates itself use the phone clock and always pass. static func isFresh(timestamp: Double?, now: Date) -> Bool { guard let timestamp, timestamp.isFinite else { return false } return abs(now.timeIntervalSince1970 - timestamp) < window @@ -1335,9 +1179,6 @@ enum ChatTranscriptRowFreshness { } private extension View { - /// Reports a transcript block's frame under `id` so the controller keeps the - /// reader's place in it through a rewrap (#1414). Frames in the content's - /// space change on a rewrap or the block's own growth, never on a scroll. func reportsReflowFrame( _ id: String, to controller: ChatScrollPositionController, diff --git a/HermesMobile/Features/Chat/ChatView.swift b/HermesMobile/Features/Chat/ChatView.swift index 41d26d30c..37196b92d 100644 --- a/HermesMobile/Features/Chat/ChatView.swift +++ b/HermesMobile/Features/Chat/ChatView.swift @@ -17,8 +17,6 @@ private enum GitChatAlert: Identifiable { } } -/// The Git toasts at the top of the chat (#1410): a busy toast names the branch under the -/// operation's static glyph, and its result adds the commit and any partial-failure detail. private extension ActionToast { static func gitProgress(_ title: String, systemImage: String, branch: String?) -> ActionToast { ActionToast(message: title, systemImage: systemImage, accessibilityLabel: title, tone: .busy, edge: .top, @@ -41,7 +39,6 @@ private enum ActiveGitSheet: Identifiable { var id: Self { self } } -/// `ChatView.turnReviewKey`: one range read per base and availability model. private struct TurnReviewKey: Hashable { let git: GitWorkspaceAvailabilityViewModel let base: GitTurnBase? @@ -53,8 +50,6 @@ private struct TurnReviewKey: Hashable { } } -/// What the per-turn diff sheet shows (issue #316): every changed file in the turn, -/// opened at one of them for a recap-card row tap, read in the range the card counted (#1392). private enum TurnDiffPresentation: Identifiable { case turnFiles([GitFile], initial: GitFile?, scope: GitReviewScope) @@ -71,9 +66,6 @@ private enum TurnDiffPresentation: Identifiable { } } -/// Reports the first completed UIKit appearance transition for a SwiftUI destination. -/// `NavigationStack` does not expose push completion directly, while `viewDidAppear` -/// and the transition coordinator remain synchronized with system animation speed. struct NavigationAppearanceCompletionObserver: UIViewControllerRepresentable { let action: @MainActor () -> Void @@ -289,8 +281,6 @@ struct ChatView: View { private let bottomAnchorID = "chat-bottom-anchor" private let transcriptSpacing: CGFloat = 8 private let composerAccessoryVerticalSpacing: CGFloat = 8 - /// The composer and its status stack keep 16 pt side insets of their own; - /// this cap lines those insets up with the transcript's reading column. private let composerMaximumWidth = ChatReadingWidth.maximumWidth(horizontalPadding: 16) @Environment(\.accessibilityReduceMotion) private var reduceMotion @@ -316,46 +306,21 @@ struct ChatView: View { let server: URL let onAPIError: (Error) -> Void let loadsInitialMessages: Bool - /// When true, the composer auto-starts voice dictation on appear — set by the - /// "New Chat with Voice" App Intent (#338). Defaults to false for normal opens. let autoStartsVoiceInput: Bool let draftStore: ChatDraftStore - /// Store holding the durable app-owned copies of staged attachments. let draftAttachmentStore: any ChatDraftAttachmentStoring - /// True only for the pending-new-chat flow: after the composer configuration - /// loads, the restored draft's settings snapshot is applied (each value - /// revalidated against the live server configuration). Existing sessions - /// load their configuration from the server and never re-apply a snapshot. let restoresDraftSettings: Bool let onConversationStarted: () -> Void - /// A Hermes session's chat (#1010): webui-only controls are hidden and its turns run - /// on the gateway socket. let isHermesSession: Bool - /// The parent the row this Hermes chat opened from named, which its "Forked from" row - /// checks (#1051). let hermesParentKey: String? - /// The working folder of the row a Hermes chat opened from (`HermesSessionChat.workspace`). let hermesRowWorkspace: String? - /// A scheduled task's run (#1413): its prompt row shows as a `CronRunPromptCard`. let isCronRun: Bool - /// Puts a new Hermes chat in this one's place: a Profile picked before anything was - /// sent (#1015). Nil pushes it on top instead. let onReplaceHermesSession: ((HermesSessionChat) -> Void)? - /// Another Shortcut text waits behind the one this chat shows (#1402). private let waitingShortcut: WaitingShortcutText? - /// A Hermes session's dictation goes to its host for its Profile (#1071). private let hermesTranscriber: ComposerTranscriber? - /// Matches a Hermes chat's `Session Open` signpost to the list push that began it. private let hermesSessionChatID: String? - /// Returns to the Sessions list under this Hermes chat, in the entry's Profile (this chat's) - /// and searching the query `/sessions` or `/resume` named (#1053). Nil pushes a list on top - /// instead. let onOpenHermesSessions: ((HermesSessionListEntry) -> Void)? - /// The composer's draft. Never read it in `body` or wrap it in a get/set - /// binding for the composer: either re-runs this whole screen on every - /// keystroke. The composer gets `$draftMessage` and reports its edits to - /// `persistDraftEdit`. @State private var draftMessage = "" @State private var draftQuotes: [ComposerQuote] = [] @State private var draftRevision = 0 @@ -365,22 +330,13 @@ struct ChatView: View { @State private var hydratedCompletionStreamID: String? @State private var composerFocusRevision = 0 @State private var followScrollGeneration = 0 - /// While true the transcript's bottom size-change anchor and follow-driven - /// scrolls are suspended so a disclosure toggle grows or shrinks in place. @State private var isDisclosureSettling = false @State private var disclosureSettleGeneration = 0 @State private var transcriptStructureMemo = TranscriptStructureMemo() - /// While set and in the future, auto-follow scrolls snap instead of animating, so - /// the cache-first → network reconcile re-pins to the bottom without a jump (#289). @State private var cacheFirstSnapUntil: Date? - /// A chat pushed on top of this one: a new fork, or this fork's parent. @State private var pushedSession: SessionSummary? - /// A new Hermes chat in another Profile, pushed on top so Back returns here (#1015). @State private var pushedHermesSession: HermesSessionChat? - /// The Sessions list `/sessions` or `/resume` pushed when no list is under this chat (#1053). @State private var pushedHermesSessionList: HermesSessionListEntry? - /// Set when this webui chat is a fork; draws the "Forked from" row. A Hermes chat's is - /// its view model's (`shownForkOrigin`). @State private var forkOrigin: ForkOrigin? @State private var isOpeningForkParent = false @State private var editContext: MessageActionContext? @@ -392,39 +348,25 @@ struct ChatView: View { @State private var attachmentPreviewItem: ChatAttachmentPreviewItem? @State private var stagedPasteItem: StagedPasteItem? @State private var transcriptMediaPreviewItem: TranscriptMediaPreviewItem? - /// A reply's images in the lightbox, opened at the tapped one. @State private var transcriptImageGallery: ImageLightboxGallery? - /// A message's or the composer's image attachments in the lightbox. @State private var attachmentImageGallery: ImageLightboxGallery? - /// A Hermes sent file or MEDIA document in the shared native artifact preview. @State private var hermesFilePreviewItem: HermesFilePreviewItem? - /// A workspace file a chat link named; presented on the source viewer at its line. @State private var openedFileReference: FileReference? @State private var pendingProfileSelection: ProfileSummary? @State private var showProfileNewSessionConfirmation = false - /// Set while the destructive `/clear` confirmation is on screen. Holds the - /// submitted draft so a confirmed clear consumes it and a cancel leaves it - /// in the composer (#389). @State private var pendingClearConfirmation: PendingClearConfirmation? @State private var goalDraft = "" @State private var showsGoalSheet = false - /// The Profile whose Serve Every Profile fix is open (#1611). @State private var servingProfile: String? @State private var activeGitSheet: ActiveGitSheet? @State private var pendingBranchCheckout: GitCheckoutTarget? @State private var turnDiffPresentation: TurnDiffPresentation? - /// Folds and viewed marks the Changes sheet and turn diffs share for as long as this chat is open. @State private var reviewProgress = ReviewProgressStore() @State private var viewModel: ChatViewModel - /// What outlives this view when a size-class change rebuilds the screen (#1528). @State private var continuity: ChatContinuity - /// This view among those on screen for `continuity`. @State private var viewID = UUID() @State private var gitAvailabilityViewModel: GitWorkspaceAvailabilityViewModel @State private var gitAlert: GitChatAlert? - /// Starts at the last empty composer's measured height, so the transcript's bottom inset is - /// right on a chat's first frame instead of moving once the composer is measured. Kept - /// across launches, since the height follows the font and text size. @State private var composerHeight = ChatView.restingComposerHeight private static let restingComposerHeightKey = "chat.restingComposerHeight" @MainActor private static var restingComposerHeight: CGFloat = { @@ -432,8 +374,6 @@ struct ChatView: View { return saved > 0 ? saved : 52 }() - /// Remembers the composer's height while it is at rest: its resting layout, with no draft or - /// attachments, and not a new chat's taller controls. private func rememberRestingComposerHeight(_ height: CGFloat, isResting: Bool) { guard isResting, draftMessage.isEmpty, viewModel.pendingAttachments.isEmpty, !showsNewChatControls, height != ChatView.restingComposerHeight else { return } @@ -441,55 +381,26 @@ struct ChatView: View { UserDefaults.standard.set(Double(height), forKey: ChatView.restingComposerHeightKey) } - /// Measured height of the collapsed clarification bar, the request's only - /// layout footprint; the expanded card overlays the transcript instead. @State private var clarificationBarHeight: CGFloat = 0 - /// The `/btw` card's height in the clarification slot, part of its footprint (#1013). @State private var btwInsetHeight: CGFloat = 0 - /// The `/btw` answer is open full screen. @State private var showsBtwFullScreen = false - /// Measured height of the run-status pill, which wraps at accessibility - /// text sizes. Seeded with its one-line height at the default size. @State private var activeRunStatusHeight: CGFloat = 28 - /// Measured height of a Hermes chat's pinned plan line (#1139); its open list overlays - /// the transcript instead. @State private var planStripHeight: CGFloat = 30 - /// Measured height of a Hermes chat's Update sign-in pill (#942), which wraps at - /// accessibility text sizes. @State private var updateSignInPillHeight: CGFloat = 36 - /// Where the draft's added text came from, until the user dismisses its notice or sends it - /// (#1402, #1476). @State private var textOrigin: ImportedTextOrigin? - /// The draft as it was before Remove Hidden Characters, and its origin, until the next edit. @State private var textBeforeHiddenRemoval: (text: String, origin: ImportedTextOrigin)? - /// Measured height of the Shortcuts notice, which wraps with Dynamic Type. @State private var shortcutNoticeHeight: CGFloat = 0 - /// The delegated-work sheet a Hermes chat's workers button opens (#1140). @State private var showsDelegatedWork = false - /// A bot's chat's pill opened the bot's profile (#1145). @State private var showsBotProfileEditor = false @State private var showsChatSettings = false @State private var showsModelSettings = false - /// Measured height of the pinned notice stack, which grows with each - /// notice and with Dynamic Type. @State private var pinnedNoticeStackHeight: CGFloat = 0 @State private var hostNoticeHeight: CGFloat = 0 @State private var composerIsFocused = false @State private var didHydrateDraft = false - /// Whether this chat has already asked the server for its skills on the - /// transcript's behalf, so a request that failed does not repeat with every - /// later transcript update. @State private var hasRequestedSkillsForTranscriptChips = false - /// True from the moment hydration finds persisted attachment records until - /// their restore pass finishes. It gates `syncDraftAttachments` across the - /// whole window, so the not-yet-rebuilt composer strip can never overwrite - /// the persisted set. @State private var isRestoringDraftAttachments = false - /// Records hydration found, handed to the restore pass that runs alongside - /// the transcript load rather than in front of it. @State private var draftAttachmentsAwaitingRestore: [ChatDraftAttachment] = [] - /// Restored attachment records whose re-upload failed; they stay in the - /// draft for a later retry and are unioned into every attachment sync. @State private var draftAttachmentsPendingRetry: [ChatDraftAttachment] = [] @State private var lastSyncedDraftAttachments: [ChatDraftAttachment] = [] @State private var restoredDraftSettings: ChatDraftSettings? @@ -499,10 +410,7 @@ struct ChatView: View { @State private var didApplyInitialComposerFocusPolicy = false @State private var shouldRestoreComposerFocusAfterPreview = false @State private var responseCompletionNotificationTracker = ResponseCompletionNotificationTracker() - /// The one-time notification offer (#863), set once a send claims it. @State private var pendingNotificationOffer: NotificationOffer.Offer? - /// Between appear and disappear; a send that returns after the chat closed must not - /// use up the offer it can no longer show. @State private var isOnScreen = false @State private var responseCompletionBackgroundTask: UIBackgroundTaskIdentifier = .invalid @State private var activeStreamStatusRefreshTask: Task? @@ -510,10 +418,7 @@ struct ChatView: View { @State private var initialAttachments: [SharedAttachmentImport] @State private var didUploadInitialAttachments = false @State private var showsStopConfirmation = false - /// What the share this new chat opened for left out (#1401), shown once over the composer. private let shareNotice: SharedSkipsNotice? - /// The chat's one toast (#1410): Git progress and results at the top, near the Git controls, - /// and over the composer the share's skips or a waiting send that expired (#1407). @State private var toastState = ActionToastState() init( @@ -576,8 +481,6 @@ struct ChatView: View { model.hermesLineageRoot = hermesSession?.lineageRoot model.onHermesDraftKeyChange = onHermesDraftKeyChange _viewModel = State(initialValue: model) - // Until its first report, a reader who wasn't following reads as away from the live edge, - // so the bottom a rebuilt transcript opens at doesn't re-arm follow. _isScrolledNearBottom = State(initialValue: model.followLatch.isFollowing) _gitAvailabilityViewModel = State(initialValue: GitWorkspaceAvailabilityViewModel( session: session, @@ -585,11 +488,6 @@ struct ChatView: View { )) } - /// A Hermes session on its Profile (#1010). It has no webui session, so nothing here - /// reaches the webui API; connection errors show in the chat itself. A bot's Bot Chat - /// (#1145) shows the bot's pill in place of the title and keeps Bot Chat's rules - /// (`HermesChatPolicy`). Update sign-in goes through the environment's - /// `HermesUpdateSignInAction`. New Chat with Voice's chat (#1180) starts dictation. init(hermesSession: HermesSessionChat, onReplace: ((HermesSessionChat) -> Void)? = nil, onOpenSessions: ((HermesSessionListEntry) -> Void)? = nil, onDraftKeyChange: ((ChatDraftKey) -> Void)? = nil, waitingShortcut: WaitingShortcutText? = nil, @@ -610,9 +508,6 @@ struct ChatView: View { ) } - // Extracted from `body` so the type-checker doesn't have to solve the whole composer - // call alongside the rest of the screen in one expression (#316 pushed it over the - // "unable to type-check in reasonable time" limit). private var messageComposer: some View { MessageComposerView( draftMessage: $draftMessage, @@ -624,17 +519,12 @@ struct ChatView: View { composerIsFocused = value } ), - // A Hermes prompt whose answer was lost holds Send until the chat reattaches (#508), and - // a request card's answer holds it while out, so Steer and Queue send no competing - // Continue (#1141). So does a cached transcript shown while the chat connects. isSending: viewModel.isStartingChat || viewModel.isSendingVoiceNote || viewModel.isHermesSubmissionUncertain || viewModel.isUndoingExchange || viewModel.hermesRequests?.answeringRequestID != nil || viewModel.isCachedCopyProvisional, isCompressingSession: viewModel.isCompressingSession, isWaitingForStream: viewModel.activeStreamID != nil, isCancellingStream: viewModel.isCancellingStream, - // Offline the draft stays editable and Send waits for the reconnect (#1375); a Hermes - // chat's plain-text Send waits as the transcript's waiting bubble (#1407). access: ChatComposerAccess(session: session, isViewingCachedData: viewModel.showsOfflineCache, offersWaitingSend: viewModel.offersWaitingSend, hasWaitingSend: viewModel.waitingSend != nil), @@ -652,11 +542,9 @@ struct ChatView: View { workspaceRoots: viewModel.workspaceRoots, selectedWorkspacePath: viewModel.selectedWorkspacePath, workspaceSuggestions: viewModel.workspaceSuggestions, - // A Hermes host has no workspace registry to manage (#1117). workspaceManagementServer: isHermesSession ? nil : server, personalitySuggestions: viewModel.personalitySuggestions, skillSuggestions: viewModel.composerSkillSuggestions, - // A Hermes chat's skills come with the catalog it reads on connect. hasLoadedSkillSuggestions: isHermesSession || viewModel.hasLoadedSkillSlashSuggestions, agentCommands: viewModel.composerAgentCommands, profileOptions: viewModel.composerProfileOptions, @@ -670,9 +558,6 @@ struct ChatView: View { isUpdatingConfiguration: viewModel.isUpdatingComposerConfiguration || viewModel.hermesSettings?.controls.isApplying == true || viewModel.pendingHermesFolder != nil, pendingAttachments: viewModel.pendingAttachments, - // An in-flight draft restore counts as an upload in progress: until - // it finishes, the composer does not yet hold the attachments the - // user expects this message to carry. isUploadingAttachment: viewModel.isUploadingAttachment || isRestoringDraftAttachments, attachmentUploadCount: viewModel.attachmentUploadCount, attachmentUploadGeneration: viewModel.attachmentUploadGeneration, @@ -762,8 +647,6 @@ struct ChatView: View { onRemoveAttachment: { id in let removedAttachment = viewModel.pendingAttachments.first(where: { $0.id == id }) viewModel.removePendingAttachment(id: id) - // Explicit discard: the record drops out of the draft via the - // observation sync; delete its now-unreferenced local copy. if let file = removedAttachment?.draftFileName { syncDraftAttachments() Task { await viewModel.deleteDraftAttachmentCopy(named: file, attachmentID: id) } @@ -787,7 +670,6 @@ struct ChatView: View { onDismissUploadAttachmentError: { viewModel.setUploadAttachmentError(nil) }, - // An unserved Profile or stale runtime is the host's state, not one attempt's. onDismissError: viewModel.errorUnserved != nil || viewModel.sendErrorRuntimeStale != nil ? nil : { viewModel.clearComposerErrors() }, onSelectFileReference: { path in @@ -796,8 +678,6 @@ struct ChatView: View { onFileReferenceCandidatesChange: { draft in await viewModel.loadFileChipReferences(draft: draft) }, - // Only typing clears an error: a restored draft (`/retry`, a prefill) keeps the - // error that came with it (#1694). onDraftEdit: { text in viewModel.clearComposerErrors() persistDraftEdit(text) @@ -851,8 +731,6 @@ struct ChatView: View { onCancelAttachmentUpload: viewModel.isSendingAttachments ? { viewModel.cancelAttachmentUpload() } : nil, hermesTranscriber: hermesTranscriber ) - // The composer flips wholesale with the transcript under the RTL - // toggle (#259): input, placeholder, and chrome mirror together. .environment(\.layoutDirection, chatLayoutDirection) .background( NavigationAppearanceCompletionObserver(action: handleInitialAppearanceCompletion) @@ -861,10 +739,6 @@ struct ChatView: View { ) } - /// Hermes documents share BotArtifactPreview. An image is known to be an image - /// before it is fetched, so it opens in the full-bleed lightbox, paging through the - /// reply's other images. Everything else keeps the preview sheet, which still has to - /// decide between audio, video, and an unsupported file once the bytes arrive. private func presentTranscriptMediaPreview( _ reference: TranscriptMediaReference, in replyMedia: [TranscriptMediaReference] @@ -882,10 +756,6 @@ struct ChatView: View { } } - /// A Hermes chip with a host path opens from the host with Save to Files and Share - /// (#1030); every other chip, a Hermes one still sending included, opens its local - /// copy or the webui file. An image pages through the message's images that open - /// the same way. private func presentSentAttachmentPreview( _ tapped: MessageAttachmentPreview, among siblings: [MessageAttachmentPreview] @@ -908,8 +778,6 @@ struct ChatView: View { } } - /// Opens `items[index]`: an image in the lightbox, paging through the image items; - /// anything else in the preview sheet. private func presentAttachmentPreview(_ items: [ChatAttachmentPreviewItem], at index: Int) { let item = items[index] presentPreviewRestoringComposerFocusIfNeeded { @@ -944,18 +812,12 @@ struct ChatView: View { ) } - /// The capped preview download behind `hermesFilePreviewItem`. A sent chip and a MEDIA - /// document's host path download from this chat's attach, as the card's export does, so a - /// result that lands after a reattach is dropped (#1030). A remote MEDIA document is a - /// public, cookie-less fetch with neither server's credentials. The whole file, past the - /// cap included, exports from the card's own download button. private func hermesFilePreviewData(for item: HermesFilePreviewItem) async throws -> Data { if item.isSentAttachment { return try await viewModel.hermesAttachmentData(path: item.reference.rawReference) } switch item.reference.source { case let .localPath(path): return try await viewModel.hermesAttachmentData(path: path) case let .remoteURL(url): - // A refusal there is not Hermes's sign-in, which `BotFailure.rejected` would say. do { return try await BotArtifactDownload.data(session: APIClient.sharedPublicMediaSession, request: URLRequest(url: url)) @@ -963,12 +825,6 @@ struct ChatView: View { } } - /// A chat link that names a workspace file opens the source viewer at its line. In a - /// Hermes chat, a link to an HTML report outside the folder (an agent's scratch copy) - /// opens the report sheet through the attach, as a `MEDIA:` report does (#1713). Every - /// other link returns nil for `transcriptLinks` to open. The viewer's own error state - /// covers a path the server no longer has, so the tap never waits on a fetch. A Hermes - /// chat's root is its folder, only while Files can read it. private func handleTranscriptLink(_ url: URL) -> OpenURLAction.Result? { let root = isHermesSession ? browsableHermesWorkspace?.cwd : session.workspace if let reference = FileReference.parse(url.absoluteString, workspaceRoot: root) { @@ -1014,21 +870,15 @@ struct ChatView: View { return sessionID } - /// A Hermes chat's folder while Files and Git can read it: `session.info` has named it, on a - /// `local` terminal backend (#1112, #1114). Nil on any other backend, and before. private var browsableHermesWorkspace: HermesWorkspaceContext? { viewModel.hermesWorkspace.flatMap { $0.isLocal ? $0 : nil } } - /// What Files, its previews and transcript file links read: the webui session's - /// workspace, or a Hermes chat's folder while `browsableHermesWorkspace` has one. private var workspaceFiles: (any WorkspaceFileClient)? { guard isHermesSession else { return WebUIWorkspaceFileClient(session: session, server: server) } return browsableHermesWorkspace == nil ? nil : viewModel.hermesWorkspaceFiles } - /// What a MEDIA reference downloads through: the webui session, or a Hermes chat's host, - /// whatever its backend, since the host resolves the path against the session. private var transcriptMediaFiles: (any WorkspaceFileClient)? { if isHermesSession { return viewModel.hermesWorkspaceFiles } return transcriptMediaSessionID.map { WebUIWorkspaceFileClient(sessionID: $0, workspace: session.workspace, server: server) } @@ -1039,7 +889,6 @@ struct ChatView: View { ?? "\(server.absoluteString)|\(transcriptMediaSessionID ?? "local:\(session.id)")" } - /// A webui server's pending approval, in the clarification's slot (#1584). private func webuiApprovalInset(_ prompt: ApprovalPromptState, maximumExpandedHeight: CGFloat) -> some View { ApprovalRequestInset( content: prompt.requestContent, @@ -1078,8 +927,6 @@ struct ChatView: View { .transition(ChatMotion.bottomOverlayTransition(reduceMotion: reduceMotion)) } - /// A Hermes session's approval (#1011, #1584): only the host's choices, each answered once, - /// and Skip all, which turns the session's bypass on and releases this approval. private func hermesApprovalInset( _ approval: BotApprovalRequest, requests: HermesChatRequests, @@ -1124,10 +971,6 @@ struct ChatView: View { .transition(ChatMotion.bottomOverlayTransition(reduceMotion: reduceMotion)) } - /// The chat scaffold: layout, title, and push presence. `body` is built in - /// layers (`chatScaffold`, `chatLifecycle`, `chatContent`, then the alerts in - /// `body`) so each chained expression stays inside the compiler's - /// type-checking budget; CI's pinned Xcode has less headroom than the newest. private var chatScaffold: some View { GeometryReader { viewport in let clarificationMaximumHeight = max( @@ -1144,8 +987,6 @@ struct ChatView: View { listenPlaybackBar messageContent - // Scope RTL to the chat transcript only (#259): the offline - // banner above stays in the app's default direction. .environment(\.layoutDirection, chatLayoutDirection) } .animation(ChatMotion.quickState(reduceMotion: reduceMotion), value: viewModel.showsListenPlaybackBar) @@ -1173,14 +1014,12 @@ struct ChatView: View { .themedPageBackground() .navigationTitle(viewModel.hermesBotChat?.botProfile?.name ?? displayTitle) .navigationBarTitleDisplayMode(.inline) - // A bot's pill names the chat; its title stays only for Back on screens pushed over it. .toolbar(removing: viewModel.hermesBotChat == nil ? nil : .title) .modifier(ChatNavigationBackground()) .accessibilityIdentifier("chat-detail:\(viewModel.displayTitle)") .pushPresence(viewModel.pushPresence) } - /// Appearance, scene, network, stream, and draft handlers over `chatScaffold`. private var chatLifecycle: some View { chatScaffold .task(id: didCompleteInitialAppearance) { @@ -1197,17 +1036,12 @@ struct ChatView: View { handleNetworkPathChange() } .onChange(of: viewModel.activeStreamID) { - // A new turn starting folds the previous one, even one that opened - // itself after failing or being stopped. Here, not in the handler, which a - // rebuilt view also runs as it appears, with the same turn still going. if viewModel.activeStreamID != nil, let previousTurnKey = viewModel.latestRunOutcome?.turnKey { viewModel.expandedTurnKeys.remove(previousTurnKey) } handleActiveStreamChange() } .onChange(of: viewModel.transcriptRelayoutScrollToken) { - // Open a brief snap window so the cache-first reconcile re-pin (and any - // message-count auto-follow racing it) lands without an animated jump (#289). cacheFirstSnapUntil = Date().addingTimeInterval(0.35) } .onChange(of: viewModel.isUploadingAttachment) { _, isUploading in @@ -1241,11 +1075,9 @@ struct ChatView: View { composerFocusRevision += 1 completionScrollPolicy.readerDidInteract() hydratedCompletionStreamID = nil - // Another view on screen, from a size-class change, still runs the model (#1528). let chatLeft = continuity.viewDisappeared(viewID) if chatLeft { parkQueuedMessages() - // A waiting send never sends from a chat that left; its text goes back to the draft (#1407). viewModel.leaveWaitingSend() } flushDraftsBestEffort() @@ -1262,7 +1094,6 @@ struct ChatView: View { gitAvailabilityViewModel.suspendPullRequestReads() } .onAppear { - // Holds only the composer's text and the toast, never this view (#1407). continuity.viewAppeared(viewID, model: viewModel) { [composerText = $draftMessage, toast = toastState] text, reason in composerText.wrappedValue = text if reason == .expired { @@ -1303,11 +1134,9 @@ struct ChatView: View { .onChange(of: viewModel.streamingHapticPulseTrigger, handleStreamingHapticPulse) } - /// Toolbar, navigation, and presentations over `chatLifecycle`. private var chatContent: some View { chatLifecycle .verticalBarToolbar { hasVerticalBar in - // A bot's chat swaps the title for the bot's pill (#1145). if let botChat = viewModel.hermesBotChat { ToolbarItem(placement: .topBarLeading) { HermesBotChatPill(turn: botChat) { showsBotProfileEditor = true } @@ -1419,9 +1248,6 @@ struct ChatView: View { } } .sheet(item: $openedFileReference, content: fileReferenceSheet) - // A file link or Git sheet opened in a Hermes chat's old folder reads through the old - // client: close it, and read the new folder's repository (#1114). A Git action still - // running there, and its toast or alert, belong to the old repository (#1115). .onChange(of: viewModel.hermesWorkspace) { openedFileReference = nil pendingBranchCheckout = nil @@ -1434,9 +1260,6 @@ struct ChatView: View { } .sheet(item: $activeGitSheet, onDismiss: runPendingBranchCheckout, content: gitSheet) .sheet(item: $turnDiffPresentation, content: turnDiffSheet) - // These sheets come from the chat, not the composer, so the composer reads their - // transition as a navigation one and keeps its focus intent. A focused composer - // would then take the keyboard back over a field on top, such as Comment…'s. .onChange(of: presentsWorkspaceSheet) { _, isPresented in if isPresented { shouldRestoreComposerFocusAfterPreview = composerIsFocused @@ -1540,7 +1363,6 @@ struct ChatView: View { ) ) .notificationOfferAlert($pendingNotificationOffer) - // Model settings asks over itself while it is up. .modifier(HermesModelConfirmationModifier( controls: showsModelSettings ? nil : viewModel.hermesSettings?.controls )) @@ -1552,7 +1374,6 @@ struct ChatView: View { pending: viewModel.pendingHermesRollback, onCancel: viewModel.cancelHermesRollback, onConfirm: confirmHermesRollback )) - // A Hermes chat's folder change asks first, in Move to Project's words (#1117). .alert( Text(verbatim: viewModel.pendingHermesFolder.map { String(localized: "Move to \($0.lastPathComponentFallback)?") } ?? ""), isPresented: Binding(get: { viewModel.pendingHermesFolder != nil }, @@ -1665,7 +1486,6 @@ struct ChatView: View { } } - /// The checkout waits for the sheet to close, since a dirty tree raises an alert from here. private func closeBranchPicker(checkingOut target: GitCheckoutTarget) { pendingBranchCheckout = target activeGitSheet = nil @@ -1694,9 +1514,6 @@ struct ChatView: View { } } - /// Where Comment… on a diff or source surface appends: the draft, persisted at once and - /// never sent, so the sheet stays open for the next comment. Nil, hiding Comment…, while - /// the session is read-only and its editor locked. private var reviewCommentHook: ((String) -> Void)? { guard !session.isSessionReadOnly else { return nil } return { markdown in @@ -1705,12 +1522,10 @@ struct ChatView: View { } } - /// A Git, turn diff, or file reference sheet is up over the chat. private var presentsWorkspaceSheet: Bool { activeGitSheet != nil || turnDiffPresentation != nil || openedFileReference != nil } - /// Back to Chat from a Git sheet: closes the Changes sheet or turn diff and any diff on top. private func closeGitPresentation() { activeGitSheet = nil turnDiffPresentation = nil @@ -1765,9 +1580,6 @@ struct ChatView: View { ) } - /// Inputs for the inline "Commit & Push" button shown under the latest assistant turn. - /// Only for git workspaces, when the latest message is an assistant turn (not while a - /// response streams), and there is something to commit (or a commit is in flight). private var inlineCommitContext: ChatInlineCommitContext? { guard ChatGitControlsVisibilityPolicy.showsInlineCommitButton( showsGitControls: showsGitControls, @@ -1784,11 +1596,6 @@ struct ChatView: View { ) } - /// Turn-end "File changes" recap card for the latest assistant turn (#316). Only for git - /// workspaces once the response finishes (status has refreshed) and the latest turn - /// actually changed files. A Hermes turn whose direct send read HEAD first joins its range - /// since then (#1392), waiting for that read; any other joins the uncommitted status, and a - /// Hermes card names which. private var turnChangesRecapSummary: TurnFileChangeSummary? { guard ChatGitControlsVisibilityPolicy.showsTurnChangesRecap( showsGitControls: showsGitControls, @@ -1806,29 +1613,20 @@ struct ChatView: View { return summary.hasChanges ? summary : nil } - /// What the latest turn's range read follows (#1392): the base an idle chat's latest turn holds, - /// on the repository the chat shows. Keyed on that, not on the stream ending, so a turn that - /// starts and ends within one update still reads, and a chat opened after its turn reads too. private var turnReviewKey: TurnReviewKey { TurnReviewKey(git: gitAvailabilityViewModel, base: viewModel.activeStreamID == nil ? viewModel.hermesTurnBase : nil) } - /// Present the per-turn diff sheet for every changed file the turn has a row for. No-op when - /// there is nothing diffable yet (e.g. status still refreshing). private func presentTurnDiff(for summary: TurnFileChangeSummary?) { guard let presentation = TurnDiffPresentation(summary) else { return } turnDiffPresentation = presentation } - /// Runs on the repository it started in: a folder change retires that one, and its outcome is - /// then `.retired`, with nothing to show. @MainActor private func performQuickCommit(push: Bool) async { let git = gitAvailabilityViewModel guard !git.isCommitting, !git.isWriteLocked else { return } - // Every path below resolves only this toast, so a commit that ends after a newer toast, - // a swipe, or the chat closing leaves that state alone. let toastID = toastState.show(.gitProgress(GitCommitPhase.generatingMessage.progressTitle, systemImage: GitCommitPhase.generatingMessage.systemImage, branch: git.currentBranchName)) @@ -1844,8 +1642,6 @@ struct ChatView: View { if let sha = result.shortSHA { detailLines.append(String(localized: "Commit \(sha)")) } if result.truncatedMessage { detailLines.append(String(localized: "Diff was large; message may be partial.")) } if let pushError = result.pushFailureMessage { - // The commit landed but the requested push failed — report partial success - // so the user knows the local commit is safe and only the push needs retrying. detailLines.append(String(localized: "Push failed: \(pushError)")) } toastState.update(toastID, to: .gitResult( @@ -1862,12 +1658,6 @@ struct ChatView: View { ChatHaptics.gitActionFinished(succeeded: false, isEnabled: isHapticsEnabled) gitAlert = .error(String(localized: "There are no changes to commit.")) case .tooManyChanges: - // Status was truncated (>500 files): the commit was blocked to avoid silently - // dropping files 501+. Always surface a message — falling back to a hardcoded - // string if the view model ever leaves actionErrorMessage unset — because a - // blocked commit with no feedback would be the very silent failure this guards - // against. (Kept separate from .failure, which intentionally stays quiet when its - // busy/no-session guard returns with no message.) No success toast/SHA. toastState.dismiss(toastID) ChatHaptics.gitActionFinished(succeeded: false, isEnabled: isHapticsEnabled) gitAlert = .error(git.actionErrorMessage @@ -1883,27 +1673,19 @@ struct ChatView: View { } } - /// Runs on the repository it started in, and shows nothing once a folder change retired it. - /// A Hermes switch with uncommitted changes fails with "Commit or discard first." (#1116); - /// only webui offers the stash. @MainActor private func performGitCheckout(_ target: GitCheckoutTarget, stashingChanges: Bool = false) async { let git = gitAvailabilityViewModel let outcome = await git.checkout(target, stashingChanges: stashingChanges) - // A model retired while its switch ran belongs to the folder the chat left. if outcome == .retired || git.isRetired { return } else if outcome == .requiresStash { gitAlert = .dirtyCheckout(target) } else if let message = git.actionErrorMessage { - // Surface real failures and partial successes (branch switched but the - // stashed changes could not be restored) — the view model sets - // actionErrorMessage in both cases and clears it on every new checkout. gitAlert = .error(message) } } - /// Runs on the repository it started in, and shows nothing once a folder change retired it. @MainActor private func performGitRemoteAction(_ action: GitRemoteAction) async { let git = gitAvailabilityViewModel @@ -1934,8 +1716,6 @@ struct ChatView: View { } } - /// webui pushes to the configured upstream. A Hermes host pushes there too, or to origin as - /// the branch's new upstream when it has none (#1115), so its copy names the branch and both. private var pushConfirmationMessage: String { guard gitAvailabilityViewModel.git?.isHermes == true else { return String(localized: "Push the current branch to its configured upstream remote?") @@ -1977,13 +1757,9 @@ struct ChatView: View { } } - /// The pending clarification or approval, pinned above the composer. Sits in the - /// same bottom stack as the composer so it rides the keyboard with it. One request - /// at a time: a question before an approval, as `HermesChatRequests.onScreen` orders. private func clarificationInset(maximumExpandedHeight: CGFloat) -> some View { ZStack(alignment: .bottom) { if let requests = viewModel.hermesRequests { - // Below the request inset, whose expanded card rises over it. btwInset(maximumExpandedHeight: maximumExpandedHeight) if case .approval(let approval)? = hermesInsetRequest { hermesApprovalInset(approval, requests: requests, maximumExpandedHeight: maximumExpandedHeight) @@ -2027,8 +1803,6 @@ struct ChatView: View { .animation(ChatMotion.quickState(reduceMotion: reduceMotion), value: viewModel.hermesSideTasks?.btw?.id) } - /// A Hermes session's `/btw` question in the clarification slot (#1013): the card, or one - /// line above a host request that takes the slot. @ViewBuilder private func btwInset(maximumExpandedHeight: CGFloat) -> some View { if let sideTasks = viewModel.hermesSideTasks, let btw = sideTasks.btw { @@ -2056,7 +1830,6 @@ struct ChatView: View { } } - /// The `/btw` answer full screen, while its question is open. @ViewBuilder private var btwFullScreen: some View { if let sideTasks = viewModel.hermesSideTasks, let btw = sideTasks.btw { @@ -2073,9 +1846,6 @@ struct ChatView: View { } } - /// The run the full-screen `/btw` answer hides, as the run-status pill names it but - /// without its ticking time; nil when idle. "Waiting for you" when a host request, - /// under the cover, holds the turn. private var btwRunStatus: ChatActiveRunStatusKind? { ChatActiveRunStatusPolicy.presentation( isStartingChat: viewModel.isStartingChat, @@ -2088,8 +1858,6 @@ struct ChatView: View { )?.kind } - /// A Hermes session's question, sudo or secret prompt, Desktop task or connection operation, - /// in the clarification's slot (#1011, #1141). private func hermesRequestInset( _ request: BotPendingRequest, requests: HermesChatRequests, @@ -2117,12 +1885,10 @@ struct ChatView: View { Task { await requests.skipQuestion(action) } }, onCredential: { value in - // The typed value goes straight from the field to the dispatch. guard let action = requests.prepareAnswer() else { return } Task { await requests.answerCredential(action, value: value) } }, onConnection: { answer in - // Typed setup values go straight from the row to the dispatch. guard let action = requests.prepareAnswer() else { return } Task { await requests.respondToConnection(action, answer) } }, @@ -2140,14 +1906,10 @@ struct ChatView: View { .transition(ChatMotion.bottomOverlayTransition(reduceMotion: reduceMotion)) } - /// The Hermes request the clarification slot shows: a question, an approval, a sudo or - /// secret prompt, a Desktop task or a connection operation. private var hermesInsetRequest: BotPendingRequest? { viewModel.hermesRequests?.onScreen } - /// The request in the clarification slot: a webui clarification or approval, or a Hermes - /// inset request. private var requestInsetID: String? { hermesInsetRequest?.requestID ?? viewModel.clarificationPrompt?.id ?? viewModel.approvalPrompt?.id } @@ -2156,7 +1918,6 @@ struct ChatView: View { private var composerAccessoryStack: some View { if composerAccessoryVisibleItemCount > 0 { VStack(spacing: composerAccessoryVerticalSpacing) { - // The host's newest notice about the session (#1746), farthest from the composer. if let hostNotices = viewModel.hermesHostNotices, let notice = hostNotices.shown { HostNoticeRow(notice: notice, waitingCount: hostNotices.waitingCount) { hostNotices.dismiss(notice) @@ -2192,7 +1953,6 @@ struct ChatView: View { .transition(ChatMotion.bottomOverlayTransition(reduceMotion: reduceMotion)) } - // Nearest the composer and its request card, under the run-status pill (#1139). if let pinnedPlan { HermesPlanStrip(plan: pinnedPlan) { height in planStripHeight = height @@ -2200,8 +1960,6 @@ struct ChatView: View { .transition(ChatMotion.bottomOverlayTransition(reduceMotion: reduceMotion)) } - // Bot Chat's pill in Reconnect's slot (#942): the composer's error line still - // says why, and the chat never signs in again on its own while it shows. if viewModel.hermesNeedsSignIn { BotComposerPillView(pill: .updateSignIn, onUpdateSignIn: { updateHermesSignIn() }) .onGeometryChange(for: CGFloat.self) { proxy in @@ -2212,7 +1970,6 @@ struct ChatView: View { .transition(ChatMotion.bottomOverlayTransition(reduceMotion: reduceMotion)) } - // Nearest the composer: it is about the text in it (#1402). if showsShortcutNotice { shortcutNotice .onGeometryChange(for: CGFloat.self) { proxy in @@ -2228,7 +1985,6 @@ struct ChatView: View { .padding(.bottom, composerHeight + 8 + clarificationFootprintHeight) .zIndex(8) .animation(ChatMotion.quickState(reduceMotion: reduceMotion), value: composerAccessoryVisibleItemCount) - // Keyed to the kind, so the compacting line (#1734) swaps words without animating. .animation(ChatMotion.quickState(reduceMotion: reduceMotion), value: activeRunStatusPresentation?.kind) .animation(ChatMotion.quickState(reduceMotion: reduceMotion), value: composerLocalNotices) .animation(ChatMotion.quickState(reduceMotion: reduceMotion), value: showsHostNotice) @@ -2241,10 +1997,6 @@ struct ChatView: View { private var showsHostNotice: Bool { viewModel.hermesHostNotices?.shown != nil } - /// Where the draft's added text came from while its notice shows: the draft holds that text, - /// or a removal of its hidden characters can still be undone, even one that took all of it. - /// `body` reads this, so the draft is read only when there is an origin to show; see - /// `draftMessage`. private var shownTextOrigin: ImportedTextOrigin? { if let removed = textBeforeHiddenRemoval { return removed.origin } guard let textOrigin, !draftMessage.isEmpty else { return nil } @@ -2269,7 +2021,6 @@ struct ChatView: View { guard let before = textBeforeHiddenRemoval else { return } persistDraftEdit(before.text) draftMessage = before.text - // A removal that emptied the draft ended its provenance. textOrigin = before.origin draftStore.setTextOrigin(before.origin, for: draftKey) }, @@ -2278,15 +2029,12 @@ struct ChatView: View { ) } - /// The user dismissed the added text's notice, deleted its text, or sent it. private func dismissShortcutNotice() { textOrigin = nil textBeforeHiddenRemoval = nil draftStore.setTextOrigin(nil, for: draftKey) } - /// The bot's profile, from its pill (#1145). Closing it reads the roster again, so the pill - /// and the `@` roster show what was saved. @ViewBuilder private var botProfileEditor: some View { if let botChat = viewModel.hermesBotChat, let profile = botChat.botProfile { let connection = botChat.engine.connection @@ -2296,17 +2044,12 @@ struct ChatView: View { } } - /// A Hermes chat's delegated workers (#1140). Nil on the offline cache's copy, which lists none. private var delegatedWork: HermesDelegatedWork? { viewModel.isViewingCachedData ? nil : viewModel.hermesActivity?.delegatedWork } - /// A bot's chat has no subtitle to tap, since the pill opens its bot. private var showsBotChatSettingsButton: Bool { viewModel.hermesBotChat != nil } - /// A Hermes chat opened from a row with a folder shows Files from its first frame, disabled - /// until the host names the session's folder, instead of the button arriving a moment later. - /// A folder Files can't read (not a `local` backend) then takes it away again. private var showsFilesLink: Bool { showsFilesButton && (!isHermesSession || browsableHermesWorkspace != nil || hermesRowWorkspace != nil && viewModel.hermesWorkspace == nil) @@ -2314,9 +2057,6 @@ struct ChatView: View { private var showsGitMenu: Bool { showsGitControls && gitAvailabilityViewModel.hasRepository } - /// Whether any trailing chat action shows. The trailing cluster and the spacer before the - /// delegated-work button are added only then: an empty cluster still draws as a blank button. - /// Keep in step with the actions the cluster and `chatActionRailItems` list. private var showsTrailingActions: Bool { showsBotChatSettingsButton || viewModel.showsGoalControls || showsFilesLink || showsGitMenu || screenShortcut != nil @@ -2344,9 +2084,6 @@ struct ChatView: View { .accessibilityLabel("Files") } - /// The trailing actions where the system draws a vertical bar (iPhone Duo): one item each, - /// since the bar can't hold the cluster's custom view. Custom labels prefer the vertical bar - /// explicitly, or they fall back to a horizontal one. @available(iOS 27.1, *) @ToolbarContentBuilder private var chatActionRailItems: some ToolbarContent { @@ -2375,8 +2112,6 @@ struct ChatView: View { } } - /// A Hermes chat's workers button (#1140), its own glass beside the cluster while any - /// worker is active. @ToolbarContentBuilder private var delegatedWorkToolbarItem: some ToolbarContent { if let work = delegatedWork, work.activeCount > 0 { @@ -2393,19 +2128,14 @@ struct ChatView: View { Task { await work.refresh() } } - /// A Hermes chat's running plan, pinned above the composer while it has an open step - /// (#1139). Hidden on the offline cache's copy. private var pinnedPlan: HermesPlan? { viewModel.isViewingCachedData ? nil : viewModel.hermesActivity?.pinnedPlan } - /// The prompt row a Hermes chat's settled plan follows (#1139). private var settledPlanAfterRenderID: String? { viewModel.hermesActivity?.settledPlan?.afterRenderID(in: displayedTranscriptMessages) } - /// How a Hermes chat's last turn ended, under it (#1139): the failure with Retry and the - /// billing page, or the host's warning. private var hermesTurnOutcome: HermesTurnOutcomeRow? { guard let activity = viewModel.hermesActivity, activity.failure != nil || activity.notice?.warning != nil else { return nil } return HermesTurnOutcomeRow( @@ -2414,21 +2144,16 @@ struct ChatView: View { onRetry: { Task { await viewModel.retryHermesFailedTurn() - // A canonical cut that went through without its send leaves the prompt to send again. if let unsent = viewModel.takeUnsentHermesEdit() { restoreUnsentEdit(unsent) } } } ) } - /// What ⌘⇧S and the header's Screen button open while this chat is on screen (#1633, #1640): its - /// card's Screen, except while the chat shows that the host doesn't serve its Profile. private var screenShortcut: BotScreenOpener? { viewModel.errorUnserved == nil ? openBotScreen : nil } - /// The header's Screen button (#1640), last among the trailing actions so the others don't - /// move when the beta is on. Opens the Screen to watch, like the card's Open. private func screenButton(_ open: BotScreenOpener) -> some View { Button { open(takingOver: false) } label: { Label("Screen", systemImage: "display") @@ -2436,15 +2161,11 @@ struct ChatView: View { .accessibilityLabel("Screen") } - /// A Hermes chat's Screen card (#1632, #1633), while the Bots home or `SessionScreenModifier` - /// offers its Screen (`openBotScreen`). private var botScreenCard: BotScreenCard? { guard let openBotScreen, !viewModel.isViewingCachedData, let use = viewModel.hermesScreenUse else { return nil } return BotScreenCard(use: use, open: { openBotScreen(takingOver: false) }, takeOver: { openBotScreen(takingOver: true) }) } - /// Serve Every Profile for `profile`, from the chat's error (#1611). The chat loads again once - /// the gateway serves it. @ViewBuilder private func serveEveryProfileSheet(_ profile: String) -> some View { if let connection = try? BotConnectionStore().load(server: server) { @@ -2597,7 +2318,6 @@ struct ChatView: View { delegatedWork: delegatedWork, onOpenDelegatedWork: openDelegatedWork ) - // Off the main body chain, which is at the type-checker's limit. .onChange(of: viewModel.latestRunOutcome) { handleLatestRunOutcomeChange(viewModel.latestRunOutcome) } @@ -2622,37 +2342,15 @@ struct ChatView: View { await loadSkillSuggestionsForTranscriptChipsIfNeeded() } .task(id: transcriptFileChipScanToken) { - // The draft is read here, not in body, so a keystroke never re-runs - // this screen. Draft edits trigger their own scan from the composer. await viewModel.loadFileChipReferences(draft: draftMessage) } } - /// Changes whenever the transcript has new text that could name a workspace - /// file, or whenever the answers already given have been thrown away: the - /// transcript grew, was swapped for the server's copy (which can rewrite a - /// message in the middle without changing the count or the last id), or the - /// workspace moved. Leaving the offline cache also changes it, so a draft - /// typed offline is confirmed on reconnect. The composer asks for a scan - /// when the draft gains or loses a finished `@…`. - /// - /// Everything here is O(1), because it runs on every transcript update, - /// including each token of a live stream. The scan of the transcript itself - /// is the view model's, and it skips candidates the server has already - /// answered for. private var transcriptFileChipScanToken: [Int] { [viewModel.messages.count, viewModel.transcriptRevision, viewModel.fileChipScopeRevision, viewModel.showsOfflineCache ? 1 : 0] } - /// How many sent messages look like they name a skill. - /// - /// It is both the trigger and the task's identity, so a cache-first - /// transcript that swaps in the server's messages still warms the list when - /// the count of messages did not change but their text did. Zero once the - /// list has loaded or this chat has already asked, which is what keeps the - /// scan off the streaming path. Zero while offline too, so the ask waits - /// for the reconnect. private var transcriptSkillReferenceCount: Int { guard !hasRequestedSkillsForTranscriptChips, !viewModel.hasLoadedSkillSlashSuggestions, !viewModel.showsOfflineCache else { @@ -2667,25 +2365,14 @@ struct ChatView: View { } } - /// A sent message draws its skill reference as a chip only for skills the - /// app has heard of, so a transcript that names one warms the skill list the - /// way a restored draft does — and a chat that never mentions a skill still - /// costs no skills request. private func loadSkillSuggestionsForTranscriptChipsIfNeeded() async { guard transcriptSkillReferenceCount > 0 else { return } await viewModel.loadSkillSlashSuggestions() - // One ask per chat. A skills request that failed must not turn every - // later transcript update into another one; typing `/` in the composer - // still retries on the reader's behalf. Set after the wait so a - // cancelled task leaves the chat free to ask again. hasRequestedSkillsForTranscriptChips = true } - /// The chat-canvas layout direction. Driven by the manual Settings → Chat - /// RTL toggle (#259); applied only to the transcript + composer so the - /// sidebar, settings, and navigation chrome stay in the default direction. private var chatLayoutDirection: LayoutDirection { ChatTranscriptDisplaySettings.chatLayoutDirection(rtlEnabled: rtlChatLayoutEnabled) } @@ -2694,8 +2381,6 @@ struct ChatView: View { viewModel.followLatch.isFollowing } - /// Automatic follows run only while the latch is on and no disclosure - /// toggle is mid-animation. private var isFollowingLatestContent: Bool { shouldFollowLatestMessage && !isDisclosureSettling } @@ -2724,10 +2409,6 @@ struct ChatView: View { composerHeight + 12 + composerAccessorySpacerHeight + clarificationFootprintHeight } - /// Bar height plus its gap above the composer while a clarification is - /// pending. Constant across expand and collapse, so the transcript never - /// moves while the card animates. A Hermes `/btw` card or line adds its own - /// height, so the live tail streams above it (#1013). private var clarificationFootprintHeight: CGFloat { let request = requestInsetID == nil ? 0 : clarificationBarHeight + 8 return request + (viewModel.hermesSideTasks?.btw == nil ? 0 : btwInsetHeight + 8) @@ -2767,8 +2448,6 @@ struct ChatView: View { height += hostNoticeHeight } if activeRunStatusPresentation != nil { - // The measured pill plus one accessory gap: 36 pt at the default - // size, and a full wrapped pill at accessibility sizes. height += activeRunStatusHeight + composerAccessoryVerticalSpacing } if pinnedPlan != nil { @@ -2817,8 +2496,6 @@ struct ChatView: View { private var headerSubtitle: String? { ChatToolbarSubtitleResolver.subtitle( - // The row's folder stands in until the host names the session's, so the line is - // whole from the first frame. workspacePath: viewModel.selectedWorkspacePath ?? hermesRowWorkspace, profileTitle: viewModel.selectedProfileTitle ) @@ -2848,10 +2525,6 @@ struct ChatView: View { transcriptMessages } - /// Settled-turn folds and the replies that close settled turns, derived again only when - /// the transcript's structure or an input below changes, so a text-only reveal tick reuses - /// them (#1417). Activity anchors count only while thinking and tool cards are shown, so - /// a turn with nothing visible to hide gets no fold. private var transcriptStructure: TranscriptStructureMemo.Structure { let activityAnchorIDs: Set = thinkingAndToolCards.showsCards ? Set(viewModel.displayedReasoningGroups.compactMap(\.anchorMessageID)) @@ -2899,7 +2572,6 @@ struct ChatView: View { } } - /// Failed or stopped turns start open so the work that went wrong is in view. private func handleLatestRunOutcomeChange(_ outcome: TranscriptTurnRunOutcome?) { guard let outcome, outcome.ending != .completed else { return } viewModel.expandedTurnKeys.insert(outcome.turnKey) @@ -2913,7 +2585,6 @@ struct ChatView: View { transcriptMessages.last?.message.role } - /// A view a size-class change rebuilt keeps its predecessor's transcript, older pages included. private var needsInitialMessages: Bool { loadsInitialMessages && !continuity.didLoadMessages } @@ -2929,8 +2600,6 @@ struct ChatView: View { await hydrateDraftIfNeeded() prepareInitialAppearance() - // Keeps transcript reconciliation and other state-heavy startup work out of the - // system navigation transition; the cache and the transcript request went out above. guard didCompleteInitialAppearance else { return } async let chatStartup: Void = performInitialAsyncWork() @@ -2953,8 +2622,6 @@ struct ChatView: View { isInitialComposerFocusContentReady = true applyInitialComposerFocusPolicyIfNeeded() } - // Approval and YOLO state are session-scoped, so they load alongside the - // profile-scoped composer config instead of waiting behind it (#678). async let approvalBypassRefresh: Void = viewModel.refreshApprovalBypassState() await viewModel.loadComposerConfiguration() if !Task.isCancelled { @@ -2975,8 +2642,6 @@ struct ChatView: View { } } - /// Ends this session's `Session Open` interval on the next main-queue turn, so - /// it includes the layout of the first transcript frame (or the empty state). private func endSessionOpenSignpost() { let sessionID = hermesSessionChatID ?? session.sessionId let messages = viewModel.messages.count @@ -2985,9 +2650,6 @@ struct ChatView: View { } } - /// A fresh Git state for the chat's repository: webui's session, or a Hermes chat's folder - /// while Files can read it (#1114), which syncs only through hermex-push (#1236). Without one, - /// Git stays hidden. private func loadInitialGitAvailability() async { let availabilityViewModel = if isHermesSession { GitWorkspaceAvailabilityViewModel(git: browsableHermesWorkspace == nil ? nil : viewModel.hermesWorkspaceGit) @@ -3003,7 +2665,6 @@ struct ChatView: View { currentGoal: viewModel.currentGoal, isViewingCachedData: viewModel.isViewingCachedData, isSetGoalDisabled: isGoalActionDisabled, - // A Hermes session's goal turns keep it busy, so its commands work mid-turn (#1013). isActionDisabled: isHermesSession ? viewModel.isViewingCachedData || viewModel.isSubmittingGoal : isGoalActionDisabled, @@ -3014,13 +2675,11 @@ struct ChatView: View { Task { await submitGoalCommand(command) } }, automations: viewModel.hermesSideTasks?.automations ?? [], - // Pause and Resume show only where the host takes `session.control` (#508). allowsAutomationChanges: viewModel.hermesSideTasks?.controlsAutomations == true, isAutomationDisabled: viewModel.isViewingCachedData || viewModel.hermesSideTasks?.isChangingAutomation == true || viewModel.hermesSideTasks?.canChangeAutomations == false, onChangeAutomation: { viewModel.hermesSideTasks?.ask($0) } ) - // On the menu, so the iPad popover points at the Goal button. .modifier(HermesAutomationConfirmationModifier( sideTasks: viewModel.hermesSideTasks, onConfirm: { control in Task { await viewModel.confirmHermesAutomation(control) } @@ -3050,7 +2709,6 @@ struct ChatView: View { let signpost = performanceSignposter.beginInterval("Load Earlier") let didLoad = await viewModel.loadOlderMessages(modelContext: modelContext) let messages = viewModel.messages.count - // The next main-queue turn, so the interval includes the prepended rows' layout. DispatchQueue.main.async { performanceSignposter.endInterval("Load Earlier", signpost, "messages=\(messages, privacy: .public)") } @@ -3086,7 +2744,6 @@ struct ChatView: View { Task { await clearConversation(pending) } } - /// Sends a confirmed `/personality` change (#1016). Its command already left the composer. private func confirmHermesPersonality(_ name: String) { Task { let result = await viewModel.confirmHermesPersonality(name) @@ -3095,7 +2752,6 @@ struct ChatView: View { } } - /// Sends a confirmed `/rollback` restore (#1728). Its command already left the composer. private func confirmHermesRollback(_ request: HermesRollbackRequest) { Task { let result = await viewModel.confirmHermesRollback(request) @@ -3118,10 +2774,6 @@ struct ChatView: View { } } - /// Sends the composer's draft. A send during a run uses `behavior`, or the - /// Send While Responding setting when it is nil (a run that started after the - /// composer last drew Send): Send passes the behavior it shows, a long-press - /// picks one for this message, and Retry after a refused steer forces `.steer`. private func sendDraftMessage(behavior: StreamingSendBehavior?) async { viewModel.clearSteerFailure() let submittedContent = ComposerDraftContent(text: draftMessage, quotes: draftQuotes) @@ -3144,8 +2796,6 @@ struct ChatView: View { } } - // A Hermes chat runs `/` text through its own commands and its host's (#1036); a name - // neither knows is sent as typed. if isHermesSession, submittedContent.quotes.isEmpty, let result = await viewModel.runHermesSlashCommand(submittedDraft, modelContext: modelContext) { let name = BotSlashCatalog.invocation(in: submittedDraft)?.name ?? "" @@ -3155,8 +2805,6 @@ struct ChatView: View { submittedDraft: submittedDraft, submittedDraftRevision: submittedDraftRevision ) - // A canonical `/retry` whose cut went through without its send: the prompt takes the - // command's place, or joins what was typed since. if let unsent = viewModel.takeUnsentHermesEdit() { if draftRevision == submittedDraftRevision { draftMessage = unsent @@ -3175,11 +2823,6 @@ struct ChatView: View { if submittedContent.quotes.isEmpty, submittedDraft.trimmingCharacters(in: .whitespacesAndNewlines).hasPrefix("/"), !isHermesSession { - // `/clear` wipes the conversation on the server, so it always asks - // first. The draft stays in the composer until the user confirms. - // A refusal the app already knows about (cached view, CLI session, - // live stream) skips the alert and falls through to the normal - // slash path, which surfaces it. if parsedCommand?.handler == .clientSide(.clear), viewModel.clearConversationRefusal == nil { pendingClearConfirmation = PendingClearConfirmation( draft: submittedDraft, @@ -3277,16 +2920,11 @@ struct ChatView: View { } } - /// Sends the composer's content when no response runs. Plain text in a Hermes chat may wait for - /// the reconnect (#1407): the composer clears as for a send, but nothing claims the host took it. private func sendStandardMessage( _ submittedContent: ComposerDraftContent, outboundMessage: String, submittedDraftRevision: Int ) async -> ChatSendOutcome { - // Attachment-only sends (empty text and quotes) flow through; the view - // model synthesizes their message text. Clearing the captured composer - // content below is the correct end state after sending. let hasStagedAttachments = !viewModel.pendingAttachments.isEmpty let trimmedMessage = outboundMessage.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmedMessage.isEmpty || hasStagedAttachments else { @@ -3296,10 +2934,6 @@ struct ChatView: View { prepareTranscriptForExplicitSend() - // Reconcile against what the composer actually staged, not against the - // draft's whole record set. A record that is not staged — awaiting a - // re-upload retry, or not yet reached by an in-flight restore — was - // never carried by this send, so its durable copy must survive. let sendReconciliation = ChatDraftSendReconciliation.outcome( draftRecords: lastSyncedDraftAttachments, stagedAttachmentIDs: Set(viewModel.pendingAttachments.map(\.id)) @@ -3309,7 +2943,6 @@ struct ChatView: View { draftQuotes = [] let outcome = await viewModel.send(outboundMessage, isPlainText: isPlainText, modelContext: modelContext) - // A waiting send left the composer as a sent one does; the view model holds its text. let didStart = outcome != .kept if outcome == .started { onConversationStarted() } if didStart { @@ -3327,10 +2960,6 @@ struct ChatView: View { draftMessage = resolvedContent.text draftQuotes = resolvedContent.quotes if didStart { - // `resolveSubmission` cleared the draft's attachment records; put - // back the ones the send never carried so they retry on a later - // open. Deterministic here rather than waiting on the observation - // sync that the emptied composer strip will also trigger. syncDraftAttachments() if outcome == .started { offerNotificationsIfNeeded() } } @@ -3349,8 +2978,6 @@ struct ChatView: View { syncDraftAttachments() } ) { - // The destination owns the retained work now; don't show a second - // unsent copy when the user returns to the sealed parent. if textOrigin != nil { dismissShortcutNotice() } draftMessage = "" draftQuotes = [] @@ -3361,11 +2988,6 @@ struct ChatView: View { } } - /// Asks once per install, right after a normal send or voice note started a run, whether - /// the user wants to hear when it ends (#863). Steers, queued messages and slash commands - /// never get here, and a failed send never started a run, so none of them use it up. - /// Runs beside the send, so its permission check never delays the send's haptic or - /// composer focus; `isCurrent` keeps a chat that closed meanwhile from claiming it. private func offerNotificationsIfNeeded() { guard isOnScreen else { return } Task { @@ -3418,7 +3040,6 @@ struct ChatView: View { ) } case .replacedHermesSession(let chat): - // The command leaves this chat's draft first; anything else in it stays here. if consumesDraft { reconcileConsumedDraft( ComposerDraftContent(text: submittedDraft, quotes: submittedQuotes), @@ -3435,7 +3056,6 @@ struct ChatView: View { } if let onOpenHermesSessions { onOpenHermesSessions(entry) } else { pushedHermesSessionList = entry } case .prefill(let text): - // Unless the user typed on meanwhile: their edit wins. if draftRevision == submittedDraftRevision { draftMessage = text persistDraftEdit(text) @@ -3452,8 +3072,6 @@ struct ChatView: View { case .needsSubArg: viewModel.setSendErrorMessage(String(localized: "Choose a slash command or continue typing.")) case .sendAsMessage, .notDelivered: - // `.notDelivered` keeps the draft; the view model already set the - // status line that says why. break } } @@ -3487,10 +3105,6 @@ struct ChatView: View { ) } - /// Records a draft edit the user made, after it lands in `draftMessage`: - /// clears a "Couldn't steer" status, bumps the revision a failed send - /// checks before restoring, and persists the draft. Writes that are not the - /// user's (clearing on send, restoring, hydrating) skip it. private func persistDraftEdit(_ text: String) { viewModel.clearSteerFailure() textBeforeHiddenRemoval = nil @@ -3531,7 +3145,6 @@ struct ChatView: View { draftQuotes == quotesBeforeHydration else { return } - // A send still waiting when the app quit comes back for a deliberate Send, never on its own (#1407). let returnedWaitingSend = viewModel.waitingSend == nil ? persistedDraft?.waitingSend?.text : nil if returnedWaitingSend != nil { persistedDraft = draftStore.returnWaitingSend(for: draftKey) } if textBeforeHydration.isEmpty { @@ -3553,8 +3166,6 @@ struct ChatView: View { restoredDraftSettings = persistedDraft?.settings lastSyncedDraftAttachments = persistedDraft?.attachments ?? [] if let persistedDraft, !persistedDraft.attachments.isEmpty { - // Hold the sync gate now and restore later: re-uploading staged - // files is network work and must not delay the transcript. isRestoringDraftAttachments = true draftAttachmentsAwaitingRestore = persistedDraft.attachments } @@ -3567,14 +3178,6 @@ struct ChatView: View { await restoreDraftAttachments(records) } - /// Rebuilds the composer's staged attachments from a persisted draft by - /// re-uploading each record's durable local copy against this session (a - /// Hermes session only stages it again; its send uploads it). The - /// persisted server path is never trusted: uploads live in a per-session - /// inbox the server deletes with the session, so only the app-owned copy - /// is a sound restore source. Records whose copy is missing are dropped - /// (with a notice); records whose re-upload fails stay in the draft and - /// retry on a later open. The rest of the draft loads either way. private func restoreDraftAttachments(_ records: [ChatDraftAttachment]) async { var pendingRetry: [ChatDraftAttachment] = [] var unrecoverableCount = 0 @@ -3582,20 +3185,12 @@ struct ChatView: View { for (offset, record) in records.enumerated() { if Task.isCancelled { - // Leaving the chat mid-restore is not a restore failure. Every - // record from here on is untried, so carry the whole remainder - // into the retry set: the sync below is authoritative, and - // anything missing from it would be dropped from the draft and - // later swept from disk. wasCancelled = true pendingRetry.append(contentsOf: records[offset...]) break } - // A model a size-class change kept still holds it (#1528). if viewModel.pendingAttachments.contains(where: { $0.id == record.id }) { continue } guard let fileName = record.file else { - // Tolerate an older or partially corrupt record that predates - // the durable-staging invariant. unrecoverableCount += 1 continue } @@ -3604,8 +3199,6 @@ struct ChatView: View { do { data = try await draftAttachmentStore.data(named: fileName) } catch { - // Only a copy that is genuinely gone is dropped. Any other - // read failure keeps the record so a later open can retry it. switch ChatDraftAttachmentReadFailure.classify(error) { case .unrecoverable: unrecoverableCount += 1 @@ -3622,12 +3215,8 @@ struct ChatView: View { isRestoringDraftAttachments = false draftAttachmentsPendingRetry = pendingRetry - // Authoritative sync after restore: persists the restored set plus the - // retry union, and drops unrecoverable records from the draft. syncDraftAttachments() - // Report only a real restore outcome. A cancelled pass has nothing to - // say, and its view is going away regardless. guard !wasCancelled else { return } if !pendingRetry.isEmpty || unrecoverableCount > 0 { viewModel.setUploadAttachmentError( @@ -3636,9 +3225,6 @@ struct ChatView: View { } } - /// Copy uses catalog plural variations rather than a hand-branched - /// singular/plural, so languages whose plural rules differ from English - /// still read correctly. The mixed case avoids a two-number sentence. private func draftRestoreFailureMessage(retryCount: Int, droppedCount: Int) -> String { switch (retryCount > 0, droppedCount > 0) { case (true, false): @@ -3650,17 +3236,8 @@ struct ChatView: View { } } - /// Mirrors the composer's staged attachments into the persisted draft. - /// Restored records whose re-upload failed are unioned back in so a - /// mid-restore or post-restore sync can't silently drop them. Gated during - /// hydration/restore so an empty or partial composer never overwrites the - /// persisted set. Records this composer never saw (a share moved in, #1181) - /// stay in the draft. private func syncDraftAttachments() { guard didHydrateDraft, !isRestoringDraftAttachments else { return } - // Only records backed by a durable copy are persisted. Without one the - // record could never be restored, and keeping it would hold the draft - // alive just to report the attachment as lost on the next open. let pendingRecords = viewModel.pendingAttachments .map(ChatDraftAttachment.init(pending:)) .filter { $0.file != nil } @@ -3672,19 +3249,11 @@ struct ChatView: View { lastSyncedDraftAttachments = records } - /// Snapshots the effective composer settings into the draft whenever they - /// change. Only new-chat contexts snapshot: an existing session's - /// configuration is owned by the server and is never re-applied from a - /// draft, so persisting it would just store choices at rest that nothing - /// reads. Snapshotting here is what lets an abandoned new chat carry its - /// model/workspace/profile/reasoning picks to the next new chat. private func syncDraftSettings(_ settings: ChatDraftSettings) { guard didHydrateDraft, restoresDraftSettings else { return } draftStore.setSettings(settings, for: draftKey) } - /// The composer choices that make up a draft's settings snapshot, as one - /// Equatable value so a single `onChange` covers all five. private var currentComposerSettings: ChatDraftSettings { ChatDraftSettings( modelID: viewModel.selectedModelID, @@ -3695,8 +3264,6 @@ struct ChatView: View { ) } - /// New-chat only. The view owns the one-shot restore trigger while the - /// model owns validation, interaction fencing, and profile ordering. private func applyRestoredDraftSettingsIfNeeded( expectedInteractionGeneration: Int ) async { @@ -3732,21 +3299,13 @@ struct ChatView: View { requestComposerFocusIfPossible() } - /// Moves messages queued behind the run into this chat's draft when the - /// chat is left or covered (#857): a suspended stream can't send them, so - /// the user reviews and sends them on return. The composer takes the merged - /// text and files too, so a covered chat shows them when it comes back and - /// its next keystroke can't overwrite the stored merge. private func parkQueuedMessages() { let queued = viewModel.takeQueuedMessages() guard !queued.isEmpty, - // Nil when the session was just deleted: there is no draft to show. let parked = draftStore.parkQueuedMessages(queued, for: draftKey) else { return } - // Not the user's edit, but a send still in flight must not clear it. draftRevision &+= 1 draftMessage = parked.text - // The composer now knows the parked files, so removing one sticks. lastSyncedDraftAttachments = parked.attachments viewModel.appendPendingAttachments(queued.flatMap(\.attachments)) } @@ -3757,8 +3316,6 @@ struct ChatView: View { } } - /// Stop. On a Hermes session holding a queued prompt or an open request it asks first, - /// since the stop discards the one and denies the other. private func cancelStream() async { if viewModel.stopNeedsConfirmation { showsStopConfirmation = true @@ -3794,15 +3351,10 @@ struct ChatView: View { } } - /// The "Forked from" row this chat draws. A Hermes branch's comes from its host, which the - /// view model asks again on a later connect when the first attach failed (#1051). private var shownForkOrigin: ForkOrigin? { isHermesSession ? viewModel.hermesForkOrigin : forkOrigin } - /// Reads the parent's title from the active server's session cache, which - /// the session list writes on every load. Only forks do the lookup. A Hermes - /// branch asks its host instead (#1051). private func resolveForkOrigin() async { if isHermesSession { await viewModel.checkHermesForkParent(hermesParentKey) @@ -3816,8 +3368,6 @@ struct ChatView: View { forkOrigin = ForkOrigin.resolve(session: session, parent: parent) } - /// Pushes the fork's parent: the cached one at once, otherwise after - /// fetching it. A failed fetch shows the message-action error and stays here. private func openForkParent() { guard let forkOrigin = shownForkOrigin, !isOpeningForkParent else { return } if isHermesSession { @@ -3860,9 +3410,6 @@ struct ChatView: View { } } - /// A new Hermes chat in `profile` (#1015), remembered for this server's next New Session. - /// A session's Profile never changes on the host. `replacing` a chat with nothing sent - /// carries its draft over; otherwise the new chat opens on top of this one. private func startHermesSession(in profile: ProfileSummary, replacing: Bool) { pendingProfileSelection = nil guard let name = profile.normalizedName, let chat = viewModel.newHermesSessionChat(profile: name) else { return } @@ -4069,8 +3616,6 @@ struct ChatView: View { return PastedFile(data: data, filename: filename) } - /// Refuses a file over the chat's limit before reading it: 20 MB on a webui session, - /// Bot Chat's 25 MB on a Hermes session (#1012). private func validateAttachmentSize(for url: URL) throws { let values = try url.resourceValues(forKeys: [.fileSizeKey]) guard let size = values.fileSize, @@ -4147,8 +3692,6 @@ struct ChatView: View { switch phase { case .background: if isHermesSession { - // The app closes the gateway socket in the background (#902); the turn - // runs on, and returning reattaches to it. viewModel.suspendStreamForBackground() } else if viewModel.activeStreamID != nil { beginResponseCompletionBackgroundTask() @@ -4171,8 +3714,6 @@ struct ChatView: View { } } - /// The network came back or moved to another interface: retry a suspended - /// stream now instead of waiting for a foreground or reopen (#869). private func handleNetworkPathChange() { Task { await viewModel.networkPathDidChange(modelContext: modelContext) @@ -4194,11 +3735,6 @@ struct ChatView: View { endResponseCompletionBackgroundTask() } - // The agent may have edited files this turn, so refresh git state (status, - // ahead/behind, branch) once the response finishes — keeps the toolbar badge, - // Changes row, and commit surfaces in sync without re-entering the chat. - // Run unconditionally: refreshAfterExternalMutation re-checks /api/git-info first, - // so it also detects a repo the agent just created (git init/clone) mid-turn. Task { await gitAvailabilityViewModel.refreshAfterExternalMutation() } return } @@ -4237,10 +3773,6 @@ struct ChatView: View { ChatHaptics.assistantResponseCompleted(isEnabled: isHapticsEnabled) } - /// Alerts once for a run that completed or failed while the scene was not active, - /// then releases the background task that kept the stream alive for it. A newer - /// run end in this chat supersedes one still waiting on its transcript load: the - /// newer alert stands, and the newer task releases the background task. private func handleRunEnd() { guard let runEndContext = responseCompletionNotificationTracker.completionContext( runEndTrigger: viewModel.runEndTrigger, @@ -4279,8 +3811,6 @@ struct ChatView: View { } } - /// A background completion waits for activation without consuming the run's - /// permission. Hydration and activation can finish in either order. private func scrollToHydratedCompletionIfReady() { guard isOnScreen, viewModel.activeStreamID == nil, viewModel.errorMessage == nil, @@ -4323,9 +3853,6 @@ struct ChatView: View { } private func scrollToBottom(_ proxy: ScrollViewProxy) { - // Deliberate jump to the latest content. Snap without animation while a - // response is streaming so the tap lands immediately instead of racing - // the short follow animations already chasing incoming tokens. ChatHaptics.scrolledToLatest(isEnabled: isHapticsEnabled) scrollToLatestContent( proxy, @@ -4355,8 +3882,6 @@ struct ChatView: View { animated: Bool = true, isUserInitiated: Bool = false ) { - // An empty chat still draws the transcript for a queued prompt (#1379), a waiting send (#1407) - // or live workers. guard !viewModel.messages.isEmpty || !viewModel.queuedPromptMessages.isEmpty || viewModel.lostTurn != nil || viewModel.waitingSendMessage != nil || (delegatedWork?.activeCount ?? 0) > 0 else { return } @@ -4376,9 +3901,6 @@ struct ChatView: View { animated: Bool, isUserInitiated: Bool ) { - // Explicit jumps re-arm the follow latch; automatic follows (streaming - // tokens, new rows) only run while the latch is already on and no - // disclosure toggle is settling. if isUserInitiated { handleFollowEvent(.reset) } else if !isFollowingLatestContent { @@ -4392,16 +3914,9 @@ struct ChatView: View { await Task.yield() try? await Task.sleep(nanoseconds: 16_000_000) guard !Task.isCancelled, generation == followScrollGeneration else { return } - // Re-check at fire time: a drag or a disclosure toggle may have - // begun during the delay. if !isUserInitiated, !isFollowingLatestContent { return } - // Snap (no animation) while inside the cache-first reconcile window so the - // taller server transcript replacing the cached one doesn't animate a jump - // (#289). Evaluated at fire time so it's robust to onChange ordering. let isCacheFirstSnapWindow = cacheFirstSnapUntil.map { Date() < $0 } ?? false - // Following a live stream snaps too: updates land every ~48 ms, so - // an animated follow is cut off by the next one and never settles. if animated, !isCacheFirstSnapWindow, viewModel.activeStreamID == nil { withAnimation(ChatMotion.scrollToLatest(reduceMotion: reduceMotion)) { proxy.scrollTo(targetID, anchor: anchor) @@ -4487,10 +4002,6 @@ struct ChatView: View { } } - /// Suspends follow scrolls and the bottom anchor through a disclosure - /// animation; the transcript view pins the offset itself. The latch is - /// untouched, so the next streaming trigger catches up once the toggle has - /// settled. private func handleDisclosureToggle() { completionScrollPolicy.readerDidInteract() completedResponseRenderID = nil @@ -4498,7 +4009,6 @@ struct ChatView: View { suspendBottomAnchorForDisclosure() } - /// One tick per view-model bump; the view model already throttles and skips replay. private func handleStreamingHapticPulse() { ChatHaptics.streamingPulse(isEnabled: isHapticsEnabled && isStreamingPulseEnabled) } @@ -4587,8 +4097,6 @@ struct ChatView: View { } } - /// Puts a Hermes edit that did not go through back in the composer (#1049), after any draft - /// already there, so neither is lost. private func restoreUnsentEdit(_ text: String) { let draft = draftMessage.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? text : "\(draftMessage)\n\n\(text)" draftMessage = draft @@ -4607,7 +4115,6 @@ struct ChatView: View { return withHermesCutNote(String(localized: "Regenerating this response will discard \(messagesAfter) later messages.")) } - /// A Hermes host's cut is permanent and every app sees it (#1049), so its warning says so. private func withHermesCutNote(_ warning: String) -> String { guard isHermesSession else { return warning } return warning + "\n\n" + String(localized: "The Hermes host removes them for every app. It can't be undone.") @@ -4681,11 +4188,6 @@ struct ChatToolbarActionCluster: View { } } -/// On iOS 26+ the navigation toolbar already renders this trailing item inside a -/// Liquid Glass pill, so styling the cluster ourselves stacked a second capsule -/// and produced the double border reported in #333. Its padding is ours too: on iOS 26 it -/// stretched a lone 44pt button's round glass into an oval beside the round back button. -/// Below iOS 26 the system supplies no pill, so we keep the original material capsule there. private struct LegacyToolbarClusterStyle: ViewModifier { @Environment(\.colorScheme) private var colorScheme @@ -4733,7 +4235,6 @@ struct ChatToolbarActionSlot: View { } enum ChatToolbarSubtitleResolver { - /// `hermes · Default`: the workspace and the Profile, whichever of them there is. static func subtitle(workspacePath: String?, profileTitle: String?) -> String? { let workspace = nonEmpty(workspacePath)?.lastPathComponentFallback let profile = nonEmpty(profileTitle).flatMap { $0 == "Profile" ? nil : $0 } @@ -4748,15 +4249,11 @@ enum ChatToolbarSubtitleResolver { } } -/// The draft that raised the destructive `/clear` confirmation, so confirming -/// consumes exactly the text that was sent and cancelling leaves it alone. private struct PendingClearConfirmation: Equatable { let draft: String let draftRevision: Int } -/// The `/clear` confirmation, in its own modifier so `ChatView.body`'s alert -/// chain stays inside the compiler's type-checking budget. private struct ClearConversationAlertModifier: ViewModifier { @Binding var pending: PendingClearConfirmation? let isHapticsEnabled: Bool @@ -4789,8 +4286,6 @@ private struct ClearConversationAlertModifier: ViewModifier { } } -/// Asks before a Stop that would lose something: a Hermes session's queued prompt, which -/// the host discards, or its open request, which it denies (#1010). private struct StopConfirmationModifier: ViewModifier { @Binding var isPresented: Bool let onStop: () -> Void @@ -4838,9 +4333,6 @@ private extension SlashCommandExecutionResult { } } -/// Mirrors composer state into the persisted draft. Extracted from `ChatView`'s -/// modifier chain: folding these two observers into one modifier keeps the -/// chain within the Swift type-checker's budget. private struct ChatDraftSyncModifier: ViewModifier { let pendingAttachments: [PendingAttachment] let composerSettings: ChatDraftSettings @@ -4858,10 +4350,6 @@ private struct ChatDraftSyncModifier: ViewModifier { } } -/// Covers the transcript behind the Chat title before iOS 26. iOS 26+ leaves the bar -/// transparent and relies on the transcript's native scroll-edge effect, which runs to -/// the screen's top edge; a forced bar background stops at the bar and leaves a gap -/// wherever no status bar sits above it, such as the folded iPhone Duo. struct ChatNavigationBackground: ViewModifier { func body(content: Content) -> some View { if #available(iOS 26, *) { @@ -4874,8 +4362,6 @@ struct ChatNavigationBackground: ViewModifier { } } -/// The host's expensive-model question for a Hermes session's model pick (#1015), as Bot -/// Chat asks it: Change model resends the pick confirmed, Cancel sends nothing. struct HermesModelConfirmationModifier: ViewModifier { let controls: BotChatControls? @@ -4885,7 +4371,6 @@ struct HermesModelConfirmationModifier: ViewModifier { set: { if !$0 { controls?.cancelConfirmation() } } ), titleVisibility: .visible) { if let controls, let confirmation = controls.confirmation { - // Dismissing clears `confirmation`, so the pending pick is captured first. Button("Change model") { controls.cancelConfirmation() Task { await controls.confirm(confirmation) } @@ -4899,8 +4384,6 @@ struct HermesModelConfirmationModifier: ViewModifier { } } -/// The one confirmation a Hermes session's loop or heartbeat Pause or Resume asks in the goal -/// menu (#1142), in Bot Chat's words. A reattach drops it unsent. private struct HermesAutomationConfirmationModifier: ViewModifier { let sideTasks: HermesChatSideTasks? let onConfirm: (BotSessionControl) -> Void @@ -4910,7 +4393,6 @@ private struct HermesAutomationConfirmationModifier: ViewModifier { get: { sideTasks?.pendingAutomation != nil }, set: { if !$0 { sideTasks?.cancelAutomation() } } ), titleVisibility: .visible) { - // Dismissing clears the ask, so the button carries its control. if let control = sideTasks?.pendingAutomation { Button(control.actionTitle) { onConfirm(control) } } @@ -4921,8 +4403,6 @@ private struct HermesAutomationConfirmationModifier: ViewModifier { } } -/// The Profile-wide question a Hermes session's `/personality ` asks first (#1016): the -/// host has no session-only personality, so the change reaches every new chat in the Profile. private struct HermesPersonalityConfirmationModifier: ViewModifier { let settings: HermesChatSettings? let profile: String @@ -4943,7 +4423,6 @@ private struct HermesPersonalityConfirmationModifier: ViewModifier { ) ) { Button("Cancel", role: .cancel) { settings?.cancelPersonality() } - // Dismissing clears the pending name, so the button captures it first. if let name = settings?.pendingPersonality { Button(confirm) { settings?.cancelPersonality() @@ -4956,8 +4435,6 @@ private struct HermesPersonalityConfirmationModifier: ViewModifier { } } -/// What a Hermes chat's `/rollback N [file]` asks first (#1728): the checkpoint by its time and -/// the host's reason, and what the restore overwrites. private struct HermesRollbackConfirmationModifier: ViewModifier { let pending: HermesRollbackRequest? let onCancel: () -> Void @@ -4986,8 +4463,6 @@ private struct HermesRollbackConfirmationModifier: ViewModifier { } } -/// One Hermes native preview presentation, for a sent chip or a MEDIA document. A sent chip's -/// path downloads from the host even when it is a URL (`BotArtifactReference`). private struct HermesFilePreviewItem: Identifiable { let id = UUID() let reference: TranscriptMediaReference diff --git a/HermesMobile/Features/Chat/ChatViewModel.swift b/HermesMobile/Features/Chat/ChatViewModel.swift index a384fd932..9b807e70b 100644 --- a/HermesMobile/Features/Chat/ChatViewModel.swift +++ b/HermesMobile/Features/Chat/ChatViewModel.swift @@ -154,8 +154,6 @@ struct ApprovalPromptState: Equatable, Identifiable { pending.displayPatternKeys } - /// What Allow session and Always allow cover on this webui server. The - /// card always offers both. var scopeLine: AttributedString? { ApprovalScope.line( keys: patternKeys, description: pending.description, command: pending.command, toolName: nil, host: .webui @@ -189,8 +187,6 @@ struct ChatPollingIntervals { let approvalNanoseconds: UInt64 let clarificationNanoseconds: UInt64 let backgroundNanoseconds: UInt64 - /// Waits out one interval between polls. A test passes its own, so it sees each poll go - /// back to sleep, and a cancelled one stop, instead of timing them. var sleep: @Sendable (UInt64) async -> Void = { try? await Task.sleep(nanoseconds: $0) } static let standard = ChatPollingIntervals( @@ -200,27 +196,14 @@ struct ChatPollingIntervals { ) } -/// A Hermes chat's one plain-text Send held until the chat reconnects (#1407). `ChatViewModel` -/// holds it when Send meets the offline cache, or a prompt that found no connection before it went -/// out. The draft keeps it on disk (`ChatDraft.waitingSend`) until the host answers. It goes out -/// once, on a later attach under the same draft key, with no files, and never after it expires -/// or from the background. Cancel, expiry, leaving the chat and every failure but another -/// missing connection put its text back in the composer. struct HermesWaitingSend: Equatable { - /// How long it waits before going back to the composer. static let lifetime: TimeInterval = 10 * 60 let send: ChatDraft.WaitingSend - /// The draft it was held in. It goes out only while the chat still writes there. let key: ChatDraftKey - /// The attach its last delivery tried, so only a distinct reconnect tries again. var triedAttach: Int? - /// Set while a delivery holds it: the prompt's own row shows in its place, and Cancel waits for the answer. var delivery: Delivery? - /// A delivery in flight: going out, or stopped before its socket write because the app went to - /// the background (`paused`: it waits again unless the host took it) or the chat left (`left`: - /// it goes back to the composer). enum Delivery: Equatable { case sending, paused, left } @@ -229,20 +212,16 @@ struct HermesWaitingSend: Equatable { now.timeIntervalSince(send.createdAt) >= Self.lifetime } - /// Whether a prompt that never went out failed only for lack of a connection, so it can wait for - /// one. An upload, a replaced Bot Chat, or a changed attach is not that. static func waitsForConnection(_ notSent: HermesChatTurnCoordinator.NotSent) -> Bool { guard !notSent.duringUpload, !notSent.followedReplacedChat else { return false } return notSent.underlying as? BotFailure == .transport || notSent.underlying is URLError } - /// Why it went back to the composer. enum Return: Equatable { case cancelled, expired, left, notSent } } -/// The waiting send's time: tests pass their own to expire it on cue. struct HermesWaitingSendClock { var now: @MainActor () -> Date var sleep: @MainActor (TimeInterval) async throws -> Void @@ -250,14 +229,10 @@ struct HermesWaitingSendClock { static let live = HermesWaitingSendClock(now: { Date() }, sleep: { try await Task.sleep(for: .seconds($0)) }) } -/// What a composer Send did: the server took it (`started`, which on Hermes includes a prompt the -/// host queued or steered), the draft stays (`kept`), or it waits for the reconnect (`waiting`, #1407). enum ChatSendOutcome: Equatable { case started, kept, waiting } -/// Which server runs a chat's turns: a webui session's SSE streams, or a Hermes session on -/// the gateway socket (#1010). enum ChatBackend { case webui case hermes(HermesChatTurnCoordinator) @@ -267,8 +242,6 @@ enum ActiveStreamRecoveryState: Equatable { case idle case checking case reconnecting - /// The phone is offline, so the stream waits for the network path to - /// return instead of spending its status probes (#869). case waitingForNetwork } @@ -279,125 +252,69 @@ final class ChatViewModel { private(set) var messages: [ChatMessage] = [] { didSet { - // A text-only reveal tick patches its one transcript row instead (`replaceStreamingReply`). guard !patchesStreamingReplyInPlace else { return } recomputeDisplayedTranscriptMessages() if hermesTurn != nil, !Self.onlyRepliesChanged(from: oldValue, to: messages) { updateHermesRewindableMessageIDs() } } } - /// A Hermes session's rows that offer Edit or Regenerate (#1049). Reassigned only when - /// the set changes, so a stream tick leaves every row's menu alone. private var hermesRewindableMessageIDs: Set = [] - /// The message ↑ brings back into an empty composer. Computed on demand: - /// the composer asks only when ↑ is pressed. var lastSentText: String? { ComposerRecall.lastSentText(in: messages) } - /// Memoized transcript mapping, recomputed once whenever `messages` or - /// `messagesOffset` changes. Views read this single cached value instead of - /// re-running the full classification pass on every body evaluation. private(set) var displayedTranscriptMessages: [TranscriptMessage] = [] - /// Bumped by every full transcript derivation and never by a text-only reveal tick, so a - /// view can reuse its own history-wide derivations (turn folds, end-of-turn rows) until - /// the transcript's structure changes (#1417). private(set) var transcriptStructureRevision = 0 - /// True only inside `replaceStreamingReply`, while `messages` changes without a re-derivation. @ObservationIgnored private var patchesStreamingReplyInPlace = false private(set) var isLoading = false private(set) var isLoadingOlderMessages = false private(set) var isStartingChat = false - /// True while a recorded voice note is being transcribed, uploaded, and sent. - /// Spans all three steps so the composer can show progress and disable input. private(set) var isSendingVoiceNote = false private(set) var isForkingMessage = false - /// A Hermes branch's "Forked from" row (#1051), once its host has said which session it - /// branched from (`checkHermesForkParent`). private(set) var hermesForkOrigin: ForkOrigin? - /// The row a Hermes chat opened from named a parent, and its host has not answered yet. @ObservationIgnored private var needsHermesForkCheck = false @ObservationIgnored private var isCheckingHermesForkParent = false private(set) var isEditingMessage = false private(set) var isRegeneratingMessage = false - /// An Edit, Regenerate or `/retry` is under way. On a canonical host each is a rewind, then a - /// send of its own (#1603), so a second one now could share the first one's rewind and run the - /// agent twice: it waits for this one. private var isChangingHermesHistory: Bool { isEditingMessage || isRegeneratingMessage } - /// A Hermes `/undo` (#1049) or whole-tree `/rollback` restore (#1728) is out. Send waits, - /// since each one can remove an exchange for good. private(set) var isUndoingExchange = false private(set) var isCompressingSession = false private(set) var isCancellingStream = false private(set) var isViewingCachedData = false { didSet { if !isViewingCachedData { isCachedCopyProvisional = false } } } - /// A Hermes chat's cached transcript shows because the host has yet to answer this open, not - /// because it can't be reached: still read-only, with Send held, but without the offline - /// banner. Only while `isViewingCachedData`. private(set) var isCachedCopyProvisional = false - /// The host replaced the Bot Chat (#1339): the next transcript the host gives ends with - /// the notice that says so. @ObservationIgnored private var needsReplacedChatNotice = false - /// The chat shows its offline presentation: the banner and the composer's reconnect line. var showsOfflineCache: Bool { isViewingCachedData && !isCachedCopyProvisional } var activeStreamID: String? { turn.activeStreamID } var successfulResponseCompletion: ChatStreamCoordinator.SuccessfulResponseCompletion? { turn.successfulResponseCompletion } var activeRunStartedAt: Date? { turn.activeRunStartedAt } - /// How the latest run ended, keyed to the turn it answered. Drives the - /// settled-turn fold label and which turns start expanded. private(set) var latestRunOutcome: TranscriptTurnRunOutcome? var activeStreamRecoveryState: ActiveStreamRecoveryState { turn.recoveryState } var liveTokensPerSecond: Double? { turn.liveTokensPerSecond } private(set) var errorMessage: String? { didSet { errorMayRetry = true; errorUnserved = nil } } - /// Whether the chat's error offers Try Again; false for a failure retrying can't fix. private(set) var errorMayRetry = true - /// The Profile a Webapp doesn't serve when that is the chat's error, or the composer's in a - /// chat that shows messages (#1611): its fix shows with it, and the host's own words under - /// the chat's error. Another error clears it. private(set) var errorUnserved: HermesUnservedProfile? private(set) var sendErrorMessage: String? { didSet { sendErrorIsFromStreamRecovery = false errorUnserved = nil - // Slash commands re-set the same text after a failed send; keep the kind then. if sendErrorMessage != oldValue, sendErrorRuntimeStale != nil { sendErrorRuntimeStale = nil } } } @ObservationIgnored private var sendErrorIsFromStreamRecovery = false - /// Set when the server refused a send because Hermes was updated under the - /// running WebUI (#955), so the composer can offer Copy fix prompt. A - /// different `sendErrorMessage` clears it. private(set) var sendErrorRuntimeStale: AgentRuntimeStale? private(set) var messageActionErrorMessage: String? private(set) var cacheErrorMessage: String? - /// Set while `POST /api/session/clear` is in flight. A send or a second - /// `/clear` refuses while it is set, so the clear response cannot wipe a - /// message the user started inside that window (#389). private(set) var isClearingConversation = false private(set) var lastError: Error? private(set) var displayTitle: String private(set) var listeningMessageID: String? private(set) var streamingScrollTrigger = 0 - /// Bumped when a cache-first cold open (#289) finishes reconciling the network - /// transcript over the instantly-rendered cached one. The richer server content - /// (tool-call / reasoning cards, content parts) is taller than the lighter cached - /// render, so the view re-pins to the bottom on this token *without* animation — - /// otherwise the height growth produces a visible scroll jump. - /// Bumped whenever something re-lays out the transcript under the reader - /// without adding a message: the server transcript replacing the lighter - /// cache-first render, or the skill catalog turning sent `/slug` text into - /// chips. A reader who was pinned to the bottom is put back there. private(set) var transcriptRelayoutScrollToken = 0 private var hasPrimedInitialCachedMessages = false - /// The transcript request `prepareInitialMessageLoad` sends while the push - /// transition runs, so the round trip overlaps the animation (#678). Only the - /// initial `loadMessages` may use it, and only while the active stream is the - /// one it was sent under; every other load discards it. @ObservationIgnored private var initialSessionPrefetch: InitialSessionPrefetch? @ObservationIgnored private var pendingStreamingScrollTriggerTask: Task? @ObservationIgnored private var pendingAssistantText = "" - /// Whether the last reveal tick held a trailing fragment back; the next tick - /// releases it even without new whitespace (`StreamingRevealGate`). @ObservationIgnored private var heldStreamingFragmentLastTick = false @ObservationIgnored private var pendingReasoningChunks: [String] = [] @ObservationIgnored private var pendingStreamingContentFlushTask: Task? @@ -406,24 +323,13 @@ final class ChatViewModel { private(set) var completedReasoningGroups: [ReasoningGroup] = [] { didSet { recomputeDisplayedTranscriptMessages() } } - /// Reasoning cards for the loaded transcript. Derived in - /// `recomputeDisplayedTranscriptMessages()` and reassigned only when the - /// cards change, so a stream tick or a keystroke neither re-derives them nor - /// hands the transcript rows a fresh array to compare. private(set) var displayedReasoningGroups: [ReasoningGroup] = [] - /// `displayedReasoningGroups` bucketed by anchor message ID (nil holds the - /// unanchored cards), so each transcript row receives only its own cards. private(set) var reasoningGroupsByAnchorID: [String?: [ReasoningGroup]] = [:] @ObservationIgnored private var reasoningCandidateCache = ReasoningCandidateCache() func completedToolCallGroupsForAnchor(_ anchorMessageID: String?) -> [ToolCallGroup] { completedToolCallGroupLookup.groups(anchorMessageID: anchorMessageID) } - /// Tool calls for the latest assistant turn, driving the in-chat "file changes" recap - /// card and composer "N changes" capsule (#316). A turn often spans multiple assistant - /// messages (tool calls on one, the final text on the next), and the archived tool group - /// anchors to the *first* of them — so collect every completed group in the current turn - /// (since the last user message) plus any still-live calls, not just one anchor. var latestTurnToolCalls: [ToolCall] { let turnAnchors = Set( TranscriptTurnClassifier.currentTurnAssistantAnchorIDs(in: messages, messageOffset: messagesOffset) @@ -459,36 +365,15 @@ final class ChatViewModel { ) recomputeCompressionReferenceCard() } - /// Synthesized "Context compaction · Reference only" card resolved from the - /// session's `compression_anchor_*` metadata; nil when the session has no - /// compaction metadata or the reference text is gated out. private(set) var compressionReferenceCard: CompressionReferenceCard? @ObservationIgnored private var compressionAnchorMetadata: CompressionAnchorMetadata? - /// A Hermes session's compaction, from its settled history (#1047), in place of the - /// webui's `compression_anchor_*` metadata. @ObservationIgnored private var hermesCompaction: HermesCompaction? - /// The offline cache a Hermes chat's settled history is written to and read back from - /// before its attach and while its host can't be reached (#1054, #1144), from the chat's - /// first load. @ObservationIgnored private var hermesCache: ModelContext? - /// The root this Hermes chat's cached transcript is kept under, once found: a session's - /// lineage root, or a Bot Chat's canonical root, which its attach confirms or replaces. @ObservationIgnored private var hermesCacheRoot: String? - /// An archived Bot Chat, opened by its key, keeps its cached copy under this lineage root, - /// and reads its bot's Bot Chat's copy of that root while it has none (#1144). Nil for any - /// other chat. - /// Whether the transcript follows the live edge. Here rather than in `ChatView`, so a - /// size-class change's new view knows whether the reader was up in history (#1528). var followLatch = ChatScrollPolicy.FollowLatch() - /// The turns the reader opened, here for the same reason: the row they are reading can sit - /// inside one. var expandedTurnKeys: Set = [] @ObservationIgnored var hermesBotChatRoot: String? - /// A session's lineage root as its row or link named it (`HermesSessionChat.lineageRoot`); - /// nil asks the cache. @ObservationIgnored var hermesLineageRoot: String? - /// The cache epoch this chat's attach took (`CacheStore.hermesCacheEpoch`): its writes are - /// dropped once a clear or removal moves the server's on, until the next attach. @ObservationIgnored private var hermesCacheEpoch: Int? private func applyCompressionAnchorMetadata(from session: SessionDetail?) { compressionAnchorMetadata = CompressionAnchorMetadata(from: session) @@ -499,10 +384,6 @@ final class ChatViewModel { compressionReferenceCard = nil } private func recomputeCompressionReferenceCard() { - // Not folded into the messages/messagesOffset observers alone: - // applyCompletedStreamSession can update the metadata without - // reassigning messages, so metadata changes recompute here too. The - // equality guard keeps the overlapping triggers observer-silent. let card = hermesCompaction.map { Self.hermesCompressionReferenceCard($0, messages: messages, transcriptMessages: displayedTranscriptMessages) } ?? Self.compressionReferenceCard( @@ -531,15 +412,9 @@ final class ChatViewModel { private(set) var hasOlderMessages = false private(set) var contextWindowSnapshot: ContextWindowSnapshot? private(set) var responseCompletionHapticTrigger = 0 - /// Bumps once for every run that ends completed or failed, after `runEndOutcome` - /// records which. `ChatView` turns each bump into at most one local alert and - /// keeps its background task open until then (#862). A stopped run never bumps. private(set) var runEndTrigger = 0 private(set) var runEndOutcome: ResponseCompletionOutcome = .completed - /// The coordinator's ending the last bump counted, so no ending counts twice. @ObservationIgnored private var runEndRecordedAt: Date? - /// Bumps at most once per throttle interval while live (non-replay) assistant - /// text arrives; the view turns each bump into one streaming pulse haptic. private(set) var streamingHapticPulseTrigger = 0 private var streamingHapticPulseThrottle = ChatHaptics.StreamingPulseThrottle() private(set) var responseCompletionNeedsTranscriptRefresh = false @@ -549,57 +424,23 @@ final class ChatViewModel { private(set) var workspaceSuggestions: [String] = [] private(set) var personalitySuggestions: [String] = ["none"] private(set) var skillSlashSuggestions: [SkillSlashSuggestion] = [] - /// The same skills in the shape the chip tokenizer needs, kept beside the - /// list so the transcript's `body` never rebuilds it. Always assigned - /// through `applySkillSlashSuggestions(_:)`. private(set) var skillChipCatalog: ComposerChipCatalog = .empty - /// Workspace files picked from the composer's `@` panel in this chat. - /// Held here rather than in the composer so the transcript draws the same - /// references the composer does, and so switching chats never carries one - /// session's paths into another. private(set) var fileChipPaths: Set = [] - /// The catalog both the composer and the transcript draw from: this chat's - /// skills plus the files it has referenced. private(set) var composerChipCatalog: ComposerChipCatalog = .empty - /// The workspace directory listings behind both the composer's `@` panel and - /// the confirmation of `@path` references in a restored draft or transcript, - /// so a folder either surface has already listed is never listed twice. @ObservationIgnored let filePathSearch = ComposerFilePathSearch() @ObservationIgnored private var fileChipReferenceLoad: Task? - /// Identifies the pass a handle belongs to, so a pass that was cancelled and - /// finishes late cannot clear the handle of the one that replaced it. @ObservationIgnored private var fileChipReferenceLoadGeneration = 0 - /// Candidates the server has already answered for, so a `@word` that is not - /// a file is not re-checked on every transcript update. @ObservationIgnored private var checkedFileChipCandidates: Set = [] - /// Bumped whenever the confirmed paths are thrown away because the - /// workspace moved. The chat re-runs its confirmation pass on the change, so - /// a file that exists in the new workspace too comes back as a chip, and a - /// pass started under an older revision applies nothing. private(set) var fileChipScopeRevision = 0 - /// Bumped whenever the transcript is replaced rather than extended: a - /// cache-first paint, the server's reconcile, a page of older messages. A - /// reconcile can rewrite a message in the middle of the list without - /// changing the count or the last id, so nothing cheaper than "the - /// transcript was swapped" can be trusted to notice a reference arriving. private(set) var transcriptRevision = 0 - /// Most folders one batch of a confirmation pass lists. The pass works - /// through every folder its candidates name, a batch at a time, so a long - /// transcript is answered in full without one burst of requests. private static let fileChipDirectoryLimit = 20 private(set) var profileOptions: [ProfileSummary] = [] private(set) var isSingleProfileMode = false private(set) var selectedProfileName: String? private(set) var selectedReasoningEffort: String? - /// Model-aware effort vocabulary (`supported_efforts` from `GET /api/reasoning`). - /// `nil` on older servers → the composer falls back to the static list (issue #18). private(set) var supportedReasoningEfforts: [String]? - /// `supports_reasoning_effort`; `false` hides the composer effort control. private(set) var supportsReasoningEffort: Bool? - /// Drops out-of-order `GET /api/reasoning` responses after rapid model switches - /// so the gating never reflects a stale model (upstream #3750 class of bug). private var reasoningGatingFetchToken = 0 - /// A Hermes session shows it unless the host marks the model `reasoning: false` (#1016). var showsReasoningEffortControl: Bool { if let hermesSettings { return hermesSettings.showsEffort } return ReasoningEffortOption.showsEffortControl( @@ -612,32 +453,20 @@ final class ChatViewModel { private(set) var composerConfigurationErrorMessage: String? var pendingAttachments: [PendingAttachment] { attachmentCoordinator.pendingAttachments } var isUploadingAttachment: Bool { attachmentCoordinator.isUploadingAttachment || isSendingAttachments } - /// A Hermes Send or Queue is uploading its files (#1012); `cancelAttachmentUpload()` stops it. var isSendingAttachments: Bool { hermesTurn?.isUploadingAttachments == true } var attachmentUploadCount: Int { attachmentCoordinator.uploadInFlightCount } var attachmentUploadGeneration: Int { attachmentCoordinator.uploadStartGeneration } var uploadAttachmentErrorMessage: String? { attachmentCoordinator.uploadAttachmentErrorMessage } var localAttachmentPreviews: [String: [String: Data]] { attachmentCoordinator.localAttachmentPreviews } private(set) var pinnedLocalNotices: [String] = [] - /// The one composer line shown while this chat's own messages wait behind - /// the run. It is derived from the queue, so it goes away when the queue - /// drains or is handed over, and it never enters a stream snapshot. A Hermes - /// session's queued prompts show as `queuedPromptMessages` instead. var queuedMessagesReceipt: String? { guard !queuedSlashMessages.isEmpty else { return nil } return String(localized: "Queued, sends when this run finishes") } - /// The prompts a Hermes host holds for later turns, as the transcript's pending bubbles show - /// them (#1379): outside `messages`, in the order the host runs them, one per canonical - /// admission (#1602), and each gone once its turn's start shows the real row or a Stop - /// discards it. Their reference lines are chips, as on a sent row, and so are the photos a - /// canonical send carried (#1644). var queuedPromptMessages: [ChatMessage] { (hermesTurn?.queuedPrompts ?? []).map { Self.hermesPromptRow($0, id: "hermes-queued-prompt-\($0.id)", timestamp: nil) } } - /// A turn a canonical host lost across its restart (#1602), as its row shows it: with its - /// prompt's bubble only when the transcript doesn't already end on that prompt. var lostTurn: ChatLostTurn? { guard let lost = hermesTurn?.lostTurn else { return nil } let last = messages.last @@ -648,9 +477,7 @@ final class ChatViewModel { ))) } - /// Discard on the lost turn's row: the host runs the prompts queued behind it. func discardLostTurn() async { - // A second tap while the first is on its way sends nothing. guard let hermesTurn, !isDiscardingLostTurn else { return } isDiscardingLostTurn = true defer { isDiscardingLostTurn = false } @@ -661,18 +488,13 @@ final class ChatViewModel { } private var isDiscardingLostTurn = false private(set) var steeringConfirmationNotice: String? - /// "Couldn't steer", plus the system's reason for a network or HTTP - /// failure, after the latest steer didn't reach the run. The composer shows - /// it with Retry; `clearSteerFailure()` removes it. private(set) var steerFailureMessage: String? var approvalPrompt: ApprovalPromptState? { pendingActionCoordinator.approvalPrompt } var isRespondingToApproval: Bool { pendingActionCoordinator.isRespondingToApproval } var approvalErrorMessage: String? { pendingActionCoordinator.approvalErrorMessage } - /// A Hermes session's reads `session.info`'s `yolo` (#1011); a webui session's, its yolo route. var isSessionApprovalBypassEnabled: Bool { hermesRequests?.approvalBypass ?? pendingActionCoordinator.isSessionApprovalBypassEnabled } - /// Model settings' Approvals row. A webui session has only its yolo route, and no mode. var composerApprovals: ComposerApprovals { if let requests = hermesRequests { return ComposerApprovals( @@ -689,7 +511,6 @@ final class ChatViewModel { ) } - /// Sets this chat's approval bypass from Model settings. func setSessionApprovalBypass(_ enabled: Bool) async { if let requests = hermesRequests { await requests.setApprovalBypass(enabled) @@ -698,7 +519,6 @@ final class ChatViewModel { } } - /// Sets the Profile's approval mode. Only a Hermes session has one. func selectApprovalMode(_ mode: HermesApprovalMode) async { await hermesRequests?.setApprovalMode(mode) } @@ -718,9 +538,6 @@ final class ChatViewModel { private(set) var isCompressionRotated = false @ObservationIgnored private var compressionRejectionMessage: String? @ObservationIgnored private var didHandOffCompressionDraft = false - /// The workspace this chat's session is pointed at. `/workspace` and the - /// composer's picker move it without the session id changing, and every - /// `@path` the chat has confirmed was confirmed against the old root. private var currentWorkspace: String? { didSet { guard currentWorkspace != oldValue else { return } @@ -732,26 +549,18 @@ final class ChatViewModel { private var currentProfile: String? private let isCLISession: Bool private let server: URL - /// A Hermes chat's session as a link names it (#1177): its Profile and current stored key, - /// which a compaction on a legacy-rotation host moves. Its run alert opens it. Nil for a - /// webui chat, and for a new one before the host names its key. var hermesSessionLink: HermesSessionDestination? { guard let engine = hermesTurn?.engine, let key = HermesDeepLink.normalizedSessionID(engine.storedKey ?? sessionID) else { return nil } return HermesSessionDestination(server: server, profile: engine.target.profile, key: key) } - /// The session pushes report under: a webui session's own ID, or a Hermes session's - /// current stored key, the `session_id` every hook sends. var pushPresence: PushPresence.Viewer? { (hermesSessionLink?.key ?? sessionID).map { PushPresence.Viewer(server: server, sessionID: $0) } } let client: APIClient - /// Webui's streams. Its start, cancel and session-load calls run only on a webui chat. private let streamCoordinator: ChatStreamCoordinator - /// The run lifecycle of whichever backend runs this chat: `streamCoordinator`, or `hermesTurn`. private let turn: any ChatTurnCoordinating - /// Set on a Hermes session: its turns run here, and webui-only paths stay off. private let hermesTurn: HermesChatTurnCoordinator? private let drafts: ChatDraftStore private let pendingActionCoordinator: ChatPendingActionCoordinator @@ -764,41 +573,16 @@ final class ChatViewModel { private let pollingIntervals: ChatPollingIntervals private let steeringConfirmationDismissDelay: @Sendable () async throws -> Void @ObservationIgnored private var steeringConfirmationDismissTask: Task? - // Real-time window over which rapid streaming updates coalesce into a single - // scroll trigger. Injectable so tests can drive coalescing deterministically; - // production keeps the 16ms default. private let streamingScrollCoalescingDelayNanoseconds: UInt64 - // Waits out one streaming reveal tick (50ms in production, #1126): buffered - // tokens and reasoning show at most once per tick. Injectable so tests drive - // ticks deterministically. private let streamingRevealTick: @Sendable () async throws -> Void - // Listen playback seam (#15): the factory builds an audio player from the server's - // or the on-device voice's bytes; injectable so tests never construct a real - // `AVAudioPlayer` (which requires decodable audio data). private let listenAudioPlayerFactory: @MainActor (Data) throws -> any ListenAudioPlaying - // A reply spoken by the on-device voice, as playable audio (#1352). Injectable so tests - // never run the real synthesizer. private let renderOnDeviceSpeech: @MainActor (String) async throws -> Data - // Waits out iOS's reaction to a Listen speed change before Now Playing is sent again - // (1 s in production). Injectable, and the task readable, so tests await it. private let listenSpeedChangeSettleDelay: @Sendable () async throws -> Void @ObservationIgnored private(set) var listenNowPlayingRefreshTask: Task? - // A reply's server speech for Listen, or nil to speak it on device: webui's `/api/tts` - // with the saved engine and voice, or a Hermes host's voice for the chat's Profile - // (#1072). Any throw also falls back on device (#15). Injectable so tests stub the server. private let synthesizeListenAudio: @MainActor (String) async throws -> Data? private var listenAudioPlayer: (any ListenAudioPlaying)? - // Identity of the Listen player currently playing. A stale finish callback from a - // superseded player (e.g. switching messages mid-playback) must not clear the new - // listen state or deactivate the session. See #252. private var activeListenPlayerID: ObjectIdentifier? - // In-flight settings/audio fetch for the Listen action. Cancelled by - // `stopListening()`; exposed (read-only) so tests can await the async - // server-first path deterministically. @ObservationIgnored private(set) var listenPreparationTask: Task? - // Identity of the Listen request the in-flight fetch belongs to. A response - // arriving after stop/switch carries a stale ID and is dropped instead of - // starting audio the user no longer wants. private var activeListenRequestID: UUID? private var listenPlaybackTitle = String(localized: "Hermex response") private(set) var listenPlaybackPhase: ListenPlaybackPhase = .idle @@ -812,20 +596,11 @@ final class ChatViewModel { private var isStreamConnectionSuspended: Bool { turn.isConnectionSuspended } var isActiveStreamConnectionSuspended: Bool { turn.isConnectionSuspended } private var hasLoadedPersonalitySuggestions = false - /// The in-flight personality list request, shared by every caller of - /// `loadPersonalitySuggestions()` so no view's cancellation can orphan it. private var personalitySuggestionsLoad: Task? - /// Whether a skills list request has succeeded for this session, even when - /// it returned no skills. Lets the composer tell "still loading" from - /// "loaded, and the server has none". private(set) var hasLoadedSkillSlashSuggestions = false - /// The in-flight skill list request, shared by every caller of - /// `loadSkillSlashSuggestions()` so no view's cancellation can orphan it. private var skillSlashSuggestionsLoad: Task? private var queuedSlashMessages: [QueuedSlashMessage] = [] private var isDrainingQueuedSlashMessage = false - /// Counts `takeQueuedMessages()` hand-overs, so an interrupt whose cancel - /// was in flight across one knows its message went to the draft. @ObservationIgnored private var queueHandOverCount = 0 private var activeBtwStreamID: String? private var activeBtwMessageID: String? @@ -834,9 +609,6 @@ final class ChatViewModel { private var backgroundPromptsByTaskID: [String: String] = [:] @ObservationIgnored private var backgroundPollTask: Task? private var isRefreshingCompletedResponseTitle = false - /// True while a reattached stream replays events the transcript may already - /// hold. Clears once replayed text catches up; until then live tool rows - /// skip their entrance. var isActiveStreamReplayConnection: Bool { turn.isReplayConnection } private var activeStreamReplayMatchedPrefixLength = 0 private var activeStreamReplayMatchedInterimLength = 0 @@ -982,9 +754,6 @@ final class ChatViewModel { ActiveChatStreamSnapshotStore.shared.removeAll() } - // Test seam: deterministically await the in-flight coalesced scroll-trigger task - // so streaming assertions never depend on the real coalescing window elapsing. - // No-op when no trigger is pending. func awaitPendingStreamingScrollTriggerForTesting() async { await pendingStreamingScrollTriggerTask?.value } @@ -995,8 +764,6 @@ final class ChatViewModel { let usedSnapshotMessagesOffset: Bool } - /// A Hermes session's model chip shows `model.options`' live model, or the pick - /// waiting on the running response (#1015); `session.info`'s model until it answers. var selectedModelID: String? { hermesSettings?.selectedModel?.id ?? currentModel } @@ -1005,63 +772,47 @@ final class ChatViewModel { hermesSettings.map { $0.selectedModel?.providerID } ?? currentModelProvider } - /// The model picker's groups: a Hermes session's `model.options` (#1015), else webui's catalog. var composerModelGroups: [ModelCatalogGroup] { hermesSettings?.controls.catalog.groups ?? modelCatalogGroups } - /// The Profile chip's list: a Hermes host's `profiles.list` (#1015), else webui's Profiles. var composerProfileOptions: [ProfileSummary] { hermesSettings?.profileOptions ?? profileOptions } - /// The Profile chip only shows its Profile: one Profile, or a Bot Chat's bot, whose chat - /// picks no other (#1145). var composerIsSingleProfileMode: Bool { guard let hermesTurn else { return isSingleProfileMode } return !hermesTurn.policy.picksProfile || hermesTurn.settings.profiles.count <= 1 } - /// A Hermes model pick the host applies after the running response (#1015). var composerConfigurationNotice: String? { guard let pending = hermesSettings?.controls.pendingModel else { return nil } return String(localized: "Switches to \(ModelDisplayNames.displayLabel(for: pending.id, displayName: pending.displayName)) after this response.") } - /// A Hermes session's model and Profile controls (#1015). Nil on a webui session. var hermesSettings: HermesChatSettings? { hermesTurn?.settings } - /// A bot's Bot Chat's turns (#1145), for its pill, `@` roster and profile; nil otherwise. var hermesBotChat: HermesChatTurnCoordinator? { hermesTurn?.policy == .botChat ? hermesTurn : nil } - /// Whether a Hermes chat's latest turn used the bot's screen (#1632, #1633), for its Screen card. var hermesScreenUse: BotScreenUse? { hermesTurn?.screenUse } - /// The effort chip's level: a Hermes session's `session.info` effort (#1016), else webui's. var composerReasoningEffort: String? { hermesSettings.map { $0.controls.effort } ?? selectedReasoningEffort } - /// The effort ladder: a Hermes host's for the live model (#1016), else webui's vocabulary. var composerSupportedReasoningEfforts: [String]? { hermesSettings?.effortLevels ?? supportedReasoningEfforts } - /// The level a Hermes host sends when the model takes less than the one picked (#1016). var composerSentReasoningEffort: String? { hermesSettings?.sentEffort } - /// A Hermes session's Fast mode (#1142); nil hides its row, as on a webui session. var composerFastMode: Bool? { hermesSettings?.fast } - /// Whether that Fast mode can change now (#1142). var composerMayChangeFastMode: Bool { hermesSettings?.mayChangeFast == true } - /// Turns a Hermes session's Fast mode on or off for this chat (#1142); false when it - /// can't go now or the host refused it. func selectFastMode(_ enabled: Bool) async -> Bool { await hermesSettings?.select(fast: enabled) ?? false } - /// The chat's workspace: a Hermes session's working folder as its host reports it (#1117). var selectedWorkspacePath: String? { hermesTurn.map(\.cwd) ?? currentWorkspace } @@ -1123,8 +874,6 @@ final class ChatViewModel { let tick = streamingRevealTick pendingStreamingContentFlushTask = Task { @MainActor [weak self] in try? await tick() - // A cancelled tick was already replaced or flushed; it must not clear - // the task slot a newer tick owns. guard let self, !Task.isCancelled else { return } self.pendingStreamingContentFlushTask = nil @@ -1132,11 +881,6 @@ final class ChatViewModel { } } - /// One reveal tick: shows buffered assistant text through `StreamingRevealGate` - /// and all buffered reasoning, then reschedules only while a fragment is held. - /// Completion paths (done/cancel/error/interim/snapshot) skip the gate via - /// `flushPendingStreamingContent()`, which cancels any scheduled tick. Each tick is a - /// `Stream Batch Apply` interval with `forced=0`; a forced flush reports `forced=1`. private func revealStreamingContentTick() { let signpost = performanceSignposter.beginInterval("Stream Batch Apply") var didMutate = false @@ -1170,10 +914,6 @@ final class ChatViewModel { pendingAssistantText = "" heldStreamingFragmentLastTick = false pendingReasoningChunks = [] - // Chunks are deduplicated at append time, so the replay matched-prefix - // counters can reference unflushed content; dropping the buffers makes them - // stale. Reset only the counters — the replay connection may still be live - // (e.g. loadOlderMessages pagination mid-catch-up), so dedup must stay armed. activeStreamReplayMatchedPrefixLength = 0 activeStreamReplayMatchedReasoningLength = 0 } @@ -1218,7 +958,6 @@ final class ChatViewModel { } func loadComposerConfiguration() async { - // A Hermes session's chips read its gateway (`HermesChatSettings`), never webui's routes. guard hermesTurn == nil else { return } if isLoadingComposerConfiguration { needsComposerConfigurationReload = true @@ -1251,10 +990,6 @@ final class ChatViewModel { } while needsComposerConfigurationReload } - /// Refreshes the model catalog when a picker opens: refetch `/api/models` - /// (so the sheet stops pinning the chat-load-time snapshot), then overlay - /// the active provider's live list from `/api/models/live`. Failures are - /// silent by design — the picker keeps whatever it already shows. func refreshModelCatalogForPickerOpen() async { if let hermesSettings { await hermesSettings.controls.reload() @@ -1359,9 +1094,6 @@ final class ChatViewModel { currentModelProvider = response.session?.modelProvider ?? option.providerID currentWorkspace = response.session?.workspace ?? currentWorkspace pendingExplicitModelPick = true - // Still inside the isUpdatingComposerConfiguration window, so the - // effort menu stays disabled until the new model's gating lands — - // no interactable flash of the previous model's options (issue #18). await refreshReasoningEffortGating() return true } catch { @@ -1371,13 +1103,6 @@ final class ChatViewModel { } } - /// Re-queries `GET /api/reasoning` for the current model/provider and updates - /// the effort gating (issue #18). Failures are silent to the user, but reset - /// the gating to the "unknown" fallback (static effort list, control shown) — - /// keeping the previous model's gating after a successful model switch could - /// hide the control for a model that supports it, or offer efforts the new - /// model rejects. If the selected effort is no longer supported, snaps to the - /// server's coerced `reasoning_effort`. func refreshReasoningEffortGating() async { guard !isViewingCachedData else { return } @@ -1408,8 +1133,6 @@ final class ChatViewModel { } } - /// Refetches the workspace registry after the manager sheet mutated it - /// (issue #22), so the picker reflects adds/removes/renames/reorders. func refreshWorkspaceRoots() async { guard !isViewingCachedData else { return } @@ -1432,7 +1155,6 @@ final class ChatViewModel { return } - // Each keystroke cancels the previous load, whose answer and cancellation both go unused. do { let response = try await client.workspaceSuggestions(prefix: prefix) guard !Task.isCancelled else { return } @@ -1444,19 +1166,8 @@ final class ChatViewModel { } } - /// Loads the personality list once, sharing a single request between - /// callers. - /// - /// Same shape as `loadSkillSlashSuggestions()` and for the same reason: the - /// request lives on a task this view model owns, so a cancelled caller - /// cannot take the fetch down with it, and a caller arriving mid-flight - /// waits for that same result instead of racing past an "already loading" - /// flag and finding an empty list. A failed load clears the handle, so the - /// next caller retries. Held while the chat shows its offline cache; the - /// composer asks again on reconnect. func loadPersonalitySuggestions() async { guard !hasLoadedPersonalitySuggestions, !showsOfflineCache else { return } - // A Hermes host lists its own (#1016), here for the `/personality ` panel (#1036). if let hermesSettings { guard let personalities = try? await hermesSettings.personalities() else { return } personalitySuggestions = ["none"] + personalities.map(\.name) @@ -1488,17 +1199,6 @@ final class ChatViewModel { await load.value } - /// Loads the skill list once, sharing a single request between callers. - /// - /// The composer asks for this from two `.task` modifiers — the chip warm-up - /// for a restored draft and the autocomplete panel — and either can be - /// cancelled by an unrelated view update. So the request lives on a task - /// this view model owns: a cancelled caller cannot take the fetch down with - /// it, and a caller arriving mid-flight waits for that same result instead - /// of racing past an "already loading" flag and finding an empty list. A - /// failed load clears the handle, so the next caller retries. Held while the - /// chat shows its offline cache; the composer and transcript ask again on - /// reconnect. func loadSkillSlashSuggestions() async { guard hermesTurn == nil, !hasLoadedSkillSlashSuggestions, !showsOfflineCache else { return } @@ -1583,16 +1283,9 @@ final class ChatViewModel { } } - // MARK: Hermes working folder (#1117) - - /// A folder picked in a Hermes chat that has run, waiting for the user to confirm the move. private(set) var pendingHermesFolder: String? - /// The folder picker's untyped list for a Hermes chat, kept while the user types a filter; - /// nil until a read for the open picker finishes. @ObservationIgnored private var hermesFolderChoices: [String]? - /// A Hermes chat's folder pick: a new chat nothing ran in moves at once; any other asks first - /// (`pendingHermesFolder`), since the work so far stays in the old folder. private func selectHermesFolder(_ path: String) async -> Bool { var folder = path.trimmingCharacters(in: .whitespacesAndNewlines) while folder.count > 1, folder.hasSuffix("/") { folder.removeLast() } @@ -1606,14 +1299,12 @@ final class ChatViewModel { func cancelHermesFolderMove() { pendingHermesFolder = nil } - /// Moves a Hermes chat to the `folder` the user confirmed; false when it didn't move. func confirmHermesFolderMove(_ folder: String) async -> Bool { pendingHermesFolder = nil guard let hermesTurn, canChangeHermesFolder() else { return false } return await moveHermesFolder(folder, on: hermesTurn) } - /// The client refuses a folder change while a reply runs, though the host would take it. private func canChangeHermesFolder() -> Bool { if isViewingCachedData { composerConfigurationErrorMessage = String(localized: "Reconnect to the server to change workspace.") @@ -1647,9 +1338,6 @@ final class ChatViewModel { return false } - /// The folder picker's list for a Hermes chat: a typed path completes from the host's - /// folders; anything else filters the untyped list, read again each time the picker opens. - /// A filter typed before that read finishes cancels it, so the filter reads the list itself. private func loadHermesFolderSuggestions(prefix: String, on hermes: HermesChatTurnCoordinator) async { let typed = prefix.trimmingCharacters(in: .whitespacesAndNewlines) if HermesFolderCompletion.completes(typed) { @@ -1755,7 +1443,6 @@ final class ChatViewModel { let selectedEffort = effort.trimmingCharacters(in: .whitespacesAndNewlines) guard !selectedEffort.isEmpty else { return false } - // A Hermes session sends it for this chat alone (#1016). if let hermesSettings { guard selectedEffort != hermesSettings.controls.effort else { return false } return await hermesSettings.select(effort: selectedEffort) @@ -1800,10 +1487,6 @@ final class ChatViewModel { } } - /// Restores one new-chat settings snapshot only while the configuration - /// remains untouched. Profile owns the defaults for the remaining fields, - /// so a missing or rejected profile stops the whole replay rather than - /// projecting its model/workspace/reasoning choices onto another profile. func restoreDraftSettings( _ rawSettings: ChatDraftSettings, expectedInteractionGeneration: Int @@ -1866,9 +1549,6 @@ final class ChatViewModel { && composerConfigurationInteractionGeneration == expectedInteractionGeneration } - /// Saves and uploads a freshly staged file into the pending strip. Returns - /// nil unless both the durable draft copy and server upload succeed. A Hermes - /// session only saves the copy; its Send or Queue uploads it (#1012). @discardableResult func uploadAttachment(data: Data, filename: String, previewData: Data? = nil) async -> PendingAttachment? { await attachmentCoordinator.uploadAttachment( @@ -1878,35 +1558,26 @@ final class ChatViewModel { ) } - /// Stages a long paste as a `pasted-text` file (#1381), with the editor left alone. @discardableResult func stagePastedText(_ text: String) -> Task { attachmentCoordinator.stagePastedText(text) } - /// Stops long pastes still staging; `ChatView` calls it as it disappears. func cancelPastedTextStaging() { attachmentCoordinator.cancelPastedTextStaging() } - /// Whether a send may be reading the staged files, or its outcome is unknown (#508), so a - /// staged paste stays read-only (#1456). A send reads each file only when it gets to it. var stagedFilesAreSending: Bool { isSubmittingHermesPrompt || isHermesSubmissionUncertain } func stagedPasteText(_ attachment: PendingAttachment) async -> StagedPasteText? { await attachmentCoordinator.stagedPasteText(attachment) } - /// Saves an edited staged paste, unless a send took it after the sheet opened. Returns - /// why it did not save, or nil once it has. func saveStagedPaste(_ attachment: PendingAttachment, text: String) async -> String? { guard !stagedFilesAreSending else { return StagedPasteText.sendingNotice } return await attachmentCoordinator.replaceStagedPaste(attachment, with: text) } - /// Re-uploads a restored draft attachment from its durable local copy, - /// preserving the draft record's identity. Quiet on failure (returns nil): - /// the caller reports in aggregate and keeps the record for a later retry. @discardableResult func reuploadDraftAttachment(_ draftAttachment: ChatDraftAttachment, data: Data) async -> PendingAttachment? { await attachmentCoordinator.reuploadDraftAttachment(data: data, draftAttachment: draftAttachment) @@ -1929,8 +1600,6 @@ final class ChatViewModel { attachmentCoordinator.removePendingAttachment(id: id) } - /// Stages files after the composer's own, such as the files of queued - /// messages parked back into the draft. func appendPendingAttachments(_ attachments: [PendingAttachment]) { attachmentCoordinator.appendPendingAttachments(attachments) } @@ -1939,8 +1608,6 @@ final class ChatViewModel { attachmentCoordinator.setUploadAttachmentError(message) } - /// A sent attachment's thumbnail bytes: a Hermes session downloads from its host - /// (#1030), a webui chat through the server's file API. Nil when it can't load. func attachmentImageData(path: String) async -> Data? { guard let hermesTurn else { return await attachmentCoordinator.attachmentImageData(path: path) } guard let data = try? await hermesTurn.attachmentData(path: path) else { return nil } @@ -1950,39 +1617,24 @@ final class ChatViewModel { ) ?? data } - /// A Hermes session's sent file in full, for its preview (#1030). Throws `.stale` on a - /// webui chat, which previews through `ChatAttachmentPreviewView` instead. func hermesAttachmentData(path: String) async throws -> Data { guard let hermesTurn else { throw BotFailure.stale } return try await hermesTurn.attachmentData(path: path) } - /// The thumbnail cache namespace of a Hermes session; nil on a webui chat. var hermesAttachmentCacheNamespace: String? { hermesTurn?.attachmentCacheNamespace } - /// A Hermes session's working folder (#1112); nil on a webui chat, and until `session.info` - /// names it. var hermesWorkspace: HermesWorkspaceContext? { hermesTurn?.workspace } - /// The folder a Hermes reply's relative Markdown image paths resolve against (#1679): its live - /// folder, else `listedFolder`, its session row's, so a cached transcript renders before the - /// host names one. Nil on webui, whose chat resolves them against its session's workspace. func transcriptWorkspaceRoot(listedFolder: String?) -> String? { guard let hermesTurn else { return nil } return hermesTurn.workspace?.cwd ?? listedFolder } - /// The HEAD a Hermes chat's latest turn's direct send read before its prompt went out (#1392), - /// which its File changes card reads its range since; nil on webui and for any other turn. var hermesTurnBase: GitTurnBase? { hermesTurn?.latestTurnBase } - /// The files of `hermesWorkspace`, on the session's connection. var hermesWorkspaceFiles: HermesWorkspaceFileClient? { hermesTurn?.workspaceFiles } - /// Files' workspace search (#1389) while `hermesWorkspace` is on a `local` backend: the `@` - /// panel's whole-folder `complete.path` search, which works while the chat is detached under - /// Files. A reply that lands after the folder moved throws `.stale`. Nil on webui and on any - /// other backend. var workspaceFileSearch: FileWorkspaceSearch? { guard let hermesTurn, let workspace = hermesTurn.workspace, workspace.isLocal else { return nil } return { [weak hermesTurn] query in @@ -1993,31 +1645,20 @@ final class ChatViewModel { } } - /// The repository holding `hermesWorkspace` (#1114), on the session's connection. Each read is a - /// new client, which resolves its root once, so keep one per folder. Its writes stop while a - /// turn runs or this chat shows cached data (#1115). var hermesWorkspaceGit: HermesGitClient? { hermesTurn?.workspaceGit { [weak self] in self?.isViewingCachedData ?? true } } - /// A sent attachment's original bytes for its inline audio player: a Hermes session downloads - /// from its host under the preview cap (#1143), a webui chat through the server's file API. - /// Nil when it can't load, including on a detached Hermes chat, which the player avoids by - /// waiting on `attachmentLoadKey`. func attachmentRawData(path: String) async -> Data? { guard let hermesTurn else { return await attachmentCoordinator.attachmentRawData(path: path) } return try? await hermesTurn.attachmentData(path: path) } - /// When `attachmentRawData` can load: a Hermes chat's current attach, nil while detached; a - /// constant on webui. The inline audio player's `loadKey`. var attachmentLoadKey: Int? { guard let hermesTurn else { return 0 } return hermesTurn.attachmentLoadKey } - /// A transcript MEDIA image's inline thumbnail: a Hermes session's from its host (#1112), a - /// webui chat's through `/api/media`. Nil when it can't load. func transcriptMediaThumbnailData(for reference: TranscriptMediaReference) async -> Data? { guard let hermesTurn else { return await attachmentCoordinator.transcriptMediaThumbnailData(for: reference) } guard reference.isRasterImageCandidate, @@ -2028,19 +1669,11 @@ final class ChatViewModel { ) ?? data } - /// A transcript MEDIA reference's bytes for inline audio and file export. A Hermes session - /// downloads a local path from its host as it does a sent file (#1112), which resolves it - /// against the session, in full as webui's `/api/media` does; a remote URL loads as on webui. - /// Nil when it can't load. func transcriptMediaData(for reference: TranscriptMediaReference) async -> Data? { guard let hermesTurn else { return await attachmentCoordinator.transcriptMediaData(for: reference) } return await hermesTranscriptMediaData(for: reference, from: hermesTurn, whole: true) } - /// A Hermes reply's HTML report for its inline render (#1623), at most - /// `HTMLReport.inlineByteLimit`: a larger file throws `BotArtifactFailure.tooLarge` and stays a - /// card. A host path downloads through this attach; a remote URL is a public, cookie-less fetch - /// with no server's credentials, as the document sheet's is. Throws `.stale` on webui. func transcriptHTMLReportData(for reference: TranscriptMediaReference) async throws -> Data { guard let hermesTurn else { throw BotFailure.stale } switch reference.source { @@ -2060,13 +1693,9 @@ final class ChatViewModel { } } - /// Reloads the newest transcript window from the server. `usesInitialPrefetch` - /// is for the chat's first load only: it takes over the request - /// `prepareInitialMessageLoad` already sent instead of sending another. func loadMessages(modelContext: ModelContext? = nil, usesInitialPrefetch: Bool = false) async { if let hermesTurn { if let modelContext { hermesCache = modelContext } - // For an open that skipped `prepareInitialMessageLoad`. showCachedHermesTranscriptBeforeAttach(hermesTurn) await loadHermesSession(hermesTurn) return @@ -2087,10 +1716,6 @@ final class ChatViewModel { lastError = nil defer { isLoading = false } - // Cache-first render (#289): capture the pre-reload window *before* painting - // any cached transcript, so the network reconcile below replaces it cleanly - // (no merge, no duplication). Then, on a cold open with a populated cache, - // render the cached messages immediately so the loading skeleton never shows. let previousMessages = messages let previousMessagesOffset = messagesOffset let usesPrimedInitialCache = hasPrimedInitialCachedMessages && !previousMessages.isEmpty @@ -2111,7 +1736,6 @@ final class ChatViewModel { do { let response: SessionResponse if let prefetchedSession { - // The prefetch is unstructured, so forward this load's cancellation to it. response = try await withTaskCancellationHandler { try await prefetchedSession.value.session } onCancel: { @@ -2158,8 +1782,6 @@ final class ChatViewModel { previousMessagesOffset: previousMessagesOffset ) if renderedCacheFirst { - // The taller server transcript has now replaced the lighter cache-first - // render; signal the view to re-pin to the bottom without a visible jump. transcriptRelayoutScrollToken += 1 } latestServerLoadHadAssistantResponseAfterLatestUser = Self.hasAssistantResponseAfterLatestUser( @@ -2281,12 +1903,6 @@ final class ChatViewModel { } } - /// Performs the fast, local portion of an existing session's first load and - /// sends its transcript request. `ChatView` applies the response only after - /// its navigation appearance completes (`loadMessages(usesInitialPrefetch:)`), - /// so rendering a richer transcript cannot stall the system push animation, - /// while the round trip overlaps it. A Hermes chat shows its cached transcript here instead, - /// and attaches from `loadMessages`. func prepareInitialMessageLoad(modelContext: ModelContext) { if let hermesTurn { hermesCache = modelContext @@ -2314,10 +1930,6 @@ final class ChatViewModel { hasPrimedInitialCachedMessages = !cachedMessages.isEmpty } - /// Clears the stored initial prefetch and returns its task when this load may - /// use it: the initial load, with the active stream unchanged since the - /// request went out. A response fetched before a stream started would read as - /// that stream having ended. Otherwise the request is cancelled. @discardableResult private func takeInitialSessionPrefetch(usable: Bool) -> Task? { guard let prefetch = initialSessionPrefetch else { return nil } @@ -2330,8 +1942,6 @@ final class ChatViewModel { } private struct InitialSessionPrefetch { - /// `SessionResponse` is not `Sendable`, but this decoded value is - /// immutable and handed from the task to its single consumer. struct Response: @unchecked Sendable { let session: SessionResponse } @@ -2348,20 +1958,10 @@ final class ChatViewModel { id: sessionID, includeMessages: true, messageLimit: messagePageLimit, - // Cold load only: widen the window to renderable-dense (upstream #3790) so a - // tool-heavy session opens populated. "Load earlier" keeps the raw cap. expandRenderable: true ) } - /// Cache-first render (#289): on a cold session open, paint the cached transcript - /// immediately so the loading skeleton never appears, then let the in-flight - /// `loadMessages` network reload reconcile silently in place. Keeps - /// `isViewingCachedData` off because this is the success-expected window, not an - /// offline failure — the offline indicator stays tied to a real network error. - /// Returns the cached messages it rendered (empty if nothing was cached), so the - /// caller can revert the placeholder if the reload surfaces an error instead of - /// content — but only while the transcript is still that exact placeholder. private func renderCachedMessagesBeforeReload( sessionID: String, modelContext: ModelContext @@ -2380,8 +1980,6 @@ final class ChatViewModel { limit: Self.messagePageLimit ) } catch { - // A cache read failure must not block the normal network load; fall back - // to the existing skeleton-until-network behavior. return [] } @@ -2395,17 +1993,11 @@ final class ChatViewModel { return cachedMessages } - /// Undo a cache-first placeholder (#289) when the reload fails without adopting - /// the offline cache, so the existing error UI (empty transcript + message) shows - /// instead of a stale cached transcript masquerading as live. private func revertCacheFirstPlaceholder( _ placeholder: [ChatMessage], to previousMessages: [ChatMessage], previousMessagesOffset: Int ) { - // Only undo the cache-first paint if nothing mutated the transcript since the - // prime (e.g. an optimistic send during the load window) — otherwise we'd wipe - // in-flight local content while its send/stream is still running. guard messages == placeholder else { return } messages = previousMessages transcriptRevision &+= 1 @@ -2506,8 +2098,6 @@ final class ChatViewModel { } func actionContext(for message: ChatMessage, visibleIndex: Int) -> MessageActionContext? { - // Steering hints are annotations on the active turn, not user-editable - // content: no edit/fork/copy actions. guard !message.isSteerMessage else { return nil } return MessageActionContext( message: message, @@ -2515,13 +2105,10 @@ final class ChatViewModel { messagesOffset: messagesOffset, offersHistoryActions: hermesTurn.map { $0.policy.offersHistoryActions && hermesRewindableMessageIDs.contains(message.id) } ?? true, - // A Hermes branch counts to a row the host saved (#1051). A Bot Chat offers neither (#1145). offersFork: hermesTurn.map { $0.policy.offersHistoryActions && message.rowID != nil } ?? true ) } - /// How many transcript rows follow `context`'s row: what an edit or a regenerate discards, - /// which its confirmation counts. Rows match by message, never by their positional render id. func transcriptMessagesAfter(_ context: MessageActionContext) -> Int { guard let index = displayedTranscriptMessages.firstIndex(where: { $0.message.id == context.messageID }) else { return 0 } return max(0, displayedTranscriptMessages.count - 1 - index) @@ -2538,8 +2125,6 @@ final class ChatViewModel { for index in stride(from: startIndex, through: 0, by: -1) { let message = messages[index] - // A steer sits between the prompt and its reply; regenerating must - // resend the prompt, never the steer's wrapped text. guard message.role == "user", !message.isSteerMessage else { continue } let text = message.content?.trimmingCharacters(in: .whitespacesAndNewlines) @@ -2656,20 +2241,6 @@ final class ChatViewModel { return Array(currentMessages[..` renderID, SwiftUI remounts the whole list, - /// and a reader who scrolled up is dumped at the top of the session. - /// - /// When the reloaded window still contains the first message we're already - /// showing at the absolute index implied by both offsets, drop the reloaded - /// rows *before* that overlap and keep the current offset: rows on screen - /// keep their renderIDs, and the tail is replaced with the - /// server-authoritative content. Returns nil when the windows don't align - /// (fall back to plain replacement). nonisolated private static func trimmingReloadedMessages( _ reloadedMessages: [ChatMessage], toPreserveCurrentMessages currentMessages: [ChatMessage], @@ -2757,10 +2328,6 @@ final class ChatViewModel { } var mergedMessages = loadedMessages - // Steer echoes ride along inside the active turn and never open a new - // one, so a trailing echo must not move the assistant search range past - // the streaming assistant: that would skip content reconciliation and - // append a duplicate assistant row. let latestUserIndex = mergedMessages.lastIndex(where: TranscriptTurnClassifier.isTurnBoundary) let assistantSearchRange: Range if let latestUserIndex { @@ -2850,11 +2417,6 @@ final class ChatViewModel { } } - /// When the session's in-flight turn started, for seeding the stream - /// coordinator's run clock: the server's `pending_started_at` first, then the - /// latest user message's timestamp. Both survive leaving and re-entering the - /// session, so "Working for" keeps counting from one instant; nil leaves the - /// coordinator counting from when it discovered the stream. nonisolated private static func activeRunStartDate( pendingStartedAt: Double?, messages: [ChatMessage] @@ -2878,8 +2440,6 @@ final class ChatViewModel { guard !messages.isEmpty else { return false } let searchRange: Range - // Steer echoes are not user-turn boundaries; a trailing echo must not - // hide an in-flight assistant response from the stream coordinator. if let latestUserIndex = messages.lastIndex(where: TranscriptTurnClassifier.isTurnBoundary) { searchRange = messages.index(after: latestUserIndex).. String { guard let content else { return "" } - // Share the single marker parser with the display layer so the two can - // never disagree about what counts as an attachment marker. Trim the - // result because this normalized form is compared for dedup equality. let withoutAttachments = MessageAttachment .contentWithoutAttachedFilesMarker(in: content) .trimmingCharacters(in: .whitespacesAndNewlines) - // The server persists an accepted steer wrapped in the out-of-band - // marker while the local echo carries the bare text. Strip the wrapper - // so the persisted row is recognized as the echo's server copy instead - // of a duplicate. let steerStripped = ChatMessage.strippedSteerText(from: withoutAttachments) ?? withoutAttachments return steerStripped.trimmingCharacters(in: .whitespacesAndNewlines) } nonisolated private static func attachmentKeys(for message: ChatMessage) -> Set { - // Match on `MessageAttachment.identityKey` (lowercased basename): the - // server returns attachment paths inconsistently on reload, so basename - // matching is the only reliable way to dedupe an optimistic bubble - // against its reloaded copy. See `identityKey` for the full rationale. Set((message.attachments ?? []).compactMap(\.identityKey)) } @@ -3096,16 +2638,12 @@ final class ChatViewModel { await send(draft, modelContext: modelContext) == .started } - /// A composer Send. `isPlainText` (no quotes, files or `/` command) lets a Hermes chat hold it - /// until it reconnects (#1407): offline, or when its prompt finds no connection before it goes out. func send(_ draft: String, isPlainText: Bool = false, modelContext: ModelContext? = nil) async -> ChatSendOutcome { - // A Send that waits does so only while the chat it began in is still here. let waitingOwner = isPlainText ? waitingSendGeneration : nil guard !isViewingCachedData else { if let waitingOwner, offersWaitingSend, let hermesTurn { return await holdForConnection(draft, on: hermesTurn, owner: waitingOwner) } - // A cached copy shown while the chat connects holds the draft without a word. if !isCachedCopyProvisional { sendErrorMessage = String(localized: "Reconnect to the server to send a message.") } return .kept } @@ -3121,10 +2659,7 @@ final class ChatViewModel { guard !isCompressionRotated else { sendErrorMessage = compressionRejectionMessage - // A failed continuation load would otherwise strand the draft here. if compressionContinuation == nil, let id = compressionContinuationID, let sessionID { - // Holds Send off during the retry, as `performChatSend` does for the first load, - // so a second Send can't race this one's composer restore and handoff. isStartingChat = true defer { isStartingChat = false } await resolveCompressionContinuation(id: id, from: sessionID, @@ -3135,8 +2670,6 @@ final class ChatViewModel { } let message = draft.trimmingCharacters(in: .whitespacesAndNewlines) - // Attachment-only sends (empty text, staged attachments) synthesize - // their message text in `PendingAttachment.chatMessageText` below. guard !message.isEmpty || !attachmentCoordinator.pendingAttachments.isEmpty else { return .kept } guard let sessionID else { @@ -3147,8 +2680,6 @@ final class ChatViewModel { let localMessageID = "local-\(UUID().uuidString)" let attachmentPreparation = attachmentCoordinator.prepareForSend(localMessageID: localMessageID) let messageForAPI = attachmentPreparation.chatMessageText(draft: message) - // Attachment-only sends show the synthesized text in the bubble, matching - // what a reload from the server displays; text sends keep the bare draft. let displayText = message.isEmpty ? messageForAPI : message let didStart = await performChatSend( @@ -3171,8 +2702,6 @@ final class ChatViewModel { return didStart ? .started : .kept } - /// Called only after ChatView restores the rejected composer submission. Uses - /// the normal pushed-session route and moves all retained draft work together. func compressionContinuationForNavigation( from sourceKey: ChatDraftKey, isCurrent: @MainActor () -> Bool, prepareDraftForHandoff: @MainActor () -> Void = {} @@ -3187,11 +2716,7 @@ final class ChatViewModel { guard generation == chatSendGeneration, compressionContinuation?.sessionId == id, isCurrent(), !Task.isCancelled, Self.compressionProfile(continuation.profile) == Self.compressionProfile(currentProfile) else { return nil } - // Never overwrite another window's unsent work. Stay here with this draft - // and the original conflict rather than dropping either composer's content. guard existing?.isEmpty != false else { return nil } - // Destination hydration suspended above. Snapshot the latest composer - // now, with no suspension between reconciliation and the atomic move. prepareDraftForHandoff() drafts.moveDraft(from: sourceKey, to: targetKey) didHandOffCompressionDraft = true @@ -3200,70 +2725,39 @@ final class ChatViewModel { return continuation } - /// Whether this chat runs a Hermes session rather than a webui one (#1010). var isHermesSession: Bool { hermesTurn != nil } - /// A Hermes prompt is on its way, from its uploads to the host's answer. @ObservationIgnored private var isSubmittingHermesPrompt = false - /// #508: a Hermes prompt's answer was lost, so nothing sends until the next attach's - /// snapshot shows whether it ran. Restored from the draft's mark when the chat opens. private(set) var isHermesSubmissionUncertain = false - /// The last attach's release of a lost prompt's mark (`releaseSubmissionMark`). @ObservationIgnored private(set) var submissionMarkRelease: Task? - /// A Hermes chat's plain-text Send held until it reconnects (#1407). Every other Send waits - /// while it does. private(set) var waitingSend: HermesWaitingSend? - /// Bumped whenever the waiting send is held, goes, or its chat leaves, so a deadline or - /// delivery begun for an earlier one does nothing. @ObservationIgnored private var waitingSendGeneration = 0 - /// A Send is being written as the waiting send, so no second one takes its draft record or - /// goes out ahead of it. @ObservationIgnored private var isHoldingWaitingSend = false @ObservationIgnored private var waitingSendDeadline: Task? @ObservationIgnored private let waitingSendClock: HermesWaitingSendClock - /// A waiting send went back: `ChatView` shows the draft's text, which now leads with it, in its - /// composer, and says why when it expired. The draft on disk has it already. @ObservationIgnored var onWaitingSendReturned: ((String, HermesWaitingSend.Return) -> Void)? - /// A Hermes session's draft key: the new-session key until the host names the session. var hermesDraftKey: ChatDraftKey? { hermesTurn?.currentDraftKey } - /// The parent list learns a New Session's accepted identity without replacing its chat. @ObservationIgnored var onHermesDraftKeyChange: ((ChatDraftKey) -> Void)? - /// Stop asks first on a Hermes session holding a queued prompt or an open request, - /// which the stop would discard or deny. var stopNeedsConfirmation: Bool { hermesTurn?.stopNeedsConfirmation == true } - /// A Hermes session's host requests (#1011, #1141): its approvals, questions, sudo and - /// secret prompts, Desktop tasks and connection operations. Nil on a webui session, whose - /// prompts are `approvalPrompt` and `clarificationPrompt`. var hermesRequests: HermesChatRequests? { hermesTurn?.requests } - /// A Hermes session is parked on one of its host's requests. var isWaitingForUser: Bool { hermesRequests?.isWaiting == true } - /// A Hermes session's host is compacting its context mid-run (#1734). var isCompacting: Bool { hermesTurn?.isCompacting == true } - /// A Hermes session's host notices (#1746). Nil on a webui session, whose host sends none. var hermesHostNotices: HermesHostNotices? { hermesTurn?.hostNotices } - /// The host refused a Hermes session's saved password (#884, #942): the chat offers Update - /// sign-in and never signs in again on its own. var hermesNeedsSignIn: Bool { hermesTurn?.needsSignIn == true } - /// A Hermes session's goal, loop and heartbeat (#1142), `/btw` question and `/background` - /// tasks (#1013). Nil on a webui session. var hermesSideTasks: HermesChatSideTasks? { hermesTurn?.sideTasks } - /// Whether the toolbar shows the goal menu: once the chat has a goal, or a Hermes - /// session's loop or heartbeat (#1142). var showsGoalControls: Bool { hasActivatedGoalCommand || hermesSideTasks?.automations.isEmpty == false } - /// Sends the loop or heartbeat Pause or Resume confirmed in the goal menu (#1142). A - /// failure shows in the composer, like a goal command's. func confirmHermesAutomation(_ control: BotSessionControl) async { guard let sideTasks = hermesSideTasks else { return } do { @@ -3279,28 +2773,19 @@ final class ChatViewModel { } } - /// A Hermes session's plan and how its last turn ended (#1139). Nil on a webui session. var hermesActivity: HermesChatActivity? { hermesTurn?.activity } - /// A new chat in `profile` on this Hermes session's server and connection (#1015). func newHermesSessionChat(profile: String) -> HermesSessionChat? { hermesTurn.map { HermesSessionChat(server: $0.engine.server, connection: $0.engine.connection, target: .new(profile: profile)) } } - /// `/sessions` and a bare `/resume` in a Hermes chat (#1053): its Profile's Sessions list, - /// searching `query`. Webui has neither command. private func hermesSessionList(searching query: String) -> SlashCommandExecutionResult { guard let hermesTurn else { return .unsupported(friendlyMessage: SlashCommandExecutor.unsupportedMessage(for: "sessions")) } return .openedHermesSessionList(HermesSessionListEntry(server: hermesTurn.engine.server, connection: hermesTurn.engine.connection, profile: hermesTurn.settings.profile, query: query)) } - /// `/resume ` in a Hermes chat (#1053): searches the Profile for `name` and opens the - /// one session titled exactly that, ignoring case. Anything else (no such title, several, - /// a Bot Chat, which opens in its bot, or a failed search) opens the Sessions list searching - /// `name`, so it never opens the wrong chat. The host's search reads ids and message text, - /// not titles, so a title none of its messages share lands on the list, whose rows match it. private func resumeHermesSession(named rawName: String) async -> SlashCommandExecutionResult { let name = rawName.trimmingCharacters(in: .whitespacesAndNewlines) guard let hermesTurn, !name.isEmpty else { return hermesSessionList(searching: name) } @@ -3309,15 +2794,12 @@ final class ChatViewModel { let results = (try? await engine.wire.searchSessions(query: name, profile: profile)) ?? [] let titled = results.filter { $0.row.title?.compare(name, options: .caseInsensitive) == .orderedSame } guard titled.count == 1, let match = titled.first?.row, !match.isBotChat else { return hermesSessionList(searching: name) } - // Already open here. if match.id == engine.storedKey { return .executed(message: nil) } return .openedHermesSession(HermesSessionChat(server: engine.server, connection: engine.connection, target: .session(profile: match.profile ?? profile, key: match.id), parentKey: match.parentSessionID, lineageRoot: match.lineageRootID)) } - /// Moves this new Hermes chat's draft, files included, to `chat`, which replaces it. A - /// draft already waiting in that Profile's new chat stays, and this one keeps its key. func handOffHermesDraft(to chat: HermesSessionChat) async { guard let key = hermesDraftKey else { return } let target = chat.target.draftKey(server: chat.server, connectionID: chat.connection.id, lineageRoot: chat.lineageRoot) @@ -3325,9 +2807,6 @@ final class ChatViewModel { drafts.moveDraft(from: key, to: target) } - /// Moves a draft saved under the segment of a compression chain this chat opened by, before - /// drafts followed the chain's root (#1176), to the chain's key, unless that has one already. - /// The chat calls it before it restores its draft. func adoptHermesSegmentDraft() async { guard let hermesTurn, let segment = hermesTurn.segmentDraftKey else { return } let key = hermesTurn.currentDraftKey @@ -3335,13 +2814,10 @@ final class ChatViewModel { drafts.moveDraft(from: segment, to: key) } - /// Who asks in a Hermes session's request card: its Profile on its saved connection. var hermesRequestIdentity: String? { hermesTurn.map { String(localized: "\($0.engine.target.profile) on \($0.engine.connection.name)") } } - /// Attaches the Hermes session; its newest history page and live state fill the transcript. - /// After a failed history read (the chat's retry, a pull to refresh) it reads the page again. private func loadHermesSession(_ hermes: HermesChatTurnCoordinator) async { isLoading = messages.isEmpty errorMessage = nil @@ -3351,17 +2827,6 @@ final class ChatViewModel { if retriesHistory { await hermes.retryHistoryIfFailed() } } - /// Sends one prompt to the Hermes session in `mode`, once (#1010). A Send shows the - /// prompt at once and a Stop & send once it takes over; a steer shows its echo once - /// accepted; a queued prompt shows in `queuedPromptMessages` until the host runs it. - /// `.kept` keeps the draft: the host refused it, did not confirm it, or it was not sent. - /// `shown` is the prompt's row when it differs from what is sent, as for a goal's message; - /// such a prompt leaves the staged files where they are. A plain-text Send passes - /// `waitingOwner`, the waiting-send generation it began in: one that found no connection - /// before it went out is held as the waiting send instead (`.waiting`, #1407), unless the chat - /// left meanwhile. `delivering` is that send's generation going out, with no files, while it is - /// still current and unexpired; `.waiting` then means it did not go out and is the waiting send's - /// to settle. private func submitHermesPrompt( _ draft: String, mode: BotPromptMode, @@ -3370,19 +2835,15 @@ final class ChatViewModel { waitingOwner: Int? = nil, delivering: Int? = nil ) async -> ChatSendOutcome { - // Nothing but the waiting send goes while a Send is written as it, even once reconnected. guard delivering != nil || !isHoldingWaitingSend else { sendErrorMessage = String(localized: "Reconnect to the server to send a message.") return .kept } let text = draft.trimmingCharacters(in: .whitespacesAndNewlines) - // Only Send and Queue carry the staged files (#1012); Steer and Stop & send stay text-only, - // and so does a waiting send, which never takes files staged since. let files = mode.startsTurn && shown == nil && delivering == nil ? attachmentCoordinator.pendingAttachments : [] guard !text.isEmpty || !files.isEmpty, !isHermesSubmissionUncertain else { return .kept } sendErrorMessage = nil lastError = nil - // A staging error is stale once the files go; the status line shows the upload and its Cancel. if !files.isEmpty { attachmentCoordinator.setUploadAttachmentError(nil) } let promptID = "local-\(UUID().uuidString)" let prompt = ChatMessage( @@ -3399,10 +2860,6 @@ final class ChatViewModel { } defer { if mode == .send { isStartingChat = false } } - // #508: from just before the prompt goes out until the host answers, the draft and - // its files are on disk with the submission marked unresolved. A lost answer keeps - // all three and holds Send while the chat reattaches; that attach clears only the - // mark, and nothing is sent again. var marked = false let outcome: BotPromptOutcome do { @@ -3411,13 +2868,11 @@ final class ChatViewModel { outcome = try await hermes.submit(text, mode: mode, attachments: attachmentCoordinator.outgoingAttachments(files)) { [drafts] in let key = hermes.currentDraftKey - // Loaded first, so the mark never stands in for the saved draft. _ = await drafts.draft(for: key) drafts.setBotSubmissionUncertain(true, for: key) marked = true try await drafts.flush() } stillCurrent: { [weak self] in - // A waiting send that paused, left, expired or went back to the composer stays unsent. guard let delivering else { return } guard self?.waitingSendGoes(delivering) == true else { throw BotFailure.stale } } @@ -3455,25 +2910,20 @@ final class ChatViewModel { switch outcome { case .started: - // A queued send that found the host idle ran at once. if mode != .send { messages.append(prompt) } case .voiceStopped: - // The host took a stop phrase: it stopped the work and started no turn. rollbackOptimisticMessage(id: promptID) case .followUpQueued, .redirectQueued: - // The host runs it as a later turn, whose start shows it. rollbackOptimisticMessage(id: promptID) case .guidanceQueued: appendLocalSteerEcho(text) showSteeringConfirmation(String(localized: "Steering hint delivered.")) case .redirected: - // The turn carries on from the new prompt, and the reply after it gets its own row. flushPendingStreamingContent() streamingAssistantMessageID = nil messages.append(prompt) case .rejected: rollbackOptimisticMessage(id: promptID) - // A refused steer leaves the run going (#856). if mode == .steer { steerFailureMessage = String(localized: "Couldn't steer") } else { @@ -3486,29 +2936,20 @@ final class ChatViewModel { holdForLostAnswer(hermes) return .kept } - // Accepted: the host holds the files now, so their local copies go. await attachmentCoordinator.consumeSentAttachments(files) return .started } - /// A prompt's answer was lost: Send waits, and the chat reattaches so the snapshot - /// shows whether it ran (#508). Its connect releases the hold. private func holdForLostAnswer(_ hermes: HermesChatTurnCoordinator) { isHermesSubmissionUncertain = true hermes.recoverAfterLostAnswer() } - /// A Hermes draft reopened with its submission still marked unresolved holds Send until - /// the chat attaches, as a lost answer does (#508). func restoreSubmissionMark(_ uncertain: Bool) { - // Attached already: that attach's snapshot was read after the lost answer. guard uncertain, let hermesTurn, hermesTurn.engine.connectionState != .connected else { return } isHermesSubmissionUncertain = true } - /// Attached again: the host's snapshot now shows whether a prompt whose answer was lost - /// ran, so Send is free again and its unresolved mark goes. The draft and its files stay - /// as they are (#508). private func releaseSubmissionMark() { guard let key = hermesDraftKey, !isSubmittingHermesPrompt else { return } isHermesSubmissionUncertain = false @@ -3519,28 +2960,17 @@ final class ChatViewModel { } } - // MARK: Waiting send (#1407) - - /// Whether Send holds a plain-text draft until the chat reconnects instead of refusing it: a - /// Hermes chat showing its offline cache, idle, signed in, with no files staged and nothing - /// waiting or unresolved. var offersWaitingSend: Bool { guard let hermesTurn else { return false } return showsOfflineCache && waitingSend == nil && activeStreamID == nil && !isHermesSubmissionUncertain && !hermesTurn.needsSignIn && attachmentCoordinator.pendingAttachments.isEmpty } - /// The waiting send as the transcript's pending bubble shows it, outside `messages`. Hidden - /// while it goes out, when the prompt's own row shows. var waitingSendMessage: ChatMessage? { guard let waitingSend, waitingSend.delivery == nil else { return nil } return ChatMessage(role: "user", content: waitingSend.send.text, timestamp: nil, messageId: "hermes-waiting-send") } - /// Holds `draft` as the waiting send once it is on disk, out of the draft's text in the same - /// write, with one deadline. `.kept` when another is waiting or being written, that write failed, - /// or the chat left since `owner`: in the last two the text goes back to the draft, ahead of - /// anything typed since, and to the composer, and nothing sends it. private func holdForConnection(_ draft: String, on hermes: HermesChatTurnCoordinator, owner: Int) async -> ChatSendOutcome { let notHeld = String(localized: "Reconnect to the server to send a message.") guard waitingSend == nil, !isHoldingWaitingSend else { @@ -3566,30 +2996,22 @@ final class ChatViewModel { waitingSendDeadline?.cancel() waitingSendDeadline = Task { [weak self, sleep = waitingSendClock.sleep] in do { try await sleep(remaining) } catch { return } - // One going out is checked at its socket write instead. guard let self, self.waitingSend?.send == send, self.waitingSend?.delivery == nil else { return } self.returnWaitingSend(.expired) } - // A reattach while the prompt failed to go out is a reconnect already. deliverWaitingSendIfReady() return .waiting } - /// Whether the delivery claimed at `generation` may still go out: nothing paused, left or - /// returned it since, and it has not expired. private func waitingSendGoes(_ generation: Int) -> Bool { waitingSendGeneration == generation && waitingSend?.hasExpired(at: waitingSendClock.now()) == false } - /// Cancel on the waiting bubble: its text goes back to the composer. Not once it is going out. func cancelWaitingSend() { guard let waitingSend, waitingSend.delivery == nil else { return } returnWaitingSend(.cancelled) } - /// The chat left the screen: its waiting send goes back to the draft and never sends from here, - /// and a Send still looking for its connection never becomes one. One already going out - /// finishes, and goes back unless the host took it. func leaveWaitingSend() { waitingSendGeneration += 1 guard var waiting = waitingSend else { return } @@ -3601,8 +3023,6 @@ final class ChatViewModel { } } - /// The app went to the background, where the socket closes: a delivery not out yet stops before - /// it reattaches or writes, and waits for the foreground's reattach. private func pauseWaitingSend() { guard var waiting = waitingSend, waiting.delivery == .sending else { return } waitingSendGeneration += 1 @@ -3610,7 +3030,6 @@ final class ChatViewModel { waitingSend = waiting } - /// Puts the waiting send back in the draft and the composer, and ends its deadline. private func returnWaitingSend(_ reason: HermesWaitingSend.Return) { guard let waiting = waitingSend else { return } waitingSend = nil @@ -3620,8 +3039,6 @@ final class ChatViewModel { onWaitingSendReturned?(draft?.text ?? waiting.send.text, reason) } - /// Sends the waiting send once its chat is attached and live again: under the draft key it was - /// held in, before it expires, and once per attach, claimed before anything awaits. private func deliverWaitingSendIfReady() { guard var waiting = waitingSend, waiting.delivery == nil, let hermes = hermesTurn, hermes.engine.connectionState == .connected, !isViewingCachedData, !isHermesSubmissionUncertain, @@ -3634,7 +3051,6 @@ final class ChatViewModel { waitingSend = waiting Task { [weak self] in guard let self else { return } - // Checked as it starts, since a submit would reattach a socket the background closed. let outcome = self.waitingSendGoes(generation) ? await self.submitHermesPrompt(waiting.send.text, mode: .send, to: hermes, delivering: generation) : .waiting @@ -3642,9 +3058,6 @@ final class ChatViewModel { } } - /// The host took the waiting send, and only it leaves the draft. One that did not go out waits - /// for a distinct reconnect, unless it expired or its chat left; anything else goes back to the - /// composer, a lost answer with its #508 hold. private func finishWaitingSend(_ outcome: ChatSendOutcome) { guard var waiting = waitingSend else { return } switch outcome { @@ -3666,7 +3079,6 @@ final class ChatViewModel { } } - /// Why a Hermes send's files did not upload; the text and files stay in the composer. private static func uploadFailureMessage(_ error: Error) -> String { if error is CancellationError || error as? BotFailure == .stale { return String(localized: "Upload cancelled. Your message and attachments are still here.") @@ -3675,15 +3087,10 @@ final class ChatViewModel { return String(localized: "Couldn't upload the attachments. Your message and attachments are still here.") } - /// Stops a Hermes send's uploads before its prompt goes out (#1012). func cancelAttachmentUpload() { hermesTurn?.cancelAttachmentUpload() } - /// A send while a Hermes turn runs: Steer is `session.steer`, Queue the host's queue, - /// and Stop & send `session.redirect` (#858). With files staged a Steer queues, since - /// only a fresh turn takes them, and Stop & send goes text-only, leaving them staged - /// (#1012). A turn that ended meanwhile takes a plain send. private func submitHermesStreamingMessage( _ draft: String, behavior: StreamingSendBehavior, @@ -3698,21 +3105,9 @@ final class ChatViewModel { return await submitHermesPrompt(draft, mode: mode, to: hermes) == .started ? .executed(message: nil) : .notDelivered } - /// Records → transcribes → uploads → sends a server-transcribed voice note - /// (Telegram-style). The sent message's text is the transcript and its sole - /// attachment is the audio clip, rendered as a playable note by the inline - /// audio player. Aborts (toast, no partial send) if transcription fails or - /// returns nothing. Returns true only if the chat send started. @discardableResult func sendVoiceNote(audioData: Data, filename: String, modelContext: ModelContext? = nil) async -> Bool { - // Voice notes ride on webui transcription, which a Hermes host does not offer. guard hermesTurn == nil else { return false } - // Reentrancy guard: bail if a voice note OR a regular chat send is already - // in flight. `performChatSend` has no internal guard, so two overlapping - // sends would both flip `isStartingChat`/`isSendingVoiceNote` and race their - // `defer { … = false }` (clearing the flag while the other still runs, and - // firing two concurrent `startChat`s). The UI already blocks this; the guard - // keeps a future caller (accessibility shortcut, test harness) safe too. guard !isSendingVoiceNote, !isStartingChat else { return false } guard !isViewingCachedData else { setUploadAttachmentError(String(localized: "Reconnect to the server to send a voice note.")) @@ -3734,8 +3129,6 @@ final class ChatViewModel { lastError = nil defer { isSendingVoiceNote = false } - // 1. Transcribe via server STT. Any error or empty transcript aborts the - // whole send — no fallback, no partial message (per the issue). let transcript: String do { let response = try await client.transcribeAudio(data: audioData, filename: filename) @@ -3756,8 +3149,6 @@ final class ChatViewModel { return false } - // 2. Upload the clip as a standalone attachment (kept out of the composer's - // pending list). On failure the coordinator already surfaced the error. guard let pending = await attachmentCoordinator.uploadStandaloneAttachment( data: audioData, filename: filename @@ -3765,7 +3156,6 @@ final class ChatViewModel { return false } - // 3. Send a chat message: text = transcript, attachments = [the clip]. let messageAttachment = MessageAttachment( name: pending.name, path: pending.path, @@ -3774,14 +3164,6 @@ final class ChatViewModel { isImage: pending.isImage ) let localMessageID = "local-\(UUID().uuidString)" - // The API message text is the bare transcript — NOT chatMessageText(…), - // which would append a "[Attached files: .m4a]" suffix. That suffix - // is the agent's only signal about a non-image attachment (the server - // strips attachment metadata before the model call and never embeds audio), - // so it makes the agent try to "inspect" / transcribe the clip itself - // instead of just answering the transcript. The clip still rides along in - // `messageAttachments` / `apiPayloads` purely so the inline player renders - // and persists; it's display-only and never reaches the model. (#330) return await performChatSend( sessionID: sessionID, localMessageID: localMessageID, @@ -3794,10 +3176,6 @@ final class ChatViewModel { ) } - /// Shared optimistic-append + `startChat` + rollback core used by both the - /// text composer (`sendMessage`) and the voice-note flow (`sendVoiceNote`). - /// `attachmentsToRestoreOnFailure` is re-staged into the composer if the send - /// fails — empty for voice notes, whose clip isn't a composer attachment. private func performChatSend( sessionID: String, localMessageID: String, @@ -3873,8 +3251,6 @@ final class ChatViewModel { ) return true } catch { - // Submission-owned cleanup survives navigation/cancellation. Roll - // back only this message and merge attachments with newer work. rollbackOptimisticMessage(id: localMessageID) cacheCurrentMessages(sessionID: sessionID, modelContext: modelContext) restorePendingAttachments(attachmentsToRestoreOnFailure) @@ -3891,7 +3267,6 @@ final class ChatViewModel { if allowsCompressionContinuation, let rotation = (error as? APIError)?.sessionRotation, rotation.continuationSessionID != sessionID { - // This POST was rejected. GET may resolve a newer tip, but never replay it. lastError = error sendErrorMessage = error.localizedDescription compressionContinuationID = rotation.continuationSessionID @@ -3901,9 +3276,6 @@ final class ChatViewModel { } if let apiError = error as? APIError, apiError.serverCode != "session_rotated", let streamID = apiError.activeStreamID { - // The existing run may have started outside this view model. Reconcile - // the server transcript first so the SSE tokens attach to the persisted - // assistant turn instead of creating a second bubble with only the tail. await loadMessages(modelContext: modelContext) guard generation == chatSendGeneration, !Task.isCancelled else { return false } _ = restoreActiveStreamSnapshotIfAvailable(streamID: streamID) @@ -3911,9 +3283,6 @@ final class ChatViewModel { .currentTurnAssistantAnchorIDs(in: messages, messageOffset: messagesOffset) .first streamCoordinator.start(streamID: streamID) - // The server kept the earlier run, not this newly submitted text. - // Report an unaccepted send so ChatView restores the draft while - // the coordinator reconnects to the existing response. return false } lastError = error @@ -3923,10 +3292,6 @@ final class ChatViewModel { } } - /// Loads the continuation a `session_rotated` 409 named, for - /// `compressionContinuationForNavigation`. The rejected send's catch calls it - /// first; a later Send on the sealed parent retries it after a failed load. - /// Neither path posts the message again. private func resolveCompressionContinuation(id: String, from sessionID: String, profile: String, generation: Int) async { do { @@ -4021,11 +3386,6 @@ final class ChatViewModel { } } - /// A `/goal` command in a Hermes session (#1013), through the host's own `/goal`: `exec` - /// output shows as a notice, and a `send` message goes out once (#508), shown as the - /// host's `display` when it names one; mid-turn the host queues it. A new goal waits for - /// a running turn to finish, as on webui; the control verbs do not, since a goal's own - /// turns keep the session busy. private func submitHermesGoal(_ args: String, to hermes: HermesChatTurnCoordinator) async -> Bool { func fail(_ message: String) -> Bool { goalErrorMessage = message @@ -4035,7 +3395,6 @@ final class ChatViewModel { guard activeStreamID == nil || HermesChatSideTasks.isGoalControl(args) else { return fail(String(localized: "Wait for the current response to finish before changing goals.")) } - // A lost prompt holds every send until the chat reattaches, and a goal's message is one. guard !isHermesSubmissionUncertain else { return fail(String(localized: "Wait for Hermes to confirm the last message before changing goals.")) } @@ -4050,17 +3409,14 @@ final class ChatViewModel { do { reply = try await hermes.sideTasks.dispatchGoal(args) } catch let error where error is HermesChatTurnCoordinator.NotSent || HermesChatSideTasks.isReaped(error) { - // Never sent, or the runtime was reaped and the chat is reattaching. return fail(String(localized: "Reconnect to the server to manage goals.")) } catch let refusal as BotSettingFailure { - // The host's own reason, such as an invalid `/goal wait`. return fail(refusal.localizedDescription) } catch { return fail(String(localized: "Hermes did not confirm the goal command. Check the goal before trying again.")) } hasActivatedGoalCommand = true - // Mid-turn a notice is pinned above the composer until the turn ends, as on webui. func notify(_ text: String) { if activeStreamID == nil { appendLocalNoticeMessage(text) } else { pinLocalNoticeMessage(text) } } @@ -4071,7 +3427,6 @@ final class ChatViewModel { case .send(let notice, let message, let display): if let notice { notify(notice) } let mode: BotPromptMode = activeStreamID == nil ? .send : .queue - // The goal is set either way; its message is never sent again by itself (#508). guard await submitHermesPrompt(message, mode: mode, to: hermes, shown: display ?? message) == .started else { return fail(String(localized: "Hermes did not confirm the goal command. Check the goal before trying again.")) } @@ -4154,8 +3509,6 @@ final class ChatViewModel { sendErrorMessage = nil } - /// `modelContext` is only needed by commands that rewrite the offline cache - /// (`/clear`); every other command ignores it. func executeSlashCommand( _ command: SlashCommand, args: String = "", @@ -4262,7 +3615,6 @@ final class ChatViewModel { return sent ? .executed(message: nil) : .unsupported(friendlyMessage: sendErrorMessage ?? String(localized: "Could not send the queued message.")) } - // `queuedMessagesReceipt` says it's queued. enqueueQueuedSlashMessage(message, attachments: attachmentCoordinator.consumePendingAttachments()) return .executed(message: nil) } @@ -4282,9 +3634,6 @@ final class ChatViewModel { return sent ? .executed(message: nil) : .unsupported(friendlyMessage: sendErrorMessage ?? String(localized: "Could not send the steering message.")) } - // Staged attachments ride along as an attached-files note. No outcome - // stops the run: the server's steer contract leaves Queue and Stop & - // send to the user. let steeredAttachments = attachmentCoordinator.pendingAttachments let steerText = PendingAttachment.steerMessageText(draft: message, attachments: steeredAttachments) @@ -4292,8 +3641,6 @@ final class ChatViewModel { case .delivered: appendLocalSteerEcho(steerText) showSteeringConfirmation(String(localized: "Steering hint delivered.")) - // Delete the durable copies of the files that rode along, as - // `sendMessage` does. takeSteeredAttachments(steeredAttachments) for attachment in steeredAttachments { guard let fileName = attachment.draftFileName else { continue } @@ -4309,9 +3656,6 @@ final class ChatViewModel { steerFailureMessage = transportError.map { "\(title)\n\($0.localizedDescription)" } ?? title return .notDelivered } - // The run ended while the steer was in flight, so "Couldn't steer" - // and its Retry would outlive it. A network failure is now a failed - // send; a server refusal goes out as a normal turn, like `.runEnded`. if let transportError { sendErrorMessage = transportError.localizedDescription return .notDelivered @@ -4320,24 +3664,14 @@ final class ChatViewModel { case .serverQueued: enqueueQueuedSlashMessage(message, attachments: takeSteeredAttachments(steeredAttachments)) case .runEnded: - // Queue first, then ask the server whether the run is over. When it - // is and the transcript has the reply, the coordinator finishes the - // run, which drains the queue as a normal send. Otherwise the live - // stream still owns the ending, and its own finish drains the queue. enqueueQueuedSlashMessage(message, attachments: takeSteeredAttachments(steeredAttachments), atFront: true) await streamCoordinator.refreshTranscriptIfCompleted(streamID: steeredStreamID) } - // The run may have finished while the steer was in flight, after its - // own drain found the queue empty. While it runs, `queuedMessagesReceipt` - // says the message is queued. drainQueuedSlashMessageIfIdle() return .executed(message: nil) } - /// Takes the files that rode along on a steer out of the composer and - /// returns the ones still staged. Files staged while the steer was in - /// flight stay for the next message. @discardableResult private func takeSteeredAttachments(_ steered: [PendingAttachment]) -> [PendingAttachment] { guard !steered.isEmpty else { return [] } @@ -4347,29 +3681,17 @@ final class ChatViewModel { return staged.filter { steeredIDs.contains($0.id) } } - /// Clears "Couldn't steer" once the user moves on: the next send, a draft - /// edit, or the end of the run. func clearSteerFailure() { - // Guarded: draft edits call this on every keystroke, and an - // `@Observable` write notifies even when the value is unchanged. guard steerFailureMessage != nil else { return } steerFailureMessage = nil } - /// Clears the composer's one-off errors (a refused send, slash command, or setting change) - /// once the user edits the draft or taps Dismiss (#1694). An unserved Profile's and a stale - /// runtime's errors stay: they describe the host, not one attempt. func clearComposerErrors() { - // Guarded like `clearSteerFailure()`: draft edits call this on every keystroke. if sendErrorMessage != nil, errorUnserved == nil, sendErrorRuntimeStale == nil { sendErrorMessage = nil } if composerConfigurationErrorMessage != nil { composerConfigurationErrorMessage = nil } hermesSettings?.controls.clearError() } - /// Appends the local echo of an accepted steer immediately, so the hint is - /// visible before the server persists it. The `local-steer-` id marks it as - /// optimistic: when the persisted row arrives in `.done` or a reload, the - /// steer-aware merge drops this echo instead of duplicating it. private func appendLocalSteerEcho(_ text: String) { messages.append(ChatMessage( role: "user", @@ -4398,8 +3720,6 @@ final class ChatViewModel { let handOverCount = queueHandOverCount await cancelActiveStream() - // The chat was left while the cancel was in flight, so the message is - // in the draft now (#857) and nothing is queued to report. guard queueHandOverCount == handOverCount else { return .executed(message: nil) } if activeStreamID != nil { @@ -4409,8 +3729,6 @@ final class ChatViewModel { return .executed(message: String(localized: "Interrupted the current response and queued your message to send next.")) } - /// Pinned when an interrupt couldn't stop the run. It describes the queue, - /// so `takeQueuedMessages()` unpins it. private static var interruptQueuedFallbackNotice: String { String(localized: "Could not stop the current response yet, so the interrupt message was queued for the next turn.") } @@ -4532,9 +3850,6 @@ final class ChatViewModel { } } - /// `/btw` in a Hermes session (#1013): asked even while a turn runs, and answered in the - /// panel, never the transcript. One at a time. A question that was not sent or was - /// refused keeps its draft. private func askHermesBtw(_ question: String, sideTasks: HermesChatSideTasks) async -> SlashCommandExecutionResult { guard !sideTasks.isAsking else { return notDelivered(String(localized: "Wait for the current /btw answer to finish first.")) @@ -4549,9 +3864,6 @@ final class ChatViewModel { return .executed(message: nil) } - /// `/background` in a Hermes session (#1013): its card shows the task running until the - /// result replaces it. A task that did not start, or whose start was not confirmed, - /// keeps its draft and is never sent again by itself. private func startHermesBackground(_ prompt: String, sideTasks: HermesChatSideTasks) async -> SlashCommandExecutionResult { do { try await sideTasks.startBackground(prompt) @@ -4565,31 +3877,21 @@ final class ChatViewModel { return .executed(message: nil) } - /// Keeps the draft, and says why on the composer's status line. private func notDelivered(_ message: String) -> SlashCommandExecutionResult { sendErrorMessage = message return .notDelivered } - // MARK: Hermes slash commands - - /// The host's slash commands in a Hermes chat (#1036); nil on webui. var hermesSlashCommands: HermesSlashCommands? { hermesTurn?.slashCommands } - /// The agent commands the composer offers: a Hermes host's catalog, less what the chat - /// refuses (#1145), or webui's list. var composerAgentCommands: [AgentCommand] { hermesTurn?.slashCommands.commands ?? agentCommands } - /// The skills the composer offers: a Hermes host's catalog, or webui's list. var composerSkillSuggestions: [SkillSlashSuggestion] { hermesTurn?.slashCommands.catalog.skills ?? skillSlashSuggestions } - /// Runs a Hermes chat's draft that opens with `/name` (#1036): Hermex's own command, the - /// #702 notice for a held one, a skill's expansion, or the host's `slash.exec`. Nil when - /// the name is no command this chat or its host knows, so the draft is sent as typed. func runHermesSlashCommand(_ draft: String, modelContext: ModelContext? = nil) async -> SlashCommandExecutionResult? { guard let hermesTurn, let invocation = BotSlashCatalog.invocation(in: draft) else { return nil } return await runHermesSlashCommand(invocation, line: draft.trimmingCharacters(in: .whitespacesAndNewlines), @@ -4634,14 +3936,12 @@ final class ChatViewModel { return .executed(message: nil) case .send(let message, let shown, let notice): if let notice { notifyLocally(notice) } - // A running turn queues it, as any send does. let mode: BotPromptMode = activeStreamID == nil ? .send : .queue return await submitHermesPrompt(message, mode: mode, to: hermes, shown: shown) == .started ? .executed(message: nil) : .notDelivered case .prefill(let message, let notice): if let notice { notifyLocally(notice) } return .prefill(message) case .alias(let target): - // Run once, with the typed argument; an alias to another alias is refused. let line = invocation.argument.isEmpty ? "/\(target)" : "/\(target) \(invocation.argument)" guard !followsAlias, let next = BotSlashCatalog.invocation(in: line) else { return notDelivered(String(localized: "/\(name) points to another alias, so Hermex didn't run it.")) @@ -4650,8 +3950,6 @@ final class ChatViewModel { } } - /// Why a Hermes slash command did not run. The draft stays. A refusal is the host's own - /// message, except in a chat with nothing sent yet, where there is nothing to run it on. private func hermesSlashFailure(_ error: Error, name: String) -> SlashCommandExecutionResult { switch error { case let notSent as HermesChatTurnCoordinator.NotSent where notSent.followedReplacedChat: @@ -4670,13 +3968,10 @@ final class ChatViewModel { } } - /// A notice in the transcript, or pinned above the composer while a turn runs. private func notifyLocally(_ text: String) { if activeStreamID == nil { appendLocalNoticeMessage(text) } else { pinLocalNoticeMessage(text) } } - /// `/yolo` in a Hermes chat (#1036): this session's approval bypass, through the same - /// `config.set yolo` as the approval card's Skip all and Model settings' switch. private func toggleHermesApprovalBypassFromSlashCommand() async -> SlashCommandExecutionResult { guard let requests = hermesRequests else { return .unsupported(friendlyMessage: SlashCommandExecutor.unsupportedMessage(for: "yolo")) @@ -4696,8 +3991,6 @@ final class ChatViewModel { return .executed(message: nil) } - /// A typed `/goal`. On failure a Hermes session keeps the draft, as its sends do (#1013), - /// with the status line `submitGoal` set; nothing is sent again by itself. Webui clears it. private func submitGoalFromSlashCommand(_ args: String) async -> SlashCommandExecutionResult { let goalArgs = args.trimmingCharacters(in: .whitespacesAndNewlines) let didSubmit = await submitGoal(args: goalArgs.isEmpty ? "status" : goalArgs) @@ -4753,9 +4046,6 @@ final class ChatViewModel { } } - /// `/model` in a Hermes session (#1015): the name resolves against `model.options` and - /// goes through the chip's pick, its expensive-model confirm included. A name the - /// catalog lacks is refused here rather than sent to the host as a guess. private func switchHermesModelFromSlashCommand(_ requestedModel: String, settings: HermesChatSettings) async -> SlashCommandExecutionResult { guard let option = settings.model(matching: requestedModel) else { @@ -4812,12 +4102,9 @@ final class ChatViewModel { } } - /// `/workspace` in a Hermes chat (#1673): the folder chip's pick. A move, the same folder, - /// or the move confirm it raises is done; a refusal keeps the draft and says why. private func switchHermesFolderFromSlashCommand(_ path: String) async -> SlashCommandExecutionResult { composerConfigurationErrorMessage = nil if await selectWorkspacePath(path) || pendingHermesFolder != nil { return .executed(message: nil) } - // The refusal moves to the send error, so one Dismiss or edit clears it (#1694). guard let refusal = composerConfigurationErrorMessage else { return .executed(message: nil) } composerConfigurationErrorMessage = nil return notDelivered(refusal) @@ -4899,8 +4186,6 @@ final class ChatViewModel { } } - /// `/title` in a Hermes chat (#1048): `session.title` on the chat's runtime, so Desktop and the - /// list see it at once. The host's refusal (a title in use, too long) keeps the draft. private func renameHermesSessionFromSlashCommand( _ title: String, on hermes: HermesChatTurnCoordinator @@ -4911,7 +4196,6 @@ final class ChatViewModel { applyLiveActivitySessionTitle(kept) return .executed(message: String(localized: "Title set to **\(displayTitle)**.")) } catch let error where HermesChatSideTasks.isReaped(error) { - // The chat is reattaching to a new runtime; nothing was renamed. return notDelivered(String(localized: "Reconnect to the server to run /\("title").")) } catch BotSettingFailure.rejected(_, let message) { return notDelivered(message) @@ -4973,7 +4257,6 @@ final class ChatViewModel { } } - /// The `/personality` list a webui server or Hermes host answered, with how to pick one. private static func personalityListMessage( _ personalities: [(name: String, description: String)] ) -> SlashCommandExecutionResult { @@ -4989,9 +4272,6 @@ final class ChatViewModel { return .executed(message: String(localized: "Available personalities:\n\n\(list)\n\nUse `/personality ` or `/personality none`.")) } - /// `/reasoning` in a Hermes session (#1016): a level goes through the effort chip's pick, - /// for this chat only. Display words are refused before anything is sent: on the host they - /// rewrite the display settings every client shares. private func switchHermesReasoningFromSlashCommand( _ level: String, settings: HermesChatSettings @@ -5013,7 +4293,6 @@ final class ChatViewModel { return .unsupported(friendlyMessage: String(localized: "This model can't turn reasoning off.")) } guard level != settings.controls.effort else { return .executed(message: nil) } - // As the effort menu is, while a reply runs. guard activeStreamID == nil else { return .unsupported(friendlyMessage: String(localized: "Wait for the current response to finish before changing reasoning.")) } @@ -5022,9 +4301,6 @@ final class ChatViewModel { ?? String(localized: "Wait for this chat to connect before changing reasoning.")) } - /// `/personality` in a Hermes session (#1016). Bare, it lists the host's personalities. A - /// name waits for the user to confirm it (`HermesChatSettings.pendingPersonality`), because - /// the host writes it to the Profile's default; `none`, `default` and `clear` clear it. private func askHermesPersonalityFromSlashCommand( _ requested: String, settings: HermesChatSettings @@ -5043,16 +4319,10 @@ final class ChatViewModel { return .executed(message: nil) } - // MARK: Hermes rollback (#1728) - - /// A `/rollback` restore waiting for the user to confirm it. private(set) var pendingHermesRollback: HermesRollbackRequest? func cancelHermesRollback() { pendingHermesRollback = nil } - /// `/rollback` in a Hermes chat: lists the host's checkpoints, shows one's diff, or asks - /// before restoring from one (`pendingHermesRollback`). A diff or restore reads the list - /// first and sends the hash of the checkpoint the number names now. private func rollbackFromSlashCommand(_ args: String) async -> SlashCommandExecutionResult { guard let hermes = hermesTurn else { return .unsupported(friendlyMessage: SlashCommandExecutor.unsupportedMessage(for: "rollback")) @@ -5068,14 +4338,12 @@ final class ChatViewModel { guard let checkpoints = try await slash.checkpoints() else { return checkpointsOff() } notifyLocally(Self.checkpointList(checkpoints)) case .diff(let ref): - // A host answers a hash it doesn't hold with an empty diff, so the list names it first. guard let checkpoints = try await slash.checkpoints() else { return checkpointsOff() } guard let checkpoint = HermesCheckpoint.named(ref, in: checkpoints) else { return noCheckpoint(ref) } let diff = try await slash.checkpointDiff(checkpoint.hash) notifyLocally(Self.checkpointDiff(stat: diff.stat, diff: diff.diff)) case .restore(let ref, let filePath): if filePath == nil { - // A whole-tree restore can rewind the newest turn (#1127 decision 3). if slash.policy == .botChat { return .unsupported(friendlyMessage: String(localized: "A bot’s chat can’t be rewound.")) } if activeStreamID != nil { return notDelivered(String(localized: "Wait for the current reply to finish.")) } } @@ -5089,9 +4357,6 @@ final class ChatViewModel { } } - /// Sends the `/rollback` restore the user confirmed, by the checkpoint's hash. A whole-tree - /// restore that rewound the newest turn leaves the transcript without it. Send waits while a - /// whole-tree restore is out, as for `/undo`, so no prompt races the host's rewind. func confirmHermesRollback(_ request: HermesRollbackRequest) async -> SlashCommandExecutionResult { pendingHermesRollback = nil guard let hermes = hermesTurn else { return .notDelivered } @@ -5110,10 +4375,8 @@ final class ChatViewModel { do { outcome = try await hermes.restoreCheckpoint(request.checkpoint.hash, filePath: request.filePath) } catch BotSettingFailure.rejected(let code, let message) { - // The host answered: a refusal is its reason, not a lost answer. return notDelivered(hermesRollbackFailure(BotSettingFailure.rejected(code, message))) } catch { - // A whole-tree restore whose answer was lost may have rewound the chat: Send waits. return notDelivered(wholeTree ? hermesHistoryFailure(error, on: hermes, reconnect: reconnect) : hermesRollbackFailure(error)) } guard outcome.success else { @@ -5132,7 +4395,6 @@ final class ChatViewModel { return .executed(message: nil) } - /// Why a `/rollback` call failed: busy, a gone runtime, which reattaches, or the host's own words. private func hermesRollbackFailure(_ error: Error) -> String { switch error { case let notSent as HermesChatTurnCoordinator.NotSent where notSent.followedReplacedChat: @@ -5150,7 +4412,6 @@ final class ChatViewModel { } } - /// The checkpoints as a numbered list: number, short hash, local time and the host's reason. static func checkpointList(_ checkpoints: [HermesCheckpoint]) -> String { guard !checkpoints.isEmpty else { return String(localized: "This chat’s folder has no checkpoints yet.") } let rows = checkpoints.map { checkpoint in @@ -5162,13 +4423,10 @@ final class ChatViewModel { .joined(separator: "\n") } - /// A checkpoint's time in the user's locale; the host's text when it doesn't parse. static func checkpointTime(_ timestamp: String) -> String { - // The host writes git's strict ISO 8601 (`%aI`), with an offset. ISO8601DateFormatter().date(from: timestamp)?.formatted(date: .abbreviated, time: .shortened) ?? timestamp } - /// A checkpoint's diff: the stat, then the diff in a `diff` fence. static func checkpointDiff(stat: String, diff: String) -> String { let diff = diff.trimmingCharacters(in: .newlines) guard !diff.trimmingCharacters(in: .whitespaces).isEmpty || !stat.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { @@ -5180,7 +4438,6 @@ final class ChatViewModel { .filter { !$0.isEmpty }.joined(separator: "\n\n") } - /// What a restore did: the files it put back, the user's edits it kept, and the turn it removed. static func rollbackNotice(_ outcome: HermesRollbackOutcome, _ request: HermesRollbackRequest) -> String { let hash = "`\(request.checkpoint.shortHash)`" var lines: [String] @@ -5199,7 +4456,6 @@ final class ChatViewModel { return lines.joined(separator: "\n\n") } - /// Sends the `/personality` change the user confirmed. The notice names the Profile it changed. func confirmHermesPersonality(_ name: String) async -> SlashCommandExecutionResult { guard let settings = hermesSettings else { return .notDelivered } guard activeStreamID == nil else { @@ -5270,26 +4526,17 @@ final class ChatViewModel { return suggestions } - /// The one way the skill list changes, so the chip catalog can never fall - /// out of step with it. private func applySkillSlashSuggestions(_ suggestions: [SkillSlashSuggestion]) { let previousCatalog = skillChipCatalog skillSlashSuggestions = suggestions skillChipCatalog = ComposerChipCatalog(skills: suggestions) composerChipCatalog = skillChipCatalog.withFilePaths(fileChipPaths) - // A catalog that draws differently redraws the transcript: sent `/slug` - // text becomes a chip, or an existing chip changes size or goes away. - // Signal the relayout so a reader pinned to the bottom stays there. A - // list that came back the same changes nothing and says nothing. if skillChipCatalog != previousCatalog { transcriptRelayoutScrollToken += 1 } } - /// Where this chat's `@` panel and `@path` chips look files up: a webui session's workspace - /// listings, or a Hermes chat's `complete.path` while its folder is on a `local` backend, - /// the same gate as Files (#1113). Nil closes the panel and leaves `@…` as text. private enum FileReferenceSource { case webui(sessionID: String) case hermes(HermesChatTurnCoordinator) @@ -5301,12 +4548,8 @@ final class ChatViewModel { return .webui(sessionID: sessionID) } - /// Whether the composer opens its `@` panel for this chat. var offersFilePathSearch: Bool { fileReferenceSource != nil } - /// One query's rows for the composer's `@` panel, into `filePathSearch`. A Hermes chat's - /// host searches every folder and ranks its own rows; a webui chat's folder is listed and - /// ranked here. func searchFilePaths(_ query: String) async { switch fileReferenceSource { case .webui(let sessionID): @@ -5318,12 +4561,6 @@ final class ChatViewModel { } } - /// Remembers a workspace file the user picked in the composer, so its - /// `@path` draws as a chip there and in the sent message. - /// - /// Recorded straight away rather than waiting on the server: the panel only - /// ever offers paths a listing just returned, so the chip appears with the - /// insertion instead of a beat later. func recordFileChipReference(_ path: String) { let path = path.trimmingCharacters(in: .whitespacesAndNewlines) guard !path.isEmpty else { return } @@ -5333,36 +4570,14 @@ final class ChatViewModel { fileChipPaths.insert(path) composerChipCatalog = skillChipCatalog.withFilePaths(fileChipPaths) - // A wider catalog can turn sent `@path` text into a chip, which changes - // the height of a bubble already on screen. transcriptRelayoutScrollToken += 1 } - /// Confirms the `@path` candidates in `draft` and in the transcript's user - /// messages against the session's workspace. - /// - /// What the composer picked lives in this view model, and this view model - /// dies when the chat is left — so on the way back in, and on any other - /// device, the only thing that knows a `@word` is a file is the server. Each - /// candidate's parent folder is listed once, through the same cache the `@` - /// panel fills (a Hermes chat asks `complete.path` instead), and every - /// candidate the listing contains becomes a chip in both the composer and - /// the transcript. - /// - /// The work lives on a task this view model owns, like the skill loader: a - /// caller cancelled by an unrelated view update cannot take the listings - /// down with it, and a caller arriving mid-pass waits for that pass rather - /// than starting a second one over the same folders. - /// - /// Held while the chat shows its offline cache: a draft typed then asks the host - /// nothing, and the chat asks for a fresh pass once it reconnects. func loadFileChipReferences(draft: String) async { while let existing = fileChipReferenceLoad { await existing.value } - // Resolved after the wait: the workspace may have moved meanwhile, such as a Hermes - // folder leaving the `local` backend, which closes the source. guard !showsOfflineCache, let source = fileReferenceSource else { return } let candidates = fileChipReferenceCandidates(draft: draft) guard !candidates.isEmpty else { return } @@ -5380,20 +4595,9 @@ final class ChatViewModel { await load.value } - /// Forgets every confirmed `@path` because the workspace moved. - /// - /// A path is only a file inside the workspace it was found in, so switching - /// one has to take the chips with it — including the ones accepted from the - /// panel, which were never checked against anything else. The revision bump - /// is what asks the chat for a fresh pass, so a file that exists under the - /// new root as well comes straight back. `reloadingOpenQuery` also reloads an - /// open `@` panel (`ComposerFilePathSearch.reset(reloadingOpenQuery:)`). private func resetFileChipReferences(reloadingOpenQuery: Bool = false) { filePathSearch.reset(reloadingOpenQuery: reloadingOpenQuery) checkedFileChipCandidates.removeAll() - // Cancelling, not just forgetting: a pass left running would keep - // listing the old root's folders, and every folder it had already - // listed would settle candidates against a workspace that is gone. fileChipReferenceLoad?.cancel() fileChipReferenceLoad = nil fileChipReferenceLoadGeneration &+= 1 @@ -5406,15 +4610,10 @@ final class ChatViewModel { transcriptRelayoutScrollToken += 1 } - /// Every `@…` the chat still has no answer for, draft first: what the user - /// is looking at while typing is worth confirming before the backlog. private func fileChipReferenceCandidates(draft: String) -> [String] { var candidates: [String] = [] var seen: Set = [] - // The draft's own trailing reference counts as finished here: a chip - // whose trailing space was backspaced is still a reference, and by the - // time a pass runs the user has moved on to whatever changed the token. for text in [draft] + messages.filter({ $0.role == "user" }).map({ $0.content ?? "" }) { for candidate in ComposerChipTokenizer.fileReferenceCandidates(in: text, isComplete: true) { guard !checkedFileChipCandidates.contains(candidate), @@ -5430,14 +4629,6 @@ final class ChatViewModel { return candidates } - /// Lists each candidate's parent folder once and keeps the candidates that - /// folder actually holds. - /// - /// A folder whose listing failed leaves its candidates unanswered rather - /// than answered "no", so the next pass retries them; a folder that answered - /// marks its candidates settled, which is what keeps a `@word` that is not a - /// file from costing a request on every transcript update. `scope` is the - /// `fileChipScopeRevision` the pass started under; nothing applies once it moves. private func confirmFileChipReferences( _ candidates: [String], source: FileReferenceSource, @@ -5465,15 +4656,9 @@ final class ChatViewModel { var settled: Set = [] for directory in batch { - // Between folders, not just between batches: a workspace switch - // part-way through a pass must stop it before the next request, - // and nothing it has learned since may be applied. Going offline - // stops it too; its candidates stay open for the reconnect's pass. guard !Task.isCancelled, !showsOfflineCache else { return } guard let wanted = wantedByDirectory[directory] else { continue } guard let lookup = try? await listedFileReferences(wanted, in: directory, source: source) else { - // A listing that failed is not an answer. Leaving the - // candidates open is what lets the next pass retry them. continue } @@ -5481,24 +4666,12 @@ final class ChatViewModel { settled.formUnion(lookup.answered) } - // Checked between batches as well as at the end: the chat can be - // left, or its workspace switched, part-way through a long pass, and - // a listing taken against the old root must never widen the new - // one's catalog. guard !Task.isCancelled, scope == fileChipScopeRevision else { return } apply(confirmed: confirmed, settled: settled) } } - /// Which of `wanted`, all in `directory`, the source lists there (`listed`), and which of - /// them it gave an answer for at all (`answered`). - /// - /// A webui folder is listed once, through the cache the `@` panel fills, so it answers all - /// of `wanted` or throws. A Hermes chat asks `complete.path` for each candidate's own path: - /// the host lists the folder's entries that start with the name, so a folder past its - /// 30-row cap still confirms one. One candidate's failed lookup leaves only that candidate - /// unanswered; its siblings keep their answers. private func listedFileReferences( _ wanted: Set, in directory: String, @@ -5523,8 +4696,6 @@ final class ChatViewModel { } } - /// Folds one batch's answers into the catalog, drawing whatever it confirmed - /// straight away rather than making the reader wait for the last folder. private func apply(confirmed: Set, settled: Set) { checkedFileChipCandidates.formUnion(settled) @@ -5703,8 +4874,6 @@ final class ChatViewModel { } } - /// The note a finished compression posts, on webui and on Hermes: the host's summary - /// headline and token line, and the focus, each when present. static func compressionNote(headline: String?, tokenLine: String?, focus: String?) -> String { let focus = focus?.trimmingCharacters(in: .whitespacesAndNewlines) let details = [headline, tokenLine, focus.flatMap { $0.isEmpty ? nil : String(localized: "Focus: \($0)") }] @@ -5714,10 +4883,6 @@ final class ChatViewModel { return details.isEmpty ? String(localized: "Context compressed.") : String(localized: "Context compressed.\n\n\(details)") } - /// Why `/clear` cannot run right now, or `nil` when it can. These are the - /// same refusals `/undo` uses, and they never touch the network. `ChatView` - /// reads this before showing the destructive confirmation so a refusal is - /// never hidden behind an alert the user has to answer first. var clearConversationRefusal: String? { if isViewingCachedData { return String(localized: "Reconnect to the server to clear the conversation.") @@ -5742,11 +4907,6 @@ final class ChatViewModel { return nil } - /// Clears the conversation on the server, then locally. Destructive and - /// irreversible, so `ChatView` confirms before calling this. Pass the - /// `ModelContext` so the offline cache is emptied too — otherwise a cold - /// open would repaint the history this just deleted. A Hermes chat deletes nothing: it - /// opens a new chat in this one's place (`clearedHermesChat`, #1050), unconfirmed. func clearConversationFromSlashCommand(modelContext: ModelContext?) async -> SlashCommandExecutionResult { if let hermesTurn { return .replacedHermesSession(clearedHermesChat(hermesTurn)) } @@ -5777,9 +4937,6 @@ final class ChatViewModel { do { try CacheStore.cacheMessages([], serverURL: server, sessionID: sessionID, in: modelContext) } catch { - // The server history is gone but the offline copy still - // holds it, so a later cold open would repaint messages the - // user just deleted. Say so where they will see it. cacheErrorMessage = error.localizedDescription sendErrorMessage = String(localized: "Cleared on the server, but the offline copy of this conversation could not be updated.") } @@ -5875,9 +5032,6 @@ final class ChatViewModel { return .unsupported(friendlyMessage: String(localized: "The server did not return a message to retry.")) } - // Post-retry reload is NOT treated as a cold load (issue #168 non-goal): the - // user already has the transcript in view, so keep the raw msg_limit cap and - // leave expandRenderable at its default false. let sessionResponse = try await client.session( id: sessionID, includeMessages: true, @@ -6127,10 +5281,6 @@ final class ChatViewModel { } } - // MARK: Hermes branches (#1051) - - /// Fork From Here in a Hermes session: a branch through `context`'s row, to open on top of - /// this chat. Nil after saying why in the message-action error. func forkHermesSession(from context: MessageActionContext) async -> HermesSessionChat? { guard let hermesTurn else { return nil } guard !isViewingCachedData else { @@ -6156,8 +5306,6 @@ final class ChatViewModel { } } - /// `/branch [name]` and `/fork [name]` in a Hermes session: the whole history, under `name` - /// when given, opened on top. A refusal keeps the draft and says why. private func branchHermesSession(named rawName: String, on hermes: HermesChatTurnCoordinator) async -> SlashCommandExecutionResult { guard !isViewingCachedData else { return notDelivered(String(localized: "Reconnect to the server to fork a conversation.")) } guard activeStreamID == nil else { @@ -6175,15 +5323,11 @@ final class ChatViewModel { } } - /// The branch `key` as a chat on this one's connection, whose parent is this session. private func hermesBranchChat(_ key: String, on hermes: HermesChatTurnCoordinator) -> HermesSessionChat { HermesSessionChat(server: hermes.engine.server, connection: hermes.engine.connection, target: .session(profile: hermes.engine.target.profile, key: key), parentKey: hermes.engine.storedKey) } - /// Why a Hermes branch failed: nothing to copy yet (4008), the host's own words for any - /// other refusal, such as a name in use, a fork in a session that continues another, or - /// what to do when it did not go out or answer. private func hermesBranchFailure(_ error: Error) -> String { switch error { case let notSent as HermesChatTurnCoordinator.NotSent where notSent.followedReplacedChat: @@ -6203,10 +5347,6 @@ final class ChatViewModel { } } - /// Asks this Hermes chat's host whether its session is a branch of `parentKey`, the parent - /// the row it opened from named, and shows the answer as `hermesForkOrigin` - /// (`HermesBranchParent`). It asks now when the chat is attached, and otherwise, or after a - /// read that failed, on the next connect. A chat opened without a parent asks nothing. func checkHermesForkParent(_ parentKey: String?) async { needsHermesForkCheck = parentKey != nil await resolveHermesForkOrigin() @@ -6223,22 +5363,15 @@ final class ChatViewModel { needsHermesForkCheck = false hermesForkOrigin = parent.map { ForkOrigin(parentSessionID: $0.id, parent: $0.summary(in: engine.target.profile)) } } catch { - // Left to ask on the next connect. } } - /// The Hermes chat that opens `session` on this chat's connection: a "Forked from" row's parent. func hermesChat(opening session: SessionSummary) -> HermesSessionChat? { guard let hermesTurn else { return nil } let engine = hermesTurn.engine return session.hermesChat(on: engine.server, connection: engine.connection, listedIn: engine.target.profile) } - /// Fetches a fork's parent from the active server so the "Forked from" row - /// can open it when the session list never cached it. A parent the server - /// no longer shows this profile (deleted: 404; owned by another profile: - /// 409 `session_profile_mismatch`) reports that through the message-action - /// error; any other failure reports its own message. func loadForkParent(id parentSessionID: String) async -> SessionSummary? { messageActionErrorMessage = nil lastError = nil @@ -6267,9 +5400,6 @@ final class ChatViewModel { return statusCode == 404 || (statusCode == 409 && error.serverCode == "session_profile_mismatch") } - /// Edit a user message: truncate to just before the selected message, then send the edited text. - /// A Hermes session cuts and resends in one call (#1049), and an edit that fails there waits in - /// `takeUnsentHermesEdit()` for the composer. func editMessage(_ context: MessageActionContext, newText: String, modelContext: ModelContext? = nil) async -> Bool { var edited = false defer { @@ -6314,13 +5444,11 @@ final class ChatViewModel { defer { isEditingMessage = false } do { - // Truncate to remove the selected user message and everything after it let truncateResponse = try await client.truncateSession( id: sessionID, keepCount: context.fullHistoryIndex ) - // Update local state from the truncated response if let session = truncateResponse.session { messages = session.messages ?? [] updateOlderMessagePagination(from: session, loadedMessageCount: messages.count) @@ -6344,7 +5472,6 @@ final class ChatViewModel { } } - // Now send the edited text through the normal chat flow let explicitModelPick = explicitModelPickForChatStart() let sentAt = Date() let chatResponse = try await client.startChat( @@ -6363,7 +5490,6 @@ final class ChatViewModel { } completeExplicitModelPickForChatStart(explicitModelPick) - // Append the optimistic user message messages.append( ChatMessage( role: "user", @@ -6485,12 +5611,6 @@ final class ChatViewModel { } } - // MARK: Hermes compress and clear (#1050) - - /// `/compress` and `/compact` in a Hermes session: the composer says "Compressing context..." - /// until the host answers, then one note says what the compaction removed, as on webui, and - /// the transcript shows the compaction card. Whatever the host left as it was says why on - /// the status line, and the draft stays. private func compressHermesSession(focus: String, on hermes: HermesChatTurnCoordinator) async -> SlashCommandExecutionResult { let reconnect = String(localized: "Reconnect to the server to compress context.") let busy = String(localized: "Already compressing; try again shortly.") @@ -6513,10 +5633,6 @@ final class ChatViewModel { } } - /// `/clear` in a Hermes session: a new chat in this one's place, in its Profile, on the - /// model its chip shows (the one the host reported while the chip's catalog is unread or - /// failed) and in its working folder. The old chat stays as it is, in the list and with - /// its draft, so nothing asks first. private func clearedHermesChat(_ hermes: HermesChatTurnCoordinator) -> HermesSessionChat { let chosen = hermes.settings.selectedModel.flatMap { option in option.providerID.map { HermesCall.Model(id: option.id, provider: $0) } @@ -6526,12 +5642,8 @@ final class ChatViewModel { model: chosen ?? hermes.reportedModel)) } - // MARK: Hermes history rewinds (#1049) - - /// A Hermes edit that did not go through, until `ChatView` puts it back in the composer. @ObservationIgnored private var unsentHermesEdit: String? - /// Takes the text of a Hermes edit that did not go through, so the composer keeps it. func takeUnsentHermesEdit() -> String? { defer { unsentHermesEdit = nil } return unsentHermesEdit @@ -6573,7 +5685,6 @@ final class ChatViewModel { return messageActionErrorMessage == nil } - /// `/retry`: the last prompt again, cut at its row, as Regenerate on its reply. private func retryHermesTurn(on hermes: HermesChatTurnCoordinator) async -> SlashCommandExecutionResult { guard let prompt = messages.last(where: Self.opensHermesTurn) else { return notDelivered(String(localized: "Send a message first, then run /\("retry").")) @@ -6592,17 +5703,12 @@ final class ChatViewModel { return .executed(message: nil) } - /// Retry on a failed Hermes turn's outcome row (#1139) can go now: the chat is connected and - /// idle, and nothing else is on its way. var mayRetryHermesTurn: Bool { guard let hermesTurn, hermesTurn.activity.retryTarget != nil else { return false } return hermesTurn.engine.connectionState == .connected && activeStreamID == nil && !isStartingChat && !isHermesSubmissionUncertain && !isViewingCachedData } - /// Retry on the outcome row: the host's raw prompt (`inflight.user`) again, cut at the - /// failed prompt's row, once, from a tap (#937). It never touches the draft. A refusal says - /// why; one the host can't cut (4018) also hides Retry for that row and rereads. func retryHermesFailedTurn() async { guard mayRetryHermesTurn, let hermes = hermesTurn, let target = hermes.activity.retryTarget else { return } stopListening() @@ -6612,7 +5718,6 @@ final class ChatViewModel { ) } - /// `/undo`: `session.undo` on the runtime, then the newest rows replace the transcript. private func undoHermesExchange(on hermes: HermesChatTurnCoordinator) async -> SlashCommandExecutionResult { let reconnect = String(localized: "Reconnect to the server to undo messages.") guard !isHermesSubmissionUncertain else { return notDelivered(reconnect) } @@ -6628,26 +5733,15 @@ final class ChatViewModel { } } - /// Cuts a Hermes session's transcript before the saved prompt `rowID` and sends `text` in - /// its place, once. Once the host takes it, the prompt shows where the cut was, the rows and - /// cards it replaced go, and the turn streams after it; the turn's end re-reads the newest - /// rows. `retrying` is Retry on the last turn, which failed: when the chat showed that turn's - /// prompt and it is still unsaved as the last one, it is cut as its row, and a 4018 hides - /// Retry. Returns why it failed, with nothing cut, or nil. On a canonical host the cut can go - /// through while the send doesn't (#1341, decision 5): the rows go, the text waits in - /// `unsentHermesEdit` for the composer, and the reason says so. private func rewindHermesTranscript(before rowID: Int, sending text: String, on hermes: HermesChatTurnCoordinator, reconnect: String, retrying: HermesChatActivity.RetryTarget? = nil) async -> String? { guard !isHermesSubmissionUncertain else { return reconnect } sendErrorMessage = nil lastError = nil - // A failed turn whose prompt the chat never showed leaves the last one an earlier - // turn's: the host's cut takes no row the chat shows. let first = messages.firstIndex { $0.rowID == rowID } ?? messages.lastIndex(where: Self.opensHermesTurn).flatMap { retrying?.showsPrompt == true && messages[$0].rowID == nil ? $0 : nil } let cut = first.map { Set(messages[$0...].map(\.id)) } ?? [] - // A later prompt means the chat already asked to discard later messages. let discardsLaterPrompts = first.map { messages[$0...].dropFirst().contains(where: Self.opensHermesTurn) } ?? false isStartingChat = true defer { isStartingChat = false } @@ -6667,30 +5761,20 @@ final class ChatViewModel { return nil } - /// Drops the rows a rewind cut, with the cards anchored to them, and puts `prompt`, when - /// there is one, where the cut began. Rows the turn's first frames added stay after it. private func removeCutRows(_ cut: Set, insertingPrompt prompt: ChatMessage?) { let start = messages.firstIndex { cut.contains($0.id) } ?? messages.endIndex var next = messages.filter { !cut.contains($0.id) } if let prompt { next.insert(prompt, at: min(start, next.endIndex)) } messages = next transcriptRevision &+= 1 - // A card without an anchor follows the last row, which the cut always takes. setCompletedToolCallGroups(completedToolCallGroups.filter { $0.anchorMessageID.map { !cut.contains($0) } ?? false }) completedReasoningGroups = completedReasoningGroups.filter { $0.anchorMessageID.map { !cut.contains($0) } ?? false } } - /// Why a Hermes rewind or `/undo` failed. A refusal is the host's own message, except busy - /// (4009) and a row it can no longer cut (4018). An answer that was lost or unreadable may - /// have been taken, and an `/undo` whose re-read failed still shows the exchange: Send - /// waits while the chat reattaches, so the transcript shows what happened, and nothing is - /// sent again (#508). private func hermesHistoryFailure(_ error: Error, on hermes: HermesChatTurnCoordinator, reconnect: String) -> String { switch error { case let notSent as HermesChatTurnCoordinator.NotSent where notSent.followedReplacedChat: return Self.notSentToReplacedChat - // A canonical host (#1603) names its refusal: a reply still running, a row it can't cut, - // or a fence that moved on, whose newer fences are kept for the next try. case BotSettingFailure.rejected(4001, "session_busy"): return String(localized: "Wait for the current reply to finish.") case BotSettingFailure.rejected(4001, "invalid_params"): @@ -6704,7 +5788,6 @@ final class ChatViewModel { case BotSettingFailure.rejected(4018, _): return String(localized: "This message can’t be changed any more.") case BotSettingFailure.rejected(4033, _): - // The host's history has prompts after the cut that this chat doesn't show. return String(localized: "This chat changed on the server. Reopen it and try again.") case BotSettingFailure.rejected(_, let message): return message @@ -6714,8 +5797,6 @@ final class ChatViewModel { } } - /// The prompt a rewind from `context`'s row resends: the row itself for a prompt, its - /// turn's prompt for a reply. Nil when the host can't cut there. private func hermesRewindPrompt(for context: MessageActionContext) -> ChatMessage? { let index = messages.indices.contains(context.visibleIndex) && messages[context.visibleIndex].id == context.messageID ? context.visibleIndex : messages.firstIndex { $0.id == context.messageID } @@ -6734,8 +5815,6 @@ final class ChatViewModel { if ids != hermesRewindableMessageIDs { hermesRewindableMessageIDs = ids } } - /// Whether only replies' text changed, row for row, as a stream tick does. A reply offers - /// Regenerate by its id and its prompt alone, so the rewindable rows stay as they were. private nonisolated static func onlyRepliesChanged(from old: [ChatMessage], to new: [ChatMessage]) -> Bool { guard old.count == new.count else { return false } for (before, after) in zip(old, new) where before != after { @@ -6745,20 +5824,15 @@ final class ChatViewModel { return true } - /// A user row that opens a turn; a steer belongs to the turn it steers. private nonisolated static func opensHermesTurn(_ message: ChatMessage) -> Bool { message.role == "user" && !message.isSteerMessage } - /// A prompt the host can cut at and resend: it has the host's `rowID`, compaction has not - /// archived it (the host cuts only in its live history), and it has no attachments, which a - /// text-only resend would drop. private nonisolated static func isHermesRewindable(_ prompt: ChatMessage) -> Bool { prompt.rowID != nil && !prompt.isCompacted && prompt.attachments?.isEmpty != false && !hermesPromptText(prompt).isEmpty } - /// A prompt's text as it shows, which a skill turn's host expands again. private nonisolated static func hermesPromptText(_ prompt: ChatMessage) -> String { (prompt.content ?? "").trimmingCharacters(in: .whitespacesAndNewlines) } @@ -6773,7 +5847,6 @@ final class ChatViewModel { defer { isCancellingStream = false } if let hermesTurn { - // Accepted is not idle: the turn's own ending frames settle it. do { return try await hermesTurn.interrupt() } catch is HermesFenceRefusal { @@ -6812,38 +5885,19 @@ final class ChatViewModel { return } - // Tapping the message that is already listening — fetching server audio or - // playing on either engine — toggles it off. Matching on `listeningMessageID` - // alone (not `isSpeaking`) also debounces rapid double-taps: the second tap - // stops cleanly instead of firing a second speech request (into webui's ~2 s - // `/api/tts` rate limit) or stacking audio (#15). if listeningMessageID == context.messageID { stopListening() return } stopListening() - // The audio session is NOT activated here: server speech can be slow or - // unreachable, and activating the non-mixable playback session before the - // fetch would silence other audio while Hermex has nothing to play (review - // on #35). Activation happens only once audio is in hand, in - // `startListenAudioPlayback`. listeningMessageID = context.messageID beginListenPlaybackPreparation(for: context) - // Prefer the server's speech; on any failure (offline, 4xx/5xx, rate - // limit, undecodable audio) fall back silently to the on-device voice — - // no error alert (#15). Over the server's ceiling, go straight to the - // on-device voice (chunking is a non-goal of #15). Both play through the - // same player, so the playback bar and Lock Screen controls cover either (#1352). let usesServerSpeech = ServerTTSPolicy.shouldUseServerTTS(for: listenText, onHermes: hermesTurn != nil) let requestID = UUID() activeListenRequestID = requestID listenPreparationTask = Task { [weak self, synthesizeListenAudio, renderOnDeviceSpeech] in - // Stopped before the fetch began (e.g. a rapid second tap): skip the - // request entirely instead of issuing one whose response would be dropped. - // Stopped or superseded while either fetch was in flight: the user no longer - // wants this audio; never start playback from a stale response. if usesServerSpeech, !Task.isCancelled, let audio = try? await synthesizeListenAudio(listenText) { guard let self, !Task.isCancelled, self.activeListenRequestID == requestID else { return } if self.startListenAudioPlayback(audio) { return } @@ -6857,14 +5911,10 @@ final class ChatViewModel { } func stopListening() { - // Cancel any in-flight server-TTS fetch so a late response can't start - // audio after the user asked to stop (or switched messages). listenPreparationTask?.cancel() listenPreparationTask = nil activeListenRequestID = nil - // `AVAudioPlayer.stop()` does not fire the finish delegate, so no stale - // callback follows; state is torn down synchronously in `finishListening()`. listenAudioPlayer?.stop() finishListening() } @@ -6886,10 +5936,6 @@ final class ChatViewModel { userDefaults.set(speed.rawValue, forKey: ListenPlaybackSpeed.storageKey) listenAudioPlayer?.rate = Float(speed.rawValue) updateListenNowPlaying() - // iOS reads Now Playing's state from the audio itself, and a rate change mid-play - // makes it report Stopped about 60 ms later while speech carries on, so the Lock - // Screen would show a paused reply whose play button does nothing. Sending Now - // Playing again once that settles puts it back to Playing. listenNowPlayingRefreshTask?.cancel() let settle = listenSpeedChangeSettleDelay listenNowPlayingRefreshTask = Task { @MainActor [weak self] in @@ -6939,15 +5985,11 @@ final class ChatViewModel { turn.suspendActiveStreamConnection() } - /// `ChatView` reconnects as it appears, before its first load, so a Hermes chat's attach can - /// start here: it takes the offline cache first, to write what that attach reads (#1144). func reconnectStreamIfNeeded(modelContext: ModelContext? = nil) async { if hermesTurn != nil, let modelContext { hermesCache = modelContext } await turn.reconnectIfNeeded(modelContext: modelContext) } - /// Retries a suspended stream, or clears a stale "Waiting for network", - /// when the device's network path changes (#869). func networkPathDidChange(modelContext: ModelContext? = nil) async { if hermesTurn != nil, let modelContext { hermesCache = modelContext } await turn.networkPathDidChange(modelContext: modelContext) @@ -7369,8 +6411,6 @@ final class ChatViewModel { ?? Self.latestAssistantAnchorID(in: messages, messageOffset: messagesOffset) } - /// Moves the last turn's live reasoning and tools into the transcript, so a new turn - /// starts with none. private func archiveLiveActivityForNewTurn() { archiveLiveReasoningIfNeeded() archiveLiveToolCallsIfNeeded() @@ -7414,9 +6454,6 @@ final class ChatViewModel { private func appendReasoning(_ text: String) -> Bool { guard !text.isEmpty else { return false } - // As with assistant tokens, normal streams do not need replay matching. - // Avoid joining all pending reasoning text unless this is a reconnect - // replay where duplicate-event suppression is required. _ = ensureStreamingAssistantMessage() let remainder: String if isActiveStreamReplayConnection { @@ -7442,7 +6479,6 @@ final class ChatViewModel { private func flushReasoningChunks() -> Bool { guard !pendingReasoningChunks.isEmpty else { return false } - // Chunks were deduplicated at append time, so flushing is pure concatenation. let appendedText = pendingReasoningChunks.joined() pendingReasoningChunks = [] @@ -7655,10 +6691,6 @@ final class ChatViewModel { private func appendAssistantToken(_ token: String) -> Bool { guard !token.isEmpty else { return false } - // Normal streams cannot contain replayed content, so constructing the - // full flushed + pending transcript before appending every token is - // unnecessary. Keep the expensive effective-content comparison only on - // reconnect replay paths, where it protects against duplicated events. let remainder: String if isActiveStreamReplayConnection { let messageID = ensureStreamingAssistantMessage() @@ -7673,8 +6705,6 @@ final class ChatViewModel { pendingAssistantText += remainder scheduleStreamingContentFlush() - // Replayed text is catch-up, not new work: reattaching to a running - // stream must not pulse for every token that already happened. if !isActiveStreamReplayConnection, streamingHapticPulseThrottle.shouldPulse(at: Date().timeIntervalSinceReferenceDate) { streamingHapticPulseTrigger += 1 @@ -7686,10 +6716,6 @@ final class ChatViewModel { private func flushAssistantTokens(throughRevealGate: Bool = false) -> Bool { guard !pendingAssistantText.isEmpty else { return false } - // Tokens were deduplicated at append time, so flushing is pure concatenation. - // The reveal gate moves only the head of the buffer into the visible - // message; the held fragment stays pending, keeping the replay-dedup - // invariant that flushed + pending text is the full received content. let appendedContent: String if throughRevealGate { let (shown, held) = StreamingRevealGate.cut( @@ -7744,10 +6770,6 @@ final class ChatViewModel { return true } - /// Puts the streaming reply at `index`, its text grown by a flush, back into `messages`. - /// When the extra text can't change the transcript's structure, only that reply's row is - /// patched; any other change re-derives the whole transcript through the `messages` - /// observer (#1417). private func replaceStreamingReply(at index: Int, with reply: ChatMessage) { guard let row = textOnlyTranscriptRow(replacing: messages[index], at: index, with: reply) else { messages[index] = reply @@ -7764,14 +6786,9 @@ final class ChatViewModel { anchorID: patched.anchorID, message: reply ) - // The compaction card's placement matches anchors by message text. recomputeCompressionReferenceCard() } - /// The transcript row a grown reply can be patched into, or nil when its new text could - /// change structure. A shown assistant row with text keeps its turn, row and bubble; only - /// reasoning reads reply text (in-text `` blocks, and echo removal for the cards - /// anchored to it), so a reply with any reasoning takes the full path. private func textOnlyTranscriptRow(replacing old: ChatMessage, at index: Int, with new: ChatMessage) -> Int? { guard old.role == "assistant", new.role == "assistant", old.messageId == new.messageId, Self.hasTranscriptMessageRowContent(old), @@ -7914,13 +6931,7 @@ final class ChatViewModel { } } - /// Hands the messages waiting behind the run to the caller, in queue order, - /// and forgets them, so the run's end sends nothing. ChatView parks them in - /// the chat's draft when the user leaves mid-run (#857). A message the drain - /// already took is in flight and stays with it. func takeQueuedMessages() -> [QueuedSlashMessage] { - // Called on every leave: skip the observable writes when there is - // nothing to hand over. guard !queuedSlashMessages.isEmpty else { return [] } let queued = queuedSlashMessages queuedSlashMessages.removeAll() @@ -7946,19 +6957,12 @@ final class ChatViewModel { if !sent { queuedSlashMessages.insert(next, at: 0) } - // Keep files staged while the send was in flight, such as a parked - // queue's (#857); a failed send put `next`'s back, and they are - // queued again. let nextAttachmentIDs = Set(next.attachments.map(\.id)) let stagedDuringSend = attachmentCoordinator.pendingAttachments.filter { !nextAttachmentIDs.contains($0.id) } attachmentCoordinator.replacePendingAttachments(savedAttachments + stagedDuringSend) isDrainingQueuedSlashMessage = false - // Only chain-drain after a *successful* send. A failed send requeues the message and - // waits for the next natural trigger (a queue append, stream completion, or an explicit - // user send) instead of immediately re-firing the drain — which, with a persistently - // failing send, was a tight retry loop hammering the network and CPU (issue #202). if sent, activeStreamID == nil { drainQueuedSlashMessageIfIdle() } @@ -7991,23 +6995,16 @@ final class ChatViewModel { applyLiveActivitySessionTitle(title) } } catch { - // Title refresh is opportunistic; the transcript has already completed successfully. } } } private func applyLiveActivitySessionTitle(_ title: String) { displayTitle = Self.displayTitle(from: hermesTurn == nil ? title : hermesHeaderTitle(title)) - // A Hermes session's turns drive their own activity (#1014); the one on screen may be - // another session's. guard hermesTurn == nil else { return } liveActivityManager.update(.sessionTitle(displayTitle)) } - /// A Hermes session's title as its header shows it (#1046), without the reference lines a - /// Hermex send appends (`MessageAttachment.hermesTitle`). The host's instant title cuts a - /// photo's reference before the photo's name, so then the first prompt's first attachment - /// names the chat. private func hermesHeaderTitle(_ title: String) -> String? { MessageAttachment.hermesTitle(title) ?? messages.first { $0.role == "user" }?.attachments?.first?.name @@ -8019,8 +7016,6 @@ final class ChatViewModel { listenAudioPlayer = nil listeningMessageID = nil clearListenPlaybackState() - // Release the shared session so any audio we interrupted can resume. Safe to - // call when nothing was speaking: `setActive(false)` no-ops via `try?`. listenAudioSession.deactivate() } @@ -8043,9 +7038,6 @@ final class ChatViewModel { listenRemoteControlCenter.clear() } - /// Attempts to start playback of Listen audio, the server's or the on-device voice's. - /// Returns `false` when the bytes can't be decoded into a player or playback fails to - /// start, so the caller can fall back to the on-device voice. private func startListenAudioPlayback(_ audioData: Data) -> Bool { guard let player = try? listenAudioPlayerFactory(audioData) else { return false @@ -8058,11 +7050,6 @@ final class ChatViewModel { player.prepareToPlay() player.rate = Float(listenPlaybackSpeed.rawValue) - // Activate the session only once decodable audio is in hand, immediately - // before playback, so the network wait or the on-device render never held it - // (review on #35). Routes speech to the speaker, not the earpiece (#252). If - // `play()` fails, release it again so other audio resumes while the on-device - // voice renders, and leave the loading bar untouched. listenAudioSession.activate() guard player.play() else { listenAudioSession.deactivate() @@ -8156,8 +7143,6 @@ final class ChatViewModel { )) } - /// Completion routed from the Listen audio player. A stale callback from a superseded - /// player must not clear the new listen state or deactivate the session. private func handleListenPlayerCompletion(for playerID: ObjectIdentifier) { guard playerID == activeListenPlayerID else { return } finishListening() @@ -8218,7 +7203,6 @@ final class ChatViewModel { private static let reasoningDisplayArgs: Set = ["show", "hide", "on", "off"] private static let reasoningEffortArgs: Set = ["none", "minimal", "low", "medium", "high", "xhigh"] private static let personalityClearArgs: Set = ["none", "default", "clear"] - /// The host's `/reasoning` display words, which write its global display settings (#1016). private static let hermesReasoningDisplayArgs: Set = [ "show", "hide", "on", "off", "full", "all", "clamp", "collapse", "short" ] @@ -8239,37 +7223,19 @@ final class ChatViewModel { """ } - /// The id prefix of a Hermes background task's transcript card, which a rebuilt - /// transcript keeps. private static let hermesBackgroundCardPrefix = "local-background-" - /// The ids of the tool and reasoning groups the settled history last laid out (#1047): an - /// older page replaces exactly these, and keeps the groups the chat archived itself. @ObservationIgnored private var hermesHistoryGroupIDs: Set = [] - /// The rows of a cached Hermes transcript that anchor their turn's tool or reasoning cards. - /// The cache holds no cards, so these let the cached copy draw each turn's fold row where - /// the host's rows will, instead of the row arriving a moment later and moving the reply. private(set) var hermesCachedWorkAnchorIDs: Set = [] - /// Where a Hermes transcript's first row counts from. A page never says how many rows come - /// before it, so the count starts high and an older page moves it back (#1047). static let hermesTranscriptBase = 1_000_000 - /// The `messagesOffset` that keeps the first row on screen at its position in `next`, and - /// so every row's render identity (`transcript:`): rows put in front move - /// it back by their count. When `next` no longer holds that row, it starts again from - /// `hermesTranscriptBase`. nonisolated static func hermesMessagesOffset(keeping shown: [ChatMessage], at offset: Int, in next: [ChatMessage]) -> Int { guard let first = shown.first?.messageId, let index = next.firstIndex(where: { $0.messageId == first }) else { return hermesTranscriptBase } return max(0, offset - index) } - /// `rows`, the host's, with this Hermes chat's own rows from `shown` where they sat (#1013): - /// background cards and local slash output, such as a goal's notice, which the host's - /// history never holds. Each follows the row it followed, comes first when it followed - /// none, and comes last when that row is gone, as a streamed row is once it takes its saved - /// id. So a turn's end moves no row. private static func hermesKeepingOwnRows(of shown: [ChatMessage], in rows: [ChatMessage]) -> [ChatMessage] { var own: [(after: String?, row: ChatMessage)] = [] var previous: String? @@ -8277,7 +7243,7 @@ final class ChatViewModel { if message.messageId?.hasPrefix(hermesBackgroundCardPrefix) == true || message.role?.hasPrefix("local_") == true { own.append((previous, message)) } else { - previous = message.messageId ?? "" // A row without an id is never found again. + previous = message.messageId ?? "" } } guard !own.isEmpty else { return rows } @@ -8291,8 +7257,6 @@ final class ChatViewModel { return next + own.filter { $0.after.map { following[$0] != nil } == true }.map(\.row) } - /// A Hermes background task's transcript card (#1013): the webui's result card, saying - /// the task runs until its result, or that the result is unavailable. private static func hermesBackgroundCard(_ task: HermesBackgroundTask, timestamp: Double?) -> ChatMessage { let body: String switch task.state { @@ -8448,9 +7412,6 @@ extension ChatViewModel: ChatStreamCoordinatorDelegate { clearSteerFailure() responseCompletionNeedsTranscriptRefresh = false if let ending = turn.latestRunEnding { - // A `done` completion already counted when it completed, and a late - // teardown can find an ending still on record, so each ending counts once. - // This catches failures and a `stream_end` that arrives without `done`. if ending.endedAt != runEndRecordedAt, let outcome = ResponseCompletionOutcome(ending: ending.ending) { recordRunEnd(outcome) } @@ -8485,9 +7446,6 @@ extension ChatViewModel: ChatStreamCoordinatorDelegate { } func streamCoordinatorDidStartConnection(isReplay: Bool) { - // A fresh connection re-arms the pulse so a reply's first live token - // always ticks, even when the previous reply pulsed less than an interval - // ago. A replay continues the same reply, so its window carries over. if !isReplay { streamingHapticPulseThrottle.reset() } @@ -8626,8 +7584,6 @@ extension ChatViewModel: HermesChatTurnDelegate { } } - /// A prompt the host holds or just ran, as its user row shows it: its text's references and - /// its photos as chips. private static func hermesPromptRow(_ prompt: HermesQueuedPrompt, id: String, timestamp: Double?) -> ChatMessage { HermesChatTurnCoordinator.displayed(ChatMessage( role: "user", content: prompt.text, timestamp: timestamp, messageId: id, @@ -8640,18 +7596,11 @@ extension ChatViewModel: HermesChatTurnDelegate { let text = reply.trimmingCharacters(in: .whitespacesAndNewlines) let shown = streamingAssistantMessageID.flatMap { id in messages.first { $0.messageId == id }?.content } ?? "" guard !text.isEmpty, !shown.trimmingCharacters(in: .whitespacesAndNewlines).hasSuffix(text) else { return } - // A reply the deltas never carried, such as the answer after a tool call: it joins - // the turn's row the way an interim reply does. appendInterimAssistant(InterimAssistantStreamEvent(text: text, alreadyStreamed: false)) flushPendingStreamingContent() } func hermesReplaceTranscript(_ transcript: HermesChatTranscript) { - // The host's own rows replace a cached copy, which shares their ids. A rebuild whose - // history read failed has none, so the cached copy stays, read-only, until the chat's - // retry or a later read succeeds. A session's copy shown while it connects goes even - // then: the rebuild holds the running turn the frames it releases next continue, and - // the failure, reported after them, shows the cache again where it would offline. if isViewingCachedData { let isBotChat = if case .canonicalChat = hermesTurn?.engine.target { true } else { false } guard transcript.newestCoverage != nil || isCachedCopyProvisional && !isBotChat else { return } @@ -8686,14 +7635,10 @@ extension ChatViewModel: HermesChatTurnDelegate { } if !messages.isEmpty { transcriptRelayoutScrollToken += 1 } cacheHermesHistory(transcript) - // The host's rows replaced the offline copy: a waiting send held for it can go now. deliverWaitingSendIfReady() } func hermesPrependHistory(_ transcript: HermesChatTranscript) { - // Only the older page's rows are new, and they go in front. Every row shown (the - // running turn, rows the host has not saved, the chat's own rows) stays as it is, with - // the live tool and reasoning cards. let shown = Set(messages.compactMap(\.messageId)) let next = Array(transcript.messages.prefix { $0.messageId.map(shown.contains) != true }) + messages messagesOffset = Self.hermesMessagesOffset(keeping: messages, at: messagesOffset, in: next) @@ -8719,11 +7664,6 @@ extension ChatViewModel: HermesChatTurnDelegate { showCachedHermesTranscript(after: error) } - /// The host replaced the Bot Chat on screen (#1339): the old chat's rows go, the chat's own - /// and a cached copy's included. The new chat's rows follow from this attach, and the notice - /// saying where the old ones went is added after them (`hermesReplaceTranscript`), where - /// the chat is scrolled to, once a history read succeeds: until then the empty chat shows - /// the failure and its retry. func hermesBotChatWasReplaced() { messages = [] hasOlderMessages = false @@ -8731,30 +7671,20 @@ extension ChatViewModel: HermesChatTurnDelegate { transcriptRevision &+= 1 isViewingCachedData = false needsReplacedChatNotice = true - // It was written for the old chat: it goes back to the composer, never to the new one. if waitingSend != nil { leaveWaitingSend() sendErrorMessage = Self.notSentToReplacedChat } } - /// An action the host's new Bot Chat stopped before it went out (#1339). private static var notSentToReplacedChat: String { String(localized: "Not sent: Hermes started a new Bot Chat.") } - /// The attach found the chat's root, before its reads: the chat writes to the cache under - /// the epoch it takes now. A Bot Chat's canonical root settles its cache's. One cached under - /// another root, shown or not, is a Bot Chat the host replaced: its copy leaves the screen - /// for the replacement's notice, and every other root's leaves the cache once that notice - /// shows. func hermesDidIdentify(root: String) { guard let engine = hermesTurn?.engine else { return } - // Taken even before the chat has its cache, so the writes after it still count. hermesCacheEpoch = CacheStore.hermesCacheEpoch(serverURL: engine.server) guard case .canonicalChat(let profile) = engine.target else { return } - // The chat cached is one the host has since replaced, as when it opens after the swap - // (#1339). A replacement the engine followed already says so. let cachedRoot = hermesCacheRoot ?? hermesCache.flatMap { try? CacheStore.cachedHermesBotChatRoot(serverURL: engine.server, connectionID: engine.connection.id, profile: profile, in: $0) @@ -8764,13 +7694,10 @@ extension ChatViewModel: HermesChatTurnDelegate { hermesBotChatWasReplaced() } hermesCacheRoot = root - // A replaced chat's copy stays until its notice shows, so a chat reopened before then - // finds it and says so again. guard !needsReplacedChatNotice else { return } removeCachedBotChats(exceptRoot: root, profile: profile) } - /// Drops this Bot Chat's cached copies under every root but `root`. private func removeCachedBotChats(exceptRoot root: String, profile: String) { guard let hermesCache, let engine = hermesTurn?.engine else { return } do { @@ -8781,19 +7708,11 @@ extension ChatViewModel: HermesChatTurnDelegate { } } - /// A chat whose host can't be reached, to attach or to read its history, shows its cached - /// transcript as the offline state, as a webui chat does offline: the copy shown while it - /// connected, else, with nothing on screen, one read now. The engine keeps reattaching, and - /// the host's transcript replaces it once a read succeeds, as the chat's retry's does. - /// Returns whether it shows the cached copy as the failure's answer. @discardableResult private func showCachedHermesTranscript(after error: Error) -> Bool { let usesCache = CacheFallbackPolicy.shouldUseCache(for: error) guard isCachedCopyProvisional else { return usesCache && showCachedHermesTranscript(provisional: false) } isCachedCopyProvisional = false - // A Bot Chat keeps the copy it shows before every attach (#1144), whatever failed. A - // session's stays only where a failure shows the cache; otherwise it goes, so the chat - // says why with nothing on screen. if case .canonicalChat = hermesTurn?.engine.target { return false } guard !usesCache else { return true } messages = [] @@ -8802,12 +7721,6 @@ extension ChatViewModel: HermesChatTurnDelegate { return false } - /// A chat opening shows its cached transcript at once, read-only, provisionally until the - /// attach's first newest read puts the host's rows in its place (#1144). Not once attached, - /// when the host's rows, even none, are the transcript, unless that read failed: a Bot Chat - /// then keeps its copy as the offline state. An attach that already failed, as one - /// `ChatView` starts as it appears can, has had its answer: a Bot Chat's copy shows as the - /// offline state, and a session's only as that failure showed it. private func showCachedHermesTranscriptBeforeAttach(_ hermes: HermesChatTurnCoordinator) { let engine = hermes.engine let isBotChat = if case .canonicalChat = engine.target { true } else { false } @@ -8822,10 +7735,6 @@ extension ChatViewModel: HermesChatTurnDelegate { if isBotChat { showCachedHermesTranscript(provisional: false) } } - /// With nothing on screen, shows the newest page of the chat's cached transcript, read-only - /// (`isViewingCachedData`), with no tool, reasoning or compaction cards (only each turn's fold row), until a newest - /// read replaces it: `provisional` while the host has yet to answer, else as the offline - /// state. Returns whether it shows the cached copy. @discardableResult private func showCachedHermesTranscript(provisional: Bool) -> Bool { guard messages.isEmpty, let scope = hermesCacheScope() else { return false } @@ -8858,9 +7767,6 @@ extension ChatViewModel: HermesChatTurnDelegate { return true } - /// Writes the settled history a Hermes transcript holds to the offline cache (#1054). A Bot - /// Chat's newest read, archived or its bot's, also drops what the host cut from the other's - /// copy of the same root, without writing there, so neither shows an undone exchange offline. private func cacheHermesHistory(_ transcript: HermesChatTranscript) { guard let scope = hermesCacheScope(), hermesCacheEpoch == CacheStore.hermesCacheEpoch(serverURL: scope.server) else { return } do { @@ -8878,16 +7784,6 @@ extension ChatViewModel: HermesChatTurnDelegate { } } - /// Where this Hermes chat's transcript sits in the offline cache: its server and scope. A - /// session's is its Profile and lineage root, which the list's cached row names for its - /// key, else its row or link names, else the key, settled once found, so a key the host - /// later moves keeps the same place. A Bot Chat's is its connection, Profile and canonical root: the one its attach - /// found, else a deep link's, else the one cached last. An archived Bot Chat's is its own, - /// under the root its row names, apart from its bot's so it never becomes that chat's - /// preview. `sameRoot` is the other copy of a Bot Chat's root, the bot's or an archive's, - /// which loses the rows this chat's newest read found cut; `fallback` is read when the - /// chat's own copy is empty, only an archive's: its bot's. Nil without a cache, for a new - /// session until the host names its key, and for a Bot Chat with no root. private func hermesCacheScope() -> (context: ModelContext, server: URL, scope: String, fallback: String?, sameRoot: String?)? { guard let hermesCache, let engine = hermesTurn?.engine else { return nil } switch engine.target { @@ -8936,7 +7832,6 @@ extension ChatViewModel: HermesChatTurnDelegate { if needsHermesForkCheck { Task { [weak self] in await self?.resolveHermesForkOrigin() } } return } - // With nothing on screen yet it is the chat's error, with its retry; otherwise the composer's. if messages.isEmpty { errorMessage = failure errorMayRetry = mayRetry @@ -8969,12 +7864,10 @@ extension ChatViewModel: HermesChatTurnDelegate { func hermesGoalDidChange(_ goal: SubmittedGoal?) { currentGoal = goal - // The goal menu shows once the session has a goal, and stays to set the next one. if goal != nil { hasActivatedGoalCommand = true } } func hermesWorkspaceDidChange() { - // The host already applied the move, so an open `@` panel asks again. resetFileChipReferences(reloadingOpenQuery: true) } } @@ -9048,7 +7941,6 @@ private final class ActiveChatStreamSnapshotStore { } } -/// A message waiting behind the run, with the files staged for it. struct QueuedSlashMessage { let text: String let attachments: [PendingAttachment] @@ -9075,11 +7967,8 @@ struct TranscriptMessage: Identifiable, Equatable { var id: String { renderID } } -/// Display model for the synthesized "Context compaction · Reference only" card. struct CompressionReferenceCard: Equatable { let referenceText: String - /// `renderID` of the transcript row the card renders directly after; - /// nil places the card above the loaded transcript. let afterRenderID: String? } @@ -9098,10 +7987,7 @@ struct MessageActionContext: Equatable, Identifiable { let messageID: String let copyText: String let listenText: String? - /// Regenerate and Edit rewrite the server's history. A Hermes session offers them only - /// where the host can cut (`ChatViewModel.hermesRewindableMessageIDs`, #1049). let offersHistoryActions: Bool - /// Fork From Here. A Hermes session offers it on a row the host saved (#1051). let offersFork: Bool init?(message: ChatMessage, visibleIndex: Int, messagesOffset: Int?, offersHistoryActions: Bool = true, @@ -9146,8 +8032,6 @@ extension ChatViewModel { ) } - /// Same as above, reusing `cache` from the previous pass so only candidates - /// whose reasoning or visible reply changed are stripped and normalized again. nonisolated static func reasoningDisplayGroups( messages: [ChatMessage], messageOffset: Int?, @@ -9305,8 +8189,6 @@ extension ChatViewModel { return message.role == "user" && message.attachments?.isEmpty == false } - /// A Hermes session's compaction card (#1047): after the last row the transcript draws at - /// or before the summary's anchor, or above the rows loaded when none is. nonisolated static func hermesCompressionReferenceCard( _ compaction: HermesCompaction, messages: [ChatMessage], @@ -9335,8 +8217,6 @@ extension ChatViewModel { case .top: return CompressionReferenceCard(referenceText: resolution.referenceText, afterRenderID: nil) case .afterLoadedMessageIndex(let loadedIndex): - // The anchor message itself may be filtered out of the transcript - // (e.g. tool-result-only); attach to the closest preceding row. let afterRenderID = transcriptMessages.last { $0.loadedIndex <= loadedIndex }?.renderID return CompressionReferenceCard(referenceText: resolution.referenceText, afterRenderID: afterRenderID) } @@ -9484,12 +8364,6 @@ private struct ReasoningDisplayCandidate { let dedupeKey: String } -/// Memo for the costly per-candidate work in -/// `ChatViewModel.reasoningDisplayGroups`: stripping the visible reply's echo -/// from the reasoning and normalizing the dedupe key. `ChatViewModel` keeps one -/// across transcript recomputes, so a stream tick re-derives only the reply that -/// changed. An entry is reused only when its inputs are equal to the current -/// ones, and each pass keeps only the entries it used. struct ReasoningCandidateCache { struct Derived { let text: String @@ -9499,15 +8373,12 @@ struct ReasoningCandidateCache { private struct Entry { let reasoning: String let visibleText: String? - /// Nil when nothing is left once the visible echo is stripped. let derived: Derived? } private var previousPass: [String: Entry] = [:] private var currentPass: [String: Entry] = [:] - /// Returns the derived candidate for `id`, calling `derive` only when the - /// previous pass saw different inputs for it. mutating func derived( id: String, reasoning: String, @@ -9524,7 +8395,6 @@ struct ReasoningCandidateCache { return entry.derived } - /// Ends a pass; entries the pass did not use are dropped. mutating func finishPass() { previousPass = currentPass currentPass = [:] @@ -9631,21 +8501,9 @@ struct SpeechTextNormalizer { } } -/// Routing policy for the "Listen" action: honor saved server preferences and -/// fall back to the -/// on-device synthesizer when the server can't serve the request. enum ServerTTSPolicy { - /// Server-enforced request cap (`400 text too long` above it); longer text - /// routes straight to the on-device synthesizer (chunking is a non-goal). static let maximumTextLength = 5000 - /// A Hermes host's ceiling (#1072). The host splits longer text into its provider's - /// chunks (Edge 5000, OpenAI 4096, others 4000) and plays only the first without ffmpeg - /// to join them, so Hermex sends one chunk's worth and speaks longer replies on device. - /// Counted in Unicode scalars, as the host's Python `len` counts them. static let maximumHermesTextLength = 4000 - /// The server's own default voice is `zh-CN-XiaoxiaoNeural`, so the client - /// must always send an explicit voice. A voice picker is a non-goal of #15; - /// this is the issue-specified default (verified live 2026-07-02). static let defaultVoice = "en-US-AriaNeural" static func shouldUseServerTTS(for text: String, onHermes: Bool = false) -> Bool { @@ -9653,13 +8511,8 @@ enum ServerTTSPolicy { } } -/// Playback seam for "Listen" audio, the server's or the on-device voice's. Injectable so tests can -/// drive playback outcomes without constructing a real `AVAudioPlayer` (which -/// requires decodable audio bytes). @MainActor protocol ListenAudioPlaying: AnyObject { - /// Fired on the main actor when playback finishes naturally. - /// `stop()` must not fire it. var onFinish: (@MainActor () -> Void)? { get set } var currentTime: TimeInterval { get set } var duration: TimeInterval { get } @@ -9672,9 +8525,6 @@ protocol ListenAudioPlaying: AnyObject { func stop() } -/// Production `ListenAudioPlaying`: wraps `AVAudioPlayer` and forwards its finish -/// delegate onto the main actor. `init` throws when the bytes aren't decodable -/// audio, which the caller treats as "fall back to the on-device voice". @MainActor final class ListenAudioPlayer: NSObject, ListenAudioPlaying { private let player: AVAudioPlayer @@ -9715,19 +8565,12 @@ final class ListenAudioPlayer: NSObject, ListenAudioPlaying { } extension ListenAudioPlayer: AVAudioPlayerDelegate { - // `AVAudioPlayer` may call its delegate off the main thread; hop back before - // touching main-actor listen state. Finished-with-error still ends playback, - // so both flag values route to `onFinish`. nonisolated func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { Task { @MainActor in self.onFinish?() } } - // A mid-playback decode error fires this callback instead of (or as well as) - // the finish one — without it the listen state would stay stuck "listening" - // forever. Route it to `onFinish` too; a double fire is harmless because the - // completion handler drops callbacks from a no-longer-active player. nonisolated func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) { Task { @MainActor in self.onFinish?() @@ -9735,10 +8578,6 @@ extension ListenAudioPlayer: AVAudioPlayerDelegate { } } -/// Speaks a reply with the on-device voice into playable audio, 16-bit PCM in a CAF -/// container, so on-device Listen plays through the same `ListenAudioPlayer`, playback -/// bar, and Lock Screen controls as server speech (#1352). Cancelling the caller's task -/// stops the render and throws `CancellationError`. enum OnDeviceSpeech { static func render(_ text: String) async throws -> Data { let render = OnDeviceSpeechRender(text: text) @@ -9750,9 +8589,6 @@ enum OnDeviceSpeech { } } -/// One `AVSpeechSynthesizer.write` run. The synthesizer delivers buffers on its own queue -/// and ends with an empty one; the lock keeps that and cancellation resuming the -/// continuation exactly once. private final class OnDeviceSpeechRender: @unchecked Sendable { private let text: String private let synthesizer = AVSpeechSynthesizer() @@ -9794,7 +8630,6 @@ private final class OnDeviceSpeechRender: @unchecked Sendable { guard continuation != nil else { return nil } let outcome: Result if buffer.frameLength == 0 { - // The last buffer. No file means the voice spoke nothing. outcome = file == nil ? .failure(CocoaError(.fileNoSuchFile)) : .success(()) } else { do { @@ -9822,13 +8657,11 @@ private final class OnDeviceSpeechRender: @unchecked Sendable { try file?.write(from: buffer) } - /// Call holding `lock`. private func takeContinuation() -> CheckedContinuation? { defer { continuation = nil } return continuation } - /// Closes the file, hands back its bytes memory-mapped, and removes it either way. private func finish(_ continuation: CheckedContinuation, with outcome: Result) { lock.withLock { file = nil } defer { try? FileManager.default.removeItem(at: url) } @@ -9836,32 +8669,21 @@ private final class OnDeviceSpeechRender: @unchecked Sendable { } } -/// Audio-session settings for the "Listen" (TTS) feature. `.playback` routes audio -/// to the speaker by default instead of the receiver/earpiece, and `.spokenAudio` is -/// the mode Apple recommends for synthesized speech (it pauses other spoken-word audio -/// rather than ducking it). Exposed as constants so the routing intent is unit-testable -/// without driving the live `AVAudioSession`. See #252. enum ListenAudioSessionConfiguration { static let category = AVAudioSession.Category.playback static let mode = AVAudioSession.Mode.spokenAudio static let deactivationOptions = AVAudioSession.SetActiveOptions.notifyOthersOnDeactivation } -/// Activates/deactivates the shared audio session around a "Listen" utterance. -/// Injectable so tests can assert the call sequence without touching real hardware. @MainActor protocol ListenAudioSessionControlling { func activate() func deactivate() } -/// Production `ListenAudioSessionControlling`: drives the real shared `AVAudioSession`. @MainActor final class ListenAudioSessionController: ListenAudioSessionControlling { func activate() { - // If composer dictation is capturing the mic, leave the shared session alone: - // switching it to `.playback` would tear down the live recording engine. Mirrors - // `InlineAudioPlayerView`'s guard so the two playback paths stay consistent. guard !ComposerAudioCaptureState.shared.isCapturing else { return } let session = AVAudioSession.sharedInstance() diff --git a/HermesMobile/Features/Chat/ClarificationRequestCard.swift b/HermesMobile/Features/Chat/ClarificationRequestCard.swift index 96549854d..ce5782222 100644 --- a/HermesMobile/Features/Chat/ClarificationRequestCard.swift +++ b/HermesMobile/Features/Chat/ClarificationRequestCard.swift @@ -1,15 +1,8 @@ import SwiftUI import UIKit -/// The clarification request pinned above the composer while the agent waits -/// for an answer. The collapsed bar is the permanent footprint: its measured -/// height feeds the transcript's bottom inset. The expanded card is an overlay -/// that rises from the bar's bottom edge, so opening or closing it never moves -/// the transcript. A new request always arrives expanded. struct ClarificationRequestInset: View { let prompt: ClarificationPromptState - /// Height between the chat's top safe edge and this inset's bottom edge. - /// The expanded card may use less, but never more. let maximumExpandedHeight: CGFloat let isResponding: Bool let isStopping: Bool @@ -17,14 +10,11 @@ struct ClarificationRequestInset: View { let isHapticsEnabled: Bool let onSubmit: (String) -> Void let onStop: () -> Void - /// Collapsing hides the response field, so the keyboard goes with it. let onDismissKeyboard: () -> Void - /// The bar's height, the only part of this view that takes layout space. let onFootprintChange: (CGFloat) -> Void @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var isExpanded = true - // Lives here rather than in the card so a typed answer survives collapse. @State private var draftResponse = "" var body: some View { @@ -41,10 +31,6 @@ struct ClarificationRequestInset: View { onFootprintChange(height) } .overlay(alignment: .bottom) { - // Clip window with its bottom edge on the bar's bottom edge: the - // opaque card slides its own height down through it, revealing the - // transcript and then the bar only where it has physically left. - // No crossfade, and nothing is drawn over the composer below. ZStack(alignment: .bottom) { if isExpanded { ClarificationRequestCard( @@ -79,7 +65,6 @@ struct ClarificationRequestInset: View { } } - /// One announcement per request; re-renders and toggles stay silent. private func announceRequest() { guard UIAccessibility.isVoiceOverRunning else { return } let announcement = String(localized: "Input needed: \(ClarificationRequestBar.summary(for: prompt.question))") @@ -87,17 +72,12 @@ struct ClarificationRequestInset: View { } } -/// One-line footprint of a pending request: what is being asked, a way back -/// into the card, and Stop for when the run should end instead. struct ClarificationRequestBar: View { - /// What the bar stands in for: a question or other input, or an approval, - /// which carries a warning accent and the count of open approvals (#1584). enum Kind: Equatable { case input case approval(pendingCount: Int) } - /// One line of what is asked (`summary(for:)`). let summary: String let isStopping: Bool let onExpand: () -> Void @@ -107,8 +87,6 @@ struct ClarificationRequestBar: View { @Environment(\.colorScheme) private var colorScheme @ScaledMetric(relativeTo: .body) private var stopButtonSize: CGFloat = 32 - /// The first non-empty line of a question, so a multi-line prompt reads - /// as one line on the bar. static func summary(for question: String) -> String { question .split(whereSeparator: \.isNewline) @@ -187,7 +165,6 @@ struct ClarificationRequestBar: View { private var isApproval: Bool { kind != .input } - /// The open approvals, or 0 for an input request. private var approvalCount: Int { if case .approval(let pendingCount) = kind { return pendingCount } return 0 @@ -225,7 +202,6 @@ struct ClarificationRequestCard: View { cardContent .frame(maxWidth: 560, alignment: .leading) .pendingRequestCardSurface(cornerRadius: ChatComposerMetrics.cardCornerRadius) - // Honor the clamped ideal height; hide only until base measurements settle. .fixedSize(horizontal: false, vertical: true) .opacity(hasMeasuredBaseContent ? 1 : 0) .allowsHitTesting(hasMeasuredBaseContent && canFit != false) @@ -301,7 +277,6 @@ struct ClarificationRequestCard: View { } } - /// Only the question and choices scroll; a drag dismisses the keyboard interactively. private var scrollableBody: some View { let content = VStack(alignment: .leading, spacing: 14) { question @@ -516,35 +491,21 @@ struct ClarificationRequestCard: View { } } -/// A Hermes session's question, sudo or secret prompt, Desktop task or connection operation, -/// pinned above the composer in the webui clarification's slot (#1011, #1141). The -/// clarification bar is its footprint; the expanded card is the Bot request card, which -/// already answers each of them: batch questions keyed by `qid`, masked credential fields, -/// Skip, a connection's rows and Continue without, and a Desktop task's Stop. The card stays mounted while collapsed, so a -/// half-typed answer survives, and slides through the bar's clip window like the webui card. -/// Taller than the space above the composer, it scrolls. With no room for even a line of it, -/// it falls back to the bar like the webui card, and expanding then puts the keyboard away. struct HermesRequestInset: View { let request: BotPendingRequest let identity: String - /// Height between the chat's top safe edge and this inset's bottom edge. let maximumExpandedHeight: CGFloat let isEnabled: Bool let isAnswering: Bool let isStopping: Bool - /// The connection card's verdict: inert after the host lost the operation, or a warning. let resolution: BotRequestResolution? let isHapticsEnabled: Bool let onAnswer: ([BotQuestionAnswer]) -> Void let onSkip: () -> Void - /// Sends a credential prompt's typed value. Empty is the host's skip. let onCredential: (String) -> Void - /// One row's answer, or Continue without, for a connection operation. let onConnection: (BotConnectionOperation.Answer) -> Void - /// The chat's Stop, from the bar and a Desktop task's card. let onStop: () -> Void let onDismissKeyboard: () -> Void - /// The bar's height, the only part of this view that takes layout space. let onFootprintChange: (CGFloat) -> Void @Environment(\.accessibilityReduceMotion) private var reduceMotion @@ -583,14 +544,10 @@ struct HermesRequestInset: View { } } - /// The card's scroll viewport at most: the space under the collapse control. private var availableScrollHeight: CGFloat { maximumExpandedHeight - collapseButtonSize - 8 } - /// Room for at least a line of the card, as the webui card requires. private var canFit: Bool { availableScrollHeight >= minimumScrollHeight } - /// The collapse control over the card, and the card, which scrolls once it is taller than - /// the space left. Hidden until measured. private var card: some View { VStack(alignment: .trailing, spacing: 8) { collapseButton @@ -627,8 +584,6 @@ struct HermesRequestInset: View { .accessibilityLabel("Collapse clarification") } - /// What the bar says is asked: the first question, the credential prompt's title, what - /// Desktop is doing, or the apps to connect. private var summary: String { switch request { case .question(let question): return ClarificationRequestBar.summary(for: question.questions.first?.prompt ?? "") @@ -651,7 +606,6 @@ struct HermesRequestInset: View { } } -/// Converts the safe gap into a body viewport, or nil to fall back to the collapsed bar. struct ClarificationRequestHeightPolicy { static let bodyHeightCap: CGFloat = 300 diff --git a/HermesMobile/Features/Chat/ComposerChipRendering.swift b/HermesMobile/Features/Chat/ComposerChipRendering.swift index 6bd206e8a..524170996 100644 --- a/HermesMobile/Features/Chat/ComposerChipRendering.swift +++ b/HermesMobile/Features/Chat/ComposerChipRendering.swift @@ -1,15 +1,7 @@ import SwiftUI import UIKit -/// The chip a skill, file or bot reference is drawn as: one attachment glyph that stands for -/// the whole `source` string. -/// -/// Everything that leaves the editor - what is sent, copied, cut, or saved as a -/// draft - reads `source` back out, so the chip never changes the message. final class ComposerChipAttachment: NSTextAttachment { - /// The reference this glyph stands for. Carried whole so a tap on the chip - /// can report what was tapped without the caller re-deriving it from a - /// caret offset. let token: ComposerChipToken var source: String { token.source } @@ -29,9 +21,6 @@ final class ComposerChipAttachment: NSTextAttachment { } } -/// A zero-source attachment for one explicitly selected response passage. -/// Unlike skill and file chips, it is backed by draft metadata rather than a -/// substring the user can type. final class ComposerQuoteAttachment: NSTextAttachment { let quote: ComposerQuote @@ -52,17 +41,9 @@ final class ComposerQuoteAttachment: NSTextAttachment { } extension NSAttributedString.Key { - /// Spacing between quote attachments is part of their presentation and must - /// never enter the typed draft. static let composerQuoteSpacer = NSAttributedString.Key("com.hermex.composerQuoteSpacer") } -/// Chip geometry, derived from the editor's own font so Dynamic Type moves the -/// chip with the text around it. -/// -/// t3code draws a 24 pt chip against a 15 pt label; every other measurement is a -/// fraction of that height, so scaling the height by the label's line height -/// keeps the proportions at every content size. struct ComposerChipMetrics: Equatable { let labelFont: UIFont let height: CGFloat @@ -85,18 +66,9 @@ struct ComposerChipMetrics: Equatable { } } -/// Draws the chip. The image is baked against a trait collection, so the editor -/// re-renders it when the appearance or the content size category changes. @MainActor enum ComposerChipRenderer { - /// Baked chips, keyed by everything that changes one. The editor redraws - /// only when its chips or its style move, but the collapsed composer draws - /// from `body`, which runs again on every parent update — including each - /// token of a live stream. Baking there uncached would burn a render pass - /// per frame for a picture that never changed. private static let cache = NSCache() - /// Retain image-valued keys and hash every component. NSArray's own hash - /// only reflects its count, which would put every chip in the same bucket. private final class CacheKey: NSObject { let values: [NSObject] init(_ values: [NSObject]) { self.values = values } @@ -153,8 +125,6 @@ struct ComposerChipMetrics: Equatable { return image } - /// The chip's glyph: an SF Symbol takes the chip's muted tint, a file-type - /// asset keeps its own colours. private static func iconImage( _ icon: ComposerChipIcon, metrics: ComposerChipMetrics, @@ -179,7 +149,6 @@ struct ComposerChipMetrics: Equatable { let view = BotAvatarView(profile: reference.profile, avatar: reference.avatar, size: metrics.iconSize, motion: .still) .environment(\.colorScheme, traits.userInterfaceStyle == .dark ? .dark : .light) let renderer = ImageRenderer(content: view) - // Traits report 0 before the view reaches a window; the real scale is a new cache key. renderer.scale = max(traits.displayScale, 1) return renderer.uiImage } @@ -237,9 +206,6 @@ struct ComposerChipMetrics: Equatable { path.lineWidth = 1 path.stroke() - // The icon leads in both directions: mirroring it by hand is what - // keeps an RTL chip from reading back to front, since the image is - // drawn once and reused as a glyph. let iconX = isRightToLeft ? width - metrics.horizontalPadding - metrics.iconSize : metrics.horizontalPadding @@ -269,10 +235,6 @@ struct ComposerChipMetrics: Equatable { } } -/// Everything about the current environment that changes a chip's picture. -/// -/// Built inside a view's `body` so SwiftUI re-evaluates — and the chips -/// re-measure — when appearance, contrast, direction, or text size moves. struct ComposerChipTextStyle { let metrics: ComposerChipMetrics let traits: UITraitCollection @@ -286,7 +248,6 @@ struct ComposerChipTextStyle { displayScale: CGFloat, appearance: AppAppearance ) { - // The same body style the editor uses, at this view's text size. metrics = ComposerChipMetrics(editorFont: .app(forTextStyle: .body, at: dynamicTypeSize)) traits = UITraitCollection { traits in traits[AppAppearanceTrait.self] = appearance @@ -298,15 +259,7 @@ struct ComposerChipTextStyle { } } -/// A run of text with its skill references drawn as chips, for the two places -/// SwiftUI does the drawing: the collapsed composer pill and the sent user -/// bubble. The expanded editor is a `UITextView` with real attachments instead, -/// but every chip is the same picture, so one reference cannot look like two -/// different things on either side of the send. enum ComposerChipTextLine { - /// The tokens that still describe `text`. A caller whose chips were - /// computed a beat earlier can hand over a set the text has since outgrown; - /// drawing none is better than drawing one in the wrong place. static func validTokens(_ tokens: [ComposerChipToken], in text: String) -> [ComposerChipToken] { let string = text as NSString guard tokens.allSatisfy({ @@ -317,8 +270,6 @@ enum ComposerChipTextLine { return tokens } - /// `text` with every token replaced by its chip picture and the rest left - /// verbatim, so nothing in a message is read as markdown or a format string. @MainActor static func text( _ text: String, tokens: [ComposerChipToken], @@ -355,21 +306,7 @@ enum ComposerChipTextLine { } } -/// Crossing between the draft the server sees and the text the editor draws. -/// -/// A chip is one character on screen and its whole source string in the draft, -/// so every caret the editor reports and every range the composer asks for has -/// to be translated. The rendered document is the authority: reading the -/// mapping off the attachments themselves means a caret can never be computed -/// from a stale idea of where the chips are. -/// -/// An attachment this file did not make contributes nothing at all — not even -/// the U+FFFC placeholder standing in for it on screen. The draft is what gets -/// sent, saved, and copied, so anything the editor cannot describe as text has -/// no business reaching it: a stray glyph would travel to the server, come back -/// in the transcript, and be rendered by whatever reads it next. extension NSAttributedString { - /// The draft text this document stands for. var composerSourceText: String { composerSourceText(in: NSRange(location: 0, length: length)) } @@ -392,7 +329,6 @@ extension NSAttributedString { return source as String } - /// The draft offset a display offset points at. func composerSourceOffset(forDisplayOffset displayOffset: Int) -> Int { let bounded = max(0, min(length, displayOffset)) guard bounded > 0 else { return 0 } @@ -409,9 +345,6 @@ extension NSAttributedString { return source } - /// The display offset a draft offset points at. An offset that lands inside - /// a chip resolves to just after it, because there is nowhere inside a chip - /// for a caret to be. func composerDisplayOffset(forSourceOffset sourceOffset: Int) -> Int { var source = 0 var display = 0 @@ -420,8 +353,6 @@ extension NSAttributedString { if let chip = attributes[.attachment] as? ComposerChipAttachment { let chipLength = (chip.source as NSString).length if sourceOffset < source + chipLength { - // The chip's own start still has a caret position; anywhere - // else inside it resolves to just after the chip. display = sourceOffset <= source ? range.location : NSMaxRange(range) stop.pointee = true return @@ -442,14 +373,12 @@ extension NSAttributedString { return display } - /// The display range a draft range covers. func composerDisplayRange(forSourceRange range: NSRange) -> NSRange { let start = composerDisplayOffset(forSourceOffset: range.location) let end = composerDisplayOffset(forSourceOffset: range.upperBound) return NSRange(location: start, length: max(0, end - start)) } - /// The draft range a display range covers. func composerSourceRange(forDisplayRange range: NSRange) -> NSRange { let start = composerSourceOffset(forDisplayOffset: range.location) let end = composerSourceOffset(forDisplayOffset: range.upperBound) diff --git a/HermesMobile/Features/Chat/ComposerChipTextView.swift b/HermesMobile/Features/Chat/ComposerChipTextView.swift index 5fcb69d94..4d4295950 100644 --- a/HermesMobile/Features/Chat/ComposerChipTextView.swift +++ b/HermesMobile/Features/Chat/ComposerChipTextView.swift @@ -1,19 +1,11 @@ import UIKit import UniformTypeIdentifiers -/// The composer's editor: a text view that draws known skill references as -/// atomic chips while every value that leaves it stays the draft's own text. final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { private var pendingTransitionFocus: UUID? - /// The owner's current focus intent, read when a deferred focus is about to - /// land. UIKit's own restoration can re-request focus after a bound blur in - /// the same pop (#831), so a cancel alone cannot guarantee the blur wins. var wantsDeferredFocus: () -> Bool = { true } - /// UIKit re-promotes the last editor while a navigation pop is still animating, - /// before SwiftUI's keyboard safe area can follow, which leaves the composer - /// behind the keyboard (#810). Defer focus until the transition finishes. override func becomeFirstResponder() -> Bool { guard let coordinator = owningViewController?.transitionCoordinator else { cancelDeferredFocus() @@ -32,14 +24,10 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { return false } - /// Blur can arrive before UIKit has made this editor first responder. func cancelDeferredFocus() { pendingTransitionFocus = nil } - /// Gives up the keyboard for dictation, sent down the responder chain from the - /// mic. A live composition is committed first, or dictation's first write would - /// replace the document under it and split its characters (#312). @objc func resignForDictation() { if markedTextRange != nil { unmarkText() } _ = resignFirstResponder() @@ -55,8 +43,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { if window == nil { cancelDeferredFocus() } } - /// Navigation temporarily resigns the editor without changing the user's - /// focus intent. Preserve that intent so the return can restore it. var isInNavigationTransition: Bool { owningViewController?.navigationController?.transitionCoordinator != nil } @@ -72,35 +58,20 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { var acceptsAttachments = true var keyboardCommands = ComposerKeyboardCommands() - /// Settings' Send with Return (#1655): a hardware-keyboard ↩ does what ⌘↩ does, - /// and ⇧↩ or ⌥↩ types the newline. UIKit sends key commands only from a - /// hardware keyboard, so the on-screen Return key keeps typing newlines. var returnSends = false - /// The chat's last sent message, which ↑ brings back into an empty editor - /// on a hardware keyboard. Nil where there is no single author to recall - /// (Bot rooms), which leaves ↑ to move the caret. var recallLastSentText: (() -> String?)? var onPasteFileProviders: ([NSItemProvider]) -> Void = { _ in } var onPasteFileURLs: ([URL]) -> Void = { _ in } var onPasteImageProviders: ([NSItemProvider]) -> Void = { _ in } var onPasteImages: ([UIImage]) -> Void = { _ in } - /// Takes a paste past `ComposerLargePaste.threshold` as a file (#1381). Nil - /// keeps every paste inline and turns Paste as Text off. var onPasteLargeText: ((String) -> Void)? - /// What paste reads and copy writes. Tests use a private one rather than the - /// clipboard the simulator shares with the Mac. var pasteboard = UIPasteboard.general - /// Reports a tap that landed on a chip's glyph. Every chip reports; what a - /// tap means belongs to the composer. var onTapChip: (ComposerChipToken) -> Void = { _ in } var onTapQuote: (ComposerQuote) -> Void = { _ in } var onRemoveQuote: (UUID) -> Void = { _ in } - /// Explicit quoted passages are zero-source chips placed before the typed - /// draft. Their ids and full text live outside the editor document. var quotes: [ComposerQuote] = [] - /// The skills whose references are drawn as chips. var chipSkills: [SkillSlashSuggestion] = [] { didSet { guard chipSkills != oldValue else { return } @@ -108,8 +79,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { } } - /// The workspace files this composer has inserted, whose `@path` references - /// are drawn as chips. var chipFilePaths: Set = [] { didSet { guard chipFilePaths != oldValue else { return } @@ -117,7 +86,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { } } - /// Resolvable bot aliases from this composer's connection, including avatars. var chipBots: [String: ComposerBotReference] = [:] { didSet { guard chipBots != oldValue else { return } @@ -126,10 +94,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { } private var chipCatalog = ComposerChipCatalog.empty - /// The chips currently on screen. The collapsed pill reads this rather than - /// re-deriving it, because `preservingTrailing` makes the set depend on what - /// was drawn before — a trailing chip whose space was deleted stays a chip, - /// and nothing but this editor knows that. private(set) var renderedTokens: [ComposerChipToken] = [] private(set) var renderedQuotes: [ComposerQuote] = [] private var renderedStyle: ChipRenderStyle? @@ -141,9 +105,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { return recognizer }() - /// What the chips were drawn against. A chip is a baked image, so a change - /// of appearance or text size has to redraw it even when the draft has not - /// moved at all. private struct ChipRenderStyle: Equatable { let fontName: String let fontPointSize: CGFloat @@ -163,9 +124,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { registerForTraitChanges( [UITraitUserInterfaceStyle.self, AppAppearanceTrait.self, UITraitAccessibilityContrast.self, UITraitPreferredContentSizeCategory.self, UITraitDisplayScale.self] ) { (view: ComposerChipTextView, _) in - // Deferred: `adjustsFontForContentSizeCategory` updates `font` from - // the same trait change, and the chips have to be sized against the - // font that wins. DispatchQueue.main.async { view.refreshChipsIfNeeded() } } } @@ -175,17 +133,10 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { nil } - // MARK: - Draft text - - /// The typed portion of the draft: every skill or file chip contributes the - /// reference it was made from, while quote chips contribute nothing. Quote - /// metadata is combined with this text by the owning composer when it saves - /// or sends; copy and slash-trigger matching use this source text directly. var sourceText: String { attributedText.composerSourceText } - /// The caret or selection in draft coordinates. var sourceSelection: NSRange { get { attributedText.composerSourceRange(forDisplayRange: selectedRange) } set { @@ -195,10 +146,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { } } - /// Applies the SwiftUI-owned direction and enabled appearance without - /// rewriting text attributes on every representable update. A redundant - /// alignment or colour assignment invalidates UITextView layout and can - /// reveal the caret after the user has manually scrolled elsewhere. func applyPresentationStyle(isRightToLeft: Bool, isDisabled: Bool) { let semanticAttribute: UISemanticContentAttribute = isRightToLeft ? .forceRightToLeft : .unspecified if semanticContentAttribute != semanticAttribute { @@ -216,33 +163,21 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { } } - /// UIKit may place a caret on the zero-source quote prefix after a chip tap. - /// Map it back through draft coordinates so typing always starts after the - /// quote metadata. func normalizeSelectionAroundQuoteMetadata() { let draftSelection = sourceSelection sourceSelection = draftSelection } - /// The on-screen range a draft range covers, or `nil` when it does not land - /// on positions this editor recognises. func displayTextRange(forSourceRange range: NSRange) -> UITextRange? { textRange(from: attributedText.composerDisplayRange(forSourceRange: range)) } - // MARK: - Chips - - /// Keeps the chip recognizer out of UIKit's gesture arbitration unless the - /// touch begins on a rendered chip. Ordinary text touches remain entirely - /// owned by the text view's native editing recognizers. func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { guard gestureRecognizer === chipTapRecognizer else { return true } guard !renderedTokens.isEmpty || !renderedQuotes.isEmpty else { return false } return tappableChip(at: touch.location(in: self)) != nil } - /// A chip tap reports its action while UIKit continues handling the same - /// touch for caret placement and selection. func gestureRecognizer( _ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer @@ -273,12 +208,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { case quote(ComposerQuote) } - /// The chip whose glyph covers `point`, or `nil`. - /// - /// `closestPosition` answers with a caret boundary, so the characters on - /// both sides of it are candidates; the glyph's own rectangle is what - /// decides, which is what keeps a tap in the space beside a chip from - /// counting as a tap on it. private func tappableChip(at point: CGPoint) -> TappableChip? { guard let position = closestPosition(to: point) else { return nil } let caret = offset(from: beginningOfDocument, to: position) @@ -305,10 +234,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { return nil } - /// Redraws the document when the chips the draft calls for, or the way they - /// have to be drawn, no longer match what is on screen. Ordinary typing - /// changes neither, so it never rebuilds — which is what keeps predictive - /// text and the undo stack alive. func refreshChipsIfNeeded() { guard markedTextRange == nil else { return } @@ -323,10 +248,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { render(source: source, tokens: tokens, quotes: quotes, sourceSelection: sourceSelection) } - /// Replaces the whole draft, chips and all. The fallback for an edit the - /// input system could not apply in place, and for a deliberate clear. - /// `isComplete` draws a reference that ends the text as a chip, the way the - /// transcript draws a sent message. func replaceDocument(with source: String, isComplete: Bool = false) { let tokens = ComposerChipTokenizer.tokens( in: source, @@ -342,9 +263,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { ) } - /// Restores the plain typing attributes a chip attachment would otherwise - /// leave behind. Never while an IME composition is marked: touching typing - /// attributes mid-composition breaks it. func restoreTypingAttributes() { guard markedTextRange == nil else { return } @@ -428,8 +346,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { } attributedText = document - // Assigning a non-uniform document clears these, and every later render - // reads them back for its base attributes. self.font = font self.textColor = textColor renderedTokens = tokens @@ -437,14 +353,9 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { renderedStyle = currentStyle self.sourceSelection = Self.clamp(sourceSelection, toLengthOf: source) restoreTypingAttributes() - // The document was replaced wholesale, so an undo recorded against the - // old one would put back text the chips no longer describe. discardUndoHistory() } - /// Clears the undo stack once no undo group is open. Clearing also drops - /// open groups, and dictation keeps one open across its insertions: its - /// later close then has no match, and UIKit aborts the app (#1303). private func discardUndoHistory() { guard let undoManager else { return } guard undoManager.groupingLevel > 0 else { @@ -463,7 +374,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { @objc private func undoGroupDidClose(_ notification: Notification) { NotificationCenter.default.removeObserver(self, name: .NSUndoManagerDidCloseUndoGroup, object: nil) - // The group is still closing while this posts. DispatchQueue.main.async { [weak self] in guard let self else { return } isUndoClearPending = false @@ -526,10 +436,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { return NSRange(location: location, length: min(max(0, range.length), length - location)) } - // MARK: - Editing - - /// A chip deletes as one thing: backspacing next to it removes the whole - /// reference rather than the last character of a name the user cannot see. override func deleteBackward() { if selectedRange.length == 0, sourceSelection.location == 0, @@ -554,8 +460,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { replace(range, withText: "") } - /// Copy and cut hand over the draft text, so a chip pasted anywhere - back - /// into this composer, or into any other app - is the reference itself. override func copy(_ sender: Any?) { guard selectedRange.length > 0 else { super.copy(sender) @@ -613,9 +517,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { title: send.title, action: #selector(sendFromKeyboard), input: "\r", modifierFlags: .command )) } - // Left out entirely while an IME composition is open, so ↩ confirms the - // candidate. Otherwise registered even while Send is unavailable, so ↩ on an - // empty or blocked draft does nothing rather than type a newline. if returnSends, acceptsKeyboardCommands { let send = UIKeyCommand( title: keyboardCommands.send?.title ?? String(localized: "Send Message"), @@ -623,7 +524,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { ) send.wantsPriorityOverSystemBehavior = true commands.append(send) - // ⌥↩ works too but stays out of the ⌘-hold overlay, which lists ⇧↩ once. let newlines = [ UIKeyCommand( title: String(localized: "New Line"), action: #selector(newlineFromKeyboard), @@ -663,7 +563,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { input: UIKeyCommand.inputUpArrow, modifierFlags: [] ) - // Arrow keys go to text editing first otherwise. recallCommand.wantsPriorityOverSystemBehavior = true return commands + [recallCommand] } @@ -704,9 +603,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { return super.canPerformAction(action, withSender: sender) } - /// A locked editor takes no command, and an unfinished IME composition keeps - /// Return and Esc for itself: ⌘↩ must never submit half-composed text. Checked - /// again when a key fires, since UIKit can dispatch a command it listed earlier. private var acceptsKeyboardCommands: Bool { isEditable && markedTextRange == nil } @@ -736,8 +632,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { keyboardCommands.escape?.perform() } - /// What ↑ would bring back. Only an empty editor takes it, so ↑ inside a - /// draft, or with a quote staged, keeps moving the caret. private var recallableText: String? { guard acceptsKeyboardCommands, quotes.isEmpty, textStorage.length == 0, let text = recallLastSentText?(), !text.isEmpty @@ -747,11 +641,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { return text } - /// Fills the empty editor with the last sent message as one undoable edit: - /// chips drawn as its bubble draws them, the caret at the end, and the - /// draft published like typing. Drawing chips replaces the document and - /// clears the undo stack, so the undo that empties the editor again is - /// registered here rather than left to the input system. @objc private func recallLastSentTextFromKeyboard() { guard let text = recallableText else { return } @@ -799,7 +688,6 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { return } - // An IME composition keeps UIKit's own paste. if let onPasteLargeText, isEditable, markedTextRange == nil, let text = pasteboard.string, ComposerLargePaste.converts(text) { onPasteLargeText(text) @@ -809,14 +697,10 @@ final class ComposerChipTextView: UITextView, UIGestureRecognizerDelegate { super.paste(sender) } - /// Whether ⌘⇧V and the edit menu's Paste as Text are on: only where long - /// pastes convert, and never mid-composition. var canPasteAsText: Bool { onPasteLargeText != nil && acceptsKeyboardCommands && pasteboard.hasStrings } - /// Puts the copied text in inline however long it is, as an ordinary edit - /// that publishes the draft and that undo takes back. @objc func pasteAsText() { guard canPasteAsText, let text = pasteboard.string else { return } insertText(text) diff --git a/HermesMobile/Features/Chat/ComposerChipToken.swift b/HermesMobile/Features/Chat/ComposerChipToken.swift index e2fc94936..5ed20c0d1 100644 --- a/HermesMobile/Features/Chat/ComposerChipToken.swift +++ b/HermesMobile/Features/Chat/ComposerChipToken.swift @@ -1,26 +1,17 @@ import Foundation import SwiftUI -/// What a chip stands for. The kind picks the glyph and decides whether tapping -/// the chip does anything: a file opens on the source viewer; skills and bots are inert. enum ComposerChipKind: Equatable { case skill case file case bot(ComposerBotReference) } -/// The picture inside a chip. -/// -/// A skill draws an SF Symbol in the chip's own muted tint. A file draws the -/// full-colour glyph the file tree already uses for its type, so one file reads -/// the same in the composer, the workspace, and the transcript. enum ComposerChipIcon: Equatable { case symbol(String) case asset(String) case bot(ComposerBotReference) - /// Value key for the renderer. Image keys retain the actual image so two - /// connections or an updated avatar cannot reuse another chip's pixels. var cacheKey: NSObject { switch self { case let .symbol(name): @@ -36,34 +27,19 @@ enum ComposerChipIcon: Equatable { } } -/// A connection-local bot identity and its already-decoded inbox thumbnail. struct ComposerBotReference: Equatable { let profile: BotProfile let avatar: UIImage? } -/// A skill, bot or workspace-file reference in the draft that the composer draws as -/// one atomic chip. -/// -/// `range` and `source` are always in draft coordinates. The chip is a picture -/// of `source`, never a replacement for it, so what the server receives and what -/// the draft store keeps is exactly the text the user would have typed. struct ComposerChipToken: Equatable { - /// UTF-16 range of the reference inside the draft. let range: NSRange - /// The exact draft substring the chip stands for, `/` or `@` included. let source: String - /// What the chip reads on screen: a skill's name, or a file's last path - /// component, or a bot's display name. let label: String let kind: ComposerChipKind - /// Matches the Skills screen's own glyph so a skill chip reads as the same - /// thing the rest of the app calls a skill. private static let skillSymbol = "hammer" - /// Derived rather than stored so a chip's picture can never drift from what - /// the chip stands for. var icon: ComposerChipIcon { switch kind { case .skill: @@ -75,21 +51,14 @@ struct ComposerChipToken: Equatable { } } - /// The workspace-relative path a file chip names, or `nil` for a skill or bot. var filePath: String? { guard kind == .file else { return nil } return String(source.dropFirst()) } } -/// The references a draft can draw as chips, in the shape the tokenizer needs. -/// -/// Built from the composer's skills, picked workspace files and bot roster, -/// and compared by value so the editor redraws only when a reference changes. struct ComposerChipCatalog: Equatable { - /// Lowercased slug to chip label. private let labelsBySlug: [String: String] - /// Workspace-relative paths, exactly as the server spells them. private let filePaths: Set let bots: [String: ComposerBotReference] @@ -101,8 +70,6 @@ struct ComposerChipCatalog: Equatable { self.filePaths = filePaths } - /// A slug that is also a built-in command is left out: `/model` is the - /// command, whatever a server happens to call its skills. init(skills: [SkillSlashSuggestion], filePaths: Set = [], bots: [String: ComposerBotReference] = [:]) { self.bots = bots var labels: [String: String] = [:] @@ -121,40 +88,19 @@ struct ComposerChipCatalog: Equatable { labelsBySlug[slug.lowercased()] } - /// Paths are compared exactly: the server's filesystem decides case, and a - /// path the app has never been handed is not a reference. func containsFile(path: String) -> Bool { filePaths.contains(path) } - /// The same skills with `paths` as the files a chip may be drawn for. func withFilePaths(_ paths: Set) -> ComposerChipCatalog { ComposerChipCatalog(labelsBySlug: labelsBySlug, filePaths: paths, bots: bots) } } -/// Finds the references in a draft. Pure: the same draft and catalog always -/// produce the same chips, which is what lets a pasted or restored draft come -/// back with its chips intact without storing anything beside the text. enum ComposerChipTokenizer { private static let slash: UInt16 = 0x2F private static let at: UInt16 = 0x40 - /// Every reference in `draft` worth drawing as a chip. - /// - /// A reference is a `/` or `@` that starts the draft or follows whitespace, - /// a name the catalog knows, and whitespace after it. A skill's name runs to - /// the end of its slug; a file's path runs to the next whitespace, because a - /// path is one unbroken word. The trailing whitespace is what says the user - /// is done typing, so a half-typed `/ask-ma` or `@src/Cha` stays ordinary - /// editable text. `previous` keeps a chip at the very end of the draft drawn - /// after its trailing space is deleted, so backspacing the space a - /// completion added does not flicker the chip back into text. - /// - /// `isComplete` says the text is finished rather than being typed, which is - /// what a sent message is: a reference that ends the message is a whole - /// reference, so the transcript draws the chip the composer was still - /// waiting for a space to confirm. static func tokens( in draft: String, catalog: ComposerChipCatalog, @@ -229,9 +175,6 @@ enum ComposerChipTokenizer { return tokens } - /// `draft` with every chip reference replaced by the chip's label, which is - /// what VoiceOver should read: the editor's attachments carry the same - /// label, so both composer states are heard the same way. static func spokenText(in draft: String, tokens: [ComposerChipToken]) -> String { guard !tokens.isEmpty else { return draft } @@ -256,18 +199,6 @@ enum ComposerChipTokenizer { return spoken as String } - /// Every `@…` run in `text` that could name a workspace file, in the order - /// they appear and without repeats. - /// - /// Deliberately the same scan the tokenizer uses — an `@` that starts the - /// text or follows whitespace, running to the next whitespace — and - /// deliberately without a "looks like a filename" heuristic. Whether a - /// candidate is a file is the server's answer to give, and guessing here - /// would mean a real reference silently failing to draw. - /// - /// `isComplete` carries the tokenizer's meaning: without it a reference that - /// ends the text is still being typed, so `@sr` on the way to `@src/x.swift` - /// is not offered as something to look up. static func fileReferenceCandidates(in text: String, isComplete: Bool = false) -> [String] { let text = text as NSString var candidates: [String] = [] @@ -298,10 +229,6 @@ enum ComposerChipTokenizer { return candidates } - /// Whether `draft` holds anything that could become a chip once the skill - /// list or the session's picked files arrive. The composer uses it to warm - /// that list for a restored draft instead of fetching skills every time a - /// chat opens. static func mayContainReference(_ draft: String) -> Bool { let text = draft as NSString var index = 0 @@ -319,13 +246,6 @@ enum ComposerChipTokenizer { return false } - /// Whether `unit` continues a reference opened by `marker`. - /// - /// A file path is any run of non-whitespace, since `/`, `.`, and `-` are all - /// ordinary path characters. A skill slug is narrower: `SlashSkillFormatter` - /// only ever emits lowercase letters, digits, and hyphens, and the rest are - /// accepted so a hand-typed `/Ask_Matt` is scanned as one word and rejected - /// by the catalog rather than cut in half. private static func isBodyUnit(_ unit: UInt16, after marker: UInt16) -> Bool { guard let scalar = Unicode.Scalar(UInt32(unit)) else { return false } guard marker == slash else { @@ -347,13 +267,6 @@ private struct ComposerChipCatalogKey: EnvironmentKey { } extension EnvironmentValues { - /// The skills and workspace files a transcript may draw as chips. - /// - /// Sent messages carry no marker for a reference, so the bubble has to look - /// the slug or path up the same way the composer does. It travels in the - /// environment because it belongs to the chat, not to any one bubble, and - /// the rows in between are `Equatable` blocks that should not have to - /// forward it. var composerChipCatalog: ComposerChipCatalog { get { self[ComposerChipCatalogKey.self] } set { self[ComposerChipCatalogKey.self] = newValue } diff --git a/HermesMobile/Features/Chat/ComposerDocumentThumbnails.swift b/HermesMobile/Features/Chat/ComposerDocumentThumbnails.swift index 844eaa3ee..f07b2836d 100644 --- a/HermesMobile/Features/Chat/ComposerDocumentThumbnails.swift +++ b/HermesMobile/Features/Chat/ComposerDocumentThumbnails.swift @@ -1,15 +1,10 @@ import QuickLookThumbnailing import UIKit -/// Draws a file's thumbnail. Quick Look in the app; a double in tests. protocol ComposerThumbnailGenerating: Sendable { - /// The thumbnail, or nil when there is none to draw. func thumbnail(ofFileAt url: URL, size: CGSize, scale: CGFloat) async -> UIImage? } -/// Quick Look's `.thumbnail` representation: a PDF's first page, or a -/// rendered excerpt of a text or Office document. Formats with no thumbnail -/// (an archive, say) answer nil rather than a generic icon. struct QuickLookComposerThumbnailGenerator: ComposerThumbnailGenerating { func thumbnail(ofFileAt url: URL, size: CGSize, scale: CGFloat) async -> UIImage? { let request = QLThumbnailGenerator.Request( @@ -26,11 +21,6 @@ struct QuickLookComposerThumbnailGenerator: ComposerThumbnailGenerating { } } -/// Previews of the documents staged in a composer, drawn from each one's -/// app-owned draft copy. One cache serves the attachment strip and the -/// collapsed pill in every chat, keyed by the copy's file name, which a draft -/// restore keeps, so a reopened chat shows its previews at once. An edited paste -/// gets a new copy (#1456), so it draws a new preview under the same attachment. @MainActor final class ComposerDocumentThumbnails { static let shared = ComposerDocumentThumbnails() @@ -38,10 +28,7 @@ final class ComposerDocumentThumbnails { private let store: any ChatDraftAttachmentStoring private let generator: any ComposerThumbnailGenerating private let limit: Int - /// A nil value is a document Quick Look couldn't draw, kept so it isn't - /// retried on every render. private var results: [String: UIImage?] = [:] - /// Oldest first, for evicting past `limit`. private var order: [String] = [] init( @@ -54,17 +41,10 @@ final class ComposerDocumentThumbnails { self.limit = limit } - /// A preview already made, without starting any work, so a tile that - /// reappears draws it in its first frame. func cachedThumbnail(for attachment: PendingAttachment) -> UIImage? { attachment.draftFileName.flatMap { results[$0] ?? nil } } - /// The document's preview, made once per copy. Images (which carry - /// their own thumbnail) and attachments without a draft copy get nil - /// without any work. A result is kept per copy, not per size, so - /// every caller asks at one size. A cancelled request keeps nothing, so - /// the next caller makes it afresh. func thumbnail(for attachment: PendingAttachment, size: CGSize, scale: CGFloat) async -> UIImage? { guard !attachment.isImage, let fileName = attachment.draftFileName else { return nil } if let result = results[fileName] { return result } diff --git a/HermesMobile/Features/Chat/ComposerFileTrigger.swift b/HermesMobile/Features/Chat/ComposerFileTrigger.swift index 824134c7a..ce22051ee 100644 --- a/HermesMobile/Features/Chat/ComposerFileTrigger.swift +++ b/HermesMobile/Features/Chat/ComposerFileTrigger.swift @@ -1,31 +1,13 @@ import Foundation -/// The `@…` run the caret is sitting in, if there is one. -/// -/// Typing `@` opens the workspace file panel the way `/` opens the command -/// panel. The trigger is found at the caret and reports the range it occupies, -/// so accepting a row replaces only that much and the rest of the draft -/// survives. struct ComposerFileTrigger: Equatable { - /// UTF-16 range of the trigger inside the draft: the `@` up to the caret. let range: NSRange - /// The trigger's text, `@` included. let text: String - /// The workspace path typed so far, without the `@`. This is what the panel - /// lists and filters on. var query: String { String(text.dropFirst()) } private static let at: UInt16 = 0x40 - /// The trigger `selection` sits in, or `nil` when there is none. - /// - /// A trigger is an `@` that starts the draft or follows whitespace, running - /// forward to the caret and never across whitespace or a line break. Those - /// two rules together are what keep an email address out: the `@` in - /// `foo@bar` follows a letter, and the scan stops at the space in front of - /// `foo` rather than looking further back. A selection with a length is - /// never a trigger: the user is selecting text, not naming a file. static func detect(in draft: String, selection: NSRange) -> ComposerFileTrigger? { guard selection.length == 0 else { return nil } @@ -49,14 +31,6 @@ struct ComposerFileTrigger: Equatable { return nil } - /// What the draft and caret become when the user accepts `replacement`. - /// - /// Only the trigger's own range changes. When the completion wants a - /// trailing space and the draft already has one waiting there, the space is - /// dropped and the caret steps over the existing one instead, so accepting a - /// file mid-sentence leaves neither a double space nor a caret stranded in - /// front of one. Deliberately the same arithmetic as - /// `ComposerSlashTrigger.applying(_:to:)`, which owns the `/` panel. func applying(_ replacement: String, to draft: String) -> (draft: String, selection: NSRange) { let draft = draft as NSString let location = min(max(0, range.location), draft.length) diff --git a/HermesMobile/Features/Chat/ComposerModelPickerSectionExpansionState.swift b/HermesMobile/Features/Chat/ComposerModelPickerSectionExpansionState.swift index b5555aea9..19ccf4b5d 100644 --- a/HermesMobile/Features/Chat/ComposerModelPickerSectionExpansionState.swift +++ b/HermesMobile/Features/Chat/ComposerModelPickerSectionExpansionState.swift @@ -36,9 +36,6 @@ struct ComposerModelPickerSectionExpansionState { } } -/// Tracks the provider groups whose server-supplied overflow models the user -/// has chosen to reveal. Both model pickers use the same small state model so -/// their counts and visible rows cannot drift apart. struct ModelPickerOverflowExpansionState { private var expandedGroupIDs: Set = [] diff --git a/HermesMobile/Features/Chat/ComposerQuote.swift b/HermesMobile/Features/Chat/ComposerQuote.swift index 20ce73e46..058f9c3c6 100644 --- a/HermesMobile/Features/Chat/ComposerQuote.swift +++ b/HermesMobile/Features/Chat/ComposerQuote.swift @@ -1,10 +1,5 @@ import Foundation -/// A passage the user explicitly selected from a completed response. -/// -/// Quotes stay separate from typed text so pasted Markdown never turns into a -/// chip. The stable id also lets identical passages remain distinct and be -/// removed one at a time. struct ComposerQuote: Identifiable, Equatable, Sendable { let id: UUID let text: String @@ -14,7 +9,6 @@ struct ComposerQuote: Identifiable, Equatable, Sendable { self.text = text } - /// A single-line label for the chip. The full passage remains in `text`. var preview: String { let collapsed = text .split(whereSeparator: { $0.isWhitespace }) @@ -24,7 +18,6 @@ struct ComposerQuote: Identifiable, Equatable, Sendable { } } -/// The user-editable parts of one persisted composer draft. struct ComposerDraftContent: Equatable, Sendable { var text: String var quotes: [ComposerQuote] @@ -36,8 +29,6 @@ struct ComposerDraftContent: Equatable, Sendable { } } -/// Converts explicit quote metadata into the ordinary Markdown text understood -/// by the existing chat endpoints. enum ComposerQuoteMessageFormatter { static func message(text: String, quotes: [ComposerQuote]) -> String { let quotedPassages = quotes.map { quote in diff --git a/HermesMobile/Features/Chat/ComposerRecall.swift b/HermesMobile/Features/Chat/ComposerRecall.swift index b68e94c99..dd6c9b41c 100644 --- a/HermesMobile/Features/Chat/ComposerRecall.swift +++ b/HermesMobile/Features/Chat/ComposerRecall.swift @@ -1,23 +1,8 @@ import Foundation -/// What ↑ in an empty composer brings back on a hardware keyboard: the last -/// message the user sent in this chat. It is read from the chat's own -/// transcript, so it survives leaving the chat and relaunching the app, and it -/// is per chat and per server by construction. enum ComposerRecall { - /// The ↑ command's name in the iPad ⌘ overlay. static let commandTitle = String(localized: "Recall Last Message") - /// The newest message the user wrote, as the text they typed, or nil when - /// they have sent nothing here. Scans from the end, skipping every row the - /// user didn't write: other roles, Bot system deliveries (a display kind - /// other than a steer), and the compaction markers the transcript draws as - /// cards. A steer loses its out-of-band wrapper and a send loses its - /// `[Attached files: …]` marker; an attachment-only send has no typed text - /// left, so the message before it wins. - /// - /// - Parameter typedText: removes a surface's own attachment text from a - /// user row. Bot Chat passes `BotAttachmentUpload.typedText(of:)`. static func lastSentText( in messages: [ChatMessage], typedText: (String) -> String = { $0 } diff --git a/HermesMobile/Features/Chat/ComposerSlashTrigger.swift b/HermesMobile/Features/Chat/ComposerSlashTrigger.swift index ceb2f5e7d..4c2893c51 100644 --- a/HermesMobile/Features/Chat/ComposerSlashTrigger.swift +++ b/HermesMobile/Features/Chat/ComposerSlashTrigger.swift @@ -1,31 +1,12 @@ import Foundation -/// The `/…` run the caret is sitting in, if there is one. -/// -/// The composer used to treat a draft as a slash query only when the whole draft -/// started with `/`, so `/` halfway through a sentence did nothing and accepting -/// a row threw the rest of the draft away. This finds the trigger at the caret -/// and reports the range it occupies, so accepting a row replaces only that much. -/// It also reports whether the trigger opens the draft: only then can the send -/// path run a command, so mid-sentence the panel offers skills only. struct ComposerSlashTrigger: Equatable { - /// UTF-16 range of the trigger inside the draft: the `/` up to the caret. let range: NSRange - /// The trigger's text, `/` included. This is what the panel filters on. let text: String - /// Whether only whitespace precedes the trigger, which is the same gate the - /// send path uses: a command row mid-sentence would be inserted text that - /// nothing executes. let startsDraft: Bool private static let slash: UInt16 = 0x2F - /// The trigger `selection` sits in, or `nil` when there is none. - /// - /// A trigger is a `/` that starts the draft or follows whitespace, running - /// forward to the caret and never across a line break. A selection with a - /// length is never a trigger: the user is selecting text, not typing a - /// command. static func detect(in draft: String, selection: NSRange, scope: SlashCommandScope = .webui) -> ComposerSlashTrigger? { guard selection.length == 0 else { return nil } @@ -33,10 +14,6 @@ struct ComposerSlashTrigger: Equatable { let caret = selection.location guard caret >= 0, caret <= draft.length else { return nil } - // Every `/` on the caret's line that could open a trigger, then the - // outermost one that holds up. A path argument such as - // `/workspace /Users/me/app` belongs to the command in front of it, so - // the inner slash must never win. var starts: [Int] = [] var index = caret - 1 while index >= 0 { @@ -62,13 +39,6 @@ struct ComposerSlashTrigger: Equatable { return nil } - /// What the slash panel filters on for this trigger, or `nil` when it stays closed. - /// - /// A command the user has typed past no longer produces a trigger at all, so besides the - /// trigger itself, three things close the panel: a settled `/skills` invocation, a settled - /// goal action, and a mid-sentence word no loaded skill matches. A Hermes chat's panel opens - /// at a host command's argument only while `hostCompletion` has suggestions for it (#1036); - /// mid-sentence it offers the host's skills, as on webui (#1679). func panelQuery( scope: SlashCommandScope, skills: [SkillSlashSuggestion], @@ -92,11 +62,6 @@ struct ComposerSlashTrigger: Equatable { return nil } - // Mid-sentence the panel's only content is skills, so once the catalog - // question is settled — a request has succeeded, even one that found - // no skills — and nothing matches the typed word, close rather than - // hold an empty box up. Before that, keep the panel open so its load - // task can fetch the list and judge the word against real data. if !startsDraft, hasLoadedSkills, SlashSkillFormatter.matching(parsed.commandName, in: skills).isEmpty { @@ -106,13 +71,6 @@ struct ComposerSlashTrigger: Equatable { return text } - /// What the draft and caret become when the user accepts `replacement`. - /// - /// Only the trigger's own range changes. When the completion wants a - /// trailing space and the draft already has one waiting there, the space is - /// dropped and the caret steps over the existing one instead, so accepting a - /// command mid-sentence leaves neither a double space nor a caret stranded in - /// front of one. A line break is not a separator, so it keeps the space. func applying(_ replacement: String, to draft: String) -> (draft: String, selection: NSRange) { let draft = draft as NSString let location = min(max(0, range.location), draft.length) @@ -134,9 +92,6 @@ struct ComposerSlashTrigger: Equatable { ) } - /// Whether only whitespace precedes `start`, matching the send path's gate: - /// `SlashCommandExecutor` trims the whole draft with - /// `.whitespacesAndNewlines` and requires a leading `/`. private static func isAtDraftStart(_ draft: NSString, before start: Int) -> Bool { var index = start - 1 while index >= 0 { @@ -146,19 +101,6 @@ struct ComposerSlashTrigger: Equatable { return true } - /// Whether `text` can still be a command being typed. - /// - /// One word is always a candidate. Past the first space, the word has to be - /// a command that takes a sub-argument, and only at the start of the draft - /// where that command could actually run — mid-sentence the panel offers - /// skills only, so the trigger ends with its word instead of chasing a - /// sub-argument through the rest of the sentence. Where the argument is one - /// of a fixed list the trigger ends as soon as the user types past it, so - /// prose such as "check the /tmp folder" or "use /reasoning high for this - /// task" does not hold an empty panel open for the rest of the sentence. - /// Where it is free-form — a workspace path, a personality name, a skill - /// query — the spaces are part of the value, so the trigger runs to the - /// caret. So does a host command's (#1036): the host says what it takes. private static func isTrigger(_ text: String, atDraftStart: Bool, scope: SlashCommandScope) -> Bool { let body = text.dropFirst() guard let space = body.firstIndex(where: { $0.isWhitespace }) else { return true } diff --git a/HermesMobile/Features/Chat/ComposerTextEditing.swift b/HermesMobile/Features/Chat/ComposerTextEditing.swift index 30fa160ca..f6a20dab5 100644 --- a/HermesMobile/Features/Chat/ComposerTextEditing.swift +++ b/HermesMobile/Features/Chat/ComposerTextEditing.swift @@ -1,46 +1,16 @@ import UIKit -/// Where the composer's caret is, and whose idea that was. -/// -/// The range is reported up on every edit and caret move, so the composer can -/// tell what the user is typing *at*. `revision` moves only when the composer -/// deliberately places the caret — accepting a slash completion is the one case -/// — so an update replaying an older value can never yank the caret back. struct ComposerSelection: Equatable { var range = NSRange(location: 0, length: 0) var revision = 0 - /// How many editor-to-composer publishes this value was built from. - /// - /// The editor bumps it every time it pushes an edit up. Because text and - /// caret are published together, it dates the draft as well, which lets the - /// bridge tell a binding that has caught up from one still carrying the - /// draft from before the user's last keystroke. var publishGeneration = 0 - /// A caret the composer is moving on purpose. func moved(to range: NSRange) -> ComposerSelection { ComposerSelection(range: range, revision: revision &+ 1, publishGeneration: publishGeneration) } } -/// When a bound draft may overwrite a live IME composition. enum ComposerMarkedText { - /// Whether `boundText` is a real replacement rather than an echo of what the - /// editor has already committed. - /// - /// While an IME composition is marked, assigning text commits it half-formed - /// and splits characters such as 자 into ㅈㅏ (#312). A parent that has - /// simply not seen the marked text yet is echoing the committed draft back, - /// which is not a change worth breaking a composition for. A deliberate - /// clear or replacement still is. - /// - /// Two questions decide it. Is this value the editor's own committed text - /// coming back — the comparison against the draft with the marked range - /// removed? And has the parent seen the composition at all — `isCurrent`, - /// from the publish generation the binding carries. They agree everywhere - /// but on an empty value, where a send that cleared a whole-draft - /// composition and a binding that predates that composition are the same - /// two strings, and only the generation can break the tie. static func isDeliberateReplacement( _ boundText: String, editorText: String, @@ -59,17 +29,10 @@ enum ComposerMarkedText { } } -/// One replacement that turns the editor's text into the text the composer wants. -/// -/// Applying it through `UITextView.replace(_:withText:)` keeps the change on the -/// editor's undo stack and leaves the rest of the draft untouched, neither of -/// which assigning `text` wholesale does. struct ComposerTextEdit: Equatable { - /// UTF-16 range to replace, in the editor's current text. let range: NSRange let replacement: String - /// The smallest edit from `current` to `target`, or `nil` when they match. static func between(current: String, target: String) -> ComposerTextEdit? { guard current != target else { return nil } @@ -88,8 +51,6 @@ struct ComposerTextEdit: Equatable { suffix += 1 } - // A range that cuts a surrogate pair in half has no `UITextRange`, so - // back the boundary off onto the character it belongs to. if prefix > 0, isTrailingSurrogate(at: prefix, in: current) || isTrailingSurrogate(at: prefix, in: target) { prefix -= 1 } @@ -110,8 +71,6 @@ struct ComposerTextEdit: Equatable { } extension UITextView { - /// The `UITextRange` for a UTF-16 range, or `nil` when it does not land on - /// positions this editor recognises. func textRange(from range: NSRange) -> UITextRange? { guard range.location >= 0, range.length >= 0, range.upperBound <= (text as NSString).length else { return nil diff --git a/HermesMobile/Features/Chat/ComposerVoiceInputController.swift b/HermesMobile/Features/Chat/ComposerVoiceInputController.swift index 8d40ce38a..744432677 100644 --- a/HermesMobile/Features/Chat/ComposerVoiceInputController.swift +++ b/HermesMobile/Features/Chat/ComposerVoiceInputController.swift @@ -6,9 +6,6 @@ import OSLog import Speech import UIKit -/// Uploads one finished dictation recording (its bytes and file name) to the server's -/// speech-to-text and returns the reply. A webui server's is `APIClient.dictationTranscriber`; -/// a Hermes chat's is `HermesTranscription.transcriber(for:)`, bound to its Profile (#1071). typealias ComposerTranscriber = @MainActor (Data, String) async throws -> TranscribeResponse @MainActor @@ -35,9 +32,7 @@ final class ComposerVoiceInputController { } private(set) var errorMessage: String? private(set) var liveTranscript = "" - /// When the current capture began, for the dictation row's timer. private(set) var captureStartedAt: Date? - /// Held apart from the controller so only the waveform redraws for each level. @ObservationIgnored let levelMeter = ComposerVoiceLevelMeter() private let speechRecognizerFactory: (Locale) -> (any ComposerSpeechRecognizing)? @@ -59,7 +54,6 @@ final class ComposerVoiceInputController { @ObservationIgnored private var transcriptionTask: Task? @ObservationIgnored private var toggleTask: Task? @ObservationIgnored private var meteringTask: Task? - /// The on-device tap's latest level. The tap runs on the audio thread. @ObservationIgnored private let onDeviceDecibels = OSAllocatedUnfairLock(initialState: nil) private var activeTranscriptionID: UUID? @ObservationIgnored private let recordingLease = ComposerDictationLease.live() @@ -74,7 +68,6 @@ final class ComposerVoiceInputController { private let mayRecord: @MainActor () -> Bool private let logger = Logger.hermesVoiceInput - /// The server's speech-to-text; nil when the server has none, which leaves only on-device. @ObservationIgnored var transcribe: ComposerTranscriber? @ObservationIgnored var providerPreference = ComposerSTTProviderPreference.defaultValue @@ -127,8 +120,6 @@ final class ComposerVoiceInputController { state == .requestingPermission } - /// Queue UI input under the same ownership as capture, so teardown can cancel - /// even a microphone tap whose task has not started executing yet. @discardableResult func scheduleToggle( draftState: @escaping () -> ComposerVoiceDraftState, @@ -143,8 +134,6 @@ final class ComposerVoiceInputController { return task } - /// `draftState` is read when capture starts and again before every write, so - /// the closure must return the composer's live values, not a captured copy. func toggle( draftState: @escaping () -> ComposerVoiceDraftState, updateDraft: @escaping (ComposerVoiceDraftUpdate) -> Void @@ -157,8 +146,6 @@ final class ComposerVoiceInputController { } } - /// Scene inactivity stops capture immediately. A server clip remains owned by this - /// composer until it returns unlocked, or explicit teardown discards it. func suspend() { toggleTask?.cancel() toggleTask = nil @@ -211,8 +198,6 @@ final class ComposerVoiceInputController { } } - /// The dictation row's cancel: drops the recording and takes back any words - /// already written, leaving the draft as it was before the mic was tapped. func cancel() { if let draftState, let updateDraft, let restored = draftUpdateSession.restoredDraft(current: draftState()) { updateDraft(restored) @@ -414,14 +399,6 @@ final class ComposerVoiceInputController { return String(localized: "On-device speech recognition is not available for the current locale.") } - // MARK: - Server STT - - // Mono AAC tuned for server speech-to-text (#1355). At 44.1 kHz a 32 kbps - // encode spreads its bits over a band speech models discard, and server STT - // dropped noticeably more words than on an Opus voice note of the same - // speech. 24 kHz keeps the speech band and 48 kbps there matched the voice - // note. ~22 MB/hour still lets recording run until the user stops it; past - // the upload ceiling (~55 minutes) the byte guard below takes over. static let serverRecordingSettings: [String: Any] = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: serverRecordingSampleRate, @@ -432,9 +409,6 @@ final class ComposerVoiceInputController { static let serverRecordingSampleRate = 24_000.0 static let serverRecordingBitrate = 48_000 static let serverRecordingFileExtension = "m4a" - // Leave 1 MiB below the server's configurable 20 MiB default for the - // multipart envelope. A lower custom limit still uses the existing fallback. - // A Hermes host takes up to 25 MiB of decoded audio (#1071). static let maximumServerRecordingUploadBytes = 19 * 1_024 * 1_024 static func serverRecordingFileSize(at url: URL) throws -> Int { @@ -445,7 +419,6 @@ final class ComposerVoiceInputController { return size } - /// Returns `nil` before reading an oversized recording into memory. static func loadServerRecordingForUpload( fileSize: Int, dataLoader: () throws -> Data @@ -555,9 +528,6 @@ final class ComposerVoiceInputController { } let transcript = response.transcript?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - // An empty transcript the transcriber reports as a success is silence: a Hermes - // host's `{ok: true, transcript: ""}` (#1071). Nothing to insert, nothing failed. - // webui's transcriber drops `ok` from an empty reply, so webui still fails it. guard !transcript.isEmpty || (response.ok == true && response.error == nil) else { await fallbackFromServerFailure( recordingURL: recordingURL, @@ -801,9 +771,6 @@ final class ComposerVoiceInputController { } } - /// Writes one result into the span this dictation owns. Returns false when the - /// draft changed underneath it: the draft and caret stay as they are, and no - /// later result is written. @discardableResult private func writeTranscript(_ transcript: String) -> Bool { guard let draftState, let updateDraft else { return true } @@ -823,9 +790,6 @@ final class ComposerVoiceInputController { updateDraft = nil } - // MARK: - Metering - - /// Samples the mic for the waveform, only while a capture runs. private func startMetering() { meteringTask?.cancel() levelMeter.reset() @@ -914,9 +878,6 @@ final class ComposerVoiceInputController { } } - /// The on-device recognizer for the first dictation locale candidate that - /// has a model, cached for the controller's lifetime. Live dictation and - /// the server-failure file fallback both record through this pick. private func onDeviceSpeechRecognizerForRecording() -> (any ComposerSpeechRecognizing)? { if let speechRecognizer { return speechRecognizer.supportsOnDeviceRecognition ? speechRecognizer : nil @@ -1059,33 +1020,20 @@ enum VoiceInputFailureLogCategory: String { case audioStartup } -/// Chooses the dictation language. `Locale.current` (app language plus device -/// region) stays first so users whose dictation already works keep the same -/// recognizer; the user's preferred languages and `en-US` cover regions whose -/// pairing has no on-device model, such as `en_PK`. enum ComposerSpeechLocalePolicy { static let preferredLanguageLimit = 3 static let lastResortIdentifier = "en-US" - /// `current`, then the first few distinct preferred languages, then `en-US`, - /// deduplicated by normalized identifier. Duplicates of `current` (usually - /// the first preferred language) do not use up a preferred-language slot. static func candidates(current: Locale, preferredLanguages: [String]) -> [Locale] { let leading = distinct([current.identifier] + preferredLanguages).prefix(1 + preferredLanguageLimit) return distinct(leading + [lastResortIdentifier]).map(Locale.init(identifier:)) } - /// Walks `candidates` in order and returns the first `recognizer` result. - /// `recognizer` is called only for candidates listed in `supportedLocales`, - /// with the supported locale itself, and returns nil when that locale has - /// no on-device model. An exact identifier match wins over a language plus - /// region match, so `hi-IN` never resolves to `hi-IN-translit`. static func firstAvailable( in candidates: [Locale], supportedLocales: Set, recognizer: (Locale) -> Recognizer? ) -> Recognizer? { - // Sorted so collisions resolve the same way on every launch. let supported = supportedLocales.sorted { $0.identifier < $1.identifier } let byExactIdentifier = Dictionary( supported.map { (exactIdentifier($0.identifier), $0) }, @@ -1105,10 +1053,6 @@ enum ComposerSpeechLocalePolicy { return nil } - /// Language plus region, lowercased: `en_US`, `en-US`, and `en_US@rg=pkzzzz` - /// all normalize to `en-us`, and `zh-Hans-CN` to `zh-cn`, because - /// `SFSpeechRecognizer.supportedLocales()` lists Chinese without a script. - /// An identifier without a region (`en`) keeps its exact form. static func normalizedIdentifier(_ identifier: String) -> String { let language = Locale(identifier: identifier).language if let code = language.languageCode?.identifier, let region = language.region?.identifier { @@ -1117,7 +1061,6 @@ enum ComposerSpeechLocalePolicy { return exactIdentifier(identifier) } - /// The identifier without any `@…` keywords, with `-` separators, lowercased. private static func exactIdentifier(_ identifier: String) -> String { let base = identifier.split(separator: "@", maxSplits: 1).first.map(String.init) ?? identifier return base.replacingOccurrences(of: "_", with: "-").lowercased() @@ -1177,22 +1120,17 @@ enum ComposerVoiceInputPreflight { } } -/// The draft as the composer holds it right now. struct ComposerVoiceDraftState { let text: String let selection: ComposerSelection } -/// One accepted dictation write: the new draft and where the caret goes in it. struct ComposerVoiceDraftUpdate: Equatable { let text: String let caret: NSRange } enum ComposerVoiceDraftComposer { - /// Replaces `range` with the trimmed transcript, leaving everything outside it - /// alone, and puts the caret after what it wrote. Nil when `range` is out of - /// bounds or splits a composed character. static func replacing(_ range: NSRange, in text: String, with transcript: String) -> ComposerVoiceDraftUpdate? { let draft = text as NSString guard range.location >= 0, range.length >= 0, range.upperBound <= draft.length, @@ -1215,13 +1153,9 @@ enum ComposerVoiceDraftComposer { ) } - /// A bounded spacing policy, not script detection: word-like text gets a space - /// from its neighbour, except beside Chinese or Japanese text, after opening - /// punctuation and before closing punctuation. No transcript locale is assumed. private static func needsSpace(between left: Character, and right: Character) -> Bool { guard !isUnspacedScript(left), !isUnspacedScript(right) else { return false } let endsWord = left.isLetter || left.isNumber || left.isSymbol || ".,;:!?)]}\u{201D}\u{2019}\u{2026}".contains(left) - // `/`, `@` and `#` start the chips and references a draft can hold. let startsWord = right.isLetter || right.isNumber || right.isSymbol || "/@#([{\u{201C}\u{2018}".contains(right) return endsWord && startsWord } @@ -1229,13 +1163,13 @@ enum ComposerVoiceDraftComposer { private static func isUnspacedScript(_ character: Character) -> Bool { guard let scalar = character.unicodeScalars.first else { return false } switch scalar.value { - case 0x2E80...0x303F, // CJK radicals, symbols and punctuation - 0x3040...0x30FF, // Hiragana, Katakana - 0x3400...0x4DBF, // CJK extension A - 0x4E00...0x9FFF, // CJK unified ideographs - 0xF900...0xFAFF, // CJK compatibility ideographs - 0xFF00...0xFFEF, // Halfwidth and fullwidth forms - 0x20000...0x3FFFF: // CJK supplementary planes + case 0x2E80...0x303F, + 0x3040...0x30FF, + 0x3400...0x4DBF, + 0x4E00...0x9FFF, + 0xF900...0xFAFF, + 0xFF00...0xFFEF, + 0x20000...0x3FFFF: return true default: return false @@ -1251,13 +1185,6 @@ enum ComposerVoiceDraftComposer { } } -/// The span of the draft one dictation owns. -/// -/// Every result replaces that span rather than rebuilding the draft from a base -/// string, and only while the draft is still exactly what this session last left. -/// Voice writes never publish a generation, so a user edit, including an edit -/// undone back to identical text, is what moves it. A write from anywhere else -/// shows up in the text. A caret that merely moved does not stop dictation. struct ComposerVoiceDraftUpdateSession { private struct Ownership { let original: ComposerVoiceDraftUpdate @@ -1281,8 +1208,6 @@ struct ComposerVoiceDraftUpdateSession { ownership = nil } - /// The draft with `transcript` in the owned span, or nil when the draft is no - /// longer this session's to write. mutating func update(for transcript: String, current: ComposerVoiceDraftState) -> ComposerVoiceDraftUpdate? { guard var ownership, Self.isUnchanged(current, since: ownership), let update = ComposerVoiceDraftComposer.replacing(ownership.range, in: current.text, with: transcript) @@ -1294,8 +1219,6 @@ struct ComposerVoiceDraftUpdateSession { return update } - /// The draft from before this session's first write, or nil when nothing was - /// written or the draft has since moved on. func restoredDraft(current: ComposerVoiceDraftState) -> ComposerVoiceDraftUpdate? { guard let ownership, Self.isUnchanged(current, since: ownership), current.text != ownership.original.text @@ -1309,7 +1232,6 @@ struct ComposerVoiceDraftUpdateSession { } } -/// The dictation row's waveform: recent mic levels, newest last. @MainActor @Observable final class ComposerVoiceLevelMeter { @@ -1328,7 +1250,6 @@ final class ComposerVoiceLevelMeter { levels.append(Self.level(decibels: decibels)) } - /// Maps decibels to 0...1, on a square root so quiet speech still shows. private static func level(decibels: Float?) -> Float { guard let decibels, decibels.isFinite, decibels > noiseFloorDecibels else { return 0 } guard decibels < 0 else { return 1 } @@ -1336,7 +1257,6 @@ final class ComposerVoiceLevelMeter { return ((pow(10, decibels / 20) - floor) / (1 - floor)).squareRoot() } - /// One audio buffer's level. Runs on the audio thread. nonisolated static func decibels(of buffer: AVAudioPCMBuffer) -> Float? { guard let samples = buffer.floatChannelData?[0], buffer.frameLength > 0 else { return nil } let count = Int(buffer.frameLength) @@ -1354,9 +1274,6 @@ private extension Logger { ) } -/// A recording-only lease. Permission prompts, deferred clips and transcription never -/// hold it. The UIKit adapter below is separate so restoration can be tested without -/// changing the test host's orientation or idle timer. @MainActor final class ComposerDictationLease { private let readIdle: () -> Bool @@ -1421,8 +1338,6 @@ final class ComposerDictationLease { scene.session.persistentIdentifier == lockedSceneID, let lockedOrientation { return lockedOrientation } - // Matches Info.plist's normal iPhone/iPad policy. UIKit still intersects - // this with the presented controller's supported orientations. return window?.traitCollection.userInterfaceIdiom == .pad ? .all : .allButUpsideDown } @@ -1433,8 +1348,6 @@ final class ComposerDictationLease { } } -/// The part of `SFSpeechRecognizer` dictation uses, so tests can stand in a -/// recognizer without the simulator's speech service. protocol ComposerSpeechRecognizing: AnyObject { var supportsOnDeviceRecognition: Bool { get } func recognitionTask( @@ -1445,12 +1358,9 @@ protocol ComposerSpeechRecognizing: AnyObject { extension SFSpeechRecognizer: ComposerSpeechRecognizing {} -/// Owns the physical server-STT recorder and its audio session. The controller owns -/// the returned file, including retention across inactivity and eventual deletion. @MainActor protocol ComposerServerRecording: AnyObject { var onFinish: (() -> Void)? { get set } - /// The mic's current level, or nil when the recorder has none to report. var decibels: Float? { get } func start() throws -> URL func stop() diff --git a/HermesMobile/Features/Chat/ComposerVoiceNoteRecorder.swift b/HermesMobile/Features/Chat/ComposerVoiceNoteRecorder.swift index 199debf18..ce8d8cfb3 100644 --- a/HermesMobile/Features/Chat/ComposerVoiceNoteRecorder.swift +++ b/HermesMobile/Features/Chat/ComposerVoiceNoteRecorder.swift @@ -4,11 +4,6 @@ import Foundation import Observation import OSLog -/// Records a short voice note to a temporary `.m4a`/AAC file with `AVAudioRecorder`, -/// distinct from `ComposerVoiceInputController` (on-device dictation). The composer -/// holds one of these as `@State`: hold the mic to `begin()`, release to `finish()`, -/// slide up to `cancel()`. Drives an elapsed-time ticker and flips the shared -/// `ComposerAudioCaptureState` so the inline audio player won't fight for the session. @MainActor @Observable final class ComposerVoiceNoteRecorder { @@ -24,10 +19,7 @@ final class ComposerVoiceNoteRecorder { let duration: TimeInterval } - /// Hard cap on a single clip. AAC mono at ~32 kbps stays far under the 20 MB - /// upload limit even at five minutes (~1.2 MB), so this bounds UX, not size. static let maximumDuration: TimeInterval = 5 * 60 - /// Clips shorter than this are treated as accidental taps and discarded. static let minimumDuration: TimeInterval = 0.5 private(set) var state: State = .idle @@ -63,10 +55,6 @@ final class ComposerVoiceNoteRecorder { AVEncoderAudioQualityKey: AVAudioQuality.medium.rawValue ] - // MARK: - Lifecycle - - /// Requests mic permission (if needed), configures the audio session, and - /// starts recording to a temporary `.m4a` file. No-op if already active. func begin() async { guard state == .idle else { return } errorMessage = nil @@ -74,8 +62,6 @@ final class ComposerVoiceNoteRecorder { state = .requestingPermission let granted = await permissionRequester() - // The state can change while we await the system prompt (e.g. the view - // disappeared and called `cancel()`); bail rather than starting late. guard state == .requestingPermission else { return } guard granted else { fail(String(localized: "Microphone access is disabled. Enable it in Settings to record a voice note.")) @@ -92,8 +78,6 @@ final class ComposerVoiceNoteRecorder { } } - /// Stops recording and returns the finished clip, or nil if it was too short, - /// failed to read, or wasn't recording. Always restores the audio session. func finish() -> RecordedVoiceNote? { guard state == .recording, let recorder, let fileURL else { cancel() @@ -123,7 +107,6 @@ final class ComposerVoiceNoteRecorder { return RecordedVoiceNote(data: data, filename: filename, duration: duration) } - /// Stops and discards the recording without producing a clip. func cancel() { stopRecorder() discardFile() @@ -131,8 +114,6 @@ final class ComposerVoiceNoteRecorder { resetState() } - // MARK: - Recording internals - private func startRecording() throws { let session = AVAudioSession.sharedInstance() try session.setCategory(.playAndRecord, mode: .default, options: [.allowBluetooth]) @@ -183,11 +164,8 @@ final class ComposerVoiceNoteRecorder { logger.error("Voice note recording failed") } - // MARK: - Ticker - private func startTicker() { stopTicker() - // `.common` so the timer keeps firing while the transcript scrolls. let timer = Timer(timeInterval: 0.1, repeats: true) { [weak self] _ in Task { @MainActor in self?.tick() } } @@ -225,10 +203,6 @@ enum ComposerVoiceNoteRecorderError: LocalizedError { } } -/// Generates collision-resistant `.m4a` names for recorded voice notes. The -/// 8-char suffix mirrors the attachment coordinator's uniquing so two quick notes -/// don't clash on upload, and the `.m4a` extension makes the inline player treat -/// the clip as audio even when the server reports a generic MIME type. enum VoiceNoteFilename { static func generate(uuid: UUID = UUID()) -> String { let suffix = uuid.uuidString.prefix(8).lowercased() @@ -241,19 +215,10 @@ enum VoiceNoteFilename { } } -/// Pure decision helpers for the hold-to-talk mic gesture, kept out of the view -/// so the thresholds and the cancel logic are unit-testable. enum ComposerVoiceNoteGesture { - /// A press must be held at least this long before it records, so a quick tap - /// still routes to dictation. Matches `LongPressGesture(minimumDuration:)`. - /// Set to the system long-press feel (0.5s) so a deliberate tap — which can - /// linger ~0.3s on screen — isn't mistaken for a hold. static let holdActivationDelay: TimeInterval = 0.5 - /// Sliding the finger up past this many points arms cancel-on-release. static let cancelTranslationThreshold: CGFloat = 80 - /// Dragging up yields a negative height; cancel once it passes the threshold. - /// Sliding down (positive height) never cancels. static func isCancelArmed(dragTranslationHeight: CGFloat) -> Bool { dragTranslationHeight <= -cancelTranslationThreshold } diff --git a/HermesMobile/Features/Chat/CompressionAnchorResolver.swift b/HermesMobile/Features/Chat/CompressionAnchorResolver.swift index 6a3127f07..9c078c7b8 100644 --- a/HermesMobile/Features/Chat/CompressionAnchorResolver.swift +++ b/HermesMobile/Features/Chat/CompressionAnchorResolver.swift @@ -1,7 +1,5 @@ import Foundation -/// Session-level compaction anchor metadata carried by `SessionDetail` -/// (`compression_anchor_*` fields in the `/api/session` payload). struct CompressionAnchorMetadata: Equatable { let visibleIdx: Int? let messageKey: CompressionAnchorMessageKey? @@ -28,18 +26,10 @@ struct CompressionAnchorMetadata: Equatable { } } -/// Resolves the synthesized "Context compaction · Reference only" card from -/// session compaction metadata, mirroring the web UI's settled-reference logic -/// (`_latestCompressionReferenceMessage`, `_shouldShowSettledCompressionReference`, -/// `_compressionMessageAnchorKey`, and `_compressionAnchorIndex` in `ui.js`). enum CompressionAnchorResolver { struct Resolution: Equatable { enum Placement: Equatable { - /// Render the card directly after the loaded message at this raw - /// index into the loaded messages array. case afterLoadedMessageIndex(Int) - /// Render the card above the loaded transcript: the anchor predates - /// the currently loaded tail window, or only a summary resolved. case top } @@ -70,13 +60,6 @@ enum CompressionAnchorResolver { } if let visibleIdx = metadata.visibleIdx, !candidateIndices.isEmpty { - // The server index counts visible messages from the absolute start - // of the session, while the app holds a `msg_limit` tail window. - // Shifting by the raw `messagesOffset` over-corrects (raw count ≥ - // visible count), which only biases unresolved anchors toward the - // top clamp — the degraded behavior the issue asks for when the - // anchor predates the loaded tail. The key match above remains the - // precise path. let localIdx = visibleIdx - max(0, messagesOffset) guard localIdx >= 0 else { return Resolution(referenceText: referenceText, placement: .top) @@ -92,11 +75,6 @@ enum CompressionAnchorResolver { return Resolution(referenceText: referenceText, placement: .top) } - // MARK: - Reference text - - /// Mirrors `_latestCompressionReferenceMessage`: prefer the latest literal - /// compaction-marker message (matching summary containment when a summary - /// exists), falling back to the summary itself. private static func referenceText(in messages: [ChatMessage], summary: String) -> String { let normalizedSummary = normalizedWhitespace(summary) @@ -112,8 +90,6 @@ enum CompressionAnchorResolver { return summary } - /// Mirrors `_shouldShowSettledCompressionReference`: non-empty reference - /// text that is not itself a literal compaction marker. private static func shouldShowReference(_ referenceText: String) -> Bool { let trimmed = referenceText.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { return false } @@ -121,8 +97,6 @@ enum CompressionAnchorResolver { return !ChatMarkerMessageClassifier.isContextCompactionText(trimmed) } - // MARK: - Anchor matching - private struct CandidateKey { let role: String let ts: Double? @@ -130,10 +104,6 @@ enum CompressionAnchorResolver { let attachments: Int } - /// Loaded indices of messages eligible to anchor the card. Approximates the - /// server's `visible_messages_for_anchor` list (which both the anchor key - /// and `compression_anchor_visible_idx` are computed against): non-tool, - /// non-marker messages that carry text, attachments, or assistant activity. private static func anchorCandidateIndices(in messages: [ChatMessage]) -> [Int] { messages.indices.filter { index in let message = messages[index] @@ -152,7 +122,6 @@ enum CompressionAnchorResolver { } } - /// Mirrors `_compressionMessageAnchorKey`. private static func candidateKey(for message: ChatMessage) -> CandidateKey? { guard let role = message.role, !role.isEmpty, role != "tool" else { return nil } @@ -166,9 +135,6 @@ enum CompressionAnchorResolver { return CandidateKey(role: role, ts: ts, text: normalizedText, attachments: attachments) } - /// Mirrors `_compressionAnchorIndex`'s reverse scan: role and normalized - /// text must match exactly, attachment counts must match, and timestamps - /// are compared only when both sides have one. private static func latestMatch( of anchorKey: CompressionAnchorMessageKey, in messages: [ChatMessage], @@ -190,8 +156,6 @@ enum CompressionAnchorResolver { return nil } - /// First 160 characters of whitespace-normalized text, matching the server's - /// `" ".join(text.split()).strip()[:160]` key construction. static func normalizedAnchorText(_ text: String) -> String { String(normalizedWhitespace(text).prefix(160)) } diff --git a/HermesMobile/Features/Chat/CustomAttachmentPicker.swift b/HermesMobile/Features/Chat/CustomAttachmentPicker.swift index 47ff704ce..00b1059c6 100644 --- a/HermesMobile/Features/Chat/CustomAttachmentPicker.swift +++ b/HermesMobile/Features/Chat/CustomAttachmentPicker.swift @@ -381,10 +381,6 @@ private struct HermexAttachmentPickerLayout { } } -/// Hosts the picker inside the app's existing window instead of presenting a -/// new controller. Its bottom follows the keyboard, so the composer remains -/// first responder and the picker always occupies the space above it, in the -/// composer's column. enum HermexAttachmentPickerPresentation { static let overlayHostAccessibilityIdentifier = "HermexAttachmentPickerOverlay" } @@ -414,9 +410,6 @@ struct HermexKeyboardRetainingOverlay: UIViewControllerRepresenta context.coordinator.update( isPresented: isPresented, anchor: controller, - // This sibling host does not inherit SwiftUI's scene environment. - // Forward it so camera/media work starts and stops with its owner, - // and set the root font it would otherwise miss. overlay: AnyView(overlay().environment(\.scenePhase, scenePhase).appRootFont()) ) } @@ -462,8 +455,6 @@ struct HermexKeyboardRetainingOverlay: UIViewControllerRepresenta attach(to: root, anchor: anchor) } - /// Spans the owner's column, so beside a sidebar the card stays by the composer that opened - /// it, and follows the column as the sidebar moves or the device folds. private func attach(to root: UIViewController, anchor: UIViewController) { guard let container = root.view.superview ?? root.view.window else { return } @@ -473,11 +464,8 @@ struct HermexKeyboardRetainingOverlay: UIViewControllerRepresenta host.view.accessibilityViewIsModal = true host.view.accessibilityIdentifier = HermexAttachmentPickerPresentation.overlayHostAccessibilityIdentifier - // UIHostingController's root view does not support UIKit subviews. - // Install the overlay beside it in their common container instead. container.addSubview(host.view) root.view.keyboardLayoutGuide.followsUndockedKeyboard = true - // Sidebars and vertical bars cover the column, so its safe area marks what shows. let column = (anchor.parent ?? root).view.safeAreaLayoutGuide NSLayoutConstraint.activate([ host.view.topAnchor.constraint(equalTo: root.view.topAnchor), @@ -501,8 +489,6 @@ struct HermexKeyboardRetainingOverlay: UIViewControllerRepresenta } } -/// The floating card's material and shadow, shared by the attachment picker -/// and the send-choice card so the two read as one control. struct HermexAttachmentPanelSurface: ViewModifier { let reduceTransparency: Bool @@ -536,7 +522,6 @@ struct HermexAttachmentPickerView: View { let imageCapacity: Int let onChooseFiles: () -> Void - /// Offers Voice note, which starts a recording the composer's bar then stops or cancels. var onRecordVoiceNote: (() -> Void)? = nil let onAdd: ([HermexPickedMedia]) -> Void let onDismiss: () -> Void @@ -1012,8 +997,6 @@ private struct HermexPhotoAssetThumbnail: View { } } -/// One choice in a floating card: a circled icon and a title. Shared by the -/// attachment picker and the send-choice card. struct HermexAttachmentMenuRow: View { let title: Text let systemImage: String diff --git a/HermesMobile/Features/Chat/DisplayMathView.swift b/HermesMobile/Features/Chat/DisplayMathView.swift index d105b51e8..d8e633709 100644 --- a/HermesMobile/Features/Chat/DisplayMathView.swift +++ b/HermesMobile/Features/Chat/DisplayMathView.swift @@ -3,14 +3,6 @@ import SwiftMath import SwiftUI import UIKit -/// Renders block/display LaTeX (`$$…$$`, `\[…\]`) with the SwiftMath TeX -/// layout engine when the expression parses, and falls back to the Unicode -/// approximation (`MarkdownMathFormatter`) for anything SwiftMath can't parse. -/// -/// Tolerant by design: an unparseable or partial expression degrades to the -/// previous Unicode rendering instead of crashing or showing SwiftMath's -/// inline red error. The Unicode approximation is also used as the VoiceOver -/// label on both paths, so the drawn math stays accessible. struct DisplayMathView: View { let latex: String @@ -37,13 +29,9 @@ struct DisplayMathView: View { .accessibilityElement(children: .ignore) .accessibilityLabel(approximation) .padding(.vertical, 2) - // Math/LaTeX is read left-to-right regardless of the chat direction (#259); - // mirroring it would reverse equations inside an RTL message. .forcedLeftToRight() } - /// The pre-SwiftMath Unicode/serif rendering, kept verbatim as the graceful - /// fallback for expressions SwiftMath cannot parse. private var fallback: some View { ScrollView(.horizontal, showsIndicators: false) { Text(approximation) @@ -61,21 +49,12 @@ struct DisplayMathView: View { } enum MathLaTeX { - /// Renderability is a pure, deterministic function of the trimmed LaTeX - /// string, so we memoize it. `DisplayMathView`/`MathFenceOrCodeBlock` - /// re-check on every layout pass, and markdown-ui rebuilds code blocks on - /// each streaming chunk — without this cache the same expression is parsed - /// many times over. `NSCache` is thread-safe and self-evicts under memory - /// pressure. nonisolated(unsafe) private static let renderableCache: NSCache = { let cache = NSCache() cache.countLimit = 256 return cache }() - /// True when SwiftMath can parse `latex` into a math list without error. - /// Used to choose the SwiftMath path vs. the Unicode fallback before the - /// `MTMathUILabel` is ever mounted, so failures never reach the screen. static func isRenderable(_ latex: String) -> Bool { let trimmed = latex.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { return false } @@ -93,15 +72,9 @@ enum MathLaTeX { } } -/// Fenced-code languages that should render as display math rather than source -/// code (e.g. ```math, ```latex, ```tex). Models sometimes wrap a standalone -/// equation in a math fence instead of `$$…$$`; those reach the renderer as a -/// code block, so we re-route the math ones (parity-plus over Hermes WebUI, -/// which shows these as code). enum MathFenceLanguage { static let languages: Set = ["math", "latex", "tex"] - /// True when a fenced code block's info string names a math language. static func matches(_ language: String?) -> Bool { guard let normalized = MarkdownHighlightPolicy.normalizedLanguage(from: language) else { return false @@ -110,9 +83,6 @@ enum MathFenceLanguage { } } -/// Wraps SwiftMath's `MTMathUILabel` (a UIKit view) for use in SwiftUI. -/// Sized to its intrinsic content so long equations scroll horizontally in the -/// surrounding `ScrollView` instead of clipping. private struct SwiftMathLabelView: UIViewRepresentable { let latex: String let fontSize: CGFloat @@ -123,8 +93,6 @@ private struct SwiftMathLabelView: UIViewRepresentable { let label = MTMathUILabel() label.labelMode = .display label.textAlignment = .left - // We pick the fallback view for unparseable input, so the inline red - // error should never appear. label.displayErrorInline = false label.contentInsets = .zero configure(label) @@ -143,8 +111,6 @@ private struct SwiftMathLabelView: UIViewRepresentable { uiView.intrinsicContentSize } - /// Applies the current inputs, skipping no-op writes so repeated SwiftUI - /// updates (e.g. during streaming) don't force needless re-typesetting. private func configure(_ label: MTMathUILabel) { if label.fontSize != fontSize { label.fontSize = fontSize @@ -160,15 +126,11 @@ private struct SwiftMathLabelView: UIViewRepresentable { } } - /// Resolves the dynamic label color against the SwiftUI color scheme so the - /// Core Graphics-drawn math matches the surrounding text in light and dark. private static func resolvedTextColor(for colorScheme: ColorScheme, appearance: AppAppearance) -> MTColor { appearance.theme(for: colorScheme).resolvedText(isDark: colorScheme == .dark) } } -// MarkdownUI draws inline images as Text attachments. SwiftMath supplies their -// intrinsic size and baseline; paragraphs and lists retain their native flow. struct InlineMathImageProvider: InlineImageProvider { let fontSize: CGFloat let colorScheme: ColorScheme @@ -204,12 +166,8 @@ enum InlineMathSource { } -/// Serializes SwiftMath work off the main actor. One bounded cache serves every -/// Markdown consumer; keys include all raster inputs, never a streaming reply. actor InlineMathImageCache { static let shared = InlineMathImageCache() - // NSCache is thread-safe. Warm reads must not hop through the actor and - // publish another view update on each token; only cold rendering is isolated. nonisolated(unsafe) private let storage = NSCache() private(set) var renderCount = 0 @@ -244,7 +202,6 @@ actor InlineMathImageCache { } image = scaled.withBaselineOffset(fromBottom: layout.descent) } else { - // Unknown commands remain readable source, never SwiftMath's error UI. let source = "$" + latex + "$" as NSString let font = UIFont.systemFont(ofSize: fontSize) let attributes: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: color] @@ -272,9 +229,6 @@ extension EnvironmentValues { } } -/// Adapts only math-bearing inline leaves. MarkdownUI still owns block layout, -/// list identity and every math-free leaf. Foundation retains nested inline -/// styles and links while SwiftUI Text attachments share the prose baseline. struct MathMarkdownLabel: View { let content: MarkdownContent let label: Label @@ -320,7 +274,6 @@ struct MathInlineText: View { @Environment(\.displayScale) private var displayScale @State private var loaded: (style: InlineMathImageStyle, images: [URL: Image])? - /// Matches the surrounding Markdown prose, which `Theme.chat` sizes the same way. private var fontSize: CGFloat { ChatTypography(dynamicTypeSize: dynamicTypeSize).bodySize } private var request: InlineMathTextRequest { @@ -387,7 +340,6 @@ struct InlineMathTextRequest: Equatable { InlineMathImageStyle(fontSize: fontSize, dark: dark, theme: theme, scale: scale, tintImages: tintImages) } - /// Token-only appends must not cancel an unchanged image download. func imageLoadIdentity() throws -> InlineMathImageLoadIdentity { let attributed = try parsed() var seen: Set = [] @@ -398,8 +350,6 @@ struct InlineMathTextRequest: Equatable { return InlineMathImageLoadIdentity(style: imageStyle, sources: sources) } - /// The usual streaming path: source changes, but every completed expression - /// is already cached. Compose the new Text without async work or state writes. func cachedResult(images suppliedImages: [URL: Image] = [:]) throws -> InlineMathTextResult? { let attributed = try parsed() var images = suppliedImages @@ -414,7 +364,6 @@ struct InlineMathTextRequest: Equatable { return compose(attributed, images: images) } - /// Always compose current prose, retaining any already available attachments. func placeholder(images suppliedImages: [URL: Image] = [:]) throws -> InlineMathTextResult { let attributed = try parsed() var images = suppliedImages @@ -427,8 +376,6 @@ struct InlineMathTextRequest: Equatable { return compose(attributed, images: images) } - /// Retry missing assets without refetching successes. The owning view task - /// cancels both provider work and backoff when its assets change or it leaves. @MainActor func renderWithRetries( provider: (any InlineImageProvider)? = nil, @@ -464,8 +411,6 @@ struct InlineMathTextRequest: Equatable { } catch is CancellationError { throw CancellationError() } catch { - // A failed ordinary image must not remove the sentence or equations. - // Its alt text remains the fallback, as on the normal Markdown path. } } try Task.checkCancellation() @@ -473,12 +418,10 @@ struct InlineMathTextRequest: Equatable { } func parsed() throws -> AttributedString { - // Foundation drops image attributes inside links. Recover image attributes - // from the parser's source spans without parsing Markdown delimiters here. var previous: UInt8 = 0 let mayContainLink = markdown.utf8.contains { byte in defer { previous = byte } - return byte == 0x5B && previous != 0x21 // An opening bracket outside image syntax. + return byte == 0x5B && previous != 0x21 } guard mayContainLink else { return try AttributedString(markdown: markdown, options: .init(interpretedSyntax: .full)) @@ -507,7 +450,6 @@ struct InlineMathTextRequest: Equatable { } private func compose(_ attributed: AttributedString, images: [URL: Image]) -> InlineMathTextResult { - // Prose runs share one `Text`: a `+` per run nests as deep as the paragraph is long. var text = Text("") var prose = AttributedString() var selectable = "" @@ -518,8 +460,6 @@ struct InlineMathTextRequest: Equatable { let alt = InlineMathSource.latex(from: url) ?? String(attributed[run.range].characters) let attachment: Text if let link = run.link { - // SwiftUI drops links on interpolated image attachments. - // Keep the destination usable with readable source/alt text. var linked = AttributedString(alt) linked.link = link attachment = Text(linked) diff --git a/HermesMobile/Features/Chat/FilePathAutocompleteView.swift b/HermesMobile/Features/Chat/FilePathAutocompleteView.swift index 8e42a6210..33b26da5b 100644 --- a/HermesMobile/Features/Chat/FilePathAutocompleteView.swift +++ b/HermesMobile/Features/Chat/FilePathAutocompleteView.swift @@ -1,19 +1,11 @@ import SwiftUI -/// The `@` panel: the workspace files and folders that match the path being -/// typed, on the same glass as the `/` panel so the two read as one surface. struct FilePathAutocompleteView: View { - // Row height tracks Dynamic Type so the panel is never taller or shorter - // than the rows it actually draws. @ScaledMetric(relativeTo: .subheadline) private var rowHeight: CGFloat = 48 @ScaledMetric(relativeTo: .subheadline) private var emptyPanelHeight: CGFloat = 64 - /// The path typed after the `@`, without it. let query: String - /// Owned by the composer, so its directory listings outlive one open panel. let search: ComposerFilePathSearch - /// Answers one query with rows. Sessions lists the workspace folder the - /// query names; Bot Chats complete the word through `complete.path`. let load: (String) async -> Void let onSelect: (ComposerFilePathSearch.Match) -> Void @@ -48,14 +40,11 @@ struct FilePathAutocompleteView: View { } } - /// What one load answers: the query, in the folder a reloading reset last moved the search to. private struct LoadKey: Equatable { let query: String let scope: Int } - /// A listing that failed reads as "nothing matched": the panel is a - /// shortcut past typing the path, never the only way to name a file. @ViewBuilder private var emptyText: some View { if search.isLoading { @@ -71,10 +60,6 @@ struct FilePathAutocompleteView: View { } } -/// One file or folder row: the entry's own glyph, its name, and the folder it -/// sits in. A folder ends in a chevron, because picking one goes deeper rather -/// than finishing the reference. The Sessions panel and the Bot `@` panel draw -/// the same row. struct FilePathRow: View { let match: ComposerFilePathSearch.Match let onSelect: (ComposerFilePathSearch.Match) -> Void @@ -121,8 +106,6 @@ struct FilePathRow: View { .accessibilityAddTraits(.isButton) } - /// The same glyphs the file tree draws: a quiet grey folder, or the file's - /// own type icon. @ViewBuilder private func icon(for match: ComposerFilePathSearch.Match) -> some View { if match.isDirectory { diff --git a/HermesMobile/Features/Chat/FilePathSearch.swift b/HermesMobile/Features/Chat/FilePathSearch.swift index 5b139ebe7..89d132bde 100644 --- a/HermesMobile/Features/Chat/FilePathSearch.swift +++ b/HermesMobile/Features/Chat/FilePathSearch.swift @@ -1,27 +1,12 @@ import Foundation -/// The workspace files and folders the composer's `@` panel offers for one query. -/// -/// For a webui session the query is a path being typed, so exactly one folder has -/// to be listed: the one the query names. `src/Ch` lists `src` and ranks its -/// entries against `Ch`; `Ch` ranks the workspace root's own entries. Nothing -/// recurses, so a large workspace costs the same as a small one. A Hermes host -/// searches every folder itself (`search(_:load:)`). -/// -/// Listings are cached for the composer's lifetime, so walking back up a path -/// the user is retyping costs no requests at all. The cache is dropped when the -/// session changes, because a path is only meaningful inside the workspace it -/// came from. @MainActor @Observable final class ComposerFilePathSearch { - /// One row: the path that gets inserted, plus what the row draws. struct Match: Identifiable, Equatable { var id: String { path } - /// Workspace-relative, exactly as the server spelled it. let path: String let name: String - /// The folder the entry sits in, empty at the workspace root. let parentPath: String let isDirectory: Bool @@ -41,7 +26,6 @@ final class ComposerFilePathSearch { ) } - /// The row's folder, spelled the way the panel draws it: empty at the root. static func parentPath(of path: String) -> String { let parent = FileTree.parentPath(of: path) return parent == FileTree.rootPath ? "" : parent @@ -50,32 +34,15 @@ final class ComposerFilePathSearch { private(set) var matches: [Match] = [] private(set) var isLoading = false - /// Bumped by `reset(reloadingOpenQuery: true)`. The panel loads again on it, so a query - /// left open while the workspace moved asks the new one rather than showing no rows. private(set) var scopeRevision = 0 - /// Directory path → its entries. A composer is short-lived next to a - /// workspace, and the worst a stale row can do is send the viewer after a - /// file the server no longer has, which the viewer already reports. private var listings: [String: [FileTreeNode]] = [:] private var loadedSessionID: String? - /// Bumped per query so a listing that lands after a newer query never - /// overwrites the rows on screen. private var generation = 0 - /// Bumped whenever the cache stops meaning what it meant: another session, - /// or a workspace switch. A listing still in flight belongs to the scope it - /// was asked in, so it must neither be cached under the new one nor counted - /// as an answer about it. private var cacheGeneration = 0 - /// Most rows one panel offers. Past this the panel is a scroll rather than - /// a choice, and the ranking already put the best rows on top. private static let matchLimit = 20 - /// Lists the folder `query` names and ranks it against the query's last - /// segment. A failed listing reads as "nothing matched": the panel is a - /// shortcut, and an error box over the keyboard would be in the way of the - /// user simply typing the path. func search(_ query: String, sessionID: String, apiClient: APIClient) async { dropCacheIfSessionChanged(sessionID) @@ -104,18 +71,6 @@ final class ComposerFilePathSearch { } } - /// One query whose rows the data source ranks itself. - /// - /// Bots use this: `complete.path` completes against the live session's - /// working directory, ranks its own rows and caps them, so there is nothing - /// to list or score here. The generation guard is the same one - /// `search(_:sessionID:apiClient:)` runs under, so a reply that lands after - /// a newer query, or after `reset()`, can never publish. - /// - /// The previous query's rows are dropped the moment a new one starts: they - /// are not this query's answer, and leaving them selectable would let a tap - /// insert a path the user is no longer typing. The webui engine clears the - /// same way whenever the folder it needs is not cached. func search(_ query: String, load: (String) async throws -> [Match]) async { generation &+= 1 let generation = self.generation @@ -134,17 +89,6 @@ final class ComposerFilePathSearch { } } - /// The entries of one workspace folder, listed at most once. - /// - /// The panel and the view model's `@path` confirmation share this cache, so - /// re-opening the panel over a directory a restored draft already had - /// checked costs nothing. Never recurses, and a folder that climbs out of - /// the workspace is answered empty without asking the server. - /// - /// Throws `CancellationError` when the session or workspace moved while the - /// listing was in flight. That is deliberately the same shape as a failed - /// request: the folder is *unanswered*, so its candidates stay open for the - /// next pass rather than being settled against a root they never described. func entries(in directory: String, sessionID: String, apiClient: APIClient) async throws -> [FileTreeNode] { dropCacheIfSessionChanged(sessionID) @@ -160,19 +104,7 @@ final class ComposerFilePathSearch { return nodes } - /// Forgets every listing. - /// - /// The session's workspace can be switched underneath a chat (`/workspace`, - /// or the composer's workspace picker) without the session id changing, and - /// a folder listed against the old root says nothing about the new one. The - /// view model calls this the moment the workspace moves. `reloadingOpenQuery` asks an - /// open panel to load its query again: only for a move the host already applied, such as - /// a Hermes chat's `session.info`. A webui switch is optimistic, and a listing taken - /// before the server applies it would still answer from the old root. func reset(reloadingOpenQuery: Bool = false) { - // A listing already in flight belongs to the old workspace; bumping both - // generations is what stops it reaching the new one's rows and the new - // one's cache. generation &+= 1 cacheGeneration &+= 1 if reloadingOpenQuery { scopeRevision &+= 1 } @@ -182,7 +114,6 @@ final class ComposerFilePathSearch { isLoading = false } - /// A path only means anything inside the session it came from. private func dropCacheIfSessionChanged(_ sessionID: String) { guard sessionID != loadedSessionID else { return } cacheGeneration &+= 1 @@ -190,7 +121,6 @@ final class ComposerFilePathSearch { loadedSessionID = sessionID } - /// The folder a query names and the segment it is filtering that folder by. private struct Request { let directory: String let segment: String @@ -207,15 +137,6 @@ final class ComposerFilePathSearch { } } - /// Drops anything a reference cannot name: an entry the server marked as a - /// symlink pointing outside the workspace, any path with a `..` component, - /// and any path containing whitespace. - /// - /// The whitespace rule is the reference syntax's, not the filesystem's. The - /// only form verified against upstream is `@` plus the plain path followed - /// by a space, which means the space inside `My File.swift` ends the - /// reference: the path would insert and then never read back as one. Better - /// not to offer it than to offer something that quietly does not work. private static func nodes(from entries: [WorkspaceEntry], in directory: String) -> [FileTreeNode] { entries .filter { $0.targetOutsideWorkspace != true } @@ -227,9 +148,6 @@ final class ComposerFilePathSearch { path.split(separator: "/", omittingEmptySubsequences: false).contains("..") } - /// An empty segment is the whole folder in tree order. A typed segment is - /// ranked by `FileTreeSearch`, which is the same scorer the workspace search - /// field uses, so the same typing finds the same file in both places. private static func ranked(_ nodes: [FileTreeNode], against segment: String) -> [Match] { guard !segment.isEmpty else { return FileTree.sorted(nodes).prefix(matchLimit).map { Match(node: $0) } diff --git a/HermesMobile/Features/Chat/ForkOrigin.swift b/HermesMobile/Features/Chat/ForkOrigin.swift index 99c89ac7a..78fa2434f 100644 --- a/HermesMobile/Features/Chat/ForkOrigin.swift +++ b/HermesMobile/Features/Chat/ForkOrigin.swift @@ -1,25 +1,14 @@ import SwiftUI -/// Where a forked chat came from, for the "Forked from" row at the top of its -/// transcript. Only chats made by Fork From Here or `/branch` count: upstream -/// stamps those `session_source: "fork"` with a `parent_session_id`. Agent -/// child sessions (subagents, cron, CLI `/new`) share `parent_session_id` -/// but are not forks, so they get no row. A Hermes branch is marked in its own -/// row instead, and its chat reads it from the host (`HermesBranchParent`, #1051). struct ForkOrigin: Equatable { let parentSessionID: String - /// The parent as the session list cached it; nil means a tap fetches it. let parent: SessionSummary? - /// The row's label: the parent's list title, or a fallback when the parent - /// is not cached. var title: String { guard let parent else { return String(localized: "Forked from another chat") } return String(localized: "Forked from \(SessionRowView.displayTitle(for: parent))") } - /// The parent to look up, or nil when `session` is not a fork. Matches the - /// webui's own test: `session_source`, trimmed and lowercased, is "fork". static func parentSessionID(of session: SessionSummary) -> String? { guard session.sessionSource?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() == "fork", let parentID = session.parentSessionId?.trimmingCharacters(in: .whitespacesAndNewlines), @@ -30,15 +19,12 @@ struct ForkOrigin: Equatable { return parentID } - /// - Parameter parent: the cached parent session, if the list held it. static func resolve(session: SessionSummary, parent: SessionSummary?) -> ForkOrigin? { guard let parentID = parentSessionID(of: session) else { return nil } return ForkOrigin(parentSessionID: parentID, parent: parent) } } -/// The first transcript row of a forked chat. Styled like the turn-fold row: -/// a 44 pt secondary line with a bottom hairline. Tapping opens the parent. struct ForkOriginRowView: View { let origin: ForkOrigin let onOpen: () -> Void diff --git a/HermesMobile/Features/Chat/HTMLReport.swift b/HermesMobile/Features/Chat/HTMLReport.swift index ae7635cc9..0053d2a49 100644 --- a/HermesMobile/Features/Chat/HTMLReport.swift +++ b/HermesMobile/Features/Chat/HTMLReport.swift @@ -4,34 +4,20 @@ import Observation import SwiftUI import UIKit -/// An agent-generated `.html` report in a Hermes reply (#1623): rendered in place in the -/// transcript, and in a full-height sheet from its expand button. webui replies keep their -/// download card. enum HTMLReport { - /// The largest file a reply renders in place. A larger one stays a file card whose tap - /// opens the sheet, which takes up to `BotArtifactBuffer.maximumBytes`. static let inlineByteLimit = 5 * 1024 * 1024 - /// Whether a reply's file renders in place: an HTML file in a settled reply, on a chat that - /// publishes a loader, which only a Hermes chat does. Everything else keeps its file card. static func rendersInline(_ reference: TranscriptMediaReference, loader: TranscriptHTMLReportLoader?, isStreaming: Bool) -> Bool { reference.isHTMLReportCandidate && loader != nil && !isStreaming } } -/// A code fence that shows as a picture or page (#1649, #1748): `svg`, `mermaid` through the -/// bundled Pele engine (`MermaidDiagram`), or `html` (`htm` too). A settled one gains a View -/// button in its header that opens the drawing or page in the report sheet, in the report's -/// sandbox. Nothing renders in the transcript, and the code block stays, so the source is never -/// lost. enum DrawableFence { case svg case mermaid case html - /// The fence's kind when it offers View; nil for any other language, and for a streaming - /// fence, whose source is still incomplete. init?(language: String?, isStreaming: Bool) { guard !isStreaming else { return nil } switch MarkdownHighlightPolicy.normalizedLanguage(from: language) { @@ -42,10 +28,6 @@ enum DrawableFence { } } - /// The sheet's page for the fence's source, or nil when it can't draw, so the sheet shows its - /// failure state rather than a blank page. A diagram lays out to fit `width`, the sheet's. An - /// `html` fence's source is the page as it is, with no card: the page brings its own layout. - /// It runs the diagram engine, so call it off the main actor. func page(for source: String, width: CGFloat) -> String? { let source = source.trimmingCharacters(in: .whitespacesAndNewlines) switch self { @@ -59,13 +41,8 @@ enum DrawableFence { } } - /// The body's and card's padding on both sides. private static let cardInsets: CGFloat = 56 - /// A drawing on a white card, since agent SVGs usually have no background and draw in black. - /// An agent SVG with a `viewBox` fits the sheet's width; one without keeps its own size and - /// scrolls inside the card instead of being cropped. A Pele diagram keeps its own size, which - /// already fits, rather than stretching its 16-point labels; pinch to zoom in. private static func card(_ svg: String) -> String { """