Skip to content

deeplink: register the link handler on macOS - #180

Open
DavyBello wants to merge 13 commits into
mainfrom
ladi-bello/deeplink-3-macos
Open

DavyBello wants to merge 13 commits into
mainfrom
ladi-bello/deeplink-3-macos

Conversation

@DavyBello

@DavyBello DavyBello commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Registers bits as the macOS handler for datadog-bits-cli:// links, so a click runs bits deep-link -- <url> in a new Terminal or iTerm2 window. It fills in #179's macOS stub.

Opt-in for now: it registers only when BITS_NO_DEEP_LINK_REGISTRATION=0.

When it runs

What it installs

  • ~/Applications/Bits CLI URL Handler.app, an applet compiled with osacompile. Info.plist: CFBundleURLTypes for datadog-bits-cli, CFBundleIdentifier com.datadoghq.bits-cli.url-handler, and LSUIElement, so there's no Dock icon.
  • codesign --force --sign - after the plist is written (Apple Silicon won't launch a broken seal), then lsregister -f. It counts as done only when Launch Services resolves the scheme to this app; bits never takes the scheme from another app.

Design notes

  • macOS delivers links as an Apple Event, not argv; the applet's on open location receives them. No cgo, Xcode or shipped binary.
  • The applet accepts only datadog-bits-cli:// links made of the characters deeplink.Build emits (one Go constant), then uses quoted form of and --. The bits path is shell-quoted in Go.
  • Terminal choice comes from TERM_PROGRAM when links are registered: iTerm.app → iTerm2, Apple_Terminal → Terminal. Others keep the previous choice (Terminal at first).
  • A rejected link, or a bits that no longer exists, shows a generic alert, never echoes the URL, and opens no terminal.

Known limits

  • The first link triggers a macOS Automation prompt, and likely again after each update, because each update rebuilds and re-signs the app.
  • The app is ad-hoc signed and not notarized. Gatekeeper skips it because it's never quarantined; Santa or MDM allowlisting may still block it.
  • A bits path with \, control or invisible characters can't register; its quoting covers POSIX shells and fish.
  • For iTerm2, a bits or login-shell path containing ' or $$ can't register (iTerm2's command parser reads backslashes inside quotes). macOS user names, the installer and Homebrew never produce one.
  • A bits in a protected folder (Documents, Downloads, iCloud) may prompt for file access; a denial reads as "not installed".

Docs (deferred)

INSTALL.md is untouched; the enable-by-default PR adds these uninstall steps. tccutil runs first because it can't resolve the bundle id once the app is unregistered:

tccutil reset AppleEvents com.datadoghq.bits-cli.url-handler
/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -u ~/Applications/"Bits CLI URL Handler.app"
rm -rf ~/Applications/"Bits CLI URL Handler.app"

Don't keep a copy of the handler app anywhere under your home folder; macOS registers every copy as a handler.

How to test it

On a Mac, with a release build:

go build -ldflags "-X github.com/datadog-labs/bits-cli/internal/version.releaseVersion=0.0.1" -o /tmp/dl/bits .
BITS_NO_DEEP_LINK_REGISTRATION=0 BITS_FAKE_BACKEND=1 /tmp/dl/bits      # send any message, then quit
open 'datadog-bits-cli://open?conversation=00000000-0000-4000-8000-000000000000'
open 'datadog-bits-cli://open?conversation=$(touch%20/tmp/pwned)'       # alert only
ls /tmp/pwned                                                           # must not exist

./scripts/test.sh and ./scripts/lint.sh pass. On macOS, CI runs the Test link handler step:

  • The applet has no quarantine flag and passes codesign --verify --deep --strict; spctl rejects it (logged only).
  • Hostile links ($(), backquotes, quotes, ;, newline) are rejected; accepted ones reach a fake bits as exactly [deep-link, --, url] under sh, bash and zsh.
  • The missing-binary check flips when bits is deleted, and Launch Services resolves the scheme to the installed app.

On Linux: goldens for both scripts and the plist, a 47-URL harness under five shells, and 13/13 mutations caught.

Checklist

  • I have reviewed the contributing guidelines (CONTRIBUTING.md in the repository root).
  • I have added tests or explained why they are not needed.
  • I have updated the documentation if needed. (Deferred to the enable-by-default PR, see "Docs (deferred)".)

🤖 Generated with Claude Code

@DavyBello
DavyBello force-pushed the ladi-bello/deeplink-3-macos branch 2 times, most recently from 31eddbb to d0e9954 Compare December 3, 2026 12:16
Base automatically changed from ladi-bello/deeplink-2-linux to main December 4, 2026 08:23
DavyBello and others added 3 commits December 4, 2026 08:37
runTool and its timeout constants move out of register_linux.go into
tool.go, and its test into tool_test.go, so the macOS link handler can
take them up without touching the desktop entry code. Both files keep the
Linux-only build constraint the code had.

This is a pure move: the code is identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On macOS the handler opens links in a terminal Bits picks, so the stamp
must record that choice and a new one must register again. The stamp gets
a Terminal field, ensure takes the terminal and prepare builds the handler
for it. An empty terminal means the current chat cannot tell, so
replaceHandler keeps the previous one instead of registering again; it
still marks the stamp unverified before installing anything.

linkTerminal reports the terminal per OS. Linux launchers pick their own
terminal and Windows does not register yet, so both return "", as does the
macOS stub until the handler lands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
macOS hands URLs only to app bundles, and Bits ships a bare binary. Bits
now compiles an AppleScript applet with osacompile into
~/Applications/Bits CLI URL Handler.app. That needs no cgo, no Xcode and
no extra release artifact. Its open location handler runs
'<bits>' deep-link -- '<url>' in a new iTerm2 or Terminal window,
following TERM_PROGRAM when Bits registers. The -- ends flag parsing, as
the Windows handler does.

A link reaches a shell only after three checks: it must start with the
scheme, it may hold only the characters Build emits (one constant feeds
both the applet and the Go test that runs Build output through it), and
it is single-quoted. The bits path is quoted in Go and must have no
backslash or control characters, because fish reads escapes inside
single quotes. A rejected link shows a notification, never echoes the
link and opens no terminal. So does a link that arrives after bits was
removed: the applet checks the path without a shell, rather than open a
terminal that only shows a shell error.

runTool's file is now built for every unix, so darwin shares it with
Linux.

prepareHandler generates the applet's source and its place without
changing anything. installHandler builds the bundle at a fixed hidden
staging path, so a repeated failure reads the same and is reported once,
writes its Info.plist to claim the scheme and re-signs it ad hoc, because
Apple Silicon refuses a broken seal. It then replaces the old applet and
registers it with lsregister. It counts as the default only when Launch
Services resolves the scheme to it. Bits never takes the scheme from an
app the user chose.

Limits: the first link that opens a terminal triggers the Automation
prompt, which likely returns after each update because each update
rebuilds and re-signs the applet. The applet is not notarized. Gatekeeper
never assesses it because it is never quarantined, but managed Macs may
block it. A link that arrives while the applet is replaced finds no
handler. User docs come with the rest of the deep link docs.

CI runs TestBuildApp with every macOS test run, and runs TestInstallHandler
in its own verbose step, in a directory outside the system temporary
directory, where Launch Services disables apps, so the log shows what
Launch Services registered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@DavyBello
DavyBello force-pushed the ladi-bello/deeplink-3-macos branch from db738cb to a736895 Compare December 4, 2026 08:38
@DavyBello
DavyBello marked this pull request as ready for review December 4, 2026 09:04
@DavyBello
DavyBello requested a review from a team as a code owner December 4, 2026 09:04

@datadog-official datadog-official Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bits Code Review: FAIL

Concurrent registrations from different configuration directories can delete the macOS handler while leaving a successful stamp that suppresses repair in one configuration.

Open Bits AI session

🤖 Bits Code Review · Commit a736895

Comment thread internal/deeplink/register_darwin.go Resolved
DavyBello and others added 2 commits December 4, 2026 11:47
A stamp that matches says the handler was installed, not that it still
is. If the user deletes the macOS applet or the Linux desktop entry,
links stop opening and every later chat trusts the stamp, so nothing
repairs them. The same happens on macOS when two chats with different
config directories, which take different locks, replace the shared app
bundle at once: one installs and stamps success, and the other removes
that bundle before it fails.

replaceHandler now returns early only when the target still exists. A
missing target installs again; any other stat error is returned. A stat
per chat is cheap next to the install it skips.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Chats with different BITS_CONFIG_DIR values take different locks in
ensure, but they all build ~/Applications/Bits CLI URL Handler.app
through the same staging path. When two install at once, one renames its
staging copy into place and stamps success. The other then removes that
bundle and fails its rename because its staging copy is gone, so links
stop opening.

installHandler now takes a lock next to the bundle, and holds it while it
stages, replaces and registers the bundle and checks Launch Services. A
busy lock returns false without touching anything, which leaves the
stamp unverified, so the next chat retries, as a busy config lock does.
The bundle lock is taken before any tool runs, so an always-run test
covers the busy case.

Linux needs no such lock: writeFile replaces the desktop entry
atomically, and every writer writes a valid entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@datadog-official datadog-official Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bits Code Review: PASS

More details

The PR adds opt-in macOS deep-link handling through Terminal or iTerm2; the latest commit fixes the shared-bundle concurrency race and reinstalls missing handlers. No reportable issues remain, although native macOS launch behavior is still unvalidated.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit eb89b2d

DavyBello and others added 2 commits December 4, 2026 12:58
On a fresh install, macOS replaces an app's first notification with the
banner that asks whether to allow its notifications. So the applet's
first error, an invalid link or a bits that is gone, never showed.

Both error paths now bring the applet forward and show an alert, with
the same text as before. The applet has no window, so without activate
the alert could open behind other windows. The alert closes after 10
seconds, so the applet still quits. It still never echoes the link and
opens no terminal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When Terminal is not running, a link opened two windows: the one
Terminal opens at launch under its default "On startup, open: New
window", and the one do script creates. The applet now notes whether
Terminal was running. If it was not, the applet waits up to about 3
seconds for that launch window and runs the command in it. A Terminal
set to open nothing at launch still gets a new window, as does a
Terminal that was already running. iTerm2 is unchanged.

handlerVersion goes to 2, so applets registered at version 1 are rebuilt.
The bump covers this change and the switch to alerts for link errors,
which changed the script without one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@datadog-official datadog-official Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bits Code Review: FAIL

The PR adds opt-in macOS deep-link handling with timed error alerts; the earlier bundle race is fixed. The latest startup-window reuse can send link commands into restored SSH sessions or other running programs instead of launching local Bits, and native macOS behavior remains unvalidated.

Open Bits AI session

🤖 Bits Code Review · Commit 5390235

Comment thread internal/deeplink/macapp.go Resolved
Running a link in Terminal's window 1 after a cold start could type the
command into a session that was already busy: a startup window group, or
a restored window whose front tab runs ssh, mosh or a REPL. An extra
window is acceptable; typing into someone's session is not.

The applet now reuses the launch window only when it is provably a fresh
local shell: the only window, with one tab that is not busy and whose
processes are exactly one login and one shell; a second shell may be
running a script. That relies on the busy and
processes properties of Terminal's tab class. It polls for up to about
3 seconds, because the shell's startup files keep the tab busy briefly,
and treats a window that closes mid-check as not reusable. Anything else
gets a new window, as before.

The process check is a plain handler, idleShell, so TestBuildApp checks
it on CI without Terminal. handlerVersion goes to 3, so applets
registered at version 2 are rebuilt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@datadog-official datadog-official Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bits Code Review: PASS

More details

The PR adds opt-in macOS deep-link handling through Terminal or iTerm2, with missing-handler repair. Both reported defects are fixed: concurrent installation is serialized, and startup-window reuse rejects busy sessions; no reportable issues remain, though native macOS behavior is still unvalidated.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 7fc59a2

No release has registered links yet, and registration is opt-in, so
the bumps made while the applet changed only affected test machines.
The version stays at 1 until registration is on by default; after that
it changes whenever the generated handler does. The generated script is
unchanged; only the applet's CFBundleVersion follows the constant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@brebernjak brebernjak left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Approved to unblock this opt-in PR. Left one follow-up on iTerm command delivery. Source review only; no tests or live desktop checks run.

Comment thread internal/deeplink/macapp.go Outdated
iTerm2: ` tell application id "com.googlecode.iterm2"
activate
set newWindow to (create window with default profile)
tell current session of newWindow to write text theCommand

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 iTerm links can send the command to SSH or a REPL. The default profile needn't start a local shell, so write text feeds that process instead of launching Bits. Can we launch a known local command explicitly?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Fixed in 69f1d02 and 2e87f61. iTerm2 no longer types into the profile's session: it uses create window with default profile command, so the profile's own command (ssh, a REPL) never receives the link. The command runs bits through the user's login shell (-l -i -c, then exec the shell), so the environment matches Terminal and the window stays usable. Quoting follows iTerm2's command splitter, and tests check bits receives exactly [deep-link, --, url].

DavyBello and others added 2 commits December 4, 2026 16:33
The iTerm2 applet created a window with the default profile and typed the
command into it. A default profile that runs ssh, a REPL or anything but
a local shell would receive the command as input, the same class of bug
as typing into a busy Terminal tab.

The applet now passes the command to create window with default profile
command, which replaces the profile's command. iTerm2 evaluates that as
an interpolated string, replaces $$NAME$$ placeholders, splits the
result with its own parser and executes the words; with the profile's
"Run command in login shell" setting on, the user's login shell parses
it instead. The command starts /bin/sh
with a fixed script, passing bits and the link as arguments, so neither
is parsed twice. The script runs bits deep-link -- <link> and then
execs the user's login shell, so the window stays open with bits'
output, as in Terminal.

The parser reads single quotes as sh does, except that backslash
escapes apply inside them too, and the interpolation step reads
backslashes as well. The bits path already cannot contain a backslash,
so the existing sh quoting yields one word, and it holds for POSIX
shells and fish when the login shell parses the command. tcsh, nushell
or PowerShell may misparse the bits path there, but links still cannot
inject a command. A bits path with
$$ cannot be registered for iTerm2, because iTerm2 would read it as a
placeholder. A Go port of the parser checks the argv for hostile bits
paths, and the test then runs that argv with /bin/sh and checks bits
gets exactly deep-link -- <link>.

The Terminal variant is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TestITermCommand built its bits paths under the temporary directory,
which on Windows holds backslashes that shellQuote rightly rejects. The
handler only runs on macOS, so on Windows the test checks the split on
a macOS-style path; other systems still run the command with /bin/sh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@datadog-official datadog-official Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bits Code Review: FAIL

The PR adds opt-in macOS deep-link handling and fixes the earlier bundle race and busy-tab reuse. Two issues remain: the new test fails on Windows paths, and direct iTerm2 launches omit shell-initialized configuration and authentication variables.

Open Bits AI session

🤖 Bits Code Review · Commit 69f1d02

Comment thread internal/deeplink/macapp_test.go Resolved
Comment thread internal/deeplink/macapp.go Resolved
iTerm2 runs the command of a new window itself, with the environment of
the GUI session, so bits started without what the user's startup files
export: BITS_CONFIG_DIR, staging settings or a PATH entry. Terminal's do
script runs in a login shell and is not affected.

The iTerm2 command now starts the user's login shell with -l -i -c, so
it reads .zprofile and, as zsh needs -i for it, .zshrc. The inner
command runs bits deep-link -- <link> and then execs the shell as a
login shell, so the window stays open as before. The applet builds the
inner command with the link's quoted form and passes it in one more
quoted form, so it reaches the shell as one -c argument, which sh, bash,
zsh, dash, ksh and fish all parse the same way. The positional script
under /bin/sh goes: fish has no $1.

The shell is read when bits registers: the account's UserShell from
dscl, else SHELL, else /bin/zsh. A candidate counts only if it is
absolute, listed in /etc/shells, quotable, and one of sh, bash, zsh,
fish, dash or ksh; csh and tcsh take -l only alone, and nushell and
PowerShell quote differently; a shell that fails moves on to the next
candidate. The stamp does not record the shell, so a changed login
shell takes effect only when bits registers again, for a new bits path,
a new terminal or a missing handler.

With -i the shell's interactive startup files run before bits, so their
banners show first, and one that execs tmux never runs the command.

AppleScript's quoted form writes ' as '\'', and iTerm2's parser reads a
backslash even inside quotes. The outer quoted form puts every
backslash of the inner command inside quotes, so the inner command must
hold none: on top of the existing ban on backslashes, a bits path or
shell containing ' cannot be registered for iTerm2.

Tests split the command with the Go port of iTerm2's parser, then run
the inner command with every shell installed, for hostile bits paths,
and check bits gets exactly deep-link -- <link> and the login shell
starts after it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@datadog-official datadog-official Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bits Code Review: PASS

More details

The PR adds opt-in macOS deep-link handling through Terminal or iTerm2; iTerm2 now loads the login-shell environment before invoking Bits. The bundle race, busy-tab reuse, Windows test paths, and shell-environment findings are resolved, with no reportable issues remaining; native macOS behavior remains unvalidated.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 2e87f61

The iTerm2 applet has the user's login shell built in, but the stamp did
not record it. A changed or removed login shell kept the old applet
until something else made bits register again, so links could run
through a shell the user no longer has.

prepare now also returns the shell it built into the handler, and
replaceHandler puts it in the stamp it compares, as it does the
terminal. A new shell registers again on the next chat. Only the macOS
iTerm2 handler runs a shell; Terminal, Linux and Windows return "", so
their stamps are unchanged, and a stamp written before this field reads
as "" and still matches. The shell lookup runs on every check of an
iTerm2 registration, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants