Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(macos): stabilize chat scrolling and message actions

leepokai3da281ecad10
diff --git a/docs/design/macos-chat.md b/docs/design/macos-chat.md
new file mode 100644
index 00000000..97615d9b
--- /dev/null
+++ b/docs/design/macos-chat.md
@@ -0,0 +1,107 @@
+# macOS chat interaction
+
+The reference is the locally installed Grok Bot 0.66.0 desktop chat. Codync renders
+its own messages and actions in SwiftUI; it does not embed Electron or a web view.
+The scope is the transcript, bubbles, composer and inspector controls, not the
+roster, account pages or Grok-specific services.
+
+## Scrolling
+
+Both Mac transcripts use `MacChatList`: an AppKit `NSScrollView` with a flipped
+document and individual SwiftUI hosting controllers for nearby rows. Native
+wheel and momentum scrolling move the document without publishing its offset
+into SwiftUI. A coalesced bounds notification reconciles the viewport plus one
+screen of overscan on each side. Unchanged, mounted rows keep their SwiftUI root
+and frame; rows leaving this range release their hosting controllers.
+If a large movement would expose an unmounted row, reconciliation runs before
+returning from the bounds notification. Incoming views are laid out before they
+are revealed, and outgoing views retire within the same non-animated layer
+transaction. Individual row hosting views do not inherit window safe-area insets.
+
+`MacChatLayout` keeps measured heights and prefix positions by stable message
+ID. Only new/changed mounted rows are measured. Width and typography changes
+invalidate measurements; existing heights remain estimates until replacement
+measurements arrive. Row-local height changes (for example loaded images) also
+update the index. Every geometry correction preserves a message ID and pixel
+offset within it, or the bottom if the reader is following. Reflow preserves the
+message and pixel offset, not a semantic paragraph location.
+
+The main conversation initially exposes the newest 40 chat items; older pages
+are added near the top or through **Load earlier messages**. Loaded history keeps
+its data and height estimates, not all of its SwiftUI views. The conversation has
+two states: following the newest message and reading history. Scrolling up
+releases the bottom; arriving back at the end or **Jump to latest** restores it.
+Content growth alone cannot change this state. Page Up/Down and beginning/end
+commands use the same policy. This implementation supports macOS 14 and later.
+An outstanding wheel-state report takes precedence over an older SwiftUI binding
+update, so it cannot be mistaken for a command to jump back to the end. Height
+reports carry a hosting-root generation and are coalesced; retired/replaced roots
+cannot correct the current scroll position. Follow-state and chrome-inset changes
+do not rebuild unchanged message roots.
+
+Completed message rows and Markdown blocks skip redundant body work. Both Apple
+renderers use MarkdownBlocks for tables, rules and repairing unfinished Markdown.
+The Mac does not animate paragraph interpolation as tokens arrive. Reply threads
+use the same following rules as the main transcript.
+
+Closed anchored menus report a constant zero geometry instead of writing their
+global position into state on every scroll frame. Only an open menu tracks its
+anchor. Native hosted rows convert their anchors to window coordinates before
+presentation. This applies to Mac message context menus and dropdowns; iPhone message
+context menus already use the system implementation.
+
+## Appearance and controls
+
+The Mac has a single composer capsule containing attachment, input and send/stop/
+call controls. Chat text uses a local typography adjustment without changing
+shared typography defaults or iPhone chrome. Agent bubbles reserve space beside
+them for compact reaction, reply and more actions. Hover controls do not change
+message height. Message dates remain available in tooltips.
+
+On Mac, `conversationInset` overlays the header and composer on a full-height
+native viewport. Their measured heights become document padding rather than
+shrinking the scroll view. Messages can therefore pass underneath both controls,
+through mirrored material/gradient fades. The last message still clears the
+composer at the bottom, and the jump button sits above it. On iPhone this helper
+delegates to the existing system safe-area inset with unchanged spacing.
+
+`<<` opens Details, replacing an open reply thread in the inspector slot. `>>`
+closes Details. Both retain the conversation view and its following state.
+Opening the inspector does not interpolate paragraph wrapping. A compact Details
+presentation dismisses when the window becomes wide enough for the inspector.
+Inspector transitions use a short 20-point slide and fade with `Motion.morph`.
+Floating chevrons, inspector actions and Jump to latest share one clipped circular
+surface, including hover and press feedback. Directional arrows move subtly on
+hover/press; pressing scales the surface to 94 percent. Reduce Motion disables
+these translations and scaling. No rounded-rectangle button background is layered
+outside the circle.
+
+The smile action opens a compact horizontal reaction strip, using the same emoji
+controls as the message's context menu. Short replies keep their action cluster
+beside the bubble, inside its hover region. Menu presentation waits for a nonzero
+anchor before the Mac modal host captures its contents. iPhone keeps its native
+context menu; Linux GTK and TUI keep their existing reaction pickers.
+
+## Platform scope and verification
+
+The iPhone implementations were inspected: they already have separate paging,
+streaming and gesture-aware following. Their control placement and typography
+remain unchanged. Linux GTK (`ui.rs`, `rows.rs`) and TUI (`app.rs`, `view.rs`) use
+their own native scrolling/rendering; SwiftUI text interpolation, hover layout
+and macOS inspector transitions do not apply. No protocol or action is added.
+
+Validation includes geometry tests for 10,000 items and very tall messages,
+native scroll-container tests that verify offscreen hosting replacement, stable
+reading position during content growth, bottom following, and no SwiftUI root
+rebuild while scrolling inside an already mounted message. macOS and iOS
+Simulator builds cover the shared source. Computer-use checks cover native
+scrolling, right-click anchors and inspector controls.
+Regression tests also cover stale follow bindings, retired height reports,
+synchronous viewport coverage and floating-chrome document padding.
+
+Time Profiler recordings are diagnostic, not a controlled frame-time benchmark;
+Computer Use's accessibility collection and recorder startup must be excluded
+from scrolling samples. No 60/120 Hz or identical-to-Grok performance claim is
+made. Real trackpad momentum, live streaming and attachment-heavy histories still
+need broader user testing. Virtualization can discard offscreen row-local UI
+state and text selection when its row leaves the overscan region.
diff --git a/kit/Sources/CodyncUI/Controls.swift b/kit/Sources/CodyncUI/Controls.swift
index 00217bbd..6082ab86 100644
--- a/kit/Sources/CodyncUI/Controls.swift
+++ b/kit/Sources/CodyncUI/Controls.swift
@@ -196,7 +196,7 @@ public struct MenuPanel: View {
VStack(alignment: .leading, spacing: 2) {
if let reactions {
ReactionStrip(pick: reactions, dismiss: dismiss)
- .padding(.bottom, 4)
+ .padding(.bottom, items.isEmpty ? 0 : 4)
}
ForEach(items) { item in
if item.divider {
@@ -215,7 +215,7 @@ public struct MenuPanel: View {
.onGeometryChange(for: CGFloat.self) { $0.size.height } action: { contentHeight = $0 }
}
.scrollBounceBehavior(.basedOnSize)
- .frame(width: min(320, availableSize.width),
+ .frame(width: min(preferredWidth, availableSize.width),
height: min(contentHeight ?? estimatedHeight, availableSize.height))
.clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
.onChange(of: contentHeight) { _, height in
@@ -232,6 +232,13 @@ public struct MenuPanel: View {
+ (reactions == nil ? 0 : InterfaceMetrics.value(mac: 32, mobile: 46))
}
+ private var preferredWidth: CGFloat {
+ #if os(macOS)
+ if items.isEmpty, let reactions { return CGFloat(reactions.emoji.count) * 26 + 12 }
+ #endif
+ return 320
+ }
+
}
/// Quick-reaction buttons; a chosen one is highlighted and tapping it takes it back.
@@ -400,14 +407,35 @@ private struct AnchoredMenu: ViewModifier {
let items: () -> [MenuItem]
var reactions: ReactionPick?
@State private var frame: CGRect = .zero
+ #if os(macOS)
+ @Environment(\.macChatCoordinates) private var chatCoordinates
+ #endif
func body(content: Content) -> some View {
content
- .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame = $0 }
- .codyncOverlay(isPresented: $isPresented) { close in
- let anchor = point.map { CGRect(x: frame.minX + $0.x, y: frame.minY + $0.y, width: 0, height: 0) } ?? frame
- AnchoredPanel(anchor: anchor, close: close) {
- MenuPanel(items: items(), reactions: reactions, dismiss: close)
+ // Closed menus have no anchor to position. Tracking their global frame
+ // invalidates every message's menu on every scroll frame.
+ .onGeometryChange(for: CGRect.self) {
+ guard isPresented else { return .zero }
+ return $0.frame(in: .global)
+ } action: { measured in
+ #if os(macOS)
+ frame = measured == .zero ? .zero : chatCoordinates?.windowFrame(measured) ?? measured
+ #else
+ frame = measured
+ #endif
+ }
+ // The Mac modal host captures its content when presentation starts.
+ // Wait for the opening geometry pass so it cannot capture EmptyView.
+ .codyncOverlay(isPresented: Binding(
+ get: { isPresented && frame != .zero },
+ set: { if !$0 { isPresented = false } }
+ )) { close in
+ if frame != .zero {
+ let anchor = point.map { CGRect(x: frame.minX + $0.x, y: frame.minY + $0.y, width: 0, height: 0) } ?? frame
+ AnchoredPanel(anchor: anchor, close: close) {
+ MenuPanel(items: items(), reactions: reactions, dismiss: close)
+ }
}
}
}
@@ -455,6 +483,21 @@ struct AnchoredPanel<Panel: View>: View {
}
}
+#if os(macOS)
+/// The message action opens the same horizontal quick reactions as right-click.
+struct ReactionMenu<Label: View>: View {
+ let pick: ReactionPick
+ @ViewBuilder let label: () -> Label
+ @State private var open = false
+
+ var body: some View {
+ Button { open.toggle() } label: { label() }
+ .buttonStyle(.plain)
+ .modifier(AnchoredMenu(isPresented: $open, point: nil, items: { [] }, reactions: pick))
+ }
+}
+#endif
+
/// A button that opens a Codync menu.
public struct DropdownMenu<Label: View>: View {
let items: () -> [MenuItem]
diff --git a/kit/Sources/CodyncUI/Thread/ChatRows.swift b/kit/Sources/CodyncUI/Thread/ChatRows.swift
index 4d97538f..9e53d6d7 100644
--- a/kit/Sources/CodyncUI/Thread/ChatRows.swift
+++ b/kit/Sources/CodyncUI/Thread/ChatRows.swift
@@ -123,6 +123,22 @@ struct ThreadChip: View {
}
}
+private var chatAgentFill: Color {
+ #if os(macOS)
+ Color(light: 0xEEEEEE, dark: 0x262626)
+ #else
+ Palette.bubbleAgent
+ #endif
+}
+
+private var chatUserFill: Color {
+ #if os(macOS)
+ Color(light: 0xE2E2E2, dark: 0x545454)
+ #else
+ Palette.bubbleUser
+ #endif
+}
+
struct UserBubble: View {
let entry: Entry
let botWorking: Bool
@@ -138,17 +154,22 @@ struct UserBubble: View {
}
if !(entry.data.text ?? "").isEmpty { text }
#if os(macOS)
- HStack(spacing: 6) {
- if hovering, entry.data.status == nil || entry.data.status == "sent" {
- MessageActions(reactions: model.reactionPick(entry), reply: reply) { Pasteboard.copy(entry.data.text) }
- }
- status
- }
- .frame(minHeight: MessageActions.height)
+ if let state = entry.data.status, state != "sent" { status }
#else
status
#endif
}
+ #if os(macOS)
+ .overlay(alignment: .bottomLeading) {
+ MessageActions(reactions: model.reactionPick(entry), reply: reply) { Pasteboard.copy(entry.data.text) }
+ .offset(x: -88)
+ .opacity(hovering ? 1 : 0)
+ .allowsHitTesting(hovering)
+ .accessibilityHidden(!hovering)
+ }
+ .padding(.leading, 88)
+ .help(entry.date.formatted(date: .abbreviated, time: .shortened))
+ #endif
.hoverTracking($hovering)
.frame(maxWidth: .infinity, alignment: .trailing)
.padding(.leading, 56)
@@ -161,7 +182,7 @@ struct UserBubble: View {
.textSelection(.enabled)
.padding(.horizontal, InterfaceMetrics.value(mac: 12, mobile: 16))
.padding(.vertical, InterfaceMetrics.value(mac: 8, mobile: 10))
- .background(Palette.bubbleUser, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
+ .background(chatUserFill, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
.contextActions(reactions: model.reactionPick(entry)) {
var items = [MenuItem("Copy", icon: "square.on.square") { Pasteboard.copy(entry.data.text) }]
if let reply { items.append(MenuItem("Reply in thread", icon: "arrowshape.turn.up.left", action: reply)) }
@@ -202,6 +223,7 @@ struct UserBubble: View {
default:
#if os(macOS)
Text(entry.date, style: .time).appFont(.system(size: 10)).foregroundStyle(Palette.tertiary)
+ .opacity(hovering ? 1 : 0)
#else
EmptyView()
#endif
@@ -228,6 +250,7 @@ struct AgentBubble: View {
.transition(.opacity)
#else
MarkdownText(entry.data.text ?? "", streaming: entry.data.final == false)
+ .equatable()
#endif
}
@@ -236,7 +259,7 @@ struct AgentBubble: View {
text
.padding(.horizontal, InterfaceMetrics.value(mac: 12, mobile: 16))
.padding(.vertical, InterfaceMetrics.value(mac: 8, mobile: 10))
- .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
+ .background(chatAgentFill, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
.contextActions(reactions: model.reactionPick(entry)) {
var items = [
MenuItem("Copy", icon: "square.on.square") { Pasteboard.copy(entry.data.text) },
@@ -245,31 +268,48 @@ struct AgentBubble: View {
if let reply { items.insert(MenuItem("Reply in thread", icon: "arrowshape.turn.up.left", action: reply), at: 1) }
return items
}
- #if os(macOS)
- HStack(spacing: 6) {
- Text(entry.date, style: .time)
- .appFont(.system(size: 10))
- .foregroundStyle(Palette.tertiary)
- if hovering {
- MessageActions(reactions: model.reactionPick(entry), reply: reply, trace: openTrace) {
- Pasteboard.copy(entry.data.text)
- }
- }
- }
- .padding(.leading, 12)
- .frame(minHeight: MessageActions.height)
- #endif
}
- .frame(maxWidth: .infinity, alignment: .leading)
#if os(macOS)
- .padding(.trailing, 64)
- #else
+ .overlay(alignment: .bottomTrailing) {
+ MessageActions(reactions: model.reactionPick(entry), reply: reply, trace: openTrace) {
+ Pasteboard.copy(entry.data.text)
+ }
+ .offset(x: 88)
+ .opacity(hovering ? 1 : 0)
+ .allowsHitTesting(hovering)
+ .accessibilityHidden(!hovering)
+ }
+ .padding(.trailing, 88)
+ .help(entry.date.formatted(date: .abbreviated, time: .shortened))
+ #endif
+ .hoverTracking($hovering)
+ #if os(macOS)
+ .modifier(MacAgentBubbleWidth())
+ #endif
+ .frame(maxWidth: .infinity, alignment: .leading)
+ #if os(iOS)
.animation(Motion.reduced(Motion.layout, reduceMotion), value: entry.id)
.padding(.trailing, 40)
#endif
}
}
+#if os(macOS)
+private struct MacAgentBubbleWidth: ViewModifier {
+ @Environment(\.macChatWidth) private var nativeWidth
+
+ @ViewBuilder func body(content: Content) -> some View {
+ if let nativeWidth {
+ content.frame(width: max(80, min((nativeWidth + 32) * 0.8 - 32, nativeWidth - 88)) + 88, alignment: .leading)
+ } else {
+ content.containerRelativeFrame(.horizontal, alignment: .leading) { width, _ in
+ max(80, min(min(820, width) * 0.8 - 32, width - 120)) + 88
+ }
+ }
+ }
+}
+#endif
+
struct NoticeRow: View {
let entry: Entry
@@ -446,8 +486,7 @@ private struct HoverTracking: ViewModifier {
}
}
-/// Mac: a message's quick actions, in its footer beside the time while the pointer is over it
-/// (next to the bubble, never on it): reactions, reply in thread, what it did, copy.
+/// Compact actions beside the bubble; showing them never changes a message's height.
struct MessageActions: View {
static let height: CGFloat = 26
let reactions: ReactionPick
@@ -456,21 +495,47 @@ struct MessageActions: View {
let copy: () -> Void
var body: some View {
- HStack(spacing: 0) {
- ReactionStrip(pick: reactions)
- Rectangle().fill(Palette.text.opacity(0.12)).frame(width: 1, height: 12).padding(.horizontal, 4)
- if let reply { action("Reply in thread", "arrowshape.turn.up.left", reply) }
- if let trace { action("Show what it did", "list.bullet", trace) }
- action("Copy", "square.on.square", copy)
+ HStack(spacing: 2) {
+ #if os(macOS)
+ ReactionMenu(pick: reactions) { symbol("face.smiling", title: "Add reaction") }
+ #else
+ DropdownMenu {
+ reactions.emoji.map { emoji in
+ MenuItem(emoji, selected: reactions.chosen.contains(emoji)) { reactions.toggle(emoji) }
+ }
+ } label: { symbol("face.smiling", title: "Add reaction") }
+ #endif
+ if let reply {
+ Button("Reply in thread", systemImage: "arrowshape.turn.up.left", action: reply)
+ .labelStyle(.iconOnly)
+ .buttonStyle(IconButtonStyle(size: Self.height))
+ .help("Reply in thread")
+ }
+ DropdownMenu {
+ var items = [MenuItem("Copy", icon: "square.on.square", action: copy)]
+ if let trace { items.append(MenuItem("Show what it did", icon: "list.bullet", action: trace)) }
+ return items
+ } label: { symbol("ellipsis", title: "More message actions") }
}
.fixedSize()
- .transition(.opacity)
}
- private func action(_ title: String, _ icon: String, _ run: @escaping () -> Void) -> some View {
- Button(title, systemImage: icon, action: run)
- .labelStyle(.iconOnly)
- .buttonStyle(IconButtonStyle(size: Self.height))
+ private func symbol(_ name: String, title: String) -> some View {
+ Image(systemName: name)
+ .font(.system(size: 14))
+ .foregroundStyle(Palette.secondary)
+ .frame(width: Self.height, height: Self.height)
+ .contentShape(Rectangle())
+ .accessibilityLabel(title)
.help(title)
}
}
+
+#if os(macOS)
+extension ChatRow: @MainActor Equatable {
+ static func == (a: Self, b: Self) -> Bool {
+ a.entry == b.entry && a.groupStart == b.groupStart && a.chat?.isGroup == b.chat?.isGroup
+ && a.chat?.isWorking == b.chat?.isWorking && (a.openThread == nil) == (b.openThread == nil)
+ }
+}
+#endif
diff --git a/kit/Sources/CodyncUI/Thread/Composer.swift b/kit/Sources/CodyncUI/Thread/Composer.swift
index 33f6e14a..aed3b86c 100644
--- a/kit/Sources/CodyncUI/Thread/Composer.swift
+++ b/kit/Sources/CodyncUI/Thread/Composer.swift
@@ -110,7 +110,9 @@ struct Composer: View {
private var field: some View {
HStack(alignment: .bottom, spacing: 8) {
- if canAttach { addButton }
+ #if os(iOS)
+ if canAttach { addButton }
+ #endif
VStack(alignment: .leading, spacing: 0) {
#if os(iOS)
let _ = clipboardTick
@@ -122,7 +124,9 @@ struct Composer: View {
box
}
.composerSurface(in: RoundedRectangle(cornerRadius: 24, style: .continuous))
- .animation(Motion.layout, value: draft)
+ #if os(iOS)
+ .animation(Motion.layout, value: draft)
+ #endif
}
.animation(Motion.layout, value: files.map(\.id))
#if os(iOS)
@@ -206,7 +210,7 @@ struct Composer: View {
.appFont(.system(size: size, weight: .bold))
.contentTransition(.symbolEffect(.replace))
.foregroundStyle(ink)
- .frame(width: state == .call ? buttonSize * 1.35 : buttonSize, height: buttonSize)
+ .frame(width: InterfaceMetrics.value(mac: buttonSize, mobile: state == .call ? buttonSize * 1.35 : buttonSize), height: buttonSize)
.background(fill, in: Capsule())
.contentShape(Capsule())
}
@@ -220,6 +224,11 @@ struct Composer: View {
private var box: some View {
HStack(alignment: .bottom, spacing: 8) {
+ #if os(macOS)
+ if canAttach {
+ addButton.padding(.bottom, max(0, (textLineHeight + 2 * fieldPadding - buttonSize) / 2))
+ }
+ #endif
TextField(placeholder, text: $draft, axis: .vertical)
.lineLimit(1...8)
.font(typography.body)
@@ -231,7 +240,7 @@ struct Composer: View {
.padding(.bottom, max(0, (textLineHeight + 2 * fieldPadding - buttonSize) / 2))
.animation(Motion.layout, value: isEmpty)
}
- .padding(.leading, InterfaceMetrics.value(mac: 14, mobile: 18))
+ .padding(.leading, InterfaceMetrics.value(mac: 8, mobile: 18))
.padding(.trailing, 6)
.padding(.vertical, boxPadding)
.onChange(of: model.routineDrafts[botId]) { _, value in
@@ -266,7 +275,8 @@ struct Composer: View {
Image(systemName: "plus")
.appFont(.system(size: InterfaceMetrics.value(mac: 13, mobile: 18), weight: .medium))
.foregroundStyle(Palette.text)
- .frame(width: fieldHeight, height: fieldHeight)
+ .frame(width: InterfaceMetrics.value(mac: buttonSize, mobile: fieldHeight),
+ height: InterfaceMetrics.value(mac: buttonSize, mobile: fieldHeight))
.composerSurface(in: Circle())
.contentShape(Circle())
}
diff --git a/kit/Sources/CodyncUI/Thread/ConversationFollow+macOS.swift b/kit/Sources/CodyncUI/Thread/ConversationFollow+macOS.swift
new file mode 100644
index 00000000..36b68bc7
--- /dev/null
+++ b/kit/Sources/CodyncUI/Thread/ConversationFollow+macOS.swift
@@ -0,0 +1,29 @@
+#if os(macOS)
+import CodyncKit
+import SwiftUI
+
+/// Scrolled away from the newest messages: a round button back down to them.
+struct MacJumpToLatest: View {
+ let visible: Bool
+ let action: () -> Void
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @Environment(\.macChatInsets) private var insets
+
+ var body: some View {
+ ZStack {
+ if visible {
+ Button("Jump to latest", systemImage: "arrow.down", action: action)
+ .labelStyle(.iconOnly)
+ .buttonStyle(MacChatButtonStyle(direction: CGSize(width: 0, height: 1)))
+ .shadow(color: .black.opacity(0.12), radius: 10, y: 3)
+ .help("Jump to latest")
+ .padding(.bottom, 10)
+ .transition(.offset(y: 6).combined(with: .opacity))
+ }
+ }
+ .animation(Motion.reduced(Motion.morph, reduceMotion), value: visible)
+ .padding(.bottom, insets.bottom)
+ }
+}
+
+#endif
diff --git a/kit/Sources/CodyncUI/Thread/ConversationInset.swift b/kit/Sources/CodyncUI/Thread/ConversationInset.swift
new file mode 100644
index 00000000..e3499c08
--- /dev/null
+++ b/kit/Sources/CodyncUI/Thread/ConversationInset.swift
@@ -0,0 +1,69 @@
+import CodyncKit
+import SwiftUI
+
+extension View {
+ /// SwiftUI scroll views understand safe-area underlap. The native Mac transcript
+ /// instead reserves document padding while keeping its viewport behind the chrome.
+ @ViewBuilder func conversationInset<Chrome: View>(edge: VerticalEdge, spacing: CGFloat? = nil,
+ @ViewBuilder content: () -> Chrome) -> some View {
+ #if os(macOS)
+ modifier(MacConversationInset(edge: edge, chrome: content()))
+ #else
+ safeAreaInset(edge: edge, spacing: spacing, content: content)
+ #endif
+ }
+}
+
+#if os(macOS)
+private struct MacConversationInset<Chrome: View>: ViewModifier {
+ let edge: VerticalEdge
+ let chrome: Chrome
+ @State private var height: CGFloat = 0
+ @Environment(\.macChatInsets) private var inherited
+
+ private var insets: EdgeInsets {
+ var result = inherited
+ if edge == .top { result.top += height }
+ else { result.bottom += height }
+ return result
+ }
+
+ func body(content: Content) -> some View {
+ content
+ .environment(\.macChatInsets, insets)
+ .overlay(alignment: edge == .top ? .top : .bottom) {
+ chrome
+ .onGeometryChange(for: CGFloat.self) { ceil($0.size.height) } action: { height = $0 }
+ .background {
+ ConversationEdgeFade(edge: edge)
+ .padding(edge == .top ? .bottom : .top, -24)
+ }
+ }
+ }
+}
+
+/// The material samples the transcript below it; the gradient hides only the outer
+/// edge, leaving text visible through the transition into the floating controls.
+private struct ConversationEdgeFade: View {
+ let edge: VerticalEdge
+
+ var body: some View {
+ let start: UnitPoint = edge == .top ? .top : .bottom
+ let end: UnitPoint = edge == .top ? .bottom : .top
+ ZStack {
+ Rectangle().fill(.ultraThinMaterial)
+ .mask(LinearGradient(colors: [.black, .clear], startPoint: start, endPoint: end))
+ LinearGradient(stops: [.init(color: Palette.background.opacity(0.9), location: 0),
+ .init(color: Palette.background.opacity(0.45), location: 0.4),
+ .init(color: .clear, location: 1)],
+ startPoint: start, endPoint: end)
+ }
+ .allowsHitTesting(false)
+ .accessibilityHidden(true)
+ }
+}
+
+extension EnvironmentValues {
+ @Entry var macChatInsets = EdgeInsets()
+}
+#endif
diff --git a/kit/Sources/CodyncUI/Thread/MacChatButtonStyle.swift b/kit/Sources/CodyncUI/Thread/MacChatButtonStyle.swift
new file mode 100644
index 00000000..f45cc58d
--- /dev/null
+++ b/kit/Sources/CodyncUI/Thread/MacChatButtonStyle.swift
@@ -0,0 +1,46 @@
+#if os(macOS)
+import CodyncKit
+import SwiftUI
+
+/// One circular surface for floating chat controls, including hover/press feedback.
+struct MacChatButtonStyle: ButtonStyle {
+ var size: CGFloat = 32
+ var direction: CGSize = .zero
+
+ func makeBody(configuration: Configuration) -> some View {
+ ButtonContent(configuration: configuration, size: size, direction: direction)
+ }
+
+ private struct ButtonContent: View {
+ let configuration: Configuration
+ let size: CGFloat
+ let direction: CGSize
+ @State private var hovering = false
+ @Environment(\.isEnabled) private var enabled
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ var body: some View {
+ configuration.label
+ .appFont(.system(size: size / 2, weight: .medium))
+ .foregroundStyle(hovering ? Palette.text : Palette.secondary)
+ .offset(x: reduceMotion ? 0 : direction.width * (configuration.isPressed ? 1.5 : hovering ? 1 : 0),
+ y: reduceMotion ? 0 : direction.height * (configuration.isPressed ? 1.5 : hovering ? 1 : 0))
+ .frame(width: size, height: size)
+ .background {
+ Circle().fill(Color(light: 0xEEEEEE, dark: 0x303030))
+ .overlay {
+ Circle().fill(Palette.text.opacity(configuration.isPressed ? 0.12 : hovering ? 0.06 : 0))
+ }
+ }
+ .clipShape(Circle())
+ .contentShape(Circle())
+ .opacity(enabled ? 1 : 0.35)
+ .scaleEffect(configuration.isPressed && !reduceMotion ? 0.94 : 1)
+ .animation(Motion.reduced(configuration.isPressed ? Motion.press : Motion.morph, reduceMotion),
+ value: configuration.isPressed)
+ .animation(Motion.reduced(Motion.hover, reduceMotion), value: hovering)
+ .onHover { hovering = $0 }
+ }
+ }
+}
+#endif
diff --git a/kit/Sources/CodyncUI/Thread/MacChatLayout.swift b/kit/Sources/CodyncUI/Thread/MacChatLayout.swift
new file mode 100644
index 00000000..159d7f6e
--- /dev/null
+++ b/kit/Sources/CodyncUI/Thread/MacChatLayout.swift
@@ -0,0 +1,73 @@
+#if os(macOS)
+import Foundation
+
+/// Geometry only: scrolling does not publish SwiftUI state or rebuild messages.
+struct MacChatLayout {
+ struct Anchor: Equatable {
+ let id: String
+ let offset: CGFloat
+ }
+
+ private(set) var ids: [String] = []
+ private(set) var heights: [CGFloat] = []
+ private(set) var starts: [CGFloat] = []
+ private(set) var total: CGFloat = 20
+ private var top: CGFloat = 8
+ private var bottom: CGFloat = 12
+
+ mutating func setInsets(top: CGFloat, bottom: CGFloat) {
+ self.top = 8 + max(0, top)
+ self.bottom = 12 + max(0, bottom)
+ rebuild()
+ }
+
+ mutating func reset(ids: [String], heights: [CGFloat]) {
+ precondition(ids.count == heights.count)
+ self.ids = ids
+ self.heights = heights.map { max(1, $0.isFinite ? $0 : 100) }
+ rebuild()
+ }
+
+ mutating func measure(_ height: CGFloat, at index: Int) -> Bool {
+ guard height.isFinite, height > 0, abs(heights[index] - height) > 0.5 else { return false }
+ heights[index] = ceil(height)
+ rebuild()
+ return true
+ }
+
+ private mutating func rebuild() {
+ var y = top
+ starts = heights.map { height in
+ defer { y += height }
+ return y
+ }
+ total = y + bottom
+ }
+
+ func index(at y: CGFloat) -> Int? {
+ guard !ids.isEmpty else { return nil }
+ var lower = 0
+ var upper = ids.count
+ while lower < upper {
+ let middle = (lower + upper) / 2
+ if starts[middle] + heights[middle] <= y { lower = middle + 1 }
+ else { upper = middle }
+ }
+ return min(lower, ids.count - 1)
+ }
+
+ func visible(in viewport: CGRect, overscan: CGFloat) -> Range<Int> {
+ guard let first = index(at: viewport.minY - overscan),
+ let last = index(at: viewport.maxY + overscan) else { return 0..<0 }
+ return first..<(last + 1)
+ }
+
+ func anchor(at y: CGFloat) -> Anchor? {
+ index(at: y).map { Anchor(id: ids[$0], offset: y - starts[$0]) }
+ }
+
+ func offset(for anchor: Anchor) -> CGFloat? {
+ ids.firstIndex(of: anchor.id).map { starts[$0] + min(anchor.offset, heights[$0]) }
+ }
+}
+#endif
diff --git a/kit/Sources/CodyncUI/Thread/MacChatList.swift b/kit/Sources/CodyncUI/Thread/MacChatList.swift
new file mode 100644
index 00000000..34b36dab
--- /dev/null
+++ b/kit/Sources/CodyncUI/Thread/MacChatList.swift
@@ -0,0 +1,441 @@
+#if os(macOS)
+import AppKit
+import SwiftUI
+
+/// SwiftUI owns message contents. AppKit owns wheel/momentum scrolling and the
+/// document geometry; only rows within a screen of the viewport have hosting views.
+struct MacChatList<Item: Identifiable & Equatable, Row: View>: NSViewRepresentable where Item.ID == String {
+ let items: [Item]
+ @Binding var following: Bool
+ var revision: AnyHashable? = nil
+ var nearTop: () -> Void = {}
+ @ViewBuilder let row: (Item) -> Row
+
+ func makeNSView(context: Context) -> ChatScrollView {
+ let scroll = ChatScrollView()
+ context.coordinator.attach(scroll)
+ return scroll
+ }
+
+ func updateNSView(_ view: ChatScrollView, context: Context) {
+ context.coordinator.update(self, environment: context.environment)
+ }
+
+ func makeCoordinator() -> Coordinator { Coordinator() }
+
+ static func dismantleNSView(_ view: ChatScrollView, coordinator: Coordinator) {
+ view.changed = nil
+ view.gesture = nil
+ view.navigate = nil
+ coordinator.cells.removeAll()
+ }
+
+ @MainActor final class Coordinator {
+ final class Cell {
+ let controller: NSHostingController<AnyView>
+ let coordinates: MacChatCoordinates
+ var generation = 0
+
+ init(controller: NSHostingController<AnyView>, coordinates: MacChatCoordinates) {
+ self.controller = controller
+ self.coordinates = coordinates
+ }
+ }
+
+ struct HeightReport {
+ let height: CGFloat
+ let width: CGFloat
+ let generation: Int
+ }
+
+ struct Appearance: Equatable {
+ let fontSize: Double
+ let colorScheme: ColorScheme
+ let contrast: ColorSchemeContrast
+ let reduceMotion: Bool
+ let enabled: Bool
+ let locale: String
+ }
+
+ weak var scroll: ChatScrollView?
+ var source: MacChatList?
+ var environment = EnvironmentValues()
+ var items: [Item] = []
+ var layout = MacChatLayout()
+ var cached: [String: CGFloat] = [:]
+ var cells: [String: Cell] = [:]
+ var width: CGFloat = 0
+ var viewportSize: CGSize = .zero
+ var fontSize: Double = 0
+ var appearance: Appearance?
+ var insets = EdgeInsets()
+ var dirty = Set<String>()
+ var nextGeneration = 0
+ var pendingHeights: [String: HeightReport] = [:]
+ var pendingAnchor: MacChatLayout.Anchor?
+ var positionRequested = false
+ var updating = false
+ var follows = true
+ var pending = false
+ var arranging = false
+ var refresh = false
+ var reportedFollow = true
+ var pendingFollowReport: Bool?
+ var lastTopRequest: String?
+
+ func attach(_ scroll: ChatScrollView) {
+ self.scroll = scroll
+ scroll.changed = { [weak self] in self?.viewportChanged() }
+ scroll.gesture = { [weak self] before, event in
+ guard let self else { return }
+ if before, event.scrollingDeltaY > 0 { setFollowing(false) }
+ if !before {
+ if event.scrollingDeltaY < 0, distanceToEnd < 32 { setFollowing(true) }
+ if event.phase == .ended || event.momentumPhase == .ended || event.phase.isEmpty {
+ requestEarlierIfNeeded()
+ }
+ }
+ }
+ scroll.navigate = { [weak self] destination in
+ guard let self, let scroll = self.scroll else { return }
+ let end = max(0, layout.total - scroll.contentSize.height)
+ let y: CGFloat
+ switch destination {
+ case .previous: y = scroll.contentView.bounds.minY - scroll.contentSize.height * 0.9
+ case .next: y = scroll.contentView.bounds.minY + scroll.contentSize.height * 0.9
+ case .first: y = 0
+ case .last: y = end
+ }
+ setFollowing(y >= end)
+ scroll.contentView.scroll(to: CGPoint(x: 0, y: min(end, max(0, y))))
+ scroll.reflectScrolledClipView(scroll.contentView)
+ schedule()
+ requestEarlierIfNeeded()
+ }
+ }
+
+ var distanceToEnd: CGFloat {
+ guard let scroll else { return 0 }
+ return max(0, layout.total - scroll.contentSize.height) - scroll.contentView.bounds.minY
+ }
+
+ func update(_ source: MacChatList, environment: EnvironmentValues) {
+ updating = true
+ defer { updating = false }
+ let anchor = scroll.flatMap { layout.anchor(at: $0.contentView.bounds.minY) }
+ let old = Dictionary(uniqueKeysWithValues: items.map { ($0.id, $0) })
+ let oldHeights = Dictionary(uniqueKeysWithValues: zip(layout.ids, layout.heights))
+ let changed = source.items != items
+ let typographyChanged = fontSize != environment.conversationTypography.pointSize
+ let newAppearance = Appearance(fontSize: environment.conversationTypography.pointSize,
+ colorScheme: environment.colorScheme, contrast: environment.colorSchemeContrast,
+ reduceMotion: environment.accessibilityReduceMotion, enabled: environment.isEnabled,
+ locale: environment.locale.identifier)
+ refresh = refresh || appearance != newAppearance || self.source?.revision != source.revision
+ appearance = newAppearance
+ let insetsChanged = insets.top != environment.macChatInsets.top || insets.bottom != environment.macChatInsets.bottom
+ insets = environment.macChatInsets
+ self.source = source
+ self.environment = environment
+ fontSize = environment.conversationTypography.pointSize
+ // A binding update from our own wheel handler is not a jump command.
+ if let report = pendingFollowReport {
+ // SwiftUI may send one update with the old binding before our
+ // deferred wheel-state report arrives. It is not a jump command.
+ if source.following == report { pendingFollowReport = nil }
+ } else if source.following != reportedFollow {
+ follows = source.following
+ reportedFollow = source.following
+ positionRequested = source.following
+ }
+ items = source.items
+ let retained = Set(items.map(\.id))
+ cached = cached.filter { retained.contains($0.key) }
+ for item in items where old[item.id] != item {
+ cached[item.id] = nil
+ dirty.insert(item.id)
+ }
+ if typographyChanged { cached.removeAll() }
+ if changed || typographyChanged || insetsChanged {
+ if pendingAnchor == nil { pendingAnchor = anchor }
+ layout.reset(ids: items.map(\.id), heights: items.map { cached[$0.id] ?? oldHeights[$0.id] ?? 100 })
+ layout.setInsets(top: insets.top, bottom: insets.bottom)
+ if changed { lastTopRequest = nil }
+ positionRequested = true
+ }
+ schedule()
+ }
+
+ func viewportChanged() {
+ guard !arranging, let scroll else { return }
+ let visible = layout.visible(in: scroll.contentView.bounds, overscan: 0)
+ if !updating, visible.contains(where: { cells[items[$0].id] == nil }) {
+ // A large wheel/page movement must not present an uncovered viewport
+ // while waiting for the next dispatch turn.
+ arrange()
+ } else {
+ schedule()
+ }
+ }
+
+ func schedule() {
+ guard !pending, !arranging else { return }
+ pending = true
+ DispatchQueue.main.async { [weak self] in
+ guard let self else { return }
+ pending = false
+ arrange()
+ }
+ }
+
+ func arrange() {
+ guard !arranging, let scroll, let source, scroll.contentSize.width > 0 else { return }
+ arranging = true
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ defer {
+ CATransaction.commit()
+ arranging = false
+ if !pendingHeights.isEmpty { schedule() }
+ }
+ let anchor = pendingAnchor ?? layout.anchor(at: scroll.contentView.bounds.minY)
+ pendingAnchor = nil
+ let newWidth = max(1, min(820, scroll.contentSize.width) - 32)
+ if abs(newWidth - width) > 0.5 {
+ width = newWidth
+ cached.removeAll()
+ // Keep existing estimates until each row is measured at the new width.
+ // In particular, opening an inspector must not collapse the document.
+ refresh = true
+ }
+ let updateRoots = refresh
+ var positionDirty = refresh || positionRequested || viewportSize != scroll.contentSize
+ positionRequested = false
+ viewportSize = scroll.contentSize
+ refresh = false
+ let reports = pendingHeights
+ pendingHeights.removeAll()
+ for (id, report) in reports {
+ guard !dirty.contains(id), let cell = cells[id], cell.generation == report.generation,
+ abs(width - report.width) < 0.5, let index = layout.ids.firstIndex(of: id) else { continue }
+ cached[id] = ceil(report.height)
+ positionDirty = layout.measure(report.height, at: index) || positionDirty
+ }
+ var refreshed = Set<String>()
+ var measuredIDs = Set<String>()
+ // Measurement may reveal that a very tall estimated row covers the viewport.
+ // Reconcile the visible range again before presenting the frame.
+ while true {
+ let previousSize = scroll.document.frame.size
+ resizeDocument()
+ if scroll.document.frame.size != previousSize { positionDirty = true }
+ if positionDirty { restore(anchor) }
+ let range = layout.visible(in: scroll.contentView.bounds, overscan: scroll.contentSize.height)
+ var measured = false
+ for index in range {
+ let item = items[index]
+ let cell: Cell
+ let created: Bool
+ if let existing = cells[item.id] { cell = existing; created = false }
+ else {
+ let coordinates = MacChatCoordinates()
+ let controller = NSHostingController(rootView: AnyView(EmptyView()))
+ controller.sizingOptions = []
+ // A row's intrinsic height must not depend on how far its
+ // hosting view has scrolled beneath the window's safe area.
+ (controller.view as? NSHostingView<AnyView>)?.safeAreaRegions = []
+ cell = Cell(controller: controller, coordinates: coordinates)
+ cells[item.id] = cell
+ controller.view.isHidden = true
+ scroll.document.addSubview(controller.view)
+ coordinates.view = controller.view
+ created = true
+ }
+ if (created || updateRoots || dirty.contains(item.id)) && refreshed.insert(item.id).inserted {
+ let measuredWidth = width
+ nextGeneration += 1
+ let generation = nextGeneration
+ cell.generation = generation
+ cell.controller.rootView = AnyView(source.row(item)
+ .environment(\.self, environment)
+ .environment(\.macChatWidth, width)
+ .environment(\.macChatCoordinates, cell.coordinates)
+ .frame(width: width, alignment: .leading)
+ .fixedSize(horizontal: false, vertical: true)
+ .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { [weak self] height in
+ self?.heightChanged(height, id: item.id, width: measuredWidth, generation: generation)
+ })
+ }
+ if (created || cached[item.id] == nil || updateRoots || dirty.contains(item.id)), measuredIDs.insert(item.id).inserted {
+ let size = cell.controller.sizeThatFits(in: CGSize(width: width, height: .greatestFiniteMagnitude))
+ if size.height.isFinite, size.height > 0 {
+ cached[item.id] = ceil(size.height)
+ measured = layout.measure(size.height, at: index) || measured
+ }
+ }
+ }
+ positionDirty = positionDirty || measured
+ if !measured { break }
+ }
+ resizeDocument()
+ // Let AppKit keep its rubber-banding and momentum when only the viewport
+ // moved. Correct the offset only after content geometry or a jump changed.
+ if positionDirty { restore(anchor) }
+ let range = layout.visible(in: scroll.contentView.bounds, overscan: scroll.contentSize.height)
+ let visible = Set(range.map { items[$0].id })
+ let x = (scroll.contentSize.width - width) / 2
+ for index in range {
+ if let view = cells[items[index].id]?.controller.view {
+ let frame = CGRect(x: x, y: layout.starts[index], width: width, height: layout.heights[index])
+ let prepare = view.isHidden || view.frame.size != frame.size || refreshed.contains(items[index].id)
+ if view.frame != frame { view.frame = frame }
+ if prepare {
+ view.layoutSubtreeIfNeeded()
+ view.isHidden = false
+ if view.window != nil { view.displayIfNeeded() }
+ }
+ }
+ }
+ // Retire outgoing rows only after every replacement has its final frame
+ // and a prepared display tree, within the same non-animated transaction.
+ for id in Array(cells.keys) where !visible.contains(id) {
+ cells.removeValue(forKey: id)?.controller.view.removeFromSuperview()
+ }
+ dirty.removeAll()
+ }
+
+ func heightChanged(_ height: CGFloat, id: String, width: CGFloat, generation: Int) {
+ guard height.isFinite, height > 0, cells[id]?.generation == generation,
+ let index = layout.ids.firstIndex(of: id), abs(layout.heights[index] - ceil(height)) > 0.5 else { return }
+ // Coalesce row-local changes; reports from retired or replaced roots can
+ // never resize the current document, even if the same message is remounted.
+ pendingHeights[id] = HeightReport(height: height, width: width, generation: generation)
+ schedule()
+ }
+
+ func resizeDocument() {
+ guard let scroll else { return }
+ let size = CGSize(width: scroll.contentSize.width, height: max(layout.total, scroll.contentSize.height))
+ if scroll.document.frame.size != size { scroll.document.setFrameSize(size) }
+ }
+
+ func restore(_ anchor: MacChatLayout.Anchor?) {
+ guard let scroll else { return }
+ let end = max(0, layout.total - scroll.contentSize.height)
+ let y = follows ? end : anchor.flatMap { layout.offset(for: $0) } ?? scroll.contentView.bounds.minY
+ let origin = CGPoint(x: 0, y: min(end, max(0, y)))
+ if abs(scroll.contentView.bounds.minY - origin.y) > 0.5 {
+ scroll.contentView.scroll(to: origin)
+ scroll.reflectScrolledClipView(scroll.contentView)
+ }
+ }
+
+ func setFollowing(_ value: Bool) {
+ guard follows != value else { return }
+ follows = value
+ reportedFollow = value
+ pendingFollowReport = value
+ DispatchQueue.main.async { [weak self] in
+ guard let self, follows == value else { return }
+ if source?.following == value { pendingFollowReport = nil }
+ else { source?.following = value }
+ }
+ }
+
+ func requestEarlierIfNeeded() {
+ guard let scroll, !follows, scroll.contentView.bounds.minY < scroll.contentSize.height / 2,
+ let first = items.dropFirst().first?.id ?? items.first?.id, lastTopRequest != first else { return }
+ lastTopRequest = first
+ DispatchQueue.main.async { [weak self] in self?.source?.nearTop() }
+ }
+ }
+}
+
+@MainActor final class ChatScrollView: NSScrollView {
+ enum Destination { case previous, next, first, last }
+ let document = ChatDocumentView()
+ var changed: (() -> Void)?
+ var gesture: ((Bool, NSEvent) -> Void)?
+ var navigate: ((Destination) -> Void)?
+
+ init() {
+ super.init(frame: .zero)
+ drawsBackground = false
+ hasVerticalScroller = false
+ hasHorizontalScroller = false
+ verticalScrollElasticity = .allowed
+ contentView.drawsBackground = false
+ contentView.postsBoundsChangedNotifications = true
+ documentView = document
+ NotificationCenter.default.addObserver(self, selector: #selector(clipMoved),
+ name: NSView.boundsDidChangeNotification, object: contentView)
+ setAccessibilityLabel("Conversation transcript")
+ }
+
+ required init?(coder: NSCoder) { nil }
+
+ @objc private func clipMoved() { changed?() }
+
+ override func layout() {
+ super.layout()
+ changed?()
+ }
+
+ override func scrollWheel(with event: NSEvent) {
+ gesture?(true, event)
+ super.scrollWheel(with: event)
+ gesture?(false, event)
+ }
+
+ override var acceptsFirstResponder: Bool { true }
+ override func pageUp(_ sender: Any?) { navigate?(.previous) }
+ override func pageDown(_ sender: Any?) { navigate?(.next) }
+ override func scrollPageUp(_ sender: Any?) { navigate?(.previous) }
+ override func scrollPageDown(_ sender: Any?) { navigate?(.next) }
+ override func scrollToBeginningOfDocument(_ sender: Any?) { navigate?(.first) }
+ override func scrollToEndOfDocument(_ sender: Any?) { navigate?(.last) }
+}
+
+@MainActor final class ChatDocumentView: NSView {
+ override var isFlipped: Bool { true }
+
+ override func accessibilityChildren() -> [Any]? {
+ // Rows mounted while scrolling upward were added after newer rows.
+ // VoiceOver must read visual order, not hosting-view creation order.
+ NSAccessibility.unignoredChildren(from: subviews.sorted { $0.frame.minY < $1.frame.minY })
+ }
+}
+
+/// Separate hosting roots need their menu anchors converted to window coordinates.
+@MainActor final class MacChatCoordinates {
+ weak var view: NSView?
+
+ func windowFrame(_ frame: CGRect) -> CGRect {
+ guard let view, let root = view.window?.contentView else { return frame }
+ let result = view.convert(frame, to: root)
+ return root.isFlipped ? result : CGRect(x: result.minX, y: root.bounds.height - result.maxY,
+ width: result.width, height: result.height)
+ }
+}
+
+extension EnvironmentValues {
+ @Entry var macChatWidth: CGFloat? = nil
+ @Entry var macChatCoordinates: MacChatCoordinates? = nil
+}
+
+enum MacTranscriptItem: Identifiable, Equatable {
+ case message(ChatItem)
+ case history(Bool)
+ case intro
+ case working(String?)
+
+ var id: String {
+ switch self {
+ case .message(let item): "message-\(item.id)"
+ case .history: "history"
+ case .intro: "intro"
+ case .working: "working"
+ }
+ }
+}
+#endif
diff --git a/kit/Sources/CodyncUI/Thread/MarkdownBlocks.swift b/kit/Sources/CodyncUI/Thread/MarkdownBlocks.swift
index 242b9ac4..162d147a 100644
--- a/kit/Sources/CodyncUI/Thread/MarkdownBlocks.swift
+++ b/kit/Sources/CodyncUI/Thread/MarkdownBlocks.swift
@@ -2,7 +2,7 @@ import Foundation
/// Block-level Markdown as replies use it: paragraphs, headings, nested lists, quotes, rules,
/// tables and fenced code. Pure parsing, apart from the views, so it's tested on its own.
-/// The iPhone's `MarkdownText` renders these; the Mac's has its own smaller parser.
+/// Both native Markdown renderers use these blocks and the same streaming syntax repair.
enum MarkdownBlocks {
enum Block: Hashable {
case paragraph(String)
diff --git a/kit/Sources/CodyncUI/Thread/MarkdownText.swift b/kit/Sources/CodyncUI/Thread/MarkdownText.swift
index 8b93583c..07393404 100644
--- a/kit/Sources/CodyncUI/Thread/MarkdownText.swift
+++ b/kit/Sources/CodyncUI/Thread/MarkdownText.swift
@@ -2,74 +2,77 @@
import CodyncKit
import SwiftUI
-/// The Mac's Markdown renderer (the iPhone's is `MarkdownText+iOS.swift`).
-/// Small block-level Markdown renderer: paragraphs, headings, lists, quotes and
-/// fenced code; inline styling comes from `AttributedString(markdown:)`.
-public struct MarkdownText: View {
- let blocks: [Block]
+/// The Mac's Markdown renderer for messages (`MarkdownBlocks`: tables, rules, nested lists
+/// too); inline styling comes from `AttributedString(markdown:)`.
+/// Equatable so a reply that didn't change skips its body; each block is equatable too, so
+/// while text streams only the block being written renders again.
+public struct MarkdownText: View, Equatable {
+ let source: String
+ /// Text is still arriving: the open end hides half-written syntax.
let streaming: Bool
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
- @Environment(\.conversationTypography) private var typography
-
- private var contentTransition: ContentTransition {
- streaming && !reduceMotion ? .interpolate : .identity
- }
-
- private var textAnimation: Animation? {
- streaming ? Motion.reduced(Motion.fade, reduceMotion) : nil
- }
public init(_ source: String, streaming: Bool = false) {
- blocks = Self.parse(source)
+ self.source = source
self.streaming = streaming
}
- enum Block: Hashable {
- case paragraph(String)
- case heading(String, level: Int)
- case bullet(String, marker: String)
- case quote(String)
- case code(String, language: String)
- }
-
public var body: some View {
- VStack(alignment: .leading, spacing: 8) {
+ let blocks = MarkdownBlocks.parse(source, streaming: streaming)
+ VStack(alignment: .leading, spacing: 10) {
ForEach(Array(blocks.enumerated()), id: \.offset) { _, block in
- view(for: block)
+ MarkdownBlock(block: block).equatable()
}
}
.textSelection(.enabled)
}
- @ViewBuilder private func view(for block: Block) -> some View {
+ /// Inline styling; inline code gets a soft tint behind it.
+ static func inline(_ s: String) -> AttributedString {
+ guard var text = try? AttributedString(markdown: s, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))
+ else { return AttributedString(s) }
+ for run in text.runs where run.inlinePresentationIntent?.contains(.code) == true {
+ text[run.range].backgroundColor = Palette.text.opacity(0.08)
+ }
+ return text
+ }
+}
+
+/// Completed blocks keep their attributed text while the open block changes.
+private struct MarkdownBlock: View, @MainActor Equatable {
+ let block: MarkdownBlocks.Block
+ @Environment(\.conversationTypography) private var typography
+
+ nonisolated static func == (a: Self, b: Self) -> Bool { a.block == b.block }
+
+ var body: some View {
+ content.lineSpacing(4 * typography.scale)
+ }
+
+ @ViewBuilder private var content: some View {
switch block {
case let .paragraph(t):
- Text(Self.inline(t))
+ Text(MarkdownText.inline(t))
.font(typography.body)
.foregroundStyle(Palette.text)
- .contentTransition(contentTransition)
- .animation(textAnimation, value: t)
case let .heading(t, level):
- Text(Self.inline(t))
+ Text(MarkdownText.inline(t))
.font(typography.heading(level: level))
.foregroundStyle(Palette.text)
- .contentTransition(contentTransition)
- .animation(textAnimation, value: t)
- case let .bullet(t, marker):
+ case let .bullet(t, marker, depth):
HStack(alignment: .firstTextBaseline, spacing: 6) {
Text(marker).foregroundStyle(Palette.secondary).monospacedDigit()
- Text(Self.inline(t))
- .foregroundStyle(Palette.text)
- .contentTransition(contentTransition)
- .animation(textAnimation, value: t)
+ Text(MarkdownText.inline(t)).foregroundStyle(Palette.text)
}
.font(typography.body)
+ .padding(.leading, CGFloat(depth) * 16)
+ case .rule:
+ Rectangle().fill(Palette.border).frame(height: 1).padding(.vertical, 4)
+ case let .table(header, rows):
+ MarkdownTable(header: header, rows: rows)
case let .quote(t):
- Text(Self.inline(t))
+ Text(MarkdownText.inline(t))
.font(typography.body)
.foregroundStyle(Palette.secondary)
- .contentTransition(contentTransition)
- .animation(textAnimation, value: t)
.padding(.leading, 10)
.overlay(alignment: .leading) { Rectangle().fill(Palette.border).frame(width: 3) }
case let .code(t, _):
@@ -82,64 +85,38 @@ public struct MarkdownText: View {
.background(Palette.codeBackground, in: RoundedRectangle(cornerRadius: 8))
}
}
+}
- static func inline(_ s: String) -> AttributedString {
- (try? AttributedString(markdown: s, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))) ?? AttributedString(s)
- }
-
- static func parse(_ source: String) -> [Block] {
- var blocks: [Block] = []
- var paragraph: [String] = []
- var code: [String]?
- var language = ""
-
- func flush() {
- if !paragraph.isEmpty {
- blocks.append(.paragraph(paragraph.joined(separator: "\n")))
- paragraph = []
- }
- }
+/// A Markdown table: a bold header and hairlines between rows, scrolling sideways when wide.
+private struct MarkdownTable: View {
+ let header: [String]
+ let rows: [[String]]
+ @Environment(\.conversationTypography) private var typography
- for raw in source.components(separatedBy: "\n") {
- let line = raw.trimmingCharacters(in: .whitespaces)
- if line.hasPrefix("```") {
- if let c = code {
- blocks.append(.code(c.joined(separator: "\n"), language: language))
- code = nil
- } else {
- flush()
- code = []
- language = String(line.dropFirst(3))
+ var body: some View {
+ let columns = max(header.count, rows.map(\.count).max() ?? 0)
+ ScrollView(.horizontal, showsIndicators: false) {
+ Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 7) {
+ GridRow {
+ ForEach(0 ..< columns, id: \.self) { i in
+ Text(MarkdownText.inline(i < header.count ? header[i] : "")).fontWeight(.semibold)
+ }
+ }
+ ForEach(Array(rows.enumerated()), id: \.offset) { _, row in
+ Rectangle().fill(Palette.border).frame(height: 1).gridCellUnsizedAxes(.horizontal)
+ GridRow {
+ ForEach(0 ..< columns, id: \.self) { i in
+ Text(MarkdownText.inline(i < row.count ? row[i] : ""))
+ }
+ }
}
- continue
- }
- if code != nil {
- code?.append(raw)
- continue
- }
- if line.isEmpty {
- flush()
- } else if let hashes = line.firstIndex(where: { $0 != "#" }), line.hasPrefix("#"), line[hashes] == " " {
- flush()
- let level = line.distance(from: line.startIndex, to: hashes)
- blocks.append(.heading(String(line[hashes...]).trimmingCharacters(in: .whitespaces), level: level))
- } else if line.hasPrefix("- ") || line.hasPrefix("* ") || line.hasPrefix("• ") {
- flush()
- blocks.append(.bullet(String(line.dropFirst(2)), marker: "•"))
- } else if let dot = line.firstIndex(of: "."), line[..<dot].allSatisfy(\.isNumber), !line[..<dot].isEmpty,
- line[line.index(after: dot)...].hasPrefix(" ") {
- flush()
- blocks.append(.bullet(String(line[line.index(dot, offsetBy: 2)...]), marker: String(line[...dot])))
- } else if line.hasPrefix("> ") {
- flush()
- blocks.append(.quote(String(line.dropFirst(2))))
- } else {
- paragraph.append(raw)
}
+ .font(typography.body)
+ .foregroundStyle(Palette.text)
+ .fixedSize()
+ .padding(.vertical, 2)
}
- if let c = code { blocks.append(.code(c.joined(separator: "\n"), language: language)) }
- flush()
- return blocks
}
}
+
#endif
diff --git a/kit/Sources/CodyncUI/Thread/RepliesView+macOS.swift b/kit/Sources/CodyncUI/Thread/RepliesView+macOS.swift
index cbd232a1..2664d557 100644
--- a/kit/Sources/CodyncUI/Thread/RepliesView+macOS.swift
+++ b/kit/Sources/CodyncUI/Thread/RepliesView+macOS.swift
@@ -3,38 +3,56 @@ import CodyncKit
import SwiftUI
extension RepliesView {
- /// The Mac's replies: a lazy stack that opens at the newest.
+ /// Replies share the native virtualized transcript with the main conversation.
@ViewBuilder var messages: some View {
let replies = model.replies(botId, root: rootId)
- ScrollView {
- LazyVStack(alignment: .leading, spacing: 0) {
- if let root {
- ChatRow(entry: root, groupStart: true, chat: chat) { showTrace = true }
+ let items = ChatItem.build(replies, streaming: chat?.isWorking(in: botId, thread: rootId) == true && !model.isOffline, steady: true)
+ let rows: [MacReplyItem] = (root.map { [.root($0, replies.count)] } ?? [])
+ + items.compactMap { item in
+ if case .entry = item.kind { return .message(item) }
+ return nil
+ }
+ + (chat?.isWorking(in: botId, thread: rootId) == true && !model.isOffline
+ ? [.working(model.currentThinking(botId, thread: rootId))] : [])
+ MacChatList(items: rows, following: $following, revision: chat.map(AnyHashable.init)) { item in
+ switch item {
+ case .root(let entry, let count):
+ VStack(alignment: .leading, spacing: 0) {
+ ChatRow(entry: entry, groupStart: true, chat: chat) { showTrace = true }.equatable()
HStack(spacing: 10) {
- Text(replies.isEmpty ? "No replies yet" : replies.count == 1 ? "1 reply" : "\(replies.count) replies")
- .appFont(.caption)
- .foregroundStyle(Palette.tertiary)
- .fixedSize()
+ Text(count == 0 ? "No replies yet" : count == 1 ? "1 reply" : "\(count) replies")
+ .appFont(.caption).foregroundStyle(Palette.tertiary).fixedSize()
Rectangle().fill(Palette.border).frame(height: 1)
}
.padding(.vertical, 12)
}
- ForEach(ChatItem.build(replies, streaming: chat?.isWorking(in: botId, thread: rootId) == true && !model.isOffline)) { item in
- if case let .entry(e, groupStart) = item.kind {
- ChatRow(entry: e, groupStart: groupStart, chat: chat) { showTrace = true }
- }
- }
- if let chat, chat.isWorking(in: botId, thread: rootId), !model.isOffline {
- WorkingIndicator(bot: chat, thinking: model.currentThinking(botId, thread: rootId)).padding(.top, 6)
+ case .message(let message):
+ if case let .entry(entry, groupStart) = message.kind {
+ ChatRow(entry: entry, groupStart: groupStart, chat: chat) { showTrace = true }.equatable()
}
- Color.clear.frame(height: 8)
+ case .working(let thinking):
+ if let chat { WorkingIndicator(bot: chat, thinking: thinking).padding(.top, 6) }
}
- .padding(.horizontal, 16)
- .padding(.top, 8)
}
- .scrollIndicators(.never)
- .defaultScrollAnchor(.bottom)
- .scrollDismissesKeyboard(.interactively)
+ .onChange(of: items.last?.id) { _, _ in
+ if items.last?.isUserMessage == true { following = true }
+ }
+ .overlay(alignment: .bottom) {
+ MacJumpToLatest(visible: !following && !items.isEmpty) { following = true }
+ }
+ }
+}
+private enum MacReplyItem: Identifiable, Equatable {
+ case root(Entry, Int)
+ case message(ChatItem)
+ case working(String?)
+
+ var id: String {
+ switch self {
+ case .root(let entry, _): "root-\(entry.id)"
+ case .message(let item): "message-\(item.id)"
+ case .working: "working"
+ }
}
}
#endif
diff --git a/kit/Sources/CodyncUI/Thread/RepliesView.swift b/kit/Sources/CodyncUI/Thread/RepliesView.swift
index 34f56f83..925107fc 100644
--- a/kit/Sources/CodyncUI/Thread/RepliesView.swift
+++ b/kit/Sources/CodyncUI/Thread/RepliesView.swift
@@ -11,8 +11,8 @@ struct RepliesView: View {
let close: () -> Void
@Environment(BotStore.self) var model
@State var showTrace = false
+ @State var following = true
#if os(iOS)
- @State var following = true
@Environment(\.accessibilityReduceMotion) var reduceMotion
#endif
@@ -37,7 +37,7 @@ struct RepliesView: View {
// The replies: each platform's own `messages`, in its `RepliesView+` file.
messages
- .safeAreaInset(edge: .bottom) {
+ .conversationInset(edge: .bottom) {
if let mismatch = model.mismatch {
UpdateNeededCard(store: model, mismatch: mismatch)
.padding(.horizontal, 16)
diff --git a/kit/Sources/CodyncUI/Thread/ThreadView+macOS.swift b/kit/Sources/CodyncUI/Thread/ThreadView+macOS.swift
index dc92fbd9..893f0613 100644
--- a/kit/Sources/CodyncUI/Thread/ThreadView+macOS.swift
+++ b/kit/Sources/CodyncUI/Thread/ThreadView+macOS.swift
@@ -6,7 +6,15 @@ extension ThreadView {
var platformBody: some View {
GeometryReader { geometry in
HStack(spacing: 0) {
- conversation.frame(maxWidth: .infinity)
+ conversation
+ // Panel motion must not interpolate every paragraph's line wrapping.
+ .transaction { transaction in
+ if transaction.animation == Motion.reduced(Motion.layout, reduceMotion)
+ || transaction.animation == Motion.reduced(Motion.morph, reduceMotion) {
+ transaction.animation = nil
+ }
+ }
+ .frame(maxWidth: .infinity)
if let openThread, geometry.size.width >= 680 {
HStack(spacing: 0) {
Rectangle().fill(Palette.border).frame(width: 1)
@@ -14,13 +22,13 @@ extension ThreadView {
.frame(width: min(420, geometry.size.width * 0.45))
}
.id(openThread.id)
- .transition(.move(edge: .trailing).combined(with: .opacity))
+ .transition(.offset(x: 20).combined(with: .opacity))
} else if showSettings && geometry.size.width >= 680 {
HStack(spacing: 0) {
Rectangle().fill(Palette.border).frame(width: 1)
detailsPanel.frame(width: 292)
}
- .transition(.move(edge: .trailing).combined(with: .opacity))
+ .transition(.offset(x: 20).combined(with: .opacity))
}
}
.clipped()
@@ -28,10 +36,12 @@ extension ThreadView {
$0.size.width
} action: {
availableWidth = $0
+ if $0 >= 680 { compactDetails = false }
}
}
.ignoresSafeArea(.container, edges: .top)
- .animation(Motion.reduced(Motion.layout, reduceMotion), value: openThread)
+ .animation(Motion.reduced(Motion.morph, reduceMotion), value: openThread)
+ .animation(Motion.reduced(Motion.morph, reduceMotion), value: showSettings)
.codyncSheet(isPresented: $compactDetails) {
detailsPanel.frame(width: 340, height: 600)
}
@@ -42,88 +52,86 @@ extension ThreadView {
}
}
- /// The Mac's messages: every loaded message in a lazy stack, brought to the newest as it
- /// changes while the reader is at the bottom.
+ private var streaming: Bool { bot?.isWorking(in: botId, thread: nil) == true && !model.isOffline }
+
+ /// Native momentum scrolling with bounded SwiftUI row hosting.
@ViewBuilder var transcript: some View {
let thread = model.chat(botId)
- let items = ChatItem.build(thread, streaming: bot?.isWorking(in: botId, thread: nil) == true && !model.isOffline)
- ScrollViewReader { proxy in
- ScrollView {
- LazyVStack(alignment: .leading, spacing: 0) {
- if !model.historyComplete.contains(botId), thread.count >= 50 {
- Button("Load earlier messages") { Task { await model.loadOlder(botId) } }
- .buttonStyle(.plain)
- .appFont(.footnote)
- .foregroundStyle(Palette.secondary)
- .frame(maxWidth: .infinity)
- .padding(.vertical, 12)
- }
- if items.isEmpty, let bot {
- if bot.isGroup { GroupIntroCard(group: bot).padding(.top, 40) } else { IntroCard(bot: bot).padding(.top, 40) }
- }
- ForEach(items) { item in
- row(item)
- .id(item.id)
- .transition(item.id == items.last?.id
- ? .asymmetric(insertion: .move(edge: .bottom).combined(with: .opacity), removal: .opacity)
- : .identity)
- }
- // Offline, "working" is only what the computer last said; don't show it as live.
- if let bot, bot.isWorking(in: botId, thread: nil), !model.isOffline {
- WorkingIndicator(bot: bot, thinking: model.currentThinking(botId, thread: nil))
- .padding(.top, 6)
- .id("working")
- }
- Color.clear.frame(height: 8).id("bottom")
+ let all = ChatItem.build(thread, streaming: streaming, steady: true)
+ let start = firstShown.flatMap { id in all.firstIndex { $0.id == id } } ?? max(0, all.count - 40)
+ let items = Array(all[start...])
+ let more = start > 0 || (!model.historyComplete.contains(botId) && thread.count >= 50)
+ let rows: [MacTranscriptItem] = (more ? [.history(loadingEarlier)] : [])
+ + (items.isEmpty ? [.intro] : items.map { .message($0) })
+ + (streaming ? [.working(model.currentThinking(botId, thread: nil))] : [])
+ MacChatList(items: rows, following: $following, revision: bot.map(AnyHashable.init), nearTop: { if more { showEarlier() } }) { item in
+ switch item {
+ case .message(let message):
+ row(message).accessibilityElement(children: .contain)
+ case .history(let loading):
+ Button { showEarlier() } label: {
+ if loading { Spinner(size: 14) }
+ else { Text("Load earlier messages").appFont(.footnote) }
}
- .padding(.horizontal, 16)
- .padding(.top, 8)
- .animation(Motion.reduced(Motion.conversation, reduceMotion), value: items.last?.id)
- .frame(maxWidth: 820)
+ .buttonStyle(.plain)
+ .foregroundStyle(Palette.secondary)
.frame(maxWidth: .infinity)
- }
- .scrollIndicators(.never)
- .conversationInitialBottomAnchor()
- .scrollDismissesKeyboard(.interactively)
- .conversationScrollEdges()
- .conversationBottomObserver($isAtBottom)
- .onChange(of: items.last?.id) { _, _ in
- guard isAtBottom || items.last?.isUserMessage == true else { return }
- withAnimation(Motion.reduced(Motion.conversation, reduceMotion)) {
- proxy.scrollTo("bottom", anchor: .bottom)
- }
- }
- .onChange(of: items.last?.textContent) { _, _ in
- guard isAtBottom else { return }
- withAnimation(Motion.reduced(Motion.conversation, reduceMotion)) {
- proxy.scrollTo("bottom", anchor: .bottom)
+ .padding(.vertical, 12)
+ .disabled(loading)
+ case .intro:
+ if let bot {
+ if bot.isGroup { GroupIntroCard(group: bot).padding(.top, 40) }
+ else { IntroCard(bot: bot).padding(.top, 40) }
}
+ case .working(let thinking):
+ if let bot { WorkingIndicator(bot: bot, thinking: thinking).padding(.top, 6) }
}
- .onChange(of: bot?.isWorking) { _, _ in
- guard isAtBottom else { return }
- withAnimation(Motion.reduced(Motion.conversation, reduceMotion)) {
- proxy.scrollTo("bottom", anchor: .bottom)
- }
+ }
+ .onChange(of: items.last?.id) { _, _ in
+ if items.last?.isUserMessage == true { following = true }
+ }
+ .overlay(alignment: .bottom) {
+ MacJumpToLatest(visible: !following && !items.isEmpty) { following = true }
+ }
+ .onChange(of: items.first?.id, initial: true) { _, id in
+ if firstShown == nil { firstShown = id }
+ }
+ }
+
+ private func showEarlier() {
+ guard !loadingEarlier else { return }
+ loadingEarlier = true
+ Task {
+ var all = ChatItem.build(model.chat(botId), streaming: streaming, steady: true)
+ var start = firstShown.flatMap { id in all.firstIndex { $0.id == id } } ?? max(0, all.count - 40)
+ if start == 0 {
+ let anchor = all.first?.id
+ await model.loadOlder(botId)
+ all = ChatItem.build(model.chat(botId), streaming: streaming, steady: true)
+ start = anchor.flatMap { id in all.firstIndex { $0.id == id } } ?? 0
}
- .onChange(of: typography.pointSize) { _, _ in
- guard isAtBottom else { return }
- proxy.scrollTo("bottom", anchor: .bottom)
+ if start > 0 {
+ firstShown = all[max(0, start - 40)].id
}
+ loadingEarlier = false
}
}
func platformChrome(_ content: some View) -> some View {
content
+ .environment(\.conversationTypography, ConversationTypography(pointSize: typography.pointSize + 2))
// Grok's desktop chat: no title bar. The chat blurs and fades as it scrolls up, with the bot
- // in a floating solid pill and the actions as glass buttons on the right.
- .safeAreaInset(edge: .top, spacing: 0) {
+ // in a floating solid pill and circular actions on the right.
+ .conversationInset(edge: .top, spacing: 0) {
ZStack {
HStack(spacing: 8) {
Spacer(minLength: 0)
- if !showSettings || availableWidth < 680 {
- IconButton("Conversation details", systemImage: "chevron.left.2") { toggleDetails() }
+ if (!showSettings || openThread != nil || availableWidth < 680) && !compactDetails {
+ Button("Conversation details", systemImage: "chevron.left.2", action: toggleDetails)
+ .labelStyle(.iconOnly)
+ .buttonStyle(MacChatButtonStyle(direction: CGSize(width: -1, height: 0)))
.keyboardShortcut("i", modifiers: [.command, .option])
- .frosted(in: Circle())
+ .help("Conversation details")
.transition(.opacity)
}
}
@@ -134,13 +142,12 @@ extension ThreadView {
.padding(.leading, 10)
.padding(.trailing, 16)
.padding(.vertical, 9)
- .background(Palette.background, in: Capsule())
+ .background(Palette.surface, in: Capsule())
.shadow(color: .black.opacity(0.12), radius: 16, y: 4)
}
.padding(.horizontal, 16)
.padding(.top, 10)
.padding(.bottom, 14)
- .background(alignment: .top) { TopFade() }
}
}
@@ -152,10 +159,18 @@ extension ThreadView {
}
private func toggleDetails() {
- if availableWidth < 680 {
- compactDetails.toggle()
- } else {
- withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { showSettings.toggle() }
+ withAnimation(Motion.reduced(Motion.morph, reduceMotion)) {
+ if availableWidth < 680 {
+ openThread = nil
+ compactDetails.toggle()
+ } else if openThread != nil {
+ // The thread occupies the inspector slot. << must actually show details,
+ // rather than toggling a flag behind the still-open thread.
+ openThread = nil
+ showSettings = true
+ } else {
+ showSettings.toggle()
+ }
}
}
@@ -166,8 +181,10 @@ extension ThreadView {
compactDetails = false
if let bot { templateRequest = EditorRequest(BotDraft(bot)) }
}) {
- withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { showSettings = false }
- compactDetails = false
+ withAnimation(Motion.reduced(Motion.morph, reduceMotion)) {
+ showSettings = false
+ compactDetails = false
+ }
}
.id(routineRequest)
}
@@ -284,17 +301,11 @@ private struct DetailsPanel: View {
.padding(.leading, 4)
}
- /// A round action in the panel's header, frosted like the chat's title pill (Grok's style).
+ /// A single circular surface, shared with the floating transcript controls.
private func roundButton(_ label: String, _ symbol: String, action: @escaping () -> Void) -> some View {
- Button(action: action) {
- Image(systemName: symbol)
- .appFont(.system(size: 13, weight: .medium))
- .foregroundStyle(Palette.text)
- .frame(width: 32, height: 32)
- .frosted(in: Circle())
- .contentShape(Circle())
- }
- .buttonStyle(PressScale())
+ Button(label, systemImage: symbol, action: action)
+ .labelStyle(.iconOnly)
+ .buttonStyle(MacChatButtonStyle(direction: CGSize(width: symbol == "chevron.right.2" ? 1 : 0, height: 0)))
.accessibilityLabel(label)
.help(label)
}
@@ -395,20 +406,4 @@ private struct DetailsPanel: View {
}
}
-/// The top edge of the chat: messages fade out gradually as they scroll under the title pill,
-/// readable behind the pill and gone only at the very top.
-private struct TopFade: View {
- var body: some View {
- ZStack {
- Rectangle().fill(.ultraThinMaterial)
- .mask(LinearGradient(colors: [.black, .clear], startPoint: .top, endPoint: .center))
- LinearGradient(stops: [.init(color: Palette.background, location: 0),
- .init(color: Palette.background.opacity(0.6), location: 0.35),
- .init(color: Palette.background.opacity(0), location: 1)],
- startPoint: .top, endPoint: .bottom)
- }
- .ignoresSafeArea(edges: .top)
- .allowsHitTesting(false)
- }
-}
#endif
diff --git a/kit/Sources/CodyncUI/Thread/ThreadView.swift b/kit/Sources/CodyncUI/Thread/ThreadView.swift
index dc24e1db..fff99931 100644
--- a/kit/Sources/CodyncUI/Thread/ThreadView.swift
+++ b/kit/Sources/CodyncUI/Thread/ThreadView.swift
@@ -29,7 +29,9 @@ public struct ThreadView: View {
@State var routineId: String?
@State var routineRequest = UUID()
#if os(macOS)
- @State var isAtBottom = true
+ @State var following = true
+ @State var firstShown: String?
+ @State var loadingEarlier = false
#else
/// iPhone: the chat stays on the newest message until the reader scrolls away.
@State var following = true
@@ -59,7 +61,7 @@ public struct ThreadView: View {
private var chat: some View {
transcript
.background(Palette.background)
- .safeAreaInset(edge: .bottom) {
+ .conversationInset(edge: .bottom) {
VStack(spacing: 6) {
if let mismatch = model.mismatch {
// Nothing sent now could be read on the other side.
@@ -151,9 +153,7 @@ public struct ThreadView: View {
} openThread: { root in
withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { openThread = ThreadTarget(id: root.id) }
}
- #if os(iOS)
- .equatable()
- #endif
+ .equatable()
}
}
}
@@ -255,8 +255,8 @@ public struct ThreadView: View {
// MARK: - Chat model
-struct ChatItem: Identifiable {
- enum Kind {
+struct ChatItem: Identifiable, Equatable {
+ enum Kind: Equatable {
case separator(Date)
case entry(Entry, groupStart: Bool)
}
@@ -407,4 +407,3 @@ extension View {
}
}
}
-
diff --git a/kit/Tests/CodyncUITests/AnchoredMenuTests.swift b/kit/Tests/CodyncUITests/AnchoredMenuTests.swift
new file mode 100644
index 00000000..1820f45a
--- /dev/null
+++ b/kit/Tests/CodyncUITests/AnchoredMenuTests.swift
@@ -0,0 +1,49 @@
+#if os(macOS)
+import AppKit
+import SwiftUI
+import Testing
+@testable import CodyncUI
+
+@MainActor @Observable private final class MenuState {
+ var open = false
+}
+
+@Test @MainActor func firstMenuPresentationBuildsItsChoices() async throws {
+ let host = ModalHost()
+ let state = MenuState()
+ var menuBuilt = false
+ let window = NSWindow(contentRect: CGRect(x: 0, y: 0, width: 600, height: 500),
+ styleMask: [.borderless], backing: .buffered, defer: false)
+ let trigger = NSHostingView(rootView: Text("React")
+ .codyncMenu(isPresented: Binding(get: { state.open }, set: { state.open = $0 })) {
+ menuBuilt = true
+ return [MenuItem("Test reaction") {}]
+ }
+ .environment(\.modalHost, host))
+ trigger.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
+ window.contentView = trigger
+ trigger.layoutSubtreeIfNeeded()
+ try await Task.sleep(for: .milliseconds(100))
+ #expect(host.entries.isEmpty)
+ state.open = true
+ trigger.layoutSubtreeIfNeeded()
+ try await Task.sleep(for: .milliseconds(100))
+ trigger.layoutSubtreeIfNeeded()
+ let entry = try #require(host.entries.first)
+ let panel = NSHostingView(rootView: entry.content)
+ panel.frame = CGRect(x: 0, y: 0, width: 600, height: 500)
+ window.contentView = panel
+ panel.layoutSubtreeIfNeeded()
+ try await Task.sleep(for: .milliseconds(100))
+ panel.layoutSubtreeIfNeeded()
+ #expect(menuBuilt)
+}
+
+@Test @MainActor func reactionOnlyMenuUsesOneCompactRow() {
+ let pick = ReactionPick(emoji: ["👍", "❤️", "😂", "🎉", "👀", "✅"], chosen: []) { _ in }
+ let controller = NSHostingController(rootView: MenuPanel(items: [], reactions: pick, dismiss: {}))
+ let size = controller.sizeThatFits(in: CGSize(width: 600, height: 500))
+ #expect(size.width <= 180)
+ #expect(size.height <= 50)
+}
+#endif
diff --git a/kit/Tests/CodyncUITests/ConversationFollowTests.swift b/kit/Tests/CodyncUITests/ConversationFollowTests.swift
new file mode 100644
index 00000000..5f0e101d
--- /dev/null
+++ b/kit/Tests/CodyncUITests/ConversationFollowTests.swift
@@ -0,0 +1,142 @@
+#if os(macOS)
+import AppKit
+import SwiftUI
+import Testing
+@testable import CodyncUI
+
+@MainActor private final class NativeChatHarness {
+ struct Message: Identifiable, Equatable {
+ let id: String
+ let height: CGFloat
+ }
+ typealias List = MacChatList<Message, AnyView>
+ let scroll = ChatScrollView()
+ let coordinator = List.Coordinator()
+ var following = true
+ var renders = 0
+ var insets = EdgeInsets()
+
+ init() {
+ scroll.frame = CGRect(x: 0, y: 0, width: 700, height: 600)
+ coordinator.attach(scroll)
+ }
+
+ func show(_ messages: [Message]) {
+ let list = List(items: messages, following: Binding(get: { self.following }, set: { self.following = $0 })) { item in
+ self.render(item)
+ }
+ var environment = EnvironmentValues()
+ environment.macChatInsets = insets
+ coordinator.update(list, environment: environment)
+ coordinator.arrange()
+ }
+
+ func render(_ item: Message) -> AnyView {
+ renders += 1
+ return AnyView(Text(item.id).frame(height: item.height))
+ }
+}
+
+@Test @MainActor func contentGrowthFollowsOnlyWhenTheReaderIsAtTheEnd() {
+ let chat = NativeChatHarness()
+ chat.show([.init(id: "reply", height: 2000)])
+ #expect(chat.scroll.contentView.bounds.minY == 1420)
+ chat.show([.init(id: "reply", height: 2500)])
+ #expect(chat.scroll.contentView.bounds.minY == 1920)
+
+ chat.following = false
+ chat.show([.init(id: "reply", height: 2500)])
+ chat.scroll.contentView.scroll(to: CGPoint(x: 0, y: 400))
+ chat.show([.init(id: "reply", height: 3000)])
+ #expect(chat.scroll.contentView.bounds.minY == 400)
+ #expect(!chat.coordinator.follows)
+}
+
+@Test @MainActor func jumpToLatestRestoresFollowingAfterReadingHistory() {
+ let chat = NativeChatHarness()
+ chat.following = false
+ chat.show([.init(id: "reply", height: 3000)])
+ chat.scroll.contentView.scroll(to: CGPoint(x: 0, y: 400))
+ chat.following = true
+ chat.show([.init(id: "reply", height: 3000)])
+ #expect(chat.scroll.contentView.bounds.minY == 2420)
+ #expect(chat.coordinator.follows)
+}
+
+@Test @MainActor func scrollingInsideAMountedMessageDoesNotRebuildItsSwiftUIRoot() {
+ let chat = NativeChatHarness()
+ chat.following = false
+ chat.show([.init(id: "article", height: 20_000)])
+ let before = chat.renders
+ for y in stride(from: 100, through: 2000, by: 100) {
+ chat.scroll.contentView.scroll(to: CGPoint(x: 0, y: CGFloat(y)))
+ chat.coordinator.arrange()
+ }
+ #expect(chat.renders == before)
+ #expect(chat.coordinator.cells.count == 1)
+}
+
+@Test @MainActor func resizingTheViewportKeepsTheNewestMessageAtTheBottom() {
+ let chat = NativeChatHarness()
+ chat.show([.init(id: "article", height: 2000)])
+ chat.scroll.setFrameSize(CGSize(width: 700, height: 800))
+ chat.scroll.layoutSubtreeIfNeeded()
+ chat.coordinator.arrange()
+ #expect(chat.scroll.contentView.bounds.maxY == chat.coordinator.layout.total)
+}
+
+@Test @MainActor func pageCommandsReleaseAndRestoreFollowing() {
+ let chat = NativeChatHarness()
+ chat.show([.init(id: "article", height: 2000)])
+ chat.scroll.pageUp(nil)
+ chat.coordinator.arrange()
+ #expect(!chat.coordinator.follows)
+ #expect(chat.scroll.contentView.bounds.minY < 1420)
+ chat.scroll.scrollToEndOfDocument(nil)
+ chat.coordinator.arrange()
+ #expect(chat.coordinator.follows)
+ #expect(chat.scroll.contentView.bounds.minY == 1420)
+}
+
+@Test @MainActor func anOldBindingUpdateCannotPullTheReaderBackToTheBottom() {
+ let chat = NativeChatHarness()
+ let messages: [NativeChatHarness.Message] = [.init(id: "article", height: 3000)]
+ chat.show(messages)
+ let renders = chat.renders
+ chat.coordinator.setFollowing(false)
+ chat.scroll.contentView.scroll(to: CGPoint(x: 0, y: 400))
+ // The representable can update before the deferred binding report is delivered.
+ #expect(chat.following)
+ chat.show(messages)
+ #expect(!chat.coordinator.follows)
+ #expect(chat.scroll.contentView.bounds.minY == 400)
+ #expect(chat.renders == renders)
+}
+
+@Test @MainActor func aReplacedRowsHeightReportCannotMoveTheCurrentConversation() {
+ let chat = NativeChatHarness()
+ chat.following = false
+ chat.show([.init(id: "article", height: 3000)])
+ let retiredGeneration = chat.coordinator.cells["article"]!.generation
+ chat.scroll.contentView.scroll(to: CGPoint(x: 0, y: 400))
+ chat.show([.init(id: "article", height: 3200)])
+ chat.coordinator.heightChanged(6000, id: "article", width: chat.coordinator.width, generation: retiredGeneration)
+ chat.coordinator.arrange()
+ #expect(chat.coordinator.layout.heights == [3200])
+ #expect(chat.scroll.contentView.bounds.minY == 400)
+}
+
+@Test @MainActor func floatingChromeReservesDocumentSpaceWithoutShrinkingTheViewport() {
+ let chat = NativeChatHarness()
+ chat.insets = EdgeInsets(top: 70, leading: 0, bottom: 80, trailing: 0)
+ chat.show([.init(id: "article", height: 2000)])
+ #expect(chat.scroll.contentSize.height == 600)
+ #expect(chat.coordinator.layout.starts == [78])
+ let messageEnd = chat.coordinator.layout.starts[0] + chat.coordinator.layout.heights[0]
+ #expect(chat.scroll.contentView.bounds.maxY - messageEnd == 92)
+ chat.coordinator.setFollowing(false)
+ chat.scroll.contentView.scroll(to: CGPoint(x: 0, y: 100))
+ chat.coordinator.arrange()
+ #expect(chat.scroll.contentView.bounds.minY > chat.coordinator.layout.starts[0])
+}
+#endif
diff --git a/kit/Tests/CodyncUITests/MacChatLayoutTests.swift b/kit/Tests/CodyncUITests/MacChatLayoutTests.swift
new file mode 100644
index 00000000..8fa1b318
--- /dev/null
+++ b/kit/Tests/CodyncUITests/MacChatLayoutTests.swift
@@ -0,0 +1,76 @@
+#if os(macOS)
+import Foundation
+import AppKit
+import SwiftUI
+import Testing
+@testable import CodyncUI
+
+@Test func prependingHistoryKeepsTheSamePixelInsideTheMessage() {
+ var layout = MacChatLayout()
+ layout.reset(ids: ["a", "b"], heights: [200, 600])
+ let anchor = layout.anchor(at: 278)!
+ layout.reset(ids: ["older", "a", "b"], heights: [350, 200, 600])
+ #expect(layout.offset(for: anchor) == 628)
+ #expect(layout.anchor(at: 628) == anchor)
+}
+
+@Test func measuringRowsAboveTheReaderPreservesTheirAnchor() {
+ var layout = MacChatLayout()
+ layout.reset(ids: ["a", "b", "c"], heights: [100, 100, 100])
+ let anchor = layout.anchor(at: 230)!
+ let changed = layout.measure(800, at: 0)
+ #expect(changed)
+ #expect(layout.offset(for: anchor) == 930)
+ #expect(layout.anchor(at: 930) == anchor)
+}
+
+@Test func longHistoryMountsOnlyTheViewportAndOverscan() {
+ var layout = MacChatLayout()
+ layout.reset(ids: (0..<10_000).map(String.init), heights: Array(repeating: 100, count: 10_000))
+ let range = layout.visible(in: CGRect(x: 0, y: 500_008, width: 700, height: 600), overscan: 600)
+ #expect(range == 4994..<5013)
+ #expect(range.count < 20)
+}
+
+@Test func oneTallMessageDoesNotMountThousandsOfOtherRows() {
+ var layout = MacChatLayout()
+ layout.reset(ids: ["before", "article", "after"], heights: [100, 20_000, 100])
+ #expect(layout.visible(in: CGRect(x: 0, y: 5000, width: 700, height: 600), overscan: 600) == 1..<2)
+}
+
+@Test func emptyHistoryAndDeletedAnchorsHaveNoInvalidIndices() {
+ var layout = MacChatLayout()
+ #expect(layout.index(at: 0) == nil)
+ #expect(layout.visible(in: .zero, overscan: 100).isEmpty)
+ layout.reset(ids: ["a"], heights: [100])
+ let anchor = layout.anchor(at: 10)!
+ layout.reset(ids: [], heights: [])
+ #expect(layout.offset(for: anchor) == nil)
+}
+
+@Test @MainActor func nativeScrollingReplacesOffscreenHostingViews() async {
+ struct Message: Identifiable, Equatable { let id: String }
+ let items = (0..<200).map { Message(id: String($0)) }
+ let list = MacChatList(items: items, following: .constant(false)) { item in
+ Text(item.id).frame(height: 100)
+ }
+ let coordinator = list.makeCoordinator()
+ let scroll = ChatScrollView()
+ scroll.frame = CGRect(x: 0, y: 0, width: 700, height: 600)
+ coordinator.attach(scroll)
+ coordinator.update(list, environment: EnvironmentValues())
+ coordinator.arrange()
+ let before = Set(coordinator.cells.keys)
+ scroll.contentView.scroll(to: CGPoint(x: 0, y: 5000))
+ // No empty frame is exposed while waiting for a dispatch turn after a large jump.
+ #expect(coordinator.cells["50"] != nil)
+ #expect(coordinator.cells.values.allSatisfy { !$0.controller.view.isHidden && $0.controller.view.frame.height > 0 })
+ // Bounds notifications schedule mounting on the next main run-loop turn.
+ try? await Task.sleep(for: .milliseconds(50))
+ #expect(!before.isEmpty)
+ #expect(Set(coordinator.cells.keys).isDisjoint(with: before))
+ #expect(coordinator.cells.count < 25)
+ #expect(coordinator.cells["50"] != nil)
+ #expect(scroll.contentView.bounds.minY == 5000)
+}
+#endif