Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .claude/settings.local.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"permissions": {
"allow": [
"Bash(ps -axo pid,lstart,command)",
"Bash(xcodegen generate *)",
"Bash(xcodebuild -project WrangURL.xcodeproj -scheme WrangURL -derivedDataPath build/DerivedData -skipPackagePluginValidation test)"
]
}
}
54 changes: 7 additions & 47 deletions .github/workflows/changelog.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Adds a section to CHANGELOG.md when a release is published, listing the pull requests merged since
# the previous release, and commits it to the default branch. Pull requests are grouped by label
# (feature/enhancement, bug/fix); unlabelled ones go under "Changed". Commits pushed straight to main
# without a pull request aren't picked up, so add those by hand.
# Adds a section to CHANGELOG.md when a release is published, listing the titles of the commits since
# the previous release tag, and commits it to the default branch. Merge commits and earlier changelog
# commits are left out. The work is done by scripts/update-changelog.py.
#
# Re-running it for a release that's already in CHANGELOG.md does nothing.
name: Changelog
Expand All @@ -12,7 +11,6 @@ on:

permissions:
contents: write
pull-requests: read

concurrency:
group: changelog
Expand All @@ -25,54 +23,16 @@ jobs:
- uses: actions/checkout@v7
with:
ref: ${{ github.event.repository.default_branch }}

- name: Build changelog
id: changelog
uses: mikepenz/release-changelog-builder-action@v6
with:
toTag: ${{ github.event.release.tag_name }}
configurationJson: |
{
"template": "#{{CHANGELOG}}",
"empty_template": "- No pull requests merged in this release",
"pr_template": "- #{{TITLE}} ([##{{NUMBER}}](#{{URL}}))",
"categories": [
{ "title": "### Added", "labels": ["feature", "enhancement"] },
{ "title": "### Fixed", "labels": ["bug", "fix"] },
{ "title": "### Changed", "labels": [] }
]
}
env:
GITHUB_TOKEN: ${{ github.token }}
# The whole history and tags, to find the previous release and the commits since it.
fetch-depth: 0

- name: Update CHANGELOG.md
env:
# Passed through the environment because pull request titles are untrusted input.
CHANGES: ${{ steps.changelog.outputs.changelog }}
TAG: ${{ github.event.release.tag_name }}
URL: ${{ github.event.release.html_url }}
PUBLISHED_AT: ${{ github.event.release.published_at }}
run: |
python3 - <<'EOF'
import os, pathlib, sys

tag, url = os.environ["TAG"], os.environ["URL"]
path = pathlib.Path("CHANGELOG.md")
text = path.read_text() if path.exists() else "# Changelog\n"
if f"## [{tag}]" in text:
print(f"{tag} is already in CHANGELOG.md")
sys.exit(0)

section = f"## [{tag}]({url}) - {os.environ['PUBLISHED_AT'][:10]}\n\n{os.environ['CHANGES'].strip()}\n\n"
# Newest first: insert above the previous release's heading, or at the end if there is none.
lines = text.splitlines(keepends=True)
index = next((i for i, line in enumerate(lines) if line.startswith("## ")), None)
if index is None:
text = text.rstrip("\n") + "\n\n" + section
else:
text = "".join(lines[:index]) + section + "".join(lines[index:])
path.write_text(text.rstrip("\n") + "\n")
EOF
REPO_URL: ${{ github.server_url }}/${{ github.repository }}
run: scripts/update-changelog.py "$TAG" "$URL" "${PUBLISHED_AT:0:10}" "$REPO_URL"

- name: Commit
env:
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ build/
DerivedData/
xcuserdata/
.DS_Store
.idea
86 changes: 86 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# AGENTS.md

This file provides guidance to Codex (Codex.ai/code) when working with code in this repository.

WrangURL is a macOS 14+ menu bar app (Swift 6, SwiftUI + AppKit) that registers as the default browser and routes each opened URL to a browser based on user rules. `README.md` covers user-facing behaviour. `PLAN.md` is the design doc; its "Notes from the spike" section records decisions and platform quirks.

## Commands

The Xcode project is generated by XcodeGen from `project.yml` and is not checked in. Run `xcodegen generate` after cloning, after adding or removing files, and after any change to `project.yml`. `WrangURL/Info.plist` and `WrangURL/WrangURL.entitlements` are also generated from `project.yml`, so edit them there, not directly.

