ccswitchlink: a ccswitch:// link that still reaches magpie goes to CC Switch, and so does the scheme (asombrado_a on X)

@asombrado_a (X, 2122995130097713493) has CC Switch and magpie both
installed, and a ccswitch://v1/import link opened magpie. magpie claims
magpie:// only since 03314b25a (v0.1.4455), but v0.1.3981 to v0.1.4454
claimed CC Switch's scheme too, and what they registered stays:
- macOS: Launch Services keeps the old Info.plist's ccswitch claim after
  the bundle is rewritten in place (seen on mote below);
- Windows: HKCU\Software\Classes\ccswitch running magpie.exe;
- Linux: magpie-ccswitch.desktop as the x-scheme-handler/ccswitch default.

The owner's call in 03314b25a stands: magpie doesn't read CC Switch's
links. A ccswitch:// link that reaches magpie anyway is now handed on:
- cli.run, before anything is read, moved or started (Windows, Linux:
  `magpie ccswitch://…`), and the Mac's URL event in gui.Run call
  ccswitchlink.Forward;
- macOS: `open -b com.ccswitch.desktop <link>`, then `lsregister -f` on
  magpie's own bundle, which reads its current Info.plist and drops the
  claim;
- Windows: the handler's program when it isn't this magpie, else
  %LOCALAPPDATA%\Programs\CC Switch\cc-switch.exe (where CC Switch's
  per-user MSI installs it); when the handler ran this magpie the key is
  rewritten as that MSI writes it ("URL:com.ccswitch.desktop protocol",
  URL Protocol, DefaultIcon, shell\open\command "exe" "%1");
- Linux: CC Switch's .desktop entry in the XDG data dirs (its first
  start's cc-switch-handler.desktop with %u first, else the package's
  "CC Switch.desktop", whose Exec has no %u, so the link is appended) is
  run, and a default that is magpie-ccswitch.desktop moves to it; magpie's
  entry is removed while it runs this magpie or a gone binary. Any other
  default is left alone.
- No CC Switch: ErrNotInstalled, nothing opened, the claim kept, so
  magpie opens such a link as it does now (it says it reads magpie://
  links only).

Existing users: nothing changes until a ccswitch:// link reaches magpie.
The first one is opened in CC Switch and the claim goes back, so later
links go to CC Switch directly.

CC Switch's facts come from farion1231/cc-switch (tauri.conf.json's
deep-link schemes ["ccswitch"], wix per-user-main.wxs, lib.rs's
register_all) and its v4.0.35 assets: macOS.zip's Info.plist
(com.ccswitch.desktop, CFBundleURLSchemes ccswitch), the portable zip's
cc-switch.exe, the .deb's "CC Switch.desktop" and /usr/bin/cc-switch.

Run (this tree on d74754970, then again where named after a rebase on
589e4ba6d, which touches none of these files):
- mote: go test -count=1 ./internal/ccswitchlink ./internal/cli
  ./internal/gui ok; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build ok; gofmt -l empty.
- wsl-run (magpie-desktop) and win-run (xiaomi-gpu): go test -count=1
  -v ./internal/ccswitchlink ok (Windows writes a test key of its own,
  Software\Classes\magpie-test-ccswitch-<pid>, removed after).
