Skip to content

Build and Install

magicelk235 edited this page Nov 18, 2026 · 18 revisions

Build and Install

The build-and-install subsystem is the back half of the pipeline: it takes the staged web-extension payload produced by the Conversion Pipeline, wraps it in an Xcode project via Apple's own packager, builds and signs a real macOS/iOS host app + Safari extension (.appex), then moves it into place and registers it with Safari. Everything lives under src/build/:

File Responsibility
src/build/packager.ts Xcode project generation, bundle-id patching, native-messaging codegen, build, and built-bundle verification
src/build/installer.ts Move-to-~/Applications, LaunchServices registration, Safari toggle/restart, uninstall, legacy broker LaunchAgent cleanup
src/build/verify.ts --verify: read pluginkit to confirm the extension is registered and enabled; verifySigning: read the built .appex's signature back with codesign -dvv on every run that asked for a team (plain --install counts)
src/build/tempload.ts --temp-load: stage-only path for Safari 18's "Add Temporary Extension…"
src/build/xcproj.ts Reads and edits the generated project in either format, the project.pbxproj plist or Xcode 27's JSON project.xcproj (Two project formats)
src/build/appicon.ts Icon Composer AppIcon.icon so the app icon follows the system appearance (App icon)

Requirements

Installing aqueduct

Aqueduct needs macOS and Node 18 or later. Most people get it through viaduct, which runs aqueduct whenever you convert for Safari:

npm install -g @magicelk235/viaduct
viaduct <input> [options]

To install aqueduct on its own:

npm install -g @magicelk235/aqueduct
aqueduct <input> [options]

viaduct <input> without --browser runs exactly the same conversion as aqueduct <input>, with the same flags (CLI Reference). The Viaduct Mac app also runs aqueduct, through the viaduct package.

Xcode

Packaging needs a full Xcode install, not just the Command Line Tools. Both xcrun safari-web-extension-packager and xcodebuild ship inside Xcode.app; a bare CLT install has neither.

aqueduct --doctor checks the toolchain before you commit to a build (doctor() in src/cli.ts). It probes each dependency and prints a fix hint on failure:

  • xcrun → "Install Xcode command line tools."
  • safari-web-extension-packager → resolved via xcrun --find; "Requires a full Xcode install (not just CLT)."
  • xcodebuild → "Requires full Xcode."
  • plutil, ditto, osascript, lsregister → part of macOS; pluginkit is checked with no hint.

lsregister is not on PATH; its absolute location is pinned in installer.ts as LSREGISTER (/System/Library/Frameworks/CoreServices.framework/…/Support/lsregister).


Packaging

runPackager() (packager.ts) shells out to Apple's packager with a fixed argument set, --swift --no-open --no-prompt --force, and threads the caller's staged dir, output dir, app name, and bundle id through. Platform selection maps the Platforms type to packager flags:

opts.platforms Flag
macos --macos-only
ios --ios-only
all (neither flag, packager emits both)

The packager writes a host app target plus a Safari-extension .appex target into a generated .xcodeproj. Because a reused output dir can hold a stale project from a prior run (and readdir order is not guaranteed), runPackager prefers the project whose basename is exactly <appName>.xcodeproj before falling back to whatever it finds.

Resource copy vs. symlink. --copy-resources is passed only when opts.copyResources is set. The CLI wires that to --ci (copyResources: values.ci, src/cli.ts); the default is false, which leaves the packager to symlink the staged resources for a fast dev loop. --ci clean-copies them into the project instead, which is what you want for a CI or TestFlight-safe archive.


Bundle-identifier patching

patchProjectBundleIds() (packager.ts) forces every PRODUCT_BUNDLE_IDENTIFIER in the generated project file (project.pbxproj, or project.xcproj on Xcode 27, see Two project formats) to the intended value: app targets get bundleId, extension targets get bundleId.Extension. The two rewrites avoid a collision where both targets end up with the same id, the appex regex is written so a user bundle id that itself ends in .Extension isn't rewritten into the appex id on a re-run, which would leave both targets identical (b0c81a1). The same pass grants ENABLE_OUTGOING_NETWORK_CONNECTIONS = YES to every sandboxed target that lacks it, because xcrun only grants it to the app target, without it the appex's URLSession can't resolve any host and the native proxy dies.

The default id comes from defaultBundleId(appName) → com.viaduct.<slug>. The com.viaduct prefix predates the rename to aqueduct and was kept, so re-converting an extension keeps the bundle id an earlier install used. The slug strips non-alphanumerics and drops leading digits (a CFBundleIdentifier segment starting with a digit is rejected by parts of Apple's toolchain). It keeps the clean slug only when the slug is a lossless rendering of the name — i.e. the name is already [A-Za-z][A-Za-z0-9]*. Otherwise (the slug dropped or reordered anything: non-ASCII, a hyphen/underscore, a leading digit, all-symbol) it derives a stable per-name suffix from a SHA-1 of the original name. This is what stops two distinct names that reduce to the same non-empty slug — Foo/1Foo, Cafe/Café, MyExt/My-Ext — from collapsing to one id and shadowing each other in LaunchServices; the earlier code only hashed when the slug was entirely empty, so those pairs collided (92fa2ee). Covered by test/derive-app-name.test.js and test/default-bundle-id.test.js.

The app name itself is sanitized upstream by deriveAppName(rawName), which whitelists letters (any script), digits, -, and _ and drops everything else. The name becomes a directory, an xcodebuild scheme, and part of the bundle id, and is passed verbatim to --app-name, which writes it into the generated .xcodeproj XML, so a whitelist (not a blacklist) closes XML / scheme / make-variable injection via characters like < > & " $ \ ( ) | (ba89cc7`).

Two project formats

Xcode 27 changed what safari-web-extension-packager writes. Up to Xcode 26 the project is a project.pbxproj plist; from Xcode 27.2 it is project.xcproj, a JSON document with trailing commas where each target carries a "build-settings": { ... } object of string and string-array values. Every project patch aqueduct makes (setBuildVersion, patchProjectBundleIds, unsandboxAppTarget, grantDownloadsFolder, writeAppearanceAwareIcon) goes through src/build/xcproj.ts (0ae45ba). readProjectFile opens whichever file the project has, project.pbxproj first, and the JSON form is edited as text, one "build-settings" block at a time, so Xcode's formatting and the trailing commas (which JSON.parse rejects) survive. The appex's block is the one whose PRODUCT_BUNDLE_IDENTIFIER ends in .Extension (isExtensionBlock), and a missing setting is inserted after a named neighbour; the outgoing-network and Downloads keys go right after ENABLE_APP_SANDBOX. The icon bundle is registered as a { "path": "AppIcon.icon", "target-membership": [...] } line next to the catalog's, with the group chain above it giving the directory on disk. Covered by test/xcproj-format.test.js.

Before this (v1.17.0 and earlier, on Xcode 27.2; fixed in v1.18.0), every patch looked for the plist only and silently did nothing. The built app still verified, because the packager had already been given the right bundle id, but the appex had no outgoing-network entitlement, so the native proxy and the WebSocket tunnel failed on every host ("A server with the specified hostname could not be found"); the container app stayed sandboxed, so native messaging could not launch a host; the version stayed 1.0, so Safari served stale resources across reinstalls; and the Dock icon stayed the packager's white tile. Measured on Claude in Chrome 1.0.104: every /v1/messages call answered 401 in the browser (the org only allows the Chrome extension origin) and the proxy retry failed to resolve the host. The entitlements of a built app are the quick check: codesign -d --entitlements :- "<App>.app/Contents/PlugIns/<App> Extension.appex/Contents/MacOS/<App> Extension" must list com.apple.security.network.client.

⚠️ The differentiator: verify the compiled .appex, not the project files

Patching the project file is best-effort. The authoritative check is verifyBuiltBundleId(appPath, bundleId) (packager.ts), which reads the built Info.plist of both the app and the compiled .appex and confirms their CFBundleIdentifiers match intent (e3e3007).

This is the check the previous generation lacked: it patched the project but never verified the compiled .appex, so Safari could end up registering the packager-default id for the wrong extension. verifyBuiltBundleId handles both bundle layouts, macOS nests everything under Contents/, iOS .apps are flat, resolving the Info.plist dir per-bundle so iOS builds don't spuriously fail (the old macOS-only Contents/ paths returned null for every iOS app, which the caller treats as a fatal mismatch). If it returns ok: false, the build aborts rather than registering the wrong extension with Safari.

Related build-config and iOS hardening: CORS-proxy + build-config hardening (8255ebc) and a batch of iOS-build / crash / codegen fixes from a multi-agent bug hunt (eb71af6).


Native-messaging handler, CORS proxy, and downloads writer

Apple's packager generates a stub SafariWebExtensionHandler.swift that just echoes messages. writeNativeHandler() (packager.ts) rewrites its beginRequest(with:) to do three real jobs inside the sandboxed appex, and is written whenever the extension declares proxy hosts, nativeMessaging, or downloads:

  1. HTTP/CORS proxy: for __c2sProxy messages it performs the request server-side (no browser CORS) and sets the Chrome-extension Origin header that Safari forbids JS/DNR from setting.
  2. Native-messaging client: for __c2sNM envelopes it frames the JSON over a loopback TCP connection to a broker running in the (unsandboxed) container app, since the sandbox forbids the appex from exec'ing the host (05cc244).
  3. Downloads writer: for __c2sDownload envelopes (filename, base64, conflictAction) it writes the bytes into ~/Downloads under the requested relative name, creating subfolders, sanitizing path components, and uniquifying (name-1.ext) unless asked to overwrite; it replies with the resolved path and size. grantDownloadsFolder() sets ENABLE_FILE_ACCESS_DOWNLOADS_FOLDER = readwrite on the .Extension build configs, which Xcode turns into the com.apple.security.files.downloads.read-write entitlement; the sandbox itself stays on, so Safari still registers the appex. This is what makes chrome.downloads.download() save a real file with its filename (Safari Quirks F1a).

The allowed hosts, Chrome origin, and broker token are baked into Swift static let literals. Every value is whitelisted to characters valid in a hostname/origin/token before it's spliced in (allowHosts → [a-zA-Z0-9.\-:], origin → adds /, token → [a-zA-Z0-9]), so a malformed manifest can't break out of the Swift string literal (dab04f1). The broker side of this, the loopback server that actually launches the native host, is generated by writeAppBroker() into the container app, and unsandboxAppTarget() drops the app target's sandbox so it can exec the host binary. See Runtime Shim for how the browser-side shim talks to this proxy. Codegen is covered by test/native-messaging-handler.test.js.


Signing modes

buildXcodeProject(xcodeproj, appName, platforms, team?, { teamAutoDetected? }) (packager.ts) picks the scheme, builds Release into a throwaway DerivedData dir under $TMPDIR (never the project tree, an iCloud-synced volume stamps the fresh .appex with file-provider xattrs that make codesign abort), and chooses one of two signing strategies based on whether a team is passed:

Ad-hoc (no --team) Team-signed (--team <id> / auto)
xcodebuild flags CODE_SIGN_IDENTITY=-, CODE_SIGN_STYLE=Manual, empty team/profile, CODE_SIGNING_REQUIRED=NO -allowProvisioningUpdates, CODE_SIGN_STYLE=Automatic, DEVELOPMENT_TEAM=<id>, CODE_SIGN_IDENTITY=Apple Development
Safari requirement Needs "Allow Unsigned Extensions" toggle Loads with no toggle
Persistence across Safari restart ✗ toggle resets every Safari session: must re-enable ✓ survives restarts (1a6ecef)
Provisioning profile none Xcode creates/refreshes one (App Sandbox entitlement requires it)
Typical expiry n/a Free personal team ≈ 7 days; paid Developer Program ≈ 1 year

Both modes sign with the App Sandbox entitlement (the targets set ENABLE_APP_SANDBOX=YES), Safari refuses to register a web-extension appex that lacks it, so CODE_SIGNING_ALLOWED=NO is deliberately not used (it would silently strip the entitlement and the extension would never appear).

Auto team detection. With --team auto (or plain --install) the CLI calls detectXcodeTeam() (packager.ts), which reads three sources and returns a team id you can actually sign with, so you team-sign without ever knowing or typing the id. The team id is the whole job: the build runs xcodebuild -allowProvisioningUpdates, so Xcode mints the development certificate and profile itself.

  1. Xcode's cached team list, IDEProvisioningTeamByIdentifier and IDEProvisioningTeams, read from both the com.apple.dt.Xcode and com.apple.dt.xcodebuild domains. Which key and which domain get written depends on the Xcode version and on what the user has provisioned, so all four are tried.
  2. Provisioning profiles on disk, ~/Library/Developer/Xcode/UserData/Provisioning Profiles then ~/Library/MobileDevice/Provisioning Profiles (Xcode 16 moved the directory, so both are read), newest first. Profiles are CMS-signed but the payload plist sits in the blob as plain XML, so the team id is scanned straight out of the bytes rather than shelling out to security cms -D per file. TeamIdentifier is the modern key; profiles cut before Xcode 6 carry only ApplicationIdentifierPrefix, and the com.apple.developer.team-identifier entitlement is read as well.
  3. The keychain, security find-identity -v -p codesigning, then the team id out of the certificate's subject OU. Development identities are preferred (Apple Development, Mac Developer, Apple Distribution, iPhone Developer), then Developer ID Application and 3rd Party Mac Developer Application: a paid account that has only ever signed notarized releases has nothing else in the keychain, and reading the team off that beats telling the user they have no Apple account. Authoritative when it hits, since the certificate is what codesign consumes.

A team id found on disk is not proof this Mac can sign for it. Profiles outlive the account that installed them, and installers drop profiles for their vendor's team, so a profile-only match hands xcodebuild a team it has no account for and every build dies on error: No Account for Team "…" (#15 auto-detected a third-party vendor's team on a Mac with no Apple account). So only sources 1 and 3 nominate a team, the ones that mean an account or a usable certificate exists; the profiles then choose among those, newest first, which is how the team you most recently provisioned for wins when the keychain holds several. When nothing usable turns up, detection returns null and the build falls back to ad-hoc, announced up front, and a warning rather than a failure at the end. Covered by test/detect-xcode-team.test.js.

The reason for the breadth: a preference cache alone was not enough. Xcode writes it asynchronously and only after it has provisioned something, so an account that was signed in and could sign perfectly well read as "no Apple account" and dropped to ad-hoc, and the remedy the tool printed ("sign in to Xcode") was one the user had already followed (#14). See CLI Reference for --team / --install.

When a detected team still can't sign. Detection can only be as good as what the machine reports: a certificate expires, an account is revoked, a free team hits Apple's app-id limit. When a team that came from detection fails the build for a signing reason (No Account for Team, No Accounts (Xcode 27, no Apple ID signed in), No signing certificate, Signing certificate is invalid (revoked or expired), requires a development team, No profiles for, a profile that doesn't match), the build is retried ad-hoc rather than throwing the whole conversion away, and returns adHocFallback: true. convert.ts then treats the run as ad-hoc throughout, so the install skips the team-signed path, the "Allow Unsigned Extensions" warning prints, and the signature check expects ad-hoc instead of failing the run. A team the user named with --team <id> is never downgraded this way: that is a deliberate request for a signature that survives Safari quitting, so the run fails, says why, and points at signing in to Xcode, --team auto, or dropping --team for an ad-hoc build (#19). Covered by test/xcodebuild-signing-failure.test.js.

Reading a failed build. xcodebuild splits a failure across both streams: the diagnostics that say why go to stdout, while stderr carries only run-destination noise and ** BUILD FAILED **. Aqueduct used to print stderr and fall back to stdout only when stderr was empty, which it never is, so every signing error was reported as a build failure with no cause, in the terminal and in bug reports alike (#15). xcodebuildDiagnostics() now collects the error: lines from both streams, de-duplicated across targets (xcodebuild repeats each one per target), capped at 20, and falls back to the tail of the raw output when a failure carries no diagnostic at all.

The build returns { builtApp, derivedDir, adHocFallback? } with the app still sitting in DerivedData, the installer moves it in one hop (no copy onto the synced project tree) and then deletes derivedDir, keeping the signature/seal untouched.

setBuildVersion() stamps a unique MARKETING_VERSION / CURRENT_PROJECT_VERSION on every target first, because the packager hardcodes 1.0 (1) and Safari keys its cached copy of the resources on the short version, serving stale JS across reinstalls until the version is bumped.

App icon follows the system appearance

Quirk. safari-web-extension-packager composites the extension's icon onto an opaque white plate (gradient + shadow baked into every AppIcon.appiconset PNG). macOS 26 then wraps that PNG in its glass squircle, so the Dock/Finder icon of a converted extension stays white in Dark Mode while every other app icon goes dark.

Handling. src/build/appicon.ts, called from convert.ts right after setBuildVersion, writes an Icon Composer bundle AppIcon.icon next to every Assets.xcassets the pbxproj references and registers it (a PBXFileReference with lastKnownFileType = folder.iconcomposer.icon, a child of the same PBXGroup, and a PBXBuildFile in the same Resources phase). On Xcode 27's project.xcproj the registration is the JSON line described under Two project formats. Xcode 26+ prefers the .icon over an appiconset of the same name, compiles both appearances into Assets.car (NSAppearanceNameAqua / NSAppearanceNameDarkAqua icon groups, plus the tintable mono variant), and renders the flat AppIcon.icns fallback for macOS < 26 from the same bundle. The packager's appiconset is left untouched.

The bundle has one layer, the extension's own glyph, chosen by sourceIconFor: the largest icons entry, else the largest action.default_icon, PNG or SVG only, and only if the file is actually staged (anything else leaves the packager's icon in place). The plate is a single white automatic-gradient fill and nothing else. macOS 27 renders every icon style from that: Default uses the fill as authored, Dark replaces it with the system dark plate, Clear and Tinted go mono, all derived at draw time from the same Assets.car. Authoring a dark fill specialization (as the first version did, 0.14/0.14/0.15) is worse, not better: on macOS 27 the system honors it and the plate comes out visibly lighter than every other Dark-style icon on the desktop (57,56,60 sampled against the system's 39,37,39); with no specialization the plate is pixel-identical to Apple's own icons. Liquid Glass translucency is on at 0.3, the value current macOS 27 icons ship with (Icon Composer's default 0.5 visibly washes brand colors toward the plate). Two details that were found empirically with actool:

  • Layers render at native pixel size on a 1024pt canvas, not fit-to-canvas. imageSize reads the PNG IHDR (or the SVG viewBox / width+height) and iconComposerJson sets position.scale = 0.8 × 1024 / longest side, so a 128px Chrome icon gets 6.4 and an 800px one 1.024. Without this a 128px glyph is a dot in the middle of the plate. 0.8 follows the macOS 27 icon style, where the artwork runs out to about 80% of the plate (Apple's Calculator is a 636px layer at scale 1.3); the packager's legacy composite gave the glyph about 75%.
  • Dark grayscale silhouettes vanish on the dark plate. glyphStats converts the PNG to a 32-bit BMP with sips and averages the ≥50%-alpha pixels; when coverage is below 85% (it is a glyph, not an opaque square), mean luminance is below 0.3 and mean chroma below 0.12, invertsInDark adds a layer fill-specializations entry that paints the glyph solid white under the dark appearance, the way Apple's own mono logos flip. Opaque squares are never repainted (filling one white would erase whatever is drawn on it) and colored glyphs keep their colors.

Gated on xcodeMajorVersion() >= 26 (xcodebuild -version); older Xcode can't compile .icon and keeps the packager's white icon. The .icon schema (fill-specializations, position.scale, translation-in-points, supported-platforms) was taken from Apple's Landmarks sample's Landmarks App Icon.icon/icon.json; Apple publishes no schema. Regression test: test/appearance-aware-appicon.test.js.

Verifying a change here is fiddly: IconServices returns the generic document icon for any app under /tmp, so copy the built app somewhere under $HOME before asking NSWorkspace.icon(forFile:) for it, and check the light variant off the AppIcon.icns fallback (iconutil -c iconset) because a process can't request an appearance the system isn't in. The plate color to match is whatever Apple's own icons render to under the user's AppleIconAppearanceTheme (defaults read -g), so sample a system icon rendered the same way and compare pixels rather than eyeballing.


Install

installToSafari(opts) (installer.ts) makes the extension persist:

  1. Move, not copy, the built app to the target dir (default ~/Applications, overridable with --install-dir) via moveBundle, a same-volume rename is atomic and leaves no duplicate behind, and preserves the signature/seal (bd3bbc7). It does not re-sign: a plain codesign --sign - would strip the entitlements and Safari would stop registering the appex.
  2. Register with LaunchServices via lsregister -f <dest>.
  3. Ad-hoc only (!opts.signed && opts.safariRestart): quit Safari and defaults write com.apple.Safari AllowUnsignedAppExtensions -bool true; Safari is reopened after step 4. A team-signed build skips this whole dance because it loads without the toggle. --no-safari-restart also skips it (gentler mode).
  4. Launch the host app once (open <dest>) so Safari actually registers the appex. With --background-launch both launches stay in the background: open -g -j <dest> for the app and open -g -a Safari for the reopen, so neither takes focus.
  5. Confirm with pluginkit, bundleRegistered() matches the appex id (<bundleId>.Extension), not a bare substring, so it doesn't report success when only the app (not the extension) appears.

The host app runs while Safari does

When the extension uses native messaging, the container app hosts the broker (writeAppBroker, packager.ts), so it has to be running whenever the extension talks to a native host. It runs exactly as long as Safari does (86b9f20):

  • Started on demand by the extension. When a native call finds nothing listening on the broker's port, the appex (launchBroker in the generated SafariWebExtensionHandler) opens the app's broker URL, <app bundle id>.broker:launch, with NSWorkspace.open(_:withApplicationAt:configuration:) and activates = false, waits up to 10 s for the broker, and retries the call. It retries only when the first connect failed, because a round-trip that broke after connecting may already have been acted on. Concurrent calls wait on one lock instead of each launching. The app's Info.plist registers the scheme as $(PRODUCT_BUNDLE_IDENTIFIER).broker (registerBrokerUrlScheme). The appex derives the app's id from its own id minus .Extension, because the sandbox won't let it read the app's Info.plist (Bundle(url:) on the containing app returns nil, checked live). A sandboxed launch opens a URL rather than passing an argument because, per Apple's NSWorkspace.OpenConfiguration.arguments docs, a sandboxed caller's launch arguments are ignored.
  • A failed launch isn't retried by every queued call. If the open reports an error (the app was moved or trashed while Safari still has its extension loaded) or the broker never comes up, the appex sets launchRetryAfter 30 s out, and calls fail fast until then instead of each waiting out the same 10 s behind the lock (91d45c3). A call that reaches a broker clears it. Checked live by moving the running app out of ~/Applications and killing it: every extension request in the following 20 s completed at once.
  • Windowless when the extension starts it. The window is ordered out in applicationWillFinishLaunching, before it is drawn. A launch URL arrives in application(_:open:) before applicationDidFinishLaunching, which sets launchedByExtension. Any other launch shows the window again. NSApplication.launchIsDefaultUserInfoKey can't be used for this: it came back false for a plain open of the app, because AppKit restores the window on launch (checked live).
  • Quits with Safari. An NSWorkspace.didTerminateApplicationNotification observer terminates the app once no com.apple.Safari or com.apple.SafariTechnologyPreview is running and its window isn't on screen. The ids are matched exactly: Safari's helper apps (com.apple.Safari.SandboxBroker, com.apple.SafariPlatformSupport.Helper) share the prefix and keep running. With the window open, the app quits when the window closes instead (applicationShouldTerminateAfterLastWindowClosed returns true once no Safari is running).
  • A user quit sticks for that Safari session. Claude in Chrome polls its native port about every 150 ms, so an app the extension restarts on demand would be back before Finder could trash it. applicationWillTerminate records the running Safari sessions (pid@launchDate) under ViaductDeclinedBrowserSessions in the app's defaults, and clears the key when no Safari is running. An extension launch during a recorded session terminates straight away, before the broker starts. When the appex sees the app exit without a broker, it sets launchDeclined and stops launching until a call reaches a broker again, so a quit costs one brief relaunch. The record is ignored in a new Safari session, and a user launch clears it. A crash or kill -9 never reaches applicationWillTerminate, so the next native call brings the broker back.

macOS's automatic termination still has to be held off while the app runs windowless: it reaps an idle windowless app and wipes the broker's host map, so applicationDidFinishLaunching holds a background activity for the whole process lifetime.

The setup button no longer quits. Apple's template button, Quit and Open Safari Settings…, opens Safari's settings and then terminates the app. That quit would count as the user's and turn native messaging off for the rest of the Safari session, and the button is the first thing a user clicks after installing. So writeAppBroker also patches the app target: ViewController.swift's terminate(nil) becomes self.view.window?.close(), and Script.js / Main.html drop "Quit and" from the label. Builds without native messaging keep Apple's button unchanged.

History. Until 86b9f20 a per-user LaunchAgent (~/Library/LaunchAgents/<bundleId>.broker.plist, open -g -W <app> --args --viaduct-broker, RunAtLoad + KeepAlive) kept the app running from login onward, with or without Safari. It relaunched the app after every quit, so the app could never stay quit and Finder refused to delete it: "The item “Claude.app” can’t be moved to the Trash because it’s open." cc15125 hid the window on the agent's relaunches, and e759a30 had the app boot the agent out on quit. Both were superseded by running the app on demand. open -W exits 0 however the app ended (checked against kill -9 and a quit Apple event), so launchd couldn't tell a quit from a crash anyway.

Reinstalling replaces a running app. installToSafari first removes any broker LaunchAgent an earlier install left (removeLegacyBrokerAgent, keyed on the id of the bundle already at the destination and on the new id), then stops a process running from the destination with SIGTERM (stopRunningApp). It uses a signal rather than a quit Apple event, because a quit while Safari runs would be recorded as the user's. The extension starts the new app on its next native call.

Uninstall. uninstallFromSafari(appName, installDir?) removes a leftover broker LaunchAgent, stops the running app, unregisters (lsregister -u) before deleting so LaunchServices drops the appex record cleanly, then removes the .app. A leftover agent is keyed on the app's bundle id, which may be a custom --bundle-id rather than com.viaduct.<name>, so uninstall reads the installed bundle's real CFBundleIdentifier off disk (before the rmSync, layout-aware for both macOS-nested and iOS-flat Info.plist) and falls back to the derived default only when that read fails (92fa2ee). It guards hard against path traversal and non-.app targets: the resolved path must be a direct child of the install dir and an actual .app directory, so --uninstall "../../../Other" can never rmSync an arbitrary bundle. parsePluginkitList() / listSafariExtensions() back --list, parsing pluginkit -mv output and requiring an absolute path per line so malformed rows are skipped rather than surfaced as garbage.


Verify

verifyInSafari(bundleId) (verify.ts) backs --verify (33e9bce). It nudges Safari to scan extensions (open -a Safari), then polls pluginkit for up to ~10s: registration lands asynchronously after Safari launches, so an immediate single query races it and flips the exit code spuriously. It reports two independent facts:

  • Registered: bundleRegistered() over the verbose pluginkit -mAvvv block.
  • Enabled: parseEnabled() over the compact pluginkit -mv listing. The enabled/disabled state is not in the verbose block; it lives in the flag (election) column at the start of each compact line. Per man pluginkit, +/! mean the user elected to use it → true, - means elected to ignore → false, and a blank/=/? column means no election recorded → null (not "disabled"). Older regexes that scanned the verbose block for "enabled"=N were dead on real output, and a bare \bdisabled\b scan false-flagged any extension whose path merely contained the word "disabled".

A null enabled state means "registered, couldn't confirm enabled", best-effort, not failure. Covered by test/verify.test.js. See Testing and Debugging for the full reinstall cycle.


Temp-load

writeTempLoadInstructions(stagedDir) (tempload.ts) backs --temp-load: it stages only: no Xcode project, no build, no signing, and drops a SAFARI_LOAD_INSTRUCTIONS.md next to (not inside) the staged dir, so the doc doesn't pollute the folder Safari loads or a --zip archive. This targets Safari 18's Develop → "Add Temporary Extension…", which loads an unpacked extension folder directly.

It's the fastest iteration loop: no compile at all, with one catch: temporary extensions must be re-added after every Safari restart (and still need "Allow Unsigned Extensions", which also resets each restart). Use it while iterating on the shim; switch to --install --team once you want persistence.


See also

Clone this wiki locally