EPOD Window Bar: a window strip above the macOS Dock

EPOD Window Bar is a macOS agent app. It shows a thin strip above the Dock
with one tab per window of the frontmost application. One click raises the
window.

Build from source with XcodeGen and Xcode. Signing uses Config.xcconfig
(ad-hoc by default; a local Local.xcconfig can set a team ID). The app needs
Accessibility and Screen Recording permissions, and runs in a reduced mode
without Screen Recording.

See README.md and docs/ for details.
This commit is contained in:
Erhan Keseli
2026-11-21 21:41:06 +01:00
commit 70d7ca5efe
43 changed files with 4332 additions and 0 deletions

449
docs/spec.md Normal file
View File

@@ -0,0 +1,449 @@
# EPOD Window Bar — Specification
> Product name: **EPOD Window Bar**. Xcode target and module name: `EPODWindowBar`. Bundle display name: `EPOD Window Bar`.
This document describes the design. The document matches the current code. The
window filter rules, the signing setup, the threading, and the logging reflect
the implementation.
---
## 1. Problem
macOS shows applications in the Dock. It does not show windows.
When one application has many windows (for example, a terminal with many
windows, or a browser with many windows), it is slow to find the correct window.
`Cmd + \`` and Mission Control are too slow for 100+ switches each day.
## 2. Goal
Make a thin, always-visible strip directly above the Dock.
The strip shows all windows of the **frontmost application** as tabs.
One click on a tab brings that window to the front.
```
[ Document 1 ][ Terminal — zsh ][ Project – main.swift ][ Downloads ][ +3 ]
──────────────────────────── Dock ────────────────────────────
```
The Dock does not change. EPOD Window Bar adds to the Dock. It does not replace it.
## 3. Design decisions (fixed — do not change without approval)
| # | Decision | Reason |
|---|----------|--------|
| D1 | The strip is always visible. No hover-to-show. | Hover delay costs time 100+ times each day. |
| D2 | The strip is horizontal, directly above the Dock, full screen width. | The owner chose this layout. Side panels were rejected. |
| D3 | The strip shows the windows of the frontmost application only. | The Dock already shows applications. |
| D4 | The strip shows windows from **all** Spaces (desktops). | Windows on other desktops are also lost windows. |
| D5 | Tabs keep a **stable order** (order of first detection). Do not sort by z-order. | Tabs must not jump when focus changes. Muscle memory. |
| D6 | EPOD Window Bar prevents windows from covering the strip (Accessibility resize). | macOS reserves space for the Dock only. |
| D7 | The strip is hidden when the frontmost window is full screen. | The Dock is also hidden in full screen. |
| D8 | Height: 30 pt. | Thin, but tab titles stay readable. |
## 4. Scope
### 4.1 In scope (v1)
- Strip panel above the Dock on the Dock's screen.
- Tabs for all windows of the frontmost application, on all Spaces.
- Tab states: active, inactive, minimized, on other Space.
- Left click: activate window (also on other Space, also when minimized).
- Right click: context menu with **Minimize** and **Close**.
- Overflow: tabs shrink to a minimum width. Then a `+N` button opens a menu with the remaining windows.
- Window constraint: windows cannot extend below the strip top.
- Full-screen detection: hide the strip.
- Menu bar item with settings.
- Launch at login.
- Excluded applications list (no constraint for these applications).
- Debug: "Dump windows to log" and "Copy window dump" menu items.
### 4.2 Out of scope (v1) — do not implement
- Pinning applications.
- Side panel, hover panel, search popup.
- Window thumbnails / previews.
- One strip per monitor. (v1: Dock screen only.)
- Native tabs inside one window (Finder, Terminal, Safari, a browser).
- Stage Manager support. (When Stage Manager is on, show the strip but do not constrain windows.)
- App Store distribution.
## 5. Platform and tooling
- macOS 14 (Sonoma) and later.
- Swift 5 language mode. The project sets `SWIFT_VERSION = 5.0`.
- AppKit for the panel and window logic. SwiftUI is allowed inside `NSHostingView` for the tab bar and the settings window.
- **No App Sandbox.** Accessibility APIs do not work in the sandbox.
- Agent application: `LSUIElement = YES` (no Dock icon, no main menu).
- Project generation: **XcodeGen** (`project.yml`). Build from the command line with `xcodebuild`. Do not commit the `.xcodeproj`.
- No third-party dependencies in v1.
## 6. Permissions and code signing
### 6.1 Permissions
| Permission | Why | API |
|------------|-----|-----|
| Accessibility | Read windows, raise, minimize, close, resize. | `AXIsProcessTrustedWithOptions` |
| Screen Recording | Read window titles of windows on other Spaces through `CGWindowListCopyWindowInfo` (`kCGWindowName` is empty without it). | `CGPreflightScreenCaptureAccess`, `CGRequestScreenCaptureAccess` |
- At start, check both permissions.
- If a permission is missing, show a small onboarding window. The window explains each permission in one sentence and has a button that opens the correct System Settings pane.
- Poll the permission state every 2 s. Continue automatically when access is granted.
- The application must work in a reduced mode without Screen Recording: show only windows that AX can find (current Space). Show a warning icon in the menu bar item.
- If Accessibility is revoked at runtime, stop all AX work and show the onboarding window again. Do not crash.
### 6.2 Code signing
macOS stores the permissions per code signature. An ad-hoc signature changes each build, so macOS resets the permissions after each build.
- The committed file `Config.xcconfig` sets ad-hoc signing by default. The default build needs no Apple account. The file ends with `#include? "Local.xcconfig"`.
- To keep the permissions between builds, sign with a stable **Apple Development** certificate. Copy `Local.xcconfig.example` to `Local.xcconfig`. Set `DEVELOPMENT_TEAM` in `Local.xcconfig`.
- Find the team ID in the `OU` field of the Apple Development certificate. The value in parentheses in the `CN` field is the personal ID, not the team ID.
- `Local.xcconfig` is in `.gitignore`. The team ID stays on the local machine. `project.yml` holds no team ID.
- Use a fixed bundle ID: `com.epod.windowbar`.
- Build output: copy the `.app` to `~/Applications/EPOD Window Bar.app` with a script. Always run from this path.
- `scripts/run.sh`: generate, build, kill the running instance, copy, start.
- `scripts/reset-permissions.sh`: `tccutil reset Accessibility com.epod.windowbar` and `tccutil reset ScreenCapture com.epod.windowbar`.
## 7. Architecture
### 7.1 Modules
```
epod-window-bar/ // repository root
├── project.yml
├── Config.xcconfig // ad-hoc default, includes Local.xcconfig
├── Local.xcconfig.example // team ID placeholder
├── .github/workflows/ci.yml
├── docs/
│ ├── spec.md
│ └── architecture.md
├── scripts/
│ ├── run.sh
│ └── reset-permissions.sh
├── Sources/
│ ├── App/
│ │ ├── main.swift
│ │ ├── AppDelegate.swift // wires every module; implements AppControl
│ │ ├── AppControl.swift // interface for the menu and the settings
│ │ ├── MenuBarController.swift
│ │ └── LaunchAtLogin.swift // SMAppService.mainApp
│ ├── Permissions/
│ │ ├── PermissionManager.swift
│ │ └── OnboardingWindow.swift
│ ├── Model/
│ │ ├── WindowInfo.swift
│ │ └── WindowStore.swift // WindowStore and AXElementCache
│ ├── Tracking/
│ │ ├── AppObserverRegistry.swift
│ │ ├── WindowEnumerator.swift
│ │ ├── WorkspaceEvents.swift
│ │ └── TrackingController.swift
│ ├── Private/
│ │ ├── PrivateAPI.swift // ALL private symbols, loaded with dlsym
│ │ └── SpaceService.swift
│ ├── Actions/
│ │ └── WindowActivator.swift
│ ├── Constraint/
│ │ ├── ConstraintMath.swift // pure math, unit-tested
│ │ └── WindowConstraintService.swift
│ ├── Strip/
│ │ ├── StripPanel.swift
│ │ ├── StripPositioner.swift
│ │ ├── TabBarView.swift
│ │ ├── TabLayout.swift // pure layout math, unit-tested
│ │ └── StripController.swift
│ ├── Settings/
│ │ ├── Settings.swift
│ │ └── SettingsWindow.swift
│ └── Util/
│ ├── Geometry.swift // coordinate conversion, unit-tested
│ └── Log.swift
└── Tests/
├── TabLayoutTests.swift
├── GeometryTests.swift
├── ConstraintMathTests.swift
├── WindowOrderTests.swift
└── WindowFilterTests.swift
```
### 7.2 Data model
```swift
struct WindowInfo: Identifiable, Equatable {
let id: CGWindowID // primary key
let pid: pid_t
let bundleID: String?
var title: String // fallback: application name
var spaceIDs: [UInt64] // from SpaceService; empty if unknown
var isOnCurrentSpace: Bool
var isMinimized: Bool
var isFullScreen: Bool
var firstSeen: Date // used for stable order (D5)
}
```
- `WindowStore` holds `[pid_t: [WindowInfo]]` and the frontmost `pid`.
- `WindowStore` is `@MainActor` and publishes changes with `@Observable`.
- `AXElementCache` holds the AX element for each window: `[CGWindowID: AXUIElement]`. The cache is separate. The value type does not hold `AXUIElement`.
- Stable order: sort by `firstSeen`. When a window closes and opens again, it gets a new `firstSeen`.
### 7.3 Window enumeration
Use two sources and merge them by `CGWindowID`.
1. **AX source** (current Space and minimized windows):
- `AXUIElementCreateApplication(pid)` → `kAXWindowsAttribute`.
- Map each AX window to `CGWindowID` with the private `_AXUIElementGetWindow`.
- Read `kAXTitleAttribute`, `kAXMinimizedAttribute`, `kAXSubroleAttribute`, `"AXFullScreen"`.
2. **CGWindowList source** (all Spaces):
- `CGWindowListCopyWindowInfo([.optionAll, .excludeDesktopElements], kCGNullWindowID)`.
- Filter: `kCGWindowOwnerPID == pid`, `kCGWindowLayer == 0`.
- Title from `kCGWindowName` (needs Screen Recording).
3. **Space source**: `SpaceService.spaces(for: [CGWindowID])` (private, see 7.5).
Filter rules (a window is shown only if all rules are true). The code is in
`Sources/Tracking/WindowEnumerator.swift`:
- The window is not owned by EPOD Window Bar.
- The CG layer is 0.
- The window is not entirely off all screens, **or** the window is minimized. The off-screen rule hides a placeholder shell such as the Eclipse "limbo" shell at `y = 10000`. A minimized window keeps its tab.
- If the window has an AX element: the AX subrole is `kAXStandardWindowSubrole`.
- If the window has no AX element (a window on another Space): the title must not equal the application name, and the CG bounds are at least 50 × 50. A ghost placeholder has the application name as the title (an empty real title, or `kCGWindowName` set to the application name), so the filter hides it.
> **Note on the Space data.** The per-window Space query (`CGSCopySpacesForWindows`) can return an empty result for a real window on another Space. So the filter does **not** use the Space data to decide visibility. The filter uses the title and the position. The Space data only sets the "on other Space" tab state.
### 7.4 Live updates
- `NSWorkspace` notifications: `didActivateApplication`, `didLaunchApplication`, `didTerminateApplication`, `activeSpaceDidChangeNotification`.
- `NSApplication.didChangeScreenParametersNotification` → reposition the strip.
- One `AXObserver` per running regular application (`activationPolicy == .regular`). Notifications:
- `kAXWindowCreatedNotification`
- `kAXUIElementDestroyedNotification` (register on each window)
- `kAXTitleChangedNotification` (register on each window — some applications change titles often)
- `kAXFocusedWindowChangedNotification`, `kAXMainWindowChangedNotification`
- `kAXWindowMiniaturizedNotification`, `kAXWindowDeminiaturizedNotification`
- `kAXWindowMovedNotification`, `kAXWindowResizedNotification` (for the constraint service)
- Coalesce updates: max one store refresh each 50 ms per application.
- Fallback reconcile: a full refresh of the frontmost application each 2 s. Some applications (Java, Electron) do not send all notifications.
- Remove observers when an application terminates.
- Do all AX calls off the main thread on one serial queue. Set `AXUIElementSetMessagingTimeout` to 0.25 s. A frozen application must not freeze the strip. `PrivateAPI` is nonisolated, so the serial queue can call the private AX wrappers.
### 7.5 Private APIs
Put all private symbols in `Private/PrivateAPI.swift`. Load each symbol with `dlsym` at runtime. If a symbol is missing, log it and disable the feature. **Never crash because of a missing private symbol.**
Mark each use with the comment `// PRIVATE API`.
| Symbol | Use | Fallback if missing |
|--------|-----|---------------------|
| `_AXUIElementGetWindow` | AX element → `CGWindowID` | Match by PID + frame + title |
| `CGSMainConnectionID` | Connection for CGS calls | Disable Space features |
| `CGSCopyManagedDisplaySpaces` | List of Spaces per display, current Space | Treat all windows as current Space |
| `CGSCopySpacesForWindows` | Spaces of a window | Same as above |
| `_AXUIElementCreateWithRemoteToken` | AX element for windows on other Spaces | Activate the application only (see 7.6) |
> The signatures of these functions are not documented. The code uses the signatures from open-source projects (AltTab, yabai, Hammerspoon). The remote-token layout is the most uncertain part. The code marks it UNCERTAIN.
### 7.6 Window activation
`WindowActivator.activate(windowID:)`:
1. If minimized: set `kAXMinimizedAttribute` to `false`.
2. If on current Space: `AXUIElementPerformAction(window, kAXRaiseAction)`, then `NSRunningApplication.activate()`. Then set `kAXMainAttribute` to `true`.
3. If on other Space:
- **Method A (default):** get the AX element (remote token method), raise it, activate the application. macOS switches to the Space if the system setting *"When switching to an application, switch to a Space with open windows for the application"* is on.
- **Method B (fallback):** if no AX element is available, activate the application only, and log a warning.
- Do not use `CGSManagedDisplaySetCurrentSpace` in v1. It is known to cause an inconsistent state.
4. Check after 300 ms if the target window is the focused window. If not, log it with the debug details.
Context menu actions:
- **Minimize:** set `kAXMinimizedAttribute` to `true`.
- **Close:** get `kAXCloseButtonAttribute`, then `kAXPressAction`. (The application can show a "save changes?" dialog. This is correct behavior.)
### 7.7 Strip panel
- `NSPanel` with `styleMask: [.borderless, .nonactivatingPanel]`.
- `becomesKeyOnlyIfNeeded = true`, `canBecomeKey = false`, `canBecomeMain = false`. A click on the strip must not take focus from the frontmost application.
- `collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle]`.
- `level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.dockWindow)) - 1)`. The strip is above normal windows but **below** the Dock, so Dock magnification can cover the strip.
- `hasShadow = false`, background: `NSVisualEffectView` with material `.hudWindow`.
- `hidesOnDeactivate = false`.
### 7.8 Strip position
`StripPositioner` calculates the frame:
- Find the Dock screen: the screen where `visibleFrame.minY > frame.minY` (Dock at bottom). If the Dock is hidden (auto-hide) or on the left/right side, use the main screen.
- Frame: `x = screen.visibleFrame.minX`, `y = screen.visibleFrame.minY`, `width = screen.visibleFrame.width`, `height` = the setting value.
- Dock auto-hide: the strip is at the bottom of the screen. The Dock covers it when the Dock appears. This is accepted.
- Recalculate on: screen parameter change, a 2 s poll of `NSScreen.main.visibleFrame` (there is no public Dock-preference notification), wake from sleep.
### 7.9 Tab bar
Layout (`TabLayout`, pure function, unit-tested):
- Input: available width, window count, active index, max tab width 220 pt, min tab width 90 pt, spacing 3 pt, `+N` button width 36 pt, application icon area 26 pt.
- Output: visible tabs with widths, and overflow windows.
- Rule: all tabs have equal width. If `count × minWidth` does not fit, show as many tabs as fit, plus `+N`.
- The active window must always be visible. If the active window is in the overflow, swap it with the last visible tab.
Tab content:
- Left of all tabs: the icon of the frontmost application (16 pt).
- Tab: title, one line, truncated with `…` in the **middle** (`.truncationMode(.middle)`). Some titles have the important part at the end.
- Tooltip: full title.
Tab states:
| State | Look |
|-------|------|
| Active (focused window) | Accent background tint, accent text |
| Normal | Secondary text, no background |
| Hover | Light background tint |
| Minimized | Text in italic, 60 % contrast |
| On other Space | Small "desktop" icon before the title, muted text |
- `+N` button: opens a menu with the overflow windows.
- Empty state (frontmost application has no windows): show only the application icon and the application name in muted text.
- Support light and dark mode. Use system colors only.
### 7.10 Window constraint service
Goal: no window extends below the top edge of the strip.
- Limit line (Cocoa coordinates): `limitY = stripFrame.maxY`.
- AX uses the top-left origin of the **primary** screen. Convert with `Geometry.swift`. The pure math is in `ConstraintMath.swift` and is unit-tested.
- On `kAXWindowMovedNotification` / `kAXWindowResizedNotification` and on window creation:
1. Skip if: setting is off, application is excluded, window is full screen, subrole is not standard, Stage Manager is on, `kAXSizeAttribute` is not settable (`AXUIElementIsAttributeSettable`).
2. Skip if the window is not on the strip screen.
3. If the window bottom is below `limitY`:
- If the window top is also below `limitY - 100`: the user moves the window down intentionally. Do nothing.
- Else: set new height so that the bottom is at `limitY`.
- Debounce: wait 150 ms after the last move/resize event of a window. Do not resize during a drag. (Check `NSEvent.pressedMouseButtons == 0` before resizing.)
- Loop protection: after own resize, ignore events for this window for 300 ms.
- If an application does not accept the new size, add it to a runtime blacklist for this session and log it.
### 7.11 Full-screen handling
- After each activation and Space change, read `"AXFullScreen"` of the focused window of the frontmost application.
- If true: `orderOut` the strip. Else: `orderFrontRegardless`.
### 7.12 Menu bar item
`NSStatusItem` with an SF Symbol (`rectangle.split.3x1`). Menu:
- Pause EPOD Window Bar (hides strip, stops constraint)
- ✓ Keep windows above strip
- Excluded apps… (opens settings window)
- ✓ Launch at login (`SMAppService.mainApp`)
- Dump windows to log
- Copy window dump
- Permissions status (text, with a warning icon if a permission is missing)
- Quit
### 7.13 Settings
`UserDefaults`, keys with prefix `ws.`:
| Key | Type | Default |
|-----|------|---------|
| `ws.paused` | Bool | false |
| `ws.constrainWindows` | Bool | true |
| `ws.excludedBundleIDs` | [String] | [] |
| `ws.stripHeight` | Double | 30 |
The settings window shows the excluded applications list with **Add** (choose from running applications) and **Remove**.
### 7.14 Logging and debugging
- `os.Logger`, subsystem `com.epod.windowbar`, categories: `app`, `tracking`, `private`, `activation`, `constraint`, `strip`.
- **Dump windows to log** writes for each running regular application: PID, bundle ID, and for each window: CGWindowID, title, AX subrole, layer, bounds, Space IDs, minimized, full screen, shown/filtered (with filter reason). The dump writes at **notice** level, so `log show` persists it. Every dump field is public (not redacted).
- **Copy window dump** puts the same dump text on the clipboard. The user reads the dump without a log tool.
- Read the log with: `log stream --predicate 'subsystem == "com.epod.windowbar"' --level debug` or `log show --last 5m --predicate 'subsystem == "com.epod.windowbar"' --info`.
### 7.15 Performance targets
- Idle CPU: < 1 % average.
- Memory: < 60 MB.
- Click on tab → window in front: < 150 ms on the current Space.
- No AX call on the main thread. All AX calls run on one serial queue.
## 8. Phases
The project was built in phases. Each phase has a manual test checklist. The
owner tests each phase on a real machine.
### Phase 0 — Skeleton
- XcodeGen project, agent app, menu bar item with Quit.
- `run.sh`, `reset-permissions.sh`, README with signing setup.
- PermissionManager + onboarding window.
**Test:** App starts from `~/Applications`. No Dock icon. Menu bar item is visible. Onboarding opens the correct settings panes. After a rebuild, permissions stay granted.
### Phase 1 — Strip panel
- Panel, positioner, static fake tabs.
**Test:** Strip is directly above the Dock. Change Dock size, Dock magnification, auto-hide, Dock position left/right, connect/disconnect a second monitor. Strip stays in the correct position. Click on the strip does not take focus from the frontmost application. Strip is visible on all Spaces.
### Phase 2 — Windows on current Space
- AX enumeration, `_AXUIElementGetWindow`, WindowStore, observers, stable order, tab bar with real data, title updates.
**Test:** Open 5 Finder windows. Switch applications: tabs change immediately. Open/close windows: tabs update. Change a document in an application: the tab title updates. Tab order does not change when focus changes.
### Phase 3 — Actions
- Activation (current Space, minimized), context menu, overflow `+N`, active tab always visible.
**Test:** Click on each tab activates the correct window. Minimized window is restored. Close/Minimize from the context menu work. Open 15 windows: `+N` appears and its menu works.
### Phase 4 — All Spaces
- CGWindowList `optionAll`, SpaceService, remote-token AX elements, other-Space tab state, activation across Spaces, debug dump.
**Test:** Windows on Desktop 2 and 3 appear with the desktop icon. Click switches to the correct Space and window. Dump output shows no wrong helper windows. Without Screen Recording permission, the app still runs (reduced mode).
### Phase 5 — Window constraint
- WindowConstraintService, coordinate conversion, loop protection, blacklist.
**Test:** Green button zoom: window ends at the strip. Drag a window down: no resize during drag; after drop, bottom is corrected unless the window was moved down intentionally. Test Finder, Terminal, a web browser, and Xcode: report which ones work. Excluded application is not resized.
### Phase 6 — Full screen, settings, login
- Full-screen hide, settings window, excluded apps, launch at login, pause.
**Test:** Full-screen application: strip disappears; exit: strip comes back. Pause works. Settings persist after restart. Launch at login works after logout/login.
### Phase 7 — Hardening
- Performance check (Activity Monitor), sleep/wake, frozen application test (`kill -STOP <pid>`), permission revoked at runtime, Stage Manager on.
**Test:** CPU and memory inside targets. A stopped application does not freeze the strip. Revoke Accessibility: onboarding appears, no crash.
## 9. Known edge cases
| Case | Expected behavior |
|------|-------------------|
| Limited AX support (for example a Java application) | If AX titles are empty, use CG titles. |
| Application with 0 windows | Empty state. |
| Application terminates | Remove observers and tabs immediately. |
| Window title changes often | Update the tab. Do not change the order. |
| Two windows with the same title | Show both. |
| Electron applications | May not send all AX notifications. The 2 s reconcile covers this. |
| Sheets and dialogs | Not shown as tabs (subrole filter). |
| Finder desktop | Not shown (filter `excludeDesktopElements`). |
| Off-screen placeholder shell | Hidden (off-screen filter rule). |
| Multiple monitors | v1: strip on the Dock screen only. The constraint service only acts on windows on this screen. |
| Sleep / wake | Reposition the strip, full refresh. |
| Display resolution change | Reposition the strip. |
## 10. Working rules
1. Put all private API code in `Private/`. Mark it with `// PRIVATE API`. Load symbols with `dlsym`.
2. Write unit tests for pure logic: tab layout, coordinate conversion, constraint math, stable order, and the window filter.
3. Keep the build green. Run `xcodebuild test`.
4. Do not change design decisions D1–D8 without approval.
## 11. Later (v2 ideas, not now)
- Pin applications.
- Search popup with hotkey (filter windows by title).
- Window thumbnails on hover.
- One strip per monitor.
- Color tags per title pattern.
- Keyboard shortcuts: `Ctrl + 1…9` for tab 1…9.