- Full suite on mica (go test -count=1 -timeout 45m ./..., on
  d74754970): 101 packages ok; reds, all filed and none in a package this
  touches: internal/dirent's watch tests (#7031; red alone on a fresh
  origin/main 589e4ba6d too), TestGatewayModeListsNoOwnSessions (#7064)
  and TestWSLStoppedDistroKept (#7071), both ok alone on mica.
- After the rebase on 589e4ba6d: go vet ./..., GOOS=linux go vet -tags
  nogui ./..., GOOS=windows go vet ./..., go build, gofmt -l on mote ok;
  ./internal/ccswitchlink and ./internal/gui ok on mote; ./internal/cli
  ok on mica. On mote three cli tests reach the 127.0.0.1:3425 an ssh
  port forward holds there (#6223).
- Real, macOS (mote, in ~/runs, cleaned up with lsregister -u): a test
  bundle registered with the old ccswitch claim kept it 5s after its
  Info.plist was rewritten without it; the built Forward then opened
  the real CC Switch v4.0.35 app and the dump showed the claim gone.
  Without CC Switch registered it returned ErrNotInstalled.
- Real, Linux (magpie-desktop, sandbox HOME and XDG dirs): with
  magpie-ccswitch.desktop as the real xdg-mime default, Forward ran
  cc-switch-handler.desktop's Exec with the link and the default was
  cc-switch-handler.desktop after.
- Broken by hand: no lsregister call (darwin), no xdg-mime default
  (linux) and no handBack (windows) each turned their test red.
- GUI suite: not run; no page, app.js or i18n change.

Not tried: a real CC Switch install on Windows (the box's real HKCU
ccswitch key is left alone; the test uses its own key), and a real
CC Switch .deb or AppImage on Linux (its entry was faked with the
package's own bytes).
This commit is contained in:
yetone
2026-11-18 20:07:09 +08:00
parent 389169f761
commit 9314999a4a
12 changed files with 872 additions and 1 deletions
+1 -1
View File
@@ -11,7 +11,7 @@ three.
| Part | Responsibility | Source |
| --- | --- | --- |
| Native host | `Run` starts the Wails v3 app: the tray icon, the panel, the main window, single-instance handover, `magpie://` import links and open at login. `host` implements `Windows` for the API: show and hide, open URLs and folders, copy to the clipboard, fit and tint the panel, and set the text size. A copy on Linux sets PRIMARY before CLIPBOARD, since GTK 3 serves CLIPBOARD empty when PRIMARY is set after it on a compositor with no primary selection (KDE Plasma with middle-click paste off, #1881); on Wayland the copy is read back through the compositor, and one that doesn't read back whole answers `/api/copy` with 501, so the page tries its clipboard API, then the copy command, then says the copy failed with the text to copy by hand (`copy-fallback.test.cjs`). On Windows, Wails reads the screens again on each display change (`WM_DISPLAYCHANGE`, and `WM_SETTINGCHANGE` for the work area) through `w32.GetAllScreens`, which makes a new Win32 callback each time; Go never frees one and throws past about 2000, killing the app and its gateway after hours of display changes (1111_13879 on Discord). `screensWndProc`, the app's `WndProcInterceptor`, takes those messages on Wails' main-thread window first and reads the screens with one callback made once (`allScreens`), then hands them to `Screen.LayoutScreens` as Wails would; see `TestScreensReadFarPastTheCallbackLimit`, `TestDisplayChangesAreReadOnWailsWindowOnly` (Windows) and `TestWailsScreensAreReadOnTheMainThreadWindow`, which fails when a Wails upgrade changes what that relies on. On Windows `appWndProc` also installs a thread-local `WH_CBT` hook (`hookNoActivate`, `noActivateCBT` in `noactivate_windows.go`) on Wails' main thread to turn down `HCBT_ACTIVATE` for hidden windows and windows shown quietly (`showQuietly`, `showMinimised`), and unhooks it (`unhookNoActivate`) when the main-thread window is destroyed or the app shuts down so `ExitProcess`'s FLS cleanup (`msctf!CicFlsCallback`) cannot call back into Go while `runtime.exit` holds `runtime.finlock` (#6705, `TestUnhookNoActivatePreventsExitDeadlock`). | [`app.go`](../../internal/gui/app.go), [`screens_windows.go`](../../internal/gui/screens_windows.go), [`noactivate_windows.go`](../../internal/gui/noactivate_windows.go), [`clipboard_gtk3.go`](../../internal/gui/clipboard_gtk3.go), [`clipboard_gtk3.h`](../../internal/gui/clipboard_gtk3.h), [`mainwindow.go`](../../internal/gui/mainwindow.go), [`traymenu.go`](../../internal/gui/traymenu.go) |
| Native host | `Run` starts the Wails v3 app: the tray icon, the panel, the main window, single-instance handover, `magpie://` import links and open at login. magpie claims `magpie://` only. v0.1.3981 to v0.1.4454 also claimed CC Switch's `ccswitch://` (Info.plist, `HKCU\Software\Classes\ccswitch`, `magpie-ccswitch.desktop`), and a start leaves what they wrote. A `ccswitch://` link that still reaches magpie that way (`magpie ccswitch://…` on Windows and Linux, before anything is read or started; the URL event on the Mac) is opened with CC Switch when it is installed, and the claim goes back to it: Launch Services registers magpie's bundle again from its Info.plist (`lsregister -f`), the per-user handler that runs this magpie is pointed at CC Switch's exe as its MSI writes it, and the desktop default that is `magpie-ccswitch.desktop` goes to CC Switch's entry, with magpie's entry removed while it runs this magpie or a gone one. With no CC Switch the link and the claim are left as they are (`ccswitchlink.ErrNotInstalled`; [`ccswitchlink`](../../internal/ccswitchlink/link.go)). `host` implements `Windows` for the API: show and hide, open URLs and folders, copy to the clipboard, fit and tint the panel, and set the text size. A copy on Linux sets PRIMARY before CLIPBOARD, since GTK 3 serves CLIPBOARD empty when PRIMARY is set after it on a compositor with no primary selection (KDE Plasma with middle-click paste off, #1881); on Wayland the copy is read back through the compositor, and one that doesn't read back whole answers `/api/copy` with 501, so the page tries its clipboard API, then the copy command, then says the copy failed with the text to copy by hand (`copy-fallback.test.cjs`). On Windows, Wails reads the screens again on each display change (`WM_DISPLAYCHANGE`, and `WM_SETTINGCHANGE` for the work area) through `w32.GetAllScreens`, which makes a new Win32 callback each time; Go never frees one and throws past about 2000, killing the app and its gateway after hours of display changes (1111_13879 on Discord). `screensWndProc`, the app's `WndProcInterceptor`, takes those messages on Wails' main-thread window first and reads the screens with one callback made once (`allScreens`), then hands them to `Screen.LayoutScreens` as Wails would; see `TestScreensReadFarPastTheCallbackLimit`, `TestDisplayChangesAreReadOnWailsWindowOnly` (Windows) and `TestWailsScreensAreReadOnTheMainThreadWindow`, which fails when a Wails upgrade changes what that relies on. On Windows `appWndProc` also installs a thread-local `WH_CBT` hook (`hookNoActivate`, `noActivateCBT` in `noactivate_windows.go`) on Wails' main thread to turn down `HCBT_ACTIVATE` for hidden windows and windows shown quietly (`showQuietly`, `showMinimised`), and unhooks it (`unhookNoActivate`) when the main-thread window is destroyed or the app shuts down so `ExitProcess`'s FLS cleanup (`msctf!CicFlsCallback`) cannot call back into Go while `runtime.exit` holds `runtime.finlock` (#6705, `TestUnhookNoActivatePreventsExitDeadlock`). | [`app.go`](../../internal/gui/app.go), [`screens_windows.go`](../../internal/gui/screens_windows.go), [`noactivate_windows.go`](../../internal/gui/noactivate_windows.go), [`clipboard_gtk3.go`](../../internal/gui/clipboard_gtk3.go), [`clipboard_gtk3.h`](../../internal/gui/clipboard_gtk3.h), [`mainwindow.go`](../../internal/gui/mainwindow.go), [`traymenu.go`](../../internal/gui/traymenu.go) |
| Backend | `startBackend` starts the gateway this process serves, unless another magpie already serves it. In that case this process only shows the other one's status (`gw` is nil), and `watchGateway` looks at it again every 15 s (`gatewayWatch`). A magpie of another version there (`otherServes` in `gateway_older.go`) is told the page as `gatewayOther` in `/api/state` and said over the Agents list (`gatewaySkewLine` in `plugins/gateway/client.js`), in the panel and the window: pi got 404 for a model the newer app had written it while an older copy of the app kept the gateway, and only the Gateway page said so (matrix0487 on Discord). An older released copy of the app (`serves` app or tray, with a pid) is this app's own predecessor: once its `/v1/magpie/concurrency` says nothing is in flight (`gateway.ServedBusy`; unknown is never idle) the app quits it as the Gateway page's button does (`quitMagpieOnPort`, a magpie only) and serves the gateway, so no stream is cut; at most three times a run (`replaceMost`), and a quit that fails is left to the button. Any other (magpie serve or the service, `magpie web`, a TUI, a newer magpie, a build of its own) is left running, with what to do; a dev build of this magpie says nothing. A request that starts between the idle read and the quit gets the older app's short drain. See `TestAppReplacesItsOlderGatewayOnceIdle`, `TestGatewaySkewOfAnotherIsSaidNotQuit` and `gateway-skew.test.cjs`. `magpie serve` (the service's, launchd's `com.yetone.magpie.serve` or systemd's) does the same beside a magpie serving or another program holding the port: before it moves or starts anything (`startUp`), it waits, looking every 15 s, and serves once the port is free (`awaitGatewayFree` in [`serve_wait.go`](../../internal/cli/serve_wait.go); `--web` excepted, which shows the other one). Before, it ran the start-up moves, the plugin host and every account's model fetch, failed to bind, exited 1 and was started again by the service, 6,035 times in two days with a 279MB serve.log and requests 504 behind it (#4938, `TestServeWaitsForTheGatewayBeforeStartingUp`). `stopServing` drains requests in flight. A restart to update can hand the listening socket to the new version instead (see [A restart to update hands the gateway over](#a-restart-to-update-hands-the-gateway-over)). | [`backend.go`](../../internal/gui/backend.go), [`gateway_older.go`](../../internal/gui/gateway_older.go) |
| API and assets | `Handler` serves `assets/` (embedded with `//go:embed assets`) and the `/api/*` routes, such as `/api/state`, `/api/set`, `/api/agents/{action}/{id}` and `/api/agents/restart/{id}` (a desktop app's Restart, after the row's confirm). `held` lets one API request's reads share one catalog build (`provider.Hold`), and drops it after any write. `revalidated` and `versionedPage` name each script by its content hash, so a cache never serves an old `app.js` under a new page; a file asked for under its current hash (`?v=`) is cached for good (`immutable`), anything else is revalidated by its ETag. | [`api.go`](../../internal/gui/api.go) |
| Settings from the terminal | `POST /api/settings` saves through `settingsapi.Apply` (`internal/settingsapi`, outside the GUI so the `nogui` build has it): the carry of keys a page leaves out (`Merge`), the vision, image and searcher checks, `settings.Save`'s own checks, and `catalog.Touched`. `magpie settings list\|get\|set\|reset` (#4745) builds the same body with `settingsapi.Body` (the whole file with one key changed, so a key the save keeps when it isn't sent is set even to off) and calls the same `Apply`; a refused value writes nothing. `settingsapi.Keys` names what the save writes; `TestKeysAreWhatTheSaveWrites` fails when a field of `settings.Settings` is saved without it, `TestSettingsCLISetsWhatTheWindowSaves` when a key the page's `savePrefs` sends isn't one, and `TestEveryRouteHasACommandOrIsNamed` when an `/api` route has neither a command nor a reason in `notYet` (`internal/cli/settings_parity_test.go`). The running app's in-process follow-ups (fonts, Dock, tray menu, alerts, language, update check) run only from the window's save; a change from the terminal is read from the file. | [`internal/settingsapi/settingsapi.go`](../../internal/settingsapi/settingsapi.go), [`settings_cli.go`](../../internal/cli/settings_cli.go) |
+47
View File
@@ -0,0 +1,47 @@
// Package ccswitchlink hands CC Switch's own ccswitch:// links back to it.
//
// magpie v0.1.3981 to v0.1.4454 claimed ccswitch:// on every system
// (889758605), and 03314b25a stopped that. A claim an older magpie made
// can still be there: macOS's Launch Services remembering the old
// Info.plist, HKCU\Software\Classes\ccswitch on Windows, and
// magpie-ccswitch.desktop as the desktop's default on Linux. A link that
// arrives that way is opened with CC Switch when it is installed, and the
// claim is given back to it, so the next link goes there directly
// (asombrado_a on X: with both apps installed, a ccswitch:// import opened
// magpie).
//
// What is known of CC Switch comes from its own source and releases
// (farion1231/cc-switch, v4.0.35): bundle id com.ccswitch.desktop with
// CFBundleURLSchemes ccswitch; the per-user MSI installs
// %LOCALAPPDATA%\Programs\CC Switch\cc-switch.exe and writes
// HKCU\Software\Classes\ccswitch to run it with "%1"; on Linux the package
// has "CC Switch.desktop" (MimeType=x-scheme-handler/ccswitch, Exec with no
// %u) and the app writes ~/.local/share/applications/cc-switch-handler.desktop
// (Exec=… %u) and makes it the default on its first start.
package ccswitchlink
import (
"errors"
"strings"
)
// Scheme is CC Switch's URL scheme.
const Scheme = "ccswitch"
// ErrNotInstalled is Forward's answer when no CC Switch is found.
var ErrNotInstalled = errors.New("CC Switch isn't installed; magpie opens magpie:// links only")
// Is reports whether link is a ccswitch:// link.
func Is(link string) bool {
return strings.HasPrefix(strings.ToLower(link), Scheme+":")
}
// Forward opens link with CC Switch and gives back the claim on the scheme
// an older magpie made. ErrNotInstalled when there is no CC Switch: the
// link is then left alone, and so is the claim.
func Forward(link string) error {
if !Is(link) {
return errors.New("not a ccswitch:// link")
}
return forward(link)
}
+65
View File
@@ -0,0 +1,65 @@
package ccswitchlink
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/yetone/magpie/internal/proc"
)
// bundleID is CC Switch's (its tauri.conf.json "identifier").
const bundleID = "com.ccswitch.desktop"
// lsregister edits Launch Services' list of apps; -f registers a bundle
// again from its Info.plist as it is now.
const lsregister = "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"
// run runs a command to its end; tests stand in for it.
var run = func(name string, args ...string) error {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
out, err := proc.CommandContext(ctx, name, args...).CombinedOutput()
if err != nil {
return fmt.Errorf("%s: %w: %s", name, err, strings.TrimSpace(string(out)))
}
return nil
}
// executable is this program's path; tests stand in for it.
var executable = os.Executable
// forward has Launch Services open the link with CC Switch by its bundle
// id, which fails when no app has that id. Then magpie's own bundle is
// registered again: its Info.plist claims magpie:// only since 03314b25a,
// so Launch Services forgets the ccswitch:// claim it remembered.
func forward(link string) error {
if err := run("open", "-b", bundleID, link); err != nil {
return fmt.Errorf("%w (%v)", ErrNotInstalled, err)
}
if b := bundle(); b != "" {
_ = run(lsregister, "-f", b)
}
return nil
}
// bundle is the .app this executable is in, "" outside one.
func bundle() string {
exe, err := executable()
if err != nil {
return ""
}
if r, err := filepath.EvalSymlinks(exe); err == nil {
exe = r
}
macos := filepath.Dir(exe)
contents := filepath.Dir(macos)
app := filepath.Dir(contents)
if filepath.Base(macos) != "MacOS" || filepath.Base(contents) != "Contents" || filepath.Ext(app) != ".app" {
return ""
}
return app
}
+61
View File
@@ -0,0 +1,61 @@
package ccswitchlink
import (
"errors"
"slices"
"strings"
"testing"
)
func stubDarwin(t *testing.T, exe string, openErr error) *[]string {
t.Helper()
var calls []string
r, e := run, executable
t.Cleanup(func() { run, executable = r, e })
run = func(name string, args ...string) error {
calls = append(calls, name+" "+strings.Join(args, " "))
if name == "open" {
return openErr
}
return nil
}
executable = func() (string, error) { return exe, nil }
return &calls
}
const link = "ccswitch://v1/import?resource=provider&app=claude&name=Relay&endpoint=https%3A%2F%2Fapi.example.com&apiKey=sk-x"
// The link goes to CC Switch by its bundle id, and magpie's bundle is
// registered again, which drops the claim an older Info.plist made.
func TestForwardOpensCCSwitchAndRegistersMagpieAgain(t *testing.T) {
calls := stubDarwin(t, "/Applications/magpie.app/Contents/MacOS/magpie", nil)
if err := Forward(link); err != nil {
t.Fatal(err)
}
want := []string{"open -b com.ccswitch.desktop " + link, lsregister + " -f /Applications/magpie.app"}
if !slices.Equal(*calls, want) {
t.Fatalf("calls %q, want %q", *calls, want)
}
}
// No CC Switch: Launch Services is told nothing more.
func TestForwardWithoutCCSwitch(t *testing.T) {
calls := stubDarwin(t, "/Applications/magpie.app/Contents/MacOS/magpie", errors.New("Unable to find application named 'com.ccswitch.desktop'"))
if err := Forward(link); !errors.Is(err, ErrNotInstalled) {
t.Fatalf("err %v, want ErrNotInstalled", err)
}
if len(*calls) != 1 {
t.Fatalf("calls %q: Launch Services was told more", *calls)
}
}
// A magpie outside a bundle (go run, the CLI on PATH) registers nothing.
func TestForwardOutsideABundle(t *testing.T) {
calls := stubDarwin(t, "/usr/local/bin/magpie", nil)
if err := Forward(link); err != nil {
t.Fatal(err)
}
if len(*calls) != 1 {
t.Fatalf("calls %q", *calls)
}
}
+232
View File
@@ -0,0 +1,232 @@
package ccswitchlink
import (
"os"
"path/filepath"
"slices"
"strings"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/proc"
)
const mime = "x-scheme-handler/" + Scheme
// magpieEntry is the desktop entry magpie v0.1.3981 to v0.1.4454 wrote for
// ccswitch:// and made the default when it had none.
const magpieEntry = "magpie-ccswitch.desktop"
// executable is this program's path; tests stand in for it.
var executable = os.Executable
// start starts CC Switch; tests stand in for it.
var start = func(argv []string) error { return proc.StartReaped(proc.Command(argv[0], argv[1:]...)) }
// forward runs the Exec of CC Switch's desktop entry with the link. Then,
// when the desktop's default for ccswitch:// is magpie's entry, that entry
// goes and CC Switch's is made the default.
func forward(link string) error {
id, exec := entry()
if id == "" {
return ErrNotInstalled
}
argv := expand(exec, link)
if len(argv) == 0 {
return ErrNotInstalled
}
if err := start(argv); err != nil {
return err
}
out, _ := proc.Command("xdg-mime", "query", "default", mime).Output()
if strings.TrimSpace(string(out)) != magpieEntry {
return nil
}
dir := filepath.Join(dataHome(), "applications")
if ours(filepath.Join(dir, magpieEntry)) {
_ = os.Remove(filepath.Join(dir, magpieEntry))
_ = proc.Command("update-desktop-database", dir).Run()
}
return proc.Command("xdg-mime", "default", id, mime).Run()
}
// dataHome is $XDG_DATA_HOME, or ~/.local/share without it.
func dataHome() string {
if d := appdir.Getenv("XDG_DATA_HOME"); d != "" {
return d
}
home, _ := os.UserHomeDir()
return filepath.Join(home, ".local", "share")
}
// dataDirs are the folders desktop entries are looked up in, the user's
// first.
func dataDirs() []string {
dirs := []string{dataHome()}
sys := appdir.Getenv("XDG_DATA_DIRS")
if sys == "" {
sys = "/usr/local/share:/usr/share"
}
for _, d := range filepath.SplitList(sys) {
if d != "" && !slices.Contains(dirs, d) {
dirs = append(dirs, d)
}
}
return dirs
}
// entry is the id and Exec of the desktop entry that handles ccswitch://
// other than magpie's: one whose Exec takes a URL (cc-switch-handler.desktop)
// before one that doesn't ("CC Switch.desktop" of the package, whose Exec
// is then given the link as its last argument). An entry earlier in the
// data folders hides one of the same id later.
func entry() (id, exec string) {
seen := map[string]bool{}
var plain, plainExec string
for _, d := range dataDirs() {
files, _ := filepath.Glob(filepath.Join(d, "applications", "*.desktop"))
for _, f := range files {
name := filepath.Base(f)
if seen[name] {
continue
}
seen[name] = true
if strings.HasPrefix(name, "magpie") {
continue
}
x, ok := handles(f)
if !ok {
continue
}
if strings.Contains(x, "%u") || strings.Contains(x, "%U") {
return name, x
}
if plain == "" {
plain, plainExec = name, x
}
}
}
return plain, plainExec
}
// handles is the Exec of a desktop entry that lists ccswitch:// in its
// MimeType and isn't hidden.
func handles(path string) (string, bool) {
b, err := os.ReadFile(path)
if err != nil {
return "", false
}
var exec string
claims, in := false, false
for _, l := range strings.Split(string(b), "\n") {
l = strings.TrimSpace(l)
if strings.HasPrefix(l, "[") {
in = l == "[Desktop Entry]"
continue
}
if !in {
continue
}
k, v, ok := strings.Cut(l, "=")
if !ok {
continue
}
switch strings.TrimSpace(k) {
case "Exec":
exec = strings.TrimSpace(v)
case "MimeType":
claims = slices.Contains(strings.Split(v, ";"), mime)
case "Hidden":
if strings.TrimSpace(v) == "true" {
return "", false
}
}
}
return exec, claims && exec != ""
}
// expand is an Exec line as arguments, with the link for %u, %U, %f or
// %F, or as the last argument when it has none of them. Other field codes
// go, and %% is a %.
func expand(exec, link string) []string {
var argv []string
put := false
for _, w := range words(exec) {
switch w {
case "%u", "%U", "%f", "%F":
argv = append(argv, link)
put = true
continue
case "%i", "%c", "%k":
continue
}
var b strings.Builder
for i := 0; i < len(w); i++ {
if w[i] == '%' && i+1 < len(w) {
i++
if w[i] == '%' {
b.WriteByte('%')
}
continue
}
b.WriteByte(w[i])
}
argv = append(argv, b.String())
}
if len(argv) > 0 && !put {
argv = append(argv, link)
}
return argv
}
// words splits an Exec line as the Desktop Entry spec quotes it: double
// quotes around an argument, a backslash before ", `, $ or \ inside them.
func words(s string) []string {
var out []string
var b strings.Builder
quoted, have := false, false
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case quoted && c == '\\' && i+1 < len(s):
i++
b.WriteByte(s[i])
case c == '"':
quoted = !quoted
have = true
case !quoted && (c == ' ' || c == '\t'):
if have {
out = append(out, b.String())
b.Reset()
have = false
}
default:
b.WriteByte(c)
have = true
}
}
if have {
out = append(out, b.String())
}
return out
}
// ours reports whether a desktop entry runs this executable, or one that
// is gone: magpie's own, not another magpie's.
func ours(path string) bool {
b, err := os.ReadFile(path)
if err != nil {
return false
}
self, _ := executable()
for _, l := range strings.Split(string(b), "\n") {
if x, ok := strings.CutPrefix(l, "Exec="); ok {
run := strings.TrimSuffix(x, " %u")
if run == self {
return true
}
_, err := os.Stat(run)
return os.IsNotExist(err)
}
}
return false
}
+174
View File
@@ -0,0 +1,174 @@
package ccswitchlink
import (
"errors"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/testenv"
)
const link = "ccswitch://v1/import?resource=provider&app=claude&name=Relay&apiKey=sk-x"
// fakeTools puts update-desktop-database and an xdg-mime that keeps the
// default it is given and answers `query default` with it.
func fakeTools(t *testing.T, root, def string) string {
t.Helper()
bin := filepath.Join(root, "bin")
if err := os.MkdirAll(bin, 0o755); err != nil {
t.Fatal(err)
}
state := filepath.Join(root, "default")
if def != "" {
write(t, state, def+"\n")
}
t.Setenv("CCSWITCH_TEST_DEFAULT", state)
t.Setenv("PATH", bin)
testenv.Program(t, filepath.Join(bin, "update-desktop-database"), "#!/bin/sh\nexit 0\n")
testenv.Program(t, filepath.Join(bin, "xdg-mime"), "#!/bin/sh\n"+
`[ "$1" = query ] && { [ -f "$CCSWITCH_TEST_DEFAULT" ] && read -r v < "$CCSWITCH_TEST_DEFAULT" && echo "$v"; exit 0; }`+"\n"+
`[ "$1" = default ] && [ "$3" = x-scheme-handler/ccswitch ] && echo "$2" > "$CCSWITCH_TEST_DEFAULT"`+"\n"+
"exit 0\n")
return state
}
func write(t *testing.T, path, s string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(s), 0o644); err != nil {
t.Fatal(err)
}
}
// pkgEntry is what CC Switch v4.0.35's .deb installs, byte for byte;
// handlerEntry is the kind the app writes on its first start.
const (
pkgEntry = "[Desktop Entry]\nCategories=\nComment=All-in-One Assistant for Claude Code, Codex & Gemini CLI\nExec=cc-switch\nStartupWMClass=cc-switch\nIcon=cc-switch\nName=CC Switch\nTerminal=false\nType=Application\nMimeType=x-scheme-handler/ccswitch"
handlerEntry = "[Desktop Entry]\nType=Application\nName=CC Switch\nExec=\"/opt/CC Switch/cc-switch\" %u\nMimeType=x-scheme-handler/ccswitch\nNoDisplay=true\n"
)
type setup struct {
data, def string
started *[][]string
}
func linuxSetup(t *testing.T, def string, handler, pkg, magpie bool) setup {
t.Helper()
root := t.TempDir()
s := setup{data: filepath.Join(root, "data")}
sys := filepath.Join(root, "sys")
t.Setenv("XDG_DATA_HOME", s.data)
t.Setenv("XDG_DATA_DIRS", sys)
s.def = fakeTools(t, root, def)
self := filepath.Join(root, "magpie")
write(t, self, "")
e, st := executable, start
t.Cleanup(func() { executable, start = e, st })
executable = func() (string, error) { return self, nil }
var started [][]string
s.started = &started
start = func(argv []string) error { started = append(started, argv); return nil }
if handler {
write(t, filepath.Join(s.data, "applications", "cc-switch-handler.desktop"), handlerEntry)
}
if pkg {
write(t, filepath.Join(sys, "applications", "CC Switch.desktop"), pkgEntry)
}
if magpie {
// as magpie v0.1.3981 to v0.1.4454 wrote it
write(t, filepath.Join(s.data, "applications", magpieEntry), "[Desktop Entry]\nType=Application\nName=magpie (ccswitch:// links)\nExec="+self+" %u\nNoDisplay=true\nMimeType=x-scheme-handler/ccswitch;\nTerminal=false\n")
}
return s
}
func (s setup) defaultIs() string {
b, _ := os.ReadFile(s.def)
return strings.TrimSpace(string(b))
}
func (s setup) magpieEntry() bool {
_, err := os.Stat(filepath.Join(s.data, "applications", magpieEntry))
return err == nil
}
// The default an older magpie took goes to CC Switch's handler, which gets
// the link, and magpie's entry goes.
func TestForwardHandsTheDefaultBack(t *testing.T) {
s := linuxSetup(t, magpieEntry, true, true, true)
if err := Forward(link); err != nil {
t.Fatal(err)
}
if len(*s.started) != 1 || !slices.Equal((*s.started)[0], []string{"/opt/CC Switch/cc-switch", link}) {
t.Fatalf("started %q", *s.started)
}
if got := s.defaultIs(); got != "cc-switch-handler.desktop" {
t.Fatalf("default %q", got)
}
if s.magpieEntry() {
t.Fatal("magpie's ccswitch entry stayed")
}
}
// Only the package's entry, whose Exec takes no URL: the link is its last
// argument.
func TestForwardToThePackagesEntry(t *testing.T) {
s := linuxSetup(t, magpieEntry, false, true, true)
if err := Forward(link); err != nil {
t.Fatal(err)
}
if len(*s.started) != 1 || !slices.Equal((*s.started)[0], []string{"cc-switch", link}) {
t.Fatalf("started %q", *s.started)
}
if got := s.defaultIs(); got != "CC Switch.desktop" {
t.Fatalf("default %q", got)
}
}
// A default that isn't magpie's is the user's or CC Switch's: left alone,
// and so is magpie's entry.
func TestForwardLeavesAnotherDefault(t *testing.T) {
s := linuxSetup(t, "other.desktop", true, false, true)
if err := Forward(link); err != nil {
t.Fatal(err)
}
if len(*s.started) != 1 {
t.Fatalf("started %q", *s.started)
}
if got := s.defaultIs(); got != "other.desktop" {
t.Fatalf("default %q", got)
}
if !s.magpieEntry() {
t.Fatal("magpie's entry went")
}
}
// No CC Switch: nothing is started and the claim stays.
func TestForwardWithoutCCSwitch(t *testing.T) {
s := linuxSetup(t, magpieEntry, false, false, true)
if err := Forward(link); !errors.Is(err, ErrNotInstalled) {
t.Fatalf("err %v", err)
}
if len(*s.started) != 0 || s.defaultIs() != magpieEntry || !s.magpieEntry() {
t.Fatalf("started %q, default %q, entry %v", *s.started, s.defaultIs(), s.magpieEntry())
}
}
func TestExpand(t *testing.T) {
for exec, want := range map[string][]string{
`cc-switch`: {"cc-switch", link},
`/usr/bin/cc-switch %u`: {"/usr/bin/cc-switch", link},
`"/opt/CC Switch/cc-switch" %U`: {"/opt/CC Switch/cc-switch", link},
`env A=1 cc-switch --x %i %c %k %u`: {"env", "A=1", "cc-switch", "--x", link},
`sh -c "echo \"a\$b\\\\\" 100%%" %u`: {"sh", "-c", `echo "a$b\\" 100%`, link},
`"/home/u/Apps/CC-Switch.AppImage"`: {"/home/u/Apps/CC-Switch.AppImage", link},
} {
if got := expand(exec, link); !slices.Equal(got, want) {
t.Errorf("expand(%q) = %q, want %q", exec, got, want)
}
}
}
+5
View File
@@ -0,0 +1,5 @@
//go:build !darwin && !windows && !linux
package ccswitchlink
func forward(string) error { return ErrNotInstalled }
+111
View File
@@ -0,0 +1,111 @@
package ccswitchlink
import (
"os"
"path/filepath"
"strings"
"golang.org/x/sys/windows/registry"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/proc"
)
// schemeKey is the per-user handler of ccswitch://, which both CC Switch's
// MSI and an older magpie wrote; tests point it elsewhere.
var schemeKey = `Software\Classes\ccswitch`
// executable is this program's path; tests stand in for it.
var executable = os.Executable
// start starts CC Switch on the link; tests stand in for it.
var start = func(exe, link string) error { return proc.StartReaped(proc.Command(exe, link)) }
// forward runs CC Switch with the link as its argument, as the handler its
// MSI writes does ("…cc-switch.exe" "%1"). Then a handler that runs this
// magpie is pointed at CC Switch, as its MSI writes it.
func forward(link string) error {
self, _ := executable()
cmd := handler()
exe := ccSwitch(cmd, self, appdir.Getenv("LOCALAPPDATA"))
if exe == "" {
return ErrNotInstalled
}
if err := start(exe, link); err != nil {
return err
}
if self != "" && samePath(cmd, self) {
return handBack(exe)
}
return nil
}
// ccSwitch is CC Switch's executable: the scheme's handler when it runs a
// program other than this one that is there, or where CC Switch's MSI
// installs it. "" when neither is.
func ccSwitch(cmd, self, localAppData string) string {
if cmd != "" && !samePath(cmd, self) && exists(cmd) {
return cmd
}
if localAppData != "" {
if p := filepath.Join(localAppData, "Programs", "CC Switch", "cc-switch.exe"); exists(p) {
return p
}
}
return ""
}
// handler is the program the per-user ccswitch:// handler runs, "" when
// there is none.
func handler() string {
k, err := registry.OpenKey(registry.CURRENT_USER, schemeKey+`\shell\open\command`, registry.QUERY_VALUE)
if err != nil {
return ""
}
defer k.Close()
v, _, _ := k.GetStringValue("")
return commandExe(v)
}
// commandExe is the program of a shell\open\command value: the quoted
// first word, or the first word.
func commandExe(v string) string {
v = strings.TrimSpace(v)
if rest, ok := strings.CutPrefix(v, `"`); ok {
exe, _, _ := strings.Cut(rest, `"`)
return exe
}
exe, _, _ := strings.Cut(v, " ")
return exe
}
// handBack writes the handler as CC Switch's MSI does (its
// wix/per-user-main.wxs).
func handBack(exe string) error {
k, _, err := registry.CreateKey(registry.CURRENT_USER, schemeKey, registry.SET_VALUE)
if err != nil {
return err
}
defer k.Close()
_ = k.SetStringValue("", "URL:com.ccswitch.desktop protocol")
_ = k.SetStringValue("URL Protocol", "")
if icon, _, err := registry.CreateKey(k, `DefaultIcon`, registry.SET_VALUE); err == nil {
_ = icon.SetStringValue("", `"`+exe+`",0`)
icon.Close()
}
cmd, _, err := registry.CreateKey(k, `shell\open\command`, registry.SET_VALUE)
if err != nil {
return err
}
defer cmd.Close()
return cmd.SetStringValue("", `"`+exe+`" "%1"`)
}
func samePath(a, b string) bool {
return a != "" && b != "" && strings.EqualFold(filepath.Clean(a), filepath.Clean(b))
}
func exists(p string) bool {
fi, err := os.Stat(p)
return err == nil && !fi.IsDir()
}
+130
View File
@@ -0,0 +1,130 @@
package ccswitchlink
import (
"errors"
"fmt"
"os"
"path/filepath"
"testing"
"golang.org/x/sys/windows/registry"
)
const link = "ccswitch://v1/import?resource=provider&app=claude&name=Relay&apiKey=sk-x"
type winSetup struct {
self, cc string
started *[][2]string
}
func touch(t *testing.T, p string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, nil, 0o644); err != nil {
t.Fatal(err)
}
}
// winForward points the handler at a key of the test's own, so the user's
// ccswitch:// handler is never read or written.
func winForward(t *testing.T, handler func(self string) string, installed bool) winSetup {
t.Helper()
root := t.TempDir()
s := winSetup{self: filepath.Join(root, "magpie.exe"), cc: filepath.Join(root, "local", "Programs", "CC Switch", "cc-switch.exe")}
touch(t, s.self)
if installed {
touch(t, s.cc)
}
t.Setenv("LOCALAPPDATA", filepath.Join(root, "local"))
k, e, st := schemeKey, executable, start
schemeKey = fmt.Sprintf(`Software\Classes\magpie-test-ccswitch-%d`, os.Getpid())
t.Cleanup(func() {
for _, sub := range []string{`\shell\open\command`, `\shell\open`, `\shell`, `\DefaultIcon`, ``} {
_ = registry.DeleteKey(registry.CURRENT_USER, schemeKey+sub)
}
schemeKey, executable, start = k, e, st
})
executable = func() (string, error) { return s.self, nil }
var started [][2]string
s.started = &started
start = func(exe, l string) error { started = append(started, [2]string{exe, l}); return nil }
if v := handler(s.self); v != "" {
c, _, err := registry.CreateKey(registry.CURRENT_USER, schemeKey+`\shell\open\command`, registry.SET_VALUE)
if err != nil {
t.Fatal(err)
}
_ = c.SetStringValue("", v)
c.Close()
}
return s
}
func command() string {
k, err := registry.OpenKey(registry.CURRENT_USER, schemeKey+`\shell\open\command`, registry.QUERY_VALUE)
if err != nil {
return ""
}
defer k.Close()
v, _, _ := k.GetStringValue("")
return v
}
// The handler an older magpie wrote runs this magpie: CC Switch, where its
// MSI installs it, gets the link and the handler.
func TestForwardHandsTheHandlerBack(t *testing.T) {
s := winForward(t, func(self string) string { return `"` + self + `" "%1"` }, true)
if err := Forward(link); err != nil {
t.Fatal(err)
}
if len(*s.started) != 1 || (*s.started)[0] != [2]string{s.cc, link} {
t.Fatalf("started %q", *s.started)
}
if got, want := command(), `"`+s.cc+`" "%1"`; got != want {
t.Fatalf("handler %q, want %q", got, want)
}
}
// CC Switch's own handler, installed elsewhere: it gets the link, and the
// handler is left as it is.
func TestForwardToTheHandlersProgram(t *testing.T) {
var other string
s := winForward(t, func(self string) string {
other = filepath.Join(filepath.Dir(self), "elsewhere", "cc-switch.exe")
touch(t, other)
return `"` + other + `" "%1"`
}, true)
if err := Forward(link); err != nil {
t.Fatal(err)
}
if len(*s.started) != 1 || (*s.started)[0] != [2]string{other, link} {
t.Fatalf("started %q", *s.started)
}
if got := command(); got != `"`+other+`" "%1"` {
t.Fatalf("handler rewritten: %q", got)
}
}
// No CC Switch: nothing started, magpie's handler stays.
func TestForwardWithoutCCSwitch(t *testing.T) {
s := winForward(t, func(self string) string { return `"` + self + `" "%1"` }, false)
if err := Forward(link); !errors.Is(err, ErrNotInstalled) {
t.Fatalf("err %v", err)
}
if len(*s.started) != 0 || command() != `"`+s.self+`" "%1"` {
t.Fatalf("started %q, handler %q", *s.started, command())
}
}
func TestCommandExe(t *testing.T) {
for v, want := range map[string]string{
`"C:\Users\u\AppData\Local\Programs\CC Switch\cc-switch.exe" "%1"`: `C:\Users\u\AppData\Local\Programs\CC Switch\cc-switch.exe`,
`C:\x\cc-switch.exe "%1"`: `C:\x\cc-switch.exe`,
``: ``,
} {
if got := commandExe(v); got != want {
t.Errorf("commandExe(%q) = %q", v, got)
}
}
}
+28
View File
@@ -0,0 +1,28 @@
package ccswitchlink
import (
"errors"
"testing"
"github.com/yetone/magpie/internal/testenv"
)
// The tests run in a home of their own, never the user's real files.
func TestMain(m *testing.M) { testenv.Main(m) }
func TestIs(t *testing.T) {
for l, want := range map[string]bool{
"ccswitch://v1/import?resource=provider&app=claude&name=x": true,
"CCSwitch://v1/import": true,
"magpie://import?preset=x": false,
"https://ccswitch.io": false,
"": false,
} {
if Is(l) != want {
t.Errorf("Is(%q) = %v", l, !want)
}
}
if err := Forward("magpie://import?preset=x"); err == nil || errors.Is(err, ErrNotInstalled) {
t.Fatalf("a magpie:// link was taken: %v", err)
}
}
+7
View File
@@ -18,6 +18,7 @@ import (
"github.com/yetone/magpie/internal/backup"
"github.com/yetone/magpie/internal/browsermcp"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/ccswitchlink"
"github.com/yetone/magpie/internal/claudebridge"
"github.com/yetone/magpie/internal/claudecode"
"github.com/yetone/magpie/internal/claudetui"
@@ -366,6 +367,12 @@ func run(args []string) error {
fmt.Println(strings.TrimRight(helpFor(args), "\n"))
return nil
}
// a ccswitch:// link an older magpie's claim on CC Switch's scheme
// handed over (Windows, Linux): CC Switch opens it and has its scheme
// back (ccswitchlink), and nothing here is read, moved or started
if len(args) > 0 && ccswitchlink.Is(args[0]) {
return ccswitchlink.Forward(args[0])
}
if len(args) > 0 && args[0] == "healthcheck" {
return healthcheck(args[1:]) // every few seconds in a container: nothing else
}
+11
View File
@@ -23,6 +23,7 @@ import (
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/autostart"
"github.com/yetone/magpie/internal/ccswitchlink"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/library"
"github.com/yetone/magpie/internal/omarchy"
@@ -774,6 +775,16 @@ func Run(version string, showMain bool, link string) error {
// Windows and Linux also report the start's own link as an event.
var skip sync.Once
h.app.Event.OnApplicationEvent(events.Common.ApplicationLaunchedWithUrl, func(e *application.ApplicationEvent) {
// a ccswitch:// link the Mac's Launch Services still sends here, from
// an older magpie's claim: CC Switch opens it and has its scheme back
if l := e.Context().URL(); ccswitchlink.Is(l) {
go func() {
if err := ccswitchlink.Forward(l); err != nil {
log.Println("ccswitch:// link:", err)
}
}()
return
}
u := ImportLink([]string{e.Context().URL()})
dup := false
if u == link {