Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

app: add claude desktop app (#17899)

Parth Sareen30546d1fd481
diff --git a/anthropic/anthropic.go b/anthropic/anthropic.go
index 08a744162..60cd78dd6 100755
--- a/anthropic/anthropic.go
+++ b/anthropic/anthropic.go
@@ -1075,7 +1075,7 @@ type CountTokensRequest struct {
// EstimateInputTokens estimates input tokens from a MessagesRequest (reuses CountTokensRequest logic)
func EstimateInputTokens(req MessagesRequest) int {
- return estimateTokens(CountTokensRequest{
+ return EstimateCountTokens(CountTokensRequest{
Model: req.Model,
Messages: req.Messages,
System: req.System,
@@ -1089,10 +1089,10 @@ type CountTokensResponse struct {
InputTokens int `json:"input_tokens"`
}
-// estimateTokens returns a rough estimate of tokens (len/4).
+// EstimateCountTokens returns a rough estimate of tokens (len/4).
// TODO: Replace with actual tokenization via Tokenize API for accuracy.
// Current len/4 heuristic is a rough approximation (~4 chars/token average).
-func estimateTokens(req CountTokensRequest) int {
+func EstimateCountTokens(req CountTokensRequest) int {
var totalLen int
// Count system prompt
diff --git a/anthropic/anthropic_test.go b/anthropic/anthropic_test.go
index d0d97854b..ff75cf126 100755
--- a/anthropic/anthropic_test.go
+++ b/anthropic/anthropic_test.go
@@ -1546,7 +1546,7 @@ func TestEstimateTokens_SimpleMessage(t *testing.T) {
},
}
- tokens := estimateTokens(req)
+ tokens := EstimateCountTokens(req)
// "user" (4) + "Hello, world!" (13) = 17 chars / 4 = 4 tokens
if tokens < 1 {
@@ -1567,7 +1567,7 @@ func TestEstimateTokens_WithSystemPrompt(t *testing.T) {
},
}
- tokens := estimateTokens(req)
+ tokens := EstimateCountTokens(req)
// System prompt adds to count
if tokens < 5 {
@@ -1590,7 +1590,7 @@ func TestEstimateTokens_WithTools(t *testing.T) {
},
}
- tokens := estimateTokens(req)
+ tokens := EstimateCountTokens(req)
// Tools add significant content
if tokens < 10 {
@@ -1619,7 +1619,7 @@ func TestEstimateTokens_WithThinking(t *testing.T) {
},
}
- tokens := estimateTokens(req)
+ tokens := EstimateCountTokens(req)
// Thinking content should be counted
if tokens < 10 {
@@ -1633,7 +1633,7 @@ func TestEstimateTokens_EmptyContent(t *testing.T) {
Messages: []MessageParam{},
}
- tokens := estimateTokens(req)
+ tokens := EstimateCountTokens(req)
if tokens != 0 {
t.Errorf("expected 0 tokens for empty content, got %d", tokens)
diff --git a/app/cmd/app/app_darwin.go b/app/cmd/app/app_darwin.go
index 341877c93..401cdbef4 100644
--- a/app/cmd/app/app_darwin.go
+++ b/app/cmd/app/app_darwin.go
@@ -10,16 +10,29 @@ package main
import "C"
import (
+ "context"
+ "errors"
+ "fmt"
"log/slog"
+ "net"
+ "net/http"
"os"
"os/exec"
+ "os/signal"
"path/filepath"
+ "strconv"
"strings"
+ "sync"
+ "syscall"
"time"
"unsafe"
+ "github.com/ollama/ollama/api"
"github.com/ollama/ollama/app/updater"
"github.com/ollama/ollama/app/version"
+ "github.com/ollama/ollama/cmd/launch"
+ "github.com/ollama/ollama/envconfig"
+ "github.com/ollama/ollama/internal/proxy"
)
var ollamaPath = func() string {
@@ -35,10 +48,28 @@ var ollamaPath = func() string {
return filepath.Join(pwd, "ollama")
}()
+type claudeProxyFailure uint8
+
+const (
+ claudeProxyFailureNone claudeProxyFailure = iota
+ claudeProxyFailurePortConflict
+)
+
var (
isApp = updater.BundlePath != ""
appLogPath = filepath.Join(os.Getenv("HOME"), ".ollama", "logs", "app.log")
launchAgentPath = filepath.Join(os.Getenv("HOME"), "Library", "LaunchAgents", "com.ollama.ollama.plist")
+ claudeAppProxy *proxy.ClaudeDesktop
+ claudeProxyMu sync.Mutex
+ claudeProxyErr error
+ claudeProxyFail claudeProxyFailure
+ claudeDesktop = &launch.ClaudeDesktop{}
+
+ claudeDesktopInstalled = launch.ClaudeDesktopInstalled
+ claudeProxyListenAddr = proxy.DefaultClaudeDesktopListenAddr
+ claudeProxyRetryWait = 750 * time.Millisecond
+ claudeProxyRetryPoll = 50 * time.Millisecond
+ claudeShutdownTimeout = 30 * time.Second
)
// TODO(jmorganca): pre-create the window and pass
@@ -176,7 +207,26 @@ func UpdateAvailable(ver string) error {
}
func osRun(_ func(), hasCompletedFirstRun, startHidden, showOnboarding bool, _ string) {
+ handoffSignal := make(chan os.Signal, 1)
+ handoffDone := make(chan struct{})
+ signal.Notify(handoffSignal, syscall.SIGUSR1)
+ defer signal.Stop(handoffSignal)
+ defer close(handoffDone)
+ go func() {
+ select {
+ case <-handoffSignal:
+ slog.Info("received app handoff signal, shutting down")
+ stopClaudeAppProxy()
+ C.quit()
+ case <-handoffDone:
+ }
+ }()
+
registerLaunchAgent(hasCompletedFirstRun)
+ if err := reconcileClaudeAppProxy(); err != nil {
+ slog.Warn("failed to start Claude gateway", "error", err)
+ }
+ defer stopClaudeAppProxy()
// Run the native macOS app
// Note: this will block until the app is closed
@@ -184,10 +234,299 @@ func osRun(_ func(), hasCompletedFirstRun, startHidden, showOnboarding bool, _ s
C.run(C._Bool(showOnboarding), C._Bool(startHidden))
}
+func reconcileClaudeAppProxy() error {
+ if !claudeDesktopInstalled() || !claudeDesktop.UsesOllamaGateway() {
+ stopClaudeAppProxy()
+ return nil
+ }
+ return startClaudeAppProxy()
+}
+
+func startClaudeAppProxy() error {
+ claudeProxyMu.Lock()
+ defer claudeProxyMu.Unlock()
+ if claudeAppProxy != nil {
+ clearClaudeProxyFailure()
+ return nil
+ }
+ if !claudeDesktopInstalled() {
+ slog.Debug("Claude Desktop is not installed; skipping gateway")
+ clearClaudeProxyFailure()
+ return nil
+ }
+ ollamaURL := envconfig.ConnectableHost()
+ gatewayPort, err := claudeGatewayPort()
+ if err != nil {
+ return setClaudeProxyFailure(fmt.Errorf("parse Claude gateway address: %w", err), claudeProxyFailureNone)
+ }
+ if ollamaURL.Port() == gatewayPort {
+ return setClaudeProxyFailure(
+ fmt.Errorf("OLLAMA_HOST cannot use port %s because it is reserved for Claude", gatewayPort),
+ claudeProxyFailurePortConflict,
+ )
+ }
+ ollamaClient := api.NewClient(ollamaURL, http.DefaultClient)
+ gateway, err := proxy.NewClaudeDesktop(proxy.ClaudeDesktopConfig{
+ ListenAddr: claudeProxyListenAddr,
+ OllamaURL: ollamaURL.String(),
+ Model: "glm-5.2:cloud",
+ Logger: slog.Default(),
+ OnCountsChanged: updateClaudeProxyMenu,
+ CloudModelsAvailable: func(ctx context.Context) bool {
+ return claudeCloudModelsAvailable(ctx, ollamaClient.CloudStatusExperimental, ollamaClient.Whoami)
+ },
+ ListLocalModels: func(ctx context.Context) ([]string, error) {
+ return claudeLocalModels(ctx, ollamaClient.List)
+ },
+ })
+ if err != nil {
+ return setClaudeProxyFailure(err, claudeProxyFailureNone)
+ }
+ if err := startClaudeGateway(gateway); err != nil {
+ _ = gateway.Close(context.Background())
+ failure := claudeProxyFailureNone
+ if errors.Is(err, syscall.EADDRINUSE) {
+ failure = claudeProxyFailurePortConflict
+ }
+ return setClaudeProxyFailure(err, failure)
+ }
+ claudeAppProxy = gateway
+ clearClaudeProxyFailure()
+ return nil
+}
+
+func startClaudeGateway(gateway *proxy.ClaudeDesktop) error {
+ deadline := time.Now().Add(claudeProxyRetryWait)
+ for {
+ err := gateway.Start()
+ if err == nil || !errors.Is(err, syscall.EADDRINUSE) || time.Now().After(deadline) {
+ return err
+ }
+ time.Sleep(claudeProxyRetryPoll)
+ }
+}
+
+func claudeCloudModelsAvailable(
+ ctx context.Context,
+ cloudStatus func(context.Context) (*api.StatusResponse, error),
+ whoami func(context.Context) (*api.UserResponse, error),
+) bool {
+ ctx, cancel := context.WithTimeout(ctx, time.Second)
+ defer cancel()
+ status, err := cloudStatus(ctx)
+ if err != nil {
+ slog.Debug("could not check whether Ollama cloud is enabled", "error", err)
+ } else if status != nil && status.Cloud.Disabled {
+ return false
+ }
+
+ user, err := whoami(ctx)
+ if err != nil {
+ var authErr api.AuthorizationError
+ if errors.As(err, &authErr) && authErr.StatusCode == http.StatusUnauthorized {
+ return false
+ }
+ slog.Debug("could not check whether cloud models are available", "error", err)
+ return true
+ }
+ return user != nil && strings.TrimSpace(user.Name) != ""
+}
+
+func claudeLocalModels(
+ ctx context.Context,
+ list func(context.Context) (*api.ListResponse, error),
+) ([]string, error) {
+ ctx, cancel := context.WithTimeout(ctx, time.Second)
+ defer cancel()
+ response, err := list(ctx)
+ if err != nil || response == nil {
+ return nil, err
+ }
+
+ names := make([]string, 0, len(response.Models)*2)
+ for _, model := range response.Models {
+ if model.RemoteModel != "" || model.RemoteHost != "" {
+ continue
+ }
+ if model.Name != "" {
+ names = append(names, model.Name)
+ }
+ if model.Model != "" && model.Model != model.Name {
+ names = append(names, model.Model)
+ }
+ }
+ return names, nil
+}
+
+func claudeGatewayPort() (string, error) {
+ _, port, err := net.SplitHostPort(claudeProxyListenAddr)
+ if err != nil {
+ return "", err
+ }
+ return port, nil
+}
+
+//export ClaudeGatewayPort
+func ClaudeGatewayPort() C.int {
+ portText, err := claudeGatewayPort()
+ if err != nil {
+ return 0
+ }
+ port, err := strconv.Atoi(portText)
+ if err != nil {
+ return 0
+ }
+ return C.int(port)
+}
+
+// These helpers require claudeProxyMu to be held.
+func setClaudeProxyFailure(err error, failure claudeProxyFailure) error {
+ claudeProxyErr = err
+ claudeProxyFail = failure
+ return err
+}
+
+func clearClaudeProxyFailure() {
+ claudeProxyErr = nil
+ claudeProxyFail = claudeProxyFailureNone
+}
+
+//export SetClaudeGatewayInstalled
+func SetClaudeGatewayInstalled(installed C.bool, restartClaude C.bool) C.bool {
+ shouldInstall := installed != C._Bool(false)
+ shouldRestart := restartClaude != C._Bool(false)
+ if err := setClaudeGatewayInstalled(shouldInstall, shouldRestart); err != nil {
+ slog.Warn("failed to change Claude Desktop gateway installation", "installed", shouldInstall, "error", err)
+ return C._Bool(false)
+ }
+ return C._Bool(true)
+}
+
+func setClaudeGatewayInstalled(installed, restart bool) error {
+ if installed && !claudeDesktopInstalled() {
+ return errors.New("Claude Desktop is not installed")
+ }
+ if installed {
+ if err := startClaudeAppProxy(); err != nil {
+ return err
+ }
+ }
+ err := claudeDesktop.SetInstalledFromDesktop(installed, restart)
+ if !claudeDesktop.UsesOllamaGateway() {
+ stopClaudeAppProxy()
+ }
+ return err
+}
+
+//export IsClaudeDesktopInstalled
+func IsClaudeDesktopInstalled() C.bool {
+ return C._Bool(claudeDesktopInstalled())
+}
+
+//export IsClaudeDesktopRunning
+func IsClaudeDesktopRunning() C.bool {
+ return C._Bool(launch.ClaudeDesktopRunning())
+}
+
+//export IsClaudeGatewayConfigured
+func IsClaudeGatewayConfigured() C.bool {
+ return C._Bool(claudeDesktop.UsesOllamaGateway())
+}
+
+//export ClaudeGatewayStartFailed
+func ClaudeGatewayStartFailed() C.bool {
+ return C._Bool(claudeGatewayStartFailed())
+}
+
+func claudeGatewayStartFailed() bool {
+ claudeProxyMu.Lock()
+ defer claudeProxyMu.Unlock()
+ return claudeProxyErr != nil
+}
+
+//export ClaudeGatewayPortConflict
+func ClaudeGatewayPortConflict() C.bool {
+ return C._Bool(claudeGatewayPortConflict())
+}
+
+func claudeGatewayPortConflict() bool {
+ claudeProxyMu.Lock()
+ defer claudeProxyMu.Unlock()
+ return claudeProxyFail == claudeProxyFailurePortConflict
+}
+
+//export RefreshClaudeProxyMenu
+func RefreshClaudeProxyMenu() {
+ claudeProxyMu.Lock()
+ proxy := claudeAppProxy
+ claudeProxyMu.Unlock()
+ if proxy == nil {
+ return
+ }
+ updateClaudeProxyMenu(proxy.Counts())
+}
+
+func updateClaudeProxyMenu(counts proxy.ClaudeDesktopCounts) {
+ C.updateClaudeProxyMenu(C.ulonglong(counts.Routed))
+}
+
+func stopClaudeAppProxy() {
+ claudeProxyMu.Lock()
+ proxy := claudeAppProxy
+ claudeAppProxy = nil
+ clearClaudeProxyFailure()
+ claudeProxyMu.Unlock()
+ if proxy == nil {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ if err := proxy.Close(ctx); err != nil {
+ slog.Debug("failed to stop Claude gateway cleanly", "error", err)
+ }
+}
+
func quit() {
+ ctx, cancel := context.WithTimeout(context.Background(), claudeShutdownTimeout)
+ defer cancel()
+ handoff := bool(C.otherOllamaInstanceRunning())
+ if err := restoreClaudeAppForTermination(ctx, handoff); err != nil {
+ slog.Warn("failed to restore Claude before quitting", "error", err)
+ }
C.quit()
}
+func restoreClaudeBeforeQuit(ctx context.Context, handoff, configured bool, restore func(context.Context) error) error {
+ if handoff || !configured {
+ return nil
+ }
+ return restore(ctx)
+}
+
+func restoreClaudeAppForTermination(ctx context.Context, handoff bool) error {
+ if handoff {
+ stopClaudeAppProxy()
+ return nil
+ }
+ configured := claudeDesktop.UsesOllamaGateway()
+ err := restoreClaudeBeforeQuit(ctx, handoff, configured, claudeDesktop.RestoreForShutdown)
+ if !claudeDesktop.UsesOllamaGateway() {
+ stopClaudeAppProxy()
+ }
+ return err
+}
+
+//export RestoreClaudeGatewayForShutdown
+func RestoreClaudeGatewayForShutdown() C.bool {
+ ctx, cancel := context.WithTimeout(context.Background(), claudeShutdownTimeout)
+ defer cancel()
+ if err := restoreClaudeAppForTermination(ctx, false); err != nil {
+ slog.Warn("failed to restore Claude during system shutdown", "error", err)
+ return C._Bool(false)
+ }
+ return C._Bool(true)
+}
+
func LaunchNewApp() {
appName := C.CString(updater.BundlePath)
defer C.free(unsafe.Pointer(appName))
diff --git a/app/cmd/app/app_darwin.h b/app/cmd/app/app_darwin.h
index 12a644480..7e553bcd6 100644
--- a/app/cmd/app/app_darwin.h
+++ b/app/cmd/app/app_darwin.h
@@ -18,6 +18,7 @@ enum AppMove
void run(bool showOnboarding, bool startHidden);
void killOtherInstances();
+bool otherOllamaInstanceRunning(void);
enum AppMove askToMoveToApplications();
int createSymlinkWithAuthorization();
int installSymlink(const char *cliPath);
@@ -42,3 +43,13 @@ void setWindowResizable(uintptr_t wndPtr, bool resizable);
void drag(uintptr_t wndPtr);
void doubleClick(uintptr_t wndPtr);
void handleConnectURL();
+bool SetClaudeGatewayInstalled(bool installed, bool restartClaude);
+bool RestoreClaudeGatewayForShutdown(void);
+bool IsClaudeGatewayConfigured(void);
+bool IsClaudeDesktopInstalled(void);
+bool IsClaudeDesktopRunning(void);
+bool ClaudeGatewayStartFailed(void);
+bool ClaudeGatewayPortConflict(void);
+int ClaudeGatewayPort(void);
+void RefreshClaudeProxyMenu(void);
+void updateClaudeProxyMenu(unsigned long long routed);
diff --git a/app/cmd/app/app_darwin.m b/app/cmd/app/app_darwin.m
index 87bc9a397..51e833398 100644
--- a/app/cmd/app/app_darwin.m
+++ b/app/cmd/app/app_darwin.m
@@ -11,10 +11,331 @@
extern NSString *SystemWidePath;
-@interface AppDelegate () <NSWindowDelegate, WKNavigationDelegate, WKUIDelegate>
+static NSString *const ClaudeDownloadURL =
+ @"https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect";
+static NSString *const ClaudeDownloadPageURL = @"https://claude.com/download";
+static NSBundle *OllamaResourceBundle(void);
+
+static NSImage *integrationAppIcon(NSString *appName,
+ NSString *fallbackSymbolName) {
+ NSArray<NSString *> *candidates = @[
+ [NSString stringWithFormat:@"/Applications/%@.app", appName],
+ [NSHomeDirectory() stringByAppendingPathComponent:
+ [NSString stringWithFormat:@"Applications/%@.app", appName]],
+ ];
+ for (NSString *path in candidates) {
+ if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
+ continue;
+ }
+ NSImage *icon = [[NSWorkspace sharedWorkspace] iconForFile:path];
+ if (icon != nil) {
+ [icon setTemplate:NO];
+ return icon;
+ }
+ }
+ NSBundle *bundle = OllamaResourceBundle();
+ NSImage *bundledIcon = [bundle imageForResource:appName.lowercaseString];
+ if (bundledIcon != nil) {
+ [bundledIcon setTemplate:NO];
+ return bundledIcon;
+ }
+ return [NSImage imageWithSystemSymbolName:fallbackSymbolName
+ accessibilityDescription:nil];
+}
+
+@interface MenuSwitch : NSButton
+@end
+
+@implementation MenuSwitch
+
+- (instancetype)initWithFrame:(NSRect)frameRect {
+ self = [super initWithFrame:frameRect];
+ if (self) {
+ [self setButtonType:NSButtonTypeToggle];
+ [self setBordered:NO];
+ [self setTitle:@""];
+ [self setFocusRingType:NSFocusRingTypeNone];
+ [self setAccessibilityRole:NSAccessibilityCheckBoxRole];
+ }
+ return self;
+}
+
+- (NSSize)intrinsicContentSize {
+ return NSMakeSize(30, 18);
+}
+
+- (void)setState:(NSControlStateValue)state {
+ [super setState:state];
+ [self setNeedsDisplay:YES];
+}
+
+- (void)setEnabled:(BOOL)enabled {
+ [super setEnabled:enabled];
+ [self setNeedsDisplay:YES];
+}
+
+- (void)drawRect:(NSRect)dirtyRect {
+ (void)dirtyRect;
+ NSRect track = NSInsetRect(self.bounds, 0, 1);
+ NSColor *trackColor = self.state == NSControlStateValueOn
+ ? [NSColor systemBlueColor]
+ : [NSColor colorWithWhite:0.55 alpha:1];
+ if (!self.enabled) {
+ trackColor = [trackColor colorWithAlphaComponent:0.45];
+ }
+ [trackColor setFill];
+ [[NSBezierPath bezierPathWithRoundedRect:track
+ xRadius:NSHeight(track) / 2
+ yRadius:NSHeight(track) / 2] fill];
+
+ CGFloat knobSize = NSHeight(track) - 4;
+ CGFloat knobX = self.state == NSControlStateValueOn
+ ? NSMaxX(track) - knobSize - 2
+ : NSMinX(track) + 2;
+ NSRect knob = NSMakeRect(knobX,
+ NSMidY(track) - knobSize / 2,
+ knobSize,
+ knobSize);
+ [[NSColor whiteColor] setFill];
+ [[NSBezierPath bezierPathWithOvalInRect:knob] fill];
+}
+
+@end
+
+@interface IntegrationMenuRow : NSButton
+@property(strong, nonatomic) NSView *controlSurface;
+@property(strong, nonatomic) NSButton *openButton;
+@property(strong, nonatomic) NSTextField *integrationTitleLabel;
+@property(strong, nonatomic) NSTextField *integrationStatusLabel;
+@property(strong, nonatomic) MenuSwitch *integrationSwitch;
+@property(strong, nonatomic) NSLayoutConstraint *titleWithStatusConstraint;
+@property(strong, nonatomic) NSLayoutConstraint *titleCenteredConstraint;
+@property(strong, nonatomic) NSTrackingArea *hoverTrackingArea;
+@property(assign, nonatomic) BOOL pointerInside;
+@property(assign, nonatomic) SEL integrationOpenAction;
+@property(copy, nonatomic) NSString *activeStatusText;
+@property(copy, nonatomic) NSString *inactiveStatusText;
+- (instancetype)initWithTitle:(NSString *)title
+ symbolName:(NSString *)symbolName
+ target:(id)target
+ openAction:(SEL)openAction
+ toggleAction:(SEL)toggleAction;
+- (void)setIntegrationActive:(BOOL)active;
+- (void)setIntegrationReady:(BOOL)ready;
+- (void)setActiveStatusText:(NSString *)status;
+- (void)setInactiveStatusText:(NSString *)status;
+- (void)resetHover;
+@end
+
+@implementation IntegrationMenuRow
+
+- (instancetype)initWithTitle:(NSString *)title
+ symbolName:(NSString *)symbolName
+ target:(id)target
+ openAction:(SEL)openAction
+ toggleAction:(SEL)toggleAction {
+ self = [super initWithFrame:NSMakeRect(0, 0, 310, 50)];
+ if (self) {
+ [self setButtonType:NSButtonTypeMomentaryChange];
+ [self setBordered:NO];
+ [self setTitle:@""];
+ [self setFocusRingType:NSFocusRingTypeNone];
+ [self setTarget:target];
+ [self setAction:openAction];
+ self.integrationOpenAction = openAction;
+ [self setAccessibilityLabel:[NSString stringWithFormat:@"Open %@", title]];
+ [self setAccessibilityRole:NSAccessibilityButtonRole];
+
+ self.controlSurface = [[NSView alloc] initWithFrame:NSZeroRect];
+ [self.controlSurface setWantsLayer:YES];
+ self.controlSurface.layer.cornerRadius = 13;
+ [self.controlSurface setTranslatesAutoresizingMaskIntoConstraints:NO];
+
+ NSImage *icon = integrationAppIcon(title, symbolName);
+ self.openButton = [NSButton buttonWithImage:icon
+ target:target
+ action:openAction];
+ [self.openButton setBordered:NO];
+ [self.openButton setImagePosition:NSImageOnly];
+ [self.openButton setImageScaling:NSImageScaleProportionallyDown];
+ [self.openButton setFocusRingType:NSFocusRingTypeNone];
+ [self.openButton setAccessibilityLabel:[NSString stringWithFormat:@"Open %@", title]];
+ [self.openButton setTranslatesAutoresizingMaskIntoConstraints:NO];
+
+ self.integrationTitleLabel = [NSTextField labelWithString:title];
+ [self.integrationTitleLabel setFont:[NSFont systemFontOfSize:13 weight:NSFontWeightSemibold]];
+ [self.integrationTitleLabel setLineBreakMode:NSLineBreakByTruncatingTail];
+ [self.integrationTitleLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
+
+ self.integrationStatusLabel = [NSTextField labelWithString:@""];
+ [self.integrationStatusLabel setFont:[NSFont systemFontOfSize:11.5]];
+ [self.integrationStatusLabel setLineBreakMode:NSLineBreakByTruncatingTail];
+ [self.integrationStatusLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
+
+ self.integrationSwitch = [[MenuSwitch alloc] initWithFrame:NSZeroRect];
+ [self.integrationSwitch setTarget:target];
+ [self.integrationSwitch setAction:toggleAction];
+ [self.integrationSwitch setAccessibilityLabel:[NSString stringWithFormat:@"Use Ollama with %@", title]];
+ [self.integrationSwitch setTranslatesAutoresizingMaskIntoConstraints:NO];
+
+ [self addSubview:self.controlSurface];
+ [self addSubview:self.openButton];
+ [self addSubview:self.integrationTitleLabel];
+ [self addSubview:self.integrationStatusLabel];
+ [self addSubview:self.integrationSwitch];
+ self.titleWithStatusConstraint =
+ [self.integrationTitleLabel.bottomAnchor
+ constraintEqualToAnchor:self.controlSurface.centerYAnchor
+ constant:-1];
+ self.titleCenteredConstraint =
+ [self.integrationTitleLabel.centerYAnchor
+ constraintEqualToAnchor:self.controlSurface.centerYAnchor];
+ [NSLayoutConstraint activateConstraints:@[
+ [self.controlSurface.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:7],
+ [self.controlSurface.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-7],
+ [self.controlSurface.topAnchor constraintEqualToAnchor:self.topAnchor constant:3],
+ [self.controlSurface.bottomAnchor constraintEqualToAnchor:self.bottomAnchor constant:-3],
+ [self.openButton.leadingAnchor constraintEqualToAnchor:self.controlSurface.leadingAnchor constant:9],
+ [self.openButton.centerYAnchor constraintEqualToAnchor:self.controlSurface.centerYAnchor],
+ [self.openButton.widthAnchor constraintEqualToConstant:34],
+ [self.openButton.heightAnchor constraintEqualToConstant:34],
+ [self.integrationTitleLabel.leadingAnchor constraintEqualToAnchor:self.openButton.trailingAnchor constant:10],
+ self.titleWithStatusConstraint,
+ [self.integrationTitleLabel.trailingAnchor constraintLessThanOrEqualToAnchor:self.integrationSwitch.leadingAnchor constant:-12],
+ [self.integrationStatusLabel.leadingAnchor constraintEqualToAnchor:self.integrationTitleLabel.leadingAnchor],
+ [self.integrationStatusLabel.topAnchor constraintEqualToAnchor:self.controlSurface.centerYAnchor constant:1],
+ [self.integrationStatusLabel.trailingAnchor constraintLessThanOrEqualToAnchor:self.integrationSwitch.leadingAnchor constant:-12],
+ [self.integrationSwitch.trailingAnchor constraintEqualToAnchor:self.controlSurface.trailingAnchor constant:-12],
+ [self.integrationSwitch.centerYAnchor constraintEqualToAnchor:self.controlSurface.centerYAnchor],
+ ]];
+ [self setIntegrationActive:NO];
+ }
+ return self;
+}
+
+- (NSView *)hitTest:(NSPoint)point {
+ if (!NSPointInRect(point, self.bounds)) {
+ return nil;
+ }
+ if (NSPointInRect(point, self.integrationSwitch.frame)) {
+ return self.integrationSwitch;
+ }
+ if (NSPointInRect(point, self.openButton.frame)) {
+ return self.openButton;
+ }
+ return self;
+}
+
+- (void)updateTrackingAreas {
+ [super updateTrackingAreas];
+ if (self.hoverTrackingArea != nil) {
+ [self removeTrackingArea:self.hoverTrackingArea];
+ }
+ self.hoverTrackingArea = [[NSTrackingArea alloc]
+ initWithRect:NSZeroRect
+ options:NSTrackingMouseEnteredAndExited |
+ NSTrackingActiveAlways |
+ NSTrackingInVisibleRect
+ owner:self
+ userInfo:nil];
+ [self addTrackingArea:self.hoverTrackingArea];
+}
+
+- (void)mouseEntered:(NSEvent *)event {
+ (void)event;
+ self.pointerInside = YES;
+ [self updateAppearance];
+}
+
+- (void)mouseExited:(NSEvent *)event {
+ (void)event;
+ self.pointerInside = NO;
+ [self updateAppearance];
+}
+
+- (void)resetHover {
+ self.pointerInside = NO;
+ [self updateAppearance];
+}
+
+- (void)viewDidChangeEffectiveAppearance {
+ [super viewDidChangeEffectiveAppearance];
+ [self updateAppearance];
+}
+
+- (void)updateAppearance {
+ BOOL active = self.integrationSwitch.state == NSControlStateValueOn;
+ BOOL hovered = self.pointerInside && self.enabled;
+ NSColor *surfaceColor = hovered
+ ? [[NSColor labelColor] colorWithAlphaComponent:0.08]
+ : [NSColor clearColor];
+ self.controlSurface.layer.backgroundColor = surfaceColor.CGColor;
+ self.integrationTitleLabel.textColor = [NSColor labelColor];
+ NSString *status = active ? (self.activeStatusText ?: @"Using Ollama")
+ : (self.inactiveStatusText ?: @"Use Ollama models");
+ BOOL hasStatus = status.length > 0;
+ self.titleWithStatusConstraint.active = hasStatus;
+ self.titleCenteredConstraint.active = !hasStatus;
+ self.integrationStatusLabel.hidden = !hasStatus;
+ self.integrationStatusLabel.stringValue = status;
+ self.integrationStatusLabel.textColor = [NSColor secondaryLabelColor];
+ [self setAccessibilityValue:status];
+}
+
+- (void)setIntegrationActive:(BOOL)active {
+ self.integrationSwitch.state = active ? NSControlStateValueOn
+ : NSControlStateValueOff;
+ [self setIntegrationReady:active];
+ [self updateAppearance];
+}
+
+- (void)setIntegrationReady:(BOOL)ready {
+ self.action = ready ? self.integrationOpenAction : nil;
+ self.openButton.enabled = ready;
+ self.openButton.alphaValue = ready ? 1.0 : 0.45;
+}
+
+- (void)setActiveStatusText:(NSString *)status {
+ _activeStatusText = [status copy];
+ [self updateAppearance];
+}
+
+- (void)setInactiveStatusText:(NSString *)status {
+ _inactiveStatusText = [status copy];
+ [self updateAppearance];
+}
+
+@end
+
+@interface AppDelegate () <NSWindowDelegate, WKNavigationDelegate, WKUIDelegate, NSMenuDelegate, NSURLSessionDownloadDelegate>
@property(strong, nonatomic) NSStatusItem *statusItem;
@property(assign, nonatomic) BOOL updateAvailable;
@property(assign, nonatomic) BOOL systemShutdownInProgress;
+@property(strong, nonatomic) NSMenuItem *updateAvailableMenuItem;
+@property(strong, nonatomic) NSMenuItem *restartMenuItem;
+@property(assign, nonatomic) BOOL claudeAppEnabled;
+@property(assign, nonatomic) BOOL claudeAppReady;
+@property(strong, nonatomic) IntegrationMenuRow *claudeAppRow;
+@property(strong, nonatomic) NSURLSession *claudeDownloadSession;
+@property(strong, nonatomic) NSURLSessionDownloadTask *claudeDownloadTask;
+@property(strong, nonatomic) NSAlert *claudeDownloadAlert;
+@property(strong, nonatomic) NSProgressIndicator *claudeDownloadProgress;
+@property(strong, nonatomic) NSURL *claudeDownloadedInstallerURL;
+@property(strong, nonatomic) NSError *claudeDownloadError;
+@property(assign, nonatomic) BOOL claudeDownloadCancelled;
+@property(assign, nonatomic) BOOL claudeDownloadCompleted;
+@property(assign, nonatomic) BOOL claudeDownloadModalRunning;
+@property(assign, nonatomic) BOOL quitInProgress;
+@property(assign, nonatomic) BOOL systemTerminationReplyPending;
+@property(strong, nonatomic) NSApplication *systemTerminationApplication;
+- (void)openClaudeApp:(id)sender;
+- (void)downloadClaude;
+- (void)finishClaudeDownload;
+- (void)showClaudeDownloadFailure:(NSError *)error;
+- (void)toggleClaudeAppProxy:(NSButton *)sender;
+- (void)refreshClaudeAppState;
+- (void)requestQuit;
+- (void)completeSystemTermination;
@end
@implementation AppDelegate
@@ -41,6 +362,15 @@ static NSBundle *OllamaResourceBundle(void) {
return bundle;
}
+static NSImage *ollamaApplicationIcon(void) {
+ NSBundle *bundle = OllamaResourceBundle();
+ NSString *iconPath = [bundle pathForResource:@"icon" ofType:@"icns"];
+ if (iconPath == nil) {
+ return [NSApp applicationIconImage];
+ }
+ return [[NSImage alloc] initWithContentsOfFile:iconPath];
+}
+
- (void)application:(NSApplication *)application openURLs:(NSArray<NSURL *> *)urls {
for (NSURL *url in urls) {
if ([url.scheme isEqualToString:@"ollama"]) {
@@ -69,46 +399,64 @@ static NSBundle *OllamaResourceBundle(void) {
// if we're in development mode, set the app icon
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
if (![bundlePath hasSuffix:@".app"]) {
- NSString *iconPath =
- [OllamaResourceBundle() pathForResource:@"icon" ofType:@"icns"];
- NSImage *customIcon = [[NSImage alloc] initWithContentsOfFile:iconPath];
- [NSApp setApplicationIconImage:customIcon];
+ NSImage *customIcon = ollamaApplicationIcon();
+ if (customIcon != nil) {
+ [NSApp setApplicationIconImage:customIcon];
+ }
}
// Create status item and menu
NSMenu *menu = [[NSMenu alloc] init];
- [menu addItemWithTitle:@"Settings..."
- action:@selector(settingsUI)
- keyEquivalent:@","];
+ [menu setDelegate:self];
+ [menu setAutoenablesItems:NO];
+
+ NSMenuItem *claudeMenuItem = [[NSMenuItem alloc] initWithTitle:@"Claude"
+ action:nil
+ keyEquivalent:@""];
+ [claudeMenuItem setEnabled:YES];
+ self.claudeAppRow = [[IntegrationMenuRow alloc]
+ initWithTitle:@"Claude"
+ symbolName:@"sparkles"
+ target:self
+ openAction:@selector(openClaudeApp:)
+ toggleAction:@selector(toggleClaudeAppProxy:)];
+ [claudeMenuItem setView:self.claudeAppRow];
+ [menu addItem:claudeMenuItem];
+ [self refreshClaudeAppState];
+ [menu addItem:[NSMenuItem separatorItem]];
NSMenuItem *openMenuItem =
- [[NSMenuItem alloc] initWithTitle:@"Open Ollama Chat"
+ [[NSMenuItem alloc] initWithTitle:@"Open Chat"
action:@selector(openUI)
keyEquivalent:@""];
[openMenuItem setTarget:self];
[menu addItem:openMenuItem];
+
+ [menu addItemWithTitle:@"Settings..."
+ action:@selector(settingsUI)
+ keyEquivalent:@","];
[menu addItem:[NSMenuItem separatorItem]];
- NSMenuItem *updateAvailable =
+ self.updateAvailableMenuItem =
[[NSMenuItem alloc] initWithTitle:@"An update is available"
action:nil
keyEquivalent:@""];
- [updateAvailable setEnabled:NO];
- [updateAvailable setHidden:YES];
- [menu addItem:updateAvailable];
+ [self.updateAvailableMenuItem setEnabled:NO];
+ [self.updateAvailableMenuItem setHidden:YES];
+ [menu addItem:self.updateAvailableMenuItem];
- NSMenuItem *restartMenuItem =
+ self.restartMenuItem =
[[NSMenuItem alloc] initWithTitle:@"Restart to update"
action:@selector(startUpdate)
keyEquivalent:@""];
- [restartMenuItem setTarget:self];
- [restartMenuItem setHidden:YES];
- [menu addItem:restartMenuItem];
+ [self.restartMenuItem setTarget:self];
+ [self.restartMenuItem setHidden:YES];
+ [menu addItem:self.restartMenuItem];
[menu addItem:[NSMenuItem separatorItem]];
[menu addItemWithTitle:@"Quit Ollama"
- action:@selector(quit)
+ action:@selector(requestQuit)
keyEquivalent:@"q"];
self.statusItem = [[NSStatusBar systemStatusBar]
@@ -253,10 +601,42 @@ static NSBundle *OllamaResourceBundle(void) {
return YES;
}
+- (void)menuWillOpen:(NSMenu *)menu {
+ if (menu != self.statusItem.menu) {
+ return;
+ }
+ [self refreshClaudeAppState];
+}
+
+- (void)refreshClaudeAppState {
+ BOOL installed = IsClaudeDesktopInstalled();
+ BOOL startFailed = ClaudeGatewayStartFailed();
+ BOOL portConflict = startFailed && ClaudeGatewayPortConflict();
+ BOOL configured = installed && IsClaudeGatewayConfigured();
+ NSString *failureStatus = portConflict
+ ? [NSString stringWithFormat:@"Port %d is in use", ClaudeGatewayPort()]
+ : (startFailed ? @"Unable to use Ollama" : nil);
+ self.claudeAppEnabled = configured;
+ self.claudeAppReady = configured && !startFailed;
+ [self.claudeAppRow setActiveStatusText:configured ? failureStatus : nil];
+ [self.claudeAppRow setInactiveStatusText:configured
+ ? nil
+ : (!installed ? @"Not installed" : failureStatus)];
+ [self.claudeAppRow setIntegrationActive:self.claudeAppEnabled];
+ [self.claudeAppRow setIntegrationReady:self.claudeAppReady];
+ RefreshClaudeProxyMenu();
+}
+
+- (void)menuDidClose:(NSMenu *)menu {
+ if (menu == self.statusItem.menu) {
+ [self.claudeAppRow resetHover];
+ }
+}
+
- (void)showUpdateAvailable {
self.updateAvailable = YES;
- [self.statusItem.menu.itemArray[3] setHidden:NO];
- [self.statusItem.menu.itemArray[4] setHidden:NO];
+ [self.updateAvailableMenuItem setHidden:NO];
+ [self.restartMenuItem setHidden:NO];
[self showIcon];
}
@@ -278,6 +658,333 @@ static NSBundle *OllamaResourceBundle(void) {
[self uiRequest:@"/"];
}
+- (void)openClaudeApp:(id)sender {
+ (void)sender;
+ if (!self.claudeAppReady) {
+ return;
+ }
+ [self.statusItem.menu cancelTracking];
+
+ NSArray<NSString *> *candidates = @[
+ @"/Applications/Claude.app",
+ [NSHomeDirectory() stringByAppendingPathComponent:@"Applications/Claude.app"],
+ ];
+ for (NSString *path in candidates) {
+ if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
+ continue;
+ }
+ NSWorkspaceOpenConfiguration *configuration =
+ [NSWorkspaceOpenConfiguration configuration];
+ configuration.activates = YES;
+ configuration.createsNewApplicationInstance = NO;
+ [[NSWorkspace sharedWorkspace]
+ openApplicationAtURL:[NSURL fileURLWithPath:path]
+ configuration:configuration
+ completionHandler:^(NSRunningApplication *application,
+ NSError *error) {
+ (void)application;
+ if (error != nil) {
+ appLogInfo([NSString stringWithFormat:
+ @"Unable to open Claude: %@", error]);
+ }
+ }];
+ return;
+ }
+
+ NSAlert *alert = [[NSAlert alloc] init];
+ [alert setAlertStyle:NSAlertStyleWarning];
+ [alert setMessageText:@"Unable to open Claude"];
+ [alert setInformativeText:@"Install Claude in Applications, then try again."];
+ [alert runModal];
+}
+
+- (void)showClaudeDownloadFailure:(NSError *)error {
+ appLogInfo([NSString stringWithFormat:@"Unable to download Claude: %@",
+ error]);
+ NSAlert *alert = [[NSAlert alloc] init];
+ [alert setAlertStyle:NSAlertStyleWarning];
+ [alert setIcon:ollamaApplicationIcon()];
+ [alert setMessageText:@"Claude couldn’t be downloaded"];
+ [alert setInformativeText:
+ @"Try again or download Claude from its website."];
+ [alert addButtonWithTitle:@"Open download page"];
+ [alert addButtonWithTitle:@"Cancel"];
+ if ([alert runModal] == NSAlertFirstButtonReturn) {
+ [[NSWorkspace sharedWorkspace]
+ openURL:[NSURL URLWithString:ClaudeDownloadPageURL]];
+ }
+}
+
+- (void)downloadClaude {
+ if (self.claudeDownloadTask != nil) {
+ return;
+ }
+
+ [self.claudeAppRow setInactiveStatusText:@"Downloading Claude…"];
+ [self.claudeAppRow.integrationSwitch setEnabled:NO];
+
+ self.claudeDownloadAlert = [[NSAlert alloc] init];
+ [self.claudeDownloadAlert setAlertStyle:NSAlertStyleInformational];
+ [self.claudeDownloadAlert setIcon:ollamaApplicationIcon()];
+ [self.claudeDownloadAlert setMessageText:@"Downloading Claude"];
+ [self.claudeDownloadAlert setInformativeText:
+ @"The installer will open when the download finishes."];
+ [self.claudeDownloadAlert addButtonWithTitle:@"Cancel"];
+ self.claudeDownloadProgress = [[NSProgressIndicator alloc]
+ initWithFrame:NSMakeRect(0, 0, 260, 12)];
+ [self.claudeDownloadProgress setStyle:NSProgressIndicatorStyleBar];
+ [self.claudeDownloadProgress setMinValue:0];
+ [self.claudeDownloadProgress setMaxValue:100];
+ [self.claudeDownloadProgress setIndeterminate:YES];
+ [self.claudeDownloadProgress startAnimation:nil];
+ [self.claudeDownloadAlert setAccessoryView:self.claudeDownloadProgress];
+
+ self.claudeDownloadCancelled = NO;
+ self.claudeDownloadCompleted = NO;
+ self.claudeDownloadedInstallerURL = nil;
+ self.claudeDownloadError = nil;
+ NSURLSessionConfiguration *configuration =
+ [NSURLSessionConfiguration ephemeralSessionConfiguration];
+ self.claudeDownloadSession = [NSURLSession
+ sessionWithConfiguration:configuration
+ delegate:self
+ delegateQueue:[NSOperationQueue mainQueue]];
+ self.claudeDownloadTask = [self.claudeDownloadSession
+ downloadTaskWithURL:[NSURL URLWithString:ClaudeDownloadURL]];
+
+ [NSApp activateIgnoringOtherApps:YES];
+ [self.claudeDownloadTask resume];
+ self.claudeDownloadModalRunning = YES;
+ NSModalResponse response = [self.claudeDownloadAlert runModal];
+ self.claudeDownloadModalRunning = NO;
+ if (response == NSAlertFirstButtonReturn &&
+ !self.claudeDownloadCompleted) {
+ self.claudeDownloadCancelled = YES;
+ [self.claudeDownloadTask cancel];
+ return;
+ }
+ if (self.claudeDownloadCompleted) {
+ [self finishClaudeDownload];
+ }
+}
+
+- (void)URLSession:(NSURLSession *)session
+ downloadTask:(NSURLSessionDownloadTask *)downloadTask
+ didWriteData:(int64_t)bytesWritten
+ totalBytesWritten:(int64_t)totalBytesWritten
+totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
+ (void)session;
+ (void)bytesWritten;
+ if (downloadTask != self.claudeDownloadTask ||
+ totalBytesExpectedToWrite <= 0) {
+ return;
+ }
+ if (self.claudeDownloadProgress.indeterminate) {
+ [self.claudeDownloadProgress stopAnimation:nil];
+ [self.claudeDownloadProgress setIndeterminate:NO];
+ }
+ [self.claudeDownloadProgress
+ setDoubleValue:(100.0 * totalBytesWritten) /
+ totalBytesExpectedToWrite];
+}
+
+- (void)URLSession:(NSURLSession *)session
+ downloadTask:(NSURLSessionDownloadTask *)downloadTask
+didFinishDownloadingToURL:(NSURL *)location {
+ (void)session;
+ if (downloadTask != self.claudeDownloadTask ||
+ self.claudeDownloadCancelled) {
+ return;
+ }
+
+ NSError *error = nil;
+ NSHTTPURLResponse *response =
+ [downloadTask.response isKindOfClass:[NSHTTPURLResponse class]]
+ ? (NSHTTPURLResponse *)downloadTask.response
+ : nil;
+ NSString *host = response.URL.host.lowercaseString;
+ BOOL trustedHost = [host isEqualToString:@"claude.ai"] ||
+ [host hasSuffix:@".claude.ai"];
+ if (response.statusCode != 200 || !trustedHost ||
+ ![response.URL.scheme isEqualToString:@"https"]) {
+ error = [NSError
+ errorWithDomain:@"com.ollama.app"
+ code:1
+ userInfo:@{NSLocalizedDescriptionKey:
+ @"Claude returned an invalid download response."}];
+ }
+
+ if (error == nil) {
+ NSDictionary *attributes = [[NSFileManager defaultManager]
+ attributesOfItemAtPath:location.path
+ error:&error];
+ if (error == nil && [attributes fileSize] < 1024 * 1024) {
+ error = [NSError
+ errorWithDomain:@"com.ollama.app"
+ code:2
+ userInfo:@{NSLocalizedDescriptionKey:
+ @"Claude returned an incomplete download."}];
+ }
+ }
+
+ if (error == nil) {
+ NSString *fileName = [NSString
+ stringWithFormat:@"Claude-%@.dmg", [NSUUID UUID].UUIDString];
+ NSURL *installerURL = [NSURL fileURLWithPath:
+ [NSTemporaryDirectory() stringByAppendingPathComponent:fileName]];
+ if ([[NSFileManager defaultManager] moveItemAtURL:location
+ toURL:installerURL
+ error:&error]) {
+ self.claudeDownloadedInstallerURL = installerURL;
+ }
+ }
+ self.claudeDownloadError = error;
+}
+
+- (void)URLSession:(NSURLSession *)session
+ task:(NSURLSessionTask *)task
+didCompleteWithError:(NSError *)error {
+ if (session != self.claudeDownloadSession ||
+ task != self.claudeDownloadTask) {
+ return;
+ }
+ if (error != nil && !self.claudeDownloadCancelled) {
+ self.claudeDownloadError = error;
+ }
+ self.claudeDownloadCompleted = YES;
+ if (self.claudeDownloadModalRunning) {
+ [NSApp abortModal];
+ return;
+ }
+ [self finishClaudeDownload];
+}
+
+- (void)finishClaudeDownload {
+ BOOL cancelled = self.claudeDownloadCancelled;
+
+ [self.claudeDownloadProgress stopAnimation:nil];
+ [self.claudeDownloadAlert.window orderOut:nil];
+ [self.claudeAppRow.integrationSwitch setEnabled:YES];
+ [self.claudeAppRow setInactiveStatusText:@"Not installed"];
+ [self.claudeDownloadSession finishTasksAndInvalidate];
+ self.claudeDownloadTask = nil;
+ self.claudeDownloadSession = nil;
+ self.claudeDownloadProgress = nil;
+ self.claudeDownloadAlert = nil;
+
+ if (cancelled) {
+ self.claudeDownloadError = nil;
+ self.claudeDownloadedInstallerURL = nil;
+ self.claudeDownloadCancelled = NO;
+ self.claudeDownloadCompleted = NO;
+ return;
+ }
+ if (self.claudeDownloadError != nil ||
+ self.claudeDownloadedInstallerURL == nil) {
+ if (self.claudeDownloadError == nil) {
+ self.claudeDownloadError = [NSError
+ errorWithDomain:@"com.ollama.app"
+ code:3
+ userInfo:@{NSLocalizedDescriptionKey:
+ @"The Claude installer was not downloaded."}];
+ }
+ [self showClaudeDownloadFailure:self.claudeDownloadError];
+ self.claudeDownloadError = nil;
+ self.claudeDownloadedInstallerURL = nil;
+ self.claudeDownloadCancelled = NO;
+ self.claudeDownloadCompleted = NO;
+ return;
+ }
+ if (![[NSWorkspace sharedWorkspace]
+ openURL:self.claudeDownloadedInstallerURL]) {
+ NSError *openError = [NSError
+ errorWithDomain:@"com.ollama.app"
+ code:4
+ userInfo:@{NSLocalizedDescriptionKey:
+ @"The Claude installer could not be opened."}];
+ [self showClaudeDownloadFailure:openError];
+ }
+ self.claudeDownloadError = nil;
+ self.claudeDownloadedInstallerURL = nil;
+ self.claudeDownloadCancelled = NO;
+ self.claudeDownloadCompleted = NO;
+}
+
+- (void)toggleClaudeAppProxy:(NSButton *)sender {
+ BOOL enabled = sender.state == NSControlStateValueOn;
+ if (enabled && !IsClaudeDesktopInstalled()) {
+ [self.claudeAppRow setInactiveStatusText:@"Not installed"];
+ [self.claudeAppRow setIntegrationActive:NO];
+
+ NSAlert *installAlert = [[NSAlert alloc] init];
+ [installAlert setAlertStyle:NSAlertStyleInformational];
+ [installAlert setIcon:ollamaApplicationIcon()];
+ [installAlert setMessageText:@"Claude is not installed"];
+ [installAlert setInformativeText:
+ @"Download Claude to add Ollama models to the Claude app."];
+ [installAlert addButtonWithTitle:@"Download Claude"];
+ [installAlert addButtonWithTitle:@"Cancel"];
+ if ([installAlert runModal] == NSAlertFirstButtonReturn) {
+ [self downloadClaude];
+ }
+ return;
+ }
+ BOOL restartClaude = IsClaudeDesktopRunning();
+ if (restartClaude) {
+ NSAlert *restartAlert = [[NSAlert alloc] init];
+ [restartAlert setAlertStyle:NSAlertStyleWarning];
+ [restartAlert setIcon:ollamaApplicationIcon()];
+ [restartAlert setMessageText:enabled
+ ? @"Restart Claude Desktop to use Ollama?"
+ : @"Restart Claude Desktop to remove Ollama?"];
+ [restartAlert setInformativeText:enabled
+ ? @"Claude Desktop must restart to use Ollama. Any running task will stop."
+ : @"Claude Desktop must restart to remove Ollama. Any running task will stop."];
+ [restartAlert addButtonWithTitle:@"Restart Claude Desktop"];
+ [restartAlert addButtonWithTitle:@"Cancel"];
+ if ([restartAlert runModal] != NSAlertFirstButtonReturn) {
+ [self refreshClaudeAppState];
+ return;
+ }
+ }
+
+ [sender setEnabled:NO];
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
+ BOOL succeeded = SetClaudeGatewayInstalled(enabled, restartClaude);
+ dispatch_async(dispatch_get_main_queue(), ^{
+ [sender setEnabled:YES];
+ if (!succeeded) {
+ BOOL portConflict = enabled && ClaudeGatewayPortConflict();
+ [self refreshClaudeAppState];
+ NSAlert *alert = [[NSAlert alloc] init];
+ [alert setAlertStyle:NSAlertStyleWarning];
+ [alert setIcon:ollamaApplicationIcon()];
+ [alert setMessageText:portConflict
+ ? [NSString stringWithFormat:@"Port %d is already in use", ClaudeGatewayPort()]
+ : (enabled
+ ? @"Unable to use Ollama with Claude"
+ : @"Unable to remove Ollama from Claude")];
+ [alert setInformativeText:portConflict
+ ? [NSString stringWithFormat:@"Change OLLAMA_HOST or quit the app using port %d, then try again.", ClaudeGatewayPort()]
+ : @"Ollama could not update Claude. Check the Ollama log for details."];
+ [alert runModal];
+ return;
+ }
+
+ self.claudeAppEnabled = enabled;
+ self.claudeAppReady = enabled;
+ [self.claudeAppRow setActiveStatusText:nil];
+ [self.claudeAppRow setInactiveStatusText:nil];
+ [self.claudeAppRow setIntegrationActive:enabled];
+ [self.claudeAppRow setIntegrationReady:enabled];
+ if (enabled) {
+ RefreshClaudeProxyMenu();
+ [self openClaudeApp:nil];
+ }
+ });
+ });
+}
+
- (void)newChat {
[self uiRequest:@"/c/new"];
}
@@ -304,9 +1011,26 @@ static NSBundle *OllamaResourceBundle(void) {
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
- // Allow termination if the system is shutting down or restarting
if (self.systemShutdownInProgress) {
- return NSTerminateNow;
+ if (!IsClaudeGatewayConfigured()) {
+ return NSTerminateNow;
+ }
+ self.systemTerminationApplication = sender;
+ self.systemTerminationReplyPending = YES;
+ if (self.quitInProgress) {
+ return NSTerminateLater;
+ }
+ self.quitInProgress = YES;
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
+ BOOL succeeded = RestoreClaudeGatewayForShutdown();
+ if (!succeeded) {
+ appLogInfo(@"Unable to restore Claude during system shutdown");
+ }
+ dispatch_async(dispatch_get_main_queue(), ^{
+ [self completeSystemTermination];
+ });
+ });
+ return NSTerminateLater;
}
// Otherwise just hide the app (for Cmd+Q, close button, etc.)
[NSApp hide:nil];
@@ -314,6 +1038,17 @@ static NSBundle *OllamaResourceBundle(void) {
return NSTerminateCancel;
}
+- (void)completeSystemTermination {
+ if (!self.systemTerminationReplyPending) {
+ return;
+ }
+ NSApplication *application = self.systemTerminationApplication;
+ self.systemTerminationReplyPending = NO;
+ self.systemTerminationApplication = nil;
+ self.quitInProgress = NO;
+ [application replyToApplicationShouldTerminate:YES];
+}
+
- (IBAction)terminate:(id)sender {
[NSApp hide:nil];
[NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];
@@ -337,8 +1072,14 @@ static NSBundle *OllamaResourceBundle(void) {
NSImage *statusImage;
statusImage = [OllamaResourceBundle() imageForResource:iconName];
- [statusImage setTemplate:YES];
- self.statusItem.button.image = statusImage;
+ if (statusImage) {
+ [statusImage setTemplate:YES];
+ self.statusItem.button.title = @"";
+ self.statusItem.button.image = statusImage;
+ } else {
+ self.statusItem.button.image = nil;
+ self.statusItem.button.title = @"Ollama";
+ }
}
- (void)observeValueForKeyPath:(NSString *)keyPath
@@ -353,6 +1094,59 @@ static NSBundle *OllamaResourceBundle(void) {
[NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];
}
+- (void)requestQuit {
+ if (self.quitInProgress) {
+ return;
+ }
+ if (!IsClaudeGatewayConfigured()) {
+ [self quit];
+ return;
+ }
+
+ BOOL restartClaude = IsClaudeDesktopRunning();
+ if (restartClaude) {
+ NSAlert *alert = [[NSAlert alloc] init];
+ [alert setAlertStyle:NSAlertStyleWarning];
+ [alert setIcon:ollamaApplicationIcon()];
+ [alert setMessageText:@"Restart Claude before quitting Ollama?"];
+ [alert setInformativeText:
+ @"Claude must restart before Ollama quits. Any running task will stop."];
+ [alert addButtonWithTitle:@"Restart Claude and Quit"];
+ [alert addButtonWithTitle:@"Cancel"];
+ if ([alert runModal] != NSAlertFirstButtonReturn) {
+ return;
+ }
+ }
+
+ self.quitInProgress = YES;
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
+ BOOL succeeded = SetClaudeGatewayInstalled(false, restartClaude);
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if (self.systemTerminationReplyPending) {
+ if (!succeeded) {
+ appLogInfo(@"Unable to restore Claude during system shutdown");
+ }
+ [self completeSystemTermination];
+ return;
+ }
+ if (succeeded) {
+ [self quit];
+ return;
+ }
+
+ self.quitInProgress = NO;
+ [self refreshClaudeAppState];
+ NSAlert *alert = [[NSAlert alloc] init];
+ [alert setAlertStyle:NSAlertStyleWarning];
+ [alert setIcon:ollamaApplicationIcon()];
+ [alert setMessageText:@"Unable to quit Ollama"];
+ [alert setInformativeText:
+ @"Ollama couldn’t update Claude, so it is still running. Check the Ollama log and try again."];
+ [alert runModal];
+ });
+ });
+}
+
- (void)quit {
[NSApp stop:self];
[NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined
@@ -633,6 +1427,28 @@ void run(bool so, bool sh) {
StopUI();
}
+static BOOL isOllamaApplication(NSRunningApplication *app) {
+ NSString *bundleId = app.bundleIdentifier;
+ if (bundleId == nil || bundleId.length == 0) {
+ return NO;
+ }
+ return [bundleId isEqualToString:[[NSBundle mainBundle] bundleIdentifier]] ||
+ [bundleId isEqualToString:@"ai.ollama.ollama"] ||
+ [bundleId isEqualToString:@"com.electron.ollama"];
+}
+
+bool otherOllamaInstanceRunning(void) {
+ pid_t myPid = getpid();
+ for (NSRunningApplication *app in
+ [[NSWorkspace sharedWorkspace] runningApplications]) {
+ if (isOllamaApplication(app) && app.processIdentifier > 0 &&
+ app.processIdentifier != myPid) {
+ return true;
+ }
+ }
+ return false;
+}
+
// killOtherInstances kills all other instances of the app currently
// running. This way we can ensure that only the most recently started
// instance of Ollama is running
@@ -641,23 +1457,15 @@ void killOtherInstances() {
NSArray *apps = [[NSWorkspace sharedWorkspace] runningApplications];
for (NSRunningApplication *app in apps) {
- NSString *bundleId = app.bundleIdentifier;
-
- // Skip apps without bundle identifiers
- if (!bundleId || [bundleId length] == 0) {
- continue;
- }
-
- if ([bundleId isEqualToString:[[NSBundle mainBundle] bundleIdentifier]] ||
- [bundleId isEqualToString:@"ai.ollama.ollama"] ||
- [bundleId isEqualToString:@"com.electron.ollama"]) {
-
+ if (isOllamaApplication(app)) {
pid_t pid = app.processIdentifier;
if (pid != myPid && pid > 0) {
appLogInfo([NSString stringWithFormat:@"terminating other ollama instance %d", pid]);
- kill(pid, SIGTERM);
+ // Preserve the Claude profile while the replacement instance
+ // takes ownership of the local gateway.
+ kill(pid, SIGUSR1);
} else if (pid == -1) {
- appLogInfo([NSString stringWithFormat:@"skipping app with invalid pid: %@", bundleId]);
+ appLogInfo([NSString stringWithFormat:@"skipping app with invalid pid: %@", app.bundleIdentifier]);
}
}
}
@@ -993,6 +1801,20 @@ void updateAvailable() {
});
}
+void updateClaudeProxyMenu(unsigned long long routed) {
+ void (^updateMenu)(void) = ^{
+ NSString *status = routed == 1
+ ? @"1 request this session"
+ : [NSString stringWithFormat:@"%llu requests this session", routed];
+ [appDelegate.claudeAppRow setActiveStatusText:status];
+ };
+ if ([NSThread isMainThread]) {
+ updateMenu();
+ } else {
+ dispatch_async(dispatch_get_main_queue(), updateMenu);
+ }
+}
+
void quit() {
dispatch_async(dispatch_get_main_queue(), ^{
[appDelegate quit];
diff --git a/app/cmd/app/app_darwin_test.go b/app/cmd/app/app_darwin_test.go
new file mode 100644
index 000000000..43b26823c
--- /dev/null
+++ b/app/cmd/app/app_darwin_test.go
@@ -0,0 +1,362 @@
+//go:build darwin
+
+package main
+
+import (
+ "context"
+ "errors"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/internal/proxy"
+)
+
+func TestClaudeCloudModelsAvailable(t *testing.T) {
+ tests := []struct {
+ name string
+ cloudStatus func(context.Context) (*api.StatusResponse, error)
+ whoami func(context.Context) (*api.UserResponse, error)
+ want bool
+ }{
+ {
+ name: "signed in",
+ whoami: func(context.Context) (*api.UserResponse, error) {
+ return &api.UserResponse{Name: "parth"}, nil
+ },
+ want: true,
+ },
+ {
+ name: "signed out",
+ whoami: func(context.Context) (*api.UserResponse, error) {
+ return nil, api.AuthorizationError{StatusCode: http.StatusUnauthorized}
+ },
+ want: false,
+ },
+ {
+ name: "empty account",
+ whoami: func(context.Context) (*api.UserResponse, error) {
+ return &api.UserResponse{}, nil
+ },
+ want: false,
+ },
+ {
+ name: "cloud disabled",
+ cloudStatus: func(context.Context) (*api.StatusResponse, error) {
+ return &api.StatusResponse{Cloud: api.CloudStatus{Disabled: true}}, nil
+ },
+ whoami: func(context.Context) (*api.UserResponse, error) {
+ t.Fatal("whoami called while cloud was disabled")
+ return nil, nil
+ },
+ want: false,
+ },
+ {
+ name: "cloud status unavailable",
+ cloudStatus: func(context.Context) (*api.StatusResponse, error) {
+ return nil, errors.New("status unavailable")
+ },
+ whoami: func(context.Context) (*api.UserResponse, error) {
+ return &api.UserResponse{Name: "parth"}, nil
+ },
+ want: true,
+ },
+ {
+ name: "account check unavailable",
+ whoami: func(context.Context) (*api.UserResponse, error) {
+ return nil, errors.New("account service unavailable")
+ },
+ want: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ cloudStatus := tt.cloudStatus
+ if cloudStatus == nil {
+ cloudStatus = func(context.Context) (*api.StatusResponse, error) {
+ return &api.StatusResponse{}, nil
+ }
+ }
+ if got := claudeCloudModelsAvailable(context.Background(), cloudStatus, tt.whoami); got != tt.want {
+ t.Fatalf("claudeCloudModelsAvailable() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestClaudeLocalModels(t *testing.T) {
+ models, err := claudeLocalModels(context.Background(), func(context.Context) (*api.ListResponse, error) {
+ return &api.ListResponse{Models: []api.ListModelResponse{
+ {Name: "qwen3.8:27b-mlx", Model: "qwen3.8:27b-mlx"},
+ {Name: "alias:latest", Model: "original:latest"},
+ {Name: "remote-model:latest", Model: "remote-model:latest", RemoteModel: "upstream/model"},
+ {Name: "remote-host:latest", Model: "remote-host:latest", RemoteHost: "https://ollama.com"},
+ }}, nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := strings.Join(models, ","); got != "qwen3.8:27b-mlx,alias:latest,original:latest" {
+ t.Fatalf("local models = %q", got)
+ }
+ models, err = claudeLocalModels(context.Background(), func(context.Context) (*api.ListResponse, error) {
+ return &api.ListResponse{Models: []api.ListModelResponse{
+ {Name: "qwen3.8:27b-mlx", Model: "qwen3.8:27b-mlx", RemoteModel: "qwen3.8:27b-mlx"},
+ }}, nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(models) != 0 {
+ t.Fatalf("remote-only models = %v, want none", models)
+ }
+
+ wantErr := errors.New("list failed")
+ if _, err := claudeLocalModels(context.Background(), func(context.Context) (*api.ListResponse, error) {
+ return nil, wantErr
+ }); !errors.Is(err, wantErr) {
+ t.Fatalf("claudeLocalModels error = %v, want %v", err, wantErr)
+ }
+}
+
+func TestRestoreClaudeBeforeQuit(t *testing.T) {
+ called := false
+ if err := restoreClaudeBeforeQuit(context.Background(), false, false, func(context.Context) error {
+ called = true
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if called {
+ t.Fatal("restore called while Claude was not configured")
+ }
+
+ if err := restoreClaudeBeforeQuit(context.Background(), false, true, func(context.Context) error {
+ called = true
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if !called {
+ t.Fatal("restore was not called")
+ }
+
+ wantErr := errors.New("restore failed")
+ if err := restoreClaudeBeforeQuit(context.Background(), false, true, func(context.Context) error {
+ return wantErr
+ }); !errors.Is(err, wantErr) {
+ t.Fatalf("restore error = %v, want %v", err, wantErr)
+ }
+
+ called = false
+ if err := restoreClaudeBeforeQuit(context.Background(), true, true, func(context.Context) error {
+ called = true
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if called {
+ t.Fatal("restore called during an app replacement handoff")
+ }
+}
+
+func TestSetClaudeGatewayInstalledRejectsMissingClaude(t *testing.T) {
+ previousInstalled := claudeDesktopInstalled
+ claudeDesktopInstalled = func() bool { return false }
+ t.Cleanup(func() {
+ claudeDesktopInstalled = previousInstalled
+ })
+
+ err := setClaudeGatewayInstalled(true, false)
+ if err == nil || !strings.Contains(err.Error(), "not installed") {
+ t.Fatalf("setClaudeGatewayInstalled error = %v, want missing Claude error", err)
+ }
+ if claudeAppProxy != nil {
+ t.Fatal("Claude gateway started without Claude Desktop installed")
+ }
+}
+
+func TestClaudeGatewayRejectsOllamaHostPortConflict(t *testing.T) {
+ t.Setenv("OLLAMA_HOST", "0.0.0.0:11435")
+
+ previousInstalled := claudeDesktopInstalled
+ previousAddr := claudeProxyListenAddr
+ claudeDesktopInstalled = func() bool { return true }
+ claudeProxyListenAddr = proxy.DefaultClaudeDesktopListenAddr
+ t.Cleanup(func() {
+ stopClaudeAppProxy()
+ claudeDesktopInstalled = previousInstalled
+ claudeProxyListenAddr = previousAddr
+ })
+
+ err := startClaudeAppProxy()
+ if err == nil || !strings.Contains(err.Error(), "port 11435") {
+ t.Fatalf("startClaudeAppProxy error = %v, want reserved-port error", err)
+ }
+ if claudeAppProxy != nil {
+ t.Fatal("Claude gateway started with a conflicting OLLAMA_HOST")
+ }
+ if !claudeGatewayStartFailed() {
+ t.Fatal("expected the port conflict to remain visible to the menu")
+ }
+ if !claudeGatewayPortConflict() {
+ t.Fatal("expected the menu failure to be classified as a port conflict")
+ }
+}
+
+func TestClaudeGatewayPortTracksListenAddress(t *testing.T) {
+ previousAddr := claudeProxyListenAddr
+ claudeProxyListenAddr = "127.0.0.1:23001"
+ t.Cleanup(func() {
+ claudeProxyListenAddr = previousAddr
+ })
+
+ port, err := claudeGatewayPort()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if port != "23001" || int(ClaudeGatewayPort()) != 23001 {
+ t.Fatalf("Claude gateway port = %q/%d, want 23001", port, int(ClaudeGatewayPort()))
+ }
+}
+
+func TestClaudeGatewayDoesNotReportPortConflictWithoutClaude(t *testing.T) {
+ t.Setenv("OLLAMA_HOST", "0.0.0.0:11435")
+
+ previousInstalled := claudeDesktopInstalled
+ previousAddr := claudeProxyListenAddr
+ claudeDesktopInstalled = func() bool { return false }
+ claudeProxyListenAddr = proxy.DefaultClaudeDesktopListenAddr
+ t.Cleanup(func() {
+ stopClaudeAppProxy()
+ claudeProxyMu.Lock()
+ clearClaudeProxyFailure()
+ claudeProxyMu.Unlock()
+ claudeDesktopInstalled = previousInstalled
+ claudeProxyListenAddr = previousAddr
+ })
+
+ if err := startClaudeAppProxy(); err != nil {
+ t.Fatalf("startClaudeAppProxy error = %v, want absent Claude to skip the gateway", err)
+ }
+ if claudeGatewayStartFailed() || claudeGatewayPortConflict() {
+ t.Fatal("absent Claude exposed a gateway port conflict")
+ }
+}
+
+func TestClaudeGatewayRecoversAfterPortConflict(t *testing.T) {
+ setClaudeProxyRetry(t, 20*time.Millisecond, 5*time.Millisecond)
+ conflict := httptest.NewServer(http.NotFoundHandler())
+ t.Cleanup(conflict.Close)
+ addr := conflict.Listener.Addr().String()
+
+ previousInstalled := claudeDesktopInstalled
+ previousAddr := claudeProxyListenAddr
+ claudeDesktopInstalled = func() bool { return true }
+ claudeProxyListenAddr = addr
+ t.Cleanup(func() {
+ stopClaudeAppProxy()
+ claudeDesktopInstalled = previousInstalled
+ claudeProxyListenAddr = previousAddr
+ })
+
+ if err := startClaudeAppProxy(); err == nil {
+ t.Fatal("startClaudeAppProxy succeeded while another service owned the port")
+ }
+ if !claudeGatewayStartFailed() {
+ t.Fatal("expected the failed start to remain visible to the menu")
+ }
+ if !claudeGatewayPortConflict() {
+ t.Fatal("expected an occupied gateway port to be classified as a conflict")
+ }
+
+ conflict.Close()
+ if err := startClaudeAppProxy(); err != nil {
+ t.Fatalf("startClaudeAppProxy did not recover after the port was released: %v", err)
+ }
+ if claudeGatewayStartFailed() {
+ t.Fatal("expected a successful retry to clear the menu failure state")
+ }
+ if claudeGatewayPortConflict() {
+ t.Fatal("expected a successful retry to clear the port conflict state")
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ if err := proxy.ProbeClaudeDesktop(ctx, "http://"+addr); err != nil {
+ t.Fatalf("recovered Claude gateway is not reachable: %v", err)
+ }
+}
+
+func TestClaudeGatewayRejectsSpoofedExistingGateway(t *testing.T) {
+ setClaudeProxyRetry(t, 20*time.Millisecond, 5*time.Millisecond)
+ spoof := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("X-Ollama-Claude-Gateway", "1")
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ defer spoof.Close()
+
+ previousInstalled := claudeDesktopInstalled
+ previousAddr := claudeProxyListenAddr
+ claudeDesktopInstalled = func() bool { return true }
+ claudeProxyListenAddr = spoof.Listener.Addr().String()
+ t.Cleanup(func() {
+ stopClaudeAppProxy()
+ claudeDesktopInstalled = previousInstalled
+ claudeProxyListenAddr = previousAddr
+ })
+
+ if err := startClaudeAppProxy(); err == nil {
+ t.Fatal("startClaudeAppProxy trusted a listener with a spoofed health response")
+ }
+ if claudeAppProxy != nil || !claudeGatewayPortConflict() {
+ t.Fatal("spoofed listener was not reported as a port conflict")
+ }
+}
+
+func TestClaudeGatewayWaitsForPreviousListenerToExit(t *testing.T) {
+ setClaudeProxyRetry(t, 500*time.Millisecond, 5*time.Millisecond)
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ previousInstalled := claudeDesktopInstalled
+ previousAddr := claudeProxyListenAddr
+ claudeDesktopInstalled = func() bool { return true }
+ claudeProxyListenAddr = listener.Addr().String()
+ t.Cleanup(func() {
+ _ = listener.Close()
+ stopClaudeAppProxy()
+ claudeDesktopInstalled = previousInstalled
+ claudeProxyListenAddr = previousAddr
+ })
+
+ go func() {
+ time.Sleep(30 * time.Millisecond)
+ _ = listener.Close()
+ }()
+ if err := startClaudeAppProxy(); err != nil {
+ t.Fatalf("startClaudeAppProxy did not acquire a released handoff port: %v", err)
+ }
+ if claudeGatewayStartFailed() || claudeAppProxy == nil {
+ t.Fatal("released handoff port did not start the Claude gateway")
+ }
+}
+
+func setClaudeProxyRetry(t *testing.T, wait, poll time.Duration) {
+ t.Helper()
+ previousWait := claudeProxyRetryWait
+ previousPoll := claudeProxyRetryPoll
+ claudeProxyRetryWait = wait
+ claudeProxyRetryPoll = poll
+ t.Cleanup(func() {
+ claudeProxyRetryWait = previousWait
+ claudeProxyRetryPoll = previousPoll
+ })
+}
diff --git a/app/darwin/Ollama.app/Contents/Resources/claude.svg b/app/darwin/Ollama.app/Contents/Resources/claude.svg
new file mode 100644
index 000000000..879ad8126
--- /dev/null
+++ b/app/darwin/Ollama.app/Contents/Resources/claude.svg
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Generated by Pixelmator Pro 3.6.17 -->
+<svg width="1200" height="1200" viewBox="0 0 1200 1200" xmlns="http://www.w3.org/2000/svg">
+ <g id="g314">
+ <path id="path147" fill="#d97757" stroke="none" d="M 233.959793 800.214905 L 468.644287 668.536987 L 472.590637 657.100647 L 468.644287 650.738403 L 457.208069 650.738403 L 417.986633 648.322144 L 283.892639 644.69812 L 167.597321 639.865845 L 54.926208 633.825623 L 26.577238 627.785339 L 3.3e-05 592.751709 L 2.73832 575.27533 L 26.577238 559.248352 L 60.724873 562.228149 L 136.187973 567.382629 L 249.422867 575.194763 L 331.570496 580.026978 L 453.261841 592.671082 L 472.590637 592.671082 L 475.328857 584.859009 L 468.724915 580.026978 L 463.570557 575.194763 L 346.389313 495.785217 L 219.543671 411.865906 L 153.100723 363.543762 L 117.181267 339.060425 L 99.060455 316.107361 L 91.248367 266.01355 L 123.865784 230.093994 L 167.677887 233.073853 L 178.872513 236.053772 L 223.248367 270.201477 L 318.040283 343.570496 L 441.825592 434.738342 L 459.946411 449.798706 L 467.194672 444.64447 L 468.080597 441.020203 L 459.946411 427.409485 L 392.617493 305.718323 L 320.778564 181.932983 L 288.80542 130.630859 L 280.348999 99.865845 C 277.369171 87.221436 275.194641 76.590698 275.194641 63.624268 L 312.322174 13.20813 L 332.8591 6.604126 L 382.389313 13.20813 L 403.248352 31.328979 L 434.013519 101.71814 L 483.865753 212.537048 L 561.181274 363.221497 L 583.812134 407.919434 L 595.892639 449.315491 L 600.40271 461.959839 L 608.214783 461.959839 L 608.214783 454.711609 L 614.577271 369.825623 L 626.335632 265.61084 L 637.771851 131.516846 L 641.718201 93.745117 L 660.402832 48.483276 L 697.530334 24.000122 L 726.52356 37.852417 L 750.362549 72 L 747.060486 94.067139 L 732.886047 186.201416 L 705.100708 330.52356 L 686.979919 427.167847 L 697.530334 427.167847 L 709.61084 415.087341 L 758.496704 350.174561 L 840.644348 247.490051 L 876.885925 206.738342 L 919.167847 161.71814 L 946.308838 140.29541 L 997.61084 140.29541 L 1035.38269 196.429626 L 1018.469849 254.416199 L 965.637634 321.422852 L 921.825562 378.201538 L 859.006714 462.765259 L 819.785278 530.41626 L 823.409424 535.812073 L 832.75177 534.92627 L 974.657776 504.724915 L 1051.328979 490.872559 L 1142.818848 475.167786 L 1184.214844 494.496582 L 1188.724854 514.147644 L 1172.456421 554.335693 L 1074.604126 578.496765 L 959.838989 601.449829 L 788.939636 641.879272 L 786.845764 643.409485 L 789.261841 646.389343 L 866.255127 653.637634 L 899.194702 655.409424 L 979.812134 655.409424 L 1129.932861 666.604187 L 1169.154419 692.537109 L 1192.671265 724.268677 L 1188.724854 748.429688 L 1128.322144 779.194641 L 1046.818848 759.865845 L 856.590759 714.604126 L 791.355774 698.335754 L 782.335693 698.335754 L 782.335693 703.731567 L 836.69812 756.885986 L 936.322205 846.845581 L 1061.073975 962.81897 L 1067.436279 991.490112 L 1051.409424 1014.120911 L 1034.496704 1011.704712 L 924.885986 929.234924 L 882.604126 892.107544 L 786.845764 811.48999 L 780.483276 811.48999 L 780.483276 819.946289 L 802.550415 852.241699 L 919.087341 1027.409424 L 925.127625 1081.127686 L 916.671204 1098.604126 L 886.469849 1109.154419 L 853.288696 1103.114136 L 785.073914 1007.355835 L 714.684631 899.516785 L 657.906067 802.872498 L 650.979858 806.81897 L 617.476624 1167.704834 L 601.771851 1186.147705 L 565.530212 1200 L 535.328857 1177.046997 L 519.302124 1139.919556 L 535.328857 1066.550537 L 554.657776 970.792053 L 570.362488 894.68457 L 584.536926 800.134277 L 592.993347 768.724976 L 592.429626 766.630859 L 585.503479 767.516968 L 514.22821 865.369263 L 405.825531 1011.865906 L 320.053711 1103.677979 L 299.516815 1111.812256 L 263.919525 1093.369263 L 267.221497 1060.429688 L 287.114136 1031.114136 L 405.825531 880.107361 L 477.422913 786.52356 L 523.651062 732.483276 L 523.328918 724.671265 L 520.590698 724.671265 L 205.288605 929.395935 L 149.154434 936.644409 L 124.993355 914.01355 L 127.973183 876.885986 L 139.409409 864.80542 L 234.201385 799.570435 L 233.879227 799.8927 Z"/>
+ </g>
+</svg>
diff --git a/cmd/launch/claude_desktop.go b/cmd/launch/claude_desktop.go
index 1ef8182c9..419b594ec 100644
--- a/cmd/launch/claude_desktop.go
+++ b/cmd/launch/claude_desktop.go
@@ -5,8 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
- "io"
- "net/http"
+ "net/url"
"os"
"os/exec"
"path/filepath"
@@ -16,22 +15,25 @@ import (
"github.com/ollama/ollama/cmd/config"
"github.com/ollama/ollama/cmd/internal/fileutil"
- "golang.org/x/term"
+ "github.com/ollama/ollama/internal/proxy"
)
const (
claudeDesktopIntegrationName = "claude-desktop"
claudeDesktopProfileName = "Ollama"
claudeDesktopProfileID = "00000000-0000-4000-8000-000000000114"
- claudeDesktopGatewayBaseURL = "https://ollama.com"
- claudeDesktopAPIKeyURL = "https://ollama.com/settings/keys"
- claudeDesktopModelLabel = "Ollama Cloud"
- claudeDesktopUnsupported = "Claude Desktop is no longer supported. Existing installations can be restored with 'ollama launch claude-desktop --restore'."
- claudeDesktopSuccessMessage = "Claude Desktop profile changed to Ollama Cloud."
+ claudeDesktopGatewayBaseURL = "http://" + proxy.DefaultClaudeDesktopListenAddr
+ claudeDesktopProbeTimeout = 2 * time.Second
+ claudeDesktopModelLabel = "Default Ollama model"
+ claudeDesktopSuccessMessage = "Claude Desktop profile changed to Ollama."
claudeDesktopRestoreMessage = "To restore the usual Claude profile, run: ollama launch claude-desktop --restore"
claudeDesktopRestoredMessage = "Claude Desktop restored to the usual Claude profile."
)
+// Cowork needs unrestricted egress for user-configured plugins and MCP servers.
+// Restore removes this override with the rest of the Ollama profile settings.
+var claudeDesktopEgressHosts = []string{"*"}
+
var (
claudeDesktopGOOS = runtime.GOOS
claudeDesktopUserHome = os.UserHomeDir
@@ -39,17 +41,14 @@ var (
claudeDesktopOpenApp = defaultClaudeDesktopOpenApp
claudeDesktopOpenAppPath = defaultClaudeDesktopOpenAppPath
claudeDesktopQuitApp = defaultClaudeDesktopQuitApp
- claudeDesktopIsRunning = defaultClaudeDesktopIsRunning
+ claudeDesktopIsRunning = defaultClaudeDesktopRunning
claudeDesktopRunningAppPath = defaultClaudeDesktopRunningAppPath
claudeDesktopGlob = filepath.Glob
- claudeDesktopSleep = time.Sleep
- claudeDesktopHTTPClient = http.DefaultClient
- claudeDesktopPromptAPIKey = promptClaudeDesktopAPIKey
- claudeDesktopValidateAPIKey = validateClaudeDesktopAPIKey
+ claudeDesktopProbeGateway = proxy.ProbeClaudeDesktop
)
// ClaudeDesktop configures and launches Claude Desktop in third-party
-// inference mode using Ollama Cloud as the gateway.
+// inference mode using the Ollama app's local gateway.
type ClaudeDesktop struct{}
func (c *ClaudeDesktop) String() string { return "Claude Desktop" }
@@ -68,34 +67,14 @@ func (c *ClaudeDesktop) ConfigureAutodiscovery() error {
if err := claudeDesktopSupported(); err != nil {
return err
}
-
- targets, err := claudeDesktopTargetPaths()
- if err != nil {
+ if err := ensureClaudeDesktopGateway(); err != nil {
return err
}
-
- key, err := claudeDesktopValidatedAPIKey(context.Background(), claudeDesktopTargetProfilePaths(targets))
+ targets, err := claudeDesktopTargetPaths()
if err != nil {
return err
}
-
- for _, path := range targets.normalConfigs {
- if err := writeClaudeDesktopDeploymentMode(path, "3p"); err != nil {
- return err
- }
- }
- for _, target := range targets.thirdPartyProfiles {
- if err := writeClaudeDesktopDeploymentMode(target.desktopConfig, "3p"); err != nil {
- return err
- }
- if err := writeClaudeDesktopMeta(target.meta, claudeDesktopProfileID, claudeDesktopProfileName); err != nil {
- return err
- }
- if err := writeClaudeDesktopGatewayProfile(target.profile, key, true); err != nil {
- return err
- }
- }
- return nil
+ return configureClaudeDesktopTargets(targets, claudeDesktopGatewayBaseURL, "ollama")
}
func (c *ClaudeDesktop) RestoreHint() string {
@@ -118,6 +97,76 @@ func (c *ClaudeDesktop) AutodiscoveryConfigured() bool {
return claudeDesktopTargetsConfigured(targets)
}
+// UsesOllamaGateway reports whether Claude Desktop is currently routed through
+// Ollama's local gateway. It intentionally ignores auxiliary profile settings
+// so the gateway can keep serving while those settings are repaired.
+func (c *ClaudeDesktop) UsesOllamaGateway() bool {
+ targets, err := claudeDesktopTargetPaths()
+ if err != nil {
+ return false
+ }
+ return claudeDesktopTargetsUseOllamaGateway(targets)
+}
+
+// SetInstalledFromDesktop changes the Claude profile from the native Ollama app.
+func (c *ClaudeDesktop) SetInstalledFromDesktop(installed, restart bool) error {
+ if err := claudeDesktopSupported(); err != nil {
+ return err
+ }
+
+ applyProfile := restoreClaudeDesktopProfile
+ if installed {
+ applyProfile = c.ConfigureAutodiscovery
+ }
+
+ running, err := claudeDesktopIsRunning(context.Background())
+ if err != nil {
+ return fmt.Errorf("check whether Claude Desktop is running: %w", err)
+ }
+ if !running {
+ if err := applyProfile(); err != nil {
+ return err
+ }
+ if installed {
+ return claudeDesktopOpenApp()
+ }
+ return nil
+ }
+ if !restart {
+ return errors.New("Claude Desktop restart confirmation is required before changing its profile")
+ }
+ return restartClaudeDesktop(applyProfile)
+}
+
+// RestoreForShutdown restores Claude's usual profile without reopening the app.
+func (c *ClaudeDesktop) RestoreForShutdown(ctx context.Context) error {
+ if err := claudeDesktopSupported(); err != nil {
+ return err
+ }
+ running, err := claudeDesktopIsRunning(ctx)
+ if err != nil {
+ return fmt.Errorf("check whether Claude Desktop is running: %w", err)
+ }
+ if !running {
+ return restoreClaudeDesktopProfile()
+ }
+ if err := claudeDesktopQuitApp(ctx); err != nil {
+ return fmt.Errorf("quit Claude Desktop: %w", err)
+ }
+ if err := waitForClaudeDesktopExit(ctx); err != nil {
+ return err
+ }
+ return restoreClaudeDesktopProfile()
+}
+
+func restoreClaudeDesktopProfile() error {
+ targets, err := claudeDesktopTargetPaths()
+ if err != nil {
+ return err
+ }
+ return restoreClaudeDesktopTargets(targets)
+}
+
func (c *ClaudeDesktop) Onboard() error {
return config.MarkIntegrationOnboarded(claudeDesktopIntegrationName)
}
@@ -130,12 +179,21 @@ func (c *ClaudeDesktop) SkipModelReadiness() bool {
return true
}
-func (c *ClaudeDesktop) Run(_ string, _ []LaunchModel, _ []string) error {
- return errClaudeDesktopUnsupported()
+func (c *ClaudeDesktop) Run(_ string, _ []LaunchModel, args []string) error {
+ if err := claudeDesktopSupported(); err != nil {
+ return err
+ }
+ if len(args) > 0 {
+ return errors.New("claude-desktop does not accept extra arguments")
+ }
+ if err := ensureClaudeDesktopGateway(); err != nil {
+ return err
+ }
+ return claudeDesktopLaunchOrRestart("Restart Claude Desktop to use Ollama?", c.ConfigureAutodiscovery)
}
func (c *ClaudeDesktop) Restore() error {
- if err := claudeDesktopSupported(); err != nil {
+ if err := claudeDesktopRestoreSupported(); err != nil {
return err
}
targets, err := claudeDesktopTargetPaths()
@@ -143,6 +201,35 @@ func (c *ClaudeDesktop) Restore() error {
return err
}
+ if err := restoreClaudeDesktopTargets(targets); err != nil {
+ return err
+ }
+ return claudeDesktopLaunchOrRestart("Restart Claude Desktop to use the usual Claude profile?", func() error {
+ return restoreClaudeDesktopTargets(targets)
+ })
+}
+
+func configureClaudeDesktopTargets(targets claudeDesktopTargets, baseURL, apiKey string) error {
+ for _, target := range targets.thirdPartyProfiles {
+ if err := writeClaudeDesktopGatewayProfile(target.profile, baseURL, apiKey, true); err != nil {
+ return err
+ }
+ if err := writeClaudeDesktopMeta(target.meta, claudeDesktopProfileID, claudeDesktopProfileName); err != nil {
+ return err
+ }
+ if err := writeClaudeDesktopDeploymentMode(target.desktopConfig, "3p"); err != nil {
+ return err
+ }
+ }
+ for _, path := range targets.normalConfigs {
+ if err := writeClaudeDesktopDeploymentMode(path, "3p"); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func restoreClaudeDesktopTargets(targets claudeDesktopTargets) error {
for _, path := range targets.normalConfigs {
if err := writeClaudeDesktopDeploymentMode(path, "1p"); err != nil {
return err
@@ -159,27 +246,42 @@ func (c *ClaudeDesktop) Restore() error {
return err
}
}
- return claudeDesktopLaunchOrRestart("Restart Claude Desktop to use the usual Claude profile?")
+ return nil
}
-func errClaudeDesktopUnsupported() error {
- return errors.New(claudeDesktopUnsupported)
+func claudeDesktopSupported() error {
+ if claudeDesktopGOOS == "darwin" {
+ return nil
+ }
+ return errors.New("Claude Desktop launch is only supported on macOS")
}
-func claudeDesktopSupported() error {
- switch claudeDesktopGOOS {
- case "darwin", "windows":
+func claudeDesktopRestoreSupported() error {
+ if claudeDesktopGOOS == "darwin" || claudeDesktopGOOS == "windows" {
return nil
- default:
- return fmt.Errorf("Claude Desktop launch is only supported on macOS and Windows")
}
+ return errors.New("Claude Desktop restore is only supported on macOS and Windows")
}
-func claudeDesktopInstalled() bool {
- if claudeDesktopAppPath() != "" {
- return true
+func ensureClaudeDesktopGateway() error {
+ ctx, cancel := context.WithTimeout(context.Background(), claudeDesktopProbeTimeout)
+ defer cancel()
+ if err := claudeDesktopProbeGateway(ctx, claudeDesktopGatewayBaseURL); err != nil {
+ return fmt.Errorf("Claude gateway is unavailable at %s: %w; restart Ollama and try again", claudeDesktopGatewayBaseURL, err)
+ }
+ return nil
+}
+
+// ClaudeDesktopInstalled reports whether Claude Desktop is installed.
+func ClaudeDesktopInstalled() bool {
+ if claudeDesktopGOOS == "darwin" {
+ return claudeDesktopAppPath() != ""
+ }
+ if claudeDesktopGOOS != "windows" {
+ return false
}
- if claudeDesktopGOOS == "windows" && claudeDesktopIsRunning() {
+ running, _ := claudeDesktopIsRunning(context.Background())
+ if claudeDesktopAppPath() != "" || running {
return true
}
for _, dir := range claudeDesktopProfileDirCandidates(false) {
@@ -327,7 +429,7 @@ func claudeDesktopWindowsConfigPaths() (claudeDesktopPaths, error) {
func claudeDesktopProfileDir(normal bool) (string, error) {
candidates := claudeDesktopProfileDirCandidates(normal)
if len(candidates) == 0 {
- return "", fmt.Errorf("Claude Desktop profile directory could not be resolved")
+ return "", errors.New("Claude Desktop profile directory could not be resolved")
}
for _, candidate := range candidates {
if _, err := claudeDesktopStat(candidate); err == nil {
@@ -413,14 +515,6 @@ func newClaudeDesktopTargets(normalRoots, thirdPartyRoots []string) claudeDeskto
return targets
}
-func claudeDesktopTargetProfilePaths(targets claudeDesktopTargets) []string {
- paths := make([]string, 0, len(targets.thirdPartyProfiles))
- for _, target := range targets.thirdPartyProfiles {
- paths = append(paths, target.profile)
- }
- return paths
-}
-
func claudeDesktopLocalAppData() (string, error) {
if local := strings.TrimSpace(os.Getenv("LOCALAPPDATA")); local != "" {
return local, nil
@@ -435,139 +529,6 @@ func claudeDesktopLocalAppData() (string, error) {
return filepath.Join(home, "AppData", "Local"), nil
}
-type claudeDesktopAPIKeySource int
-
-const (
- claudeDesktopAPIKeySourceNone claudeDesktopAPIKeySource = iota
- claudeDesktopAPIKeySourceEnv
- claudeDesktopAPIKeySourceProfile
-)
-
-func claudeDesktopValidatedAPIKey(ctx context.Context, profilePaths []string) (string, error) {
- key, source, err := claudeDesktopAPIKey(profilePaths)
- if err != nil {
- return "", err
- }
- if err := claudeDesktopValidateAPIKey(ctx, key); err == nil {
- return key, nil
- } else if source != claudeDesktopAPIKeySourceProfile || !canPromptClaudeDesktopAPIKey() {
- return "", err
- }
- return promptValidClaudeDesktopAPIKey(ctx)
-}
-
-func claudeDesktopAPIKey(profilePaths []string) (string, claudeDesktopAPIKeySource, error) {
- if key := strings.TrimSpace(os.Getenv("OLLAMA_API_KEY")); key != "" {
- return key, claudeDesktopAPIKeySourceEnv, nil
- }
- for _, profilePath := range profilePaths {
- if key := readClaudeDesktopGatewayAPIKey(profilePath); key != "" {
- return key, claudeDesktopAPIKeySourceProfile, nil
- }
- }
- key, err := promptClaudeDesktopAPIKeyValue()
- return key, claudeDesktopAPIKeySourceNone, err
-}
-
-func canPromptClaudeDesktopAPIKey() bool {
- return isInteractiveSession() && !currentLaunchConfirmPolicy.requireYesMessage
-}
-
-func promptValidClaudeDesktopAPIKey(ctx context.Context) (string, error) {
- key, err := promptClaudeDesktopAPIKeyValue()
- if err != nil {
- return "", err
- }
- if err := claudeDesktopValidateAPIKey(ctx, key); err != nil {
- return "", err
- }
- return key, nil
-}
-
-func promptClaudeDesktopAPIKeyValue() (string, error) {
- if !canPromptClaudeDesktopAPIKey() {
- return "", missingClaudeDesktopAPIKeyError()
- }
- key, err := claudeDesktopPromptAPIKey()
- if err != nil {
- return "", err
- }
- key = strings.TrimSpace(key)
- if key == "" {
- return "", missingClaudeDesktopAPIKeyError()
- }
- return key, nil
-}
-
-func missingClaudeDesktopAPIKeyError() error {
- return fmt.Errorf("OLLAMA_API_KEY is required for Claude Desktop. Create an API key at %s, then re-run with OLLAMA_API_KEY set", claudeDesktopAPIKeyURL)
-}
-
-func promptClaudeDesktopAPIKey() (string, error) {
- fmt.Fprint(os.Stderr, claudeDesktopAPIKeyPrompt())
- key, err := term.ReadPassword(int(os.Stdin.Fd()))
- fmt.Fprintln(os.Stderr)
- if err != nil {
- return "", err
- }
- return string(key), nil
-}
-
-func claudeDesktopAPIKeyPrompt() string {
- return fmt.Sprintf("Create an Ollama API key at %s\nEnter Ollama API key (input hidden): ", claudeDesktopAPIKeyURL)
-}
-
-func readClaudeDesktopGatewayAPIKey(path string) string {
- cfg, err := readClaudeDesktopJSON(path)
- if err != nil {
- return ""
- }
- key, _ := cfg["inferenceGatewayApiKey"].(string)
- return strings.TrimSpace(key)
-}
-
-func validateClaudeDesktopAPIKey(ctx context.Context, key string) error {
- ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
- defer cancel()
-
- if claudeDesktopAPIKeyHasInvalidHeaderChars(key) {
- return claudeDesktopAPIKeyVerificationError()
- }
-
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, claudeDesktopGatewayBaseURL+"/v1/models", nil)
- if err != nil {
- return claudeDesktopAPIKeyVerificationError()
- }
- req.Header.Set("Authorization", "Bearer "+key)
- req.Header.Set("Accept", "application/json")
-
- resp, err := claudeDesktopHTTPClient.Do(req)
- if err != nil {
- return claudeDesktopAPIKeyVerificationError()
- }
- defer resp.Body.Close()
- _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10))
-
- switch {
- case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden:
- return fmt.Errorf("Ollama API key was rejected; create a valid key at %s", claudeDesktopAPIKeyURL)
- case resp.StatusCode >= 200 && resp.StatusCode < 300:
- return nil
- default:
- return fmt.Errorf("could not verify Ollama API key; ollama.com returned status %d, try again later", resp.StatusCode)
- }
-}
-
-func claudeDesktopAPIKeyHasInvalidHeaderChars(key string) bool {
- return strings.ContainsFunc(key, func(r rune) bool {
- return r < ' ' || r == 0x7f
- })
-}
-
-func claudeDesktopAPIKeyVerificationError() error {
- return fmt.Errorf("could not verify Ollama API key; copy a key from %s and try again", claudeDesktopAPIKeyURL)
-}
-
func writeClaudeDesktopDeploymentMode(path, mode string) error {
cfg, err := readClaudeDesktopJSONAllowMissing(path)
if err != nil {
@@ -604,17 +565,25 @@ func writeClaudeDesktopMeta(path, id, name string) error {
return writeClaudeDesktopJSON(path, meta)
}
-func writeClaudeDesktopGatewayProfile(path string, apiKey string, forceChooser bool) error {
+func writeClaudeDesktopGatewayProfile(path, baseURL, apiKey string, forceChooser bool) error {
cfg, err := readClaudeDesktopJSONAllowMissing(path)
if err != nil {
return fmt.Errorf("parse Claude Desktop Ollama profile: %w", err)
}
cfg["inferenceProvider"] = "gateway"
- cfg["inferenceGatewayBaseUrl"] = claudeDesktopGatewayBaseURL
+ cfg["inferenceGatewayBaseUrl"] = baseURL
cfg["inferenceGatewayApiKey"] = apiKey
cfg["inferenceGatewayAuthScheme"] = "bearer"
+ cfg["chatTabEnabled"] = true
delete(cfg, "inferenceModels")
cfg["disableDeploymentModeChooser"] = forceChooser
+ cfg["coworkEgressAllowedHosts"] = claudeDesktopEgressHosts
+ cfg["disableEssentialTelemetry"] = true
+ cfg["disableNonessentialTelemetry"] = true
+ // Auto mode sends separate classifier requests through the configured
+ // inference provider. Keep it disabled until the mapped models are tested
+ // for that classifier contract.
+ cfg["autoModeEnabled"] = false
return writeClaudeDesktopJSON(path, cfg)
}
@@ -666,6 +635,10 @@ func restoreClaudeDesktopOllamaProfile(path string) error {
delete(cfg, "inferenceGatewayBaseUrl")
delete(cfg, "inferenceGatewayAuthScheme")
delete(cfg, "inferenceModels")
+ delete(cfg, "coworkEgressAllowedHosts")
+ delete(cfg, "autoModeEnabled")
+ delete(cfg, "disableEssentialTelemetry")
+ delete(cfg, "disableNonessentialTelemetry")
return writeClaudeDesktopJSON(path, cfg)
}
@@ -688,6 +661,18 @@ func readClaudeDesktopDeploymentMode(path string) string {
}
func claudeDesktopTargetsConfigured(targets claudeDesktopTargets) bool {
+ if !claudeDesktopTargetsUseOllamaGateway(targets) {
+ return false
+ }
+ for _, target := range targets.thirdPartyProfiles {
+ if !claudeDesktopThirdPartyProfileConfigured(target) {
+ return false
+ }
+ }
+ return true
+}
+
+func claudeDesktopTargetsUseOllamaGateway(targets claudeDesktopTargets) bool {
if len(targets.normalConfigs) == 0 || len(targets.thirdPartyProfiles) == 0 {
return false
}
@@ -700,7 +685,7 @@ func claudeDesktopTargetsConfigured(targets claudeDesktopTargets) bool {
if readClaudeDesktopDeploymentMode(target.desktopConfig) != "3p" {
return false
}
- if !claudeDesktopThirdPartyProfileConfigured(target) {
+ if !claudeDesktopThirdPartyProfileUsesOllamaGateway(target) {
return false
}
}
@@ -708,6 +693,36 @@ func claudeDesktopTargetsConfigured(targets claudeDesktopTargets) bool {
}
func claudeDesktopThirdPartyProfileConfigured(target claudeDesktopThirdPartyPaths) bool {
+ if !claudeDesktopThirdPartyProfileUsesOllamaGateway(target) {
+ return false
+ }
+
+ cfg, err := readClaudeDesktopJSON(target.profile)
+ if err != nil {
+ return false
+ }
+ if s, _ := cfg["inferenceGatewayApiKey"].(string); strings.TrimSpace(s) == "" {
+ return false
+ }
+ egressHosts := claudeDesktopAnySlice(cfg["coworkEgressAllowedHosts"])
+ if len(egressHosts) != len(claudeDesktopEgressHosts) {
+ return false
+ }
+ for i, host := range egressHosts {
+ if host != claudeDesktopEgressHosts[i] {
+ return false
+ }
+ }
+ if disabled, _ := cfg["disableEssentialTelemetry"].(bool); !disabled {
+ return false
+ }
+ if disabled, _ := cfg["disableNonessentialTelemetry"].(bool); !disabled {
+ return false
+ }
+ return true
+}
+
+func claudeDesktopThirdPartyProfileUsesOllamaGateway(target claudeDesktopThirdPartyPaths) bool {
if readClaudeDesktopAppliedID(target.meta) != claudeDesktopProfileID {
return false
}
@@ -719,13 +734,21 @@ func claudeDesktopThirdPartyProfileConfigured(target claudeDesktopThirdPartyPath
if s, _ := cfg["inferenceProvider"].(string); s != "gateway" {
return false
}
- if s, _ := cfg["inferenceGatewayBaseUrl"].(string); strings.TrimRight(s, "/") != claudeDesktopGatewayBaseURL {
+ if s, _ := cfg["inferenceGatewayBaseUrl"].(string); !claudeDesktopGatewayURLMatches(s) {
return false
}
- if s, _ := cfg["inferenceGatewayApiKey"].(string); strings.TrimSpace(s) == "" {
+ return true
+}
+
+func claudeDesktopGatewayURLMatches(value string) bool {
+ parsed, err := url.Parse(strings.TrimSpace(value))
+ if err != nil || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {
return false
}
- return true
+ if strings.TrimRight(parsed.EscapedPath(), "/") != "" {
+ return false
+ }
+ return strings.EqualFold(parsed.Scheme, "http") && strings.EqualFold(parsed.Host, proxy.DefaultClaudeDesktopListenAddr)
}
func readClaudeDesktopJSONAllowMissing(path string) (map[string]any, error) {
@@ -774,15 +797,14 @@ func claudeDesktopAnySlice(value any) []any {
}
}
-func claudeDesktopLaunchOrRestart(prompt string) error {
- if !claudeDesktopIsRunning() {
- return claudeDesktopOpenApp()
+func claudeDesktopLaunchOrRestart(prompt string, reapplyProfile func() error) error {
+ running, err := claudeDesktopIsRunning(context.Background())
+ if err != nil {
+ return fmt.Errorf("check whether Claude Desktop is running: %w", err)
}
- restartAppPath := ""
- if claudeDesktopGOOS == "windows" {
- restartAppPath = claudeDesktopRunningAppPath()
+ if !running {
+ return claudeDesktopOpenApp()
}
-
restart, err := ConfirmPrompt(prompt)
if err != nil {
return err
@@ -791,41 +813,87 @@ func claudeDesktopLaunchOrRestart(prompt string) error {
fmt.Fprintln(os.Stderr, "\nQuit and reopen Claude Desktop when you're ready for the profile change to take effect.")
return nil
}
+ return restartClaudeDesktop(reapplyProfile)
+}
- if err := claudeDesktopQuitApp(); err != nil {
+func restartClaudeDesktop(reapplyProfile func() error) error {
+ restartAppPath := ""
+ if claudeDesktopGOOS == "windows" {
+ restartAppPath = claudeDesktopRunningAppPath()
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := claudeDesktopQuitApp(ctx); err != nil {
return fmt.Errorf("quit Claude Desktop: %w", err)
}
- if err := waitForClaudeDesktopExit(30 * time.Second); err != nil {
+ if err := waitForClaudeDesktopExit(ctx); err != nil {
return err
}
+ // Claude persists settings while shutting down. Reapply the profile after
+ // exit so its last write cannot restore stale surface or gateway values.
+ if err := reapplyProfile(); err != nil {
+ reapplyErr := fmt.Errorf("reapply Claude Desktop profile: %w", err)
+ if openErr := openClaudeDesktopAfterRestart(restartAppPath); openErr != nil {
+ return errors.Join(reapplyErr, fmt.Errorf("reopen Claude Desktop after profile failure: %w", openErr))
+ }
+ return reapplyErr
+ }
+ return openClaudeDesktopAfterRestart(restartAppPath)
+}
+
+func openClaudeDesktopAfterRestart(restartAppPath string) error {
if restartAppPath != "" {
return claudeDesktopOpenAppPath(restartAppPath)
}
return claudeDesktopOpenApp()
}
-func waitForClaudeDesktopExit(timeout time.Duration) error {
- deadline := time.Now().Add(timeout)
- for time.Now().Before(deadline) {
- if !claudeDesktopIsRunning() {
+func waitForClaudeDesktopExit(ctx context.Context) error {
+ for {
+ running, err := claudeDesktopIsRunning(ctx)
+ if err != nil {
+ return fmt.Errorf("check whether Claude Desktop is running: %w", err)
+ }
+ if !running {
return nil
}
- claudeDesktopSleep(200 * time.Millisecond)
+ select {
+ case <-ctx.Done():
+ return errors.New("Claude Desktop did not quit; quit it manually and re-run the command")
+ case <-time.After(200 * time.Millisecond):
+ }
}
- return fmt.Errorf("Claude Desktop did not quit; quit it manually and re-run the command")
}
-func defaultClaudeDesktopIsRunning() bool {
+// ClaudeDesktopRunning reports whether Claude Desktop is open.
+func ClaudeDesktopRunning() bool {
+ running, _ := claudeDesktopIsRunning(context.Background())
+ return running
+}
+
+func defaultClaudeDesktopRunning(ctx context.Context) (bool, error) {
+ var (
+ out []byte
+ err error
+ )
switch claudeDesktopGOOS {
case "darwin":
- out, err := exec.Command("pgrep", "-f", "Claude.app/Contents/MacOS/Claude").Output()
- return err == nil && strings.TrimSpace(string(out)) != ""
+ out, err = exec.CommandContext(ctx, "pgrep", "-f", "Claude.app/Contents/MacOS/Claude").Output()
+ if exitErr := (*exec.ExitError)(nil); errors.As(err, &exitErr) && exitErr.ExitCode() == 1 && ctx.Err() == nil {
+ return false, nil
+ }
case "windows":
- out, err := exec.Command("powershell.exe", "-NoProfile", "-Command", `(Get-Process claude -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 } | Select-Object -First 1).Id`).Output()
- return err == nil && strings.TrimSpace(string(out)) != ""
+ out, err = exec.CommandContext(ctx, "powershell.exe", "-NoProfile", "-Command", `(Get-Process claude -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 } | Select-Object -First 1).Id`).Output()
default:
- return false
+ return false, nil
+ }
+ if ctxErr := ctx.Err(); ctxErr != nil {
+ return false, ctxErr
+ }
+ if err != nil {
+ return false, err
}
+ return strings.TrimSpace(string(out)) != "", nil
}
func defaultClaudeDesktopOpenApp() error {
@@ -837,7 +905,7 @@ func defaultClaudeDesktopOpenApp() error {
if path := claudeDesktopRunningAppPath(); path != "" {
return claudeDesktopOpenAppPath(path)
}
- return fmt.Errorf("Claude Desktop executable was not found; open Claude Desktop manually once and re-run 'ollama launch claude-desktop --restore'")
+ return errors.New("Claude Desktop executable was not found; open Claude Desktop manually once and re-run 'ollama launch claude-desktop --restore'")
case "darwin":
return openClaudeDesktopDarwin()
default:
@@ -875,12 +943,12 @@ func defaultClaudeDesktopRunningAppPath() string {
return strings.TrimSpace(string(out))
}
-func defaultClaudeDesktopQuitApp() error {
+func defaultClaudeDesktopQuitApp(ctx context.Context) error {
if claudeDesktopGOOS == "windows" {
script := `Get-Process claude -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 } | ForEach-Object { [void]$_.CloseMainWindow() }`
- return exec.Command("powershell.exe", "-NoProfile", "-Command", script).Run()
+ return exec.CommandContext(ctx, "powershell.exe", "-NoProfile", "-Command", script).Run()
}
- return exec.Command("osascript", "-e", `tell application "Claude" to quit`).Run()
+ return exec.CommandContext(ctx, "osascript", "-e", `tell application "Claude" to quit`).Run()
}
func quotePowerShellString(s string) string {
diff --git a/cmd/launch/claude_desktop_test.go b/cmd/launch/claude_desktop_test.go
index ab20d3ce7..019c6530d 100644
--- a/cmd/launch/claude_desktop_test.go
+++ b/cmd/launch/claude_desktop_test.go
@@ -4,8 +4,9 @@ import (
"context"
"encoding/json"
"errors"
- "io"
+ "fmt"
"net/http"
+ "net/http/httptest"
"os"
"path/filepath"
"strings"
@@ -13,36 +14,15 @@ import (
"time"
)
-type roundTripFunc func(*http.Request) (*http.Response, error)
-
-func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
- return f(req)
-}
-
func withClaudeDesktopPlatform(t *testing.T, goos string) {
t.Helper()
- old := claudeDesktopGOOS
+ oldGOOS := claudeDesktopGOOS
+ oldProbe := claudeDesktopProbeGateway
claudeDesktopGOOS = goos
+ claudeDesktopProbeGateway = func(context.Context, string) error { return nil }
t.Cleanup(func() {
- claudeDesktopGOOS = old
- })
-}
-
-func withClaudeDesktopValidation(t *testing.T, fn func(context.Context, string) error) {
- t.Helper()
- old := claudeDesktopValidateAPIKey
- claudeDesktopValidateAPIKey = fn
- t.Cleanup(func() {
- claudeDesktopValidateAPIKey = old
- })
-}
-
-func withClaudeDesktopPrompt(t *testing.T, fn func() (string, error)) {
- t.Helper()
- old := claudeDesktopPromptAPIKey
- claudeDesktopPromptAPIKey = fn
- t.Cleanup(func() {
- claudeDesktopPromptAPIKey = old
+ claudeDesktopGOOS = oldGOOS
+ claudeDesktopProbeGateway = oldProbe
})
}
@@ -53,20 +33,17 @@ func withClaudeDesktopProcessHooks(t *testing.T, running func() bool, quit func(
oldOpen := claudeDesktopOpenApp
oldOpenPath := claudeDesktopOpenAppPath
oldRunningPath := claudeDesktopRunningAppPath
- oldSleep := claudeDesktopSleep
- claudeDesktopIsRunning = running
- claudeDesktopQuitApp = quit
+ claudeDesktopIsRunning = func(context.Context) (bool, error) { return running(), nil }
+ claudeDesktopQuitApp = func(context.Context) error { return quit() }
claudeDesktopOpenApp = open
claudeDesktopOpenAppPath = oldOpenPath
claudeDesktopRunningAppPath = oldRunningPath
- claudeDesktopSleep = func(time.Duration) {}
t.Cleanup(func() {
claudeDesktopIsRunning = oldRunning
claudeDesktopQuitApp = oldQuit
claudeDesktopOpenApp = oldOpen
claudeDesktopOpenAppPath = oldOpenPath
claudeDesktopRunningAppPath = oldRunningPath
- claudeDesktopSleep = oldSleep
})
}
@@ -83,6 +60,35 @@ func claudeDesktopReadJSON(t *testing.T, path string) map[string]any {
return cfg
}
+func claudeDesktopReadStringSlice(t *testing.T, value any) []string {
+ t.Helper()
+ items, ok := value.([]any)
+ if !ok {
+ t.Fatalf("value = %T, want JSON array", value)
+ }
+ result := make([]string, len(items))
+ for i, item := range items {
+ result[i], ok = item.(string)
+ if !ok {
+ t.Fatalf("value[%d] = %T, want string", i, item)
+ }
+ }
+ return result
+}
+
+func assertClaudeDesktopEgressHosts(t *testing.T, profile map[string]any) {
+ t.Helper()
+ got := claudeDesktopReadStringSlice(t, profile["coworkEgressAllowedHosts"])
+ if len(got) != len(claudeDesktopEgressHosts) {
+ t.Fatalf("coworkEgressAllowedHosts = %v, want %v", got, claudeDesktopEgressHosts)
+ }
+ for i := range got {
+ if got[i] != claudeDesktopEgressHosts[i] {
+ t.Fatalf("coworkEgressAllowedHosts = %v, want %v", got, claudeDesktopEgressHosts)
+ }
+ }
+}
+
func TestClaudeDesktopIntegration(t *testing.T) {
c := &ClaudeDesktop{}
@@ -92,9 +98,9 @@ func TestClaudeDesktopIntegration(t *testing.T) {
t.Run("implements managed autodiscovery integration", func(t *testing.T) {
var _ ManagedAutodiscoveryIntegration = c
})
- t.Run("does not use local Ollama Cloud auth gate", func(t *testing.T) {
+ t.Run("does not use Ollama Cloud auth gate", func(t *testing.T) {
if _, ok := any(c).(ManagedAutodiscoveryCloudIntegration); ok {
- t.Fatal("Claude Desktop should validate OLLAMA_API_KEY directly instead of requiring local Ollama Cloud sign-in")
+ t.Fatal("Claude Desktop's loopback gateway should not require Ollama Cloud sign-in")
}
})
t.Run("implements restore", func(t *testing.T) {
@@ -112,7 +118,7 @@ func TestClaudeDesktopIntegration(t *testing.T) {
t.Run("has success messages", func(t *testing.T) {
var _ ConfigurationSuccessIntegration = c
var _ RestoreSuccessIntegration = c
- if got := c.ConfigurationSuccessMessage(); got != "Claude Desktop profile changed to Ollama Cloud.\nTo restore the usual Claude profile, run: ollama launch claude-desktop --restore" {
+ if got := c.ConfigurationSuccessMessage(); got != "Claude Desktop profile changed to Ollama.\nTo restore the usual Claude profile, run: ollama launch claude-desktop --restore" {
t.Fatalf("configuration success message = %q", got)
}
if got := c.RestoreSuccessMessage(); got != "Claude Desktop restored to the usual Claude profile." {
@@ -127,59 +133,72 @@ func TestClaudeDesktopIntegration(t *testing.T) {
})
}
-func TestLaunchIntegration_ClaudeDesktopLaunchReturnsUnsupported(t *testing.T) {
- for _, name := range []string{"claude-desktop", "claude-app"} {
- t.Run(name, func(t *testing.T) {
- err := LaunchIntegration(context.Background(), IntegrationLaunchRequest{Name: name})
- if err == nil {
- t.Fatal("expected Claude Desktop launch to fail")
- }
- if !strings.Contains(err.Error(), "Claude Desktop is no longer supported") {
- t.Fatalf("expected unsupported guidance, got %v", err)
- }
- if !strings.Contains(err.Error(), "ollama launch claude-desktop --restore") {
- t.Fatalf("expected restore guidance, got %v", err)
- }
- })
+func TestClaudeDesktopSupportedOnlyOnDarwin(t *testing.T) {
+ withClaudeDesktopPlatform(t, "windows")
+ if err := (&ClaudeDesktop{}).Supported(); err == nil || !strings.Contains(err.Error(), "only supported on macOS") {
+ t.Fatalf("Supported error = %v, want macOS-only error", err)
+ }
+}
+
+func TestClaudeDesktopConfigureRequiresOllamaGateway(t *testing.T) {
+ withClaudeDesktopPlatform(t, "darwin")
+ claudeDesktopProbeGateway = func(context.Context, string) error {
+ return errors.New("another service is using 127.0.0.1:11435")
+ }
+
+ err := (&ClaudeDesktop{}).ConfigureAutodiscovery()
+ if err == nil || !strings.Contains(err.Error(), "restart Ollama and try again") {
+ t.Fatalf("ConfigureAutodiscovery error = %v, want gateway recovery guidance", err)
}
}
-func TestLaunchIntegration_ClaudeDesktopRestoreStillWorks(t *testing.T) {
+func TestLaunchIntegration_ClaudeDesktopDoesNotRequireLocalCloudSignIn(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
withClaudeDesktopPlatform(t, "darwin")
- withClaudeDesktopProcessHooks(t, func() bool { return false }, func() error { return nil }, func() error { return nil })
+ withInteractiveSession(t, true)
+ withLauncherHooks(t)
+ t.Setenv("OLLAMA_API_KEY", "test-api-key")
if err := os.MkdirAll(filepath.Join(tmpDir, "Applications", "Claude.app"), 0o755); err != nil {
t.Fatal(err)
}
- paths, err := claudeDesktopConfigPaths()
- if err != nil {
- t.Fatal(err)
- }
- if err := os.MkdirAll(filepath.Dir(paths.profile), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(paths.meta, []byte(`{"appliedId":"`+claudeDesktopProfileID+`","entries":[{"id":"`+claudeDesktopProfileID+`","name":"Ollama"}]}`), 0o644); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(paths.profile, []byte(`{"disableDeploymentModeChooser":true,"inferenceGatewayApiKey":"keep","inferenceProvider":"gateway","inferenceGatewayBaseUrl":"https://ollama.com","inferenceGatewayAuthScheme":"bearer"}`), 0o644); err != nil {
- t.Fatal(err)
- }
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/status":
+ w.WriteHeader(http.StatusNotFound)
+ fmt.Fprint(w, `{"error":"not found"}`)
+ case "/api/me":
+ w.WriteHeader(http.StatusUnauthorized)
+ fmt.Fprint(w, `{"error":"unauthorized","signin_url":"https://example.com/signin"}`)
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ t.Setenv("OLLAMA_HOST", srv.URL)
- stderr := captureStderr(t, func() {
- err = LaunchIntegration(context.Background(), IntegrationLaunchRequest{Name: "claude-desktop", Restore: true})
- })
- if err != nil {
- t.Fatalf("LaunchIntegration restore returned error: %v", err)
+ DefaultSignIn = func(modelName, signInURL string) (string, error) {
+ t.Fatalf("Claude Desktop launch should not require Ollama Cloud sign-in, got %s at %s", modelName, signInURL)
+ return "", nil
}
- if !strings.Contains(stderr, claudeDesktopRestoredMessage) {
- t.Fatalf("expected restore success message, got stderr: %q", stderr)
+
+ var openCalls int
+ withClaudeDesktopProcessHooks(t,
+ func() bool { return false },
+ func() error { return nil },
+ func() error {
+ openCalls++
+ return nil
+ },
+ )
+
+ if err := LaunchIntegration(context.Background(), IntegrationLaunchRequest{Name: "claude-desktop"}); err != nil {
+ t.Fatalf("LaunchIntegration returned error: %v", err)
}
- desktopConfig := claudeDesktopReadJSON(t, paths.desktopConfig)
- if desktopConfig["deploymentMode"] != "1p" {
- t.Fatalf("deploymentMode = %v, want 1p", desktopConfig["deploymentMode"])
+ if openCalls != 1 {
+ t.Fatalf("open calls = %d, want 1", openCalls)
}
}
@@ -189,12 +208,6 @@ func TestClaudeDesktopConfigureWritesOllamaCloudProfile(t *testing.T) {
withClaudeDesktopPlatform(t, "darwin")
t.Setenv("OLLAMA_API_KEY", "test-api-key")
- var validatedKey string
- withClaudeDesktopValidation(t, func(_ context.Context, key string) error {
- validatedKey = key
- return nil
- })
-
paths, err := claudeDesktopConfigPaths()
if err != nil {
t.Fatal(err)
@@ -215,9 +228,6 @@ func TestClaudeDesktopConfigureWritesOllamaCloudProfile(t *testing.T) {
if err := (&ClaudeDesktop{}).ConfigureAutodiscovery(); err != nil {
t.Fatalf("Configure returned error: %v", err)
}
- if validatedKey != "test-api-key" {
- t.Fatalf("validated key = %q, want test API key", validatedKey)
- }
desktopConfig := claudeDesktopReadJSON(t, paths.desktopConfig)
if desktopConfig["existing"] != true {
@@ -247,8 +257,8 @@ func TestClaudeDesktopConfigureWritesOllamaCloudProfile(t *testing.T) {
if profile["inferenceGatewayBaseUrl"] != claudeDesktopGatewayBaseURL {
t.Fatalf("base URL = %v, want %s", profile["inferenceGatewayBaseUrl"], claudeDesktopGatewayBaseURL)
}
- if profile["inferenceGatewayApiKey"] != "test-api-key" {
- t.Fatal("expected configured API key to be written")
+ if profile["inferenceGatewayApiKey"] != "ollama" {
+ t.Fatal("expected local placeholder API key to be written")
}
if profile["inferenceGatewayAuthScheme"] != "bearer" {
t.Fatalf("auth scheme = %v, want bearer", profile["inferenceGatewayAuthScheme"])
@@ -256,17 +266,64 @@ func TestClaudeDesktopConfigureWritesOllamaCloudProfile(t *testing.T) {
if profile["disableDeploymentModeChooser"] != true {
t.Fatalf("disableDeploymentModeChooser = %v, want true", profile["disableDeploymentModeChooser"])
}
+ if profile["chatTabEnabled"] != true {
+ t.Fatalf("chatTabEnabled = %v, want true", profile["chatTabEnabled"])
+ }
+ if profile["autoModeEnabled"] != false {
+ t.Fatalf("autoModeEnabled = %v, want false", profile["autoModeEnabled"])
+ }
+ assertClaudeDesktopEgressHosts(t, profile)
+ if profile["disableEssentialTelemetry"] != true {
+ t.Fatalf("disableEssentialTelemetry = %v, want true", profile["disableEssentialTelemetry"])
+ }
+ if profile["disableNonessentialTelemetry"] != true {
+ t.Fatalf("disableNonessentialTelemetry = %v, want true", profile["disableNonessentialTelemetry"])
+ }
if _, ok := profile["inferenceModels"]; ok {
t.Fatalf("inferenceModels should be omitted so Claude can discover models, got %v", profile["inferenceModels"])
}
}
+func TestClaudeDesktopConfigureActivatesNormalProfileLast(t *testing.T) {
+ tmpDir := t.TempDir()
+ setTestHome(t, tmpDir)
+ withClaudeDesktopPlatform(t, "darwin")
+
+ paths, err := claudeDesktopConfigPaths()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Dir(paths.normalConfig), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Dir(paths.desktopConfig), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(paths.normalConfig, []byte(`{"deploymentMode":"1p","existing":true}`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(paths.desktopConfig, []byte(`{"deploymentMode":`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ err = (&ClaudeDesktop{}).ConfigureAutodiscovery()
+ if err == nil {
+ t.Fatal("ConfigureAutodiscovery succeeded with malformed third-party config")
+ }
+ normal := claudeDesktopReadJSON(t, paths.normalConfig)
+ if normal["deploymentMode"] != "1p" || normal["existing"] != true {
+ t.Fatalf("normal profile changed before third-party assets were ready: %v", normal)
+ }
+ if (&ClaudeDesktop{}).UsesOllamaGateway() {
+ t.Fatal("failed configuration left Claude routed through Ollama")
+ }
+}
+
func TestClaudeDesktopConfigureAutodiscoveryRemovesExistingModelCatalog(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
withClaudeDesktopPlatform(t, "darwin")
t.Setenv("OLLAMA_API_KEY", "test-api-key")
- withClaudeDesktopValidation(t, func(context.Context, string) error { return nil })
paths, err := claudeDesktopConfigPaths()
if err != nil {
@@ -275,7 +332,7 @@ func TestClaudeDesktopConfigureAutodiscoveryRemovesExistingModelCatalog(t *testi
if err := os.MkdirAll(filepath.Dir(paths.profile), 0o755); err != nil {
t.Fatal(err)
}
- if err := os.WriteFile(paths.profile, []byte(`{"inferenceModels":["qwen3.5"],"inferenceGatewayApiKey":"old"}`), 0o644); err != nil {
+ if err := os.WriteFile(paths.profile, []byte(`{"autoModeEnabled":true,"chatTabEnabled":false,"coworkEgressAllowedHosts":["old.example.com"],"disableEssentialTelemetry":false,"disableNonessentialTelemetry":false,"inferenceModels":["qwen3.5"],"inferenceGatewayApiKey":"old"}`), 0o644); err != nil {
t.Fatal(err)
}
@@ -287,8 +344,18 @@ func TestClaudeDesktopConfigureAutodiscoveryRemovesExistingModelCatalog(t *testi
if _, ok := profile["inferenceModels"]; ok {
t.Fatalf("inferenceModels should be removed, got %v", profile["inferenceModels"])
}
- if profile["inferenceGatewayApiKey"] != "test-api-key" {
- t.Fatal("expected env API key to replace the old key")
+ if profile["inferenceGatewayApiKey"] != "ollama" {
+ t.Fatal("expected local placeholder API key to replace the old key")
+ }
+ if profile["chatTabEnabled"] != true {
+ t.Fatalf("chatTabEnabled = %v, want true", profile["chatTabEnabled"])
+ }
+ if profile["autoModeEnabled"] != false {
+ t.Fatalf("autoModeEnabled = %v, want false", profile["autoModeEnabled"])
+ }
+ assertClaudeDesktopEgressHosts(t, profile)
+ if profile["disableEssentialTelemetry"] != true || profile["disableNonessentialTelemetry"] != true {
+ t.Fatalf("telemetry flags = %v/%v, want true/true", profile["disableEssentialTelemetry"], profile["disableNonessentialTelemetry"])
}
}
@@ -329,102 +396,40 @@ func TestClaudeDesktopWindowsConfigPathsFallbackToNestProfile(t *testing.T) {
}
}
-func TestClaudeDesktopAutodiscoveryConfiguredOnWindows(t *testing.T) {
- tmpDir := t.TempDir()
- setTestHome(t, tmpDir)
- withClaudeDesktopPlatform(t, "windows")
- t.Setenv("LOCALAPPDATA", filepath.Join(tmpDir, "LocalAppData"))
- t.Setenv("OLLAMA_API_KEY", "test-api-key")
- withClaudeDesktopValidation(t, func(context.Context, string) error { return nil })
-
- c := &ClaudeDesktop{}
- if err := c.ConfigureAutodiscovery(); err != nil {
- t.Fatalf("Configure returned error: %v", err)
- }
- if !c.AutodiscoveryConfigured() {
- t.Fatal("expected Claude Desktop autodiscovery config to be detected on Windows")
- }
-}
-
-func TestClaudeDesktopConfigureAutodiscoveryTouchesAllWindowsProfileCandidates(t *testing.T) {
+func TestClaudeDesktopInstalledOnWindowsRecognizesLocalProfileDir(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
withClaudeDesktopPlatform(t, "windows")
local := filepath.Join(tmpDir, "LocalAppData")
t.Setenv("LOCALAPPDATA", local)
- t.Setenv("OLLAMA_API_KEY", "test-api-key")
- withClaudeDesktopValidation(t, func(context.Context, string) error { return nil })
-
- targets, err := claudeDesktopTargetPaths()
- if err != nil {
+ withClaudeDesktopProcessHooks(t, func() bool { return false }, func() error { return nil }, func() error { return nil })
+ if err := os.MkdirAll(filepath.Join(local, "Claude-3p"), 0o755); err != nil {
t.Fatal(err)
}
- if len(targets.normalConfigs) != 2 {
- t.Fatalf("normal config target count = %d, want 2", len(targets.normalConfigs))
- }
- if len(targets.thirdPartyProfiles) != 2 {
- t.Fatalf("third-party target count = %d, want 2", len(targets.thirdPartyProfiles))
- }
-
- c := &ClaudeDesktop{}
- if err := c.ConfigureAutodiscovery(); err != nil {
- t.Fatalf("ConfigureAutodiscovery returned error: %v", err)
- }
- for _, path := range targets.normalConfigs {
- cfg := claudeDesktopReadJSON(t, path)
- if cfg["deploymentMode"] != "3p" {
- t.Fatalf("%s deploymentMode = %v, want 3p", path, cfg["deploymentMode"])
- }
- }
- for _, target := range targets.thirdPartyProfiles {
- cfg := claudeDesktopReadJSON(t, target.desktopConfig)
- if cfg["deploymentMode"] != "3p" {
- t.Fatalf("%s deploymentMode = %v, want 3p", target.desktopConfig, cfg["deploymentMode"])
- }
- meta := claudeDesktopReadJSON(t, target.meta)
- if meta["appliedId"] != claudeDesktopProfileID {
- t.Fatalf("%s appliedId = %v, want %s", target.meta, meta["appliedId"], claudeDesktopProfileID)
- }
- profile := claudeDesktopReadJSON(t, target.profile)
- if profile["inferenceProvider"] != "gateway" {
- t.Fatalf("%s inferenceProvider = %v, want gateway", target.profile, profile["inferenceProvider"])
- }
- if profile["inferenceGatewayBaseUrl"] != claudeDesktopGatewayBaseURL {
- t.Fatalf("%s base URL = %v, want %s", target.profile, profile["inferenceGatewayBaseUrl"], claudeDesktopGatewayBaseURL)
- }
- if profile["inferenceGatewayApiKey"] != "test-api-key" {
- t.Fatalf("%s should contain the configured API key", target.profile)
- }
- if _, ok := profile["inferenceModels"]; ok {
- t.Fatalf("%s inferenceModels should be omitted, got %v", target.profile, profile["inferenceModels"])
- }
- }
- if !c.AutodiscoveryConfigured() {
- t.Fatal("expected all Windows profile candidates to be considered configured")
- }
-
- if err := writeClaudeDesktopDeploymentMode(targets.thirdPartyProfiles[1].desktopConfig, "1p"); err != nil {
- t.Fatal(err)
- }
- if c.AutodiscoveryConfigured() {
- t.Fatal("expected a stale Windows candidate to force reconfiguration")
+ if !ClaudeDesktopInstalled() {
+ t.Fatal("expected Claude Desktop to be installed when the Windows profile directory exists")
}
}
-func TestClaudeDesktopInstalledOnWindowsRecognizesLocalProfileDir(t *testing.T) {
+func TestClaudeDesktopInstalledOnDarwinRequiresApp(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
- withClaudeDesktopPlatform(t, "windows")
- local := filepath.Join(tmpDir, "LocalAppData")
- t.Setenv("LOCALAPPDATA", local)
- withClaudeDesktopProcessHooks(t, func() bool { return false }, func() error { return nil }, func() error { return nil })
- if err := os.MkdirAll(filepath.Join(local, "Claude-3p"), 0o755); err != nil {
+ withClaudeDesktopPlatform(t, "darwin")
+ previousStat := claudeDesktopStat
+ claudeDesktopStat = func(path string) (os.FileInfo, error) {
+ if strings.HasPrefix(path, "/Applications/") {
+ return nil, os.ErrNotExist
+ }
+ return os.Stat(path)
+ }
+ t.Cleanup(func() { claudeDesktopStat = previousStat })
+ if err := os.MkdirAll(filepath.Join(tmpDir, "Library", "Application Support", "Claude"), 0o755); err != nil {
t.Fatal(err)
}
- if !claudeDesktopInstalled() {
- t.Fatal("expected Claude Desktop to be installed when the Windows profile directory exists")
+ if ClaudeDesktopInstalled() {
+ t.Fatal("profile files alone should not make Claude Desktop appear installed on macOS")
}
}
@@ -459,7 +464,9 @@ func TestWaitForClaudeDesktopExitUsesRunningHook(t *testing.T) {
func() error { return nil },
)
- if err := waitForClaudeDesktopExit(time.Second); err != nil {
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ if err := waitForClaudeDesktopExit(ctx); err != nil {
t.Fatalf("waitForClaudeDesktopExit returned error: %v", err)
}
if runningChecks < 2 {
@@ -467,56 +474,6 @@ func TestWaitForClaudeDesktopExitUsesRunningHook(t *testing.T) {
}
}
-func TestClaudeDesktopWindowsRestoreRestartUsesCapturedDesktopPath(t *testing.T) {
- tmpDir := t.TempDir()
- setTestHome(t, tmpDir)
- withClaudeDesktopPlatform(t, "windows")
- t.Setenv("LOCALAPPDATA", filepath.Join(tmpDir, "LocalAppData"))
- restoreConfirm := withLaunchConfirmPolicy(launchConfirmPolicy{yes: true})
- defer restoreConfirm()
-
- paths, err := claudeDesktopConfigPaths()
- if err != nil {
- t.Fatal(err)
- }
- if err := os.MkdirAll(filepath.Dir(paths.profile), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(paths.meta, []byte(`{"appliedId":"`+claudeDesktopProfileID+`","entries":[{"id":"`+claudeDesktopProfileID+`","name":"Ollama"}]}`), 0o644); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(paths.profile, []byte(`{"disableDeploymentModeChooser":true,"inferenceGatewayApiKey":"keep"}`), 0o644); err != nil {
- t.Fatal(err)
- }
-
- desktopPath := `C:\Users\parth\AppData\Local\AnthropicClaude\app-1.2.3\Claude.exe`
- running := true
- var openedPath string
- withClaudeDesktopProcessHooks(t,
- func() bool { return running },
- func() error {
- running = false
- return nil
- },
- func() error {
- t.Fatal("expected restart to open the captured Desktop executable path, not the generic launcher")
- return nil
- },
- )
- claudeDesktopRunningAppPath = func() string { return desktopPath }
- claudeDesktopOpenAppPath = func(path string) error {
- openedPath = path
- return nil
- }
-
- if err := (&ClaudeDesktop{}).Restore(); err != nil {
- t.Fatalf("Restore returned error: %v", err)
- }
- if openedPath != desktopPath {
- t.Fatalf("opened path = %q, want %q", openedPath, desktopPath)
- }
-}
-
func TestClaudeDesktopWindowsOpenDoesNotFallBackToClaudeCommand(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
@@ -533,99 +490,37 @@ func TestClaudeDesktopWindowsOpenDoesNotFallBackToClaudeCommand(t *testing.T) {
}
}
-func TestClaudeDesktopConfigureStopsBeforeWriteWhenKeyValidationFails(t *testing.T) {
+func TestClaudeDesktopConfigureIgnoresCloudAPIKey(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
withClaudeDesktopPlatform(t, "darwin")
t.Setenv("OLLAMA_API_KEY", "bad-key")
- withClaudeDesktopValidation(t, func(context.Context, string) error {
- return errors.New("invalid key")
- })
- err := (&ClaudeDesktop{}).ConfigureAutodiscovery()
- if err == nil || !strings.Contains(err.Error(), "invalid key") {
- t.Fatalf("Configure error = %v, want invalid key", err)
+ if err := (&ClaudeDesktop{}).ConfigureAutodiscovery(); err != nil {
+ t.Fatalf("Configure error = %v", err)
}
paths, err := claudeDesktopConfigPaths()
if err != nil {
t.Fatal(err)
}
- if _, err := os.Stat(paths.desktopConfig); !errors.Is(err, os.ErrNotExist) {
- t.Fatalf("desktop config should not be written after validation failure, stat err = %v", err)
- }
-}
-
-func TestValidateClaudeDesktopAPIKeyUsesClaudeModelsRoute(t *testing.T) {
- oldClient := claudeDesktopHTTPClient
- var gotPath, gotAuth string
- claudeDesktopHTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
- gotPath = req.URL.Path
- gotAuth = req.Header.Get("Authorization")
- return &http.Response{
- StatusCode: http.StatusOK,
- Body: io.NopCloser(strings.NewReader(`{"data":[]}`)),
- Header: make(http.Header),
- }, nil
- })}
- t.Cleanup(func() {
- claudeDesktopHTTPClient = oldClient
- })
-
- if err := validateClaudeDesktopAPIKey(context.Background(), "test-key"); err != nil {
- t.Fatalf("validateClaudeDesktopAPIKey returned error: %v", err)
- }
- if gotPath != "/v1/models" {
- t.Fatalf("validation path = %q, want /v1/models", gotPath)
- }
- if gotAuth != "Bearer test-key" {
- t.Fatalf("Authorization header = %q, want bearer key", gotAuth)
- }
-}
-
-func TestValidateClaudeDesktopAPIKeyHidesInvalidHeaderDetails(t *testing.T) {
- err := validateClaudeDesktopAPIKey(context.Background(), "bad\nkey")
- if err == nil {
- t.Fatal("expected validation error for key with newline")
- }
- if !strings.Contains(err.Error(), "could not verify Ollama API key") {
- t.Fatalf("validation error = %v, want friendly verification message", err)
- }
- if strings.Contains(err.Error(), "invalid header") || strings.Contains(err.Error(), "net/http") {
- t.Fatalf("validation error should not expose transport internals: %v", err)
- }
- if !strings.Contains(err.Error(), "https://ollama.com/settings/keys") {
- t.Fatalf("validation error should include settings link: %v", err)
+ profile := claudeDesktopReadJSON(t, paths.profile)
+ if profile["inferenceGatewayApiKey"] != "ollama" {
+ t.Fatalf("gateway API key = %v, want local placeholder", profile["inferenceGatewayApiKey"])
}
}
-func TestClaudeDesktopConfigureRequiresAPIKey(t *testing.T) {
+func TestClaudeDesktopConfigureDoesNotRequireAPIKey(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
withClaudeDesktopPlatform(t, "darwin")
t.Setenv("OLLAMA_API_KEY", "")
- withClaudeDesktopValidation(t, func(context.Context, string) error {
- t.Fatal("validation should not run without an API key")
- return nil
- })
-
- err := (&ClaudeDesktop{}).ConfigureAutodiscovery()
- if err == nil || !strings.Contains(err.Error(), "OLLAMA_API_KEY is required") {
- t.Fatalf("Configure error = %v, want missing key guidance", err)
- }
-}
-
-func TestClaudeDesktopAPIKeyPromptIncludesSettingsLink(t *testing.T) {
- prompt := claudeDesktopAPIKeyPrompt()
- if !strings.Contains(prompt, "Enter Ollama API key") {
- t.Fatalf("prompt should ask for the API key, got %q", prompt)
- }
- if !strings.Contains(prompt, "https://ollama.com/settings/keys") {
- t.Fatalf("prompt should include API key settings link, got %q", prompt)
+ if err := (&ClaudeDesktop{}).ConfigureAutodiscovery(); err != nil {
+ t.Fatalf("Configure error = %v", err)
}
}
-func TestClaudeDesktopConfigureReusesExistingAPIKey(t *testing.T) {
+func TestClaudeDesktopConfigureReplacesExistingAPIKeyWithPlaceholder(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
withClaudeDesktopPlatform(t, "darwin")
@@ -642,21 +537,16 @@ func TestClaudeDesktopConfigureReusesExistingAPIKey(t *testing.T) {
t.Fatal(err)
}
- var validatedKey string
- withClaudeDesktopValidation(t, func(_ context.Context, key string) error {
- validatedKey = key
- return nil
- })
-
if err := (&ClaudeDesktop{}).ConfigureAutodiscovery(); err != nil {
t.Fatalf("ConfigureAutodiscovery returned error: %v", err)
}
- if validatedKey != "existing-key" {
- t.Fatalf("validated key = %q, want existing-key", validatedKey)
+ profile := claudeDesktopReadJSON(t, paths.profile)
+ if profile["inferenceGatewayApiKey"] != "ollama" {
+ t.Fatalf("gateway API key = %v, want local placeholder", profile["inferenceGatewayApiKey"])
}
}
-func TestClaudeDesktopConfigureReplacesInvalidExistingAPIKey(t *testing.T) {
+func TestClaudeDesktopConfigureDoesNotPromptForExistingAPIKey(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
withClaudeDesktopPlatform(t, "darwin")
@@ -674,67 +564,12 @@ func TestClaudeDesktopConfigureReplacesInvalidExistingAPIKey(t *testing.T) {
t.Fatal(err)
}
- var validated []string
- withClaudeDesktopValidation(t, func(_ context.Context, key string) error {
- validated = append(validated, key)
- if key == "stale-key" {
- return errors.New("invalid key")
- }
- return nil
- })
- withClaudeDesktopPrompt(t, func() (string, error) {
- return "replacement-key", nil
- })
-
if err := (&ClaudeDesktop{}).ConfigureAutodiscovery(); err != nil {
t.Fatalf("ConfigureAutodiscovery returned error: %v", err)
}
- if diff := compareStrings(validated, []string{"stale-key", "replacement-key"}); diff != "" {
- t.Fatalf("validated keys mismatch: %s", diff)
- }
profile := claudeDesktopReadJSON(t, paths.profile)
- if profile["inferenceGatewayApiKey"] != "replacement-key" {
- t.Fatalf("configured key = %v, want replacement-key", profile["inferenceGatewayApiKey"])
- }
-}
-
-func TestClaudeDesktopConfigureReusesExistingAPIKeyFromAnyWindowsProfile(t *testing.T) {
- tmpDir := t.TempDir()
- setTestHome(t, tmpDir)
- withClaudeDesktopPlatform(t, "windows")
- local := filepath.Join(tmpDir, "LocalAppData")
- t.Setenv("LOCALAPPDATA", local)
- t.Setenv("OLLAMA_API_KEY", "")
-
- targets, err := claudeDesktopTargetPaths()
- if err != nil {
- t.Fatal(err)
- }
- fallbackProfile := targets.thirdPartyProfiles[1].profile
- if err := os.MkdirAll(filepath.Dir(fallbackProfile), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(fallbackProfile, []byte(`{"inferenceGatewayApiKey":"fallback-key"}`), 0o644); err != nil {
- t.Fatal(err)
- }
-
- var validatedKey string
- withClaudeDesktopValidation(t, func(_ context.Context, key string) error {
- validatedKey = key
- return nil
- })
-
- if err := (&ClaudeDesktop{}).ConfigureAutodiscovery(); err != nil {
- t.Fatalf("ConfigureAutodiscovery returned error: %v", err)
- }
- if validatedKey != "fallback-key" {
- t.Fatalf("validated key = %q, want fallback-key", validatedKey)
- }
- for _, target := range targets.thirdPartyProfiles {
- profile := claudeDesktopReadJSON(t, target.profile)
- if profile["inferenceGatewayApiKey"] != "fallback-key" {
- t.Fatalf("%s should reuse fallback key, got %v", target.profile, profile["inferenceGatewayApiKey"])
- }
+ if profile["inferenceGatewayApiKey"] != "ollama" {
+ t.Fatalf("configured key = %v, want local placeholder", profile["inferenceGatewayApiKey"])
}
}
@@ -743,7 +578,6 @@ func TestClaudeDesktopAutodiscoveryConfiguredRequiresAppliedOllamaProfile(t *tes
setTestHome(t, tmpDir)
withClaudeDesktopPlatform(t, "darwin")
t.Setenv("OLLAMA_API_KEY", "test-api-key")
- withClaudeDesktopValidation(t, func(context.Context, string) error { return nil })
c := &ClaudeDesktop{}
if err := c.ConfigureAutodiscovery(); err != nil {
@@ -763,6 +597,9 @@ func TestClaudeDesktopAutodiscoveryConfiguredRequiresAppliedOllamaProfile(t *tes
if c.AutodiscoveryConfigured() {
t.Fatal("expected another applied profile to hide Claude Desktop autodiscovery config")
}
+ if c.UsesOllamaGateway() {
+ t.Fatal("expected another applied profile to stop routing through Ollama")
+ }
}
func TestClaudeDesktopAutodiscoveryConfiguredRequiresAPIKey(t *testing.T) {
@@ -770,7 +607,6 @@ func TestClaudeDesktopAutodiscoveryConfiguredRequiresAPIKey(t *testing.T) {
setTestHome(t, tmpDir)
withClaudeDesktopPlatform(t, "darwin")
t.Setenv("OLLAMA_API_KEY", "test-api-key")
- withClaudeDesktopValidation(t, func(context.Context, string) error { return nil })
c := &ClaudeDesktop{}
if err := c.ConfigureAutodiscovery(); err != nil {
@@ -794,6 +630,150 @@ func TestClaudeDesktopAutodiscoveryConfiguredRequiresAPIKey(t *testing.T) {
if c.AutodiscoveryConfigured() {
t.Fatal("expected missing gateway API key to force Claude Desktop reconfiguration")
}
+ if !c.UsesOllamaGateway() {
+ t.Fatal("expected missing gateway API key to leave Ollama routing active")
+ }
+}
+
+func TestClaudeDesktopAutodiscoveryConfiguredRequiresTelemetryDisabled(t *testing.T) {
+ tmpDir := t.TempDir()
+ setTestHome(t, tmpDir)
+ withClaudeDesktopPlatform(t, "darwin")
+
+ c := &ClaudeDesktop{}
+ if err := c.ConfigureAutodiscovery(); err != nil {
+ t.Fatalf("Configure returned error: %v", err)
+ }
+
+ paths, err := claudeDesktopConfigPaths()
+ if err != nil {
+ t.Fatal(err)
+ }
+ profile := claudeDesktopReadJSON(t, paths.profile)
+ profile["disableEssentialTelemetry"] = false
+ if err := writeClaudeDesktopJSON(paths.profile, profile); err != nil {
+ t.Fatal(err)
+ }
+ if c.AutodiscoveryConfigured() {
+ t.Fatal("expected essential telemetry to force Claude Desktop profile reconfiguration")
+ }
+ if !c.UsesOllamaGateway() {
+ t.Fatal("expected essential telemetry drift to leave Ollama routing active")
+ }
+
+ profile["disableEssentialTelemetry"] = true
+ profile["disableNonessentialTelemetry"] = false
+ if err := writeClaudeDesktopJSON(paths.profile, profile); err != nil {
+ t.Fatal(err)
+ }
+
+ if c.AutodiscoveryConfigured() {
+ t.Fatal("expected nonessential telemetry to force Claude Desktop profile reconfiguration")
+ }
+ if !c.UsesOllamaGateway() {
+ t.Fatal("expected nonessential telemetry drift to leave Ollama routing active")
+ }
+}
+
+func TestClaudeDesktopAutodiscoveryConfiguredRequiresEgressHosts(t *testing.T) {
+ tmpDir := t.TempDir()
+ setTestHome(t, tmpDir)
+ withClaudeDesktopPlatform(t, "darwin")
+
+ c := &ClaudeDesktop{}
+ if err := c.ConfigureAutodiscovery(); err != nil {
+ t.Fatalf("Configure returned error: %v", err)
+ }
+ paths, err := claudeDesktopConfigPaths()
+ if err != nil {
+ t.Fatal(err)
+ }
+ profile := claudeDesktopReadJSON(t, paths.profile)
+
+ for _, value := range []any{nil, []string{"github.com"}} {
+ if value == nil {
+ delete(profile, "coworkEgressAllowedHosts")
+ } else {
+ profile["coworkEgressAllowedHosts"] = value
+ }
+ if err := writeClaudeDesktopJSON(paths.profile, profile); err != nil {
+ t.Fatal(err)
+ }
+ if c.AutodiscoveryConfigured() {
+ t.Fatalf("expected egress hosts %v to force Claude Desktop profile reconfiguration", value)
+ }
+ if !c.UsesOllamaGateway() {
+ t.Fatalf("expected egress hosts %v to leave Ollama routing active", value)
+ }
+ }
+}
+
+func TestClaudeDesktopUsesOllamaGatewayRequiresCoreRoutingSettings(t *testing.T) {
+ setTestHome(t, t.TempDir())
+ withClaudeDesktopPlatform(t, "darwin")
+
+ c := &ClaudeDesktop{}
+ paths, err := claudeDesktopConfigPaths()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ tests := []struct {
+ name string
+ mutate func() error
+ }{
+ {
+ name: "normal deployment mode",
+ mutate: func() error {
+ return writeClaudeDesktopDeploymentMode(paths.normalConfig, "1p")
+ },
+ },
+ {
+ name: "third-party deployment mode",
+ mutate: func() error {
+ return writeClaudeDesktopDeploymentMode(paths.desktopConfig, "1p")
+ },
+ },
+ {
+ name: "applied profile",
+ mutate: func() error {
+ return writeClaudeDesktopMeta(paths.meta, "custom", "Custom")
+ },
+ },
+ {
+ name: "inference provider",
+ mutate: func() error {
+ profile := claudeDesktopReadJSON(t, paths.profile)
+ profile["inferenceProvider"] = "bedrock"
+ return writeClaudeDesktopJSON(paths.profile, profile)
+ },
+ },
+ {
+ name: "gateway base URL",
+ mutate: func() error {
+ profile := claudeDesktopReadJSON(t, paths.profile)
+ profile["inferenceGatewayBaseUrl"] = "http://127.0.0.1:11434"
+ return writeClaudeDesktopJSON(paths.profile, profile)
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if err := c.ConfigureAutodiscovery(); err != nil {
+ t.Fatal(err)
+ }
+ if !c.UsesOllamaGateway() {
+ t.Fatal("expected configured Claude Desktop to route through Ollama")
+ }
+ if err := tt.mutate(); err != nil {
+ t.Fatal(err)
+ }
+ if c.UsesOllamaGateway() {
+ t.Fatal("expected core routing drift to stop Ollama routing")
+ }
+ })
+ }
}
func TestClaudeDesktopRestoreSwitchesBackToFirstPartyMode(t *testing.T) {
@@ -812,7 +792,7 @@ func TestClaudeDesktopRestoreSwitchesBackToFirstPartyMode(t *testing.T) {
if err := os.WriteFile(paths.meta, []byte(`{"appliedId":"`+claudeDesktopProfileID+`","entries":[{"id":"`+claudeDesktopProfileID+`","name":"Ollama"}]}`), 0o644); err != nil {
t.Fatal(err)
}
- if err := os.WriteFile(paths.profile, []byte(`{"disableDeploymentModeChooser":true,"inferenceGatewayApiKey":"keep","inferenceProvider":"gateway","inferenceGatewayBaseUrl":"https://ollama.com","inferenceGatewayAuthScheme":"bearer","inferenceModels":["legacy"]}`), 0o644); err != nil {
+ if err := os.WriteFile(paths.profile, []byte(`{"autoModeEnabled":true,"coworkEgressAllowedHosts":["github.com"],"disableDeploymentModeChooser":true,"disableEssentialTelemetry":true,"disableNonessentialTelemetry":true,"inferenceGatewayApiKey":"keep","inferenceProvider":"gateway","inferenceGatewayBaseUrl":"https://ollama.com","inferenceGatewayAuthScheme":"bearer","inferenceModels":["legacy"]}`), 0o644); err != nil {
t.Fatal(err)
}
@@ -835,7 +815,7 @@ func TestClaudeDesktopRestoreSwitchesBackToFirstPartyMode(t *testing.T) {
if profile["inferenceGatewayApiKey"] != "keep" {
t.Fatal("restore should leave existing Ollama profile credentials in place")
}
- for _, key := range []string{"inferenceProvider", "inferenceGatewayBaseUrl", "inferenceGatewayAuthScheme", "inferenceModels"} {
+ for _, key := range []string{"inferenceProvider", "inferenceGatewayBaseUrl", "inferenceGatewayAuthScheme", "inferenceModels", "coworkEgressAllowedHosts", "autoModeEnabled", "disableEssentialTelemetry", "disableNonessentialTelemetry"} {
if _, ok := profile[key]; ok {
t.Fatalf("restore should clear stale %s from the Ollama profile: %v", key, profile)
}
@@ -849,32 +829,35 @@ func TestClaudeDesktopRestoreSwitchesBackToFirstPartyMode(t *testing.T) {
}
}
-func TestClaudeDesktopRestoreTouchesAllWindowsProfileCandidates(t *testing.T) {
- tmpDir := t.TempDir()
- setTestHome(t, tmpDir)
+func TestClaudeDesktopRestoreRemainsAvailableOnWindows(t *testing.T) {
+ localAppData := t.TempDir()
+ t.Setenv("LOCALAPPDATA", localAppData)
withClaudeDesktopPlatform(t, "windows")
- local := filepath.Join(tmpDir, "LocalAppData")
- t.Setenv("LOCALAPPDATA", local)
withClaudeDesktopProcessHooks(t, func() bool { return false }, func() error { return nil }, func() error { return nil })
targets, err := claudeDesktopTargetPaths()
if err != nil {
t.Fatal(err)
}
- if len(targets.normalConfigs) != 2 {
- t.Fatalf("normal config target count = %d, want 2", len(targets.normalConfigs))
- }
- if len(targets.thirdPartyProfiles) != 2 {
- t.Fatalf("third-party target count = %d, want 2", len(targets.thirdPartyProfiles))
+ for _, path := range targets.normalConfigs {
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(`{"deploymentMode":"3p"}`), 0o644); err != nil {
+ t.Fatal(err)
+ }
}
for _, target := range targets.thirdPartyProfiles {
if err := os.MkdirAll(filepath.Dir(target.profile), 0o755); err != nil {
t.Fatal(err)
}
- if err := os.WriteFile(target.meta, []byte(`{"appliedId":"`+claudeDesktopProfileID+`","entries":[{"id":"`+claudeDesktopProfileID+`","name":"Ollama"}]}`), 0o644); err != nil {
+ if err := os.WriteFile(target.desktopConfig, []byte(`{"deploymentMode":"3p"}`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(target.meta, []byte(`{"appliedId":"`+claudeDesktopProfileID+`"}`), 0o644); err != nil {
t.Fatal(err)
}
- if err := os.WriteFile(target.profile, []byte(`{"disableDeploymentModeChooser":true,"inferenceGatewayApiKey":"keep","inferenceProvider":"gateway","inferenceGatewayBaseUrl":"https://ollama.com","inferenceGatewayAuthScheme":"bearer","inferenceModels":["legacy"]}`), 0o644); err != nil {
+ if err := os.WriteFile(target.profile, []byte(`{"inferenceProvider":"gateway","inferenceGatewayBaseUrl":"http://127.0.0.1:11435"}`), 0o644); err != nil {
t.Fatal(err)
}
}
@@ -882,65 +865,271 @@ func TestClaudeDesktopRestoreTouchesAllWindowsProfileCandidates(t *testing.T) {
if err := (&ClaudeDesktop{}).Restore(); err != nil {
t.Fatalf("Restore returned error: %v", err)
}
-
for _, path := range targets.normalConfigs {
- cfg := claudeDesktopReadJSON(t, path)
- if cfg["deploymentMode"] != "1p" {
- t.Fatalf("%s deploymentMode = %v, want 1p", path, cfg["deploymentMode"])
+ if got := claudeDesktopReadJSON(t, path)["deploymentMode"]; got != "1p" {
+ t.Fatalf("%s deploymentMode = %v, want 1p", path, got)
}
}
for _, target := range targets.thirdPartyProfiles {
- cfg := claudeDesktopReadJSON(t, target.desktopConfig)
- if cfg["deploymentMode"] != "1p" {
- t.Fatalf("%s deploymentMode = %v, want 1p", target.desktopConfig, cfg["deploymentMode"])
- }
- meta := claudeDesktopReadJSON(t, target.meta)
- if _, ok := meta["appliedId"]; ok {
- t.Fatalf("%s should not keep the Ollama applied profile: %v", target.meta, meta)
- }
- profile := claudeDesktopReadJSON(t, target.profile)
- if profile["disableDeploymentModeChooser"] != false {
- t.Fatalf("%s disableDeploymentModeChooser = %v, want false", target.profile, profile["disableDeploymentModeChooser"])
- }
- if profile["inferenceGatewayApiKey"] != "keep" {
- t.Fatalf("%s should preserve gateway API key", target.profile)
+ if got := claudeDesktopReadJSON(t, target.desktopConfig)["deploymentMode"]; got != "1p" {
+ t.Fatalf("%s deploymentMode = %v, want 1p", target.desktopConfig, got)
}
- for _, key := range []string{"inferenceProvider", "inferenceGatewayBaseUrl", "inferenceGatewayAuthScheme", "inferenceModels"} {
- if _, ok := profile[key]; ok {
- t.Fatalf("%s should clear stale %s: %v", target.profile, key, profile)
- }
+ if _, ok := claudeDesktopReadJSON(t, target.profile)["inferenceProvider"]; ok {
+ t.Fatalf("%s still contains inferenceProvider", target.profile)
}
}
}
-func TestClaudeDesktopRunReturnsUnsupported(t *testing.T) {
+func TestClaudeDesktopRunRestartsRunningAppWhenConfirmed(t *testing.T) {
+ tmpDir := t.TempDir()
+ setTestHome(t, tmpDir)
withClaudeDesktopPlatform(t, "darwin")
+ restoreConfirm := withLaunchConfirmPolicy(launchConfirmPolicy{yes: true})
+ defer restoreConfirm()
+ paths, err := claudeDesktopConfigPaths()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Dir(paths.profile), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ running := true
+ var quitCalls, openCalls int
withClaudeDesktopProcessHooks(t,
- func() bool {
- t.Fatal("Run should not inspect Claude Desktop process state")
- return false
+ func() bool { return running },
+ func() error {
+ quitCalls++
+ running = false
+ return os.WriteFile(paths.profile, []byte(`{"chatTabEnabled":false}`), 0o644)
},
func() error {
- t.Fatal("Run should not quit Claude Desktop")
+ openCalls++
return nil
},
+ )
+
+ if err := (&ClaudeDesktop{}).Run("qwen3.5", nil, nil); err != nil {
+ t.Fatalf("Run returned error: %v", err)
+ }
+ if quitCalls != 1 || openCalls != 1 {
+ t.Fatalf("quit/open calls = %d/%d, want 1/1", quitCalls, openCalls)
+ }
+ profile := claudeDesktopReadJSON(t, paths.profile)
+ if profile["chatTabEnabled"] != true {
+ t.Fatalf("chatTabEnabled = %v, want true after Claude shutdown write", profile["chatTabEnabled"])
+ }
+}
+
+func TestClaudeDesktopSetInstalledFromDesktopRequiresRestartConfirmation(t *testing.T) {
+ setTestHome(t, t.TempDir())
+ withClaudeDesktopPlatform(t, "darwin")
+ withClaudeDesktopProcessHooks(t,
+ func() bool { return true },
+ func() error { t.Fatal("Claude should not quit without confirmation"); return nil },
+ func() error { t.Fatal("Claude should not open without confirmation"); return nil },
+ )
+
+ err := (&ClaudeDesktop{}).SetInstalledFromDesktop(true, false)
+ if err == nil || !strings.Contains(err.Error(), "restart confirmation is required") {
+ t.Fatalf("SetInstalledFromDesktop error = %v, want restart confirmation error", err)
+ }
+}
+
+func TestClaudeDesktopSetInstalledFromDesktopOpensStoppedAppWhenEnabled(t *testing.T) {
+ setTestHome(t, t.TempDir())
+ withClaudeDesktopPlatform(t, "darwin")
+ openCalls := 0
+ withClaudeDesktopProcessHooks(t,
+ func() bool { return false },
+ func() error { t.Fatal("stopped Claude should not be quit"); return nil },
+ func() error { openCalls++; return nil },
+ )
+
+ c := &ClaudeDesktop{}
+ if err := c.SetInstalledFromDesktop(true, false); err != nil {
+ t.Fatalf("SetInstalledFromDesktop returned error: %v", err)
+ }
+ if openCalls != 1 || !c.AutodiscoveryConfigured() {
+ t.Fatalf("open calls/configured = %d/%v, want 1/true", openCalls, c.AutodiscoveryConfigured())
+ }
+}
+
+func TestClaudeDesktopSetInstalledFromDesktopDoesNotOpenStoppedAppWhenDisabled(t *testing.T) {
+ setTestHome(t, t.TempDir())
+ withClaudeDesktopPlatform(t, "darwin")
+ c := &ClaudeDesktop{}
+ if err := c.ConfigureAutodiscovery(); err != nil {
+ t.Fatal(err)
+ }
+ withClaudeDesktopProcessHooks(t,
+ func() bool { return false },
+ func() error { t.Fatal("stopped Claude should not be quit"); return nil },
+ func() error { t.Fatal("disabling should not open stopped Claude"); return nil },
+ )
+
+ if err := c.SetInstalledFromDesktop(false, false); err != nil {
+ t.Fatalf("SetInstalledFromDesktop returned error: %v", err)
+ }
+ if c.AutodiscoveryConfigured() {
+ t.Fatal("Claude gateway remains configured after disabling")
+ }
+}
+
+func TestClaudeDesktopRestoreForShutdownDoesNotReopenApp(t *testing.T) {
+ tmpDir := t.TempDir()
+ setTestHome(t, tmpDir)
+ withClaudeDesktopPlatform(t, "darwin")
+ c := &ClaudeDesktop{}
+ if err := c.ConfigureAutodiscovery(); err != nil {
+ t.Fatal(err)
+ }
+ paths, err := claudeDesktopConfigPaths()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ running := true
+ quitCalls := 0
+ withClaudeDesktopProcessHooks(t,
+ func() bool { return running },
+ func() error {
+ quitCalls++
+ running = false
+ return os.WriteFile(paths.profile, []byte(`{"provider":"ollama"}`), 0o644)
+ },
func() error {
- t.Fatal("Run should not open Claude Desktop")
+ t.Fatal("Claude reopened during shutdown")
return nil
},
)
- for _, args := range [][]string{nil, {"--foo"}} {
- err := (&ClaudeDesktop{}).Run("qwen3.5", nil, args)
- if err == nil {
- t.Fatal("expected Run to fail")
- }
- if !strings.Contains(err.Error(), "Claude Desktop is no longer supported") {
- t.Fatalf("expected unsupported guidance, got %v", err)
- }
- if !strings.Contains(err.Error(), "ollama launch claude-desktop --restore") {
- t.Fatalf("expected restore guidance, got %v", err)
+ if err := c.RestoreForShutdown(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if quitCalls != 1 {
+ t.Fatalf("quit calls = %d, want 1", quitCalls)
+ }
+ if c.UsesOllamaGateway() {
+ t.Fatal("Claude gateway remains configured after shutdown restore")
+ }
+}
+
+func TestClaudeDesktopRestoreForShutdownBoundsHungQuit(t *testing.T) {
+ withClaudeDesktopPlatform(t, "darwin")
+ oldRunning := claudeDesktopIsRunning
+ oldQuit := claudeDesktopQuitApp
+ claudeDesktopIsRunning = func(context.Context) (bool, error) { return true, nil }
+ claudeDesktopQuitApp = func(ctx context.Context) error {
+ <-ctx.Done()
+ return ctx.Err()
+ }
+ t.Cleanup(func() {
+ claudeDesktopIsRunning = oldRunning
+ claudeDesktopQuitApp = oldQuit
+ })
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
+ defer cancel()
+ err := (&ClaudeDesktop{}).RestoreForShutdown(ctx)
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("RestoreForShutdown error = %v, want deadline exceeded", err)
+ }
+}
+
+func TestClaudeDesktopRestoreForShutdownBoundsExitWait(t *testing.T) {
+ withClaudeDesktopPlatform(t, "darwin")
+ oldRunning := claudeDesktopIsRunning
+ oldQuit := claudeDesktopQuitApp
+ claudeDesktopIsRunning = func(context.Context) (bool, error) { return true, nil }
+ claudeDesktopQuitApp = func(context.Context) error { return nil }
+ t.Cleanup(func() {
+ claudeDesktopIsRunning = oldRunning
+ claudeDesktopQuitApp = oldQuit
+ })
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
+ defer cancel()
+ err := (&ClaudeDesktop{}).RestoreForShutdown(ctx)
+ if err == nil || !strings.Contains(err.Error(), "did not quit") {
+ t.Fatalf("RestoreForShutdown error = %v, want bounded exit error", err)
+ }
+}
+
+func TestClaudeDesktopRestoreForShutdownPreservesProfileWhenInitialCheckExpires(t *testing.T) {
+ setTestHome(t, t.TempDir())
+ withClaudeDesktopPlatform(t, "darwin")
+ c := &ClaudeDesktop{}
+ if err := c.ConfigureAutodiscovery(); err != nil {
+ t.Fatal(err)
+ }
+
+ oldRunning := claudeDesktopIsRunning
+ oldQuit := claudeDesktopQuitApp
+ claudeDesktopIsRunning = func(ctx context.Context) (bool, error) {
+ <-ctx.Done()
+ return false, ctx.Err()
+ }
+ claudeDesktopQuitApp = func(context.Context) error {
+ t.Fatal("quit called after an indeterminate process check")
+ return nil
+ }
+ t.Cleanup(func() {
+ claudeDesktopIsRunning = oldRunning
+ claudeDesktopQuitApp = oldQuit
+ })
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
+ defer cancel()
+ err := c.RestoreForShutdown(ctx)
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("RestoreForShutdown error = %v, want deadline exceeded", err)
+ }
+ if !c.UsesOllamaGateway() {
+ t.Fatal("indeterminate initial process check restored the profile")
+ }
+}
+
+func TestClaudeDesktopRestoreForShutdownPreservesProfileWhenExitCheckExpires(t *testing.T) {
+ setTestHome(t, t.TempDir())
+ withClaudeDesktopPlatform(t, "darwin")
+ c := &ClaudeDesktop{}
+ if err := c.ConfigureAutodiscovery(); err != nil {
+ t.Fatal(err)
+ }
+
+ oldRunning := claudeDesktopIsRunning
+ oldQuit := claudeDesktopQuitApp
+ checks := 0
+ claudeDesktopIsRunning = func(ctx context.Context) (bool, error) {
+ checks++
+ if checks == 1 {
+ return true, nil
}
+ <-ctx.Done()
+ return false, ctx.Err()
+ }
+ claudeDesktopQuitApp = func(context.Context) error { return nil }
+ t.Cleanup(func() {
+ claudeDesktopIsRunning = oldRunning
+ claudeDesktopQuitApp = oldQuit
+ })
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
+ defer cancel()
+ err := c.RestoreForShutdown(ctx)
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("RestoreForShutdown error = %v, want deadline exceeded", err)
+ }
+ if !c.UsesOllamaGateway() {
+ t.Fatal("indeterminate exit process check restored the profile")
+ }
+}
+
+func TestClaudeDesktopRunRejectsExtraArgs(t *testing.T) {
+ withClaudeDesktopPlatform(t, "darwin")
+ err := (&ClaudeDesktop{}).Run("qwen3.5", nil, []string{"--foo"})
+ if err == nil || !strings.Contains(err.Error(), "does not accept extra arguments") {
+ t.Fatalf("Run error = %v, want extra args rejection", err)
}
}
diff --git a/cmd/launch/command_test.go b/cmd/launch/command_test.go
index 8a23e98a2..2fa97f5bf 100644
--- a/cmd/launch/command_test.go
+++ b/cmd/launch/command_test.go
@@ -233,31 +233,54 @@ func TestLaunchCmdTUICallback(t *testing.T) {
})
}
-func TestLaunchCmdClaudeDesktopLaunchReturnsUnsupported(t *testing.T) {
+func TestLaunchCmdClaudeDesktopRequiresRestore(t *testing.T) {
for _, name := range []string{"claude-desktop", "claude-app"} {
- t.Run(name, func(t *testing.T) {
- cmd := LaunchCmd(func(cmd *cobra.Command, args []string) error {
- t.Fatal("heartbeat check should not run before Claude Desktop unsupported error")
- return nil
- }, func(cmd *cobra.Command) {
- t.Fatal("TUI callback should not run for direct integration launch")
- })
- cmd.SetArgs([]string{name})
-
- err := cmd.Execute()
- if err == nil {
- t.Fatal("expected Claude Desktop launch command to fail")
- }
- if !strings.Contains(err.Error(), "Claude Desktop is no longer supported") {
- t.Fatalf("expected unsupported guidance, got %v", err)
- }
- if !strings.Contains(err.Error(), "ollama launch claude-desktop --restore") {
- t.Fatalf("expected restore guidance, got %v", err)
- }
- })
+ heartbeatCalled := false
+ cmd := LaunchCmd(func(cmd *cobra.Command, args []string) error {
+ heartbeatCalled = true
+ return nil
+ }, func(cmd *cobra.Command) {})
+ cmd.SetArgs([]string{name})
+
+ err := cmd.Execute()
+ if err == nil || !strings.Contains(err.Error(), "can only be restored from the command line") {
+ t.Fatalf("expected %s launch to require --restore, got %v", name, err)
+ }
+ if heartbeatCalled {
+ t.Fatalf("expected %s to fail before checking the Ollama server heartbeat", name)
+ }
}
}
+func TestLaunchCmdClaudeDesktopRestoreRemainsAvailable(t *testing.T) {
+ runner := &commandRestorableRunner{}
+ restore := OverrideIntegration("claude-desktop", runner)
+ defer restore()
+
+ heartbeatCalled := false
+ cmd := LaunchCmd(func(cmd *cobra.Command, args []string) error {
+ heartbeatCalled = true
+ return nil
+ }, func(cmd *cobra.Command) {})
+ cmd.SetArgs([]string{"claude-desktop", "--restore"})
+
+ if err := cmd.Execute(); err != nil {
+ t.Fatalf("expected Claude Desktop restore command to succeed, got %v", err)
+ }
+ if !runner.restored {
+ t.Fatal("expected Claude Desktop restore command to run restore")
+ }
+ if heartbeatCalled {
+ t.Fatal("expected Claude Desktop restore to skip the Ollama server heartbeat")
+ }
+}
+
+type commandRestorableRunner struct {
+ launcherRestorableRunner
+}
+
+func (r *commandRestorableRunner) SkipRestoreInstallCheck() bool { return true }
+
func TestLaunchCmdNilHeartbeat(t *testing.T) {
cmd := LaunchCmd(nil, nil)
if cmd == nil {
diff --git a/cmd/launch/integrations_test.go b/cmd/launch/integrations_test.go
index cccc84736..a602d4b0f 100644
--- a/cmd/launch/integrations_test.go
+++ b/cmd/launch/integrations_test.go
@@ -131,7 +131,7 @@ func TestChatGPTMigratesLegacyCodexAppLaunchConfig(t *testing.T) {
func TestHiddenIntegrationsExcludedFromVisibleLists(t *testing.T) {
for _, info := range ListIntegrationInfos() {
switch info.Name {
- case "vscode", "kimi", "muse":
+ case "claude-desktop", "vscode", "kimi", "muse":
t.Fatalf("hidden integration %q should not appear in ListIntegrationInfos", info.Name)
}
}
@@ -1924,7 +1924,7 @@ func TestListIntegrationInfos(t *testing.T) {
}
wantPrefix := []string{"claude", "chatgpt", "hermes", "openclaw", "opencode", "hermes-desktop", "codex", "copilot", "omp"}
if codexAppSupported() != nil {
- wantPrefix = []string{"claude", "hermes", "openclaw", "opencode", "hermes-desktop", "codex", "copilot", "omp"}
+ wantPrefix = slices.DeleteFunc(wantPrefix, func(name string) bool { return name == "chatgpt" })
}
if len(got) < len(wantPrefix) {
t.Fatalf("expected at least %d integrations, got %v", len(wantPrefix), got)
@@ -2009,11 +2009,19 @@ func TestListIntegrationInfos_HidesPoolsideOnWindows(t *testing.T) {
}
}
-func TestListIntegrationInfos_HidesClaudeDesktop(t *testing.T) {
- for _, info := range ListIntegrationInfos() {
- if info.Name == "claude-desktop" {
- t.Fatal("expected hidden claude-desktop to be absent")
- }
+func TestListIntegrationInfos_HidesClaudeDesktopOnUnsupportedPlatform(t *testing.T) {
+ for _, goos := range []string{"linux", "windows"} {
+ t.Run(goos, func(t *testing.T) {
+ previous := claudeDesktopGOOS
+ claudeDesktopGOOS = goos
+ t.Cleanup(func() { claudeDesktopGOOS = previous })
+
+ for _, info := range ListIntegrationInfos() {
+ if info.Name == "claude-desktop" {
+ t.Fatal("expected claude-desktop to be absent on unsupported platforms")
+ }
+ }
+ })
}
}
diff --git a/cmd/launch/launch.go b/cmd/launch/launch.go
index 86c69c984..5bd7f3c0a 100644
--- a/cmd/launch/launch.go
+++ b/cmd/launch/launch.go
@@ -307,6 +307,7 @@ Supported integrations:
Examples:
ollama launch
+ ollama launch claude-desktop --restore
ollama launch claude
ollama launch claude --model <model>
ollama launch chatgpt
@@ -319,9 +320,12 @@ Examples:
ollama launch codex -- --sandbox workspace-write`,
Args: cobra.ArbitraryArgs,
PreRunE: func(cmd *cobra.Command, args []string) error {
- if restoreFlag || launchCommandCanSkipHeartbeat(args) {
+ if restoreFlag {
return nil
}
+ if len(args) > 0 && launchCommandIsClaudeDesktop(args[0]) {
+ return fmt.Errorf("Claude Desktop can only be restored from the command line: ollama launch claude-desktop --restore")
+ }
return checkServerHeartbeat(cmd, args)
},
RunE: func(cmd *cobra.Command, args []string) error {
@@ -359,10 +363,6 @@ Examples:
return nil
}
- if !restoreFlag && launchCommandIsClaudeDesktop(name) {
- return errClaudeDesktopUnsupported()
- }
-
if modelFlag != "" && isCloudModelName(modelFlag) {
if client, err := api.ClientFromEnvironment(); err == nil {
if disabled, _ := cloudStatusDisabled(cmd.Context(), client); disabled {
@@ -404,13 +404,6 @@ Examples:
return cmd
}
-func launchCommandCanSkipHeartbeat(args []string) bool {
- if len(args) == 0 {
- return false
- }
- return launchCommandIsClaudeDesktop(args[0])
-}
-
func launchCommandIsClaudeDesktop(name string) bool {
canonical, _, err := LookupIntegration(name)
return err == nil && canonical == claudeDesktopIntegrationName
@@ -483,10 +476,6 @@ func LaunchIntegration(ctx context.Context, req IntegrationLaunchRequest) error
return err
}
- if name == claudeDesktopIntegrationName && !req.Restore {
- return errClaudeDesktopUnsupported()
- }
-
policy := launchIntegrationPolicy(req)
if req.Restore {
return restoreIntegration(name, runner, req)
@@ -859,7 +848,6 @@ func (c *launcherClient) launchManagedAutodiscoveryIntegration(ctx context.Conte
if err := c.ensureManagedAutodiscoveryUsable(ctx, autodiscovery, target); err != nil {
return err
}
-
needsConfigure := req.ForceConfigure || req.ConfigureOnly || !autodiscovery.AutodiscoveryConfigured() || !savedMatchesModels(saved, []string{target})
if needsConfigure {
diff --git a/cmd/launch/registry.go b/cmd/launch/registry.go
index 3e5aa845e..f0453aaf2 100644
--- a/cmd/launch/registry.go
+++ b/cmd/launch/registry.go
@@ -56,11 +56,11 @@ var integrationSpecs = []*IntegrationSpec{
Name: "claude-desktop",
Runner: &ClaudeDesktop{},
Aliases: []string{"claude-app"},
- Description: "Claude Desktop with Ollama Cloud",
Hidden: true,
+ Description: "Use Ollama models in Claude Desktop",
Install: IntegrationInstallSpec{
CheckInstalled: func() bool {
- return claudeDesktopInstalled()
+ return ClaudeDesktopInstalled()
},
URL: "https://claude.com/download",
},
diff --git a/cmd/tui/tui_test.go b/cmd/tui/tui_test.go
index bf40ba748..ead25b84a 100644
--- a/cmd/tui/tui_test.go
+++ b/cmd/tui/tui_test.go
@@ -174,33 +174,6 @@ func TestMenuStartsExpandedForPreviousOverflowSelection(t *testing.T) {
}
}
-func TestMenuOmitsMoreWithoutAdditionalIntegrations(t *testing.T) {
- state := launcherTestState()
- for name := range state.Integrations {
- if name != "claude" && name != "opencode" && name != "hermes" && name != "openclaw" {
- delete(state.Integrations, name)
- }
- }
- state.Integrations["claude-desktop"] = launch.LauncherIntegrationState{
- Name: "claude-desktop",
- DisplayName: "Claude Desktop",
- Selectable: true,
- Changeable: true,
- }
-
- menu := newModel(state)
- want := []string{"run", "claude", "opencode", "hermes", "openclaw"}
- if diff := compareStrings(integrationSequence(menu.items), want); diff != "" {
- t.Fatalf("unexpected menu without additional integrations: %s", diff)
- }
- if strings.Contains(menu.View(), "More...") {
- t.Fatalf("expected no More item without additional integrations\n%s", menu.View())
- }
- if strings.Contains(menu.View(), "Claude Desktop") {
- t.Fatalf("expected hidden integration to remain omitted\n%s", menu.View())
- }
-}
-
func TestMenuEnterOnRunSelectsRun(t *testing.T) {
menu := newModel(launcherTestState())
updated, _ := menu.Update(tea.KeyMsg{Type: tea.KeyEnter})
diff --git a/internal/proxy/claude_desktop.go b/internal/proxy/claude_desktop.go
new file mode 100644
index 000000000..dc319e004
--- /dev/null
+++ b/internal/proxy/claude_desktop.go
@@ -0,0 +1,806 @@
+package proxy
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "net/http/httputil"
+ "net/url"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/ollama/ollama/anthropic"
+ "github.com/ollama/ollama/internal/modelref"
+)
+
+const (
+ // DefaultClaudeDesktopListenAddr is the loopback address used by the Ollama
+ // app and the Claude Desktop profile it manages.
+ DefaultClaudeDesktopListenAddr = "127.0.0.1:11435"
+ maxRequestBodyBytes = 64 << 20
+ maxErrorBodyBytes = 64 << 10
+ upstreamReadyTimeout = 10 * time.Second
+ upstreamReadyPoll = 100 * time.Millisecond
+ upstreamReadyTTL = 5 * time.Second
+ healthPath = "/_ollama/health"
+ healthHeader = "X-Ollama-Claude-Gateway"
+ unsupportedImageNotice = "[Image omitted by Ollama because the selected model does not support image recognition.]"
+)
+
+// claudeModels are Claude-compatible IDs for Ollama models
+var claudeModels = []gatewayModel{
+ {
+ ID: "claude-fable-5",
+ Type: "model",
+ DisplayName: "GLM 5.2",
+ CreatedAt: "2026-06-09T00:00:00Z",
+ MaxTokens: 128_000,
+ AnthropicFamilyTier: "fable",
+ IsFamilyDefault: true,
+ OllamaModel: "glm-5.2:cloud",
+ },
+ {
+ ID: "claude-opus-5",
+ Type: "model",
+ DisplayName: "Kimi K3",
+ CreatedAt: "2026-07-24T00:00:00Z",
+ MaxTokens: 262_144,
+ AnthropicFamilyTier: "opus",
+ IsFamilyDefault: true,
+ OllamaModel: "kimi-k3:cloud",
+ SupportsVision: true,
+ },
+ {
+ ID: "claude-sonnet-5",
+ Type: "model",
+ DisplayName: "DeepSeek V4 Pro",
+ CreatedAt: "2026-06-30T00:00:00Z",
+ MaxTokens: 128_000,
+ AnthropicFamilyTier: "sonnet",
+ IsFamilyDefault: true,
+ OllamaModel: "deepseek-v4-pro:cloud",
+ },
+ {
+ ID: "claude-haiku-4-5-20251001",
+ Type: "model",
+ DisplayName: "DeepSeek V4 Flash",
+ CreatedAt: "2025-10-01T00:00:00Z",
+ MaxTokens: 64_000,
+ AnthropicFamilyTier: "haiku",
+ IsFamilyDefault: true,
+ OllamaModel: "deepseek-v4-flash:0731:cloud",
+ },
+ {
+ ID: "claude-sonnet-5-20251001",
+ Type: "model",
+ DisplayName: "Qwen3.8 MLX",
+ CreatedAt: "2025-10-01T00:00:00Z",
+ MaxTokens: 64_000,
+ AnthropicFamilyTier: "sonnet",
+ IsFamilyDefault: false,
+ OllamaModel: "qwen3.8:27b-mlx",
+ },
+}
+
+type gatewayModel struct {
+ ID string `json:"id"`
+ Type string `json:"type"`
+ DisplayName string `json:"display_name"`
+ CreatedAt string `json:"created_at"`
+ MaxTokens int `json:"max_tokens"`
+ AnthropicFamilyTier string `json:"anthropic_family_tier"`
+ IsFamilyDefault bool `json:"is_family_default"`
+ OllamaModel string `json:"-"`
+ SupportsVision bool `json:"-"`
+}
+
+// ClaudeDesktopConfig configures a Claude Desktop proxy instance.
+type ClaudeDesktopConfig struct {
+ ListenAddr string
+ OllamaURL string
+ Model string
+ Logger *slog.Logger
+ OnCountsChanged func(ClaudeDesktopCounts)
+ CloudModelsAvailable func(context.Context) bool
+ ListLocalModels func(context.Context) ([]string, error)
+}
+
+// ClaudeDesktopCounts reports requests routed through the proxy.
+type ClaudeDesktopCounts struct {
+ Routed uint64
+}
+
+type upstreamReadinessCheck struct {
+ done chan struct{}
+ err error
+}
+
+// ClaudeDesktop is the local gateway that Claude Desktop reaches through its
+// native third-party inference mode. It is deliberately an ordinary HTTP reverse
+// proxy: Claude terminates its own gateway protocol here, so no TLS
+// interception or system trust changes are necessary.
+type ClaudeDesktop struct {
+ listenAddr string
+ ollamaURL *url.URL
+ ollamaProxy *httputil.ReverseProxy
+ logger *slog.Logger
+ model string
+ onCountsChanged func(ClaudeDesktopCounts)
+ cloudModelsAvailable func(context.Context) bool
+ listLocalModels func(context.Context) ([]string, error)
+ routed atomic.Uint64
+ shutdown chan struct{}
+ shutdownOnce sync.Once
+
+ readyMu sync.Mutex
+ readyUntil time.Time
+ readyCheck *upstreamReadinessCheck
+ readyWait time.Duration
+ readyPoll time.Duration
+ dial func(context.Context, string, string) (net.Conn, error)
+
+ mu sync.Mutex
+ listener net.Listener
+ server *http.Server
+}
+
+// NewClaudeDesktop creates a Claude Desktop proxy.
+func NewClaudeDesktop(config ClaudeDesktopConfig) (*ClaudeDesktop, error) {
+ if strings.TrimSpace(config.ListenAddr) == "" {
+ return nil, errors.New("Claude gateway listen address is required")
+ }
+ if strings.TrimSpace(config.Model) == "" {
+ return nil, errors.New("Claude gateway model is required")
+ }
+
+ ollamaURL, err := url.Parse(config.OllamaURL)
+ if err != nil {
+ return nil, fmt.Errorf("parse Ollama URL: %w", err)
+ }
+ if ollamaURL.Scheme == "" || ollamaURL.Host == "" {
+ return nil, fmt.Errorf("invalid Ollama URL %q", config.OllamaURL)
+ }
+
+ logger := config.Logger
+ if logger == nil {
+ logger = slog.Default()
+ }
+ transport := http.DefaultTransport.(*http.Transport).Clone()
+ transport.Proxy = nil
+ proxy := httputil.NewSingleHostReverseProxy(ollamaURL)
+ proxy.Transport = transport
+ proxy.FlushInterval = -1
+ p := &ClaudeDesktop{
+ listenAddr: config.ListenAddr,
+ ollamaURL: ollamaURL,
+ logger: logger,
+ model: config.Model,
+ onCountsChanged: config.OnCountsChanged,
+ cloudModelsAvailable: config.CloudModelsAvailable,
+ listLocalModels: config.ListLocalModels,
+ shutdown: make(chan struct{}),
+ readyWait: upstreamReadyTimeout,
+ readyPoll: upstreamReadyPoll,
+ }
+ dialer := &net.Dialer{Timeout: upstreamReadyPoll}
+ p.dial = dialer.DialContext
+ proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
+ p.markUpstreamNotReady()
+ logger.Warn("Claude gateway upstream request failed", "path", r.URL.Path, "error", err)
+ http.Error(w, "Ollama gateway unavailable", http.StatusBadGateway)
+ }
+ proxy.ModifyResponse = func(response *http.Response) error {
+ retried, err := retryWithoutUnsupportedImages(response, transport)
+ if err != nil {
+ logger.Warn("Claude gateway image fallback failed", "path", response.Request.URL.Path, "error", err)
+ return nil
+ }
+ if retried {
+ logger.Debug("Claude gateway retried request without unsupported images", "path", response.Request.URL.Path)
+ }
+ return nil
+ }
+
+ p.ollamaProxy = proxy
+ return p, nil
+}
+
+// ProbeClaudeDesktop verifies that baseURL is served by Ollama's Claude gateway rather than
+// another process using the configured port.
+func ProbeClaudeDesktop(ctx context.Context, baseURL string) error {
+ u, err := url.Parse(strings.TrimRight(baseURL, "/") + healthPath)
+ if err != nil || u.Scheme == "" || u.Host == "" {
+ return fmt.Errorf("invalid Claude gateway URL %q", baseURL)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
+ if err != nil {
+ return fmt.Errorf("create Claude gateway health request: %w", err)
+ }
+ transport := http.DefaultTransport.(*http.Transport).Clone()
+ transport.Proxy = nil
+ defer transport.CloseIdleConnections()
+ resp, err := (&http.Client{Transport: transport}).Do(req)
+ if err != nil {
+ return fmt.Errorf("connect to Claude gateway: %w", err)
+ }
+ defer resp.Body.Close()
+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10))
+ if resp.StatusCode != http.StatusNoContent || resp.Header.Get(healthHeader) != "1" {
+ return fmt.Errorf("another service is using %s", u.Host)
+ }
+ return nil
+}
+
+func (p *ClaudeDesktop) Start() error {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.listener != nil {
+ return errors.New("Claude gateway already started")
+ }
+
+ listener, err := net.Listen("tcp", p.listenAddr)
+ if err != nil {
+ return fmt.Errorf("listen for Claude gateway: %w", err)
+ }
+ p.listener = listener
+ p.server = &http.Server{
+ Handler: p,
+ ReadHeaderTimeout: 10 * time.Second,
+ }
+ go func() {
+ if err := p.server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ p.logger.Warn("Claude gateway stopped", "error", err)
+ }
+ }()
+ p.logger.Info("Claude gateway started", "address", listener.Addr().String())
+ return nil
+}
+
+func (p *ClaudeDesktop) Close(ctx context.Context) error {
+ p.shutdownOnce.Do(func() { close(p.shutdown) })
+ p.mu.Lock()
+ server := p.server
+ p.mu.Unlock()
+ var err error
+ if server != nil {
+ err = server.Shutdown(ctx)
+ }
+ if transport, ok := p.ollamaProxy.Transport.(*http.Transport); ok {
+ transport.CloseIdleConnections()
+ }
+ return err
+}
+
+func (p *ClaudeDesktop) Addr() string {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.listener == nil {
+ return ""
+ }
+ return p.listener.Addr().String()
+}
+
+func (p *ClaudeDesktop) Counts() ClaudeDesktopCounts {
+ return ClaudeDesktopCounts{Routed: p.routed.Load()}
+}
+
+func (p *ClaudeDesktop) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ if !p.allowsHost(r.Host) {
+ http.Error(w, "forbidden", http.StatusForbidden)
+ return
+ }
+
+ model := p.model
+ switch r.URL.Path {
+ case healthPath:
+ if r.Method != http.MethodGet {
+ methodNotAllowed(w, http.MethodGet)
+ return
+ }
+ w.Header().Set(healthHeader, "1")
+ w.WriteHeader(http.StatusNoContent)
+ return
+ case "/v1/models":
+ if r.Method != http.MethodGet {
+ methodNotAllowed(w, http.MethodGet)
+ return
+ }
+ p.serveModels(w, r.Context())
+ return
+ case "/v1/messages/count_tokens":
+ if r.Method != http.MethodPost {
+ methodNotAllowed(w, http.MethodPost)
+ return
+ }
+ p.serveTokenCount(w, r, model)
+ return
+ case "/v1/messages":
+ if r.Method != http.MethodPost {
+ methodNotAllowed(w, http.MethodPost)
+ return
+ }
+ if err := p.routeModel(r, model); err != nil {
+ writeAnthropicError(w, http.StatusBadRequest, err)
+ return
+ }
+ default:
+ http.NotFound(w, r)
+ return
+ }
+
+ // Claude authenticates to this loopback gateway with a placeholder key.
+ // Never forward that credential (or browser cookies) to the Ollama daemon.
+ r.Header.Del("Authorization")
+ r.Header.Del("Cookie")
+ r.Header.Del("Proxy-Authorization")
+ r.Header.Set("X-Api-Key", "ollama")
+ r.Host = p.ollamaURL.Host
+
+ if err := p.waitForUpstream(r.Context()); err != nil {
+ p.logger.Warn("Claude gateway upstream is not ready", "path", r.URL.Path, "error", err)
+ http.Error(w, "Ollama gateway unavailable", http.StatusBadGateway)
+ return
+ }
+ counts := ClaudeDesktopCounts{Routed: p.routed.Add(1)}
+ if p.onCountsChanged != nil {
+ p.onCountsChanged(counts)
+ }
+ p.ollamaProxy.ServeHTTP(w, r)
+}
+
+func (p *ClaudeDesktop) allowsHost(host string) bool {
+ _, listenerPort, err := net.SplitHostPort(p.Addr())
+ if err != nil {
+ return false
+ }
+
+ host, port, err := net.SplitHostPort(host)
+ if err != nil || port != listenerPort {
+ return false
+ }
+ if strings.EqualFold(host, "localhost") {
+ return true
+ }
+
+ ip := net.ParseIP(host)
+ return ip != nil && ip.IsLoopback()
+}
+
+func methodNotAllowed(w http.ResponseWriter, allow string) {
+ w.Header().Set("Allow", allow)
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+}
+
+func (p *ClaudeDesktop) waitForUpstream(ctx context.Context) error {
+ p.readyMu.Lock()
+ if time.Now().Before(p.readyUntil) {
+ p.readyMu.Unlock()
+ return nil
+ }
+ check := p.readyCheck
+ if check == nil {
+ check = &upstreamReadinessCheck{done: make(chan struct{})}
+ p.readyCheck = check
+ go p.runUpstreamReadinessCheck(check)
+ }
+ p.readyMu.Unlock()
+
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-check.done:
+ return check.err
+ }
+}
+
+func (p *ClaudeDesktop) runUpstreamReadinessCheck(check *upstreamReadinessCheck) {
+ ctx, cancel := context.WithTimeout(context.Background(), p.readyWait)
+ defer cancel()
+ ticker := time.NewTicker(p.readyPoll)
+ defer ticker.Stop()
+
+ var err error
+checkLoop:
+ for {
+ select {
+ case <-p.shutdown:
+ err = errors.New("Claude gateway stopped")
+ break checkLoop
+ default:
+ }
+
+ conn, dialErr := p.dial(ctx, "tcp", p.ollamaURL.Host)
+ if dialErr == nil {
+ _ = conn.Close()
+ select {
+ case <-p.shutdown:
+ err = errors.New("Claude gateway stopped")
+ default:
+ }
+ break
+ }
+
+ select {
+ case <-p.shutdown:
+ err = errors.New("Claude gateway stopped")
+ break checkLoop
+ case <-ctx.Done():
+ err = fmt.Errorf("timed out waiting for %s", p.ollamaURL.Host)
+ break checkLoop
+ case <-ticker.C:
+ }
+ }
+ p.readyMu.Lock()
+ if err == nil {
+ p.readyUntil = time.Now().Add(upstreamReadyTTL)
+ }
+ check.err = err
+ if p.readyCheck == check {
+ p.readyCheck = nil
+ }
+ close(check.done)
+ p.readyMu.Unlock()
+}
+
+func (p *ClaudeDesktop) markUpstreamNotReady() {
+ p.readyMu.Lock()
+ p.readyUntil = time.Time{}
+ p.readyMu.Unlock()
+}
+
+func (p *ClaudeDesktop) serveModels(w http.ResponseWriter, ctx context.Context) {
+ cloudModelsAvailable := p.cloudModelsAvailable == nil || p.cloudModelsAvailable(ctx)
+ var localModels map[string]struct{}
+ if p.listLocalModels != nil {
+ localModels = make(map[string]struct{})
+ names, err := p.listLocalModels(ctx)
+ if err != nil {
+ p.logger.Debug("could not list local models for Claude", "error", err)
+ } else {
+ for _, name := range names {
+ localModels[name] = struct{}{}
+ }
+ }
+ }
+
+ models := make([]gatewayModel, 0, len(claudeModels))
+ for _, model := range claudeModels {
+ if modelref.HasExplicitCloudSource(model.OllamaModel) {
+ if cloudModelsAvailable {
+ models = append(models, model)
+ }
+ continue
+ }
+ if localModels == nil {
+ models = append(models, model)
+ continue
+ }
+ if _, ok := localModels[model.OllamaModel]; ok {
+ models = append(models, model)
+ }
+ }
+
+ var firstID, lastID string
+ if len(models) > 0 {
+ firstID = models[0].ID
+ lastID = models[len(models)-1].ID
+ }
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(struct {
+ Data []gatewayModel `json:"data"`
+ FirstID string `json:"first_id"`
+ LastID string `json:"last_id"`
+ HasMore bool `json:"has_more"`
+ }{
+ Data: models,
+ FirstID: firstID,
+ LastID: lastID,
+ }); err != nil {
+ p.logger.Debug("write Claude model catalog", "error", err)
+ }
+}
+
+func (p *ClaudeDesktop) serveTokenCount(w http.ResponseWriter, r *http.Request, model string) {
+ body, err := readRequestBody(r)
+ if err != nil {
+ writeAnthropicError(w, http.StatusBadRequest, err)
+ return
+ }
+ var request anthropic.CountTokensRequest
+ if err := json.Unmarshal(body, &request); err != nil {
+ writeAnthropicError(w, http.StatusBadRequest, fmt.Errorf("decode Claude token-count request: %w", err))
+ return
+ }
+ selected := p.modelForClaudeID(request.Model, model)
+ request.Model = selected.OllamaModel
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(anthropic.CountTokensResponse{
+ InputTokens: anthropic.EstimateCountTokens(request),
+ }); err != nil {
+ p.logger.Debug("write Claude token-count response", "error", err)
+ }
+}
+
+func (p *ClaudeDesktop) routeModel(r *http.Request, model string) error {
+ body, err := readRequestBody(r)
+ if err != nil {
+ return err
+ }
+ var payload map[string]json.RawMessage
+ if err := json.Unmarshal(body, &payload); err != nil {
+ return fmt.Errorf("decode Claude gateway request: %w", err)
+ }
+ var requestedModel string
+ if err := json.Unmarshal(payload["model"], &requestedModel); err != nil || strings.TrimSpace(requestedModel) == "" {
+ return errors.New("decode Claude gateway request: model is required")
+ }
+ selected := p.modelForClaudeID(requestedModel, model)
+ targetModel := selected.OllamaModel
+ if targetModel == requestedModel {
+ setRequestBody(r, body)
+ return nil
+ }
+ modelJSON, _ := json.Marshal(targetModel)
+ payload["model"] = modelJSON
+ rewritten, err := json.Marshal(payload)
+ if err != nil {
+ return fmt.Errorf("encode Claude gateway request: %w", err)
+ }
+ setRequestBody(r, rewritten)
+ return nil
+}
+
+func retryWithoutUnsupportedImages(response *http.Response, transport http.RoundTripper) (bool, error) {
+ if response.StatusCode != http.StatusBadRequest || response.Request.Method != http.MethodPost || response.Request.URL.Path != "/v1/messages" || response.Request.GetBody == nil {
+ return false, nil
+ }
+ if !responseRejectsImages(response) {
+ return false, nil
+ }
+
+ body, err := response.Request.GetBody()
+ if err != nil {
+ return false, fmt.Errorf("replay Claude gateway request: %w", err)
+ }
+ defer body.Close()
+ rewrittenBody, err := io.ReadAll(io.LimitReader(body, maxRequestBodyBytes+1))
+ if err != nil {
+ return false, fmt.Errorf("read replayable Claude gateway request: %w", err)
+ }
+ if len(rewrittenBody) > maxRequestBodyBytes {
+ return false, nil
+ }
+
+ var payload map[string]json.RawMessage
+ if err := json.Unmarshal(rewrittenBody, &payload); err != nil {
+ return false, nil
+ }
+ var targetModel string
+ if err := json.Unmarshal(payload["model"], &targetModel); err != nil {
+ return false, nil
+ }
+ selected, _ := gatewayModelForClaudeID(targetModel, targetModel)
+ if selected.SupportsVision {
+ return false, nil
+ }
+
+ changed, err := replaceUnsupportedImages(payload)
+ if err != nil || !changed {
+ return false, err
+ }
+ rewrittenBody, err = json.Marshal(payload)
+ if err != nil {
+ return false, fmt.Errorf("encode Claude image fallback request: %w", err)
+ }
+
+ retry := response.Request.Clone(response.Request.Context())
+ setRequestBody(retry, rewrittenBody)
+ retryResponse, err := transport.RoundTrip(retry)
+ if err != nil {
+ if retryResponse != nil && retryResponse.Body != nil {
+ _ = retryResponse.Body.Close()
+ }
+ return false, fmt.Errorf("retry Claude gateway request: %w", err)
+ }
+ defer func() {
+ if retryResponse.Body != nil {
+ _ = retryResponse.Body.Close()
+ }
+ }()
+ _ = response.Body.Close()
+ *response = *retryResponse
+ retryResponse.Body = nil
+ return true, nil
+}
+
+func responseRejectsImages(response *http.Response) bool {
+ if response.Body == nil {
+ return false
+ }
+ body := response.Body
+ prefix, err := io.ReadAll(io.LimitReader(body, maxErrorBodyBytes+1))
+ response.Body = struct {
+ io.Reader
+ io.Closer
+ }{Reader: io.MultiReader(bytes.NewReader(prefix), body), Closer: body}
+ if err != nil || len(prefix) > maxErrorBodyBytes {
+ return false
+ }
+ var responseError anthropic.ErrorResponse
+ if err := json.Unmarshal(prefix, &responseError); err != nil ||
+ responseError.Type != "error" || responseError.Error.Type != "invalid_request_error" {
+ return false
+ }
+ lower := strings.ToLower(responseError.Error.Message)
+ mentionsImages := strings.Contains(lower, "image") || strings.Contains(lower, "vision")
+ unsupported := strings.Contains(lower, "does not support") ||
+ strings.Contains(lower, "not support") ||
+ strings.Contains(lower, "unsupported")
+ return mentionsImages && unsupported
+}
+
+func setRequestBody(r *http.Request, body []byte) {
+ _ = r.Body.Close()
+ r.Body = io.NopCloser(bytes.NewReader(body))
+ r.GetBody = func() (io.ReadCloser, error) {
+ return io.NopCloser(bytes.NewReader(body)), nil
+ }
+ r.ContentLength = int64(len(body))
+ r.Header.Set("Content-Length", fmt.Sprintf("%d", len(body)))
+}
+
+func (p *ClaudeDesktop) modelForClaudeID(id, fallback string) gatewayModel {
+ model, known := gatewayModelForClaudeID(id, fallback)
+ if !known {
+ p.logger.Debug("Claude gateway using default for unknown model", "requested_model", id, "default_model", model.OllamaModel)
+ }
+ return model
+}
+
+func gatewayModelForClaudeID(id, fallback string) (gatewayModel, bool) {
+ for _, model := range claudeModels {
+ if model.ID == id {
+ return model, true
+ }
+ }
+ for _, model := range claudeModels {
+ if model.OllamaModel == fallback {
+ return model, false
+ }
+ }
+ return gatewayModel{DisplayName: fallback, OllamaModel: fallback}, false
+}
+
+func replaceUnsupportedImages(payload map[string]json.RawMessage) (bool, error) {
+ rawMessages, ok := payload["messages"]
+ if !ok {
+ return false, nil
+ }
+
+ var messages []json.RawMessage
+ if err := json.Unmarshal(rawMessages, &messages); err != nil {
+ return false, fmt.Errorf("decode Claude messages for image fallback: %w", err)
+ }
+
+ changed := false
+ for i, rawMessage := range messages {
+ var message map[string]json.RawMessage
+ if err := json.Unmarshal(rawMessage, &message); err != nil {
+ continue
+ }
+ content, ok := message["content"]
+ if !ok {
+ continue
+ }
+ rewritten, contentChanged, err := replaceImagesInContent(content)
+ if err != nil {
+ return false, err
+ }
+ if !contentChanged {
+ continue
+ }
+ message["content"] = rewritten
+ messages[i], err = json.Marshal(message)
+ if err != nil {
+ return false, fmt.Errorf("encode sanitized Claude message: %w", err)
+ }
+ changed = true
+ }
+ if !changed {
+ return false, nil
+ }
+
+ rewritten, err := json.Marshal(messages)
+ if err != nil {
+ return false, fmt.Errorf("encode sanitized Claude messages: %w", err)
+ }
+ payload["messages"] = rewritten
+ return true, nil
+}
+
+func replaceImagesInContent(content json.RawMessage) (json.RawMessage, bool, error) {
+ var blocks []json.RawMessage
+ if err := json.Unmarshal(content, &blocks); err != nil {
+ return content, false, fmt.Errorf("decode Claude content for image fallback: %w", err)
+ }
+
+ changed := false
+ for i, raw := range blocks {
+ var block struct {
+ Type string `json:"type"`
+ Content json.RawMessage `json:"content"`
+ }
+ if err := json.Unmarshal(raw, &block); err != nil {
+ continue
+ }
+ switch block.Type {
+ case "image":
+ replacement, err := json.Marshal(struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+ }{Type: "text", Text: unsupportedImageNotice})
+ if err != nil {
+ return nil, false, fmt.Errorf("encode unsupported-image notice: %w", err)
+ }
+ blocks[i] = replacement
+ changed = true
+ case "tool_result":
+ rewritten, contentChanged, err := replaceImagesInContent(block.Content)
+ if err != nil {
+ return nil, false, err
+ }
+ if !contentChanged {
+ continue
+ }
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &fields); err != nil {
+ continue
+ }
+ fields["content"] = rewritten
+ blocks[i], err = json.Marshal(fields)
+ if err != nil {
+ return nil, false, fmt.Errorf("encode sanitized Claude tool result: %w", err)
+ }
+ changed = true
+ }
+ }
+ if !changed {
+ return content, false, nil
+ }
+
+ rewritten, err := json.Marshal(blocks)
+ if err != nil {
+ return nil, false, fmt.Errorf("encode sanitized Claude content: %w", err)
+ }
+ return rewritten, true, nil
+}
+
+func writeAnthropicError(w http.ResponseWriter, status int, err error) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ if encodeErr := json.NewEncoder(w).Encode(anthropic.NewError(status, err.Error())); encodeErr != nil {
+ slog.Debug("write Claude gateway error", "error", encodeErr)
+ }
+}
+
+func readRequestBody(r *http.Request) ([]byte, error) {
+ if r.Body == nil {
+ return nil, errors.New("Claude gateway request body is required")
+ }
+ body, err := io.ReadAll(io.LimitReader(r.Body, maxRequestBodyBytes+1))
+ if err != nil {
+ return nil, fmt.Errorf("read Claude gateway request: %w", err)
+ }
+ if len(body) > maxRequestBodyBytes {
+ return nil, fmt.Errorf("Claude gateway request exceeds %d bytes", maxRequestBodyBytes)
+ }
+ return body, nil
+}
diff --git a/internal/proxy/claude_desktop_test.go b/internal/proxy/claude_desktop_test.go
new file mode 100644
index 000000000..15ae385a4
--- /dev/null
+++ b/internal/proxy/claude_desktop_test.go
@@ -0,0 +1,885 @@
+package proxy
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/ollama/ollama/anthropic"
+)
+
+func TestGatewayRoutesClaudeProtocolToOllama(t *testing.T) {
+ var paths []string
+ var messageModels []string
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ paths = append(paths, r.URL.RequestURI())
+ if r.Header.Get("Authorization") != "" || r.Header.Get("Cookie") != "" {
+ t.Fatal("gateway credential leaked upstream")
+ }
+ if r.Header.Get("X-Api-Key") != "ollama" {
+ t.Fatalf("X-Api-Key = %q", r.Header.Get("X-Api-Key"))
+ }
+ if r.URL.Path == "/v1/messages" {
+ messageModels = append(messageModels, requestModel(t, r))
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, `{"ok":true}`)
+ }))
+ defer upstream.Close()
+
+ p := startTestGateway(t, upstream.URL)
+ client := &http.Client{Timeout: 2 * time.Second}
+ for _, request := range []struct {
+ method string
+ path string
+ body string
+ }{
+ {http.MethodGet, "/v1/models?limit=1000", ""},
+ {http.MethodPost, "/v1/messages", `{"model":"claude-fable-5","messages":[]}`},
+ {http.MethodPost, "/v1/messages", `{"model":"claude-opus-5","messages":[]}`},
+ {http.MethodPost, "/v1/messages", `{"model":"claude-sonnet-5","messages":[]}`},
+ {http.MethodPost, "/v1/messages", `{"model":"claude-haiku-4-5-20251001","messages":[]}`},
+ {http.MethodPost, "/v1/messages", `{"model":"claude-sonnet-5-20251001","messages":[]}`},
+ {http.MethodPost, "/v1/messages", `{"model":"claude-opus-4-6","messages":[]}`},
+ } {
+ req, err := http.NewRequest(request.method, "http://"+p.Addr()+request.path, strings.NewReader(request.body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Authorization", "Bearer local-placeholder")
+ req.Header.Set("Cookie", "session=secret")
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.StatusCode != http.StatusOK {
+ _ = resp.Body.Close()
+ t.Fatalf("%s = %d", request.path, resp.StatusCode)
+ }
+ if request.path == "/v1/models?limit=1000" {
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var catalog struct {
+ Data []gatewayModel `json:"data"`
+ FirstID string `json:"first_id"`
+ LastID string `json:"last_id"`
+ HasMore bool `json:"has_more"`
+ }
+ if err := json.Unmarshal(body, &catalog); err != nil {
+ t.Fatal(err)
+ }
+ var rawCatalog struct {
+ Data []map[string]json.RawMessage `json:"data"`
+ }
+ if err := json.Unmarshal(body, &rawCatalog); err != nil {
+ t.Fatal(err)
+ }
+ for _, model := range rawCatalog.Data {
+ if _, ok := model["max_input_tokens"]; ok {
+ t.Fatalf("gateway model should not advertise context size: %s", body)
+ }
+ }
+ gotIDs := make([]string, len(catalog.Data))
+ gotNames := make([]string, len(catalog.Data))
+ familyDefaults := make(map[string]int)
+ for i, model := range catalog.Data {
+ gotIDs[i] = model.ID
+ gotNames[i] = model.DisplayName
+ if model.Type != "model" || model.AnthropicFamilyTier == "" {
+ t.Fatalf("incomplete gateway model metadata: %+v", model)
+ }
+ if model.IsFamilyDefault {
+ familyDefaults[model.AnthropicFamilyTier]++
+ }
+ if model.ID == "claude-sonnet-5-20251001" && model.AnthropicFamilyTier != "sonnet" {
+ t.Fatalf("Qwen family tier = %q, want sonnet", model.AnthropicFamilyTier)
+ }
+ }
+ for _, family := range []string{"opus", "fable", "sonnet", "haiku"} {
+ if familyDefaults[family] != 1 {
+ t.Fatalf("%s family defaults = %d, want 1", family, familyDefaults[family])
+ }
+ }
+ wantIDs := "claude-fable-5,claude-opus-5,claude-sonnet-5,claude-haiku-4-5-20251001,claude-sonnet-5-20251001"
+ if strings.Join(gotIDs, ",") != wantIDs || catalog.FirstID != gotIDs[0] || catalog.LastID != gotIDs[len(gotIDs)-1] || catalog.HasMore {
+ t.Fatalf("gateway catalog = %+v", catalog.Data)
+ }
+ wantNames := "GLM 5.2,Kimi K3,DeepSeek V4 Pro,DeepSeek V4 Flash,Qwen3.8 MLX"
+ if strings.Join(gotNames, ",") != wantNames {
+ t.Fatalf("gateway display names = %v, want %s", gotNames, wantNames)
+ }
+ }
+ _ = resp.Body.Close()
+ }
+
+ wantModels := []string{
+ "glm-5.2:cloud",
+ "kimi-k3:cloud",
+ "deepseek-v4-pro:cloud",
+ "deepseek-v4-flash:0731:cloud",
+ "qwen3.8:27b-mlx",
+ "glm-5.2:cloud",
+ }
+ if strings.Join(messageModels, ",") != strings.Join(wantModels, ",") {
+ t.Fatalf("rewritten message models = %v", messageModels)
+ }
+ if len(paths) != 6 {
+ t.Fatalf("upstream paths = %v", paths)
+ }
+ if got := p.Counts().Routed; got != 6 {
+ t.Fatalf("routed requests = %d, want 6", got)
+ }
+}
+
+func TestGatewayPrunesCloudModelsWhenSignedOut(t *testing.T) {
+ upstream := httptest.NewServer(http.NotFoundHandler())
+ defer upstream.Close()
+
+ var cloudModelsAvailable atomic.Bool
+ var localModelAvailable atomic.Bool
+ p, err := NewClaudeDesktop(ClaudeDesktopConfig{
+ ListenAddr: "127.0.0.1:0",
+ OllamaURL: upstream.URL,
+ Model: "kimi-k3:cloud",
+ CloudModelsAvailable: func(context.Context) bool { return cloudModelsAvailable.Load() },
+ ListLocalModels: func(context.Context) ([]string, error) {
+ if localModelAvailable.Load() {
+ return []string{"qwen3.8:27b-mlx"}, nil
+ }
+ return nil, nil
+ },
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := p.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ if err := p.Close(ctx); err != nil {
+ t.Fatal(err)
+ }
+ })
+
+ fetchCatalog := func() struct {
+ Data []gatewayModel `json:"data"`
+ FirstID string `json:"first_id"`
+ LastID string `json:"last_id"`
+ } {
+ resp, err := http.Get("http://" + p.Addr() + "/v1/models")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d, want 200", resp.StatusCode)
+ }
+ var catalog struct {
+ Data []gatewayModel `json:"data"`
+ FirstID string `json:"first_id"`
+ LastID string `json:"last_id"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&catalog); err != nil {
+ t.Fatal(err)
+ }
+ return catalog
+ }
+
+ catalog := fetchCatalog()
+ if len(catalog.Data) != 0 || catalog.FirstID != "" || catalog.LastID != "" {
+ t.Fatalf("signed-out empty catalog = %+v", catalog)
+ }
+
+ localModelAvailable.Store(true)
+ catalog = fetchCatalog()
+ if len(catalog.Data) != 1 || catalog.Data[0].DisplayName != "Qwen3.8 MLX" {
+ t.Fatalf("signed-out catalog = %+v, want local model only", catalog.Data)
+ }
+ if catalog.FirstID != catalog.Data[0].ID || catalog.LastID != catalog.Data[0].ID {
+ t.Fatalf("signed-out catalog bounds = %q, %q", catalog.FirstID, catalog.LastID)
+ }
+
+ cloudModelsAvailable.Store(true)
+ catalog = fetchCatalog()
+ if len(catalog.Data) != len(claudeModels) {
+ t.Fatalf("signed-in catalog has %d models, want %d", len(catalog.Data), len(claudeModels))
+ }
+}
+
+func TestGatewayCountsTokensLocally(t *testing.T) {
+ upstreamCalls := 0
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ upstreamCalls++
+ }))
+ defer upstream.Close()
+ p := startTestGateway(t, upstream.URL)
+
+ resp, err := http.Post(
+ "http://"+p.Addr()+"/v1/messages/count_tokens",
+ "application/json",
+ strings.NewReader(`{"model":"claude-sonnet","messages":[{"role":"user","content":"hello world"}]}`),
+ )
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d", resp.StatusCode)
+ }
+ var result struct {
+ InputTokens int `json:"input_tokens"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ t.Fatal(err)
+ }
+ if result.InputTokens <= 0 {
+ t.Fatalf("input_tokens = %d, want positive estimate", result.InputTokens)
+ }
+ if upstreamCalls != 0 {
+ t.Fatalf("upstream calls = %d, want 0", upstreamCalls)
+ }
+}
+
+func TestGatewayRejectsNonLoopbackHost(t *testing.T) {
+ var upstreamCalls atomic.Int32
+ upstream := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ upstreamCalls.Add(1)
+ }))
+ defer upstream.Close()
+ p := startTestGateway(t, upstream.URL)
+
+ _, port, err := net.SplitHostPort(p.Addr())
+ if err != nil {
+ t.Fatal(err)
+ }
+ req, err := http.NewRequest(http.MethodPost, "http://"+p.Addr()+"/v1/messages", strings.NewReader(`{"model":"claude-sonnet-5","messages":[]}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = net.JoinHostPort("attacker.example", port)
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusForbidden {
+ t.Fatalf("status = %d, want 403", resp.StatusCode)
+ }
+ if got := upstreamCalls.Load(); got != 0 {
+ t.Fatalf("upstream calls = %d, want 0", got)
+ }
+}
+
+func TestGatewayRejectsHostWithWrongPort(t *testing.T) {
+ var upstreamCalls atomic.Int32
+ upstream := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ upstreamCalls.Add(1)
+ }))
+ defer upstream.Close()
+ p := startTestGateway(t, upstream.URL)
+
+ _, port, err := net.SplitHostPort(p.Addr())
+ if err != nil {
+ t.Fatal(err)
+ }
+ wrongPort := "1"
+ if port == wrongPort {
+ wrongPort = "2"
+ }
+ req, err := http.NewRequest(http.MethodGet, "http://"+p.Addr()+"/v1/models", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = net.JoinHostPort("127.0.0.1", wrongPort)
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusForbidden {
+ t.Fatalf("status = %d, want 403", resp.StatusCode)
+ }
+ if got := upstreamCalls.Load(); got != 0 {
+ t.Fatalf("upstream calls = %d, want 0", got)
+ }
+}
+
+func TestGatewayAllowsLoopbackHosts(t *testing.T) {
+ upstream := httptest.NewServer(http.NotFoundHandler())
+ defer upstream.Close()
+ p := startTestGateway(t, upstream.URL)
+
+ _, port, err := net.SplitHostPort(p.Addr())
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, host := range []string{"localhost", "127.0.0.1", "::1"} {
+ t.Run(host, func(t *testing.T) {
+ req, err := http.NewRequest(http.MethodGet, "http://"+p.Addr()+"/v1/models", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = net.JoinHostPort(host, port)
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d, want 200", resp.StatusCode)
+ }
+ })
+ }
+}
+
+func TestGatewayDoesNotForwardUnsupportedRoutes(t *testing.T) {
+ var upstreamCalls atomic.Int32
+ upstream := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ upstreamCalls.Add(1)
+ }))
+ defer upstream.Close()
+ p := startTestGateway(t, upstream.URL)
+
+ for _, test := range []struct {
+ method string
+ path string
+ status int
+ allow string
+ }{
+ {http.MethodPost, "/api/delete", http.StatusNotFound, ""},
+ {http.MethodPost, "/v1/chat/completions", http.StatusNotFound, ""},
+ {http.MethodGet, "/v1/messages", http.StatusMethodNotAllowed, http.MethodPost},
+ {http.MethodGet, "/v1/messages/count_tokens", http.StatusMethodNotAllowed, http.MethodPost},
+ } {
+ t.Run(test.method+" "+test.path, func(t *testing.T) {
+ req, err := http.NewRequest(test.method, "http://"+p.Addr()+test.path, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != test.status {
+ t.Fatalf("status = %d, want %d", resp.StatusCode, test.status)
+ }
+ if resp.Header.Get("Allow") != test.allow {
+ t.Fatalf("Allow = %q, want %q", resp.Header.Get("Allow"), test.allow)
+ }
+ })
+ }
+ if got := upstreamCalls.Load(); got != 0 {
+ t.Fatalf("upstream calls = %d, want 0", got)
+ }
+}
+
+func TestGatewayLazilyRetriesUnsupportedVision(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ body string
+ preserve string
+ }{
+ {
+ name: "message image",
+ body: `{"model":"claude-sonnet-5","messages":[{"role":"user","content":[{"type":"text","text":"Describe this"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aW1hZ2U="}}]}],"stream":true}`,
+ preserve: "Describe this",
+ },
+ {
+ name: "tool result image",
+ body: `{"model":"claude-fable-5","messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"tool_1","content":[{"type":"text","text":"Screenshot"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aW1hZ2U="}}]}]}]}`,
+ preserve: "tool_1",
+ },
+ {
+ name: "historical image with later text",
+ body: `{"model":"claude-fable-5","messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aW1hZ2U="}},{"type":"text","text":"what dis"}]},{"role":"assistant","content":[{"type":"text","text":"I cannot inspect it"}]},{"role":"user","content":[{"type":"text","text":"kk"}]}]}`,
+ preserve: "kk",
+ },
+ {
+ name: "unknown ID uses non-vision fallback",
+ body: `{"model":"claude-unknown","messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aW1hZ2U="}}]}]}`,
+ preserve: unsupportedImageNotice,
+ },
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ var upstreamBodies [][]byte
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ upstreamBodies = append(upstreamBodies, body)
+ w.Header().Set("Content-Type", "application/json")
+ if len(upstreamBodies) == 1 {
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = io.WriteString(w, `{"type":"error","error":{"type":"invalid_request_error","message":"model does not support images"}}`)
+ return
+ }
+ _, _ = io.WriteString(w, `{"ok":true}`)
+ }))
+ defer upstream.Close()
+ p := startTestGateway(t, upstream.URL)
+
+ resp, err := http.Post("http://"+p.Addr()+"/v1/messages", "application/json", strings.NewReader(test.body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d, want 200", resp.StatusCode)
+ }
+ if len(upstreamBodies) != 2 {
+ t.Fatalf("upstream calls = %d, want 2", len(upstreamBodies))
+ }
+ if !strings.Contains(string(upstreamBodies[0]), `"type":"image"`) || !strings.Contains(string(upstreamBodies[0]), "aW1hZ2U=") {
+ t.Fatalf("first request was unexpectedly sanitized: %s", upstreamBodies[0])
+ }
+ if strings.Contains(string(upstreamBodies[1]), `"type":"image"`) || strings.Contains(string(upstreamBodies[1]), "aW1hZ2U=") {
+ t.Fatalf("image reached fallback request: %s", upstreamBodies[1])
+ }
+ if !strings.Contains(string(upstreamBodies[1]), unsupportedImageNotice) || !strings.Contains(string(upstreamBodies[1]), test.preserve) {
+ t.Fatalf("sanitized fallback body = %s", upstreamBodies[1])
+ }
+ })
+ }
+}
+
+func TestGatewayDoesNotSanitizeImagesOnSuccessfulRequest(t *testing.T) {
+ var upstreamBodies [][]byte
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ upstreamBodies = append(upstreamBodies, body)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, `{"ok":true}`)
+ }))
+ defer upstream.Close()
+ p := startTestGateway(t, upstream.URL)
+
+ body := `{"model":"claude-fable-5","messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aW1hZ2U="}},{"type":"text","text":"what dis"}]}]}`
+ resp, err := http.Post("http://"+p.Addr()+"/v1/messages", "application/json", strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d, want 200", resp.StatusCode)
+ }
+ if len(upstreamBodies) != 1 {
+ t.Fatalf("upstream calls = %d, want 1", len(upstreamBodies))
+ }
+ if !strings.Contains(string(upstreamBodies[0]), `"type":"image"`) || !strings.Contains(string(upstreamBodies[0]), "aW1hZ2U=") {
+ t.Fatalf("successful request was unexpectedly sanitized: %s", upstreamBodies[0])
+ }
+}
+
+func TestGatewayDoesNotRetryImageFreeBadRequest(t *testing.T) {
+ upstreamCalls := 0
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ upstreamCalls++
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = io.WriteString(w, `{"type":"error","error":{"type":"invalid_request_error","message":"bad tool schema"}}`)
+ }))
+ defer upstream.Close()
+ p := startTestGateway(t, upstream.URL)
+
+ body := `{"model":"claude-fable-5","messages":[{"role":"user","content":[{"type":"text","text":"hello"}]}]}`
+ resp, err := http.Post("http://"+p.Addr()+"/v1/messages", "application/json", strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400", resp.StatusCode)
+ }
+ if upstreamCalls != 1 {
+ t.Fatalf("upstream calls = %d, want 1", upstreamCalls)
+ }
+}
+
+func TestGatewayDoesNotRetryUnrelatedBadRequestWithImage(t *testing.T) {
+ upstreamCalls := 0
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ upstreamCalls++
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = io.WriteString(w, `{"type":"error","error":{"type":"invalid_request_error","message":"bad tool schema"}}`)
+ }))
+ defer upstream.Close()
+ p := startTestGateway(t, upstream.URL)
+
+ body := `{"model":"claude-fable-5","messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aW1hZ2U="}}]}]}`
+ resp, err := http.Post("http://"+p.Addr()+"/v1/messages", "application/json", strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ responseBody, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.StatusCode != http.StatusBadRequest || upstreamCalls != 1 {
+ t.Fatalf("status/calls = %d/%d, want 400/1", resp.StatusCode, upstreamCalls)
+ }
+ if !strings.Contains(string(responseBody), "bad tool schema") {
+ t.Fatalf("original upstream error was not preserved: %s", responseBody)
+ }
+}
+
+func TestGatewayDoesNotRetryUnstructuredImageError(t *testing.T) {
+ upstreamCalls := 0
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ upstreamCalls++
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = io.WriteString(w, "model does not support images")
+ }))
+ defer upstream.Close()
+ p := startTestGateway(t, upstream.URL)
+
+ body := `{"model":"claude-fable-5","messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aW1hZ2U="}}]}]}`
+ resp, err := http.Post("http://"+p.Addr()+"/v1/messages", "application/json", strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ responseBody, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.StatusCode != http.StatusBadRequest || upstreamCalls != 1 {
+ t.Fatalf("status/calls = %d/%d, want 400/1", resp.StatusCode, upstreamCalls)
+ }
+ if string(responseBody) != "model does not support images" {
+ t.Fatalf("response body = %q", responseBody)
+ }
+}
+
+func TestGatewayLogsUnknownModelFallback(t *testing.T) {
+ var logs bytes.Buffer
+ p := &ClaudeDesktop{
+ logger: slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})),
+ }
+
+ model := p.modelForClaudeID("claude-future", "kimi-k3:cloud")
+ if model.OllamaModel != "kimi-k3:cloud" {
+ t.Fatalf("fallback model = %q", model.OllamaModel)
+ }
+ if output := logs.String(); !strings.Contains(output, "requested_model=claude-future") || !strings.Contains(output, "default_model=kimi-k3:cloud") {
+ t.Fatalf("fallback log = %q", output)
+ }
+}
+
+func TestGatewayAllowsVisionForSupportedModel(t *testing.T) {
+ upstreamCalls := 0
+ upstreamModel := ""
+ var upstreamBody []byte
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ upstreamCalls++
+ var err error
+ upstreamBody, err = io.ReadAll(r.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var request struct {
+ Model string `json:"model"`
+ }
+ if err := json.Unmarshal(upstreamBody, &request); err != nil {
+ t.Fatal(err)
+ }
+ upstreamModel = request.Model
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, `{"ok":true}`)
+ }))
+ defer upstream.Close()
+ p := startTestGateway(t, upstream.URL)
+
+ body := `{"model":"claude-opus-5","messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aW1hZ2U="}}]}]}`
+ resp, err := http.Post("http://"+p.Addr()+"/v1/messages", "application/json", strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d, want 200", resp.StatusCode)
+ }
+ if upstreamCalls != 1 || upstreamModel != "kimi-k3:cloud" {
+ t.Fatalf("upstream calls/model = %d/%q", upstreamCalls, upstreamModel)
+ }
+ if !strings.Contains(string(upstreamBody), `"type":"image"`) || !strings.Contains(string(upstreamBody), "aW1hZ2U=") {
+ t.Fatalf("vision request was unexpectedly sanitized: %s", upstreamBody)
+ }
+}
+
+func TestGatewayDoesNotRetryVisionModelBadRequest(t *testing.T) {
+ upstreamCalls := 0
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ upstreamCalls++
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = io.WriteString(w, `{"type":"error","error":{"type":"invalid_request_error","message":"bad request"}}`)
+ }))
+ defer upstream.Close()
+ p := startTestGateway(t, upstream.URL)
+
+ body := `{"model":"claude-opus-5","messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aW1hZ2U="}}]}]}`
+ resp, err := http.Post("http://"+p.Addr()+"/v1/messages", "application/json", strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400", resp.StatusCode)
+ }
+ if upstreamCalls != 1 {
+ t.Fatalf("upstream calls = %d, want 1", upstreamCalls)
+ }
+}
+
+func TestGatewayCountsUnsupportedVisionWithoutUpstream(t *testing.T) {
+ upstreamCalls := 0
+ upstream := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ upstreamCalls++
+ }))
+ defer upstream.Close()
+ p := startTestGateway(t, upstream.URL)
+
+ body := `{"model":"claude-haiku-4-5-20251001","messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aW1hZ2U="}}]}]}`
+ resp, err := http.Post("http://"+p.Addr()+"/v1/messages/count_tokens", "application/json", strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d, want 200", resp.StatusCode)
+ }
+ var response anthropic.CountTokensResponse
+ if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
+ t.Fatal(err)
+ }
+ if response.InputTokens <= 0 {
+ t.Fatalf("input_tokens = %d, want positive estimate", response.InputTokens)
+ }
+ if upstreamCalls != 0 {
+ t.Fatalf("upstream calls = %d, want 0", upstreamCalls)
+ }
+}
+
+func TestGatewayWaitsForColdUpstream(t *testing.T) {
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ address := listener.Addr().String()
+ if err := listener.Close(); err != nil {
+ t.Fatal(err)
+ }
+
+ p := startTestGateway(t, "http://"+address)
+ response := make(chan int, 1)
+ errs := make(chan error, 1)
+ go func() {
+ resp, err := http.Post(
+ "http://"+p.Addr()+"/v1/messages",
+ "application/json",
+ strings.NewReader(`{"model":"claude-sonnet-5","messages":[]}`),
+ )
+ if err != nil {
+ errs <- err
+ return
+ }
+ defer resp.Body.Close()
+ response <- resp.StatusCode
+ }()
+
+ time.Sleep(250 * time.Millisecond)
+ upstreamListener, err := net.Listen("tcp", address)
+ if err != nil {
+ t.Fatal(err)
+ }
+ upstream := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, `{"ok":true}`)
+ })}
+ go func() { _ = upstream.Serve(upstreamListener) }()
+ t.Cleanup(func() { _ = upstream.Close() })
+
+ select {
+ case err := <-errs:
+ t.Fatal(err)
+ case status := <-response:
+ if status != http.StatusOK {
+ t.Fatalf("status = %d, want 200", status)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("gateway did not resume after upstream became ready")
+ }
+}
+
+func TestProbeIdentifiesOllamaGateway(t *testing.T) {
+ upstream := httptest.NewServer(http.NotFoundHandler())
+ defer upstream.Close()
+ p := startTestGateway(t, upstream.URL)
+
+ if err := ProbeClaudeDesktop(context.Background(), "http://"+p.Addr()); err != nil {
+ t.Fatalf("ProbeClaudeDesktop returned error: %v", err)
+ }
+
+ other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ defer other.Close()
+ if err := ProbeClaudeDesktop(context.Background(), other.URL); err == nil || !strings.Contains(err.Error(), "another service is using") {
+ t.Fatalf("ProbeClaudeDesktop error = %v, want port ownership error", err)
+ }
+}
+
+func TestGatewayCachesSuccessfulUpstreamReadiness(t *testing.T) {
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ p, err := NewClaudeDesktop(ClaudeDesktopConfig{
+ ListenAddr: "127.0.0.1:0",
+ OllamaURL: "http://" + listener.Addr().String(),
+ Model: "glm-5.2:cloud",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := p.waitForUpstream(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if err := listener.Close(); err != nil {
+ t.Fatal(err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ defer cancel()
+ if err := p.waitForUpstream(ctx); err != nil {
+ t.Fatalf("cached readiness returned error: %v", err)
+ }
+
+ p.markUpstreamNotReady()
+ ctx, cancel = context.WithTimeout(context.Background(), 50*time.Millisecond)
+ defer cancel()
+ if err := p.waitForUpstream(ctx); err == nil {
+ t.Fatal("expected invalidated readiness to probe the closed upstream")
+ }
+}
+
+func TestGatewaySharesFailedUpstreamReadinessCheck(t *testing.T) {
+ p, err := NewClaudeDesktop(ClaudeDesktopConfig{
+ ListenAddr: "127.0.0.1:0",
+ OllamaURL: "http://127.0.0.1:1",
+ Model: "glm-5.2:cloud",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ p.readyWait = 100 * time.Millisecond
+ p.readyPoll = 5 * time.Millisecond
+ dialCalls := 0
+ p.dial = func(context.Context, string, string) (net.Conn, error) {
+ dialCalls++
+ return nil, errors.New("upstream unavailable")
+ }
+
+ const requests = 8
+ start := make(chan struct{})
+ results := make(chan error, requests)
+ for range requests {
+ go func() {
+ <-start
+ results <- p.waitForUpstream(context.Background())
+ }()
+ }
+ close(start)
+ for range requests {
+ if err := <-results; err == nil {
+ t.Fatal("expected readiness check to fail")
+ }
+ }
+ if dialCalls >= requests*10 {
+ t.Fatalf("dial calls = %d, readiness checks were serialized", dialCalls)
+ }
+}
+
+func TestGatewayCloseCancelsUpstreamReadinessCheck(t *testing.T) {
+ p, err := NewClaudeDesktop(ClaudeDesktopConfig{
+ ListenAddr: "127.0.0.1:0",
+ OllamaURL: "http://127.0.0.1:1",
+ Model: "glm-5.2:cloud",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ started := make(chan struct{}, 1)
+ p.dial = func(context.Context, string, string) (net.Conn, error) {
+ select {
+ case started <- struct{}{}:
+ default:
+ }
+ return nil, errors.New("upstream unavailable")
+ }
+ result := make(chan error, 1)
+ go func() { result <- p.waitForUpstream(context.Background()) }()
+ <-started
+ if err := p.Close(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case err := <-result:
+ if err == nil {
+ t.Fatal("expected canceled readiness check to fail")
+ }
+ case <-time.After(time.Second):
+ t.Fatal("readiness check remained blocked after gateway close")
+ }
+}
+
+func startTestGateway(t *testing.T, upstreamURL string) *ClaudeDesktop {
+ t.Helper()
+ p, err := NewClaudeDesktop(ClaudeDesktopConfig{ListenAddr: "127.0.0.1:0", OllamaURL: upstreamURL, Model: "glm-5.2:cloud"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := p.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ if err := p.Close(ctx); err != nil {
+ t.Fatal(err)
+ }
+ })
+ return p
+}
+
+func requestModel(t *testing.T, r *http.Request) string {
+ t.Helper()
+ var payload struct {
+ Model string `json:"model"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatal(err)
+ }
+ return payload.Model
+}