oficina / base Public

Draw Ask Base natively

The thread as the mockups draw it: the person's and the Assistant's
bubbles, the reply streaming in with its caret, the thinking bubble's
dots and then Equipo's words; job pills with their state marks, title
and status, the Try it link and the open cards hanging under them;
question, confirm, outcome and connect cards with ghost buttons; Jump
to latest; and the composer with Send and Stop inside the field and the
luminous focus edge. Ask's other states show the web's approved copy,
and norunner and oldrunner their note with its link to Equipo. A pill
opens its job view, a popover on the Mac and a sheet on the iPhone.

The Assistant's Markdown is Equipo's parser and renderer (EquipoKit at
00d09aa7, each copied file naming its source), with links held to
Base's rule: absolute http(s) only. VoiceOver reads a pill as its title
and status, the type follows Dynamic Type, and Reduce Motion stills the
working arc, the dots, the caret and the focus edge.

The web's Ask copy is in the catalog under ask.*, Equipo's code-block
labels under chat.paste.*, and check-strings.py now counts a key handed
to a helper as used.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev daeb33b0031a9bfe2dfa062dc8298743f3f25de0 parent 9c8d52c
19 files changed, +2,264 −3
  • native/apple/Sources/BaseKit/Ask/AskModel.swift +4 −0
  • native/apple/Sources/BaseKit/Ask/AskView.swift +100 −0
  • native/apple/Sources/BaseKit/Ask/Card.swift +153 −0
  • native/apple/Sources/BaseKit/Ask/Composer.swift +141 −0
  • native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift +174 −0
  • native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift +505 −0
  • native/apple/Sources/BaseKit/Ask/Markdown/MarkdownActions.swift +43 −0
  • native/apple/Sources/BaseKit/Ask/Markdown/MarkdownDraft.swift +79 −0
  • native/apple/Sources/BaseKit/Ask/Markdown/MarkdownEntities.swift +78 −0
  • native/apple/Sources/BaseKit/Ask/Markdown/MarkdownInput.swift +159 −0
  • native/apple/Sources/BaseKit/Ask/Markdown/MarkdownPresentation.swift +47 −0
  • native/apple/Sources/BaseKit/Ask/Markdown/MarkdownRenderCache.swift +46 −0
  • native/apple/Sources/BaseKit/Ask/Markdown/MarkdownStreamRenderer.swift +65 −0
  • native/apple/Sources/BaseKit/Ask/Markdown/MarkdownTranscript.swift +33 −0
  • native/apple/Sources/BaseKit/Ask/Pill.swift +236 −0
  • native/apple/Sources/BaseKit/Ask/Thread.swift +224 −0
  • native/apple/Tests/BaseKitTests/AskViewTests.swift +45 −0
  • native/apple/Tests/BaseSnapshots/AskSnapshots.swift +127 −0
  • native/scripts/check-strings.py +5 −3
