import RastrilloApple import SwiftUI /// The conversation: Roster's bylines and cards over live data, with the /// composer at the bottom. Used as is on iPhone; the Mac draws the same feed /// in AppKit. public struct ConversationScreen: View { let session: EquipoSession /// A card to bring into view (a tapped notification); cleared once shown. @Binding var focus: String? var openTask: (String) -> Void @State private var viewport: CGFloat = 0 public init(session: EquipoSession, focus: Binding = .constant(nil), openTask: @escaping (String) -> Void) { self.session = session; _focus = focus; self.openTask = openTask } public var body: some View { let items = Feed.build(session) ScrollViewReader { proxy in ScrollView { LazyVStack(alignment: .leading, spacing: 20) { if items.isEmpty && session.status != .ready && session.refreshFailed { ReadFailed { Task { await session.refresh() } } } if items.isEmpty && session.status == .ready { Text(String(localized: "conversation.empty", bundle: .module)) .font(Typo.body).foregroundStyle(Palette.secondary).padding(.top, 40) } ForEach(items) { item in row(item).id(item.id) } Color.clear.frame(height: 8).id("bottom") } .padding(.horizontal, 16).padding(.top, 12).padding(.bottom, 20) .frame(maxWidth: 760).frame(maxWidth: .infinity) // At least the visible height, so a short conversation's empty // space is background too. .frame(minHeight: viewport, alignment: .bottom) .tapDismissesKeyboard() } .onScrollGeometryChange(for: CGFloat.self) { $0.containerSize.height } action: { _, height in viewport = height } .accessibilityIdentifier("conversation-scroll") .defaultScrollAnchor(.bottom) .refreshable { await session.refresh() } .onChange(of: items.count) { _, _ in if focus != nil { show(focus, items, proxy) } else { withAnimation { proxy.scrollTo("bottom", anchor: .bottom) } } } .onChange(of: focus, initial: true) { _, id in show(id, items, proxy) } } .background(Palette.background) .safeAreaInset(edge: .top, spacing: 0) { NativeOfflineBanner(origin: session.origin) } .safeAreaInset(edge: .bottom, spacing: 0) { VStack(spacing: 0) { ProjectSelectionChip(catalog: session.projectCatalog) Composer(placeholder: String(localized: "conversation.placeholder", bundle: .module), attachments: session.attachments) { text in _ = sendFromComposer(text) } } } .dismissesKeyboardWhileReading() .keyboardPinned() } func sendFromComposer(_ text: String) -> Task { session.sendFromComposer(text) } /// Scrolls to the card once the feed has it; reads again if it does not yet. private func show(_ id: String?, _ items: [FeedItem], _ proxy: ScrollViewProxy) { guard let id else { return } if items.contains(where: { $0.id == id }) { Task { @MainActor in withAnimation { proxy.scrollTo(id, anchor: .center) } focus = nil } } else { // Not in the feed yet: read again, and give up if it still is not. Task { @MainActor in await session.refresh() if !Feed.build(session).contains(where: { $0.id == id }) { focus = nil } } } } @ViewBuilder private func row(_ item: FeedItem) -> some View { if let reply = item.reply { CoordinatorMessage(reply: reply, messageID: item.id, origin: session.origin, transcript: session.markdown, openTask: openTask) } else { switch item { case .draft, .coordinator, .notice: EmptyView() case .own(let m): OwnMessage(text: m.text, attachments: m.attachments ?? [], client: session.client) case .outgoing(let o): OutgoingMessage(item: o, client: session.client) { Task { await session.retry(o.id) } } case .report(_, let byline, let report, let compact): VStack(alignment: .leading, spacing: 8) { Byline(byline: byline) LiveReport(report: report, session: session, compact: compact, onRunNow: { run in Task { await session.runNow(task: report.task.id, run) } }) { openTask(report.task.id) } } case .question(let card, let byline): VStack(alignment: .leading, spacing: 8) { Byline(byline: byline) LiveQuestionCard(card: card, taskTitle: session.task(card.taskId)?.title, session: session) } case .decision(let card, let byline): VStack(alignment: .leading, spacing: 8) { Byline(byline: byline) LiveDecisionCard(card: card, taskTitle: session.task(card.taskId)?.title, session: session) } case .receipt(let card, _): LiveReceipt(card: card) case .thinking(let turn, let activity): ThinkingLine(turn: turn, activity: activity, stopping: session.stopping.contains(turn.id)) { Task { await session.stop(turn) } } } } } } /// A message this device is still sending, and how it is going. struct OutgoingMessage: View { let item: EquipoSession.Outgoing var client: EquipoClient? = nil var retry: () -> Void var body: some View { VStack(alignment: .trailing, spacing: 4) { if let project = item.projectName { ProjectChip(name: project) } OwnMessage(text: item.text, attachments: item.attachments, client: client).opacity(item.state == .sending ? 0.7 : 1) if let notice = item.notice { Text(notice).font(Typo.secondary).foregroundStyle(Palette.negative) } switch item.state { case .sending: Text(String(localized: "message.sending", bundle: .module)).font(Typo.caption).foregroundStyle(Palette.faint) case .waiting: Button(action: retry) { Text(String(localized: "message.waiting", bundle: .module)).underline() } .buttonStyle(.plain).font(Typo.caption).foregroundStyle(Palette.secondary).frame(minHeight: Metric.target) case .failed: Button(action: retry) { Text(String(localized: "message.failed", bundle: .module)).underline() } .buttonStyle(.plain).font(Typo.caption).foregroundStyle(Palette.negative).frame(minHeight: Metric.target) } } .frame(maxWidth: .infinity, alignment: .trailing) } } /// The composer: attachments above, an add button beside the tinted field. struct Composer: View { let placeholder: String var attachments: AttachmentDraft? = nil var onSend: (String) -> Void @State private var text = "" @FocusState private var focused: Bool #if os(iOS) @State private var screenshot = RecentScreenshot() @Environment(\.scenePhase) private var scenePhase #endif var body: some View { let has = attachments?.canSend(text: text) ?? !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty let shape = RoundedRectangle(cornerRadius: 10, style: .continuous) VStack(spacing: 4) { #if os(iOS) if let attachments { ScreenshotChip(model: screenshot, draft: attachments) } #endif if let attachments { AttachmentDraftStrip(draft: attachments) } HStack(alignment: .bottom, spacing: 8) { #if os(iOS) if let attachments { PhoneAttachmentPicker(draft: attachments, screenshot: screenshot) } #endif HStack(alignment: .bottom, spacing: 0) { TextField("", text: $text, prompt: Text(placeholder).foregroundColor(Palette.placeholder), axis: .vertical) .font(Typo.body).foregroundStyle(Palette.controlText).textFieldStyle(.plain) .lineLimit(1...6).focused($focused) .padding(.leading, 14).padding(.vertical, 11) .frame(minHeight: 44) .accessibilityLabel(placeholder) .onSubmit(send) Button(action: send) { Image(systemName: "arrow.up").font(.system(size: 16, weight: .bold)) .foregroundStyle(has ? Color.white : Palette.faint) .frame(width: 34, height: 34) .background(has ? Palette.primaryFill : Palette.surface2, in: Circle()) .frame(width: 44, height: 44).contentShape(Circle()) } .buttonStyle(.plain).disabled(!has) .accessibilityLabel(Text(String(localized: "composer.send", bundle: .module))) } .background(Palette.surface2, in: shape) .overlay(shape.strokeBorder(Palette.controlBorder, lineWidth: 1)) .background { if focused { RoundedRectangle(cornerRadius: 13, style: .continuous) .strokeBorder(Palette.accent, lineWidth: 2).padding(-3) } } } } .padding(.horizontal, 16).padding(.top, 10).padding(.bottom, 8) .frame(maxWidth: 760).frame(maxWidth: .infinity) .background(Palette.background) #if os(iOS) .task { if attachments != nil { screenshot.start() while !Task.isCancelled { try? await Task.sleep(for: .seconds(30)); if !Task.isCancelled { screenshot.refresh() } } } } // Leaving the conversation (a task link, another tab) gives up the // keyboard; coming back never raises it until the field is tapped. .onDisappear { screenshot.stop(); focused = false } .onChange(of: scenePhase) { _, phase in if phase == .active && attachments != nil { screenshot.start() } else { screenshot.stop() } } .onChange(of: attachments.map(ObjectIdentifier.init)) { _, _ in screenshot.stop(); screenshot = RecentScreenshot(); if attachments != nil { screenshot.start() } } #endif } private func send() { let value = text.trimmingCharacters(in: .whitespacesAndNewlines) guard attachments?.canSend(text: value) ?? !value.isEmpty else { return } onSend(value); text = "" } }