Files
hapi/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatPipeline.swift
T
weishu a4355d1837 feat(ios): read-only chat assembly (A-M2f)
Wires the merged M2 pieces into a usable pair -> list -> live chat flow:

- pbxproj: link HapiUI into the app target (UUIDs C7/C8, mirroring the
  existing HapiProtocol/HapiClient product references; only project change).
- HubSession: MessageWindowControllers registry + per-chat ChatSession
  factory with in-memory per-session SSE resume cursors and scene-phase
  forwarding to the active chat.
- ChatSession (app): session-scope SSEClient while the chat is open;
  window opened/activated before subscribing; a single consume task awaits
  every event into the window actor, giving Android-channel-equivalent
  arrival-order ingestion; session-updated and friends route through the
  shared SyncEventRouter (detail patching), session-removed clears the
  window, a gap handshake triggers full resync + detail refetch + catch-up
  tail sync; stop hands the cursor back for seamless reopen.
- ChatPipeline (HapiClient): actor running the reduction path off-main -
  queued-row filter, normalization memoized by row instance identity,
  reduce + buildVisibleChatBlocks with previousGroups-stable group ids.
- ChatModel: window state + detail agentState + machine labels -> serial
  ~100 ms-coalesced pipeline loop (first run immediate, publishes strictly
  ordered), header title cascade, loading/empty/error states, loadOlder /
  retry, last-seen stamping on every update.
- ChatView: bottom-anchored ScrollView/LazyVStack (defaultScrollAnchor +
  scrollPosition(id:)), auto-stick at bottom, new-messages pill, top
  sentinel paging with documented scroll re-anchoring, degraded banners.
- Block views: user bubble w/ attachment chips, agent markdown, collapsed
  reasoning, tool cards (knownTools.tsx-parity presentation, status chip,
  read-only permission row w/ pending banner, per-tool bodies: terminal,
  before/after edits, write content, unified-diff detection -> DiffTextView,
  checklists, read-only questions, pretty-JSON fallback, children rail),
  tool groups, centered event rows (presentation.ts port), cli output,
  generated images (authed bytes + in-memory cache + full-screen viewer),
  codex review verdict card.
- Navigation/links: session list now pushes ChatView; app-level
  \.hapiOpenURL handler (https/http -> SFSafariViewController, custom
  schemes confirm first, hapi-file:// -> M4 placeholder) + theme injection.
- Tests: ChatPipelineTests drive the runner with fixture-derived windows
  (stable ids, memo-stable recomputes, queued filter, group-id stability
  across an older-page arrival).
- README: M2f app-layer description.
2026-08-17 20:55:36 +08:00

97 lines
4.2 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
}
let next = normalizeDecryptedMessage(row.asDecryptedMessage)
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 = []
}
}