Skip to content

armgit / cra

Public Imported from GitHub
0

The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.

Tidy Tabs on the Mac's own Apple Intelligence, like Arc Max's

Victor6301fcb2229b
diff --git a/CLAUDE.md b/CLAUDE.md
index 9cedda5..fe8ef93 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,6 +1,6 @@
# Cra: notes for coding agents
-[CONTRIBUTING.md](CONTRIBUTING.md) says what fits (Arc parity by default, no built-in AI,
+[CONTRIBUTING.md](CONTRIBUTING.md) says what fits (Arc parity by default, no cloud AI,
nothing leaves the Mac) and how to send a change. [docs/development.md](docs/development.md)
has the layout and the tests, and [docs/testing.md](docs/testing.md) has the test rules. This
file holds the layer rules.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 47b2a21..4bdac55 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -10,8 +10,9 @@ you can send. Code is welcome too, within the few rules below.
include a screenshot or clip of both. Arc isn't the only source of truth, though: if
Arc's way is unintuitive or worse than it could be, open an issue that makes the case,
and we'll decide it on its merits.
-- **No built-in AI.** Arc Max-style features (tidy tabs, summaries, LLM search) are out
- of scope.
+- **No cloud AI.** Arc Max-style features (summaries, LLM search, anything that needs an
+ API key or sends pages away) are out of scope. The one exception is Tidy Tabs, which runs
+ on the Mac's own Apple Intelligence model and only shows when that is turned on.
- **No account, no server, no telemetry.** Everything stays on the user's Mac.
- **Native first.** The app is AppKit and SwiftUI; web content is Chromium through CEF.
diff --git a/Packages/CraCore/Sources/CraCore/SidebarModel.swift b/Packages/CraCore/Sources/CraCore/SidebarModel.swift
index aca15de..ebae93b 100644
--- a/Packages/CraCore/Sources/CraCore/SidebarModel.swift
+++ b/Packages/CraCore/Sources/CraCore/SidebarModel.swift
@@ -176,9 +176,12 @@ public struct SidebarItem: Identifiable, Codable, Equatable {
public var folderIcon: FolderIconStyle? = nil
/// Set on a folder that fills itself (Arc: list.automaticLiveFolderData).
public var liveFolder: LiveFolderData? = nil
+ /// A Today folder shown as a group header, as Tidy Tabs makes them (Arc: SidebarItemData.tabGroup,
+ /// its title in `title`). Kept on a folder so a Cra that predates groups still reads the file.
+ public var tabGroup: Bool? = nil
public init(id: UUID, parentID: UUID?, title: String?, children: [UUID], isUnread: Bool, createdAt: Date, data: ItemData,
- folderIcon: FolderIconStyle? = nil, liveFolder: LiveFolderData? = nil) {
+ folderIcon: FolderIconStyle? = nil, liveFolder: LiveFolderData? = nil, tabGroup: Bool? = nil) {
self.id = id
self.parentID = parentID
self.title = title
@@ -188,6 +191,7 @@ public struct SidebarItem: Identifiable, Codable, Equatable {
self.data = data
self.folderIcon = folderIcon
self.liveFolder = liveFolder
+ self.tabGroup = tabGroup
}
public var tab: TabData? {
@@ -197,6 +201,7 @@ public struct SidebarItem: Identifiable, Codable, Equatable {
public var isTab: Bool { tab != nil }
public var isFolder: Bool { if case .folder = data { return true }; return false }
public var isLiveFolder: Bool { isFolder && liveFolder != nil }
+ public var isTabGroup: Bool { isFolder && tabGroup == true }
public var split: SplitData? {
if case .split(let s) = data { return s }
return nil
@@ -238,6 +243,11 @@ public struct SidebarItem: Identifiable, Codable, Equatable {
createdAt: Date(), data: .folder)
}
+ public static func tabGroup(_ name: String, parent: UUID?) -> SidebarItem {
+ SidebarItem(id: UUID(), parentID: parent, title: name, children: [], isUnread: false,
+ createdAt: Date(), data: .folder, tabGroup: true)
+ }
+
public static func container(_ kind: ContainerKind, id: UUID = UUID()) -> SidebarItem {
SidebarItem(id: id, parentID: nil, title: nil, children: [], isUnread: false,
createdAt: Date(), data: .container(kind))
@@ -508,6 +518,9 @@ public struct AppSettings: Codable, Equatable {
public static let perfRecordingDefault = true
/// Settings ▸ Performance ▸ "Hide site names": every site in the diagnostics zip becomes site-N.
public var perfHidesSiteNames: Bool = false
+ /// Arc Max's Tidy Tabs (tidyTabsEnabled), done by the Mac's Apple Intelligence model: the Today
+ /// divider's Tidy button. On by default; the button only shows while Apple Intelligence is on.
+ public var tidyTabs: Bool = true
public init() {}
@@ -670,6 +683,7 @@ extension AppSettings {
edgeToEdgeContent = try c.decodeIfPresent(Bool.self, forKey: .edgeToEdgeContent) ?? false
perfRecording = try c.decodeIfPresent(Bool.self, forKey: .perfRecording) ?? Self.perfRecordingDefault
perfHidesSiteNames = try c.decodeIfPresent(Bool.self, forKey: .perfHidesSiteNames) ?? false
+ tidyTabs = try c.decodeIfPresent(Bool.self, forKey: .tidyTabs) ?? true
}
}
diff --git a/Packages/CraCore/Sources/CraCore/TidyTabs.swift b/Packages/CraCore/Sources/CraCore/TidyTabs.swift
new file mode 100644
index 0000000..2f8dfe0
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/TidyTabs.swift
@@ -0,0 +1,128 @@
+import Foundation
+
+/// Arc's Tidy Tabs (Arc Max, `createUnpinnedTabGroups()`), done with the Mac's own Apple Intelligence
+/// model instead of Arc's server. The divider's Tidy button sorts a space's loose Today tabs under
+/// named group headers (Arc's `SidebarItemData.tabGroup`): the model only proposes names and members;
+/// everything here decides what the sidebar does with that answer. Arc 1.171, 4 Nov 2026.
+public enum TidyTabs {
+ /// Arc 1.171 (canAutoOrganizeTodayTabs, offline copy, 4 Nov 2026): Tidy shows once Today holds six
+ /// tabs, grouped ones included (five loose tabs: only Clear; two loose and six grouped: Tidy).
+ public static let minimumTabs = 6
+ /// A model answer can't hold a sidebar's worth of tabs: the on-device model reads ~4K tokens.
+ public static let maximumTabs = 60
+ static let maximumTitleLength = 80
+ static let maximumNameLength = 32
+
+ /// One loose Today tab as the model sees it: its place in the prompt is its id.
+ public struct Tab: Equatable, Sendable {
+ public var title: String
+ public var host: String
+ public init(title: String, host: String) {
+ self.title = title
+ self.host = host
+ }
+ }
+
+ /// One group of the model's answer: tab ids from the prompt.
+ public struct Proposal: Equatable, Sendable {
+ public var name: String
+ public var tabs: [Int]
+ public init(name: String, tabs: [Int]) {
+ self.name = name
+ self.tabs = tabs
+ }
+ }
+
+ /// What the sidebar does: new groups, in order, and tabs added to groups Today already has.
+ public struct Plan: Equatable, Sendable {
+ public var newGroups: [Proposal]
+ /// Existing group index (as passed in) → tab ids joining it.
+ public var joins: [Int: [Int]]
+ public init(newGroups: [Proposal], joins: [Int: [Int]]) {
+ self.newGroups = newGroups
+ self.joins = joins
+ }
+ public var isEmpty: Bool { newGroups.isEmpty && joins.isEmpty }
+ }
+
+ /// Whether the divider offers Tidy: Today holds enough tabs, one of them loose, and a loose tab
+ /// came in since the last run (`tidied`: Today's tabs then). Arc hid the button after a run, even
+ /// one that grouped nothing, and a second click on that spot did nothing.
+ public static func offers<ID: Hashable>(todayTabs: Int, looseTabs: [ID], tidied: Set<ID>?) -> Bool {
+ guard todayTabs >= minimumTabs, !looseTabs.isEmpty else { return false }
+ guard let tidied else { return true }
+ return looseTabs.contains { !tidied.contains($0) }
+ }
+
+ public static let instructions = """
+ You sort a person's open browser tabs into groups, like tidying loose papers into labelled folders. \
+ Put tabs about the same topic, task or project in one group, even when they come from different websites. \
+ Make two to six groups and give each tab to exactly one group if it fits; a group needs at least two tabs. \
+ Name each group with the topic, not the website.
+ """
+
+ /// The request: Arc's "Here are my tabs, in the format 'id: title':", plus the site, and the
+ /// groups Today already has so new tabs can join them (Arc does that on a second Tidy).
+ public static func prompt(tabs: [Tab], existingGroups: [String]) -> String {
+ var lines = ["Here are my tabs, as 'id: title (site)':"]
+ for (i, t) in tabs.prefix(maximumTabs).enumerated() {
+ let title = clip(t.title.isEmpty ? t.host : t.title, maximumTitleLength)
+ lines.append(t.host.isEmpty ? "\(i): \(title)" : "\(i): \(title) (\(t.host))")
+ }
+ if !existingGroups.isEmpty {
+ lines.append("")
+ lines.append("I already have these groups; reuse a name exactly to add tabs to it: "
+ + existingGroups.map { "\"\($0)\"" }.joined(separator: ", ") + ".")
+ }
+ return lines.joined(separator: "\n")
+ }
+
+ /// The model's answer made safe: ids in range and used once (first group wins), names trimmed
+ /// and capped, a name that matches an existing group (any case) adds to it, two new groups with
+ /// one name merge, and a new group needs two tabs. New groups keep the order of their first tab.
+ public static func plan(_ proposals: [Proposal], tabCount: Int, existingGroups: [String]) -> Plan {
+ var used = Set<Int>()
+ var joins: [Int: [Int]] = [:]
+ var newGroups: [Proposal] = []
+ let existing = existingGroups.map(key)
+ for p in proposals {
+ let name = clip(p.name.trimmingCharacters(in: .whitespacesAndNewlines.union(.punctuationCharacters)), maximumNameLength)
+ guard !name.isEmpty else { continue }
+ var ids: [Int] = []
+ for id in p.tabs where id >= 0 && id < min(tabCount, maximumTabs) && !used.contains(id) {
+ used.insert(id)
+ ids.append(id)
+ }
+ guard !ids.isEmpty else { continue }
+ if let e = existing.firstIndex(of: key(name)) {
+ joins[e, default: []].append(contentsOf: ids)
+ } else if let n = newGroups.firstIndex(where: { key($0.name) == key(name) }) {
+ newGroups[n].tabs.append(contentsOf: ids)
+ } else {
+ newGroups.append(Proposal(name: name, tabs: ids))
+ }
+ }
+ newGroups = newGroups.filter { $0.tabs.count >= 2 }.map { Proposal(name: $0.name, tabs: $0.tabs.sorted()) }
+ newGroups.sort { ($0.tabs.first ?? 0) < ($1.tabs.first ?? 0) }
+ return Plan(newGroups: newGroups, joins: joins.mapValues { $0.sorted() })
+ }
+
+ /// Today's top level after a tidy: loose tabs left over first, in their order (Arc keeps new
+ /// tabs above the groups), then the groups Today had, then the new ones. `Item` is either a loose
+ /// tab or a group; `isGroup` tells them apart.
+ public static func order<ID: Hashable>(today: [ID], isGroup: (ID) -> Bool, grouped: Set<ID>, newGroups: [ID]) -> [ID] {
+ let loose = today.filter { !isGroup($0) && !grouped.contains($0) }
+ let groups = today.filter(isGroup)
+ return loose + groups + newGroups
+ }
+
+ static func key(_ name: String) -> String {
+ name.folding(options: [.caseInsensitive, .diacriticInsensitive, .widthInsensitive], locale: nil)
+ .trimmingCharacters(in: .whitespaces)
+ }
+
+ static func clip(_ s: String, _ n: Int) -> String {
+ let one = s.split(whereSeparator: \.isNewline).joined(separator: " ")
+ return one.count <= n ? one : String(one.prefix(n - 1)) + "…"
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/TidyTabsTests.swift b/Packages/CraCore/Tests/CraCoreTests/TidyTabsTests.swift
new file mode 100644
index 0000000..0cb972d
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/TidyTabsTests.swift
@@ -0,0 +1,89 @@
+import CraCore
+import Foundation
+import Testing
+
+/// Arc's Tidy Tabs with the Mac's own model: what the sidebar makes of the model's answer.
+struct TidyTabsTests {
+ @Test func offeredFromSixTodayTabsUntilTidied() {
+ let six = ["a", "b", "c", "d", "e", "f"]
+ #expect(TidyTabs.offers(todayTabs: 6, looseTabs: six, tidied: nil))
+ #expect(!TidyTabs.offers(todayTabs: 5, looseTabs: Array(six.prefix(5)), tidied: nil))
+ // Grouped tabs count (Arc: two loose and six grouped offered Tidy); nothing loose, nothing to do.
+ #expect(TidyTabs.offers(todayTabs: 8, looseTabs: ["a", "b"], tidied: nil))
+ #expect(!TidyTabs.offers(todayTabs: 8, looseTabs: [String](), tidied: nil))
+ // After a run (even one that grouped nothing) the tabs it saw don't bring it back…
+ #expect(!TidyTabs.offers(todayTabs: 6, looseTabs: six.reversed(), tidied: Set(six)))
+ #expect(!TidyTabs.offers(todayTabs: 6, looseTabs: ["a"], tidied: Set(six)))
+ // …a new tab does.
+ #expect(TidyTabs.offers(todayTabs: 7, looseTabs: ["a", "g"], tidied: Set(six)))
+ }
+
+ @Test func promptListsTabsWithIdsAndExistingGroups() {
+ let p = TidyTabs.prompt(tabs: [.init(title: "Mars - Wikipedia", host: "en.wikipedia.org"),
+ .init(title: "", host: "example.com"),
+ .init(title: "Line one\nline two", host: "")],
+ existingGroups: ["Bread"])
+ #expect(p == """
+ Here are my tabs, as 'id: title (site)':
+ 0: Mars - Wikipedia (en.wikipedia.org)
+ 1: example.com (example.com)
+ 2: Line one line two
+
+ I already have these groups; reuse a name exactly to add tabs to it: "Bread".
+ """)
+ }
+
+ @Test func promptCutsLongTitlesAndTabLists() {
+ let tabs = Array(repeating: TidyTabs.Tab(title: String(repeating: "x", count: 200), host: "h"), count: 100)
+ let lines = TidyTabs.prompt(tabs: tabs, existingGroups: []).split(separator: "\n")
+ #expect(lines.count == TidyTabs.maximumTabs + 1)
+ #expect(lines[1] == "0: " + String(repeating: "x", count: 79) + "… (h)")
+ }
+
+ @Test func planDropsBadIdsDuplicatesAndOneTabGroups() {
+ let plan = TidyTabs.plan([.init(name: "Planets", tabs: [6, 0, 3, 99, -1]),
+ .init(name: "Bread", tabs: [1, 4, 7, 0]),
+ .init(name: "Email", tabs: [8]),
+ .init(name: " ", tabs: [2, 5])],
+ tabCount: 9, existingGroups: [])
+ #expect(plan.newGroups == [.init(name: "Planets", tabs: [0, 3, 6]), .init(name: "Bread", tabs: [1, 4, 7])])
+ #expect(plan.joins.isEmpty)
+ }
+
+ @Test func planMergesSameNamesAndJoinsExistingGroups() {
+ let plan = TidyTabs.plan([.init(name: "Python", tabs: [4]),
+ .init(name: "bread.", tabs: [0]),
+ .init(name: "python", tabs: [2]),
+ .init(name: "Travel", tabs: [3, 1])],
+ tabCount: 5, existingGroups: ["Planets", "Bread"])
+ #expect(plan.joins == [1: [0]])
+ // New groups follow their first tab's place.
+ #expect(plan.newGroups == [.init(name: "Travel", tabs: [1, 3]), .init(name: "Python", tabs: [2, 4])])
+ }
+
+ @Test func planCapsNames() {
+ let plan = TidyTabs.plan([.init(name: String(repeating: "n", count: 50), tabs: [0, 1])], tabCount: 2, existingGroups: [])
+ #expect(plan.newGroups.first?.name.count == 32)
+ #expect(TidyTabs.plan([], tabCount: 3, existingGroups: []).isEmpty)
+ }
+
+ @Test func orderKeepsLooseTabsAboveTheGroups() {
+ let today = ["t1", "G", "t2", "t3", "t4"]
+ let order = TidyTabs.order(today: today, isGroup: { $0.hasPrefix("G") || $0.hasPrefix("N") },
+ grouped: ["t2", "t4"], newGroups: ["N1", "N2"])
+ #expect(order == ["t1", "t3", "G", "N1", "N2"])
+ }
+}
+
+/// A tab group is a folder with a mark, so a Cra from before groups still reads the file.
+struct TabGroupItemTests {
+ @Test func groupRoundTripsAndPlainFoldersWriteNoMark() throws {
+ let group = SidebarItem.tabGroup("Planets", parent: nil)
+ #expect(group.isFolder && group.isTabGroup && group.title == "Planets")
+ let data = try JSONEncoder().encode(group)
+ #expect(try JSONDecoder().decode(SidebarItem.self, from: data) == group)
+ let folder = try JSONEncoder().encode(SidebarItem.folder("F", parent: nil))
+ #expect(!String(decoding: folder, as: UTF8.self).contains("tabGroup"))
+ #expect(try !JSONDecoder().decode(SidebarItem.self, from: folder).isTabGroup)
+ }
+}
diff --git a/README.md b/README.md
index 6e41594..90ee414 100644
--- a/README.md
+++ b/README.md
@@ -70,7 +70,7 @@ Embedded Framework, so sites and Chrome extensions work as they do in Chrome.
| Boosts | Not yet |
| Peek | ✅ |
| Notes | Not yet |
-| Arc Max | No, Cra has no built-in AI |
+| Arc Max | Tidy Tabs only, on the Mac's Apple Intelligence; nothing goes to a server |
The [roadmap](https://crabrowser.app/roadmap) lists what's next.
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index bd8aa2c..bf61a7f 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -609,6 +609,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
return
}
if let st = dict["status"] { main.browserManager(statusMessage: st); return }
+ // tidy: the divider's Tidy on the window's space, without hovering it; undoTidy: ⌘Z's.
+ if dict["tidy"] != nil { TidyTabsService.shared.tidy(store.focusedSpace(window: main.windowID).id, store: store); return }
+ if dict["undoTidy"] != nil { _ = store.undoTidy(); return }
// Scenario hooks (scripts/scenario.sh): what a journey needs without a pointer.
if dict["checkStore"] != nil { logSidebarProblems(); return }
// A main-thread stall of this many milliseconds, for the performance recorder's tests.
@@ -911,8 +914,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
return false
}
- /// Arc: ⌘Z brings back the tab you closed last (closing registers an undo, GitHub #21),
- /// unless the keyboard is in something with text to undo: a text field, or an editable
+ /// Arc: ⌘Z brings back the tab you closed last (closing registers an undo, GitHub #21), or undoes
+ /// the last Tidy, unless the keyboard is in something with text to undo: a text field, or an editable
/// element in a page (Chromium's page view reports its ui::TextInputType, 0 = none).
private func undoClosedTab(_ event: NSEvent) -> Bool {
guard Shortcut("z", .command).matches(event) else { return false }
@@ -921,7 +924,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
if let view = responder as? NSView, NSStringFromClass(type(of: view)) == "RenderWidgetHostViewCocoa",
view.responds(to: NSSelectorFromString("textInputType")),
(view.value(forKey: "textInputType") as? Int ?? 0) != 0 { return false }
- perform("reopenClosedTab")
+ // The last thing to undo may be a tidy (Arc's "Undo Tidy Tabs"); a tab closed since comes first.
+ if !store.undoTidy() { perform("reopenClosedTab") }
return true
}
diff --git a/Sources/Cra/Services/SidebarStore.swift b/Sources/Cra/Services/SidebarStore.swift
index d1d90ce..c5579b8 100644
--- a/Sources/Cra/Services/SidebarStore.swift
+++ b/Sources/Cra/Services/SidebarStore.swift
@@ -202,6 +202,7 @@ final class SidebarStore {
}
private func touch() {
+ pruneEmptyGroups()
revision &+= 1
save()
}
@@ -677,12 +678,15 @@ final class SidebarStore {
return
}
let fromParent = it.parentID
+ // A tab group lives at the top of Today and holds tabs and splits only (Arc's tabGroup items).
+ if it.isTabGroup, items[newParent]?.container != .today(spaceID: spaceID(ofItem: id) ?? UUID()) { return }
+ if items[newParent]?.isTabGroup == true, !(it.isTab || it.isSplit) { return }
// A live folder fills itself: nothing is dropped into it, and it never unpacks into Today.
if items[newParent]?.isLiveFolder == true, fromParent != newParent { return }
if it.isLiveFolder, case .today? = rootContainerKind(newParent) { return }
if fromParent != newParent, let from = fromParent, items[from]?.isLiveFolder == true { hideLiveItem(id, in: from) }
let oldIndex = fromParent.flatMap { items[$0]?.children.firstIndex(of: id) }
- if it.isFolder, case .today? = rootContainerKind(newParent) {
+ if it.isFolder, !it.isTabGroup, case .today? = rootContainerKind(newParent) {
// Unpack: move the folder's tabs instead.
let kids = it.children
detach(id)
@@ -1268,9 +1272,9 @@ final class SidebarStore {
// the item's signal, not on `prefs`, which changes on every tab switch and window move;
// `notifyItemReaders` signals the items whose state actually changed.
+ /// A tab group is always open: it has a header, not a folder's disclosure (Arc's TabGroupHeaderCellView).
func isExpanded(_ id: UUID) -> Bool {
- items.observe(id)
- return _prefs.expandedFolders.contains(id)
+ items[id]?.isTabGroup == true || _prefs.expandedFolders.contains(id)
}
/// The tabs a closed folder lists under itself (FolderPeek), in sidebar order.
@@ -1290,7 +1294,7 @@ final class SidebarStore {
if c.isTab { return [c.id] }
if let s = c.split { return [s.focusTabID.flatMap { c.children.contains($0) ? $0 : nil } ?? c.children.first].compactMap { $0 } }
guard c.isFolder else { return [] }
- return _prefs.expandedFolders.contains(c.id) ? shownTabs(under: c.id) : peekedTabs(in: c.id).map(\.id)
+ return c.isTabGroup || _prefs.expandedFolders.contains(c.id) ? shownTabs(under: c.id) : peekedTabs(in: c.id).map(\.id)
}
}
@@ -1522,6 +1526,8 @@ final class SidebarStore {
func archiveTab(_ id: UUID, reason: ArchiveReason) {
guard let it = items[id], it.isTab else { return }
+ // ⌘Z now brings this tab back, not the tidy before it (Arc's undo stack).
+ lastTidy = nil
let sid = spaceID(ofItem: id)
// Each window and space that has it open, every space sharing it for a favorite.
let shownIn = spaceIDs(ofItem: id)
@@ -1622,6 +1628,136 @@ final class SidebarStore {
touch()
}
+ // MARK: Tab groups (Tidy Tabs)
+
+ /// Spaces whose Today tabs the model is sorting: the divider draws its squiggle meanwhile.
+ private(set) var tidyingSpaces: Set<UUID> = []
+ /// Per space, Today's tabs when Tidy last ran: Tidy waits for a new loose tab (TidyTabs.offers).
+ /// Not saved, like Arc's.
+ private(set) var tidiedTabs: [UUID: Set<UUID>] = [:]
+ /// What ⌘Z puts back: the last tidy, until a tab closes or a group's header is used.
+ @ObservationIgnored private var lastTidy: (spaceID: UUID, todayBefore: [UUID], moved: [UUID])?
+
+ /// Today's top-level tabs, outside any group: what Tidy sorts.
+ func looseTodayTabs(_ sid: UUID) -> [SidebarItem] {
+ guard let space = spaces[sid] else { return [] }
+ return children(of: space.todayContainerID).filter(\.isTab)
+ }
+
+ func tabGroups(in sid: UUID) -> [SidebarItem] {
+ guard let space = spaces[sid] else { return [] }
+ return children(of: space.todayContainerID).filter(\.isTabGroup)
+ }
+
+ /// Whether the divider offers Tidy now (the Apple Intelligence check is the caller's).
+ func canTidy(_ sid: UUID) -> Bool {
+ guard let space = spaces[sid], !isIncognito(space: sid) else { return false }
+ return TidyTabs.offers(todayTabs: tabs(under: space.todayContainerID).count,
+ looseTabs: looseTodayTabs(sid).map(\.id), tidied: tidiedTabs[sid])
+ }
+
+ func setTidying(_ sid: UUID, _ on: Bool) {
+ if on { tidyingSpaces.insert(sid) } else { tidyingSpaces.remove(sid) }
+ }
+
+ /// Sorts `tabIDs` (the loose tabs the model saw, in prompt order) as the plan says: new groups
+ /// under the loose tabs left over, tabs joining groups Today already had. A plan that changes
+ /// nothing still counts as a run, as Arc's did.
+ func applyTidy(_ plan: TidyTabs.Plan, tabIDs: [UUID], in sid: UUID) {
+ guard let space = spaces[sid] else { return }
+ let today = space.todayContainerID
+ let before = items[today]?.children ?? []
+ let groups = tabGroups(in: sid)
+ let loose = Set(looseTodayTabs(sid).map(\.id))
+ func ids(_ indices: [Int]) -> [UUID] {
+ indices.compactMap { tabIDs.indices.contains($0) ? tabIDs[$0] : nil }.filter(loose.contains)
+ }
+ var moved: [UUID] = []
+ for (g, indices) in plan.joins.sorted(by: { $0.key < $1.key }) where groups.indices.contains(g) {
+ let tabs = ids(indices)
+ moveItems(tabs, to: groups[g].id, index: nil)
+ moved += tabs
+ }
+ var newGroups: [UUID] = []
+ for p in plan.newGroups {
+ let tabs = ids(p.tabs)
+ guard tabs.count >= 2 else { continue }
+ var g = SidebarItem.tabGroup(p.name, parent: today)
+ g.createdAt = clock.now
+ items[g.id] = g
+ var t = items[today]!
+ t.children.append(g.id)
+ items[today] = t
+ moveItems(tabs, to: g.id, index: nil)
+ newGroups.append(g.id)
+ moved += tabs
+ }
+ if var t = items[today] {
+ let rest = t.children.filter { !newGroups.contains($0) }
+ t.children = TidyTabs.order(today: rest, isGroup: { self.items[$0]?.isTabGroup == true }, grouped: [], newGroups: newGroups)
+ items[today] = t
+ }
+ lastTidy = moved.isEmpty ? nil : (sid, before, moved)
+ tidiedTabs[sid] = Set(tabs(under: today).map(\.id))
+ touch()
+ }
+
+ /// A run that ended without a plan (the model failed or had nothing to say) still hides Tidy.
+ func markTidied(_ sid: UUID) {
+ guard let space = spaces[sid] else { return }
+ tidiedTabs[sid] = Set(tabs(under: space.todayContainerID).map(\.id))
+ }
+
+ /// ⌘Z after a tidy: the tabs it moved go back where they were, its new groups go with them.
+ func undoTidy() -> Bool {
+ guard let u = lastTidy, let space = spaces[u.spaceID] else { return false }
+ lastTidy = nil
+ let today = space.todayContainerID
+ for id in u.moved where items[id] != nil && items[id]?.parentID != today {
+ moveItem(id, to: today, index: nil)
+ }
+ if var t = items[today] {
+ let old = u.todayBefore.filter(t.children.contains)
+ t.children = t.children.filter { !old.contains($0) } + old
+ items[today] = t
+ }
+ tidiedTabs[u.spaceID] = nil
+ touch()
+ return true
+ }
+
+ /// Arc's "Remove header": the tabs stay where they are, loose.
+ func removeGroupHeader(_ id: UUID) {
+ guard let g = items[id], g.isTabGroup, let p = g.parentID, let at = items[p]?.children.firstIndex(of: id) else { return }
+ lastTidy = nil
+ moveItems(g.children, to: p, index: at)
+ touch()
+ }
+
+ /// Arc's "Create Folder" on a group header: an open folder of that name leads the space's
+ /// pinned tabs, holding the group's tabs (pinned now); the group goes.
+ @discardableResult
+ func folderFromGroup(_ id: UUID) -> SidebarItem? {
+ guard let g = items[id], g.isTabGroup, let sid = spaceID(ofItem: id), let space = spaces[sid] else { return nil }
+ lastTidy = nil
+ let f = createFolder(named: g.title ?? "Folder", in: space.pinnedContainerID, index: 0)
+ moveItems(g.children, to: f.id, index: nil)
+ touch()
+ return items[f.id]
+ }
+
+ /// A group whose last tab closed or moved out goes too (Arc never shows an empty header).
+ private func pruneEmptyGroups() {
+ for space in spaces.values {
+ guard var t = items[space.todayContainerID] else { continue }
+ let empty = t.children.filter { items[$0].map { $0.isTabGroup && $0.children.isEmpty } ?? false }
+ guard !empty.isEmpty else { continue }
+ t.children.removeAll { empty.contains($0) }
+ items[t.id] = t
+ for g in empty { items[g] = nil }
+ }
+ }
+
func clearToday(_ sid: UUID? = nil) {
guard let space = spaces[sid ?? focusedSpaceID] else { return }
for t in tabs(under: space.todayContainerID) { archiveTab(t.id, reason: .clear) }
diff --git a/Sources/Cra/Services/TidyTabsService.swift b/Sources/Cra/Services/TidyTabsService.swift
new file mode 100644
index 0000000..4d285f6
--- /dev/null
+++ b/Sources/Cra/Services/TidyTabsService.swift
@@ -0,0 +1,153 @@
+import AppKit
+import Foundation
+import Observation
+#if canImport(FoundationModels)
+import FoundationModels
+#endif
+
+/// Tidy Tabs on the Mac's own Apple Intelligence model (FoundationModels, macOS 26): free, and
+/// nothing leaves the Mac. Arc sent the same "id: title" list to its server (Arc Max). Without
+/// Apple Intelligence (an older macOS, a Mac that can't run it, or it is off) the Tidy button
+/// doesn't show at all. What the answer does to the sidebar is TidyTabs (CraCore) and the store.
+@MainActor @Observable
+final class TidyTabsService {
+ static let shared = TidyTabsService()
+
+ /// Whether the system model can run now. Read again when Cra comes to the front, so turning
+ /// Apple Intelligence on in System Settings shows the button without a relaunch.
+ private(set) var modelAvailable = false
+ /// Why not, for Settings (nil while available).
+ private(set) var unavailableReason: String? = "Needs macOS 26 and Apple Intelligence."
+
+ @ObservationIgnored private var activation: NSObjectProtocol?
+
+ private init() {
+ refresh()
+ activation = NotificationCenter.default.addObserver(forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main) { _ in
+ MainActor.assumeIsolated { TidyTabsService.shared.refresh() }
+ }
+ }
+
+ func refresh() {
+ // A test copy can stand in a fixed model (CRA_TIDY_FAKE_MODEL=1) where Apple Intelligence is off.
+ if Self.fakeModel {
+ set(available: true, reason: nil)
+ return
+ }
+ #if canImport(FoundationModels)
+ if #available(macOS 26.0, *) {
+ switch SystemLanguageModel.default.availability {
+ case .available: set(available: true, reason: nil)
+ case .unavailable(.appleIntelligenceNotEnabled):
+ set(available: false, reason: "Turn on Apple Intelligence in System Settings to use it.")
+ case .unavailable(.deviceNotEligible):
+ set(available: false, reason: "This Mac can’t run Apple Intelligence.")
+ case .unavailable(.modelNotReady):
+ set(available: false, reason: "Apple Intelligence is still getting ready.")
+ case .unavailable:
+ set(available: false, reason: "Apple Intelligence isn’t available right now.")
+ }
+ return
+ }
+ #endif
+ set(available: false, reason: "Needs macOS 26 and Apple Intelligence.")
+ }
+
+ private func set(available: Bool, reason: String?) {
+ if modelAvailable != available { modelAvailable = available }
+ if unavailableReason != reason { unavailableReason = reason }
+ }
+
+ /// Whether the divider may show Tidy for this space now.
+ func offers(_ sid: UUID, store: SidebarStore) -> Bool {
+ modelAvailable && store.settings.tidyTabs && store.canTidy(sid)
+ }
+
+ /// The Tidy button: ask the model about the space's loose Today tabs and apply its answer.
+ func tidy(_ sid: UUID, store: SidebarStore) {
+ guard modelAvailable, !store.tidyingSpaces.contains(sid) else { return }
+ let loose = Array(store.looseTodayTabs(sid).prefix(TidyTabs.maximumTabs))
+ guard !loose.isEmpty else { return }
+ let tabs = loose.map { item in
+ TidyTabs.Tab(title: item.displayTitle, host: item.tab.flatMap { URL(string: $0.url)?.host() } ?? "")
+ }
+ let groups = store.tabGroups(in: sid).map { $0.title ?? "" }
+ let ids = loose.map(\.id)
+ let prompt = TidyTabs.prompt(tabs: tabs, existingGroups: groups)
+ store.setTidying(sid, true)
+ let started = Date()
+ Task { @MainActor in
+ let proposals = await Self.ask(prompt)
+ // Counts and time only: tab titles stay out of the log (it goes into diagnostics).
+ CraLog.note(String(format: "Tidy Tabs: %d tabs, %d groups proposed in %.1f s", tabs.count, proposals?.count ?? -1,
+ Date().timeIntervalSince(started)))
+ // The squiggle runs at least one full swing of the broom, so a quick answer doesn't flash.
+ let rest = SidebarTidyMetrics.minimumRun - Date().timeIntervalSince(started)
+ if rest > 0 { try? await Task.sleep(for: .seconds(rest)) }
+ store.setTidying(sid, false)
+ guard let proposals else {
+ store.markTidied(sid)
+ return
+ }
+ // The list slides the tabs under their new headers (SpaceListView.placeViews).
+ store.applyTidy(TidyTabs.plan(proposals, tabCount: tabs.count, existingGroups: groups), tabIDs: ids, in: sid)
+ }
+ }
+
+ /// The model's groups, nil when it couldn't answer.
+ private static func ask(_ prompt: String) async -> [TidyTabs.Proposal]? {
+ if fakeModel { return await fakeAnswer(prompt) }
+ #if canImport(FoundationModels)
+ if #available(macOS 26.0, *) {
+ do {
+ let session = LanguageModelSession(instructions: TidyTabs.instructions)
+ let answer = try await session.respond(to: prompt, generating: TidyAnswer.self,
+ options: GenerationOptions(sampling: .greedy))
+ return answer.content.groups.map { TidyTabs.Proposal(name: $0.name, tabs: $0.tabs) }
+ } catch {
+ CraLog.note("Tidy Tabs: the model failed: \(error)")
+ return nil
+ }
+ }
+ #endif
+ return nil
+ }
+
+ // MARK: Test model
+
+ static let fakeModel = ProcessInfo.processInfo.environment["CRA_TIDY_FAKE_MODEL"] == "1"
+
+ /// Groups tabs by site, named after it, after a model-like pause: enough to drive the UI in a
+ /// test copy on a Mac without Apple Intelligence.
+ private static func fakeAnswer(_ prompt: String) async -> [TidyTabs.Proposal] {
+ try? await Task.sleep(for: .seconds(1.6))
+ var bySite: [String: [Int]] = [:]
+ var order: [String] = []
+ for line in prompt.split(separator: "\n") {
+ guard let colon = line.firstIndex(of: ":"), let id = Int(line[..<colon]),
+ let open = line.lastIndex(of: "("), line.hasSuffix(")") else { continue }
+ let site = String(line[line.index(after: open)..<line.index(before: line.endIndex)])
+ if bySite[site] == nil { order.append(site) }
+ bySite[site, default: []].append(id)
+ }
+ return order.map { TidyTabs.Proposal(name: $0.replacingOccurrences(of: "www.", with: ""), tabs: bySite[$0] ?? []) }
+ }
+}
+
+#if canImport(FoundationModels)
+@available(macOS 26.0, *)
+@Generable
+struct TidyAnswer {
+ @Guide(description: "The groups, each with a name and the ids of its tabs")
+ var groups: [TidyGroup]
+}
+
+@available(macOS 26.0, *)
+@Generable
+struct TidyGroup {
+ @Guide(description: "What the tabs have in common, in one or two words, like a folder name: 'Planets', 'Trip to Lisbon', 'Cra Pull Requests'")
+ var name: String
+ @Guide(description: "Ids of every tab that belongs in this group")
+ var tabs: [Int]
+}
+#endif
diff --git a/Sources/Cra/UI/Settings/TabsPane.swift b/Sources/Cra/UI/Settings/TabsPane.swift
index a16d25b..fe82cfe 100644
--- a/Sources/Cra/UI/Settings/TabsPane.swift
+++ b/Sources/Cra/UI/Settings/TabsPane.swift
@@ -71,6 +71,12 @@ struct TabsPane: View {
isOn: $store.settings.tabSleepOnMemoryPressure)
Text(tabSleepNote).font(.system(size: 11)).foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
+ // Arc Max's Tidy Tabs, on the Mac's own model.
+ SettingsCheckbox(title: "Show Tidy to sort Today tabs into groups", isOn: $store.settings.tidyTabs)
+ .disabled(!tidy.modelAvailable)
+ Text(tidy.unavailableReason ?? "Uses Apple Intelligence on this Mac. Nothing leaves it.")
+ .font(.system(size: 11)).foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
}
}
.sheet(isPresented: $showsAirTrafficControl) {
@@ -79,6 +85,7 @@ struct TabsPane: View {
}
@State private var showsAirTrafficControl = false
+ private var tidy: TidyTabsService { TidyTabsService.shared }
/// Says what a forced-out tab costs, and which tabs stay, before the user finds out.
private var tabSleepNote: String {
diff --git a/Sources/Cra/UI/Sidebar/List/SidebarMenus.swift b/Sources/Cra/UI/Sidebar/List/SidebarMenus.swift
index 7b0e83d..b9849bd 100644
--- a/Sources/Cra/UI/Sidebar/List/SidebarMenus.swift
+++ b/Sources/Cra/UI/Sidebar/List/SidebarMenus.swift
@@ -40,6 +40,15 @@ enum SidebarMenus {
NSPasteboard.general.setString(string, forType: .string)
}
+ // MARK: Tab groups
+
+ /// Arc's Tab Group Context Menu: one item, "Remove header" (the tabs stay, loose).
+ static func tabGroup(_ id: UUID, list: SpaceListView) -> NSMenu {
+ let menu = menu()
+ add(menu, "Remove header") { list.store.removeGroupHeader(id) }
+ return menu
+ }
+
// MARK: Tabs
static func tab(_ m: TabRowModel, list: SpaceListView) -> NSMenu {
diff --git a/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift b/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift
index 3f59b48..834b5da 100644
--- a/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift
+++ b/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift
@@ -2192,16 +2192,28 @@ struct ClipboardPaste: Equatable {
}
}
-/// The line between pinned and Today; "Clear" shows on hover.
+/// Tidy on the divider: off, offered (shown on hover), or sorting (shown, squiggling).
+enum DividerTidy: Equatable {
+ case none, offered, running
+}
+
+/// The line between pinned and Today; "Clear" shows on hover, and "Tidy" before it once Tidy Tabs
+/// can sort Today (Arc 1.171: UnpinnedSectionHeaderCellView with SidebarTidyButton, a
+/// SquiggleDivider while it works).
final class DividerRowView: SidebarRowView {
private let line = NSView()
private var clear: ClearButton?
+ private var tidyButton: TidyButton?
+ private let squiggle = SquiggleLayer()
private var hasToday = false
+ private var tidy = DividerTidy.none
override init(key: SpaceListView.RowKey, list: SpaceListView, colors: SidebarColors) {
super.init(key: key, list: list, colors: colors)
line.wantsLayer = true
addSubview(line)
+ layer?.addSublayer(squiggle)
+ squiggle.onFlat = { [weak self] in self?.refresh() }
}
required init?(coder: NSCoder) { fatalError() }
@@ -2209,8 +2221,14 @@ final class DividerRowView: SidebarRowView {
override var mouseDownCanMoveWindow: Bool { true }
override func mouseDown(with event: NSEvent) { super.mouseDown(with: event) }
- func apply(hasToday: Bool) {
+ func apply(hasToday: Bool, tidy: DividerTidy) {
+ let wasRunning = self.tidy == .running
self.hasToday = hasToday
+ self.tidy = tidy
+ if (tidy == .running) != wasRunning {
+ squiggle.setRunning(tidy == .running, animated: window != nil)
+ tidyButton?.setSweeping(tidy == .running)
+ }
refresh()
}
@@ -2223,8 +2241,10 @@ final class DividerRowView: SidebarRowView {
private func refresh() {
line.layer?.backgroundColor = colors.separator.cgColor
- line.alphaValue = hasToday ? 1 : 0
- let show = isHovered && hasToday
+ squiggle.strokeColor = colors.separator.cgColor
+ // The squiggle stands in for the line while Tidy works.
+ line.alphaValue = hasToday && !squiggle.isShowing ? 1 : 0
+ let show = (isHovered || tidy == .running) && hasToday
if show, clear == nil, let list {
let b = ClearButton(colors: colors) { [weak list] in
guard let list else { return }
@@ -2236,14 +2256,35 @@ final class DividerRowView: SidebarRowView {
b.animator().alphaValue = 1
} else if !show, let b = clear {
clear = nil
- NSAnimationContext.runAnimationGroup { ctx in
- ctx.duration = 0.15
- b.animator().alphaValue = 0
- } completionHandler: { b.removeFromSuperview() }
+ fadeOut(b)
+ }
+ let showTidy = show && tidy != .none
+ if showTidy, tidyButton == nil, let list {
+ let b = TidyButton(colors: colors) { [weak list] in
+ guard let list else { return }
+ TidyTabsService.shared.tidy(list.spaceID, store: list.store)
+ }
+ b.alphaValue = 0
+ addSubview(b)
+ tidyButton = b
+ b.setSweeping(tidy == .running)
+ b.animator().alphaValue = 1
+ } else if !showTidy, let b = tidyButton {
+ tidyButton = nil
+ fadeOut(b)
}
+ clear?.colors = colors
+ tidyButton?.colors = colors
needsLayout = true
}
+ private func fadeOut(_ v: NSView) {
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.15
+ v.animator().alphaValue = 0
+ } completionHandler: { v.removeFromSuperview() }
+ }
+
override func layout() {
super.layout()
// Arc 1.171 at 1x (GitHub #139): the line runs 18 pt in from both edges; "Clear" ends 20 pt in.
@@ -2252,16 +2293,28 @@ final class DividerRowView: SidebarRowView {
let s = clear.fittingSize
clear.frame = NSRect(x: bounds.width - 20 - s.width, y: (bounds.height - s.height) / 2, width: s.width, height: s.height)
right = clear.frame.minX - 8
+ if let tidy = tidyButton {
+ // Arc 1.171, 2x capture of a 347 pt sidebar: the hairline 11 pt before "Clear", the
+ // line 9.5 pt before the broom.
+ let t = tidy.fittingSize
+ tidy.frame = NSRect(x: clear.frame.minX - TidyButton.trailingGap - t.width, y: (bounds.height - t.height) / 2,
+ width: t.width, height: t.height)
+ right = tidy.frame.minX + TidyButton.broomInkInset - 9.5
+ }
}
- line.frame = NSRect(x: 18, y: (bounds.height - 1) / 2, width: max(0, right - 18), height: 1)
+ let y = (bounds.height - 1) / 2
+ line.frame = NSRect(x: 18, y: y, width: max(0, right - 18), height: 1)
+ squiggle.place(from: 18, to: max(18, right), midY: y + 0.5)
}
private final class ClearButton: NSView {
private let label = NSTextField.sidebarLabel(size: 11, weight: .semibold)
private let action: () -> Void
+ var colors: SidebarColors { didSet { label.textColor = colors.textSecondary } }
init(colors: SidebarColors, action: @escaping () -> Void) {
self.action = action
+ self.colors = colors
super.init(frame: .zero)
label.stringValue = "Clear"
label.textColor = colors.textSecondary
@@ -2283,6 +2336,370 @@ final class DividerRowView: SidebarRowView {
}
}
+/// Timings of Tidy on the divider, measured on Arc 1.171 (120 fps capture, 4 Nov 2026).
+enum SidebarTidyMetrics {
+ /// The squiggle: a sine of 12.75 pt period, 3 pt amplitude, travelling left at 5 periods a
+ /// second; the amplitude ramps in and out linearly over 0.4 s (SquiggleDivider's
+ /// amplitudeAnimationDuration).
+ static let period: CGFloat = 12.75
+ static let amplitude: CGFloat = 3
+ static let cyclesPerSecond: Double = 5
+ static let ramp: TimeInterval = 0.4
+ /// One sweep of the broom: tips 31° clockwise from the top of its handle in 0.2 s, holds,
+ /// swings 7° past upright and settles, 0.9 s in all.
+ static let sweep: TimeInterval = 0.9
+ /// A tidy runs at least this long on screen: one sweep and the squiggle's ramp in.
+ static let minimumRun: TimeInterval = 0.9
+}
+
+/// The divider's squiggle (Arc's SquiggleDivider): the line becomes a travelling sine wave
+/// while Tidy works and flattens back when it is done.
+final class SquiggleLayer: CALayer {
+ private let wave = CAShapeLayer()
+ private(set) var isShowing = false
+ /// Called once the wave has flattened and the straight line can come back.
+ var onFlat: (() -> Void)?
+ private var width: CGFloat = 0
+ var strokeColor: CGColor? {
+ get { wave.strokeColor }
+ set { wave.strokeColor = newValue }
+ }
+
+ override init() {
+ super.init()
+ masksToBounds = true
+ isHidden = true
+ actions = ["position": NSNull(), "bounds": NSNull(), "hidden": NSNull()]
+ wave.fillColor = nil
+ wave.lineWidth = 1
+ wave.lineCap = .round
+ wave.actions = ["position": NSNull(), "bounds": NSNull(), "path": NSNull(), "strokeColor": NSNull()]
+ addSublayer(wave)
+ }
+
+ override init(layer: Any) { super.init(layer: layer) }
+ required init?(coder: NSCoder) { fatalError() }
+
+ /// Spans the line's run, centred on it.
+ func place(from x0: CGFloat, to x1: CGFloat, midY: CGFloat) {
+ let h = 2 * SidebarTidyMetrics.amplitude + 4
+ frame = CGRect(x: x0, y: midY - h / 2, width: x1 - x0, height: h)
+ if abs(width - (x1 - x0)) > 0.5 {
+ width = x1 - x0
+ wave.frame = CGRect(x: 0, y: 0, width: width + 2 * SidebarTidyMetrics.period, height: h)
+ if isShowing, wave.animation(forKey: "flatten") == nil { wave.path = path(amplitude: SidebarTidyMetrics.amplitude) }
+ }
+ }
+
+ /// One point per 0.5 pt, the same count flat or waving, so the path animates point by point.
+ private func path(amplitude: CGFloat) -> CGPath {
+ let p = CGMutablePath()
+ let mid = bounds.height / 2
+ let total = width + 2 * SidebarTidyMetrics.period
+ var x: CGFloat = 0
+ p.move(to: CGPoint(x: 0, y: mid))
+ while x <= total {
+ p.addLine(to: CGPoint(x: x, y: mid + amplitude * sin(2 * .pi * x / SidebarTidyMetrics.period)))
+ x += 0.5
+ }
+ return p
+ }
+
+ func setRunning(_ on: Bool, animated: Bool) {
+ let flat = path(amplitude: 0), full = path(amplitude: SidebarTidyMetrics.amplitude)
+ if on {
+ isShowing = true
+ isHidden = false
+ wave.removeAnimation(forKey: "flatten")
+ wave.path = full
+ if animated {
+ let grow = CABasicAnimation(keyPath: "path")
+ grow.fromValue = flat
+ grow.toValue = full
+ grow.duration = SidebarTidyMetrics.ramp
+ wave.add(grow, forKey: "grow")
+ }
+ // Leftward travel: the wave slides one period left, over and over. A translation, so the
+ // line growing shorter as the Tidy button comes in doesn't move it.
+ let travel = CABasicAnimation(keyPath: "transform.translation.x")
+ travel.fromValue = 0
+ travel.toValue = -SidebarTidyMetrics.period
+ travel.duration = 1 / SidebarTidyMetrics.cyclesPerSecond
+ travel.repeatCount = .infinity
+ wave.add(travel, forKey: "travel")
+ } else {
+ guard isShowing else { return }
+ let finish = { [weak self] in
+ guard let self else { return }
+ self.isShowing = false
+ self.isHidden = true
+ self.wave.removeAllAnimations()
+ self.onFlat?()
+ }
+ guard animated else { finish(); return }
+ let flatten = CABasicAnimation(keyPath: "path")
+ flatten.fromValue = wave.presentation()?.path ?? full
+ flatten.toValue = flat
+ flatten.duration = SidebarTidyMetrics.ramp
+ CATransaction.begin()
+ CATransaction.setCompletionBlock { finish() }
+ wave.path = flat
+ wave.add(flatten, forKey: "flatten")
+ CATransaction.commit()
+ }
+ }
+}
+
+/// Arc's SidebarTidyButton: a broom, "Tidy" and a hairline before "Clear". The broom sweeps while
+/// Tidy works.
+final class TidyButton: NSView {
+ /// From the hairline to "Clear"'s frame (Arc: 11 pt from the hairline to its first glyph).
+ static let trailingGap: CGFloat = 7.7
+ /// The broom's box is 14 pt; its ink starts 3 pt in.
+ static let broomInkInset: CGFloat = 3
+ /// Arc: the hairline 8.5 pt after "Tidy"'s last glyph.
+ private static let barOffset: CGFloat = 7
+ private let broom = CALayer()
+ private let broomMask = CALayer()
+ private let label = NSTextField.sidebarLabel(size: 11, weight: .semibold)
+ private let bar = CALayer()
+ private let action: () -> Void
+ private var hovering = false { didSet { tint() } }
+ private var sweeping = false
+ var colors: SidebarColors { didSet { if colors != oldValue { tint() } } }
+
+ init(colors: SidebarColors, action: @escaping () -> Void) {
+ self.colors = colors
+ self.action = action
+ super.init(frame: .zero)
+ wantsLayer = true
+ label.stringValue = "Tidy"
+ label.sizeToFit()
+ addSubview(label)
+ broomMask.contents = BroomGlyph.image
+ broom.mask = broomMask
+ broom.actions = ["backgroundColor": NSNull(), "position": NSNull(), "bounds": NSNull()]
+ bar.actions = ["backgroundColor": NSNull(), "position": NSNull(), "bounds": NSNull()]
+ layer?.addSublayer(broom)
+ layer?.addSublayer(bar)
+ frame.size = fittingSize
+ setAccessibilityElement(true)
+ setAccessibilityRole(.button)
+ setAccessibilityLabel("Tidy")
+ _ = ArcTooltipAnchorView.attach(to: self, help: "Organize Today Tabs")
+ tint()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ /// Broom box, "Tidy" 5 pt after the broom's ink, then the hairline 8.5 pt after its last glyph.
+ override var fittingSize: NSSize {
+ let l = label.frame.size
+ return NSSize(width: Self.labelX + l.width - SidebarText.inset + Self.barOffset + 1, height: max(14, l.height))
+ }
+
+ /// The broom's ink ends 10.6 pt into its box; "Tidy"'s first glyph 5 pt later (Arc).
+ private static let labelX: CGFloat = 10.6 + 5 - SidebarText.inset
+
+ override func layout() {
+ super.layout()
+ let h = bounds.height
+ let l = label.frame.size
+ // The broom turns about the top of its handle, as a hand holds it.
+ let pivot = BroomGlyph.pivot
+ broom.anchorPoint = pivot
+ broom.bounds = CGRect(x: 0, y: 0, width: 14, height: 14)
+ broom.position = CGPoint(x: 14 * pivot.x, y: (h - 14) / 2 + 14 * (isFlipped ? 1 - pivot.y : pivot.y))
+ broomMask.frame = broom.bounds
+ label.frame = NSRect(x: Self.labelX, y: (h - l.height) / 2, width: l.width, height: l.height)
+ let scale = window?.backingScaleFactor ?? 2
+ bar.frame = CGRect(x: label.frame.maxX - SidebarText.inset + Self.barOffset, y: (h - 12.5) / 2, width: 1 / scale, height: 12.5)
+ broomMask.contentsScale = scale
+ }
+
+ private func tint() {
+ let c = hovering || sweeping ? colors.textPrimary : colors.textSecondary
+ label.textColor = c
+ broom.backgroundColor = c.cgColor
+ bar.backgroundColor = colors.separator.cgColor
+ }
+
+ /// Arc's broom while Tidy works: sweep after sweep until the answer is in.
+ func setSweeping(_ on: Bool) {
+ guard on != sweeping else { return }
+ sweeping = on
+ tint()
+ if on {
+ let a = CAKeyframeAnimation(keyPath: "transform.rotation.z")
+ let tip = -31 * CGFloat.pi / 180, past = 7 * CGFloat.pi / 180
+ a.values = [0, tip, tip, past, 0]
+ a.keyTimes = [0, 0.22, 0.39, 0.72, 1]
+ a.timingFunctions = [CAMediaTimingFunction(name: .easeOut), CAMediaTimingFunction(name: .linear),
+ CAMediaTimingFunction(name: .easeInEaseOut), CAMediaTimingFunction(name: .easeInEaseOut)]
+ a.duration = SidebarTidyMetrics.sweep
+ a.repeatCount = .infinity
+ broom.add(a, forKey: "sweep")
+ } else {
+ // Back to upright from wherever the sweep is.
+ let now = (broom.presentation()?.value(forKeyPath: "transform.rotation.z") as? CGFloat) ?? 0
+ broom.removeAnimation(forKey: "sweep")
+ let settle = CABasicAnimation(keyPath: "transform.rotation.z")
+ settle.fromValue = now
+ settle.toValue = 0
+ settle.duration = 0.25
+ settle.timingFunction = CAMediaTimingFunction(name: .easeOut)
+ broom.add(settle, forKey: "settle")
+ }
+ }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+
+ override func mouseEntered(with event: NSEvent) { hovering = true }
+ override func mouseExited(with event: NSEvent) { hovering = false }
+ override var mouseDownCanMoveWindow: Bool { false }
+ override func hitTest(_ point: NSPoint) -> NSView? { frame.contains(point) ? self : nil }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ if bounds.contains(convert(event.locationInWindow, from: nil)), !sweeping { action() }
+ }
+ override func accessibilityPerformPress() -> Bool {
+ if !sweeping { action() }
+ return true
+ }
+}
+
+/// Cra's own broom for Tidy, drawn after Arc's 14 pt template (2x capture): an almost upright
+/// handle leaning ~18° right, a band, and bristles fanning out to the bottom left, 8.5 × 12 pt of ink.
+enum BroomGlyph {
+ /// The top of the handle, in the image's unit square (y up): where a hand would hold it.
+ static let pivot = CGPoint(x: 9.8 / 14, y: 1 - 1.2 / 14)
+
+ static let image: NSImage = {
+ let img = NSImage(size: NSSize(width: 14, height: 14), flipped: true) { _ in
+ NSColor.black.set()
+ let handle = NSBezierPath()
+ handle.lineWidth = 1.15
+ handle.lineCapStyle = .round
+ handle.move(to: NSPoint(x: 9.8, y: 1.3))
+ handle.line(to: NSPoint(x: 8.1, y: 6.7))
+ handle.stroke()
+ let band = NSBezierPath()
+ band.move(to: NSPoint(x: 5.3, y: 6.9))
+ band.line(to: NSPoint(x: 8.8, y: 6.6))
+ band.line(to: NSPoint(x: 9.0, y: 7.5))
+ band.line(to: NSPoint(x: 5.0, y: 7.8))
+ band.close()
+ band.fill()
+ let head = NSBezierPath()
+ head.move(to: NSPoint(x: 4.6, y: 8.2))
+ head.line(to: NSPoint(x: 9.9, y: 8.0))
+ head.curve(to: NSPoint(x: 10.6, y: 12.3), controlPoint1: NSPoint(x: 10.4, y: 9.6), controlPoint2: NSPoint(x: 10.6, y: 11.0))
+ head.line(to: NSPoint(x: 7.6, y: 12.1))
+ head.curve(to: NSPoint(x: 3.0, y: 10.3), controlPoint1: NSPoint(x: 5.8, y: 11.6), controlPoint2: NSPoint(x: 4.2, y: 11.0))
+ head.curve(to: NSPoint(x: 4.6, y: 8.2), controlPoint1: NSPoint(x: 3.6, y: 9.4), controlPoint2: NSPoint(x: 4.1, y: 8.7))
+ head.close()
+ head.fill()
+ // Gaps between the bristles.
+ NSGraphicsContext.current?.compositingOperation = .clear
+ let cuts = NSBezierPath()
+ cuts.lineWidth = 0.4
+ cuts.move(to: NSPoint(x: 6.3, y: 10.0)); cuts.line(to: NSPoint(x: 7.3, y: 12.4))
+ cuts.move(to: NSPoint(x: 8.2, y: 9.8)); cuts.line(to: NSPoint(x: 8.9, y: 12.5))
+ cuts.stroke()
+ return true
+ }
+ img.isTemplate = true
+ return img
+ }()
+}
+
+// MARK: - Tab group header
+
+struct GroupHeaderRowModel: Equatable {
+ var id: UUID
+ var title: String
+}
+
+/// Arc's TabGroupHeaderCellView: a group's name over its tabs in Today (13 pt semibold in the space
+/// header's tone, at the tabs' icon inset, a tab row's height). Hovered, it offers "Create Folder"
+/// and "Close tab group"; its menu has "Remove header". Arc 1.171, offline copy, 4 Nov 2026.
+final class GroupHeaderRowView: SidebarRowView {
+ private(set) var model: GroupHeaderRowModel?
+ private let titleLabel = NSTextField.sidebarLabel(size: 13, weight: .semibold)
+ private var buttons: [SidebarGlyphButton] = []
+
+ override init(key: SpaceListView.RowKey, list: SpaceListView, colors: SidebarColors) {
+ super.init(key: key, list: list, colors: colors)
+ addSubview(titleLabel)
+ setAccessibilityElement(true)
+ setAccessibilityRole(.staticText)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ func apply(_ m: GroupHeaderRowModel) {
+ guard m != model else { return }
+ model = m
+ titleLabel.stringValue = m.title
+ titleLabel.textColor = colors.isDark ? NSColor.white.withAlphaComponent(0.45) : colors.textSecondary
+ setAccessibilityLabel(m.title)
+ needsLayout = true
+ }
+
+ override func setColors(_ c: SidebarColors) {
+ guard c != colors else { return }
+ super.setColors(c)
+ for b in buttons { b.colors = c }
+ if let m = model { model = nil; apply(m) }
+ }
+
+ override func hoverChanged() {
+ super.hoverChanged()
+ if isHovered, buttons.isEmpty, let m = model, let list {
+ let id = m.id
+ let folder = SidebarGlyphButton(symbol: "folder.badge.plus", size: 26, iconSize: 13, weight: .regular,
+ help: "Create Folder", colors: colors) { [weak list] in
+ guard let list, let f = list.store.folderFromGroup(id) else { return }
+ list.store.setExpanded(f.id, true)
+ }
+ let close = SidebarGlyphButton(symbol: "xmark", size: 26, iconSize: 13, help: "", colors: colors) { [weak list] in
+ guard let list else { return }
+ list.closeTabs(list.store.tabs(under: id).map(\.id))
+ }
+ close.setCloseMark(minus: false, help: "Close tab group")
+ buttons = [folder, close]
+ buttons.forEach(addSubview)
+ needsLayout = true
+ } else if !isHovered {
+ buttons.forEach { $0.removeFromSuperview() }
+ buttons = []
+ }
+ }
+
+ override func layout() {
+ super.layout()
+ let h = bounds.height
+ // Arc: the ✕ ends 5 pt in from the row, the folder button right before it.
+ var right = bounds.width - 5
+ for b in buttons.reversed() {
+ b.frame = NSRect(x: right - b.size.width, y: (h - b.size.height) / 2, width: b.size.width, height: b.size.height)
+ right = b.frame.minX
+ }
+ let x = CraMetrics.rowLeading
+ let th = titleLabel.intrinsicContentSize.height
+ titleLabel.frame = NSRect(x: x - SidebarText.inset, y: (h - th) / 2, width: max(0, right - 8 - x) + 2 * SidebarText.inset, height: th)
+ }
+
+ override func contextMenu(at point: NSPoint) -> NSMenu? {
+ guard let m = model, let list else { return nil }
+ return SidebarMenus.tabGroup(m.id, list: list)
+ }
+}
+
/// "Drop to Pin": an empty pinned list opens a target while a drag is on.
final class PinPlaceholderRowView: SidebarRowView {
private let border = CAShapeLayer()
diff --git a/Sources/Cra/UI/Sidebar/List/SpaceListView.swift b/Sources/Cra/UI/Sidebar/List/SpaceListView.swift
index 49893f3..0d73d51 100644
--- a/Sources/Cra/UI/Sidebar/List/SpaceListView.swift
+++ b/Sources/Cra/UI/Sidebar/List/SpaceListView.swift
@@ -28,7 +28,8 @@ final class SpaceListView: NSView, NSDraggingSource {
case split(SplitRowModel)
case liveStatus(LiveStatusModel)
case placeholder(active: Bool)
- case divider(hasToday: Bool)
+ case divider(hasToday: Bool, tidy: DividerTidy)
+ case groupHeader(GroupHeaderRowModel)
case newTab(active: Bool)
}
@@ -248,7 +249,15 @@ final class SpaceListView: NSView, NSDraggingSource {
func add(_ item: SidebarItem, depth: Int, pinned: Bool, parent: UUID, index: Int, peeked: Bool = false) {
var row = Row(key: .item(item.id), content: .newTab(active: false), decor: decor(item.id), itemID: item.id, parent: parent, index: index, depth: depth)
- if item.isFolder {
+ if item.isTabGroup {
+ // Arc lists a group's tabs under its header without an indent.
+ row.content = .groupHeader(GroupHeaderRowModel(id: item.id, title: item.title ?? "Untitled"))
+ out.append(row)
+ let kids = item.children
+ for c in store.children(of: item.id) {
+ add(c, depth: depth, pinned: pinned, parent: item.id, index: kids.firstIndex(of: c.id) ?? 0)
+ }
+ } else if item.isFolder {
let expanded = store.isExpanded(item.id)
let peeked = expanded ? [] : store.peekedTabs(in: item.id)
let glyph = palette.folderColors(item.folderIcon)
@@ -327,7 +336,9 @@ final class SpaceListView: NSView, NSDraggingSource {
}
let pinnedCount = out.count
let todayKids = store.item(space.todayContainerID)?.children ?? []
- out.append(Row(key: .divider, content: .divider(hasToday: !todayKids.isEmpty)))
+ let tidy: DividerTidy = store.tidyingSpaces.contains(spaceID) ? .running
+ : TidyTabsService.shared.offers(spaceID, store: store) ? .offered : .none
+ out.append(Row(key: .divider, content: .divider(hasToday: !todayKids.isEmpty, tidy: tidy)))
let atTop = store.settings.newTabButtonAtTop
if atTop && showsNewTab { out.append(Row(key: .newTab, content: .newTab(active: placeholder))) }
for item in store.children(of: space.todayContainerID) {
@@ -435,6 +446,7 @@ final class SpaceListView: NSView, NSDraggingSource {
case .liveStatus: return v is LiveStatusRowView
case .placeholder: return v is PinPlaceholderRowView
case .divider: return v is DividerRowView
+ case .groupHeader: return v is GroupHeaderRowView
case .newTab: return v is NewTabRowView
}
}
@@ -447,6 +459,7 @@ final class SpaceListView: NSView, NSDraggingSource {
case .liveStatus: return LiveStatusRowView(key: row.key, list: self, colors: colors)
case .placeholder: return PinPlaceholderRowView(key: row.key, list: self, colors: colors)
case .divider: return DividerRowView(key: row.key, list: self, colors: colors)
+ case .groupHeader: return GroupHeaderRowView(key: row.key, list: self, colors: colors)
case .newTab: return NewTabRowView(key: row.key, list: self, colors: colors)
}
}
@@ -458,7 +471,8 @@ final class SpaceListView: NSView, NSDraggingSource {
case .split(let m): (v as? SplitRowView)?.apply(m)
case .liveStatus(let m): (v as? LiveStatusRowView)?.apply(m)
case .placeholder(let active): (v as? PinPlaceholderRowView)?.apply(active: active)
- case .divider(let hasToday): (v as? DividerRowView)?.apply(hasToday: hasToday)
+ case .divider(let hasToday, let tidy): (v as? DividerRowView)?.apply(hasToday: hasToday, tidy: tidy)
+ case .groupHeader(let m): (v as? GroupHeaderRowView)?.apply(m)
case .newTab(let active): (v as? NewTabRowView)?.apply(active: active)
}
}
@@ -523,7 +537,7 @@ final class SpaceListView: NSView, NSDraggingSource {
pinnedFrame = NSRect(x: CraMetrics.rowInset, y: pinnedTop, width: inner, height: y - pinnedTop)
}
if isDivider {
- afterLine = rows[i].content == .divider(hasToday: true)
+ if case .divider(true, _) = rows[i].content { afterLine = true } else { afterLine = false }
let h: CGFloat = afterLine ? 18 : 0
rows[i].frame = NSRect(x: 0, y: y, width: width, height: h)
y += h
@@ -1050,7 +1064,8 @@ final class SpaceListView: NSView, NSDraggingSource {
}
// An empty pinned list shows its own placeholder instead of a line.
guard let y else { return drop }
- let depth = items.first { $0.itemID == parent }.map { $0.depth + 1 } ?? 0
+ // A group's tabs sit at its header's depth (Arc doesn't indent them).
+ let depth = items.first { $0.itemID == parent }.map { $0.depth + (store.item(parent)?.isTabGroup == true ? 0 : 1) } ?? 0
drop.line = .init(y: y, minX: todayFrame.minX + CraMetrics.rowLeading + CGFloat(depth) * CraMetrics.indent, maxX: todayFrame.maxX - 6)
drop.rowAbove = items.last { $0.frame.maxY <= y + 1 }?.itemID
drop.rowBelow = items.first { $0.frame.minY >= y - 1 }?.itemID
diff --git a/Tests/StoreTests.swift b/Tests/StoreTests.swift
index 9b7d444..33a4523 100644
--- a/Tests/StoreTests.swift
+++ b/Tests/StoreTests.swift
@@ -35,6 +35,7 @@ enum StoreTests {
favoritesEmptyState()
sharedFavorites()
themePreview()
+ tidyTabs()
print("Store: \(checks) checks passed")
}
@@ -847,6 +848,85 @@ enum StoreTests {
expect(store.integrityProblems().isEmpty, "and the sidebar stays sound")
}
+ /// Tidy Tabs (Arc's tab groups in Today): the model's plan applied, undone, and the header's
+ /// actions, on the production store.
+ @MainActor
+ private static func tidyTabs() {
+ let store = AppComposition(clock: ManualScheduler()).store
+ // A space of its own: earlier checks leave tabs in the first one.
+ let sid = store.createSpace(title: "Tidy", emoji: "🧹").id
+ let today = store.focusedSpace.todayContainerID
+ let names = ["Mars", "Baguette", "Saturn", "Croissant", "Python", "Mail"]
+ let tabs = names.map { store.createTab(url: "https://example.org/\($0)", in: sid, select: false) }
+ let byName = Dictionary(uniqueKeysWithValues: zip(names, tabs.map(\.id)))
+ expect(store.tabGroups(in: sid).isEmpty && store.canTidy(sid), "six loose Today tabs offer Tidy")
+ let before = store.item(today)!.children
+ // The model sees the loose tabs in sidebar order (new tabs at the top: Mail first).
+ let loose = store.looseTodayTabs(sid).map(\.id)
+ func at(_ name: String) -> Int { loose.firstIndex(of: byName[name]!)! }
+ let plan = TidyTabs.plan([.init(name: "Planets", tabs: [at("Mars"), at("Saturn")]),
+ .init(name: "Bread", tabs: [at("Baguette"), at("Croissant")])],
+ tabCount: loose.count, existingGroups: [])
+ store.applyTidy(plan, tabIDs: loose, in: sid)
+ var groups = store.tabGroups(in: sid)
+ expect(groups.map(\.title) == ["Bread", "Planets"], "groups follow their first tab's place")
+ expect(store.item(today)!.children == [byName["Mail"]!, byName["Python"]!] + groups.map(\.id),
+ "tabs left loose stay above the groups")
+ expect(groups[1].children == [byName["Saturn"]!, byName["Mars"]!], "a group keeps its tabs in sidebar order")
+ expect(groups.allSatisfy { store.isExpanded($0.id) } && store.tabs(under: today).count == 6, "groups are always open")
+ expect(!store.canTidy(sid), "after a run Tidy waits for a new tab")
+ expect(store.integrityProblems().isEmpty, "the tidied sidebar is sound")
+
+ expect(store.undoTidy() && store.tabGroups(in: sid).isEmpty && store.item(today)!.children == before,
+ "⌘Z puts every tab back and the groups go")
+ expect(!store.undoTidy() && store.canTidy(sid), "once; then Tidy is offered again")
+
+ store.applyTidy(plan, tabIDs: loose, in: sid)
+ let fresh = store.createTab(url: "https://example.org/Jupiter", in: sid, select: false)
+ expect(store.canTidy(sid), "a new loose tab brings Tidy back")
+ let loose2 = store.looseTodayTabs(sid).map(\.id)
+ let existing = store.tabGroups(in: sid).map { $0.title ?? "" }
+ let join = TidyTabs.plan([.init(name: "planets", tabs: [loose2.firstIndex(of: fresh.id)!])], tabCount: loose2.count, existingGroups: existing)
+ store.applyTidy(join, tabIDs: loose2, in: sid)
+ groups = store.tabGroups(in: sid)
+ expect(groups[1].children.last == fresh.id, "a second run adds a tab to the group the model named")
+
+ // Moves: groups stay at the top of Today and hold tabs.
+ let pinned = store.focusedSpace.pinnedContainerID
+ store.moveItem(groups[0].id, to: pinned, index: 0)
+ expect(store.item(groups[0].id)?.parentID == today, "a group doesn't move into the pinned tabs")
+ let folder = store.createFolder(named: "F", in: pinned)
+ store.moveItem(folder.id, to: groups[0].id, index: 0)
+ expect(store.item(folder.id)?.parentID == pinned, "a folder doesn't go into a group")
+ store.moveItem(byName["Mail"]!, to: groups[0].id, index: 0)
+ expect(store.item(groups[0].id)!.children.first == byName["Mail"], "a tab dropped on a group joins it")
+ store.moveItem(byName["Mail"]!, to: today, index: 0)
+
+ // The header's actions; after one, ⌘Z no longer undoes the tidy.
+ store.removeGroupHeader(groups[0].id)
+ expect(!store.undoTidy(), "a header action since the tidy takes ⌘Z's undo off")
+
+ expect(store.item(groups[0].id) == nil && store.item(today)!.children.prefix(4) == [byName["Mail"]!, byName["Python"]!, byName["Croissant"]!, byName["Baguette"]!],
+ "Remove header leaves the tabs loose where the group was")
+ let made = store.folderFromGroup(groups[1].id)
+ expect(made?.title == "Planets" && store.item(pinned)!.children.first == made?.id && made?.children.count == 3
+ && store.item(groups[1].id) == nil && store.isExpanded(made!.id) && store.isPinned(byName["Mars"]!),
+ "Create Folder makes an open folder at the top of Pinned with the group's tabs, now pinned")
+
+ store.applyTidy(TidyTabs.plan([.init(name: "Bread", tabs: [0, 1])], tabCount: 2, existingGroups: []),
+ tabIDs: [byName["Baguette"]!, byName["Croissant"]!], in: sid)
+ let bread = store.tabGroups(in: sid)[0]
+ store.archiveTab(byName["Baguette"]!, reason: .manual)
+ expect(store.item(bread.id)?.children == [byName["Croissant"]!], "closing one tab keeps the group")
+ expect(!store.undoTidy(), "a close since the tidy owns ⌘Z")
+ store.saveAll()
+ let restored = AppComposition(clock: ManualScheduler()).store
+ expect(restored.item(bread.id)?.isTabGroup == true && restored.item(bread.id)?.title == "Bread", "a group reads back after a relaunch")
+ store.archiveTab(byName["Croissant"]!, reason: .manual)
+ expect(store.item(bread.id) == nil && !store.item(today)!.children.contains(bread.id), "its last tab takes the header with it")
+ expect(store.integrityProblems().isEmpty, "and the sidebar stays sound")
+ }
+
private static func expect(_ condition: @autoclosure () -> Bool, _ message: String) {
guard condition() else {
FileHandle.standardError.write(Data("FAIL: \(message)\n".utf8))
diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.md
index a95e55b..4f3bcf8 100644
--- a/docs/arc-reverse-engineering.md
+++ b/docs/arc-reverse-engineering.md
@@ -3018,3 +3018,45 @@ Sidebar width via StorableWindows' `sidebarWidth`, window size over AX. Frames f
- [?] Not measured: whether the switch depends on the host's width (only github.com was tried), the grid
cells' hover and pressed fills, where a grid pin's popup opens (Cra: under the cell), a space with
pins but no favorites (Cra: the header follows the grid as it follows tiles).
+
+## Tidy Tabs (Arc 1.171, 4 Nov 2026, Swift metadata + strings, Victor's Arc with Arc Max on, offline Arc at 2x, 120 fps)
+
+Arc Max's "Organize Today Tabs". Arc sends the loose Today tabs to its server (OpenAI) and files them under
+named group headers; Cra asks the Mac's own Apple Intelligence model instead (Victor, 4 Nov 2026: only when
+Apple Intelligence is on, so it's free and nothing leaves the Mac).
+- [O static] `tidyTabsEnabled` (defaults), `canAutoOrganizeTodayTabs`, `createUnpinnedTabGroups()` in
+ WindowData+TabGroups.swift with the request "Here are my tabs, in the format 'id: title':" and "Your array
+ of group assignments, as valid JSON within a ```code block```:" plus a "Tab group of miscellaneous tabs".
+ The answer becomes `SidebarItemData.tabGroup(SidebarTabGroup { title })` items in the unpinned container,
+ the tabs their children: in StorableSidebar, `"data": {"tabGroup": {"title": "Planets"}}` (an empty `{}`
+ fails to decode and Arc drops the item with its tabs). Undo string "Undo prompt for tidying explore tabs".
+- [O static] UnpinnedSectionHeaderCellView: stackView, tidyButton (SidebarTidyButton: imageView "broom-stick",
+ a 14 pt template SVG in ARCClients_BaseAssets, label, divider), clearButton, downArrowImage, borderView,
+ squiggleView. SquiggleDivider (viewModel, height, amplitudeAnimationDuration) over SquiggleViewModel (period,
+ phase, controlPointFraction, amplitudeFunction); window state `dividerSquiggleActiveSpaceIDs`.
+- [O] Shown on hovering the divider once Today holds 6 tabs, grouped ones counted (offline: 5 loose tabs →
+ Clear only; 6 → Tidy; 2 loose + 6 grouped → Tidy). Tooltip "Organize Today Tabs". After a run Tidy is
+ gone until Today changes, even when the run grouped nothing (Arc's server no longer answers: a click gave
+ 0.57 s of squiggle and no groups; a second click on that spot did nothing).
+- [O] Layout at 2x on a 347 pt sidebar (dark space): the line ends 239, broom ink 248.5–257, "Tidy"
+ 262–282.5 (11 pt semibold, the Clear label's tone, brighter on hover), a 0.5 pt hairline 12.5 pt tall at 291,
+ "Clear" 302–327.5.
+- [O] The squiggle (60 fps, sine fitted per frame): period 12.75 pt, amplitude 3.0 pt the whole length of the
+ line, travelling left at 5 periods a second (phase +0.52 rad per 1/60 s); the amplitude ramps linearly 0 → 3
+ in 0.4 s from the click and back in 0.4 s when the answer is in.
+- [O] The broom turns about the top of its handle: 31° clockwise in ~0.2 s (ease out) at the click, holds
+ ~0.12 s, swings back 7° past upright by ~0.65 s and settles by ~0.9 s. Only one sweep was seen (the run
+ ended); Cra repeats it while the model works.
+- [O] Group header (offline Arc, hand-written tabGroup items): a 41 pt row like a tab's, no icon, the name in
+ 13 pt semibold in the space header's tone at the tabs' icon inset (x 17); the tabs below are not indented.
+ Hovered, two 26 pt buttons end 13 pt in: `folder.badge.plus` "Create Folder" and ✕ "Close tab group"; no
+ row fill. Right-click: one item, "Remove header" (the tabs stay where they are, loose). Create Folder: an open
+ folder with the group's name at the top of Pinned, its tabs inside and pinned; the group goes.
+- Cra: TidyTabs (CraCore: when to offer, the prompt, cleaning the model's answer, Today's order),
+ TidyTabsService (FoundationModels guided generation, macOS 26, hidden without Apple Intelligence),
+ SidebarStore tab groups (a folder with `tabGroup: true`, so an older Cra reads the file), DividerRowView's
+ TidyButton + SquiggleLayer + BroomGlyph (Cra's own drawing of the broom), GroupHeaderRowView. ⌘Z undoes the
+ last tidy until a tab closes or a header is used. Measured on Cra: amplitude 2.97 pt, +0.52 rad a frame,
+ ramps 0.38 s.
+- [?] Not seen: Arc's real grouping (the server is gone), what Arc does with a model answer naming an existing
+ group, whether a header can be dragged, and the arrow Arc sometimes draws before "Clear" (offline copy).
diff --git a/docs/development.md b/docs/development.md
index 2735caf..8b36dd1 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -155,6 +155,11 @@ swipe (22 trackpad samples of 14 pt) and `cra://debug?scroll=30,30,150,700` scro
scroll view at x 150, y 700 of the window (from its top left) 30 pt a frame for 30 frames.
Measure them with `sample <pid> 6 1` and compare the main thread's busy time between builds.
+Tidy Tabs needs Apple Intelligence. `CRA_TIDY_FAKE_MODEL=1` stands in a model that groups by
+site (after a 1.6 s pause), so a test instance on any Mac shows the button, the squiggle and the
+groups; `cra://debug?tidy=1` runs Tidy on the window's space without hovering the divider and
+`cra://debug?undoTidy=1` is ⌘Z's undo.
+
`cra://debug?menuAt=315,24` opens the menu a click at that window point would open (the
developer-mode ⌄ here), and `&button=right` the context menu, a tab row's for instance.
`&target=little` aims at the newest Little Window instead (its profile chip, for one).