Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook
Swift apple-silicongemmagemma4gemma4-26b-a4bgpgpullmllm-inferencelocal-aimacosmetalon-device-aion-device-llmswift
Add Mac text-size settings and open an empty chat on launch (#179)
Andrey Mikhaylovcdaa282f80d5
diff --git a/README.md b/README.mdindex 9da9bfbf..45cd3d18 100644--- a/README.md+++ b/README.md@@ -177,10 +177,14 @@ right pane to configure sampling, context length, expert-cache slots, andruntime options. See [Runtime controls](docs/RUNTIME_CONTROLS.md) for detailsand defaults.+Use **Settings → Text Size** to enlarge conversation and message-editor text+from 100% to 200%. Changes apply immediately and are remembered across launches.+#### Conversation historyThe app saves chats locally so you can browse and continue them from the-sidebar. Only one conversation's model context (KV cache) stays in memory.+sidebar. Every launch opens an empty chat. Only one conversation's model context+(KV cache) stays in memory.Browsing other chats keeps that cache intact; continuing another chat replacesit. **New Chat** starts fresh.diff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppTextSize.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppTextSize.swiftnew file mode 100644index 00000000..b1c4b28b--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Configuration/AppTextSize.swift@@ -0,0 +1,11 @@+public enum AppTextSize: Int, CaseIterable, Codable, Identifiable, Sendable {+ case standard = 100+ case large = 125+ case larger = 150+ case extraLarge = 175+ case largest = 200++ public var id: Int { rawValue }+ public var label: String { "\(rawValue)%" }+ public var scale: Double { Double(rawValue) / 100 }+}diff --git a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swiftindex 47ac9b51..52fe1964 100644--- a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift+++ b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift@@ -16,6 +16,7 @@ struct MacAppSettings: Codable, Equatable, Sendable {var prefillEnabled: Bool = truevar newlineShortcut: AppNewlineShortcut = .returnvar showPromptExamples: Bool = true+ var textSize: AppTextSize = .standard/// Whether the list of chats is showing. Remembered because hiding it is a/// choice about how the window looks, and a window that forgot it every/// launch would be making that choice again for the user each time.@@ -26,7 +27,6 @@ struct MacAppSettings: Codable, Equatable, Sendable {var visionResidencyPolicy: VisionResidencyPolicy = .onDemandvar rdadvisePolicy: AppRDAdvicePolicy = .offvar loadModelOnLaunch: Bool = false- var selectedConversationID: UUID?private enum CodingKeys: String, CodingKey {case version@@ -40,12 +40,12 @@ struct MacAppSettings: Codable, Equatable, Sendable {case prefillEnabledcase newlineShortcutcase showPromptExamples+ case textSizecase sidebarVisiblecase inspectorVisiblecase visionResidencyPolicycase rdadvisePolicycase loadModelOnLaunch- case selectedConversationID}init(version: Int = currentVersion,@@ -59,12 +59,12 @@ struct MacAppSettings: Codable, Equatable, Sendable {prefillEnabled: Bool = true,newlineShortcut: AppNewlineShortcut = .return,showPromptExamples: Bool = true,+ textSize: AppTextSize = .standard,sidebarVisible: Bool = true,inspectorVisible: Bool = true,visionResidencyPolicy: VisionResidencyPolicy = .onDemand,rdadvisePolicy: AppRDAdvicePolicy = .off,- loadModelOnLaunch: Bool = false,- selectedConversationID: UUID? = nil) {+ loadModelOnLaunch: Bool = false) {self.version = versionself.contextTokens = contextTokensself.expertCacheSlots = expertCacheSlots@@ -76,12 +76,12 @@ struct MacAppSettings: Codable, Equatable, Sendable {self.prefillEnabled = prefillEnabledself.newlineShortcut = newlineShortcutself.showPromptExamples = showPromptExamples+ self.textSize = textSizeself.sidebarVisible = sidebarVisibleself.inspectorVisible = inspectorVisibleself.visionResidencyPolicy = visionResidencyPolicyself.rdadvisePolicy = rdadvisePolicyself.loadModelOnLaunch = loadModelOnLaunch- self.selectedConversationID = selectedConversationID}init(from decoder: Decoder) throws {@@ -101,6 +101,18 @@ struct MacAppSettings: Codable, Equatable, Sendable {showPromptExamples = try container.decodeIfPresent(Bool.self,forKey: .showPromptExamples) ?? true+ // A damaged appearance preference must not reach settings-wide recovery,+ // which discards the file and would reset unrelated runtime choices.+ // Foundation can throw a non-DecodingError for a fractional integer.+ if container.contains(.textSize) {+ do {+ textSize = try container.decode(AppTextSize.self, forKey: .textSize)+ } catch {+ FileHandle.standardError.write(Data(+ "Invalid Mac app setting textSize: unsupported value or type; using 100%.\n".utf8))+ textSize = .standard+ }+ }// Additive, like every field around it: absent means the default, so// no version bump and no rewrite of a file an older build can still// read.@@ -119,9 +131,6 @@ struct MacAppSettings: Codable, Equatable, Sendable {loadModelOnLaunch = try container.decodeIfPresent(Bool.self,forKey: .loadModelOnLaunch) ?? false- selectedConversationID = try container.decodeIfPresent(- UUID.self,- forKey: .selectedConversationID)}func isValid() -> Bool {diff --git a/Sources/TurboFieldfareApp/Core/State/AppModel.swift b/Sources/TurboFieldfareApp/Core/State/AppModel.swiftindex e645f16e..bcd47dae 100644--- a/Sources/TurboFieldfareApp/Core/State/AppModel.swift+++ b/Sources/TurboFieldfareApp/Core/State/AppModel.swift@@ -72,6 +72,7 @@ public final class AppModel {public var topP: Double = 0.95public private(set) var newlineShortcut: AppNewlineShortcut = .returnpublic private(set) var showPromptExamples: Bool = true+ public private(set) var textSize: AppTextSize = .standard/// Whether the list of chats is showing. Persisted, so the window comes/// back the way it was left.public private(set) var isSidebarVisible: Bool = true@@ -192,7 +193,6 @@ public final class AppModel {var conversationBindingGeneration: UInt64 = 0let conversationIdentityProvider: @Sendable (URL) throws -> ConversationIdentitylet conversationStoreProvider: @Sendable (URL) -> ConversationStore- var pendingRestoredConversationID: UUID?var pendingServiceRecoveryConversationID: UUID?/// Stored copies of the in-flight turn's images, written while the model is/// generating so the wait is not paid twice.@@ -249,10 +249,10 @@ public final class AppModel {self.topP = settings.topPself.newlineShortcut = settings.newlineShortcutself.showPromptExamples = settings.showPromptExamples+ self.textSize = settings.textSizeself.isSidebarVisible = settings.sidebarVisibleself.isInspectorVisible = settings.inspectorVisibleself.loadModelOnLaunch = settings.loadModelOnLaunch- self.pendingRestoredConversationID = settings.selectedConversationIDself.installationStatus = AppModelInstallationProbe.status(at: directory)self.visionInstallationStatus = AppVisionPackInstallationProbe.status(at: directory)self.client = client@@ -828,6 +828,12 @@ public final class AppModel {persistSettings()}+ public func setTextSize(_ size: AppTextSize) {+ guard textSize != size else { return }+ textSize = size+ persistSettings()+ }+public func setShowPromptExamples(_ show: Bool) {guard showPromptExamples != show else { return }showPromptExamples = show@@ -1948,10 +1954,10 @@ public final class AppModel {topP = settings.topPnewlineShortcut = settings.newlineShortcutshowPromptExamples = settings.showPromptExamples+ textSize = settings.textSizeisSidebarVisible = settings.sidebarVisibleisInspectorVisible = settings.inspectorVisibleloadModelOnLaunch = settings.loadModelOnLaunch- pendingRestoredConversationID = settings.selectedConversationID}func persistSettings() {@@ -1967,12 +1973,12 @@ public final class AppModel {prefillEnabled: runtimeOptions.prefillEnabled,newlineShortcut: newlineShortcut,showPromptExamples: showPromptExamples,+ textSize: textSize,sidebarVisible: isSidebarVisible,inspectorVisible: isInspectorVisible,visionResidencyPolicy: runtimeOptions.visionResidencyPolicy,rdadvisePolicy: runtimeOptions.rdadvisePolicy,- loadModelOnLaunch: loadModelOnLaunch,- selectedConversationID: history.selection)+ loadModelOnLaunch: loadModelOnLaunch)let modelDirectory = URL(fileURLWithPath: modelPathText, isDirectory: true)do {try MacAppSettingsFileStore.save(settings, forModelDirectory: modelDirectory)diff --git a/Sources/TurboFieldfareApp/Core/State/AppModelHistory.swift b/Sources/TurboFieldfareApp/Core/State/AppModelHistory.swiftindex fee6077b..41c4434e 100644--- a/Sources/TurboFieldfareApp/Core/State/AppModelHistory.swift+++ b/Sources/TurboFieldfareApp/Core/State/AppModelHistory.swift@@ -69,7 +69,7 @@ extension AppModel {pendingServiceRecoveryConversationID = nilmachine = ConversationScreenMachine()history.replaceEntries([])- history.selection = pendingRestoredConversationID+ history.selection = nilhistory.setUnreadableCount(0)history.setDiscardedLegacyTrashCount(0)history.setReadOnlyStore(false)@@ -169,15 +169,6 @@ extension AppModel {}.joined(separator: ", "))}history.replaceEntries(entries)- if let saved = pendingRestoredConversationID {- pendingRestoredConversationID = nil- if history.entry(saved) != nil {- openConversation(id: saved)- } else {- history.selection = nil- persistHistorySelection()- }- }}/// Says so when a conversation's `conversation.json` had to be rebuilt.@@ -239,7 +230,7 @@ extension AppModel {sampling: currentSampling())storedConversationID = meta.idhistory.selection = meta.id- persistHistorySelection()+ persistSettings()await refreshHistory()return meta.id} catch {@@ -492,7 +483,7 @@ extension AppModel {self.error = .conversationPersistenceFailed("\(error)")storedConversationID = nilhistory.selection = nil- persistHistorySelection()+ persistSettings()}}}@@ -855,7 +846,7 @@ extension AppModel {switch effect {case .select(let id):history.selection = id- persistHistorySelection()+ persistSettings()case .dropOutOfContextTurns:conversation.dropOutOfContextPairs()case .loadDocument(let id, let renderID):@@ -891,10 +882,6 @@ extension AppModel {}}- private func persistHistorySelection() {- persistSettings()- }-/// The held chat's turns move out of context and keep their pictures:/// they are still drawn there, and New Chat releases them along with the/// rest. Releasing them here first carried pairs whose thumbnails pointeddiff --git a/Sources/TurboFieldfareApp/Mac/App/RootView.swift b/Sources/TurboFieldfareApp/Mac/App/RootView.swiftindex d94792e7..87b20042 100644--- a/Sources/TurboFieldfareApp/Mac/App/RootView.swift+++ b/Sources/TurboFieldfareApp/Mac/App/RootView.swift@@ -154,7 +154,7 @@ struct RootView: View {.frame(maxHeight: .infinity, alignment: .top)}- conversationChrome+ conversationChrome(availableHeight: geometry.size.height).background {GeometryReader { chromeGeometry inColor.clear.preference(@@ -174,7 +174,7 @@ struct RootView: View {}}- private var conversationChrome: some View {+ private func conversationChrome(availableHeight: CGFloat) -> some View {VStack(spacing: 10) {ErrorBanner(model: model)ConversationStateNoticeView(model: model)@@ -184,7 +184,7 @@ struct RootView: View {}}ModelActionBanner(model: model)- PromptComposerView(model: model)+ PromptComposerView(model: model, availableHeight: availableHeight)}.padding(.horizontal, 20).padding(.bottom, 16)diff --git a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swiftindex f8b3dc4a..0528f069 100644--- a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift+++ b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift@@ -187,6 +187,14 @@ struct TurboFieldfareMacApp: App {.disabled(!model.canRemoveVisionPack)}CommandMenu("Settings") {+ Picker("Text Size", selection: textSizeBinding) {+ ForEach(AppTextSize.allCases) { size in+ Text(size.label).tag(size)+ .accessibilityIdentifier(AccessibilityID.textSizeOption(size))+ }+ }+ .accessibilityIdentifier(.settingsTextSize)+ Divider()Picker("Send Message With", selection: newlineShortcutBinding) {ForEach(AppNewlineShortcut.sendMessageOptions) { shortcut inText(shortcut.sendMessageLabel).tag(shortcut)@@ -221,6 +229,10 @@ struct TurboFieldfareMacApp: App {}}+ private var textSizeBinding: Binding<AppTextSize> {+ Binding(get: { model.textSize }, set: { model.setTextSize($0) })+ }+private var newlineShortcutBinding: Binding<AppNewlineShortcut> {Binding {model.newlineShortcutdiff --git a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swiftindex dcd35c69..90aaffe4 100644--- a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift+++ b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift@@ -40,6 +40,7 @@ struct OutputPaneView: View {private var transcript: some View {IncrementalTranscriptView(+ typography: ConversationTypography(model.textSize),history: model.transcriptHistory,contextBreak: model.transcriptContextBreak,conversationEpoch: model.displayedTranscriptID,@@ -279,43 +280,6 @@ private struct EmptyPlaceholderIcon: View {}}-private struct EmptyConversationLayout: Layout {- let spacing: CGFloat-- func sizeThatFits(- proposal: ProposedViewSize,- subviews: Subviews,- cache: inout ()- ) -> CGSize {- proposal.replacingUnspecifiedDimensions()- }-- func placeSubviews(- in bounds: CGRect,- proposal: ProposedViewSize,- subviews: Subviews,- cache: inout ()- ) {- guard subviews.count == 2 else { return }-- let iconSize = subviews[0].sizeThatFits(.unspecified)- let iconCenter = CGPoint(x: bounds.midX, y: bounds.midY)- subviews[0].place(- at: iconCenter,- anchor: .center,- proposal: ProposedViewSize(- width: iconSize.width,- height: iconSize.height))-- subviews[1].place(- at: CGPoint(- x: bounds.midX,- y: iconCenter.y + iconSize.height / 2 + spacing),- anchor: .top,- proposal: ProposedViewSize(width: bounds.width, height: nil))- }-}-private struct LoadingModelText: View {@Environment(\.accessibilityReduceMotion) private var reduceMotion@State private var animationStart = Date()@@ -342,6 +306,7 @@ private struct LoadingModelText: View {}private struct IncrementalTranscriptView: NSViewRepresentable {+ var typography = ConversationTypography()var history: [(user: AppChatTurn, assistant: AppChatTurn)] = []/// Pairs above this index are on screen but no longer in the model's/// context. Nil when everything drawn is still in the KV.@@ -409,6 +374,9 @@ private struct IncrementalTranscriptView: NSViewRepresentable {func attach(scrollView: NSScrollView, textView: NSTextView) {self.scrollView = scrollViewself.textView = textView+ (scrollView as? TranscriptScrollView)?.didRestoreReadingPosition = { [weak self] in+ self?.recordScrollPosition()+ }// Right-click inside a turn offers that turn's answer, so a// transcript of several turns has an unambiguous copy affordance// rather than one floating button that reads as the first turn's.@@ -441,6 +409,7 @@ private struct IncrementalTranscriptView: NSViewRepresentable {}func synchronize(+ typography: ConversationTypography,history: [(user: AppChatTurn, assistant: AppChatTurn)],contextBreak: Int?,conversationEpoch: UUID,@@ -492,6 +461,8 @@ private struct IncrementalTranscriptView: NSViewRepresentable {// view that is already at the bottom.if !response.isEmpty || isTerminal { follow.end() }if startedNewRun || shouldFollowNow() { scrollToBottom() }+ refreshTypography(typography, history: history, contextBreak: contextBreak,+ epoch: conversationEpoch)}/// Keeps the drawn document in step with the conversation.@@ -520,14 +491,7 @@ private struct IncrementalTranscriptView: NSViewRepresentable {epoch: epoch, historyCount: history.count, contextBreak: contextBreak,startedNewRun: startedNewRun, firstSynchronize: firstSynchronize)) { index in- let pair = history[index]- _ = controller.synchronize(- storage: storage, prompt: pair.user.text,- response: pair.assistant.text, isTerminal: true,- promptPrefix: Self.makePromptPrefix(pair.user.images),- promptPrefixIdentifier: pair.user.images- .map { "\($0.id.uuidString):\($0.sha256)" }- .joined(separator: ","))+ drawHistoryPair(history[index], storage: storage)}for step in steps {switch step {@@ -544,6 +508,40 @@ private struct IncrementalTranscriptView: NSViewRepresentable {}}+ private func refreshTypography(+ _ typography: ConversationTypography,+ history: [(user: AppChatTurn, assistant: AppChatTurn)],+ contextBreak: Int?, epoch: UUID+ ) {+ guard documentController.typography != typography,+ let textView, let scrollView, let storage = textView.textStorage else { return }+ let position = TranscriptReadingPosition(+ textView: textView, scrollView: scrollView, followsPrefill: shouldFollowNow())+ let update = documentController.refreshTypography(+ typography, storage: storage, planner: &planner,+ input: .init(epoch: epoch, historyCount: history.count,+ contextBreak: contextBreak, startedNewRun: false,+ firstSynchronize: true),+ promptPrefix: promptPrefix+ ) { index in+ drawHistoryPair(history[index], storage: storage)+ }+ position.restore(textView: textView, scrollView: scrollView,+ replacing: update.replaced)+ recordScrollPosition()+ }++ private func drawHistoryPair(+ _ pair: (user: AppChatTurn, assistant: AppChatTurn), storage: NSMutableAttributedString+ ) {+ documentController.synchronize(+ storage: storage, prompt: pair.user.text, response: pair.assistant.text,+ isTerminal: true, promptPrefix: Self.makePromptPrefix(pair.user.images),+ promptPrefixIdentifier: pair.user.images.map {+ "\($0.id.uuidString):\($0.sha256)"+ }.joined(separator: ","))+ }+func scrollToBottom() {guard let textView else { return }if let textContainer = textView.textContainer {@@ -835,7 +833,7 @@ private struct IncrementalTranscriptView: NSViewRepresentable {func makeCoordinator() -> Coordinator { Coordinator() }func makeNSView(context: Context) -> NSScrollView {- let scrollView = NSScrollView()+ let scrollView = TranscriptScrollView()scrollView.hasVerticalScroller = truescrollView.autohidesScrollers = truescrollView.drawsBackground = false@@ -862,6 +860,7 @@ private struct IncrementalTranscriptView: NSViewRepresentable {guard let textView = scrollView.documentView as? NSTextView else { return }context.coordinator.attach(scrollView: scrollView, textView: textView)context.coordinator.synchronize(+ typography: typography,history: history,contextBreak: contextBreak,conversationEpoch: conversationEpoch,diff --git a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swiftindex f369c9ea..1d34dd3b 100644--- a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift+++ b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift@@ -7,6 +7,7 @@ import UniformTypeIdentifiersstruct PromptComposerView: View {@Bindable var model: AppModel+ var availableHeight: CGFloat = .infinity@FocusState private var promptFocused: Bool@State private var showingImagePicker = false@State private var isImageDropTargeted = false@@ -43,6 +44,7 @@ struct PromptComposerView: View {private var editor: some View {PromptTextEditor(text: $model.promptText,+ typography: ConversationTypography(model.textSize),isFocused: Binding(get: { promptFocused },set: { promptFocused = $0 }),@@ -73,7 +75,7 @@ struct PromptComposerView: View {// Matches the NSTextView text origin: 5pt line fragment// padding, no vertical inset.Text("Message")- .font(.body)+ .font(.system(size: ConversationTypography(model.textSize).bodySize)).foregroundStyle(.tertiary).padding(.leading, 5).allowsHitTesting(false)@@ -89,7 +91,8 @@ struct PromptComposerView: View {}private var editorHeight: CGFloat {- model.shouldShowPromptExamples ? 46 : 84+ ConversationTypography(model.textSize).editorHeight(+ showsExamples: model.shouldShowPromptExamples, availableHeight: availableHeight)}private var footer: some View {@@ -238,6 +241,7 @@ struct PromptComposerView: View {private struct PromptTextEditor: NSViewRepresentable {@Binding var text: String+ let typography: ConversationTypographylet isFocused: Binding<Bool>let newlineShortcut: AppNewlineShortcutlet canRun: Bool@@ -258,7 +262,7 @@ private struct PromptTextEditor: NSViewRepresentable {let textView = ImageDropTextView()textView.delegate = context.coordinatortextView.string = text- textView.font = .systemFont(ofSize: NSFont.systemFontSize)+ textView.typography = typographytextView.textColor = .labelColortextView.drawsBackground = falsetextView.isRichText = false@@ -292,6 +296,7 @@ private struct PromptTextEditor: NSViewRepresentable {func updateNSView(_ scrollView: NSScrollView, context: Context) {guard let textView = scrollView.documentView as? ImageDropTextView else { return }context.coordinator.parent = self+ textView.typography = typographytextView.canAcceptImages = canAcceptImagestextView.onImagesDropped = onImagesDroppedtextView.onImageDataPasted = onImageDataPasted@@ -363,7 +368,7 @@ private struct PromptTextEditor: NSViewRepresentable {}}-private final class ImageDropTextView: NSTextView {+private final class ImageDropTextView: PromptEditorTextView {var canAcceptImages = falsevar onImagesDropped: (([URL]) -> Void)?/// Promised files arrive in a directory we made and must not keep.diff --git a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swiftindex cdc0567a..ec251b1e 100644--- a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift+++ b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift@@ -17,7 +17,7 @@ public enum AboutPanelPresentation {// Most users build from a clone, where there is no Info.plist to read a// version from, so this constant is what they see. Scripts/check_app_version.rb// fails CI when it falls behind the newest published release.- public static let fallbackShortVersion = "0.8.0"+ public static let fallbackShortVersion = "0.8.1"private static let licenseURL = URL(string: "https://github.com/drumih/turbo-fieldfare/blob/main/LICENSE")!diff --git a/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swift b/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swiftindex a42b90b6..8fc7419b 100644--- a/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swift+++ b/Sources/TurboFieldfareApp/MacPresentation/AccessibilityID.swift@@ -1,4 +1,5 @@import SwiftUI+import TurboFieldfareAppCore/// Every control the Mac app exposes to an acceptance pass, named once.///@@ -9,6 +10,23 @@ import SwiftUI/// `Scripts/check_app_case_coverage.rb` fails when one has no case in the/// `mac-app-acceptance` skill, so a new control cannot land without its case.public enum AccessibilityID: String, CaseIterable, Sendable {+ case settingsTextSize = "settings.textSize"+ case settingsTextSizeStandard = "settings.textSize.standard"+ case settingsTextSizeLarge = "settings.textSize.large"+ case settingsTextSizeLarger = "settings.textSize.larger"+ case settingsTextSizeExtraLarge = "settings.textSize.extraLarge"+ case settingsTextSizeLargest = "settings.textSize.largest"++ public static func textSizeOption(_ size: AppTextSize) -> AccessibilityID {+ switch size {+ case .standard: .settingsTextSizeStandard+ case .large: .settingsTextSizeLarge+ case .larger: .settingsTextSizeLarger+ case .extraLarge: .settingsTextSizeExtraLarge+ case .largest: .settingsTextSizeLargest+ }+ }+case stripSidebar = "strip.sidebar"case stripNewChat = "strip.newChat"case stripInspector = "strip.inspector"diff --git a/Sources/TurboFieldfareApp/MacPresentation/ConversationTypography.swift b/Sources/TurboFieldfareApp/MacPresentation/ConversationTypography.swiftnew file mode 100644index 00000000..f51cf583--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/ConversationTypography.swift@@ -0,0 +1,22 @@+import AppKit+import TurboFieldfareAppCore++public struct ConversationTypography: Equatable, Sendable {+ public let textSize: AppTextSize++ public init(_ textSize: AppTextSize = .standard) {+ self.textSize = textSize+ }++ public var scale: CGFloat { CGFloat(textSize.scale) }+ public func scaled(_ baseline: CGFloat) -> CGFloat { baseline * scale }+ public var bodySize: CGFloat { scaled(NSFont.systemFontSize) }+ public var labelSize: CGFloat { scaled(NSFont.smallSystemFontSize) }+ public var bodyFont: NSFont { .systemFont(ofSize: bodySize) }++ public func editorHeight(showsExamples: Bool, availableHeight: CGFloat) -> CGFloat {+ // At large text sizes a fixed line count can consume the conversation+ // viewport. Keep two readable lines and let the editor scroll instead.+ min(scaled(showsExamples ? 46 : 84), max(scaled(40), availableHeight / 5))+ }+}diff --git a/Sources/TurboFieldfareApp/MacPresentation/EmptyConversationLayout.swift b/Sources/TurboFieldfareApp/MacPresentation/EmptyConversationLayout.swiftnew file mode 100644index 00000000..f98630b6--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/EmptyConversationLayout.swift@@ -0,0 +1,53 @@+import SwiftUI++public struct EmptyConversationLayout: Layout {+ let spacing: CGFloat++ public init(spacing: CGFloat) { self.spacing = spacing }++ public func sizeThatFits(+ proposal: ProposedViewSize,+ subviews: Subviews,+ cache: inout ()+ ) -> CGSize {+ proposal.replacingUnspecifiedDimensions()+ }++ public func placeSubviews(+ in bounds: CGRect,+ proposal: ProposedViewSize,+ subviews: Subviews,+ cache: inout ()+ ) {+ guard subviews.count == 2 else { return }++ let iconSize = subviews[0].sizeThatFits(.unspecified)+ let contentSize = subviews[1].sizeThatFits(+ ProposedViewSize(width: bounds.width, height: nil))+ let iconCenter = CGPoint(+ x: bounds.midX,+ y: Self.iconCenterY(in: bounds, iconHeight: iconSize.height,+ contentHeight: contentSize.height, spacing: spacing))+ subviews[0].place(+ at: iconCenter,+ anchor: .center,+ proposal: ProposedViewSize(+ width: iconSize.width,+ height: iconSize.height))++ subviews[1].place(+ at: CGPoint(+ x: bounds.midX,+ y: iconCenter.y + iconSize.height / 2 + spacing),+ anchor: .top,+ proposal: ProposedViewSize(width: bounds.width, height: nil))+ }+ static func iconCenterY(+ in bounds: CGRect, iconHeight: CGFloat, contentHeight: CGFloat, spacing: CGFloat+ ) -> CGFloat {+ // Keep the familiar centered icon when space permits, but reserve room+ // for the model action above the composer in compact windows.+ max(bounds.minY + iconHeight / 2,+ min(bounds.midY, bounds.maxY - contentHeight - spacing - iconHeight / 2))+ }+}diff --git a/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift b/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swiftindex e4fbd55f..d25372d7 100644--- a/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift+++ b/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift@@ -117,15 +117,21 @@ public final class InstructionTranscriptDocumentController {private var prefillPlaceholderRange: NSRange?private var prefillDotCount = 0- private let renderer: any TranscriptBlockRendering+ private var renderer: any TranscriptBlockRendering+ public private(set) var typography: ConversationTypography+ private let environment: [String: String]private let progressiveRendering: Boolprivate var progressive = ProgressiveState()public init(- renderer: any TranscriptBlockRendering = ResponseMarkdownRenderer(),+ renderer: (any TranscriptBlockRendering)? = nil,+ typography: ConversationTypography = .init(),environment: [String: String] = ProcessInfo.processInfo.environment) {- self.renderer = renderer+ self.typography = typography+ self.environment = environment+ self.renderer = renderer ?? ResponseMarkdownRenderer(+ typography: typography, environment: environment)progressiveRendering = environment["TURBO_FIELDFARE_PROGRESSIVE_RENDER"] != "0"}@@ -346,7 +352,7 @@ public final class InstructionTranscriptDocumentController {prefillDotCount = (prefillDotCount + 1) % 4let replacement = NSAttributedString(string: Self.prefillPlaceholder(dotCount: prefillDotCount),- attributes: Self.prefillPlaceholderAttributes())+ attributes: prefillPlaceholderAttributes())storage.replaceCharacters(in: range, with: replacement)range.length = replacement.lengthprefillPlaceholderRange = range@@ -359,7 +365,7 @@ public final class InstructionTranscriptDocumentController {) -> Mutation {storage.append(NSAttributedString(string: delta,- attributes: Self.responseAttributes()))+ attributes: responseAttributes()))assistantRange.length += (delta as NSString).lengthreturn .appended}@@ -376,35 +382,35 @@ public final class InstructionTranscriptDocumentController {if !prompt.isEmpty || promptPrefix.length > 0 {document.append(NSAttributedString(string: "You\n",- attributes: Self.userLabelAttributes()))+ attributes: userLabelAttributes()))if promptPrefix.length > 0 {document.append(promptPrefix)if !prompt.isEmpty {document.append(NSAttributedString(string: "\n\n",- attributes: Self.promptAttributes()))+ attributes: promptAttributes()))}}if !prompt.isEmpty {document.append(NSAttributedString(string: prompt,- attributes: Self.promptAttributes()))+ attributes: promptAttributes()))}document.append(NSAttributedString(string: "\n\n",- attributes: Self.promptAttributes()))+ attributes: promptAttributes()))}// Recovery can clear the live turn while leaving completed history.if !prompt.isEmpty || promptPrefix.length > 0|| !response.isEmpty || showsPrefillPlaceholder {document.append(NSAttributedString(string: "Answer\n",- attributes: Self.assistantLabelAttributes()))+ attributes: assistantLabelAttributes()))}assistantRange = NSRange(location: document.length, length: 0)let assistant = progressiveRendering? progressiveRender(response, closingTail: closingTail)- : NSAttributedString(string: response, attributes: Self.responseAttributes())+ : NSAttributedString(string: response, attributes: responseAttributes())document.append(assistant)assistantRange.length = assistant.lengthprefillDotCount = 0@@ -412,7 +418,7 @@ public final class InstructionTranscriptDocumentController {if showsPrefillPlaceholder {let placeholder = NSAttributedString(string: Self.prefillPlaceholder(dotCount: prefillDotCount),- attributes: Self.prefillPlaceholderAttributes())+ attributes: prefillPlaceholderAttributes())prefillPlaceholderRange = NSRange(location: document.length,length: placeholder.length)@@ -446,7 +452,7 @@ public final class InstructionTranscriptDocumentController {let start = frozenLengthlet answer = responsestorage.append(NSAttributedString(- string: "\n\n", attributes: Self.promptAttributes()))+ string: "\n\n", attributes: promptAttributes()))frozenLength = storage.lengthsealedTurns.append((range: NSRange(location: start, length: frozenLength - start),@@ -482,7 +488,7 @@ public final class InstructionTranscriptDocumentController {public func appendContextBreak(storage: NSMutableAttributedString, text: String) {guard storage.length == frozenLength else { return }storage.append(NSAttributedString(- string: "\(text)\n\n", attributes: Self.contextBreakAttributes()))+ string: "\(text)\n\n", attributes: contextBreakAttributes()))frozenLength = storage.lengthassistantRange = NSRange(location: frozenLength, length: 0)}@@ -955,63 +961,63 @@ public final class InstructionTranscriptDocumentController {return count + seed}- private static func userLabelAttributes() -> [NSAttributedString.Key: Any] {+ private func userLabelAttributes() -> [NSAttributedString.Key: Any] {labelAttributes(color: .secondaryLabelColor)}- private static func assistantLabelAttributes() -> [NSAttributedString.Key: Any] {+ private func assistantLabelAttributes() -> [NSAttributedString.Key: Any] {labelAttributes(color: TurboFieldfareMacTheme.accentNSColor)}- private static func labelAttributes(+ private func labelAttributes(color: NSColor) -> [NSAttributedString.Key: Any] {let style = NSMutableParagraphStyle()- style.paragraphSpacing = 5+ style.paragraphSpacing = typography.scaled(5)return [.font: NSFont.systemFont(- ofSize: NSFont.smallSystemFontSize,+ ofSize: typography.labelSize,weight: .semibold),.foregroundColor: color,.paragraphStyle: style,]}- private static func contextBreakAttributes() -> [NSAttributedString.Key: Any] {+ private func contextBreakAttributes() -> [NSAttributedString.Key: Any] {let style = NSMutableParagraphStyle()style.alignment = .center- style.paragraphSpacingBefore = 8- style.paragraphSpacing = 8+ style.paragraphSpacingBefore = typography.scaled(8)+ style.paragraphSpacing = typography.scaled(8)return [.font: NSFont.systemFont(- ofSize: NSFont.smallSystemFontSize, weight: .regular),+ ofSize: typography.labelSize, weight: .regular),.foregroundColor: NSColor.tertiaryLabelColor,.paragraphStyle: style,]}- private static func promptAttributes() -> [NSAttributedString.Key: Any] {+ private func promptAttributes() -> [NSAttributedString.Key: Any] {let style = NSMutableParagraphStyle()- style.lineSpacing = 3+ style.lineSpacing = typography.scaled(3)return [- .font: NSFont.systemFont(ofSize: NSFont.systemFontSize),+ .font: typography.bodyFont,.foregroundColor: NSColor.secondaryLabelColor,.paragraphStyle: style,]}- private static func responseAttributes() -> [NSAttributedString.Key: Any] {+ private func responseAttributes() -> [NSAttributedString.Key: Any] {let style = NSMutableParagraphStyle()- style.lineSpacing = 3- style.paragraphSpacing = 6+ style.lineSpacing = typography.scaled(3)+ style.paragraphSpacing = typography.scaled(6)return [- .font: NSFont.systemFont(ofSize: NSFont.systemFontSize),+ .font: typography.bodyFont,.foregroundColor: NSColor.labelColor,.paragraphStyle: style,]}- private static func prefillPlaceholderAttributes() -> [NSAttributedString.Key: Any] {+ private func prefillPlaceholderAttributes() -> [NSAttributedString.Key: Any] {var attributes = responseAttributes()attributes[.foregroundColor] = NSColor.secondaryLabelColorreturn attributes@@ -1030,6 +1036,52 @@ extension Array {extension InstructionTranscriptDocumentController {+ /// Replays the current presentation once, without inventing a new run or+ /// finalizing its open block. Ordinary token updates retain their caches.+ @discardableResult+ public func refreshTypography(+ _ typography: ConversationTypography,+ storage: NSMutableAttributedString,+ planner: inout TranscriptSyncPlanner,+ input: TranscriptSyncPlanner.Input,+ promptPrefix: NSAttributedString,+ renderer: (any TranscriptBlockRendering)? = nil,+ drawPair: (Int) -> Void+ ) -> UpdateResult {+ guard typography != self.typography else {+ return UpdateResult(mutation: .none, assistantRange: assistantRange)+ }+ let old = storage.string as NSString+ let currentPrompt = prompt+ let currentResponse = response+ let prefixIdentifier = promptPrefixIdentifier+ let terminal = isFinalized+ let placeholder = showsPrefillPlaceholder+ let dots = prefillDotCount+ self.typography = typography+ self.renderer = renderer ?? ResponseMarkdownRenderer(+ typography: typography, environment: environment)+ // resetTranscript deliberately retains this cache for ordinary replay.+ // At a new size, every cached attributed run is stale.+ progressive = ProgressiveState()+ planner = TranscriptSyncPlanner()+ storage.beginEditing()+ defer { storage.endEditing() }+ synchronizeHistory(storage: storage, planner: &planner, input: input,+ drawPair: drawPair)+ synchronize(storage: storage, prompt: currentPrompt, response: currentResponse,+ isTerminal: terminal, showsPrefillPlaceholder: placeholder,+ promptPrefix: promptPrefix, promptPrefixIdentifier: prefixIdentifier)+ if placeholder {+ for _ in 0..<dots { advancePrefillAnimation(storage: storage) }+ }+ return UpdateResult(+ mutation: .rebuilt, assistantRange: assistantRange,+ replaced: ReplacedRange.differing(+ previous: NSRange(location: 0, length: old.length),+ old: old, new: storage.string as NSString))+ }+/// Execute history updates as one storage edit before the new live turn./// The view supplies cached image prefixes without moving image loading here.@discardableResultdiff --git a/Sources/TurboFieldfareApp/MacPresentation/PromptEditorTypography.swift b/Sources/TurboFieldfareApp/MacPresentation/PromptEditorTypography.swiftnew file mode 100644index 00000000..73caf479--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/PromptEditorTypography.swift@@ -0,0 +1,32 @@+import AppKit++@MainActor+open class PromptEditorTextView: NSTextView {+ public var typography = ConversationTypography() {+ didSet { applyTypography() }+ }++ open override func unmarkText() {+ super.unmarkText()+ applyTypography()+ }++ open override func insertText(_ insertString: Any, replacementRange: NSRange) {+ super.insertText(insertString, replacementRange: replacementRange)+ applyTypography()+ }++ /// Changing the backing string to restyle it would lose undo and marked+ /// input. AppKit owns those; typography only changes its font attributes.+ @discardableResult+ func applyTypography() -> Bool {+ guard !hasMarkedText() else { return false }+ let font = typography.bodyFont+ guard self.font != font else { return false }+ let ranges = selectedRanges+ self.font = font+ typingAttributes[.font] = font+ selectedRanges = ranges+ return true+ }+}diff --git a/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swift b/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swiftindex 9e9a3637..3da45992 100644--- a/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swift+++ b/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swift@@ -79,13 +79,16 @@ public struct ResponseMarkdownRenderer: TranscriptBlockRendering {let block: Block}+ private let typography: ConversationTypographyprivate let mathEnabled: Boolprivate let typesetter: any MathTypesettingpublic init(+ typography: ConversationTypography = .init(),environment: [String: String] = ProcessInfo.processInfo.environment,typesetter: any MathTypesetting = SwiftMathTypesetter()) {+ self.typography = typographymathEnabled = environment["TURBO_FIELDFARE_DISABLE_MATH"] != "1"self.typesetter = typesetter}@@ -129,7 +132,7 @@ public struct ResponseMarkdownRenderer: TranscriptBlockRendering {})let output = NSMutableAttributedString()- let decoration = BlockDecoration()+ let decoration = BlockDecoration(typography: typography)var previousBlock: Block?var index = 0while index < items.count {@@ -244,7 +247,7 @@ public struct ResponseMarkdownRenderer: TranscriptBlockRendering {let alone = blockShaped && Self.isAloneInParagraph(output, sentinel: sentinel)let mode: MathRenderMode = span.mode == .display || alone ? .display : .inlinelet font = attributes[.font] as? NSFont- ?? NSFont.systemFont(ofSize: NSFont.systemFontSize)+ ?? typography.bodyFontlet tint = attributes[.foregroundColor] as? NSColor ?? .labelColorguard let render = typesetter.render(latex: MathCommandNormalizer.normalize(span.latex),@@ -748,7 +751,7 @@ public struct ResponseMarkdownRenderer: TranscriptBlockRendering {decoration: BlockDecoration) -> NSParagraphStyle {let style = NSMutableParagraphStyle()- style.lineSpacing = 3+ style.lineSpacing = typography.scaled(3)style.paragraphSpacing = 0style.alignment = cell.alignmentstyle.textBlocks = [decoration.tableCell(@@ -780,12 +783,12 @@ public struct ResponseMarkdownRenderer: TranscriptBlockRendering {/// one cell when they carry the same block object, so a fresh dictionary/// per tick would draw a new box per line.public func streamingCodeAttributes() -> [NSAttributedString.Key: Any] {- codeAttributes(cell: BlockDecoration.codeCell())+ codeAttributes(cell: BlockDecoration.codeCell(typography: typography))}private func codeAttributes(cell: NSTextTableBlock) -> [NSAttributedString.Key: Any] {let style = NSMutableParagraphStyle()- style.lineSpacing = 2+ style.lineSpacing = typography.scaled(2)style.paragraphSpacing = 0style.textBlocks = [cell]return [@@ -869,7 +872,7 @@ public struct ResponseMarkdownRenderer: TranscriptBlockRendering {private func baseAttributes() -> [NSAttributedString.Key: Any] {[- .font: NSFont.systemFont(ofSize: NSFont.systemFontSize),+ .font: typography.bodyFont,.foregroundColor: NSColor.labelColor,.paragraphStyle: paragraphStyle(for: .paragraph),]@@ -890,13 +893,13 @@ public struct ResponseMarkdownRenderer: TranscriptBlockRendering {var size: CGFloatvar baseWeight: NSFont.Weightif monospaced {- size = NSFont.systemFontSize - 0.5+ size = typography.scaled(NSFont.systemFontSize - 0.5)baseWeight = .regular} else if case .heading(let level) = block {- size = max(NSFont.systemFontSize + 1, 22 - CGFloat(level - 1) * 2)+ size = typography.scaled(max(NSFont.systemFontSize + 1, 22 - CGFloat(level - 1) * 2))baseWeight = .semibold} else {- size = NSFont.systemFontSize+ size = typography.bodySizebaseWeight = .regular}if html.scriptDepth > 0 {@@ -916,28 +919,28 @@ public struct ResponseMarkdownRenderer: TranscriptBlockRendering {private func paragraphStyle(for block: BlockKind) -> NSParagraphStyle {let style = NSMutableParagraphStyle()- style.lineSpacing = 3- style.paragraphSpacing = 6+ style.lineSpacing = typography.scaled(3)+ style.paragraphSpacing = typography.scaled(6)switch block {case .heading:- style.paragraphSpacingBefore = 8- style.paragraphSpacing = 4+ style.paragraphSpacingBefore = typography.scaled(8)+ style.paragraphSpacing = typography.scaled(4)case .quote:- style.firstLineHeadIndent = 4- style.headIndent = 20- style.tailIndent = -8- style.tabStops = [NSTextTab(textAlignment: .left, location: 16)]+ style.firstLineHeadIndent = typography.scaled(4)+ style.headIndent = typography.scaled(20)+ style.tailIndent = typography.scaled(-8)+ style.tabStops = [NSTextTab(textAlignment: .left, location: typography.scaled(16))]case .unorderedList(let indent), .orderedList(_, let indent):- let base = CGFloat(22 + indent * 18)- style.firstLineHeadIndent = CGFloat(indent * 18)+ let base = typography.scaled(CGFloat(22 + indent * 18))+ style.firstLineHeadIndent = typography.scaled(CGFloat(indent * 18))style.headIndent = basestyle.tabStops = [NSTextTab(textAlignment: .left, location: base)]- style.paragraphSpacing = 2+ style.paragraphSpacing = typography.scaled(2)case .thematicBreak:style.alignment = .center- style.paragraphSpacingBefore = 8- style.paragraphSpacing = 8+ style.paragraphSpacingBefore = typography.scaled(8)+ style.paragraphSpacing = typography.scaled(8)// A table cell's style comes from `tableCellStyle`, which owns the// text block the cell is drawn in.case .paragraph, .code, .tableCell:@@ -1103,6 +1106,12 @@ extension ResponseMarkdownRenderer {/// styles that reference it.@MainActorprivate final class BlockDecoration {+ private let typography: ConversationTypography++ init(typography: ConversationTypography) {+ self.typography = typography+ }+private var codeCells: [Int: NSTextTableBlock] = [:]private var tables: [Int: NSTextTable] = [:]private var tableCells: [TableCellKey: NSTextTableBlock] = [:]@@ -1113,7 +1122,7 @@ private final class BlockDecoration {let column: Int}- static func codeCell() -> NSTextTableBlock {+ static func codeCell(typography: ConversationTypography) -> NSTextTableBlock {let table = NSTextTable()table.numberOfColumns = 1table.collapsesBorders = true@@ -1124,7 +1133,7 @@ private final class BlockDecoration {startingColumn: 0,columnSpan: 1)cell.setContentWidth(100, type: .percentageValueType)- cell.setWidth(8, type: .absoluteValueType, for: .padding)+ cell.setWidth(typography.scaled(8), type: .absoluteValueType, for: .padding)cell.setWidth(1, type: .absoluteValueType, for: .border)cell.setBorderColor(.separatorColor)cell.backgroundColor = .quaternarySystemFill@@ -1133,7 +1142,7 @@ private final class BlockDecoration {func codeCell(for identity: Int) -> NSTextTableBlock {if let existing = codeCells[identity] { return existing }- let cell = Self.codeCell()+ let cell = Self.codeCell(typography: typography)codeCells[identity] = cellreturn cell}@@ -1154,7 +1163,7 @@ private final class BlockDecoration {rowSpan: 1,startingColumn: column,columnSpan: 1)- cell.setWidth(6, type: .absoluteValueType, for: .padding)+ cell.setWidth(typography.scaled(6), type: .absoluteValueType, for: .padding)cell.setWidth(1, type: .absoluteValueType, for: .border)cell.setBorderColor(.separatorColor)if isHeader { cell.backgroundColor = .quaternarySystemFill }diff --git a/Sources/TurboFieldfareApp/MacPresentation/TranscriptReadingPosition.swift b/Sources/TurboFieldfareApp/MacPresentation/TranscriptReadingPosition.swiftnew file mode 100644index 00000000..e6199087--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/TranscriptReadingPosition.swift@@ -0,0 +1,78 @@+import AppKit++public final class TranscriptScrollView: NSScrollView {+ public var didRestoreReadingPosition: (() -> Void)?++ public override func resizeSubviews(withOldSize oldSize: NSSize) {+ guard let textView = documentView as? NSTextView else {+ super.resizeSubviews(withOldSize: oldSize)+ return+ }+ // SwiftUI measures the composer after typography reflows the text.+ // Keep the anchor through that later viewport resize as well.+ let position = TranscriptReadingPosition(+ textView: textView, scrollView: self, followsPrefill: false)+ super.resizeSubviews(withOldSize: oldSize)+ position.restore(textView: textView, scrollView: self, replacing: nil)+ didRestoreReadingPosition?()+ }+}++/// A character anchor survives reflow; the old pixel scroll offset does not.+@MainActor+public struct TranscriptReadingPosition {+ private let selections: [NSRange]+ private let character: Int+ private let lineOffset: CGFloat+ private let followsBottom: Bool++ public init(textView: NSTextView, scrollView: NSScrollView, followsPrefill: Bool) {+ selections = textView.selectedRanges.map(\.rangeValue)+ let visible = scrollView.contentView.bounds+ followsBottom = followsPrefill || visible.maxY >= textView.bounds.maxY - 24+ if let manager = textView.layoutManager, let container = textView.textContainer,+ !textView.string.isEmpty {+ manager.ensureLayout(for: container)+ let origin = textView.textContainerOrigin+ let glyph = manager.glyphIndex(+ for: NSPoint(x: max(0, visible.minX - origin.x),+ y: max(0, visible.minY - origin.y)), in: container)+ character = manager.characterIndexForGlyph(at: glyph)+ lineOffset = visible.minY - origin.y+ - manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil).minY+ } else {+ character = 0+ lineOffset = 0+ }+ }++ public func restore(+ textView: NSTextView, scrollView: NSScrollView,+ replacing: InstructionTranscriptDocumentController.ReplacedRange?+ ) {+ let count = (textView.string as NSString).length+ func adjusted(_ ranges: [NSRange]) -> [NSRange] {+ let mapped = replacing.map {+ InstructionTranscriptDocumentController.adjustedRanges(+ ranges, replacing: $0.previous, newLength: $0.length)+ } ?? ranges+ return InstructionTranscriptDocumentController.clampedRanges(mapped, toLength: count)+ }+ textView.selectedRanges = adjusted(selections).map(NSValue.init(range:))+ guard let manager = textView.layoutManager, let container = textView.textContainer else { return }+ manager.ensureLayout(for: container)+ if followsBottom {+ textView.scrollToEndOfDocument(nil)+ } else if count > 0 {+ let index = min(adjusted([NSRange(location: character, length: 0)])[0].location,+ count - 1)+ let glyph = manager.glyphIndexForCharacter(at: index)+ let y = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil).minY+ + textView.textContainerOrigin.y + lineOffset+ let maximum = max(0, textView.bounds.height - scrollView.contentView.bounds.height)+ scrollView.contentView.scroll(to: NSPoint(+ x: scrollView.contentView.bounds.minX, y: min(max(y, 0), maximum)))+ scrollView.reflectScrolledClipView(scrollView.contentView)+ }+ }+}diff --git a/Sources/TurboFieldfareApp/MacPresentation/TranscriptSyncPlanner.swift b/Sources/TurboFieldfareApp/MacPresentation/TranscriptSyncPlanner.swiftindex ac4b8867..7eb79164 100644--- a/Sources/TurboFieldfareApp/MacPresentation/TranscriptSyncPlanner.swift+++ b/Sources/TurboFieldfareApp/MacPresentation/TranscriptSyncPlanner.swift@@ -65,19 +65,21 @@ public struct TranscriptSyncPlanner: Equatable, Sendable {renderedHistory = input.historyCount} else {while renderedHistory < input.historyCount {+ if input.contextBreak == renderedHistory, !renderedContextBreak {+ steps.append(.appendContextBreak)+ }steps.append(.drawPair(index: renderedHistory))renderedHistory += 1}}}- // After the history, not before it. Drawing the break first put it above- // the very turns it is supposed to sit under, and on the pass that- // resets for a new epoch it was skipped entirely — leaving archived- // turns on screen unmarked until some unrelated change forced another- // pass.+ // Replay can include turns on both sides of the boundary; the loop+ // inserts an interior break before its next pair. End boundaries and+ // a break whose previous append was refused still need an attempt here.if let contextBreak = input.contextBreak,!renderedContextBreak,+ !steps.contains(.appendContextBreak),renderedHistory >= contextBreak {steps.append(.appendContextBreak)}diff --git a/Tests/TurboFieldfareApp/Core/Configuration/AppTextSizeTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/AppTextSizeTests.swiftnew file mode 100644index 00000000..1c460af8--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Configuration/AppTextSizeTests.swift@@ -0,0 +1,113 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++@Suite struct AppTextSizeTests {+ @Test func menuHasExactlyTheFiveAgreedPresets() {+ #expect(AppTextSize.allCases.map(\.rawValue) == [100, 125, 150, 175, 200])+ #expect(AppTextSize.allCases.map(\.label) == ["100%", "125%", "150%", "175%", "200%"])+ }++ @Test(arguments: AppTextSize.allCases)+ func presetsRoundTrip(_ size: AppTextSize) throws {+ let settings = MacAppSettings(textSize: size)+ #expect(try JSONDecoder().decode(MacAppSettings.self,+ from: JSONEncoder().encode(settings)) == settings)+ #expect(size.scale == Double(size.rawValue) / 100)+ }++ // Throwing this appearance field into the store's recovery path used to+ // delete the settings file, resetting unrelated context/sampling choices.+ @Test(arguments: ["110", "999", "null", "\"private arbitrary string\"", "{}", "1.5"])+ func malformedAppearanceKeepsOtherSettingsAndFile(_ value: String) throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: root) }+ let directory = root.appendingPathComponent("model.gturbo")+ let settings = MacAppSettings(contextTokens: 4096, temperature: 0.7,+ showPromptExamples: false, textSize: .largest)+ try MacAppSettingsFileStore.save(settings, forModelDirectory: directory)+ let file = MacAppSettingsFileStore.fileURL(forModelDirectory: directory)+ let encoded = try #require(String(data: JSONEncoder().encode(settings), encoding: .utf8))+ let broken = Data(encoded.replacingOccurrences(of: "\"textSize\":200",+ with: "\"textSize\":\(value)").utf8)+ #expect(broken != Data(encoded.utf8))+ try broken.write(to: file)+ let read = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: directory)+ #expect(read.textSize == .standard)+ #expect(read.contextTokens == 4096)+ #expect(read.temperature == 0.7)+ #expect(!read.showPromptExamples)+ #expect(try Data(contentsOf: file) == broken)+ }++ @Test func absentFieldIsBackwardCompatible() throws {+ let original = MacAppSettings(contextTokens: 4096)+ var object = try #require(JSONSerialization.jsonObject(+ with: JSONEncoder().encode(original)) as? [String: Any])+ object.removeValue(forKey: "textSize")+ let decoded = try JSONDecoder().decode(MacAppSettings.self,+ from: JSONSerialization.data(withJSONObject: object))+ #expect(decoded == original)+ #expect(decoded.version == MacAppSettings.currentVersion)+ }++ @MainActor @Test func selectionPersistsBeforeSendAndFollowsModelLocation() throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: root) }+ let first = root.appendingPathComponent("first/model.gturbo")+ let second = root.appendingPathComponent("second/model.gturbo")+ try MacAppSettingsFileStore.save(.init(textSize: .large), forModelDirectory: second)+ let model = AppModel(modelDirectory: first, client: MockLifecycleInferenceClient(),+ settingsPersistenceEnabled: true)+ model.setTextSize(.largest)+ model.setTextSize(.largest)+ #expect(MacAppSettingsFileStore.loadOrCreate(forModelDirectory: first).textSize == .largest)+ let reopened = AppModel(modelDirectory: first, client: MockLifecycleInferenceClient(),+ settingsPersistenceEnabled: true)+ #expect(reopened.textSize == .largest)+ model.setModelURL(second)+ #expect(model.textSize == .large)+ model.setModelURL(first)+ #expect(model.textSize == .largest)+ }++ @MainActor @Test func appearanceDoesNotInvalidateLoadedSessionOrDraft() throws {+ let directory = try makeCompleteModelInstall("text-size")+ defer { try? FileManager.default.removeItem(at: directory) }+ let client = MockLifecycleInferenceClient()+ let model = AppModel(modelDirectory: directory, client: client)+ model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))+ model.promptText = "Preserve my draft"+ let key = model.loadedRuntimeKey+ let epoch = model.displayedTranscriptID+ let conversationEpoch = model.conversation.epoch+ for size in AppTextSize.allCases {+ model.setTextSize(size)+ #expect(model.loadedRuntimeKey == key)+ #expect(model.displayedTranscriptID == epoch)+ #expect(model.conversation.epoch == conversationEpoch)+ #expect(model.promptText == "Preserve my draft")+ #expect(model.canRun)+ #expect(!model.hasStaleLoadedRuntime)+ #expect(client.ensureLoadedCallCount() == 0)+ }+ }++ @MainActor @Test func sizeCanChangeDuringMockStreamingWithoutCancelling() async {+ let client = MockInferenceClient(response: "one two three four", tokenDelayNanos: 20_000_000)+ client.prefillSteps = 0+ let model = AppModel(client: client)+ let directory = FileManager.default.temporaryDirectory+ model.modelPathText = directory.path+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 0)+ model.promptText = "go"+ model.send()+ await SendWaiting.generationStarts(model)+ model.setTextSize(.largest)+ #expect(model.textSize == .largest)+ #expect(model.isRunning)+ await SendWaiting.turnEnds(model)+ #expect(model.outputText.contains("four"))+ #expect(model.error == nil)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swiftindex f876e0ff..1881747a 100644--- a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift+++ b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift@@ -109,21 +109,19 @@ import Testing#expect(decoded.version == MacAppSettings.currentVersion)}- @Test func selectedConversationRoundTripsAndIsAdditive() throws {- let id = UUID()- let initial = MacAppSettings(selectedConversationID: id)+ @Test(arguments: ["null", "42", "\"invalid\"", "\"00000000-0000-0000-0000-000000000001\""])+ func obsoleteSelectionIsIgnoredWithoutResettingPreferences(_ selection: String) throws {+ let initial = MacAppSettings(contextTokens: 4_096, textSize: .largest, sidebarVisible: false)+ var json = try #require(JSONSerialization.jsonObject(+ with: JSONEncoder().encode(initial)) as? [String: Any])+ json["selectedConversationID"] = try JSONSerialization.jsonObject(+ with: Data(selection.utf8), options: .fragmentsAllowed)let decoded = try JSONDecoder().decode(- MacAppSettings.self, from: try JSONEncoder().encode(initial))- #expect(decoded.selectedConversationID == id)-- let oldJSON = """- {"version":2,"contextTokens":8192,"expertCacheSlots":16,- "temperature":0.2,"topKEnabled":true,"topK":64,"topPEnabled":true,- "topP":0.95,"prefillEnabled":true}- """- let old = try JSONDecoder().decode(- MacAppSettings.self, from: Data(oldJSON.utf8))- #expect(old.selectedConversationID == nil)+ MacAppSettings.self, from: JSONSerialization.data(withJSONObject: json))+ #expect(decoded == initial)+ let encoded = try #require(JSONSerialization.jsonObject(+ with: JSONEncoder().encode(decoded)) as? [String: Any])+ #expect(encoded["selectedConversationID"] == nil)}@MainActor@@ -139,24 +137,6 @@ import Testing#expect(saved.contextTokens == 4_096)}- @MainActor- @Test func unknownRestoredSelectionIsClearedFromSettings() async throws {- let root = try makeTemporaryRoot()- defer { try? FileManager.default.removeItem(at: root) }- let directory = root.appendingPathComponent("model.gturbo", isDirectory: true)- try MacAppSettingsFileStore.save(- MacAppSettings(selectedConversationID: UUID()),- forModelDirectory: directory)-- let model = AppModel(modelDirectory: directory, settingsPersistenceEnabled: true)- try await waitUntil {- MacAppSettingsFileStore.loadOrCreate(- forModelDirectory: directory).selectedConversationID == nil- }-- #expect(model.history.selection == nil)- }-/// The Inspector's visibility is remembered on the same terms as the/// sidebar's: additive, no version bump, and a file that predates it opens/// with the panel shown rather than with the window missing a side.diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelHistoryTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelHistoryTests.swiftindex d4f73d3d..df387131 100644--- a/Tests/TurboFieldfareApp/Core/State/AppModelHistoryTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppModelHistoryTests.swift@@ -1188,7 +1188,7 @@ import TurboFieldfare}@MainActor- @Test func relaunchRestoresTheSelectedTranscriptWhileSidebarStaysHidden() async throws {+ @Test func relaunchStartsEmptyAndSavedChatOpensOnlyWhenSelected() async throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent("history-selection-\(UUID())", isDirectory: true)defer { try? FileManager.default.removeItem(at: root) }@@ -1216,6 +1216,14 @@ import TurboFieldfarefirst = niltry await Task.sleep(for: .milliseconds(20))+ // Older builds persisted the selected row. It must not reopen a chat+ // on launch, even when the sidebar is hidden.+ let settingsURL = MacAppSettingsFileStore.fileURL(forModelDirectory: directory)+ var settings = try #require(JSONSerialization.jsonObject(+ with: Data(contentsOf: settingsURL)) as? [String: Any])+ settings["selectedConversationID"] = selected.uuidString+ try JSONSerialization.data(withJSONObject: settings).write(to: settingsURL)+let second = AppModel(modelDirectory: directory,client: FakeInferenceClient(eventDelay: .milliseconds(1)),@@ -1223,9 +1231,18 @@ import TurboFieldfaresecond.conversationIdentity = Self.identitysecond.installationStatus = .completetry await second.waitForHistory(count: 1)- try await waitUntil { await second.screen.document != nil }+ await second.refreshHistory()#expect(!second.isSidebarVisible)+ #expect(second.history.selection == nil)+ #expect(second.screen.document == nil)+ #expect(second.transcriptHistory.isEmpty)+ #expect(second.promptText.isEmpty)+ #expect(second.outputText.isEmpty)+ #expect(second.history.entry(selected) != nil)++ second.openConversation(id: selected)+ try await waitUntil { await second.screen.document != nil }#expect(second.history.selection == selected)#expect(second.transcriptHistory.map(\.user.text) == ["remember this"])}diff --git a/Tests/TurboFieldfareApp/Core/Support/HistoryHarness.swift b/Tests/TurboFieldfareApp/Core/Support/HistoryHarness.swiftindex 5778af3f..ba3db1d7 100644--- a/Tests/TurboFieldfareApp/Core/Support/HistoryHarness.swift+++ b/Tests/TurboFieldfareApp/Core/Support/HistoryHarness.swift@@ -138,12 +138,6 @@ final class HistoryHarness {forceLogitsHead: true) { _ in }try await waitForWritableStore()try await settle("start")- if let restored = reference.reading {- try await settle("restore selection") {- model.screen.conversationID == restored- && model.screen.document != nil- }- }}private func waitForWritableStore() async throws {diff --git a/Tests/TurboFieldfareApp/Core/Support/HistoryReferenceModel.swift b/Tests/TurboFieldfareApp/Core/Support/HistoryReferenceModel.swiftindex a9f5dba1..fb1f2c04 100644--- a/Tests/TurboFieldfareApp/Core/Support/HistoryReferenceModel.swift+++ b/Tests/TurboFieldfareApp/Core/Support/HistoryReferenceModel.swift@@ -167,13 +167,11 @@ struct HistoryReferenceModel {stoppedTurnOnScreen = nil}- /// Quitting and starting again. The store and selected row survive; no KV- /// does, so the selection returns as a stored copy awaiting replay.+ /// Relaunch keeps saved conversations and preferences, but starts an empty chat.mutating func relaunch() {- let selected = reading ?? heldheld = nilheldIsInKV = false- reading = selected.flatMap { conversations[$0] == nil ? nil : $0 }+ reading = niloutOfContext = []stoppedTurnOnScreen = nilmaxContextTokens = persistedContextTokensdiff --git a/Tests/TurboFieldfareApp/MacPresentation/ConversationTypographyTests.swift b/Tests/TurboFieldfareApp/MacPresentation/ConversationTypographyTests.swiftnew file mode 100644index 00000000..67a404af--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/ConversationTypographyTests.swift@@ -0,0 +1,70 @@+import AppKit+import Testing+import TurboFieldfareAppCore+@testable import TurboFieldfareMacPresentation++@MainActor @Suite struct ConversationTypographyTests {+ @Test func compactWindowKeepsRoomForTranscriptAtLargestSize() {+ let typography = ConversationTypography(.largest)+ #expect(typography.editorHeight(showsExamples: false, availableHeight: 500) == 100)+ #expect(typography.editorHeight(showsExamples: true, availableHeight: 500) == 92)+ #expect(typography.editorHeight(showsExamples: false, availableHeight: 300) == 80)+ #expect(typography.editorHeight(showsExamples: false, availableHeight: 1000) == 168)+ #expect(ConversationTypography().editorHeight(showsExamples: false, availableHeight: 500) == 84)+ }++ @Test(arguments: AppTextSize.allCases)+ func scalesEveryRunWithoutChangingCharactersOrTraits(_ size: AppTextSize) throws {+ let source = """+ # Heading++ Body **bold** *italic* `inline` <sup>script</sup> [link](https://example.com).++ > Quote++ - Item+ - Nested++ ```swift+ let value = 1+ ```++ | Name | Value |+ | --- | --- |+ | one | two |+ """+ let baseline = ResponseMarkdownRenderer().render(source).attributedString+ let scaled = ResponseMarkdownRenderer(typography: .init(size)).render(source).attributedString+ #expect(baseline.string == scaled.string)+ baseline.enumerateAttributes(in: NSRange(location: 0, length: baseline.length)) { attrs, range, _ in+ guard let baseFont = attrs[.font] as? NSFont else { return }+ let new = scaled.attributes(at: range.location, effectiveRange: nil)+ let font = new[.font] as? NSFont+ #expect(font?.pointSize == baseFont.pointSize * CGFloat(size.scale))+ #expect(font?.fontDescriptor.symbolicTraits == baseFont.fontDescriptor.symbolicTraits)+ guard let before = attrs[.paragraphStyle] as? NSParagraphStyle,+ let after = new[.paragraphStyle] as? NSParagraphStyle else { return }+ #expect(after.lineSpacing == before.lineSpacing * CGFloat(size.scale))+ #expect(after.headIndent == before.headIndent * CGFloat(size.scale))+ #expect(after.paragraphSpacing == before.paragraphSpacing * CGFloat(size.scale))+ for (a, b) in zip(before.textBlocks, after.textBlocks) {+ #expect(b.width(for: .padding, edge: .minX)+ == a.width(for: .padding, edge: .minX) * CGFloat(size.scale))+ }+ }+ }++ @Test(arguments: AppTextSize.allCases)+ func mathAndRawFallbackUseChosenBodySize(_ size: AppTextSize) throws {+ let fake = FakeMathTypesetter()+ let renderer = ResponseMarkdownRenderer(typography: .init(size), typesetter: fake)+ _ = renderer.render("Equation $x^2$ and $$y^2$$.")+ #expect(!fake.calls.isEmpty)+ #expect(fake.calls.allSatisfy { $0.fontSize == NSFont.systemFontSize * CGFloat(size.scale) })+ let fallback = renderer.render("<div>unsupported block</div>")+ #expect(fallback.usedFallback)+ let font = try #require(fallback.attributedString.attribute(.font, at: 0,+ effectiveRange: nil) as? NSFont)+ #expect(font.pointSize == NSFont.systemFontSize * CGFloat(size.scale))+ }+}diff --git a/Tests/TurboFieldfareApp/MacPresentation/EmptyConversationLayoutTests.swift b/Tests/TurboFieldfareApp/MacPresentation/EmptyConversationLayoutTests.swiftnew file mode 100644index 00000000..f8483c62--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/EmptyConversationLayoutTests.swift@@ -0,0 +1,28 @@+import Foundation+import Testing+@testable import TurboFieldfareMacPresentation++@Suite struct EmptyConversationLayoutTests {+ @Test func compactPlaceholderReservesRoomForItsModelAction() {+ // Centering only the icon put the load button behind the examples at 200%.+ let bounds = CGRect(x: 0, y: 20, width: 600, height: 140)+ let center = EmptyConversationLayout.iconCenterY(+ in: bounds, iconHeight: 32, contentHeight: 64, spacing: 8)+ #expect(center == 72)+ #expect(center + 16 + 8 + 64 == bounds.maxY)+ }++ @Test func roomyPlaceholderKeepsItsCenteredIcon() {+ #expect(EmptyConversationLayout.iconCenterY(+ in: CGRect(x: 0, y: 20, width: 600, height: 300),+ iconHeight: 32, contentHeight: 64, spacing: 8) == 170)+ }++ @Test func exactFitAndUndersizedAreasKeepTheIconWithinTheTopEdge() {+ for height: CGFloat in [104, 60, 0] {+ #expect(EmptyConversationLayout.iconCenterY(+ in: CGRect(x: 0, y: 20, width: 600, height: height),+ iconHeight: 32, contentHeight: 64, spacing: 8) == 36)+ }+ }+}diff --git a/Tests/TurboFieldfareApp/MacPresentation/PromptEditorTypographyTests.swift b/Tests/TurboFieldfareApp/MacPresentation/PromptEditorTypographyTests.swiftnew file mode 100644index 00000000..9ee55099--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/PromptEditorTypographyTests.swift@@ -0,0 +1,57 @@+import AppKit+import Testing+import TurboFieldfareAppCore+@testable import TurboFieldfareMacPresentation++@MainActor @Suite struct PromptEditorTypographyTests {+ @Test func changingSizePreservesStringSelectionAndUndo() throws {+ let editor = PromptEditorTextView()+ editor.isRichText = false+ editor.allowsUndo = true+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 200),+ styleMask: [.titled], backing: .buffered, defer: false)+ window.contentView = editor+ window.makeFirstResponder(editor)+ editor.typography = .init()+ editor.insertText("A cafe\u{301} draft", replacementRange: NSRange(location: 0, length: 0))+ editor.breakUndoCoalescing()+ let text = editor.string+ let range = NSRange(location: 2, length: 5)+ editor.setSelectedRange(range)+ let undo = try #require(editor.undoManager)+ #expect(undo.canUndo)+ for size in AppTextSize.allCases + [.standard] {+ editor.typography = .init(size)+ #expect(editor.string == text)+ #expect(editor.selectedRange() == range)+ #expect(editor.font?.pointSize == NSFont.systemFontSize * CGFloat(size.scale))+ }+ undo.undo()+ #expect(editor.string.isEmpty)+ }++ @Test func unmarkWithoutEditingAppliesDeferredSize() {+ let editor = PromptEditorTextView()+ editor.isRichText = false+ editor.typography = .init()+ editor.setMarkedText("draft", selectedRange: NSRange(location: 5, length: 0),+ replacementRange: NSRange(location: 0, length: 0))+ #expect(editor.hasMarkedText())+ editor.typography = .init(.largest)+ #expect(editor.hasMarkedText())+ #expect(editor.font?.pointSize == NSFont.systemFontSize)+ editor.unmarkText()+ #expect(editor.string == "draft")+ #expect(!editor.hasMarkedText())+ #expect(editor.font?.pointSize == NSFont.systemFontSize * 2)+ }++ @Test func emptyEditorTypesAtNewSizeAndSameSizeIsNoOp() {+ let editor = PromptEditorTextView()+ editor.typography = .init(.larger)+ #expect(!editor.applyTypography())+ editor.insertText("next", replacementRange: NSRange(location: 0, length: 0))+ #expect(editor.font?.pointSize == NSFont.systemFontSize * 1.5)+ #expect((editor.typingAttributes[.font] as? NSFont)?.pointSize == NSFont.systemFontSize * 1.5)+ }+}diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptTypographyTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptTypographyTests.swiftnew file mode 100644index 00000000..e7f37eb7--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptTypographyTests.swift@@ -0,0 +1,287 @@+import AppKit+import Testing+import TurboFieldfareAppCore+@testable import TurboFieldfareMacPresentation++@MainActor @Suite struct TranscriptTypographyTests {+ private func input(_ epoch: UUID, history: Int, boundary: Int? = nil) -> TranscriptSyncPlanner.Input {+ .init(epoch: epoch, historyCount: history, contextBreak: boundary,+ startedNewRun: false, firstSynchronize: true)+ }++ // A renderer-only size change leaves frozen turns and cached progressive+ // blocks at their old size, even though subsequent tokens look correct.+ @Test(arguments: AppTextSize.allCases)+ func sealedHistoryAndOpenFenceResizeThenContinue(_ size: AppTextSize) throws {+ let controller = InstructionTranscriptDocumentController()+ let storage = NSMutableAttributedString()+ var planner = TranscriptSyncPlanner()+ let state = input(UUID(), history: 2, boundary: 1)+ func draw(_ index: Int) {+ controller.synchronize(storage: storage, prompt: "question \(index)",+ response: "historic \(index)", isTerminal: true)+ }+ controller.synchronizeHistory(storage: storage, planner: &planner, input: state, drawPair: draw)+ let open = "Finished paragraph.\n\n```swift\nlet a = 1"+ controller.synchronize(storage: storage, prompt: "live", response: open, isTerminal: false)+ let baseline = storage.copy() as! NSAttributedString+ let spy = CountingTypographyRenderer(.init(size))+ let update = controller.refreshTypography(+ .init(size), storage: storage, planner: &planner, input: state,+ promptPrefix: NSAttributedString(), renderer: spy, drawPair: draw)+ #expect(update.replaced == nil)+ #expect(storage.string == baseline.string)+ #expect(!controller.isFinalized)+ #expect(planner.renderedHistory == 2)+ #expect(planner.renderedContextBreak)+ baseline.enumerateAttribute(.font, in: NSRange(location: 0, length: baseline.length)) { value, range, _ in+ guard let font = value as? NSFont else { return }+ let scaled = storage.attribute(.font, at: range.location, effectiveRange: nil) as? NSFont+ #expect(scaled?.pointSize == font.pointSize * CGFloat(size.scale))+ }+ let calls = spy.sources.count+ let noChange = controller.refreshTypography(+ .init(size), storage: storage, planner: &planner, input: state,+ promptPrefix: NSAttributedString(), drawPair: { _ in Issue.record("same size replayed history") })+ #expect(noChange.mutation == .none)+ #expect(spy.sources.count == calls)+ let historicCalls = spy.sources.filter { $0.contains("historic") }.count+ controller.synchronize(storage: storage, prompt: "live", response: open + "\nlet b = 2",+ isTerminal: false)+ controller.synchronize(storage: storage, prompt: "live", response: open + "\nlet b = 2\n```",+ isTerminal: true)+ #expect(storage.string.contains("let b = 2"))+ #expect(controller.isFinalized)+ #expect(spy.sources.filter { $0.contains("historic") }.count == historicCalls)+ #expect(controller.answer(at: 0) == "historic 0")+ #expect(controller.answer(at: (storage.string as NSString).range(of: "historic 1").location)+ == "historic 1")+ _ = controller.refreshTypography(+ .init(), storage: storage, planner: &planner, input: state,+ promptPrefix: NSAttributedString(), drawPair: draw)+ let body = (storage.string as NSString).range(of: "historic 0")+ #expect((storage.attribute(.font, at: body.location, effectiveRange: nil) as? NSFont)?.pointSize+ == NSFont.systemFontSize)+ }++ @Test(arguments: [0, 1, 3])+ func replayInsertsContextBreakAtExactBoundary(_ boundary: Int) {+ let controller = InstructionTranscriptDocumentController()+ let storage = NSMutableAttributedString()+ var planner = TranscriptSyncPlanner()+ let state = input(UUID(), history: 3, boundary: boundary)+ func draw(_ i: Int) {+ controller.synchronize(storage: storage, prompt: "Q\(i)", response: "A\(i)", isTerminal: true)+ }+ controller.synchronizeHistory(storage: storage, planner: &planner, input: state, drawPair: draw)+ for size in [AppTextSize.largest, .standard] {+ controller.refreshTypography(.init(size), storage: storage, planner: &planner, input: state,+ promptPrefix: NSAttributedString(), drawPair: draw)+ let string = storage.string as NSString+ let marker = string.range(of: "Earlier turns").location+ if boundary > 0 { #expect(marker > string.range(of: "A\(boundary - 1)").location) }+ if boundary < 3 { #expect(marker < string.range(of: "Q\(boundary)").location) }+ #expect(storage.string.components(separatedBy: "Earlier turns").count == 2)+ }+ }++ @Test(arguments: [true, false])+ func finalizedMathSelectionAndCopySurviveReflow(progressive: Bool) throws {+ let environment = ["TURBO_FIELDFARE_PROGRESSIVE_RENDER": progressive ? "1" : "0"]+ let controller = InstructionTranscriptDocumentController(environment: environment)+ let scroll = NSScrollView(frame: NSRect(x: 0, y: 0, width: 400, height: 100))+ let view = TranscriptTextView(frame: scroll.bounds)+ scroll.documentView = view+ let storage = try #require(view.textStorage)+ var planner = TranscriptSyncPlanner()+ let state = input(UUID(), history: 0)+ controller.synchronizeHistory(storage: storage, planner: &planner, input: state) { _ in }+ let answer = "Before $x^2$ after.\n\nTail cafe\u{301}."+ controller.synchronize(storage: storage, prompt: "math", response: answer, isTerminal: true)+ let baseline = storage.string+ let oldAttachment = try #require(attachments(storage).first)+ let selection = (baseline as NSString).range(of: "Before \u{fffc} after.")+ #expect(selection.location != NSNotFound)+ view.setSelectedRange(selection)+ let position = TranscriptReadingPosition(textView: view, scrollView: scroll, followsPrefill: false)+ let copied = TranscriptPlainText.string(of: storage.attributedSubstring(from: selection))+ let update = controller.refreshTypography(+ .init(.largest), storage: storage, planner: &planner, input: state,+ promptPrefix: NSAttributedString(), drawPair: { _ in })+ #expect(update.replaced == nil)+ position.restore(textView: view, scrollView: scroll, replacing: update.replaced)+ #expect(view.selectedRange() == selection)+ #expect(TranscriptPlainText.string(of: storage.attributedSubstring(from: view.selectedRange())) == copied)+ #expect(storage.string == baseline)+ #expect(controller.isFinalized)+ #expect(controller.answer(at: selection.location) == answer)+ let newAttachment = try #require(attachments(storage).first)+ #expect(newAttachment.bounds.height > oldAttachment.bounds.height)+ #expect(newAttachment.latexSource == oldAttachment.latexSource)+ }++ @Test func prefillDotsAndLatePhotoPrefixKeepChosenSize() throws {+ let controller = InstructionTranscriptDocumentController()+ let storage = NSMutableAttributedString()+ var planner = TranscriptSyncPlanner()+ let state = input(UUID(), history: 0)+ controller.synchronizeHistory(storage: storage, planner: &planner, input: state) { _ in }+ controller.synchronize(storage: storage, prompt: "look", response: "", isTerminal: false,+ showsPrefillPlaceholder: true)+ controller.advancePrefillAnimation(storage: storage)+ controller.advancePrefillAnimation(storage: storage)+ let old = storage.string+ controller.refreshTypography(.init(.largest), storage: storage, planner: &planner, input: state,+ promptPrefix: NSAttributedString(), drawPair: { _ in })+ #expect(storage.string == old)+ #expect(controller.showsPrefillPlaceholder)+ let photo = NSTextAttachment()+ photo.bounds = NSRect(x: 0, y: 0, width: 100, height: 60)+ controller.synchronize(storage: storage, prompt: "look", response: "", isTerminal: false,+ showsPrefillPlaceholder: true,+ promptPrefix: NSAttributedString(attachment: photo),+ promptPrefixIdentifier: "photo")+ #expect(photo.bounds.size == NSSize(width: 100, height: 60))+ let word = (storage.string as NSString).range(of: "look")+ #expect((storage.attribute(.font, at: word.location, effectiveRange: nil) as? NSFont)?.pointSize+ == NSFont.systemFontSize * 2)+ }++ @Test(arguments: [false, true])+ func realTextViewPreservesReadingAnchorAndSelection(atBottom: Bool) throws {+ let scroll = TranscriptScrollView(frame: NSRect(x: 0, y: 0, width: 360, height: 150))+ let text = NSTextView(frame: scroll.bounds)+ text.isVerticallyResizable = true+ text.isHorizontallyResizable = false+ text.autoresizingMask = [.width]+ text.textContainer?.widthTracksTextView = true+ scroll.documentView = text+ let controller = InstructionTranscriptDocumentController()+ let storage = try #require(text.textStorage)+ var planner = TranscriptSyncPlanner()+ let state = input(UUID(), history: 0)+ controller.synchronizeHistory(storage: storage, planner: &planner, input: state) { _ in }+ let response = (0..<50).map { "Paragraph \($0): the quick brown fox jumps over the dog." }+ .joined(separator: "\n\n")+ controller.synchronize(storage: storage, prompt: "read", response: response, isTerminal: true)+ let manager = try #require(text.layoutManager)+ let container = try #require(text.textContainer)+ manager.ensureLayout(for: container)+ let selected = (storage.string as NSString).range(of: "Paragraph 8")+ text.setSelectedRange(selected)+ if atBottom {+ text.scrollToEndOfDocument(nil)+ } else {+ let glyph = manager.glyphIndexForCharacter(at: selected.location)+ let y = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil).minY+ + text.textContainerOrigin.y + 3+ scroll.contentView.scroll(to: NSPoint(x: 0, y: y))+ }+ for size in [AppTextSize.largest, .standard] {+ let position = TranscriptReadingPosition(textView: text, scrollView: scroll, followsPrefill: false)+ let update = controller.refreshTypography(+ .init(size), storage: storage, planner: &planner, input: state,+ promptPrefix: NSAttributedString(), drawPair: { _ in })+ position.restore(textView: text, scrollView: scroll, replacing: update.replaced)+ var follow = TranscriptScrollFollow()+ if atBottom { follow.beginRun() }+ follow.recordScroll(origin: scroll.contentView.bounds.minY, documentHeight: text.bounds.height)+ scroll.didRestoreReadingPosition = {+ follow.recordScroll(origin: scroll.contentView.bounds.minY, documentHeight: text.bounds.height)+ }+ // The composer preference resizes the viewport after typography has+ // restored the anchor. Without resize restoration, the newest text+ // falls below the viewport and subsequent streaming stops following.+ scroll.setFrameSize(NSSize(width: 360, height: size == .largest ? 74 : 150))+ let follows = follow.shouldScrollToBottom(+ origin: scroll.contentView.bounds.minY, documentHeight: text.bounds.height)+ #expect(follows == atBottom)+ scroll.didRestoreReadingPosition = nil+ #expect(text.selectedRange() == selected)+ if atBottom {+ #expect(scroll.contentView.bounds.maxY >= text.bounds.maxY - 24)+ } else {+ let glyph = manager.glyphIndexForCharacter(at: selected.location)+ let expected = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil).minY+ + text.textContainerOrigin.y + 3+ #expect(abs(scroll.contentView.bounds.minY - expected) < 1)+ }+ }+ }++ @Test(arguments: ["Equation $x^", "Equation $$x^"])+ func unfinishedEquationStaysRawUntilFinalized(_ prefix: String) throws {+ let controller = InstructionTranscriptDocumentController()+ let storage = NSMutableAttributedString()+ var planner = TranscriptSyncPlanner()+ let state = input(UUID(), history: 0)+ controller.synchronizeHistory(storage: storage, planner: &planner, input: state) { _ in }+ controller.synchronize(storage: storage, prompt: "math", response: prefix, isTerminal: false)+ let original = storage.string+ controller.refreshTypography(.init(.largest), storage: storage, planner: &planner, input: state,+ promptPrefix: NSAttributedString(), drawPair: { _ in })+ #expect(storage.string == original)+ #expect(attachments(storage).isEmpty)+ #expect(!controller.isFinalized)+ controller.synchronize(storage: storage, prompt: "math",+ response: prefix + (prefix.contains("$$") ? "2$$" : "2$"),+ isTerminal: true)+ let equation = try #require(attachments(storage).first)+ #expect(equation.bounds.height > 0)+ storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: storage.length)) { value, range, _ in+ guard value is MathAttachment else { return }+ #expect((storage.attribute(.font, at: range.location, effectiveRange: nil) as? NSFont)?.pointSize+ == NSFont.systemFontSize * 2)+ }+ }++ @Test(arguments: [false, true], [AppTextSize.standard, .largest])+ func readableMixedContentFrames(dark: Bool, size: AppTextSize) throws {+ let source = """+ ## Readable at a larger size++ A response with **emphasis**, a [link](https://example.com), and $x^2 + y^2$.++ - First item+ - Second item++ | Setting | Choice |+ | --- | --- |+ | Text size | \(size.label) |++ ```swift+ let readable = true+ ```+ """+ let result = ResponseMarkdownRenderer(typography: .init(size)).render(source)+ let image = try TranscriptFrameRenderer.image(result.attributedString, width: 530, dark: dark)+ #expect(image.size.height < TranscriptFrameRenderer.maximumHeight)+ try TranscriptFrameRenderer.record(image, named: "text-size-\(size.rawValue)-\(dark ? "dark" : "light")")+ }++ private func attachments(_ string: NSAttributedString) -> [MathAttachment] {+ var result: [MathAttachment] = []+ string.enumerateAttribute(.attachment, in: NSRange(location: 0, length: string.length)) { value, _, _ in+ if let value = value as? MathAttachment { result.append(value) }+ }+ return result+ }+}++@MainActor private final class CountingTypographyRenderer: TranscriptBlockRendering {+ private let renderer: ResponseMarkdownRenderer+ var sources: [String] = []+ init(_ typography: ConversationTypography) {+ renderer = ResponseMarkdownRenderer(typography: typography)+ }+ func render(_ source: String, typesetsMath: Bool) -> ResponseMarkdownRenderer.Result {+ sources.append(source)+ return renderer.render(source, typesetsMath: typesetsMath)+ }+ func blockSeparator(trailingNewlines: Int) -> NSAttributedString {+ renderer.blockSeparator(trailingNewlines: trailingNewlines)+ }+ func streamingCodeAttributes() -> [NSAttributedString.Key: Any] {+ renderer.streamingCodeAttributes()+ }+}