Files
hapi/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatPipeline.swift
T
weishu eed3dddb94 feat(ios): composer, permission actions, session config (A-M3ab)
Interaction layer turning the read-only chat into a working remote control,
mirroring the merged Android B-M3ab feature-for-feature (web authority where
the ports disagreed):

- ChatInteractor (HapiClient, fully swift-test covered): optimistic composer
  sends (appendOptimistic -> POST -> status settle), queue-by-default with a
  long-press Send&Steer intent while a turn is active, tap-to-retry on failed
  rows (steer retries degrade to queue), per-session drafts
  (UserDefaultsChatDrafts, hub-scoped keys, debounced + flushed on close).
- session_inactive (409) recovery: one POST /resume (current permissionMode)
  then retry; a superseding session id seeds the new window
  (MessageWindowControllers.seed), migrates the draft, retargets the
  optimistic row and emits sessionSuperseded -- ChatView/HomeView replace the
  navigation entry in place.
- Queued bar: uninvoked sends in web sort order with Cancel (optimistic
  DELETE; invoked-race ingests the authoritative row as sent), Edit
  (cancel + composer prefill, newer-draft guard) and Steer (invoked answers
  reconcile a missed consume); single-flight per-row op guard.
  reconcileQueuedState now runs on chat open and on session-pipe gap.
- Permission actions: flavor-exact bodies mirroring PermissionFooter.tsx --
  claude {} / allowTools (Bash(cmd)) / mode:acceptEdits, codex-family
  decision approved / approved_for_session / abort via deny -- plus
  AskUserQuestion flat answers (option cards, Other free text, no-questions
  fallback, cursor stable ids) and request_user_input nested answers
  (user_note suffix, required validation); optimistic Resolving /
  AlreadyHandled (404/409) overrides settled by the agentState patch.
  ChatPipeline now re-attaches the window row's client status so failed
  user rows actually render the retry affordance (web normalize.ts parity;
  the Android reference misses this overlay).
- Session config sheet (toolbar gear): catalog-driven permission-mode picker
  with tones, claude static model/effort catalogs (ModelCatalog port), codex
  models via new GET /sessions/:id/codex-models endpoint + wire types with
  per-model reasoning efforts; optimistic detail updates
  (SessionListStore.updateDetailLocal, new) rolled forward to server truth
  on error.
- Lifecycle: VisibilityReporter posts POST /api/visibility per tracked
  handshake subscriptionId on scene-phase flips (404 prunes); ChatSession
  exposes its subscriptionId and feeds the reporter; the global SSE pipe was
  already HubSession-lifetime on iOS.
- Tests: ChatInteractorTests transcribes the Android interaction suite
  against the real APIClient/AuthManager/SessionListStore/window registry
  with only HTTP scripted -- canonical JSON bodies asserted byte-for-byte
  (send/approve/deny/config), optimistic send happy/fail/retry, 409 resume
  both id paths, cancel invoked-race, steer reconcile, edit prefill,
  override lifecycle, config optimistic + rollback, drafts, abort.
2026-08-18 10:33:04 +08:00

106 lines
4.8 KiB
Swift

import Foundation
import HapiProtocol
/// Off-main executor for the read-only chat reduction path (M2f): window rows
/// → `normalizeDecryptedMessage` → `reduceChatBlocks` → `buildVisibleChatBlocks`.
/// Mirrors the web `SessionChat.tsx` pipeline via the Android port's
/// `ChatViewModel.buildUiState`:
///
/// - **Queued-not-invoked rows are filtered out** — they belong to the
/// composer's queue bar (M3a), not the thread (shared predicate with the
/// window store: `WindowMessage.isQueuedForInvocation`).
/// - **Normalization is memoized per message id by row *instance* identity**
/// (the web `normalizedCache` keyed on object identity). ``WindowMessage``
/// is an identity-carrying class whose transitions allocate a new instance
/// for every changed row, so `===` on the cached source is exactly the
/// web's `cached.source !== message` invalidation. The entry retains the
/// source row (instead of a bare `ObjectIdentifier`) so a deallocated
/// row's identity can never be recycled into a false cache hit.
/// - **Group ids are stabilized across recomputes** by feeding the previous
/// run's `ToolGroupBlock`s back through `ToolGroupingOptions.previousGroups`
/// (web `buildVisibleChatBlocks`'s `previousGroups` contract) — scroll
/// anchoring and expansion state key off `ToolGroupBlock.id`.
///
/// An `actor` so (a) the synchronous pipeline body runs on the cooperative
/// pool, off the main actor that publishes the result, and (b) the memo
/// dictionaries are data-race free while staying plain mutable state. The
/// app-side `ChatModel` is the single caller and awaits each run to
/// completion, so runs never interleave in practice; the actor makes that a
/// guarantee rather than a convention.
public actor ChatPipeline {
private struct NormalizeCacheEntry {
/// The exact row instance the cached result was computed from.
let source: WindowMessage
/// `nil` == the reference dropped this row (skippable output).
let normalized: NormalizedMessage?
}
private var normalizeCache: [String: NormalizeCacheEntry] = [:]
private var previousGroups: [ToolGroupBlock] = []
public init() {}
/// One pipeline run over the current window + agent state. Pure with
/// respect to its inputs except for the two memo fields above.
public func run(
messages: [WindowMessage],
agentState: AgentState?,
hasMoreMessages: Bool
) -> [VisibleChatBlock] {
// Composer-owned rows out; duplicate ids keep the first occurrence
// (merge output cannot contain duplicates — defensive, like Android).
let visibleRows = messages.filter { !$0.isQueuedForInvocation }
var normalized: [NormalizedMessage] = []
normalized.reserveCapacity(visibleRows.count)
var seenIds = Set<String>(minimumCapacity: visibleRows.count * 2)
for row in visibleRows {
guard seenIds.insert(row.id).inserted else { continue }
if let cached = normalizeCache[row.id], cached.source === row {
if let value = cached.normalized {
normalized.append(value)
}
continue
}
var next = normalizeDecryptedMessage(row.asDecryptedMessage)
// The wire model carries no client send-state; re-attach the
// window row's status so failed optimistic rows render their
// retry affordance (the web normalizes `DecryptedMessage &
// {status}` directly — `normalize.ts` copies `message.status`).
// Cache correctness holds: a status change allocates a new row
// instance, which invalidates the memo entry above.
if let status = row.status {
next?.status = status.rawValue
}
normalizeCache[row.id] = NormalizeCacheEntry(source: row, normalized: next)
if let next {
normalized.append(next)
}
}
// Drop cache entries for rows no longer in the window (trims, resets).
if normalizeCache.count > seenIds.count {
normalizeCache = normalizeCache.filter { seenIds.contains($0.key) }
}
let reduced = reduceChatBlocks(normalized, agentState: agentState)
let visible = buildVisibleChatBlocks(
reduced.blocks,
options: ToolGroupingOptions(
hasMoreMessages: hasMoreMessages,
previousGroups: previousGroups
)
)
previousGroups = visible.compactMap { block in
if case .toolGroup(let group) = block { return group }
return nil
}
return visible
}
/// Forget all memo state (session switch / tests).
public func reset() {
normalizeCache = [:]
previousGroups = []
}
}