diff --git a/ios/Hapi.xcodeproj/project.pbxproj b/ios/Hapi.xcodeproj/project.pbxproj index cb84d80c..1ea2f346 100644 --- a/ios/Hapi.xcodeproj/project.pbxproj +++ b/ios/Hapi.xcodeproj/project.pbxproj @@ -481,7 +481,7 @@ CODE_SIGN_ENTITLEMENTS = Hapi/Hapi.entitlements; "CODE_SIGN_ENTITLEMENTS[sdk=macosx*]" = "Hapi/Hapi-macOS.entitlements"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 12; + CURRENT_PROJECT_VERSION = 14; DERIVE_MACCATALYST_PRODUCT_BUNDLE_IDENTIFIER = NO; DEVELOPMENT_TEAM = X75CUV458P; ENABLE_PREVIEWS = YES; @@ -516,7 +516,7 @@ CODE_SIGN_ENTITLEMENTS = Hapi/Hapi.entitlements; "CODE_SIGN_ENTITLEMENTS[sdk=macosx*]" = "Hapi/Hapi-macOS.entitlements"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 12; + CURRENT_PROJECT_VERSION = 14; DERIVE_MACCATALYST_PRODUCT_BUNDLE_IDENTIFIER = NO; DEVELOPMENT_TEAM = X75CUV458P; ENABLE_PREVIEWS = YES; @@ -549,7 +549,7 @@ CODE_SIGN_ENTITLEMENTS = HapiNotificationService/HapiNotificationService.entitlements; "CODE_SIGN_ENTITLEMENTS[sdk=macosx*]" = "HapiNotificationService/HapiNotificationService-macOS.entitlements"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 12; + CURRENT_PROJECT_VERSION = 14; DERIVE_MACCATALYST_PRODUCT_BUNDLE_IDENTIFIER = NO; DEVELOPMENT_TEAM = X75CUV458P; GENERATE_INFOPLIST_FILE = YES; @@ -578,7 +578,7 @@ CODE_SIGN_ENTITLEMENTS = HapiNotificationService/HapiNotificationService.entitlements; "CODE_SIGN_ENTITLEMENTS[sdk=macosx*]" = "HapiNotificationService/HapiNotificationService-macOS.entitlements"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 12; + CURRENT_PROJECT_VERSION = 14; DERIVE_MACCATALYST_PRODUCT_BUNDLE_IDENTIFIER = NO; DEVELOPMENT_TEAM = X75CUV458P; GENERATE_INFOPLIST_FILE = YES; @@ -607,7 +607,7 @@ APPLICATION_EXTENSION_API_ONLY = YES; CODE_SIGN_ENTITLEMENTS = HapiWidgets/HapiWidgets.entitlements; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 12; + CURRENT_PROJECT_VERSION = 14; DEVELOPMENT_TEAM = X75CUV458P; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = HapiWidgets/Info.plist; @@ -637,7 +637,7 @@ APPLICATION_EXTENSION_API_ONLY = YES; CODE_SIGN_ENTITLEMENTS = HapiWidgets/HapiWidgets.entitlements; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 12; + CURRENT_PROJECT_VERSION = 14; DEVELOPMENT_TEAM = X75CUV458P; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = HapiWidgets/Info.plist; diff --git a/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift b/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift index 3170ea60..d2451432 100644 --- a/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift +++ b/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift @@ -230,11 +230,12 @@ struct TerminalTextView: View { @Environment(\.hapiTheme) private var theme @Environment(\.hapiTypography) private var typography + @Environment(\.hapiCodeFontSize) private var codeFontSize var body: some View { ScrollView(.horizontal, showsIndicators: false) { Text(text) - .font(typography.codeFont) + .font(typography.codeFont(size: codeFontSize)) .lineSpacing(typography.codeLineSpacing) .foregroundStyle(isError ? AnyShapeStyle(theme.danger) : AnyShapeStyle(theme.textPrimary)) .textSelection(.enabled) diff --git a/ios/Hapi/Features/Sessions/SessionListModel.swift b/ios/Hapi/Features/Sessions/SessionListModel.swift index 08610344..46ed074b 100644 --- a/ios/Hapi/Features/Sessions/SessionListModel.swift +++ b/ios/Hapi/Features/Sessions/SessionListModel.swift @@ -14,6 +14,10 @@ struct SessionRowUI: Identifiable, Equatable { /// Short project name only. Paths, machine/worktree details and the /// conversation summary stay out of the compact home row. let project: String? + /// Human machine label, resolved from `machineFilters`. + let machine: String? + /// Worktree name for directory-group rows. + let worktree: String? /// Raw flavor id (`claude`, `codex`, …); labels resolve via the catalog. let flavor: String? let unread: Bool @@ -22,6 +26,45 @@ struct SessionRowUI: Identifiable, Equatable { var status: SessionRowStatus? { SessionRowStatus(summary: summary) } } +struct SessionListBucketUI: Identifiable, Equatable { + let bucket: SessionListBucket + let rows: [SessionRowUI] + + var id: String { bucket.rawValue } +} + +/// One section of the H5-style list. Pins/directories carry `rows`; +/// In-progress/Active sections carry `buckets`. +struct SessionListSectionUI: Identifiable, Equatable { + let id: String + let kind: SessionListGroupKind + let directoryName: String? + let machineLabel: String? + let rows: [SessionRowUI] + let buckets: [SessionListBucketUI] + let hasActive: Bool + let hasProjectPinned: Bool + + var totalCount: Int { + rows.count + buckets.reduce(0) { $0 + $1.rows.count } + } + + var defaultCollapsed: Bool { + kind == .directory && !hasActive && !hasProjectPinned + } + + func contains(_ sessionId: String) -> Bool { + rows.contains { $0.id == sessionId } + || buckets.contains { $0.rows.contains { $0.id == sessionId } } + } +} + +struct SessionListSnapshot: Equatable { + let rows: [SessionRowUI] + let sections: [SessionListSectionUI] + let searching: Bool +} + /// Presentation only: request totals/kinds come from the hub, independently /// of the capped request slice and the local read watermark. enum SessionRowStatus: Equatable { @@ -104,6 +147,7 @@ final class SessionListModel { private let sessionStore: any SessionListStoring private let machineStore: any MachineListStoring private let lastSeenStore: LastSeenStore + private let personalPins: PersonalPinStore private let hubUrl: String /// Reopen follows a superseding id with the composer draft (web /// `transferComposerDraftThenNavigate`). @@ -137,12 +181,14 @@ final class SessionListModel { sessionStore: any SessionListStoring, machineStore: any MachineListStoring, lastSeenStore: LastSeenStore, + personalPins: PersonalPinStore = .shared, hubUrl: String, drafts: (any ChatDrafts)? = nil ) { self.sessionStore = sessionStore self.machineStore = machineStore self.lastSeenStore = lastSeenStore + self.personalPins = personalPins self.hubUrl = hubUrl self.drafts = drafts } @@ -314,17 +360,71 @@ final class SessionListModel { visible = SessionListSearch.rank(visible, by: index) } } + let machineLabels = Dictionary(uniqueKeysWithValues: machineFilters.map { ($0.id, $0.label) }) return visible.map { summary in - SessionRowUI( + let worktree = summary.metadata?.worktree?.name + .trimmingCharacters(in: .whitespacesAndNewlines) + return SessionRowUI( summary: summary, title: Self.sessionTitle(summary), project: Self.projectLabel(summary), + machine: summary.metadata?.machineId.flatMap { machineLabels[$0] } + ?? machineLabels[unknownMachineFilterId], + worktree: worktree?.isEmpty == false ? worktree : nil, flavor: summary.metadata?.flavor, unread: LastSeenStore.isUnread(summary, state: readState, followedTails: followedTails) ) } } + /// H5-style grouped sections. Search stays flat (the view uses `rows`). + var sections: [SessionListSectionUI] { + isSearching ? [] : groupedSections(from: rows) + } + + var snapshot: SessionListSnapshot { + let visibleRows = rows + return SessionListSnapshot( + rows: visibleRows, + sections: isSearching ? [] : groupedSections(from: visibleRows), + searching: isSearching + ) + } + + private func groupedSections(from visibleRows: [SessionRowUI]) -> [SessionListSectionUI] { + let rowById = Dictionary(uniqueKeysWithValues: visibleRows.map { ($0.id, $0) }) + let machineLabels = Dictionary(uniqueKeysWithValues: machineFilters.map { ($0.id, $0.label) }) + return SessionListGrouping.groups( + sessions: visibleRows.map(\.summary), + personalPinned: personalPins.sessionIds + ).map { group in + let machineLabel = machineLabels[group.machineId ?? unknownMachineFilterId] + return SessionListSectionUI( + id: group.id, + kind: group.kind, + directoryName: group.displayName, + machineLabel: machineLabel, + rows: group.sessions.compactMap { rowById[$0.id] }, + buckets: group.buckets.map { bucket in + SessionListBucketUI( + bucket: bucket.bucket, + rows: bucket.sessions.compactMap { rowById[$0.id] } + ) + }, + hasActive: group.hasActive, + hasProjectPinned: group.hasProjectPinned + ) + } + } + + func isPersonallyPinned(_ sessionId: String) -> Bool { + personalPins.contains(sessionId) + } + + func togglePersonalPin(sessionId: String) { + personalPins.toggle(sessionId) + } + /// The sort contract puts globalPinned/pinned rows first; this boundary /// index is where the pinned section ends. static func pinnedCount(of rows: [SessionRowUI]) -> Int { diff --git a/ios/Hapi/Features/Sessions/SessionListView.swift b/ios/Hapi/Features/Sessions/SessionListView.swift index 72cb89ae..6202f30a 100644 --- a/ios/Hapi/Features/Sessions/SessionListView.swift +++ b/ios/Hapi/Features/Sessions/SessionListView.swift @@ -23,6 +23,12 @@ import SwiftUI /// an alert. struct SessionListView: View { @Environment(\.hapiTheme) private var theme + @Environment(DisplayPrefs.self) private var displayPrefs + @ScaledMetric(relativeTo: .body) private var baseTitleSize: CGFloat = 17 + @ScaledMetric(relativeTo: .footnote) private var baseDetailSize: CGFloat = 13 + @ScaledMetric(relativeTo: .footnote) private var baseHeaderSize: CGFloat = 13 + @ScaledMetric(relativeTo: .body) private var baseIconSize: CGFloat = 30 + @ScaledMetric(relativeTo: .footnote) private var baseStatusSlotSize: CGFloat = 16 let model: SessionListModel var selection: Binding? = nil let onOpenSession: (String) -> Void @@ -30,8 +36,33 @@ struct SessionListView: View { @State private var renameTarget: SessionRowUI? @State private var renameText = "" @State private var deleteTarget: SessionRowUI? - /// Rows kept while a pushed chat covers the list (see `sessionList`). - @State private var frozenRows: [SessionRowUI]? + /// Grouped rows kept while a pushed chat covers the list. + @State private var frozenSnapshot: SessionListSnapshot? + /// Per-section overrides; nil means use the section's default. Kept + /// in-memory like the web sidebar. + @State private var collapseOverrides: [String: Bool] = [:] + + private var listScale: CGFloat { CGFloat(displayPrefs.listFontScale) } + + private var metrics: SessionListMetrics { + let scale = listScale + #if targetEnvironment(macCatalyst) + let baseInset: CGFloat = 6 + #else + let baseInset: CGFloat = 12 + #endif + return SessionListMetrics( + titleSize: baseTitleSize * scale, + detailSize: baseDetailSize * scale, + headerSize: baseHeaderSize * scale, + iconSize: baseIconSize * scale, + statusSlotSize: baseStatusSlotSize * scale, + iconSpacing: 12 * scale, + rowVerticalInset: baseInset * scale, + bucketDotSize: max(5, 6 * scale), + bucketLabelSize: baseHeaderSize * scale * 0.9 + ) + } var body: some View { // Rows own their minute-tick age labels; the list itself only @@ -47,6 +78,9 @@ struct SessionListView: View { .onChange(of: model.machineFilterIds, initial: true) { _, _ in model.reconcileFilters() } + .onChange(of: model.selectedSessionId, initial: true) { _, sessionId in + expandSelectedSection(sessionId) + } .task { // Explicit fetch on entry: the snapshot may be stale and a // `resume: ok` handshake deliberately skips the REST resync. @@ -114,104 +148,125 @@ struct SessionListView: View { // MARK: - List - /// Covered by a pushed chat, the list keeps its last rows: on a large - /// hub every streaming session would otherwise rebuild and diff + /// Covered by a pushed chat, the list keeps its last grouped snapshot: on + /// a large hub every streaming session would otherwise rebuild and diff /// thousands of rows nobody sees (~80 ms main-thread stalls while - /// scrolling the chat). A side-by-side split never disappears and - /// stays live; returning refreshes once. + /// scrolling the chat). A side-by-side split never disappears and stays + /// live; returning refreshes once. private var sessionList: some View { - let rows = frozenRows ?? model.rows - return KeyedContent(key: ListRenderKey(rows: rows, selectable: selection != nil, - theme: theme, filters: model.filters)) { - list(rows) + let snapshot = frozenSnapshot ?? model.snapshot + return KeyedContent(key: ListRenderKey( + snapshot: snapshot, + selectable: selection != nil, + theme: theme, + filters: model.filters, + metrics: metrics + )) { + list(snapshot) } .equatable() - .onAppear { frozenRows = nil } - .onDisappear { frozenRows = model.rows } + .onAppear { frozenSnapshot = nil } + .onDisappear { frozenSnapshot = model.snapshot } } - private func list(_ rows: [SessionRowUI]) -> some View { - let pinnedCount = SessionListModel.pinnedCount(of: rows) - return List(selection: selection) { - if pinnedCount > 0 { + private func list(_ snapshot: SessionListSnapshot) -> some View { + List(selection: selection) { + if snapshot.searching { Section { - ForEach(rows.prefix(pinnedCount)) { row in - equatableRow(row) + ForEach(snapshot.rows) { row in + equatableRow(row, detail: .projectMachine) } - } header: { - sectionHeader("Pinned") } .listSectionSeparator(.hidden, edges: .top) - } - if rows.count > pinnedCount { - // Headerless when nothing is pinned: an empty-string Section - // header still reserves a blank sticky band above the list - // (device feedback: "一片空白"). - if pinnedCount > 0 { - Section { - ForEach(rows.dropFirst(pinnedCount)) { row in - equatableRow(row) - } - } header: { - // Not "Sessions": the navigation title already says so. - sectionHeader("Recent") - } - .listSectionSeparator(.hidden, edges: .top) - } else { - // Top edge hidden: a plain list otherwise draws a stray - // separator above the very first row (device feedback). - Section { - ForEach(rows) { row in - equatableRow(row) - } - } - .listSectionSeparator(.hidden, edges: .top) + } else { + ForEach(snapshot.sections) { section in + sectionView(section) } } } .modifier(PlatformSessionListStyle()) - // The default plain header height leaves a blank band between - // Pinned and Recent; headers size to their compact text instead. .environment(\.defaultMinListHeaderHeight, 0) // An explicit filter change starts at the top. SSE/count/name changes // keep this identity (and the reading position), as does chat return. .id(model.filters) .accessibilityIdentifier("home.sessions") .overlay { - if rows.isEmpty { + if snapshot.rows.isEmpty { emptyState .allowsHitTesting(false) // keep the pull-to-refresh gesture } } } + @ViewBuilder + private func sectionView(_ section: SessionListSectionUI) -> some View { + let collapsed = isCollapsed(section) + Section { + if !collapsed { + if section.kind == .inProgress || section.kind == .active { + ForEach(section.buckets) { bucket in + BucketHeader( + bucket: bucket.bucket, + count: bucket.rows.count, + metrics: metrics + ) + ForEach(bucket.rows) { row in + equatableRow(row, detail: .projectMachine) + } + } + } else { + ForEach(section.rows) { row in + equatableRow( + row, + detail: section.kind == .directory ? .worktree : .projectMachine + ) + } + } + } + } header: { + sectionHeader(section, collapsed: collapsed) + } + .listSectionSeparator(.hidden, edges: .top) + } + /// The List evaluates every row's content (offscreen ones included) on /// each list change, so one streaming session cost O(all rows) per /// update. Rows compare only what they draw and skip unchanged content. - private func equatableRow(_ row: SessionRowUI) -> some View { - KeyedContent(key: RowRenderKey(row: row, selectable: selection != nil, theme: theme)) { - rowCell(row) + private func equatableRow(_ row: SessionRowUI, detail: SessionRowDetail) -> some View { + KeyedContent(key: RowRenderKey( + row: row, + detail: detail, + metrics: metrics, + selectable: selection != nil, + theme: theme + )) { + rowCell(row, detail: detail) } .equatable() } - private func rowCell(_ row: SessionRowUI) -> some View { + private func rowCell(_ row: SessionRowUI, detail: SessionRowDetail) -> some View { Group { if selection != nil { NavigationLink(value: row.id) { - rowLabel(row) + rowLabel(row, detail: detail) } .tag(row.id) } else { Button { onOpenSession(row.id) } label: { - rowLabel(row) + rowLabel(row, detail: detail) } .buttonStyle(.plain) } } - .listRowInsets(EdgeInsets(top: Self.rowVerticalInset, leading: 16, bottom: Self.rowVerticalInset, trailing: 16)) + .listRowInsets(EdgeInsets( + top: metrics.rowVerticalInset, + leading: 16, + bottom: metrics.rowVerticalInset, + trailing: 16 + )) // Default separator color reads heavy against these rows; the theme // divider is the WeChat-style faint hairline. .listRowSeparatorTint(theme.divider) @@ -226,22 +281,116 @@ struct SessionListView: View { } } - /// Pointer rows on a Mac sidebar are denser than touch rows. - private static var rowVerticalInset: CGFloat { - #if targetEnvironment(macCatalyst) - 6 - #else - 12 - #endif + /// Filters force groups open, matching the web sidebar. Users can still + /// collapse them after the filter is cleared; while filtering, the + /// headers are disabled so a tap cannot appear to do nothing. + private func isCollapsed(_ section: SessionListSectionUI) -> Bool { + if model.hasActiveFilters { return false } + return collapseOverrides[section.id] ?? section.defaultCollapsed } - /// Compact header (Mail-style) instead of the large plain-list default. - private func sectionHeader(_ title: LocalizedStringKey) -> some View { - Text(title) - .font(.footnote.weight(.semibold)) + private func toggle(_ section: SessionListSectionUI) { + withAnimation(.easeInOut(duration: 0.2)) { + collapseOverrides[section.id] = !isCollapsed(section) + } + } + + private func expandSelectedSection(_ sessionId: String?) { + guard let sessionId, + let section = model.sections.first(where: { $0.contains(sessionId) }), + isCollapsed(section) else { return } + collapseOverrides[section.id] = false + } + + private func sectionHeader(_ section: SessionListSectionUI, collapsed: Bool) -> some View { + Button { + toggle(section) + } label: { + HStack(spacing: 6) { + Image(systemName: "chevron.right") + .font(.system(size: metrics.headerSize * 0.75, weight: .semibold)) + .rotationEffect(.degrees(collapsed ? 0 : 90)) + .frame(width: 10) + sectionIcon(section) + sectionTitle(section) + .font(.system(size: metrics.headerSize, weight: .semibold)) + .lineLimit(1) + Text("(\(section.totalCount))") + .font(.system(size: metrics.headerSize, weight: .regular)) + .monospacedDigit() + Spacer(minLength: 0) + } .foregroundStyle(theme.textSecondary) .textCase(nil) - .listRowInsets(EdgeInsets(top: 4, leading: 16, bottom: 4, trailing: 16)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(model.hasActiveFilters) + .listRowInsets(EdgeInsets(top: 4, leading: 16, bottom: 4, trailing: 16)) + .accessibilityLabel(Text(sectionAccessibilityLabel(section))) + } + + @ViewBuilder + private func sectionTitle(_ section: SessionListSectionUI) -> some View { + switch section.kind { + case .personalPinned: + Text("My sessions") + case .globalPinned: + Text("Pinned") + case .inProgress: + Text("In progress") + case .active: + Text("Active sessions") + case .directory: + Text(verbatim: directoryTitle(section)) + } + } + + private func directoryTitle(_ section: SessionListSectionUI) -> String { + let base: String + if let name = section.directoryName, name != "Other" { + base = name + } else { + base = String(localized: "Other") + } + guard model.showsMachineFilter, + model.activeMachineFilter == nil, + let machine = section.machineLabel else { return base } + return "\(base) · \(machine)" + } + + private func sectionAccessibilityLabel(_ section: SessionListSectionUI) -> String { + let title: String = switch section.kind { + case .personalPinned: String(localized: "My sessions") + case .globalPinned: String(localized: "Pinned") + case .inProgress: String(localized: "In progress") + case .active: String(localized: "Active sessions") + case .directory: directoryTitle(section) + } + return "\(title), \(section.totalCount)" + } + + @ViewBuilder + private func sectionIcon(_ section: SessionListSectionUI) -> some View { + switch section.kind { + case .personalPinned: + Image(systemName: "person.crop.circle") + .font(.system(size: metrics.headerSize)) + case .globalPinned: + Image(systemName: "pin.fill") + .font(.system(size: metrics.headerSize)) + case .inProgress: + Image(systemName: "circle.fill") + .font(.system(size: metrics.bucketDotSize)) + .foregroundStyle(theme.success) + case .active: + Image(systemName: "circle.fill") + .font(.system(size: metrics.bucketDotSize)) + .foregroundStyle(theme.textSecondary) + case .directory: + Image(systemName: "folder") + .font(.system(size: metrics.headerSize)) + } } /// Leading swipe: the quick toggles (pin, read), as in Mail. @@ -296,8 +445,8 @@ struct SessionListView: View { } } - private func rowLabel(_ row: SessionRowUI) -> some View { - SessionRowView(row: row) + private func rowLabel(_ row: SessionRowUI, detail: SessionRowDetail) -> some View { + SessionRowView(row: row, metrics: metrics, detail: detail) .frame(maxWidth: .infinity, alignment: .leading) .contentShape(Rectangle()) } @@ -305,6 +454,23 @@ struct SessionListView: View { @ViewBuilder private func contextMenuActions(_ row: SessionRowUI) -> some View { let summary = row.summary + if model.isPersonallyPinned(row.id) { + Button { + withAnimation(.easeInOut(duration: 0.2)) { + model.togglePersonalPin(sessionId: row.id) + } + } label: { + Label("Remove from my sessions", systemImage: "person.crop.circle.badge.minus") + } + } else { + Button { + withAnimation(.easeInOut(duration: 0.2)) { + model.togglePersonalPin(sessionId: row.id) + } + } label: { + Label("Mark as my session", systemImage: "person.crop.circle.badge.plus") + } + } Button { renameText = row.title renameTarget = row @@ -404,30 +570,91 @@ private struct KeyedContent: View, Equatable { static func == (lhs: Self, rhs: Self) -> Bool { lhs.key == rhs.key } } +struct SessionListMetrics: Equatable { + let titleSize: CGFloat + let detailSize: CGFloat + let headerSize: CGFloat + let iconSize: CGFloat + let statusSlotSize: CGFloat + let iconSpacing: CGFloat + let rowVerticalInset: CGFloat + let bucketDotSize: CGFloat + let bucketLabelSize: CGFloat +} + +enum SessionRowDetail: Equatable { + case projectMachine + case worktree +} + private struct RowRenderKey: Equatable { let row: SessionRowUI + let detail: SessionRowDetail + let metrics: SessionListMetrics let selectable: Bool let theme: HapiTheme } private struct ListRenderKey: Equatable { - let rows: [SessionRowUI] + let snapshot: SessionListSnapshot let selectable: Bool let theme: HapiTheme let filters: SessionListFilters + let metrics: SessionListMetrics +} + +private struct BucketHeader: View { + let bucket: SessionListBucket + let count: Int + let metrics: SessionListMetrics + @Environment(\.hapiTheme) private var theme + + var body: some View { + HStack(spacing: 5) { + Image(systemName: "circle.fill") + .font(.system(size: metrics.bucketDotSize)) + .foregroundStyle(color) + Text(label) + .font(.system(size: metrics.bucketLabelSize, weight: .semibold)) + Text("(\(count))") + .font(.system(size: metrics.bucketLabelSize, weight: .regular)) + .monospacedDigit() + Spacer(minLength: 0) + } + .foregroundStyle(theme.textSecondary) + .listRowInsets(EdgeInsets(top: 2, leading: 16, bottom: 2, trailing: 16)) + .listRowSeparator(.hidden) + .listRowBackground(Color.clear) + .selectionDisabled() + } + + private var label: LocalizedStringKey { + switch bucket { + case .working: return "Running" + case .pending: return "Pending" + case .active: return "Active" + case .idle: return "Idle" + } + } + + private var color: Color { + switch bucket { + case .working: return theme.success + case .pending: return theme.warning + case .active, .idle: return theme.textSecondary + } + } } struct SessionRowView: View { @Environment(\.hapiTheme) private var theme - @ScaledMetric(relativeTo: .body) private var iconSize: CGFloat = 30 - @ScaledMetric(relativeTo: .footnote) private var statusSlotSize: CGFloat = 16 let row: SessionRowUI - - private let iconSpacing: CGFloat = 12 + let metrics: SessionListMetrics + let detail: SessionRowDetail var body: some View { - HStack(alignment: .center, spacing: iconSpacing) { + HStack(alignment: .center, spacing: metrics.iconSpacing) { agentIcon VStack(alignment: .leading, spacing: 3) { titleLine @@ -435,7 +662,7 @@ struct SessionRowView: View { } } // Separators start under the text column, as in Mail and Messages. - .alignmentGuide(.listRowSeparatorLeading) { _ in iconSize + iconSpacing } + .alignmentGuide(.listRowSeparatorLeading) { _ in metrics.iconSize + metrics.iconSpacing } .accessibilityElement(children: .combine) .accessibilityValue(row.unread ? Text("Unread") : Text(verbatim: "")) .accessibilityIdentifier("home.session.\(row.id)") @@ -444,8 +671,8 @@ struct SessionRowView: View { /// The agent owns the leading column; a presence badge marks connected /// sessions (pulsing while the agent works) instead of dimming the rest. private var agentIcon: some View { - AgentFlavorIconView(flavor: row.flavor, size: iconSize * 0.8) - .frame(width: iconSize, height: iconSize) + AgentFlavorIconView(flavor: row.flavor, size: metrics.iconSize * 0.8) + .frame(width: metrics.iconSize, height: metrics.iconSize) .overlay(alignment: .bottomTrailing) { if row.summary.active { presenceBadge @@ -456,7 +683,7 @@ struct SessionRowView: View { private var presenceBadge: some View { let isRunning = row.status == .running return Image(systemName: "circle.fill") - .font(.system(size: iconSize * 0.3)) + .font(.system(size: metrics.iconSize * 0.3)) .foregroundStyle(theme.success) .symbolEffect(.pulse, options: .repeating, isActive: isRunning) .padding(2) @@ -468,8 +695,7 @@ struct SessionRowView: View { private var titleLine: some View { HStack(spacing: 8) { Text(verbatim: row.title) - .font(.body) - .fontWeight(row.unread ? .semibold : .regular) + .font(.system(size: metrics.titleSize, weight: row.unread ? .semibold : .regular)) .foregroundStyle(theme.textPrimary) .lineLimit(1) Spacer(minLength: 4) @@ -479,23 +705,22 @@ struct SessionRowView: View { TimelineView(.periodic(from: .now, by: 60)) { context in Text(verbatim: formatRelativeAge(now: context.date, thenEpochMs: row.summary.updatedAt)) } - .font(.footnote) - .fontWeight(row.unread ? .semibold : .regular) + .font(.system(size: metrics.detailSize, weight: row.unread ? .semibold : .regular)) .foregroundStyle(row.unread ? theme.accent : theme.textSecondary) .monospacedDigit() .fixedSize() } } - /// Project left; only states that need the user (reply/approval) get a - /// trailing symbol. Routine activity lives on the icon badge. + /// Project/machine in pinned and bucket sections; worktree name inside a + /// folder group. Routine activity lives on the icon badge. private var detailLine: some View { HStack(alignment: .center, spacing: 0) { // Keep the same text line height when metadata is missing, // so the row height does not jump. - Text(verbatim: row.project ?? " ") + Text(verbatim: detailText ?? " ") .lineLimit(1) - .accessibilityHidden(row.project == nil) + .accessibilityHidden(detailText == nil) Spacer(minLength: 12) if let status = row.status, let symbol = status.symbolName { Image(systemName: symbol) @@ -503,16 +728,29 @@ struct SessionRowView: View { .symbolRenderingMode(.monochrome) .foregroundStyle(attentionColor) // One slot keeps every attention symbol aligned. - .frame(width: statusSlotSize, height: statusSlotSize) + .frame(width: metrics.statusSlotSize, height: metrics.statusSlotSize) .fixedSize() .layoutPriority(1) .accessibilityLabel(statusAccessibilityText(status)) } } - .font(.footnote) + .font(.system(size: metrics.detailSize)) .foregroundStyle(theme.textSecondary) } + private var detailText: String? { + switch detail { + case .projectMachine: + let text = [row.project, row.machine] + .compactMap { $0 } + .filter { !$0.isEmpty } + .joined(separator: " · ") + return text.isEmpty ? nil : text + case .worktree: + return row.worktree + } + } + // Darker amber keeps thin strokes visible on white without a filled // symbol, background badge or animation competing with the session title. private var attentionColor: Color { diff --git a/ios/Hapi/Features/Settings/SettingsView.swift b/ios/Hapi/Features/Settings/SettingsView.swift index 48c90f8f..5a288e31 100644 --- a/ios/Hapi/Features/Settings/SettingsView.swift +++ b/ios/Hapi/Features/Settings/SettingsView.swift @@ -71,6 +71,7 @@ struct SettingsView: View { @State private var confirmSignOut = false @Environment(AppModel.self) private var appModel @Environment(ThemePrefs.self) private var themePrefs + @Environment(DisplayPrefs.self) private var displayPrefs @Environment(\.dismiss) private var dismiss @Environment(\.openURL) private var openURL @@ -163,15 +164,43 @@ struct SettingsView: View { } private var appearanceSection: some View { - Section("Appearance") { + Section { Picker("Theme", selection: themeBinding) { ForEach(ThemeMode.allCases, id: \.self) { mode in Text(mode.label).tag(mode) } } + Picker("List text size", selection: listFontScaleBinding) { + ForEach(DisplayPrefs.listFontScales, id: \.self) { scale in + Text(verbatim: "\(Int((scale * 100).rounded()))%").tag(scale) + } + } + Picker("Code & terminal text size", selection: codeFontSizeBinding) { + ForEach(DisplayPrefs.codeFontSizes, id: \.self) { size in + Text(verbatim: "\(Int(size)) pt").tag(size) + } + } + } header: { + Text("Appearance") + } footer: { + Text("List size affects the session list only; code size affects CLI output, code blocks and diffs.") } } + private var listFontScaleBinding: Binding { + Binding( + get: { displayPrefs.listFontScale }, + set: { displayPrefs.setListFontScale($0) } + ) + } + + private var codeFontSizeBinding: Binding { + Binding( + get: { displayPrefs.codeFontSize }, + set: { displayPrefs.setCodeFontSize($0) } + ) + } + private var themeBinding: Binding { Binding( get: { themePrefs.mode }, diff --git a/ios/Hapi/Resources/Localizable.xcstrings b/ios/Hapi/Resources/Localizable.xcstrings index 001a2594..6649f598 100644 --- a/ios/Hapi/Resources/Localizable.xcstrings +++ b/ios/Hapi/Resources/Localizable.xcstrings @@ -11714,6 +11714,193 @@ } } } + }, + "My sessions" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Мои сеансы" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "我的会话" + } + } + } + }, + "In progress" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "В процессе" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "进行中" + } + } + } + }, + "Active sessions" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Активные сеансы" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "活跃会话" + } + } + } + }, + "Pending" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "В ожидании" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "待处理" + } + } + } + }, + "Idle" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Простой" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "空闲" + } + } + } + }, + "Other" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Другое" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "其他" + } + } + } + }, + "List text size" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Размер текста списка" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "列表文字大小" + } + } + } + }, + "Code & terminal text size" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Размер текста кода и терминала" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "代码和终端文字大小" + } + } + } + }, + "Mark as my session" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отметить как мой сеанс" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "标为我的会话" + } + } + } + }, + "Remove from my sessions" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Удалить из моих сеансов" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "从我的会话移除" + } + } + } + }, + "List size affects the session list only; code size affects CLI output, code blocks and diffs." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Размер списка влияет только на список сеансов; размер кода влияет на вывод CLI, блоки кода и diff." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "列表字号只影响会话列表;代码字号影响 CLI 输出、代码块和 diff。" + } + } + } } }, "version" : "1.0" diff --git a/ios/Hapi/RootView.swift b/ios/Hapi/RootView.swift index 8553d272..af8c2e58 100644 --- a/ios/Hapi/RootView.swift +++ b/ios/Hapi/RootView.swift @@ -12,6 +12,7 @@ struct RootView: View { @Environment(AppModel.self) private var model @Environment(\.colorScheme) private var colorScheme @State private var themePrefs = ThemePrefs() + @State private var displayPrefs = DisplayPrefs() var body: some View { @Bindable var model = model @@ -64,6 +65,7 @@ struct RootView: View { } .background(MacWindowConfigurator()) .hapiTypography() + .environment(\.hapiCodeFontSize, CGFloat(displayPrefs.codeFontSize)) .hapiTheme(themePrefs.mode.hapiTheme(systemColorScheme: colorScheme)) // Explicit modes force the presentation's chrome to match their // palette; `.system` passes nil so the OS scheme flows through. @@ -71,6 +73,7 @@ struct RootView: View { // the palette resolution only consults it in `.system` mode.) .preferredColorScheme(themePrefs.mode.preferredColorScheme) .environment(themePrefs) + .environment(displayPrefs) .handlesHapiLinks() } } diff --git a/ios/HapiTests/HomeFilterPresentationTests.swift b/ios/HapiTests/HomeFilterPresentationTests.swift index 2678f58f..348ca3a4 100644 --- a/ios/HapiTests/HomeFilterPresentationTests.swift +++ b/ios/HapiTests/HomeFilterPresentationTests.swift @@ -22,6 +22,7 @@ final class HomeFilterPresentationTests: XCTestCase { var theme: HapiTheme = .light var size: DynamicTypeSize = .large var locale = Locale(identifier: "en") + var displayPrefs = DisplayPrefs() var body: some View { @Bindable var navigation = navigation @@ -48,6 +49,7 @@ final class HomeFilterPresentationTests: XCTestCase { } .hapiTypography() .hapiTheme(theme) + .environment(displayPrefs) .environment(\.dynamicTypeSize, size) .environment(\.locale, locale) .environment(\.colorScheme, theme.isDark ? .dark : .light) @@ -117,9 +119,11 @@ final class HomeFilterPresentationTests: XCTestCase { XCTAssertTrue(model.showsMachineFilter) } - func testNativeListRowsKeepOnlyTitleAndProjectStatus() async throws { + func testNativeListRowsKeepTheTwoLineContract() async throws { let sessions = HomeFilterTestSessions((0..<3).map { index in var summary = HomeFilterTestData.summary("row-\(index)", machine: nil) + summary.active = false + summary.pinned = index == 0 summary.metadata?.summary = .init(text: "A short preview") summary.pendingRequestsCount = index == 2 ? 0 : 1 summary.pendingRequestKinds = [.input] @@ -141,6 +145,34 @@ final class HomeFilterPresentationTests: XCTestCase { XCTAssertEqual(heights[0], heights[2], accuracy: 1, "Activity shares the same quiet secondary line") } + func testListFontScaleGrowsRowsWithoutAddingLines() async throws { + let suite = "HomeFilterFontScale-\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let prefs = DisplayPrefs(defaults: defaults) + prefs.setListFontScale(1.3) + + let sessions = HomeFilterTestSessions((0..<2).map { index in + var summary = HomeFilterTestData.summary("scaled-\(index)", machine: nil) + summary.active = false + summary.pinned = index == 0 + return summary + }) + let model = HomeFilterTestData.model(sessions: sessions) + let window = try makeWindow( + Harness(model: model, navigation: Navigation(), displayPrefs: prefs), + width: 390 + ) + defer { window.isHidden = true } + try await settle() + let list = try XCTUnwrap(findCollection(window)) + let heights = try (0..<2).map { index in + try XCTUnwrap(list.layoutAttributesForItem(at: IndexPath(item: index, section: 0))).size.height + } + XCTAssertGreaterThan(heights[0], 70, "130% must grow the default 60-70pt row") + XCTAssertEqual(heights[0], heights[1], accuracy: 1) + } + func testHomeLayoutSpecimens() async throws { let now = Int(Date.now.timeIntervalSince1970 * 1_000) let sessions = HomeFilterTestSessions((0..<6).map { diff --git a/ios/HapiTests/SessionListCoveredRefreshTests.swift b/ios/HapiTests/SessionListCoveredRefreshTests.swift index 469e136a..05355b05 100644 --- a/ios/HapiTests/SessionListCoveredRefreshTests.swift +++ b/ios/HapiTests/SessionListCoveredRefreshTests.swift @@ -43,11 +43,17 @@ final class SessionListCoveredRefreshTests: XCTestCase { .navigationDestination(for: String.self) { Text($0) } } .hapiTheme(.light) + .environment(DisplayPrefs()) } } func testCoveredListKeepsItsRowsAndRefreshesOnReturn() async throws { - let sessions = Sessions((0..<3).map { HomeFilterTestData.summary("s\($0)", machine: "mac") }) + let sessions = Sessions((0..<3).map { index -> SessionSummary in + var summary = HomeFilterTestData.summary("s\(index)", machine: "mac") + summary.active = false + summary.pinned = index == 0 + return summary + }) let model = SessionListModel(sessionStore: sessions, machineStore: HomeFilterTestMachines(), lastSeenStore: LastSeenStore(), hubUrl: "test") let navigation = Navigation() @@ -63,7 +69,11 @@ final class SessionListCoveredRefreshTests: XCTestCase { navigation.path = ["s0"] try await settle() - sessions.sessions += (3..<5).map { HomeFilterTestData.summary("s\($0)", machine: "mac") } + sessions.sessions += (3..<5).map { index -> SessionSummary in + var summary = HomeFilterTestData.summary("s\(index)", machine: "mac") + summary.active = false + return summary + } try await settle() XCTAssertEqual(itemCount(list), 3, "A covered list must not rebuild for session changes") diff --git a/ios/HapiTests/SessionListGroupingPresentationTests.swift b/ios/HapiTests/SessionListGroupingPresentationTests.swift new file mode 100644 index 00000000..cacd0475 --- /dev/null +++ b/ios/HapiTests/SessionListGroupingPresentationTests.swift @@ -0,0 +1,118 @@ +import HapiClient +import HapiProtocol +import XCTest +@testable import Hapi + +@MainActor +final class SessionListGroupingPresentationTests: XCTestCase { + private func makeModel( + _ summaries: [SessionSummary], + pins pinnedIds: [String] = [] + ) throws -> (SessionListModel, PersonalPinStore, String) { + let suite = "SessionListGroupingPresentation-\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + let store = PersonalPinStore(defaults: defaults) + for id in pinnedIds { store.toggle(id) } + let sessions = HomeFilterTestSessions(summaries) + let model = SessionListModel( + sessionStore: sessions, + machineStore: HomeFilterTestMachines(), + lastSeenStore: LastSeenStore(), + personalPins: store, + hubUrl: "test" + ) + return (model, store, suite) + } + + func testSectionsFollowH5OrderBucketsAndPersonalPins() async throws { + var personal = HomeFilterTestData.summary("personal", machine: "mac") + personal.thinking = true + personal.metadata?.path = "/repo/a" + + var global = HomeFilterTestData.summary("global", machine: "mac") + global.globalPinned = true + global.metadata?.path = "/repo/g" + + var working = HomeFilterTestData.summary("working", machine: "mac") + working.thinking = true + working.metadata?.path = "/repo/w" + + var pending = HomeFilterTestData.summary("pending", machine: "mac") + pending.pendingRequestsCount = 1 + pending.pendingRequestKinds = [.input] + pending.metadata?.path = "/repo/p" + + var idle = HomeFilterTestData.summary("idle", machine: "mac") + idle.thinking = false + idle.metadata?.lifecycleState = "idle" + idle.metadata?.path = "/repo/i" + + var active = HomeFilterTestData.summary("active", machine: "mac") + active.thinking = false + active.metadata?.path = "/repo/active" + + var project = HomeFilterTestData.summary("project", machine: "mac") + project.pinned = true + project.thinking = true + project.metadata?.path = "/repo/a" + + var inactive = HomeFilterTestData.summary("inactive", machine: "mac") + inactive.active = false + inactive.thinking = false + inactive.metadata?.path = "/repo/b" + + let (model, pins, suite) = try makeModel( + [personal, global, working, pending, idle, active, project, inactive], + pins: ["personal"] + ) + defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) } + await model.refresh() + + let sections = model.sections + XCTAssertEqual(sections.map(\.kind), [ + .personalPinned, .globalPinned, .inProgress, .active, .directory, .directory, + ]) + XCTAssertEqual(sections[0].rows.map(\.id), ["personal"]) + XCTAssertEqual(sections[1].rows.map(\.id), ["global"]) + + let inProgress = sections[2] + XCTAssertEqual(inProgress.buckets.map(\.bucket), [.working, .pending]) + XCTAssertEqual(inProgress.buckets[0].rows.map(\.id), ["working"]) + XCTAssertEqual(inProgress.buckets[1].rows.map(\.id), ["pending"]) + + let activeSection = sections[3] + XCTAssertEqual(activeSection.buckets.map(\.bucket), [.active, .idle]) + XCTAssertEqual(activeSection.buckets[0].rows.map(\.id), ["active"]) + XCTAssertEqual(activeSection.buckets[1].rows.map(\.id), ["idle"]) + + let projectGroup = sections[4] + XCTAssertEqual(projectGroup.rows.map(\.id), ["project"]) + XCTAssertFalse(projectGroup.defaultCollapsed) + + let inactiveGroup = sections[5] + XCTAssertEqual(inactiveGroup.rows.map(\.id), ["inactive"]) + XCTAssertTrue(inactiveGroup.defaultCollapsed) + + XCTAssertTrue(pins.contains("personal")) + XCTAssertTrue(model.isPersonallyPinned("personal")) + } + + func testTogglingPersonalPinMovesRowIntoMySessions() async throws { + let first = HomeFilterTestData.summary("first", machine: "mac") + let second = HomeFilterTestData.summary("second", machine: "mac") + let (model, _, suite) = try makeModel([first, second]) + defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) } + await model.refresh() + + XCTAssertNotEqual(model.sections.first?.kind, .personalPinned) + model.togglePersonalPin(sessionId: "second") + let sections = model.sections + XCTAssertEqual(sections.first?.kind, .personalPinned) + XCTAssertEqual(sections.first?.rows.map(\.id), ["second"]) + XCTAssertTrue(model.isPersonallyPinned("second")) + + model.togglePersonalPin(sessionId: "second") + XCTAssertFalse(model.isPersonallyPinned("second")) + XCTAssertNotEqual(model.sections.first?.kind, .personalPinned) + } +} diff --git a/ios/HapiTests/SessionSplitPresentationTests.swift b/ios/HapiTests/SessionSplitPresentationTests.swift index c3fa1f47..c7cfbcad 100644 --- a/ios/HapiTests/SessionSplitPresentationTests.swift +++ b/ios/HapiTests/SessionSplitPresentationTests.swift @@ -78,6 +78,7 @@ final class SessionSplitPresentationTests: XCTestCase { } .hapiTypography() .hapiTheme(.light) + .environment(DisplayPrefs()) } } @@ -184,6 +185,7 @@ final class SessionSplitPresentationTests: XCTestCase { } .hapiTypography() .hapiTheme(.light) + .environment(DisplayPrefs()) } } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Settings/DisplayPrefs.swift b/ios/Packages/HapiKit/Sources/HapiClient/Settings/DisplayPrefs.swift new file mode 100644 index 00000000..e47307fa --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Settings/DisplayPrefs.swift @@ -0,0 +1,54 @@ +import Foundation +import Observation + +/// User-adjustable display sizes, independent of Dynamic Type. +/// +/// The web sidebar exposes a global font scale and a terminal font size. iOS +/// keeps the scales app-local and applies the list scale only to the session +/// list; the code scale applies to terminal-styled output and code blocks. +@MainActor @Observable +public final class DisplayPrefs { + public static let listFontScaleKey = "settings.sessionListFontScale" + public static let codeFontSizeKey = "settings.codeFontSize" + + public static let listFontScales: [Double] = [0.8, 0.9, 1.0, 1.1, 1.2, 1.3] + public static let codeFontSizes: [Double] = [9, 11, 13, 15, 17] + + public static let defaultListFontScale = 1.0 + public static let defaultCodeFontSize = 13.0 + + public private(set) var listFontScale: Double + public private(set) var codeFontSize: Double + + private let defaults: UserDefaults + + public init(defaults: UserDefaults = .standard) { + self.defaults = defaults + let storedScale = defaults.object(forKey: Self.listFontScaleKey) as? Double + self.listFontScale = Self.validScale(storedScale) ?? Self.defaultListFontScale + let storedCode = defaults.object(forKey: Self.codeFontSizeKey) as? Double + self.codeFontSize = Self.validCodeSize(storedCode) ?? Self.defaultCodeFontSize + } + + public func setListFontScale(_ value: Double) { + guard let value = Self.validScale(value) else { return } + listFontScale = value + defaults.set(value, forKey: Self.listFontScaleKey) + } + + public func setCodeFontSize(_ value: Double) { + guard let value = Self.validCodeSize(value) else { return } + codeFontSize = value + defaults.set(value, forKey: Self.codeFontSizeKey) + } + + private static func validScale(_ value: Double?) -> Double? { + guard let value, listFontScales.contains(value) else { return nil } + return value + } + + private static func validCodeSize(_ value: Double?) -> Double? { + guard let value, codeFontSizes.contains(value) else { return nil } + return value + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/PersonalPinStore.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/PersonalPinStore.swift new file mode 100644 index 00000000..8c299f9a --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/PersonalPinStore.swift @@ -0,0 +1,42 @@ +import Foundation +import Observation + +/// Install-global, client-only personal pins ("My sessions" in the web +/// sidebar). This never talks to the hub; it is the iOS counterpart of the +/// web `localStorage` set. +@MainActor @Observable +public final class PersonalPinStore { + public static let key = "settings.personalPinnedSessions" + public static let shared = PersonalPinStore() + + public private(set) var sessionIds: Set + + private let defaults: UserDefaults + + public init(defaults: UserDefaults = .standard) { + self.defaults = defaults + self.sessionIds = Set(defaults.stringArray(forKey: Self.key) ?? []) + } + + public func contains(_ sessionId: String) -> Bool { + sessionIds.contains(sessionId) + } + + public func toggle(_ sessionId: String) { + if sessionIds.contains(sessionId) { + sessionIds.remove(sessionId) + } else { + sessionIds.insert(sessionId) + } + persist() + } + + public func remove(_ sessionId: String) { + guard sessionIds.remove(sessionId) != nil else { return } + persist() + } + + private func persist() { + defaults.set(sessionIds.sorted(), forKey: Self.key) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionListGrouping.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionListGrouping.swift new file mode 100644 index 00000000..12864cc8 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionListGrouping.swift @@ -0,0 +1,232 @@ +import Foundation + +/// A connected-session bucket in the H5 sidebar. +public enum SessionListBucket: String, CaseIterable, Hashable, Sendable { + case working + case pending + case active + case idle +} + +/// Top-level sections the iOS list mirrors from the web sidebar. +public enum SessionListGroupKind: String, Hashable, Sendable { + case personalPinned + case globalPinned + case inProgress + case active + case directory +} + +/// One bucket inside an In-progress / Active section. +public struct SessionListBucketGroup: Equatable, Sendable, Identifiable { + public var bucket: SessionListBucket + public var sessions: [SessionSummary] + + public var id: String { bucket.rawValue } + + public init(bucket: SessionListBucket, sessions: [SessionSummary]) { + self.bucket = bucket + self.sessions = sessions + } +} + +/// One rendered list group. Personal/global pins and directories carry +/// `sessions`; In-progress/Active groups carry `buckets`. +public struct SessionListGroup: Equatable, Sendable, Identifiable { + public var id: String + public var kind: SessionListGroupKind + public var machineId: String? + public var projectPath: String? + public var displayName: String? + public var sessions: [SessionSummary] + public var buckets: [SessionListBucketGroup] + public var hasActive: Bool + public var hasProjectPinned: Bool + + public init( + id: String, + kind: SessionListGroupKind, + machineId: String? = nil, + projectPath: String? = nil, + displayName: String? = nil, + sessions: [SessionSummary] = [], + buckets: [SessionListBucketGroup] = [], + hasActive: Bool = false, + hasProjectPinned: Bool = false + ) { + self.id = id + self.kind = kind + self.machineId = machineId + self.projectPath = projectPath + self.displayName = displayName + self.sessions = sessions + self.buckets = buckets + self.hasActive = hasActive + self.hasProjectPinned = hasProjectPinned + } + + public var totalCount: Int { + sessions.count + buckets.reduce(0) { $0 + $1.sessions.count } + } +} + +/// Pure port of the web sidebar grouping rules: +/// personal pins → global pins → In progress → Active sessions → directories. +public enum SessionListGrouping { + public static let unknownMachineId = "__unknown__" + + public static func groups( + sessions: [SessionSummary], + personalPinned: Set + ) -> [SessionListGroup] { + var result: [SessionListGroup] = [] + + let personal = sessions + .filter { personalPinned.contains($0.id) } + .sorted { + if $0.updatedAt != $1.updatedAt { return $0.updatedAt > $1.updatedAt } + return $0.id < $1.id + } + if !personal.isEmpty { + result.append(SessionListGroup( + id: "personal", + kind: .personalPinned, + sessions: personal + )) + } + + let global = sessions.filter { + $0.globalPinned == true && !personalPinned.contains($0.id) + } + if !global.isEmpty { + result.append(SessionListGroup( + id: "global", + kind: .globalPinned, + sessions: global + )) + } + + var working: [SessionSummary] = [] + var pending: [SessionSummary] = [] + var active: [SessionSummary] = [] + var idle: [SessionSummary] = [] + for summary in sessions { + guard summary.active, + !personalPinned.contains(summary.id), + summary.globalPinned != true, + summary.pinned != true else { continue } + if summary.thinking || summary.backgroundTaskCount > 0 { + working.append(summary) + } else if summary.pendingRequestsCount > 0 { + pending.append(summary) + } else if summary.metadata?.lifecycleState == "idle" { + idle.append(summary) + } else { + active.append(summary) + } + } + let inProgress = makeBuckets([ + (SessionListBucket.working, working), + (.pending, pending), + ]) + if !inProgress.isEmpty { + result.append(SessionListGroup( + id: "inProgress", + kind: .inProgress, + buckets: inProgress + )) + } + let activeBuckets = makeBuckets([ + (.active, active), + (.idle, idle), + ]) + if !activeBuckets.isEmpty { + result.append(SessionListGroup( + id: "active", + kind: .active, + buckets: activeBuckets + )) + } + + var directories: [String: DirectoryAccumulator] = [:] + for summary in sessions { + guard !personalPinned.contains(summary.id), + summary.globalPinned != true else { continue } + // Non-project-pinned active sessions float into the top buckets. + if summary.active && summary.pinned != true { continue } + let path = projectPath(summary) + let machineId = summary.metadata?.machineId + let key = "\(machineId ?? unknownMachineId)::\(path)" + if directories[key] == nil { + directories[key] = DirectoryAccumulator( + path: path, + machineId: machineId, + displayName: displayName(for: path) + ) + } + directories[key]?.sessions.append(summary) + } + + let sortedDirectories = directories.map { key, value -> (SessionListGroup, Int) in + let latest = value.sessions.reduce(Int.min) { partial, session in + max(partial, session.lastUserMessageAt ?? session.createdAt ?? 0) + } + let group = SessionListGroup( + id: "dir:\(key)", + kind: .directory, + machineId: value.machineId, + projectPath: value.path, + displayName: value.displayName, + sessions: value.sessions, + hasActive: value.sessions.contains { $0.active }, + hasProjectPinned: value.sessions.contains { $0.pinned == true } + ) + return (group, latest) + } + .sorted { lhs, rhs in + if lhs.0.hasProjectPinned != rhs.0.hasProjectPinned { + return lhs.0.hasProjectPinned + } + if lhs.0.hasActive != rhs.0.hasActive { + return lhs.0.hasActive + } + if lhs.1 != rhs.1 { + return lhs.1 > rhs.1 + } + return lhs.0.id < rhs.0.id + } + .map(\.0) + result.append(contentsOf: sortedDirectories) + + return result + } + + private static func makeBuckets( + _ entries: [(SessionListBucket, [SessionSummary])] + ) -> [SessionListBucketGroup] { + entries + .filter { !$0.1.isEmpty } + .map { SessionListBucketGroup(bucket: $0.0, sessions: $0.1) } + } + + private static func projectPath(_ summary: SessionSummary) -> String { + let path = summary.metadata?.worktree?.basePath ?? summary.metadata?.path ?? "" + let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? "Other" : trimmed + } + + private static func displayName(for path: String) -> String { + let components = path + .split(whereSeparator: { $0 == "/" || $0 == "\\" }) + .map(String.init) + guard !components.isEmpty else { return path } + return components.suffix(2).joined(separator: "/") + } + + private struct DirectoryAccumulator { + var path: String + var machineId: String? + var displayName: String + var sessions: [SessionSummary] = [] + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Code/CodeBlockView.swift b/ios/Packages/HapiKit/Sources/HapiUI/Code/CodeBlockView.swift index eb81aa53..1f224dfa 100644 --- a/ios/Packages/HapiKit/Sources/HapiUI/Code/CodeBlockView.swift +++ b/ios/Packages/HapiKit/Sources/HapiUI/Code/CodeBlockView.swift @@ -14,6 +14,7 @@ public struct CodeBlockView: View { @Environment(\.hapiTheme) private var theme @Environment(\.hapiTypography) private var typography + @Environment(\.hapiCodeFontSize) private var codeFontSize @Environment(\.hapiSyntaxHighlighter) private var highlighter @Environment(\.hapiPasteboard) private var pasteboard @@ -40,7 +41,7 @@ public struct CodeBlockView: View { header ScrollView(.horizontal, showsIndicators: false) { Text(highlighted ?? AttributedString(code)) - .font(typography.codeFont) + .font(typography.codeFont(size: codeFontSize)) .lineSpacing(typography.codeLineSpacing) .foregroundStyle(theme.textPrimary) .textSelection(.enabled) diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Diff/DiffTextView.swift b/ios/Packages/HapiKit/Sources/HapiUI/Diff/DiffTextView.swift index 58380d7f..c80a04f7 100644 --- a/ios/Packages/HapiKit/Sources/HapiUI/Diff/DiffTextView.swift +++ b/ios/Packages/HapiKit/Sources/HapiUI/Diff/DiffTextView.swift @@ -12,6 +12,7 @@ public struct DiffTextView: View { @State private var expanded = false @Environment(\.hapiTheme) private var theme @Environment(\.hapiTypography) private var typography + @Environment(\.hapiCodeFontSize) private var codeFontSize public init(files: [DiffFile], compact: Bool = false, compactLineLimit: Int = 12) { self.files = files @@ -139,7 +140,7 @@ public struct DiffTextView: View { .background(theme.codeHeaderBackground) case .hunkHeader(let header): Text(header) - .font(typography.codeFont) + .font(typography.codeFont(size: codeFontSize)) .foregroundStyle(theme.textSecondary) .padding(.horizontal, 12) .padding(.vertical, 3) @@ -182,7 +183,7 @@ public struct DiffTextView: View { text.append(content) return Text(text) - .font(typography.codeFont) + .font(typography.codeFont(size: codeFontSize)) .padding(.horizontal, 12) .padding(.vertical, typography.codeLineSpacing / 2) .background(background ?? Color.clear) diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Theme/HapiTypography.swift b/ios/Packages/HapiKit/Sources/HapiUI/Theme/HapiTypography.swift index 3d2a2d5c..47a00475 100644 --- a/ios/Packages/HapiKit/Sources/HapiUI/Theme/HapiTypography.swift +++ b/ios/Packages/HapiKit/Sources/HapiUI/Theme/HapiTypography.swift @@ -24,6 +24,13 @@ public struct HapiTypography: Equatable, Sendable { public var codeLineSpacing: CGFloat { 2 * codeScale } public var bodyFont: Font { .system(size: bodySize, weight: regularWeight) } public var codeFont: Font { .system(size: codeSize, weight: regularWeight, design: .monospaced) } + + /// Code/terminal text uses the user override when present; everything + /// else keeps the Dynamic-Type-derived code size. + public func codeFont(size: CGFloat?) -> Font { + guard let size else { return codeFont } + return .system(size: size, weight: regularWeight, design: .monospaced) + } public var captionFont: Font { .system(size: captionSize, weight: regularWeight) } public var inlineCodeFont: Font { .system(size: inlineCodeSize, weight: regularWeight, design: .monospaced) } public var captionMonoFont: Font { .system(size: captionSize, weight: regularWeight, design: .monospaced) } @@ -49,11 +56,23 @@ private struct HapiTypographyKey: EnvironmentKey { static let defaultValue = HapiTypography() } +/// Optional override for terminal-styled/code text only. Kept separate from +/// `HapiTypography` so the app's existing local typography installs do not +/// reset it and chat body text is unaffected. +private struct HapiCodeFontSizeKey: EnvironmentKey { + static let defaultValue: CGFloat? = nil +} + public extension EnvironmentValues { var hapiTypography: HapiTypography { get { self[HapiTypographyKey.self] } set { self[HapiTypographyKey.self] = newValue } } + + var hapiCodeFontSize: CGFloat? { + get { self[HapiCodeFontSizeKey.self] } + set { self[HapiCodeFontSizeKey.self] = newValue } + } } private struct HapiTypographyModifier: ViewModifier { diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/DisplayPrefsTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/DisplayPrefsTests.swift new file mode 100644 index 00000000..88dba6c1 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/DisplayPrefsTests.swift @@ -0,0 +1,56 @@ +import Foundation +import HapiClient +import Testing + +@MainActor +@Suite("Display prefs") +struct DisplayPrefsTests { + private func makeDefaults() throws -> (UserDefaults, String) { + let suiteName = "DisplayPrefsTests-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + return (defaults, suiteName) + } + + @Test func defaultsMatchTheH5Steps() throws { + let (defaults, suiteName) = try makeDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + + let prefs = DisplayPrefs(defaults: defaults) + #expect(prefs.listFontScale == 1.0) + #expect(prefs.codeFontSize == 13.0) + #expect(DisplayPrefs.listFontScales == [0.8, 0.9, 1.0, 1.1, 1.2, 1.3]) + #expect(DisplayPrefs.codeFontSizes == [9, 11, 13, 15, 17]) + } + + @Test func roundTripsAndRejectsUnknownValues() throws { + let (defaults, suiteName) = try makeDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + + let prefs = DisplayPrefs(defaults: defaults) + prefs.setListFontScale(1.3) + prefs.setCodeFontSize(17) + #expect(DisplayPrefs(defaults: defaults).listFontScale == 1.3) + #expect(DisplayPrefs(defaults: defaults).codeFontSize == 17) + + prefs.setListFontScale(1.25) + prefs.setCodeFontSize(14) + #expect(prefs.listFontScale == 1.3) + #expect(prefs.codeFontSize == 17) + } + + @Test func corruptStorageDegradesToDefaults() throws { + let (defaults, suiteName) = try makeDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + defaults.set(99.0, forKey: DisplayPrefs.listFontScaleKey) + defaults.set("large", forKey: DisplayPrefs.codeFontSizeKey) + + let prefs = DisplayPrefs(defaults: defaults) + #expect(prefs.listFontScale == 1.0) + #expect(prefs.codeFontSize == 13.0) + } + + @Test func storageKeysAreStable() { + #expect(DisplayPrefs.listFontScaleKey == "settings.sessionListFontScale") + #expect(DisplayPrefs.codeFontSizeKey == "settings.codeFontSize") + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/PersonalPinStoreTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/PersonalPinStoreTests.swift new file mode 100644 index 00000000..84e9de08 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/PersonalPinStoreTests.swift @@ -0,0 +1,46 @@ +import Foundation +import HapiClient +import Testing + +@MainActor +@Suite("Personal pin store") +struct PersonalPinStoreTests { + private func makeDefaults() throws -> (UserDefaults, String) { + let suiteName = "PersonalPinStoreTests-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + return (defaults, suiteName) + } + + @Test func togglesAndPersistsSessionIds() throws { + let (defaults, suiteName) = try makeDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + + let store = PersonalPinStore(defaults: defaults) + #expect(store.sessionIds.isEmpty) + #expect(!store.contains("a")) + + store.toggle("a") + store.toggle("b") + #expect(store.contains("a")) + #expect(store.contains("b")) + + let reloaded = PersonalPinStore(defaults: defaults) + #expect(reloaded.sessionIds == ["a", "b"]) + + store.toggle("a") + #expect(!store.contains("a")) + #expect(PersonalPinStore(defaults: defaults).sessionIds == ["b"]) + } + + @Test func corruptStorageDegradesToEmpty() throws { + let (defaults, suiteName) = try makeDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + defaults.set("not-an-array", forKey: PersonalPinStore.key) + + #expect(PersonalPinStore(defaults: defaults).sessionIds.isEmpty) + } + + @Test func storageKeyIsStable() { + #expect(PersonalPinStore.key == "settings.personalPinnedSessions") + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiProtocolTests/SessionListGroupingTests.swift b/ios/Packages/HapiKit/Tests/HapiProtocolTests/SessionListGroupingTests.swift new file mode 100644 index 00000000..a3e422bb --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiProtocolTests/SessionListGroupingTests.swift @@ -0,0 +1,177 @@ +import Foundation +import HapiProtocol +import Testing + +@Suite("Session list grouping") +struct SessionListGroupingTests { + private func summary( + _ id: String, + active: Bool = true, + thinking: Bool = false, + pending: Int = 0, + kinds: [PendingRequestKind] = [], + background: Int = 0, + pinned: Bool = false, + globalPinned: Bool = false, + updatedAt: Int = 1_000, + lastUserMessageAt: Int? = nil, + path: String = "/Users/me/projects/hapi", + machineId: String? = "mac", + lifecycleState: String? = nil, + worktree: WorktreeMetadata? = nil + ) -> SessionSummary { + SessionSummary( + id: id, + active: active, + thinking: thinking, + activeAt: updatedAt, + updatedAt: updatedAt, + createdAt: updatedAt, + lastUserMessageAt: lastUserMessageAt, + pinned: pinned, + globalPinned: globalPinned, + metadata: SessionSummaryMetadata( + path: path, + machineId: machineId, + worktree: worktree, + lifecycleState: lifecycleState + ), + metadataVersion: 1, + agentStateVersion: 1, + todosUpdatedAt: 0, + pendingRequestsCount: pending, + pendingRequestKinds: kinds, + backgroundTaskCount: background + ) + } + + @Test func followsTheWebSectionOrderAndBucketPrecedence() { + let groups = SessionListGrouping.groups( + sessions: [ + summary("personal", updatedAt: 500), + summary("global", globalPinned: true), + summary("working", thinking: true), + summary("background", background: 1), + summary("pending", pending: 1, kinds: [.input]), + summary("idle", lifecycleState: "idle"), + summary("quiet"), + summary("project", pinned: true, path: "/repo/app"), + summary("inactive", active: false, updatedAt: 10, path: "/repo/app"), + ], + personalPinned: ["personal"] + ) + + let kinds: [SessionListGroupKind] = [ + .personalPinned, .globalPinned, .inProgress, .active, .directory, + ] + #expect(groups.map { $0.kind } == kinds) + #expect(groups[0].sessions.map { $0.id } == ["personal"]) + #expect(groups[1].sessions.map { $0.id } == ["global"]) + + let inProgress = groups[2] + let working = inProgress.buckets[0] + let pending = inProgress.buckets[1] + let inProgressBuckets: [SessionListBucket] = [.working, .pending] + #expect(inProgress.buckets.map { $0.bucket } == inProgressBuckets) + #expect(working.sessions.map { $0.id } == ["working", "background"]) + #expect(pending.sessions.map { $0.id } == ["pending"]) + + let active = groups[3] + let activeBuckets: [SessionListBucket] = [.active, .idle] + #expect(active.buckets.map { $0.bucket } == activeBuckets) + #expect(active.buckets[0].sessions.map { $0.id } == ["quiet"]) + #expect(active.buckets[1].sessions.map { $0.id } == ["idle"]) + + let directory = groups[4] + #expect(directory.sessions.map { $0.id } == ["project", "inactive"]) + #expect(directory.hasActive) + #expect(directory.hasProjectPinned) + } + + @Test func globalPinsExcludePersonalPinsAndNeverDuplicate() { + let groups = SessionListGrouping.groups( + sessions: [ + summary("both", globalPinned: true), + summary("globalOnly", globalPinned: true, updatedAt: 200), + ], + personalPinned: ["both"] + ) + + #expect(groups[0].kind == .personalPinned) + #expect(groups[0].sessions.map { $0.id } == ["both"]) + #expect(groups[1].kind == .globalPinned) + #expect(groups[1].sessions.map { $0.id } == ["globalOnly"]) + + let ids = groups.flatMap { group in + group.sessions.map { $0.id } + group.buckets.flatMap { $0.sessions.map { $0.id } } + } + #expect(ids.count == Set(ids).count) + } + + @Test func personalPinsSortByUpdatedAtDescending() { + let groups = SessionListGrouping.groups( + sessions: [ + summary("older", updatedAt: 100), + summary("newer", updatedAt: 300), + summary("middle", updatedAt: 200), + ], + personalPinned: ["older", "newer", "middle"] + ) + + #expect(groups[0].kind == .personalPinned) + #expect(groups[0].sessions.map { $0.id } == ["newer", "middle", "older"]) + } + + @Test func projectPinnedActiveStaysInItsDirectory() { + let groups = SessionListGrouping.groups( + sessions: [ + summary("projectPinned", active: true, thinking: true, pinned: true, path: "/repo/app"), + summary("floating", active: true, thinking: true, path: "/repo/app"), + ], + personalPinned: [] + ) + + #expect(groups.map { $0.kind } == [.inProgress, .directory]) + #expect(groups[0].buckets[0].sessions.map { $0.id } == ["floating"]) + #expect(groups[1].sessions.map { $0.id } == ["projectPinned"]) + } + + @Test func directoriesUseMachineScopedKeysAndParentLeafNames() { + let groups = SessionListGrouping.groups( + sessions: [ + summary("a", active: false, path: "/Users/me/projects/hapi", machineId: "mac"), + summary("b", active: false, path: "/Users/me/projects/hapi", machineId: "linux"), + summary("c", active: false, path: "/repo/apps/hapi", machineId: "mac"), + summary("d", active: false, path: "/repo/other", machineId: "mac"), + ], + personalPinned: [] + ) + + #expect(groups.allSatisfy { $0.kind == .directory }) + #expect(groups.map { $0.displayName } == [ + "projects/hapi", "projects/hapi", "apps/hapi", "repo/other", + ]) + #expect(groups[0].machineId == "linux") + #expect(groups[1].machineId == "mac") + #expect(groups[0].id == "dir:linux::/Users/me/projects/hapi") + #expect(groups[1].id == "dir:mac::/Users/me/projects/hapi") + } + + @Test func worktreeBasePathWinsForTheDirectoryKey() { + let worktree = WorktreeMetadata( + basePath: "/repo/base", + branch: "feature/x", + name: "feature/x" + ) + let groups = SessionListGrouping.groups( + sessions: [ + summary("worktree", active: false, path: "/repo/base/.worktrees/x", worktree: worktree), + ], + personalPinned: [] + ) + + #expect(groups.count == 1) + #expect(groups[0].projectPath == "/repo/base") + #expect(groups[0].displayName == "repo/base") + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiUITests/TypographyTests.swift b/ios/Packages/HapiKit/Tests/HapiUITests/TypographyTests.swift index 4aab368d..d2f0b1b1 100644 --- a/ios/Packages/HapiKit/Tests/HapiUITests/TypographyTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiUITests/TypographyTests.swift @@ -31,6 +31,17 @@ struct TypographyTests { #expect(MarkdownBlockListView.spacing(before: paragraph, after: paragraph) == 12) } + @Test func codeFontOverrideUsesTheProvidedSize() { + var values = EnvironmentValues() + #expect(values.hapiCodeFontSize == nil) + values.hapiCodeFontSize = 17 + #expect(values.hapiCodeFontSize == 17) + + let typography = HapiTypography() + #expect(typography.codeFont(size: nil) == typography.codeFont) + #expect(typography.codeFont(size: 17) != typography.codeFont(size: 13)) + } + @Test func conversationRhythmDoesNotMistakeHistoryForANewTurn() { #expect(TranscriptRowRole.user.spacing(after: nil) == 12) #expect(TranscriptRowRole.user.spacing(after: .history) == 12) diff --git a/ios/README.md b/ios/README.md index b8c99108..0cc9a16f 100644 --- a/ios/README.md +++ b/ios/README.md @@ -21,6 +21,16 @@ archive (active) or reopen/delete (inactive), from the row's context menu or the chat's … menu; sending to an inactive session or reopening it can resume it and migrate the draft/navigation when the returned session ID changes. +The list mirrors the web sidebar's core structure: **My sessions** (client-only +personal pins) and global **Pins** first, then collapsible **In progress** +(running/pending) and **Active sessions** (active/idle) sections, then collapsible +project/folder groups. Rows show `project · machine` in pinned/bucket sections and +the worktree name inside a folder; group headers carry counts, and selecting a +session expands its folder. Collapsed states are in-memory and reset on launch. +Settings → Appearance controls **List text size** (80–130%, list only) and +**Code & terminal text size** (9–17 pt, CLI output/code blocks/diffs) independently +of Dynamic Type. + Agent-displayed media (`display_image`, `display_video`, `display_media`) uses MIME-based cards: images load automatically, while video, audio and other files load only on request. Video/audio use native playback controls without autoplay;