Files
magpie/internal/agent/cherrystudio.go
T
yetone d1f8d8aae7 agent: Cherry Studio adds magpie through its providers link (plugins#865)
Cherry Studio (CherryHQ) shows on the Agents page, and with
`magpie cherrystudio`, on macOS, Windows and Linux. Its row is the link
its main process takes, cherrystudio://providers/api-keys?v=1&data=, with
the gateway at <gw>/v1 as an OpenAI-compatible provider named magpie and
the named key agentKeyAt("cherrystudio"). Cherry Studio asks the user to
confirm it. magpie writes nothing into its store. "Added" is read
untouched from its 2.x database (Data/cherrystudio.sqlite, user_provider),
in the default userData and every one boot-config.json moved it to. A
database or boot-config that can't be read, or a 1.x userData (Local
Storage, no database), is unknown. The data is standard base64, because
Cherry Studio swaps raw + and / before parsing and back after. /api/open
lets that link through. aionui's database status is generalized into
dbStatus{has} so both apps share it. Icon: Cherry Studio's own logo, not
cherryin-color (a different product).

Run (mote, at this change on origin/main c66cdbea9; then rebased on
0f04dca6e and run again: vet of agent/gui/cli, Windows vet of agent/gui,
and the Cherry, AionUi, gateway-key and import-link tests, ok):
- gofmt -l clean; go vet ./internal/agent ./internal/gui ./internal/cli;
  GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...
