diff --git a/README.md b/README.md index d2b7190..c734d50 100644 --- a/README.md +++ b/README.md @@ -72,10 +72,10 @@ It comes in two styles, chosen in **Settings… → Menu Bar**: Click the date and time to open Notification Center, choose **Edit Widgets**, and add **Agent Watch**. The small widget opens **Projects & Recent**. The medium widget also has shortcuts to -**Waiting for you** in that window and to **Settings**. Both widgets work when the menu bar icon is hidden. +the **Waiting for you** filter in **Recent** and to **Settings**. Both widgets work when the menu bar icon is hidden. An optional orange beacon appears when a chat is waiting for your reply. Choose **Full screen only** or **All modes** to show it on windowed desktops too. -Click the ring to open **Projects & Recent** on **Waiting for you**, then choose a chat. +Click the ring to open **Recent** with the **Waiting for you** filter selected, then choose a chat. Right-click the ring to open **Waiting Beacon Settings…**. You can also open **Settings → Waiting Beacon** to turn it on, resize it, or choose its position. @@ -223,8 +223,9 @@ Open **Projects & Recent…** from the menu bar to find an observed Claude or Co Opening Agent Watch again from Finder or Spotlight opens the same window, even with the menu bar icon hidden. Linked Git working folders appear under the same project. Filter by activity, search by branch or -chat name, and open the matching conversation. Recent shows up to 20 chats. **Usage profiles** -shows the last observed limits and their time for the default Claude profile and configured Codex folders. +chat name, and open the matching conversation. **Waiting for you** lists all chats waiting for a +reply. The other **Recent** filters show up to 20 chats. **Usage profiles** shows the last observed +limits and their time for the default Claude profile and configured Codex folders. In **Settings… → Git Protection**, check the hook status beside each Claude Code or Codex profile. Click **Install…** to connect a profile or **Repair…** to fix an outdated hook. diff --git a/Sources/AgentWatchApp/AppDelegate.swift b/Sources/AgentWatchApp/AppDelegate.swift index 0a99415..d61a952 100644 --- a/Sources/AgentWatchApp/AppDelegate.swift +++ b/Sources/AgentWatchApp/AppDelegate.swift @@ -773,14 +773,14 @@ extension AppDelegate: StatusMenuHost, SettingsHost { private func navigate(to destination: WatchDestination, on screen: NSScreen? = nil) { switch destination { case .projects: showProjects() - case .waiting: presentProjects(.waiting, on: screen) + case .waiting: presentProjects(filter: .waiting, on: screen) case .settings: showWidgetSettings() } } - func showProjects() { presentProjects(.recent) } + func showProjects() { presentProjects(filter: .all) } - private func presentProjects(_ scope: ProjectBrowserScope, on screen: NSScreen? = nil) { + private func presentProjects(filter: ProjectBrowserFilter, on screen: NSScreen? = nil) { if projectsWindow == nil { projectsWindow = ProjectBrowserWindow( waitingChats: waitingChats, @@ -790,7 +790,7 @@ extension AppDelegate: StatusMenuHost, SettingsHost { updateProjects(supervisor.sessions, refresh: true) } } - projectsWindow?.present(scope, on: screen) + projectsWindow?.presentRecent(filter: filter, on: screen) } private func updateProjects(_ sessions: [SessionSnapshot], refresh: Bool = false) { diff --git a/Sources/AgentWatchApp/ProjectBrowser.swift b/Sources/AgentWatchApp/ProjectBrowser.swift index 8b57209..1e2169c 100644 --- a/Sources/AgentWatchApp/ProjectBrowser.swift +++ b/Sources/AgentWatchApp/ProjectBrowser.swift @@ -7,6 +7,14 @@ struct ProjectBrowserEntry: Identifiable, Equatable, Sendable { var session: SessionSnapshot let copy: GitWorkingCopy? var id: String { session.id } + + func matchesSearch(_ needle: String) -> Bool { + let fields = [ + session.title, session.projectName, session.gitBranch, session.source.rawValue, copy?.root.path, + copy?.projectURL.path, + ] + return fields.compactMap { $0 }.contains { $0.localizedCaseInsensitiveContains(needle) } + } } enum ProjectBrowserFilter: String, CaseIterable { @@ -27,7 +35,7 @@ enum ProjectBrowserFilter: String, CaseIterable { } enum ProjectBrowserScope: Hashable { - case recent, waiting, project(URL), unknown, profiles + case recent, project(URL), unknown, profiles } enum WatchDestination: String, CaseIterable { @@ -56,12 +64,7 @@ enum ProjectBrowserCatalog { case .unknown where entry.copy != nil: return false default: break } - let fields = [ - row.title, row.projectName, row.gitBranch, row.source.rawValue, entry.copy?.root.path, - entry.copy?.projectURL.path, - ] - return filter.includes(row, now: now) - && (needle.isEmpty || fields.compactMap { $0 }.contains { $0.localizedCaseInsensitiveContains(needle) }) + return filter.includes(row, now: now) && (needle.isEmpty || entry.matchesSearch(needle)) }.sorted { left, right in let lhs = left.session let rhs = right.session @@ -79,9 +82,11 @@ final class ProjectBrowserModel: ObservableObject { @Published var filter = ProjectBrowserFilter.all @Published var search = "" - func navigate(to scope: ProjectBrowserScope) { - self.scope = scope - filter = .all + var showsWaitingChats: Bool { (scope ?? .recent) == .recent && filter == .waiting } + + func showRecent(filter: ProjectBrowserFilter) { + scope = .recent + self.filter = filter search = "" message = nil } @@ -229,11 +234,11 @@ final class ProjectBrowserWindow: NSWindowController, NSWindowDelegate { @available(*, unavailable) required init?(coder: NSCoder) { nil } - func present(_ scope: ProjectBrowserScope, on preferredScreen: NSScreen?) { + func presentRecent(filter: ProjectBrowserFilter, on preferredScreen: NSScreen?) { guard let window else { return } - model.navigate(to: scope) + model.showRecent(filter: filter) let wasKey = window.isKeyWindow - let showsWaiting = scope == .waiting + let showsWaiting = filter == .waiting let targetScreen = showsWaiting ? preferredScreen ?? NSScreen.screens.first { $0.frame.contains(NSEvent.mouseLocation) } @@ -283,8 +288,6 @@ private struct ProjectBrowserView: View { NavigationSplitView { List(selection: $model.scope) { Label("Recent", systemImage: "clock").tag(ProjectBrowserScope.recent) - Label("Waiting for you", systemImage: "bubble.left.and.exclamationmark.bubble.right") - .tag(ProjectBrowserScope.waiting) Label("Usage profiles", systemImage: "chart.bar").tag(ProjectBrowserScope.profiles) Section("Projects") { ForEach(projects, id: \.commonDirectory) { copy in @@ -302,9 +305,7 @@ private struct ProjectBrowserView: View { } .navigationSplitViewColumnWidth(min: 150, ideal: 205) } detail: { - if model.scope == .waiting { - WaitingChatsView(model: waitingChats) - } else if model.scope == .profiles, let folders = model.folders { + if model.scope == .profiles, let folders = model.folders { UsageProfilesView( folders: folders, defaultClaudeUsage: model.claudeUsage, sessions: model.profileSessions, readsTranscripts: model.readsTranscripts) @@ -327,21 +328,30 @@ private struct ProjectBrowserView: View { Picker("Filter", selection: $model.filter) { ForEach(ProjectBrowserFilter.allCases, id: \.self) { Text($0.rawValue).tag($0) } }.pickerStyle(.segmented) - if model.entries.contains(where: { $0.session.phase.claimsWork }) { - TimelineView(.periodic(from: .now, by: 15)) { context in - chatList(now: context.date) - } + if model.showsWaitingChats { + WaitingChatsView(model: waitingChats, search: model.search, projectEntries: model.entries) } else { - chatList(now: .now) + desktopChats } - if let message = model.message { Text(message).foregroundStyle(.secondary) } - Text( - "Observed desktop chats with a verified link. Recent shows up to \(ProjectBrowserCatalog.recentLimit). Closed chats are excluded." - ) - .font(.caption).foregroundStyle(.secondary) }.padding() } + @ViewBuilder + private var desktopChats: some View { + if model.entries.contains(where: { $0.session.phase.claimsWork }) { + TimelineView(.periodic(from: .now, by: 15)) { context in + chatList(now: context.date) + } + } else { + chatList(now: .now) + } + if let message = model.message { Text(message).foregroundStyle(.secondary) } + Text( + "Observed desktop chats with a verified link. Recent shows up to \(ProjectBrowserCatalog.recentLimit). Closed chats are excluded." + ) + .font(.caption).foregroundStyle(.secondary) + } + @ViewBuilder private func chatList(now: Date) -> some View { let rows = ProjectBrowserCatalog.visible( diff --git a/Sources/AgentWatchApp/WaitingChats.swift b/Sources/AgentWatchApp/WaitingChats.swift index cd281a0..40245c2 100644 --- a/Sources/AgentWatchApp/WaitingChats.swift +++ b/Sources/AgentWatchApp/WaitingChats.swift @@ -13,8 +13,8 @@ final class WaitingChatsModel: ObservableObject { id = session.id title = session.title ?? session.projectName ?? "Chat \(session.id.suffix(8))" let agent = session.source == .codex ? "Codex" : "Claude" - detail = [agent, session.projectName == title ? nil : session.projectName].compactMap { $0 }.joined( - separator: " · ") + detail = [agent, session.projectName == title ? nil : session.projectName, session.gitBranch] + .compactMap { $0 }.joined(separator: " · ") canResetBeacon = session.source == .codex && session.pendingCodexQuestions?.isEmpty == false } } @@ -39,6 +39,16 @@ final class WaitingChatsModel: ObservableObject { if let unavailableID, !waiting.contains(where: { $0.id == unavailableID }) { self.unavailableID = nil } } + func visibleRows(search: String, projectEntries: [ProjectBrowserEntry]) -> [Row] { + let needle = search.trimmingCharacters(in: .whitespacesAndNewlines) + guard !needle.isEmpty else { return rows } + let projectMatches = Set(projectEntries.lazy.filter { $0.matchesSearch(needle) }.map(\.id)) + return rows.filter { row in + projectMatches.contains(row.id) || row.title.localizedCaseInsensitiveContains(needle) + || row.detail.localizedCaseInsensitiveContains(needle) + } + } + func open(_ id: String) { guard rows.contains(where: { $0.id == id }) else { return } unavailableID = focus(id) == .raised ? nil : id @@ -52,14 +62,17 @@ final class WaitingChatsModel: ObservableObject { struct WaitingChatsView: View { @ObservedObject var model: WaitingChatsModel + let search: String + let projectEntries: [ProjectBrowserEntry] var body: some View { - if model.rows.isEmpty { - Text("All caught up. No chats are waiting for a reply.") + let rows = model.visibleRows(search: search, projectEntries: projectEntries) + if rows.isEmpty { + Text(model.rows.isEmpty ? "All caught up. No chats are waiting for a reply." : "No matching chats") .foregroundStyle(.secondary).padding() .frame(maxWidth: .infinity, maxHeight: .infinity) } else { - List(model.rows) { row in + List(rows) { row in Button { model.open(row.id) } label: { diff --git a/Tests/AgentWatchAppTests/ProjectBrowserTests.swift b/Tests/AgentWatchAppTests/ProjectBrowserTests.swift index 22b8b0b..7c80eb9 100644 --- a/Tests/AgentWatchAppTests/ProjectBrowserTests.swift +++ b/Tests/AgentWatchAppTests/ProjectBrowserTests.swift @@ -27,21 +27,27 @@ final class ProjectBrowserTests: XCTestCase { } @MainActor - func testNavigatingStartsTheChosenScopeWithoutAnOldSearchOrFilter() { + func testOpeningRecentSelectsTheRequestedFilterAndClearsThePreviousSearch() { let model = ProjectBrowserModel() defer { model.stop() } model.scope = .profiles model.search = "an old search" model.filter = .quiet model.message = "An old opening error" - model.navigate(to: .waiting) - XCTAssertEqual(model.scope, .waiting) + model.showRecent(filter: .waiting) + XCTAssertEqual(model.scope, .recent) + XCTAssertEqual(model.filter, .waiting) + XCTAssertTrue(model.showsWaitingChats) XCTAssertTrue(model.search.isEmpty) - XCTAssertEqual(model.filter, .all) XCTAssertNil(model.message) - model.navigate(to: .recent) + model.scope = .unknown + XCTAssertFalse(model.showsWaitingChats) + + model.showRecent(filter: .all) XCTAssertEqual(model.scope, .recent) + XCTAssertEqual(model.filter, .all) + XCTAssertFalse(model.showsWaitingChats) } /// A new chat appearing while a click is being resolved rereads the list; the click still diff --git a/Tests/AgentWatchAppTests/WaitingChatsTests.swift b/Tests/AgentWatchAppTests/WaitingChatsTests.swift index 132184b..1049911 100644 --- a/Tests/AgentWatchAppTests/WaitingChatsTests.swift +++ b/Tests/AgentWatchAppTests/WaitingChatsTests.swift @@ -4,6 +4,7 @@ import XCTest @testable import AgentWatchApp @testable import AgentWatchCore +@testable import AgentWatchLookup @MainActor final class WaitingChatsTests: XCTestCase { @@ -34,6 +35,25 @@ final class WaitingChatsTests: XCTestCase { XCTAssertTrue(model.rows.isEmpty) } + func testSearchCanFindTerminalChatsAndKnownProjectFoldersWithoutCappingTheWaitingList() { + let now = Date(timeIntervalSince1970: 100) + var terminalChats = (1...25).map { + testSession(index: $0, phase: .waitingForUser, clientKind: .cli, lastObservedAt: now) + } + terminalChats[24].gitBranch = "Beacon-Fix" + let desktop = testSession(source: .codex, phase: .waitingForUser, clientKind: .desktop, lastObservedAt: now) + let root = URL(fileURLWithPath: "/workspace/shared-project") + let project = GitWorkingCopy(commonDirectory: root.appendingPathComponent(".git"), root: root) + let entries = [ProjectBrowserEntry(session: desktop, copy: project)] + let model = WaitingChatsModel(focus: { _ in .raised }, resetBeacon: { _ in }) + model.update(terminalChats + [desktop]) + + XCTAssertEqual(model.visibleRows(search: "", projectEntries: entries).count, 26) + XCTAssertEqual( + model.visibleRows(search: " beacon-fix ", projectEntries: entries).map(\.id), [terminalChats[24].id]) + XCTAssertEqual(model.visibleRows(search: "shared-project", projectEntries: entries).map(\.id), [desktop.id]) + } + func testCodexCanKeepWorkingWhileItsQuestionIsInTheList() { var session = testSession(source: .codex, phase: .executing, lastObservedAt: .now) session.pendingCodexQuestions = ["question-1": .now] diff --git a/docs/menu-bar.md b/docs/menu-bar.md index c5b443b..cb93d68 100644 --- a/docs/menu-bar.md +++ b/docs/menu-bar.md @@ -80,9 +80,9 @@ `Full screen only` для полноэкранных рабочих столов или `All modes` для всех подключённых экранов, включая рабочие столы с обычными окнами. Под строкой меню появляется оранжевое кольцо с числом чатов, которые ждут ответа. Щелчок выводит окно -`Projects & Recent` на передний план и выбирает раздел `Waiting for you`. Выберите чат, чтобы -вернуться к вопросу. Если открыть чат не удалось, строка предлагает открыть его в приложении -или повторить попытку. +`Projects & Recent` на передний план и включает фильтр `Waiting for you` в разделе `Recent`. +Выберите чат, чтобы вернуться к вопросу. Если открыть чат не удалось, строка предлагает открыть +его в приложении или повторить попытку. Чтобы убрать сигнал об уже показанных асинхронных вопросах Codex, нажмите правой кнопкой на чат в списке и выберите `Reset Beacon`. Обычное текстовое сообщение в том же чате тоже сбрасывает @@ -122,15 +122,15 @@ ### Проекты и недавние чаты Пункт `Projects & Recent…` открывает окно с наблюдаемыми чатами настольных Claude и Codex. -Раздел `Waiting for you` показывает те же ожидающие чаты, которые считает маячок, включая -сессии в терминале. То же окно открывается, когда уже запущенный Agent Watch открывают снова из Finder или Spotlight: так до него можно добраться и со скрытым значком в строке меню. -В разделе `Recent` видно до 20 чатов. Сначала идут текущие, затем чаты с завершённым ходом, -внутри каждой группы — по времени последнего наблюдения. Фильтры и поиск по имени, агенту, -ветке или папке применяются до ограничения. Поиск по выбранному проекту охватывает все его строки. +В разделе `Recent` фильтр `Waiting for you` показывает все ожидающие чаты, которые считает +маячок, включая сессии в терминале. С остальными фильтрами видно до 20 чатов: сначала текущие, +затем чаты с завершённым ходом, внутри каждой группы — по времени последнего наблюдения. +Фильтры и поиск по имени, агенту, ветке или известной папке применяются до ограничения. +Поиск по выбранному проекту охватывает все его строки. Фильтр `No recent activity` выбирает работающие сессии, от которых минуту не поступало сведений. -Строка показывает последнее известное состояние, время наблюдения и вид выполняемой работы, если он известен. +В обычном списке недавних чатов строка показывает последнее известное состояние, время наблюдения и вид выполняемой работы, если он известен. Git сообщает корень рабочей копии и общий служебный каталог репозитория. Внешняя рабочая копия поэтому видна в том же проекте, а два разных репозитория с одинаковым именем — в разных. @@ -141,12 +141,12 @@ Git сообщает корень рабочей копии и общий слу Если папка неизвестна или принадлежность репозиторию не подтверждается, чат попадает в `Unknown project`. -Щелчок открывает чат по [ссылке настольного клиента](session-focus.md#десктопные-клиенты). -Ссылка проверяется при чтении списка и ещё раз при выборе. Для Claude нужна текущая запись -процесса, для Codex — файл чата в действующем каталоге сессий. Архивную папку окно не читает. -Закрытая сессия и сессия без подтверждённой ссылки пропускаются. После перезапуска окно смотрит -на сессии, восстановленные обычным наблюдением. Кнопка `Refresh` заново проверяет список -и папки открытых сессий. +В списке проектов и обычных недавних чатов щелчок открывает +[ссылку настольного клиента](session-focus.md#десктопные-клиенты). Ссылка проверяется при чтении +списка и ещё раз при выборе. Для Claude нужна текущая запись процесса, для Codex — файл чата +в действующем каталоге сессий. Этот список пропускает закрытые чаты и чаты без подтверждённой +ссылки. После перезапуска окно показывает сессии, восстановленные обычным наблюдением. +Кнопка `Refresh` заново проверяет список и папки открытых сессий. ### Лимиты по папкам агента diff --git a/docs/settings.md b/docs/settings.md index 9fa99ce..8bc5c26 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -151,8 +151,8 @@ Нажатие на дату и время открывает Центр уведомлений macOS. Через «Изменить виджеты» можно добавить Agent Watch. Малый виджет открывает проекты и недавние чаты. В среднем есть также -кнопка `Waiting for you`, которая, как и маячок, выбирает раздел ожидающих чатов в окне -`Projects & Recent`, и переход к настройкам. +кнопка `Waiting for you`, которая, как и маячок, включает этот фильтр в разделе `Recent` +окна `Projects & Recent`, и переход к настройкам. Как это вообще работает, когда приложение никогда не активно, и почему выбран Carbon — [ADR-0009](adr/0009-the-global-shortcut-goes-through-carbon.md).