From a4355d183748954a216c9b73cb20aef98564e7c2 Mon Sep 17 00:00:00 2001 From: weishu Date: Mon, 17 Aug 2026 20:55:36 +0800 Subject: [PATCH] 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. --- ios/Hapi.xcodeproj/project.pbxproj | 7 + .../Features/Chat/Blocks/ChatBlockCard.swift | 131 +++++ ios/Hapi/Features/Chat/Blocks/ChatJSON.swift | 127 +++++ .../Chat/Blocks/CodexReviewBlockView.swift | 140 +++++ .../Chat/Blocks/EventPresentation.swift | 228 ++++++++ .../Chat/Blocks/GeneratedImageBlockView.swift | 101 ++++ .../Features/Chat/Blocks/TextBlockViews.swift | 163 ++++++ .../Features/Chat/Blocks/ToolBodies.swift | 368 +++++++++++++ .../Chat/Blocks/ToolCallBlockView.swift | 200 +++++++ .../Chat/Blocks/ToolCardPresentation.swift | 504 ++++++++++++++++++ .../Chat/Blocks/ToolGroupBlockView.swift | 112 ++++ ios/Hapi/Features/Chat/ChatModel.swift | 307 +++++++++++ ios/Hapi/Features/Chat/ChatView.swift | 285 ++++++++++ ios/Hapi/Features/Home/HomeView.swift | 4 +- .../Features/Links/LinkOpenHandling.swift | 130 +++++ .../Sessions/SessionDetailStubView.swift | 25 - ios/Hapi/Models/ChatSession.swift | 222 ++++++++ ios/Hapi/Models/HubSession.swift | 54 +- ios/Hapi/RootView.swift | 9 +- .../HapiClient/Chat/ChatPipeline.swift | 96 ++++ .../HapiClient/Stores/SyncEventRouting.swift | 13 +- .../HapiClientTests/ChatPipelineTests.swift | 187 +++++++ ios/README.md | 55 +- 23 files changed, 3421 insertions(+), 47 deletions(-) create mode 100644 ios/Hapi/Features/Chat/Blocks/ChatBlockCard.swift create mode 100644 ios/Hapi/Features/Chat/Blocks/ChatJSON.swift create mode 100644 ios/Hapi/Features/Chat/Blocks/CodexReviewBlockView.swift create mode 100644 ios/Hapi/Features/Chat/Blocks/EventPresentation.swift create mode 100644 ios/Hapi/Features/Chat/Blocks/GeneratedImageBlockView.swift create mode 100644 ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift create mode 100644 ios/Hapi/Features/Chat/Blocks/ToolBodies.swift create mode 100644 ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift create mode 100644 ios/Hapi/Features/Chat/Blocks/ToolCardPresentation.swift create mode 100644 ios/Hapi/Features/Chat/Blocks/ToolGroupBlockView.swift create mode 100644 ios/Hapi/Features/Chat/ChatModel.swift create mode 100644 ios/Hapi/Features/Chat/ChatView.swift create mode 100644 ios/Hapi/Features/Links/LinkOpenHandling.swift delete mode 100644 ios/Hapi/Features/Sessions/SessionDetailStubView.swift create mode 100644 ios/Hapi/Models/ChatSession.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatPipeline.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/ChatPipelineTests.swift diff --git a/ios/Hapi.xcodeproj/project.pbxproj b/ios/Hapi.xcodeproj/project.pbxproj index 3b8655ec..9cd5c811 100644 --- a/ios/Hapi.xcodeproj/project.pbxproj +++ b/ios/Hapi.xcodeproj/project.pbxproj @@ -9,6 +9,7 @@ /* Begin PBXBuildFile section */ A100000000000000000000C4 /* HapiProtocol in Frameworks */ = {isa = PBXBuildFile; productRef = A100000000000000000000C2 /* HapiProtocol */; }; A100000000000000000000C5 /* HapiClient in Frameworks */ = {isa = PBXBuildFile; productRef = A100000000000000000000C3 /* HapiClient */; }; + A100000000000000000000C8 /* HapiUI in Frameworks */ = {isa = PBXBuildFile; productRef = A100000000000000000000C7 /* HapiUI */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -47,6 +48,7 @@ files = ( A100000000000000000000C4 /* HapiProtocol in Frameworks */, A100000000000000000000C5 /* HapiClient in Frameworks */, + A100000000000000000000C8 /* HapiUI in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -91,6 +93,7 @@ packageProductDependencies = ( A100000000000000000000C2 /* HapiProtocol */, A100000000000000000000C3 /* HapiClient */, + A100000000000000000000C7 /* HapiUI */, ); productName = Hapi; productReference = A100000000000000000000A4 /* Hapi.app */; @@ -310,6 +313,10 @@ isa = XCSwiftPackageProductDependency; productName = HapiClient; }; + A100000000000000000000C7 /* HapiUI */ = { + isa = XCSwiftPackageProductDependency; + productName = HapiUI; + }; /* End XCSwiftPackageProductDependency section */ }; rootObject = A100000000000000000000A6 /* Project object */; diff --git a/ios/Hapi/Features/Chat/Blocks/ChatBlockCard.swift b/ios/Hapi/Features/Chat/Blocks/ChatBlockCard.swift new file mode 100644 index 00000000..5d3febe8 --- /dev/null +++ b/ios/Hapi/Features/Chat/Blocks/ChatBlockCard.swift @@ -0,0 +1,131 @@ +import HapiClient +import HapiProtocol +import SwiftUI +import UIKit + +// MARK: - List identity + +extension VisibleChatBlock { + /// Stable list key: block ids are reducer-stable and tool-group ids are + /// pinned across recomputes via `previousGroups`, so scroll anchoring + /// and expansion state survive pipeline re-runs. + var stableId: String { + switch self { + case .block(let block): return block.id + case .toolGroup(let group): return group.id + } + } + + /// Recycling bucket (the Android `contentKind` / web block `kind`). + var contentKind: String { + switch self { + case .block(let block): return block.kind + case .toolGroup: return "tool-group" + } + } +} + +// MARK: - Media plumbing + +/// Per-chat generated-image loading: `GET /generated-images/:imageId` bytes +/// through the authed APIClient (URLCache underneath serves immutable-ETag +/// repeats), plus a small in-memory decode cache so scroll-back does not +/// re-decode. Injected down the block tree via `\.chatMedia`. +@MainActor +final class GeneratedImageLoader { + private let api: APIClient + private let sessionId: String + private let cache = NSCache() + private var inFlight: [String: Task] = [:] + + init(api: APIClient, sessionId: String) { + self.api = api + self.sessionId = sessionId + cache.countLimit = 40 + } + + func image(for imageId: String) async -> UIImage? { + if let cached = cache.object(forKey: imageId as NSString) { + return cached + } + if let running = inFlight[imageId] { + return await running.value + } + let api = api + let sessionId = sessionId + let task = Task { + guard let payload = try? await api.generatedImage(sessionId: sessionId, imageId: imageId) else { + return nil + } + return UIImage(data: payload.data) + } + inFlight[imageId] = task + let image = await task.value + inFlight[imageId] = nil + if let image { + cache.setObject(image, forKey: imageId as NSString) + } + return image + } +} + +private struct ChatMediaKey: EnvironmentKey { + static let defaultValue: GeneratedImageLoader? = nil +} + +extension EnvironmentValues { + /// The open chat's image loader; nil (previews/tests) degrades generated + /// images to a filename placeholder. + var chatMedia: GeneratedImageLoader? { + get { self[ChatMediaKey.self] } + set { self[ChatMediaKey.self] = newValue } + } +} + +// MARK: - Dispatcher + +/// One thread entry: routes a reduced `VisibleChatBlock` to its card — the +/// SwiftUI analogue of the web block-kind → component mapping and the +/// Android `ChatBlockCard`. Also used recursively for tool-call children +/// (sidechain transcripts). +struct ChatBlockCard: View { + let block: VisibleChatBlock + let basePath: String? + + var body: some View { + switch block { + case .toolGroup(let group): + ToolGroupBlockView(block: group, basePath: basePath) + case .block(let chatBlock): + ChatSubBlockView(block: chatBlock, basePath: basePath) + } + } +} + +/// Dispatcher for the plain `ChatBlock` union (shared by the thread and by +/// tool-card children). +struct ChatSubBlockView: View { + let block: ChatBlock + let basePath: String? + + var body: some View { + switch block { + case .userText(let value): + UserTextBlockView(block: value) + case .agentText(let value): + AgentTextBlockView(block: value) + case .agentReasoning(let value): + AgentReasoningBlockView(block: value) + case .agentEvent(let value): + AgentEventBlockView(block: value) + case .cliOutput(let value): + CliOutputBlockView(block: value) + case .generatedImage(let value): + GeneratedImageBlockView(block: value) + case .codexReview(let value): + CodexReviewBlockView(block: value) + case .toolCall(let value): + ToolCallBlockView(block: value, basePath: basePath) + } + } +} diff --git a/ios/Hapi/Features/Chat/Blocks/ChatJSON.swift b/ios/Hapi/Features/Chat/Blocks/ChatJSON.swift new file mode 100644 index 00000000..d253e2df --- /dev/null +++ b/ios/Hapi/Features/Chat/Blocks/ChatJSON.swift @@ -0,0 +1,127 @@ +import Foundation +import HapiProtocol + +// App-side JSONValue conveniences. HapiProtocol keeps its own accessors +// internal (they encode JS semantics for the pipeline port); these are the +// small read-only subset the chat presentation layer needs. + +extension JSONValue { + var chatObject: [String: JSONValue]? { + if case .object(let value) = self { return value } + return nil + } + + var chatArray: [JSONValue]? { + if case .array(let value) = self { return value } + return nil + } + + var chatString: String? { + if case .string(let value) = self { return value } + return nil + } + + var chatNumber: Double? { + if case .number(let value) = self { return value } + return nil + } + + /// Object member lookup; nil for arrays/scalars/missing keys. + subscript(chatKey key: String) -> JSONValue? { + chatObject?[key] + } +} + +/// First string value among `keys` (the app-side twin of the pipeline's +/// internal `getInputStringAny`). +func chatInputString(_ input: JSONValue?, _ keys: [String]) -> String? { + guard let object = input?.chatObject else { return nil } + for key in keys { + if let value = object[key]?.chatString { + return value + } + } + return nil +} + +/// Web `truncate`: hard cap with a trailing ellipsis. +func chatTruncate(_ text: String, _ limit: Int) -> String { + guard text.count > limit else { return text } + return String(text.prefix(limit)) + "…" +} + +/// Pretty JSON for generic tool inputs/results: sorted keys, 2-space indent, +/// whole numbers printed without a trailing `.0`. Display-only (never feeds +/// the normative projection). +func chatPrettyJSON(_ value: JSONValue) -> String { + var output = "" + appendJSON(value, indent: 0, into: &output) + return output +} + +private func appendJSON(_ value: JSONValue, indent: Int, into output: inout String) { + let pad = String(repeating: " ", count: indent) + let childPad = String(repeating: " ", count: indent + 1) + switch value { + case .null: + output += "null" + case .bool(let flag): + output += flag ? "true" : "false" + case .number(let number): + output += formatJSONNumber(number) + case .string(let text): + output += quoteJSONString(text) + case .array(let items): + if items.isEmpty { + output += "[]" + return + } + output += "[\n" + for (index, item) in items.enumerated() { + output += childPad + appendJSON(item, indent: indent + 1, into: &output) + output += index == items.count - 1 ? "\n" : ",\n" + } + output += pad + "]" + case .object(let members): + if members.isEmpty { + output += "{}" + return + } + output += "{\n" + let keys = members.keys.sorted() + for (index, key) in keys.enumerated() { + output += childPad + quoteJSONString(key) + ": " + appendJSON(members[key] ?? .null, indent: indent + 1, into: &output) + output += index == keys.count - 1 ? "\n" : ",\n" + } + output += pad + "}" + } +} + +func formatJSONNumber(_ number: Double) -> String { + if number.rounded() == number, abs(number) < 1e15 { + return String(Int64(number)) + } + return String(number) +} + +private func quoteJSONString(_ text: String) -> String { + var escaped = "\"" + for scalar in text.unicodeScalars { + switch scalar { + case "\"": escaped += "\\\"" + case "\\": escaped += "\\\\" + case "\n": escaped += "\\n" + case "\r": escaped += "\\r" + case "\t": escaped += "\\t" + default: + if scalar.value < 0x20 { + escaped += String(format: "\\u%04x", scalar.value) + } else { + escaped.unicodeScalars.append(scalar) + } + } + } + return escaped + "\"" +} diff --git a/ios/Hapi/Features/Chat/Blocks/CodexReviewBlockView.swift b/ios/Hapi/Features/Chat/Blocks/CodexReviewBlockView.swift new file mode 100644 index 00000000..94467b16 --- /dev/null +++ b/ios/Hapi/Features/Chat/Blocks/CodexReviewBlockView.swift @@ -0,0 +1,140 @@ +import HapiProtocol +import HapiUI +import SwiftUI + +/// Codex `/review` verdict card (web `CodexReviewCard`): header with the +/// overall-correctness badge (+ confidence), the explanation as markdown, +/// and the findings list collapsed behind a count row. +struct CodexReviewBlockView: View { + let block: CodexReviewBlock + + @State private var findingsOpen = false + @Environment(\.hapiTheme) private var theme + + var body: some View { + let review = block.review + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 6) { + Text("Code review") + .font(.subheadline.weight(.semibold)) + Spacer(minLength: 8) + if let verdict = review.overallCorrectness { + VerdictBadge(verdict: verdict) + } + if let confidence = formatPercent(review.overallConfidenceScore) { + Text(confidence) + .font(.caption2) + .foregroundStyle(.secondary) + } + } + .padding(.horizontal, 12) + .padding(.vertical, 10) + + if let explanation = review.overallExplanation, + !explanation.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + Divider() + MarkdownView(markdown: explanation) + .padding(.horizontal, 12) + .padding(.vertical, 8) + } + + if !review.findings.isEmpty { + Divider() + Button { + withAnimation(.easeInOut(duration: 0.15)) { + findingsOpen.toggle() + } + } label: { + Label( + "\(review.findings.count) finding\(review.findings.count == 1 ? "" : "s")", + systemImage: findingsOpen ? "chevron.down" : "chevron.right" + ) + .font(.footnote) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 12) + .padding(.vertical, 8) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + if findingsOpen { + VStack(alignment: .leading, spacing: 8) { + ForEach(Array(review.findings.enumerated()), id: \.offset) { _, finding in + FindingRow(finding: finding) + } + } + .padding(.horizontal, 12) + .padding(.bottom, 12) + } + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .background(theme.surface) + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + } +} + +private struct VerdictBadge: View { + let verdict: String + + var body: some View { + let lowered = verdict.lowercased() + let tint: Color = lowered.contains("incorrect") + ? .red + : (lowered.contains("correct") ? .green : .secondary) + Text(verdict) + .font(.caption2) + .foregroundStyle(tint) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(tint.opacity(0.15), in: RoundedRectangle(cornerRadius: 6)) + } +} + +private struct FindingRow: View { + let finding: CodexReviewFinding + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 6) { + if let priority = finding.priority { + let value = Int(priority.rounded()) + Text("P\(value)") + .font(.caption2.weight(.semibold)) + .foregroundStyle(value <= 1 ? Color.red : Color.secondary) + .padding(.horizontal, 4) + .padding(.vertical, 1) + .background( + (value <= 1 ? Color.red : Color.secondary).opacity(0.14), + in: RoundedRectangle(cornerRadius: 4) + ) + } + Text(finding.title) + .font(.subheadline.weight(.semibold)) + } + Text(finding.body) + .font(.footnote) + if let location = formatLocation(finding) { + Text(location) + .font(.system(size: 10, design: .monospaced)) + .foregroundStyle(.secondary) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(10) + .background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8)) + } +} + +private func formatPercent(_ value: Double?) -> String? { + guard let value, value.isFinite else { return nil } + return "\(Int((value * 100).rounded()))%" +} + +private func formatLocation(_ finding: CodexReviewFinding) -> String? { + guard let filePath = finding.filePath else { return nil } + guard let start = finding.lineStart.map({ Int($0.rounded()) }) else { return filePath } + if let end = finding.lineEnd.map({ Int($0.rounded()) }), end != start { + return "\(filePath):\(start)-\(end)" + } + return "\(filePath):\(start)" +} diff --git a/ios/Hapi/Features/Chat/Blocks/EventPresentation.swift b/ios/Hapi/Features/Chat/Blocks/EventPresentation.swift new file mode 100644 index 00000000..1e0b4cdb --- /dev/null +++ b/ios/Hapi/Features/Chat/Blocks/EventPresentation.swift @@ -0,0 +1,228 @@ +import Foundation +import HapiProtocol + +/// Centered event-row wording: port of `web/src/chat/presentation.ts` via the +/// Android `getEventPresentation`. Render-only (the fixture projection never +/// includes presentation), so date formatting uses Foundation formatters +/// instead of the browser's `toLocaleString` while keeping the same rules. +struct EventPresentation: Equatable { + /// Leading glyph; nil for plain informational rows. + var icon: String? + var text: String +} + +// MARK: - Formatting helpers + +private func normalizedTimestampMs(_ value: Double) -> Double { + value < 1_000_000_000_000 ? value * 1000 : value +} + +func chatFormatUnixTimestamp(_ value: Double) -> String { + let date = Date(timeIntervalSince1970: normalizedTimestampMs(value) / 1000) + let formatter = DateFormatter() + formatter.dateFormat = "yyyy/M/d HH:mm:ss" + return formatter.string(from: date) +} + +func chatFormatResetTime(_ value: Double, now: Date = Date()) -> String { + let date = Date(timeIntervalSince1970: normalizedTimestampMs(value) / 1000) + let formatter = DateFormatter() + formatter.dateFormat = Calendar.current.isDate(date, inSameDayAs: now) ? "H:mm" : "MMM d, H:mm" + return formatter.string(from: date) +} + +/// Known limit types: five_hour → "5-hour", seven_day → "7-day"; otherwise +/// underscores become spaces. +private func formatLimitType(_ limitType: String?) -> String { + guard let limitType, !limitType.isEmpty else { return "" } + if limitType == "five_hour" { return "5-hour" } + if limitType == "seven_day" { return "7-day" } + return limitType.replacingOccurrences(of: "_", with: " ") +} + +func chatFormatDuration(ms: Double) -> String { + let seconds = ms / 1000 + if seconds < 60 { + return String(format: "%.1fs", seconds) + } + let minutes = Int(seconds / 60) + let remainder = Int((seconds.truncatingRemainder(dividingBy: 60)).rounded()) + return "\(minutes)m \(remainder)s" +} + +private func formatTokenCount(_ value: Double) -> String { + if value >= 1_000_000 { return String(format: "%.1fM", value / 1_000_000) } + if value >= 10_000 { return String(format: "%.1fk", value / 1_000) } + if value >= 1_000 { return "\(Int((value / 1_000).rounded()))k" } + return formatJSONNumber(value) +} + +private func formatGoalStatus(_ status: String) -> String { + switch status { + case "active": return "active" + case "paused": return "paused" + case "budgetLimited": return "limited by budget" + case "usageLimited": return "limited by usage" + case "blocked": return "blocked" + case "complete": return "complete" + default: return status + } +} + +private func threadGoalPresentation(_ event: AgentEvent) -> EventPresentation { + guard let goal = event["goal"]?.chatObject else { + return EventPresentation(icon: nil, text: "Goal updated") + } + let status = goal["status"]?.chatString ?? "updated" + var parts = ["Goal \(formatGoalStatus(status))"] + let tokensUsed = goal["tokensUsed"]?.chatNumber ?? goal["tokens_used"]?.chatNumber + let tokenBudget = goal["tokenBudget"]?.chatNumber ?? goal["token_budget"]?.chatNumber + if let tokensUsed, let tokenBudget { + parts.append("\(formatTokenCount(tokensUsed)) / \(formatTokenCount(tokenBudget))") + } + return EventPresentation(icon: nil, text: parts.joined(separator: " · ")) +} + +private func tokenCountPresentation(_ event: AgentEvent) -> EventPresentation { + let info = event["info"]?.chatObject + guard let total = info?["total"]?.chatObject ?? info else { + return EventPresentation(icon: "◷", text: "Context updated") + } + let inputTokens = total["inputTokens"]?.chatNumber ?? total["input_tokens"]?.chatNumber + let outputTokens = total["outputTokens"]?.chatNumber ?? total["output_tokens"]?.chatNumber + let cachedTokens = total["cachedInputTokens"]?.chatNumber + ?? total["cacheReadInputTokens"]?.chatNumber + ?? total["cache_read_input_tokens"]?.chatNumber + let reasoningTokens = total["reasoningOutputTokens"]?.chatNumber + ?? total["reasoning_output_tokens"]?.chatNumber + let contextWindow = total["modelContextWindow"]?.chatNumber + ?? total["model_context_window"]?.chatNumber + + var parts: [String] = [] + if let inputTokens, let contextWindow, contextWindow > 0 { + let percent = Int((inputTokens / contextWindow * 100).rounded()) + parts.append("Context \(formatTokenCount(inputTokens)) / \(formatTokenCount(contextWindow)) (\(percent)%)") + } else if let inputTokens { + parts.append("Context \(formatTokenCount(inputTokens))") + } else { + parts.append("Context updated") + } + if let outputTokens { parts.append("out \(formatTokenCount(outputTokens))") } + if let cachedTokens, cachedTokens > 0 { parts.append("cached \(formatTokenCount(cachedTokens))") } + if let reasoningTokens, reasoningTokens > 0 { parts.append("reasoning \(formatTokenCount(reasoningTokens))") } + return EventPresentation(icon: "◷", text: parts.joined(separator: " · ")) +} + +private func apiErrorDetail(_ error: JSONValue?) -> String? { + if let text = error?.chatString { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : trimmed + } + guard let record = error?.chatObject, record["message"] != nil else { return nil } + let trimmed = record["message"]?.chatString?.trimmingCharacters(in: .whitespacesAndNewlines) + return (trimmed?.isEmpty ?? true) ? nil : trimmed +} + +// MARK: - Entry point + +func eventPresentation(_ event: AgentEvent) -> EventPresentation { + switch event.type { + case "api-error": + let retryAttempt = event["retryAttempt"]?.chatNumber ?? 0 + let maxRetries = event["maxRetries"]?.chatNumber ?? 0 + if maxRetries > 0, retryAttempt >= maxRetries { + return EventPresentation(icon: "⚠️", text: "API error: Max retries reached") + } + if maxRetries > 0 { + return EventPresentation( + icon: "⏳", + text: "API error: Retrying (\(formatJSONNumber(retryAttempt))/\(formatJSONNumber(maxRetries)))" + ) + } + if retryAttempt > 0 { + if let detail = apiErrorDetail(event["error"]) { + return EventPresentation(icon: "⏳", text: "API error: Retrying... \(detail)") + } + return EventPresentation(icon: "⏳", text: "API error: Retrying...") + } + return EventPresentation(icon: "⚠️", text: "API error") + + case "switch": + let mode = event["mode"]?.chatString == "local" ? "local" : "remote" + return EventPresentation(icon: "🔄", text: "Switched to \(mode)") + + case "title-changed": + let title = event["title"]?.chatString ?? "" + return EventPresentation( + icon: nil, + text: title.isEmpty ? "Title changed" : "Title changed to \"\(title)\"" + ) + + case "permission-mode-changed": + let mode = event["mode"]?.chatString ?? "default" + return EventPresentation(icon: "🔐", text: "Permission mode: \(mode)") + + case "limit-warning": + let percent = Int(((event["utilization"]?.chatNumber ?? 0) * 100).rounded()) + let typeLabel = formatLimitType(event["limitType"]?.chatString) + let suffix = typeLabel.isEmpty ? "" : " (\(typeLabel))" + if let endsAt = event["endsAt"]?.chatNumber { + return EventPresentation( + icon: "⚠️", + text: "Usage limit \(percent)%\(suffix) · resets \(chatFormatResetTime(endsAt))" + ) + } + return EventPresentation(icon: "⚠️", text: "Usage limit \(percent)%\(suffix)") + + case "limit-reached": + let typeLabel = formatLimitType(event["limitType"]?.chatString) + let suffix = typeLabel.isEmpty ? "" : " (\(typeLabel))" + if let endsAt = event["endsAt"]?.chatNumber { + return EventPresentation( + icon: "⏳", + text: "Usage limit reached\(suffix) until \(chatFormatUnixTimestamp(endsAt))" + ) + } + return EventPresentation(icon: "⏳", text: "Usage limit reached\(suffix)") + + case "error": + return EventPresentation(icon: "⚠️", text: event["message"]?.chatString ?? "Error") + + case "message": + return EventPresentation(icon: nil, text: event["message"]?.chatString ?? "Message") + + case "turn-duration": + let ms = event["durationMs"]?.chatNumber ?? 0 + return EventPresentation(icon: "⏱️", text: "Turn: \(chatFormatDuration(ms: ms))") + + case "microcompact": + let saved = event["tokensSaved"]?.chatNumber ?? 0 + let formatted = saved >= 1000 + ? "\(Int((saved / 1000).rounded()))K" + : formatJSONNumber(saved) + return EventPresentation(icon: "📦", text: "Context compacted (saved \(formatted) tokens)") + + case "compact": + return EventPresentation(icon: "📦", text: "Conversation compacted") + + case "compact-summary": + return EventPresentation(icon: "📦", text: "Context compacted") + + case "recap": + let text = event["text"]?.chatString ?? "" + return EventPresentation(icon: "💭", text: "recap: \(text)") + + case "thread-goal-updated": + return threadGoalPresentation(event) + + case "thread-goal-cleared": + return EventPresentation(icon: nil, text: "Goal cleared") + + case "token-count": + return tokenCountPresentation(event) + + default: + // Unknown event types: generic raw rendering, truncated. + return EventPresentation(icon: nil, text: chatTruncate(chatPrettyJSON(event.wireValue), 300)) + } +} diff --git a/ios/Hapi/Features/Chat/Blocks/GeneratedImageBlockView.swift b/ios/Hapi/Features/Chat/Blocks/GeneratedImageBlockView.swift new file mode 100644 index 00000000..14927787 --- /dev/null +++ b/ios/Hapi/Features/Chat/Blocks/GeneratedImageBlockView.swift @@ -0,0 +1,101 @@ +import HapiProtocol +import SwiftUI +import UIKit + +/// Hub-generated image (`/api/sessions/:id/generated-images/:imageId`), +/// loaded as authed bytes through the chat's `GeneratedImageLoader` +/// (`\.chatMedia`; URLCache underneath honors the hub's immutable ETag). +/// Tap opens a simple full-screen viewer. Without a loader (previews/tests) +/// the card degrades to a filename placeholder. +struct GeneratedImageBlockView: View { + let block: GeneratedImageBlock + + @Environment(\.chatMedia) private var media + @State private var image: UIImage? + @State private var failed = false + @State private var viewerOpen = false + + var body: some View { + Group { + if media == nil || failed { + placeholder + } else if let image { + Button { + viewerOpen = true + } label: { + Image(uiImage: image) + .resizable() + .scaledToFit() + .frame(maxHeight: 360) + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + } + .buttonStyle(.plain) + } else { + loadingFrame + } + } + .task(id: block.imageId) { + guard let media, image == nil else { return } + if let loaded = await media.image(for: block.imageId) { + image = loaded + } else { + failed = true + } + } + .fullScreenCover(isPresented: $viewerOpen) { + ImageViewer(image: image, title: block.fileName) + } + } + + private var placeholder: some View { + Label(block.fileName, systemImage: "photo") + .font(.caption) + .foregroundStyle(.secondary) + .padding(.vertical, 4) + } + + private var loadingFrame: some View { + RoundedRectangle(cornerRadius: 12, style: .continuous) + .fill(Color.secondary.opacity(0.1)) + .frame(height: 160) + .overlay { + ProgressView() + } + } +} + +/// Minimal full-screen viewer: dark backdrop, fit-scaled image, tap or the +/// close button dismisses. (Pinch-zoom lands with the files feature.) +private struct ImageViewer: View { + let image: UIImage? + let title: String + + @Environment(\.dismiss) private var dismiss + + var body: some View { + ZStack(alignment: .topTrailing) { + Color.black.ignoresSafeArea() + if let image { + Image(uiImage: image) + .resizable() + .scaledToFit() + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding(8) + } else { + Text(title) + .foregroundStyle(.white) + } + Button { + dismiss() + } label: { + Image(systemName: "xmark.circle.fill") + .font(.title2) + .foregroundStyle(.white.opacity(0.8)) + .padding(16) + } + } + .onTapGesture { + dismiss() + } + } +} diff --git a/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift b/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift new file mode 100644 index 00000000..8660bedc --- /dev/null +++ b/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift @@ -0,0 +1,163 @@ +import HapiProtocol +import HapiUI +import SwiftUI + +// MARK: - User bubble + +/// Operator prompt: right-aligned bubble. Whitespace is preserved and the +/// text is NOT rendered as markdown — matching the web user bubble and the +/// Android port. Attachments render as chips; a restored failed optimistic +/// row gets a "Not delivered" hint. +struct UserTextBlockView: View { + let block: UserTextBlock + + var body: some View { + HStack(alignment: .bottom, spacing: 0) { + Spacer(minLength: 48) + VStack(alignment: .trailing, spacing: 2) { + VStack(alignment: .leading, spacing: 8) { + Text(block.text) + .font(.subheadline) + .textSelection(.enabled) + if let attachments = block.attachments, !attachments.isEmpty { + VStack(alignment: .leading, spacing: 4) { + ForEach(attachments, id: \.id) { attachment in + AttachmentChip(attachment: attachment) + } + } + } + } + .padding(.horizontal, 14) + .padding(.vertical, 10) + .background(.tint.opacity(0.16)) + .clipShape( + .rect( + topLeadingRadius: 16, + bottomLeadingRadius: 16, + bottomTrailingRadius: 4, + topTrailingRadius: 16 + ) + ) + if block.status == "failed" { + Text("Not delivered") + .font(.caption2) + .foregroundStyle(.red) + .padding(.trailing, 4) + } + } + } + } +} + +private struct AttachmentChip: View { + let attachment: AttachmentMetadata + + var body: some View { + Label( + attachment.filename, + systemImage: attachment.mimeType.hasPrefix("image/") ? "photo" : "paperclip" + ) + .font(.caption) + .lineLimit(1) + .padding(.horizontal, 8) + .padding(.vertical, 4) + .background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8)) + } +} + +// MARK: - Agent prose + +/// Assistant prose: full-width markdown through the shared M2e renderer. +struct AgentTextBlockView: View { + let block: AgentTextBlock + + var body: some View { + MarkdownView(markdown: block.text) + .frame(maxWidth: .infinity, alignment: .leading) + } +} + +/// Extended thinking: collapsed to a subdued one-liner, expanding in place to +/// the full reasoning markdown (still subdued — it is meta-content). +struct AgentReasoningBlockView: View { + let block: AgentReasoningBlock + @State private var expanded = false + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + Button { + withAnimation(.easeInOut(duration: 0.15)) { + expanded.toggle() + } + } label: { + Label( + expanded ? "Reasoning" : "Reasoning…", + systemImage: expanded ? "chevron.down" : "chevron.right" + ) + .font(.caption) + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + if expanded { + MarkdownView(markdown: block.text) + .opacity(0.75) + .padding(.leading, 8) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } +} + +// MARK: - Event rows + +/// Compact centered status row for the `'event'` family (limits, compaction, +/// switches, errors, turn duration, …); wording via `eventPresentation`. +struct AgentEventBlockView: View { + let block: AgentEventBlock + + var body: some View { + let presentation = eventPresentation(block.event) + Text([presentation.icon, presentation.text].compactMap { $0 }.joined(separator: " ")) + .font(.caption) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .lineLimit(3) + .frame(maxWidth: .infinity) + .padding(.horizontal, 24) + .padding(.vertical, 2) + } +} + +// MARK: - CLI output + +/// `` / slash-command echo: terminal-styled monospace +/// panel (no header chrome — this is transcript, not a code sample). +struct CliOutputBlockView: View { + let block: CliOutputBlock + + var body: some View { + TerminalTextView(text: block.text) + } +} + +/// Shared terminal-look panel (cli output + tool stdout). +struct TerminalTextView: View { + let text: String + var isError = false + + @Environment(\.hapiTheme) private var theme + + var body: some View { + ScrollView(.horizontal, showsIndicators: false) { + Text(text) + .font(.system(size: 12, design: .monospaced)) + .foregroundStyle(isError ? AnyShapeStyle(theme.danger) : AnyShapeStyle(theme.textPrimary)) + .textSelection(.enabled) + .padding(.horizontal, 12) + .padding(.vertical, 8) + } + .frame(maxWidth: .infinity, alignment: .leading) + .background(theme.codeBackground) + .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) + } +} diff --git a/ios/Hapi/Features/Chat/Blocks/ToolBodies.swift b/ios/Hapi/Features/Chat/Blocks/ToolBodies.swift new file mode 100644 index 00000000..433fcccc --- /dev/null +++ b/ios/Hapi/Features/Chat/Blocks/ToolBodies.swift @@ -0,0 +1,368 @@ +import HapiProtocol +import HapiUI +import SwiftUI + +/// Expanded tool-card body: input rendering per tool kind + the result +/// section (the read-only slice of `web/src/components/ToolCard/views/`, +/// via the Android `ToolBodies` port): +/// +/// - terminal family → command as a bash code block, stdout/stderr +/// terminal-styled; +/// - `Edit`/`MultiEdit` structured edits → before/after code blocks; +/// - `Write` → the written content as a code block; +/// - `CodexDiff` (and any input/result that parses as a unified diff) → +/// `DiffTextView`; +/// - `TodoWrite`/`update_plan` → checklist rows; +/// - Ask/RequestUserInput → questions + options, read-only; +/// - anything else → pretty-printed JSON input, then the generic result. +struct ToolCallBody: View { + let tool: ChatToolCall + let basePath: String? + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + ToolInputSection(tool: tool, basePath: basePath) + ToolResultSection(tool: tool) + } + } +} + +// MARK: - Input + +private let terminalToolNames: Set = [ + "Bash", "CodexBash", "shell_command", "run_shell_command", +] + +private struct ToolInputSection: View { + let tool: ChatToolCall + let basePath: String? + + var body: some View { + let input = tool.input + if terminalToolNames.contains(tool.name) { + if let command = chatTerminalCommand(input) { + CodeBlockView(language: "bash", code: command) + } + } else if tool.name == "Edit" { + if let old = chatInputString(input, ["old_string"]), + let new = chatInputString(input, ["new_string"]) { + BeforeAfterView( + old: old, + new: new, + language: languageForPath(chatInputString(input, ["file_path", "path"])) + ) + } else { + GenericJSONInput(input: input) + } + } else if tool.name == "MultiEdit" { + multiEditBody(input) + } else if tool.name == "Write" { + if let content = chatInputString(input, ["content", "text"]) { + CodeBlockView( + language: languageForPath(chatInputString(input, ["file_path", "path"])), + code: content + ) + } else { + GenericJSONInput(input: input) + } + } else if tool.name == "CodexDiff" { + if let unified = chatInputString(input, ["unified_diff"]), + let files = tryParseDiff(unified) { + DiffTextView(files: files) + } else { + GenericJSONInput(input: input) + } + } else if tool.name == "TodoWrite" || tool.name == "update_plan" { + let items = checklistItems(input) + if !items.isEmpty { + VStack(alignment: .leading, spacing: 2) { + ForEach(Array(items.enumerated()), id: \.offset) { _, item in + Text("\(item.glyph) \(item.text)") + .font(.footnote) + } + } + } else { + GenericJSONInput(input: input) + } + } else if isAskUserQuestionToolName(tool.name) || isRequestUserInputToolName(tool.name) { + QuestionsReadOnlyView(input: input) + } else if tool.name == "Read" || tool.name == "NotebookRead" || tool.name == "LS" { + // The title already carries the path; nothing else worth echoing. + if let path = chatInputString(input, ["file_path", "path", "notebook_path"]) { + SectionLabel(text: chatDisplayPath(path, basePath: basePath)) + } + } else { + GenericJSONInput(input: input) + } + } + + @ViewBuilder + private func multiEditBody(_ input: JSONValue?) -> some View { + let language = languageForPath(chatInputString(input, ["file_path", "path"])) + if let edits = input?[chatKey: "edits"]?.chatArray { + VStack(alignment: .leading, spacing: 8) { + ForEach(Array(edits.enumerated()), id: \.offset) { index, edit in + if let old = chatInputString(edit, ["old_string"]), + let new = chatInputString(edit, ["new_string"]) { + VStack(alignment: .leading, spacing: 6) { + if edits.count > 1 { + SectionLabel(text: "Edit \(index + 1)/\(edits.count)") + } + BeforeAfterView(old: old, new: new, language: language) + } + } + } + } + } else { + GenericJSONInput(input: input) + } + } +} + +private struct BeforeAfterView: View { + let old: String + let new: String + let language: String? + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + SectionLabel(text: "Before") + CodeBlockView(language: language, code: old.isEmpty ? "(empty)" : old) + SectionLabel(text: "After") + CodeBlockView(language: language, code: new.isEmpty ? "(empty)" : new) + } + } +} + +private struct GenericJSONInput: View { + let input: JSONValue? + + var body: some View { + switch input { + case nil, .some(.null): + EmptyView() + case .some(.string(let text)): + CodeBlockView(language: nil, code: text) + case .some(let value): + CodeBlockView(language: "json", code: chatPrettyJSON(value)) + } + } +} + +/// Questions + options, read-only (answer flows land in M3b). +private struct QuestionsReadOnlyView: View { + let input: JSONValue? + + var body: some View { + let questions = input?[chatKey: "questions"]?.chatArray ?? [] + VStack(alignment: .leading, spacing: 8) { + ForEach(Array(questions.enumerated()), id: \.offset) { _, entry in + if let question = entry.chatObject { + VStack(alignment: .leading, spacing: 2) { + if let header = question["header"]?.chatString { + Text(header) + .font(.footnote.weight(.semibold)) + } + if let text = question["question"]?.chatString { + Text(text) + .font(.subheadline) + } + ForEach(Array(optionLabels(question).enumerated()), id: \.offset) { _, label in + Text("◦ \(label)") + .font(.footnote) + .foregroundStyle(.secondary) + .padding(.leading, 8) + .padding(.top, 2) + } + } + } + } + } + } + + private func optionLabels(_ question: [String: JSONValue]) -> [String] { + guard let options = question["options"]?.chatArray else { return [] } + return options.compactMap { option in + if let text = option.chatString { return text } + if let object = option.chatObject { + return object["label"]?.chatString ?? object["value"]?.chatString + } + return nil + } + } +} + +// MARK: - Result + +private let resultRenderCap = 20_000 + +private struct ToolResultSection: View { + let tool: ChatToolCall + + var body: some View { + if let result = tool.result, result != .null, + let rendering = resultRendering(result) { + VStack(alignment: .leading, spacing: 4) { + SectionLabel(text: tool.state == .error ? "Result · error" : "Result") + switch rendering { + case .diffs(let files): + DiffTextView(files: files) + case .terminal(let text): + TerminalTextView(text: text, isError: tool.state == .error) + case .json(let pretty): + CodeBlockView(language: "json", code: pretty) + } + } + } + } +} + +/// How a tool result renders: parsed diff > extracted text > pretty JSON. +private enum ResultRendering { + case diffs([DiffFile]) + case terminal(String) + case json(String) +} + +private func resultRendering(_ result: JSONValue) -> ResultRendering? { + if let text = extractResultText(result) { + if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + return nil + } + if let files = tryParseDiff(text) { + return .diffs(files) + } + return .terminal(String(text.prefix(resultRenderCap))) + } + return .json(String(chatPrettyJSON(result).prefix(resultRenderCap))) +} + +/// Text of the common result shapes: plain string; `{stdout, stderr}`; +/// Claude-style `[{type: "text", text}]` arrays (or the same under +/// `content`). Nil → not text-like, render as JSON. +func extractResultText(_ result: JSONValue) -> String? { + switch result { + case .string(let text): + return text + case .array(let entries): + var texts: [String] = [] + for entry in entries { + guard let object = entry.chatObject, + object["type"]?.chatString == "text", + let text = object["text"]?.chatString else { + return nil + } + texts.append(text) + } + return texts.joined(separator: "\n") + case .object(let object): + let stdout = object["stdout"]?.chatString + let stderr = object["stderr"]?.chatString + if stdout != nil || stderr != nil { + var parts: [String] = [] + if let out = stdout?.trimmedTrailing(), !out.isEmpty { + parts.append(out) + } + if let err = stderr?.trimmedTrailing(), !err.isEmpty { + parts.append("stderr:\n\(err)") + } + return parts.joined(separator: "\n\n") + } + if let content = object["content"] { + if case .array = content { + return extractResultText(content) + } + if let text = content.chatString { + return text + } + } + return nil + default: + return nil + } +} + +extension String { + fileprivate func trimmedTrailing() -> String { + var value = Substring(self) + while let last = value.last, last.isWhitespace || last.isNewline { + value = value.dropLast() + } + return String(value) + } +} + +// MARK: - Shared helpers + +/// Parse `text` as a unified diff when it plausibly is one (the same marker +/// heuristics as the Android port, over the HapiUI parser). +func tryParseDiff(_ text: String) -> [DiffFile]? { + guard hasDiffMarkers(text) else { return nil } + let files = UnifiedDiffParser.parse(text) + guard !files.isEmpty, files.contains(where: { !$0.hunks.isEmpty || $0.isBinary }) else { + return nil + } + return files +} + +private func hasDiffMarkers(_ text: String) -> Bool { + var sawHunk = false + var sawHeader = false + for rawLine in text.split(separator: "\n", omittingEmptySubsequences: false) { + if !sawHunk, rawLine.hasPrefix("@@ -"), rawLine.dropFirst(4).first?.isNumber == true { + sawHunk = true + } + if !sawHeader, rawLine.hasPrefix("diff --git ") || rawLine.hasPrefix("--- ") { + sawHeader = true + } + if sawHunk && sawHeader { + return true + } + } + return false +} + +private let extensionLanguages: [String: String] = [ + "kt": "kotlin", "kts": "kotlin", "java": "java", "ts": "typescript", + "tsx": "typescript", "js": "javascript", "jsx": "javascript", "py": "python", + "rb": "ruby", "go": "go", "rs": "rust", "swift": "swift", "c": "c", + "h": "c", "cpp": "cpp", "cc": "cpp", "cs": "csharp", "sh": "shell", + "bash": "shell", "json": "json", "yml": "yaml", "yaml": "yaml", + "xml": "xml", "html": "html", "css": "css", "md": "markdown", "sql": "sql", +] + +func languageForPath(_ path: String?) -> String? { + guard let path, let dot = path.lastIndex(of: "."), dot != path.startIndex else { return nil } + let ext = path[path.index(after: dot)...].lowercased() + guard !ext.isEmpty, !ext.contains("/") else { return nil } + return extensionLanguages[ext] +} + +/// `(glyph, text)` rows for TodoWrite `todos` / update_plan `plan` items. +func checklistItems(_ input: JSONValue?) -> [(glyph: String, text: String)] { + guard let object = input?.chatObject else { return [] } + guard let array = (object["todos"] ?? object["plan"])?.chatArray else { return [] } + return array.compactMap { entry in + guard let item = entry.chatObject else { return nil } + guard let content = item["content"]?.chatString ?? item["step"]?.chatString else { + return nil + } + let glyph: String + switch item["status"]?.chatString { + case "completed", "complete", "done": glyph = "☑" + case "in_progress": glyph = "◐" + default: glyph = "☐" + } + return (glyph: glyph, text: content) + } +} + +struct SectionLabel: View { + let text: String + + var body: some View { + Text(text) + .font(.caption2) + .foregroundStyle(.secondary) + } +} diff --git a/ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift b/ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift new file mode 100644 index 00000000..ae31731e --- /dev/null +++ b/ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift @@ -0,0 +1,200 @@ +import HapiProtocol +import HapiUI +import SwiftUI + +/// One tool invocation (web `ToolCard`): collapsed header row — icon, title, +/// subtitle, status — expanding to the per-tool body (`ToolCallBody`), the +/// read-only permission state, and nested children (sidechain transcript +/// behind an indent rail). Cards with a pending permission start expanded +/// and carry the "awaiting approval" banner (actions land in M3b). +struct ToolCallBlockView: View { + let block: ToolCallBlock + let basePath: String? + + @State private var expanded: Bool + @State private var childrenOpen: Bool + @Environment(\.hapiTheme) private var theme + + init(block: ToolCallBlock, basePath: String?) { + self.block = block + self.basePath = basePath + let pending = block.tool.permission?.status == .pending + _expanded = State(initialValue: pending) + _childrenOpen = State(initialValue: pending) + } + + var body: some View { + let presentation = toolCardPresentation(block.tool, basePath: basePath) + VStack(alignment: .leading, spacing: 0) { + headerRow(presentation) + if let permission = block.tool.permission { + PermissionStateRow(permission: permission) + } + if expanded { + ToolCallBody(tool: block.tool, basePath: basePath) + .padding(.horizontal, 10) + .padding(.bottom, 10) + } + if !block.children.isEmpty { + childrenSection + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .background(theme.surface) + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + } + + private func headerRow(_ presentation: ToolCardPresentation) -> some View { + Button { + withAnimation(.easeInOut(duration: 0.15)) { + expanded.toggle() + } + } label: { + HStack(spacing: 8) { + Image(systemName: presentation.icon) + .font(.footnote) + .foregroundStyle(.secondary) + .frame(width: 18) + VStack(alignment: .leading, spacing: 1) { + Text(presentation.title) + .font(.subheadline) + .foregroundStyle(theme.textPrimary) + .lineLimit(1) + if let subtitle = presentation.subtitle { + Text(subtitle) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + Spacer(minLength: 8) + ToolStatusIndicator(state: block.tool.state) + } + .padding(.horizontal, 10) + .padding(.vertical, 8) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + + /// Sidechain children, nested behind an indent rail; collapsed to a + /// count row. + private var childrenSection: some View { + VStack(alignment: .leading, spacing: 0) { + Button { + withAnimation(.easeInOut(duration: 0.15)) { + childrenOpen.toggle() + } + } label: { + Label( + "\(block.children.count) agent step\(block.children.count == 1 ? "" : "s")", + systemImage: childrenOpen ? "chevron.down" : "chevron.right" + ) + .font(.caption) + .foregroundStyle(.secondary) + .padding(.horizontal, 10) + .padding(.vertical, 6) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + if childrenOpen { + HStack(alignment: .top, spacing: 10) { + RoundedRectangle(cornerRadius: 1) + .fill(theme.divider) + .frame(width: 2) + VStack(alignment: .leading, spacing: 8) { + ForEach(block.children, id: \.id) { child in + ChatSubBlockView(block: child, basePath: basePath) + } + } + } + .padding(.leading, 12) + .padding(.trailing, 8) + .padding(.bottom, 10) + } + } + } +} + +// MARK: - Status + +struct ToolStatusIndicator: View { + let state: ToolCallState + + var body: some View { + switch state { + case .running: + ProgressView() + .controlSize(.small) + case .pending: + StatusChip(text: "pending", tint: .secondary) + case .error: + StatusChip(text: "error", tint: .red) + case .completed: + Image(systemName: "checkmark") + .font(.caption) + .foregroundStyle(.secondary) + } + } +} + +private struct StatusChip: View { + let text: String + let tint: Color + + var body: some View { + Text(text) + .font(.caption2) + .foregroundStyle(tint) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(tint.opacity(0.14), in: RoundedRectangle(cornerRadius: 6)) + } +} + +// MARK: - Permission (read-only) + +/// Read-only permission verdict: highlighted banner while pending (approval +/// actions are M3b), subdued line once decided. +private struct PermissionStateRow: View { + let permission: ToolPermission + + var body: some View { + switch permission.status { + case .pending: + VStack(alignment: .leading, spacing: 2) { + Label("Awaiting approval", systemImage: "hourglass") + .font(.footnote.weight(.semibold)) + Text("Respond from the hub web app — in-app approval arrives in the next milestone.") + .font(.caption2) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 10) + .padding(.vertical, 6) + .background(.orange.opacity(0.18)) + .foregroundStyle(.orange) + case .approved: + PermissionLine(text: "✓ Approved" + (permission.mode.map { " · \($0)" } ?? "")) + case .denied: + PermissionLine( + text: "✕ Denied" + (permission.reason.map { " · \($0)" } ?? ""), + isError: true + ) + case .canceled: + PermissionLine(text: "— Canceled") + } + } +} + +private struct PermissionLine: View { + let text: String + var isError = false + + var body: some View { + Text(text) + .font(.caption2) + .foregroundStyle(isError ? AnyShapeStyle(.red) : AnyShapeStyle(.secondary)) + .padding(.horizontal, 10) + .padding(.bottom, 6) + } +} diff --git a/ios/Hapi/Features/Chat/Blocks/ToolCardPresentation.swift b/ios/Hapi/Features/Chat/Blocks/ToolCardPresentation.swift new file mode 100644 index 00000000..2d002582 --- /dev/null +++ b/ios/Hapi/Features/Chat/Blocks/ToolCardPresentation.swift @@ -0,0 +1,504 @@ +import Foundation +import HapiProtocol + +/// Collapsed tool-card header: SF Symbol + title + optional subtitle. Port of +/// the presentation registry in `web/src/components/ToolCard/knownTools.tsx` +/// (read-only subset), matching the Android port's `ToolCardPresentation` +/// line for line so the three clients label tools identically. Kept in the +/// app layer — `HapiProtocol.ToolPresentation` stays the thin +/// fixture-adjacent helper it is. +struct ToolCardPresentation: Equatable { + /// SF Symbol name. + var icon: String + var title: String + var subtitle: String? +} + +private enum ToolIcon { + static let terminal = "terminal" + static let read = "eye" + static let search = "magnifyingglass" + static let edit = "pencil" + static let web = "globe" + static let agent = "paperplane" + static let question = "questionmark.circle" + static let plan = "list.clipboard" + static let idea = "lightbulb" + static let puzzle = "puzzlepiece.extension" + static let message = "bubble.left" + static let team = "person.2" + static let warning = "exclamationmark.triangle" + static let wrench = "wrench.and.screwdriver" +} + +// MARK: - Path display + +/// Strip the session root so paths read workspace-relative +/// (web `resolveDisplayPath`). +func chatDisplayPath(_ path: String, basePath: String?) -> String { + guard let basePath, !basePath.isEmpty else { return path } + let root = trimTrailingSlashes(basePath) + if path == root { return "." } + if path.hasPrefix(root + "/") { + return String(path.dropFirst(root.count + 1)) + } + return path +} + +private func trimTrailingSlashes(_ path: String) -> String { + var value = path + while value.hasSuffix("/") { + value = String(value.dropLast()) + } + return value +} + +private func chatBasename(_ path: String) -> String { + let trimmed = trimTrailingSlashes(path) + return trimmed.split(separator: "/").last.map(String.init) ?? trimmed +} + +// MARK: - Terminal parsing (web `formatTerminalCommandTitle`) + +private let commandsWithSubcommand: Set = [ + "git", "bun", "npm", "pnpm", "yarn", "docker", "systemctl", "cargo", "go", +] + +private func isAssignment(_ part: String?) -> Bool { + guard let part, let first = part.first, + first == "_" || first.isLetter else { return false } + var seenEquals = false + for (index, character) in part.enumerated() { + if character == "=" { + seenEquals = index > 0 + break + } + let valid = character == "_" || character.isLetter || (index > 0 && character.isNumber) + if !valid { return false } + } + return seenEquals +} + +private func hasAmbiguousShellSyntax(_ command: String) -> Bool { + command.contains(where: { ";&|<>$`(){}\n\r".contains($0) }) +} + +/// The leading executable(+subcommand) of a simple command; nil when the +/// command carries shell syntax that makes the guess ambiguous. +func formatTerminalCommandTitle(_ command: String?) -> String? { + guard let command, !command.isEmpty, !hasAmbiguousShellSyntax(command) else { return nil } + + let parts = command + .trimmingCharacters(in: .whitespacesAndNewlines) + .split(whereSeparator: { $0.isWhitespace }) + .map(String.init) + var index = 0 + func part(_ offset: Int) -> String? { + let position = index + offset + return position >= 0 && position < parts.count ? parts[position] : nil + } + + while isAssignment(part(0)) { index += 1 } + if part(0) == "env" { + index += 1 + while part(0) == "-i" || part(0) == "--ignore-environment" || isAssignment(part(0)) { + index += 1 + } + } + if part(0) == "sudo" { + index += 1 + while ["-n", "--non-interactive", "-E", "--preserve-env"].contains(part(0) ?? "") { + index += 1 + } + } + if part(0)?.hasPrefix("-") == true { return nil } + + guard let head = part(0) else { return nil } + let executable = chatBasename(head) + guard !executable.isEmpty else { return nil } + + guard let subcommand = part(1), !subcommand.hasPrefix("-"), + commandsWithSubcommand.contains(executable) else { + return executable + } + if ["bun", "npm", "pnpm", "yarn"].contains(executable), subcommand == "run" { + if let script = part(2), !script.hasPrefix("-") { + return "\(executable) run \(script)" + } + return "\(executable) run" + } + if executable == "docker", subcommand == "compose" { + if let action = part(2), !action.hasPrefix("-") { + return "docker compose \(action)" + } + return "docker compose" + } + return "\(executable) \(subcommand)" +} + +/// The command string, joining Codex-style `command: string[]` arrays. +func chatTerminalCommand(_ input: JSONValue?) -> String? { + if let command = chatInputString(input, ["command", "cmd"]) { + return command + } + guard let array = input?[chatKey: "command"]?.chatArray else { return nil } + let parts = array.compactMap { $0.chatString }.filter { !$0.isEmpty } + return parts.isEmpty ? nil : parts.joined(separator: " ") +} + +private func terminalTitle(_ input: JSONValue?, description: String?) -> String { + let command = chatTerminalCommand(input) + if let description, description != command { + return description + } + return formatTerminalCommandTitle(command) ?? description ?? "Terminal" +} + +private func terminalSubtitle(_ input: JSONValue?, description: String?) -> String? { + let command = chatTerminalCommand(input) + return command == terminalTitle(input, description) ? nil : command +} + +// MARK: - Questions + +private func questionTitle(_ input: JSONValue?) -> String { + let questions = input?[chatKey: "questions"]?.chatArray ?? [] + if questions.count > 1 { return "\(questions.count) Questions" } + let header = questions.first?[chatKey: "header"]?.chatString? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return header.isEmpty ? "Question" : header +} + +private func questionSubtitle(_ input: JSONValue?) -> String? { + let questions = input?[chatKey: "questions"]?.chatArray ?? [] + let question = questions.first?[chatKey: "question"]?.chatString? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if questions.count > 1, !question.isEmpty { + return chatTruncate(question, 100) + " (+\(questions.count - 1) more)" + } + return question.isEmpty ? nil : chatTruncate(question, 120) +} + +// MARK: - MCP names + +private func snakeToTitle(_ value: String) -> String { + value.split(separator: "_") + .filter { !$0.isEmpty } + .map { $0.lowercased().prefix(1).uppercased() + $0.lowercased().dropFirst() } + .joined(separator: " ") +} + +private func mcpTitle(_ toolName: String) -> String { + let withoutPrefix = toolName.hasPrefix("mcp__") + ? String(toolName.dropFirst("mcp__".count)) + : toolName + let parts = withoutPrefix.components(separatedBy: "__") + if parts.count >= 2 { + let rest = parts.dropFirst().joined(separator: "_") + return "MCP: \(snakeToTitle(parts[0])) \(snakeToTitle(rest))" + } + return "MCP: \(snakeToTitle(withoutPrefix))" +} + +// MARK: - Entry point + +func toolCardPresentation(_ tool: ChatToolCall, basePath: String?) -> ToolCardPresentation { + let input = tool.input + let name = tool.name + let description = tool.description + + if name.hasPrefix("mcp__") { + return ToolCardPresentation(icon: ToolIcon.puzzle, title: mcpTitle(name), subtitle: nil) + } + if isAskUserQuestionToolName(name) || isRequestUserInputToolName(name) { + return ToolCardPresentation( + icon: ToolIcon.question, + title: questionTitle(input), + subtitle: questionSubtitle(input) + ) + } + + func filePathTitle(_ keys: [String], fallback: String) -> String { + chatInputString(input, keys).map { chatDisplayPath($0, basePath: basePath) } ?? fallback + } + + switch name { + case "Bash", "CodexBash", "shell_command", "run_shell_command": + // A CodexBash single parsed read renders as the file it reads. + if name == "CodexBash", + let parsed = input?[chatKey: "parsed_cmd"]?.chatArray, + parsed.count == 1, + parsed[0][chatKey: "type"]?.chatString == "read", + let file = parsed[0][chatKey: "name"]?.chatString { + return ToolCardPresentation( + icon: ToolIcon.read, + title: chatDisplayPath(file, basePath: basePath), + subtitle: terminalSubtitle(input, description: description) + ) + } + return ToolCardPresentation( + icon: ToolIcon.terminal, + title: terminalTitle(input, description: description), + subtitle: terminalSubtitle(input, description: description) + ) + + case "Read": + return ToolCardPresentation( + icon: ToolIcon.read, + title: filePathTitle(["file_path", "path", "file"], fallback: "Read file"), + subtitle: nil + ) + + case "NotebookRead": + return ToolCardPresentation( + icon: ToolIcon.read, + title: filePathTitle(["notebook_path"], fallback: "Read notebook"), + subtitle: nil + ) + + case "Edit": + return ToolCardPresentation( + icon: ToolIcon.edit, + title: filePathTitle(["file_path", "path"], fallback: "Edit file"), + subtitle: nil + ) + + case "MultiEdit": + guard let file = chatInputString(input, ["file_path", "path"]) else { + return ToolCardPresentation(icon: ToolIcon.edit, title: "Edit file", subtitle: nil) + } + let count = input?[chatKey: "edits"]?.chatArray?.count ?? 0 + let path = chatDisplayPath(file, basePath: basePath) + return ToolCardPresentation( + icon: ToolIcon.edit, + title: count > 1 ? "\(path) (\(count) edits)" : path, + subtitle: nil + ) + + case "Write": + let content = chatInputString(input, ["content", "text"]) + let subtitle = content.map { text -> String in + let lines = text.split(separator: "\n", omittingEmptySubsequences: false).count + return lines > 1 ? "\(lines) lines" : "\(text.count) chars" + } + return ToolCardPresentation( + icon: ToolIcon.edit, + title: filePathTitle(["file_path", "path"], fallback: "Write file"), + subtitle: subtitle + ) + + case "NotebookEdit": + return ToolCardPresentation( + icon: ToolIcon.edit, + title: filePathTitle(["notebook_path"], fallback: "Edit notebook"), + subtitle: chatInputString(input, ["edit_mode"]).map { "mode: \($0)" } + ) + + case "Glob": + return ToolCardPresentation( + icon: ToolIcon.search, + title: chatInputString(input, ["pattern"]) ?? "Search files", + subtitle: nil + ) + + case "Grep": + let pattern = chatInputString(input, ["pattern"]) + return ToolCardPresentation( + icon: ToolIcon.search, + title: pattern.map { "grep(pattern: \($0))" } ?? "Search content", + subtitle: nil + ) + + case "LS": + return ToolCardPresentation( + icon: ToolIcon.search, + title: filePathTitle(["path"], fallback: "List files"), + subtitle: nil + ) + + case "WebFetch": + guard let url = chatInputString(input, ["url"]) else { + return ToolCardPresentation(icon: ToolIcon.web, title: "Web fetch", subtitle: nil) + } + let host = URL(string: url)?.host ?? url + return ToolCardPresentation(icon: ToolIcon.web, title: host, subtitle: url) + + case "WebSearch": + let query = chatInputString(input, ["query"]) + return ToolCardPresentation( + icon: ToolIcon.web, + title: query ?? "Web search", + subtitle: query.map { chatTruncate($0, 80) } + ) + + case "Task", "Agent": + let inputName = chatInputString(input, ["name"]) + let teamName = chatInputString(input, ["team_name"]) + let title: String + if name == "Task", let inputName, teamName != nil { + title = "Agent: \(inputName)" + } else { + title = chatInputString(input, ["description"]) + ?? (name == "Task" ? "Task" : "Launch Agent") + } + let subtitle = chatInputString(input, ["prompt"]).map { chatTruncate($0, 120) } + ?? chatInputString(input, ["subagent_type"]) + return ToolCardPresentation(icon: ToolIcon.agent, title: title, subtitle: subtitle) + + case "CodexAgent", "spawn_agent", "resume_agent", "wait_agent", "close_agent", "interrupt_agent": + let title: String + switch name { + case "spawn_agent": title = "Spawn agent" + case "resume_agent": title = "Resume agent" + case "wait_agent": title = "Wait for agent" + case "close_agent": title = "Close agent" + case "interrupt_agent": title = "Interrupt agent" + default: title = "Agent" + } + let prompt = chatInputString(input, ["prompt", "summary"]) + return ToolCardPresentation( + icon: ToolIcon.agent, + title: title, + subtitle: prompt.map { chatTruncate($0, 120) } + ) + + case "SendMessage", "send_input", "send_message", "followup_task": + let recipient = chatInputString(input, ["recipient"]) + let messageType = chatInputString(input, ["type"]) + let title: String + if messageType == "broadcast" { + title = "Broadcast" + } else if messageType == "shutdown_request" { + title = "Shutdown: \(recipient ?? "agent")" + } else if messageType == "shutdown_response" { + title = "Shutdown Response" + } else if let recipient { + title = "Message: \(recipient)" + } else { + title = "Message agent" + } + let summary = chatInputString(input, ["summary"]) + return ToolCardPresentation( + icon: ToolIcon.message, + title: title, + subtitle: summary.map { chatTruncate($0, 120) } + ) + + case "list_agents": + return ToolCardPresentation(icon: ToolIcon.team, title: "List agents", subtitle: nil) + + case "TeamCreate": + let teamName = chatInputString(input, ["team_name"]) + return ToolCardPresentation( + icon: ToolIcon.team, + title: teamName.map { "Team: \($0)" } ?? "Create Team", + subtitle: chatInputString(input, ["description"]) + ) + + case "TeamDelete": + return ToolCardPresentation(icon: ToolIcon.team, title: "Delete Team", subtitle: nil) + + case "TodoWrite": + return ToolCardPresentation(icon: ToolIcon.idea, title: "Todo list", subtitle: nil) + + case "update_plan": + return ToolCardPresentation(icon: ToolIcon.plan, title: "Plan", subtitle: nil) + + case "ExitPlanMode", "exit_plan_mode": + return ToolCardPresentation(icon: ToolIcon.plan, title: "Plan proposal", subtitle: nil) + + case "Skill": + let skill = chatInputString(input, ["skill"]) + return ToolCardPresentation( + icon: ToolIcon.puzzle, + title: skill.map { "Skill: \($0)" } ?? "Skill", + subtitle: nil + ) + + case "CodexReasoning": + return ToolCardPresentation( + icon: ToolIcon.idea, + title: chatInputString(input, ["title"]) ?? "Reasoning", + subtitle: nil + ) + + case "CodexPermission": + let permissionTool = chatInputString(input, ["tool"]) + return ToolCardPresentation( + icon: ToolIcon.question, + title: permissionTool.map { "Permission: \($0)" } ?? "Permission request", + subtitle: chatInputString(input, ["message", "command"]) + ) + + case "CodexPatch": + let files = input?[chatKey: "changes"]?.chatObject.map { Array($0.keys).sorted() } ?? [] + let subtitle = files.first.map { first -> String in + let display = chatBasename(chatDisplayPath(first, basePath: basePath)) + return files.count > 1 ? "\(display) (+\(files.count - 1))" : display + } + return ToolCardPresentation(icon: ToolIcon.edit, title: "Apply changes", subtitle: subtitle) + + case "CodexDiff": + let unified = chatInputString(input, ["unified_diff"]) + let subtitle = unified? + .split(separator: "\n", omittingEmptySubsequences: false) + .first(where: { $0.hasPrefix("+++ ") }) + .map { line -> String in + var value = String(line.dropFirst("+++ ".count)) + if value.hasPrefix("b/") { value = String(value.dropFirst(2)) } + return chatBasename(value) + } + return ToolCardPresentation(icon: ToolIcon.edit, title: "Diff", subtitle: subtitle) + + case "AgyTaskLog": + let task = chatInputString(input, ["task"]) + return ToolCardPresentation( + icon: ToolIcon.message, + title: task.map { "\($0) log" } ?? "Inspecting task log", + subtitle: nil + ) + + case "AgyAsyncTask": + return ToolCardPresentation( + icon: ToolIcon.plan, + title: description ?? "Background task", + subtitle: nil + ) + + case "AgyError": + return ToolCardPresentation(icon: ToolIcon.warning, title: description ?? "Error", subtitle: nil) + + default: + break + } + + // Generic fallback (web `getToolPresentation` tail): promote a semantic + // label when an ACP agent's title is the verbatim argument. + let filePath = chatInputString(input, ["file_path", "path", "filePath", "file"]) + let command = chatInputString(input, ["command", "cmd"]) + let pattern = chatInputString(input, ["pattern"]) + let url = chatInputString(input, ["url"]) + let query = chatInputString(input, ["query"]) + let nameInput = chatInputString(input, ["name"]) + let subtitle = filePath ?? command ?? pattern ?? url ?? query ?? nameInput + + var title = description ?? name + if let subtitle, subtitle == title { + if filePath != nil { + title = "Read file" + } else if command != nil { + title = "Run shell" + } else if pattern != nil { + title = "Search" + } else if url != nil { + title = "Open URL" + } else if query != nil { + title = "Query" + } + } + return ToolCardPresentation( + icon: ToolIcon.wrench, + title: title, + subtitle: subtitle.flatMap { $0 == title ? nil : chatTruncate($0, 80) } + ) +} diff --git a/ios/Hapi/Features/Chat/Blocks/ToolGroupBlockView.swift b/ios/Hapi/Features/Chat/Blocks/ToolGroupBlockView.swift new file mode 100644 index 00000000..9dc51652 --- /dev/null +++ b/ios/Hapi/Features/Chat/Blocks/ToolGroupBlockView.swift @@ -0,0 +1,112 @@ +import HapiProtocol +import HapiUI +import SwiftUI + +/// Run of adjacent groupable tools (web `ToolGroupCard`): a one-line summary +/// — count + first targets + error/running signals — expanding to the +/// individual `ToolCallBlockView`s. Codex exploration groups honor their +/// `defaultOpen`. +struct ToolGroupBlockView: View { + let block: ToolGroupBlock + let basePath: String? + + @State private var expanded: Bool + @Environment(\.hapiTheme) private var theme + + init(block: ToolGroupBlock, basePath: String?) { + self.block = block + self.basePath = basePath + _expanded = State(initialValue: block.defaultOpen) + } + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + headerRow + if expanded { + VStack(alignment: .leading, spacing: 6) { + ForEach(block.tools, id: \.id) { tool in + ToolCallBlockView(block: tool, basePath: basePath) + } + } + .padding(.horizontal, 10) + .padding(.bottom, 10) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .background(theme.surface) + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + } + + private var headerRow: some View { + Button { + withAnimation(.easeInOut(duration: 0.15)) { + expanded.toggle() + } + } label: { + HStack(spacing: 8) { + Image(systemName: "wrench.and.screwdriver") + .font(.footnote) + .foregroundStyle(.secondary) + .frame(width: 18) + VStack(alignment: .leading, spacing: 1) { + Text(title) + .font(.subheadline) + .foregroundStyle(theme.textPrimary) + .lineLimit(1) + if !summaryText.isEmpty { + Text(summaryText) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + Spacer(minLength: 8) + trailingIndicator + } + .padding(.horizontal, 10) + .padding(.vertical, 8) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + + private var title: String { + if let activityTitle = block.activityTitle { + return activityTitle + } + let count = block.summary.totalTools + return "\(count) tool\(count == 1 ? "" : "s")" + } + + /// "file, other-file +2" digest from the group summary targets. + private var summaryText: String { + let summary = block.summary + let targets = summary.fileTargets + summary.searchTargets + + summary.commandTargets + summary.urlTargets + summary.otherTargets + guard !targets.isEmpty else { return "" } + let shown = targets.prefix(3) + .map { target -> String in + let tail = target.split(separator: "/").last.map(String.init) ?? target + return tail.isEmpty ? target : tail + } + .joined(separator: ", ") + let more = targets.count - 3 + return more > 0 ? "\(shown) +\(more)" : shown + } + + @ViewBuilder + private var trailingIndicator: some View { + if block.summary.runningCount > 0 { + ProgressView() + .controlSize(.small) + } else if block.summary.errorCount > 0 { + Text("\(block.summary.errorCount) ⚠") + .font(.caption2) + .foregroundStyle(.red) + } else { + Image(systemName: expanded ? "chevron.down" : "chevron.right") + .font(.caption) + .foregroundStyle(.secondary) + } + } +} diff --git a/ios/Hapi/Features/Chat/ChatModel.swift b/ios/Hapi/Features/Chat/ChatModel.swift new file mode 100644 index 00000000..8b89365d --- /dev/null +++ b/ios/Hapi/Features/Chat/ChatModel.swift @@ -0,0 +1,307 @@ +import Foundation +import HapiClient +import HapiProtocol +import Observation + +/// Chat top-bar state: title cascade + status dot + meta line. +struct ChatHeaderUI: Equatable { + var title: String + /// "Flavor · machine · worktree" meta line; nil when nothing is known. + var subtitle: String? + var active: Bool + var thinking: Bool +} + +/// Presentation state machine for the read-only chat screen (M2f) — the iOS +/// counterpart of the Android `ChatViewModel`'s pipeline half. It combines +/// the message window's UI state with the cached session detail (whose +/// `agentState` carries permission verdicts) and machine labels, runs the +/// reduction pipeline **off the main actor** through ``ChatPipeline``, and +/// publishes render-ready `[VisibleChatBlock]` plus header/loading state. +/// +/// Recompute scheduling mirrors the web's render batching (Android's +/// `sample(100ms)`): inputs bump a revision and a single serial loop drains +/// it — the first run starts immediately, later runs coalesce to at most one +/// per ~100 ms, and because exactly one loop runs at a time every publish is +/// computed-from-latest-at-start and strictly ordered (a stale run can never +/// overwrite a newer one — the race the "detached task keyed by revision" +/// design exists to prevent). +/// +/// Pipeline memoization (normalize per row instance, `previousGroups` for +/// stable group ids) lives inside ``ChatPipeline``; see its docs. +@MainActor @Observable +final class ChatModel { + let sessionId: String + + // MARK: Published render state + + private(set) var blocks: [VisibleChatBlock] = [] + private(set) var header: ChatHeaderUI + /// Workspace root, for path display in tool cards. + private(set) var basePath: String? + private(set) var hasMore = false + private(set) var isLoadingOlder = false + private(set) var isSyncingTail = true + /// First sync still running and nothing (snapshot included) to show yet. + private(set) var isInitialLoading = true + /// Initial load produced nothing and the last attempt failed. + private(set) var loadFailed = false + /// Tail-sync warning — the degraded banner. + private(set) var warning: String? + /// Bumps on tail-side content changes (drives the new-messages pill). + private(set) var tailRevision = 0 + /// Bumps when an older page was prepended (drives scroll re-anchoring). + private(set) var historyVersion = 0 + + /// Session-pipe connection state (observed through the chat session). + var connectionState: SSEConnectionState { chat.connectionState } + + // MARK: Wiring + + private let hub: HubSession + /// Rebuilt on every `start()` after a `stop()` — a `ChatSession` is + /// single-use (its SSE client cannot restart), and the saved resume + /// cursor makes the rebuild cheap. This absorbs SwiftUI's + /// appear/disappear cycles around full-screen presentations. + private var chat: ChatSession + @ObservationIgnored private let pipeline = ChatPipeline() + @ObservationIgnored let imageLoader: GeneratedImageLoader + + @ObservationIgnored private var windowState: MessageWindowState? + @ObservationIgnored private var detailLoadFailed = false + @ObservationIgnored private var inputRevision = 0 + @ObservationIgnored private var pipelineTask: Task? + @ObservationIgnored private var statesTask: Task? + @ObservationIgnored private var olderTask: Task? + @ObservationIgnored private var isActive = false + @ObservationIgnored private var everStarted = false + + init(session: HubSession, sessionId: String) { + self.hub = session + self.sessionId = sessionId + self.chat = session.makeChatSession(sessionId: sessionId) + self.imageLoader = GeneratedImageLoader(api: session.api, sessionId: sessionId) + self.header = ChatHeaderUI( + title: String(sessionId.prefix(8)), + subtitle: nil, + active: false, + thinking: false + ) + } + + // MARK: - Lifecycle (paired with the screen's appear/disappear) + + func start() { + guard !isActive else { return } + isActive = true + if everStarted { + // Coming back from a stop (e.g. a full-screen cover fired the + // screen's disappear): fresh wiring, resumed at the saved cursor. + chat = hub.makeChatSession(sessionId: sessionId) + } + everStarted = true + let chat = chat + chat.onStoreActivity = { [weak self] in + self?.scheduleRecompute() + } + Task { [weak self] in + await chat.start() + guard let self, self.isActive, self.chat === chat else { return } + guard let controller = chat.windowController else { return } + self.statesTask = Task { [weak self] in + let states = await controller.states() + for await state in states { + guard let self, !Task.isCancelled else { return } + self.windowState = state + self.scheduleRecompute() + } + } + await self.loadDetail() + } + } + + func stop() { + guard isActive else { return } + isActive = false + statesTask?.cancel() + statesTask = nil + pipelineTask?.cancel() + pipelineTask = nil + olderTask?.cancel() + olderTask = nil + chat.stop() + } + + // MARK: - Actions + + /// Top sentinel reached: one older page. No-ops while one is in flight + /// or while a tail sync could race the cursor (Android gate). + func loadOlder() { + guard olderTask == nil, let controller = chat.windowController else { return } + guard let windowState, windowState.hasMore, + !windowState.isLoadingMore, !windowState.isSyncingTail else { return } + olderTask = Task { [weak self] in + _ = await controller.fetchOlder() + self?.olderTask = nil + } + } + + /// Error state → try again (detail + a tail sync past any in-flight run). + func retry() { + let controller = chat.windowController + Task { [weak self] in + await self?.loadDetail() + if let controller { + await controller.syncTail(ensureAfterCurrent: true) + } + } + } + + private func loadDetail() async { + do { + _ = try await hub.sessionStore.loadSessionDetail(sessionId) + detailLoadFailed = false + } catch is CancellationError { + return + } catch { + detailLoadFailed = true + } + scheduleRecompute() + } + + // MARK: - Pipeline scheduling + + private func scheduleRecompute() { + inputRevision += 1 + guard pipelineTask == nil else { return } + pipelineTask = Task { [weak self] in + await self?.pipelineLoop() + } + } + + /// Serial drain loop; see the type comment for the ordering argument. + /// All state reads/writes happen on the main actor — only the reduction + /// itself hops onto the pipeline actor. + private func pipelineLoop() async { + while !Task.isCancelled { + let revision = inputRevision + if let window = windowState { + let detail = hub.sessionStore.detail(for: sessionId) + let summary = hub.sessionStore.sessions.first { $0.id == sessionId } + let machines = hub.machineStore.machines + let visible = await pipeline.run( + messages: window.messages, + agentState: detail?.agentState, + hasMoreMessages: window.hasMore + ) + guard !Task.isCancelled else { return } + apply(visible, window: window, detail: detail, summary: summary, machines: machines) + } + // No suspension between this check and parking, so a concurrent + // scheduleRecompute either lands before it (loop again) or finds + // pipelineTask nil and starts a fresh loop — never lost. + if inputRevision == revision { + pipelineTask = nil + return + } + try? await Task.sleep(for: .milliseconds(100)) + } + } + + private func apply( + _ visible: [VisibleChatBlock], + window: MessageWindowState, + detail: Session?, + summary: SessionSummary?, + machines: [Machine] + ) { + blocks = visible + header = Self.buildHeader( + sessionId: sessionId, + detail: detail, + summary: summary, + machines: machines + ) + basePath = detail?.metadata?.path ?? summary?.metadata?.path + hasMore = window.hasMore + isLoadingOlder = window.isLoadingMore + isSyncingTail = window.isSyncingTail + warning = window.warning + tailRevision = window.tailRevision + historyVersion = window.historyVersion + + let isEmpty = visible.isEmpty + // syncGeneration 0 = no tail sync has even begun (the moment between + // open and syncTail) — still "loading", never a flash of empty state. + let syncSettled = !window.isSyncingTail && window.syncGeneration > 0 + isInitialLoading = isEmpty && !syncSettled && window.warning == nil + loadFailed = isEmpty && syncSettled && (window.warning != nil || detailLoadFailed) + + // Watermark = the updatedAt currently on screen, from whichever cache + // is fresher (summary via the global pipe, detail via this one). + // markSeen is monotonic, so stale inputs cannot rewind it. + let updatedAt = max(detail?.updatedAt ?? 0, summary?.updatedAt ?? 0) + if updatedAt > 0 { + hub.lastSeenStore.markSeen(sessionId: sessionId, seenAt: updatedAt) + } + } + + // MARK: - Header derivation (Android `buildHeader` port) + + private static func buildHeader( + sessionId: String, + detail: Session?, + summary: SessionSummary?, + machines: [Machine] + ) -> ChatHeaderUI { + // Detail first — the fresher source once loaded (this pipe patches + // it live); a detail without usable metadata falls through to the + // list summary, then to the id prefix (`getSessionTitle` cascade). + let title = detail.flatMap(detailTitle) + ?? summary.map(SessionListModel.sessionTitle) + ?? String(sessionId.prefix(8)) + + let flavor = detail?.metadata?.flavor ?? summary?.metadata?.flavor + let machineId = detail?.metadata?.machineId ?? summary?.metadata?.machineId + let machineLabel: String? = machineId.map { id in + guard let metadata = machines.first(where: { $0.id == id })?.metadata else { + return String(id.prefix(8)) + } + if let displayName = metadata.displayName, + !displayName.trimmingCharacters(in: .whitespaces).isEmpty { + return displayName + } + return metadata.host + } + let worktree = (detail?.metadata?.worktree ?? summary?.metadata?.worktree).map { tree in + tree.name.trimmingCharacters(in: .whitespaces).isEmpty ? tree.branch : tree.name + } + let parts: [String] = [ + flavor.map { flavorLabel(forFlavor: $0) }, + machineLabel, + worktree, + ].compactMap { $0 } + + return ChatHeaderUI( + title: title, + subtitle: parts.isEmpty ? nil : parts.joined(separator: " · "), + active: detail?.active ?? summary?.active ?? false, + thinking: detail?.thinking ?? summary?.thinking ?? false + ) + } + + /// Detail-side title cascade; nil when the metadata carries nothing usable. + private static func detailTitle(_ detail: Session) -> String? { + guard let metadata = detail.metadata else { return nil } + if let name = metadata.name, !name.isEmpty { + return name + } + if let text = metadata.summary?.text, !text.isEmpty { + return text + } + if let tail = metadata.path.split(separator: "/").last(where: { !$0.isEmpty }) { + return String(tail) + } + return nil + } +} diff --git a/ios/Hapi/Features/Chat/ChatView.swift b/ios/Hapi/Features/Chat/ChatView.swift new file mode 100644 index 00000000..7fe6ff55 --- /dev/null +++ b/ios/Hapi/Features/Chat/ChatView.swift @@ -0,0 +1,285 @@ +import HapiClient +import HapiProtocol +import HapiUI +import SwiftUI + +/// Read-only chat screen (M2f): `ScrollView + LazyVStack` over the reduced +/// `VisibleChatBlock`s, newest at the bottom. +/// +/// Scrolling model (iOS 17 APIs, kept deliberately simple): +/// - `defaultScrollAnchor(.bottom)` opens the thread at the newest message +/// AND keeps the bottom edge pinned while the reader is at the bottom — +/// that is the auto-stick; +/// - `scrollPosition(id:anchor:.top)` is used for the two programmatic +/// jumps: the new-messages pill (scroll to the bottom sentinel) and +/// **older-page re-anchoring** — before `loadOlder()` the current top +/// block id is captured, and when `historyVersion` bumps (rows were +/// prepended above the viewport, which shifts a non-bottom-anchored +/// scroll view) the position is re-set to that id so the reader stays on +/// the block they were looking at. Lazy estimated layout makes this +/// re-anchor approximate to the row, which is the documented trade-off; +/// - at-bottom detection uses a 1 pt bottom sentinel's lazy realization +/// (`onAppear`/`onDisappear`) — slightly eager because of lazy prefetch, +/// which errs toward sticking, the harmless direction. +struct ChatView: View { + @State private var model: ChatModel + /// Scroll position binding (anchor `.top`, so it tracks/targets the + /// top-visible block). + @State private var positionID: String? + @State private var isAtBottom = true + /// Newest block id last seen while at the bottom (new-messages pill). + @State private var newestSeenID: String? + /// Top-visible block captured when an older page was requested. + @State private var pendingAnchorID: String? + + private static let bottomSentinelID = "chat-bottom-sentinel" + + init(session: HubSession, sessionId: String) { + _model = State(initialValue: ChatModel(session: session, sessionId: sessionId)) + } + + var body: some View { + Group { + if model.isInitialLoading { + initialLoading + } else if model.loadFailed { + loadFailedState + } else if model.blocks.isEmpty { + emptyState + } else { + blockList + } + } + .safeAreaInset(edge: .top, spacing: 0) { + banners + } + .toolbar { + ToolbarItem(placement: .principal) { + headerTitle + } + } + .navigationBarTitleDisplayMode(.inline) + .environment(\.chatMedia, model.imageLoader) + .onAppear { + model.start() + } + .onDisappear { + // Pop-only navigation below this screen, so disappear == closed. + model.stop() + } + } + + // MARK: - Thread + + private var blockList: some View { + ScrollView { + LazyVStack(alignment: .leading, spacing: 10) { + if model.hasMore || model.isLoadingOlder { + OlderHistoryRow(isLoading: model.isLoadingOlder) + .onAppear { + requestOlderPage() + } + } + ForEach(model.blocks, id: \.stableId) { block in + ChatBlockCard(block: block, basePath: model.basePath) + } + bottomSentinel + } + .scrollTargetLayout() + .padding(.horizontal, 12) + .padding(.top, 10) + } + .defaultScrollAnchor(.bottom) + .scrollPosition(id: $positionID, anchor: .top) + .scrollDismissesKeyboard(.interactively) + .overlay(alignment: .bottom) { + newMessagesPill + } + .onChange(of: model.historyVersion) { + reanchorAfterPrepend() + } + .onChange(of: newestBlockID) { + if isAtBottom { + newestSeenID = newestBlockID + } + } + } + + private var bottomSentinel: some View { + Color.clear + .frame(height: 1) + .id(Self.bottomSentinelID) + .onAppear { + isAtBottom = true + newestSeenID = newestBlockID + } + .onDisappear { + isAtBottom = false + } + } + + private var newestBlockID: String? { + model.blocks.last?.stableId + } + + /// Capture the anchor BEFORE the prepend lands, then ask for the page. + private func requestOlderPage() { + if pendingAnchorID == nil { + let id = positionID + // The binding may currently point at chrome rows; fall back to + // the oldest real block. + let isBlock = id.map { candidate in + model.blocks.contains { $0.stableId == candidate } + } ?? false + pendingAnchorID = isBlock ? id : model.blocks.first?.stableId + } + model.loadOlder() + } + + /// `historyVersion` bumped: rows were prepended above the viewport. + /// Re-set the position to the captured block on the next runloop turn + /// (after SwiftUI laid the new rows out). + private func reanchorAfterPrepend() { + guard let anchor = pendingAnchorID else { return } + pendingAnchorID = nil + guard !isAtBottom else { return } // bottom-anchored: nothing shifted + Task { @MainActor in + positionID = anchor + } + } + + // MARK: - New-messages pill + + private var unseenCount: Int { + guard !isAtBottom, let seen = newestSeenID else { return 0 } + guard let index = model.blocks.lastIndex(where: { $0.stableId == seen }) else { return 0 } + return model.blocks.count - 1 - index + } + + @ViewBuilder + private var newMessagesPill: some View { + let count = unseenCount + if count > 0 { + Button { + newestSeenID = newestBlockID + positionID = Self.bottomSentinelID + } label: { + Text(count == 1 ? "1 new message ↓" : "\(count) new messages ↓") + .font(.footnote.weight(.medium)) + .padding(.horizontal, 14) + .padding(.vertical, 7) + .background(.tint, in: Capsule()) + .foregroundStyle(.white) + .shadow(radius: 3, y: 1) + } + .buttonStyle(.plain) + .padding(.bottom, 12) + } + } + + // MARK: - Chrome + + private var headerTitle: some View { + HStack(spacing: 8) { + StatusDot(active: model.header.active, thinking: model.header.thinking) + VStack(alignment: .leading, spacing: 0) { + Text(model.header.title) + .font(.headline) + .lineLimit(1) + if let subtitle = model.header.subtitle { + Text(subtitle) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + } + } + + @ViewBuilder + private var banners: some View { + VStack(spacing: 0) { + if let warning = model.warning { + HStack(spacing: 8) { + Text(warning) + .font(.footnote) + .lineLimit(2) + Spacer(minLength: 8) + Button("Retry") { + model.retry() + } + .font(.footnote.weight(.semibold)) + } + .padding(.horizontal, 16) + .padding(.vertical, 6) + .frame(maxWidth: .infinity) + .background(.red.opacity(0.14)) + .foregroundStyle(.red) + } + if case .backoff = model.connectionState { + Text("Live updates interrupted — reconnecting…") + .font(.footnote) + .frame(maxWidth: .infinity) + .padding(.vertical, 5) + .background(.orange.opacity(0.15)) + .foregroundStyle(.orange) + } + } + } + + // MARK: - Empty / loading / error + + private var initialLoading: some View { + VStack(spacing: 12) { + ProgressView() + Text("Loading messages…") + .font(.subheadline) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + + private var loadFailedState: some View { + ContentUnavailableView { + Label("Couldn't load this session", systemImage: "wifi.slash") + } description: { + Text("Check the connection to your hub and try again.") + } actions: { + Button("Retry") { + model.retry() + } + .buttonStyle(.borderedProminent) + } + } + + private var emptyState: some View { + ContentUnavailableView { + Label("No messages yet", systemImage: "bubble.left.and.bubble.right") + } description: { + Text("Messages will appear here as the agent works.") + } + } +} + +/// Centered "· · ·" / spinner row doubling as the load-older top sentinel. +private struct OlderHistoryRow: View { + let isLoading: Bool + + var body: some View { + HStack(spacing: 8) { + if isLoading { + ProgressView() + .controlSize(.small) + Text("Loading older messages…") + .font(.caption) + .foregroundStyle(.secondary) + } else { + Text("· · ·") + .font(.caption) + .foregroundStyle(.secondary) + } + } + .frame(maxWidth: .infinity) + .padding(.vertical, 8) + } +} diff --git a/ios/Hapi/Features/Home/HomeView.swift b/ios/Hapi/Features/Home/HomeView.swift index 5271064a..2f9d6ffd 100644 --- a/ios/Hapi/Features/Home/HomeView.swift +++ b/ios/Hapi/Features/Home/HomeView.swift @@ -3,7 +3,7 @@ import SwiftUI /// Post-pairing home: the session list for the active hub, with the hub /// switcher (switch / add / sign out) and the live global-SSE connection dot -/// in the toolbar. Tapping a row pushes the M2f chat placeholder. +/// in the toolbar. Tapping a row pushes the read-only chat (M2f). struct HomeView: View { let session: HubSession @@ -23,7 +23,7 @@ struct HomeView: View { } } .navigationDestination(for: String.self) { sessionId in - SessionDetailStubView(sessionId: sessionId) + ChatView(session: session, sessionId: sessionId) } .navigationTitle(HubDisplay.host(session.hubUrl)) .navigationBarTitleDisplayMode(.inline) diff --git a/ios/Hapi/Features/Links/LinkOpenHandling.swift b/ios/Hapi/Features/Links/LinkOpenHandling.swift new file mode 100644 index 00000000..2c8de47d --- /dev/null +++ b/ios/Hapi/Features/Links/LinkOpenHandling.swift @@ -0,0 +1,130 @@ +import HapiUI +import SafariServices +import SwiftUI + +/// App-level handler for everything HapiUI markdown emits through +/// `\.hapiOpenURL` (the renderer never opens anything itself and has already +/// dropped `HrefPolicy.blocked` links): +/// +/// - `hapi-file://?path=&line=` workspace citations → an explanatory alert; +/// the session file viewer lands in M4; +/// - `https` (and, after confirmation, `http`) → in-app +/// `SFSafariViewController`; +/// - other `HrefPolicy.allowed` schemes (`mailto`, …) → the system open; +/// - `HrefPolicy.confirmFirst` schemes → alert first, then open. +/// +/// Installed once at the root (see `RootView`), so links behave identically +/// wherever markdown renders. +struct LinkOpenHandling: ViewModifier { + @State private var safariURL: IdentifiedURL? + @State private var confirmURL: IdentifiedURL? + @State private var fileNotice: FilePathLink? + + @Environment(\.openURL) private var systemOpenURL + + func body(content: Content) -> some View { + content + .environment(\.hapiOpenURL, HapiOpenURLAction { url in + // Hop to the main actor: link taps arrive from view code, + // but the action type is a plain @Sendable closure. + Task { @MainActor in + handle(url) + } + }) + .sheet(item: $safariURL) { item in + SafariView(url: item.url) + .ignoresSafeArea() + } + .alert( + "Open link?", + isPresented: Binding( + get: { confirmURL != nil }, + set: { presented in + if !presented { + confirmURL = nil + } + } + ), + presenting: confirmURL + ) { item in + Button("Open") { + confirmURL = nil + open(item.url) + } + Button("Cancel", role: .cancel) { + confirmURL = nil + } + } message: { item in + Text(item.url.absoluteString) + } + .alert( + "Workspace file", + isPresented: Binding( + get: { fileNotice != nil }, + set: { presented in + if !presented { + fileNotice = nil + } + } + ), + presenting: fileNotice + ) { _ in + Button("OK") { + fileNotice = nil + } + } message: { link in + Text("\(link.path)\(link.line.map { ":\($0)" } ?? "")\n\nThe session file viewer arrives in a later milestone.") + } + } + + @MainActor + private func handle(_ url: URL) { + if let fileLink = FilePathLink(url: url) { + fileNotice = fileLink + return + } + switch HrefPolicy.classify(url) { + case .allowed: + open(url) + case .confirmFirst: + confirmURL = IdentifiedURL(url: url) + case .blocked: + break // defense in depth; the renderer never links these + } + } + + @MainActor + private func open(_ url: URL) { + let scheme = url.scheme?.lowercased() + if scheme == "https" || scheme == "http" { + safariURL = IdentifiedURL(url: url) + } else { + systemOpenURL(url) + } + } +} + +extension View { + /// Installs the app's `\.hapiOpenURL` handler (plus its presentation + /// surfaces) for this subtree. + func handlesHapiLinks() -> some View { + modifier(LinkOpenHandling()) + } +} + +private struct IdentifiedURL: Identifiable { + let id = UUID() + let url: URL +} + +/// Thin `SFSafariViewController` wrapper — reader-friendly in-app browsing +/// without leaving the session. +private struct SafariView: UIViewControllerRepresentable { + let url: URL + + func makeUIViewController(context: Context) -> SFSafariViewController { + SFSafariViewController(url: url) + } + + func updateUIViewController(_ controller: SFSafariViewController, context: Context) {} +} diff --git a/ios/Hapi/Features/Sessions/SessionDetailStubView.swift b/ios/Hapi/Features/Sessions/SessionDetailStubView.swift deleted file mode 100644 index 2862a627..00000000 --- a/ios/Hapi/Features/Sessions/SessionDetailStubView.swift +++ /dev/null @@ -1,25 +0,0 @@ -import SwiftUI - -// TODO(M2f): push ChatView — this stub only proves the list → detail -// navigation and shows which session was opened. -struct SessionDetailStubView: View { - let sessionId: String - - var body: some View { - ContentUnavailableView { - Label("Session \(sessionId.prefix(8))", systemImage: "bubble.left.and.bubble.right") - } description: { - Text("Chat lands in M2f.\n\(sessionId)") - .font(.footnote) - .monospaced() - } - .navigationTitle("Session") - .navigationBarTitleDisplayMode(.inline) - } -} - -#Preview { - NavigationStack { - SessionDetailStubView(sessionId: "0b9f5a1c-4c63-4a5e-8f6f-demo") - } -} diff --git a/ios/Hapi/Models/ChatSession.swift b/ios/Hapi/Models/ChatSession.swift new file mode 100644 index 00000000..0881399c --- /dev/null +++ b/ios/Hapi/Models/ChatSession.swift @@ -0,0 +1,222 @@ +import Foundation +import HapiClient +import HapiProtocol +import Observation + +/// Per-open-chat transport wiring (M2f) — the iOS counterpart of the +/// Android `ChatViewModel`'s lifecycle half: +/// +/// - opens this session's ``MessageWindowController`` through the hub's +/// registry (snapshot hydration + `activate()`), then kicks a tail sync; +/// - owns the **session-scope** SSE subscription while the chat is on screen +/// (dual-subscription model: `HubSession` keeps the global pipe for the +/// list) and routes its events: +/// - message-stream family → the window controller's ingest hooks, +/// - `session-updated`/lifecycle + `machine-updated` + `toast` → the +/// shared `SyncEventRouter` (detail patching included), +/// - `session-removed` for this session → clears the window, +/// - a `gap` handshake verdict → full REST resync + detail refetch + +/// the window's catch-up tail sync (`ensureAfterCurrent`); +/// - suspends/resumes with the scene phase (forwarded by `HubSession`) and +/// on `stop()` hands its SSE resume cursor back to the hub session, so a +/// reopened chat resumes instead of replaying cold. +/// +/// **Ordering.** The window must observe SSE events in arrival order (the +/// Android port funnels them through a single-consumer Channel for this). +/// Here the same guarantee falls out of structure: `SSEClient` yields into +/// one `AsyncStream`, exactly one task consumes it, and every event is +/// `await`ed to completion — including the hop into the window controller's +/// actor — before the next one is pulled. One producer, one consumer, one +/// awaited hop per event: no interleaving is possible. +@MainActor @Observable +final class ChatSession { + let sessionId: String + + /// Session-pipe connection state, for the chat header/banner. + private(set) var connectionState: SSEConnectionState = .idle + /// Set once `start()` opened the window; the chat model observes its + /// state stream and calls its `fetchOlder`/`syncTail`. + private(set) var windowController: MessageWindowController? + + /// Fired (on the main actor) after every handled SSE event so the chat + /// model can re-run its pipeline over the freshly patched stores. + @ObservationIgnored var onStoreActivity: (@MainActor () -> Void)? + + private let baseURL: URL + private let authManager: AuthManager + private let windows: MessageWindowControllers + private let sessionStore: SessionListStore + @ObservationIgnored private let router: SyncEventRouter + @ObservationIgnored private let initialCursor: String? + @ObservationIgnored private let registerActive: @MainActor (ChatSession) -> Void + @ObservationIgnored private let saveCursor: @MainActor (String?) -> Void + + @ObservationIgnored private var sse: SSEClient? + @ObservationIgnored private var consumeTask: Task? + @ObservationIgnored private var started = false + @ObservationIgnored private var stopped = false + + init( + sessionId: String, + baseURL: URL, + authManager: AuthManager, + windows: MessageWindowControllers, + sessionStore: SessionListStore, + machineStore: MachineStore, + initialCursor: String?, + registerActive: @escaping @MainActor (ChatSession) -> Void, + saveCursor: @escaping @MainActor (String?) -> Void + ) { + self.sessionId = sessionId + self.baseURL = baseURL + self.authManager = authManager + self.windows = windows + self.sessionStore = sessionStore + self.router = SyncEventRouter(sessions: sessionStore, machines: machineStore) + self.initialCursor = initialCursor + self.registerActive = registerActive + self.saveCursor = saveCursor + } + + // MARK: - Lifecycle + + /// Open the window, then subscribe: every routed message event finds the + /// controller already in place (the Android wiring order). Idempotent. + func start() async { + guard !started, !stopped else { return } + started = true + registerActive(self) + let controller = await windows.open(sessionId: sessionId) + await controller.activate() + // A stop() can land while the opens above were suspended; do not + // bring the SSE up for a dead chat. + guard !stopped else { return } + windowController = controller + startSessionSSE() + // Explicit catch-up on entry (the snapshot may be stale); the SSE + // handshake's own gap handling covers everything missed after this. + Task { await controller.syncTail() } + } + + /// Tears the session pipe down; the engine-side resume cursor is saved + /// so a reopened chat for this session resumes where it left off. + /// Idempotent — both the view's disappear and a hub shutdown call it. + func stop() { + guard !stopped else { return } + stopped = true + onStoreActivity = nil + consumeTask?.cancel() + consumeTask = nil + connectionState = .idle + // Nobody observes the detail once the chat closes (mirror of the + // Android `sessionStore.releaseDetail`). + sessionStore.releaseDetail(sessionId) + if let sse { + self.sse = nil + let save = saveCursor + Task { + let cursor = await sse.lastEventId + await sse.stop() + save(cursor) + } + } + } + + /// Scene-phase forwarding (see `HubSession.enterForeground`): resume the + /// parked retry loop, with the 45 s staleness distrust for a socket that + /// survived suspension. + func enterForeground() { + guard started, !stopped, let sse else { return } + Task { await sse.resume() } + } + + func enterBackground() { + guard let sse else { return } + Task { await sse.suspend() } + } + + // MARK: - Session-scope SSE + + private func startSessionSSE() { + let auth = authManager + let configuration = SSEClientConfiguration( + baseUrl: baseURL, + tokenProvider: { + // Transient failures park the SSE loop in backoff; the + // terminal (re-pair required) case is owned by the global + // pipe in `HubSession`, which tears this session down too. + try? await auth.validToken() + }, + scope: .session(sessionId) + ) + let client = SSEClient(configuration: configuration, pathObserver: NWPathObserver()) + sse = client + let cursor = initialCursor + consumeTask = Task { [weak self] in + // Seed before start (the client ignores seeds after the run + // loop exists); both calls run sequentially on the client actor. + if let cursor { await client.seedCursor(cursor) } + let stream = await client.start() + for await event in stream { + guard let self, !Task.isCancelled else { return } + // Sequential handling — see the ordering note on the type. + await self.handle(event) + } + } + } + + private func handle(_ event: SSEClientEvent) async { + switch event { + case .stateChanged(let state): + connectionState = state + case .handshake(let resume, _): + // `.ok` = the replay that follows covers the gap. Anything else + // (including the verdict-less first connect) cannot prove + // continuity for this filter set. + if resume != .ok { + recoverFromGap() + } + case .event(let syncEvent): + await route(syncEvent) + } + onStoreActivity?() + } + + private func route(_ event: SyncEvent) async { + switch event { + case .messageReceived, .messagesConsumed, .messageCancelled, + .messagesInvalidated, .scheduledMatured: + // Message-stream family → the open window (the controller + // re-checks the session id defensively). + if let controller = windowController { + await controller.onMessageEvent(event) + } + case .sessionRemoved(_, let removedId): + router.route(event, scope: .session(sessionId)) + if removedId == sessionId { + // Web `clearMessageWindow` on session-removed. + await windows.clear(sessionId: sessionId) + } + default: + // `session-updated` (detail patch / full session), lifecycle, + // `machine-updated`, `toast` — the shared store fan-out. + router.route(event, scope: .session(sessionId)) + } + } + + /// `resume: gap` on the session pipe (Android `requestFullResync` with a + /// session key): list + cached details + machines over REST, make sure + /// THIS detail exists even if it was never cached, and catch the window + /// up past any in-flight sync (web `resyncMessages`). + private func recoverFromGap() { + router.requestFullResync() + if sessionStore.detail(for: sessionId) == nil { + let store = sessionStore + let id = sessionId + Task { try? await store.loadSessionDetail(id) } + } + if let controller = windowController { + Task { await controller.syncTail(ensureAfterCurrent: true) } + } + } +} diff --git a/ios/Hapi/Models/HubSession.swift b/ios/Hapi/Models/HubSession.swift index 25bcb2e8..f386fff5 100644 --- a/ios/Hapi/Models/HubSession.swift +++ b/ios/Hapi/Models/HubSession.swift @@ -6,8 +6,9 @@ import Observation /// Everything the app holds for the currently active hub: the typed REST /// client, its auth manager, the **global** SSE subscription /// (`scope: .global` — one per app session; per-chat `.session` subscriptions -/// arrive with M2f), and the M2a stores it feeds (session list, machines, -/// last-seen watermarks). +/// are vended per open chat via ``makeChatSession(sessionId:)``), the M2a +/// stores it feeds (session list, machines, last-seen watermarks), and the +/// M2f message-window registry. /// /// Lifecycle is driven by `AppModel` from `scenePhase`: the SSE connection /// starts on the first foreground, suspends in background (flushing the @@ -28,6 +29,8 @@ final class HubSession { let machineStore: MachineStore /// Unread watermarks, snapshot-backed per hub. let lastSeenStore: LastSeenStore + /// Per-session message window registry (M2f), snapshot-backed per hub. + let windows: MessageWindowControllers /// Global SSE connection state, for the UI's connection dot. private(set) var connectionState: SSEConnectionState = .idle @@ -47,6 +50,15 @@ final class HubSession { @ObservationIgnored private var reportedAuthFailure = false @ObservationIgnored private var isShutDown = false + /// The chat currently on screen (at most one in this UI), forwarded the + /// scene-phase transitions so its session-scope SSE parks in background. + @ObservationIgnored private weak var activeChat: ChatSession? + /// Session-pipe resume cursors surviving chat close/reopen within this + /// hub session (the Android engine keeps its per-key cursor the same + /// way). Keyed by session id; never reused across hubs because the whole + /// `HubSession` — cursors included — dies on hub switch. + @ObservationIgnored private var chatCursors: [String: String] = [:] + init?( hubUrl: String, credentialStore: any CredentialStoring, @@ -72,9 +84,42 @@ final class HubSession { self.sessionStore = sessionStore self.machineStore = machineStore self.lastSeenStore = LastSeenStore(snapshotDirectory: snapshotDirectory) + self.windows = MessageWindowControllers( + provider: api, + snapshots: WindowSnapshotStore( + directory: snapshotDirectory.appendingPathComponent("windows", isDirectory: true) + ) + ) self.router = SyncEventRouter(sessions: sessionStore, machines: machineStore) } + // MARK: - Per-chat sessions (M2f) + + /// Builds the per-session wiring for an opened chat: window controller + /// access, the session-scope SSE pipe, and event routing into the shared + /// stores. The caller (ChatModel) drives `start()`/`stop()` with the + /// screen's lifetime; this hub session only forwards scene-phase + /// transitions and remembers the SSE resume cursor across reopens. + func makeChatSession(sessionId: String) -> ChatSession { + ChatSession( + sessionId: sessionId, + baseURL: baseURL, + authManager: authManager, + windows: windows, + sessionStore: sessionStore, + machineStore: machineStore, + initialCursor: chatCursors[sessionId], + registerActive: { [weak self] chat in + self?.activeChat = chat + }, + saveCursor: { [weak self] cursor in + if let cursor { + self?.chatCursors[sessionId] = cursor + } + } + ) + } + // MARK: - Lifecycle (driven by AppModel from scenePhase) /// First call starts the global SSE subscription; later calls resume a @@ -86,6 +131,7 @@ final class HubSession { } else { startGlobalSSE() } + activeChat?.enterForeground() } /// Parks the SSE retry loop; a live connection is left to the OS. Also @@ -95,6 +141,7 @@ final class HubSession { if let sse { Task { await sse.suspend() } } + activeChat?.enterBackground() let sessionStore = sessionStore let machineStore = machineStore let lastSeenStore = lastSeenStore @@ -109,6 +156,9 @@ final class HubSession { func shutdown() { isShutDown = true onTerminalAuthFailure = nil + // Hub switch can outrun the chat view's disappear; stop is idempotent. + activeChat?.stop() + activeChat = nil consumeTask?.cancel() consumeTask = nil if let sse { diff --git a/ios/Hapi/RootView.swift b/ios/Hapi/RootView.swift index 541d4aa8..500580e3 100644 --- a/ios/Hapi/RootView.swift +++ b/ios/Hapi/RootView.swift @@ -1,11 +1,14 @@ import HapiClient +import HapiUI import SwiftUI /// Switches the app root on pairing state and hosts the presentation that -/// must survive that switch: the deep-link pairing confirm sheet and the -/// "already paired" notice. +/// must survive that switch: the deep-link pairing confirm sheet, the +/// "already paired" notice, the HapiUI palette matching the system +/// appearance, and the app-wide markdown link handler. struct RootView: View { @Environment(AppModel.self) private var model + @Environment(\.colorScheme) private var colorScheme var body: some View { @Bindable var model = model @@ -55,6 +58,8 @@ struct RootView: View { } message: { Text(model.infoNotice ?? "") } + .hapiTheme(HapiTheme.resolve(for: colorScheme)) + .handlesHapiLinks() } } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatPipeline.swift b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatPipeline.swift new file mode 100644 index 00000000..a0e32caa --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatPipeline.swift @@ -0,0 +1,96 @@ +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(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 = [] + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/SyncEventRouting.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/SyncEventRouting.swift index d60f5d5a..3cc0a387 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Stores/SyncEventRouting.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/SyncEventRouting.swift @@ -22,13 +22,12 @@ import HapiProtocol /// /// The app's `HubSession` owns one of these per hub and calls /// ``handleHandshake(resume:)`` / ``route(_:scope:)`` from its SSE consume -/// loop. -/// -/// WIRING(M2f): the message-window bookkeeping the web also performs here -/// (`markMessagesConsumed` / optimistic reconciliation / ingest into the open -/// window) belongs to the message-window store — the session-scope branch of -/// ``route(_:scope:)`` grows a window target when it lands; the session-list -/// handling below stays as is. +/// loop. Since M2f the app's per-chat `ChatSession` reuses this router for +/// the session-scope pipe's non-message events and delivers the +/// message-stream family to the open `MessageWindowController` itself — +/// awaiting each ingest from its single consume task, which is what +/// preserves SSE arrival order into the window actor (the role the Android +/// port's `StoreSyncTargets` channel plays). @MainActor public struct SyncEventRouter { private let sessions: any SessionListStoring diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/ChatPipelineTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/ChatPipelineTests.swift new file mode 100644 index 00000000..763cae07 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/ChatPipelineTests.swift @@ -0,0 +1,187 @@ +import Foundation +import HapiClient +import HapiProtocol +import Testing + +/// Unit tests for the M2f `ChatPipeline` runner — the reduction path the +/// app's `ChatModel` drives (normalize memo → reduce → group with +/// `previousGroups`). Inputs come from real chat fixtures so the scripted +/// window states exercise the same wire shapes the golden suite does; the +/// golden byte-for-byte conformance itself lives in +/// `HapiProtocolTests/ChatFixtureTests`. +@Suite("Chat pipeline runner (M2f)") +struct ChatPipelineTests { + // MARK: - Fixture plumbing (same #filePath scheme as PaginationFixtureTests) + + private struct FixtureDocument: Decodable { + struct Input: Decodable { + let messages: [DecryptedMessage] + let agentState: AgentState? + } + + let input: Input + } + + private static func fixturesDirectory() -> URL { + URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // Tests/HapiClientTests + .deletingLastPathComponent() // Tests + .deletingLastPathComponent() // package root: ios/Packages/HapiKit + .appendingPathComponent("../../../shared/fixtures") + .standardizedFileURL + } + + private static func loadFixture(_ fileName: String) throws -> FixtureDocument { + let url = fixturesDirectory() + .appendingPathComponent("chat") + .appendingPathComponent(fileName) + return try JSONDecoder().decode(FixtureDocument.self, from: Data(contentsOf: url)) + } + + /// Window rows for fixture messages. Unlike `WindowMessage(wire:)` — + /// which maps a V8 hub page's collapsed `invokedAt` nil to the explicit + /// null of a queued row — fixture inputs model historical rows, where an + /// absent key means already-invoked. Mapping absence to `.absent` keeps + /// them out of the queued filter, as on a real historical page. + private static func windowRows(_ document: FixtureDocument) -> [WindowMessage] { + document.input.messages.map { wire in + WindowMessage( + id: wire.id, + seq: wire.seq, + localId: wire.localId, + content: wire.content, + createdAt: wire.createdAt, + invokedAt: wire.invokedAt.map(InvokedAtField.number) ?? .absent, + scheduledAt: wire.scheduledAt + ) + } + } + + private static func blockIds(_ blocks: [VisibleChatBlock]) -> [String] { + blocks.map { block in + switch block { + case .block(let value): return value.id + case .toolGroup(let group): return group.id + } + } + } + + private static func groupIds(_ blocks: [VisibleChatBlock]) -> [String] { + blocks.compactMap { block in + if case .toolGroup(let group) = block { return group.id } + return nil + } + } + + // MARK: - Reduction path over scripted fixture windows + + @Test( + "fixture windows reduce to non-empty stable-id blocks", + arguments: [ + "claude-assistant-text.json", + "claude-tool-use-result-pair.json", + "codex-exploration-tool-group.json", + ] + ) + func reducesFixtureWindow(_ fileName: String) async throws { + let document = try Self.loadFixture(fileName) + let rows = Self.windowRows(document) + let pipeline = ChatPipeline() + + let visible = await pipeline.run( + messages: rows, + agentState: document.input.agentState, + hasMoreMessages: false + ) + + #expect(!visible.isEmpty, "\(fileName): expected rendered blocks") + let ids = Self.blockIds(visible) + #expect(ids.allSatisfy { !$0.isEmpty }, "\(fileName): empty stable id") + #expect(Set(ids).count == ids.count, "\(fileName): duplicate stable ids \(ids)") + } + + @Test func memoizedRecomputeIsStable() async throws { + let document = try Self.loadFixture("claude-tool-use-result-pair.json") + let rows = Self.windowRows(document) + let pipeline = ChatPipeline() + + let first = await pipeline.run( + messages: rows, + agentState: document.input.agentState, + hasMoreMessages: false + ) + // Same row instances → every normalization is a memo hit; the + // output must be value-identical (ids included). + let second = await pipeline.run( + messages: rows, + agentState: document.input.agentState, + hasMoreMessages: false + ) + #expect(first == second) + #expect(Self.blockIds(first) == Self.blockIds(second)) + } + + @Test func queuedNotInvokedRowsStayOutOfTheThread() async throws { + let document = try Self.loadFixture("claude-assistant-text.json") + var rows = Self.windowRows(document) + // A queued composer row: user role, explicit-null invokedAt. + rows.append( + buildOptimisticMessage( + localId: "local-queued-1", + text: "queued follow-up", + createdAt: 1_755_000_999_000, + status: .queued + ) + ) + let pipeline = ChatPipeline() + + let visible = await pipeline.run(messages: rows, agentState: nil, hasMoreMessages: false) + + #expect(!visible.isEmpty) + #expect( + !Self.blockIds(visible).contains("local-queued-1"), + "queued-not-invoked rows belong to the composer bar, not the thread" + ) + } + + // MARK: - Group-id stability via previousGroups + + @Test func groupIdSurvivesOlderHistoryArrival() async throws { + let document = try Self.loadFixture("codex-exploration-tool-group.json") + let allRows = Self.windowRows(document) + // Drop the leading user prompt: the exploration group is now the + // oldest visible block with more history behind it. + let tailRows = Array(allRows.dropFirst()) + let pipeline = ChatPipeline() + + let truncated = await pipeline.run( + messages: tailRows, + agentState: document.input.agentState, + hasMoreMessages: true + ) + let truncatedGroupIds = Self.groupIds(truncated) + #expect(truncatedGroupIds.count == 1, "expected one exploration group") + + // The older page lands (full window, no more history): the group no + // longer starts at the oldest boundary, but previousGroups pins the + // id it already rendered under. + let complete = await pipeline.run( + messages: allRows, + agentState: document.input.agentState, + hasMoreMessages: false + ) + let completeGroupIds = Self.groupIds(complete) + #expect(completeGroupIds == truncatedGroupIds, "group id must not change across recomputes") + + // Control: a fresh pipeline (no previousGroups) keys the same window + // by its first tool instead — proof the pin above did the work. + let fresh = await ChatPipeline().run( + messages: allRows, + agentState: document.input.agentState, + hasMoreMessages: false + ) + let freshGroupIds = Self.groupIds(fresh) + #expect(freshGroupIds.count == 1) + #expect(freshGroupIds != truncatedGroupIds) + } +} diff --git a/ios/README.md b/ios/README.md index c289e692..5b6b32f2 100644 --- a/ios/README.md +++ b/ios/README.md @@ -45,7 +45,17 @@ ios/ APIClient/AuthManager/global SSEClient, connection state, the M2a stores — session list / machines / last-seen — - and the SyncEventRouter feeding them). + the SyncEventRouter feeding them, the + M2f message-window registry, and the + per-chat session factory) + ChatSession + (M2f per-open-chat wiring: session-scope + SSEClient with kept resume cursor, + window open/activate/tail-sync, ordered + event routing — one consume task, + every event awaited to the window + actor before the next — gap-handshake + full resync + detail refetch + catch-up + tail sync, scene-phase suspend/resume). Features/ Pairing/ (welcome, VisionKit QR scan, manual entry, shared confirm + error states), Home/ (session list host with @@ -56,8 +66,25 @@ ios/ pending/todo badges, unread dots, pinned section, machine filter chips, pull-to-refresh, long-press - pin/archive; row taps push an M2f chat - placeholder). + pin/archive; row taps push the chat), + Chat/ (M2f read-only chat: ChatModel — + window state + session detail → + ChatPipeline off-main, ~100 ms + coalesced, last-seen stamping, header + cascade; ChatView — bottom-anchored + ScrollView/LazyVStack with auto-stick, + new-messages pill, top sentinel paging + with scroll re-anchoring, degraded + banners; Blocks/ — user bubble, agent + markdown, reasoning, tool cards with + per-tool bodies + knownTools-parity + presentation, tool groups, event rows, + cli output, generated images with + full-screen viewer, codex review), + Links/ (app-wide \.hapiOpenURL handler: + https/http → SFSafariViewController, + confirm-first schemes → alert, + hapi-file:// → M4 placeholder). Packages/HapiKit/ Local SPM package with the real logic: HapiProtocol Pure-Foundation protocol layer. As of M2a: Models/ wire types mirroring shared/src/schemas.ts @@ -190,9 +217,15 @@ ios/ MessageWindowControllers registry (hydrate on open, seed across resume/reopen id changes). - Chat assembly (M2f) lands next; feature endpoints - (git/files, scratchlist, voice, usage) join - Endpoints/ with their feature packages. + Chat/ ChatPipeline (M2f): the actor the + app's chat screen runs its + reduction on — queued-row filter, + normalize memoized by row instance + identity, reduce + toolGroups with + previousGroups-stable group ids. + Feature endpoints (git/files, scratchlist, voice, + usage) join Endpoints/ with their feature packages + in M3/M4. HapiUI Rendering foundation (M2e). SwiftUI, no app coupling: Markdown/ MarkdownTransforms (string-level ports of the web remark plugins: table repair, @@ -210,8 +243,9 @@ ios/ (hunks, +/- gutters, compact/expand) Theme/ HapiTheme palettes (light/dark/OLED) via the \.hapiTheme environment - The app target does not import HapiUI yet; it gets - wired in with the chat views (M2f). + Since M2f the app target links HapiUI and renders + chat prose/code/diffs through it; RootView injects + the palette and the \.hapiOpenURL link handler. ``` The app target stays thin; features live in `HapiKit` so they are testable @@ -237,7 +271,10 @@ query objects (`expectedRequests`, including the explicit-null `untilAt`/`untilSeq` of the first catch-up request), the older-load outcomes, the queued-state reconcile candidates, and the final window projection (`expectedState`) — all canonical-JSON compares with the same per-op labels -and first-differing-line diffs. +and first-differing-line diffs. Since M2f, `HapiClientTests/ChatPipelineTests` +drives the app-facing `ChatPipeline` runner with fixture-derived window rows: +non-empty unique stable ids, memo-stable recomputes, the queued-row filter, +and group-id stability across an older-page arrival (`previousGroups`). ## Pairing (M1d)