```sh
xcodegen generate
xcodebuild -project WrangURL.xcodeproj -scheme WrangURL -derivedDataPath build/DerivedData -skipPackagePluginValidation build
xcodebuild -project WrangURL.xcodeproj -scheme WrangURL -derivedDataPath build/DerivedData -skipPackagePluginValidation test

# One suite or one test (Swift Testing; include the parentheses for a single test)
xcodebuild ... test -only-testing:WrangURLTests/SimplePatternTests
xcodebuild ... test "-only-testing:WrangURLTests/RoutePlannerTests/singleBrowserRuleOpensDirectly()"
```

Test output includes harmless `com.apple.linkd.autoShortcut` connection errors from the test host; filter them out.

SwiftLint runs as a build tool plugin (`SimplyDanny/SwiftLintPlugins`) on both targets, so its warnings appear in every build; rules are in `.swiftlint.yml`. Command-line builds need `-skipPackagePluginValidation` because the plugin isn't trusted there; in Xcode, trust it once when prompted. Keep builds free of lint warnings. No formatter is configured. `scripts/release.sh` makes a Developer ID signed, notarized DMG (`SKIP_NOTARIZE=1` to only sign). `scripts/make-app-icon.swift` regenerates `Assets.xcassets/AppIcon.appiconset`.

App logs use subsystem `com.thepublicgood.wrangurl`. In zsh, `log` is a shell builtin, so call `/usr/bin/log stream --level info --predicate 'subsystem == "com.thepublicgood.wrangurl"'`.

## Architecture

