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.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(kit): smooth out the iPhone chat
leepokaia448dd942e04
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex bda93109..6c1cacf7 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -10,7 +10,13 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o### zh-Hant- 語音通話預設改用各家最新的模型(例如 OpenAI 的 gpt-transcribe,辨識更準、更認得 bot 的名字),之後有新模型推出也會自動換上,不用等 app 更新。+- 回覆串流更順:文字平穩地一路浮現,畫面穩穩跟著最新內容;往上捲就停在你在看的地方,按下箭頭回到最新。+- 進聊天室先顯示最新的訊息,往上捲再接上更早的;更新 app 之後也不用等對話重新載入。+- 回覆裡的表格、分隔線、巢狀清單和行內程式碼都會正確排版。### en-US- Voice calls now default to each provider's newest models (such as OpenAI's gpt-transcribe: more accurate, and better at your bots' names), and move to newer ones as they come out, without an app update.+- Smoother streaming: replies flow in steadily and the chat glides along with them; scroll up and it stays where you're reading, with an arrow back to the latest.+- A chat opens on its newest messages and brings in earlier ones as you scroll up, and no longer reloads after an app update.+- Tables, dividers, nested lists and inline code in replies are now formatted properly.diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex db24d6a3..9a3f6cf6 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -40,6 +40,7 @@ Source: `apps/macos/App/CodyncMacApp.swift`.- A shared view or control must look the same on both platforms, apart from `InterfaceMetrics.value(mac:mobile:)` sizes. A one-platform look goes in that value's own side, or in a platform file; never change a shared default (fill, spacing, font) for one platform.- Where a screen's chrome differs, it lives in a whole-file platform extension (`ThreadView+iOS.swift`, `ThreadView+macOS.swift`: `platformBody`, `platformChrome`, `header`), not in `#if os()` branches inside the shared body.+- The conversation itself is per platform too: `transcript` (a chat's messages) and `messages` (a thread's replies) live in `ThreadView+…` / `RepliesView+…`. The Mac keeps every loaded message in a lazy stack and scrolls to the newest as it changes. iPhone renders the newest page first and earlier ones as the reader scrolls up, follows the newest message until they scroll away (`ConversationFollow+iOS.swift`, with a round "Jump to latest" button), and reveals a reply steadily as it's written (`ChatRows+iOS.swift`, `MarkdownText+iOS.swift`). Logic both can use stays shared: `ChatItem.build`, `MarkdownBlocks`.- A commit that touches `kit/` is scoped `kit`, not `macos` or `ios`, and is checked on both platforms.## Shared application controlsdiff --git a/kit/Sources/CodyncUI/Thread/ChatRows+iOS.swift b/kit/Sources/CodyncUI/Thread/ChatRows+iOS.swiftnew file mode 100644index 00000000..de720474--- /dev/null+++ b/kit/Sources/CodyncUI/Thread/ChatRows+iOS.swift@@ -0,0 +1,72 @@+#if os(iOS)+import CodyncKit+import SwiftUI++/// iPhone: a row renders again only when what it shows changed, so a reply being written+/// elsewhere in the chat skips it.+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)+ }+}++/// A reply as it's written. The host sends text in bursts; in between, what arrived is+/// revealed at a steady pace, so the reply flows instead of jumping a line at a time.+struct StreamingMarkdown: View {+ let text: String+ /// Still being written (`final == false`).+ let live: Bool+ /// Characters shown while revealing; nil shows all of it.+ @State private var shown: Int?+ /// Text is surfacing right now (caught up, the fade settles).+ @State private var revealing = false+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @Environment(\.conversationScrolling) private var scrolling++ /// How long a burst takes to reveal: a bit over the host's flush interval, so bursts join up.+ private static let window = 0.32+ private static let frame = 1.0 / 60++ var body: some View {+ MarkdownText(shown.map { String(text.prefix($0)) } ?? text, streaming: live, revealing: revealing)+ .equatable()+ .onAppear {+ // A reply already well under way when it scrolls in shows as it is.+ if live, !reduceMotion, shown == nil { shown = text.count > 280 ? text.count : 0 }+ }+ .task(id: RevealTarget(text: text, live: live, paused: scrolling)) { await reveal() }+ }++ private func reveal() async {+ // While the reader scrolls, the text holds still: scrolling never competes with layout.+ guard let start = shown, !scrolling else { return }+ let total = text.count+ var position = Double(min(start, total))+ let step = max((Double(total) - position) / (Self.window / Self.frame), 0.5)+ revealing = position < Double(total)+ defer { if !Task.isCancelled { revealing = false } }+ while position < Double(total) {+ try? await Task.sleep(for: .seconds(Self.frame))+ if Task.isCancelled { return }+ position = min(Double(total), position + step)+ shown = Int(position)+ }+ // Between bursts the open end keeps its fade a moment, so it doesn't flicker.+ if live { try? await Task.sleep(for: .seconds(0.6)) }+ if Task.isCancelled { return }+ if !live { shown = nil }+ }++ private struct RevealTarget: Equatable {+ let text: String+ let live: Bool+ let paused: Bool+ }+}++extension EnvironmentValues {+ /// The reader is scrolling the conversation: streamed text holds still until they stop.+ @Entry var conversationScrolling = false+}+#endifdiff --git a/kit/Sources/CodyncUI/Thread/ChatRows.swift b/kit/Sources/CodyncUI/Thread/ChatRows.swiftindex 5149adc5..4d97538f 100644--- a/kit/Sources/CodyncUI/Thread/ChatRows.swift+++ b/kit/Sources/CodyncUI/Thread/ChatRows.swift@@ -215,10 +215,25 @@ struct AgentBubble: View {var reply: (() -> Void)?@Environment(BotStore.self) private var model@State private var hovering = false+ #if os(iOS)+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ #endif++ /// The reply's text. iPhone: revealed steadily as it's written; the turn's next text+ /// segment takes the bubble over with a cross-fade instead of retyping.+ @ViewBuilder private var text: some View {+ #if os(iOS)+ StreamingMarkdown(text: entry.data.text ?? "", live: entry.data.final == false)+ .id(entry.id)+ .transition(.opacity)+ #else+ MarkdownText(entry.data.text ?? "", streaming: entry.data.final == false)+ #endif+ }var body: some View {VStack(alignment: .leading, spacing: 4) {- MarkdownText(entry.data.text ?? "", streaming: entry.data.final == false)+ 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))@@ -249,6 +264,7 @@ struct AgentBubble: View {#if os(macOS).padding(.trailing, 64)#else+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: entry.id).padding(.trailing, 40)#endif}diff --git a/kit/Sources/CodyncUI/Thread/ConversationFollow+iOS.swift b/kit/Sources/CodyncUI/Thread/ConversationFollow+iOS.swiftnew file mode 100644index 00000000..753cf324--- /dev/null+++ b/kit/Sources/CodyncUI/Thread/ConversationFollow+iOS.swift@@ -0,0 +1,160 @@+#if os(iOS)+import CodyncKit+import SwiftUI++extension View {+ /// Reports whether the top of the content is within half a screen.+ @ViewBuilder func nearTop(_ changed: @escaping (Bool) -> Void) -> some View {+ if #available(iOS 18, *) {+ onScrollGeometryChange(for: Bool.self) { geometry in+ geometry.contentOffset.y + geometry.contentInsets.top < geometry.containerSize.height / 2+ } action: { _, near in+ changed(near)+ }+ } else {+ self+ }+ }++ /// A conversation's scrolling: opens at the newest message and follows it (`following`) as+ /// messages arrive and replies grow. Scrolling away stops following, so the text being read+ /// stays put; scrolling back to the end resumes it.+ /// `keepingPlace`: earlier messages are going in above; the message with this id stays put.+ @ViewBuilder func followsConversation(_ following: Binding<Bool>, keepingPlace: Binding<String?> = .constant(nil)) -> some View {+ if #available(iOS 18, *) {+ modifier(FollowConversation(following: following, keepingPlace: keepingPlace))+ } else {+ defaultScrollAnchor(.bottom)+ }+ }+}++/// Follows the newest message: pinned to the end until the reader scrolls up (their own input,+/// never layout), pinned again once they're back at the end. While the reader is scrolling,+/// nothing moves under them. Pinning always goes through the scroll view's own end+/// (`scrollTo(edge:)`), never a computed offset, and after the layout pass, not inside it.+@available(iOS 18, *)+private struct FollowConversation: ViewModifier {+ @Binding var following: Bool+ /// Earlier messages are going in above: keep this message where it is on screen.+ @Binding var keepingPlace: String?+ @State private var position = ScrollPosition(edge: .bottom)+ @State private var phase = ScrollPhase.idle+ /// Not observed: updated every scrolled frame, read by the handlers.+ @State private var state = FollowState()+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ private static let nearEnd: CGFloat = 32+ private var readerScrolling: Bool {+ phase == .interacting || phase == .decelerating || phase == .tracking+ }++ private struct Place: Equatable {+ var offset: CGFloat+ var content: CGFloat+ var viewport: CGFloat+ var distanceToEnd: CGFloat+ }++ func body(content: Content) -> some View {+ content+ .environment(\.conversationScrolling, readerScrolling)+ .scrollPosition($position)+ .defaultScrollAnchor(.bottom, for: .initialOffset)+ .onScrollGeometryChange(for: Place.self) { geometry in+ let end = geometry.contentSize.height + geometry.contentInsets.bottom - geometry.containerSize.height+ return Place(offset: geometry.contentOffset.y, content: geometry.contentSize.height,+ viewport: geometry.containerSize.height,+ distanceToEnd: max(end, -geometry.contentInsets.top) - geometry.contentOffset.y)+ } action: { old, raw in+ // Geometry's offsets and insets don't always add up to the real end; where a pin+ // to the end actually lands says how far off they are.+ if state.pinned, !readerScrolling, raw.content == old.content {+ state.correction = raw.distanceToEnd+ }+ state.pinned = false+ var new = raw+ new.distanceToEnd -= state.correction+ state.distanceToEnd = new.distanceToEnd+ if keepingPlace != nil, !following, new.content != old.content {+ keepPlace()+ } else if readerScrolling, new.offset < old.offset - 0.5 {+ // The reader moved up: stop following.+ following = false+ } else if !following, new.offset > old.offset, new.distanceToEnd < Self.nearEnd {+ following = true+ } else if following, !readerScrolling, abs(new.distanceToEnd) > 0.5, !state.pinPending {+ // Grown below the view, or shrunk out from under it. Pin after this layout+ // pass, not inside it.+ state.pinPending = true+ DispatchQueue.main.async {+ state.pinPending = false+ if following, !readerScrolling { pin(nil) }+ }+ }+ }+ .onScrollPhaseChange { _, new in+ let wasScrolling = readerScrolling+ phase = new+ if wasScrolling, !readerScrolling { settle() }+ }+ .onChange(of: following) { _, follow in+ if follow { pin(Motion.conversation) }+ }+ }++ /// The reader stopped scrolling: resting at the end follows again; anywhere else stays put.+ private func settle() {+ let atEnd = state.distanceToEnd < Self.nearEnd+ if atEnd, following { pin(nil) }+ following = atEnd+ }++ private func keepPlace() {+ guard let id = keepingPlace else { return }+ var transaction = Transaction()+ transaction.disablesAnimations = true+ withTransaction(transaction) { position.scrollTo(id: id, anchor: .top) }+ }++ private func pin(_ animation: Animation?) {+ state.pinned = animation == nil+ var transaction = Transaction(animation: animation.flatMap { Motion.reduced($0, reduceMotion) })+ transaction.disablesAnimations = animation == nil+ withTransaction(transaction) { position.scrollTo(edge: .bottom) }+ }+}++/// What the follower knows between frames, outside SwiftUI's change tracking.+@MainActor private final class FollowState {+ var distanceToEnd: CGFloat = 0+ /// How far the computed end sits from where pinning to the end really lands.+ var correction: CGFloat = 0+ /// An instant pin was just requested; the next geometry shows where it landed.+ var pinned = false+ var pinPending = false+}++/// Scrolled away from the newest messages: a round button back down to them.+struct JumpToLatest: View {+ let visible: Bool+ let action: () -> Void+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ var body: some View {+ ZStack {+ if visible {+ Button("Jump to latest", systemImage: "arrow.down", action: action)+ .labelStyle(.iconOnly)+ .buttonStyle(IconButtonStyle())+ .frosted(in: Circle())+ .shadow(color: .black.opacity(0.12), radius: 10, y: 3)+ .help("Jump to latest")+ .padding(.bottom, 10)+ .transition(.scale(scale: 0.8).combined(with: .opacity))+ }+ }+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: visible)+ }+}+#endifdiff --git a/kit/Sources/CodyncUI/Thread/MarkdownBlocks.swift b/kit/Sources/CodyncUI/Thread/MarkdownBlocks.swiftnew file mode 100644index 00000000..242b9ac4--- /dev/null+++ b/kit/Sources/CodyncUI/Thread/MarkdownBlocks.swift@@ -0,0 +1,149 @@+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.+enum MarkdownBlocks {+ enum Block: Hashable {+ case paragraph(String)+ case heading(String, level: Int)+ case bullet(String, marker: String, depth: Int = 0)+ case quote(String)+ case code(String, language: String)+ case table(header: [String], rows: [[String]])+ case rule++ /// Flowing text (where a fading end reads as words arriving).+ var isText: Bool {+ switch self {+ case .paragraph, .heading, .bullet, .quote: true+ case .code, .table, .rule: false+ }+ }+ }++ /// Blocks of `source`; while `streaming`, the last one is healed so a marker that's only+ /// half there (`**bo`, `` `co ``, `[link](ht`) doesn't flash as raw syntax.+ static func parse(_ source: String, streaming: Bool) -> [Block] {+ var blocks = parse(source)+ guard streaming, let last = blocks.last else { return blocks }+ switch last {+ case let .paragraph(t): blocks[blocks.count - 1] = .paragraph(heal(t))+ case let .heading(t, level): blocks[blocks.count - 1] = .heading(heal(t), level: level)+ case let .bullet(t, marker, depth): blocks[blocks.count - 1] = .bullet(heal(t), marker: marker, depth: depth)+ case let .quote(t): blocks[blocks.count - 1] = .quote(heal(t))+ case .code, .table, .rule: break+ }+ return blocks+ }++ /// Closes the inline markers left open at the end of text being written.+ static func heal(_ text: String) -> String {+ var t = text+ // A link still being typed shows as its label: `[label](partial` or `[label`.+ if let open = t.lastIndex(of: "[") {+ let rest = t[t.index(after: open)...]+ if let close = rest.firstIndex(of: "]") {+ let after = rest[rest.index(after: close)...]+ if after.hasPrefix("("), !after.contains(")") { t = String(t[..<open]) + rest[..<close] }+ } else if !rest.contains("\n"), rest.count < 120 {+ t = String(t[..<open]) + rest+ }+ }+ let ticks = t.count(where: { $0 == "`" })+ if ticks % 2 == 1 { t += "`" }+ // Outside inline code only.+ let plain = t.split(separator: "`", omittingEmptySubsequences: false).enumerated()+ .filter { $0.offset % 2 == 0 }.map(\.element).joined()+ for marker in ["**", "~~"] where plain.components(separatedBy: marker).count % 2 == 0 {+ t += marker+ }+ return t+ }++ static func parse(_ source: String) -> [Block] {+ var blocks: [Block] = []+ var paragraph: [String] = []+ var table: [String] = []+ var code: [String]?+ var language = ""++ func flush() {+ if !paragraph.isEmpty {+ blocks.append(.paragraph(paragraph.joined(separator: "\n")))+ paragraph = []+ }+ if !table.isEmpty {+ // A header and its `|---|` line make a table; anything less stays text.+ if table.count >= 2, isTableRule(table[1]) {+ blocks.append(.table(header: cells(table[0]), rows: table.dropFirst(2).map(cells)))+ } else {+ blocks.append(.paragraph(table.joined(separator: "\n")))+ }+ table = []+ }+ }++ 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))+ }+ continue+ }+ if code != nil {+ code?.append(raw)+ continue+ }+ if line.hasPrefix("|") {+ if !paragraph.isEmpty { flush() }+ table.append(line)+ continue+ }+ if !table.isEmpty { flush() }+ let depth = min(raw.prefix { $0 == " " || $0 == "\t" }.count / 2, 3)+ if line.isEmpty {+ flush()+ } else if line == "---" || line == "***" || line == "___" {+ flush()+ blocks.append(.rule)+ } 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("+ ") || line.hasPrefix("• ") {+ flush()+ blocks.append(.bullet(String(line.dropFirst(2)), marker: depth > 0 ? "◦" : "•", depth: depth))+ } 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]), depth: depth))+ } else if line.hasPrefix(">") {+ flush()+ blocks.append(.quote(String(line.dropFirst()).trimmingCharacters(in: .whitespaces)))+ } else {+ paragraph.append(raw)+ }+ }+ if let c = code { blocks.append(.code(c.joined(separator: "\n"), language: language)) }+ flush()+ return blocks+ }++ private static func isTableRule(_ line: String) -> Bool {+ line.contains("-") && line.allSatisfy { "|-: ".contains($0) }+ }++ private static func cells(_ line: String) -> [String] {+ var row = line+ if row.hasPrefix("|") { row.removeFirst() }+ if row.hasSuffix("|") { row.removeLast() }+ return row.split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }+ }+}diff --git a/kit/Sources/CodyncUI/Thread/MarkdownText+iOS.swift b/kit/Sources/CodyncUI/Thread/MarkdownText+iOS.swiftnew file mode 100644index 00000000..29cdfc72--- /dev/null+++ b/kit/Sources/CodyncUI/Thread/MarkdownText+iOS.swift@@ -0,0 +1,179 @@+#if os(iOS)+import CodyncKit+import SwiftUI++/// The iPhone'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+ /// New text is surfacing right now: the open end fades in.+ let revealing: Bool++ public init(_ source: String, streaming: Bool = false, revealing: Bool = false) {+ self.source = source+ self.streaming = streaming+ self.revealing = revealing+ }++ public var body: some View {+ let blocks = MarkdownBlocks.parse(source, streaming: streaming)+ VStack(alignment: .leading, spacing: 8) {+ ForEach(Array(blocks.enumerated()), id: \.offset) { i, block in+ MarkdownBlock(block: block, writing: revealing && i == blocks.count - 1).equatable()+ }+ }+ .textSelection(.enabled)+ }++ /// 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+ }+}++/// One block of a reply. The block being written (`writing`) fades in toward its end, so+/// new words surface instead of popping in; once it's done the fade settles.+private struct MarkdownBlock: View, @MainActor Equatable {+ let block: MarkdownBlocks.Block+ let writing: Bool+ @Environment(\.conversationTypography) private var typography+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ nonisolated static func == (a: Self, b: Self) -> Bool { a.block == b.block && a.writing == b.writing }++ var body: some View {+ // The fade alone eases out; text and layout changes stay unanimated.+ content.animation(Motion.reduced(.easeOut(duration: 0.35), reduceMotion)) {+ $0.writingFade(writing && !reduceMotion && block.isText)+ }+ }++ @ViewBuilder private var content: some View {+ switch block {+ case let .paragraph(t):+ Text(MarkdownText.inline(t))+ .font(typography.body)+ .foregroundStyle(Palette.text)+ case let .heading(t, level):+ Text(MarkdownText.inline(t))+ .font(typography.heading(level: level))+ .foregroundStyle(Palette.text)+ case let .bullet(t, marker, depth):+ HStack(alignment: .firstTextBaseline, spacing: 6) {+ Text(marker).foregroundStyle(Palette.secondary).monospacedDigit()+ 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(MarkdownText.inline(t))+ .font(typography.body)+ .foregroundStyle(Palette.secondary)+ .padding(.leading, 10)+ .overlay(alignment: .leading) { Rectangle().fill(Palette.border).frame(width: 3) }+ case let .code(t, _):+ ScrollView(.horizontal, showsIndicators: false) {+ Text(t)+ .font(typography.code)+ .foregroundStyle(Palette.text)+ .padding(10)+ }+ .background(Palette.codeBackground, in: RoundedRectangle(cornerRadius: 8))+ }+ }+}++/// 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++ 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] : ""))+ }+ }+ }+ }+ .font(typography.body)+ .foregroundStyle(Palette.text)+ .fixedSize()+ .padding(.vertical, 2)+ }+ }+}++private extension View {+ @ViewBuilder func writingFade(_ on: Bool) -> some View {+ if #available(iOS 18, *) {+ textRenderer(TrailingFade(length: on ? TrailingFade.writingLength : 0))+ } else {+ self+ }+ }+}++/// Draws text with its last `length` glyphs fading out toward the end, the soft edge of text+/// being written. As more arrives, earlier glyphs move out of the fade and settle.+@available(iOS 18, *)+private struct TrailingFade: TextRenderer {+ static let writingLength: Double = 28+ var length: Double++ var animatableData: Double {+ get { length }+ set { length = newValue }+ }++ func draw(layout: Text.Layout, in context: inout GraphicsContext) {+ guard length > 0.5 else {+ for line in layout { context.draw(line) }+ return+ }+ let total = layout.reduce(0) { $0 + $1.reduce(0) { $0 + $1.count } }+ var index = 0+ for line in layout {+ for run in line {+ // Whole runs before the fade draw as they are.+ if Double(total - index - run.count) >= length {+ context.draw(run)+ index += run.count+ continue+ }+ for slice in run {+ let fromEnd = Double(total - index)+ index += 1+ var glyph = context+ if fromEnd <= length { glyph.opacity = (fromEnd / (length + 1)) * 0.9 + 0.1 }+ glyph.draw(slice)+ }+ }+ }+ }+}+#endifdiff --git a/kit/Sources/CodyncUI/Thread/MarkdownText.swift b/kit/Sources/CodyncUI/Thread/MarkdownText.swiftindex 43edfb2b..8b93583c 100644--- a/kit/Sources/CodyncUI/Thread/MarkdownText.swift+++ b/kit/Sources/CodyncUI/Thread/MarkdownText.swift@@ -1,6 +1,8 @@+#if os(macOS)import CodyncKitimport 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 {@@ -140,3 +142,4 @@ public struct MarkdownText: View {return blocks}}+#endifdiff --git a/kit/Sources/CodyncUI/Thread/RepliesView+iOS.swift b/kit/Sources/CodyncUI/Thread/RepliesView+iOS.swiftnew file mode 100644index 00000000..6a47ac5f--- /dev/null+++ b/kit/Sources/CodyncUI/Thread/RepliesView+iOS.swift@@ -0,0 +1,58 @@+#if os(iOS)+import CodyncKit+import SwiftUI++extension RepliesView {+ /// iPhone: the replies follow the newest one until the reader scrolls away.+ @ViewBuilder var messages: some View {+ let replies = model.replies(botId, root: rootId)+ let working = chat?.isWorking(in: botId, thread: rootId) == true && !model.isOffline+ let items = ChatItem.build(replies, streaming: working, steady: true)+ ScrollView {+ VStack(alignment: .leading, spacing: 0) {+ if let root {+ ChatRow(entry: root, 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()+ Rectangle().fill(Palette.border).frame(height: 1)+ }+ .padding(.vertical, 12)+ }+ ForEach(items) { item in+ if case let .entry(e, groupStart) = item.kind {+ ChatRow(entry: e, groupStart: groupStart, chat: chat) { showTrace = true }+ .equatable()+ .id(item.id)+ .transition(item.id == items.last?.id+ ? .asymmetric(insertion: .move(edge: .bottom).combined(with: .opacity), removal: .opacity)+ : .identity)+ }+ }+ if let chat, working {+ WorkingIndicator(bot: chat, thinking: model.currentThinking(botId, thread: rootId))+ .padding(.top, 6)+ .transition(.opacity)+ }+ Color.clear.frame(height: 8).id("bottom")+ }+ .padding(.horizontal, 16)+ .padding(.top, 8)+ .animation(Motion.reduced(Motion.conversation, reduceMotion), value: items.last?.id)+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: working)+ }+ .scrollIndicators(.never)+ .followsConversation($following)+ .scrollDismissesKeyboard(.interactively)+ .onChange(of: items.last?.id) { _, _ in+ if items.last?.isUserMessage == true { following = true }+ }+ .overlay(alignment: .bottom) {+ JumpToLatest(visible: !following && !items.isEmpty) { following = true }+ }+ }+}+#endifdiff --git a/kit/Sources/CodyncUI/Thread/RepliesView+macOS.swift b/kit/Sources/CodyncUI/Thread/RepliesView+macOS.swiftnew file mode 100644index 00000000..cbd232a1--- /dev/null+++ b/kit/Sources/CodyncUI/Thread/RepliesView+macOS.swift@@ -0,0 +1,40 @@+#if os(macOS)+import CodyncKit+import SwiftUI++extension RepliesView {+ /// The Mac's replies: a lazy stack that opens at the newest.+ @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 }+ HStack(spacing: 10) {+ Text(replies.isEmpty ? "No replies yet" : replies.count == 1 ? "1 reply" : "\(replies.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)+ }+ Color.clear.frame(height: 8)+ }+ .padding(.horizontal, 16)+ .padding(.top, 8)+ }+ .scrollIndicators(.never)+ .defaultScrollAnchor(.bottom)+ .scrollDismissesKeyboard(.interactively)+ }+}+#endifdiff --git a/kit/Sources/CodyncUI/Thread/RepliesView.swift b/kit/Sources/CodyncUI/Thread/RepliesView.swiftindex 678e90a6..34f56f83 100644--- a/kit/Sources/CodyncUI/Thread/RepliesView.swift+++ b/kit/Sources/CodyncUI/Thread/RepliesView.swift@@ -9,14 +9,17 @@ struct RepliesView: View {let botId: Stringlet rootId: Stringlet close: () -> Void- @Environment(BotStore.self) private var model- @State private var showTrace = false+ @Environment(BotStore.self) var model+ @State var showTrace = false+ #if os(iOS)+ @State var following = true+ @Environment(\.accessibilityReduceMotion) var reduceMotion+ #endif- private var chat: Bot? { model.bots[botId] }- private var root: Entry? { model.allEntries(botId).first { $0.id == rootId } }+ var chat: Bot? { model.bots[botId] }+ var root: Entry? { model.allEntries(botId).first { $0.id == rootId } }var body: some View {- let replies = model.replies(botId, root: rootId)VStack(spacing: 0) {HStack(spacing: 8) {VStack(alignment: .leading, spacing: 0) {@@ -32,43 +35,17 @@ struct RepliesView: View {.frame(height: InterfaceMetrics.value(mac: 48, mobile: 56))Rectangle().fill(Palette.border).frame(height: 0.5)- ScrollView {- LazyVStack(alignment: .leading, spacing: 0) {- if let root {- ChatRow(entry: root, groupStart: true, chat: chat) { showTrace = true }- HStack(spacing: 10) {- Text(replies.isEmpty ? "No replies yet" : replies.count == 1 ? "1 reply" : "\(replies.count) replies")- .appFont(.caption)- .foregroundStyle(Palette.tertiary)- .fixedSize()- Rectangle().fill(Palette.border).frame(height: 1)- }- .padding(.vertical, 12)+ // The replies: each platform's own `messages`, in its `RepliesView+` file.+ messages+ .safeAreaInset(edge: .bottom) {+ if let mismatch = model.mismatch {+ UpdateNeededCard(store: model, mismatch: mismatch)+ .padding(.horizontal, 16)+ .padding(.bottom, 8)+ } else {+ Composer(botId: botId, thread: rootId)}- 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)- }- Color.clear.frame(height: 8)}- .padding(.horizontal, 16)- .padding(.top, 8)- }- .defaultScrollAnchor(.bottom)- .scrollDismissesKeyboard(.interactively)- .safeAreaInset(edge: .bottom) {- if let mismatch = model.mismatch {- UpdateNeededCard(store: model, mismatch: mismatch)- .padding(.horizontal, 16)- .padding(.bottom, 8)- } else {- Composer(botId: botId, thread: rootId)- }- }}.background(Palette.background).task(id: rootId) { await model.loadThread(botId, root: rootId) }diff --git a/kit/Sources/CodyncUI/Thread/ThreadView+iOS.swift b/kit/Sources/CodyncUI/Thread/ThreadView+iOS.swiftindex 38990d37..a4d2cb28 100644--- a/kit/Sources/CodyncUI/Thread/ThreadView+iOS.swift+++ b/kit/Sources/CodyncUI/Thread/ThreadView+iOS.swift@@ -11,6 +11,107 @@ extension ThreadView {}}+ /// Messages rendered per page, newest first.+ static let page = 40+ /// Paging needs to know when the reader nears the top (scroll geometry); before that, all render.+ static var paged: Bool {+ if #available(iOS 18, *) { true } else { false }+ }++ private var streaming: Bool { bot?.isWorking(in: botId, thread: nil) == true && !model.isOffline }++ /// iPhone's messages: the newest page first, earlier ones as the reader scrolls up (from+ /// this device, then from the computer); the chat follows the newest message until they+ /// scroll away, and a reply is revealed steadily as it's written.+ @ViewBuilder var transcript: some View {+ let thread = model.chat(botId)+ let all = ChatItem.build(thread, streaming: streaming, steady: true)+ let start = Self.paged ? firstShown.flatMap { id in all.firstIndex { $0.id == id } } ?? max(0, all.count - Self.page) : 0+ let items = Array(all[start...])+ let moreOnComputer = !model.historyComplete.contains(botId) && thread.count >= 50+ ScrollView {+ // Not lazy: only a page or a few render, and lazy rows of very different heights+ // (long replies) mis-estimate on the way to the bottom and can leave it blank.+ VStack(alignment: .leading, spacing: 0) {+ if start > 0 || moreOnComputer {+ Spinner(size: 14)+ .frame(maxWidth: .infinity)+ .padding(.vertical, 14)+ .onChange(of: following) { _, _ in showEarlier() }+ .accessibilityLabel("Loading earlier messages")+ }+ if all.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")+ .transition(.opacity)+ }+ Color.clear.frame(height: 8).id("bottom")+ }+ .padding(.horizontal, 16)+ .padding(.top, 8)+ .animation(Motion.reduced(Motion.conversation, reduceMotion), value: items.last?.id)+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: bot?.isWorking(in: botId, thread: nil))+ }+ .scrollIndicators(.never)+ .nearTop { near in+ topVisible = near+ showEarlier()+ }+ .followsConversation($following, keepingPlace: $keepingPlace)+ .scrollDismissesKeyboard(.interactively)+ .conversationScrollEdges()+ .simultaneousGesture(TapGesture().onEnded { dismissChatKeyboard() })+ .onChange(of: items.last?.id) { _, _ in+ // Sending brings the chat back down to your message.+ if items.last?.isUserMessage == true { following = true }+ }+ .overlay(alignment: .bottom) {+ JumpToLatest(visible: !following && !items.isEmpty) { following = true }+ }+ .onAppear { if firstShown == nil { firstShown = items.first?.id } }+ }++ /// The reader scrolled up to the top: render the previous page, fetching it from the+ /// computer when this device has no more. The message they were on keeps its place.+ private func showEarlier() {+ guard topVisible, !following, !loadingEarlier else { return }+ loadingEarlier = true+ Task {+ var list = ChatItem.build(model.chat(botId), streaming: streaming, steady: true)+ var start = firstShown.flatMap { id in list.firstIndex { $0.id == id } } ?? max(0, list.count - Self.page)+ if start == 0 {+ let anchor = list.first?.id+ await model.loadOlder(botId)+ list = ChatItem.build(model.chat(botId), streaming: streaming, steady: true)+ start = anchor.flatMap { id in list.firstIndex { $0.id == id } } ?? 0+ }+ guard start > 0 else {+ loadingEarlier = false+ return+ }+ keepingPlace = list[start].id+ firstShown = list[max(0, start - Self.page)].id+ // Rows above settle over a few layout passes.+ try? await Task.sleep(for: .milliseconds(400))+ keepingPlace = nil+ loadingEarlier = false+ // Still at the top with more to show: keep going.+ showEarlier()+ }+ }+/// The system navigation bar: the title pill holds the bot's actions; the corner is the computer.func platformChrome(_ content: some View) -> some View {contentdiff --git a/kit/Sources/CodyncUI/Thread/ThreadView+macOS.swift b/kit/Sources/CodyncUI/Thread/ThreadView+macOS.swiftindex 12663d5c..dc92fbd9 100644--- a/kit/Sources/CodyncUI/Thread/ThreadView+macOS.swift+++ b/kit/Sources/CodyncUI/Thread/ThreadView+macOS.swift@@ -42,6 +42,76 @@ 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.+ @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")+ }+ .padding(.horizontal, 16)+ .padding(.top, 8)+ .animation(Motion.reduced(Motion.conversation, reduceMotion), value: items.last?.id)+ .frame(maxWidth: 820)+ .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)+ }+ }+ .onChange(of: bot?.isWorking) { _, _ in+ guard isAtBottom else { return }+ withAnimation(Motion.reduced(Motion.conversation, reduceMotion)) {+ proxy.scrollTo("bottom", anchor: .bottom)+ }+ }+ .onChange(of: typography.pointSize) { _, _ in+ guard isAtBottom else { return }+ proxy.scrollTo("bottom", anchor: .bottom)+ }+ }+ }+func platformChrome(_ content: some View) -> some View {content// Grok's desktop chat: no title bar. The chat blurs and fades as it scrolls up, with the botdiff --git a/kit/Sources/CodyncUI/Thread/ThreadView.swift b/kit/Sources/CodyncUI/Thread/ThreadView.swiftindex befc4d4c..dc24e1db 100644--- a/kit/Sources/CodyncUI/Thread/ThreadView.swift+++ b/kit/Sources/CodyncUI/Thread/ThreadView.swift@@ -28,7 +28,19 @@ public struct ThreadView: View {@State var showRoutines = false@State var routineId: String?@State var routineRequest = UUID()- @State var isAtBottom = true+ #if os(macOS)+ @State var isAtBottom = true+ #else+ /// iPhone: the chat stays on the newest message until the reader scrolls away.+ @State var following = true+ /// The oldest message rendered (nil: the latest page).+ @State var firstShown: String?+ @State var loadingEarlier = false+ /// Earlier messages are going in above: this one keeps its place on screen.+ @State var keepingPlace: String?+ /// The top of the rendered messages is within reach.+ @State var topVisible = false+ #endif@Environment(\.accessibilityReduceMotion) var reduceMotion#if os(macOS)@Environment(\.conversationTypography) var typography@@ -42,79 +54,10 @@ public struct ThreadView: View {withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { openThread = nil }}- /// The messages and the composer, without the platform's top chrome.- @ViewBuilder private var chat: 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")- }- .padding(.horizontal, 16)- .padding(.top, 8)- .animation(Motion.reduced(Motion.conversation, reduceMotion), value: items.last?.id)- #if os(macOS)- .frame(maxWidth: 820)- .frame(maxWidth: .infinity)- #endif- }- .conversationInitialBottomAnchor()- .scrollDismissesKeyboard(.interactively)- .conversationScrollEdges()- .conversationBottomObserver($isAtBottom)- #if os(iOS)- .simultaneousGesture(TapGesture().onEnded { dismissChatKeyboard() })- #endif- .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)- }- }- .onChange(of: bot?.isWorking) { _, _ in- guard isAtBottom else { return }- withAnimation(Motion.reduced(Motion.conversation, reduceMotion)) {- proxy.scrollTo("bottom", anchor: .bottom)- }- }- #if os(macOS)- .onChange(of: typography.pointSize) { _, _ in- guard isAtBottom else { return }- proxy.scrollTo("bottom", anchor: .bottom)- }- #endif- }+ /// The messages (each platform's own `transcript`, in its `ThreadView+` file) and the+ /// composer, without the platform's top chrome.+ private var chat: some View {+ transcript.background(Palette.background).safeAreaInset(edge: .bottom) {VStack(spacing: 6) {@@ -185,7 +128,7 @@ public struct ThreadView: View {// MARK: rows- @ViewBuilder private func row(_ item: ChatItem) -> some View {+ @ViewBuilder func row(_ item: ChatItem) -> some View {switch item.kind {case .separator(let date):Text(RelativeTime.separator(date))@@ -208,6 +151,9 @@ public struct ThreadView: View {} openThread: { root inwithAnimation(Motion.reduced(Motion.layout, reduceMotion)) { openThread = ThreadTarget(id: root.id) }}+ #if os(iOS)+ .equatable()+ #endif}}}@@ -322,14 +268,24 @@ struct ChatItem: Identifiable {/// `streaming`: a turn is running in this chat, so the text being generated right now/// (the lane's last entry, still `final == false`) shows in place and never pops in later./// Earlier segments of the turn, tool calls in between, and a room pass stay trace-only.- static func build(_ entries: [Entry], streaming: Bool = false) -> [ChatItem] {+ /// `steady` (iPhone): the turn's newest text stays while the agent works on (tools,+ /// thinking) until newer text replaces it, and a reply is one item per author and turn,+ /// from its first words to the final message, so its bubble never pops out and back in.+ static func build(_ entries: [Entry], streaming: Bool = false, steady: Bool = false) -> [ChatItem] {var out: [ChatItem] = []+ var used = Set<String>()var lastDate: Date?var lastAuthor: String?- let live = streaming ? entries.last.flatMap { $0.kind == "agent" && $0.data.final == false ? $0.id : nil } : nil+ let live = !streaming ? nil+ : steady ? liveText(entries)+ : entries.last.flatMap { $0.kind == "agent" && $0.data.final == false ? $0.id : nil }for e in entries where e.isChat || (e.id == live && !(e.data.text ?? "").isEmpty && e.data.text != "(pass)") {let date = e.date- let id = e.kind == "user" ? e.data.clientNonce.map { "user-\($0)" } ?? e.id : e.id+ var id = e.kind == "user" ? e.data.clientNonce.map { "user-\($0)" } ?? e.id : e.id+ if steady, e.kind == "agent", !used.contains("reply-\(e.data.author ?? "")-\(e.turn)") {+ id = "reply-\(e.data.author ?? "")-\(e.turn)"+ }+ used.insert(id)if lastDate.map({ date.timeIntervalSince($0) > 3600 }) ?? true {out.append(ChatItem(id: "sep-\(id)", kind: .separator(date)))lastAuthor = nil@@ -343,6 +299,17 @@ struct ChatItem: Identifiable {return out}+ /// The running turn's newest text, if any since the last message or final reply.+ static func liveText(_ entries: [Entry]) -> String? {+ for e in entries.reversed() {+ if e.kind == "user" || (e.kind == "agent" && e.data.final == true) { return nil }+ if e.kind == "agent", let text = e.data.text, !text.isEmpty {+ return text == "(pass)" ? nil : e.id+ }+ }+ return nil+ }+var isUserMessage: Bool {if case let .entry(entry, _) = kind { entry.kind == "user" } else { false }}@@ -353,7 +320,7 @@ struct ChatItem: Identifiable {}/// The start of an empty group chat: who's in it and how the room works.-private struct GroupIntroCard: View {+struct GroupIntroCard: View {let group: Bot@Environment(BotStore.self) private var model@@ -382,7 +349,7 @@ private struct GroupIntroCard: View {}}-private struct IntroCard: View {+struct IntroCard: View {let bot: Bot@Environment(BotStore.self) private var model@@ -411,7 +378,7 @@ private struct IntroCard: View {}}-private extension View {+extension View {@ViewBuilder func conversationInitialBottomAnchor() -> some View {if #available(iOS 18, macOS 15, *) {defaultScrollAnchor(.bottom, for: .initialOffset)diff --git a/kit/Tests/CodyncUITests/ChatItemTests.swift b/kit/Tests/CodyncUITests/ChatItemTests.swiftindex c1d5606e..e6f3190d 100644--- a/kit/Tests/CodyncUITests/ChatItemTests.swift+++ b/kit/Tests/CodyncUITests/ChatItemTests.swift@@ -24,3 +24,63 @@ import Testing// A room pass is being generated: still not chat.#expect(ids(ChatItem.build([running[0], entry(2, "agent", "(pass)", final: false)], streaming: true)) == ["e1"])}++/// iPhone (`steady`): the turn's newest text stays while tools run, and a reply is one item+/// from its first words to the final message.+@Test func steadyChatKeepsTheTurnsNewestTextInOneBubble() {+ func entry(_ seq: Int64, _ kind: String, _ text: String? = nil, final: Bool? = nil) -> Entry {+ var data = EntryData(text: text)+ data.final = final+ return Entry(id: "e\(seq)", seq: seq, botId: "b", rev: seq, kind: kind, turn: 1, data: data, createdAt: 0, updatedAt: 0)+ }+ let ids = { (items: [ChatItem]) in items.compactMap { if case let .entry(e, _) = $0.kind { e.id } else { nil } } }+ let build = { (entries: [Entry], streaming: Bool) in ChatItem.build(entries, streaming: streaming, steady: true) }++ let running = [entry(1, "user", "Fix it"), entry(2, "agent", "I'll read it first.", final: false),+ entry(3, "tool_call", "Read"), entry(4, "agent", "Done. It raced", final: false)]+ let done = [running[0], running[1], running[2], entry(4, "agent", "Done. It raced the refresh.", final: true)]+ #expect(ids(build(running, true)) == ["e1", "e4"])+ #expect(ids(build(running, false)) == ["e1"])+ #expect(ids(build(done, false)) == ["e1", "e4"])+ // A tool runs after the narration: the narration stays until newer text comes.+ #expect(ids(build(Array(running.prefix(3)), true)) == ["e1", "e2"])+ // Narration, the answer being written and the final reply are the same bubble.+ let live = build(running, true).last?.id+ #expect(live == build(done, false).last?.id)+ #expect(build(Array(running.prefix(3)), true).last?.id == live)+ // A room pass is being generated: still not chat.+ #expect(ids(build([running[0], entry(2, "agent", "(pass)", final: false)], true)) == ["e1"])+}++/// Text being written hides half-typed markers instead of flashing them raw.+@Test func markdownBlocksHealTheOpenEnd() {+ #expect(MarkdownBlocks.heal("so **bo") == "so **bo**")+ #expect(MarkdownBlocks.heal("run `ls") == "run `ls`")+ #expect(MarkdownBlocks.heal("`a**b` and **c") == "`a**b` and **c**")+ #expect(MarkdownBlocks.heal("see [the docs](https://exa") == "see the docs")+ #expect(MarkdownBlocks.heal("see [the do") == "see the do")+ #expect(MarkdownBlocks.heal("- [ ] task") == "- [ ] task")+ #expect(MarkdownBlocks.heal("done [x](y) **ok**") == "done [x](y) **ok**")+ // Only the block being written is healed.+ #expect(MarkdownBlocks.parse("**a\n\nb **c", streaming: true) == [.paragraph("**a"), .paragraph("b **c**")])+}++/// Tables, rules and nested lists, as agents write them.+@Test func markdownBlocksParseTablesRulesAndNesting() {+ let blocks = MarkdownBlocks.parse("""+ | Name | Size |+ |---|:-:|+ | a | 1 |+ ---+ - top+ - inner+ | not a table+ """)+ #expect(blocks == [+ .table(header: ["Name", "Size"], rows: [["a", "1"]]),+ .rule,+ .bullet("top", marker: "•", depth: 0),+ .bullet("inner", marker: "◦", depth: 1),+ .paragraph("| not a table"),+ ])+}