From b45b2caa85f2051a56fe1cf529f5121c2de8a714 Mon Sep 17 00:00:00 2001 From: Han Ngo Date: Sun, 15 Nov 2026 21:26:24 +0700 Subject: [PATCH 1/8] feat(sharebar): members, all links and app state models --- mac/Sources/ShareBarCore/AllLinksModel.swift | 196 ++++++++++++++ .../ShareBarCore/Popover/AppState.swift | 108 ++++++++ .../ShareBarCore/Settings/ImpactSheet.swift | 30 +++ .../ShareBarCore/Settings/MembersModel.swift | 244 ++++++++++++++++++ .../AllLinksModelTests.swift | 117 +++++++++ .../Popover/AppStateTests.swift | 131 ++++++++++ .../Settings/MembersModelTests.swift | 136 ++++++++++ 7 files changed, 962 insertions(+) create mode 100644 mac/Sources/ShareBarCore/AllLinksModel.swift create mode 100644 mac/Sources/ShareBarCore/Popover/AppState.swift create mode 100644 mac/Sources/ShareBarCore/Settings/MembersModel.swift create mode 100644 mac/Tests/ShareBarCoreTests/AllLinksModelTests.swift create mode 100644 mac/Tests/ShareBarCoreTests/Popover/AppStateTests.swift create mode 100644 mac/Tests/ShareBarCoreTests/Settings/MembersModelTests.swift diff --git a/mac/Sources/ShareBarCore/AllLinksModel.swift b/mac/Sources/ShareBarCore/AllLinksModel.swift new file mode 100644 index 0000000..1214e3b --- /dev/null +++ b/mac/Sources/ShareBarCore/AllLinksModel.swift @@ -0,0 +1,196 @@ +import Foundation + +/// The tabs of the All links window (`share-bar-interactions.md` 3a): every link of the +/// current tenant, expired ones included. +public enum AllLinksTab: String, CaseIterable, Sendable { + case all, live, needsLook, expired + + public var title: String { + switch self { + case .all: return "All" + case .live: return "Live" + case .needsLook: return "Needs a look" + case .expired: return "Expired" + } + } +} + +/// One table row: the popover's `RowModel` plus the columns the window adds. +public struct AllLinksRow: Sendable, Equatable, Identifiable { + public var id: String { row.id } + public let row: RowModel + public let tab: AllLinksTab + public let owner: String + public let livesOn: String + public let expires: String + /// Cloud rows only; blank for every other row. + public let views: Int? + /// `created today`, `created yesterday`, `created 3d ago`; nil when the CLI gave no day. + public let created: String? + /// The state word when the link does not answer (`Owner offline`, `Paused`, `Expired`). + public let stateWord: String? + + public var dimmed: Bool { tab == .expired } + /// Copy is off for an expired or removed link (DEC-52). + public var canCopy: Bool { tab != .expired && row.canCopy } + public var removable: Bool { LinkRemoval.allowed(for: row) } + + public var accessibilityLabel: String { + var parts = [row.title, owner, livesOn, "expires \(expires)"] + if let stateWord { parts.insert(stateWord, at: 1) } + if let views { parts.append(views == 1 ? "1 view" : "\(views) views") } + return parts.joined(separator: ", ") + } +} + +/// The window's own state: a tab, a query and a selection. Pure, so a swift row covers each move. +public struct AllLinksState: Sendable, Equatable { + public var tab: AllLinksTab = .all + public var query = "" + public var selection: Set = [] + + public init(tab: AllLinksTab = .all, query: String = "", selection: Set = []) { + self.tab = tab + self.query = query + self.selection = selection + } + + /// A tab change clears the selection, as the design does. + public mutating func show(_ next: AllLinksTab) { + tab = next + selection = [] + } + + public mutating func toggle(_ id: String) { + if selection.contains(id) { selection.remove(id) } else { selection.insert(id) } + } + + /// Select all: selects every visible row, or clears them when all are already selected. + public mutating func selectAll(_ visible: [AllLinksRow]) { + let ids = Set(visible.map(\.id)) + if !ids.isEmpty, ids.isSubset(of: selection) { selection.subtract(ids) } else { selection.formUnion(ids) } + } + + public mutating func clear() { selection = [] } +} + +/// What the All links window shows for the current tenant. Pure: the CLI's `link_state` decides +/// every tab, the window never classifies a link itself. +public struct AllLinksModel: Sendable, Equatable { + public let profile: String + public let host: String + public let all: [AllLinksRow] + public let rows: [AllLinksRow] + public let counts: [AllLinksTab: Int] + public let state: AllLinksState + public let emptyText: String? + + public static let columns = ["Name", "Owner", "Lives on", "Expires", "Views"] + + public init(entry: ProfileEntry?, state: AllLinksState, now: Date = Date()) { + self.state = state + profile = entry?.name ?? "" + host = entry?.state?.host ?? entry?.name ?? "" + let snapshot = entry?.state + let role = entry.map { ProfileView(entry: $0).role } ?? .unset + let built = (snapshot?.shares ?? []).map { share in + Self.row(for: share, profile: entry?.name ?? "", snapshot: snapshot, role: role, now: now) + } + all = built + counts = Dictionary(uniqueKeysWithValues: AllLinksTab.allCases.map { tab in + (tab, tab == .all ? built.count : built.filter { $0.tab == tab }.count) + }) + let needle = state.query.trimmingCharacters(in: .whitespaces).lowercased() + var shown = state.tab == .all ? built : built.filter { $0.tab == state.tab } + if !needle.isEmpty { + shown = shown.filter { "\($0.row.title) \($0.owner) \($0.livesOn)".lowercased().contains(needle) } + } + rows = shown + emptyText = shown.isEmpty ? (needle.isEmpty ? "Nothing here." : "No links match.") : nil + } + + // MARK: rows + + static func row(for share: Share, profile: String, snapshot: Snapshot?, role: Role, now: Date) -> AllLinksRow { + let model = PopoverViewModel.row(for: share, profile: profile, state: snapshot, role: role, scope: .team, now: now) + let expired = PopoverViewModel.isExpired(share, now: now) + let tab: AllLinksTab = expired ? .expired : (model.state == .live ? .live : .needsLook) + let owner = PopoverViewModel.ownerName(of: share, state: snapshot, role: role) ?? "" + let place = share.storage == "cloud" ? "cloud" : (model.machine) + return AllLinksRow( + row: model, tab: tab, owner: owner, livesOn: place, + expires: expiresText(share, expired: expired, now: now), + views: share.storage == "cloud" ? share.views : nil, + created: createdText(model.age), + stateWord: stateWord(model.state, expired: expired) + ) + } + + static func expiresText(_ share: Share, expired: Bool, now: Date) -> String { + if expired { return "Expired" } + if share.kind == "live" { return "Live" } + if share.expires == 0 { return "Never" } + let left = LinkView.timeLeft(of: share, now: now) ?? "Never" + return left.replacingOccurrences(of: " left", with: "") + } + + static func createdText(_ age: String?) -> String? { + guard let age else { return nil } + if age == "today" { return "created today" } + if age == "1d" { return "created yesterday" } + return "created \(age) ago" + } + + static func stateWord(_ state: LinkState, expired: Bool) -> String? { + if expired { return "Expired" } + switch state { + case .live, .shadowed: return nil + case .offline: return "Owner offline" + case .paused: return "Paused" + case .revoked: return "Removed by admin" + case .expired: return "Expired" + case .gateMissing: return "No login gate" + } + } + + // MARK: footer and bulk bar + + public var footer: String { + let mine = all.filter(\.row.own).count + return "\(all.count) \(all.count == 1 ? "link" : "links") · \(mine) yours · Views are counted for cloud links only" + } + + public var selectedRows: [AllLinksRow] { all.filter { state.selection.contains($0.id) } } + public var selectedText: String { "\(state.selection.count) selected" } + + // MARK: bulk actions + + /// One URL per line, in table order; an expired or removed link is skipped (its Copy is off). + public var bulkCopyText: String { selectedRows.filter(\.canCopy).map(\.row.url).joined(separator: "\n") } + + public var bulkCopyCount: Int { selectedRows.filter(\.canCopy).count } + + public static func copiedSentence(_ count: Int) -> String { + count == 1 ? "Copied 1 link." : "Copied \(count) links, one per line." + } + + /// The links a bulk Remove acts on: own links, and another member's link when the viewer is + /// an admin (that one is revoked, not removed). + public var bulkRemovable: [AllLinksRow] { selectedRows.filter(\.removable) } + + /// One `rm ...` for every removable id: another member's link is revoked by the same verb. + public var bulkRemoveArgv: [String]? { + let ids = bulkRemovable.map(\.id) + guard !ids.isEmpty, !profile.isEmpty else { return nil } + return ProfileArgs.argv(profile, ["rm"] + ids) + } + + public var bulkRemoveSentence: String { + let rows = bulkRemovable + let revoked = rows.filter { !$0.row.own }.count + let removed = rows.count - revoked + if revoked == 0 { return "Removed \(removed) \(removed == 1 ? "link" : "links"). \(removed == 1 ? "It stops" : "They stop") answering." } + if removed == 0 { return "Revoked \(revoked) \(revoked == 1 ? "link" : "links"). \(revoked == 1 ? "It stops" : "They stop") answering now; the files stay on their machines." } + return "Removed \(removed) and revoked \(revoked). They stop answering." + } +} diff --git a/mac/Sources/ShareBarCore/Popover/AppState.swift b/mac/Sources/ShareBarCore/Popover/AppState.swift new file mode 100644 index 0000000..6169cc0 --- /dev/null +++ b/mac/Sources/ShareBarCore/Popover/AppState.swift @@ -0,0 +1,108 @@ +import Foundation + +/// The app states before any tenant view (`share-bar-interactions.md` section 1, gap G8). +/// Pure: the CLI's answer picks the state, the view only draws its panel. +public enum AppState: Sendable, Equatable { + case loading + case cliMissing + case cliTooOld(minimum: String) + case noTenant + case ready + + /// First match wins: no CLI, an old CLI, nothing read yet, no tenant set up, else ready. + /// A `cli_below_min` answer counts only when every set-up tenant gives it (one tenant + /// that needs a newer share never hides the others). + public static func of(profiles: ProfilesSnapshot?, failure: Failure?) -> AppState { + if failure == .cliNotFound { return .cliMissing } + if failure == .oldCLI { return .cliTooOld(minimum: Self.defaultMinimum) } + guard let profiles else { return failure == nil ? .loading : .ready } + let setUp = profiles.profiles.filter { ProfileView(entry: $0).role != .unset } + if setUp.isEmpty { return .noTenant } + let below = setUp.filter { $0.state?.compat?.status == "cli_below_min" } + if below.count == setUp.count, let first = below.first { + return .cliTooOld(minimum: Self.minorVersion(first.state?.compat?.minCLI) ?? Self.defaultMinimum) + } + return .ready + } + + public static let defaultMinimum = "0.10" + public static let installCommand = "brew install dwarvesf/tools/share" + public static let upgradeCommand = "brew upgrade dwarvesf/tools/share" + + /// `0.10.0` reads `0.10`. + static func minorVersion(_ version: String?) -> String? { + guard let version else { return nil } + let parts = version.split(separator: ".") + guard parts.count >= 2, parts.allSatisfy({ Int($0) != nil }) else { return nil } + return "\(parts[0]).\(parts[1])" + } + + /// What replaces the popover's list body; nil for `noTenant` (the first-run panel) and `ready`. + public var panel: AppStatePanel? { + switch self { + case .loading: + return AppStatePanel(symbol: "ellipsis.circle", title: "Loading", body: "Reading your tenants.", button: nil, copy: nil) + case .cliMissing: + return AppStatePanel( + symbol: "terminal", title: "Install the share command", + body: "Share Bar runs the share command to read and publish links. Install it, then open this menu again.", + button: "Copy install command", copy: Self.installCommand) + case .cliTooOld(let minimum): + return AppStatePanel( + symbol: "arrow.down.circle", title: "Update share to \(minimum)", + body: "This Share Bar needs a newer share command. Update it, then open this menu again.", + button: "Copy upgrade command", copy: Self.upgradeCommand) + case .noTenant, .ready: + return nil + } + } +} + +public struct AppStatePanel: Sendable, Equatable { + public let symbol: String + public let title: String + public let body: String + public let button: String? + /// What the button puts on the pasteboard. + public let copy: String? +} + +/// The footer's line for a journaled command another process is running: `Working: add (3/6)`. +public enum WorkingLine { + /// The newest alive op of the profile, or nil; a journal the CLI could not read never shows. + public static func text(for entry: ProfileEntry?) -> String? { + guard let op = entry?.state?.ops?.last(where: { $0.alive && $0.verb != "?" }) else { return nil } + let verb = OpLineText.clean(op.verb) + guard let step = op.step, let of = op.of else { return "Working: \(verb)" } + return "Working: \(verb) (\(step)/\(of))" + } +} + +enum OpLineText { + static func clean(_ text: String) -> String { OpLine.clean(text) } +} + +/// Keyboard focus by row id: arrows move by id, a refresh that reorders rows keeps the id. +public enum RowFocus { + /// The id after a refresh: the same id when its row is still there, else the nearest slot. + public static func restored(previous: String?, previousIndex: Int?, ids: [String]) -> String? { + guard let previous else { return nil } + if ids.contains(previous) { return previous } + guard !ids.isEmpty else { return nil } + return ids[min(max(previousIndex ?? 0, 0), ids.count - 1)] + } + + /// Arrow Down (+1) or Up (-1): the next id, clamped; with no focus, the first or last row. + public static func moved(from current: String?, step: Int, ids: [String]) -> String? { + guard !ids.isEmpty else { return nil } + guard let current, let index = ids.firstIndex(of: current) else { return step > 0 ? ids.first : ids.last } + return ids[max(0, min(ids.count - 1, index + step))] + } +} + +/// What VoiceOver reads and offers for one link row. +public enum RowAccessibility { + /// The row's actions beyond the default press, in the row menu's order (VoiceOver's + /// Actions rotor): the same items the menu offers, so nothing is reachable by pointer only. + public static func actions(for row: RowModel) -> [RowAction] { RowMenu.items(for: row) } +} diff --git a/mac/Sources/ShareBarCore/Settings/ImpactSheet.swift b/mac/Sources/ShareBarCore/Settings/ImpactSheet.swift index 04b398c..ea2c0b1 100644 --- a/mac/Sources/ShareBarCore/Settings/ImpactSheet.swift +++ b/mac/Sources/ShareBarCore/Settings/ImpactSheet.swift @@ -178,6 +178,7 @@ public struct RefusalSheet: Sendable, Equatable { /// other code shows its sentence and, when it names one, the next command to copy. public static func from(code: String, message: String, next: String?, host: String) -> RefusalSheet { if code == "members_present" { return Impact.refusedMembers(host: host) } + if let known = knownJoinOrMember(code: code, message: message) { return known } if let next, !next.isEmpty { return RefusalSheet(title: "Can't do that", sentence: message, next: "Copy command", action: .copyCommand(Redact.tokenShaped(next))) } @@ -185,6 +186,35 @@ public struct RefusalSheet: Sendable, Equatable { } } +extension RefusalSheet { + /// The codes SPEC-009 maps to a sheet beyond `members_present`: a member verb refused for a + /// verb still running, a CLI below the Worker's minimum, and the join table of + /// `share-bar-interactions.md` 2a. Each reads as a sentence plus the way through. + static func knownJoinOrMember(code: String, message: String) -> RefusalSheet? { + let ask = "Ask your admin for a new code." + switch code { + case "member_busy": + return RefusalSheet(title: "Still working", sentence: message.isEmpty ? "Another change to this member is still running. Wait for it to finish, or press Finish in Members." : message, + next: "Open Members", action: .openMembers) + case "cli_below_min": + return RefusalSheet(title: "Update share to \(AppState.defaultMinimum)", sentence: message.isEmpty ? "This share command is older than the team's server allows." : message, + next: "Copy upgrade command", action: .copyCommand(AppState.upgradeCommand)) + case "invite_unknown_or_used": + return RefusalSheet(title: "Can't join", sentence: "This code was already used, or it does not exist. \(ask)", next: nil, action: .none) + case "invite_expired": + return RefusalSheet(title: "Can't join", sentence: "This code expired. \(ask)", next: nil, action: .none) + case "invite_tampered": + return RefusalSheet(title: "Can't join", sentence: "This code was changed on the way. \(ask)", next: nil, action: .none) + case "member_changed": + return RefusalSheet(title: "Can't join", sentence: "The admin changed your invite. \(ask)", next: nil, action: .none) + case "invite_unavailable": + return RefusalSheet(title: "Can't join", sentence: "The invite is not available right now. \(ask)", next: nil, action: .none) + default: + return nil + } + } +} + /// The code sheet: the code once, Copy code, Done. public struct CodeSheet: Sendable, Equatable { public let title: String diff --git a/mac/Sources/ShareBarCore/Settings/MembersModel.swift b/mac/Sources/ShareBarCore/Settings/MembersModel.swift new file mode 100644 index 0000000..abecaec --- /dev/null +++ b/mac/Sources/ShareBarCore/Settings/MembersModel.swift @@ -0,0 +1,244 @@ +import Foundation + +/// A verb of the Members row menu. The CLI's `can[]` decides which ones a member has (DEC-53); +/// this type only names them, orders them and builds the argv. +public enum MemberVerb: String, CaseIterable, Sendable { + case finish, resume, pause, invite, rotate, renew, rm, purge + + /// The menu title. `finish` reads "Finish pausing" and so on from the running status. + public func title(status: String) -> String { + switch self { + case .finish: + let word = MemberStatus(raw: status)?.stateWord.word.lowercased() ?? "the verb" + return "Finish \(word)" + case .resume: return "Resume" + case .pause: return "Pause…" + case .invite: return "Send a new code" + case .rotate: return "Rotate keys…" + case .renew: return "Renew key…" + case .rm: return "Remove…" + case .purge: return "Delete record" + } + } + + /// The destructive item sits last, after a separator. + public var isDestructive: Bool { self == .rm || self == .purge } +} + +/// The Members filter control: All, Needs a look, Removed, each with its count. +public enum MemberFilter: String, CaseIterable, Sendable { + case all, needsLook, removed + + public var title: String { + switch self { + case .all: return "All" + case .needsLook: return "Needs a look" + case .removed: return "Removed" + } + } +} + +public struct MemberChip: Sendable, Equatable { + public enum Tone: Sendable, Equatable { case info, quiet, attention } + public let text: String + public let tone: Tone +} + +/// One row of the Members list (`### Components & states`): initials, name, a sub line, a +/// status chip or the presence word, the link count and the row menu. +public struct MemberRowModel: Sendable, Equatable, Identifiable { + public var id: String { memberID } + public let memberID: String + public let name: String + public let initials: String + public let subLine: String + /// A chip for Invited, Paused, Removed, Left and a running or stopped verb; nil for an + /// active member, who shows `presence` instead. + public let chip: MemberChip? + /// `Online` or `Offline` for an active machine or cloud member with no chip. + public let presence: String? + public let isOnline: Bool + public let linkCount: Int + public let menu: [MemberVerb] + public let status: String + + public var linkText: String { linkCount == 0 ? "" : (linkCount == 1 ? "1 link" : "\(linkCount) links") } + + /// What VoiceOver reads: the name, then what the row shows. + public var accessibilityLabel: String { + var parts = [name, subLine] + if let chip { parts.append(chip.text) } else if let presence { parts.append(presence) } + if linkCount > 0 { parts.append(linkText) } + return parts.filter { !$0.isEmpty }.joined(separator: ", ") + } +} + +/// The Members tab's list model: pure, so a swift row covers every filter, count and menu. +public struct MembersModel: Sendable, Equatable { + public let filter: MemberFilter + public let query: String + public let rows: [MemberRowModel] + public let counts: [MemberFilter: Int] + /// The sentence shown instead of rows. + public let emptyText: String? + + public init(members: [MemberRecord], shares: [Share], filter: MemberFilter, query: String, now: Date = Date()) { + self.filter = filter + self.query = query + let built = members.filter { !$0.name.isEmpty }.map { Self.row(for: $0, shares: shares, now: now) } + let pairs = zip(members.filter { !$0.name.isEmpty }, built).map { ($0, $1) } + let removed = pairs.filter { $0.0.status == "removed" } + let live = pairs.filter { $0.0.status != "removed" } + counts = [ + .all: live.count, + .needsLook: pairs.filter { Self.needsLook($0.0, links: $0.1.linkCount) }.count, + .removed: removed.count, + ] + let needle = query.trimmingCharacters(in: .whitespaces).lowercased() + var chosen: [(MemberRecord, MemberRowModel)] + switch filter { + case .all: chosen = live + case .needsLook: chosen = pairs.filter { Self.needsLook($0.0, links: $0.1.linkCount) } + case .removed: chosen = removed + } + if !needle.isEmpty { chosen = chosen.filter { $0.0.name.lowercased().contains(needle) } } + rows = chosen.map(\.1) + if rows.isEmpty { + emptyText = !needle.isEmpty ? "No members match." + : filter == .needsLook ? "Nobody needs a look." : filter == .removed ? "No removed members." : "No members yet. Invite the first one." + } else { + emptyText = nil + } + } + + // MARK: row + + static func row(for member: MemberRecord, shares: [Share], now: Date) -> MemberRowModel { + let name = display(member.name) + let links = linkCount(of: member, in: shares) + let stale = member.isRunning && (member.lease.map { !$0.live } ?? true) + let machine = machineName(of: member, shares: shares, fallback: name) + let chip: MemberChip? + var presence: String? + switch member.status { + case "invited": chip = MemberChip(text: member.expired ? "Code expired" : "Invited", tone: member.expired ? .attention : .info) + case "paused": chip = MemberChip(text: "Paused", tone: .quiet) + case "left": chip = MemberChip(text: "Left", tone: .attention) + case "removed": chip = MemberChip(text: "Removed", tone: .quiet) + case "expired": chip = MemberChip(text: "Code expired", tone: .attention) + case "invalid": chip = MemberChip(text: "Unreadable", tone: .attention) + default: + if member.isRunning { + chip = MemberChip(text: stale ? "Stopped" : MemberStatus(raw: member.status)?.stateWord.word ?? member.status, tone: .attention) + } else { + chip = nil + presence = member.mode == "cloud" ? "Online" : (member.isOnline ? "Online" : "Offline") + } + } + return MemberRowModel( + memberID: member.memberID, name: name, initials: String(name.prefix(2)), + subLine: subLine(member, machine: machine, stale: stale, now: now), + chip: chip, presence: presence, isOnline: member.isOnline, linkCount: links, + menu: menu(for: member), status: member.status + ) + } + + static func display(_ name: String) -> String { name.prefix(1).uppercased() + name.dropFirst() } + + /// The machine a member publishes from: the `by` of one of their links, else `'s machine`. + static func machineName(of member: MemberRecord, shares: [Share], fallback: String) -> String { + if member.mode == "cloud" { return "cloud only" } + let suffix = MemberID.suffix(of: member.memberID) + let by = shares.first { share in + guard let origin = share.origin, let theirs = MemberID.suffix(of: origin) else { return false } + return theirs == suffix + }?.by + return by ?? "\(fallback)'s machine" + } + + static func linkCount(of member: MemberRecord, in shares: [Share]) -> Int { + guard let mine = MemberID.suffix(of: member.memberID) else { return 0 } + return shares.filter { share in + guard let origin = share.origin, let theirs = MemberID.suffix(of: origin) else { return false } + return theirs == mine && LinkState(raw: share.linkState) != .expired + }.count + } + + /// The second line: a code expiry, the step of a running verb, "left", or the machine + /// (with "offline" when it is not connected). + static func subLine(_ member: MemberRecord, machine: String, stale: Bool, now: Date) -> String { + if member.status == "invited" || member.status == "expired" { + if member.expired { return "code expired" } + if let seconds = member.inviteExpires { + let left = seconds - Int(now.timeIntervalSince1970) + if left > 0 { return "code expires in \(max(1, left / 86_400))d" } + return "code expired" + } + return "waiting for them to join" + } + if member.isRunning { + let verb = (MemberStatus(raw: member.status)?.stateWord.word ?? member.status).lowercased() + let step = member.lease?.step ?? member.step + let position = step.map { s in member.of.map { "step \(s) of \($0)" } ?? "step \(s)" } + if stale { return position.map { "\(verb) stopped at \($0)" } ?? "\(verb) stopped" } + let word = member.stepName.map { " (\($0))" } ?? "" + let head = verb.prefix(1).uppercased() + verb.dropFirst() + return position.map { "\(head), \($0)\(word)" } ?? head + } + if member.status == "left" { return "left, \(machine)" } + if member.status == "removed" { return machine } + if member.mode == "machine", !member.isOnline, member.status == "active" { return "\(machine) · offline" } + return machine + } + + // MARK: menu and filters + + /// The verbs `member ls --json` reports in `can[]`, in the menu's order; a verb this app does + /// not know (add, adopt, join, leave, sync) never shows. Never mirrors the CLI's table. + public static func menu(for member: MemberRecord) -> [MemberVerb] { + let allowed = Set(member.can) + return MemberVerb.allCases.filter { allowed.contains($0.rawValue) } + } + + /// Needs a look: a paused, left or expired-code member, a verb stopped half way, or an + /// active machine member that is offline while links depend on it. + public static func needsLook(_ member: MemberRecord, links: Int) -> Bool { + switch member.status { + case "paused", "left", "expired", "invalid": return true + case "invited": return member.expired + case "removed": return false + default: + if member.isRunning { return true } + return member.mode == "machine" && member.status == "active" && !member.isOnline && links > 0 + } + } + + // MARK: argv + + /// The CLI call a menu item runs. `finish` reruns the verb its `...ing` status stopped on. + /// A name starting with `-` never becomes an argument (nil). + public static func argv(_ verb: MemberVerb, member: MemberRecord, profile: String) -> [String]? { + guard !member.name.hasPrefix("-"), !member.name.isEmpty, !profile.isEmpty else { return nil } + let real: String + switch verb { + case .finish: + guard let rerun = IssueList.finishVerb[member.status] ?? member.lease?.verb, rerun != "add" else { return nil } + real = rerun + default: real = verb.rawValue + } + return ProfileArgs.argv(profile, ["member", real, member.name]) + } + + /// `share member ls --json` for a profile. + public static func listArgv(profile: String) -> [String] { ProfileArgs.argv(profile, ["member", "ls", "--json"]) } + + /// The sentence shown in place of the list when `member ls` fails (never the raw exit code). + public static func failureSentence(_ result: CLIResult) -> String { + if let error = ErrorLine.last(inStderr: result.stderr) { return error.message } + guard !result.stderr.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + return "Couldn't read the members. Try again, or run share member ls." + } + let line = result.lastErrorLine + return line.hasPrefix("share: ") ? String(line.dropFirst(7)) : line + } +} diff --git a/mac/Tests/ShareBarCoreTests/AllLinksModelTests.swift b/mac/Tests/ShareBarCoreTests/AllLinksModelTests.swift new file mode 100644 index 0000000..14d7049 --- /dev/null +++ b/mac/Tests/ShareBarCoreTests/AllLinksModelTests.swift @@ -0,0 +1,117 @@ +import XCTest +@testable import ShareBarCore + +/// SPEC-009 TASK-4b20: the All links window's model. +final class AllLinksModelTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + private let far = 4_102_444_800 + private var past: Int { Int(now.timeIntervalSince1970) - 86_400 } + + private func entry(role: String = "tenant_origin") -> ProfileEntry { + let shares = [ + makeShare(id: "own001", name: "notes.txt", url: "https://s.t/own001/notes.txt", expires: far, storage: "machine", by: "Mac-mini", linkState: "live"), + makeShare(id: "cld001", name: "hero.png", url: "https://s.t/cld001/hero.png", expires: far, storage: "cloud", by: "Linh", origin: "m-linh-5e6f7a8b", linkState: "live", views: 3), + makeShare(id: "mac001", name: "deck.pdf", url: "https://s.t/mac001/deck.pdf", expires: far, storage: "machine", by: "An's MacBook", origin: "m-an-1a2b3c4d", linkState: "offline", views: 9), + makeShare(id: "old001", name: "invoice.pdf", url: "https://s.t/old001/invoice.pdf", expires: past, storage: "cloud", linkState: "expired", views: 12), + makeShare(id: "pau001", name: "page.html", url: "https://s.t/pau001/page.html", expires: far, storage: "machine", by: "Dung's iMac", origin: "m-dung-9a8b7c6d", linkState: "paused"), + ] + return makeEntry(name: "console", state: makeSnapshot(host: "s.console.so", shares: shares, role: role, tier: "t2")) + } + + private func model(_ state: AllLinksState = AllLinksState(), role: String = "tenant_origin") -> AllLinksModel { + AllLinksModel(entry: entry(role: role), state: state, now: now) + } + + func testTabCounts() { + let m = model() + XCTAssertEqual(m.counts[.all], 5) + XCTAssertEqual(m.counts[.live], 2) + XCTAssertEqual(m.counts[.needsLook], 2) + XCTAssertEqual(m.counts[.expired], 1) + XCTAssertEqual(model(AllLinksState(tab: .expired)).rows.map(\.id), ["old001"]) + XCTAssertEqual(model(AllLinksState(tab: .needsLook)).rows.map(\.id), ["mac001", "pau001"]) + XCTAssertEqual(AllLinksTab.allCases.map(\.title), ["All", "Live", "Needs a look", "Expired"]) + } + + func testViewsOnlyOnCloudRows() { + let rows = Dictionary(uniqueKeysWithValues: model().all.map { ($0.id, $0.views) }) + XCTAssertEqual(rows["cld001"], 3) + XCTAssertEqual(rows["old001"], 12) + XCTAssertNil(rows["mac001"] ?? nil, "a machine row never shows views, even when the CLI sent a number") + XCTAssertNil(rows["own001"] ?? nil) + } + + func testExpiredRowsAreDimmedAndCannotCopy() { + let expired = model().all.first { $0.id == "old001" }! + XCTAssertTrue(expired.dimmed) + XCTAssertFalse(expired.canCopy) + XCTAssertEqual(expired.expires, "Expired") + XCTAssertEqual(expired.stateWord, "Expired") + XCTAssertTrue(model().all.first { $0.id == "own001" }!.canCopy) + } + + func testColumnsNameOwnerLivesOnExpires() { + let rows = Dictionary(uniqueKeysWithValues: model().all.map { ($0.id, $0) }) + XCTAssertEqual(rows["own001"]?.owner, "You") + XCTAssertEqual(rows["own001"]?.expires.hasSuffix("d"), true, "time left without the word left") + XCTAssertEqual(AllLinksModel.expiresText(makeShare(expires: 0), expired: false, now: now), "Never") + XCTAssertEqual(AllLinksModel.expiresText(makeShare(kind: "live", expires: 0), expired: false, now: now), "Live") + XCTAssertEqual(rows["mac001"]?.owner, "An") + XCTAssertEqual(rows["mac001"]?.livesOn, "An's MacBook") + XCTAssertEqual(rows["mac001"]?.stateWord, "Owner offline") + XCTAssertEqual(rows["cld001"]?.livesOn, "cloud") + XCTAssertEqual(rows["pau001"]?.stateWord, "Paused") + } + + func testSearchMatchesNameOwnerAndMachine() { + XCTAssertEqual(model(AllLinksState(query: "hero")).rows.map(\.id), ["cld001"]) + XCTAssertEqual(model(AllLinksState(query: "linh")).rows.map(\.id), ["cld001"]) + XCTAssertEqual(model(AllLinksState(query: "macbook")).rows.map(\.id), ["mac001"]) + let none = model(AllLinksState(query: "zzz")) + XCTAssertEqual(none.rows, []) + XCTAssertEqual(none.emptyText, "No links match.") + XCTAssertEqual(model(AllLinksState(tab: .expired, query: "")).emptyText, nil) + } + + func testBulkCopyJoinsURLsOneperLineAndSkipsExpired() { + var state = AllLinksState() + state.selection = ["own001", "cld001", "old001"] + let m = model(state) + XCTAssertEqual(m.bulkCopyText, "https://s.t/own001/notes.txt\nhttps://s.t/cld001/hero.png") + XCTAssertEqual(m.selectedText, "3 selected") + XCTAssertEqual(AllLinksModel.copiedSentence(2), "Copied 2 links, one per line.") + } + + func testBulkRemoveArgvRevokesOthersLinks() { + var state = AllLinksState() + state.selection = ["own001", "mac001", "cld001"] + let m = model(state) + XCTAssertEqual(m.bulkRemoveArgv, ["--profile", "console", "rm", "own001", "cld001", "mac001"], "one rm with every removable id, table order") + XCTAssertEqual(m.bulkRemoveSentence, "Removed 1 and revoked 2. They stop answering.") + } + + func testAMemberCannotRemoveAnotherMembersLink() { + var state = AllLinksState() + state.selection = ["mac001"] + XCTAssertNil(model(state, role: "member").bulkRemoveArgv, "a member's selection of someone else's link has nothing to remove") + } + + func testSelectionMoves() { + var state = AllLinksState() + let m = model(state) + state.toggle("own001") + XCTAssertEqual(state.selection, ["own001"]) + state.selectAll(m.rows) + XCTAssertEqual(state.selection.count, 5) + state.selectAll(m.rows) + XCTAssertEqual(state.selection, [], "select all again clears") + state.toggle("own001") + state.show(.live) + XCTAssertEqual(state.selection, [], "a tab change clears the selection") + XCTAssertEqual(state.tab, .live) + } + + func testFooterCountsLinksAndYours() { + XCTAssertEqual(model().footer, "5 links · 2 yours · Views are counted for cloud links only") + } +} diff --git a/mac/Tests/ShareBarCoreTests/Popover/AppStateTests.swift b/mac/Tests/ShareBarCoreTests/Popover/AppStateTests.swift new file mode 100644 index 0000000..cf6b479 --- /dev/null +++ b/mac/Tests/ShareBarCoreTests/Popover/AppStateTests.swift @@ -0,0 +1,131 @@ +import XCTest +@testable import ShareBarCore + +/// SPEC-009 TASK-4b21, TASK-4b22 and TASK-4b23: app states, keyboard and VoiceOver, running ops. +final class AppStateTests: XCTestCase { + private func tenant(_ role: String?, compat: CompatInfo? = nil) -> ProfileEntry { + makeEntry(name: "p", state: makeSnapshot(host: "s.t", role: role, tier: "t1", compat: compat)) + } + + func testLoadingBeforeAnyProfilesResult() { + XCTAssertEqual(AppState.of(profiles: nil, failure: nil), .loading) + XCTAssertEqual(AppState.loading.panel?.title, "Loading") + XCTAssertNil(AppState.loading.panel?.button) + } + + func testCLIMissingOffersTheInstallCommand() { + let state = AppState.of(profiles: nil, failure: .cliNotFound) + XCTAssertEqual(state, .cliMissing) + XCTAssertEqual(state.panel?.title, "Install the share command") + XCTAssertEqual(state.panel?.button, "Copy install command") + XCTAssertEqual(state.panel?.copy, "brew install dwarvesf/tools/share") + } + + func testCLITooOldFromAnOldHelpBannerOrCompat() { + let banner = AppState.of(profiles: nil, failure: .oldCLI) + XCTAssertEqual(banner, .cliTooOld(minimum: "0.10")) + XCTAssertEqual(banner.panel?.title, "Update share to 0.10") + XCTAssertEqual(banner.panel?.button, "Copy upgrade command") + let compat = CompatInfo(cli: "0.9.0", worker: "5 abc", status: "cli_below_min", minCLI: "0.11.0") + let below = AppState.of(profiles: makeProfiles([tenant("member", compat: compat)]), failure: nil) + XCTAssertEqual(below, .cliTooOld(minimum: "0.11")) + } + + func testOneTenantBelowMinDoesNotHideTheOthers() { + let compat = CompatInfo(cli: "0.9.0", worker: "5 abc", status: "cli_below_min", minCLI: "0.10.0") + let mixed = makeProfiles([makeEntry(name: "a", state: makeSnapshot(role: "member", compat: compat)), tenant("tenant_origin")]) + XCTAssertEqual(AppState.of(profiles: mixed, failure: nil), .ready) + } + + func testNoTenantWhenEveryProfileHasNoRole() { + let state = AppState.of(profiles: makeProfiles([tenant("none"), tenant("none")]), failure: nil) + XCTAssertEqual(state, .noTenant) + XCTAssertNil(state.panel, "the first-run panel is its own view") + XCTAssertEqual(AppState.of(profiles: makeProfiles([tenant("tenant_origin")]), failure: nil), .ready) + } + + // MARK: TASK-4b22 + + func testRowLabelsCarryTheNameAndTheMetaLineForEveryLinkState() { + let now = Date(timeIntervalSince1970: 1_800_000_000) + let state = makeSnapshot(host: "s.t", role: "tenant_origin", tier: "t2") + for raw in ["live", "offline", "paused", "expired", "revoked", "shadowed", "gate_missing"] { + let share = makeShare(id: "x1", name: "deck.pdf", url: "u", expires: 4_102_444_800, storage: "machine", by: "Mac", linkState: raw) + let row = PopoverViewModel.row(for: share, profile: "p", state: state, role: .tenantOrigin, scope: .mine, now: now) + XCTAssertTrue(row.accessibilityLabel.hasPrefix("deck.pdf, "), "\(raw): \(row.accessibilityLabel)") + if raw != "live" { + let word = LinkState(raw: raw).stateWord.word + XCTAssertTrue(row.accessibilityLabel.contains(word), "\(raw) says its state word: \(row.accessibilityLabel)") + } + } + } + + func testRowsExposeTheMenuItemsAsAccessibilityActions() { + let now = Date(timeIntervalSince1970: 1_800_000_000) + let state = makeSnapshot(host: "s.t", servesHere: true, role: "origin", tier: "t0") + let share = makeShare(id: "x1", name: "a", url: "u", expires: 4_102_444_800, storage: "machine", linkState: "live") + let row = PopoverViewModel.row(for: share, profile: "p", state: state, role: .origin, scope: .mine, now: now) + XCTAssertEqual(RowAccessibility.actions(for: row), RowMenu.items(for: row)) + XCTAssertTrue(RowAccessibility.actions(for: row).contains(.copyLink)) + } + + func testFocusRestoresByIDAfterARefreshThatReordersRows() { + let before = ["a", "b", "c", "d"] + XCTAssertEqual(RowFocus.moved(from: "a", step: 1, ids: before), "b") + XCTAssertEqual(RowFocus.moved(from: "b", step: 1, ids: before), "c", "Arrow Down twice lands on the third row") + let after = ["d", "c", "a", "b"] + XCTAssertEqual(RowFocus.restored(previous: "c", previousIndex: 2, ids: after), "c") + XCTAssertEqual(RowFocus.restored(previous: "z", previousIndex: 2, ids: after), "a", "a vanished row falls to its slot") + XCTAssertEqual(RowFocus.restored(previous: "z", previousIndex: 9, ids: after), "b", "clamped") + XCTAssertNil(RowFocus.restored(previous: nil, previousIndex: nil, ids: after)) + XCTAssertNil(RowFocus.restored(previous: "a", previousIndex: 0, ids: [])) + XCTAssertEqual(RowFocus.moved(from: nil, step: -1, ids: before), "d") + XCTAssertEqual(RowFocus.moved(from: "d", step: 1, ids: before), "d", "clamped at the end") + } + + func testTheStatusItemLabelCarriesTheCount() { + XCTAssertEqual(PopoverViewModel.statusItemLabel(count: 0), "Share Bar") + XCTAssertEqual(PopoverViewModel.statusItemLabel(count: 1), "Share Bar, 1 need a look") + XCTAssertEqual(PopoverViewModel.statusItemLabel(count: 4), "Share Bar, 4 need a look") + } + + // MARK: TASK-4b23 + + func testWorkingLineForAnAddFromTheTerminal() { + let alive = OpInfo(verb: "add", step: 3, of: 6, name: "upload", alive: true) + let stopped = OpInfo(verb: "setup", step: 2, of: 5, name: "dns", alive: false) + XCTAssertEqual(WorkingLine.text(for: makeEntry(name: "p", state: makeSnapshot(ops: [stopped, alive]))), "Working: add (3/6)") + XCTAssertNil(WorkingLine.text(for: makeEntry(name: "p", state: makeSnapshot(ops: [stopped])))) + XCTAssertNil(WorkingLine.text(for: makeEntry(name: "p", state: makeSnapshot(ops: [OpInfo(verb: "?", alive: true)])))) + XCTAssertEqual(WorkingLine.text(for: makeEntry(name: "p", state: makeSnapshot(ops: [OpInfo(verb: "add", alive: true)]))), "Working: add") + XCTAssertNil(WorkingLine.text(for: nil)) + } + + func testTheStopWaitingCopyForAnAdd() { + XCTAssertEqual(StopWaiting.addConfirmText, "The add stops where it is; share prune cleans up what it left.") + } + + func testEveryCodeTheAppMapsToASheet() { + let members = RefusalSheet.from(code: "members_present", message: "m", next: nil, host: "s.t") + XCTAssertEqual(members.action, .openMembers) + let busy = RefusalSheet.from(code: "member_busy", message: "pausing an is still running", next: "share member ls", host: "s.t") + XCTAssertEqual(busy.action, .openMembers) + XCTAssertEqual(busy.sentence, "pausing an is still running") + let old = RefusalSheet.from(code: "cli_below_min", message: "", next: nil, host: "s.t") + XCTAssertEqual(old.title, "Update share to 0.10") + XCTAssertEqual(old.action, .copyCommand("brew upgrade dwarvesf/tools/share")) + for code in ["invite_unknown_or_used", "invite_expired", "invite_tampered", "member_changed", "invite_unavailable"] { + let sheet = RefusalSheet.from(code: code, message: "cli text", next: "share x", host: "s.t") + XCTAssertEqual(sheet.title, "Can't join", code) + XCTAssertTrue(sheet.sentence.hasSuffix("Ask your admin for a new code."), "\(code): \(sheet.sentence)") + } + XCTAssertEqual(RefusalSheet.from(code: "port_busy", message: "Port 8787 is in use", next: nil, host: "h").title, "Can't do that") + } + + func testAPublishFailureShowsItsSentenceWithTheNextStepAsACopyableLine() { + let result = CLIResult(status: 1, stdout: "", stderr: "share: the bucket refused the upload\n{\"error\":{\"code\":\"upload_refused\",\"message\":\"the bucket refused the upload\",\"next\":\"share status\"}}\n", timedOut: false) + let alert = MutationOutcome.alert(for: result, warningShareID: nil, notServingHere: false) + XCTAssertEqual(alert?.message, "the bucket refused the upload") + XCTAssertEqual(alert?.next, "share status") + } +} diff --git a/mac/Tests/ShareBarCoreTests/Settings/MembersModelTests.swift b/mac/Tests/ShareBarCoreTests/Settings/MembersModelTests.swift new file mode 100644 index 0000000..f395074 --- /dev/null +++ b/mac/Tests/ShareBarCoreTests/Settings/MembersModelTests.swift @@ -0,0 +1,136 @@ +import XCTest +@testable import ShareBarCore + +/// SPEC-009 TASK-4b19: the Members tab's list model, its row menu and its argv. +final class MembersModelTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + + private func record( + _ name: String, _ status: String, mode: String = "machine", connectors: Int = 1, can: [String] = [], + expired: Bool = false, lease: MemberLease? = nil, step: Int? = nil, of: Int? = nil, stepName: String? = nil, + inviteExpires: Int? = nil + ) -> MemberRecord { + MemberRecord(memberID: "m-\(name)-1a2b3c4d", name: name, mode: mode, status: status, expired: expired, step: step, of: of, + stepName: stepName, lease: lease, connectors: connectors, inviteExpires: inviteExpires, can: can) + } + + /// The design's CAN table, one entry per stored status, in the CLI's own order. + private let canByStatus: [String: [String]] = [ + "invited": ["invite", "renew", "rm"], "joining": ["finish", "rm"], "active": ["pause", "invite", "rotate", "renew", "rm"], + "paused": ["resume", "rotate", "renew", "rm"], "left": ["invite", "rm"], "removed": ["purge"], + "pausing": ["finish", "rm"], "resuming": ["finish", "rm"], "rotating": ["finish", "rm"], "removing": ["finish"], + ] + + func testRowMenuEqualsCanForEveryStoredStatus() { + for (status, can) in canByStatus { + let menu = MembersModel.menu(for: record("x", status, can: can)).map(\.rawValue) + XCTAssertEqual(Set(menu), Set(can), "\(status): the menu lists exactly can[]") + XCTAssertEqual(menu.count, can.count, "\(status): nothing twice") + } + } + + func testTheMenuOrderPutsTheDestructiveVerbLast() { + let menu = MembersModel.menu(for: record("x", "active", can: ["rm", "renew", "pause", "rotate", "invite"])) + XCTAssertEqual(menu, [.pause, .invite, .rotate, .renew, .rm]) + XCTAssertEqual(menu.last?.isDestructive, true) + XCTAssertEqual(MembersModel.menu(for: record("x", "removed", can: ["purge"])), [.purge]) + } + + func testAVerbTheAppDoesNotKnowNeverShows() { + XCTAssertEqual(MembersModel.menu(for: record("x", "active", can: ["pause", "adopt", "join", "sync", "leave"])), [.pause]) + XCTAssertEqual(MembersModel.menu(for: record("x", "active", can: [])), []) + } + + func testEachVerbMapsToItsArgv() { + let member = record("an", "active") + for verb in [MemberVerb.resume, .pause, .invite, .rotate, .renew, .rm, .purge] { + XCTAssertEqual(MembersModel.argv(verb, member: member, profile: "console"), ["--profile", "console", "member", verb.rawValue, "an"]) + } + } + + func testFinishRerunsTheVerbTheStatusStoppedOn() { + let cases = [("pausing", "pause"), ("resuming", "resume"), ("rotating", "rotate"), ("renewing", "renew"), ("removing", "rm"), ("inviting", "invite")] + for (status, verb) in cases { + XCTAssertEqual(MembersModel.argv(.finish, member: record("minh", status, can: ["finish"]), profile: "p"), ["--profile", "p", "member", verb, "minh"]) + } + XCTAssertNil(MembersModel.argv(.finish, member: record("x", "adding"), profile: "p"), "adding reruns through Invite, not Finish") + } + + func testANameWithALeadingDashNeverReachesArgv() { + XCTAssertNil(MembersModel.argv(.pause, member: record("-rf", "active"), profile: "p")) + XCTAssertNil(MembersModel.argv(.pause, member: record("an", "active"), profile: "")) + } + + func testFiltersCount() throws { + let members = [ + record("an", "active", connectors: 0), record("bao", "active"), record("chi", "paused"), record("dung", "invited", expired: true), + record("ha", "left"), record("minh", "pausing", lease: MemberLease(verb: "pause", step: 2, live: false)), record("quan", "removed"), + ] + let shares = [makeShare(id: "a1", url: "u", by: "An's MacBook", origin: "m-an-1a2b3c4d")] + let all = MembersModel(members: members, shares: shares, filter: .all, query: "", now: now) + XCTAssertEqual(all.counts[.all], 6, "removed members are not in All") + XCTAssertEqual(all.counts[.removed], 1) + XCTAssertEqual(all.counts[.needsLook], 5, "offline with links, paused, expired code, left, stopped verb") + XCTAssertEqual(all.rows.map(\.name), ["An", "Bao", "Chi", "Dung", "Ha", "Minh"]) + XCTAssertEqual(MembersModel(members: members, shares: shares, filter: .removed, query: "", now: now).rows.map(\.name), ["Quan"]) + XCTAssertEqual(MembersModel(members: members, shares: shares, filter: .needsLook, query: "", now: now).rows.map(\.name), ["An", "Chi", "Dung", "Ha", "Minh"]) + } + + func testSearchFiltersByNameAndSaysWhenNothingMatches() { + let members = [record("an", "active"), record("bao", "active")] + XCTAssertEqual(MembersModel(members: members, shares: [], filter: .all, query: "ba", now: now).rows.map(\.name), ["Bao"]) + let none = MembersModel(members: members, shares: [], filter: .all, query: "zz", now: now) + XCTAssertEqual(none.emptyText, "No members match.") + XCTAssertEqual(MembersModel(members: members, shares: [], filter: .needsLook, query: "", now: now).emptyText, "Nobody needs a look.") + XCTAssertEqual(MembersModel(members: members, shares: [], filter: .removed, query: "", now: now).emptyText, "No removed members.") + } + + func testTheRowShowsAChipOrThePresenceWordAndTheLinkCount() { + let shares = [makeShare(id: "a1", url: "u", by: "An's MacBook", origin: "m-an-1a2b3c4d"), makeShare(id: "a2", url: "u", origin: "m-an-1a2b3c4d")] + let rows = MembersModel(members: [record("an", "active"), record("chi", "paused"), record("dung", "invited", inviteExpires: Int(now.timeIntervalSince1970) + 6 * 86_400 + 60)], + shares: shares, filter: .all, query: "", now: now).rows + XCTAssertEqual(rows[0].presence, "Online") + XCTAssertNil(rows[0].chip) + XCTAssertEqual(rows[0].linkText, "2 links") + XCTAssertEqual(rows[0].subLine, "An's MacBook") + XCTAssertEqual(rows[1].chip, MemberChip(text: "Paused", tone: .quiet)) + XCTAssertEqual(rows[2].chip, MemberChip(text: "Invited", tone: .info)) + XCTAssertEqual(rows[2].subLine, "code expires in 6d") + } + + func testARunningVerbShowsItsStepAndAStaleLeaseShowsFinish() { + let running = record("minh", "pausing", can: ["finish", "rm"], lease: MemberLease(holder: "han", verb: "pause", step: 2, live: true), stepName: "deploy") + let stale = record("nam", "pausing", can: ["finish", "rm"], lease: MemberLease(holder: "han", verb: "pause", step: 2, live: false)) + let rows = MembersModel(members: [running, stale], shares: [], filter: .all, query: "", now: now).rows + XCTAssertEqual(rows[0].subLine, "Pausing, step 2 (deploy)") + XCTAssertEqual(rows[0].chip, MemberChip(text: "Pausing", tone: .attention)) + XCTAssertEqual(rows[1].subLine, "pausing stopped at step 2") + XCTAssertEqual(rows[1].chip, MemberChip(text: "Stopped", tone: .attention)) + XCTAssertEqual(rows[1].menu, [.finish, .rm]) + XCTAssertEqual(MemberVerb.finish.title(status: "pausing"), "Finish pausing") + } + + func testAnOfflineMachineMemberSaysSoInItsSubLine() { + let rows = MembersModel(members: [record("nam", "active", connectors: 0)], shares: [], filter: .all, query: "", now: now).rows + XCTAssertEqual(rows[0].presence, "Offline") + XCTAssertEqual(rows[0].subLine, "Nam's machine · offline") + } + + func testAMemberLsFailureShowsItsSentence() { + let json = CLIResult(status: 1, stdout: "", stderr: "share: x\n{\"error\":{\"code\":\"member_failed\",\"message\":\"The bucket refused the read.\",\"next\":\"share member ls\"}}\n", timedOut: false) + XCTAssertEqual(MembersModel.failureSentence(json), "The bucket refused the read.") + let plain = CLIResult(status: 1, stdout: "", stderr: "share: needs the admin key\n", timedOut: false) + XCTAssertEqual(MembersModel.failureSentence(plain), "needs the admin key") + XCTAssertEqual(MembersModel.failureSentence(CLIResult(status: 1, stdout: "", stderr: "", timedOut: false)).hasPrefix("Couldn't read the members"), true) + } + + func testTheListArgvAsksForJSONOnTheProfile() { + XCTAssertEqual(MembersModel.listArgv(profile: "console"), ["--profile", "console", "member", "ls", "--json"]) + } + + func testTheFixtureRosterDecodesIntoRows() throws { + let list = try XCTUnwrap(MemberList.decode(String(data: loadFixtureData("member-ls"), encoding: .utf8) ?? "")) + let model = MembersModel(members: list.members, shares: [], filter: .all, query: "", now: now) + XCTAssertEqual(model.rows.first?.menu, [.pause, .invite, .rotate, .renew, .rm]) + } +} From 66cad908bc776a0dba508bdda48eec5bb3a80c17 Mon Sep 17 00:00:00 2001 From: Han Ngo Date: Sun, 15 Nov 2026 21:36:31 +0700 Subject: [PATCH 2/8] feat(sharebar): Members tab with a row menu from can[] --- .../ShareBar/Settings/MembersActions.swift | 104 +++++ .../ShareBar/Settings/MembersPane.swift | 273 ++++++++++++ .../ShareBar/Settings/MembersStore.swift | 65 +++ .../ShareBar/Settings/SettingsRootView.swift | 17 - .../ShareBar/Settings/SettingsStore.swift | 42 +- .../Settings/SettingsWindowController.swift | 1 + .../ShareBar/Settings/ShotsHooks.swift | 20 +- .../ShareBarCore/Settings/ImpactSheet.swift | 31 ++ .../ShareBarCore/Settings/MembersModel.swift | 2 +- mac/Tests/fixtures/settings/run-shots.sh | 2 + .../scenarios/admin-members/member-ls.json | 389 ++++++++++++++++++ .../scenarios/admin-members/profiles.json | 264 ++++++++++++ .../fixtures/settings/steps/members-all.shot | 3 + .../settings/steps/members-invite-code.shot | 4 + .../settings/steps/members-invite-sheet.shot | 3 + .../settings/steps/members-menu-active.shot | 3 + .../settings/steps/members-menu-removed.shot | 3 + .../settings/steps/members-menu-stale.shot | 3 + .../settings/steps/members-needs-look.shot | 3 + .../settings/steps/members-pause-resume.shot | 5 + .../settings/steps/members-removed.shot | 3 + .../steps/members-rotate-confirm.shot | 3 + 22 files changed, 1214 insertions(+), 29 deletions(-) create mode 100644 mac/Sources/ShareBar/Settings/MembersActions.swift create mode 100644 mac/Sources/ShareBar/Settings/MembersPane.swift create mode 100644 mac/Sources/ShareBar/Settings/MembersStore.swift create mode 100644 mac/Tests/fixtures/settings/scenarios/admin-members/member-ls.json create mode 100644 mac/Tests/fixtures/settings/scenarios/admin-members/profiles.json create mode 100644 mac/Tests/fixtures/settings/steps/members-all.shot create mode 100644 mac/Tests/fixtures/settings/steps/members-invite-code.shot create mode 100644 mac/Tests/fixtures/settings/steps/members-invite-sheet.shot create mode 100644 mac/Tests/fixtures/settings/steps/members-menu-active.shot create mode 100644 mac/Tests/fixtures/settings/steps/members-menu-removed.shot create mode 100644 mac/Tests/fixtures/settings/steps/members-menu-stale.shot create mode 100644 mac/Tests/fixtures/settings/steps/members-needs-look.shot create mode 100644 mac/Tests/fixtures/settings/steps/members-pause-resume.shot create mode 100644 mac/Tests/fixtures/settings/steps/members-removed.shot create mode 100644 mac/Tests/fixtures/settings/steps/members-rotate-confirm.shot diff --git a/mac/Sources/ShareBar/Settings/MembersActions.swift b/mac/Sources/ShareBar/Settings/MembersActions.swift new file mode 100644 index 0000000..c59f2c7 --- /dev/null +++ b/mac/Sources/ShareBar/Settings/MembersActions.swift @@ -0,0 +1,104 @@ +import ShareBarCore +import SwiftUI + +/// Settings > Members: reading the roster and running the verbs of a row menu (SPEC-009 +/// TASK-4b19). Every verb goes through the keyed path the other admin verbs use, so an asked +/// key reaches only that one child. +extension SettingsStore { + /// The tenant the tab shows: the popover's current tenant when it is an admin tenant with + /// members, else the first one. + var membersProfile: ProfileEntry? { + let admins = tenants.filter { entry in + guard let state = entry.state, state.tier == "t2" else { return false } + let role = Role(raw: state.role) + return role != .member && role != .unset && role != .unknown && role != .migrated + } + return admins.first { $0.name == popoverPrefs.currentProfile } ?? admins.first + } + + /// The tab opened: read the roster, asking for the admin key first when its source says so. + func requestMembers() { + guard let entry = membersProfile, members.shouldRequest() else { return } + members.begin(profile: entry.name) + collectKeys(keysNeedingAsk([.admin], profile: entry.name), asked: [:], + purpose: "Share Bar uses it to read the members and forgets it right away.") { [weak self] keys in + guard let self else { return } + Task { await self.loadMembers(profile: entry.name, keys: keys) } + } + } + + /// `member ls --json`. A failure shows the CLI's sentence in place of the list. + func loadMembers(profile: String, keys: [String: String] = [:]) async { + let argv = MembersModel.listArgv(profile: profile) + let result: CLIResult + if keys.isEmpty { + result = await readCLI(argv) + } else { + result = await AskedKeyCommand(argv: argv, environment: keys).spawn().result + } + guard result.status == 0, let list = MemberList.decode(result.stdout) else { + members.failed(MembersModel.failureSentence(result), profile: profile) + onMembers(nil, profile) + return + } + members.loaded(list, profile: profile) + onMembers(list, profile) + } + + /// One row-menu item. + func memberVerb(_ verb: MemberVerb, member: MemberRecord) { + members.closeMenu() + guard let profile = members.profile ?? membersProfile?.name, let argv = MembersModel.argv(verb, member: member, profile: profile) else { return } + let host = entry(profile)?.state?.host ?? profile + let name = MembersModel.display(member.name) + switch verb { + case .pause: + presentPause(member: member.name, profile: profile, display: name) + case .rm: + presentRemoveMember(member: member.name, profile: profile, display: name) + case .resume: + runKeyed(argv, kinds: [.admin], profile: profile, host: host, done: "\(name) is resumed.") + case .finish: + runKeyed(argv, kinds: [.admin, .minter], profile: profile, host: host, done: "\(name): finished.") + case .invite: + runForCode(argv, kinds: [.admin, .minter], profile: profile, member: name, rotate: false) + case .rotate: + sheet = .confirm(Impact.rotate(member: name), .runForCode(argv: argv, kinds: [.admin, .minter], profile: profile, member: name, rotate: true)) + case .renew: + sheet = .confirm(Impact.renew(member: name), .runKeyed(argv: argv, kinds: [.admin, .minter], profile: profile, done: "\(name)'s key is renewed.")) + case .purge: + sheet = .confirm(Impact.purge(member: name), .runKeyed(argv: argv, kinds: [.admin], profile: profile, done: "\(name)'s record is deleted.")) + } + } + + /// A verb that prints a code to send: run it, then show the code once. + func runForCode(_ argv: [String], kinds: [KeyKind], profile: String, member: String, rotate: Bool) { + let host = entry(profile)?.state?.host ?? profile + collectKeys(keysNeedingAsk(kinds, profile: profile), asked: [:], + purpose: "Share Bar uses it for this one action and forgets it right away.") { [weak self] keys in + guard let self else { return } + Task { + let result = await self.runWith(argv, keys: keys) + guard result.status == 0, let code = InviteForm.code(fromStdout: result.stdout) else { + if result.status != 0 { self.showFailure(result, host: host) } + await self.loadMembers(profile: profile, keys: keys) + return + } + self.sheet = .code(CodeSheet(member: member, code: code, rotate: rotate, ttlDays: 7)) + await self.loadMembers(profile: profile, keys: keys) + } + } + } + + func copyMemberCode(_ code: String) { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(code, forType: .string) + } +} + +extension SettingsStore { + /// "Open Members" from a needs-a-look line: show the member's row marked, once the roster is read. + func pointAtMember(_ name: String) { + members.point(at: name) + } +} diff --git a/mac/Sources/ShareBar/Settings/MembersPane.swift b/mac/Sources/ShareBar/Settings/MembersPane.swift new file mode 100644 index 0000000..18a204c --- /dev/null +++ b/mac/Sources/ShareBar/Settings/MembersPane.swift @@ -0,0 +1,273 @@ +import ShareBarCore +import SwiftUI + +/// Settings > Members (SPEC-009 TASK-4b19): filters with counts, a search, Invite…, and a list +/// whose row menu offers exactly the verbs `member ls --json` reports in `can[]`. +struct MembersPane: View { + @ObservedObject var store: SettingsStore + @ObservedObject var members: MembersStore + @Environment(\.colorScheme) private var scheme + @State private var moreFrames: [String: CGRect] = [:] + @State private var menuActive: String? + + init(store: SettingsStore) { + self.store = store + members = store.members + } + + private var profile: ProfileEntry? { store.membersProfile } + + var body: some View { + let t = SettingsTheme(scheme) + let model = members.model(shares: profile?.state?.shares ?? []) + ZStack(alignment: .topLeading) { + VStack(alignment: .leading, spacing: 10) { + topBar(model, t) + list(model, t) + } + .padding(.horizontal, 20).padding(.top, 14).padding(.bottom, 18) + if let id = members.menuMember, let record = members.record(id) { + menu(for: record, t) + } + } + .coordinateSpace(name: "members") + .frame(width: SettingsRootView.width, alignment: .topLeading) + .frame(minHeight: 440, alignment: .top) + .onPreferenceChange(MoreFramesKey.self) { moreFrames = $0 } + .accessibilityElement(children: .contain) + .accessibilityLabel("Members") + .accessibilityIdentifier("members-pane") + } + + // MARK: top bar + + private func topBar(_ model: MembersModel, _ t: SettingsTheme) -> some View { + HStack(spacing: 8) { + filterControl(model, t) + Spacer(minLength: 0) + searchField(t) + Button("Invite…") { + if let name = profile?.name { store.presentInvite(profile: name) } + } + .sbButton(.primary) + .accessibilityIdentifier("m-new") + } + } + + private func filterControl(_ model: MembersModel, _ t: SettingsTheme) -> some View { + HStack(spacing: 2) { + ForEach(MemberFilter.allCases, id: \.self) { filter in + let on = members.filter == filter + Button { members.filter = filter } label: { + Text("\(filter.title) \(model.counts[filter] ?? 0)") + .font(.system(size: 11, weight: .medium)).foregroundColor(t.label) + .padding(.horizontal, 10).padding(.vertical, 4) + .background(RoundedRectangle(cornerRadius: 5).fill(on ? t.field : .clear) + .shadow(color: .black.opacity(on ? 0.14 : 0), radius: 1, y: 1)) + .overlay(RoundedRectangle(cornerRadius: 5).stroke(on ? t.separator : .clear, lineWidth: 0.5)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityIdentifier("mv-\(filter.rawValue)") + .accessibilityLabel("\(filter.title), \(model.counts[filter] ?? 0)") + .accessibilityAddTraits(on ? .isSelected : []) + } + } + .padding(2) + .background(RoundedRectangle(cornerRadius: 7).fill(t.hover)) + .accessibilityElement(children: .contain) + .accessibilityLabel("Show") + } + + private func searchField(_ t: SettingsTheme) -> some View { + HStack(spacing: 5) { + Image(systemName: "magnifyingglass").font(.system(size: 11)).foregroundColor(t.tertiary).accessibilityHidden(true) + ZStack(alignment: .leading) { + if members.query.isEmpty { + Text("Search").font(t.bodyFont).foregroundColor(t.tertiary).allowsHitTesting(false).accessibilityHidden(true) + } + TextField("", text: Binding(get: { members.query }, set: { members.query = $0 })) + .textFieldStyle(.plain).font(t.bodyFont).foregroundColor(t.label) + .accessibilityLabel("Search members") + .accessibilityIdentifier("mf") + } + } + .padding(.horizontal, 8).padding(.vertical, 4) + .frame(width: 160) + .background(RoundedRectangle(cornerRadius: 6).fill(t.field)) + .overlay(RoundedRectangle(cornerRadius: 6).stroke(t.softBorder, lineWidth: 1)) + } + + // MARK: list + + @ViewBuilder + private func list(_ model: MembersModel, _ t: SettingsTheme) -> some View { + VStack(spacing: 0) { + if let failure = members.failure, members.list == nil { + VStack(spacing: 0) { + notice(failure, symbol: "exclamationmark.triangle", ink: t.errorInk, t, id: "members-failure") + Button("Try again") { store.requestMembers() }.sbButton().padding(.bottom, 20) + .accessibilityIdentifier("members-retry") + } + } else if members.list == nil { + notice("Reading the members…", symbol: "ellipsis.circle", ink: t.secondary, t, id: "members-loading") + } else if let empty = model.emptyText { + notice(empty, symbol: nil, ink: t.secondary, t, id: "members-empty") + } else { + ScrollView(.vertical) { + VStack(spacing: 0) { + ForEach(Array(model.rows.enumerated()), id: \.element.id) { index, row in + MemberRowView(row: row, open: members.menuMember == row.id, highlighted: members.highlighted == row.id) { + members.toggleMenu(row.id) + } + if index < model.rows.count - 1 { Rectangle().fill(t.separator).frame(height: 1) } + } + } + } + .frame(maxHeight: 330) + .fixedSize(horizontal: false, vertical: true) + } + } + .background(RoundedRectangle(cornerRadius: 8).fill(t.field)) + .overlay(RoundedRectangle(cornerRadius: 8).stroke(t.separator, lineWidth: 1)) + .clipShape(RoundedRectangle(cornerRadius: 8)) + .accessibilityElement(children: .contain) + .accessibilityLabel("Members list") + } + + private func notice(_ text: String, symbol: String?, ink: Color, _ t: SettingsTheme, id: String) -> some View { + HStack(spacing: 6) { + if let symbol { Image(systemName: symbol).foregroundColor(ink).accessibilityHidden(true) } + Text(text).font(t.bodyFont).foregroundColor(symbol == nil ? t.secondary : t.label).fixedSize(horizontal: false, vertical: true) + } + .frame(maxWidth: .infinity).padding(.vertical, 28).padding(.horizontal, 20) + .accessibilityElement(children: .combine) + .accessibilityIdentifier(id) + } + + // MARK: row menu + + private func menu(for record: MemberRecord, _ t: SettingsTheme) -> some View { + let theme = Theme(scheme) + let verbs = MembersModel.menu(for: record) + let safe = verbs.filter { !$0.isDestructive } + let danger = verbs.filter(\.isDestructive) + let width: CGFloat = 200 + let height = CGFloat(verbs.count) * 28 + 8 + (safe.isEmpty || danger.isEmpty ? 0 : 9) + let anchor = moreFrames[record.memberID] ?? CGRect(x: SettingsRootView.width - 60, y: 120, width: 26, height: 26) + let x = max(8, min(anchor.maxX - width, SettingsRootView.width - width - 8)) + let y = anchor.maxY + 4 + let name = MembersModel.display(record.name) + return ZStack(alignment: .topLeading) { + Color.clear.contentShape(Rectangle()).onTapGesture { members.closeMenu() } + VStack(alignment: .leading, spacing: 0) { + ForEach(safe, id: \.self) { verb in + MenuRow(theme: theme, id: "mm-\(verb.rawValue)", title: verb.title(status: record.status), trailing: nil, checked: false, indent: false, active: $menuActive) { + store.memberVerb(verb, member: record) + } + } + if !safe.isEmpty, !danger.isEmpty { Divider().padding(.vertical, 4) } + ForEach(danger, id: \.self) { verb in + MenuRow(theme: theme, id: "mm-\(verb.rawValue)", title: verb == .rm ? "Remove \(name)…" : verb.title(status: record.status), + trailing: nil, checked: false, indent: false, destructive: true, active: $menuActive) { + store.memberVerb(verb, member: record) + } + } + if verbs.isEmpty { + Text("Nothing to do for \(name) right now.").font(t.metaFont).foregroundColor(t.secondary).padding(8) + } + } + .padding(4) + .frame(width: width) + .menuSurface(theme) + .offset(x: x, y: y) + .accessibilityElement(children: .contain) + .accessibilityLabel("Actions for \(name)") + } + .onAppear { menuActive = (safe.first ?? danger.first).map { "mm-\($0.rawValue)" } } + } +} + +private struct MemberRowView: View { + let row: MemberRowModel + let open: Bool + let highlighted: Bool + let toggle: () -> Void + @Environment(\.colorScheme) private var scheme + @State private var hovering = false + + var body: some View { + let t = SettingsTheme(scheme) + HStack(spacing: 10) { + Text(row.initials).font(.system(size: 10.5, weight: .semibold)).foregroundColor(t.secondary) + .frame(width: 26, height: 26) + .background(Circle().fill(t.label.opacity(0.08))) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 0) { + Text(row.name).font(.system(size: 13, weight: .medium)).foregroundColor(t.label).lineLimit(1) + Text(row.subLine).font(t.metaFont).foregroundColor(t.secondary).lineLimit(1).truncationMode(.tail) + } + Spacer(minLength: 4) + statusCell(t).frame(width: 92, alignment: .leading) + Text(row.linkText).font(t.metaFont).foregroundColor(t.secondary).monospacedDigit() + .frame(width: 52, alignment: .trailing) + Button(action: toggle) { + Image(systemName: "ellipsis").font(.system(size: 13)).foregroundColor(hovering || open ? t.secondary : t.secondary.opacity(0.0)) + .frame(width: 26, height: 26).contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityIdentifier("mk-\(row.name.lowercased())") + .accessibilityLabel("Actions for \(row.name)") + .background(GeometryReader { proxy in + Color.clear.preference(key: MoreFramesKey.self, value: [row.id: proxy.frame(in: .named("members"))]) + }) + } + .padding(.leading, 10).padding(.trailing, 8).padding(.vertical, 7) + .background(open || hovering ? t.hover : (highlighted ? t.selection : .clear)) + .onHover { hovering = $0 } + .accessibilityElement(children: .contain) + .accessibilityLabel(row.accessibilityLabel) + .accessibilityIdentifier("mr-\(row.name.lowercased())") + .accessibilityAction(named: "Actions") { toggle() } + } + + @ViewBuilder + private func statusCell(_ t: SettingsTheme) -> some View { + if let chip = row.chip { + Chip(chip: chip) + } else if let presence = row.presence { + HStack(spacing: 5) { + if row.isOnline || presence == "Online" { + Circle().fill(t.ok).frame(width: 7, height: 7) + } else { + Circle().stroke(t.tertiary, lineWidth: 1.5).frame(width: 5, height: 5).padding(1) + } + Text(presence).font(t.metaFont).foregroundColor(t.secondary) + } + .accessibilityElement(children: .combine) + } + } +} + +/// A status chip: the state color at 14% (24% in dark) behind its ink (`chip-bg`, `chip-fg`). +private struct Chip: View { + let chip: MemberChip + @Environment(\.colorScheme) private var scheme + + var body: some View { + let t = SettingsTheme(scheme) + let palette = Tokens.palette(scheme == .dark ? .dark : .light) + let base: RGB + let ink: Color + switch chip.tone { + case .info: base = palette.semantic.info; ink = t.infoInk + case .quiet: base = palette.semantic.quiet; ink = t.color(palette.semantic.quietInk) + case .attention: base = palette.semantic.attention; ink = t.attentionInk + } + return Text(chip.text) + .font(.system(size: 11, weight: .medium)).foregroundColor(ink) + .padding(.horizontal, 6).padding(.vertical, 2) + .background(RoundedRectangle(cornerRadius: 4).fill(t.color(base, opacity: palette.semantic.chipOpacity))) + .accessibilityLabel(chip.text) + } +} diff --git a/mac/Sources/ShareBar/Settings/MembersStore.swift b/mac/Sources/ShareBar/Settings/MembersStore.swift new file mode 100644 index 0000000..d101fec --- /dev/null +++ b/mac/Sources/ShareBar/Settings/MembersStore.swift @@ -0,0 +1,65 @@ +import ShareBarCore +import SwiftUI + +/// The Members tab's own state: the last `member ls --json` read, its filter and search, the +/// open row menu. `SettingsStore` loads it when the tab opens and after each member action +/// (DEC-54), never on the 60 s poll. +@MainActor +final class MembersStore: ObservableObject { + @Published private(set) var list: MemberList? + /// The CLI's sentence when `member ls` failed; shown in place of the list. + @Published private(set) var failure: String? + @Published private(set) var loading = false + @Published var filter: MemberFilter = .all + @Published var query = "" + /// The member id whose row menu is open. + @Published var menuMember: String? + /// The row Needs a look pointed at ("Open Members"). + @Published var highlighted: String? + /// The profile the list was read for. + @Published private(set) var profile: String? + private var pointedName: String? + private var lastRequest = Date.distantPast + + /// A tab open and the refresh behind it can both ask; one read per second is enough. + func shouldRequest(now: Date = Date()) -> Bool { + defer { lastRequest = now } + return now.timeIntervalSince(lastRequest) > 1 + } + + func begin(profile: String) { + self.profile = profile + loading = list == nil + } + + func loaded(_ list: MemberList, profile: String) { + self.profile = profile + self.list = list + failure = nil + loading = false + if let pointedName { point(at: pointedName) } + } + + func failed(_ sentence: String, profile: String) { + self.profile = profile + failure = sentence + loading = false + } + + func model(shares: [Share], now: Date = Date()) -> MembersModel { + MembersModel(members: list?.members ?? [], shares: shares, filter: filter, query: query, now: now) + } + + func record(_ id: String) -> MemberRecord? { list?.members.first { $0.memberID == id } } + + /// A member named by Needs a look: show it in a filter that holds it, with the row marked. + func point(at name: String) { + pointedName = name + guard let found = list?.members.first(where: { $0.name == name }) else { highlighted = nil; return } + highlighted = found.memberID + if found.status == "removed" { filter = .removed } else if filter == .removed { filter = .all } + } + + func toggleMenu(_ id: String) { menuMember = menuMember == id ? nil : id } + func closeMenu() { menuMember = nil } +} diff --git a/mac/Sources/ShareBar/Settings/SettingsRootView.swift b/mac/Sources/ShareBar/Settings/SettingsRootView.swift index da978a2..0370d21 100644 --- a/mac/Sources/ShareBar/Settings/SettingsRootView.swift +++ b/mac/Sources/ShareBar/Settings/SettingsRootView.swift @@ -145,20 +145,3 @@ struct SmallText: View { .fixedSize(horizontal: false, vertical: true) } } - -/// The Members tab is built by the next sub-goal (SPEC-009 TASK-4b19); the tab itself shows -/// for an admin so the Settings shape is complete. -struct MembersPane: View { - @ObservedObject var store: SettingsStore - @Environment(\.colorScheme) private var scheme - - var body: some View { - let t = SettingsTheme(scheme) - VStack(spacing: 8) { - Text("Members").font(t.titleFont).foregroundColor(t.label) - Text("Your team's people and their machines.").font(t.bodyFont).foregroundColor(t.secondary) - } - .frame(maxWidth: .infinity, minHeight: 420) - .accessibilityIdentifier("members-pane") - } -} diff --git a/mac/Sources/ShareBar/Settings/SettingsStore.swift b/mac/Sources/ShareBar/Settings/SettingsStore.swift index 950b040..23cabfb 100644 --- a/mac/Sources/ShareBar/Settings/SettingsStore.swift +++ b/mac/Sources/ShareBar/Settings/SettingsStore.swift @@ -38,6 +38,8 @@ enum ConfirmAction { case rollBack(op: OpInfo, profile: String) /// A verb whose argv depends on the sheet's pop-up (Remove member: keep or delete cloud links). case runChoice(done: String, kinds: [KeyKind], profile: String, argv: (Int) -> [String]) + /// A member verb that ends in a code to send (rotate keys, send a new code). + case runForCode(argv: [String], kinds: [KeyKind], profile: String, member: String, rotate: Bool) } struct AddForm: Equatable { @@ -85,7 +87,9 @@ struct FlowStepPlan { final class SettingsStore: ObservableObject { @Published private(set) var profiles: ProfilesSnapshot? @Published private(set) var failure: Failure? - @Published var pane: SettingsPane = .general + @Published var pane: SettingsPane = .general { + didSet { if pane == .members, oldValue != .members { requestMembers() } } + } @Published var selectedProfile: String? @Published var sheet: SheetContent? @Published private(set) var flow: FlowRun? @@ -118,6 +122,10 @@ final class SettingsStore: ObservableObject { let general: GeneralPrefs let keyStore: KeySourceStore + let members = MembersStore() + /// Called after every `member ls` read, so the popover's member lines of needs a look follow + /// the roster (the popover never runs `member ls` itself, DEC-54). + var onMembers: (MemberList?, String) -> Void = { _, _ in } let popoverPrefs: PopoverPrefs private let defaults: UserDefaults private let queue = MutationQueue() @@ -194,7 +202,10 @@ final class SettingsStore: ObservableObject { if pane == .tenants, let current = popoverPrefs.currentProfile, tenants.contains(where: { $0.name == current }) { selectedProfile = current } - Task { await refresh() } + Task { + await refresh() + if self.pane == .members { requestMembers() } + } } func refresh() async { @@ -477,18 +488,21 @@ final class SettingsStore: ObservableObject { sheet = .invite(profile: profile) } - func presentPause(member: String, profile: String) { + /// `display` is the capitalised name the sheet says; `member` is the CLI name argv carries. + func presentPause(member: String, profile: String, display: String? = nil) { let shares = entry(profile)?.state?.shares ?? [] + let shown = display ?? member impactChoice = 0 - sheet = .confirm(Impact.pause(member: member, shares: shares), - .runKeyed(argv: ProfileArgs.argv(profile, ["member", "pause", member]), kinds: [.admin], profile: profile, done: "\(member) is paused.")) + sheet = .confirm(Impact.pause(member: shown, shares: shares), + .runKeyed(argv: ProfileArgs.argv(profile, ["member", "pause", member]), kinds: [.admin], profile: profile, done: "\(shown) is paused.")) } - func presentRemoveMember(member: String, profile: String) { + func presentRemoveMember(member: String, profile: String, display: String? = nil) { let shares = entry(profile)?.state?.shares ?? [] + let shown = display ?? member impactChoice = 0 - sheet = .confirm(Impact.removeMember(member: member, shares: shares), - .runChoice(done: "\(member) is removed. Their machine links stopped answering.", kinds: [.admin, .minter], profile: profile) { choice in + sheet = .confirm(Impact.removeMember(member: shown, shares: shares), + .runChoice(done: "\(shown) is removed. Their machine links stopped answering.", kinds: [.admin, .minter], profile: profile) { choice in ProfileArgs.argv(profile, ["member", "rm", member, "--cloud-links", choice == 0 ? "keep" : "delete"]) }) } @@ -507,6 +521,7 @@ final class SettingsStore: ObservableObject { return } self.sheet = .code(CodeSheet(member: form.name.trimmingCharacters(in: .whitespaces), code: code, rotate: false, ttlDays: form.ttlDays)) + await self.loadMembers(profile: profile, keys: keys) } } } @@ -535,18 +550,19 @@ final class SettingsStore: ObservableObject { /// Runs one command with the asked keys in its environment, through the app's queue when /// there are none. - private func runWith(_ argv: [String], keys: [String: String]) async -> CLIResult { + func runWith(_ argv: [String], keys: [String: String]) async -> CLIResult { if keys.isEmpty { return await writeCLI(argv) } return await AskedKeyCommand(argv: argv, environment: keys).spawn().result } - private func runKeyed(_ argv: [String], kinds: [KeyKind], profile: String, host: String, done: String) { + func runKeyed(_ argv: [String], kinds: [KeyKind], profile: String, host: String, done: String) { collectKeys(keysNeedingAsk(kinds, profile: profile), asked: [:], purpose: "Share Bar uses it for this one action and forgets it right away.") { [weak self] keys in guard let self else { return } Task { let result = await self.runWith(argv, keys: keys) await self.refresh() + if argv.contains("member") { await self.loadMembers(profile: profile, keys: keys) } if result.status == 0 { self.announce(done) } else { self.showFailure(result, host: host) } } } @@ -625,6 +641,8 @@ final class SettingsStore: ObservableObject { runKeyed(argv(impactChoice), kinds: kinds, profile: profile, host: entry(profile)?.state?.host ?? profile, done: done) case .runKeyed(let argv, let kinds, let profile, let done): runKeyed(argv, kinds: kinds, profile: profile, host: entry(profile)?.state?.host ?? profile, done: done) + case .runForCode(let argv, let kinds, let profile, let member, let rotate): + runForCode(argv, kinds: kinds, profile: profile, member: member, rotate: rotate) case .flow(let step, let profile, let done): startPlan([step], needsKey: true, profile: profile, done: done) case .run(let argv, let done): @@ -770,6 +788,10 @@ final class SettingsStore: ObservableObject { guard let sheet else { return } if !sheet.kind.escCloses { return } self.sheet = nil + // Esc on the key the tab asked for: the list stays unread, with a way to ask again. + if case .askKey = sheet, pane == .members, members.list == nil, members.profile != nil { + members.failed("Reading the members needs the admin key.", profile: members.profile ?? "") + } } /// Esc: closes every sheet but progress. diff --git a/mac/Sources/ShareBar/Settings/SettingsWindowController.swift b/mac/Sources/ShareBar/Settings/SettingsWindowController.swift index 2eeddef..ae74740 100644 --- a/mac/Sources/ShareBar/Settings/SettingsWindowController.swift +++ b/mac/Sources/ShareBar/Settings/SettingsWindowController.swift @@ -17,6 +17,7 @@ final class SettingsWindowController: NSObject, NSWindowDelegate { func show(pane: SettingsPane, member: String? = nil) { let window = ensureWindow() store.show(pane: pane) + if let member { store.pointAtMember(member) } NSApp.activate(ignoringOtherApps: true) window.makeKeyAndOrderFront(nil) startRefreshing() diff --git a/mac/Sources/ShareBar/Settings/ShotsHooks.swift b/mac/Sources/ShareBar/Settings/ShotsHooks.swift index 23e4f57..5b4a2b4 100644 --- a/mac/Sources/ShareBar/Settings/ShotsHooks.swift +++ b/mac/Sources/ShareBar/Settings/ShotsHooks.swift @@ -15,7 +15,8 @@ import SwiftUI /// `source::<1p|cmd|ask>`, `pick::`, `cmd:=`, /// `commit:`, `test:`, `askkey=`, `invite:`, `name=`, /// `invite-mode=`, `invite-ttl=`, `create-code`, `pause::`, -/// `remove-member::`, `wait:`. +/// `remove-member::`, `wait:`. Members tab: `keys` (both key sources as stored commands), `mload` (wait for the roster), +/// `mfilter:`, `mquery=`, `mmenu:`, `mverb::`. @MainActor enum ShotsHooks { static func installIfRequested() { @@ -109,6 +110,23 @@ enum ShotsHooks { case "remove-member": let parts = rest.split(separator: ":").map(String.init) if parts.count == 2 { store.presentRemoveMember(member: parts[1], profile: parts[0]) } + case "keys": + // Both key sources as stored commands, so no step asks for a key it was not meant to show. + for inner in ["source:admin:cmd", "cmd:admin=pass show cf-admin", "commit:admin", + "source:minter:cmd", "cmd:minter=pass show cf-minter", "commit:minter"] { + await step(inner, store: store, controller: controller) + try? await Task.sleep(nanoseconds: 150_000_000) + } + case "mload": + for _ in 0..<60 where store.members.list == nil && store.members.failure == nil { try? await Task.sleep(nanoseconds: 100_000_000) } + case "mfilter": store.members.filter = MemberFilter(rawValue: rest) ?? .all + case "mquery": store.members.query = rest + case "mmenu": + if let record = store.members.list?.members.first(where: { $0.name == rest }) { store.members.menuMember = record.memberID } + case "mverb": + let parts = rest.split(separator: ":").map(String.init) + if parts.count == 2, let verb = MemberVerb(rawValue: parts[1]), + let record = store.members.list?.members.first(where: { $0.name == parts[0] }) { store.memberVerb(verb, member: record) } case "wait": try? await Task.sleep(nanoseconds: UInt64((Double(rest) ?? 1) * 1_000_000_000)) default: break } diff --git a/mac/Sources/ShareBarCore/Settings/ImpactSheet.swift b/mac/Sources/ShareBarCore/Settings/ImpactSheet.swift index ea2c0b1..e4f1b64 100644 --- a/mac/Sources/ShareBarCore/Settings/ImpactSheet.swift +++ b/mac/Sources/ShareBarCore/Settings/ImpactSheet.swift @@ -104,6 +104,37 @@ public enum Impact { ) } + /// Rotate keys: the old keys stop now, the links keep their addresses, the member joins again with a new code. + public static func rotate(member: String) -> ImpactSheet { + ImpactSheet( + title: "Rotate keys for \(member)?", + body: "You get a new code to send them. They join again with it.", + lines: [ + ImpactLine(.stops, "Their old keys stop working now"), + ImpactLine(.keeps, "Their links keep the same addresses"), + ], + actionTitle: "Rotate keys" + ) + } + + /// Renew key: extends the key by the CLI's default; nothing changes on their machine. + public static func renew(member: String) -> ImpactSheet { + ImpactSheet( + title: "Renew \(member)'s key?", + body: "Extends the key by 90 days. Nothing changes on their machine.", + actionTitle: "Renew" + ) + } + + /// Delete record: only a removed member has one; nothing of them is left to stop. + public static func purge(member: String) -> ImpactSheet { + ImpactSheet( + title: "Delete \(member)'s record?", + body: "\(member) is already removed. This deletes the record that remembers them. It cannot be undone.", + actionTitle: "Delete record", destructive: true + ) + } + /// Turn on members: the CLI's own warning, shown before `--yes` is passed. public static func turnOnMembers(host: String) -> ImpactSheet { ImpactSheet( diff --git a/mac/Sources/ShareBarCore/Settings/MembersModel.swift b/mac/Sources/ShareBarCore/Settings/MembersModel.swift index abecaec..556e368 100644 --- a/mac/Sources/ShareBarCore/Settings/MembersModel.swift +++ b/mac/Sources/ShareBarCore/Settings/MembersModel.swift @@ -143,7 +143,7 @@ public struct MembersModel: Sendable, Equatable { ) } - static func display(_ name: String) -> String { name.prefix(1).uppercased() + name.dropFirst() } + public static func display(_ name: String) -> String { name.prefix(1).uppercased() + name.dropFirst() } /// The machine a member publishes from: the `by` of one of their links, else `'s machine`. static func machineName(of member: MemberRecord, shares: [Share], fallback: String) -> String { diff --git a/mac/Tests/fixtures/settings/run-shots.sh b/mac/Tests/fixtures/settings/run-shots.sh index b9de19d..35bbce9 100755 --- a/mac/Tests/fixtures/settings/run-shots.sh +++ b/mac/Tests/fixtures/settings/run-shots.sh @@ -73,6 +73,8 @@ capture() { # capture RUN_DIR="$(mktemp -d "$WORK/run.XXXXXX")" mkdir -p "$RUN_DIR/scenario" command cp -f "$HERE/scenarios/$scenario"/* "$RUN_DIR/scenario/" + # a code that expires in 6 days, read against the clock of the run + [[ ! -f $RUN_DIR/scenario/member-ls.json ]] || sed -i '' "s/@EXP6@/$(( $(date +%s) + 6 * 86400 + 3600 ))/g" "$RUN_DIR/scenario/member-ls.json" : > "$RUN_DIR/argv.log" : > "$RUN_DIR/env.log" defaults delete "$BUNDLE_ID" >/dev/null 2>&1 || true diff --git a/mac/Tests/fixtures/settings/scenarios/admin-members/member-ls.json b/mac/Tests/fixtures/settings/scenarios/admin-members/member-ls.json new file mode 100644 index 0000000..6b125a8 --- /dev/null +++ b/mac/Tests/fixtures/settings/scenarios/admin-members/member-ls.json @@ -0,0 +1,389 @@ +[ + { + "member_id": "m-an-1a2b3c4d", + "name": "an", + "mode": "machine", + "status": "active", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": true, + "paused": false + }, + "account": { + "tunnel": "t-an", + "connectors": 1, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "pause", + "invite", + "rotate", + "renew", + "rm" + ] + }, + { + "member_id": "m-nam-1a2b4e81", + "name": "nam", + "mode": "machine", + "status": "pausing", + "expired": false, + "step": 2, + "of": 3, + "step_name": "deploy", + "lease": { + "holder": "han", + "verb": "pause", + "step": 2, + "live": false + }, + "deploy": { + "bound": false, + "paused": false + }, + "account": { + "tunnel": "t-nam", + "connectors": 0, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "finish", + "rm" + ] + }, + { + "member_id": "m-linh-1a2b60b5", + "name": "linh", + "mode": "cloud", + "status": "invited", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": false, + "paused": false + }, + "account": { + "tunnel": "t-linh", + "connectors": 0, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": @EXP6@, + "prev_status": null, + "drift": [], + "can": [ + "invite", + "rm" + ] + }, + { + "member_id": "m-bao-1a2b72e9", + "name": "bao", + "mode": "machine", + "status": "active", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": true, + "paused": false + }, + "account": { + "tunnel": "t-bao", + "connectors": 1, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "pause", + "invite", + "rotate", + "renew", + "rm" + ] + }, + { + "member_id": "m-chi-1a2b851d", + "name": "chi", + "mode": "machine", + "status": "paused", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": false, + "paused": true + }, + "account": { + "tunnel": "t-chi", + "connectors": 0, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "resume", + "rotate", + "rm" + ] + }, + { + "member_id": "m-duc-1a2b9751", + "name": "duc", + "mode": "machine", + "status": "active", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": true, + "paused": false + }, + "account": { + "tunnel": "t-duc", + "connectors": 1, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "pause", + "invite", + "rotate", + "renew", + "rm" + ] + }, + { + "member_id": "m-hai-1a2ba985", + "name": "hai", + "mode": "machine", + "status": "joining", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": false, + "paused": false + }, + "account": { + "tunnel": "t-hai", + "connectors": 0, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "finish", + "rm" + ] + }, + { + "member_id": "m-khoa-1a2bbbb9", + "name": "khoa", + "mode": "cloud", + "status": "active", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": true, + "paused": false + }, + "account": { + "tunnel": "t-khoa", + "connectors": 1, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "pause", + "invite", + "rotate", + "renew", + "rm" + ] + }, + { + "member_id": "m-lan-1a2bcded", + "name": "lan", + "mode": "machine", + "status": "left", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": false, + "paused": false + }, + "account": { + "tunnel": "t-lan", + "connectors": 0, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": "active", + "drift": [], + "can": [ + "invite", + "rm" + ] + }, + { + "member_id": "m-minh-1a2be021", + "name": "minh", + "mode": "machine", + "status": "active", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": true, + "paused": false + }, + "account": { + "tunnel": "t-minh", + "connectors": 1, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "pause", + "invite", + "rotate", + "renew", + "rm" + ] + }, + { + "member_id": "m-nhi-1a2bf255", + "name": "nhi", + "mode": "machine", + "status": "removing", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": false, + "paused": false + }, + "account": { + "tunnel": "t-nhi", + "connectors": 0, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "finish", + "rm" + ] + }, + { + "member_id": "m-phuc-1a2c0489", + "name": "phuc", + "mode": "machine", + "status": "active", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": true, + "paused": false + }, + "account": { + "tunnel": "t-phuc", + "connectors": 1, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "pause", + "invite", + "rotate", + "renew", + "rm" + ] + }, + { + "member_id": "m-quan-9d8e7f6a", + "name": "quan", + "mode": "machine", + "status": "removed", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": false, + "paused": false + }, + "account": { + "tunnel": null, + "connectors": 0, + "services": 0 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "purge" + ] + } +] \ No newline at end of file diff --git a/mac/Tests/fixtures/settings/scenarios/admin-members/profiles.json b/mac/Tests/fixtures/settings/scenarios/admin-members/profiles.json new file mode 100644 index 0000000..c0d47fb --- /dev/null +++ b/mac/Tests/fixtures/settings/scenarios/admin-members/profiles.json @@ -0,0 +1,264 @@ +{ + "schema": 1, + "profiles": [ + { + "name": "console", + "state": { + "schema": 1, + "state": "serving", + "ready": true, + "mode": "named", + "host": "s.console.so", + "hosts": "Mac-mini", + "serves_here": true, + "service": true, + "access_pending": 0, + "r2": true, + "storage_default": "cloud", + "role": "tenant_origin", + "tier": "t2", + "serve": { + "phase": "serving", + "reason": "ok" + }, + "ops": [], + "token": { + "source": "keychain", + "status": "expiring", + "expires_on": "2026-12-01" + }, + "compat": { + "cli": "0.10.0", + "worker": "5 a1b2c3d4e5f6", + "status": "ok", + "min_cli": "0.10.0" + }, + "shares": [ + { + "id": "c0a0b1", + "name": "notes.txt", + "url": "https://s.console.so/c0a0b1/notes.txt", + "kind": "snapshot", + "own_host": null, + "expires": 4102444800, + "storage": "machine", + "type": "text", + "by": "Mac-mini", + "link_state": "live" + }, + { + "id": "c1a0b1", + "name": "brief-v2.pdf", + "url": "https://s.console.so/c1a0b1/brief-v2.pdf", + "kind": "snapshot", + "own_host": null, + "expires": 4102444800, + "storage": "machine", + "type": "pdf", + "by": "Mac-mini", + "link_state": "live" + }, + { + "id": "c2a0b1", + "name": "invoice-nov.pdf", + "url": "https://s.console.so/c2a0b1/invoice-nov.pdf", + "kind": "snapshot", + "own_host": null, + "expires": 4102444800, + "storage": "machine", + "type": "pdf", + "by": "Mac-mini", + "link_state": "live" + }, + { + "id": "c3a0b1", + "name": "roadmap.key", + "url": "https://s.console.so/c3a0b1/roadmap.key", + "kind": "snapshot", + "own_host": null, + "expires": 4102444800, + "storage": "machine", + "type": "image", + "by": "Mac-mini", + "link_state": "live" + }, + { + "id": "d0b1c2", + "name": "design-review.key", + "url": "https://s.console.so/d0b1c2/design-review.key", + "kind": "snapshot", + "own_host": null, + "expires": 4102444800, + "storage": "cloud", + "type": "pdf", + "by": "Mac-mini", + "link_state": "live" + }, + { + "id": "d1b1c2", + "name": "press-kit.zip", + "url": "https://s.console.so/d1b1c2/press-kit.zip", + "kind": "snapshot", + "own_host": null, + "expires": 4102444800, + "storage": "cloud", + "type": "pdf", + "by": "Mac-mini", + "link_state": "live" + }, + { + "id": "d2b1c2", + "name": "q3-plan.xlsx", + "url": "https://s.console.so/d2b1c2/q3-plan.xlsx", + "kind": "snapshot", + "own_host": null, + "expires": 4102444800, + "storage": "cloud", + "type": "pdf", + "by": "Mac-mini", + "link_state": "live" + }, + { + "id": "d3b1c2", + "name": "logo.png", + "url": "https://s.console.so/d3b1c2/logo.png", + "kind": "snapshot", + "own_host": null, + "expires": 4102444800, + "storage": "cloud", + "type": "pdf", + "by": "Mac-mini", + "link_state": "live" + }, + { + "id": "e0c2d3", + "name": "playdate-uat-run.mov", + "url": "https://s.console.so/e0c2d3/playdate-uat-run.mov", + "kind": "snapshot", + "own_host": null, + "expires": 4102444800, + "storage": "machine", + "type": "pdf", + "by": "An", + "link_state": "live", + "origin": "m-an-1a2b3c4d" + }, + { + "id": "e1c2d3", + "name": "bao-cao-thang-10.pdf", + "url": "https://s.console.so/e1c2d3/bao-cao-thang-10.pdf", + "kind": "snapshot", + "own_host": null, + "expires": 4102444800, + "storage": "machine", + "type": "pdf", + "by": "An", + "link_state": "live", + "origin": "m-an-1a2b3c4d" + }, + { + "id": "e2c2d3", + "name": "kickoff.pdf", + "url": "https://s.console.so/e2c2d3/kickoff.pdf", + "kind": "snapshot", + "own_host": null, + "expires": 4102444800, + "storage": "machine", + "type": "pdf", + "by": "An", + "link_state": "live", + "origin": "m-an-1a2b3c4d" + }, + { + "id": "e3c2d3", + "name": "sketch.fig", + "url": "https://s.console.so/e3c2d3/sketch.fig", + "kind": "snapshot", + "own_host": null, + "expires": 4102444800, + "storage": "machine", + "type": "pdf", + "by": "An", + "link_state": "live", + "origin": "m-an-1a2b3c4d" + }, + { + "id": "e4c2d3", + "name": "demo.mp4", + "url": "https://s.console.so/e4c2d3/demo.mp4", + "kind": "snapshot", + "own_host": null, + "expires": 4102444800, + "storage": "machine", + "type": "pdf", + "by": "An", + "link_state": "live", + "origin": "m-an-1a2b3c4d" + } + ] + } + }, + { + "name": "dfoundation", + "state": { + "schema": 1, + "state": "stopped", + "ready": false, + "mode": "named", + "host": "s.d.foundation", + "hosts": "Mac-mini", + "serves_here": true, + "service": true, + "access_pending": 0, + "r2": true, + "storage_default": "cloud", + "role": "tenant_origin", + "tier": "t1", + "serve": { + "phase": "stopped", + "reason": "stopped" + }, + "ops": [ + { + "verb": "setup-members", + "step": 3, + "of": 9, + "name": "carry", + "alive": false, + "rerun": "share --profile dfoundation setup s.d.foundation --members", + "rerun_argv": [ + "--profile", + "dfoundation", + "setup", + "s.d.foundation", + "--members" + ] + } + ], + "shares": [] + } + }, + { + "name": "han", + "state": { + "schema": 1, + "state": "serving", + "ready": true, + "mode": "named", + "host": "s.han.ws", + "hosts": "Mac-mini", + "serves_here": true, + "service": true, + "access_pending": 0, + "role": "origin", + "tier": "t0", + "serve": { + "phase": "serving", + "reason": "ok" + }, + "ops": [], + "shares": [] + } + } + ] +} \ No newline at end of file diff --git a/mac/Tests/fixtures/settings/steps/members-all.shot b/mac/Tests/fixtures/settings/steps/members-all.shot new file mode 100644 index 0000000..52e6f3a --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/members-all.shot @@ -0,0 +1,3 @@ +scenario admin-members +script tab:advanced,keys,tab:members,mload +label members-all diff --git a/mac/Tests/fixtures/settings/steps/members-invite-code.shot b/mac/Tests/fixtures/settings/steps/members-invite-code.shot new file mode 100644 index 0000000..1cf04cf --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/members-invite-code.shot @@ -0,0 +1,4 @@ +scenario admin-members +script tab:advanced,keys,tab:members,mload,invite:console,name=chi2,create-code,wait:1 +label members-invite-code +expect-argv member add chi2 --machine --invite-ttl 7d diff --git a/mac/Tests/fixtures/settings/steps/members-invite-sheet.shot b/mac/Tests/fixtures/settings/steps/members-invite-sheet.shot new file mode 100644 index 0000000..caa65be --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/members-invite-sheet.shot @@ -0,0 +1,3 @@ +scenario admin-members +script tab:advanced,keys,tab:members,mload,invite:console,name=chi2 +label members-invite-sheet diff --git a/mac/Tests/fixtures/settings/steps/members-menu-active.shot b/mac/Tests/fixtures/settings/steps/members-menu-active.shot new file mode 100644 index 0000000..3c973cb --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/members-menu-active.shot @@ -0,0 +1,3 @@ +scenario admin-members +script tab:advanced,keys,tab:members,mload,mmenu:an +label members-menu-active diff --git a/mac/Tests/fixtures/settings/steps/members-menu-removed.shot b/mac/Tests/fixtures/settings/steps/members-menu-removed.shot new file mode 100644 index 0000000..c437cd5 --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/members-menu-removed.shot @@ -0,0 +1,3 @@ +scenario admin-members +script tab:advanced,keys,tab:members,mload,mfilter:removed,mmenu:quan +label members-menu-removed diff --git a/mac/Tests/fixtures/settings/steps/members-menu-stale.shot b/mac/Tests/fixtures/settings/steps/members-menu-stale.shot new file mode 100644 index 0000000..0b977fb --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/members-menu-stale.shot @@ -0,0 +1,3 @@ +scenario admin-members +script tab:advanced,keys,tab:members,mload,mmenu:nam +label members-menu-stale diff --git a/mac/Tests/fixtures/settings/steps/members-needs-look.shot b/mac/Tests/fixtures/settings/steps/members-needs-look.shot new file mode 100644 index 0000000..b128ee6 --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/members-needs-look.shot @@ -0,0 +1,3 @@ +scenario admin-members +script tab:advanced,keys,tab:members,mload,mfilter:needsLook +label members-needs-look diff --git a/mac/Tests/fixtures/settings/steps/members-pause-resume.shot b/mac/Tests/fixtures/settings/steps/members-pause-resume.shot new file mode 100644 index 0000000..0bf2bf5 --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/members-pause-resume.shot @@ -0,0 +1,5 @@ +scenario admin-members +script tab:advanced,keys,tab:members,mload,mverb:an:pause,ok,wait:1,mverb:chi:resume,wait:1 +expect-argv member pause an +expect-argv member resume chi +label members-pause-resume diff --git a/mac/Tests/fixtures/settings/steps/members-removed.shot b/mac/Tests/fixtures/settings/steps/members-removed.shot new file mode 100644 index 0000000..0121a49 --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/members-removed.shot @@ -0,0 +1,3 @@ +scenario admin-members +script tab:advanced,keys,tab:members,mload,mfilter:removed +label members-removed diff --git a/mac/Tests/fixtures/settings/steps/members-rotate-confirm.shot b/mac/Tests/fixtures/settings/steps/members-rotate-confirm.shot new file mode 100644 index 0000000..3585084 --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/members-rotate-confirm.shot @@ -0,0 +1,3 @@ +scenario admin-members +script tab:advanced,keys,tab:members,mload,mverb:an:rotate +label members-rotate-confirm From 42449496e695456ab8de53a8b60788221700ae5f Mon Sep 17 00:00:00 2001 From: Han Ngo Date: Sun, 15 Nov 2026 21:41:38 +0700 Subject: [PATCH 3/8] feat(sharebar): All links window with bulk copy and remove --- .../ShareBar/AllLinks/AllLinksStore.swift | 83 ++++++ .../ShareBar/AllLinks/AllLinksView.swift | 247 ++++++++++++++++++ .../AllLinks/AllLinksWindowController.swift | 64 +++++ mac/Sources/ShareBar/Router/AppRouter.swift | 4 +- 4 files changed, 396 insertions(+), 2 deletions(-) create mode 100644 mac/Sources/ShareBar/AllLinks/AllLinksStore.swift create mode 100644 mac/Sources/ShareBar/AllLinks/AllLinksView.swift create mode 100644 mac/Sources/ShareBar/AllLinks/AllLinksWindowController.swift diff --git a/mac/Sources/ShareBar/AllLinks/AllLinksStore.swift b/mac/Sources/ShareBar/AllLinks/AllLinksStore.swift new file mode 100644 index 0000000..94b6eb2 --- /dev/null +++ b/mac/Sources/ShareBar/AllLinks/AllLinksStore.swift @@ -0,0 +1,83 @@ +import AppKit +import Combine +import ShareBarCore +import SwiftUI + +/// The All links window's state: a tab, a query and a selection over the popover's last +/// `profiles` read. It holds no CLI state of its own: a bulk Remove joins the popover's one +/// `pending` list (DEC-70), so its Undo, its clock and its single `rm ...` are the popover's. +@MainActor +final class AllLinksStore: ObservableObject { + @Published var state = AllLinksState() + /// A short confirmation that replaces the footer line (Copied 3 links). + @Published private(set) var toast: String? + let popover: PopoverStore + private var cancellable: AnyCancellable? + private var toastTask: Task? + + init(popover: PopoverStore) { + self.popover = popover + cancellable = popover.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() } + } + + var entry: ProfileEntry? { + let profiles = popover.profiles?.profiles ?? [] + return profiles.first { $0.name == popover.currentProfile } ?? profiles.first + } + + var model: AllLinksModel { AllLinksModel(entry: entry, state: state, now: Date()) } + + /// The window opened: search first, selection cleared, the Undo clock running while one is open. + func opened() { + state = AllLinksState() + toast = nil + } + + func setQuery(_ text: String) { state.query = text } + + /// One row's Copy button; the sentence is the popover's own for that link state. + func copy(_ row: AllLinksRow) { + let outcome = LinkClick.outcome(for: row.row) + if outcome.copies, row.canCopy { write(row.row.url) } + say(outcome.message) + } + + func bulkCopy() { + let model = self.model + let count = model.bulkCopyCount + guard count > 0 else { return } + write(model.bulkCopyText) + say(AllLinksModel.copiedSentence(count)) + state.clear() + } + + func bulkRemove() { + let model = self.model + guard let argv = model.bulkRemoveArgv else { return } + popover.removeBulk(ids: model.bulkRemovable.map(\.id), argv: argv, message: model.bulkRemoveSentence) + state.clear() + } + + func undo() { popover.undo() } + + /// The Undo toast of a pending removal, when one is open: its text and whether Undo shows. + var pendingToast: String? { popover.undoVisible ? popover.state.footer?.text : nil } + + func tick() { if popover.needsClock { popover.tick() } } + + private func write(_ text: String) { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(text, forType: .string) + } + + private func say(_ text: String) { + toast = text + NSAccessibility.post(element: NSApp as Any, notification: .announcementRequested, + userInfo: [.announcement: text, .priority: NSAccessibilityPriorityLevel.high.rawValue]) + toastTask?.cancel() + toastTask = Task { [weak self] in + try? await Task.sleep(nanoseconds: UInt64(PopoverState.toastSeconds * 1_000_000_000)) + if !Task.isCancelled { self?.toast = nil } + } + } +} diff --git a/mac/Sources/ShareBar/AllLinks/AllLinksView.swift b/mac/Sources/ShareBar/AllLinks/AllLinksView.swift new file mode 100644 index 0000000..325f2ab --- /dev/null +++ b/mac/Sources/ShareBar/AllLinks/AllLinksView.swift @@ -0,0 +1,247 @@ +import ShareBarCore +import SwiftUI + +/// The All links window (SPEC-009 TASK-4b20, interactions doc 3a): counted tabs, a search that +/// has focus on open, a table with checkboxes, and a bar for the selection. +struct AllLinksView: View { + @ObservedObject var store: AllLinksStore + @Environment(\.colorScheme) private var scheme + @FocusState private var searchFocused: Bool + + static let width: CGFloat = 620 + private static let nameWidth: CGFloat = 196 + + var body: some View { + let t = SettingsTheme(scheme) + let model = store.model + VStack(spacing: 0) { + Text("All links on \(model.host)") + .font(.system(size: 13, weight: .semibold)).foregroundColor(t.secondary) + .frame(maxWidth: .infinity).padding(.top, 7).padding(.bottom, 10) + .accessibilityAddTraits(.isHeader) + .accessibilityIdentifier("all-links-title") + Rectangle().fill(t.separator).frame(height: 1) + VStack(alignment: .leading, spacing: 10) { + topBar(model, t) + if !model.state.selection.isEmpty { bulkBar(model, t) } + table(model, t) + } + .padding(.horizontal, 20).padding(.top, 14).padding(.bottom, 12) + footer(model, t) + } + .frame(width: Self.width) + .ignoresSafeArea(.container, edges: .top) + .windowSurface() + .onAppear { DispatchQueue.main.async { searchFocused = true } } + .accessibilityElement(children: .contain) + .accessibilityLabel("All links") + } + + // MARK: top bar + + private func topBar(_ model: AllLinksModel, _ t: SettingsTheme) -> some View { + HStack(spacing: 8) { + HStack(spacing: 2) { + ForEach(AllLinksTab.allCases, id: \.self) { tab in + let on = model.state.tab == tab + Button { store.state.show(tab) } label: { + Text("\(tab.title) \(model.counts[tab] ?? 0)") + .font(.system(size: 11, weight: .medium)).foregroundColor(t.label) + .padding(.horizontal, 10).padding(.vertical, 4) + .background(RoundedRectangle(cornerRadius: 5).fill(on ? t.field : .clear) + .shadow(color: .black.opacity(on ? 0.14 : 0), radius: 1, y: 1)) + .overlay(RoundedRectangle(cornerRadius: 5).stroke(on ? t.separator : .clear, lineWidth: 0.5)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityIdentifier("lf-\(tab.rawValue)") + .accessibilityLabel("\(tab.title), \(model.counts[tab] ?? 0)") + .accessibilityAddTraits(on ? .isSelected : []) + } + } + .padding(2) + .background(RoundedRectangle(cornerRadius: 7).fill(t.hover)) + .accessibilityElement(children: .contain) + .accessibilityLabel("Show") + Spacer(minLength: 0) + HStack(spacing: 5) { + Image(systemName: "magnifyingglass").font(.system(size: 11)).foregroundColor(t.tertiary).accessibilityHidden(true) + ZStack(alignment: .leading) { + if model.state.query.isEmpty { + Text("Search").font(t.bodyFont).foregroundColor(t.tertiary).allowsHitTesting(false).accessibilityHidden(true) + } + TextField("", text: Binding(get: { store.state.query }, set: { store.setQuery($0) })) + .textFieldStyle(.plain).font(t.bodyFont).foregroundColor(t.label) + .focused($searchFocused) + .accessibilityLabel("Search links") + .accessibilityIdentifier("lq") + } + } + .padding(.horizontal, 8).padding(.vertical, 4) + .frame(width: 180) + .background(RoundedRectangle(cornerRadius: 6).fill(t.field)) + .overlay(RoundedRectangle(cornerRadius: 6).stroke(searchFocused ? t.focus : t.softBorder, lineWidth: searchFocused ? 2 : 1)) + } + } + + // MARK: bulk bar + + private func bulkBar(_ model: AllLinksModel, _ t: SettingsTheme) -> some View { + HStack(spacing: 8) { + Text(model.selectedText).font(.system(size: 13, weight: .medium)).foregroundColor(t.label) + .accessibilityIdentifier("bulk-count") + Spacer(minLength: 0) + Button("Copy links") { store.bulkCopy() }.sbButton() + .disabled(model.bulkCopyCount == 0).accessibilityIdentifier("lb-copy") + Button("Remove…") { store.bulkRemove() }.sbButton(.destructiveText) + .disabled(model.bulkRemoveArgv == nil).accessibilityIdentifier("lb-rm") + Button { store.state.clear() } label: { + Image(systemName: "xmark").font(.system(size: 10, weight: .semibold)).foregroundColor(t.secondary) + .frame(width: 22, height: 22).contentShape(Rectangle()) + } + .buttonStyle(.plain).accessibilityLabel("Clear selection").accessibilityIdentifier("lb-x") + } + .padding(.leading, 12).padding(.trailing, 8).padding(.vertical, 6) + .background(RoundedRectangle(cornerRadius: 7).fill(t.info.opacity(0.10))) + .accessibilityElement(children: .contain) + .accessibilityLabel("Selection") + } + + // MARK: table + + private func table(_ model: AllLinksModel, _ t: SettingsTheme) -> some View { + VStack(spacing: 0) { + header(model, t) + Rectangle().fill(t.separator).frame(height: 1) + if let empty = model.emptyText { + Text(empty).font(t.bodyFont).foregroundColor(t.secondary) + .frame(maxWidth: .infinity).padding(.vertical, 36) + .accessibilityIdentifier("links-empty") + } else { + ScrollView(.vertical) { + VStack(spacing: 0) { + ForEach(Array(model.rows.enumerated()), id: \.element.id) { index, row in + LinkTableRow(store: store, row: row, selected: model.state.selection.contains(row.id)) + if index < model.rows.count - 1 { Rectangle().fill(t.separator).frame(height: 1) } + } + } + } + .frame(maxHeight: 340) + .fixedSize(horizontal: false, vertical: true) + } + } + .background(RoundedRectangle(cornerRadius: 8).fill(t.field)) + .overlay(RoundedRectangle(cornerRadius: 8).stroke(t.separator, lineWidth: 1)) + .clipShape(RoundedRectangle(cornerRadius: 8)) + .accessibilityElement(children: .contain) + .accessibilityLabel("Links") + } + + private func header(_ model: AllLinksModel, _ t: SettingsTheme) -> some View { + let all = !model.rows.isEmpty && model.rows.allSatisfy { model.state.selection.contains($0.id) } + return HStack(spacing: 10) { + Toggle("", isOn: Binding(get: { all }, set: { _ in store.state.selectAll(model.rows) })) + .toggleStyle(.checkbox).labelsHidden().frame(width: 18) + .accessibilityLabel("Select all").accessibilityIdentifier("l-all") + Text("Name").frame(width: Self.nameWidth, alignment: .leading) + Text("Owner").frame(width: 62, alignment: .leading) + Text("Lives on").frame(maxWidth: .infinity, alignment: .leading) + Text("Expires").frame(width: 58, alignment: .trailing) + Text("Views").frame(width: 44, alignment: .trailing) + Color.clear.frame(width: 26) + } + .font(.system(size: 11, weight: .medium)).foregroundColor(t.secondary) + .padding(.horizontal, 10).padding(.vertical, 7) + .background(t.hover.opacity(0.5)) + } + + // MARK: footer + + private func footer(_ model: AllLinksModel, _ t: SettingsTheme) -> some View { + VStack(spacing: 0) { + Rectangle().fill(t.separator).frame(height: 1) + HStack(spacing: 8) { + if let pending = store.pendingToast { + Image(systemName: "checkmark.circle").foregroundColor(t.secondary).accessibilityHidden(true) + Text(pending).font(t.metaFont).foregroundColor(t.label).lineLimit(2) + .accessibilityIdentifier("links-toast") + .accessibilityAddTraits(.updatesFrequently) + Spacer(minLength: 8) + Button("Undo") { store.undo() }.sbButton().accessibilityIdentifier("undo-button") + } else if let toast = store.toast { + Image(systemName: "checkmark.circle").foregroundColor(t.ok).accessibilityHidden(true) + Text(toast).font(t.metaFont).foregroundColor(t.label).lineLimit(2) + .accessibilityIdentifier("links-toast") + .accessibilityAddTraits(.updatesFrequently) + Spacer() + } else { + Text(model.footer).font(t.metaFont).foregroundColor(t.secondary) + .accessibilityIdentifier("links-footer") + Spacer() + } + } + .padding(.horizontal, 20).padding(.vertical, 9) + .frame(minHeight: 38) + } + } +} + +private struct LinkTableRow: View { + @ObservedObject var store: AllLinksStore + let row: AllLinksRow + let selected: Bool + @Environment(\.colorScheme) private var scheme + + var body: some View { + let t = SettingsTheme(scheme) + HStack(spacing: 10) { + Toggle("", isOn: Binding(get: { selected }, set: { _ in store.state.toggle(row.id) })) + .toggleStyle(.checkbox).labelsHidden().frame(width: 18) + .accessibilityLabel("Select \(row.row.title)").accessibilityIdentifier("lc-\(row.id)") + HStack(spacing: 8) { + RoundedRectangle(cornerRadius: 6).fill(t.hover).frame(width: 24, height: 24) + .overlay(Image(systemName: row.row.glyph).font(.system(size: 11)).foregroundColor(row.dimmed ? t.tertiary : t.secondary)) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 0) { + Text(row.row.title).font(.system(size: 13, weight: .medium)) + .foregroundColor(row.dimmed ? t.secondary : t.label).lineLimit(1).truncationMode(.middle) + metaLine(t) + } + } + .frame(width: 196, alignment: .leading) + Text(row.owner).frame(width: 62, alignment: .leading) + Text(row.livesOn).lineLimit(1).truncationMode(.tail).frame(maxWidth: .infinity, alignment: .leading) + Text(row.expires).monospacedDigit().frame(width: 58, alignment: .trailing) + Text(row.views.map(String.init) ?? "").monospacedDigit().frame(width: 44, alignment: .trailing) + Button { store.copy(row) } label: { + Image(systemName: "doc.on.doc").font(.system(size: 12)) + .foregroundColor(t.secondary).frame(width: 26, height: 24).contentShape(Rectangle()) + } + .buttonStyle(.plain).disabled(!row.canCopy) + .opacity(row.canCopy ? 1 : 0.35) + .accessibilityLabel("Copy link to \(row.row.title)") + .accessibilityIdentifier("lcopy-\(row.id)") + } + .font(t.metaFont).foregroundColor(row.dimmed ? t.tertiary : t.secondary) + .padding(.horizontal, 10).padding(.vertical, 6) + .background(selected ? t.info.opacity(0.10) : .clear) + .accessibilityElement(children: .contain) + .accessibilityLabel(row.accessibilityLabel) + .accessibilityIdentifier("lr-\(row.id)") + } + + @ViewBuilder + private func metaLine(_ t: SettingsTheme) -> some View { + let parts: [String] = [row.stateWord, row.created].compactMap { $0 } + if !parts.isEmpty { + HStack(spacing: 0) { + if let word = row.stateWord { + Text(word).foregroundColor(row.tab == .expired ? t.secondary : t.attentionInk) + if row.created != nil { Text(" · ") } + } + if let created = row.created { Text(created) } + } + .font(t.metaFont).foregroundColor(t.secondary).lineLimit(1) + } + } +} diff --git a/mac/Sources/ShareBar/AllLinks/AllLinksWindowController.swift b/mac/Sources/ShareBar/AllLinks/AllLinksWindowController.swift new file mode 100644 index 0000000..1bc9001 --- /dev/null +++ b/mac/Sources/ShareBar/AllLinks/AllLinksWindowController.swift @@ -0,0 +1,64 @@ +import AppKit +import ShareBarCore +import SwiftUI + +/// Owns the one All links window: 620 pt wide, the surface painted on its root like Settings. +/// `AppRouter.openAllLinks()` opens it; the status item controller hands it the popover's store. +@MainActor +final class AllLinksWindowController: NSObject, NSWindowDelegate { + static let shared = AllLinksWindowController() + + private(set) var store: AllLinksStore? + private var window: NSWindow? + private var clock: Timer? + + var isShown: Bool { window?.isVisible ?? false } + var windowNumber: Int { window?.windowNumber ?? 0 } + + /// Called once by the status item controller, with the store the popover reads. + func attach(_ popover: PopoverStore) { + guard store == nil else { return } + store = AllLinksStore(popover: popover) + } + + func show() { + guard let store else { return } + store.opened() + let window = ensureWindow(store) + NSApp.activate(ignoringOtherApps: true) + window.makeKeyAndOrderFront(nil) + clock?.invalidate() + clock = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { [weak store] _ in + MainActor.assumeIsolated { store?.tick() } + } + } + + private func ensureWindow(_ store: AllLinksStore) -> NSWindow { + if let window { return window } + let hosting = NSHostingController(rootView: AllLinksView(store: store)) + hosting.sizingOptions = [.preferredContentSize] + let window = NSWindow(contentViewController: hosting) + window.styleMask = [.titled, .closable, .fullSizeContentView] + window.titlebarAppearsTransparent = true + window.titleVisibility = .hidden + window.title = "All links" + window.isReleasedWhenClosed = false + window.isMovableByWindowBackground = true + window.backgroundColor = NSColor(name: nil) { appearance in + let dark = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua + let rgb = dark ? SettingsTheme.surfaceDark : SettingsTheme.surfaceLight + return NSColor(srgbRed: rgb.red / 255, green: rgb.green / 255, blue: rgb.blue / 255, alpha: 1) + } + window.delegate = self + window.center() + self.window = window + return window + } + + func windowWillClose(_ notification: Notification) { + clock?.invalidate() + clock = nil + // A pending removal commits when its window closes, as it does when the popover closes. + store?.popover.send(.close) + } +} diff --git a/mac/Sources/ShareBar/Router/AppRouter.swift b/mac/Sources/ShareBar/Router/AppRouter.swift index 3e7f2e9..d523710 100644 --- a/mac/Sources/ShareBar/Router/AppRouter.swift +++ b/mac/Sources/ShareBar/Router/AppRouter.swift @@ -4,8 +4,7 @@ import os private let routerLogger = Logger(subsystem: "com.dwarves.sharebar", category: "router") -/// Where the popover's buttons land. The Settings window and its add sheet are real; the All -/// links window belongs to a later sub-goal, which replaces that body and nothing else. +/// Where the popover's buttons land: the Settings window, its add sheet and the All links window. enum SettingsTab: String { case general, tenants, members, advanced @@ -38,6 +37,7 @@ final class AppRouter { /// "Show all N links…". func openAllLinks() { routerLogger.log("openAllLinks") + MainActor.assumeIsolated { AllLinksWindowController.shared.show() } } /// The two first-run buttons. From 2c849ea927207d55539869df07d7f69294367b69 Mon Sep 17 00:00:00 2001 From: Han Ngo Date: Sun, 15 Nov 2026 21:41:38 +0700 Subject: [PATCH 4/8] feat(sharebar): app states, working line, notifications and shortcut status --- mac/Sources/ShareBar/Notifier.swift | 24 +++++ mac/Sources/ShareBar/Popover/ListBody.swift | 60 +++++++++--- .../ShareBar/Popover/OtherBodies.swift | 40 ++++++++ .../ShareBar/Popover/PopoverController.swift | 21 ++++- .../ShareBar/Popover/PopoverStore.swift | 79 ++++++++++++++-- .../ShareBar/Popover/ShareBarView.swift | 4 +- .../ShareBar/Settings/GeneralPane.swift | 11 ++- .../ShareBar/Settings/SettingsStore.swift | 2 + .../ShareBar/StatusItemController.swift | 8 ++ .../ShareBarCore/Popover/AppState.swift | 11 +++ .../Popover/AttentionNotify.swift | 92 +++++++++++++++++++ .../states/scenarios/working/member-ls.json | 1 + .../scenarios/working/profiles.json.tmpl | 78 ++++++++++++++++ mac/Tests/fixtures/states/states-shots.sh | 74 +++++++++++++++ 14 files changed, 482 insertions(+), 23 deletions(-) create mode 100644 mac/Sources/ShareBar/Notifier.swift create mode 100644 mac/Sources/ShareBarCore/Popover/AttentionNotify.swift create mode 100644 mac/Tests/fixtures/states/scenarios/working/member-ls.json create mode 100644 mac/Tests/fixtures/states/scenarios/working/profiles.json.tmpl create mode 100755 mac/Tests/fixtures/states/states-shots.sh diff --git a/mac/Sources/ShareBar/Notifier.swift b/mac/Sources/ShareBar/Notifier.swift new file mode 100644 index 0000000..abd10b5 --- /dev/null +++ b/mac/Sources/ShareBar/Notifier.swift @@ -0,0 +1,24 @@ +import Foundation +import ShareBarCore +import UserNotifications + +/// Posts one local notification for a General toggle that is on. The first post asks macOS for +/// permission; a refusal is silent (the toggle stays what the person set). +enum Notifier { + static func post(_ event: NotifyEvent) { + post(title: event.title, body: event.body, id: event.key) + } + + static func post(title: String, body: String, id: String) { + // A bare executable has no bundle for the center to attach to. + guard Bundle.main.bundleURL.pathExtension == "app" else { return } + let center = UNUserNotificationCenter.current() + center.requestAuthorization(options: [.alert]) { granted, _ in + guard granted else { return } + let content = UNMutableNotificationContent() + content.title = title + content.body = body + center.add(UNNotificationRequest(identifier: id, content: content, trigger: nil)) + } + } +} diff --git a/mac/Sources/ShareBar/Popover/ListBody.swift b/mac/Sources/ShareBar/Popover/ListBody.swift index eb3bf56..e588724 100644 --- a/mac/Sources/ShareBar/Popover/ListBody.swift +++ b/mac/Sources/ShareBar/Popover/ListBody.swift @@ -207,8 +207,13 @@ struct RowView: View { .accessibilityLabel(row.accessibilityLabel) .accessibilityIdentifier("row-\(row.id)") .accessibilityAddTraits(.isButton) - .accessibilityAction(named: "Copy link") { store.click(row) } - .accessibilityAction(named: "More actions") { store.openMenu(row.id) } + .accessibilityActions { + // The same items the row menu offers, so VoiceOver reaches every one of them. + ForEach(RowAccessibility.actions(for: row), id: \.self) { action in + Button(action.title) { store.choose(action, for: row) } + } + Button("More actions") { store.openMenu(row.id) } + } } } @@ -237,6 +242,16 @@ struct FooterBar: View { status(toast) Spacer(minLength: 8) if store.undoVisible { undoButton } + } else if let working = store.workingLine { + HStack(spacing: 6) { + SBWorkingDot(theme: theme) + Text(working).font(theme.metaFont).foregroundColor(theme.label) + } + .padding(.vertical, 4).padding(.horizontal, 6) + .accessibilityElement(children: .combine) + .accessibilityIdentifier("footer-working") + .accessibilityAddTraits(.updatesFrequently) + Spacer() } else { baseline Spacer() @@ -248,16 +263,31 @@ struct FooterBar: View { } private func status(_ footer: Footer) -> some View { - HStack(spacing: 6) { - Image(systemName: footer.kind == .failure ? "exclamationmark.triangle" : "checkmark.circle") - .font(.system(size: 12)).foregroundColor(footer.kind == .failure ? theme.errorInk : theme.secondary) - .accessibilityHidden(true) - Text(footer.text).font(theme.metaFont).foregroundColor(footer.kind == .failure ? theme.errorInk : theme.label) - .lineLimit(3).fixedSize(horizontal: false, vertical: true) + let failed = footer.kind == .failure + let line = failed ? FailureLine.split(footer.text) : (sentence: footer.text, next: nil as String?) + return VStack(alignment: .leading, spacing: 4) { + HStack(alignment: .firstTextBaseline, spacing: 6) { + Image(systemName: failed ? "exclamationmark.triangle" : "checkmark.circle") + .font(.system(size: 12)).foregroundColor(failed ? theme.errorInk : theme.secondary) + .accessibilityHidden(true) + Text(line.sentence).font(theme.metaFont).foregroundColor(failed ? theme.errorInk : theme.label) + .lineLimit(3).fixedSize(horizontal: false, vertical: true) + } + .accessibilityElement(children: .combine) + .accessibilityIdentifier("footer-status") + .accessibilityAddTraits(.updatesFrequently) + if let next = line.next { + HStack(spacing: 6) { + Text(next).font(theme.monoFont).foregroundColor(theme.label).lineLimit(1).truncationMode(.middle) + .textSelection(.enabled) + .padding(.horizontal, 6).padding(.vertical, 2) + .background(RoundedRectangle(cornerRadius: 4).fill(theme.hover)) + .accessibilityIdentifier("footer-next") + PanelButton(theme: theme, title: "Copy", id: "footer-next-copy") { store.copyCommand(next) } + } + .padding(.leading, 18) + } } - .accessibilityElement(children: .combine) - .accessibilityIdentifier("footer-status") - .accessibilityAddTraits(.updatesFrequently) } private var undoButton: some View { @@ -341,3 +371,11 @@ struct UploadRowView: View { .accessibilityIdentifier("upload-\((upload.title))") } } + +/// A small steady ring beside "Working:": motion is never the only sign, and Reduce Motion needs none. +struct SBWorkingDot: View { + let theme: Theme + var body: some View { + Circle().stroke(theme.info, lineWidth: 1.5).frame(width: 9, height: 9).accessibilityHidden(true) + } +} diff --git a/mac/Sources/ShareBar/Popover/OtherBodies.swift b/mac/Sources/ShareBar/Popover/OtherBodies.swift index 811f9bb..850fec2 100644 --- a/mac/Sources/ShareBar/Popover/OtherBodies.swift +++ b/mac/Sources/ShareBar/Popover/OtherBodies.swift @@ -108,3 +108,43 @@ struct FirstRunView: View { } } } + +/// Loading, the share command missing, or too old: one panel with the sentence and, when there +/// is a command to run, a button that copies it (SPEC-009 TASK-4b21). +struct AppStateView: View { + @ObservedObject var store: PopoverStore + let panel: AppStatePanel + @Environment(\.colorScheme) private var scheme + private var theme: Theme { Theme(scheme) } + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + HStack { + Text("Share Bar").font(theme.titleFont).foregroundColor(theme.label).padding(.horizontal, 6) + Spacer() + IconButton(theme: theme, symbol: "gearshape", id: "settings-button", label: "Settings") { store.openSettings(.general) } + } + .padding(.leading, 10).padding(.trailing, 8).padding(.top, 8).padding(.bottom, 6) + VStack(alignment: .leading, spacing: 10) { + HStack(spacing: 8) { + Image(systemName: panel.symbol).font(.system(size: 15)).foregroundColor(theme.secondary).accessibilityHidden(true) + Text(panel.title).font(theme.titleFont).foregroundColor(theme.label) + } + Text(panel.body).font(theme.bodyFont).foregroundColor(theme.secondary).fixedSize(horizontal: false, vertical: true) + if let button = panel.button, let text = panel.copy { + PanelButton(theme: theme, title: button, id: "app-state-copy", prominent: true) { store.copyCommand(text) } + Text(text).font(theme.monoFont).foregroundColor(theme.secondary).textSelection(.enabled) + .accessibilityIdentifier("app-state-command") + } + if let footer = store.state.footer { + Text(footer.text).font(theme.metaFont).foregroundColor(footer.kind == .failure ? theme.errorInk : theme.label) + .accessibilityIdentifier("footer-status") + .accessibilityAddTraits(.updatesFrequently) + } + } + .padding(.horizontal, 16).padding(.top, 8).padding(.bottom, 16) + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("app-state-\(panel.title)") + } +} diff --git a/mac/Sources/ShareBar/Popover/PopoverController.swift b/mac/Sources/ShareBar/Popover/PopoverController.swift index bc04fed..ef04c4c 100644 --- a/mac/Sources/ShareBar/Popover/PopoverController.swift +++ b/mac/Sources/ShareBar/Popover/PopoverController.swift @@ -113,7 +113,9 @@ final class PopoverController: NSObject, NSPopoverDelegate { /// `-ShareBarShotsScene ` (read here, so the frozen AppDelegate stays as it is) puts the /// popover in one state of TASK-4b10 to TASK-4b13 through the same reducer events a real drag, key /// or hotkey sends: `drop`, `uploading`, `flashed`, `dragout`, `hotkey`, and `ql-pdf`, `ql-folder`, - /// `ql-port`, `ql-cloud` for the Quick Look view. + /// `ql-port`, `ql-cloud` for the Quick Look view. The app states and the keyboard and error screens + /// of TASK-4b21 to TASK-4b23: `loading`, `cli-missing`, `cli-old`, `focus-third`, `menu-shift-f10`, + /// `publish-failure`; `first-run` and `working-line` come from the scenario the fake CLI answers with. func debugRender(to path: String, menuRow: String?, appearance: NSAppearance?, done: @escaping () -> Void) { let scene = UserDefaults.standard.string(forKey: "ShareBarShotsScene") let quickLookRow = ["ql-pdf": "pd0001", "ql-folder": "d4e5f6", "ql-port": "lv0001", "ql-cloud": "cl0001"][scene ?? ""] @@ -172,6 +174,23 @@ final class PopoverController: NSObject, NSPopoverDelegate { case "hotkey": store.showIssues() openForHotkey() + case "loading": + store.freezeForShots(profiles: nil, failure: nil) + case "cli-missing": + store.freezeForShots(profiles: nil, failure: .cliNotFound) + case "cli-old": + store.freezeForShots(profiles: nil, failure: .oldCLI) + case "focus-third": + // The popover opens with search focused, so the first Down enters row 1: the third row takes three. + for _ in 0..<3 { store.moveFocus(1) } + case "menu-shift-f10": + store.moveFocus(1) + store.openMenuOnFocused() + case "publish-failure": + let file = "/Users/demo/Q4-plan.pdf" + store.send(.publishStarted(file: file)) + let stderr = "share: the bucket refused the upload\n{\"error\":{\"code\":\"upload_refused\",\"message\":\"the bucket refused the upload\",\"next\":\"share status\"}}\n" + store.send(.publishFinished(file: file, result: PublishOutcome.result(status: 1, stdout: "", stderr: stderr, fallbackURL: nil), now: Date())) default: break } diff --git a/mac/Sources/ShareBar/Popover/PopoverStore.swift b/mac/Sources/ShareBar/Popover/PopoverStore.swift index 2fef520..90d0ccd 100644 --- a/mac/Sources/ShareBar/Popover/PopoverStore.swift +++ b/mac/Sources/ShareBar/Popover/PopoverStore.swift @@ -44,6 +44,11 @@ final class PopoverStore: ObservableObject { await CLI.spawnCancellable(argv, environment: ["SHARE_PROGRESS": "1", "SHARE_ERROR_JSON": "1"], onOutput: out).result } private var visible = false + /// General's After sharing and Notify me when, read at the moment they matter. + var general = GeneralPrefs() + /// Posts one notification; the app points it at `Notifier`, tests and shots leave it empty. + var notify: (NotifyEvent) -> Void = { _ in } + private var attention = AttentionNotifier() init(prefs: PopoverPrefs = PopoverPrefs(), router: AppRouter = .shared) { self.prefs = prefs @@ -88,12 +93,50 @@ final class PopoverStore: ObservableObject { var showsIssues: Bool { state.mode == .issues } var isFirstRun: Bool { state.mode == .firstRun } var isStale: Bool { failure != nil } + + /// Loading, CLI missing, CLI too old: bodies that replace the list (the first-run panel is `isFirstRun`). + var appState: AppState { AppState.of(profiles: profiles, failure: failure) } + + /// `Working: add (3/6)` for a journaled command another process runs; our own publishes show their placeholder rows. + var workingLine: String? { + guard state.publishing.isEmpty else { return nil } + return WorkingLine.text(for: profiles?.profiles.first { $0.name == currentProfile }) + } + + /// The panel's button: puts the command on the pasteboard and says so. + func copyCommand(_ text: String) { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(text, forType: .string) + state.footer = Footer(text: "Copied. Paste it in Terminal.", kind: .toast, expires: Date().addingTimeInterval(PopoverState.toastSeconds)) + } var undoVisible: Bool { !state.pending.isEmpty } // MARK: input /// A fresh `profiles` read from the controller. + #if DEBUG + /// Screenshot scenes only: holds the state a scene set against the controller's own reads. + var shotsFrozen = false + + func freezeForShots(profiles: ProfilesSnapshot?, failure: Failure?) { + shotsFrozen = true + self.profiles = profiles + self.failure = failure + send(.profilesChanged(hasRole: profiles.map { !$0.profiles.isEmpty } ?? false)) + } + #endif + func update(profiles: ProfilesSnapshot?, failure: Failure?) { + #if DEBUG + if shotsFrozen { return } + #endif + let before = viewModel.rows.map(\.id) + defer { + // Focus follows the row's id, never its position: a refresh that reorders rows keeps it. + if let focused = focusedRow { + focusedRow = RowFocus.restored(previous: focused, previousIndex: before.firstIndex(of: focused), ids: viewModel.rows.map(\.id)) + } + } self.profiles = profiles self.failure = failure now = Date() @@ -107,6 +150,12 @@ final class PopoverStore: ObservableObject { if profiles != nil { send(.profilesChanged(hasRole: !tenants.isEmpty)) } + notifyAttention() + } + + /// Notify me when: what is newly true since the last read, for the toggles that are on. + private func notifyAttention() { + for event in attention.events(profiles: profiles, members: members, prefs: general.notifyPrefs, current: currentProfile) { notify(event) } } private func applyRememberedScope() { @@ -201,6 +250,14 @@ final class PopoverStore: ObservableObject { state = next } + /// A bulk Remove from the All links window: one `pending` entry for every id, with its Undo. + func removeBulk(ids: [String], argv: [String], message: String) { + let now = Date() + var next = state.reduce(.remove(action: .bulkRemove, ids: ids, argv: argv, now: now, message: message)).state + next.footer = Footer(text: message, kind: .toast, expires: now.addingTimeInterval(Undo.window)) + state = next + } + /// The Delete key. func deleteFocused() { guard let id = focusedRow, let row = row(id) else { return } @@ -220,13 +277,7 @@ final class PopoverStore: ObservableObject { func moveFocus(_ step: Int) { keyboardFocus = true searchFocused = false - let ids = viewModel.rows.map(\.id) - guard !ids.isEmpty else { return } - guard let current = focusedRow, let index = ids.firstIndex(of: current) else { - focusedRow = step > 0 ? ids.first : ids.last - return - } - focusedRow = ids[max(0, min(ids.count - 1, index + step))] + focusedRow = RowFocus.moved(from: focusedRow, step: step, ids: viewModel.rows.map(\.id)) ?? focusedRow } func returnOnFocused() { @@ -346,8 +397,17 @@ final class PopoverStore: ObservableObject { ? await newRowURL(profile: profile, before: before, title: (path as NSString).lastPathComponent) : nil stepNames[path] = nil let outcome = PublishOutcome.result(status: result.status, stdout: result.stdout, stderr: result.stderr, fallbackURL: fresh?.url) - send(.publishFinished(file: path, result: outcome, now: Date())) - if case .copied = outcome, let id = fresh?.id { flash(id) } + // After sharing: Copy the link and Show a notification, each its own toggle. + var shown = outcome + if case .copied = outcome, !general.copyAfterSharing { shown = .copied(url: "") } + send(.publishFinished(file: path, result: shown, now: Date())) + if case .copied(let url) = outcome { + if general.copyAfterSharing, let id = fresh?.id { flash(id) } + if general.notifyAfterSharing { + let name = (path as NSString).lastPathComponent + notify(NotifyEvent(key: "shared:\(path)", title: general.copyAfterSharing ? "Link copied" : "Published", body: url.isEmpty ? name : "\(name): \(url)")) + } + } } private func hasPrintedLink(_ stdout: String) -> Bool { @@ -417,6 +477,7 @@ final class PopoverStore: ObservableObject { /// needs a look exist once the tab has loaded the roster. func setMembers(_ list: MemberList?, for profile: String) { if let list { members[profile] = list } else { members[profile] = nil } + notifyAttention() } // MARK: effects diff --git a/mac/Sources/ShareBar/Popover/ShareBarView.swift b/mac/Sources/ShareBar/Popover/ShareBarView.swift index cf1732b..e0a3f12 100644 --- a/mac/Sources/ShareBar/Popover/ShareBarView.swift +++ b/mac/Sources/ShareBar/Popover/ShareBarView.swift @@ -18,7 +18,9 @@ struct ShareBarView: View { var body: some View { ZStack(alignment: .topLeading) { Group { - if store.isFirstRun { + if let panel = store.appState.panel { + AppStateView(store: store, panel: panel) + } else if store.isFirstRun { FirstRunView(store: store) } else if store.showsIssues { IssuesView(store: store) diff --git a/mac/Sources/ShareBar/Settings/GeneralPane.swift b/mac/Sources/ShareBar/Settings/GeneralPane.swift index f76834e..b9a61fc 100644 --- a/mac/Sources/ShareBar/Settings/GeneralPane.swift +++ b/mac/Sources/ShareBar/Settings/GeneralPane.swift @@ -54,7 +54,16 @@ struct GeneralPane: View { .background(RoundedRectangle(cornerRadius: 6).fill(t.field)) .overlay(RoundedRectangle(cornerRadius: 6).stroke(t.border, lineWidth: 1)) .accessibilityIdentifier("g-shortcut") - SmallText("Opens the menu from anywhere.") + if let problem = store.hotkeyMessage() { + HStack(spacing: 5) { + Image(systemName: "exclamationmark.triangle").font(.system(size: 11)).foregroundColor(t.attentionInk).accessibilityHidden(true) + Text(problem).font(t.metaFont).foregroundColor(t.attentionInk).fixedSize(horizontal: false, vertical: true) + } + .accessibilityElement(children: .combine) + .accessibilityIdentifier("g-shortcut-status") + } else { + SmallText("Opens the menu from anywhere.") + } } } .frame(width: 506, alignment: .topLeading) diff --git a/mac/Sources/ShareBar/Settings/SettingsStore.swift b/mac/Sources/ShareBar/Settings/SettingsStore.swift index 23cabfb..e1b2c46 100644 --- a/mac/Sources/ShareBar/Settings/SettingsStore.swift +++ b/mac/Sources/ShareBar/Settings/SettingsStore.swift @@ -126,6 +126,8 @@ final class SettingsStore: ObservableObject { /// Called after every `member ls` read, so the popover's member lines of needs a look follow /// the roster (the popover never runs `member ls` itself, DEC-54). var onMembers: (MemberList?, String) -> Void = { _, _ in } + /// Why ⌃⌥S did not register (`Control-Option-S is in use by another app`), or nil; the popover owns the key. + var hotkeyMessage: () -> String? = { nil } let popoverPrefs: PopoverPrefs private let defaults: UserDefaults private let queue = MutationQueue() diff --git a/mac/Sources/ShareBar/StatusItemController.swift b/mac/Sources/ShareBar/StatusItemController.swift index 37399a9..1255646 100644 --- a/mac/Sources/ShareBar/StatusItemController.swift +++ b/mac/Sources/ShareBar/StatusItemController.swift @@ -105,7 +105,13 @@ final class StatusItemController: NSObject, @unchecked Sendable { super.init() MainActor.assumeIsolated { popoverStore = PopoverStore() + popoverStore.notify = { Notifier.post($0) } popoverController = PopoverController(store: popoverStore) + AllLinksWindowController.shared.attach(popoverStore) + // The Members tab reads the roster; the popover's member lines follow it (DEC-54). + let store = popoverStore + SettingsWindowController.shared.store.onMembers = { list, profile in store?.setMembers(list, for: profile) } + SettingsWindowController.shared.store.hotkeyMessage = { store?.hotkeyStatus.message } } menu.delegate = self menu.autoenablesItems = false @@ -204,6 +210,8 @@ final class StatusItemController: NSObject, @unchecked Sendable { popoverStore.onAddFile = { [weak self] in self?.pickFilesForPopover() } let queue = mutationQueue popoverStore.runCLI = { await queue.run($0) } + // One queue for the popover and the Settings window: a verb started in either waits for the other. + SettingsWindowController.shared.store.writeCLI = { await queue.run($0) } popoverStore.runPublish = { argv, output in await queue.run(argv, environment: ["SHARE_PROGRESS": "1"], onOutput: output) } diff --git a/mac/Sources/ShareBarCore/Popover/AppState.swift b/mac/Sources/ShareBarCore/Popover/AppState.swift index 6169cc0..1c4555b 100644 --- a/mac/Sources/ShareBarCore/Popover/AppState.swift +++ b/mac/Sources/ShareBarCore/Popover/AppState.swift @@ -106,3 +106,14 @@ public enum RowAccessibility { /// Actions rotor): the same items the menu offers, so nothing is reachable by pointer only. public static func actions(for row: RowModel) -> [RowAction] { RowMenu.items(for: row) } } + +/// A failure toast reads ` Next: ` (`PublishOutcome`): the sentence, then the +/// command as its own copyable line. +public enum FailureLine { + public static func split(_ text: String) -> (sentence: String, next: String?) { + guard let range = text.range(of: " Next: ", options: .backwards) else { return (text, nil) } + let next = String(text[range.upperBound...]).trimmingCharacters(in: .whitespaces) + guard !next.isEmpty else { return (text, nil) } + return (String(text[.. = [] + private var primed = false + + public init() {} + + /// Links that expire within this many seconds count as about to expire. + public static let expirySoon = 86_400 + + public mutating func events( + profiles: ProfilesSnapshot?, members: [String: MemberList], prefs: NotifyPrefs, current: String?, now: Date = Date() + ) -> [NotifyEvent] { + guard let profiles else { return [] } + var facts: [NotifyEvent] = [] + for entry in profiles.profiles { + guard let state = entry.state else { continue } + let role = ProfileView(entry: entry).role + let host = state.host ?? entry.name + if prefs.offline { + let offline = state.shares.filter { + LinkState(raw: $0.linkState) == .offline && PopoverViewModel.isOwn($0, state: state, role: role) + } + let machines = Dictionary(grouping: offline) { $0.by ?? "this Mac" } + for (machine, rows) in machines { + let count = rows.count + facts.append(NotifyEvent( + key: "offline:\(entry.name):\(machine)", title: "\(machine) is offline", + body: "\(count) of your \(count == 1 ? "link answers" : "links answer") 503 on \(host) until it is back.")) + } + } + if prefs.expiry { + let now = Int(now.timeIntervalSince1970) + for share in state.shares where share.kind != "live" && share.expires > now && share.expires - now <= Self.expirySoon + && LinkState(raw: share.linkState) == .live && PopoverViewModel.isOwn(share, state: state, role: role) { + let hours = max(1, (share.expires - now) / 3_600) + facts.append(NotifyEvent(key: "expiry:\(entry.name):\(share.id)", title: "\(share.name) expires soon", + body: "It stops answering in about \(hours) \(hours == 1 ? "hour" : "hours") on \(host).")) + } + } + } + if prefs.member { + let issues = IssueList(profiles: profiles, current: current, members: members, now: now) + for group in issues.groups { + for line in group.lines where line.kind == .member { + facts.append(NotifyEvent(key: "member:\(line.id)", title: line.title, body: "\(line.detail) on \(group.host).")) + } + } + } + let keys = Set(facts.map(\.key)) + defer { seen = keys } + guard primed else { + primed = true + return [] + } + return facts.filter { !seen.contains($0.key) }.sorted { $0.key < $1.key } + } +} diff --git a/mac/Tests/fixtures/states/scenarios/working/member-ls.json b/mac/Tests/fixtures/states/scenarios/working/member-ls.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/mac/Tests/fixtures/states/scenarios/working/member-ls.json @@ -0,0 +1 @@ +[] diff --git a/mac/Tests/fixtures/states/scenarios/working/profiles.json.tmpl b/mac/Tests/fixtures/states/scenarios/working/profiles.json.tmpl new file mode 100644 index 0000000..26c8b4b --- /dev/null +++ b/mac/Tests/fixtures/states/scenarios/working/profiles.json.tmpl @@ -0,0 +1,78 @@ +{ + "schema": 1, + "profiles": [ + { + "name": "default", + "state": { + "schema": 1, + "state": "serving", + "ready": true, + "mode": "named", + "host": "s.han.ws", + "hosts": "Mac-mini", + "serves_here": true, + "service": true, + "access_pending": 0, + "role": "origin", + "tier": "t0", + "serve": { + "phase": "serving", + "reason": "ok" + }, + "ops": [{"verb": "add", "step": 3, "of": 6, "name": "upload", "alive": true, "id": "9f9f9f", "rerun": "share add big.mov", "rerun_argv": ["add", "big.mov"], "rollback": null, "rollback_argv": null}], + "token": { + "source": "keychain", + "status": "ok", + "expires_on": "2027-06-01" + }, + "compat": { + "cli": "0.10.0", + "worker": "5 a1b2c3d4e5f6", + "status": "ok", + "min_cli": "0.10.0" + }, + "shares": [ + { + "id": "a1b2c3", + "name": "posture-routine.html", + "url": "https://s.han.ws/a1b2c3/posture-routine.html", + "kind": "snapshot", + "own_host": null, + "expires": 0, + "storage": "machine", + "type": "page", + "by": "Mac-mini", + "link_state": "live", + "added": "@D1@" + }, + { + "id": "d4e5f6", + "name": "trang-mobility", + "url": "https://s.han.ws/d4e5f6/trang-mobility", + "kind": "snapshot", + "own_host": null, + "expires": 0, + "storage": "machine", + "type": "folder", + "by": "Mac-mini", + "link_state": "live", + "added": "@D8@" + }, + { + "id": "0a9b8c", + "name": "max-big-race.html", + "url": "https://s.han.ws/0a9b8c/max-big-race.html", + "kind": "snapshot", + "own_host": null, + "expires": @EXP27@, + "storage": "machine", + "type": "page", + "by": "Mac-mini", + "link_state": "live", + "added": "@D3@" + } + ] + } + } + ] +} \ No newline at end of file diff --git a/mac/Tests/fixtures/states/states-shots.sh b/mac/Tests/fixtures/states/states-shots.sh new file mode 100755 index 0000000..6d76f54 --- /dev/null +++ b/mac/Tests/fixtures/states/states-shots.sh @@ -0,0 +1,74 @@ +#!/bin/bash +# states-shots.sh: the popover screens of SPEC-009 TASK-4b21 to TASK-4b23, rendered through the app's +# DEBUG hook with no pointer or key input on the desktop (DEC-83). Each scene is +# `-ShareBarShotsRender -ShareBarShotsScene `; light and dark; the fake CLI answers from a +# scenario copy. +# +# Usage: mac/Tests/fixtures/states/states-shots.sh [scene ...] +# Scenes: loading cli-missing cli-old first-run focus-third menu-shift-f10 publish-failure working-line +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +MAC="$(cd "$HERE/../../.." && pwd)" +FIX="$MAC/Tests/fixtures" +OUT="${1:?usage: states-shots.sh [scene ...]}" +shift || true +SCENES=("$@") +if [[ ${#SCENES[@]} -eq 0 ]]; then SCENES=(loading cli-missing cli-old first-run focus-third menu-shift-f10 publish-failure working-line); fi +WORK="$MAC/build/states-shots" +mkdir -p "$OUT" "$WORK/gone" + +APP_PID="" +cleanup() { + if [[ -n $APP_PID ]]; then kill "$APP_PID" 2>/dev/null || true; wait "$APP_PID" 2>/dev/null || true; fi +} +trap cleanup EXIT + +swift build --package-path "$MAC" >/dev/null +BIN="$(swift build --package-path "$MAC" --show-bin-path)" +APP="$WORK/Share Bar.app" +mkdir -p "$APP/Contents/MacOS" +command cp -f "$BIN/ShareBar" "$APP/Contents/MacOS/ShareBar" +command cp -f "$MAC/Info.plist" "$APP/Contents/Info.plist" +/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier com.dwarves.sharebar.shots.states" "$APP/Contents/Info.plist" +codesign --force --sign - "$APP" >/dev/null 2>&1 + +prepare() { # prepare [template] + RUN="$WORK/run" + mv "$RUN" "$WORK/gone/run.$$.$RANDOM" 2>/dev/null || true + mkdir -p "$RUN/scenario" + command cp -f "$1/member-ls.json" "$RUN/scenario/" + if [[ -f $1/profiles.json.tmpl ]]; then + sed -e "s/@D1@/$(date -v-1d +%F)/" -e "s/@D3@/$(date -v-3d +%F)/" -e "s/@D8@/$(date -v-8d +%F)/" \ + -e "s/@EXP27@/$(( $(date +%s) + 27 * 86400 + 3600 ))/" "$1/profiles.json.tmpl" > "$RUN/scenario/profiles.json" + else + command cp -f "$1/profiles.json" "$RUN/scenario/" + fi + : > "$RUN/argv.log" +} + +shoot() { # shoot + local scene="$1" mode="$2" png="$OUT/$1-$2.png" args=() + mv -f "$png" "$WORK/gone/$(basename "$png").$$" 2>/dev/null || true + args=(-ShareBarShotsRender "$png" -ShareBarShotsScene "$scene") + [[ $mode == dark ]] && args+=(-ShareBarShotsAppearance dark) + SHARE_BIN="$FIX/bin/share" SHARE_FAKE_DIR="$RUN" SHARE_FAKE_DELAY=0 \ + "$APP/Contents/MacOS/ShareBar" "${args[@]}" >"$RUN/app-$scene-$mode.log" 2>&1 & + APP_PID=$! + local i + for i in $(seq 1 80); do kill -0 "$APP_PID" 2>/dev/null || break; sleep 0.5; done + kill "$APP_PID" 2>/dev/null || true + wait "$APP_PID" 2>/dev/null || true + APP_PID="" + [[ -s $png ]] || { echo "states-shots.sh: no image for $scene $mode (see $RUN/app-$scene-$mode.log)" >&2; exit 1; } + echo "wrote $png" +} + +for scene in "${SCENES[@]}"; do + case $scene in + first-run) prepare "$FIX/scenarios/firstrun" ;; + working-line) prepare "$HERE/scenarios/working" ;; + *) prepare "$FIX/popover/scenarios/parity-calm" ;; + esac + for mode in light dark; do shoot "$scene" "$mode"; done +done From 2e5f7870e9046ecdc7a4d0b1fc685f40832d4aeb Mon Sep 17 00:00:00 2001 From: Han Ngo Date: Sun, 15 Nov 2026 21:44:55 +0700 Subject: [PATCH 5/8] test(sharebar): All links window screens through in-app hooks --- .../ShareBar/AllLinks/AllLinksView.swift | 2 +- .../ShareBar/Settings/ShotsHooks.swift | 20 +- mac/Sources/ShareBarCore/AllLinksModel.swift | 2 +- mac/Tests/fixtures/settings/run-shots.sh | 7 + .../settings/scenarios/links/member-ls.json | 389 ++++++++++++++++++ .../settings/scenarios/links/profiles.json | 223 ++++++++++ .../fixtures/settings/steps/links-all.shot | 3 + .../settings/steps/links-bulk-copy.shot | 3 + .../settings/steps/links-bulk-remove.shot | 4 + .../settings/steps/links-bulk-removed.shot | 4 + .../settings/steps/links-expired.shot | 3 + .../settings/steps/links-needs-look.shot | 3 + .../settings/steps/links-no-match.shot | 3 + .../settings/steps/links-selected.shot | 3 + 14 files changed, 666 insertions(+), 3 deletions(-) create mode 100644 mac/Tests/fixtures/settings/scenarios/links/member-ls.json create mode 100644 mac/Tests/fixtures/settings/scenarios/links/profiles.json create mode 100644 mac/Tests/fixtures/settings/steps/links-all.shot create mode 100644 mac/Tests/fixtures/settings/steps/links-bulk-copy.shot create mode 100644 mac/Tests/fixtures/settings/steps/links-bulk-remove.shot create mode 100644 mac/Tests/fixtures/settings/steps/links-bulk-removed.shot create mode 100644 mac/Tests/fixtures/settings/steps/links-expired.shot create mode 100644 mac/Tests/fixtures/settings/steps/links-needs-look.shot create mode 100644 mac/Tests/fixtures/settings/steps/links-no-match.shot create mode 100644 mac/Tests/fixtures/settings/steps/links-selected.shot diff --git a/mac/Sources/ShareBar/AllLinks/AllLinksView.swift b/mac/Sources/ShareBar/AllLinks/AllLinksView.swift index 325f2ab..9e88f91 100644 --- a/mac/Sources/ShareBar/AllLinks/AllLinksView.swift +++ b/mac/Sources/ShareBar/AllLinks/AllLinksView.swift @@ -151,7 +151,7 @@ struct AllLinksView: View { Color.clear.frame(width: 26) } .font(.system(size: 11, weight: .medium)).foregroundColor(t.secondary) - .padding(.horizontal, 10).padding(.vertical, 7) + .padding(.horizontal, 10).frame(height: 28) .background(t.hover.opacity(0.5)) } diff --git a/mac/Sources/ShareBar/Settings/ShotsHooks.swift b/mac/Sources/ShareBar/Settings/ShotsHooks.swift index 5b4a2b4..ec447e2 100644 --- a/mac/Sources/ShareBar/Settings/ShotsHooks.swift +++ b/mac/Sources/ShareBar/Settings/ShotsHooks.swift @@ -17,8 +17,13 @@ import SwiftUI /// `invite-mode=`, `invite-ttl=`, `create-code`, `pause::`, /// `remove-member::`, `wait:`. Members tab: `keys` (both key sources as stored commands), `mload` (wait for the roster), /// `mfilter:`, `mquery=`, `mmenu:`, `mverb::`. +/// All links window (the capture then takes that window): `links`, `ltab:`, +/// `lq=`, `lselect:+`, `lbulkcopy`, `lbulkremove`. @MainActor enum ShotsHooks { + /// Set by `links`: the capture then takes the All links window, not Settings. + private static var captureAllLinks = false + static func installIfRequested() { guard let script = UserDefaults.standard.string(forKey: "ShareBarShotsScreen"), !script.isEmpty else { return } DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { @@ -36,7 +41,8 @@ enum ShotsHooks { } try? await Task.sleep(nanoseconds: 600_000_000) if let dir = ProcessInfo.processInfo.environment["SHARE_FAKE_DIR"] { - let info = "\(controller.windowNumber)\n" + let number = captureAllLinks ? AllLinksWindowController.shared.windowNumber : controller.windowNumber + let info = "\(number)\n" try? info.write(toFile: dir + "/shots-ready", atomically: true, encoding: .utf8) } } @@ -117,6 +123,18 @@ enum ShotsHooks { await step(inner, store: store, controller: controller) try? await Task.sleep(nanoseconds: 150_000_000) } + case "links": + let popover = AllLinksWindowController.shared.store?.popover + for _ in 0..<80 where popover?.profiles == nil { try? await Task.sleep(nanoseconds: 100_000_000) } + AllLinksWindowController.shared.show() + captureAllLinks = true + case "ltab": + AllLinksWindowController.shared.store?.state.show(AllLinksTab(rawValue: rest) ?? .all) + case "lq": AllLinksWindowController.shared.store?.setQuery(rest) + case "lselect": + for id in rest.split(separator: "+") { AllLinksWindowController.shared.store?.state.toggle(String(id)) } + case "lbulkcopy": AllLinksWindowController.shared.store?.bulkCopy() + case "lbulkremove": AllLinksWindowController.shared.store?.bulkRemove() case "mload": for _ in 0..<60 where store.members.list == nil && store.members.failure == nil { try? await Task.sleep(nanoseconds: 100_000_000) } case "mfilter": store.members.filter = MemberFilter(rawValue: rest) ?? .all diff --git a/mac/Sources/ShareBarCore/AllLinksModel.swift b/mac/Sources/ShareBarCore/AllLinksModel.swift index 1214e3b..8704d8b 100644 --- a/mac/Sources/ShareBarCore/AllLinksModel.swift +++ b/mac/Sources/ShareBarCore/AllLinksModel.swift @@ -116,7 +116,7 @@ public struct AllLinksModel: Sendable, Equatable { let expired = PopoverViewModel.isExpired(share, now: now) let tab: AllLinksTab = expired ? .expired : (model.state == .live ? .live : .needsLook) let owner = PopoverViewModel.ownerName(of: share, state: snapshot, role: role) ?? "" - let place = share.storage == "cloud" ? "cloud" : (model.machine) + let place = share.storage == "cloud" ? "cloud" : (model.own ? "this Mac" : model.machine) return AllLinksRow( row: model, tab: tab, owner: owner, livesOn: place, expires: expiresText(share, expired: expired, now: now), diff --git a/mac/Tests/fixtures/settings/run-shots.sh b/mac/Tests/fixtures/settings/run-shots.sh index 35bbce9..949fd62 100755 --- a/mac/Tests/fixtures/settings/run-shots.sh +++ b/mac/Tests/fixtures/settings/run-shots.sh @@ -73,6 +73,13 @@ capture() { # capture RUN_DIR="$(mktemp -d "$WORK/run.XXXXXX")" mkdir -p "$RUN_DIR/scenario" command cp -f "$HERE/scenarios/$scenario"/* "$RUN_DIR/scenario/" + # @E@ is n days from now (an expiry epoch), @A@ is n days ago (an added day), read against the clock of the run + local rule="" n + for n in 0 1 2 3 4 5 6 7 9 14 21 30; do + rule="$rule -e s/@E$n@/$(( $(date +%s) + n * 86400 + 3600 ))/g -e s/@A$n@/$(date -v-${n}d +%F)/g" + done + # shellcheck disable=SC2086 + [[ ! -f $RUN_DIR/scenario/profiles.json ]] || sed -i '' $rule "$RUN_DIR/scenario/profiles.json" # a code that expires in 6 days, read against the clock of the run [[ ! -f $RUN_DIR/scenario/member-ls.json ]] || sed -i '' "s/@EXP6@/$(( $(date +%s) + 6 * 86400 + 3600 ))/g" "$RUN_DIR/scenario/member-ls.json" : > "$RUN_DIR/argv.log" diff --git a/mac/Tests/fixtures/settings/scenarios/links/member-ls.json b/mac/Tests/fixtures/settings/scenarios/links/member-ls.json new file mode 100644 index 0000000..6b125a8 --- /dev/null +++ b/mac/Tests/fixtures/settings/scenarios/links/member-ls.json @@ -0,0 +1,389 @@ +[ + { + "member_id": "m-an-1a2b3c4d", + "name": "an", + "mode": "machine", + "status": "active", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": true, + "paused": false + }, + "account": { + "tunnel": "t-an", + "connectors": 1, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "pause", + "invite", + "rotate", + "renew", + "rm" + ] + }, + { + "member_id": "m-nam-1a2b4e81", + "name": "nam", + "mode": "machine", + "status": "pausing", + "expired": false, + "step": 2, + "of": 3, + "step_name": "deploy", + "lease": { + "holder": "han", + "verb": "pause", + "step": 2, + "live": false + }, + "deploy": { + "bound": false, + "paused": false + }, + "account": { + "tunnel": "t-nam", + "connectors": 0, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "finish", + "rm" + ] + }, + { + "member_id": "m-linh-1a2b60b5", + "name": "linh", + "mode": "cloud", + "status": "invited", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": false, + "paused": false + }, + "account": { + "tunnel": "t-linh", + "connectors": 0, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": @EXP6@, + "prev_status": null, + "drift": [], + "can": [ + "invite", + "rm" + ] + }, + { + "member_id": "m-bao-1a2b72e9", + "name": "bao", + "mode": "machine", + "status": "active", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": true, + "paused": false + }, + "account": { + "tunnel": "t-bao", + "connectors": 1, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "pause", + "invite", + "rotate", + "renew", + "rm" + ] + }, + { + "member_id": "m-chi-1a2b851d", + "name": "chi", + "mode": "machine", + "status": "paused", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": false, + "paused": true + }, + "account": { + "tunnel": "t-chi", + "connectors": 0, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "resume", + "rotate", + "rm" + ] + }, + { + "member_id": "m-duc-1a2b9751", + "name": "duc", + "mode": "machine", + "status": "active", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": true, + "paused": false + }, + "account": { + "tunnel": "t-duc", + "connectors": 1, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "pause", + "invite", + "rotate", + "renew", + "rm" + ] + }, + { + "member_id": "m-hai-1a2ba985", + "name": "hai", + "mode": "machine", + "status": "joining", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": false, + "paused": false + }, + "account": { + "tunnel": "t-hai", + "connectors": 0, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "finish", + "rm" + ] + }, + { + "member_id": "m-khoa-1a2bbbb9", + "name": "khoa", + "mode": "cloud", + "status": "active", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": true, + "paused": false + }, + "account": { + "tunnel": "t-khoa", + "connectors": 1, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "pause", + "invite", + "rotate", + "renew", + "rm" + ] + }, + { + "member_id": "m-lan-1a2bcded", + "name": "lan", + "mode": "machine", + "status": "left", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": false, + "paused": false + }, + "account": { + "tunnel": "t-lan", + "connectors": 0, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": "active", + "drift": [], + "can": [ + "invite", + "rm" + ] + }, + { + "member_id": "m-minh-1a2be021", + "name": "minh", + "mode": "machine", + "status": "active", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": true, + "paused": false + }, + "account": { + "tunnel": "t-minh", + "connectors": 1, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "pause", + "invite", + "rotate", + "renew", + "rm" + ] + }, + { + "member_id": "m-nhi-1a2bf255", + "name": "nhi", + "mode": "machine", + "status": "removing", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": false, + "paused": false + }, + "account": { + "tunnel": "t-nhi", + "connectors": 0, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "finish", + "rm" + ] + }, + { + "member_id": "m-phuc-1a2c0489", + "name": "phuc", + "mode": "machine", + "status": "active", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": true, + "paused": false + }, + "account": { + "tunnel": "t-phuc", + "connectors": 1, + "services": 1 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "pause", + "invite", + "rotate", + "renew", + "rm" + ] + }, + { + "member_id": "m-quan-9d8e7f6a", + "name": "quan", + "mode": "machine", + "status": "removed", + "expired": false, + "step": null, + "of": null, + "step_name": null, + "lease": null, + "deploy": { + "bound": false, + "paused": false + }, + "account": { + "tunnel": null, + "connectors": 0, + "services": 0 + }, + "token_expires": "2027-01-15", + "invite_expires": null, + "prev_status": null, + "drift": [], + "can": [ + "purge" + ] + } +] \ No newline at end of file diff --git a/mac/Tests/fixtures/settings/scenarios/links/profiles.json b/mac/Tests/fixtures/settings/scenarios/links/profiles.json new file mode 100644 index 0000000..1c3adf6 --- /dev/null +++ b/mac/Tests/fixtures/settings/scenarios/links/profiles.json @@ -0,0 +1,223 @@ +{ + "schema": 1, + "profiles": [ + { + "name": "console", + "state": { + "schema": 1, + "state": "serving", + "ready": true, + "mode": "named", + "host": "s.console.so", + "hosts": "Mac-mini", + "serves_here": true, + "service": true, + "access_pending": 0, + "r2": true, + "storage_default": "cloud", + "role": "tenant_origin", + "tier": "t2", + "serve": { + "phase": "serving", + "reason": "ok" + }, + "ops": [], + "token": { + "source": "keychain", + "status": "expiring", + "expires_on": "2026-12-01" + }, + "compat": { + "cli": "0.10.0", + "worker": "5 a1b2c3d4e5f6", + "status": "ok", + "min_cli": "0.10.0" + }, + "shares": [ + { + "id": "0d489d", + "name": "kid-demos", + "url": "https://s.console.so/0d489d/kid-demos", + "kind": "snapshot", + "own_host": null, + "expires": 0, + "storage": "machine", + "type": "folder", + "by": "Mac-mini", + "link_state": "live", + "added": "@A0@" + }, + { + "id": "c4e211", + "name": "q4-pitch-deck.pdf", + "url": "https://s.console.so/c4e211/q4-pitch-deck.pdf", + "kind": "snapshot", + "own_host": null, + "expires": @E6@, + "storage": "machine", + "type": "pdf", + "by": "Mac-mini", + "link_state": "live", + "added": "@A0@" + }, + { + "id": "7f3a21", + "name": "playdate-uat-run.mov", + "url": "https://s.console.so/7f3a21/playdate-uat-run.mov", + "kind": "snapshot", + "own_host": null, + "expires": @E3@, + "storage": "machine", + "type": "video", + "by": "An's MacBook", + "link_state": "offline", + "added": "@A0@", + "origin": "m-an-1a2b3c4d" + }, + { + "id": "a19f03", + "name": "press-kit.html", + "url": "https://s.console.so/a19f03/press-kit.html", + "kind": "snapshot", + "own_host": null, + "expires": @E21@, + "storage": "machine", + "type": "page", + "by": "Mac-mini", + "link_state": "live", + "added": "@A0@" + }, + { + "id": "91fe20", + "name": "hero-v4.png", + "url": "https://s.console.so/91fe20/hero-v4.png", + "kind": "snapshot", + "own_host": null, + "expires": @E7@, + "storage": "cloud", + "type": "image", + "by": "Linh", + "link_state": "live", + "added": "@A0@", + "origin": "m-linh-5e6f7a8b", + "views": 3 + }, + { + "id": "91ac4e", + "name": "localhost:3000", + "url": "http://localhost:3000", + "kind": "live", + "own_host": null, + "expires": 0, + "storage": "machine", + "type": "page", + "by": "Binh's server", + "link_state": "live", + "added": "@A0@", + "origin": "m-binh-7a7b7c7d" + }, + { + "id": "e04b9c", + "name": "landing-draft.html", + "url": "https://s.console.so/e04b9c/landing-draft.html", + "kind": "snapshot", + "own_host": null, + "expires": @E2@, + "storage": "machine", + "type": "page", + "by": "Dung's iMac", + "link_state": "paused", + "added": "@A1@", + "origin": "m-dung-9a8b7c6d" + }, + { + "id": "f1d7e2", + "name": "hermes-demo-45s.mp4", + "url": "https://s.console.so/f1d7e2/hermes-demo-45s.mp4", + "kind": "snapshot", + "own_host": null, + "expires": @E30@, + "storage": "cloud", + "type": "video", + "by": "Mac-mini", + "link_state": "live", + "added": "@A1@", + "views": 12 + }, + { + "id": "b2c3d4", + "name": "invoice-2026-10.pdf", + "url": "https://s.console.so/b2c3d4/invoice-2026-10.pdf", + "kind": "snapshot", + "own_host": null, + "expires": 1700000000, + "storage": "cloud", + "type": "pdf", + "by": "Mac-mini", + "link_state": "expired", + "added": "@A9@", + "views": 7 + }, + { + "id": "2be8d0", + "name": "bao-cao-thang-10.pdf", + "url": "https://s.console.so/2be8d0/bao-cao-thang-10.pdf", + "kind": "snapshot", + "own_host": null, + "expires": @E6@, + "storage": "machine", + "type": "pdf", + "by": "An's MacBook", + "link_state": "offline", + "added": "@A2@", + "origin": "m-an-1a2b3c4d" + }, + { + "id": "3c8d11", + "name": "contract-draft-v2.pdf", + "url": "https://s.console.so/3c8d11/contract-draft-v2.pdf", + "kind": "snapshot", + "own_host": null, + "expires": @E14@, + "storage": "cloud", + "type": "pdf", + "by": "Khoa", + "link_state": "live", + "added": "@A2@", + "origin": "m-khoa-2c2d2e2f", + "views": 1 + }, + { + "id": "7a2b90", + "name": "brand-assets", + "url": "https://s.console.so/7a2b90/brand-assets", + "kind": "snapshot", + "own_host": null, + "expires": 0, + "storage": "machine", + "type": "folder", + "by": "Minh's Mac Studio", + "link_state": "live", + "added": "@A3@", + "origin": "m-minh-3a3b3c3d" + }, + { + "id": "d4e5f6", + "name": "moodboard.png", + "url": "https://s.console.so/d4e5f6/moodboard.png", + "kind": "snapshot", + "own_host": null, + "expires": @E5@, + "storage": "cloud", + "type": "image", + "by": "Phuc", + "link_state": "live", + "added": "@A4@", + "origin": "m-phuc-4e4f5a5b", + "views": 0 + } + ] + } + } + ] +} \ No newline at end of file diff --git a/mac/Tests/fixtures/settings/steps/links-all.shot b/mac/Tests/fixtures/settings/steps/links-all.shot new file mode 100644 index 0000000..1127917 --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/links-all.shot @@ -0,0 +1,3 @@ +scenario links +script links,wait:1 +label links-all diff --git a/mac/Tests/fixtures/settings/steps/links-bulk-copy.shot b/mac/Tests/fixtures/settings/steps/links-bulk-copy.shot new file mode 100644 index 0000000..73ff8c0 --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/links-bulk-copy.shot @@ -0,0 +1,3 @@ +scenario links +script links,lselect:91fe20+f1d7e2+3c8d11,lbulkcopy +label links-bulk-copied diff --git a/mac/Tests/fixtures/settings/steps/links-bulk-remove.shot b/mac/Tests/fixtures/settings/steps/links-bulk-remove.shot new file mode 100644 index 0000000..68e6580 --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/links-bulk-remove.shot @@ -0,0 +1,4 @@ +scenario links +script links,lselect:91fe20+3c8d11+7f3a21,lbulkremove +expect-no-argv rm +label links-bulk-remove-pending diff --git a/mac/Tests/fixtures/settings/steps/links-bulk-removed.shot b/mac/Tests/fixtures/settings/steps/links-bulk-removed.shot new file mode 100644 index 0000000..96a9e46 --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/links-bulk-removed.shot @@ -0,0 +1,4 @@ +scenario links +script links,lselect:91fe20+3c8d11+7f3a21,lbulkremove,wait:7.5 +expect-argv rm 7f3a21 91fe20 3c8d11 +label links-bulk-removed diff --git a/mac/Tests/fixtures/settings/steps/links-expired.shot b/mac/Tests/fixtures/settings/steps/links-expired.shot new file mode 100644 index 0000000..087f449 --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/links-expired.shot @@ -0,0 +1,3 @@ +scenario links +script links,ltab:expired +label links-expired diff --git a/mac/Tests/fixtures/settings/steps/links-needs-look.shot b/mac/Tests/fixtures/settings/steps/links-needs-look.shot new file mode 100644 index 0000000..09f8178 --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/links-needs-look.shot @@ -0,0 +1,3 @@ +scenario links +script links,ltab:needsLook +label links-needs-look diff --git a/mac/Tests/fixtures/settings/steps/links-no-match.shot b/mac/Tests/fixtures/settings/steps/links-no-match.shot new file mode 100644 index 0000000..33008db --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/links-no-match.shot @@ -0,0 +1,3 @@ +scenario links +script links,lq=zzz +label links-no-match diff --git a/mac/Tests/fixtures/settings/steps/links-selected.shot b/mac/Tests/fixtures/settings/steps/links-selected.shot new file mode 100644 index 0000000..8038ce9 --- /dev/null +++ b/mac/Tests/fixtures/settings/steps/links-selected.shot @@ -0,0 +1,3 @@ +scenario links +script links,lselect:91fe20+f1d7e2+3c8d11 +label links-selected From fc906ace6237bd4cbf6dcf2a4cab10436bb2aeb3 Mon Sep 17 00:00:00 2001 From: Han Ngo Date: Sun, 15 Nov 2026 21:45:49 +0700 Subject: [PATCH 6/8] test(sharebar): notifications, failure line and shots helpers --- .../Popover/AttentionNotifyTests.swift | 50 +++++++++++++++++++ mac/Tests/fixtures/ax/axdrive.swift | 9 +++- mac/shots.sh | 13 ++++- 3 files changed, 70 insertions(+), 2 deletions(-) create mode 100644 mac/Tests/ShareBarCoreTests/Popover/AttentionNotifyTests.swift diff --git a/mac/Tests/ShareBarCoreTests/Popover/AttentionNotifyTests.swift b/mac/Tests/ShareBarCoreTests/Popover/AttentionNotifyTests.swift new file mode 100644 index 0000000..3429002 --- /dev/null +++ b/mac/Tests/ShareBarCoreTests/Popover/AttentionNotifyTests.swift @@ -0,0 +1,50 @@ +import XCTest +@testable import ShareBarCore + +/// General's Notify me when toggles and the After sharing failure line. +final class AttentionNotifyTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + private let all = NotifyPrefs(offline: true, expiry: true, member: true) + + private func profiles(state: String = "live", expires: Int = 4_102_444_800) -> ProfilesSnapshot { + let share = makeShare(id: "x1", name: "deck.pdf", url: "u", expires: expires, storage: "machine", by: "Mac", linkState: state) + return makeProfiles([("p", makeSnapshot(host: "s.t", shares: [share], role: "origin", tier: "t0"))]) + } + + func testTheFirstReadOnlyPrimes() { + var notifier = AttentionNotifier() + XCTAssertEqual(notifier.events(profiles: profiles(state: "offline"), members: [:], prefs: all, current: "p", now: now), []) + } + + func testAnOwnLinkGoingOfflineNotifiesOnceAndRefiresAfterItClears() { + var notifier = AttentionNotifier() + _ = notifier.events(profiles: profiles(), members: [:], prefs: all, current: "p", now: now) + let first = notifier.events(profiles: profiles(state: "offline"), members: [:], prefs: all, current: "p", now: now) + XCTAssertEqual(first.map(\.title), ["Mac is offline"]) + XCTAssertEqual(notifier.events(profiles: profiles(state: "offline"), members: [:], prefs: all, current: "p", now: now), []) + _ = notifier.events(profiles: profiles(), members: [:], prefs: all, current: "p", now: now) + XCTAssertEqual(notifier.events(profiles: profiles(state: "offline"), members: [:], prefs: all, current: "p", now: now).count, 1) + } + + func testAToggleThatIsOffSaysNothing() { + var notifier = AttentionNotifier() + let off = NotifyPrefs(offline: false, expiry: false, member: false) + _ = notifier.events(profiles: profiles(), members: [:], prefs: off, current: "p", now: now) + XCTAssertEqual(notifier.events(profiles: profiles(state: "offline"), members: [:], prefs: off, current: "p", now: now), []) + } + + func testALinkAboutToExpireNotifies() { + var notifier = AttentionNotifier() + _ = notifier.events(profiles: profiles(), members: [:], prefs: all, current: "p", now: now) + let soon = Int(now.timeIntervalSince1970) + 3 * 3_600 + let events = notifier.events(profiles: profiles(expires: soon), members: [:], prefs: all, current: "p", now: now) + XCTAssertEqual(events.map(\.title), ["deck.pdf expires soon"]) + XCTAssertTrue(events[0].body.contains("3 hours")) + } + + func testFailureLineSplitsTheNextStep() { + XCTAssertEqual(FailureLine.split("Couldn't publish: no. Next: share status").next, "share status") + XCTAssertEqual(FailureLine.split("Couldn't publish: no. Next: share status").sentence, "Couldn't publish: no.") + XCTAssertNil(FailureLine.split("Couldn't publish: no.").next) + } +} diff --git a/mac/Tests/fixtures/ax/axdrive.swift b/mac/Tests/fixtures/ax/axdrive.swift index a014582..45a7b95 100644 --- a/mac/Tests/fixtures/ax/axdrive.swift +++ b/mac/Tests/fixtures/ax/axdrive.swift @@ -160,7 +160,7 @@ case "find", "click": // A panel's button can drop a click that lands while the app is not yet active (an // NSAlert on another display). If the button is still there after the click, press // it through its own Accessibility action: still the control's own handler, no state set. - if text(element, kAXRoleAttribute) == kAXButtonRole as String { + if ProcessInfo.processInfo.environment["AXDRIVE_NO_PRESS"] == nil, text(element, kAXRoleAttribute) == kAXButtonRole as String { Thread.sleep(forTimeInterval: 0.5) if frame(element) != nil { AXUIElementPerformAction(element, kAXPressAction as CFString) } } @@ -183,6 +183,13 @@ case "key": guard args.count >= 3 else { fail("usage: axdrive key [cmd] [opt] [ctrl] [shift]", code: 2) } guard AXIsProcessTrusted() else { fail("Accessibility is not granted to this terminal", code: 4) } if !press(args[2], modifiers: Array(args.dropFirst(3))) { fail("unknown key: \(args[2])", code: 2) } +case "type": + guard args.count >= 3 else { fail("usage: axdrive type ", code: 2) } + guard AXIsProcessTrusted() else { fail("Accessibility is not granted to this terminal", code: 4) } + for character in args[2...].joined(separator: " ") { + let name = character == " " ? "space" : String(character).lowercased() + if !press(name, modifiers: []) { fail("cannot type: \(character)", code: 2) } + } case "window": guard args.count >= 3, let pid = Int32(args[2]) else { fail("usage: axdrive window ", code: 2) } guard let id = frontWindow(pid) else { fail("no on-screen window for pid \(pid)", code: 3) } diff --git a/mac/shots.sh b/mac/shots.sh index dc6ba5a..b560307 100755 --- a/mac/shots.sh +++ b/mac/shots.sh @@ -15,6 +15,8 @@ # scenario default scenario for `shots.sh all` # click real click; is `status-item` or a title/description # find fail unless the control exists +# click-once a click with no follow-up AXPress, for a toggling button +# type real key presses for the text (letters, digits, space) # key [cmd|opt|ctrl|shift]... # wait # shot