- go test -tags nogui -count=1 ./internal/agent ./internal/gui
  ./internal/cli: agent and cli ok; gui ok but TestCoreScriptBudget, red the
  same on a clean c66cdbea9 (#4526, 1533856 > 1533802)
- node --test import-row.test.cjs i18n-keys.test.cjs: import-row 20/20,
  chromium and webkit, en/zh/zh-TW/ja/de, and 420px wide; i18n-keys red
  only on "a plugin's words are its own", the same on clean c66cdbea9
  (#5332, #5426, #5482). No new strings.
- TestCherryStudioLinkParsedAs2_1_10 runs the link through 2.1.10's own
  parser (copied into testdata) and the renderer's zod checks, with
  gateways whose base64 spells + and /.
- Real try on mote (macOS 27.2, arm64): released Cherry Studio 2.1.10 in a
  sandbox HOME and --user-data-dir, with a sandbox magpie of this tree on
  127.0.0.1:3561 and a fake upstream. `magpie cherrystudio add` opened the
  dialog with base URL http://127.0.0.1:3561/v1 and the key
  magpie-cherrystudio. Add saved it, turned off as every Cherry provider
  is. `magpie cherrystudio` then said added, read while the app ran (WAL).
  Sync models listed fake/fake-1 from the gateway, and adding it turned
  the provider on. A chat got the fake upstream's reply, and magpie usage
  counted it as Cherry Studio's. A link sent while the first-run welcome
  page was up showed no dialog; after "set up later" it did.

Broken by hand, each red, then restored:
- URL-safe base64: TestCherryStudioLinkParsedAs2_1_10 (baseUrl decoded as
  /x~>/v1 and /xy\x7f?/v1)
- no closing quote/slash on the address match: TestCherryStudioHas
  (another port's provider counted)
- the /api/open prefix dropped: TestCherryStudioImportRow
- Cherry Studio dropped from /api/open's app case:
  TestImportLinkNothingOpens

Not tried: a real run on Windows or Linux (detection is unit tests
only); Cherry Studio 1.x, which reads as unknown; a real vendor upstream
(the try used a fake). Full suite not run at push.

Reported-by: mysterysqwq
2026-11-08 19:09:21 +08:00

189 lines
6.1 KiB
Go

package agent
// Cherry Studio (CherryHQ's Electron chat client) keeps its model
// providers in its own SQLite database, so there is nothing for magpie to
// write. It takes a new one through its providers link, which opens
// Settings → Model Provider with a dialog for the user to confirm:
//
// cherrystudio://providers/api-keys?v=1&data=<base64 of {id, baseUrl, apiKey, name, type}>
//
// (handleProvidersProtocolUrl in its main process, 1.x and 2.x alike; 2.x's
// renderer creates the provider in useProviderDeepLinkImport.) So magpie's
// row is that link, the gateway as one OpenAI-compatible provider, and
// whether Cherry Studio has it, read from its database and never written.
import (
"encoding/base64"
"encoding/json"
"errors"
"io/fs"
"net/url"
"os"
"path/filepath"
"sync"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/sessions"
_ "github.com/yetone/magpie/internal/sqlitedb"
)
// CherryStudioScheme begins every Cherry Studio add-provider link.
const CherryStudioScheme = "cherrystudio://providers/api-keys?"
// CherryStudioLink is the link that opens Cherry Studio's add-provider
// dialog with the gateway at gw as an OpenAI-compatible provider named
// magpie, keyed so that its requests are counted as Cherry Studio's.
//
// Cherry Studio reads data as standard base64: before URLSearchParams sees
// the query it turns a raw + into _ and / into -, and back again after, so
// URL-safe base64 (whose - and _ mean + and /) would decode wrong. The
// data is query-escaped, which its URLSearchParams undoes. The base URL
// ends in /v1, as its own example's does; its formatApiHost keeps a URL
// that already has a version, and type openai is its OpenAI chat
// completions endpoint, whose models it lists from <base>/models.
func CherryStudioLink(gw string) string {
b, _ := json.Marshal(struct {
ID string `json:"id"`
BaseURL string `json:"baseUrl"`
APIKey string `json:"apiKey"`
Name string `json:"name"`
Type string `json:"type"`
}{magpieID, gw + "/v1", agentKeyAt("cherrystudio", gw), magpieID, "openai"})
return CherryStudioScheme + "v=1&data=" + url.QueryEscape(base64.StdEncoding.EncodeToString(b))
}
// cherryUserData is Cherry Studio's Electron userData by default
// (~/Library/Application Support/CherryStudio, %APPDATA%\CherryStudio,
// ~/.config/CherryStudio): its package name, CherryStudio.
func cherryUserData() string {
d, err := os.UserConfigDir()
if err != nil {
return ""
}
return filepath.Join(d, "CherryStudio")
}
// cherryDirs is every userData Cherry Studio may use here: the default and
// each one the user moved it to, which it keeps in
// ~/.cherrystudio/boot-config.json under app.user_data_path (one per
// executable). ok is false when that file is there but can't be read.
func cherryDirs(home string) (dirs []string, ok bool) {
if d := cherryUserData(); d != "" {
dirs = append(dirs, d)
}
if home == "" {
return dirs, true
}
b, err := os.ReadFile(filepath.Join(home, ".cherrystudio", "boot-config.json"))
if errors.Is(err, fs.ErrNotExist) {
return dirs, true
}
var cfg struct {
Moved map[string]string `json:"app.user_data_path"`
}
if err != nil || json.Unmarshal(b, &cfg) != nil {
return dirs, false
}
for _, d := range cfg.Moved {
if filepath.IsAbs(d) {
dirs = append(dirs, filepath.Clean(d))
}
}
return dirs, true
}
// cherryDB is where Cherry Studio 2.x keeps its database in userData dir.
func cherryDB(dir string) string { return filepath.Join(dir, "Data", "cherrystudio.sqlite") }
// cherryRan says Cherry Studio has run with userData dir: 2.x's Data
// folder, or Chromium's Local Storage, where 1.x kept its providers.
func cherryRan(dir string) bool {
return isDir(filepath.Join(dir, "Data")) || isDir(filepath.Join(dir, "Local Storage"))
}
// cherryHas reports whether Cherry Studio's database at path has a
// provider whose base URL is the gateway's, read untouched (WAL mode,
// sessions.OpenUntouched). One that can't be read is unknown.
func cherryHas(path, gw string) (has, known bool) {
if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) {
return false, true
} else if err != nil {
return false, false
}
db, done, err := sessions.OpenUntouched(path)
if err != nil {
return false, false
}
defer done()
// endpoint_configs is JSON.stringify'd {"<endpoint>": {"baseUrl": …}};
// the gateway's address is followed by its path or the closing quote,
// so another port that begins with this one's doesn't count
var n int
if err := db.QueryRow(`SELECT count(*) FROM user_provider WHERE instr(endpoint_configs, ?) > 0 OR instr(endpoint_configs, ?) > 0`,
`"`+gw+`/`, `"`+gw+`"`).Scan(&n); err != nil {
return false, false
}
return n > 0, true
}
// cherryStatus reads each userData's database through its own dbStatus.
type cherryStatus struct {
mu sync.Mutex
dirs map[string]*dbStatus
}
// read says whether any of Cherry Studio's databases has the gateway. A
// userData that has run 1.x only (no database) can't be read, so it is
// unknown, as is a database or boot-config that can't be read.
func (s *cherryStatus) read(home, gw string) (has, known bool) {
dirs, known := cherryDirs(home)
for _, d := range dirs {
db := cherryDB(d)
if _, err := os.Stat(db); errors.Is(err, fs.ErrNotExist) {
if cherryRan(d) {
known = false
}
continue
}
s.mu.Lock()
if s.dirs == nil {
s.dirs = map[string]*dbStatus{}
}
st := s.dirs[db]
if st == nil {
st = &dbStatus{has: cherryHas}
s.dirs[db] = st
}
s.mu.Unlock()
h, k := st.read(db, gw)
if h {
return true, true
}
if !k {
known = false
}
}
return false, known
}
func cherryStudio(home string) *Agent {
dir := cherryUserData()
st := &cherryStatus{}
return &Agent{
ID: "cherrystudio", Name: "Cherry Studio", Icon: "cherrystudio-color",
Aliases: []string{"cherry-studio"},
Dir: dir, Path: dir,
detect: func() bool {
dirs, _ := cherryDirs(home)
for _, d := range dirs {
if cherryRan(d) {
return true
}
}
return false
},
Import: func() string { return CherryStudioLink(gateway.URL()) },
Added: func() (bool, bool) { return st.read(home, gateway.URL()) },
}
}