**URL flow.** macOS delivers URLs to `AppDelegate.application(_:open:)` → `URLRouter.handle`. The router queues URLs until `markReady()` in `applicationDidFinishLaunching`, because a cold launch can deliver them early. `URLRouter.preview(_:)` does the decision part:
1. `RuleMatcher` finds the first enabled rule matching the URL and its source app (`SourceApp`, read from the Apple Event's sender in `application(_:open:)`). It is compiled once per rules array and cached in the router.
2. `RoutePlanner` decides `.open(browserID)`, `.pick(browserIDs)` or `.noBrowserAvailable`. It applies the fallback browser (configured browser, then Safari, then the first installed one), the unmatched-URL behaviour, removal of uninstalled browsers, and "file URLs go to the fallback". Holding exactly `AppSettings.pickerModifiers` (default ⌥⌘) forces `.pick` with every browser; `URLRouter.handle` works out the keys on arrival, before any queueing: those of a left click in the last 2 seconds (`ClickModifierTracker`, a global mouse monitor, since apps often deliver links after the keys are released), else `NSEvent.modifierFlags`.

The router then either opens the URL via `NSWorkspace` or shows `BrowserPickerController`. The URL testers in Settings call `preview(_:)`, so they can't diverge from real routing. `RoutePlanner`, `RuleMatcher`/`SimplePattern`, `PickerAction` and the `Config` import helpers are deliberately AppKit-free and pure; keep new routing logic there so it stays unit-testable.

**Simple patterns** are compiled by `SimplePattern.regexSource` into one anchored, case-insensitive regex over `url.absoluteString`, so there is a single matching engine. The documented semantics are pinned down by `RuleMatcherTests`:
- no scheme matches http and https;
- no port matches any port;
- `*.host` also matches the bare host;
- a path matches as a prefix.

**State and dependency wiring.** The long-lived objects are `@MainActor @Observable` classes created in `AppDelegate.init`:
- `ConfigStore`
- `BrowserRegistry`
- `URLRouter`
- `DefaultBrowserManager`
- `LoginItemManager`
- `HistoryStore` (opened links, saved to `history.json` next to `config.json`)
- `UpdateManager` (wraps Sparkle; its updater isn't started when hosting tests)
- the three window controllers (Settings, Onboarding, History)

They reach SwiftUI through `View.appEnvironment(_:)` in `WrangURLApp.swift`, so a new shared object must be added there. `ConfigStore` is the single source of truth. Mutate it only via `update { }`, which writes `config.json` straight away.

**Persistence compatibility.** `Rule`, `AppSettings` and `Config` have hand-written `init(from:)` implementations in extensions that use `decodeIfPresent` with defaults. When you add a field, add it to that decoder too, or older config files stop loading. An unreadable config file is renamed to `config.corrupt-<timestamp>.json`, never overwritten. `Config.decodeForImport` is intentionally stricter, so that importing `{}` can't wipe the rules.

**Windows are AppKit-managed, not SwiftUI scenes.** A menubar-only app can't reliably open a SwiftUI `Settings` scene from outside a view, so:
- `SettingsWindowController` (an `NSTabViewController` with toolbar tabs) and `OnboardingWindowController` host SwiftUI views.
- Their content is built by `makeContent` closures that `AppDelegate` sets, so the views get the environment.
- `ManagedWindow`/`DockPresence` switch the activation policy to `.regular` while any window is open (Dock icon, ⌘-Tab) and back to `.accessory` when all are closed.

**Browser picker.** `PickerPanel` is a borderless `.nonactivatingPanel` that can become key, so the source app stays frontmost while the panel still gets keystrokes. Keys are intercepted in `sendEvent` and mapped by `PickerAction`. The window's rounded shape comes from a masked `NSVisualEffectView`, with `NSGlassEffectView` inside it on macOS 26. Don't replace this with a SwiftUI background: that leaves a rectangular window shadow showing at the corners. Requests that arrive while the picker is open are queued.

**Sandbox constraints.** The app is sandboxed and distributed with Developer ID, not via the App Store:
- `Bundle(url:)` fails for apps outside readable locations. There is a read-only entitlement exception for `~/Applications`, and `DefaultBrowserManager` compares app paths as well as bundle IDs (an Xcode build lives in `~/Library/Developer`).
- `BrowserRegistry` lists only apps in `/Applications`, `~/Applications` and system app folders. This hides Playwright's "Chrome for Testing" and build products. Use `resolve(_:)` to reach hidden ones.
- The router never opens a URL with WrangURL itself (loop guard).
- When setting the default browser, confirming the `http` dialog also switches `https`. `makeDefault()` therefore skips schemes already handled and judges success by the final state.
- Release builds set `CODE_SIGN_INJECT_BASE_ENTITLEMENTS = NO`, because notarization rejects `get-task-allow`.
- Sparkle needs `SUEnableInstallerLauncherService`, the `-spks`/`-spki` mach-lookup exceptions and `network.client`. Its feed is `releases/latest/download/appcast.xml`, which the release workflow generates and signs with the `SPARKLE_PRIVATE_KEY` secret. Updates are accepted on the EdDSA signature.
- Release builds from CI are built ad-hoc, then re-signed by `scripts/resign.sh` with the self-signed "WrangURL Self-Signed" certificate. Xcode won't sign with an untrusted identity. An ad-hoc designated requirement is the build's hash, so without this each update would look like a different app to macOS. Builds without a Team ID need `disable-library-validation` to load Sparkle.framework. Debug builds only work without it because of `get-task-allow`.

## Testing and manual UI checks

The tests use Swift Testing and are hosted in the app. `AppDelegate.isRunningTests` (checks `XCTestConfigurationFilePath`) skips startup side effects, so tests must not rely on the app delegate's objects. Anything that writes files should take an injected URL (`ConfigStore(fileURL:)`).

Debug builds accept launch arguments for inspecting UI without clicking. For example: `open build/DerivedData/Build/Products/Debug/WrangURL.app --args -DebugSettingsTab rules`.
- `-DebugSettingsTab general|rules` opens Settings on that tab.
- `-DebugEditRule <index>` opens the rule editor.
- `-DebugInsertionIndex <n>` draws the rule editor's drop line at that position.
- `-DebugOnboardingStep 0-3` opens the setup assistant on that step.
- `-DebugShowHistory YES` opens the History window.
- `-DebugAppearance light|dark` overrides the system appearance.
- `-DebugShowPicker <bundleIDs,…>` (plus optional `-DebugPickerURL <url>`) shows the picker. `docs/picker.png` was captured this way.

`docs/` is also the GitHub Pages site (`index.html`, `style.css`, `site.js`, no build step). Its screenshots in `docs/images/` were captured this way in light and dark variants (`-DebugAppearance`; `-NSRequiresAquaSystemAppearance` is ignored), using the demo `config.json` and `history.json` in `docs/demo/`. Its README has the steps.

The debug build shares its sandbox container, and so its `config.json`, with any installed copy of WrangURL: `~/Library/Containers/com.thepublicgood.wrangurl/Data/Library/Application Support/WrangURL/`. Back that file up before experimenting with rules, and restore it afterwards.
Loading