diff --git a/native/apple/Sources/BaseKit/Ask/AskModel.swift b/native/apple/Sources/BaseKit/Ask/AskModel.swift
index 83072ca..080143b 100644
--- a/native/apple/Sources/BaseKit/Ask/AskModel.swift
+++ b/native/apple/Sources/BaseKit/Ask/AskModel.swift
@@ -40,6 +40,7 @@ import Observation
public var open: [AskCard]
public var ended: [AskCard]
public var state: JobState { card.jobState ?? .working }
+ public init(card: AskCard, open: [AskCard] = [], ended: [AskCard] = []) { self.card = card; self.open = open; self.ended = ended }
}
/// An open connect card, drawn as the Connect Oficina button; connected,
@@ -334,6 +335,9 @@ import Observation
setTurn(s.turn, line: s.status)
}
+ /// Draws a state with no stream: previews and snapshots.
+ public func applyForPreview(_ s: AskSnapshot) { apply(s) }
+
/// One event from the stream (ask.js `listen`).
public func apply(_ event: AskEvent) {
switch event {
diff --git a/native/apple/Sources/BaseKit/Ask/AskView.swift b/native/apple/Sources/BaseKit/Ask/AskView.swift
new file mode 100644
index 0000000..beda8b4
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/AskView.swift
@@ -0,0 +1,100 @@
+import SwiftUI
+
+/// What the app does for Ask beyond Base's routes: opening links (the
+/// browser, or another app), and setting Ask up (Task 12 runs Oficina ID's
+/// set-up; until then the web's Settings).
+public struct AskActions {
+ public var setUp: () -> Void
+ public init(setUp: @escaping () -> Void) { self.setUp = setUp }
+}
+
+/// Ask Base, drawn: the conversation, its status line and the composer, or
+/// in their place the state Ask is in, with the web's approved copy
+/// (chat.html `ask-body`). The window's bar, title and the Mac's sidebar
+/// are the apps' own (Tasks 13 and 14).
+public struct AskView: View {
+ @Bindable var model: AskModel
+ let layout: AskLayout
+ let timeZone: TimeZone?
+ let actions: AskActions
+ @FocusState private var focused: Bool
+ @Environment(\.colorScheme) private var scheme
+
+ public init(model: AskModel, layout: AskLayout, timeZone: TimeZone?, actions: AskActions) {
+ self.model = model; self.layout = layout; self.timeZone = timeZone; self.actions = actions
+ }
+
+ public var body: some View {
+ let p = Palette(scheme)
+ Group {
+ if model.phase.chatting {
+ VStack(spacing: 0) {
+ if model.isEmpty {
+ Spacer(minLength: 0)
+ Text(BaseText.text("ask.empty"))
+ .font(BaseFont.body(14, relativeTo: .subheadline)).foregroundStyle(p[.haze])
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 20).padding(.bottom, 12)
+ } else {
+ AskThread(model: model, layout: layout, timeZone: timeZone)
+ }
+ foot(p)
+ }
+ } else {
+ note(p)
+ }
+ }
+ .foregroundStyle(p[.frost])
+ }
+
+ @ViewBuilder private func foot(_ p: Palette) -> some View {
+ VStack(alignment: .leading, spacing: 6) {
+ if model.phase == .norunner || model.phase == .oldrunner {
+ Text(runnerNote(model.phase == .norunner ? "ask.norunner" : "ask.oldrunner"))
+ .font(BaseFont.body(14, relativeTo: .subheadline)).foregroundStyle(p[.haze]).tint(p[.focus])
+ .accessibilityAddTraits(.isStaticText)
+ }
+ if !model.status.isEmpty {
+ Text(verbatim: model.status)
+ .font(BaseFont.body(14, relativeTo: .subheadline)).foregroundStyle(p[.haze])
+ .accessibilityAddTraits(.updatesFrequently)
+ }
+ Composer(model: model, focused: $focused)
+ }
+ .padding(.horizontal, layout == .window ? 24 : 10)
+ .padding(.top, 6)
+ .padding(.bottom, layout == .window ? 20 : 12)
+ }
+
+ /// The web's note, its link to Equipo kept a link.
+ private func runnerNote(_ key: String) -> AttributedString {
+ let origin = model.equipoOrigin?.absoluteString ?? ""
+ let text = BaseText.format(key, ["equipo": origin])
+ guard var out = try? AttributedString(markdown: text) else { return AttributedString(text) }
+ for run in out.runs where run.link != nil { out[run.range].underlineStyle = .single }
+ return out
+ }
+
+ @ViewBuilder private func note(_ p: Palette) -> some View {
+ VStack(alignment: .leading, spacing: 14) {
+ switch model.phase {
+ case .connect: lede("ask.connect.lede", p); button("ask.connect.button")
+ case .pending: lede("ask.pending.lede", p); button("ask.pending.button")
+ case .reconnect: lede("ask.reconnect.lede", p); button("ask.reconnect.button")
+ case .notLinked: lede("native.ask.not_linked", p)
+ case .loading: ProgressView().controlSize(.small)
+ default: lede("ask.unavailable", p)
+ }
+ }
+ .padding(.vertical, 22).padding(.horizontal, 20)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ }
+
+ private func lede(_ key: String, _ p: Palette) -> some View {
+ Text(BaseText.text(key)).font(BaseFont.body(16)).foregroundStyle(p[.haze]).fixedSize(horizontal: false, vertical: true)
+ }
+
+ private func button(_ key: String) -> some View {
+ Button(action: actions.setUp) { Text(BaseText.text(key)) }.buttonStyle(BaseButtonStyle(.primary))
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Card.swift b/native/apple/Sources/BaseKit/Ask/Card.swift
new file mode 100644
index 0000000..b8b1ac7
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Card.swift
@@ -0,0 +1,153 @@
+import SwiftUI
+
+/// The web's buttons (`.btn`, `.btn.ghost`): one control height, 44 pt,
+/// 10 pt corners, semibold. Primary is frost on the dark (ink on the
+/// light); ghost is a faint fill with an edge.
+public struct BaseButtonStyle: ButtonStyle {
+ public enum Kind: Sendable { case primary, ghost }
+ let kind: Kind
+ var expands = false
+ @Environment(\.colorScheme) private var scheme
+ @Environment(\.isEnabled) private var enabled
+ public init(_ kind: Kind, expands: Bool = false) { self.kind = kind; self.expands = expands }
+
+ public func makeBody(configuration: Configuration) -> some View {
+ let p = Palette(scheme)
+ let shape = RoundedRectangle(cornerRadius: 10, style: .continuous)
+ configuration.label
+ .font(BaseFont.body(15, .semibold))
+ .lineLimit(2)
+ .multilineTextAlignment(.center)
+ .padding(.horizontal, 18)
+ .frame(minHeight: 44)
+ .frame(maxWidth: expands ? .infinity : nil)
+ .foregroundStyle(kind == .primary ? p[.btnInk] : p[.frost])
+ .background(kind == .primary ? p[.btn] : p[.ghost], in: shape)
+ .overlay { if kind == .ghost { shape.strokeBorder(p[.ghostEdge], lineWidth: 1) } }
+ .opacity(enabled ? (configuration.isPressed ? 0.8 : 1) : 0.55)
+ .contentShape(shape)
+ }
+}
+
+/// What a card is drawn with: its question, a link per link, a ghost button
+/// per option while it is open, and the line saying how it ended (ask.js
+/// `addCard`, chat.html `ask-card`). A job's decision cards hang under its
+/// pill with a thread line (`hanging`).
+struct CardView: View {
+ let card: AskCard
+ let busy: Bool
+ var hanging = false
+ let answer: (AskCard.Option) -> Void
+ @Environment(\.colorScheme) private var scheme
+ @Environment(\.openURL) private var openURL
+
+ var body: some View {
+ let p = Palette(scheme)
+ VStack(alignment: .leading, spacing: 10) {
+ Text(verbatim: card.question).font(BaseFont.body(15)).fixedSize(horizontal: false, vertical: true)
+ ForEach(card.links, id: \.self) { link in
+ if let url = link.url {
+ Button { openURL(url) } label: {
+ Text(verbatim: link.label.isEmpty ? url.absoluteString : link.label)
+ .font(BaseFont.body(15, .medium)).underline().foregroundStyle(p[.focus])
+ .frame(minHeight: 44, alignment: .leading)
+ }
+ .buttonStyle(.plain)
+ .accessibilityAddTraits(.isLink)
+ }
+ }
+ if card.isOpen, !card.options.isEmpty {
+ FlowLayout(spacing: 8) {
+ ForEach(card.options, id: \.self) { option in
+ Button { answer(option) } label: { Text(verbatim: option.label.isEmpty ? option.value : option.label) }
+ .buttonStyle(BaseButtonStyle(.ghost))
+ .disabled(busy)
+ }
+ }
+ }
+ if !card.result.isEmpty {
+ Text(verbatim: card.result).font(BaseFont.body(14, relativeTo: .subheadline)).foregroundStyle(p[.haze])
+ }
+ }
+ .foregroundStyle(p[.frost])
+ .padding(.vertical, 10).padding(.horizontal, 14)
+ .frame(maxWidth: hanging ? 340 : .infinity, alignment: .leading)
+ .background(p[.card], in: RoundedRectangle(cornerRadius: 14, style: .continuous))
+ .overlay { RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(p[.cardEdge], lineWidth: 1) }
+ .accessibilityElement(children: .contain)
+ }
+}
+
+/// An open connect card: the Connect Oficina button, coloured glass teal
+/// into violet with white ink in both themes, and under it what connecting
+/// unlocks; connected, a quiet line with a tick (chat.html `ask-offer`).
+/// Connecting is Base's own web page: it opens in the browser.
+struct OfferView: View {
+ let offer: AskModel.Offer
+ @Environment(\.colorScheme) private var scheme
+ @Environment(\.openURL) private var openURL
+
+ var body: some View {
+ let p = Palette(scheme)
+ if offer.connected {
+ HStack(spacing: 6) {
+ Icon(.done, weight: 2.4).foregroundStyle(p[.focus]).frame(width: 16, height: 16)
+ Text(BaseText.text("ask.connected")).font(BaseFont.body(14, .medium)).foregroundStyle(p[.haze])
+ }
+ .padding(.leading, 4)
+ } else {
+ VStack(alignment: .leading, spacing: 6) {
+ Button {
+ if let url = offer.card.connectLink?.url { openURL(url) }
+ } label: {
+ HStack(spacing: 10) {
+ Image(systemName: "circle.hexagongrid.fill")
+ .font(.system(size: 18))
+ .frame(width: 32, height: 32)
+ .accessibilityHidden(true)
+ Text(BaseText.text("ask.connect_oficina")).font(BaseFont.body(15, .semibold))
+ }
+ .foregroundStyle(p[.goInk])
+ .padding(.leading, 8).padding(.trailing, 20)
+ .frame(minHeight: 48)
+ .background(LinearGradient(colors: [p[.go1], p[.go2]], startPoint: .leading, endPoint: .trailing), in: Capsule())
+ .overlay { Capsule().strokeBorder(p[.goEdge], lineWidth: 1) }
+ .shadow(color: p[.edgeGlowB].opacity(0.6), radius: 11, y: 10)
+ }
+ .buttonStyle(.plain)
+ Text(BaseText.text("ask.connect_oficina.line"))
+ .font(BaseFont.body(13.5, relativeTo: .footnote)).foregroundStyle(p[.haze]).padding(.leading, 8)
+ }
+ .padding(.leading, 4)
+ }
+ }
+}
+
+/// Lays its children in rows, wrapping, as `.choices` (flex-wrap) does.
+struct FlowLayout: Layout {
+ var spacing: CGFloat = 8
+
+ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
+ let width = proposal.width ?? .infinity
+ var x: CGFloat = 0, y: CGFloat = 0, row: CGFloat = 0, widest: CGFloat = 0
+ for view in subviews {
+ let size = view.sizeThatFits(ProposedViewSize(width: width, height: nil))
+ if x > 0, x + size.width > width { y += row + spacing; x = 0; row = 0 }
+ x += size.width + spacing
+ row = max(row, size.height)
+ widest = max(widest, x - spacing)
+ }
+ return CGSize(width: min(widest, width), height: y + row)
+ }
+
+ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
+ var x = bounds.minX, y = bounds.minY, row: CGFloat = 0
+ for view in subviews {
+ let size = view.sizeThatFits(ProposedViewSize(width: bounds.width, height: nil))
+ if x > bounds.minX, x + size.width > bounds.maxX { y += row + spacing; x = bounds.minX; row = 0 }
+ view.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(width: min(size.width, bounds.width), height: size.height))
+ x += size.width + spacing
+ row = max(row, size.height)
+ }
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Composer.swift b/native/apple/Sources/BaseKit/Ask/Composer.swift
new file mode 100644
index 0000000..9d9a4d7
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Composer.swift
@@ -0,0 +1,141 @@
+import SwiftUI
+
+/// The composer (chat.html `.composer`): one field that grows to a few
+/// lines, with Send (an arrow) and, while a turn runs, Stop (a square) in
+/// its end, round and filled like a primary button. Return sends; Shift
+/// Return is a new line. Focused, a thin luminous edge outside the field,
+/// teal into violet, drifts round it (a turn every 6 s) over a soft glow;
+/// with Reduce Motion it holds still.
+public struct Composer: View {
+ @Bindable var model: AskModel
+ @FocusState.Binding var focused: Bool
+ @Environment(\.colorScheme) private var scheme
+
+ public init(model: AskModel, focused: FocusState<Bool>.Binding) {
+ self.model = model
+ _focused = focused
+ }
+
+ private var canSend: Bool { model.turn == nil && !model.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
+
+ public var body: some View {
+ let p = Palette(scheme)
+ let shape = RoundedRectangle(cornerRadius: 10, style: .continuous)
+ HStack(alignment: .bottom, spacing: 0) {
+ TextField(text: $model.text, prompt: Text(BaseText.text("ask.placeholder")).foregroundStyle(p[.placeholder]), axis: .vertical) {
+ Text(BaseText.text("ask.message_label"))
+ }
+ .textFieldStyle(.plain)
+ .font(BaseFont.body(16))
+ .foregroundStyle(p[.frost])
+ .lineLimit(1...7)
+ .focused($focused)
+ .onSubmit(send)
+ // Return sends and Shift Return is a new line, as on the web.
+ .onKeyPress(.return, phases: .down) { press in
+ guard !press.modifiers.contains(.shift) else { return .ignored }
+ send()
+ return .handled
+ }
+ #if os(iOS)
+ .submitLabel(.send)
+ #endif
+ .padding(.vertical, 11).padding(.leading, 14).padding(.trailing, model.turn != nil || canSend ? 4 : 14)
+ .frame(minHeight: 44)
+ .accessibilityLabel(Text(BaseText.text("ask.message_label")))
+ if model.turn != nil {
+ RoundAction(icon: .stop, label: BaseText.text("ask.stop")) { Task { await model.stop() } }
+ .transition(.scale(scale: 0.6).combined(with: .opacity))
+ } else if canSend {
+ RoundAction(icon: .send, label: BaseText.text("ask.send"), action: send)
+ .disabled(model.sending)
+ .transition(.scale(scale: 0.6).combined(with: .opacity))
+ }
+ }
+ .background(p[.field], in: shape)
+ .overlay { shape.strokeBorder(p[.fieldEdge], lineWidth: 1) }
+ .background { if focused { FocusEdge() } }
+ .animation(.easeOut(duration: 0.16), value: model.turn == nil)
+ .animation(.easeOut(duration: 0.16), value: canSend)
+ }
+
+ private func send() {
+ guard canSend else { return }
+ Task { await model.send() }
+ }
+}
+
+/// Send and Stop: a 32 pt circle in a 44 pt target.
+struct RoundAction: View {
+ enum Kind { case send, stop }
+ let icon: Kind
+ let label: String
+ let action: () -> Void
+ @Environment(\.colorScheme) private var scheme
+ var body: some View {
+ let p = Palette(scheme)
+ Button(action: action) {
+ ZStack {
+ Circle().fill(p[.btn])
+ switch icon {
+ case .send: Icon(.send, weight: 2.4).frame(width: 18, height: 18)
+ case .stop: RoundedRectangle(cornerRadius: 2 * 18 / 24).frame(width: 11 * 18 / 24, height: 11 * 18 / 24)
+ }
+ }
+ .foregroundStyle(p[.btnInk])
+ .frame(width: 32, height: 32)
+ .frame(width: 44, height: 44)
+ .contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(Text(label))
+ .help(Text(label))
+ }
+}
+
+/// The focus edge: a 2 pt ring 3 pt outside the field, a conic gradient
+/// (--edge-a, --edge-hi, --edge-a, --edge-b) turning every 6 s, over a glow
+/// of --edge-glow-a and --edge-glow-b that breathes (2.25 s). The edge
+/// stays at full strength, so it is a real focus indicator.
+struct FocusEdge: View {
+ @Environment(\.colorScheme) private var scheme
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @Environment(\.skyFrozen) private var frozen
+
+ var body: some View {
+ if reduceMotion || frozen {
+ ring(turn: 0, breath: 0.6)
+ } else {
+ TimelineView(.animation(minimumInterval: 1.0 / 30)) { timeline in
+ let t = timeline.date.timeIntervalSinceReferenceDate
+ ring(turn: t.truncatingRemainder(dividingBy: 6) / 6 * 360,
+ breath: SkyPainter.cubicBezier(SkyPainter.progress(t, period: 2.25, delay: 0, reverse: false), 0.37, 0, 0.63, 1))
+ }
+ }
+ }
+
+ func ring(turn: Double, breath: Double) -> some View {
+ let p = Palette(scheme)
+ let shape = RoundedRectangle(cornerRadius: 13, style: .continuous)
+ let gradient = AngularGradient(stops: [
+ .init(color: p[.edgeA], location: 0), .init(color: p[.edgeHi], location: 0.09), .init(color: p[.edgeA], location: 0.2),
+ .init(color: p[.edgeB], location: 0.5), .init(color: p[.edgeA], location: 1),
+ ], center: .center, angle: .degrees(turn - 90))
+ return ZStack {
+ // A box-shadow: outside the field only, never under it.
+ ZStack {
+ shape.fill(p[.edgeGlowA].opacity(0.55 + 0.35 * breath)).blur(radius: 8 + 3 * breath).padding(3)
+ shape.fill(p[.edgeGlowB].opacity(0.4 + 0.3 * breath)).blur(radius: 14 + 4 * breath).padding(6)
+ }
+ .mask {
+ Rectangle().padding(-40)
+ .overlay { RoundedRectangle(cornerRadius: 10, style: .continuous).padding(3).blendMode(.destinationOut) }
+ .compositingGroup()
+ }
+ shape.strokeBorder(gradient, lineWidth: 2)
+ }
+ .padding(-3)
+ .allowsHitTesting(false)
+ .accessibilityHidden(true)
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift b/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift
new file mode 100644
index 0000000..a512933
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift
@@ -0,0 +1,174 @@
+// Adapted from Equipo's ChatMarkdownView (oficina/equipo 00d09aa7,
+// native/apple/Sources/EquipoKit/Markdown/ChatMarkdownView.swift): the same
+// tree, rows and inline runs, set in Base's type and colours, with links
+// opening on the web only (Base's Assistant writes no task links).
+import SwiftUI
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+/// The Assistant's prose: the little Markdown it writes (lists, links,
+/// bold, italics), parsed off the main thread as it streams. The source is
+/// untrusted text; only absolute http(s) links are actionable.
+struct BaseMarkdownView: View {
+ private let draft: Bool
+ private let stream: MarkdownStreamRenderer
+ private let request: MarkdownRenderCache.Request
+ private let initial: MarkdownRenderCache.Result
+ @Environment(\.colorScheme) private var scheme
+ @Environment(\.openURL) private var openURL
+
+ private var nodes: [ChatMarkdownNode] {
+ initial.complete ? initial.tree : stream.visible(for: request) ?? initial.tree
+ }
+
+ init(_ text: String, draft: Bool, id: String, transcript: MarkdownTranscript) {
+ self.draft = draft
+ request = MarkdownRenderCache.Request(messageID: id, text: text, draft: draft)
+ initial = MarkdownRenderCache.shared.initial(request)
+ stream = transcript.renderer(for: id)
+ }
+
+ var body: some View {
+ let p = Palette(scheme)
+ MarkdownRows(nodes: nodes)
+ .font(BaseFont.body(15))
+ .foregroundStyle(p[.frost])
+ .tint(p[.focus])
+ .textSelection(.enabled)
+ .onAppear { stream.submit(request, needsParsing: !initial.complete) }
+ .onChange(of: request) { stream.submit(request, needsParsing: !initial.complete) }
+ .environment(\.openURL, OpenURLAction { url in
+ guard let original = MarkdownActions.originalTarget(url, in: nodes),
+ case .external(let target)? = MarkdownActions.destination(original, origin: url) else { return .discarded }
+ openURL(target)
+ return .handled
+ })
+ }
+}
+
+private struct MarkdownRows: View {
+ let nodes: [ChatMarkdownNode]
+ @Environment(\.colorScheme) private var scheme
+ var body: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ ForEach(MarkdownPresentation.rows(nodes)) { row in
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ if let marker = row.marker { Text(verbatim: marker).monospacedDigit().accessibilityHidden(true) }
+ MarkdownBlock(node: row.node)
+ }
+ .padding(.leading, CGFloat(row.indentation) * 16)
+ }
+ }
+ }
+}
+
+private struct MarkdownBlock: View {
+ let node: ChatMarkdownNode
+ var body: some View {
+ switch node.kind {
+ case "paragraph", "inlineGroup": Text(inline(node.children)).fixedSize(horizontal: false, vertical: true)
+ case "plain": Text(verbatim: node.text ?? "").fixedSize(horizontal: false, vertical: true)
+ case "paste": MarkdownPaste(node: node)
+ case "codeBlock": MarkdownCode(text: node.text ?? "", wraps: false)
+ default: EmptyView()
+ }
+ }
+
+ private func prose(_ text: String) -> String {
+ text.replacingOccurrences(of: #"[ \t\r\n\f]+"#, with: " ", options: .regularExpression)
+ }
+
+ private func inline(_ nodes: [ChatMarkdownNode]) -> AttributedString {
+ struct Work { var node: ChatMarkdownNode; var bold = false; var italic = false; var link: String? }
+ var stack = nodes.reversed().map { Work(node: $0) }
+ var result = AttributedString()
+ while let work = stack.popLast() {
+ let node = work.node
+ if !["text", "code", "break"].contains(node.kind) {
+ for child in node.children.reversed() {
+ stack.append(Work(node: child, bold: work.bold || node.kind == "strong", italic: work.italic || node.kind == "emphasis",
+ link: node.kind == "link" ? node.target : work.link))
+ }
+ continue
+ }
+ var part = AttributedString(node.kind == "break" ? "\n" : prose(node.text ?? ""))
+ if node.kind == "code" { part.font = BaseFont.body(15).monospaced() }
+ var intent: InlinePresentationIntent = []
+ if work.bold { intent.insert(.stronglyEmphasized) }
+ if work.italic { intent.insert(.emphasized) }
+ part.inlinePresentationIntent = intent
+ if let target = work.link, ChatMarkdown.allowsLink(target) {
+ part.link = MarkdownActions.linkURL(target)
+ part.underlineStyle = .single
+ }
+ if result.characters.last == " ", part.characters.first == " " {
+ part.removeSubrange(part.startIndex..<part.index(afterCharacter: part.startIndex))
+ }
+ result.append(part)
+ }
+ return result
+ }
+}
+
+private struct MarkdownCode: View {
+ let text: String
+ let wraps: Bool
+ var body: some View {
+ if wraps {
+ Text(verbatim: text).fixedSize(horizontal: false, vertical: true)
+ .frame(maxWidth: .infinity, alignment: .leading).padding(12)
+ } else {
+ ScrollView(.horizontal) {
+ Text(verbatim: text).font(BaseFont.body(14).monospaced()).fixedSize().padding(12)
+ }
+ }
+ }
+}
+
+private struct MarkdownPaste: View {
+ let node: ChatMarkdownNode
+ @State private var copied = false
+ @Environment(\.colorScheme) private var scheme
+ var body: some View {
+ let p = Palette(scheme)
+ VStack(alignment: .leading, spacing: 0) {
+ HStack {
+ if let label = node.label { Text(verbatim: label).foregroundStyle(p[.haze]) }
+ Spacer(minLength: 8)
+ Button {
+ guard let value = MarkdownActions.copyText(node) else { return }
+ #if os(macOS)
+ NSPasteboard.general.clearContents()
+ copied = NSPasteboard.general.setString(value, forType: .string)
+ #else
+ UIPasteboard.general.string = value
+ copied = true
+ #endif
+ if copied { AccessibilityNotification.Announcement(node.copied ?? "").post() }
+ } label: {
+ Label(copied ? (node.copied ?? "") : (node.copy ?? ""), systemImage: copied ? "checkmark" : "doc.on.doc")
+ }
+ .buttonStyle(.plain)
+ .foregroundStyle(p[.focus])
+ .disabled(node.copyEnabled != true)
+ }
+ .font(BaseFont.body(13, .medium, relativeTo: .footnote))
+ .padding(.horizontal, 12).padding(.vertical, 8)
+ .background(p[.chip])
+ MarkdownCode(text: node.text ?? "", wraps: node.wrap == true)
+ }
+ .background(p[.well])
+ .clipShape(.rect(cornerRadius: 10))
+ .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(p[.wellEdge], lineWidth: 1))
+ .onChange(of: node.text) { _, _ in copied = false }
+ .task(id: copied) {
+ guard copied else { return }
+ do { try await Task.sleep(for: .milliseconds(1800)); copied = false } catch {}
+ }
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel(Text(verbatim: MarkdownPresentation.pasteLabel(node)))
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift b/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift
new file mode 100644
index 0000000..b51346c
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift
@@ -0,0 +1,505 @@
+// Copied from Equipo's EquipoKit (oficina/equipo 00d09aa7,
+// native/apple/Sources/EquipoKit/Markdown/ChatMarkdown.swift). Base's changes are
+// marked "Base:"; keep the rest in step with Equipo's.
+import Foundation
+import cmark_gfm
+
+/// The rendered subset, shared by fixtures and both native transcripts.
+struct ChatMarkdownNode: Codable, Equatable, Sendable {
+ // Source anchors survive appended chunks and a fence's closing line.
+ var sourceOffset = 0
+ enum CodingKeys: String, CodingKey { case kind, text, target, label, copy, copied, wrap, copyEnabled, children }
+ static func == (lhs: Self, rhs: Self) -> Bool {
+ lhs.kind == rhs.kind && lhs.text == rhs.text && lhs.target == rhs.target && lhs.label == rhs.label && lhs.copy == rhs.copy && lhs.copied == rhs.copied && lhs.wrap == rhs.wrap && lhs.copyEnabled == rhs.copyEnabled && lhs.children == rhs.children
+ }
+ var kind: String
+ var text: String?
+ var target: String?
+ var label: String?
+ var copy: String?
+ var copied: String?
+ var wrap: Bool?
+ var copyEnabled: Bool?
+ var children: [ChatMarkdownNode] = []
+}
+
+enum ChatMarkdown {
+ static func parse(_ source: String, draft: Bool) -> [ChatMarkdownNode] {
+ let source = draft ? MarkdownDraft.steady(source) : source
+ let prepared = MarkdownInput.prepare(source)
+ return prepared.source.withCString { _ in
+ guard let parser = cmark_parser_new(CMARK_OPT_SOURCEPOS) else { return [] }
+ defer { cmark_parser_free(parser) }
+ // Observe each parser transition before EOF finalizes open fences.
+ // An explicit closing fence returns current to the code's parent;
+ // ending a surrounding list/quote does not count as closing it.
+ var closedFences = Set<UnsafeMutablePointer<cmark_node>>()
+ var input = Array(prepared.source.utf8)
+ var longFences: [UnsafeMutablePointer<cmark_node>: Int] = [:]
+ var lineStart = 0
+ for end in 0...input.count where end == input.count || input[end] == 10 {
+ if Task.isCancelled { return [] }
+ if end == input.count && lineStart == end { break }
+ let old = parser.pointee.current
+ let parent = old?.pointee.parent
+ let wasFence = old.map { $0.pointee.type == CMARK_NODE_CODE_BLOCK.rawValue && $0.pointee.as.code.fenced != 0 } ?? false
+ let length = end < input.count ? end - lineStart + 1 : end - lineStart
+ if wasFence, let old, let required = longFences[old], required > 255 {
+ let marker = old.pointee.as.code.fence_char
+ var cursor = lineStart
+ while cursor < end {
+ guard input[cursor] == marker else { cursor += 1; continue }
+ let begin = cursor
+ while cursor < end, input[cursor] == marker { cursor += 1 }
+ // cmark stores fence lengths in one byte. Keep a shorter
+ // run as content instead of letting that truncation close
+ // the block; the retained input restores its literal.
+ if cursor - begin >= 255, cursor - begin < required { input[begin] = 1 }
+ }
+ }
+ input.withUnsafeBytes { raw in
+ cmark_parser_feed(parser, raw.baseAddress!.assumingMemoryBound(to: CChar.self).advanced(by: lineStart), length)
+ }
+ if end == input.count, input.last != 13 { cmark_parser_feed(parser, "\n", 1) }
+ if wasFence, let old, parser.pointee.current == parent, old.pointee.flags & UInt16(CMARK_NODE__OPEN.rawValue) == 0 { closedFences.insert(old) }
+ if let current = parser.pointee.current, current.pointee.type == CMARK_NODE_CODE_BLOCK.rawValue, current.pointee.as.code.fenced != 0, longFences[current] == nil {
+ let marker = current.pointee.as.code.fence_char
+ let line = Array(prepared.originalLines[max(0, Int(current.pointee.start_line) - 1)].utf8)
+ if let first = line.firstIndex(of: marker) { longFences[current] = line[first...].prefix { $0 == marker }.count }
+ }
+ lineStart = end + 1
+ }
+ let consumed = MarkdownInput.Prepared(source: String(decoding: input, as: UTF8.self), original: source)
+ var openFences = Set<UnsafeMutablePointer<cmark_node>>()
+ var blockSources: [UnsafeMutablePointer<cmark_node>: [UInt8]] = [:]
+ if let root = parser.pointee.root, let iterator = cmark_iter_new(root) {
+ while cmark_iter_next(iterator) != CMARK_EVENT_DONE {
+ guard let node = cmark_iter_get_node(iterator) else { continue }
+ if blockSources[node] == nil, node.pointee.type == CMARK_NODE_PARAGRAPH.rawValue || node.pointee.type == CMARK_NODE_HEADING.rawValue {
+ let held = Array(UnsafeBufferPointer(start: node.pointee.content.ptr, count: Int(node.pointee.content.size)))
+ let raw = consumed.block(held, startLine: Int(node.pointee.start_line))
+ blockSources[node] = raw
+ let input = MarkdownInput.forCMark(raw)
+ input.withUnsafeBufferPointer { cmark_strbuf_set(&node.pointee.content, $0.baseAddress, Int32($0.count)) }
+ }
+ if node.pointee.type == CMARK_NODE_CODE_BLOCK.rawValue,
+ !closedFences.contains(node) { openFences.insert(node) }
+ }
+ cmark_iter_free(iterator)
+ }
+ guard let root = cmark_parser_finish(parser) else { return [] }
+ defer { cmark_node_free(root) }
+ var projection = MarkdownProjection(source: source, draft: draft, root: root, openFences: openFences, blockSources: blockSources, prepared: consumed)
+ return projection.tree(root)
+ }
+ }
+
+ @concurrent static func parseInBackground(_ source: String, draft: Bool) async -> [ChatMarkdownNode] {
+ assert(!Thread.isMainThread)
+ guard !Task.isCancelled else { return [] }
+ return parse(source, draft: draft)
+ }
+
+ static func allowsLink(_ destination: String) -> Bool {
+ // Base: only absolute http(s) links, as ask.js's webURL and
+ // equipo.WebURL (Equipo's MarkdownLinks also allows its own paths
+ // and mailto).
+ BaseJSON.webURL(destination) != nil
+ }
+}
+
+private struct MarkdownProjection {
+ let source: String
+ let draft: Bool
+ let bytes: [UInt8]
+ let lines: [String]
+ let starts: [Int]
+ let openFrom: Int?
+ let linkHidden: [Range<Int>]
+ let openFences: Set<UnsafeMutablePointer<cmark_node>>
+ let references: [String: String]
+ let blockSources: [UnsafeMutablePointer<cmark_node>: [UInt8]]
+ let prepared: MarkdownInput.Prepared
+ var projected: [UnsafeMutablePointer<cmark_node>: [ChatMarkdownNode]] = [:]
+ struct InlineSource {
+ let bytes: [UInt8]
+ let starts: [Int]
+ let originalStarts: [Int]
+ }
+ var inlineSources: [UnsafeMutablePointer<cmark_node>: InlineSource] = [:]
+ var inlineOwners: [UnsafeMutablePointer<cmark_node>: UnsafeMutablePointer<cmark_node>] = [:]
+ static let referencePattern = try! NSRegularExpression(pattern: #"(?m)^ {0,3}\[([^\]]+)\]:[ \t]*(<[^>]*>|\S+)"#)
+ static func normalized(_ value: String) -> String { value.split(whereSeparator: { $0.isWhitespace }).joined(separator: " ").lowercased() }
+
+
+ init(source: String, draft: Bool, root: UnsafeMutablePointer<cmark_node>, openFences: Set<UnsafeMutablePointer<cmark_node>>, blockSources: [UnsafeMutablePointer<cmark_node>: [UInt8]], prepared: MarkdownInput.Prepared) {
+ self.prepared = prepared
+ self.blockSources = blockSources
+ self.openFences = openFences
+ var refs: [String: String] = [:]
+ for match in Self.referencePattern.matches(in: source, range: NSRange(source.startIndex..., in: source)) {
+ guard let key = Range(match.range(at: 1), in: source), let value = Range(match.range(at: 2), in: source) else { continue }
+ let label = Self.normalized(String(source[key]))
+ if refs[label] == nil { refs[label] = String(source[value]) }
+ }
+ references = refs
+ self.source = source; self.draft = draft
+ let bytes = Array(source.utf8)
+ self.bytes = bytes
+ lines = source.components(separatedBy: "\n")
+ var offsets = [0]
+ for (index, byte) in bytes.enumerated() where byte == 10 { offsets.append(index + 1) }
+ starts = offsets
+ func offset(_ line: Int32, _ column: Int32) -> Int {
+ guard line > 0, Int(line) <= offsets.count else { return bytes.count }
+ return min(bytes.count, offsets[Int(line) - 1] + max(0, Int(column) - 1))
+ }
+ var last = root
+ while let child = cmark_node_last_child(last), ["document", "block_quote", "list", "item", "paragraph", "heading", "code_block", "html_block", "thematic_break"].contains(Self.kind(child)) { last = child }
+ let end = offset(cmark_node_get_end_line(last), cmark_node_get_end_column(last) + 1)
+ let breaks = bytes[end...].filter { $0 == 10 }.count
+ if draft, ["paragraph", "heading"].contains(Self.kind(last)), breaks <= 1,
+ !(Self.kind(last) == "heading" && breaks > 0) {
+ openFrom = offset(cmark_node_get_start_line(last), cmark_node_get_start_column(last))
+ } else { openFrom = nil }
+ if let from = openFrom {
+ let line = max(from, offsets.last ?? 0)
+ let tail = String(decoding: bytes[line...], as: UTF8.self)
+ let regex = try! NSRegularExpression(pattern: #"(!?\[)[^\[\]\n`]*(\](?:\([^()\x09\x0a\x0c\x0d\x20]*)?)?\z"#)
+ if let match = regex.firstMatch(in: tail, range: NSRange(tail.startIndex..., in: tail)),
+ let first = Range(match.range(at: 1), in: tail) {
+ let start = line + tail[..<first.lowerBound].utf8.count
+ if start == 0 || bytes[start - 1] != 92 {
+ linkHidden = (1...2).compactMap { group in
+ guard let range = Range(match.range(at: group), in: tail) else { return nil }
+ let start = line + tail[..<range.lowerBound].utf8.count
+ return start..<(start + tail[range].utf8.count)
+ }
+ } else { linkHidden = [] }
+ } else { linkHidden = [] }
+ } else { linkHidden = [] }
+ }
+
+ static func kind(_ node: UnsafeMutablePointer<cmark_node>) -> String { String(cString: cmark_node_get_type_string(node)) }
+ func literal(_ node: UnsafeMutablePointer<cmark_node>) -> String {
+ let value = cmark_node_get_literal(node).map(String.init(cString:)) ?? ""
+ if ["code_block", "html_block"].contains(Self.kind(node)) {
+ let skip = Self.kind(node) == "code_block" && node.pointee.as.code.fenced != 0 ? 1 : 0
+ return String(decoding: prepared.block(Array(value.utf8), startLine: Int(node.pointee.start_line) + skip), as: UTF8.self).replacingOccurrences(of: "\r", with: "\n")
+ }
+ return value
+ }
+ func offset(_ line: Int32, _ column: Int32) -> Int {
+ guard line > 0, Int(line) <= starts.count else { return bytes.count }
+ return min(bytes.count, starts[Int(line) - 1] + max(0, Int(column) - 1))
+ }
+ // Inline columns are relative to the block's normalized content, not the
+ // original continuation line. Map through that content before reading.
+ func inlineRange(_ node: UnsafeMutablePointer<cmark_node>) -> (UnsafeMutablePointer<cmark_node>, [UInt8], Range<Int>)? {
+ guard let parent = inlineOwners[node], let context = inlineSources[parent] else { return nil }
+ let raw = context.bytes, offsets = context.starts
+ let base = Int(parent.pointee.start_column - 1 + parent.pointee.internal_offset)
+ func position(_ line: Int32, _ column: Int32, end: Bool) -> Int {
+ let index = Int(line - parent.pointee.start_line)
+ guard offsets.indices.contains(index) else { return raw.count }
+ // Multiline code/HTML end columns omit the block offset in cmark.
+ let adjustment = end && node.pointee.end_line != node.pointee.start_line && ["code", "html_inline"].contains(Self.kind(node)) ? 0 : base
+ return min(raw.count, max(0, offsets[index] + Int(column) - 1 - adjustment))
+ }
+ let lo = position(node.pointee.start_line, node.pointee.start_column, end: false)
+ let hi = position(node.pointee.end_line, node.pointee.end_column + 1, end: true)
+ return (parent, raw, lo..<max(lo, hi))
+ }
+ func inlineRaw(_ node: UnsafeMutablePointer<cmark_node>) -> String {
+ guard let (_, content, span) = inlineRange(node) else { return literal(node) }
+ return String(decoding: content[span], as: UTF8.self)
+ }
+ func range(_ node: UnsafeMutablePointer<cmark_node>) -> Range<Int> {
+ if let (block, _, span) = inlineRange(node) {
+ func original(_ at: Int) -> Int {
+ guard let context = inlineSources[block] else { return bytes.count }
+ var lo = 0, hi = context.starts.count
+ while lo + 1 < hi {
+ let mid = (lo + hi) / 2
+ if context.starts[mid] <= at { lo = mid } else { hi = mid }
+ }
+ return min(bytes.count, context.originalStarts[lo] + at - context.starts[lo])
+ }
+ let lo = original(span.lowerBound)
+ return lo..<max(lo, original(span.upperBound))
+ }
+ let start = offset(cmark_node_get_start_line(node), cmark_node_get_start_column(node))
+ return start..<max(start, offset(cmark_node_get_end_line(node), cmark_node_get_end_column(node) + 1))
+ }
+ mutating func prepareInlineSources(_ root: UnsafeMutablePointer<cmark_node>) {
+ guard let iterator = cmark_iter_new(root) else { return }
+ defer { cmark_iter_free(iterator) }
+ while true {
+ let event = cmark_iter_next(iterator)
+ if event == CMARK_EVENT_DONE { break }
+ guard event == CMARK_EVENT_ENTER, let node = cmark_iter_get_node(iterator) else { continue }
+ if ["paragraph", "heading"].contains(Self.kind(node)) {
+ let content = node.pointee.content
+ let held = blockSources[node] ?? Array(UnsafeBufferPointer(start: content.ptr, count: Int(content.size)))
+ let raw = Array(held.suffix(Int(content.size)))
+ var offsets = [0]
+ for (i, b) in raw.enumerated() where b == 10 { offsets.append(i + 1) }
+ var originals: [Int] = []
+ for (line, start) in offsets.enumerated() {
+ let end = line + 1 < offsets.count ? offsets[line + 1] - 1 : raw.count
+ let index = Int(node.pointee.start_line) - 1 + line
+ guard lines.indices.contains(index) else { originals.append(bytes.count); continue }
+ let normalized = String(decoding: raw[start..<end], as: UTF8.self)
+ let original = lines[index]
+ let prefix = original.range(of: normalized, options: .backwards).map { original[..<$0.lowerBound].utf8.count } ?? 0
+ originals.append(starts[index] + prefix)
+ }
+ inlineSources[node] = InlineSource(bytes: raw, starts: offsets, originalStarts: originals)
+ } else if node.pointee.type & 0xc000 == 0xc000, let parent = cmark_node_parent(node) {
+ inlineOwners[node] = inlineSources[parent] != nil ? parent : inlineOwners[parent]
+ }
+ }
+ }
+ mutating func tree(_ root: UnsafeMutablePointer<cmark_node>) -> [ChatMarkdownNode] {
+ prepareInlineSources(root)
+ // Postorder on an explicit heap stack. Quotes can be thousands deep.
+ var stack: [(UnsafeMutablePointer<cmark_node>, Bool)] = [(root, false)]
+ while let (node, visited) = stack.popLast() {
+ if Task.isCancelled { return [] }
+ if !visited {
+ stack.append((node, true))
+ var child = cmark_node_last_child(node)
+ while let current = child { stack.append((current, false)); child = cmark_node_previous(current) }
+ } else {
+ var nodes = project(node)
+ if nodes.count == 1, !["document", "block_quote", "image"].contains(Self.kind(node)) { nodes[0].sourceOffset = range(node).lowerBound }
+ projected[node] = nodes
+ var child = cmark_node_first_child(node)
+ while let current = child { projected.removeValue(forKey: current); child = cmark_node_next(current) }
+ }
+ }
+ return projected[root] ?? []
+ }
+ func children(_ node: UnsafeMutablePointer<cmark_node>) -> [ChatMarkdownNode] {
+ var out: [ChatMarkdownNode] = []
+ var child = cmark_node_first_child(node)
+ while let current = child {
+ for next in projected[current] ?? [] {
+ if next.kind == "text", next.text == nil || next.text == "" || next.text == "\n" && ["document", "list", "item"].contains(Self.kind(node)) { continue }
+ if next.kind == "text", out.last?.kind == "text" { out[out.count - 1].text! += next.text ?? "" }
+ else { out.append(next) }
+ }
+ child = cmark_node_next(current)
+ }
+ return out.map { value in
+ var value = value
+ if value.kind == "text" { value.text = value.text?.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") }
+ return value
+ }
+ }
+ func leaf(_ kind: String, _ text: String = "") -> ChatMarkdownNode { ChatMarkdownNode(kind: kind, text: text.isEmpty ? nil : text) }
+ func project(_ node: UnsafeMutablePointer<cmark_node>) -> [ChatMarkdownNode] {
+ switch Self.kind(node) {
+ case "text":
+ var value = draftText(node)
+ if let next = cmark_node_next(node), ["linebreak", "softbreak"].contains(Self.kind(next)) { while value.last == " " || value.last == "\t" { value.removeLast() } }
+ return [leaf("text", value)]
+ case "softbreak": return [leaf("text", "\n")]
+ case "linebreak": return [leaf("break")]
+ case "code":
+ var raw = inlineRaw(node)
+ // cmark caps code-span delimiter runs at 80. The inline adapter
+ // pads longer paired delimiters without changing source columns.
+ if node.pointee.backtick_count == 80 {
+ while raw.first == "`" { raw.removeFirst() }
+ while raw.last == "`" { raw.removeLast() }
+ }
+ // Goldmark keeps internal line breaks; cmark replaces them with spaces.
+ var code = raw
+ if code.contains(where: { $0 != " " && $0 != "\n" }),
+ let first = code.first, let last = code.last,
+ (first == " " || first == "\n"), (last == " " || last == "\n") {
+ code = String(code.dropFirst().dropLast())
+ }
+ return [leaf("code", code.replacingOccurrences(of: "\r", with: "\n"))]
+ case "html_inline": return [leaf("text", inlineRaw(node))]
+ case "html_block":
+ var value = literal(node)
+ if Int(node.pointee.end_line) == lines.count, bytes.last != 10, bytes.last != 13, value.hasSuffix("\n") { value.removeLast() }
+ return [leaf("text", value)]
+ case "thematic_break": return [] // Render has no rule output.
+ case "code_block":
+ var length: Int32 = 0, indent: Int32 = 0
+ var character: CChar = 0
+ guard cmark_node_get_fenced(node, &length, &indent, &character) != 0 else { return [leaf("codeBlock", literal(node))] }
+ let opening = Array(lines[max(0, Int(node.pointee.start_line) - 1)].utf8)
+ var info: [UInt8] = []
+ var infoLength = 0
+ if let first = opening.firstIndex(of: UInt8(bitPattern: character)) {
+ var at = first
+ while at < opening.count, opening[at] == UInt8(bitPattern: character) { at += 1 }
+ infoLength = opening.count - at
+ while at < opening.count, [9, 10, 11, 12, 13, 32].contains(opening[at]) { at += 1 }
+ var end = opening.count
+ while end > at, [9, 10, 11, 12, 13, 32].contains(opening[end - 1]) { end -= 1 }
+ info = Array(opening[at..<end])
+ }
+ let candidate = Int(node.pointee.start_line) == lines.count && bytes.last != 10 && infoLength == 1 ? "" : String(decoding: info.prefix(while: { $0 != 32 }), as: UTF8.self)
+ let lang = MarkdownDraft.matches(#"^\.?[A-Za-z0-9][A-Za-z0-9_+#.-]{0,23}$"#, candidate) ? candidate : ""
+ let lower = lang.lowercased()
+ var value = literal(node)
+ if cmark_node_parent(node).map({ Self.kind($0) != "document" }) == true, bytes.last == 13, bytes.dropLast().last == 10, Int(node.pointee.end_line) >= lines.count, value.hasSuffix("\n") { value.removeLast() }
+ var box = leaf("paste", value)
+ switch lower {
+ case "prompt": box.label = BaseText.text("chat.paste.prompt")
+ case "text": box.label = BaseText.text("chat.paste.text")
+ case "bash", "sh", "zsh", "shell", "console": box.label = BaseText.text("chat.paste.command")
+ default: box.label = lang.isEmpty ? nil : lang
+ }
+ box.wrap = ["prompt", "text"].contains(lower) ? true : nil
+ box.copy = BaseText.text("chat.paste.copy")
+ box.copied = BaseText.text("chat.paste.copied")
+ box.copyEnabled = !draft || !openFences.contains(node)
+ return [box]
+ case "paragraph":
+ if let item = cmark_node_parent(node), Self.kind(item) == "item",
+ let list = cmark_node_parent(item), cmark_node_get_list_tight(list) != 0 { return children(node) }
+ return [ChatMarkdownNode(kind: "paragraph", children: children(node))]
+ case "heading": return [ChatMarkdownNode(kind: "paragraph", children: children(node))]
+ case "emph": return [ChatMarkdownNode(kind: "emphasis", children: children(node))]
+ case "strong": return [ChatMarkdownNode(kind: "strong", children: children(node))]
+ case "list": return [ChatMarkdownNode(kind: cmark_node_get_list_type(node) == CMARK_ORDERED_LIST ? "ordered" : "unordered", children: children(node))]
+ case "item": return [ChatMarkdownNode(kind: "item", children: children(node))]
+ case "link":
+ // Goldmark's AutoLink is outside Render's vocabulary.
+ if range(node).lowerBound < bytes.count, bytes[range(node).lowerBound] == 60 { return [] }
+ let target = linkTarget(node)
+ guard ChatMarkdown.allowsLink(target) else { return children(node) }
+ return [ChatMarkdownNode(kind: "link", target: target, children: children(node))]
+ default: return children(node) // Quotes/images keep only their children.
+ }
+ }
+
+ /// Render resolves HTML entities in destinations but keeps punctuation
+ /// escapes. cmark's destination has already removed those backslashes.
+ func linkTarget(_ node: UnsafeMutablePointer<cmark_node>) -> String {
+ let raw = inlineRaw(node)
+ func destination(_ tail: Substring) -> String {
+ let trimmed = tail.drop(while: { " \t\n\r\u{000B}\u{000C}".contains($0) })
+ if trimmed.first == "<", let end = trimmed.dropFirst().firstIndex(of: ">") {
+ return String(trimmed[trimmed.index(after: trimmed.startIndex)..<end])
+ }
+ return String(trimmed.prefix(while: { !" \t\n\r\u{000B}\u{000C}".contains($0) }))
+ }
+ let resolved = cmark_node_get_url(node).map(String.init(cString:)) ?? ""
+ // A title or the destination itself can contain "](". A candidate is
+ // accepted only when its parser-normalized value equals the URL cmark
+ // actually selected. Source syntax can never redirect another link.
+ var search = raw.startIndex
+ while raw.last == ")", let opener = raw.range(of: "](", range: search..<raw.endIndex) {
+ let tail = raw[opener.upperBound..<raw.index(before: raw.endIndex)]
+ let candidate = destination(tail)
+ let angled = tail.drop(while: { " \t\n\r\u{000B}\u{000C}".contains($0) }).first == "<"
+ let parserValue = MarkdownInput.destinationForParser(candidate, angled: angled)
+ if parserValue == resolved || angled && parserValue.trimmingCharacters(in: .whitespacesAndNewlines) == resolved { return MarkdownDraft.entities(candidate) }
+ search = opener.upperBound
+ }
+ // Reference definitions carry the original destination too.
+ let groups = raw.components(separatedBy: "[").dropFirst().compactMap { $0.split(separator: "]", omittingEmptySubsequences: false).first.map(String.init) }
+ let label = groups.last(where: { !$0.isEmpty }) ?? ""
+ if let target = references[Self.normalized(label)] { return MarkdownDraft.entities(destination(target[...])) }
+ return cmark_node_get_url(node).map(String.init(cString:)) ?? ""
+ }
+
+ func textValue(_ node: UnsafeMutablePointer<cmark_node>) -> String {
+ var raw = inlineRaw(node)
+ let actual = literal(node)
+ // cmark leaves the original source span on partially consumed
+ // delimiter leaves. Their surviving delimiter count is in the literal.
+ for marker: Character in ["*", "_"] {
+ if raw.first == marker, actual.first == marker {
+ let old = raw.prefix(while: { $0 == marker }).count
+ let kept = actual.prefix(while: { $0 == marker }).count
+ if old > kept { raw.removeFirst(old - kept) }
+ }
+ if raw.last == marker, actual.last == marker {
+ let old = raw.reversed().prefix(while: { $0 == marker }).count
+ let kept = actual.reversed().prefix(while: { $0 == marker }).count
+ if old > kept { raw.removeLast(old - kept) }
+ }
+ }
+ return MarkdownDraft.decodeText(raw)
+ }
+ func draftText(_ node: UnsafeMutablePointer<cmark_node>) -> String {
+ guard let from = openFrom else { return textValue(node) }
+ let segment = range(node)
+ guard segment.lowerBound >= from, !segment.isEmpty else { return textValue(node) }
+ let partiallyConsumed = literal(node).allSatisfy { $0 == "*" || $0 == "_" } && literal(node).utf8.count < inlineRaw(node).utf8.count
+ var hidden = linkHidden
+ var firstBacktick: Int?
+ var at = segment.lowerBound
+ while at < segment.upperBound {
+ let char = bytes[at]
+ // The watched fallback text is extended up to the next inline
+ // parser trigger, even if that parser ultimately finds no node.
+ var startsLinkLabel = false
+ if let firstBacktick, [33, 42, 60, 91, 93, 95, 96].contains(char) {
+ var escapes = 0, previous = at
+ while previous > 0, bytes[previous - 1] == 92 { escapes += 1; previous -= 1 }
+ if escapes % 2 == 0 {
+ hidden.append(firstBacktick..<at)
+ // A link/image opener starts its own text segment, even
+ // before its destination arrives. Its label is not part
+ // of the watched unmatched code opener.
+ if char == 91 || char == 33 && at + 1 < bytes.count && bytes[at + 1] == 91 { startsLinkLabel = true }
+ }
+ }
+ if startsLinkLabel { firstBacktick = nil }
+ guard [42, 95, 96].contains(char) else { at += 1; continue }
+ let start = at
+ while at < segment.upperBound, bytes[at] == char { at += 1 }
+ var slashes = 0, before = start
+ while before > 0, bytes[before - 1] == 92 { slashes += 1; before -= 1 }
+ if slashes % 2 == 1 { at = start + 1; continue }
+ if char == 96 {
+ // Goldmark coalesces watched fallback text through the next
+ // unmatched code opener; its draft hides that entire span.
+ firstBacktick = firstBacktick ?? start
+ hidden.append(firstBacktick!..<at)
+ continue
+ }
+ let left = String(decoding: bytes[max(0, start - 4)..<start], as: UTF8.self).unicodeScalars.last
+ let right = String(decoding: bytes[at..<min(bytes.count, at + 4)], as: UTF8.self).unicodeScalars.first
+ func space(_ c: Unicode.Scalar?) -> Bool { c.map { CharacterSet.whitespacesAndNewlines.contains($0) } ?? true }
+ func punct(_ c: Unicode.Scalar?) -> Bool { c.map { CharacterSet.punctuationCharacters.union(.symbols).contains($0) } ?? false }
+ let lf = !space(right) && (!punct(right) || space(left) || punct(left))
+ let rf = !space(left) && (!punct(left) || space(right) || punct(right))
+ let canOpen = char == 42 ? lf : lf && (!rf || punct(left))
+ let canClose = char == 42 ? rf : rf && (!lf || punct(right))
+ // Goldmark creates a delimiter even when it cannot open or
+ // close. Removing that first unmatched delimiter merges it into
+ // the watched backtick text; later text is a separate segment.
+ if let firstBacktick { hidden.append(firstBacktick..<at) }
+ // A closer that cannot open is removed during the forward
+ // delimiter pass. An adjacent surviving delimiter can then merge
+ // into that same watched text during the final reverse pass.
+ if !(canClose && !canOpen && at < bytes.count && [42, 95].contains(bytes[at])) { firstBacktick = nil }
+ if canOpen && (!canClose || at - start >= 2) || at == bytes.count && !partiallyConsumed { hidden.append(start..<at) }
+ }
+ if let firstBacktick, segment.upperBound < bytes.count,
+ [33, 42, 60, 91, 93, 95, 96].contains(bytes[segment.upperBound]) {
+ hidden.append(firstBacktick..<segment.upperBound)
+ }
+ let relevant = hidden.filter { $0.overlaps(segment) }
+ guard !relevant.isEmpty else { return textValue(node) }
+ var kept: [UInt8] = []
+ var cursor = segment.lowerBound
+ for span in relevant.sorted(by: { $0.lowerBound < $1.lowerBound }) {
+ let begin = max(segment.lowerBound, span.lowerBound)
+ if begin > cursor { kept.append(contentsOf: bytes[cursor..<begin]) }
+ cursor = max(cursor, min(segment.upperBound, span.upperBound))
+ }
+ if cursor < segment.upperBound { kept.append(contentsOf: bytes[cursor..<segment.upperBound]) }
+ return MarkdownDraft.decodeText(String(decoding: kept, as: UTF8.self))
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownActions.swift b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownActions.swift
new file mode 100644
index 0000000..bc39ddf
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownActions.swift
@@ -0,0 +1,43 @@
+// Copied from Equipo's EquipoKit (oficina/equipo 00d09aa7,
+// native/apple/Sources/EquipoKit/Markdown/MarkdownActions.swift). Base's changes are
+// marked "Base:"; keep the rest in step with Equipo's.
+import Foundation
+
+// Base: every link Base's Assistant may write is a web address; there are
+// no task links (Equipo's /tasks/ and /projects/ paths).
+enum MarkdownDestination: Equatable {
+ case external(URL)
+}
+
+enum MarkdownActions {
+ static func destination(_ target: String, origin: URL) -> MarkdownDestination? {
+ guard let url = linkURL(target) else { return nil }
+ return .external(url)
+ }
+ static func linkURL(_ target: String) -> URL? {
+ guard ChatMarkdown.allowsLink(target) else { return nil }
+ if let url = URL(string: target) { return url }
+ // Foundation rejects a few host characters Go's URL parser allows.
+ // Encode only that authority after validating the original target.
+ guard let scheme = target.range(of: "://") else { return nil }
+ let rest = target[scheme.upperBound...]
+ let end = rest.firstIndex(where: { "/?#".contains($0) }) ?? target.endIndex
+ let authority = target[scheme.upperBound..<end]
+ let safe = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:%@")
+ guard let encoded = String(authority).addingPercentEncoding(withAllowedCharacters: safe) else { return nil }
+ return URL(string: String(target[..<scheme.upperBound]) + encoded + target[end...])
+ }
+ static func originalTarget(_ url: URL, in nodes: [ChatMarkdownNode]) -> String? {
+ var stack = nodes
+ while let node = stack.popLast() {
+ if node.kind == "link", let target = node.target, linkURL(target) == url { return target }
+ stack.append(contentsOf: node.children)
+ }
+ return nil
+ }
+ static func copyText(_ node: ChatMarkdownNode) -> String? {
+ guard node.kind == "paste", node.copyEnabled == true else { return nil }
+ let text = node.text ?? ""
+ return text.hasSuffix("\n") ? String(text.dropLast()) : text
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownDraft.swift b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownDraft.swift
new file mode 100644
index 0000000..d3bda1a
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownDraft.swift
@@ -0,0 +1,79 @@
+// Copied from Equipo's EquipoKit (oficina/equipo 00d09aa7,
+// native/apple/Sources/EquipoKit/Markdown/MarkdownDraft.swift). Base's changes are
+// marked "Base:"; keep the rest in step with Equipo's.
+import Foundation
+
+/// The web's steady/open-link rules. Unmatched delimiters are removed only
+/// from text leaves in the final open paragraph, after CommonMark parsing.
+enum MarkdownDraft {
+ static func matches(_ pattern: String, _ text: String) -> Bool {
+ text.range(of: pattern, options: .regularExpression) != nil
+ }
+ static func entities(_ value: String) -> String { MarkdownEntities.link(value) }
+ static func decodeText(_ value: String) -> String {
+ let bytes = Array(value.utf8)
+ var out: [UInt8] = [], at = 0
+ while at < bytes.count {
+ if bytes[at] == 92, at + 1 < bytes.count, (33...47).contains(bytes[at+1]) || (58...64).contains(bytes[at+1]) || (91...96).contains(bytes[at+1]) || (123...126).contains(bytes[at+1]) { at += 1 }
+ out.append(bytes[at]); at += 1
+ }
+ return MarkdownEntities.text(String(decoding: out, as: UTF8.self))
+ }
+ static func steady(_ source: String) -> String {
+ // CRLF is one Swift Character, but the web splits on the LF byte.
+ let bytes = Array(source.utf8)
+ let start = bytes.lastIndex(of: 10).map { $0 + 1 } ?? 0
+ let tail = Array(bytes[start...])
+ return markerOnly(tail) || fenceLine(tail) ? String(decoding: bytes[..<start], as: UTF8.self) : source
+ }
+
+ private static func space(_ c: UInt8) -> Bool { c == 32 || c == 9 }
+ private static func suffix(_ b: [UInt8], _ start: Int) -> Bool {
+ var i = start
+ while i < b.count, space(b[i]) { i += 1 }
+ while i < b.count, [42, 95, 96].contains(b[i]) { i += 1 }
+ return i == b.count
+ }
+ // Each alternative is scanned once. No backtracking through whitespace.
+ static func markerOnly(_ b: [UInt8]) -> Bool {
+ var i = 0
+ while i < b.count, space(b[i]) { i += 1 }
+ if suffix(b, i) { return true }
+ guard i < b.count else { return true }
+ if [45, 43, 42, 62].contains(b[i]), suffix(b, i + 1) { return true }
+ var j = i
+ while j < b.count, (48...57).contains(b[j]), j - i < 9 { j += 1 }
+ if j > i {
+ if j < b.count, [46, 41].contains(b[j]) { j += 1 }
+ if suffix(b, j) { return true }
+ }
+ j = i
+ while j < b.count, b[j] == 35, j - i < 6 { j += 1 }
+ if j > i, suffix(b, j) { return true }
+ j = i
+ while j < b.count, [96, 126].contains(b[j]) { j += 1 }
+ if j > i, suffix(b, j) { return true }
+ j = i
+ while j < b.count, [45, 61, 95, 42, 32, 9].contains(b[j]) { j += 1 }
+ return j > i && suffix(b, j)
+ }
+ static func fenceLine(_ b: [UInt8]) -> Bool {
+ var i = 0
+ while i < b.count, space(b[i]) || b[i] == 62 { i += 1 }
+ func fence(_ j: Int) -> Bool {
+ j + 2 < b.count && (b[j] == 96 || b[j] == 126) && b[j+1] == b[j] && b[j+2] == b[j]
+ }
+ if fence(i) { return true }
+ guard i < b.count else { return false }
+ if [45, 43, 42].contains(b[i]) { i += 1 }
+ else {
+ let start = i
+ while i < b.count, (48...57).contains(b[i]), i - start < 9 { i += 1 }
+ guard i > start, i < b.count, [46, 41].contains(b[i]) else { return false }
+ i += 1
+ }
+ guard i < b.count, space(b[i]) else { return false }
+ while i < b.count, space(b[i]) { i += 1 }
+ return fence(i)
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownEntities.swift b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownEntities.swift
new file mode 100644
index 0000000..8c66fee
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownEntities.swift
@@ -0,0 +1,78 @@
+// Copied from Equipo's EquipoKit (oficina/equipo 00d09aa7,
+// native/apple/Sources/EquipoKit/Markdown/MarkdownEntities.swift). Base's changes are
+// marked "Base:"; keep the rest in step with Equipo's.
+import Foundation
+import cmark_gfm
+
+/// The web has distinct text and destination decoders. Text uses Goldmark's
+/// numeric pass followed by its name pass; destinations decode proper HTML
+/// entities once. Keeping these separate preserves nested escapes and queries.
+enum MarkdownEntities {
+ private enum Mode { case link, numericText, namedText }
+ static func link(_ value: String) -> String { decode(value, mode: .link) }
+ static func text(_ value: String) -> String {
+ decode(decode(value, mode: .numericText), mode: .namedText)
+ }
+ private static func alphaNumeric(_ b: UInt8) -> Bool { (48...57).contains(b) || (65...90).contains(b) || (97...122).contains(b) }
+ private static func decode(_ value: String, mode: Mode) -> String {
+ let bytes = Array(value.utf8)
+ var out: [UInt8] = [], at = 0
+ while at < bytes.count {
+ guard bytes[at] == 38 else { out.append(bytes[at]); at += 1; continue }
+ let begin = at
+ var end = at + 1
+ let numeric = end < bytes.count && bytes[end] == 35
+ if numeric { end += 1 }
+ while end < bytes.count, alphaNumeric(bytes[end]) { end += 1 }
+ guard end < bytes.count, bytes[end] == 59, end > at + (numeric ? 2 : 1) else {
+ out.append(bytes[at]); at += 1; continue
+ }
+ let entity = String(decoding: bytes[begin...end], as: UTF8.self)
+ var replacement: String?
+ if numeric, mode != .namedText {
+ var digits = Array(bytes[(begin + 2)..<end])
+ let hex = digits.first == 120 || digits.first == 88
+ if hex { digits.removeFirst() }
+ if !digits.isEmpty, digits.allSatisfy({ hex ? (48...57).contains($0) || (65...70).contains($0) || (97...102).contains($0) : (48...57).contains($0) }) {
+ replacement = number(digits, hex: hex, text: mode == .numericText)
+ }
+ } else if !numeric, mode != .numericText {
+ var buffer = cmark_strbuf()
+ cmark_strbuf_init(cmark_get_default_mem_allocator(), &buffer, 0)
+ let raw = Array(entity.utf8)
+ raw.withUnsafeBufferPointer { houdini_unescape_html_f(&buffer, $0.baseAddress, Int32($0.count)) }
+ replacement = String(decoding: UnsafeBufferPointer(start: buffer.ptr, count: Int(buffer.size)), as: UTF8.self)
+ cmark_strbuf_free(&buffer)
+ }
+ out.append(contentsOf: (replacement ?? entity).utf8)
+ at = end + 1
+ }
+ return String(decoding: out, as: UTF8.self)
+ }
+ private static func number(_ digits: [UInt8], hex: Bool, text: Bool) -> String? {
+ if text, !hex, digits.count >= 8 { return nil }
+ // Goldmark's decimal text pass uses ParseUint(base: 0), so a leading
+ // zero selects octal. Its hexadecimal pass accepts any digit count.
+ let radix: UInt32 = hex ? 16 : text && digits.first == 48 ? 8 : 10
+ var value: UInt32 = 0
+ for byte in digits {
+ let digit = UInt32(byte <= 57 ? byte - 48 : (byte | 32) - 87)
+ if text {
+ if digit >= radix { value = 0; break }
+ let multiplied = value.multipliedReportingOverflow(by: radix)
+ let added = multiplied.partialValue.addingReportingOverflow(digit)
+ if multiplied.overflow || added.overflow { value = .max; break }
+ value = added.partialValue
+ } else {
+ // html.UnescapeString accumulates a signed 32-bit rune.
+ value = value &* radix &+ digit
+ }
+ }
+ if !text, (0x80...0x9f).contains(value) {
+ let windows: [UInt32] = [0x20ac,0x81,0x201a,0x192,0x201e,0x2026,0x2020,0x2021,0x2c6,0x2030,0x160,0x2039,0x152,0x8d,0x17d,0x8f,0x90,0x2018,0x2019,0x201c,0x201d,0x2022,0x2013,0x2014,0x2dc,0x2122,0x161,0x203a,0x153,0x9d,0x17e,0x178]
+ value = windows[Int(value - 0x80)]
+ }
+ guard value != 0, let scalar = Unicode.Scalar(value) else { return "\u{fffd}" }
+ return String(scalar)
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownInput.swift b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownInput.swift
new file mode 100644
index 0000000..2c67f34
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownInput.swift
@@ -0,0 +1,159 @@
+// Copied from Equipo's EquipoKit (oficina/equipo 00d09aa7,
+// native/apple/Sources/EquipoKit/Markdown/MarkdownInput.swift). Base's changes are
+// marked "Base:"; keep the rest in step with Equipo's.
+import Foundation
+import cmark_gfm
+
+/// Goldmark's delimiter classification includes Unicode symbols and NEL.
+/// Adapt only the inline parser's private block buffer, preserving byte widths.
+/// All projected text and targets come from the retained original block buffer.
+enum MarkdownInput {
+ struct Prepared {
+ let source: String
+ let original: String
+ let preparedLines: [String]
+ let originalLines: [String]
+ init(source: String, original: String) {
+ self.source = source; self.original = original
+ preparedLines = source.components(separatedBy: "\n")
+ originalLines = original.components(separatedBy: "\n")
+ }
+ func block(_ bytes: [UInt8], startLine: Int) -> [UInt8] {
+ var result: [UInt8] = []
+ var line = max(0, startLine - 1)
+ for part in bytes.split(separator: 10, omittingEmptySubsequences: false).dropLast(bytes.last == 10 ? 1 : 0) {
+ // Block content has one entry for each physical LF line,
+ // including empty lines. Never search into a later block.
+ if line < preparedLines.count {
+ let candidate = preparedLines[line]
+ var suffix = part[...]
+ var restored: [UInt8]?
+ while !suffix.isEmpty {
+ let wanted = String(decoding: suffix, as: UTF8.self)
+ if let range = candidate.range(of: wanted, options: .backwards) {
+ let offset = candidate[..<range.lowerBound].utf8.count
+ restored = Array(part.prefix(part.count - suffix.count)) + Array(originalLines[line].utf8.dropFirst(offset).prefix(suffix.count))
+ break
+ }
+ // cmark can expand the remainder of an indentation tab
+ // into spaces. Those generated spaces precede the
+ // verbatim suffix, whose byte mapping is unchanged.
+ guard suffix.first == 32 else { break }
+ suffix = suffix.dropFirst()
+ }
+ result += restored ?? Array(part)
+ } else { result += part }
+ line += 1
+ result.append(10)
+ }
+ if bytes.last != 10, !result.isEmpty { result.removeLast() }
+ return result
+ }
+ }
+ static func prepare(_ source: String) -> Prepared {
+ var bytes = Array(source.utf8)
+ // Goldmark splits lines on LF and treats preceding CRs as whitespace.
+ // cmark also splits lone CRs; preserve widths while preventing an extra
+ // CR before CRLF from inventing a blank line or a loose list.
+ for i in bytes.indices where bytes[i] == 13 {
+ if i + 1 < bytes.count, bytes[i + 1] != 10 { bytes[i] = 32 }
+ }
+ // The reference-definition block parser runs before the inline phase.
+ // Adapt angle destinations here too; the retained block restores bytes.
+ if let placeholder = (Array(UInt8(1)...UInt8(8)) + [127]).first(where: { !bytes.contains($0) }) {
+ var i = 0
+ while i + 2 < bytes.count {
+ if bytes[i] == 93, bytes[i+1] == 40 || bytes[i+1] == 58 {
+ var j = i + 2
+ while j < bytes.count, [32,9,10,13].contains(bytes[j]) { j += 1 }
+ if j < bytes.count, bytes[j] == 60 {
+ j += 1
+ while j < bytes.count, bytes[j] != 62, bytes[j] != 10 {
+ if bytes[j] == 60 { bytes[j] = placeholder }
+ j += 1
+ }
+ }
+ }
+ i += 1
+ }
+ }
+ return Prepared(source: String(decoding: bytes, as: UTF8.self), original: source)
+ }
+
+ static func destinationForParser(_ value: String, angled: Bool) -> String {
+ var bytes = forCMark(Array(value.utf8))
+ if angled { bytes = bytes.map { $0 == 60 ? 1 : $0 } }
+ var buffer = cmark_strbuf()
+ cmark_strbuf_init(cmark_get_default_mem_allocator(), &buffer, 0)
+ defer { cmark_strbuf_free(&buffer) }
+ bytes.withUnsafeBufferPointer { houdini_unescape_html_f(&buffer, $0.baseAddress, Int32($0.count)) }
+ cmark_strbuf_unescape(&buffer)
+ return String(decoding: UnsafeBufferPointer(start: buffer.ptr, count: Int(buffer.size)), as: UTF8.self)
+ }
+
+ static func forCMark(_ bytes: [UInt8]) -> [UInt8] {
+ var out: [UInt8] = []
+ for scalar in String(decoding: bytes, as: UTF8.self).unicodeScalars {
+ let replacement: String
+ if scalar.value == 13 { replacement = " " }
+ else if scalar.value == 0x85 { replacement = "\u{a0}" }
+ else if scalar.value == 0x2028 || scalar.value == 0x2029 { replacement = "\u{2000}" }
+ else if scalar.value == 11 { replacement = "\u{000C}" }
+ else if scalar.value > 127, CharacterSet.punctuationCharacters.union(.symbols).contains(scalar), cmark_utf8proc_is_punctuation(Int32(scalar.value)) == 0 {
+ switch scalar.utf8.count {
+ case 2: replacement = "¡"
+ case 3: replacement = "‼"
+ default: replacement = "\u{10100}"
+ }
+ } else { replacement = String(scalar) }
+ out.append(contentsOf: replacement.utf8)
+ }
+ // Goldmark allows a '<' inside an angle destination. cmark rejects it.
+ // A same-width placeholder lets cmark recognize the link structure;
+ // the original destination is retained and validated before linking.
+ var at = 0
+ while at + 2 < out.count {
+ if out[at] == 93, out[at + 1] == 40 || out[at + 1] == 58 {
+ var i = at + 2
+ while i < out.count, [32, 9, 10, 13].contains(out[i]) { i += 1 }
+ if i < out.count, out[i] == 60 {
+ i += 1
+ while i < out.count, out[i] != 62, out[i] != 10 {
+ if out[i] == 60 { out[i] = 1 }
+ i += 1
+ }
+ }
+ }
+ at += 1
+ }
+ // cmark's inline backtick cache has 80 slots. Preserve source widths
+ // while presenting longer matching runs as an 80-tick delimiter.
+ var runs: [(start: Int, end: Int)] = []
+ var cursor = 0
+ while cursor < out.count {
+ guard out[cursor] == 96 else { cursor += 1; continue }
+ let start = cursor
+ while cursor < out.count, out[cursor] == 96 { cursor += 1 }
+ runs.append((start, cursor))
+ }
+ var next: [Int: Int] = [:], matching: [Int: Int] = [:]
+ for index in runs.indices.reversed() {
+ let length = runs[index].end - runs[index].start
+ matching[index] = next[length]
+ next[length] = index
+ }
+ var index = 0
+ while index < runs.count {
+ let run = runs[index]
+ var before = run.start
+ while before > 0, out[before - 1] == 92 { before -= 1 }
+ guard (run.start - before) % 2 == 0, let close = matching[index] else { index += 1; continue }
+ if run.end - run.start > 80 {
+ for at in (run.start + 80)..<run.end { out[at] = 1 }
+ for at in runs[close].start..<(runs[close].end - 80) { out[at] = 1 }
+ }
+ index = close + 1
+ }
+ return out
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownPresentation.swift b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownPresentation.swift
new file mode 100644
index 0000000..98f51e3
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownPresentation.swift
@@ -0,0 +1,47 @@
+// Copied from Equipo's EquipoKit (oficina/equipo 00d09aa7,
+// native/apple/Sources/EquipoKit/Markdown/MarkdownPresentation.swift). Base's changes are
+// marked "Base:"; keep the rest in step with Equipo's.
+import Foundation
+
+/// A flat list of layout rows. Depth changes indentation, never view nesting.
+/// Indentation stops at four levels so deeply nested replies remain readable
+/// at phone width; every item and all of its content are still present.
+enum MarkdownPresentation {
+ static func pasteLabel(_ node: ChatMarkdownNode) -> String { node.label ?? BaseText.text("chat.paste.text") }
+ struct Row: Identifiable {
+ var node: ChatMarkdownNode
+ var indentation: Int
+ var marker: String?
+ var id: Int { node.sourceOffset }
+ }
+ static func groups(_ nodes: [ChatMarkdownNode]) -> [ChatMarkdownNode] {
+ var out: [ChatMarkdownNode] = []
+ for node in nodes {
+ if ["text", "emphasis", "strong", "link", "code", "break"].contains(node.kind) {
+ if out.last?.kind == "inlineGroup" { out[out.count - 1].children.append(node) }
+ else { out.append(ChatMarkdownNode(sourceOffset: node.sourceOffset, kind: "inlineGroup", children: [node])) }
+ } else { out.append(node) }
+ }
+ return out
+ }
+ static func rows(_ nodes: [ChatMarkdownNode]) -> [Row] {
+ var stack = groups(nodes).reversed().map { Row(node: $0, indentation: 0, marker: nil) }
+ var out: [Row] = []
+ while let row = stack.popLast() {
+ if ["unordered", "ordered"].contains(row.node.kind) {
+ for (index, item) in row.node.children.enumerated().reversed() {
+ let children = groups(item.children)
+ for (offset, child) in children.enumerated().reversed() {
+ stack.append(Row(node: child, indentation: row.indentation + 1,
+ marker: offset == 0 ? (row.node.kind == "ordered" ? "\(index + 1)." : "•") : nil))
+ }
+ }
+ } else {
+ var visible = row
+ visible.indentation = min(4, max(0, row.indentation - 1))
+ out.append(visible)
+ }
+ }
+ return out
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownRenderCache.swift b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownRenderCache.swift
new file mode 100644
index 0000000..030bd54
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownRenderCache.swift
@@ -0,0 +1,46 @@
+// Copied from Equipo's EquipoKit (oficina/equipo 00d09aa7,
+// native/apple/Sources/EquipoKit/Markdown/MarkdownRenderCache.swift). Base's changes are
+// marked "Base:"; keep the rest in step with Equipo's.
+import Foundation
+
+/// A bounded cache of message revisions, shared across transcript view lifetimes.
+/// The source and draft flag are the revision: completion must settle draft rules
+/// even when it does not append any bytes.
+@MainActor final class MarkdownRenderCache {
+ struct Request: Hashable {
+ let messageID: String
+ let text: String
+ let draft: Bool
+ }
+ struct Result {
+ let tree: [ChatMarkdownNode]
+ let complete: Bool
+ }
+ static let shared = MarkdownRenderCache()
+ private var entries: [Request: [ChatMarkdownNode]] = [:]
+ private var order: [Request] = []
+ private let parse: (String, Bool) -> [ChatMarkdownNode]
+ init(parse: @escaping (String, Bool) -> [ChatMarkdownNode] = { ChatMarkdown.parse($0, draft: $1) }) {
+ self.parse = parse
+ }
+ func initial(_ request: Request) -> Result {
+ if let tree = entries[request] { return Result(tree: tree, complete: true) }
+ if request.text.utf8.count <= 16_384 {
+ let tree = parse(request.text, request.draft)
+ store(tree, for: request)
+ return Result(tree: tree, complete: true)
+ }
+ // Large inputs never start at zero height. During streaming retain the
+ // previous revision; the first revision shows all its plain text.
+ let previous = order.last { $0.messageID == request.messageID }
+ let held = previous.flatMap { entries[$0] }
+ let fallback = held.flatMap { $0.isEmpty ? nil : $0 } ?? [ChatMarkdownNode(kind: "plain", text: request.text)]
+ return Result(tree: fallback, complete: false)
+ }
+ func store(_ tree: [ChatMarkdownNode], for request: Request) {
+ entries[request] = tree
+ order.removeAll { $0 == request }
+ order.append(request)
+ while order.count > 256 { entries[order.removeFirst()] = nil }
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownStreamRenderer.swift b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownStreamRenderer.swift
new file mode 100644
index 0000000..c600061
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownStreamRenderer.swift
@@ -0,0 +1,65 @@
+// Copied from Equipo's EquipoKit (oficina/equipo 00d09aa7,
+// native/apple/Sources/EquipoKit/Markdown/MarkdownStreamRenderer.swift). Base's changes are
+// marked "Base:"; keep the rest in step with Equipo's.
+import Foundation
+import Observation
+
+/// One parser per message. New deltas replace the pending request, never
+/// the in-flight parse; each completed prefix can become visible immediately.
+@MainActor @Observable final class MarkdownStreamRenderer {
+ typealias Request = MarkdownRenderCache.Request
+ struct Publication {
+ let request: Request
+ let tree: [ChatMarkdownNode]
+ }
+ private(set) var publication: Publication?
+ @ObservationIgnored private var pending: Request?
+ @ObservationIgnored private var worker: Task<Void, Never>?
+ @ObservationIgnored private var generation = 0
+ @ObservationIgnored private let cache: MarkdownRenderCache
+ @ObservationIgnored private let parse: (Request) async -> [ChatMarkdownNode]
+
+ init(cache: MarkdownRenderCache = .shared, parse: @escaping (Request) async -> [ChatMarkdownNode] = {
+ await ChatMarkdown.parseInBackground($0.text, draft: $0.draft)
+ }) {
+ self.cache = cache
+ self.parse = parse
+ }
+
+ func visible(for request: Request) -> [ChatMarkdownNode]? {
+ guard let publication, publication.request.messageID == request.messageID,
+ request.text.hasPrefix(publication.request.text) else { return nil }
+ return publication.tree
+ }
+
+ func submit(_ request: Request, needsParsing: Bool = true) {
+ guard needsParsing else { stop(); return }
+ if pending == request || publication?.request == request { return }
+ if let previous = pending ?? publication?.request,
+ previous.messageID != request.messageID || !request.text.hasPrefix(previous.text) {
+ stop()
+ }
+ pending = request
+ guard worker == nil else { return }
+ let epoch = generation
+ worker = Task { [weak self] in
+ guard let self else { return }
+ while let request = self.pending {
+ let tree = await self.parse(request)
+ guard !Task.isCancelled, self.generation == epoch else { return }
+ self.cache.store(tree, for: request)
+ self.publication = Publication(request: request, tree: tree)
+ if self.pending == request { self.pending = nil }
+ }
+ self.worker = nil
+ }
+ }
+
+ func stop() {
+ generation += 1
+ worker?.cancel()
+ worker = nil
+ pending = nil
+ publication = nil
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownTranscript.swift b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownTranscript.swift
new file mode 100644
index 0000000..60abd27
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownTranscript.swift
@@ -0,0 +1,33 @@
+// Copied from Equipo's EquipoKit (oficina/equipo 00d09aa7,
+// native/apple/Sources/EquipoKit/Markdown/MarkdownTranscript.swift). Base's changes are
+// marked "Base:"; keep the rest in step with Equipo's.
+import Foundation
+
+/// Parsing belongs to messages in a signed-in conversation, not to their
+/// temporary SwiftUI hosts. Scrolling or re-hosting cannot end a reply's work.
+@MainActor public final class MarkdownTranscript {
+ private var renderers: [String: MarkdownStreamRenderer] = [:]
+ private let makeRenderer: () -> MarkdownStreamRenderer
+ public init() { makeRenderer = { MarkdownStreamRenderer() } }
+ init(makeRenderer: @escaping () -> MarkdownStreamRenderer) { self.makeRenderer = makeRenderer }
+
+ func renderer(for messageID: String) -> MarkdownStreamRenderer {
+ if let renderer = renderers[messageID] { return renderer }
+ let renderer = makeRenderer()
+ renderers[messageID] = renderer
+ return renderer
+ }
+
+ public func retainMessages(_ ids: Set<String>, origin: URL) {
+ let keys = Set(ids.map { origin.absoluteString + "/" + $0 })
+ for key in Array(renderers.keys) where !keys.contains(key) {
+ renderers.removeValue(forKey: key)?.stop()
+ }
+ }
+
+ public func removeAll() {
+ for renderer in renderers.values { renderer.stop() }
+ renderers.removeAll()
+ }
+ isolated deinit { for renderer in renderers.values { renderer.stop() } }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Pill.swift b/native/apple/Sources/BaseKit/Ask/Pill.swift
new file mode 100644
index 0000000..57176d6
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Pill.swift
@@ -0,0 +1,236 @@
+import SwiftUI
+
+/// "Started {when}" (ask.js `startedText`, the web's approved form): how
+/// long ago in minutes or hours, then from a day on the day in Base's time
+/// zone ("Started on 12 November").
+public enum StartedText {
+ public static func text(_ at: Date, now: Date, timeZone: TimeZone?) -> String {
+ let minutes = Int(floor(now.timeIntervalSince(at) / 60)), hours = minutes / 60
+ let when: String
+ if minutes < 1 { when = BaseText.text("ask.when.now") }
+ else if minutes == 1 { when = BaseText.text("ask.when.minute") }
+ else if minutes < 60 { when = BaseText.format("ask.when.minutes", ["n": String(minutes)]) }
+ else if hours == 1 { when = BaseText.text("ask.when.hour") }
+ else if hours < 24 { when = BaseText.format("ask.when.hours", ["n": String(hours)]) }
+ else {
+ var style = Date.FormatStyle(locale: Locale(identifier: "en_GB")).day().month(.wide)
+ style.timeZone = timeZone ?? .current
+ when = BaseText.format("ask.when.day", ["day": at.formatted(style)])
+ }
+ return BaseText.format("native.job.started", ["when": when])
+ }
+}
+
+/// A job, a pill (ask.js `addJob`, chat.html `ask-job`): its state's mark,
+/// the title and its status on one line, the state's colour washed in from
+/// the left, and once there is something to see (ready, done) the link to
+/// it. Pressing it opens the job's view: a popover on the Mac, a sheet on
+/// the iPhone. The cards waiting on the person hang under it.
+struct JobPill: View {
+ let job: AskModel.Job
+ let busy: Set<String>
+ let timeZone: TimeZone?
+ let answer: (AskCard, AskCard.Option) -> Void
+ @State private var viewing = false
+ @Environment(\.colorScheme) private var scheme
+ @Environment(\.openURL) private var openURL
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ pill
+ ForEach(job.open) { card in
+ CardView(card: card, busy: busy.contains(card.id), hanging: true) { answer(card, $0) }
+ .padding(.leading, 22)
+ .background(alignment: .topLeading) { ThreadLine(color: Palette(scheme)[.pillEdge]) }
+ }
+ }
+ }
+
+ private var pill: some View {
+ let p = Palette(scheme)
+ let st = StateMark.color(job.state, p)
+ let label = BaseText.format("ask.pill_a11y", ["title": job.card.question, "stage": job.card.result])
+ return HStack(spacing: 0) {
+ Button { viewing = true } label: {
+ HStack(spacing: 8) {
+ StateMark(job.state)
+ Text(verbatim: job.card.question)
+ .font(BaseFont.body(13.5, .semibold, relativeTo: .subheadline))
+ .lineLimit(1).truncationMode(.tail)
+ .frame(minWidth: 40, alignment: .leading)
+ .layoutPriority(0)
+ if !job.card.result.isEmpty {
+ Text(verbatim: "· " + job.card.result)
+ .font(BaseFont.body(13, relativeTo: .subheadline)).foregroundStyle(p[.haze])
+ .lineLimit(1)
+ .layoutPriority(1)
+ }
+ }
+ .padding(.leading, 8).padding(.trailing, 14)
+ .frame(minHeight: 44)
+ .contentShape(Capsule())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(Text(verbatim: label))
+ .accessibilityAddTraits(.isButton)
+ .modifier(JobViewPresentation(isPresented: $viewing, job: job, timeZone: timeZone))
+ if let go = job.card.go, let url = go.url {
+ Rectangle().fill(p[.pillEdge]).frame(width: 1)
+ Button { openURL(url) } label: {
+ Text(verbatim: go.label)
+ .font(BaseFont.body(13.5, .semibold, relativeTo: .subheadline)).underline()
+ .foregroundStyle(p[.focus])
+ .padding(.leading, 10).padding(.trailing, 14)
+ .frame(minHeight: 44)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityAddTraits(.isLink)
+ }
+ }
+ .foregroundStyle(p[.frost])
+ .fixedSize(horizontal: false, vertical: true)
+ .background {
+ ZStack {
+ Capsule().fill(p[.pill])
+ Capsule().fill(LinearGradient(stops: [.init(color: st.opacity(p.stateWash), location: 0), .init(color: st.opacity(0), location: 0.7)],
+ startPoint: .leading, endPoint: .trailing))
+ }
+ .shadow(color: p[.pillLift].opacity(0.6), radius: 9, y: 8)
+ }
+ .overlay {
+ ZStack {
+ Capsule().strokeBorder(p[.pillEdge], lineWidth: 1)
+ TopShine(radius: 22, color: p[.pillShine])
+ }
+ .allowsHitTesting(false)
+ }
+ }
+}
+
+/// The line from a pill down to a card that hangs under it: left -10,
+/// from 6 above the card to its middle, turning in with a 10 pt corner.
+struct ThreadLine: View {
+ let color: Color
+ var body: some View {
+ GeometryReader { geo in
+ Path { path in
+ let x: CGFloat = 12, bottom = geo.size.height / 2
+ path.move(to: CGPoint(x: x, y: -6))
+ path.addLine(to: CGPoint(x: x, y: bottom - 10))
+ path.addQuadCurve(to: CGPoint(x: x + 10, y: bottom), control: CGPoint(x: x, y: bottom))
+ }
+ .stroke(color, lineWidth: 2)
+ }
+ .frame(width: 22)
+ .accessibilityHidden(true)
+ }
+}
+
+/// The job view: a popover beside the pill on the Mac, a sheet from the
+/// foot of the screen on the iPhone.
+struct JobViewPresentation: ViewModifier {
+ @Binding var isPresented: Bool
+ let job: AskModel.Job
+ let timeZone: TimeZone?
+ func body(content: Content) -> some View {
+ #if os(macOS)
+ content.popover(isPresented: $isPresented, arrowEdge: .top) {
+ JobView(job: job, timeZone: timeZone, close: { isPresented = false }).frame(width: 320)
+ }
+ #else
+ content.sheet(isPresented: $isPresented) {
+ JobView(job: job, timeZone: timeZone, close: { isPresented = false })
+ .presentationDetents([.medium, .large])
+ .presentationDragIndicator(.visible)
+ }
+ #endif
+ }
+}
+
+/// What the job view shows (chat.html `ask-jobview`): the title, linked to
+/// the job's own page in Equipo; the status; one sentence more; the cards
+/// that have ended, each its question and how it ended; when it started;
+/// and the link to the work once there is something to see. The jobs
+/// design (11-20) adds its decisions here later.
+public struct JobView: View {
+ let job: AskModel.Job
+ let timeZone: TimeZone?
+ let close: () -> Void
+ var now: Date = .now
+ @Environment(\.colorScheme) private var scheme
+ @Environment(\.openURL) private var openURL
+
+ public init(job: AskModel.Job, timeZone: TimeZone?, close: @escaping () -> Void, now: Date = .now) {
+ self.job = job; self.timeZone = timeZone; self.close = close; self.now = now
+ }
+
+ public var body: some View {
+ let p = Palette(scheme)
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 10) {
+ StateMark(job.state, size: 26)
+ title(p)
+ Spacer(minLength: 0)
+ Button(action: close) {
+ Icon(.close).frame(width: 20, height: 20).frame(width: 44, height: 44).contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(Text(BaseText.text("ask.close")))
+ }
+ VStack(alignment: .leading, spacing: 2) {
+ if !job.card.result.isEmpty { Text(verbatim: job.card.result).font(BaseFont.body(14, .medium)) }
+ if !job.card.detail.isEmpty { Text(verbatim: job.card.detail).font(BaseFont.body(14)).foregroundStyle(p[.haze]) }
+ if !job.ended.isEmpty {
+ VStack(alignment: .leading, spacing: 6) {
+ ForEach(job.ended) { card in
+ VStack(alignment: .leading, spacing: 0) {
+ Text(verbatim: card.question).font(BaseFont.body(14))
+ Text(verbatim: card.result).font(BaseFont.body(13, relativeTo: .footnote)).foregroundStyle(p[.haze])
+ }
+ }
+ }
+ .padding(.top, 8)
+ .overlay(alignment: .top) { Rectangle().fill(p[.rule]).frame(height: 1) }
+ .padding(.top, 10)
+ }
+ if let started = job.card.startedAt {
+ Text(verbatim: StartedText.text(started, now: now, timeZone: timeZone))
+ .font(BaseFont.body(13, relativeTo: .footnote)).foregroundStyle(p[.haze])
+ .padding(.top, 8)
+ }
+ if let go = job.card.go, let url = go.url {
+ Button { openURL(url) } label: { Text(verbatim: go.label) }
+ .buttonStyle(BaseButtonStyle(.primary))
+ .padding(.top, 14)
+ }
+ }
+ .padding(.leading, 36).padding(.trailing, 10)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .foregroundStyle(p[.frost])
+ .padding(.top, 10).padding(.trailing, 10).padding(.bottom, 12).padding(.leading, 16)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(p[.menuBase])
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel(Text(verbatim: job.card.question))
+ }
+
+ @ViewBuilder private func title(_ p: Palette) -> some View {
+ let text = Text(verbatim: job.card.question).font(BaseFont.heading(16, .semibold, relativeTo: .headline))
+ if let page = job.card.equipoLink, let url = page.url {
+ Button { openURL(url) } label: {
+ HStack(spacing: 6) {
+ text.multilineTextAlignment(.leading)
+ Icon(.arrowOut, weight: 2.2).foregroundStyle(p[.haze]).frame(width: 13, height: 13)
+ }
+ .frame(minHeight: 44)
+ }
+ .buttonStyle(.plain)
+ .help(Text(verbatim: page.label))
+ .accessibilityAddTraits(.isLink)
+ } else {
+ text.padding(.vertical, 11)
+ }
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Thread.swift b/native/apple/Sources/BaseKit/Ask/Thread.swift
new file mode 100644
index 0000000..2083a5e
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Thread.swift
@@ -0,0 +1,224 @@
+import SwiftUI
+
+/// How wide the thread's bubbles may grow: 86% of the thread on the Mac
+/// and in the menu-bar panel, 92% on the iPhone (app.css `.msg`).
+public enum AskLayout: Sendable { case window, panel, phone
+ var bubbleShare: CGFloat { self == .phone ? 0.92 : 0.86 }
+ var padding: EdgeInsets {
+ switch self {
+ case .window: EdgeInsets(top: 18, leading: 24, bottom: 18, trailing: 24)
+ case .panel, .phone: EdgeInsets(top: 14, leading: 12, bottom: 8, trailing: 12)
+ }
+ }
+}
+
+/// The conversation (chat.html `.thread`): its lines, pills and cards from
+/// AskModel, newest at the foot. It follows the newest line while the
+/// person is at (or within 80 pt of) the foot; scrolled up to read, it
+/// stays put and Jump to latest appears when something new arrives.
+struct AskThread: View {
+ @Bindable var model: AskModel
+ let layout: AskLayout
+ let timeZone: TimeZone?
+ @State private var transcript = MarkdownTranscript()
+ @State private var position = ScrollPosition(edge: .bottom)
+ @State private var pinned = true
+ @State private var unseen = false
+ @State private var width: CGFloat = 600
+ @Environment(\.colorScheme) private var scheme
+
+ var body: some View {
+ let p = Palette(scheme)
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 10) {
+ ForEach(model.entries) { entry in
+ row(entry)
+ }
+ }
+ .padding(layout.padding)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .scrollPosition($position)
+ .defaultScrollAnchor(.bottom)
+ .defaultScrollAnchor(.bottom, for: .sizeChanges)
+ .onScrollGeometryChange(for: Bool.self) { geo in
+ geo.contentSize.height - geo.visibleRect.maxY < 80
+ } action: { _, atFoot in
+ pinned = atFoot
+ if atFoot { unseen = false }
+ }
+ .onChange(of: model.entries) {
+ if pinned { position.scrollTo(edge: .bottom) } else { unseen = true }
+ }
+ .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width = $0 }
+ // Scrolled to its newest, the thread fades out under the header.
+ .mask {
+ VStack(spacing: 0) {
+ LinearGradient(colors: [.clear, .black], startPoint: .top, endPoint: .bottom).frame(height: 56)
+ Color.black
+ }
+ }
+ .overlay(alignment: .bottom) {
+ if unseen {
+ Button {
+ position.scrollTo(edge: .bottom)
+ unseen = false
+ } label: {
+ Text(BaseText.text("ask.jump"))
+ .font(BaseFont.body(13, .semibold, relativeTo: .footnote))
+ .foregroundStyle(p[.onSignal])
+ .padding(.horizontal, 14).frame(minHeight: 36)
+ .background(p[.signal], in: Capsule())
+ .shadow(color: p[.glassShadow].opacity(0.5), radius: 9, y: 6)
+ }
+ .buttonStyle(.plain)
+ .padding(.bottom, 10)
+ }
+ }
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel(Text(BaseText.text("ask.conversation_a11y")))
+ }
+
+ private var bubbleWidth: CGFloat {
+ max(120, (width - layout.padding.leading - layout.padding.trailing) * layout.bubbleShare)
+ }
+
+ @ViewBuilder private func row(_ entry: AskModel.Entry) -> some View {
+ switch entry {
+ case .message(let m):
+ Bubble(person: m.isPerson, maxWidth: bubbleWidth) {
+ if m.isPerson {
+ Text(verbatim: m.text).font(BaseFont.body(15)).fixedSize(horizontal: false, vertical: true)
+ } else {
+ BaseMarkdownView(m.text, draft: false, id: m.id, transcript: transcript)
+ }
+ }
+ case .draft(let d):
+ Bubble(person: false, maxWidth: bubbleWidth) {
+ VStack(alignment: .leading, spacing: 4) {
+ if !d.text.isEmpty { BaseMarkdownView(d.text, draft: !d.settled, id: "draft:" + d.turnID, transcript: transcript) }
+ if !d.settled { Caret() }
+ }
+ }
+ .accessibilityElement(children: .combine)
+ case .thinking(let t):
+ ThinkingBubble(line: t.line, maxWidth: bubbleWidth)
+ case .job(let job):
+ JobPill(job: job, busy: model.answering, timeZone: timeZone) { card, option in
+ Task { await model.answer(card, option) }
+ }
+ case .card(let card):
+ CardView(card: card, busy: model.answering.contains(card.id)) { option in
+ Task { await model.answer(card, option) }
+ }
+ case .offer(let offer):
+ OfferView(offer: offer)
+ }
+ }
+}
+
+/// A line of the conversation: the person's on the right in teal, the
+/// Assistant's on the left, each with one tucked corner (app.css `.msg`).
+struct Bubble<Content: View>: View {
+ let person: Bool
+ let maxWidth: CGFloat
+ @ViewBuilder let content: Content
+ @Environment(\.colorScheme) private var scheme
+
+ var body: some View {
+ let p = Palette(scheme)
+ let shape = UnevenRoundedRectangle(topLeadingRadius: 14, bottomLeadingRadius: person ? 14 : 4,
+ bottomTrailingRadius: person ? 4 : 14, topTrailingRadius: 14, style: .continuous)
+ content
+ .foregroundStyle(p[.frost])
+ .padding(.vertical, 10).padding(.horizontal, 14)
+ .background(person ? p[.mine] : p[.theirs], in: shape)
+ .overlay { shape.strokeBorder(person ? p[.mineEdge] : p[.theirsEdge], lineWidth: 1) }
+ .frame(maxWidth: maxWidth, alignment: person ? .trailing : .leading)
+ .frame(maxWidth: .infinity, alignment: person ? .trailing : .leading)
+ }
+}
+
+/// The streaming reply's caret: a block of the accent that blinks (steps,
+/// 1 s); still with Reduce Motion.
+struct Caret: View {
+ @Environment(\.colorScheme) private var scheme
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @Environment(\.skyFrozen) private var frozen
+ var body: some View {
+ let block = Rectangle().fill(Palette(scheme)[.signal]).frame(width: 7, height: 15)
+ Group {
+ if reduceMotion || frozen {
+ block
+ } else {
+ TimelineView(.periodic(from: .now, by: 0.5)) { timeline in
+ block.opacity(Int(timeline.date.timeIntervalSinceReferenceDate * 2) % 2 == 0 ? 1 : 0)
+ }
+ }
+ }
+ .accessibilityHidden(true)
+ }
+}
+
+/// The Assistant's bubble while it works on an answer: three soft dots,
+/// then what Equipo says it is doing, in the secondary ink, italic, the
+/// dots still after it; its edge glows teal into violet. (The web's spark
+/// running round the edge is drawn here as the web's reduced-motion glow.)
+struct ThinkingBubble: View {
+ let line: String?
+ let maxWidth: CGFloat
+ @Environment(\.colorScheme) private var scheme
+
+ var body: some View {
+ let p = Palette(scheme)
+ let shape = UnevenRoundedRectangle(topLeadingRadius: 14, bottomLeadingRadius: 4, bottomTrailingRadius: 14, topTrailingRadius: 14, style: .continuous)
+ HStack(spacing: 5) {
+ if let line {
+ Text(verbatim: line).font(BaseFont.body(15)).italic().foregroundStyle(p[.haze]).lineLimit(1)
+ ThinkingDots().accessibilityHidden(true)
+ } else {
+ ThinkingDots().accessibilityLabel(Text(BaseText.text("ask.thinking_a11y")))
+ }
+ }
+ .frame(minHeight: 22)
+ .padding(.vertical, 10).padding(.horizontal, 14)
+ .background(p[.theirs], in: shape)
+ .overlay {
+ shape.strokeBorder(LinearGradient(colors: [p[.edgeA], p[.edgeB], p[.spkRose]], startPoint: .leading, endPoint: .trailing), lineWidth: 1.5)
+ .opacity(0.7)
+ }
+ .shadow(color: p[.edgeGlowA].opacity(0.7), radius: 8)
+ .frame(maxWidth: maxWidth, alignment: .leading)
+ .accessibilityElement(children: .combine)
+ }
+}
+
+/// Three dots, each lifting and brightening a beat after the last while
+/// their colour drifts through teal, violet and rose; still with Reduce
+/// Motion (one of each).
+struct ThinkingDots: View {
+ @Environment(\.colorScheme) private var scheme
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @Environment(\.skyFrozen) private var frozen
+ var body: some View {
+ let p = Palette(scheme)
+ let colours = [p[.edgeA], p[.edgeB], p[.spkRose]]
+ if reduceMotion || frozen {
+ HStack(spacing: 6) { ForEach(0..<3, id: \.self) { Circle().fill(colours[$0]).frame(width: 6, height: 6).opacity(0.85) } }
+ } else {
+ TimelineView(.animation(minimumInterval: 1.0 / 30)) { timeline in
+ let t = timeline.date.timeIntervalSinceReferenceDate
+ HStack(spacing: 6) {
+ ForEach(0..<3, id: \.self) { i in
+ // think-dot: 1.4 s, peaking at 35%, each 0.18 s after the last.
+ let phase = ((t - Double(i) * 0.18).truncatingRemainder(dividingBy: 1.4) + 1.4).truncatingRemainder(dividingBy: 1.4) / 1.4
+ let lift = phase < 0.35 ? SkyPainter.easeInOut(phase / 0.35) : phase < 0.7 ? SkyPainter.easeInOut(1 - (phase - 0.35) / 0.35) : 0
+ let hue = Int(((t + Double(i) * 1.4) / 1.4).rounded(.down)) % 3
+ Circle().fill(colours[hue]).frame(width: 6, height: 6)
+ .scaleEffect(0.85 + 0.15 * lift).offset(y: -2 * lift).opacity(0.45 + 0.55 * lift)
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/native/apple/Tests/BaseKitTests/AskViewTests.swift b/native/apple/Tests/BaseKitTests/AskViewTests.swift
new file mode 100644
index 0000000..c63a8b1
--- /dev/null
+++ b/native/apple/Tests/BaseKitTests/AskViewTests.swift
@@ -0,0 +1,45 @@
+@testable import BaseKit
+import Foundation
+import XCTest
+
+final class AskViewTests: XCTestCase {
+ /// "Started {when}", in the web's words (ask.js startedText).
+ func testStartedText() {
+ let now = Date(timeIntervalSince1970: 1_768_473_000) // 2026-01-15 10:30 UTC
+ let zone = TimeZone(identifier: "Europe/Dublin")
+ func at(_ seconds: Double) -> String { StartedText.text(now.addingTimeInterval(-seconds), now: now, timeZone: zone) }
+ XCTAssertEqual(at(20), "Started just now")
+ XCTAssertEqual(at(60), "Started 1 minute ago")
+ XCTAssertEqual(at(5 * 60 + 30), "Started 5 minutes ago")
+ XCTAssertEqual(at(3600), "Started 1 hour ago")
+ XCTAssertEqual(at(18 * 3600), "Started 18 hours ago")
+ XCTAssertEqual(at(3 * 86400), "Started on 12 January")
+ }
+
+ /// Only absolute http(s) links act, as ask.js's webURL; Equipo's own
+ /// paths and mailto are text in Base.
+ func testOnlyWebLinksAct() {
+ XCTAssertTrue(ChatMarkdown.allowsLink("https://fennel.example/menu"))
+ XCTAssertTrue(ChatMarkdown.allowsLink("http://fennel.example"))
+ XCTAssertFalse(ChatMarkdown.allowsLink("/tasks/tk123"))
+ XCTAssertFalse(ChatMarkdown.allowsLink("mailto:ana@fennel.example"))
+ XCTAssertFalse(ChatMarkdown.allowsLink("javascript:alert(1)"))
+ XCTAssertFalse(ChatMarkdown.allowsLink("https://user:pw@fennel.example"))
+ }
+
+ /// The Assistant's little Markdown: a list is a list, bold is bold, and
+ /// a draft holds back what its next words could change.
+ func testTheAssistantsMarkdownParses() {
+ let tree = ChatMarkdown.parse("Three things:\n- **08:00** Flour\n- [Menu](https://fennel.example/menu)", draft: false)
+ XCTAssertEqual(tree.map(\.kind), ["paragraph", "unordered"])
+ XCTAssertEqual(tree[1].children.count, 2)
+ let draft = ChatMarkdown.parse("Three things:\n- ", draft: true)
+ XCTAssertEqual(draft.map(\.kind), ["paragraph"], "a marker alone waits for its words")
+ }
+
+ func testTheWebsCopyIsInTheCatalog() {
+ XCTAssertEqual(BaseText.text("ask.placeholder"), "Ask Base anything")
+ XCTAssertEqual(BaseText.format("ask.pill_a11y", ["title": "Christmas order form", "stage": "One question for you"]),
+ "Christmas order form, One question for you")
+ }
+}
diff --git a/native/apple/Tests/BaseSnapshots/AskSnapshots.swift b/native/apple/Tests/BaseSnapshots/AskSnapshots.swift
new file mode 100644
index 0000000..054577a
--- /dev/null
+++ b/native/apple/Tests/BaseSnapshots/AskSnapshots.swift
@@ -0,0 +1,127 @@
+import BaseKit
+import Foundation
+import RastrilloApple
+import RastrilloSnapshots
+import RastrilloTestSupport
+import SwiftUI
+import XCTest
+
+/// Ask, drawn (Task 11): the approved mockups' thread (mac-main-b,
+/// phone-ask) on the Mac and the iPhone, the job view, and Ask's other
+/// states, in light and dark, and on iPhone at AX3. Fixed fixtures; no
+/// server. The window's bar and sidebar are Tasks 13 and 14's: the frame
+/// here is only enough to compare with the mockups.
+final class AskSnapshots: XCTestCase {
+ @MainActor func testAsk() async throws {
+ try XCTSkipUnless(ProcessInfo.processInfo.environment["RASTRILLO_SNAPSHOTS"] != nil, "Run with native/scripts/snapshots.sh")
+ BaseFonts.register()
+ await assertSnapshots(of: Self.catalog)
+ }
+
+ @MainActor static var catalog: SnapshotCatalog {
+ SnapshotCatalog(app: "base-ask", settings: SnapshotSettings(tint: LookSnapshots.tint), screens: [
+ SnapshotScreen("thread", mac: .fixed(width: 1000, height: 720), iphone: .fixed(width: 402, height: 874)) {
+ AskFrame { AskView(model: AskFixtures.thread(), layout: frameLayout, timeZone: AskFixtures.zone, actions: AskActions {}) }
+ },
+ SnapshotScreen("job-view", mac: .width(320), iphone: .width(402)) {
+ JobView(job: AskFixtures.job, timeZone: AskFixtures.zone, close: {}, now: SnapshotSettings.now)
+ },
+ SnapshotScreen("norunner", mac: .fixed(width: 640, height: 420), iphone: .fixed(width: 402, height: 520)) {
+ AskFrame { AskView(model: AskFixtures.model(state: "norunner", extra: AskFixtures.shortThread), layout: frameLayout, timeZone: AskFixtures.zone, actions: AskActions {}) }
+ },
+ SnapshotScreen("connect", mac: .fixed(width: 640, height: 300), iphone: .fixed(width: 402, height: 360)) {
+ AskFrame { AskView(model: AskFixtures.model(state: "connect"), layout: frameLayout, timeZone: AskFixtures.zone, actions: AskActions {}) }
+ },
+ SnapshotScreen("not-linked", mac: .fixed(width: 640, height: 300), iphone: .fixed(width: 402, height: 360)) {
+ AskFrame { AskView(model: AskFixtures.notLinked(), layout: frameLayout, timeZone: AskFixtures.zone, actions: AskActions {}) }
+ },
+ ])
+ }
+}
+
+let frameLayout: AskLayout = {
+ #if os(macOS)
+ .window
+ #else
+ .phone
+ #endif
+}()
+
+/// The sky and the conversation's sheet, with its title bar, as the
+/// mockups frame Ask.
+struct AskFrame<Content: View>: View {
+ @ViewBuilder let content: Content
+ @Environment(\.colorScheme) private var scheme
+ var body: some View {
+ let p = Palette(scheme)
+ ZStack {
+ Sky()
+ VStack(spacing: 0) {
+ HStack(spacing: 9) {
+ BaseMark(size: 16)
+ Text(BaseText.text("native.sidebar.ask")).font(BaseFont.heading(17, .semibold))
+ Spacer()
+ }
+ .padding(.horizontal, 20).frame(height: 52)
+ .overlay(alignment: .bottom) { Rectangle().fill(p[.rule]).frame(height: 1) }
+ content.frame(maxWidth: 760)
+ }
+ .foregroundStyle(p[.frost])
+ .glassSheet(cornerRadius: 18)
+ .padding(10)
+ }
+ .skyFrozen()
+ }
+}
+
+@MainActor enum AskFixtures {
+ static let zone = TimeZone(identifier: "Europe/Dublin")!
+
+ static func model(state: String, extra: String = "") -> AskModel {
+ let m = AskModel(client: BaseClient(transport: ScriptedTransport()) {}, schedule: { _, _ in })
+ let json = #"{"state":"\#(state)","messages":[\#(extra)],"jobs":[],"cards":[],"turn":null,"status":"","cursor":1,"equipo_origin":"https://equipo.fennel.example"}"#
+ m.applyForPreview(try! JSONDecoder().decode(AskSnapshot.self, from: Data(json.utf8)))
+ return m
+ }
+
+ static let shortThread = #"{"id":"m1","role":"person","text":"What's on tomorrow?","turn_id":"t1"}"#
+
+ static func notLinked() -> AskModel {
+ let m = model(state: "connect")
+ m.show(.notLinked)
+ return m
+ }
+
+ /// The mockups' thread: the bakery website on its way, a question on
+ /// the Christmas order form, invoice reminders ready, and tomorrow's
+ /// plan streaming in.
+ static func thread() -> AskModel {
+ let m = AskModel(client: BaseClient(transport: ScriptedTransport()) {}, schedule: { _, _ in })
+ let json = #"""
+ {"state":"ready","cursor":40,"status":"","turn":null,"cards":[],
+ "messages":[
+ {"id":"m1","role":"person","text":"Can you make us a website for the bakery? Use the menu in our Sheets.","turn_id":"t1"},
+ {"id":"m2","role":"assistant","text":"On it. You'll see a first look in a couple of minutes, with the menu from your Sheets.","turn_id":"t1"}],
+ "jobs":[
+ {"id":"j1","revision":1,"kind":"job","state":"working","question":"Bakery website","result":"Building a first look","options":[],"links":[]},
+ {"id":"j2","revision":1,"kind":"job","state":"asking","question":"Christmas order form","result":"One question for you","options":[],"links":[],
+ "cards":[{"id":"c1","revision":1,"kind":"question","state":"open","question":"When should Christmas orders close?","job":"j2",
+ "options":[{"value":"fri","label":"Fri 18 Dec"},{"value":"tue","label":"Tue 22 Dec"},{"value":"else","label":"Something else"}],"links":[]}]},
+ {"id":"j3","revision":1,"kind":"job","state":"ready","question":"Invoice reminders","result":"Ready to try","options":[],
+ "links":[{"label":"Try it","url":"https://fennel.base.example/apps/reminders"}]}]}
+ """#
+ m.applyForPreview(try! JSONDecoder().decode(AskSnapshot.self, from: Data(json.utf8)))
+ m.apply(.message(AskMessage(id: "m3", role: "person", text: "What's on tomorrow?", turnID: "t2")))
+ m.apply(.delta(AskDelta(turnID: "t2", offset: 0, text: "Three things tomorrow:\n- 08:00 Flour delivery\n- 11:30 Ana, about the Christmas menu\n- 15:00 Call with the accountant\n")))
+ return m
+ }
+
+ static let job = AskModel.Job(
+ card: AskCard(id: "j2", revision: 3, kind: "job", state: "asking", question: "Christmas order form",
+ links: [.init(label: "Open in Equipo", url: URL(string: "https://equipo.fennel.example/tasks/tk2"), rel: "equipo")],
+ result: "One question for you",
+ detail: "The form is built and works. It needs a closing date before it goes on the website.",
+ startedAt: SnapshotSettings.now.addingTimeInterval(-18 * 3600)),
+ open: [],
+ ended: [AskCard(id: "c0", kind: "confirm", state: "answered", question: "Use the autumn menu's prices?", result: "You said yes", job: "j2")])
+}
diff --git a/native/scripts/check-strings.py b/native/scripts/check-strings.py
index 07ef83d..e9648d9 100755
--- a/native/scripts/check-strings.py
+++ b/native/scripts/check-strings.py
@@ -3,7 +3,8 @@
1. Every entry in apple/Sources/BaseKit/Resources/Localizable.xcstrings has
its English text.
-2. Every key a Swift source asks for (BaseText.text / BaseText.format) is in
+2. Every key a Swift source asks for (BaseText.text / format / plural, or a
+ key literal handed to a helper) is in
the catalog, and every catalog entry is asked for somewhere or listed as
waiting for a later task (WAITING below).
3. No view hard-codes copy: Text, Button, Label and friends take catalog
@@ -41,14 +42,15 @@ for key, entry in catalog["strings"].items():
# Strings copy review approved for screens later tasks draw (Tasks 12 to
# 14). They stay in the catalog so the review's text is the app's text.
-WAITING = re.compile(r"^native\.(signin|sidebar|account|menubar|settings|phone|colophon|offline|ask|job)\b|^ask\.|^chat\.paste\.") # ask.* and chat.paste.*: Task 11 draws them
+WAITING = re.compile(r"^native\.(signin|sidebar|account|menubar|settings|phone|colophon|offline)\b")
used = set()
for path in sources.rglob("*.swift"):
text = path.read_text()
for match in re.finditer(r'BaseText\.(?:text|format|plural)\(\s*"([^"]+)"', text):
if match.group(1) != "…": used.add(match.group(1))
- for match in re.finditer(r'(?:baseKey|textKey):\s*"([^"]+)"', text):
+ # A key handed to a helper (lede("ask.connect.lede", …)) is used too.
+ for match in re.finditer(r'"((?:ask|native|chat)\.[a-z0-9_.]+)"', text):
used.add(match.group(1))
for n, line in enumerate(text.splitlines(), 1):
if re.search(r'\b(Text|Button|Label|Toggle|Section|LabeledContent|Picker|TextField|Link|Menu)\(\s*"(?!")', line) and "verbatim" not in line: