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

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

130 lines
4.5 KiB
Swift

import HapiClient
import SwiftUI
/// A pending (M4) attachment chip — the row renders only when non-empty, so
/// the M4 upload flow can light it up without composer surgery.
struct ComposerAttachment: Identifiable, Equatable {
let filename: String
let mimeType: String
var id: String { filename }
}
/// The chat input bar (A-M3a): multiline text field (return = newline, the
/// mobile default), a send button whose long-press offers "Send & steer"
/// while a turn is active (`messageDelivery.ts` — queue is always the
/// default), and an abort button during thinking. Attachments are an M4 seam
/// (chips render when present; no picker yet).
struct ChatComposerView: View {
let interactor: ChatInteractor
var attachments: [ComposerAttachment] = []
private var text: Binding<String> {
Binding(
get: { interactor.composerText },
set: { interactor.setComposerText($0) }
)
}
var body: some View {
let composer = interactor.composer
VStack(spacing: 6) {
if !attachments.isEmpty {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 6) {
ForEach(attachments) { attachment in
Label(attachment.filename, systemImage: "paperclip")
.font(.caption)
.lineLimit(1)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(
.fill.tertiary,
in: RoundedRectangle(cornerRadius: 8, style: .continuous)
)
}
}
}
}
HStack(alignment: .bottom, spacing: 8) {
TextField("Message the agent…", text: text, axis: .vertical)
.lineLimit(1...6)
.textFieldStyle(.plain)
.padding(.horizontal, 14)
.padding(.vertical, 9)
.background(.fill.tertiary, in: RoundedRectangle(cornerRadius: 20, style: .continuous))
if composer.canSteer {
abortButton
}
sendButton(composer)
}
}
.padding(.horizontal, 10)
.padding(.vertical, 6)
.background(.bar)
}
// MARK: - Buttons
private var abortButton: some View {
Button {
interactor.abortSession()
} label: {
Image(systemName: "stop.fill")
.font(.subheadline)
.frame(width: 38, height: 38)
.background(.red.opacity(0.15), in: Circle())
.foregroundStyle(.red)
}
.buttonStyle(.plain)
.accessibilityLabel("Stop the current turn")
}
@ViewBuilder
private func sendButton(_ composer: ComposerState) -> some View {
let hasText = !composer.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
let enabled = hasText && !composer.isSending
let label = sendLabel(composer, enabled: enabled)
if composer.canSteer && enabled {
// Tap sends (queue); long-press opens the deliberate steer intent.
Menu {
Button("Send & steer into current turn") {
interactor.sendMessage(steer: true)
}
} label: {
label
} primaryAction: {
interactor.sendMessage()
}
.accessibilityLabel("Send — long-press to steer")
} else {
Button {
interactor.sendMessage()
} label: {
label
}
.buttonStyle(.plain)
.disabled(!enabled)
.accessibilityLabel("Send")
}
}
private func sendLabel(_ composer: ComposerState, enabled: Bool) -> some View {
Group {
if composer.isSending {
ProgressView()
.controlSize(.small)
} else {
Image(systemName: "arrow.up")
.font(.subheadline.weight(.semibold))
}
}
.frame(width: 38, height: 38)
.background(
enabled ? AnyShapeStyle(.tint) : AnyShapeStyle(.fill.tertiary),
in: Circle()
)
.foregroundStyle(enabled ? AnyShapeStyle(.white) : AnyShapeStyle(.secondary))
}
}