Files
coucou/NotchBuddy/Sources/Phone/ChatView.swift
LouisandClaude 62bde92a94 Botan's conversations on the iPhone, and what each Mochi got done (#1297)
- iPhone: a Conversations button in Botan's chat lists Botan, each team (as its lead) and each
  Mochi on its own, like a messaging app: the start of what it last did, when, a red mark if it
  failed, and a badge for what waits for a tap (a lead counts its team's). A tap opens the thread.
- Mac: a Mochi's sheet shows what it got done over 30 days: PRs opened and merged since (checked
  once with gh, then kept), reviews and replies posted, PRs closed, and the time saved (an
  estimate). brain `mochi stats <id>`, 0.15.5.


Claude-Session: https://claude.ai/code/session_01LJm3SRL9k3gBPaVtfPhwcT

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-03 21:32:08 +00:00

843 lines
37 KiB
Swift

import SwiftUI
/// The Chat tab: ask Botan about your agents, services and OKs, like Messages, with Mochi
/// answering. Apple's model runs on the iPhone (BotanChat).
struct ChatView: View {
@State private var chat = BotanChat.shared
@State private var threads = MochiThreads.shared
@State private var link = PhoneLink.shared
/// A Mochi's runs show folded (title and one line); these ones are unfolded.
@State private var unfolded: Set<String> = []
@State private var text = ""
/// The list of conversations: Botan, the teams' leads, the Mochis on their own
@State private var inbox = false
@State private var dictation = Dictation()
@FocusState private var focused: Bool
private static let suggestions = [
"What happened today?",
"Anything waiting for me?",
"Did a deploy fail this week?",
"What did I earn today?",
"What did Claude do last?",
]
private static let mochiSuggestions = ["What did you do last?", "Run now", "Pause for now", "Wake up"]
/// One spring for everything that moves when a chat starts or ends.
private static let move = Animation.spring(duration: 0.55, bounce: 0.12)
private var mochis: [PhoneMochi] { link.macMochis?.mochis ?? [] }
/// The Mochi you're talking to, while it's still on the Mac.
private var current: PhoneMochi? { threads.mochi(threads.selected) }
var body: some View {
NavigationStack {
ZStack {
ChatBackdrop(active: chat.answering)
.ignoresSafeArea()
if let m = current {
mochiConversation(m)
.id(m.id)
.transition(.opacity)
} else if let reason = chat.unavailableReason, chat.messages.isEmpty {
unavailable(reason)
.transition(.opacity)
} else if chat.messages.isEmpty {
welcome
.transition(.asymmetric(insertion: .opacity.combined(with: .scale(scale: 0.92)),
removal: .opacity.combined(with: .scale(scale: 1.06))))
} else {
conversation
.transition(.opacity)
}
}
// A swipe down anywhere puts the keyboard away, like Messages.
.simultaneousGesture(
DragGesture(minimumDistance: 12).onChanged { drag in
if focused, drag.translation.height > 24, abs(drag.translation.width) < drag.translation.height {
focused = false
}
}
)
// the Mac's Mochis may have changed while the app was closed
.task { await PhoneLink.shared.refresh() }
.animation(.spring(duration: 0.3, bounce: 0.15), value: picker?.id)
.sheet(isPresented: $inbox) {
MochiInbox(mochis: mochis) { id in
inbox = false
withAnimation(Self.move) { threads.selected = id }
}
.presentationDetents([.medium, .large])
}
.navigationTitle(current?.name ?? "Chat")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
if !mochis.isEmpty {
ToolbarItem(placement: .topBarLeading) {
Button {
inbox = true
Haptics.impact()
} label: {
Image(systemName: "bubble.left.and.bubble.right")
.overlay(alignment: .topTrailing) {
// something waits for a tap somewhere
if mochis.contains(where: { !$0.waiting.isEmpty }) {
Circle().fill(Color.botan).frame(width: 8, height: 8).offset(x: 4, y: -3)
}
}
}
.accessibilityLabel("Conversations")
}
}
if !chat.messages.isEmpty && current == nil {
ToolbarItem(placement: .topBarTrailing) {
Button {
withAnimation(Self.move) { chat.reset() }
Haptics.impact()
} label: {
Image(systemName: "arrow.counterclockwise")
}
.disabled(chat.answering)
.accessibilityLabel("New chat")
}
}
}
.safeAreaInset(edge: .bottom) {
if chat.unavailableReason == nil || current != nil {
VStack(spacing: 0) {
if let panel = picker {
pickerPanel(panel)
.padding(.horizontal, 12)
.padding(.bottom, 8)
.transition(.move(edge: .bottom).combined(with: .opacity))
}
if current == nil, let plan = link.macMochis?.team,
Date().timeIntervalSince(plan.at) < 3 * 3600, threads.teamDismissed != plan.at {
TeamPlanCard(plan: plan, mochis: mochis)
.padding(.horizontal, 12)
.padding(.bottom, 8)
.transition(.move(edge: .bottom).combined(with: .opacity))
}
if !mochis.isEmpty {
pillsRow.padding(.bottom, 8)
}
// Always laid out, folded away once the chat starts: it fades and
// shrinks with the rest instead of vanishing.
let showSuggestions = (current.map { threads.lines(for: $0).isEmpty } ?? chat.messages.isEmpty) && picker == nil
suggestionsRow
.opacity(showSuggestions ? 1 : 0)
.scaleEffect(showSuggestions ? 1 : 0.9, anchor: .bottom)
.frame(height: showSuggestions ? nil : 0, alignment: .bottom)
.padding(.bottom, showSuggestions ? 10 : 0)
.clipped()
.allowsHitTesting(showSuggestions)
composer
}
}
}
.onChange(of: dictation.transcript) { _, words in
if dictation.isRecording { text = dictation.prefix + words }
}
}
}
// MARK: Empty states
private var welcome: some View {
VStack(spacing: 14) {
Spacer()
MochiLive(state: .idle)
.frame(width: 96)
.padding(.bottom, 4)
Text("Ask Botan")
.font(.title2.weight(.semibold))
Text("Your agents, your services, what you allowed.\nApple's model answers on your iPhone: nothing leaves it.")
.font(.subheadline)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal, 36)
Spacer()
Spacer()
}
.frame(maxWidth: .infinity)
.contentShape(Rectangle())
.onTapGesture { focused = false }
}
private func unavailable(_ reason: String) -> some View {
ContentUnavailableView {
VStack(spacing: 12) {
MochiLive(state: .sleeping)
.frame(width: 80)
Text("Botan can't talk here")
}
} description: {
Text(reason)
}
}
/// Small chips just above the field, scrolling sideways. Plain, not glass: the tab bar and
/// the field are glass already.
private var suggestionsRow: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
ForEach(current == nil ? Self.suggestions : Self.mochiSuggestions, id: \.self) { suggestion in
Button {
ask(suggestion)
} label: {
Text(suggestion)
.font(.footnote.weight(.medium))
.foregroundStyle(.white.opacity(0.85))
.lineLimit(1)
.padding(.horizontal, 13)
.padding(.vertical, 8)
.background(Color.white.opacity(0.07), in: Capsule())
.overlay(Capsule().strokeBorder(Color.white.opacity(0.1), lineWidth: 0.5))
}
.buttonStyle(PressableButtonStyle())
}
}
.padding(.horizontal, 12)
}
.scrollClipDisabled()
}
// MARK: Conversation
private var conversation: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 10) {
ForEach(chat.messages) { message in
bubble(message)
.id(message.id)
.transition(.asymmetric(
insertion: .opacity
.combined(with: .offset(y: 24))
.combined(with: .scale(scale: 0.9, anchor: message.role == .you ? .bottomTrailing : .bottomLeading)),
removal: .opacity))
}
}
.padding(.horizontal, 14)
.padding(.top, 20)
.padding(.bottom, 12)
}
.defaultScrollAnchor(.bottom)
.scrollDismissesKeyboard(.interactively)
}
@ViewBuilder private func bubble(_ message: ChatMessage) -> some View {
switch message.role {
case .you:
HStack {
Spacer(minLength: 48)
Text(message.text)
.font(.body)
.foregroundStyle(.white)
.padding(.horizontal, 14)
.padding(.vertical, 9)
.yourBubble()
.textSelection(.enabled)
}
case .botan:
let last = message.id == chat.messages.last(where: { $0.role == .botan })?.id
let thinking = message.text.isEmpty && chat.answering && last
HStack(alignment: .bottom, spacing: 8) {
// One Mochi only, beside Botan's latest answer, alive like everywhere else.
Group {
if last {
MochiLive(state: chat.mood)
.transition(.scale.combined(with: .opacity))
} else {
Color.clear
}
}
.frame(width: 30, height: 30)
Group {
if thinking {
// Botan is thinking: three dots, like Messages.
Image(systemName: "ellipsis")
.font(.title3.weight(.bold))
.foregroundStyle(.secondary)
.symbolEffect(.variableColor.iterative.dimInactiveLayers, options: .repeating)
.frame(width: 44, height: 22)
} else {
StreamingText(text: message.text, animate: last)
.font(.body)
.foregroundStyle(message.failed ? .secondary : .primary)
}
}
.padding(.horizontal, 14)
.padding(.vertical, 9)
.background(Color.white.opacity(0.08), in: RoundedRectangle(cornerRadius: 19, style: .continuous))
.overlay(RoundedRectangle(cornerRadius: 19, style: .continuous).strokeBorder(Color.white.opacity(0.08), lineWidth: 0.5))
Spacer(minLength: 32)
}
.animation(.spring(duration: 0.35), value: message.text.isEmpty)
}
}
// MARK: Mochis
/// Who you talk to: Botan, or one of the Mac's Mochis (an orange dot: something waits for you).
private var pillsRow: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
pill(name: "Botan", color: "#FF5A24", outfit: .none, waiting: false, selected: current == nil) {
threads.selected = nil
}
// a team shows as its lead: its Mochis are reached through it (or with @)
ForEach(mochis.filter { $0.spokenFor != true }) { m in
pill(name: m.name, color: m.color, outfit: Outfit.mochiParts(m.outfit).head,
waiting: !m.waiting.isEmpty, selected: current?.id == m.id) {
threads.selected = m.id
}
.opacity(m.enabled ? 1 : 0.6)
}
}
.padding(.horizontal, 12)
}
.scrollClipDisabled()
}
private func pill(name: String, color: String, outfit: Outfit, waiting: Bool, selected: Bool,
action: @escaping () -> Void) -> some View {
Button {
withAnimation(Self.move) { action() }
Haptics.impact()
} label: {
HStack(spacing: 6) {
MochiLive(state: .idle, bodyHex: color, outfit: outfit, fps: 30)
.frame(width: 20, height: 20)
Text(name)
.font(.footnote.weight(.semibold))
.foregroundStyle(.white.opacity(selected ? 1 : 0.8))
.lineLimit(1)
if waiting {
Circle().fill(Color.botan).frame(width: 7, height: 7)
}
}
.padding(.leading, 8)
.padding(.trailing, 12)
.padding(.vertical, 6)
.background((selected ? Color(hex: color).opacity(0.3) : Color.white.opacity(0.07)), in: Capsule())
.overlay(Capsule().strokeBorder(selected ? Color(hex: color).opacity(0.7) : Color.white.opacity(0.1), lineWidth: selected ? 1 : 0.5))
}
.buttonStyle(PressableButtonStyle())
}
// MARK: @ and / pickers
/// A slash command: in Botan's thread, or in a Mochi's.
struct SlashCommand: Identifiable {
let name: String
let detail: String
let symbol: String
/// What it says, as if typed ("" = only fills the field)
let says: String
var id: String { name }
}
static let botanCommands = [
SlashCommand(name: "/today", detail: "What happened today", symbol: "sun.max", says: "What happened today?"),
SlashCommand(name: "/waiting", detail: "Anything waiting for me", symbol: "hand.raised", says: "Anything waiting for me?"),
SlashCommand(name: "/mochi", detail: "Talk to one of your Mochis", symbol: "at", says: ""),
SlashCommand(name: "/team", detail: "Give your team a mission", symbol: "person.3", says: ""),
]
static let mochiCommands = [
SlashCommand(name: "/run", detail: "Run now, on your Mac", symbol: "play.fill", says: "run"),
SlashCommand(name: "/last", detail: "What did you do last?", symbol: "clock.arrow.circlepath", says: "What did you do last?"),
SlashCommand(name: "/waiting", detail: "What's waiting for my tap?", symbol: "hand.raised", says: "What's waiting for my tap?"),
SlashCommand(name: "/pause", detail: "Turn it off for now", symbol: "pause.fill", says: "pause"),
SlashCommand(name: "/wake", detail: "Turn it back on", symbol: "sunrise", says: "wake up"),
SlashCommand(name: "/botan", detail: "Back to Botan", symbol: "arrow.uturn.backward", says: ""),
]
/// What the panel above the field offers while you type "@…" or "/…".
enum ChatPicker: Equatable {
case mochis([PhoneMochi])
case commands([SlashCommand])
/// "@" typed, but no Mochi came from the Mac yet
case noMochis
var id: String {
switch self {
case .mochis(let m): return "m" + m.map(\.id).joined()
case .commands(let c): return "c" + c.map(\.id).joined()
case .noMochis: return "none"
}
}
static func == (a: ChatPicker, b: ChatPicker) -> Bool { a.id == b.id }
}
private var picker: ChatPicker? {
let typed = text.trimmingCharacters(in: .whitespaces)
if typed.hasPrefix("/"), !typed.contains(" ") {
let all = current == nil ? Self.botanCommands : Self.mochiCommands
let match = all.filter { $0.name.hasPrefix(typed.lowercased()) }
return match.isEmpty ? nil : .commands(match)
}
if current == nil, typed.hasPrefix("@"), MochiThreads.mention(in: text, among: mochis) == nil {
if mochis.isEmpty { return .noMochis }
let after = typed.dropFirst().lowercased()
let match = mochis.filter { after.isEmpty || $0.name.lowercased().hasPrefix(after) }
return match.isEmpty ? nil : .mochis(match)
}
return nil
}
private func pickerPanel(_ p: ChatPicker) -> some View {
VStack(alignment: .leading, spacing: 0) {
switch p {
case .mochis(let list):
ForEach(list.prefix(6)) { m in
pickerRow {
MochiLive(state: .idle, bodyHex: m.color, outfit: Outfit.mochiParts(m.outfit).head, fps: 30)
.frame(width: 28, height: 28)
} title: { m.name } detail: { m.enabled ? m.wake : "Off · \(m.wake)" } action: {
text = "@\(m.name) "
}
}
case .commands(let list):
ForEach(list) { c in
pickerRow {
Image(systemName: c.symbol)
.font(.system(size: 13, weight: .semibold))
.foregroundStyle(Color.botan)
.frame(width: 28, height: 28)
.background(Color.botan.opacity(0.15), in: Circle())
} title: { c.name } detail: { c.detail } action: {
runCommand(c)
}
}
case .noMochis:
HStack(alignment: .top, spacing: 12) {
Image(systemName: "laptopcomputer.and.iphone")
.font(.system(size: 15, weight: .semibold))
.foregroundStyle(.secondary)
.frame(width: 28, height: 28)
VStack(alignment: .leading, spacing: 3) {
Text("No Mochis from your Mac yet").font(.subheadline.weight(.semibold))
Text("On the Mac: Coucou → Settings → Devices → iPhone, turn on both switches. They show up here within a minute.")
.font(.footnote)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
.padding(12)
}
}
.padding(.vertical, 4)
.frame(maxWidth: .infinity, alignment: .leading)
.background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 20, style: .continuous))
.overlay(RoundedRectangle(cornerRadius: 20, style: .continuous).strokeBorder(Color.white.opacity(0.1), lineWidth: 0.5))
.environment(\.colorScheme, .dark)
}
private func pickerRow<Icon: View>(@ViewBuilder icon: () -> Icon, title: () -> String, detail: () -> String,
action: @escaping () -> Void) -> some View {
Button {
Haptics.impact()
withAnimation(.spring(duration: 0.3, bounce: 0.15)) { action() }
} label: {
HStack(spacing: 12) {
icon()
VStack(alignment: .leading, spacing: 1) {
Text(title()).font(.subheadline.weight(.semibold)).foregroundStyle(.white)
Text(detail()).font(.caption).foregroundStyle(.secondary).lineLimit(1)
}
Spacer(minLength: 0)
}
.padding(.horizontal, 12)
.padding(.vertical, 8)
.contentShape(Rectangle())
}
.buttonStyle(PressableButtonStyle())
}
/// A command picked, or typed and sent.
private func runCommand(_ c: SlashCommand) {
switch c.name {
case "/mochi": text = "@"
case "/team": text = "/team "
case "/botan":
text = ""
threads.selected = nil
default:
text = ""
ask(c.says)
}
}
/// A Mochi's thread: who it is, what it did (newest at the bottom), what waits for your tap.
private func mochiConversation(_ m: PhoneMochi) -> some View {
let lines = threads.lines(for: m)
return ScrollView {
LazyVStack(alignment: .leading, spacing: 10) {
VStack(spacing: 8) {
MochiLive(state: m.running ? .working : (m.enabled ? .idle : .sleeping), bodyHex: m.color,
outfit: Outfit.mochiParts(m.outfit).head)
.frame(width: 76)
Text(m.name).font(.title3.weight(.semibold))
Text(m.enabled ? m.wake : "Off · \(m.wake)")
.font(.footnote)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
if let next = m.next, m.enabled {
Text("Next: \(next.formatted(.relative(presentation: .named)))")
.font(.caption)
.foregroundStyle(.tertiary)
}
}
.frame(maxWidth: .infinity)
.padding(.bottom, 10)
if lines.isEmpty {
Text("Nothing yet. Say \"run\" and it starts on your Mac.")
.font(.subheadline)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity)
}
ForEach(lines) { line in mochiBubble(line, m) }
ForEach(m.waiting, id: \.t) { p in proposalCard(p, m) }
if threads.answering.contains(m.id) {
HStack(alignment: .bottom, spacing: 8) {
MochiLive(state: .thinking, bodyHex: m.color, outfit: Outfit.mochiParts(m.outfit).head)
.frame(width: 30, height: 30)
Image(systemName: "ellipsis")
.font(.title3.weight(.bold))
.foregroundStyle(.secondary)
.symbolEffect(.variableColor.iterative.dimInactiveLayers, options: .repeating)
.frame(width: 44, height: 22)
.padding(.horizontal, 14)
.padding(.vertical, 9)
.background(Color.white.opacity(0.08), in: RoundedRectangle(cornerRadius: 19, style: .continuous))
}
}
}
.padding(.horizontal, 14)
.padding(.top, 20)
.padding(.bottom, 12)
}
.defaultScrollAnchor(.bottom)
.scrollDismissesKeyboard(.interactively)
}
@ViewBuilder private func mochiBubble(_ line: MochiThreads.Line, _ m: PhoneMochi) -> some View {
if line.fromYou {
HStack {
Spacer(minLength: 48)
Text(line.text)
.foregroundStyle(.white)
.padding(.horizontal, 14)
.padding(.vertical, 9)
.yourBubble()
.textSelection(.enabled)
}
} else {
HStack(alignment: .bottom, spacing: 8) {
MochiLive(state: line.failed ? .error : .idle, bodyHex: m.color, outfit: Outfit.mochiParts(m.outfit).head, fps: 30)
.frame(width: 30, height: 30)
// a run (it has a title) shows folded: its title and one line; a tap unfolds it
let run = !line.title.isEmpty
let open = !run || unfolded.contains(line.id)
VStack(alignment: .leading, spacing: 4) {
if run {
HStack(alignment: .firstTextBaseline, spacing: 8) {
Text(line.title)
.font(.subheadline.weight(.semibold))
.lineLimit(open ? nil : 2)
Spacer(minLength: 4)
Image(systemName: "chevron.down")
.font(.caption.weight(.bold))
.foregroundStyle(.tertiary)
.rotationEffect(.degrees(open ? 180 : 0))
}
}
if !line.text.isEmpty {
if open {
Text(StreamingText.styled(line.text))
.font(run ? .subheadline : .body)
.foregroundStyle(line.failed || run ? .secondary : .primary)
.transition(.opacity)
} else {
Text(MochiThreads.summary(line.text))
.font(.footnote)
.foregroundStyle(.secondary)
.lineLimit(2)
}
}
Text(line.date.formatted(.relative(presentation: .named)))
.font(.caption2)
.foregroundStyle(.tertiary)
}
.textSelection(.enabled)
.padding(.horizontal, 14)
.padding(.vertical, 9)
.frame(maxWidth: run ? .infinity : nil, alignment: .leading)
.background(Color.white.opacity(0.08), in: RoundedRectangle(cornerRadius: 19, style: .continuous))
.overlay(RoundedRectangle(cornerRadius: 19, style: .continuous).strokeBorder(Color(hex: m.color).opacity(0.25), lineWidth: 0.5))
.contentShape(RoundedRectangle(cornerRadius: 19, style: .continuous))
.onTapGesture {
guard run else { return }
Haptics.impact()
withAnimation(.spring(duration: 0.35, bounce: 0.12)) {
if open { unfolded.remove(line.id) } else { unfolded.insert(line.id) }
}
}
Spacer(minLength: 32)
}
}
}
/// Something it made that waits for you: open the PR or post it, or drop it. Only on a tap.
private func proposalCard(_ p: PhoneMochi.Proposal, _ m: PhoneMochi) -> some View {
let done = threads.sent.contains(p.t)
return VStack(alignment: .leading, spacing: 10) {
HStack(spacing: 8) {
Image(systemName: p.type == "pr" ? "arrow.triangle.pull" : "text.bubble")
.foregroundStyle(Color(hex: m.color))
Text(p.title).font(.subheadline.weight(.semibold))
}
if done {
Text("Sent to your Mac.").font(.footnote).foregroundStyle(.secondary)
} else {
HStack(spacing: 10) {
Button {
Haptics.impact()
Task { await threads.act(true, on: p, of: m) }
} label: {
Text(p.type == "pr" ? "Open the PR" : p.type == "review" ? "Post the review" : "Post the reply")
.font(.footnote.weight(.semibold))
.foregroundStyle(.white)
.padding(.horizontal, 14)
.padding(.vertical, 8)
.background(Color(hex: m.color).opacity(0.55), in: Capsule())
}
.buttonStyle(PressableButtonStyle())
Button {
Task { await threads.act(false, on: p, of: m) }
} label: {
Text("Drop").font(.footnote.weight(.semibold)).foregroundStyle(.secondary)
}
.buttonStyle(PressableButtonStyle())
}
}
}
.padding(14)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color(hex: m.color).opacity(0.12), in: RoundedRectangle(cornerRadius: 18, style: .continuous))
.overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).strokeBorder(Color(hex: m.color).opacity(0.35), lineWidth: 0.5))
.padding(.leading, 38)
}
// MARK: Composer
/// One glass capsule: the field, the mic and the send button inside it, like Messages.
private var composer: some View {
let empty = text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
return HStack(alignment: .bottom, spacing: 0) {
TextField(current.map { "Message \($0.name)…" } ?? "Ask Botan… (@ a Mochi)", text: $text, axis: .vertical)
.lineLimit(1...6)
.focused($focused)
.padding(.leading, 16)
.padding(.vertical, 11)
if empty {
Button {
Task { await dictation.toggle(startingFrom: text) }
} label: {
Image(systemName: dictation.isRecording ? "waveform" : "mic.fill")
.foregroundStyle(dictation.isRecording ? Color.red : Color.secondary)
.symbolEffect(.variableColor.iterative, isActive: dictation.isRecording)
.frame(width: 44, height: 42)
}
.transition(.scale.combined(with: .opacity))
} else {
Button {
ask(text)
} label: {
Image(systemName: "arrow.up")
.font(.subheadline.weight(.bold))
.foregroundStyle(.white)
.frame(width: 32, height: 32)
.background(Color.botan, in: Circle())
.padding(5)
}
.buttonStyle(PressableButtonStyle())
.disabled(current == nil ? chat.answering : threads.answering.contains(current?.id ?? ""))
.transition(.scale.combined(with: .opacity))
}
}
.animation(.spring(duration: 0.3), value: empty)
.glassPill(RoundedRectangle(cornerRadius: 22, style: .continuous))
.padding(.horizontal, 12)
.padding(.bottom, 6)
}
private func ask(_ question: String) {
dictation.stop()
let typed = question.trimmingCharacters(in: .whitespacesAndNewlines)
// "/team <mission>": the Mac's team lead makes a plan, shown above the field
if current == nil, typed.lowercased().hasPrefix("/team ") {
let goal = String(typed.dropFirst(6)).trimmingCharacters(in: .whitespaces)
guard goal.count >= 3 else { return }
text = ""
focused = false
Haptics.impact()
Task { _ = await threads.plan(goal) }
return
}
if typed.hasPrefix("/"), !typed.contains(" ") {
let all = current == nil ? Self.botanCommands : Self.mochiCommands
if let c = all.first(where: { $0.name == typed.lowercased() }) ?? all.first(where: { $0.name.hasPrefix(typed.lowercased()) }) {
runCommand(c)
return
}
}
// "@someone" that isn't one of the Mac's Mochis: stays in the field, the panel says why
if current == nil, typed.hasPrefix("@"), MochiThreads.mention(in: typed, among: mochis) == nil {
Haptics.warning()
return
}
// a Mochi's thread, or "@Name …" from Botan's: the words go to that Mochi
let target: (PhoneMochi, String)? = current.map { ($0, question) } ?? MochiThreads.mention(in: question, among: mochis)
if let target {
let (m, words) = target
text = ""
Haptics.impact()
withAnimation(Self.move) { threads.selected = m.id }
guard !words.trimmingCharacters(in: .whitespaces).isEmpty else { return }
focused = false
Task { await threads.send(words, to: m) }
return
}
var started: String?
// Inside the animation: the welcome fades, the chips fold, the bubbles rise.
withAnimation(Self.move) {
started = chat.begin(question)
}
guard let started else { return }
text = ""
focused = false
Haptics.impact()
Task { await chat.respond(to: started) }
}
}
// MARK: - Text that writes itself
/// Botan's answer, written letter by letter whatever chunks the model sends: the shown part
/// catches up smoothly and its last letters fade in.
struct StreamingText: View {
let text: String
@State private var shown: Double
/// Letters that are still fading in, at the end.
private static let tail = 10.0
init(text: String, animate: Bool) {
self.text = text
_shown = State(initialValue: animate ? 0 : .greatestFiniteMagnitude)
}
var body: some View {
let full = Self.styled(text)
let total = full.characters.count
Group {
if shown >= Double(total) + Self.tail {
Text(full)
} else {
let count = min(total, max(0, Int(shown)))
let end = full.characters.index(full.startIndex, offsetBy: count)
Text(AttributedString(full[full.startIndex..<end]))
.textRenderer(FadingTail(shown: shown, tail: Self.tail))
}
}
.textSelection(.enabled)
.task(id: text) {
// Faster when far behind, never slower than a quick typing pace.
while !Task.isCancelled, shown < Double(total) + Self.tail {
let behind = Double(total) - shown
shown += max(0.7, behind / 12)
try? await Task.sleep(for: .milliseconds(16))
}
}
}
/// Bold, italics and code from the model's answer; plain text when it isn't Markdown.
static func styled(_ text: String) -> AttributedString {
(try? AttributedString(markdown: text, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)))
?? AttributedString(text)
}
}
/// Draws the text with its newest letters fading in.
private struct FadingTail: TextRenderer {
var shown: Double
var tail: Double
func draw(layout: Text.Layout, in context: inout GraphicsContext) {
var index = 0.0
for line in layout {
for run in line {
for slice in run {
var copy = context
copy.opacity = max(0, min(1, (shown - index) / tail))
copy.draw(slice)
index += 1
}
}
}
}
}
// MARK: - Background
/// The chat's background: black, with a Botan-orange glow breathing and drifting at the bottom.
struct ChatBackdrop: View {
var active: Bool
/// Moves only while on screen (the tab view keeps hidden tabs alive).
@State private var visible = false
var body: some View {
TimelineView(.animation(minimumInterval: 1 / 30, paused: !visible)) { context in
let t = context.date.timeIntervalSinceReferenceDate * (active ? 0.7 : 0.35)
let glow = 0.42 + 0.1 * sin(t * 0.8) + (active ? 0.12 : 0)
MeshGradient(
width: 3, height: 3,
points: [
[0, 0], [0.5, 0], [1, 0],
[0, 0.55 + Self.wave(t, 1.3, 0.05)],
[0.5 + Self.wave(t, 2.1, 0.14), 0.62 + Self.wave(t * 1.3, 0.7, 0.07)],
[1, 0.55 + Self.wave(t, 2.9, 0.05)],
[0, 1], [0.5 + Self.wave(t * 0.9, 1.9, 0.22), 1], [1, 1],
],
colors: [
.black, .black, .black,
.black, Color(red: 0.03, green: 0.015, blue: 0.01), .black,
Color(red: 0.12, green: 0.035, blue: 0.01), Color.botan.opacity(glow), Color(red: 0.1, green: 0.03, blue: 0.01),
]
)
}
.background(Color.black)
.onAppear { visible = true }
.onDisappear { visible = false }
}
private static func wave(_ t: Double, _ phase: Double, _ amount: Double) -> Float {
Float(sin(t + phase) * amount)
}
}
private extension View {
/// Your bubbles: the same see-through glass as Botan's, in Botan's orange. The background
/// shows through (darker over the black, warmer over the glow), with a faint orange edge.
func yourBubble() -> some View {
let shape = RoundedRectangle(cornerRadius: 19, style: .continuous)
return self
.background(Color.botan.opacity(0.26), in: shape)
.overlay(shape.strokeBorder(Color.botan.opacity(0.35), lineWidth: 0.5))
}
}