Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a6b975607 |
No files matched your search
@@ -39,27 +39,11 @@ jobs:
|
||||
APPLE_ID: ${{ vars.APPLE_ID }}
|
||||
MACOS_SIGNING_KEY: ${{ secrets.MACOS_SIGNING_KEY }}
|
||||
MACOS_SIGNING_KEY_PASSWORD: ${{ secrets.MACOS_SIGNING_KEY_PASSWORD }}
|
||||
DEVELOPER_DIR: /Applications/Xcode_26.4.1.app/Contents/Developer
|
||||
CGO_CFLAGS: '-mmacosx-version-min=14.0 -O3'
|
||||
CGO_CXXFLAGS: '-mmacosx-version-min=14.0 -O3'
|
||||
CGO_LDFLAGS: '-mmacosx-version-min=14.0 -O3'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Select Xcode 26.4.1
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ ! -d "${DEVELOPER_DIR}" ]; then
|
||||
echo "Missing ${DEVELOPER_DIR}"
|
||||
ls -1 /Applications | grep '^Xcode' || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sudo xcode-select -s "${DEVELOPER_DIR}"
|
||||
sw_vers
|
||||
xcodebuild -version
|
||||
xcrun --sdk macosx --show-sdk-version
|
||||
xcrun --find metal
|
||||
- run: |
|
||||
echo $MACOS_SIGNING_KEY | base64 --decode > certificate.p12
|
||||
security create-keychain -p password build.keychain
|
||||
@@ -93,7 +77,6 @@ jobs:
|
||||
windows-depends:
|
||||
needs: setup-environment
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows]
|
||||
arch: [amd64]
|
||||
@@ -125,22 +108,6 @@ jobs:
|
||||
- '"nvvm"'
|
||||
- '"nvptxcompiler"'
|
||||
cuda-version: '13.0'
|
||||
- os: windows
|
||||
arch: amd64
|
||||
preset: 'CUDA 13 ARM64'
|
||||
build-steps: cuda13Arm64Cross
|
||||
install: https://packages.nvidia.com/prerelease/cuda/13.4.0/local_installers/cuda_13.4.0_windows_x86_64.exe
|
||||
cuda-components:
|
||||
- '"cudart"'
|
||||
- '"cudart_cross"'
|
||||
- '"nvcc"'
|
||||
- '"nvcc_cross"'
|
||||
- '"cublas_cross"'
|
||||
- '"cublas_dev"'
|
||||
- '"crt"'
|
||||
- '"nvvm"'
|
||||
- '"nvptxcompiler"'
|
||||
cuda-version: '13.4'
|
||||
- os: windows
|
||||
arch: amd64
|
||||
preset: 'ROCm 7'
|
||||
@@ -215,18 +182,8 @@ jobs:
|
||||
name: Install CUDA ${{ matrix.cuda-version }}
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
if ("${{ steps.cache-install.outputs.cache-hit }}" -ne 'true') {
|
||||
for ($attempt = 1; $attempt -le 3; $attempt++) {
|
||||
try {
|
||||
Invoke-WebRequest -Uri "${{ matrix.install }}" -OutFile "install.exe"
|
||||
break
|
||||
} catch {
|
||||
if ($attempt -eq 3) { throw }
|
||||
Write-Host "CUDA installer download attempt $attempt failed: $($_.Exception.Message); retrying in 15s"
|
||||
Start-Sleep -Seconds 15
|
||||
}
|
||||
}
|
||||
Invoke-WebRequest -Uri "${{ matrix.install }}" -OutFile "install.exe"
|
||||
$subpackages = @(${{ join(matrix.cuda-components, ', ') }}) | Foreach-Object {"${_}_${{ matrix.cuda-version }}"}
|
||||
Start-Process -FilePath .\install.exe -ArgumentList (@("-s") + $subpackages) -NoNewWindow -Wait
|
||||
}
|
||||
@@ -461,7 +418,6 @@ jobs:
|
||||
|
||||
linux-depends:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: amd64
|
||||
@@ -543,7 +499,6 @@ jobs:
|
||||
# and just assembles, runs the Go build, pushes the final image, and extracts release bundles.
|
||||
docker-build-push:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: linux
|
||||
@@ -694,7 +649,6 @@ jobs:
|
||||
# Merge Docker images for the same flavor into a single multi-arch manifest
|
||||
docker-merge-push:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
suffix: ['', '-rocm']
|
||||
runs-on: linux
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
name: test-darwin-xcode-pin
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- test/darwin-xcode-pin
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/test-darwin-xcode-pin.yaml'
|
||||
- 'scripts/build_darwin.sh'
|
||||
- 'MLX_VERSION'
|
||||
- 'MLX_C_VERSION'
|
||||
- 'cmake/**'
|
||||
- 'x/mlxrunner/**'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
CGO_CFLAGS: '-O3'
|
||||
CGO_CXXFLAGS: '-O3'
|
||||
PINNED_DEVELOPER_DIR: /Applications/Xcode_26.4.1.app/Contents/Developer
|
||||
|
||||
jobs:
|
||||
darwin-build:
|
||||
runs-on: macos-26-xlarge
|
||||
env:
|
||||
CGO_CFLAGS: '-mmacosx-version-min=14.0 -O3'
|
||||
CGO_CXXFLAGS: '-mmacosx-version-min=14.0 -O3'
|
||||
CGO_LDFLAGS: '-mmacosx-version-min=14.0 -O3'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set build environment
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
VERSION="0.0.0-xcode-pin-${GITHUB_SHA::7}"
|
||||
{
|
||||
echo "VERSION=${VERSION}"
|
||||
echo "GOFLAGS='-ldflags=-w -s \"-X=github.com/ollama/ollama/version.Version=${VERSION}\" \"-X=github.com/ollama/ollama/server.mode=release\"'"
|
||||
} >>"${GITHUB_ENV}"
|
||||
|
||||
- name: Select Xcode 26.4.1
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ ! -d "${PINNED_DEVELOPER_DIR}" ]; then
|
||||
echo "Missing ${PINNED_DEVELOPER_DIR}"
|
||||
ls -1 /Applications | grep '^Xcode' || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sudo xcode-select -s "${PINNED_DEVELOPER_DIR}"
|
||||
echo "DEVELOPER_DIR=${PINNED_DEVELOPER_DIR}" >>"${GITHUB_ENV}"
|
||||
|
||||
sw_vers
|
||||
xcodebuild -version
|
||||
xcrun --sdk macosx --show-sdk-version
|
||||
xcrun --find metal
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache-dependency-path: |
|
||||
go.sum
|
||||
LLAMA_CPP_VERSION
|
||||
MLX_VERSION
|
||||
MLX_C_VERSION
|
||||
|
||||
- name: Build unsigned Darwin runtime
|
||||
run: ./scripts/build_darwin.sh build package
|
||||
|
||||
- name: Verify MLX payload
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -f dist/darwin/lib/ollama/mlx_metal_v3/libmlxc.dylib
|
||||
test -f dist/darwin/lib/ollama/mlx_metal_v3/mlx.metallib
|
||||
test -f dist/darwin/lib/ollama/mlx_metal_v4/libmlxc.dylib
|
||||
test -f dist/darwin/lib/ollama/mlx_metal_v4/mlx.metallib
|
||||
find dist/darwin/lib/ollama -maxdepth 3 -type f \( -name 'libmlx*.dylib' -o -name '*.metallib' \) -print
|
||||
lipo -archs dist/darwin/lib/ollama/mlx_metal_v3/libmlxc.dylib
|
||||
lipo -archs dist/darwin/lib/ollama/mlx_metal_v4/libmlxc.dylib
|
||||
|
||||
- name: Log build results
|
||||
run: ls -l dist/
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ollama-darwin-xcode-pin
|
||||
path: dist/ollama-darwin.tgz
|
||||
compression-level: 0
|
||||
@@ -321,22 +321,6 @@ jobs:
|
||||
- '"nvvm"'
|
||||
- '"nvptxcompiler"'
|
||||
cuda-version: '13.0'
|
||||
- os: windows
|
||||
arch: amd64
|
||||
preset: 'CUDA 13 ARM64'
|
||||
build-steps: cuda13Arm64Cross
|
||||
install: https://packages.nvidia.com/prerelease/cuda/13.4.0/local_installers/cuda_13.4.0_windows_x86_64.exe
|
||||
cuda-components:
|
||||
- '"cudart"'
|
||||
- '"cudart_cross"'
|
||||
- '"nvcc"'
|
||||
- '"nvcc_cross"'
|
||||
- '"cublas_cross"'
|
||||
- '"cublas_dev"'
|
||||
- '"crt"'
|
||||
- '"nvvm"'
|
||||
- '"nvptxcompiler"'
|
||||
cuda-version: '13.4'
|
||||
- os: windows
|
||||
arch: amd64
|
||||
preset: 'ROCm 7'
|
||||
@@ -381,18 +365,8 @@ jobs:
|
||||
name: Install CUDA ${{ matrix.cuda-version }}
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
if ("${{ steps.cache-install.outputs.cache-hit }}" -ne 'true') {
|
||||
for ($attempt = 1; $attempt -le 3; $attempt++) {
|
||||
try {
|
||||
Invoke-WebRequest -Uri "${{ matrix.install }}" -OutFile "install.exe"
|
||||
break
|
||||
} catch {
|
||||
if ($attempt -eq 3) { throw }
|
||||
Write-Host "CUDA installer download attempt $attempt failed: $($_.Exception.Message); retrying in 15s"
|
||||
Start-Sleep -Seconds 15
|
||||
}
|
||||
}
|
||||
Invoke-WebRequest -Uri "${{ matrix.install }}" -OutFile "install.exe"
|
||||
$subpackages = @(${{ join(matrix.cuda-components, ', ') }}) | Foreach-Object {"${_}_${{ matrix.cuda-version }}"}
|
||||
Start-Process -FilePath .\install.exe -ArgumentList (@("-s") + $subpackages) -NoNewWindow -Wait
|
||||
}
|
||||
|
||||
@@ -416,3 +416,5 @@ jobs:
|
||||
run: go test -count=1 -tags updater_live ./app/...
|
||||
|
||||
- uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
only-new-issues: true
|
||||
@@ -45,10 +45,6 @@ if(APPLE)
|
||||
set(CMAKE_BUILD_RPATH "@loader_path")
|
||||
set(CMAKE_INSTALL_RPATH "@loader_path")
|
||||
set(CMAKE_BUILD_WITH_INSTALL_RPATH ON)
|
||||
elseif(UNIX)
|
||||
set(CMAKE_BUILD_RPATH "$ORIGIN")
|
||||
set(CMAKE_INSTALL_RPATH "$ORIGIN")
|
||||
set(CMAKE_BUILD_WITH_INSTALL_RPATH ON)
|
||||
endif()
|
||||
|
||||
set(OLLAMA_BUILD_DIR ${CMAKE_BINARY_DIR}/lib/ollama)
|
||||
|
||||
@@ -15,9 +15,9 @@ FROM scratch AS local-mlx
|
||||
FROM scratch AS local-mlx-c
|
||||
|
||||
FROM --platform=linux/amd64 rocm/dev-almalinux-8:${ROCMVERSION}-complete AS base-amd64
|
||||
RUN dnf install -y yum-utils ccache gcc-toolset-13-gcc gcc-toolset-13-gcc-c++ gcc-toolset-13-binutils \
|
||||
RUN dnf install -y yum-utils ccache gcc-toolset-11-gcc gcc-toolset-11-gcc-c++ gcc-toolset-11-binutils \
|
||||
&& yum-config-manager --add-repo https://developer.download.nvidia.com/compute/cuda/repos/rhel8/x86_64/cuda-rhel8.repo
|
||||
ENV PATH=/opt/rh/gcc-toolset-13/root/usr/bin:$PATH
|
||||
ENV PATH=/opt/rh/gcc-toolset-11/root/usr/bin:$PATH
|
||||
|
||||
FROM --platform=linux/arm64 almalinux:8 AS base-arm64
|
||||
# install epel-release for ccache
|
||||
@@ -42,8 +42,8 @@ ENV LDFLAGS=-s
|
||||
#
|
||||
|
||||
FROM base AS cpu-deps
|
||||
RUN dnf install -y gcc-toolset-13-gcc gcc-toolset-13-gcc-c++
|
||||
ENV PATH=/opt/rh/gcc-toolset-13/root/usr/bin:$PATH
|
||||
RUN dnf install -y gcc-toolset-11-gcc gcc-toolset-11-gcc-c++
|
||||
ENV PATH=/opt/rh/gcc-toolset-11/root/usr/bin:$PATH
|
||||
|
||||
FROM base AS cuda-12-deps
|
||||
ARG CUDA12VERSION=12.8
|
||||
@@ -91,8 +91,8 @@ RUN --mount=type=cache,target=/root/.ccache \
|
||||
&& for lib in \
|
||||
/usr/lib64/libgomp.so* \
|
||||
/usr/lib64/libomp.so* \
|
||||
/opt/rh/gcc-toolset-13/root/usr/lib64/libgomp.so* \
|
||||
/opt/rh/gcc-toolset-13/root/usr/lib64/libomp.so*; do \
|
||||
/opt/rh/gcc-toolset-11/root/usr/lib64/libgomp.so* \
|
||||
/opt/rh/gcc-toolset-11/root/usr/lib64/libomp.so*; do \
|
||||
[ -e "$lib" ] && cp -a "$lib" dist/lib/ollama/ || true; \
|
||||
done
|
||||
|
||||
@@ -124,7 +124,7 @@ FROM scratch AS publish-llama-server-cuda_v13
|
||||
COPY --from=llama-server-cuda_v13 dist/lib/ollama /lib/ollama/
|
||||
|
||||
FROM rocm-7-deps AS llama-server-rocm_v7_2
|
||||
ENV CC=clang CXX=clang++ CXXFLAGS=--gcc-toolchain=/opt/rh/gcc-toolset-13/root/usr
|
||||
ENV CC=clang CXX=clang++
|
||||
COPY LLAMA_CPP_VERSION .
|
||||
COPY llama/server llama/server
|
||||
COPY llama/compat llama/compat
|
||||
@@ -213,8 +213,7 @@ ENV CGO_LDFLAGS="-L/usr/local/cuda-13/lib64 -L/usr/local/cuda-13/targets/x86_64-
|
||||
WORKDIR /go/src/github.com/ollama/ollama
|
||||
COPY CMakeLists.txt CMakePresets.json .
|
||||
COPY cmake cmake
|
||||
COPY mlx mlx
|
||||
COPY x/mlxrunner/mlx x/mlxrunner/mlx
|
||||
COPY x/imagegen/mlx x/imagegen/mlx
|
||||
COPY go.mod go.sum .
|
||||
COPY MLX_VERSION MLX_C_VERSION .
|
||||
RUN curl -fsSL https://golang.org/dl/go$(awk '/^go/ { print $2 }' go.mod).linux-$(case $(uname -m) in x86_64) echo amd64 ;; aarch64) echo arm64 ;; esac).tar.gz | tar xz -C /usr/local
|
||||
|
||||
@@ -1 +1 @@
|
||||
b10488
|
||||
b9672
|
||||
@@ -1 +1 @@
|
||||
27fec909a3df9e572f5195607a453e273e7d80d0
|
||||
2165dc08d7b33258260aa849d39f087d50e62962
|
||||
@@ -65,7 +65,7 @@ To launch a specific integration:
|
||||
ollama launch claude
|
||||
```
|
||||
|
||||
Supported integrations include [Claude Code](https://docs.ollama.com/integrations/claude-code), [Codex](https://docs.ollama.com/integrations/codex), [Copilot CLI](https://docs.ollama.com/integrations/copilot-cli), [DeepSeek Harness](https://docs.ollama.com/integrations/deepseek-harness), [Droid](https://docs.ollama.com/integrations/droid), and [OpenCode](https://docs.ollama.com/integrations/opencode).
|
||||
Supported integrations include [Claude Code](https://docs.ollama.com/integrations/claude-code), [Codex](https://docs.ollama.com/integrations/codex), [Copilot CLI](https://docs.ollama.com/integrations/copilot-cli), [Droid](https://docs.ollama.com/integrations/droid), and [OpenCode](https://docs.ollama.com/integrations/opencode).
|
||||
|
||||
### AI assistant
|
||||
|
||||
|
||||
@@ -777,18 +777,6 @@ func (c *StreamConverter) Process(r api.ChatResponse) []StreamEvent {
|
||||
}
|
||||
|
||||
if r.Message.Thinking != "" && !c.thinkingDone {
|
||||
if c.textStarted {
|
||||
events = append(events, StreamEvent{
|
||||
Event: "content_block_stop",
|
||||
Data: ContentBlockStopEvent{
|
||||
Type: "content_block_stop",
|
||||
Index: c.contentIndex,
|
||||
},
|
||||
})
|
||||
c.contentIndex++
|
||||
c.textStarted = false
|
||||
}
|
||||
|
||||
if !c.thinkingStarted {
|
||||
c.thinkingStarted = true
|
||||
events = append(events, StreamEvent{
|
||||
@@ -1075,7 +1063,7 @@ type CountTokensRequest struct {
|
||||
|
||||
// EstimateInputTokens estimates input tokens from a MessagesRequest (reuses CountTokensRequest logic)
|
||||
func EstimateInputTokens(req MessagesRequest) int {
|
||||
return EstimateCountTokens(CountTokensRequest{
|
||||
return estimateTokens(CountTokensRequest{
|
||||
Model: req.Model,
|
||||
Messages: req.Messages,
|
||||
System: req.System,
|
||||
@@ -1089,10 +1077,10 @@ type CountTokensResponse struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
}
|
||||
|
||||
// EstimateCountTokens returns a rough estimate of tokens (len/4).
|
||||
// estimateTokens 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 EstimateCountTokens(req CountTokensRequest) int {
|
||||
func estimateTokens(req CountTokensRequest) int {
|
||||
var totalLen int
|
||||
|
||||
// Count system prompt
|
||||
|
||||
@@ -3,7 +3,6 @@ package anthropic
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -1141,56 +1140,6 @@ func TestStreamConverter_ThinkingDirectlyFollowedByToolCall(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamConverter_TextBeforeThinking(t *testing.T) {
|
||||
conv := NewStreamConverter("msg_123", "test-model", 0)
|
||||
|
||||
responses := []api.ChatResponse{
|
||||
{Message: api.Message{Role: "assistant", Content: "---\n"}},
|
||||
{Message: api.Message{Role: "assistant", Thinking: "Let me think."}},
|
||||
{
|
||||
Message: api.Message{Role: "assistant", Content: "The answer."},
|
||||
Done: true,
|
||||
DoneReason: "stop",
|
||||
Metrics: api.Metrics{PromptEvalCount: 10, EvalCount: 5},
|
||||
},
|
||||
}
|
||||
|
||||
var got []string
|
||||
for _, response := range responses {
|
||||
for _, event := range conv.Process(response) {
|
||||
switch data := event.Data.(type) {
|
||||
case ContentBlockStartEvent:
|
||||
got = append(got, fmt.Sprintf("%s:%s:%d", event.Event, data.ContentBlock.Type, data.Index))
|
||||
case ContentBlockDeltaEvent:
|
||||
got = append(got, fmt.Sprintf("%s:%s:%d", event.Event, data.Delta.Type, data.Index))
|
||||
case ContentBlockStopEvent:
|
||||
got = append(got, fmt.Sprintf("%s:%d", event.Event, data.Index))
|
||||
default:
|
||||
got = append(got, event.Event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
want := []string{
|
||||
"message_start",
|
||||
"content_block_start:text:0",
|
||||
"content_block_delta:text_delta:0",
|
||||
"content_block_stop:0",
|
||||
"content_block_start:thinking:1",
|
||||
"content_block_delta:thinking_delta:1",
|
||||
"content_block_stop:1",
|
||||
"content_block_start:text:2",
|
||||
"content_block_delta:text_delta:2",
|
||||
"content_block_stop:2",
|
||||
"message_delta",
|
||||
"message_stop",
|
||||
}
|
||||
|
||||
if diff := cmp.Diff(want, got); diff != "" {
|
||||
t.Fatalf("unexpected stream events (-want +got):\n%s", diff)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamConverter_ToolCallWithUnmarshalableArgs(t *testing.T) {
|
||||
// Test that unmarshalable arguments (like channels) are handled gracefully
|
||||
// and don't cause a panic or corrupt stream
|
||||
@@ -1546,7 +1495,7 @@ func TestEstimateTokens_SimpleMessage(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
tokens := EstimateCountTokens(req)
|
||||
tokens := estimateTokens(req)
|
||||
|
||||
// "user" (4) + "Hello, world!" (13) = 17 chars / 4 = 4 tokens
|
||||
if tokens < 1 {
|
||||
@@ -1567,7 +1516,7 @@ func TestEstimateTokens_WithSystemPrompt(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
tokens := EstimateCountTokens(req)
|
||||
tokens := estimateTokens(req)
|
||||
|
||||
// System prompt adds to count
|
||||
if tokens < 5 {
|
||||
@@ -1590,7 +1539,7 @@ func TestEstimateTokens_WithTools(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
tokens := EstimateCountTokens(req)
|
||||
tokens := estimateTokens(req)
|
||||
|
||||
// Tools add significant content
|
||||
if tokens < 10 {
|
||||
@@ -1619,7 +1568,7 @@ func TestEstimateTokens_WithThinking(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
tokens := EstimateCountTokens(req)
|
||||
tokens := estimateTokens(req)
|
||||
|
||||
// Thinking content should be counted
|
||||
if tokens < 10 {
|
||||
@@ -1633,7 +1582,7 @@ func TestEstimateTokens_EmptyContent(t *testing.T) {
|
||||
Messages: []MessageParam{},
|
||||
}
|
||||
|
||||
tokens := EstimateCountTokens(req)
|
||||
tokens := estimateTokens(req)
|
||||
|
||||
if tokens != 0 {
|
||||
t.Errorf("expected 0 tokens for empty content, got %d", tokens)
|
||||
|
||||
@@ -473,26 +473,6 @@ func (c *Client) CloudStatusExperimental(ctx context.Context) (*StatusResponse,
|
||||
return &status, nil
|
||||
}
|
||||
|
||||
// WebSearchExperimental searches the web through the local server's
|
||||
// experimental web search endpoint.
|
||||
func (c *Client) WebSearchExperimental(ctx context.Context, req *WebSearchRequest) (*WebSearchResponse, error) {
|
||||
var resp WebSearchResponse
|
||||
if err := c.do(ctx, http.MethodPost, "/api/experimental/web_search", req, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// WebFetchExperimental fetches web page content through the local server's
|
||||
// experimental web fetch endpoint.
|
||||
func (c *Client) WebFetchExperimental(ctx context.Context, req *WebFetchRequest) (*WebFetchResponse, error) {
|
||||
var resp WebFetchResponse
|
||||
if err := c.do(ctx, http.MethodPost, "/api/experimental/web_fetch", req, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// Signout will signout a client for a local ollama server.
|
||||
func (c *Client) Signout(ctx context.Context) error {
|
||||
return c.do(ctx, http.MethodPost, "/api/signout", nil, nil)
|
||||
|
||||
@@ -2,7 +2,6 @@ package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -352,140 +351,6 @@ func TestClientDo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWebSearchExperimentalUsesLocalRoute(t *testing.T) {
|
||||
var gotPath string
|
||||
var gotMethod string
|
||||
var gotRequest WebSearchRequest
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath = r.URL.Path
|
||||
gotMethod = r.Method
|
||||
if err := json.NewDecoder(r.Body).Decode(&gotRequest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := json.NewEncoder(w).Encode(WebSearchResponse{
|
||||
Results: []WebSearchResult{{Title: "Ollama", URL: "https://ollama.com", Content: "models"}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
client := NewClient(&url.URL{Scheme: "http", Host: ts.Listener.Addr().String()}, http.DefaultClient)
|
||||
resp, err := client.WebSearchExperimental(t.Context(), &WebSearchRequest{Query: "ollama", MaxResults: 3})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gotMethod != http.MethodPost {
|
||||
t.Fatalf("method = %q, want POST", gotMethod)
|
||||
}
|
||||
if gotPath != "/api/experimental/web_search" {
|
||||
t.Fatalf("path = %q, want /api/experimental/web_search", gotPath)
|
||||
}
|
||||
if gotRequest.Query != "ollama" || gotRequest.MaxResults != 3 {
|
||||
t.Fatalf("request = %#v", gotRequest)
|
||||
}
|
||||
if len(resp.Results) != 1 || resp.Results[0].Title != "Ollama" {
|
||||
t.Fatalf("response = %#v", resp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWebSearchExperimentalErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
assertError func(*testing.T, error)
|
||||
}{
|
||||
{
|
||||
name: "unauthorized retains sign in URL",
|
||||
status: http.StatusUnauthorized,
|
||||
body: `{"error":"unauthorized","signin_url":"https://ollama.com/signin/example"}`,
|
||||
assertError: func(t *testing.T, err error) {
|
||||
t.Helper()
|
||||
var authErr AuthorizationError
|
||||
if !errors.As(err, &authErr) {
|
||||
t.Fatalf("error = %T, want AuthorizationError", err)
|
||||
}
|
||||
if authErr.StatusCode != http.StatusUnauthorized || authErr.SigninURL != "https://ollama.com/signin/example" {
|
||||
t.Fatalf("authorization error = %#v", authErr)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "rate limit retains status",
|
||||
status: http.StatusTooManyRequests,
|
||||
body: `{"error":"rate limit exceeded"}`,
|
||||
assertError: func(t *testing.T, err error) {
|
||||
t.Helper()
|
||||
var statusErr StatusError
|
||||
if !errors.As(err, &statusErr) {
|
||||
t.Fatalf("error = %T, want StatusError", err)
|
||||
}
|
||||
if statusErr.StatusCode != http.StatusTooManyRequests || statusErr.ErrorMessage != "rate limit exceeded" {
|
||||
t.Fatalf("status error = %#v", statusErr)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(tt.status)
|
||||
_, _ = w.Write([]byte(tt.body))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
client := NewClient(&url.URL{Scheme: "http", Host: ts.Listener.Addr().String()}, http.DefaultClient)
|
||||
_, err := client.WebSearchExperimental(t.Context(), &WebSearchRequest{Query: "ollama"})
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
tt.assertError(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWebFetchExperimentalUsesLocalRoute(t *testing.T) {
|
||||
var gotPath string
|
||||
var gotMethod string
|
||||
var gotRequest WebFetchRequest
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath = r.URL.Path
|
||||
gotMethod = r.Method
|
||||
if err := json.NewDecoder(r.Body).Decode(&gotRequest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := json.NewEncoder(w).Encode(WebFetchResponse{
|
||||
Title: "Ollama",
|
||||
Content: "models",
|
||||
Links: []string{"https://ollama.com/library"},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
client := NewClient(&url.URL{Scheme: "http", Host: ts.Listener.Addr().String()}, http.DefaultClient)
|
||||
resp, err := client.WebFetchExperimental(t.Context(), &WebFetchRequest{URL: "https://ollama.com"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gotMethod != http.MethodPost {
|
||||
t.Fatalf("method = %q, want POST", gotMethod)
|
||||
}
|
||||
if gotPath != "/api/experimental/web_fetch" {
|
||||
t.Fatalf("path = %q, want /api/experimental/web_fetch", gotPath)
|
||||
}
|
||||
if gotRequest.URL != "https://ollama.com" {
|
||||
t.Fatalf("request = %#v", gotRequest)
|
||||
}
|
||||
if resp.Title != "Ollama" || resp.Content != "models" {
|
||||
t.Fatalf("response = %#v", resp)
|
||||
}
|
||||
}
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
|
||||
@@ -127,6 +127,20 @@ type GenerateRequest struct {
|
||||
// each with an associated log probability. Only applies when Logprobs is true.
|
||||
// Valid values are 0-20. Default is 0 (only return the selected token's logprob).
|
||||
TopLogprobs int `json:"top_logprobs,omitempty"`
|
||||
|
||||
// Experimental: Image generation fields (may change or be removed)
|
||||
|
||||
// Width is the width of the generated image in pixels.
|
||||
// Only used for image generation models.
|
||||
Width int32 `json:"width,omitempty"`
|
||||
|
||||
// Height is the height of the generated image in pixels.
|
||||
// Only used for image generation models.
|
||||
Height int32 `json:"height,omitempty"`
|
||||
|
||||
// Steps is the number of diffusion steps for image generation.
|
||||
// Only used for image generation models.
|
||||
Steps int32 `json:"steps,omitempty"`
|
||||
}
|
||||
|
||||
// ChatRequest describes a request sent by [Client.Chat].
|
||||
@@ -692,11 +706,8 @@ type CreateRequest struct {
|
||||
// Messages is a list of messages added to the model before chat and generation requests.
|
||||
Messages []Message `json:"messages,omitempty"`
|
||||
|
||||
// Renderer is the name of the renderer used when constructing a request to the model.
|
||||
Renderer string `json:"renderer,omitempty"`
|
||||
|
||||
// Parser is the name of the parser used to parse the output of the request.
|
||||
Parser string `json:"parser,omitempty"`
|
||||
Parser string `json:"parser,omitempty"`
|
||||
|
||||
// Requires is the minimum version of Ollama required by the model.
|
||||
Requires string `json:"requires,omitempty"`
|
||||
@@ -857,36 +868,6 @@ type StatusResponse struct {
|
||||
Cloud CloudStatus `json:"cloud"`
|
||||
}
|
||||
|
||||
// WebSearchRequest is the request for [Client.WebSearchExperimental].
|
||||
type WebSearchRequest struct {
|
||||
Query string `json:"query"`
|
||||
MaxResults int `json:"max_results,omitempty"`
|
||||
}
|
||||
|
||||
// WebSearchResult is a single result from [Client.WebSearchExperimental].
|
||||
type WebSearchResult struct {
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// WebSearchResponse is the response from [Client.WebSearchExperimental].
|
||||
type WebSearchResponse struct {
|
||||
Results []WebSearchResult `json:"results"`
|
||||
}
|
||||
|
||||
// WebFetchRequest is the request for [Client.WebFetchExperimental].
|
||||
type WebFetchRequest struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// WebFetchResponse is the response from [Client.WebFetchExperimental].
|
||||
type WebFetchResponse struct {
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
Links []string `json:"links,omitempty"`
|
||||
}
|
||||
|
||||
// GenerateResponse is the response passed into [GenerateResponseFunc].
|
||||
type GenerateResponse struct {
|
||||
// Model is the model name that generated the response.
|
||||
@@ -927,6 +908,20 @@ type GenerateResponse struct {
|
||||
// Logprobs contains log probability information for the generated tokens,
|
||||
// if requested via the Logprobs parameter.
|
||||
Logprobs []Logprob `json:"logprobs,omitempty"`
|
||||
|
||||
// Experimental: Image generation fields (may change or be removed)
|
||||
|
||||
// Image contains a base64-encoded generated image.
|
||||
// Only present for image generation models.
|
||||
Image string `json:"image,omitempty"`
|
||||
|
||||
// Completed is the number of completed steps in image generation.
|
||||
// Only present for image generation models during streaming.
|
||||
Completed int64 `json:"completed,omitempty"`
|
||||
|
||||
// Total is the total number of steps for image generation.
|
||||
// Only present for image generation models during streaming.
|
||||
Total int64 `json:"total,omitempty"`
|
||||
}
|
||||
|
||||
// ModelDetails provides details about a model.
|
||||
@@ -1105,7 +1100,7 @@ func DefaultOptions() Options {
|
||||
TopP: 0.9,
|
||||
TypicalP: 1.0,
|
||||
RepeatLastN: 64,
|
||||
RepeatPenalty: 1.0,
|
||||
RepeatPenalty: 1.1,
|
||||
PresencePenalty: 0.0,
|
||||
FrequencyPenalty: 0.0,
|
||||
Seed: -1,
|
||||
|
||||
@@ -146,10 +146,15 @@ func main() {
|
||||
// Do this after logging is set up so we can debug issues
|
||||
if runtime.GOOS == "windows" && urlSchemeRequest != "" {
|
||||
slog.Debug("checking for existing instance", "url", urlSchemeRequest)
|
||||
// This exits after forwarding the request when another instance is
|
||||
// running. First-instance requests are handled later by osRun, after the
|
||||
// Windows UI dependencies are initialized and from the primary thread.
|
||||
checkAndHandleExistingInstance(urlSchemeRequest)
|
||||
if checkAndHandleExistingInstance(urlSchemeRequest) {
|
||||
// The function will exit if it successfully sends to another instance
|
||||
// If we reach here, we're the first/only instance
|
||||
} else {
|
||||
// No existing instance found, handle the URL scheme in this instance
|
||||
go func() {
|
||||
handleURLSchemeInCurrentInstance(urlSchemeRequest)
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// Detect if this is a first start after an upgrade, in
|
||||
@@ -200,12 +205,6 @@ func main() {
|
||||
uiServerPort = port
|
||||
|
||||
st := &store.Store{}
|
||||
if devMode {
|
||||
if dbPath := strings.TrimSpace(os.Getenv("OLLAMA_APP_DB_PATH")); dbPath != "" {
|
||||
st.DBPath = dbPath
|
||||
slog.Debug("using development app database", "path", dbPath)
|
||||
}
|
||||
}
|
||||
appStore = st
|
||||
|
||||
// Enable CORS in development mode
|
||||
@@ -325,11 +324,11 @@ func main() {
|
||||
quit()
|
||||
}()
|
||||
|
||||
if urlSchemeRequest != "" && runtime.GOOS != "windows" {
|
||||
if urlSchemeRequest != "" {
|
||||
go func() {
|
||||
handleURLSchemeInCurrentInstance(urlSchemeRequest)
|
||||
}()
|
||||
} else if urlSchemeRequest == "" {
|
||||
} else {
|
||||
slog.Debug("no URL scheme request to handle")
|
||||
}
|
||||
|
||||
@@ -344,13 +343,7 @@ func main() {
|
||||
}
|
||||
}()
|
||||
|
||||
settings, settingsErr := st.Settings()
|
||||
showOnboarding := shouldShowOnboarding(settings, settingsErr)
|
||||
if settingsErr != nil {
|
||||
slog.Error("failed to load onboarding state", "error", settingsErr)
|
||||
}
|
||||
|
||||
osRun(cancel, hasCompletedFirstRun, startHidden, showOnboarding, urlSchemeRequest)
|
||||
osRun(cancel, hasCompletedFirstRun, startHidden)
|
||||
|
||||
slog.Info("shutting down desktop server")
|
||||
if err := srv.Close(); err != nil {
|
||||
@@ -362,33 +355,6 @@ func main() {
|
||||
<-done
|
||||
}
|
||||
|
||||
func shouldShowOnboarding(settings store.Settings, err error) bool {
|
||||
return err != nil || settings.OnboardingVersion < store.CurrentOnboardingVersion
|
||||
}
|
||||
|
||||
func runInitialWindowsUI(
|
||||
startHidden bool,
|
||||
showOnboarding bool,
|
||||
urlSchemeRequest string,
|
||||
startHiddenFn func(),
|
||||
handleURLFn func(string),
|
||||
showUIFn func(string),
|
||||
) {
|
||||
if urlSchemeRequest != "" {
|
||||
handleURLFn(urlSchemeRequest)
|
||||
return
|
||||
}
|
||||
if startHidden {
|
||||
startHiddenFn()
|
||||
return
|
||||
}
|
||||
if showOnboarding {
|
||||
showUIFn("/")
|
||||
return
|
||||
}
|
||||
showUIFn("/connect")
|
||||
}
|
||||
|
||||
func startHiddenTasks() {
|
||||
// If an upgrade is ready and we're in hidden mode, perform it at startup.
|
||||
// If we're not in hidden mode, we want to start as fast as possible and not
|
||||
@@ -409,7 +375,7 @@ func startHiddenTasks() {
|
||||
return
|
||||
}
|
||||
|
||||
if err := updater.DoUpgradeAtStartup(); err != nil { //nolint:staticcheck,nolintlint // DoUpgradeAtStartup may always return non-nil on Windows
|
||||
if err := updater.DoUpgradeAtStartup(); err != nil {
|
||||
slog.Info("unable to perform upgrade at startup", "error", err)
|
||||
// Make sure the restart to upgrade menu shows so we can attempt an interactive upgrade to get authorization
|
||||
UpdateAvailable("")
|
||||
@@ -466,7 +432,7 @@ func checkUserLoggedIn(uiServerPort int) bool {
|
||||
func handleConnectURLScheme() {
|
||||
if checkUserLoggedIn(uiServerPort) {
|
||||
slog.Info("user is already logged in, opening app instead")
|
||||
openUI("/")
|
||||
showWindow(wv.webview.Window())
|
||||
return
|
||||
}
|
||||
|
||||
@@ -525,23 +491,17 @@ func parseURLScheme(urlSchemeRequest string) (isConnect bool, err error) {
|
||||
|
||||
// handleURLSchemeInCurrentInstance processes URL scheme requests in the current instance
|
||||
func handleURLSchemeInCurrentInstance(urlSchemeRequest string) {
|
||||
err := dispatchURLSchemeRequest(urlSchemeRequest, handleConnectURLScheme, func() {
|
||||
openUI("/")
|
||||
})
|
||||
if err != nil {
|
||||
slog.Error("failed to parse URL scheme request", "url", urlSchemeRequest, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func dispatchURLSchemeRequest(urlSchemeRequest string, connect, open func()) error {
|
||||
isConnect, err := parseURLScheme(urlSchemeRequest)
|
||||
if err != nil {
|
||||
return err
|
||||
slog.Error("failed to parse URL scheme request", "url", urlSchemeRequest, "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
if isConnect {
|
||||
connect()
|
||||
handleConnectURLScheme()
|
||||
} else {
|
||||
open()
|
||||
if wv.webview != nil {
|
||||
showWindow(wv.webview.Window())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -16,9 +16,8 @@ enum AppMove
|
||||
MoveError,
|
||||
};
|
||||
|
||||
void run(bool showOnboarding, bool startHidden);
|
||||
void run(bool firstTimeRun, bool startHidden);
|
||||
void killOtherInstances();
|
||||
bool otherOllamaInstanceRunning(void);
|
||||
enum AppMove askToMoveToApplications();
|
||||
int createSymlinkWithAuthorization();
|
||||
int installSymlink(const char *cliPath);
|
||||
@@ -26,7 +25,6 @@ extern void Restart();
|
||||
// extern void Quit();
|
||||
void StartUI(const char *path);
|
||||
void ShowUI();
|
||||
bool IsOnboardingActive(void);
|
||||
void StopUI();
|
||||
void StartUpdate();
|
||||
void darwinStartHiddenTasks();
|
||||
@@ -40,30 +38,6 @@ void setWindowDelegate(void *window);
|
||||
void showWindow(uintptr_t wndPtr);
|
||||
void hideWindow(uintptr_t wndPtr);
|
||||
void styleWindow(uintptr_t wndPtr);
|
||||
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 HasUsedClaudeDesktopIntegration(void);
|
||||
bool RestoreClaudeGatewayForShutdown(void);
|
||||
bool IsClaudeGatewayConfigured(void);
|
||||
bool IsClaudeDesktopInstalled(void);
|
||||
bool IsClaudeDesktopRunning(void);
|
||||
bool ClaudeGatewayStartFailed(void);
|
||||
bool ClaudeGatewayPortConflict(void);
|
||||
char *ClaudeGatewayErrorMessage(void);
|
||||
int ClaudeGatewayPort(void);
|
||||
void RefreshClaudeProxyMenu(void);
|
||||
void updateClaudeProxyMenu(unsigned long long routed);
|
||||
bool ShowAppsInMenu(void);
|
||||
void SetShowAppsInMenu(bool visible);
|
||||
enum ClaudeInstallResult
|
||||
{
|
||||
ClaudeInstallCancelled,
|
||||
ClaudeInstallerOpened,
|
||||
ClaudeInstallFailed,
|
||||
};
|
||||
enum ClaudeInstallResult installClaudeDesktop(void);
|
||||
char *ClaudeDesktopDownloadRequest(char **authorization);
|
||||
bool InstallClaudeDesktopArchive(const char *archivePath);
|
||||
@@ -1,140 +0,0 @@
|
||||
//go:build windows || darwin
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/ollama/ollama/app/store"
|
||||
)
|
||||
|
||||
func TestShouldShowOnboarding(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
settings store.Settings
|
||||
err error
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "fresh install",
|
||||
settings: store.Settings{OnboardingVersion: 0},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "completed onboarding",
|
||||
settings: store.Settings{OnboardingVersion: store.CurrentOnboardingVersion},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "settings failure",
|
||||
err: errors.New("settings unavailable"),
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := shouldShowOnboarding(tt.settings, tt.err); got != tt.want {
|
||||
t.Fatalf("shouldShowOnboarding() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatchURLSchemeRequest(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
request string
|
||||
wantConnect bool
|
||||
wantOpen bool
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "bare URL opens app", request: "ollama://", wantOpen: true},
|
||||
{name: "connect URL starts connection", request: "ollama://connect", wantConnect: true},
|
||||
{name: "unsupported URL", request: "ollama://unsupported", wantErr: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
connected := false
|
||||
opened := false
|
||||
err := dispatchURLSchemeRequest(
|
||||
tt.request,
|
||||
func() { connected = true },
|
||||
func() { opened = true },
|
||||
)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("dispatchURLSchemeRequest() error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
if connected != tt.wantConnect {
|
||||
t.Errorf("connect called = %v, want %v", connected, tt.wantConnect)
|
||||
}
|
||||
if opened != tt.wantOpen {
|
||||
t.Errorf("open called = %v, want %v", opened, tt.wantOpen)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunInitialWindowsUIWithBareURL(t *testing.T) {
|
||||
hiddenCalls := 0
|
||||
urlCalls := 0
|
||||
onboardingCalls := 0
|
||||
openCalls := 0
|
||||
|
||||
runInitialWindowsUI(
|
||||
false,
|
||||
true,
|
||||
"ollama://",
|
||||
func() { hiddenCalls++ },
|
||||
func(request string) {
|
||||
urlCalls++
|
||||
if err := dispatchURLSchemeRequest(request, func() {}, func() { openCalls++ }); err != nil {
|
||||
t.Fatalf("dispatchURLSchemeRequest() error = %v", err)
|
||||
}
|
||||
},
|
||||
func(path string) {
|
||||
onboardingCalls++
|
||||
},
|
||||
)
|
||||
|
||||
if urlCalls != 1 {
|
||||
t.Fatalf("URL handled %d times, want 1", urlCalls)
|
||||
}
|
||||
if openCalls != 1 {
|
||||
t.Errorf("app opened %d times, want 1", openCalls)
|
||||
}
|
||||
if hiddenCalls != 0 {
|
||||
t.Errorf("hidden startup called %d times, want 0", hiddenCalls)
|
||||
}
|
||||
if onboardingCalls != 0 {
|
||||
t.Errorf("onboarding opened %d times, want 0", onboardingCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunInitialWindowsUIRoutesInteractiveLaunch(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
showOnboarding bool
|
||||
wantPath string
|
||||
}{
|
||||
{name: "fresh install preserves onboarding", showOnboarding: true, wantPath: "/"},
|
||||
{name: "returning launch opens apps", wantPath: "/connect"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var gotPath string
|
||||
runInitialWindowsUI(
|
||||
false,
|
||||
tt.showOnboarding,
|
||||
"",
|
||||
func() { t.Fatal("unexpected hidden startup") },
|
||||
func(string) { t.Fatal("unexpected URL handling") },
|
||||
func(path string) { gotPath = path },
|
||||
)
|
||||
if gotPath != tt.wantPath {
|
||||
t.Fatalf("initial UI path = %q, want %q", gotPath, tt.wantPath)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -95,15 +95,11 @@ func (ac *appCallbacks) UIRun(path string) {
|
||||
}
|
||||
|
||||
func (*appCallbacks) UIShow() {
|
||||
openUI("/")
|
||||
}
|
||||
|
||||
func openUI(path string) {
|
||||
if wv.IsRunning() && wv.webview != nil {
|
||||
if wv.webview != nil {
|
||||
showWindow(wv.webview.Window())
|
||||
return
|
||||
} else {
|
||||
wv.Run("/")
|
||||
}
|
||||
wv.Run(path)
|
||||
}
|
||||
|
||||
func (*appCallbacks) UITerminate() {
|
||||
@@ -114,10 +110,6 @@ func (*appCallbacks) UIRunning() bool {
|
||||
return wv.IsRunning()
|
||||
}
|
||||
|
||||
func (*appCallbacks) UIOnboarding() bool {
|
||||
return wv.OnboardingActive()
|
||||
}
|
||||
|
||||
func (app *appCallbacks) Quit() {
|
||||
app.t.Quit()
|
||||
wv.Terminate()
|
||||
@@ -134,7 +126,7 @@ func (app *appCallbacks) DoUpdate() {
|
||||
|
||||
app.shutdown()
|
||||
|
||||
if err := updater.DoUpgrade(true); err != nil { //nolint:staticcheck,nolintlint // DoUpgrade may always return non-nil on Windows
|
||||
if err := updater.DoUpgrade(true); err != nil {
|
||||
slog.Warn(fmt.Sprintf("upgrade attempt failed: %s", err))
|
||||
}
|
||||
}
|
||||
@@ -146,7 +138,19 @@ func (app *appCallbacks) HandleURLScheme(urlScheme string) {
|
||||
|
||||
// handleURLSchemeRequest processes URL scheme requests from other instances
|
||||
func handleURLSchemeRequest(urlScheme string) {
|
||||
handleURLSchemeInCurrentInstance(urlScheme)
|
||||
isConnect, err := parseURLScheme(urlScheme)
|
||||
if err != nil {
|
||||
slog.Error("failed to parse URL scheme request", "url", urlScheme, "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
if isConnect {
|
||||
handleConnectURLScheme()
|
||||
} else {
|
||||
if wv.webview != nil {
|
||||
showWindow(wv.webview.Window())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func UpdateAvailable(ver string) error {
|
||||
@@ -157,7 +161,7 @@ func UpdateAvailable(ver string) error {
|
||||
return app.t.UpdateAvailable(ver)
|
||||
}
|
||||
|
||||
func osRun(shutdown func(), hasCompletedFirstRun, startHidden, showOnboarding bool, urlSchemeRequest string) {
|
||||
func osRun(shutdown func(), hasCompletedFirstRun, startHidden bool) {
|
||||
var err error
|
||||
app.shutdown = shutdown
|
||||
app.t, err = wintray.NewTray(app)
|
||||
@@ -201,8 +205,10 @@ func osRun(shutdown func(), hasCompletedFirstRun, startHidden, showOnboarding bo
|
||||
}
|
||||
}
|
||||
}
|
||||
runInitialWindowsUI(startHidden, showOnboarding, urlSchemeRequest, startHiddenTasks, handleURLSchemeInCurrentInstance, func(path string) {
|
||||
ptr := wv.Run(path)
|
||||
if startHidden {
|
||||
startHiddenTasks()
|
||||
} else {
|
||||
ptr := wv.Run("/")
|
||||
|
||||
// Set the window icon using the tray icon
|
||||
if ptr != nil {
|
||||
@@ -219,7 +225,7 @@ func osRun(shutdown func(), hasCompletedFirstRun, startHidden, showOnboarding bo
|
||||
}
|
||||
|
||||
centerWindow(ptr)
|
||||
})
|
||||
}
|
||||
|
||||
if !hasCompletedFirstRun {
|
||||
// Only create the login shortcut on first start
|
||||
@@ -402,8 +408,6 @@ func hideWindow(ptr unsafe.Pointer) {
|
||||
}
|
||||
}
|
||||
|
||||
func setOnboardingWindowStyle(_ unsafe.Pointer, _ bool) {}
|
||||
|
||||
func runInBackground() {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
@@ -428,13 +432,17 @@ func drag(ptr unsafe.Pointer) {}
|
||||
func doubleClick(ptr unsafe.Pointer) {}
|
||||
|
||||
// checkAndHandleExistingInstance checks if another instance is running and sends the URL to it
|
||||
func checkAndHandleExistingInstance(urlSchemeRequest string) {
|
||||
func checkAndHandleExistingInstance(urlSchemeRequest string) bool {
|
||||
if urlSchemeRequest == "" {
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
// Try to send URL to existing instance using wintray messaging
|
||||
if wintray.CheckAndSendToExistingInstance(urlSchemeRequest) {
|
||||
os.Exit(0)
|
||||
return true
|
||||
}
|
||||
|
||||
// No existing instance, we'll handle it ourselves
|
||||
return false
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
//go:build darwin
|
||||
|
||||
package main
|
||||
|
||||
import "github.com/ollama/ollama/app/webview"
|
||||
|
||||
func bindClaudeDesktop(wv webview.WebView) {
|
||||
wv.Bind("getClaudeDesktopStatus", func() claudeDesktopStatus {
|
||||
return getClaudeDesktopConnectionStatus()
|
||||
})
|
||||
|
||||
wv.Bind("setClaudeDesktopConnected", func(enabled bool) claudeDesktopActionResult {
|
||||
err := setClaudeDesktopConnection(enabled)
|
||||
result := claudeDesktopActionResult{
|
||||
Status: getClaudeDesktopConnectionStatus(),
|
||||
}
|
||||
if err != nil {
|
||||
result.Error = err.Error()
|
||||
}
|
||||
return result
|
||||
})
|
||||
|
||||
wv.Bind("prepareClaudeDesktopConnection", func() claudeDesktopActionResult {
|
||||
err := prepareClaudeDesktopConnection()
|
||||
result := claudeDesktopActionResult{
|
||||
Status: getClaudeDesktopConnectionStatus(),
|
||||
}
|
||||
if err != nil {
|
||||
result.Error = err.Error()
|
||||
}
|
||||
return result
|
||||
})
|
||||
|
||||
wv.Bind("openClaudeDesktop", func() string {
|
||||
if err := openClaudeDesktopApplication(); err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
return ""
|
||||
})
|
||||
|
||||
wv.Bind("installClaudeDesktop", func() claudeDesktopInstallResult {
|
||||
return requestClaudeDesktopInstall()
|
||||
})
|
||||
|
||||
wv.Bind("restartClaudeDesktop", func(models []string) claudeDesktopActionResult {
|
||||
err := restartClaudeDesktopWithModels(models)
|
||||
result := claudeDesktopActionResult{Status: getClaudeDesktopConnectionStatus()}
|
||||
if err != nil {
|
||||
result.Error = err.Error()
|
||||
}
|
||||
return result
|
||||
})
|
||||
|
||||
wv.Bind("getShowAppsInMenu", func() bool {
|
||||
return getShowAppsInMenu()
|
||||
})
|
||||
|
||||
wv.Bind("setShowAppsInMenu", func(visible bool) {
|
||||
setShowAppsInMenu(visible)
|
||||
})
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import "github.com/ollama/ollama/app/webview"
|
||||
|
||||
func bindClaudeDesktop(_ webview.WebView) {}
|
||||
@@ -1,252 +0,0 @@
|
||||
//go:build darwin
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
maxClaudeDesktopArchiveBytes = 1 << 30
|
||||
maxClaudeDesktopExtractBytes = 2 << 30
|
||||
maxClaudeDesktopArchiveFiles = 100_000
|
||||
claudeDesktopBundleID = "com.anthropic.claudefordesktop"
|
||||
claudeDesktopTeamID = "Q6L2SF6YDW"
|
||||
)
|
||||
|
||||
var errClaudeDesktopDestinationExists = errors.New("Claude Desktop installation destination already exists")
|
||||
|
||||
func claudeDesktopInstallDestinations() []string {
|
||||
destinations := []string{"/Applications/Claude.app"}
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
destinations = append(destinations, filepath.Join(home, "Applications", "Claude.app"))
|
||||
}
|
||||
return destinations
|
||||
}
|
||||
|
||||
func installClaudeDesktopZip(archivePath string, destinations []string, verify func(string) error) (string, error) {
|
||||
if len(destinations) == 0 {
|
||||
return "", errors.New("Claude Desktop installation destination is required")
|
||||
}
|
||||
if verify == nil {
|
||||
return "", errors.New("Claude Desktop bundle verifier is required")
|
||||
}
|
||||
info, err := os.Stat(archivePath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("stat Claude Desktop archive: %w", err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return "", errors.New("Claude Desktop archive is not a regular file")
|
||||
}
|
||||
if info.Size() > maxClaudeDesktopArchiveBytes {
|
||||
return "", fmt.Errorf("Claude Desktop archive exceeds %d bytes", maxClaudeDesktopArchiveBytes)
|
||||
}
|
||||
|
||||
workDir, err := os.MkdirTemp("", "ollama-claude-install-")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create Claude Desktop installation directory: %w", err)
|
||||
}
|
||||
defer os.RemoveAll(workDir)
|
||||
|
||||
if err := extractClaudeDesktopZip(archivePath, workDir); err != nil {
|
||||
return "", err
|
||||
}
|
||||
bundlePath := filepath.Join(workDir, "Claude.app")
|
||||
if err := validateClaudeDesktopBundle(bundlePath); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := verify(bundlePath); err != nil {
|
||||
return "", fmt.Errorf("verify Claude Desktop signature: %w", err)
|
||||
}
|
||||
|
||||
var permissionErr error
|
||||
for _, destination := range destinations {
|
||||
if strings.TrimSpace(destination) == "" {
|
||||
continue
|
||||
}
|
||||
if _, err := os.Stat(destination); err == nil {
|
||||
return "", fmt.Errorf("%w: %s", errClaudeDesktopDestinationExists, destination)
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("check Claude Desktop destination %s: %w", destination, err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(destination), 0o755); err != nil {
|
||||
if errors.Is(err, os.ErrPermission) {
|
||||
permissionErr = err
|
||||
continue
|
||||
}
|
||||
return "", fmt.Errorf("create Claude Desktop destination: %w", err)
|
||||
}
|
||||
if err := os.Rename(bundlePath, destination); err != nil {
|
||||
if errors.Is(err, os.ErrPermission) {
|
||||
permissionErr = err
|
||||
continue
|
||||
}
|
||||
return "", fmt.Errorf("move Claude Desktop to %s: %w", destination, err)
|
||||
}
|
||||
return destination, nil
|
||||
}
|
||||
if permissionErr != nil {
|
||||
return "", fmt.Errorf("install Claude Desktop in Applications: %w", permissionErr)
|
||||
}
|
||||
return "", errors.New("Claude Desktop installation destination is required")
|
||||
}
|
||||
|
||||
func extractClaudeDesktopZip(archivePath, destination string) error {
|
||||
reader, err := zip.OpenReader(archivePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open Claude Desktop archive: %w", err)
|
||||
}
|
||||
defer reader.Close()
|
||||
if len(reader.File) == 0 {
|
||||
return errors.New("Claude Desktop archive is empty")
|
||||
}
|
||||
if len(reader.File) > maxClaudeDesktopArchiveFiles {
|
||||
return fmt.Errorf("Claude Desktop archive contains more than %d files", maxClaudeDesktopArchiveFiles)
|
||||
}
|
||||
|
||||
var expanded uint64
|
||||
for _, file := range reader.File {
|
||||
clean, err := safeClaudeDesktopArchivePath(file.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
expanded += file.UncompressedSize64
|
||||
if expanded > maxClaudeDesktopExtractBytes {
|
||||
return fmt.Errorf("Claude Desktop archive expands beyond %d bytes", maxClaudeDesktopExtractBytes)
|
||||
}
|
||||
path := filepath.Join(destination, filepath.FromSlash(clean))
|
||||
switch {
|
||||
case file.FileInfo().IsDir():
|
||||
if err := os.MkdirAll(path, file.Mode().Perm()); err != nil {
|
||||
return fmt.Errorf("create Claude Desktop archive directory: %w", err)
|
||||
}
|
||||
case file.Mode()&os.ModeSymlink != 0:
|
||||
target, err := readClaudeDesktopZipFile(file, 16<<10)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read Claude Desktop archive symlink: %w", err)
|
||||
}
|
||||
if err := validateClaudeDesktopSymlink(clean, string(target)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return fmt.Errorf("create Claude Desktop archive directory: %w", err)
|
||||
}
|
||||
if err := os.Symlink(string(target), path); err != nil {
|
||||
return fmt.Errorf("create Claude Desktop archive symlink: %w", err)
|
||||
}
|
||||
case file.Mode().IsRegular():
|
||||
if err := extractClaudeDesktopZipFile(file, path); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("Claude Desktop archive contains unsupported file %q", file.Name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeClaudeDesktopArchivePath(name string) (string, error) {
|
||||
if strings.ContainsRune(name, '\x00') || filepath.IsAbs(name) {
|
||||
return "", fmt.Errorf("Claude Desktop archive contains unsafe path %q", name)
|
||||
}
|
||||
clean := filepath.ToSlash(filepath.Clean(name))
|
||||
if clean != "Claude.app" && !strings.HasPrefix(clean, "Claude.app/") {
|
||||
return "", fmt.Errorf("Claude Desktop archive contains unexpected path %q", name)
|
||||
}
|
||||
return clean, nil
|
||||
}
|
||||
|
||||
func validateClaudeDesktopSymlink(name, target string) error {
|
||||
if target == "" || filepath.IsAbs(target) {
|
||||
return fmt.Errorf("Claude Desktop archive contains unsafe symlink %q", name)
|
||||
}
|
||||
resolved := filepath.Clean(filepath.Join(filepath.Dir(name), target))
|
||||
resolved = filepath.ToSlash(resolved)
|
||||
if resolved != "Claude.app" && !strings.HasPrefix(resolved, "Claude.app/") {
|
||||
return fmt.Errorf("Claude Desktop archive symlink %q escapes Claude.app", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func extractClaudeDesktopZipFile(file *zip.File, path string) error {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return fmt.Errorf("create Claude Desktop archive directory: %w", err)
|
||||
}
|
||||
input, err := file.Open()
|
||||
if err != nil {
|
||||
return fmt.Errorf("open Claude Desktop archive file: %w", err)
|
||||
}
|
||||
output, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, file.Mode().Perm())
|
||||
if err != nil {
|
||||
input.Close()
|
||||
return fmt.Errorf("create Claude Desktop archive file: %w", err)
|
||||
}
|
||||
_, copyErr := io.Copy(output, input)
|
||||
inputErr := input.Close()
|
||||
outputErr := output.Close()
|
||||
if copyErr != nil {
|
||||
return fmt.Errorf("extract Claude Desktop archive file: %w", copyErr)
|
||||
}
|
||||
if inputErr != nil {
|
||||
return fmt.Errorf("close Claude Desktop archive file: %w", inputErr)
|
||||
}
|
||||
if outputErr != nil {
|
||||
return fmt.Errorf("close extracted Claude Desktop file: %w", outputErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readClaudeDesktopZipFile(file *zip.File, limit int64) ([]byte, error) {
|
||||
reader, err := file.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer reader.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(reader, limit+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int64(len(data)) > limit {
|
||||
return nil, fmt.Errorf("archive entry exceeds %d bytes", limit)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func validateClaudeDesktopBundle(bundlePath string) error {
|
||||
info, err := os.Stat(bundlePath)
|
||||
if err != nil || !info.IsDir() {
|
||||
return errors.New("Claude Desktop archive does not contain Claude.app")
|
||||
}
|
||||
executable := filepath.Join(bundlePath, "Contents", "MacOS", "Claude")
|
||||
info, err = os.Stat(executable)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Claude Desktop executable is missing: %w", err)
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Mode()&0o111 == 0 {
|
||||
return errors.New("Claude Desktop executable is not executable")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func verifyClaudeDesktopBundle(bundlePath string) error {
|
||||
if output, err := exec.Command("/usr/bin/codesign", "--verify", "--deep", "--strict", bundlePath).CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("codesign verification failed: %w: %s", err, strings.TrimSpace(string(output)))
|
||||
}
|
||||
output, err := exec.Command("/usr/bin/codesign", "-d", "--verbose=4", bundlePath).CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("read code signature: %w: %s", err, strings.TrimSpace(string(output)))
|
||||
}
|
||||
details := string(output)
|
||||
if !strings.Contains(details, "Identifier="+claudeDesktopBundleID) ||
|
||||
!strings.Contains(details, "TeamIdentifier="+claudeDesktopTeamID) {
|
||||
return fmt.Errorf("unexpected Claude Desktop signing identity")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
//go:build darwin
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInstallClaudeDesktopZip(t *testing.T) {
|
||||
archive := writeClaudeDesktopTestZip(t, map[string]claudeDesktopTestZipEntry{
|
||||
"Claude.app/": {directory: true},
|
||||
"Claude.app/Contents/": {directory: true},
|
||||
"Claude.app/Contents/MacOS/": {directory: true},
|
||||
"Claude.app/Contents/MacOS/Claude": {body: "binary", mode: 0o755},
|
||||
"Claude.app/Contents/Resources/": {directory: true},
|
||||
"Claude.app/Contents/Resources/link": {body: "../MacOS/Claude", mode: os.ModeSymlink | 0o777},
|
||||
})
|
||||
destination := filepath.Join(t.TempDir(), "Applications", "Claude.app")
|
||||
var verified string
|
||||
installed, err := installClaudeDesktopZip(archive, []string{destination}, func(bundle string) error {
|
||||
verified = bundle
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if installed != destination || verified == "" {
|
||||
t.Fatalf("installed = %q, verified = %q", installed, verified)
|
||||
}
|
||||
info, err := os.Stat(filepath.Join(installed, "Contents", "MacOS", "Claude"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode()&0o111 == 0 {
|
||||
t.Fatal("installed Claude executable is not executable")
|
||||
}
|
||||
if target, err := os.Readlink(filepath.Join(installed, "Contents", "Resources", "link")); err != nil || target != "../MacOS/Claude" {
|
||||
t.Fatalf("symlink target = %q, err = %v", target, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallClaudeDesktopZipRejectsUnsafeArchives(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
entries map[string]claudeDesktopTestZipEntry
|
||||
}{
|
||||
{name: "path traversal", entries: map[string]claudeDesktopTestZipEntry{"../Claude.app/Contents/MacOS/Claude": {body: "binary", mode: 0o755}}},
|
||||
{name: "unexpected root", entries: map[string]claudeDesktopTestZipEntry{"README": {body: "nope", mode: 0o644}}},
|
||||
{name: "escaping symlink", entries: map[string]claudeDesktopTestZipEntry{
|
||||
"Claude.app/Contents/MacOS/Claude": {body: "binary", mode: 0o755},
|
||||
"Claude.app/escape": {body: "../../outside", mode: os.ModeSymlink | 0o777},
|
||||
}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
archive := writeClaudeDesktopTestZip(t, test.entries)
|
||||
destination := filepath.Join(t.TempDir(), "Claude.app")
|
||||
if _, err := installClaudeDesktopZip(archive, []string{destination}, func(string) error { return nil }); err == nil {
|
||||
t.Fatal("installClaudeDesktopZip succeeded")
|
||||
}
|
||||
if _, err := os.Stat(destination); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("unsafe archive created destination: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallClaudeDesktopZipVerifiesBeforeMove(t *testing.T) {
|
||||
archive := writeClaudeDesktopTestZip(t, map[string]claudeDesktopTestZipEntry{
|
||||
"Claude.app/Contents/MacOS/Claude": {body: "binary", mode: 0o755},
|
||||
})
|
||||
destination := filepath.Join(t.TempDir(), "Claude.app")
|
||||
wantErr := errors.New("invalid signature")
|
||||
if _, err := installClaudeDesktopZip(archive, []string{destination}, func(string) error { return wantErr }); !errors.Is(err, wantErr) {
|
||||
t.Fatalf("error = %v, want %v", err, wantErr)
|
||||
}
|
||||
if _, err := os.Stat(destination); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("invalid bundle created destination: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallClaudeDesktopZipDoesNotOverwrite(t *testing.T) {
|
||||
archive := writeClaudeDesktopTestZip(t, map[string]claudeDesktopTestZipEntry{
|
||||
"Claude.app/Contents/MacOS/Claude": {body: "binary", mode: 0o755},
|
||||
})
|
||||
destination := filepath.Join(t.TempDir(), "Claude.app")
|
||||
if err := os.MkdirAll(destination, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := installClaudeDesktopZip(archive, []string{destination}, func(string) error { return nil }); !errors.Is(err, errClaudeDesktopDestinationExists) {
|
||||
t.Fatalf("error = %v, want destination exists", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallClaudeDesktopZipRealArchive(t *testing.T) {
|
||||
archive := os.Getenv("OLLAMA_TEST_CLAUDE_DESKTOP_ZIP")
|
||||
if archive == "" {
|
||||
t.Skip("set OLLAMA_TEST_CLAUDE_DESKTOP_ZIP to a downloaded Claude Desktop ZIP")
|
||||
}
|
||||
destination := filepath.Join(t.TempDir(), "Applications", "Claude.app")
|
||||
installed, err := installClaudeDesktopZip(
|
||||
archive,
|
||||
[]string{destination},
|
||||
verifyClaudeDesktopBundle,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if installed != destination {
|
||||
t.Fatalf("installed = %q, want %q", installed, destination)
|
||||
}
|
||||
}
|
||||
|
||||
type claudeDesktopTestZipEntry struct {
|
||||
body string
|
||||
mode os.FileMode
|
||||
directory bool
|
||||
}
|
||||
|
||||
func writeClaudeDesktopTestZip(t *testing.T, entries map[string]claudeDesktopTestZipEntry) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "Claude.zip")
|
||||
file, err := os.Create(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writer := zip.NewWriter(file)
|
||||
for name, entry := range entries {
|
||||
header := &zip.FileHeader{Name: name, Method: zip.Deflate}
|
||||
if entry.directory {
|
||||
header.SetMode(os.ModeDir | 0o755)
|
||||
} else {
|
||||
header.SetMode(entry.mode)
|
||||
}
|
||||
item, err := writer.CreateHeader(header)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := item.Write([]byte(entry.body)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestSafeClaudeDesktopArchivePath(t *testing.T) {
|
||||
for _, name := range []string{"Claude.app", "Claude.app/Contents/MacOS/Claude"} {
|
||||
if got, err := safeClaudeDesktopArchivePath(name); err != nil || got != strings.TrimSuffix(name, "/") {
|
||||
t.Fatalf("safeClaudeDesktopArchivePath(%q) = %q, %v", name, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
//go:build darwin
|
||||
|
||||
package main
|
||||
|
||||
import "github.com/ollama/ollama/internal/proxy"
|
||||
|
||||
type claudeDesktopInstallResult string
|
||||
|
||||
const (
|
||||
claudeDesktopInstallCancelled claudeDesktopInstallResult = "cancelled"
|
||||
claudeDesktopInstallerOpened claudeDesktopInstallResult = "opened"
|
||||
claudeDesktopInstallFailed claudeDesktopInstallResult = "failed"
|
||||
)
|
||||
|
||||
type claudeDesktopStatus struct {
|
||||
Supported bool `json:"supported"`
|
||||
Used bool `json:"used"`
|
||||
Installed bool `json:"installed"`
|
||||
Configured bool `json:"configured"`
|
||||
Connected bool `json:"connected"`
|
||||
Running bool `json:"running"`
|
||||
StartFailed bool `json:"startFailed"`
|
||||
PortConflict bool `json:"portConflict"`
|
||||
GatewayPort int `json:"gatewayPort,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
ModelSource string `json:"modelSource,omitempty"`
|
||||
Models []claudeDesktopModelStatus `json:"models,omitempty"`
|
||||
}
|
||||
|
||||
type claudeDesktopModelStatus struct {
|
||||
Name string `json:"name"`
|
||||
DisplayName string `json:"displayName"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Cloud bool `json:"cloud"`
|
||||
Selected bool `json:"selected"`
|
||||
Availability proxy.ClaudeDesktopAvailability `json:"availability"`
|
||||
Reason proxy.ClaudeDesktopAccessReason `json:"reason,omitempty"`
|
||||
RequiredPlan string `json:"requiredPlan,omitempty"`
|
||||
}
|
||||
|
||||
type claudeDesktopActionResult struct {
|
||||
Status claudeDesktopStatus `json:"status"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
@@ -16,7 +16,6 @@ import (
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
@@ -25,21 +24,11 @@ import (
|
||||
"github.com/ollama/ollama/app/webview"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultWindowWidth = 1360
|
||||
defaultWindowHeight = 960
|
||||
onboardingWindowWidth = 900
|
||||
onboardingWindowHeight = 660
|
||||
minimumWindowWidth = onboardingWindowWidth
|
||||
minimumWindowHeight = onboardingWindowHeight
|
||||
)
|
||||
|
||||
type Webview struct {
|
||||
port int
|
||||
token string
|
||||
webview webview.WebView
|
||||
mutex sync.Mutex
|
||||
onboarding atomic.Bool
|
||||
port int
|
||||
token string
|
||||
webview webview.WebView
|
||||
mutex sync.Mutex
|
||||
|
||||
Store *store.Store
|
||||
}
|
||||
@@ -99,32 +88,85 @@ func (w *Webview) Run(path string) unsafe.Pointer {
|
||||
// Windows-specific scrollbar styling
|
||||
if runtime.GOOS == "windows" {
|
||||
init += `
|
||||
// Keep Edge WebView2 scrollbars aligned with the light-only app theme.
|
||||
// Fix scrollbar styling for Edge WebView2 on Windows only
|
||||
function updateScrollbarStyles() {
|
||||
const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
const existingStyle = document.getElementById('scrollbar-style');
|
||||
if (existingStyle) existingStyle.remove();
|
||||
|
||||
|
||||
const style = document.createElement('style');
|
||||
style.id = 'scrollbar-style';
|
||||
style.textContent = ` + "`" + `
|
||||
::-webkit-scrollbar { width: 6px !important; height: 6px !important; }
|
||||
::-webkit-scrollbar-track { background: #f0f0f0 !important; }
|
||||
::-webkit-scrollbar-thumb { background: #c0c0c0 !important; border-radius: 6px !important; }
|
||||
::-webkit-scrollbar-thumb:hover { background: #a0a0a0 !important; }
|
||||
::-webkit-scrollbar-corner { background: #f0f0f0 !important; }
|
||||
::-webkit-scrollbar-button {
|
||||
background: transparent !important;
|
||||
border: none !important;
|
||||
width: 0px !important;
|
||||
height: 0px !important;
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
` + "`" + `;
|
||||
|
||||
if (isDark) {
|
||||
style.textContent = ` + "`" + `
|
||||
::-webkit-scrollbar { width: 6px !important; height: 6px !important; }
|
||||
::-webkit-scrollbar-track { background: #1a1a1a !important; }
|
||||
::-webkit-scrollbar-thumb { background: #404040 !important; border-radius: 6px !important; }
|
||||
::-webkit-scrollbar-thumb:hover { background: #505050 !important; }
|
||||
::-webkit-scrollbar-corner { background: #1a1a1a !important; }
|
||||
::-webkit-scrollbar-button {
|
||||
background: transparent !important;
|
||||
border: none !important;
|
||||
width: 0px !important;
|
||||
height: 0px !important;
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
::-webkit-scrollbar-button:vertical:start:decrement {
|
||||
background: transparent !important;
|
||||
height: 0px !important;
|
||||
}
|
||||
::-webkit-scrollbar-button:vertical:end:increment {
|
||||
background: transparent !important;
|
||||
height: 0px !important;
|
||||
}
|
||||
::-webkit-scrollbar-button:horizontal:start:decrement {
|
||||
background: transparent !important;
|
||||
width: 0px !important;
|
||||
}
|
||||
::-webkit-scrollbar-button:horizontal:end:increment {
|
||||
background: transparent !important;
|
||||
width: 0px !important;
|
||||
}
|
||||
` + "`" + `;
|
||||
} else {
|
||||
style.textContent = ` + "`" + `
|
||||
::-webkit-scrollbar { width: 6px !important; height: 6px !important; }
|
||||
::-webkit-scrollbar-track { background: #f0f0f0 !important; }
|
||||
::-webkit-scrollbar-thumb { background: #c0c0c0 !important; border-radius: 6px !important; }
|
||||
::-webkit-scrollbar-thumb:hover { background: #a0a0a0 !important; }
|
||||
::-webkit-scrollbar-corner { background: #f0f0f0 !important; }
|
||||
::-webkit-scrollbar-button {
|
||||
background: transparent !important;
|
||||
border: none !important;
|
||||
width: 0px !important;
|
||||
height: 0px !important;
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
::-webkit-scrollbar-button:vertical:start:decrement {
|
||||
background: transparent !important;
|
||||
height: 0px !important;
|
||||
}
|
||||
::-webkit-scrollbar-button:vertical:end:increment {
|
||||
background: transparent !important;
|
||||
height: 0px !important;
|
||||
}
|
||||
::-webkit-scrollbar-button:horizontal:start:decrement {
|
||||
background: transparent !important;
|
||||
width: 0px !important;
|
||||
}
|
||||
::-webkit-scrollbar-button:horizontal:end:increment {
|
||||
background: transparent !important;
|
||||
width: 0px !important;
|
||||
}
|
||||
` + "`" + `;
|
||||
}
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
|
||||
window.addEventListener('load', updateScrollbarStyles);
|
||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', updateScrollbarStyles);
|
||||
`
|
||||
}
|
||||
// on windows make ctrl+n open new chat
|
||||
@@ -145,32 +187,15 @@ func (w *Webview) Run(path string) unsafe.Pointer {
|
||||
`
|
||||
}
|
||||
|
||||
init += fmt.Sprintf(`
|
||||
window.OLLAMA_PLATFORM = %q;
|
||||
init += `
|
||||
window.OLLAMA_WEBSEARCH = true;
|
||||
`, runtime.GOOS)
|
||||
`
|
||||
|
||||
wv.Init(init)
|
||||
|
||||
// Add keyboard handler for zoom
|
||||
wv.Init(`
|
||||
window.addEventListener('keydown', function(e) {
|
||||
const isZoomShortcut = (e.metaKey || e.ctrlKey) && (
|
||||
e.key === '+' || e.key === '=' || e.key === '-' ||
|
||||
e.key === '_' || e.key === '0' ||
|
||||
e.code === 'NumpadAdd' || e.code === 'NumpadSubtract'
|
||||
);
|
||||
|
||||
// Keep fixed-scale onboarding and apps pages at their intended size.
|
||||
const isFixedScalePage =
|
||||
window.location.pathname === '/onboarding' ||
|
||||
window.location.pathname === '/connect';
|
||||
if (isFixedScalePage && isZoomShortcut) {
|
||||
e.preventDefault();
|
||||
e.stopImmediatePropagation();
|
||||
return false;
|
||||
}
|
||||
|
||||
// CMD/Ctrl + Plus/Equals (zoom in)
|
||||
if ((e.metaKey || e.ctrlKey) && (e.key === '+' || e.key === '=')) {
|
||||
e.preventDefault();
|
||||
@@ -212,41 +237,10 @@ func (w *Webview) Run(path string) unsafe.Pointer {
|
||||
showWindow(wv.Window())
|
||||
})
|
||||
|
||||
wv.Bind("activateOllama", func() {
|
||||
showWindow(wv.Window())
|
||||
})
|
||||
|
||||
bindClaudeDesktop(wv)
|
||||
|
||||
wv.Bind("close", func() {
|
||||
hideWindow(wv.Window())
|
||||
})
|
||||
|
||||
wv.Bind("setOnboardingWindow", func(enabled bool) {
|
||||
w.onboarding.Store(enabled)
|
||||
wv.Dispatch(func() {
|
||||
if enabled {
|
||||
wv.SetSize(onboardingWindowWidth, onboardingWindowHeight, webview.HintFixed)
|
||||
setOnboardingWindowStyle(wv.Window(), true)
|
||||
return
|
||||
}
|
||||
|
||||
width, height := defaultWindowWidth, defaultWindowHeight
|
||||
if w.Store != nil {
|
||||
storedWidth, storedHeight, err := w.Store.WindowSize()
|
||||
if err != nil {
|
||||
slog.Error("failed to restore window size", "error", err)
|
||||
} else if storedWidth > 0 && storedHeight > 0 {
|
||||
width, height = storedWidth, storedHeight
|
||||
}
|
||||
}
|
||||
|
||||
wv.SetSize(width, height, webview.HintNone)
|
||||
wv.SetSize(minimumWindowWidth, minimumWindowHeight, webview.HintMin)
|
||||
setOnboardingWindowStyle(wv.Window(), false)
|
||||
})
|
||||
})
|
||||
|
||||
// Webviews do not allow access to the file system by default, so we need to
|
||||
// bind file system operations here
|
||||
wv.Bind("selectModelsDirectory", func() {
|
||||
@@ -456,18 +450,18 @@ func (w *Webview) Run(path string) unsafe.Pointer {
|
||||
}()
|
||||
}
|
||||
|
||||
width, height := defaultWindowWidth, defaultWindowHeight
|
||||
if w.Store != nil {
|
||||
storedWidth, storedHeight, err := w.Store.WindowSize()
|
||||
width, height, err := w.Store.WindowSize()
|
||||
if err != nil {
|
||||
slog.Error("failed to get window size", "error", err)
|
||||
}
|
||||
if storedWidth > 0 && storedHeight > 0 {
|
||||
width, height = storedWidth, storedHeight
|
||||
if width > 0 && height > 0 {
|
||||
wv.SetSize(width, height, webview.HintNone)
|
||||
} else {
|
||||
wv.SetSize(800, 600, webview.HintNone)
|
||||
}
|
||||
}
|
||||
wv.SetSize(width, height, webview.HintNone)
|
||||
wv.SetSize(minimumWindowWidth, minimumWindowHeight, webview.HintMin)
|
||||
wv.SetSize(800, 600, webview.HintMin)
|
||||
|
||||
w.webview = wv
|
||||
w.webview.Navigate(url)
|
||||
@@ -482,7 +476,6 @@ func (w *Webview) Run(path string) unsafe.Pointer {
|
||||
}
|
||||
|
||||
func (w *Webview) Terminate() {
|
||||
w.onboarding.Store(false)
|
||||
w.mutex.Lock()
|
||||
if w.webview == nil {
|
||||
w.mutex.Unlock()
|
||||
@@ -496,10 +489,6 @@ func (w *Webview) Terminate() {
|
||||
wv.Destroy()
|
||||
}
|
||||
|
||||
func (w *Webview) OnboardingActive() bool {
|
||||
return w.onboarding.Load()
|
||||
}
|
||||
|
||||
func (w *Webview) IsRunning() bool {
|
||||
w.mutex.Lock()
|
||||
defer w.mutex.Unlock()
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
<?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>
|
||||
|
Before Width: | Height: | Size: 4.0 KiB |
@@ -143,13 +143,13 @@ func utf16ptr(utf16 []uint16) *uint16 {
|
||||
|
||||
func utf16slice(ptr *uint16) []uint16 { //nolint:unused
|
||||
hdr := reflect.SliceHeader{Data: uintptr(unsafe.Pointer(ptr)), Len: 1, Cap: 1}
|
||||
slice := *(*[]uint16)(unsafe.Pointer(&hdr)) //nolint:govet
|
||||
slice := *((*[]uint16)(unsafe.Pointer(&hdr))) //nolint:govet
|
||||
i := 0
|
||||
for slice[len(slice)-1] != 0 {
|
||||
i++
|
||||
}
|
||||
hdr.Len = i
|
||||
slice = *(*[]uint16)(unsafe.Pointer(&hdr)) //nolint:govet
|
||||
slice = *((*[]uint16)(unsafe.Pointer(&hdr))) //nolint:govet
|
||||
return slice
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
|
||||
// currentSchemaVersion defines the current database schema version.
|
||||
// Increment this when making schema changes that require migrations.
|
||||
const currentSchemaVersion = 18
|
||||
const currentSchemaVersion = 16
|
||||
|
||||
// database wraps the SQLite connection.
|
||||
// SQLite handles its own locking for concurrent access:
|
||||
@@ -82,14 +82,12 @@ func (db *database) init() error {
|
||||
websearch_enabled BOOLEAN NOT NULL DEFAULT 0,
|
||||
selected_model TEXT NOT NULL DEFAULT '',
|
||||
sidebar_open BOOLEAN NOT NULL DEFAULT 0,
|
||||
last_home_view TEXT NOT NULL DEFAULT 'chat',
|
||||
onboarding_version INTEGER NOT NULL DEFAULT 0,
|
||||
last_home_view TEXT NOT NULL DEFAULT 'launch',
|
||||
think_enabled BOOLEAN NOT NULL DEFAULT 0,
|
||||
think_level TEXT NOT NULL DEFAULT '',
|
||||
cloud_setting_migrated BOOLEAN NOT NULL DEFAULT 0,
|
||||
remote TEXT NOT NULL DEFAULT '', -- deprecated
|
||||
auto_update_enabled BOOLEAN NOT NULL DEFAULT 1,
|
||||
claude_desktop_used BOOLEAN NOT NULL DEFAULT 0,
|
||||
schema_version INTEGER NOT NULL DEFAULT %d
|
||||
);
|
||||
|
||||
@@ -273,18 +271,6 @@ func (db *database) migrate() error {
|
||||
return fmt.Errorf("migrate v15 to v16: %w", err)
|
||||
}
|
||||
version = 16
|
||||
case 16:
|
||||
// Existing users should not be shown onboarding after an upgrade.
|
||||
if err := db.migrateV16ToV17(); err != nil {
|
||||
return fmt.Errorf("migrate v16 to v17: %w", err)
|
||||
}
|
||||
version = 17
|
||||
case 17:
|
||||
// Remember that Claude Desktop has been connected at least once.
|
||||
if err := db.migrateV17ToV18(); err != nil {
|
||||
return fmt.Errorf("migrate v17 to v18: %w", err)
|
||||
}
|
||||
version = 18
|
||||
default:
|
||||
// If we have a version we don't recognize, just set it to current
|
||||
// This might happen during development
|
||||
@@ -541,7 +527,7 @@ func (db *database) migrateV14ToV15() error {
|
||||
|
||||
// migrateV15ToV16 adds the last_home_view column to the settings table
|
||||
func (db *database) migrateV15ToV16() error {
|
||||
_, err := db.conn.Exec(`ALTER TABLE settings ADD COLUMN last_home_view TEXT NOT NULL DEFAULT 'chat'`)
|
||||
_, err := db.conn.Exec(`ALTER TABLE settings ADD COLUMN last_home_view TEXT NOT NULL DEFAULT 'launch'`)
|
||||
if err != nil && !duplicateColumnError(err) {
|
||||
return fmt.Errorf("add last_home_view column: %w", err)
|
||||
}
|
||||
@@ -554,38 +540,6 @@ func (db *database) migrateV15ToV16() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// migrateV16ToV17 adds versioned onboarding state. The schema default stays at
|
||||
// zero for genuinely new installs, while all existing rows are marked complete
|
||||
// and moved off the retired launch home view.
|
||||
func (db *database) migrateV16ToV17() error {
|
||||
_, err := db.conn.Exec(`ALTER TABLE settings ADD COLUMN onboarding_version INTEGER NOT NULL DEFAULT 0`)
|
||||
if err != nil && !duplicateColumnError(err) {
|
||||
return fmt.Errorf("add onboarding_version column: %w", err)
|
||||
}
|
||||
|
||||
_, err = db.conn.Exec(`UPDATE settings SET onboarding_version = 1, last_home_view = 'chat', schema_version = 17`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("complete onboarding for existing users: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// migrateV17ToV18 adds durable Claude Desktop integration history.
|
||||
func (db *database) migrateV17ToV18() error {
|
||||
_, err := db.conn.Exec(`ALTER TABLE settings ADD COLUMN claude_desktop_used BOOLEAN NOT NULL DEFAULT 0`)
|
||||
if err != nil && !duplicateColumnError(err) {
|
||||
return fmt.Errorf("add claude_desktop_used column: %w", err)
|
||||
}
|
||||
|
||||
_, err = db.conn.Exec(`UPDATE settings SET schema_version = 18`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("update schema version: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// cleanupOrphanedData removes orphaned records that may exist due to the foreign key bug
|
||||
func (db *database) cleanupOrphanedData() error {
|
||||
_, err := db.conn.Exec(`
|
||||
@@ -1234,9 +1188,9 @@ func (db *database) getSettings() (Settings, error) {
|
||||
var s Settings
|
||||
|
||||
err := db.conn.QueryRow(`
|
||||
SELECT expose, survey, browser, models, agent, tools, working_dir, context_length, turbo_enabled, websearch_enabled, selected_model, sidebar_open, last_home_view, onboarding_version, think_enabled, think_level, auto_update_enabled, claude_desktop_used
|
||||
SELECT expose, survey, browser, models, agent, tools, working_dir, context_length, turbo_enabled, websearch_enabled, selected_model, sidebar_open, last_home_view, think_enabled, think_level, auto_update_enabled
|
||||
FROM settings
|
||||
`).Scan(&s.Expose, &s.Survey, &s.Browser, &s.Models, &s.Agent, &s.Tools, &s.WorkingDir, &s.ContextLength, &s.TurboEnabled, &s.WebSearchEnabled, &s.SelectedModel, &s.SidebarOpen, &s.LastHomeView, &s.OnboardingVersion, &s.ThinkEnabled, &s.ThinkLevel, &s.AutoUpdateEnabled, &s.ClaudeDesktopUsed)
|
||||
`).Scan(&s.Expose, &s.Survey, &s.Browser, &s.Models, &s.Agent, &s.Tools, &s.WorkingDir, &s.ContextLength, &s.TurboEnabled, &s.WebSearchEnabled, &s.SelectedModel, &s.SidebarOpen, &s.LastHomeView, &s.ThinkEnabled, &s.ThinkLevel, &s.AutoUpdateEnabled)
|
||||
if err != nil {
|
||||
return Settings{}, fmt.Errorf("get settings: %w", err)
|
||||
}
|
||||
@@ -1246,14 +1200,28 @@ func (db *database) getSettings() (Settings, error) {
|
||||
|
||||
func (db *database) setSettings(s Settings) error {
|
||||
lastHomeView := strings.ToLower(strings.TrimSpace(s.LastHomeView))
|
||||
validLaunchView := map[string]struct{}{
|
||||
"launch": {},
|
||||
"openclaw": {},
|
||||
"claude": {},
|
||||
"hermes": {},
|
||||
"codex": {},
|
||||
"codex-app": {},
|
||||
"copilot": {},
|
||||
"opencode": {},
|
||||
"droid": {},
|
||||
"pi": {},
|
||||
}
|
||||
if lastHomeView != "chat" {
|
||||
lastHomeView = "chat"
|
||||
if _, ok := validLaunchView[lastHomeView]; !ok {
|
||||
lastHomeView = "launch"
|
||||
}
|
||||
}
|
||||
|
||||
_, err := db.conn.Exec(`
|
||||
UPDATE settings
|
||||
SET expose = ?, survey = ?, browser = ?, models = ?, agent = ?, tools = ?, working_dir = ?, context_length = ?, turbo_enabled = ?, websearch_enabled = ?, selected_model = ?, sidebar_open = ?, last_home_view = ?, onboarding_version = ?, think_enabled = ?, think_level = ?, auto_update_enabled = ?, claude_desktop_used = ?
|
||||
`, s.Expose, s.Survey, s.Browser, s.Models, s.Agent, s.Tools, s.WorkingDir, s.ContextLength, s.TurboEnabled, s.WebSearchEnabled, s.SelectedModel, s.SidebarOpen, lastHomeView, s.OnboardingVersion, s.ThinkEnabled, s.ThinkLevel, s.AutoUpdateEnabled, s.ClaudeDesktopUsed)
|
||||
SET expose = ?, survey = ?, browser = ?, models = ?, agent = ?, tools = ?, working_dir = ?, context_length = ?, turbo_enabled = ?, websearch_enabled = ?, selected_model = ?, sidebar_open = ?, last_home_view = ?, think_enabled = ?, think_level = ?, auto_update_enabled = ?
|
||||
`, s.Expose, s.Survey, s.Browser, s.Models, s.Agent, s.Tools, s.WorkingDir, s.ContextLength, s.TurboEnabled, s.WebSearchEnabled, s.SelectedModel, s.SidebarOpen, lastHomeView, s.ThinkEnabled, s.ThinkLevel, s.AutoUpdateEnabled)
|
||||
if err != nil {
|
||||
return fmt.Errorf("set settings: %w", err)
|
||||
}
|
||||
|
||||
@@ -135,7 +135,7 @@ func TestMigrationV13ToV14ContextLength(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationV15ToV16LastHomeViewMigratesToChat(t *testing.T) {
|
||||
func TestMigrationV15ToV16LastHomeViewDefaultsToLaunch(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
dbPath := filepath.Join(tmpDir, "test.db")
|
||||
|
||||
@@ -161,8 +161,8 @@ func TestMigrationV15ToV16LastHomeViewMigratesToChat(t *testing.T) {
|
||||
t.Fatalf("failed to read last_home_view: %v", err)
|
||||
}
|
||||
|
||||
if lastHomeView != "chat" {
|
||||
t.Fatalf("expected last_home_view to migrate to chat, got %q", lastHomeView)
|
||||
if lastHomeView != "launch" {
|
||||
t.Fatalf("expected last_home_view to default to launch after migration, got %q", lastHomeView)
|
||||
}
|
||||
|
||||
version, err := db.getSchemaVersion()
|
||||
@@ -174,88 +174,6 @@ func TestMigrationV15ToV16LastHomeViewMigratesToChat(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnboardingVersionDefaultsAndMigration(t *testing.T) {
|
||||
t.Run("fresh installs need onboarding", func(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "fresh.db")
|
||||
db, err := newDatabase(dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create database: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
settings, err := db.getSettings()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read settings: %v", err)
|
||||
}
|
||||
if settings.OnboardingVersion != 0 {
|
||||
t.Fatalf("expected fresh install onboarding version 0, got %d", settings.OnboardingVersion)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("existing installs skip onboarding", func(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "existing.db")
|
||||
db, err := newDatabase(dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create database: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
if _, err := db.conn.Exec(`
|
||||
ALTER TABLE settings DROP COLUMN onboarding_version;
|
||||
UPDATE settings SET schema_version = 16;
|
||||
`); err != nil {
|
||||
t.Fatalf("failed to seed v16 settings row: %v", err)
|
||||
}
|
||||
|
||||
if err := db.migrate(); err != nil {
|
||||
t.Fatalf("migration from v16 to v17 failed: %v", err)
|
||||
}
|
||||
|
||||
settings, err := db.getSettings()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read settings: %v", err)
|
||||
}
|
||||
if settings.OnboardingVersion != 1 {
|
||||
t.Fatalf("expected existing install onboarding version 1, got %d", settings.OnboardingVersion)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestClaudeDesktopUsedDefaultsAndMigration(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "claude-history.db")
|
||||
db, err := newDatabase(dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create database: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
settings, err := db.getSettings()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read settings: %v", err)
|
||||
}
|
||||
if settings.ClaudeDesktopUsed {
|
||||
t.Fatal("expected fresh installs to have no Claude Desktop history")
|
||||
}
|
||||
|
||||
if _, err := db.conn.Exec(`
|
||||
ALTER TABLE settings DROP COLUMN claude_desktop_used;
|
||||
UPDATE settings SET schema_version = 17;
|
||||
`); err != nil {
|
||||
t.Fatalf("failed to seed v17 settings row: %v", err)
|
||||
}
|
||||
if err := db.migrate(); err != nil {
|
||||
t.Fatalf("migration from v17 to v18 failed: %v", err)
|
||||
}
|
||||
|
||||
settings, err = db.getSettings()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read migrated settings: %v", err)
|
||||
}
|
||||
if settings.ClaudeDesktopUsed {
|
||||
t.Fatal("expected existing installs to start with no inferred Claude Desktop history")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatDeletionWithCascade(t *testing.T) {
|
||||
t.Run("chat deletion cascades to related messages", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
@@ -57,14 +57,6 @@ func TestConfigMigration(t *testing.T) {
|
||||
t.Error("expected has completed first run to be true after migration")
|
||||
}
|
||||
|
||||
settings, err := s.Settings()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get settings: %v", err)
|
||||
}
|
||||
if settings.OnboardingVersion != CurrentOnboardingVersion {
|
||||
t.Fatalf("expected migrated user to skip onboarding, got version %d", settings.OnboardingVersion)
|
||||
}
|
||||
|
||||
// Verify migration is marked as complete
|
||||
migrated, err := s.db.isConfigMigrated()
|
||||
if err != nil {
|
||||
|
||||
@@ -167,22 +167,13 @@ type Settings struct {
|
||||
// SidebarOpen indicates if the chat sidebar is open
|
||||
SidebarOpen bool
|
||||
|
||||
// LastHomeView is retained for settings compatibility and resolves to chat.
|
||||
// LastHomeView stores the preferred home route target ("chat" or integration name)
|
||||
LastHomeView string
|
||||
|
||||
// OnboardingVersion stores the latest onboarding flow the user has completed.
|
||||
OnboardingVersion int
|
||||
|
||||
// AutoUpdateEnabled indicates if automatic updates should be downloaded
|
||||
AutoUpdateEnabled bool
|
||||
|
||||
// ClaudeDesktopUsed records whether Claude Desktop has ever been connected through Ollama.
|
||||
ClaudeDesktopUsed bool
|
||||
}
|
||||
|
||||
// Keep in sync with CURRENT_ONBOARDING_VERSION in app/ui/app/src/lib/onboarding.ts.
|
||||
const CurrentOnboardingVersion = 1
|
||||
|
||||
type Store struct {
|
||||
// DBPath allows overriding the default database path (mainly for testing)
|
||||
DBPath string
|
||||
@@ -343,16 +334,6 @@ func (s *Store) migrateFromConfig(database *database) error {
|
||||
if err := database.setHasCompletedFirstRun(hasCompleted); err != nil {
|
||||
return fmt.Errorf("migrate first time run: %w", err)
|
||||
}
|
||||
if hasCompleted {
|
||||
settings, err := database.getSettings()
|
||||
if err != nil {
|
||||
return fmt.Errorf("read settings for onboarding migration: %w", err)
|
||||
}
|
||||
settings.OnboardingVersion = CurrentOnboardingVersion
|
||||
if err := database.setSettings(settings); err != nil {
|
||||
return fmt.Errorf("migrate onboarding completion: %w", err)
|
||||
}
|
||||
}
|
||||
slog.Info("migrated first run status from config.json", "hasCompleted", hasCompleted)
|
||||
|
||||
// Mark as migrated
|
||||
@@ -412,7 +393,7 @@ func (s *Store) Settings() (Settings, error) {
|
||||
}
|
||||
|
||||
if settings.LastHomeView == "" {
|
||||
settings.LastHomeView = "chat"
|
||||
settings.LastHomeView = "launch"
|
||||
}
|
||||
|
||||
return settings, nil
|
||||
|
||||
@@ -81,18 +81,18 @@ func TestStore(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("settings default home view is chat", func(t *testing.T) {
|
||||
t.Run("settings default home view is launch", func(t *testing.T) {
|
||||
loaded, err := s.Settings()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if loaded.LastHomeView != "chat" {
|
||||
t.Fatalf("expected default LastHomeView to be chat, got %q", loaded.LastHomeView)
|
||||
if loaded.LastHomeView != "launch" {
|
||||
t.Fatalf("expected default LastHomeView to be launch, got %q", loaded.LastHomeView)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("settings empty home view falls back to chat", func(t *testing.T) {
|
||||
t.Run("settings empty home view falls back to launch", func(t *testing.T) {
|
||||
if err := s.SetSettings(Settings{LastHomeView: ""}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -102,12 +102,12 @@ func TestStore(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if loaded.LastHomeView != "chat" {
|
||||
t.Fatalf("expected empty LastHomeView to fall back to chat, got %q", loaded.LastHomeView)
|
||||
if loaded.LastHomeView != "launch" {
|
||||
t.Fatalf("expected empty LastHomeView to fall back to launch, got %q", loaded.LastHomeView)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("settings retired home view falls back to chat", func(t *testing.T) {
|
||||
t.Run("settings disabled home view falls back to launch", func(t *testing.T) {
|
||||
if err := s.SetSettings(Settings{LastHomeView: "claude-desktop"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -117,12 +117,12 @@ func TestStore(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if loaded.LastHomeView != "chat" {
|
||||
t.Fatalf("expected retired LastHomeView to fall back to chat, got %q", loaded.LastHomeView)
|
||||
if loaded.LastHomeView != "launch" {
|
||||
t.Fatalf("expected disabled LastHomeView to fall back to launch, got %q", loaded.LastHomeView)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("settings integration home view falls back to chat", func(t *testing.T) {
|
||||
t.Run("settings codex app home view is accepted", func(t *testing.T) {
|
||||
if err := s.SetSettings(Settings{LastHomeView: "codex-app"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -132,8 +132,8 @@ func TestStore(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if loaded.LastHomeView != "chat" {
|
||||
t.Fatalf("expected integration LastHomeView to fall back to chat, got %q", loaded.LastHomeView)
|
||||
if loaded.LastHomeView != "codex-app" {
|
||||
t.Fatalf("expected codex-app LastHomeView to be preserved, got %q", loaded.LastHomeView)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -227,58 +227,6 @@ func TestStore(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestOnboardingVersionRoundTrip(t *testing.T) {
|
||||
s, cleanup := setupTestStore(t)
|
||||
defer cleanup()
|
||||
|
||||
settings, err := s.Settings()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if settings.OnboardingVersion != 0 {
|
||||
t.Fatalf("expected onboarding version 0 by default, got %d", settings.OnboardingVersion)
|
||||
}
|
||||
|
||||
settings.OnboardingVersion = 1
|
||||
if err := s.SetSettings(settings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
loaded, err := s.Settings()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if loaded.OnboardingVersion != 1 {
|
||||
t.Fatalf("expected onboarding version 1, got %d", loaded.OnboardingVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaudeDesktopUsedRoundTrip(t *testing.T) {
|
||||
s, cleanup := setupTestStore(t)
|
||||
defer cleanup()
|
||||
|
||||
settings, err := s.Settings()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if settings.ClaudeDesktopUsed {
|
||||
t.Fatal("expected Claude Desktop history to be false by default")
|
||||
}
|
||||
|
||||
settings.ClaudeDesktopUsed = true
|
||||
if err := s.SetSettings(settings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
loaded, err := s.Settings()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !loaded.ClaudeDesktopUsed {
|
||||
t.Fatal("expected Claude Desktop history to persist")
|
||||
}
|
||||
}
|
||||
|
||||
// setupTestStore creates a temporary store for testing
|
||||
func setupTestStore(t *testing.T) (*Store, func()) {
|
||||
t.Helper()
|
||||
|
||||
@@ -415,9 +415,7 @@ export class Settings {
|
||||
SelectedModel: string;
|
||||
SidebarOpen: boolean;
|
||||
LastHomeView: string;
|
||||
OnboardingVersion: number;
|
||||
AutoUpdateEnabled: boolean;
|
||||
ClaudeDesktopUsed: boolean;
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
@@ -436,9 +434,7 @@ export class Settings {
|
||||
this.SelectedModel = source["SelectedModel"];
|
||||
this.SidebarOpen = source["SidebarOpen"];
|
||||
this.LastHomeView = source["LastHomeView"];
|
||||
this.OnboardingVersion = source["OnboardingVersion"];
|
||||
this.AutoUpdateEnabled = source["AutoUpdateEnabled"];
|
||||
this.ClaudeDesktopUsed = source["ClaudeDesktopUsed"];
|
||||
}
|
||||
}
|
||||
export class SettingsResponse {
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en" style="overflow: hidden; color-scheme: light">
|
||||
<html lang="en" style="overflow: hidden">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="color-scheme" content="light" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="stylesheet" href="/src/index.css" />
|
||||
<title>Ollama</title>
|
||||
</head>
|
||||
<body class="bg-white select-text">
|
||||
<body class="dark:bg-neutral-900 select-text">
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
<script>
|
||||
|
||||
|
Before Width: | Height: | Size: 245 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 21 KiB |
@@ -1,8 +0,0 @@
|
||||
<svg width="92" height="96" viewBox="0 0 92 96" xmlns="http://www.w3.org/2000/svg">
|
||||
<g fill="#24292F">
|
||||
<path fill-rule="evenodd" d="M65.45 16.8c10.89 0 19.71 8.86 19.71 19.8v6.6l5.74 11.46a4 4 0 0 1-.01 3.6l-5.73 11.34v6.6c0 10.94-8.82 19.8-19.71 19.8H26.02C15.13 96 6.31 87.14 6.31 76.2v-6.6L.45 58.3a4 4 0 0 1-.01-3.67l5.87-11.43v-6.6c0-10.94 8.82-19.8 19.71-19.8h39.43Zm-2.52 5.7H29.19c-9.32 0-16.87 7.56-16.87 16.88V45L7.44 54.46a4 4 0 0 0 .01 3.68L12.32 67.5v5.63c0 9.32 7.55 16.87 16.87 16.87h33.74c9.32 0 16.87-7.55 16.87-16.87V67.5l4.77-9.39a4 4 0 0 0 .01-3.61L79.8 45v-5.62c0-9.32-7.55-16.88-16.87-16.88Z"/>
|
||||
<circle cx="45.73" cy="11.5" r="11"/>
|
||||
<rect x="27" y="41" width="13" height="30" rx="6.5"/>
|
||||
<rect x="51" y="41" width="13" height="30" rx="6.5"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 795 B |
@@ -1,4 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 50 50" fill="none">
|
||||
<style>@media (prefers-color-scheme: dark) { path { fill: #fff; } }</style>
|
||||
<path d="M48.8354 10.0479C48.3232 9.79199 48.1025 10.2798 47.8032 10.5278C46.7793 11.624 45.9048 12.1597 44.7622 12.0957C43.0923 12 41.666 12.5356 40.4058 13.8398C40.1377 12.2319 39.2476 11.272 37.8926 10.6558C36.4668 10.0156 35.9702 9.31982 35.356 7.72754C35.2456 7.3999 35.1353 7.06396 34.7651 7.00781C34.3633 6.94385 34.2056 7.2876 34.0479 7.57568C33.418 8.75195 33.1733 10.0479 33.1973 11.3599C33.2524 14.312 34.4736 16.6641 36.8999 18.3359C37.1758 18.5278 37.2466 18.7197 37.1597 19C36.9946 19.5757 36.7974 20.1357 36.624 20.7119C36.5137 21.0801 36.3486 21.1597 35.9624 21C32.4092 19.4878 30.0381 16.2319 27.2334 13.52C26.7764 13.1758 26.3193 12.856 25.8467 12.5518C23.8618 10.584 26.1069 8.96777 26.627 8.77588C27.1704 8.57568 26.8159 7.8877 25.0591 7.896C22.8691 7.90381 20.4507 9.06396 18.7095 9.58398C16.8501 9.22363 14.9199 9.14355 12.9033 9.37598C5.30859 10.2397 1.15674 16.4717 1.30664 27.2559C2.11768 31.9521 4.46582 35.8398 8.07373 38.8799C11.8159 42.0322 16.1255 43.5762 21.041 43.2803C24.0269 43.104 27.3516 42.6963 31.1016 39.4561C33.0396 40.1279 37.1758 40.208 38.1211 40.0078C39.6021 39.688 39.4995 38.2881 38.9639 38.0322C34.623 35.9678 35.5762 36.8081 34.71 36.1279C36.9155 33.4639 40.2402 30.6958 41.54 21.728C41.6426 21.0161 41.5557 20.5679 41.54 19.9917C41.5322 19.6396 41.6108 19.5039 42.0049 19.4639C46.6924 18.9116 49.064 15.9038 49.3315 11.2559C49.3711 10.7837 49.3237 10.2959 48.8354 10.0479ZM24.3262 37.8398C20.1196 34.4639 18.0791 33.3521 17.2358 33.3999C16.4482 33.4482 16.5898 34.3682 16.7632 34.9678C16.9443 35.5601 17.1812 35.9683 17.5117 36.4878C17.7402 36.832 17.8979 37.3442 17.2832 37.728C15.9282 38.584 13.5728 37.4399 13.4624 37.3838C7.97949 34.0879 4.48926 28.9282 4.19775 21.3677C4.1582 20.5757 4.38672 20.2959 5.15869 20.1519C11.8945 18.8799 17.165 22.0879 19.2529 25.7759C23.5381 30.104 25.335 35.1523 30.479 39.104C28.8643 39.2881 26.1699 39.3281 24.3262 37.8398ZM26.3433 24.6001C26.3433 24.248 26.6191 23.9678 26.9658 23.9678C27.3042 23.9678 27.5801 24.248 27.5801 24.6001C27.5801 24.9521 27.3042 25.2319 26.9575 25.2319C26.6108 25.2319 26.3433 24.9521 26.3433 24.6001ZM32.6064 27.8799C31.6372 28.2881 30.6289 28.3042 29.8096 27.688C28.6987 26.8555 28.6279 25.7759 28.7305 24.9199C28.8721 24.248 28.7144 23.8159 28.2495 23.4238C27.8716 23.104 27.3911 23.0161 26.8633 23.0161C26.666 23.0161 26.4849 22.9277 26.3511 22.856C25.8467 22.5762 25.9805 22.1758 26.5088 21.688C28.0996 20.7598 29.6362 21.9917 30.834 23.3281C31.6216 24.2559 32.8901 26.312 33.1104 26.9521C33.2446 27.3521 33.0713 27.6802 32.6064 27.8799Z" fill="#000"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.7 KiB |
@@ -1,11 +0,0 @@
|
||||
<svg viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<linearGradient id="omp-gradient" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#ed4abf"/>
|
||||
<stop offset=".5" stop-color="#9b4dff"/>
|
||||
<stop offset="1" stop-color="#5ad8e6"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="64" height="64" rx="12" fill="#0f0a14"/>
|
||||
<path fill="url(#omp-gradient)" d="M14 16h36v8H40v32h-8V24h-6v22h-8V24h-4z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 451 B |
@@ -1,11 +0,0 @@
|
||||
<svg viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<linearGradient id="poolside-gradient" x1="8" y1="5" x2="55" y2="59" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#6c5cff"/>
|
||||
<stop offset="1" stop-color="#3c2cff"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="64" height="64" rx="13" fill="url(#poolside-gradient)"/>
|
||||
<path d="M13 32c0-10.5 8.5-19 19-19 10.49 0 19 8.5 19 19s-8.51 19-19 19c-10.5 0-19-8.5-19-19Z" fill="none" stroke="#fff" stroke-width="4"/>
|
||||
<path d="M16 24c8-4.1 17.1-.9 22.6 7.1 4.3-1.2 8.6.5 11 4.1M23.5 47.5 38 17.5" fill="none" stroke="#fff" stroke-linecap="round" stroke-linejoin="round" stroke-width="4"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 682 B |
@@ -1,3 +0,0 @@
|
||||
<svg viewBox="0 0 141.38 140" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill="#6D44E8" d="m140.93 85-16.35-28.33-1.93-3.34 8.66-15a3.32 3.32 0 0 0 0-3.34l-9.62-16.67a3.34 3.34 0 0 0-2.89-1.67H82.23l-8.66-15A3.33 3.33 0 0 0 70.68-.02H51.43a3.33 3.33 0 0 0-2.88 1.67L32.19 29.98l-1.92 3.33H12.96a3.34 3.34 0 0 0-2.88 1.67L.45 51.66a3.32 3.32 0 0 0 0 3.34l18.28 31.67-8.66 15a3.32 3.32 0 0 0 0 3.34l9.62 16.67a3.34 3.34 0 0 0 2.89 1.67h36.56l8.66 15a3.35 3.35 0 0 0 2.89 1.67h19.25a3.34 3.34 0 0 0 2.89-1.67l18.28-31.67h17.32a3.34 3.34 0 0 0 2.89-1.67l9.62-16.67a3.32 3.32 0 0 0-.01-3.34ZM51.44 3.33 61.07 20l-9.63 16.66h76.98l-9.62 16.66H45.67l-11.54-20zM57.21 120H22.58l9.63-16.67h19.25l-38.5-66.67h19.25l9.62 16.67L68.78 100l-11.55 20Zm61.59-33.34-9.62-16.67-38.49 66.67-9.63-16.67 9.63-16.66 26.94-46.67h23.1l17.32 30z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 832 B |
@@ -1,141 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
const { listModels } = vi.hoisted(() => ({ listModels: vi.fn() }));
|
||||
vi.mock("./lib/ollama-client", () => ({
|
||||
ollamaClient: { list: listModels },
|
||||
}));
|
||||
|
||||
import {
|
||||
fetchConnectUrl,
|
||||
getClaudeDesktopAvailableModels,
|
||||
getIntegrationStatuses,
|
||||
} from "./api";
|
||||
|
||||
describe("fetchConnectUrl", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("requests a desktop handoff after account creation", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
signin_url:
|
||||
"https://ollama.com/connect?name=MacBook&key=public-key",
|
||||
}),
|
||||
{ status: 401 },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
await expect(fetchConnectUrl()).resolves.toBe(
|
||||
"https://ollama.com/connect?name=MacBook&key=public-key&launch=true",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getIntegrationStatuses", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("returns desktop and launcher integration metadata", async () => {
|
||||
const fetch = vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify([
|
||||
{
|
||||
id: "claude-desktop",
|
||||
name: "Claude",
|
||||
description: "Use Ollama models in Claude Desktop",
|
||||
installed: true,
|
||||
},
|
||||
{
|
||||
id: "opencode",
|
||||
name: "OpenCode",
|
||||
description: "Open-source coding agent",
|
||||
command: "ollama launch opencode",
|
||||
},
|
||||
]),
|
||||
{ status: 200 },
|
||||
),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
|
||||
await expect(getIntegrationStatuses()).resolves.toEqual([
|
||||
{
|
||||
id: "claude-desktop",
|
||||
name: "Claude",
|
||||
description: "Use Ollama models in Claude Desktop",
|
||||
installed: true,
|
||||
},
|
||||
{
|
||||
id: "opencode",
|
||||
name: "OpenCode",
|
||||
description: "Open-source coding agent",
|
||||
command: "ollama launch opencode",
|
||||
},
|
||||
]);
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"http://127.0.0.1:3001/api/v1/integrations",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getClaudeDesktopAvailableModels", () => {
|
||||
afterEach(() => {
|
||||
listModels.mockReset();
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("returns installed local models while pruning remote entries", async () => {
|
||||
listModels.mockResolvedValue({
|
||||
models: [
|
||||
{ name: "llama3.2:latest", digest: "local" },
|
||||
{
|
||||
name: "remote-placeholder",
|
||||
digest: "remote",
|
||||
remote_host: "https://ollama.com",
|
||||
},
|
||||
],
|
||||
});
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
|
||||
const models = await getClaudeDesktopAvailableModels();
|
||||
|
||||
expect(models.map((model) => model.model)).toEqual(["llama3.2"]);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not request cloud models when they are unavailable to the user", async () => {
|
||||
listModels.mockResolvedValue({
|
||||
models: [
|
||||
{ name: "qwen3:8b", digest: "local" },
|
||||
{ name: "deepseek-v4-flash:cloud", digest: "cached-cloud" },
|
||||
{ name: "gemma4:31b-cloud", digest: "legacy-cached-cloud" },
|
||||
],
|
||||
});
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
|
||||
const models = await getClaudeDesktopAvailableModels();
|
||||
|
||||
expect(models.map((model) => model.model)).toEqual(["qwen3:8b"]);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not use the global cloud model list", async () => {
|
||||
listModels.mockResolvedValue({
|
||||
models: [{ name: "qwen3:8b", digest: "local" }],
|
||||
});
|
||||
const fetch = vi.fn().mockRejectedValue(new Error("offline"));
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
|
||||
const models = await getClaudeDesktopAvailableModels();
|
||||
|
||||
expect(models.map((model) => model.model)).toEqual(["qwen3:8b"]);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -32,24 +32,6 @@ export interface CloudStatusResponse {
|
||||
disabled: boolean;
|
||||
source: CloudStatusSource;
|
||||
}
|
||||
|
||||
export interface IntegrationStatus {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
installed?: boolean;
|
||||
command?: string;
|
||||
}
|
||||
|
||||
export type IntegrationStatuses = IntegrationStatus[];
|
||||
|
||||
export async function getIntegrationStatuses(): Promise<IntegrationStatuses> {
|
||||
const response = await fetch(`${API_BASE}/api/v1/integrations`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch integration statuses: ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
// Helper function to convert Uint8Array to base64
|
||||
function uint8ArrayToBase64(uint8Array: Uint8Array): string {
|
||||
const chunkSize = 0x8000; // 32KB chunks to avoid stack overflow
|
||||
@@ -99,9 +81,7 @@ export async function fetchConnectUrl(): Promise<string> {
|
||||
if (response.status === 401) {
|
||||
const data = await response.json();
|
||||
if (data.signin_url) {
|
||||
const connectUrl = new URL(data.signin_url);
|
||||
connectUrl.searchParams.set("launch", "true");
|
||||
return connectUrl.toString();
|
||||
return data.signin_url;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,53 +176,6 @@ export async function getModels(query?: string): Promise<Model[]> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function getClaudeDesktopAvailableModels(): Promise<Model[]> {
|
||||
try {
|
||||
const { models: modelsResponse } = await ollama.list();
|
||||
|
||||
const seen = new Set<string>();
|
||||
return modelsResponse
|
||||
.filter((model: ModelResponse) => {
|
||||
const response = model as ModelResponse & {
|
||||
remote_model?: string;
|
||||
remote_host?: string;
|
||||
};
|
||||
const name = model.name.replace(/:latest$/, "");
|
||||
return (
|
||||
!response.remote_model &&
|
||||
!response.remote_host &&
|
||||
!name.endsWith("cloud")
|
||||
);
|
||||
})
|
||||
.filter((model: ModelResponse) => {
|
||||
const base = model.name.replace(/:latest$/, "");
|
||||
if (!base || seen.has(base)) return false;
|
||||
|
||||
const families = model.details?.families;
|
||||
const supported =
|
||||
!families ||
|
||||
families.length === 0 ||
|
||||
!families.every((family: string) =>
|
||||
family.toLowerCase().includes("bert"),
|
||||
);
|
||||
if (supported) seen.add(base);
|
||||
return supported;
|
||||
})
|
||||
.map(
|
||||
(model: ModelResponse) =>
|
||||
new Model({
|
||||
model: model.name.replace(/:latest$/, ""),
|
||||
digest: model.digest,
|
||||
modified_at: model.modified_at
|
||||
? new Date(model.modified_at)
|
||||
: undefined,
|
||||
}),
|
||||
);
|
||||
} catch (err) {
|
||||
throw new Error(`Failed to fetch Ollama models: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getModelCapabilities(
|
||||
modelName: string,
|
||||
): Promise<ModelCapabilitiesResponse> {
|
||||
@@ -485,9 +418,7 @@ export interface ModelRecommendationsResponse {
|
||||
recommendations: ModelRecommendation[];
|
||||
}
|
||||
|
||||
export async function getModelRecommendations(): Promise<
|
||||
ModelRecommendation[]
|
||||
> {
|
||||
export async function getModelRecommendations(): Promise<ModelRecommendation[]> {
|
||||
const response = await fetch(
|
||||
`${API_BASE}/api/experimental/model-recommendations`,
|
||||
);
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
import { Link } from "@/components/ui/link";
|
||||
import { ChatIcon } from "@/components/ChatIcon";
|
||||
import { Cog6ToothIcon, RectangleGroupIcon } from "@heroicons/react/24/outline";
|
||||
|
||||
type AppSection = "apps" | "chat" | "settings";
|
||||
|
||||
export function AppNavigation({ current }: { current: AppSection }) {
|
||||
const itemClass = (section: AppSection) =>
|
||||
`flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left text-sm text-neutral-700 hover:bg-neutral-100 dark:text-neutral-100 dark:hover:bg-neutral-800 ${
|
||||
current === section ? "bg-neutral-100 dark:bg-neutral-800" : ""
|
||||
}`;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Link to="/connect" className={itemClass("apps")} draggable={false}>
|
||||
<RectangleGroupIcon className="h-5 w-5 stroke-current" />
|
||||
<span className="truncate">Apps</span>
|
||||
</Link>
|
||||
<Link
|
||||
to="/c/$chatId"
|
||||
params={{ chatId: "new" }}
|
||||
mask={{ to: "/" }}
|
||||
className={itemClass("chat")}
|
||||
draggable={false}
|
||||
>
|
||||
<ChatIcon />
|
||||
<span className="truncate">Chat</span>
|
||||
</Link>
|
||||
<Link to="/settings" className={itemClass("settings")} draggable={false}>
|
||||
<Cog6ToothIcon className="h-5 w-5 stroke-current" />
|
||||
<span className="truncate">Settings</span>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AppSidebar({ current }: { current: AppSection }) {
|
||||
return (
|
||||
<nav className="flex flex-1 flex-col px-4 pb-4 select-none">
|
||||
<AppNavigation current={current} />
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
export function ChatIcon({ className = "h-5 w-5" }: { className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className={`${className} fill-current`}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="M17.0859 3.39949L15.2135 5.27196H7.27028C5.78649 5.27196 4.94684 6.11336 4.94684 7.59716V16.664C4.94684 18.1558 5.78649 18.9892 7.27028 18.9892H16.3406C17.8324 18.9892 18.6623 18.1558 18.6623 16.664V8.79514L20.5428 6.9115C20.567 7.11532 20.5773 7.33066 20.5773 7.55419V16.7149C20.5773 19.4069 19.0818 20.9024 16.3898 20.9024H7.22107C4.53708 20.9024 3.03357 19.4069 3.03357 16.7149V7.55419C3.03357 4.8622 4.53708 3.35869 7.22107 3.35869H16.3898C16.6329 3.35869 16.8662 3.37094 17.0859 3.39949Z" />
|
||||
<path d="M9.92714 14.381L11.914 13.5403L20.8312 4.63114L19.3404 3.1581L10.433 12.0655L9.55234 13.9964C9.45664 14.2169 9.70293 14.4714 9.92714 14.381ZM21.5767 3.89364L22.2588 3.19384C22.6347 2.80184 22.6435 2.2663 22.2711 1.90536L22.0148 1.64287C21.6822 1.31377 21.1334 1.36513 20.7689 1.72158L20.0859 2.39833L21.5767 3.89364Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -6,12 +6,14 @@ import { getChat } from "@/api";
|
||||
import { Link } from "@/components/ui/link";
|
||||
import { useState, useRef, useEffect, useCallback, useMemo } from "react";
|
||||
import { ChatsResponse } from "@/gotypes";
|
||||
import { AppNavigation } from "@/components/AppSidebar";
|
||||
import { CogIcon, RocketLaunchIcon } from "@heroicons/react/24/outline";
|
||||
|
||||
// there's a hidden debug feature to copy a chat's data to the clipboard by
|
||||
// holding shift and clicking this many times within this many seconds
|
||||
const DEBUG_SHIFT_CLICKS_REQUIRED = 5;
|
||||
const DEBUG_SHIFT_CLICK_WINDOW_MS = 7000; // 7 seconds
|
||||
const launchSidebarRequestedKey = "ollama.launchSidebarRequested";
|
||||
|
||||
interface ChatSidebarProps {
|
||||
currentChatId?: string;
|
||||
}
|
||||
@@ -258,10 +260,56 @@ export function ChatSidebar({ currentChatId }: ChatSidebarProps) {
|
||||
);
|
||||
}
|
||||
|
||||
const isWindows = navigator.platform.toLowerCase().includes("win");
|
||||
|
||||
return (
|
||||
<nav className="flex flex-1 flex-col min-h-0 select-none">
|
||||
<header className="flex flex-col gap-0.5 px-4 pb-2">
|
||||
<AppNavigation current="chat" />
|
||||
<Link
|
||||
href="/c/new"
|
||||
mask={{ to: "/" }}
|
||||
className={`flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left text-sm text-neutral-700 hover:bg-neutral-100 dark:hover:bg-neutral-800 dark:text-neutral-100 ${currentChatId === "new" ? "bg-neutral-100 dark:bg-neutral-800" : ""
|
||||
}`}
|
||||
draggable={false}
|
||||
>
|
||||
<svg
|
||||
className="h-5 w-5 fill-current"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="M17.0859 3.39949L15.2135 5.27196H7.27028C5.78649 5.27196 4.94684 6.11336 4.94684 7.59716V16.664C4.94684 18.1558 5.78649 18.9892 7.27028 18.9892H16.3406C17.8324 18.9892 18.6623 18.1558 18.6623 16.664V8.79514L20.5428 6.9115C20.567 7.11532 20.5773 7.33066 20.5773 7.55419V16.7149C20.5773 19.4069 19.0818 20.9024 16.3898 20.9024H7.22107C4.53708 20.9024 3.03357 19.4069 3.03357 16.7149V7.55419C3.03357 4.8622 4.53708 3.35869 7.22107 3.35869H16.3898C16.6329 3.35869 16.8662 3.37094 17.0859 3.39949Z" />
|
||||
<path d="M9.92714 14.381L11.914 13.5403L20.8312 4.63114L19.3404 3.1581L10.433 12.0655L9.55234 13.9964C9.45664 14.2169 9.70293 14.4714 9.92714 14.381ZM21.5767 3.89364L22.2588 3.19384C22.6347 2.80184 22.6435 2.2663 22.2711 1.90536L22.0148 1.64287C21.6822 1.31377 21.1334 1.36513 20.7689 1.72158L20.0859 2.39833L21.5767 3.89364Z" />
|
||||
</svg>
|
||||
<span className="truncate">New Chat</span>
|
||||
</Link>
|
||||
<Link
|
||||
to="/c/$chatId"
|
||||
params={{ chatId: "launch" }}
|
||||
onClick={() => {
|
||||
if (currentChatId !== "launch") {
|
||||
sessionStorage.setItem(launchSidebarRequestedKey, "1");
|
||||
}
|
||||
}}
|
||||
className={`flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left text-sm text-neutral-700 hover:bg-neutral-100 dark:hover:bg-neutral-800 dark:text-neutral-100 cursor-pointer ${currentChatId === "launch"
|
||||
? "bg-neutral-100 dark:bg-neutral-800"
|
||||
: ""
|
||||
}`}
|
||||
draggable={false}
|
||||
>
|
||||
<RocketLaunchIcon className="h-5 w-5 stroke-current" />
|
||||
<span className="truncate">Launch</span>
|
||||
</Link>
|
||||
{isWindows && (
|
||||
<Link
|
||||
href="/settings"
|
||||
className={`flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left text-sm text-neutral-700 hover:bg-neutral-100 dark:hover:bg-neutral-800 dark:text-neutral-300`}
|
||||
draggable={false}
|
||||
>
|
||||
<CogIcon className="h-5 w-5 stroke-current" />
|
||||
<span className="truncate">Settings</span>
|
||||
</Link>
|
||||
)}
|
||||
</header>
|
||||
<div className="flex flex-1 flex-col px-4 py-1 overflow-y-auto overscroll-auto scrollbar-gutter">
|
||||
<div className="flex flex-col gap-3 pt-4">
|
||||
@@ -273,19 +321,18 @@ export function ChatSidebar({ currentChatId }: ChatSidebarProps) {
|
||||
{group.chats.map((chat) => (
|
||||
<div
|
||||
key={chat.id}
|
||||
className={`allow-context-menu flex items-center relative text-sm text-neutral-800 dark:text-neutral-400 rounded-lg hover:bg-neutral-100 dark:hover:bg-neutral-800 ${
|
||||
chat.id === currentChatId
|
||||
? "bg-neutral-100 text-black dark:bg-neutral-800"
|
||||
: ""
|
||||
}`}
|
||||
className={`allow-context-menu flex items-center relative text-sm text-neutral-800 dark:text-neutral-400 rounded-lg hover:bg-neutral-100 dark:hover:bg-neutral-800 ${chat.id === currentChatId
|
||||
? "bg-neutral-100 text-black dark:bg-neutral-800"
|
||||
: ""
|
||||
}`}
|
||||
onMouseEnter={() => handleMouseEnter(chat.id)}
|
||||
onContextMenu={(e) =>
|
||||
handleContextMenu(
|
||||
e,
|
||||
chat.id,
|
||||
chat.title ||
|
||||
chat.userExcerpt ||
|
||||
chat.createdAt.toLocaleString(),
|
||||
chat.userExcerpt ||
|
||||
chat.createdAt.toLocaleString(),
|
||||
)
|
||||
}
|
||||
>
|
||||
|
||||
@@ -1,424 +0,0 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ClaudeDesktopModelsSettings } from "./ClaudeDesktopModelsSettings";
|
||||
|
||||
describe("ClaudeDesktopModelsSettings", () => {
|
||||
it("shows Claude recommendations and an installed-model search in Settings", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ClaudeDesktopModelsSettings
|
||||
initialLocalModels={["llama3.2", "qwen3:8b"]}
|
||||
initialStatus={{
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
connected: true,
|
||||
running: false,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
modelSource: "endpoint",
|
||||
models: [
|
||||
{
|
||||
name: "glm-5.2:cloud",
|
||||
displayName: "glm-5.2:cloud",
|
||||
cloud: true,
|
||||
selected: true,
|
||||
},
|
||||
{
|
||||
name: "deepseek-v4-flash:cloud",
|
||||
displayName: "deepseek-v4-flash:cloud",
|
||||
cloud: true,
|
||||
selected: false,
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain(">Claude<");
|
||||
expect(html).toContain(">Apps<");
|
||||
expect(html).toContain('id="apps-settings-heading"');
|
||||
expect(html).toContain('src="/launch-icons/claude.svg"');
|
||||
expect(html).not.toContain("Models in Claude");
|
||||
expect(html).toContain("glm-5.2:cloud");
|
||||
expect(html).toContain("deepseek-v4-flash:cloud");
|
||||
expect(html).toContain("Search Ollama models");
|
||||
expect(html).not.toContain("Add any Ollama model");
|
||||
expect(html).toContain("Restart Claude");
|
||||
expect((html.match(/checked=""/g) ?? []).length).toBe(2);
|
||||
});
|
||||
|
||||
it("does not show the invalid Ollama Cloud sentinel", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ClaudeDesktopModelsSettings
|
||||
initialStatus={{
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
connected: true,
|
||||
running: false,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
modelSource: "user",
|
||||
models: [
|
||||
{
|
||||
name: "Ollama Cloud",
|
||||
displayName: "Ollama Cloud",
|
||||
selected: true,
|
||||
},
|
||||
{
|
||||
name: "qwen3:8b",
|
||||
displayName: "qwen3:8b",
|
||||
selected: true,
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).not.toContain("Ollama Cloud");
|
||||
expect(html).toContain("qwen3:8b");
|
||||
});
|
||||
|
||||
it("labels the built-in fallback without exposing MLX", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ClaudeDesktopModelsSettings
|
||||
initialStatus={{
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
connected: true,
|
||||
running: false,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
modelSource: "fallback",
|
||||
models: [
|
||||
{
|
||||
name: "deepseek-v4-flash:0731:cloud",
|
||||
displayName: "deepseek-v4-flash:0731:cloud",
|
||||
cloud: true,
|
||||
selected: true,
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Built-in defaults");
|
||||
expect(html).toContain("deepseek-v4-flash:0731:cloud");
|
||||
expect(html).not.toContain("MLX");
|
||||
});
|
||||
|
||||
it("prevents a sixth selection when the literal Claude slots are full", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ClaudeDesktopModelsSettings
|
||||
initialStatus={{
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
connected: true,
|
||||
running: false,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
modelSource: "endpoint",
|
||||
maxModels: 5,
|
||||
models: [
|
||||
{
|
||||
name: "glm-5.2:cloud",
|
||||
displayName: "glm-5.2:cloud",
|
||||
cloud: true,
|
||||
selected: true,
|
||||
},
|
||||
{
|
||||
name: "kimi-k3:cloud",
|
||||
displayName: "kimi-k3:cloud",
|
||||
cloud: true,
|
||||
selected: true,
|
||||
},
|
||||
{
|
||||
name: "deepseek-v4-pro:cloud",
|
||||
displayName: "deepseek-v4-pro:cloud",
|
||||
cloud: true,
|
||||
selected: true,
|
||||
},
|
||||
{
|
||||
name: "deepseek-v4-flash:cloud",
|
||||
displayName: "deepseek-v4-flash:cloud",
|
||||
cloud: true,
|
||||
selected: true,
|
||||
},
|
||||
{
|
||||
name: "gemma4:26b:cloud",
|
||||
displayName: "gemma4:26b:cloud",
|
||||
cloud: true,
|
||||
selected: true,
|
||||
},
|
||||
{
|
||||
name: "qwen3:8b",
|
||||
displayName: "qwen3:8b",
|
||||
selected: false,
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
const index = html.indexOf(">qwen3:8b</span>");
|
||||
expect(index).toBeGreaterThan(-1);
|
||||
const label = html.slice(html.lastIndexOf("<label", index), index);
|
||||
expect(label).toContain("disabled");
|
||||
expect((html.match(/disabled=""/g) ?? []).length).toBe(1);
|
||||
expect(html).toContain(
|
||||
"Claude supports up to 5 models. Deselect one to add another.",
|
||||
);
|
||||
});
|
||||
|
||||
it("honors a smaller maxModels limit from the status", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ClaudeDesktopModelsSettings
|
||||
initialStatus={{
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
connected: true,
|
||||
running: false,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
modelSource: "endpoint",
|
||||
maxModels: 1,
|
||||
models: [
|
||||
{
|
||||
name: "kimi-k3:cloud",
|
||||
displayName: "kimi-k3:cloud",
|
||||
cloud: true,
|
||||
selected: true,
|
||||
},
|
||||
{
|
||||
name: "qwen3:8b",
|
||||
displayName: "qwen3:8b",
|
||||
selected: false,
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
const index = html.indexOf(">qwen3:8b</span>");
|
||||
expect(index).toBeGreaterThan(-1);
|
||||
const label = html.slice(html.lastIndexOf("<label", index), index);
|
||||
expect(label).toContain("disabled");
|
||||
});
|
||||
|
||||
it("hides recommendation and selected cloud models when cloud is disabled", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ClaudeDesktopModelsSettings
|
||||
initialLocalModels={["qwen3:8b"]}
|
||||
initialStatus={{
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
connected: false,
|
||||
running: false,
|
||||
startFailed: true,
|
||||
portConflict: false,
|
||||
error: "Cloud models are off. Select an installed model in Settings.",
|
||||
modelSource: "endpoint",
|
||||
models: [
|
||||
{
|
||||
name: "glm-5.2:cloud",
|
||||
displayName: "glm-5.2:cloud",
|
||||
cloud: true,
|
||||
selected: true,
|
||||
availability: "unavailable",
|
||||
reason: "cloud_off",
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).not.toContain("glm-5.2:cloud");
|
||||
expect(html).toContain("Search Ollama models");
|
||||
expect(html).toContain(
|
||||
"Cloud models are off. Select an installed model in Settings.",
|
||||
);
|
||||
expect(html).not.toContain(
|
||||
"These models will be available when Claude starts.",
|
||||
);
|
||||
expect(html).not.toContain("text-red");
|
||||
});
|
||||
|
||||
it("shows account requirements and prevents selecting unavailable models", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ClaudeDesktopModelsSettings
|
||||
initialStatus={{
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
connected: true,
|
||||
running: false,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
modelSource: "endpoint",
|
||||
models: [
|
||||
{
|
||||
name: "glm-5.2:cloud",
|
||||
displayName: "glm-5.2:cloud",
|
||||
cloud: true,
|
||||
selected: false,
|
||||
availability: "unavailable",
|
||||
reason: "upgrade_required",
|
||||
requiredPlan: "pro",
|
||||
},
|
||||
{
|
||||
name: "gemma4:31b-cloud",
|
||||
displayName: "gemma4:31b-cloud",
|
||||
cloud: true,
|
||||
selected: true,
|
||||
availability: "available",
|
||||
requiredPlan: "free",
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("pro plan required");
|
||||
const index = html.indexOf(">glm-5.2:cloud</span>");
|
||||
const label = html.slice(html.lastIndexOf("<label", index), index);
|
||||
expect(label).toContain("disabled");
|
||||
expect(html).toContain("gemma4:31b-cloud");
|
||||
});
|
||||
|
||||
it("replaces paid defaults with the available free recommendation", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ClaudeDesktopModelsSettings
|
||||
initialStatus={{
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
connected: false,
|
||||
running: false,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
modelSource: "endpoint",
|
||||
models: [
|
||||
"glm-5.2:cloud",
|
||||
"kimi-k3:cloud",
|
||||
"deepseek-v4-pro:cloud",
|
||||
"deepseek-v4-flash:cloud",
|
||||
]
|
||||
.map((name) => ({
|
||||
name,
|
||||
displayName: name,
|
||||
cloud: true,
|
||||
selected: true,
|
||||
availability: "unavailable" as const,
|
||||
reason: "upgrade_required" as const,
|
||||
requiredPlan: "pro",
|
||||
}))
|
||||
.concat([
|
||||
{
|
||||
name: "gemma4:31b-cloud",
|
||||
displayName: "gemma4:31b-cloud",
|
||||
cloud: true,
|
||||
selected: false,
|
||||
availability: "available" as const,
|
||||
requiredPlan: "free",
|
||||
},
|
||||
]),
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect((html.match(/>pro plan required<\/span>/g) ?? []).length).toBe(4);
|
||||
expect((html.match(/checked=""/g) ?? []).length).toBe(1);
|
||||
const gemmaIndex = html.indexOf(">gemma4:31b-cloud</span>");
|
||||
const gemmaInput = html.slice(
|
||||
html.lastIndexOf("<input", gemmaIndex),
|
||||
gemmaIndex,
|
||||
);
|
||||
expect(gemmaInput).toContain('checked=""');
|
||||
expect(html).toContain("Start Claude");
|
||||
});
|
||||
|
||||
it("does not restart Claude when every selected model is unavailable", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ClaudeDesktopModelsSettings
|
||||
initialStatus={{
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
connected: true,
|
||||
running: false,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
modelSource: "endpoint",
|
||||
models: [
|
||||
{
|
||||
name: "glm-5.2:cloud",
|
||||
displayName: "glm-5.2:cloud",
|
||||
cloud: true,
|
||||
selected: true,
|
||||
availability: "unavailable",
|
||||
reason: "upgrade_required",
|
||||
requiredPlan: "pro",
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Select a model available to your account.");
|
||||
const button = html.slice(html.lastIndexOf("<button"));
|
||||
expect(button).toContain("disabled");
|
||||
});
|
||||
|
||||
it("remains visible after Claude has been disconnected", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ClaudeDesktopModelsSettings
|
||||
initialStatus={{
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
connected: false,
|
||||
running: false,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
modelSource: "user",
|
||||
models: [
|
||||
{
|
||||
name: "qwen3:8b",
|
||||
displayName: "qwen3:8b",
|
||||
selected: true,
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain(">Claude<");
|
||||
expect(html).toContain("qwen3:8b");
|
||||
expect(html).toContain(
|
||||
"These models will be available when Claude starts.",
|
||||
);
|
||||
expect(html).toContain("Start Claude");
|
||||
});
|
||||
|
||||
it("stays hidden until Claude has been enabled once", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ClaudeDesktopModelsSettings
|
||||
initialStatus={{
|
||||
supported: true,
|
||||
used: false,
|
||||
installed: true,
|
||||
connected: false,
|
||||
running: false,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -1,420 +0,0 @@
|
||||
import { getClaudeDesktopAvailableModels } from "@/api";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
addClaudeModelSelection,
|
||||
claudeDesktopRecoveryMessage,
|
||||
claudeDesktopMaxModels,
|
||||
claudeDesktopMaxModelsMessage,
|
||||
claudeDesktopUsableSelection,
|
||||
} from "@/lib/claudeDesktop";
|
||||
import type {
|
||||
ClaudeDesktopModelStatus,
|
||||
ClaudeDesktopStatus,
|
||||
} from "@/types/webview";
|
||||
import { ArrowPathIcon } from "@heroicons/react/20/solid";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
interface ClaudeDesktopModelsSettingsProps {
|
||||
initialStatus?: ClaudeDesktopStatus;
|
||||
initialLocalModels?: string[];
|
||||
}
|
||||
|
||||
function isInvalidModelName(name: string): boolean {
|
||||
const normalized = name.trim().toLowerCase().replace(/[-:]+/g, " ");
|
||||
return normalized === "ollama cloud";
|
||||
}
|
||||
|
||||
function visibleModels(
|
||||
status: ClaudeDesktopStatus,
|
||||
): ClaudeDesktopModelStatus[] {
|
||||
return (status.models ?? []).filter(
|
||||
(model) => !isInvalidModelName(model.name) && model.reason !== "cloud_off",
|
||||
);
|
||||
}
|
||||
|
||||
function selectedModelNames(status: ClaudeDesktopStatus): string[] {
|
||||
return claudeDesktopUsableSelection(
|
||||
visibleModels(status),
|
||||
status.modelSource !== "user",
|
||||
claudeDesktopMaxModels(status),
|
||||
);
|
||||
}
|
||||
|
||||
function modelAccessLabel(model: ClaudeDesktopModelStatus): string | null {
|
||||
switch (model.reason) {
|
||||
case "sign_in_required":
|
||||
return "Sign in required";
|
||||
case "upgrade_required":
|
||||
return model.requiredPlan
|
||||
? `${model.requiredPlan} plan required`
|
||||
: "Upgrade required";
|
||||
case "verification_unavailable":
|
||||
return "Access unavailable";
|
||||
case "model_not_installed":
|
||||
return "Not installed";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function explicitCloudName(name: string): string {
|
||||
return name.endsWith(":cloud") ? name : `${name}:cloud`;
|
||||
}
|
||||
|
||||
export function ClaudeDesktopModelsSettings({
|
||||
initialStatus,
|
||||
initialLocalModels,
|
||||
}: ClaudeDesktopModelsSettingsProps) {
|
||||
const [status, setStatus] = useState<ClaudeDesktopStatus | null>(
|
||||
initialStatus ?? null,
|
||||
);
|
||||
const [models, setModels] = useState<ClaudeDesktopModelStatus[]>(() =>
|
||||
initialStatus ? visibleModels(initialStatus) : [],
|
||||
);
|
||||
const [selection, setSelection] = useState<string[]>(() =>
|
||||
initialStatus ? selectedModelNames(initialStatus) : [],
|
||||
);
|
||||
const [localModels, setLocalModels] = useState<string[]>(
|
||||
initialLocalModels ?? [],
|
||||
);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
const [modelsLoading, setModelsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [restarting, setRestarting] = useState(false);
|
||||
const pickerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const applyStatus = useCallback((next: ClaudeDesktopStatus) => {
|
||||
setStatus(next);
|
||||
setModels(visibleModels(next));
|
||||
setSelection(selectedModelNames(next));
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
const refreshStatus = useCallback(async () => {
|
||||
if (!window.getClaudeDesktopStatus) return;
|
||||
try {
|
||||
applyStatus(await window.getClaudeDesktopStatus());
|
||||
} catch {
|
||||
setError("Ollama could not read the Claude connection status.");
|
||||
}
|
||||
}, [applyStatus]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialStatus) void refreshStatus();
|
||||
const handleFocus = () => void refreshStatus();
|
||||
window.addEventListener("focus", handleFocus);
|
||||
return () => window.removeEventListener("focus", handleFocus);
|
||||
}, [initialStatus, refreshStatus]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!status) return;
|
||||
setModels(visibleModels(status));
|
||||
setSelection(selectedModelNames(status));
|
||||
}, [status]);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialLocalModels || !status?.used) return;
|
||||
let cancelled = false;
|
||||
setModelsLoading(true);
|
||||
void getClaudeDesktopAvailableModels()
|
||||
.then((installed) => {
|
||||
if (!cancelled) {
|
||||
setLocalModels(installed.map((model) => model.model));
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setError("Ollama could not load your models.");
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setModelsLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [initialLocalModels, status?.used]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (
|
||||
pickerRef.current &&
|
||||
!pickerRef.current.contains(event.target as Node)
|
||||
) {
|
||||
setPickerOpen(false);
|
||||
}
|
||||
};
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, []);
|
||||
|
||||
const matchingLocalModels = useMemo(() => {
|
||||
const current = new Set(
|
||||
models.map((model) =>
|
||||
model.cloud ? explicitCloudName(model.name) : model.name,
|
||||
),
|
||||
);
|
||||
const query = searchQuery.trim().toLowerCase();
|
||||
return localModels
|
||||
.filter(
|
||||
(name) =>
|
||||
!current.has(name) &&
|
||||
!isInvalidModelName(name) &&
|
||||
(!query || name.toLowerCase().includes(query)),
|
||||
)
|
||||
.sort((left, right) => left.localeCompare(right));
|
||||
}, [localModels, models, searchQuery]);
|
||||
|
||||
const toggleModel = (name: string) => {
|
||||
setError(null);
|
||||
setSelection((current) => {
|
||||
if (!current.includes(name)) {
|
||||
const result = addClaudeModelSelection(
|
||||
current,
|
||||
name,
|
||||
claudeDesktopMaxModels(status),
|
||||
);
|
||||
if (result.error) {
|
||||
setError(result.error);
|
||||
return current;
|
||||
}
|
||||
return result.selection;
|
||||
}
|
||||
if (current.length === 1) {
|
||||
setError("Select at least one model for Claude.");
|
||||
return current;
|
||||
}
|
||||
return current.filter((model) => model !== name);
|
||||
});
|
||||
};
|
||||
|
||||
const addLocalModel = (name: string) => {
|
||||
const maxModels = claudeDesktopMaxModels(status);
|
||||
const result = addClaudeModelSelection(selection, name, maxModels);
|
||||
if (result.error) {
|
||||
setError(result.error);
|
||||
return;
|
||||
}
|
||||
const cloud = name.endsWith(":cloud");
|
||||
setModels((current) => [
|
||||
...current,
|
||||
{
|
||||
name,
|
||||
displayName: name,
|
||||
cloud,
|
||||
selected: true,
|
||||
availability: "available",
|
||||
},
|
||||
]);
|
||||
setSelection(result.selection);
|
||||
setSearchQuery("");
|
||||
setPickerOpen(false);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const hasAvailableSelection = selection.some((name) => {
|
||||
const model = models.find((candidate) => candidate.name === name);
|
||||
return !model?.availability || model.availability === "available";
|
||||
});
|
||||
|
||||
const restartClaude = async () => {
|
||||
if (!window.restartClaudeDesktop) {
|
||||
setError("Claude restart is available in the Ollama macOS app.");
|
||||
return;
|
||||
}
|
||||
if (selection.length === 0) {
|
||||
setError("Select at least one model for Claude.");
|
||||
return;
|
||||
}
|
||||
if (!hasAvailableSelection) {
|
||||
setError("Select a model available to your account.");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
status?.running &&
|
||||
!window.confirm(
|
||||
"Restart Claude Desktop to update its models? Any running task will stop.",
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
setRestarting(true);
|
||||
try {
|
||||
const result = await window.restartClaudeDesktop(selection);
|
||||
applyStatus(result.status);
|
||||
if (result.error) setError(result.error);
|
||||
} catch {
|
||||
setError("Ollama could not restart Claude.");
|
||||
} finally {
|
||||
setRestarting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!status?.supported || !status.used) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const maxModels = claudeDesktopMaxModels(status);
|
||||
const selectionFull = selection.length >= maxModels;
|
||||
const guidance =
|
||||
claudeDesktopRecoveryMessage(status.error, error) ??
|
||||
(!hasAvailableSelection && models.length > 0
|
||||
? "Select a model available to your account."
|
||||
: selectionFull
|
||||
? claudeDesktopMaxModelsMessage(maxModels)
|
||||
: status.connected
|
||||
? "Restart Claude to refresh its model list."
|
||||
: "These models will be available when Claude starts.");
|
||||
|
||||
return (
|
||||
<section aria-labelledby="apps-settings-heading" className="space-y-2">
|
||||
<h2
|
||||
id="apps-settings-heading"
|
||||
className="px-1 text-xs font-medium uppercase tracking-wider text-neutral-400 dark:text-neutral-500"
|
||||
>
|
||||
Apps
|
||||
</h2>
|
||||
<div
|
||||
aria-labelledby="claude-models-settings-heading"
|
||||
className="overflow-visible rounded-xl bg-white p-4 dark:bg-neutral-800"
|
||||
>
|
||||
<div className="flex items-start space-x-3">
|
||||
<img
|
||||
src="/launch-icons/claude.svg"
|
||||
alt=""
|
||||
className="mt-0.5 h-5 w-5 flex-shrink-0"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2
|
||||
id="claude-models-settings-heading"
|
||||
className="text-sm font-medium text-neutral-900 dark:text-white"
|
||||
>
|
||||
Claude
|
||||
</h2>
|
||||
{status.modelSource === "fallback" && models.length > 0 && (
|
||||
<span className="text-xs text-neutral-400">
|
||||
Built-in defaults
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-3 grid grid-cols-2 gap-x-5 gap-y-2 max-[850px]:grid-cols-1">
|
||||
{models.map((model) => {
|
||||
const selected = selection.includes(model.name);
|
||||
const accessLabel = modelAccessLabel(model);
|
||||
const unavailable =
|
||||
model.availability !== undefined &&
|
||||
model.availability !== "available";
|
||||
return (
|
||||
<label
|
||||
key={model.name}
|
||||
className="flex min-w-0 cursor-pointer items-center gap-2 rounded-md py-1 text-sm text-neutral-600 dark:text-neutral-300"
|
||||
title={accessLabel ?? model.description}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected}
|
||||
disabled={
|
||||
restarting ||
|
||||
(!selected && (selectionFull || unavailable))
|
||||
}
|
||||
onChange={() => toggleModel(model.name)}
|
||||
className="h-4 w-4 rounded border-neutral-300 accent-neutral-900 dark:border-neutral-600 dark:accent-white"
|
||||
/>
|
||||
<span className="truncate">{model.displayName}</span>
|
||||
{accessLabel && (
|
||||
<span className="flex-shrink-0 text-xs text-neutral-400">
|
||||
{accessLabel}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div ref={pickerRef} className="relative mt-3">
|
||||
<Input
|
||||
type="search"
|
||||
value={searchQuery}
|
||||
onFocus={() => setPickerOpen(true)}
|
||||
onChange={(event) => {
|
||||
setSearchQuery(event.target.value);
|
||||
setPickerOpen(true);
|
||||
}}
|
||||
placeholder="Search Ollama models"
|
||||
aria-label="Search Ollama models"
|
||||
aria-expanded={pickerOpen}
|
||||
aria-controls="claude-local-models"
|
||||
disabled={restarting}
|
||||
autoComplete="off"
|
||||
/>
|
||||
{pickerOpen && (
|
||||
<div
|
||||
id="claude-local-models"
|
||||
className="absolute z-20 mt-1 max-h-52 w-full overflow-y-auto rounded-lg border border-neutral-200 bg-white p-1 shadow-lg dark:border-neutral-600 dark:bg-neutral-800"
|
||||
>
|
||||
{modelsLoading ? (
|
||||
<p className="px-3 py-2 text-sm text-neutral-400">
|
||||
Loading models…
|
||||
</p>
|
||||
) : selectionFull ? (
|
||||
<p className="px-3 py-2 text-sm text-neutral-400">
|
||||
{claudeDesktopMaxModelsMessage(maxModels)}
|
||||
</p>
|
||||
) : matchingLocalModels.length > 0 ? (
|
||||
matchingLocalModels.map((name) => (
|
||||
<button
|
||||
key={name}
|
||||
type="button"
|
||||
onClick={() => addLocalModel(name)}
|
||||
className="block w-full rounded-md px-3 py-2 text-left text-sm text-neutral-700 hover:bg-neutral-100 dark:text-neutral-200 dark:hover:bg-neutral-700"
|
||||
>
|
||||
{name}
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<p className="px-3 py-2 text-sm text-neutral-400">
|
||||
No models found.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex items-center justify-between gap-4 max-sm:flex-col max-sm:items-stretch">
|
||||
<p
|
||||
role={error || status.error ? "alert" : undefined}
|
||||
className="text-xs leading-5 text-neutral-500 dark:text-neutral-400"
|
||||
>
|
||||
{guidance}
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
color="white"
|
||||
onClick={restartClaude}
|
||||
disabled={
|
||||
restarting || selection.length === 0 || !hasAvailableSelection
|
||||
}
|
||||
className="flex-shrink-0 max-sm:w-full"
|
||||
>
|
||||
{restarting && (
|
||||
<ArrowPathIcon data-slot="icon" className="animate-spin" />
|
||||
)}
|
||||
{restarting
|
||||
? status.connected
|
||||
? "Restarting…"
|
||||
: "Starting…"
|
||||
: status.connected
|
||||
? "Restart Claude"
|
||||
: "Start Claude"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -68,7 +68,7 @@ const CopyButton: React.FC<CopyButtonProps> = ({
|
||||
const iconSize = size === "sm" ? "h-3 w-3" : "h-7 w-7";
|
||||
const baseClasses =
|
||||
size === "sm"
|
||||
? `text-xs px-4 py-2 z-10 cursor-pointer rounded-lg ${className}`
|
||||
? `text-xs px-4 py-2 z-10 rounded-lg hover:cursor-pointer ${className}`
|
||||
: `${iconSize} px-1 py-0.5 text-xs cursor-pointer rounded-lg hover:bg-neutral-100 dark:hover:bg-neutral-800 flex items-center justify-center ${className}`;
|
||||
|
||||
const icon = isCopied ? (
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { useSettings } from "@/hooks/useSettings";
|
||||
import CopyButton from "@/components/CopyButton";
|
||||
|
||||
interface LaunchCommand {
|
||||
id: string;
|
||||
name: string;
|
||||
command: string;
|
||||
description: string;
|
||||
icon: string;
|
||||
darkIcon?: string;
|
||||
iconClassName?: string;
|
||||
borderless?: boolean;
|
||||
}
|
||||
|
||||
const LAUNCH_COMMANDS: LaunchCommand[] = [
|
||||
{
|
||||
id: "claude",
|
||||
name: "Claude Code",
|
||||
command: "ollama launch claude",
|
||||
description: "Anthropic's coding tool with subagents",
|
||||
icon: "/launch-icons/claude-code.svg",
|
||||
iconClassName: "h-7 w-7",
|
||||
},
|
||||
{
|
||||
id: "codex-app",
|
||||
name: "Codex App",
|
||||
command: "ollama launch codex-app",
|
||||
description: "An AI agent you can delegate real work to, by OpenAI",
|
||||
icon: "/launch-icons/codex-app.png",
|
||||
iconClassName: "h-full w-full",
|
||||
},
|
||||
{
|
||||
id: "hermes",
|
||||
name: "Hermes Agent",
|
||||
command: "ollama launch hermes",
|
||||
description: "Self-improving AI agent built by Nous Research",
|
||||
icon: "/launch-icons/hermes-agent.svg",
|
||||
iconClassName: "h-7 w-7",
|
||||
},
|
||||
{
|
||||
id: "openclaw",
|
||||
name: "OpenClaw",
|
||||
command: "ollama launch openclaw",
|
||||
description: "Personal AI with 100+ skills",
|
||||
icon: "/launch-icons/openclaw.svg",
|
||||
},
|
||||
{
|
||||
id: "opencode",
|
||||
name: "OpenCode",
|
||||
command: "ollama launch opencode",
|
||||
description: "Anomaly's open-source coding agent",
|
||||
icon: "/launch-icons/opencode.svg",
|
||||
iconClassName: "h-7 w-7 rounded",
|
||||
},
|
||||
{
|
||||
id: "codex",
|
||||
name: "Codex",
|
||||
command: "ollama launch codex",
|
||||
description: "OpenAI's open-source coding agent",
|
||||
icon: "/launch-icons/codex.svg",
|
||||
darkIcon: "/launch-icons/codex-dark.svg",
|
||||
iconClassName: "h-7 w-7",
|
||||
},
|
||||
{
|
||||
id: "copilot",
|
||||
name: "Copilot CLI",
|
||||
command: "ollama launch copilot",
|
||||
description: "GitHub's AI coding agent for the terminal",
|
||||
icon: "/launch-icons/copilot.svg",
|
||||
darkIcon: "/launch-icons/copilot-dark.svg",
|
||||
iconClassName: "h-7 w-7",
|
||||
},
|
||||
{
|
||||
id: "droid",
|
||||
name: "Droid",
|
||||
command: "ollama launch droid",
|
||||
description: "Factory's coding agent across terminal and IDEs",
|
||||
icon: "/launch-icons/droid.svg",
|
||||
},
|
||||
{
|
||||
id: "pi",
|
||||
name: "Pi",
|
||||
command: "ollama launch pi",
|
||||
description: "Minimal AI agent toolkit with plugin support",
|
||||
icon: "/launch-icons/pi.svg",
|
||||
darkIcon: "/launch-icons/pi-dark.svg",
|
||||
iconClassName: "h-7 w-7",
|
||||
},
|
||||
];
|
||||
|
||||
export default function LaunchCommands() {
|
||||
const isWindows = navigator.platform.toLowerCase().includes("win");
|
||||
const { setSettings } = useSettings();
|
||||
|
||||
const renderCommandCard = (item: LaunchCommand) => (
|
||||
<div key={item.command} className="w-full text-left">
|
||||
<div className="flex items-start gap-4 sm:gap-5">
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-lg overflow-hidden ${item.borderless ? "" : "border border-neutral-200 bg-white dark:border-neutral-700 dark:bg-neutral-900"}`}
|
||||
>
|
||||
{item.darkIcon ? (
|
||||
<picture>
|
||||
<source srcSet={item.darkIcon} media="(prefers-color-scheme: dark)" />
|
||||
<img src={item.icon} alt="" className={`${item.iconClassName ?? "h-8 w-8"} rounded-sm`} />
|
||||
</picture>
|
||||
) : (
|
||||
<img src={item.icon} alt="" className={item.borderless ? "h-full w-full rounded-xl" : `${item.iconClassName ?? "h-8 w-8"} rounded-sm`} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="text-sm font-medium text-neutral-900 dark:text-neutral-100">
|
||||
{item.name}
|
||||
</span>
|
||||
<p className="mt-0.5 text-xs text-neutral-500 dark:text-neutral-400">
|
||||
{item.description}
|
||||
</p>
|
||||
<div className="mt-2 flex items-center gap-2 rounded-xl border-neutral-200 dark:border-neutral-700 bg-neutral-50 dark:bg-neutral-800 px-3 py-2">
|
||||
<code className="min-w-0 flex-1 truncate text-xs text-neutral-600 dark:text-neutral-300">
|
||||
{item.command}
|
||||
</code>
|
||||
<CopyButton
|
||||
content={item.command}
|
||||
size="md"
|
||||
title="Copy command to clipboard"
|
||||
className="text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-200 hover:bg-neutral-200/60 dark:hover:bg-neutral-700/70"
|
||||
onCopy={() => {
|
||||
setSettings({ LastHomeView: item.id }).catch(() => { });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<main className="flex h-screen w-full flex-col relative">
|
||||
<section
|
||||
className={`flex-1 overflow-y-auto overscroll-contain relative min-h-0 ${isWindows ? "xl:pt-4" : "xl:pt-8"}`}
|
||||
>
|
||||
<div className="max-w-[730px] mx-auto w-full px-4 pt-4 pb-20 sm:px-6 sm:pt-6 sm:pb-24 lg:px-8 lg:pt-8 lg:pb-28">
|
||||
<h1 className="text-xl font-semibold text-neutral-900 dark:text-neutral-100">
|
||||
Launch
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-neutral-500 dark:text-neutral-400">
|
||||
Copy a command and run it in your terminal.
|
||||
</p>
|
||||
|
||||
<div className="mt-6 grid gap-7">
|
||||
{LAUNCH_COMMANDS.map(renderCommandCard)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,597 +0,0 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
FIRST_MODEL_COMMAND,
|
||||
ConnectAppsScreen,
|
||||
IntroScreen,
|
||||
default as Onboarding,
|
||||
RunOllamaScreen,
|
||||
terminalRowsForWindowHeight,
|
||||
WelcomeScreen,
|
||||
} from "./Onboarding";
|
||||
import {
|
||||
CLAUDE_INSTALL_TIMEOUT_MS,
|
||||
isClaudeConnectionComplete,
|
||||
scheduleClaudeInstallTimeout,
|
||||
} from "@/lib/claudeDesktop";
|
||||
import { isWindowsPlatform } from "@/lib/platform";
|
||||
import {
|
||||
authenticationTimeoutAction,
|
||||
nextOnboardingStep,
|
||||
onboardingConnectUrl,
|
||||
} from "@/lib/onboarding";
|
||||
import type { IntegrationStatuses } from "@/api";
|
||||
|
||||
describe("Onboarding", () => {
|
||||
it("explains what Ollama is before asking the user to choose a path", () => {
|
||||
const html = renderToStaticMarkup(<IntroScreen onContinue={vi.fn()} />);
|
||||
|
||||
expect(html).toContain("Welcome to Ollama!");
|
||||
expect(html.indexOf('alt="Ollama waving"')).toBeLessThan(
|
||||
html.indexOf("Welcome to Ollama!"),
|
||||
);
|
||||
expect(html).toContain(
|
||||
"Run open models with your coding agents so you can spend less while keeping your data private.",
|
||||
);
|
||||
expect(html.indexOf("Connect your apps")).toBeLessThan(
|
||||
html.indexOf("Easily switch models"),
|
||||
);
|
||||
expect(html.indexOf("Easily switch models")).toBeLessThan(
|
||||
html.indexOf("Your data stays yours"),
|
||||
);
|
||||
expect(html).toContain("Power your existing coding apps with open models");
|
||||
expect(html).toContain("Swap between frontier models in one click.");
|
||||
expect(html).toContain("Your prompt data is never logged or trained on.");
|
||||
expect(html).toContain("Continue");
|
||||
expect(html).not.toContain("Skip");
|
||||
});
|
||||
|
||||
it("shows more terminal integrations as the window gets taller", () => {
|
||||
expect(terminalRowsForWindowHeight(400)).toBe(1);
|
||||
expect(terminalRowsForWindowHeight(660)).toBe(4);
|
||||
expect(terminalRowsForWindowHeight(960)).toBe(8);
|
||||
});
|
||||
|
||||
it("renders the apps screen without browser platform globals", () => {
|
||||
vi.stubGlobal("navigator", undefined);
|
||||
try {
|
||||
expect(() =>
|
||||
renderToStaticMarkup(<ConnectAppsScreen initialIntegrations={[]} />),
|
||||
).not.toThrow();
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it("hides the Claude application on Windows", () => {
|
||||
vi.stubGlobal("window", {
|
||||
OLLAMA_PLATFORM: "windows",
|
||||
innerHeight: 660,
|
||||
});
|
||||
vi.stubGlobal("navigator", { platform: "MacIntel" });
|
||||
try {
|
||||
expect(isWindowsPlatform()).toBe(true);
|
||||
const html = renderToStaticMarkup(
|
||||
<ConnectAppsScreen
|
||||
initialIntegrations={[
|
||||
{
|
||||
id: "claude-desktop",
|
||||
name: "Claude",
|
||||
description: "Use Ollama models in Claude Desktop",
|
||||
installed: true,
|
||||
},
|
||||
{
|
||||
id: "claude",
|
||||
name: "Claude Code",
|
||||
description: "Anthropic's coding tool with subagents",
|
||||
command: "ollama launch claude",
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).not.toContain('id="applications-heading"');
|
||||
expect(html).not.toContain("Use Ollama models in Claude Desktop");
|
||||
expect(html).toContain('id="terminal-heading"');
|
||||
expect(html).toContain("ollama launch claude");
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows the account choice only to signed-out users", () => {
|
||||
expect(nextOnboardingStep("intro", "continue", false)).toBe("welcome");
|
||||
expect(nextOnboardingStep("intro", "continue", true)).toBe("apps");
|
||||
expect(nextOnboardingStep("welcome", "authenticated", true)).toBe("apps");
|
||||
expect(nextOnboardingStep("apps", "continue", true)).toBe("apps");
|
||||
expect(nextOnboardingStep("welcome", "local", false)).toBe("run");
|
||||
});
|
||||
|
||||
it("lets an in-flight authentication check finish before timing out", () => {
|
||||
expect(authenticationTimeoutAction(false, true)).toBe("defer");
|
||||
expect(authenticationTimeoutAction(false, false)).toBe("fail");
|
||||
expect(authenticationTimeoutAction(true, true)).toBe("ignore");
|
||||
});
|
||||
|
||||
it("finishes Claude connection states from the native status hook", () => {
|
||||
const status = {
|
||||
supported: true,
|
||||
installed: true,
|
||||
configured: true,
|
||||
connected: true,
|
||||
running: false,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
};
|
||||
|
||||
expect(isClaudeConnectionComplete(true, status)).toBe(true);
|
||||
expect(
|
||||
isClaudeConnectionComplete(true, { ...status, connected: false }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isClaudeConnectionComplete(true, { ...status, startFailed: true }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isClaudeConnectionComplete(false, {
|
||||
...status,
|
||||
configured: false,
|
||||
connected: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isClaudeConnectionComplete(false, { ...status, connected: false }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("bounds the Claude installer wait", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal("window", { setTimeout: globalThis.setTimeout });
|
||||
const onTimeout = vi.fn();
|
||||
|
||||
try {
|
||||
scheduleClaudeInstallTimeout(onTimeout);
|
||||
vi.advanceTimersByTime(CLAUDE_INSTALL_TIMEOUT_MS - 1);
|
||||
expect(onTimeout).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(onTimeout).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it("opens the device connection flow without relaunching the app", () => {
|
||||
expect(
|
||||
onboardingConnectUrl(
|
||||
"https://ollama.com/connect?name=MacBook&key=public-key&launch=true",
|
||||
"signin",
|
||||
),
|
||||
).toBe("https://ollama.com/connect?name=MacBook&key=public-key");
|
||||
expect(
|
||||
onboardingConnectUrl(
|
||||
"https://ollama.com/connect?name=MacBook&key=public-key",
|
||||
"signup",
|
||||
),
|
||||
).toBe(
|
||||
"https://ollama.com/connect?name=MacBook&key=public-key&signup=true",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves the intro for a device that is already connected", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<Onboarding
|
||||
isAuthenticated
|
||||
isSigningIn={false}
|
||||
signInError={null}
|
||||
completionError={null}
|
||||
onOpenApps={vi.fn().mockResolvedValue(true)}
|
||||
onSignIn={vi.fn()}
|
||||
onSignUp={vi.fn()}
|
||||
onRetryCompletion={vi.fn()}
|
||||
onUseLocal={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Welcome to Ollama");
|
||||
expect(html).not.toContain("Run Ollama");
|
||||
expect(html).not.toContain("Sign up");
|
||||
});
|
||||
|
||||
it("groups disconnected Claude with applications and terminal separately", () => {
|
||||
const integrations: IntegrationStatuses = [
|
||||
{
|
||||
id: "claude-desktop",
|
||||
name: "Claude",
|
||||
description: "Use Ollama models in Claude Desktop",
|
||||
installed: true,
|
||||
action: "connect",
|
||||
},
|
||||
{
|
||||
id: "claude",
|
||||
name: "Claude Code",
|
||||
description: "Anthropic's coding tool with subagents",
|
||||
installed: true,
|
||||
action: "copy",
|
||||
command: "ollama launch claude",
|
||||
},
|
||||
{
|
||||
id: "codex",
|
||||
name: "Codex",
|
||||
description: "OpenAI's open-source coding agent",
|
||||
installed: true,
|
||||
action: "copy",
|
||||
command: "ollama launch codex",
|
||||
},
|
||||
{
|
||||
id: "openclaw",
|
||||
name: "OpenClaw",
|
||||
description: "Personal AI with 100+ skills",
|
||||
installed: true,
|
||||
action: "copy",
|
||||
command: "ollama launch openclaw",
|
||||
},
|
||||
{
|
||||
id: "opencode",
|
||||
name: "OpenCode",
|
||||
description: "Anomaly's open-source coding agent",
|
||||
installed: false,
|
||||
action: "copy",
|
||||
command: "ollama launch opencode",
|
||||
},
|
||||
{
|
||||
id: "droid",
|
||||
name: "Droid",
|
||||
description: "AI software engineering agent",
|
||||
installed: false,
|
||||
action: "copy",
|
||||
command: "ollama launch droid",
|
||||
},
|
||||
{
|
||||
id: "terminal",
|
||||
name: "Terminal",
|
||||
description: "Run local models from your terminal",
|
||||
action: "copy",
|
||||
command: "ollama",
|
||||
},
|
||||
];
|
||||
const html = renderToStaticMarkup(
|
||||
<ConnectAppsScreen
|
||||
completionError={null}
|
||||
onRetryCompletion={vi.fn()}
|
||||
initialIntegrations={integrations}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).not.toContain(
|
||||
"Connect Claude, or copy a command to run in your terminal.",
|
||||
);
|
||||
expect(html).toContain("Claude");
|
||||
expect(html).toContain("Use Ollama models in Claude Desktop");
|
||||
expect(html).toContain("Claude Code");
|
||||
expect(html).not.toContain("Search apps");
|
||||
expect(html).not.toContain('type="search"');
|
||||
expect(html).toContain("Application");
|
||||
expect(html).toContain('id="applications-heading"');
|
||||
expect(html).toContain('id="terminal-heading"');
|
||||
expect(html).not.toContain("Ready to launch");
|
||||
expect(html).not.toContain('id="claude-apps-heading"');
|
||||
expect(html.indexOf("Application")).toBeLessThan(
|
||||
html.indexOf("Use Ollama models in Claude Desktop"),
|
||||
);
|
||||
expect(html).not.toContain(">Command</th>");
|
||||
expect(html).toContain("ollama launch claude");
|
||||
expect(html).not.toContain("Installed");
|
||||
expect(html).not.toContain("Not installed");
|
||||
expect(html).toContain('aria-label="Connect Claude"');
|
||||
expect(html).toContain('role="switch"');
|
||||
expect(html).toContain('aria-checked="false"');
|
||||
expect(html).not.toContain("Inactive");
|
||||
expect(html).not.toContain("Download & connect");
|
||||
expect(html).not.toContain("Active");
|
||||
expect(html).toContain("bg-transparent");
|
||||
expect(html).toContain('aria-label="Copy OpenCode command"');
|
||||
expect(html).toContain('aria-label="Copy Terminal command"');
|
||||
expect(html).not.toContain(">Copy command</button>");
|
||||
expect(html).not.toContain("ChatGPT");
|
||||
expect(html).toContain("OpenCode");
|
||||
expect(html).toContain("Terminal");
|
||||
expect(html).toContain('aria-label="Show more apps"');
|
||||
expect(html).toContain('aria-expanded="false"');
|
||||
expect(html).toContain("grid-rows-[0fr]");
|
||||
expect(html).not.toContain("Collapse");
|
||||
expect(html).toContain("/launch-icons/claude.svg");
|
||||
expect(html).toContain("/launch-icons/claude-code.svg");
|
||||
expect(html).not.toContain("<table");
|
||||
expect(html).not.toContain("<footer");
|
||||
expect(html).not.toContain("Command copied. Run it in your terminal.");
|
||||
expect(html).toContain("Run local models from your terminal");
|
||||
expect(html).not.toContain("Launch command");
|
||||
expect(html).not.toContain('aria-pressed="true"');
|
||||
expect(html).not.toContain("Continue");
|
||||
expect(html).not.toContain("Run Ollama");
|
||||
expect(html).not.toContain('viewBox="0 0 3400 3400"');
|
||||
});
|
||||
|
||||
it("keeps connected Claude in Application without an idle status", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ConnectAppsScreen
|
||||
completionError={null}
|
||||
onRetryCompletion={vi.fn()}
|
||||
initialClaudeStatus={{
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
connected: true,
|
||||
running: false,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
}}
|
||||
initialIntegrations={[
|
||||
{
|
||||
id: "claude-desktop",
|
||||
name: "Claude",
|
||||
description: "Use Ollama models in Claude Desktop",
|
||||
installed: true,
|
||||
action: "connect",
|
||||
},
|
||||
{
|
||||
id: "codex",
|
||||
name: "Codex",
|
||||
description: "OpenAI's open-source coding agent",
|
||||
installed: true,
|
||||
action: "copy",
|
||||
command: "ollama launch codex",
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain('id="applications-heading"');
|
||||
expect(html).not.toContain('id="claude-apps-heading"');
|
||||
expect(html).not.toContain("Ready to launch");
|
||||
expect(html).not.toContain("Active");
|
||||
expect(html).not.toContain("Inactive");
|
||||
expect(html).toContain('aria-checked="true"');
|
||||
expect(html).toContain('aria-label="Disconnect Claude"');
|
||||
});
|
||||
|
||||
it("shows initial Claude recovery guidance without error styling", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ConnectAppsScreen
|
||||
completionError={null}
|
||||
onRetryCompletion={vi.fn()}
|
||||
initialClaudeStatus={{
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
configured: true,
|
||||
connected: false,
|
||||
running: false,
|
||||
startFailed: true,
|
||||
portConflict: false,
|
||||
error: "Cloud models are off. Select an installed model in Settings.",
|
||||
}}
|
||||
initialIntegrations={[
|
||||
{
|
||||
id: "claude-desktop",
|
||||
name: "Claude",
|
||||
description: "Use Ollama models in Claude Desktop",
|
||||
installed: true,
|
||||
action: "connect",
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain(
|
||||
"Cloud models are off. Select an installed model in Settings.",
|
||||
);
|
||||
expect(html).toContain('role="alert"');
|
||||
expect(html).not.toContain("text-red");
|
||||
expect(html).toContain('aria-checked="true"');
|
||||
expect(html).toContain('aria-label="Disconnect Claude"');
|
||||
});
|
||||
|
||||
it("keeps Claude model management off the Connect Apps page", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ConnectAppsScreen
|
||||
completionError={null}
|
||||
onRetryCompletion={vi.fn()}
|
||||
initialClaudeStatus={{
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
connected: true,
|
||||
running: true,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
modelSource: "endpoint",
|
||||
models: [
|
||||
{
|
||||
name: "glm-5.2:cloud",
|
||||
displayName: "GLM 5.2",
|
||||
description: "Long-horizon coding",
|
||||
selected: true,
|
||||
},
|
||||
{
|
||||
name: "qwen3.8:27b",
|
||||
displayName: "Qwen 3.8 27B",
|
||||
description: "Local coding",
|
||||
selected: false,
|
||||
},
|
||||
],
|
||||
}}
|
||||
initialIntegrations={[
|
||||
{
|
||||
id: "claude-desktop",
|
||||
name: "Claude",
|
||||
description: "Use Ollama models in Claude Desktop",
|
||||
installed: true,
|
||||
action: "connect",
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).not.toContain("Models in Claude");
|
||||
expect(html).not.toContain("GLM 5.2");
|
||||
expect(html).not.toContain("Qwen 3.8 27B");
|
||||
expect(html).not.toContain('type="checkbox"');
|
||||
expect(html).not.toContain("Restart Claude");
|
||||
expect(html).not.toContain("Built-in defaults");
|
||||
});
|
||||
|
||||
it("keeps Claude available without a separate not-installed group", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ConnectAppsScreen
|
||||
completionError={null}
|
||||
onRetryCompletion={vi.fn()}
|
||||
initialIntegrations={[
|
||||
{
|
||||
id: "claude-desktop",
|
||||
name: "Claude",
|
||||
description: "Use Ollama models in Claude Desktop",
|
||||
installed: false,
|
||||
action: "connect",
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Use Ollama models in Claude Desktop");
|
||||
expect(html).toContain('aria-label="Connect Claude"');
|
||||
expect(html).toContain("Download & connect");
|
||||
expect(html).not.toContain("Inactive");
|
||||
expect(html).not.toContain("Not installed");
|
||||
expect(html).not.toContain('disabled=""');
|
||||
});
|
||||
|
||||
it("uses branded icons for the remaining launcher integrations", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ConnectAppsScreen
|
||||
completionError={null}
|
||||
onRetryCompletion={vi.fn()}
|
||||
initialIntegrations={[
|
||||
{
|
||||
id: "cline",
|
||||
name: "Cline",
|
||||
description: "Autonomous coding agent",
|
||||
action: "copy",
|
||||
command: "ollama launch cline",
|
||||
},
|
||||
{
|
||||
id: "omp",
|
||||
name: "Oh My Pi",
|
||||
description: "AI coding agent",
|
||||
action: "copy",
|
||||
command: "ollama launch omp",
|
||||
},
|
||||
{
|
||||
id: "pool",
|
||||
name: "Poolside",
|
||||
description: "Poolside's coding agent",
|
||||
action: "copy",
|
||||
command: "ollama launch pool",
|
||||
},
|
||||
{
|
||||
id: "qwen",
|
||||
name: "Qwen Code",
|
||||
description: "Qwen's coding agent",
|
||||
action: "copy",
|
||||
command: "ollama launch qwen",
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("/launch-icons/cline.svg");
|
||||
expect(html).toContain("/launch-icons/oh-my-pi.svg");
|
||||
expect(html).toContain("/launch-icons/poolside.svg");
|
||||
expect(html).toContain("/launch-icons/qwen-code.svg");
|
||||
});
|
||||
|
||||
it("offers cloud sign-up, local setup, and sign in on the welcome screen", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<WelcomeScreen
|
||||
isAuthenticated={false}
|
||||
isSigningIn={false}
|
||||
signInError={null}
|
||||
onSignIn={vi.fn()}
|
||||
onSignUp={vi.fn()}
|
||||
onLocal={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Create an account");
|
||||
expect(html).toContain(
|
||||
"Create your account for access to faster, larger open models.",
|
||||
);
|
||||
expect(html).toContain("Your data is never logged or trained on.");
|
||||
expect(html).toContain("Sign up");
|
||||
expect(html).toContain("No thanks, I'll use Ollama locally");
|
||||
expect(html).toContain("Sign in");
|
||||
expect(html).not.toContain("Skip");
|
||||
});
|
||||
|
||||
it("shows the cloud choice without a sign-in link for authenticated users", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<WelcomeScreen
|
||||
isAuthenticated
|
||||
isSigningIn={false}
|
||||
signInError={null}
|
||||
onSignIn={vi.fn()}
|
||||
onSignUp={vi.fn()}
|
||||
onLocal={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Create an account");
|
||||
expect(html).toContain(
|
||||
"Create your account for access to faster, larger open models.",
|
||||
);
|
||||
expect(html).toContain("Your data is never logged or trained on.");
|
||||
expect(html).not.toContain(">Sign in<");
|
||||
});
|
||||
|
||||
it("shows only the local command on the final page", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<RunOllamaScreen completionError={null} onRetryCompletion={vi.fn()} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Run Ollama");
|
||||
expect(html).toContain(FIRST_MODEL_COMMAND);
|
||||
expect(html).not.toContain("Finish");
|
||||
expect(html).not.toContain("Sign in");
|
||||
expect(html).not.toContain("create an account");
|
||||
});
|
||||
|
||||
it("shows the connecting state on the welcome action", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<WelcomeScreen
|
||||
isAuthenticated={false}
|
||||
isSigningIn
|
||||
signInError={null}
|
||||
onSignIn={vi.fn()}
|
||||
onSignUp={vi.fn()}
|
||||
onLocal={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Finish in your browser…");
|
||||
expect(html).not.toContain("Waiting for sign in…");
|
||||
});
|
||||
|
||||
it("shows a retryable error when onboarding completion cannot be saved", () => {
|
||||
const onRetryCompletion = vi.fn();
|
||||
const html = renderToStaticMarkup(
|
||||
<RunOllamaScreen
|
||||
completionError="Unable to save setup. Please try again."
|
||||
onRetryCompletion={onRetryCompletion}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Unable to save setup. Please try again.");
|
||||
expect(html).toContain('role="alert"');
|
||||
expect(html).toContain("Try again");
|
||||
});
|
||||
});
|
||||
@@ -6,19 +6,19 @@ import { Field, Label, Description } from "@/components/ui/fieldset";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Slider } from "@/components/ui/slider";
|
||||
import { ClaudeDesktopModelsSettings } from "@/components/ClaudeDesktopModelsSettings";
|
||||
import {
|
||||
WifiIcon,
|
||||
FolderIcon,
|
||||
BoltIcon,
|
||||
WrenchIcon,
|
||||
CloudIcon,
|
||||
XMarkIcon,
|
||||
CogIcon,
|
||||
ArrowLeftIcon,
|
||||
ArrowDownTrayIcon,
|
||||
Squares2X2Icon,
|
||||
} from "@heroicons/react/20/solid";
|
||||
import { Settings as SettingsType } from "@/gotypes";
|
||||
import { isWindowsPlatform } from "@/lib/platform";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { useUser } from "@/hooks/useUser";
|
||||
import { useCloudStatus } from "@/hooks/useCloudStatus";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
@@ -48,8 +48,6 @@ export default function Settings() {
|
||||
const queryClient = useQueryClient();
|
||||
const [showSaved, setShowSaved] = useState(false);
|
||||
const [restartMessage, setRestartMessage] = useState(false);
|
||||
const [showAppsInMenu, setShowAppsInMenuState] = useState(true);
|
||||
const [showAppsInMenuPending, setShowAppsInMenuPending] = useState(false);
|
||||
const {
|
||||
user,
|
||||
isAuthenticated,
|
||||
@@ -63,6 +61,7 @@ export default function Settings() {
|
||||
const [isAwaitingConnection, setIsAwaitingConnection] = useState(false);
|
||||
const [connectionError, setConnectionError] = useState<string | null>(null);
|
||||
const [pollingInterval, setPollingInterval] = useState<number | null>(null);
|
||||
const navigate = useNavigate();
|
||||
const {
|
||||
cloudDisabled,
|
||||
cloudStatus,
|
||||
@@ -144,15 +143,6 @@ export default function Settings() {
|
||||
refetchUser();
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
window
|
||||
.getShowAppsInMenu?.()
|
||||
.then(setShowAppsInMenuState)
|
||||
.catch((error) =>
|
||||
console.error("Failed to load menu app visibility:", error),
|
||||
);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const handleFocus = () => {
|
||||
if (isAwaitingConnection && pollingInterval) {
|
||||
@@ -230,22 +220,6 @@ export default function Settings() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleShowAppsInMenu = async (checked: boolean) => {
|
||||
const previous = showAppsInMenu;
|
||||
setShowAppsInMenuState(checked);
|
||||
setShowAppsInMenuPending(true);
|
||||
try {
|
||||
await window.setShowAppsInMenu?.(checked);
|
||||
setShowSaved(true);
|
||||
setTimeout(() => setShowSaved(false), 1500);
|
||||
} catch (error) {
|
||||
setShowAppsInMenuState(previous);
|
||||
console.error("Failed to update menu app visibility:", error);
|
||||
} finally {
|
||||
setShowAppsInMenuPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const cloudOverriddenByEnv =
|
||||
cloudStatus?.source === "env" || cloudStatus?.source === "both";
|
||||
const cloudToggleDisabled =
|
||||
@@ -292,18 +266,49 @@ export default function Settings() {
|
||||
|
||||
if (error || !settings) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="text-red-500">Failed to load settings</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const isWindows = isWindowsPlatform();
|
||||
const isWindows = navigator.platform.toLowerCase().includes("win");
|
||||
const handleCloseSettings = () => {
|
||||
const chatId = settings.LastHomeView === "chat" ? "new" : "launch";
|
||||
navigate({ to: "/c/$chatId", params: { chatId } });
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="flex min-h-0 w-full flex-1 flex-col select-none dark:bg-neutral-900">
|
||||
<main className="flex h-screen w-full flex-col select-none dark:bg-neutral-900">
|
||||
<header
|
||||
className="w-full flex flex-none justify-between h-[52px] py-2.5 items-center border-b border-neutral-200 dark:border-neutral-800 select-none"
|
||||
onMouseDown={() => window.drag && window.drag()}
|
||||
onDoubleClick={() => window.doubleClick && window.doubleClick()}
|
||||
>
|
||||
<h1
|
||||
className={`${isWindows ? "pl-4" : "pl-24"} flex items-center font-rounded text-md font-medium dark:text-white`}
|
||||
>
|
||||
{isWindows && (
|
||||
<button
|
||||
onClick={handleCloseSettings}
|
||||
className="hover:bg-neutral-100 mr-3 dark:hover:bg-neutral-800 rounded-full p-1.5"
|
||||
>
|
||||
<ArrowLeftIcon className="w-5 h-5 dark:text-white" />
|
||||
</button>
|
||||
)}
|
||||
Settings
|
||||
</h1>
|
||||
{!isWindows && (
|
||||
<button
|
||||
onClick={handleCloseSettings}
|
||||
className="p-1 hover:bg-neutral-100 mr-3 dark:hover:bg-neutral-800 rounded-full"
|
||||
>
|
||||
<XMarkIcon className="w-6 h-6 dark:text-white" />
|
||||
</button>
|
||||
)}
|
||||
</header>
|
||||
<div className="w-full p-6 overflow-y-auto flex-1 overscroll-contain">
|
||||
<div className="mx-auto max-w-4xl space-y-4">
|
||||
<div className="space-y-4 max-w-2xl mx-auto">
|
||||
{/* Connect Ollama Account */}
|
||||
<div className="overflow-hidden rounded-xl bg-white dark:bg-neutral-800">
|
||||
<div className="p-4">
|
||||
@@ -441,29 +446,6 @@ export default function Settings() {
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
{!isWindows && (
|
||||
<Field>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex flex-1 items-start space-x-3">
|
||||
<Squares2X2Icon className="mt-1 h-5 w-5 flex-shrink-0 text-black dark:text-neutral-100" />
|
||||
<div>
|
||||
<Label>Show apps in menu</Label>
|
||||
<Description>
|
||||
Show connected apps at the top of the Ollama menu.
|
||||
</Description>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-shrink-0">
|
||||
<Switch
|
||||
checked={showAppsInMenu}
|
||||
disabled={showAppsInMenuPending}
|
||||
onChange={handleShowAppsInMenu}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Field>
|
||||
)}
|
||||
|
||||
{/* Auto Update */}
|
||||
<Field>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
@@ -481,9 +463,7 @@ export default function Settings() {
|
||||
<div className="flex-shrink-0">
|
||||
<Switch
|
||||
checked={settings.AutoUpdateEnabled}
|
||||
onChange={(checked) =>
|
||||
handleChange("AutoUpdateEnabled", checked)
|
||||
}
|
||||
onChange={(checked) => handleChange("AutoUpdateEnabled", checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -564,9 +544,7 @@ export default function Settings() {
|
||||
</Description>
|
||||
<div className="mt-3">
|
||||
<Slider
|
||||
value={
|
||||
settings.ContextLength || defaultContextLength || 0
|
||||
}
|
||||
value={settings.ContextLength || defaultContextLength || 0}
|
||||
onChange={(value) => {
|
||||
handleChange("ContextLength", value);
|
||||
}}
|
||||
@@ -588,8 +566,6 @@ export default function Settings() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ClaudeDesktopModelsSettings />
|
||||
|
||||
{/* Agent Mode */}
|
||||
{window.OLLAMA_TOOLS && (
|
||||
<div className="overflow-hidden rounded-xl bg-white dark:bg-neutral-800">
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { SidebarLayout } from "./layout";
|
||||
|
||||
describe("SidebarLayout", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("keeps the macOS title offset in step with the sidebar transition", () => {
|
||||
vi.stubGlobal("window", { OLLAMA_PLATFORM: "darwin" });
|
||||
|
||||
const html = renderToStaticMarkup(
|
||||
<SidebarLayout title="Connect your apps" sidebar={<nav />}>
|
||||
<div />
|
||||
</SidebarLayout>,
|
||||
);
|
||||
|
||||
expect(html).toContain("pl-36");
|
||||
expect(html).toContain("transition-[padding-left]");
|
||||
expect(html).toContain("duration-300");
|
||||
});
|
||||
});
|
||||
@@ -1,39 +1,30 @@
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { ChatIcon } from "@/components/ChatIcon";
|
||||
import { isWindowsPlatform } from "@/lib/platform";
|
||||
import { useState } from "react";
|
||||
|
||||
let sessionSidebarOpen = false;
|
||||
import { useSettings } from "@/hooks/useSettings";
|
||||
|
||||
export function SidebarLayout({
|
||||
sidebar,
|
||||
title,
|
||||
children,
|
||||
}: React.PropsWithChildren<{
|
||||
sidebar: React.ReactNode;
|
||||
title?: string;
|
||||
collapsible?: boolean;
|
||||
chatId?: string;
|
||||
}>) {
|
||||
const [sidebarOpen, setSidebarOpen] = useState(sessionSidebarOpen);
|
||||
const isWindows = isWindowsPlatform();
|
||||
|
||||
const toggleSidebar = () => {
|
||||
sessionSidebarOpen = !sidebarOpen;
|
||||
setSidebarOpen(sessionSidebarOpen);
|
||||
};
|
||||
const { settings, setSettings } = useSettings();
|
||||
const isWindows = navigator.platform.toLowerCase().includes("win");
|
||||
|
||||
return (
|
||||
<div className="flex h-screen w-full overflow-hidden dark:bg-neutral-900">
|
||||
<div className={`flex transition-[width] duration-300 dark:bg-neutral-900`}>
|
||||
<div
|
||||
className={`absolute flex mx-2 py-2 z-20 items-center transition-[left] duration-375 text-neutral-500 dark:text-neutral-400 ${sidebarOpen ? (isWindows ? "left-2" : "left-[140px]") : isWindows ? "left-2" : "left-20"}`}
|
||||
className={`absolute flex mx-2 py-2 z-20 items-center transition-[left] duration-375 text-neutral-500 dark:text-neutral-400 ${settings.sidebarOpen ? (isWindows ? "left-2" : "left-[204px]") : isWindows ? "left-2" : "left-20"}`}
|
||||
>
|
||||
<button
|
||||
onClick={toggleSidebar}
|
||||
onClick={() => setSettings({ SidebarOpen: !settings.sidebarOpen })}
|
||||
onMouseDown={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
className="h-9 w-9 flex items-center justify-center rounded-full hover:bg-neutral-100 dark:hover:bg-neutral-700/75 cursor-pointer"
|
||||
aria-label={sidebarOpen ? "Hide sidebar" : "Show sidebar"}
|
||||
title={sidebarOpen ? "Hide sidebar" : "Show sidebar"}
|
||||
aria-label={settings.sidebarOpen ? "Hide sidebar" : "Show sidebar"}
|
||||
title={settings.sidebarOpen ? "Hide sidebar" : "Show sidebar"}
|
||||
>
|
||||
<svg
|
||||
className="h-5 w-5 fill-current"
|
||||
@@ -44,47 +35,45 @@ export function SidebarLayout({
|
||||
<path d="M7.76132 16.6344H9.58103V1.59842H7.76132V16.6344ZM4.20898 18.2316H19.124C21.6518 18.2316 23.1293 16.6963 23.1293 14.0209V4.2205C23.1293 1.54512 21.6518 0.00351715 19.124 0.00351715H4.20898C1.54336 0.00351715 0 1.54512 0 4.2205V14.0209C0 16.6963 1.54336 18.2316 4.20898 18.2316ZM4.31191 16.3184C2.79628 16.3184 1.91327 15.4434 1.91327 13.926V4.31542C1.91327 2.79979 2.79628 1.91678 4.31191 1.91678H18.8174C20.333 1.91678 21.216 2.79979 21.216 4.31542V13.926C21.216 15.4434 20.333 16.3184 18.8174 16.3184H4.31191ZM5.85116 5.50038C6.1951 5.50038 6.49217 5.20507 6.49217 4.87968C6.49217 4.54628 6.1951 4.25722 5.85116 4.25722H3.8412C3.49725 4.25722 3.20819 4.54628 3.20819 4.87968C3.20819 5.20507 3.49725 5.50038 3.8412 5.50038H5.85116ZM5.85116 8.1158C6.1951 8.1158 6.49217 7.82049 6.49217 7.4871C6.49217 7.1537 6.1951 6.8744 5.85116 6.8744H3.8412C3.49725 6.8744 3.20819 7.1537 3.20819 7.4871C3.20819 7.82049 3.49725 8.1158 3.8412 8.1158H5.85116ZM5.85116 10.725C6.1951 10.725 6.49217 10.4439 6.49217 10.1105C6.49217 9.77713 6.1951 9.48983 5.85116 9.48983H3.8412C3.49725 9.48983 3.20819 9.77713 3.20819 10.1105C3.20819 10.4439 3.49725 10.725 3.8412 10.725H5.85116Z" />
|
||||
</svg>
|
||||
</button>
|
||||
{!title && (
|
||||
<Link
|
||||
to="/c/$chatId"
|
||||
params={{ chatId: "new" }}
|
||||
title="New chat"
|
||||
className={`flex ml-1 items-center justify-center rounded-full transition-opacity duration-375 h-9 w-9 hover:bg-neutral-100 dark:hover:bg-neutral-700 ${
|
||||
sidebarOpen ? "opacity-0 pointer-events-none" : "opacity-100"
|
||||
}`}
|
||||
<Link
|
||||
to="/c/$chatId"
|
||||
params={{ chatId: "new" }}
|
||||
title="New chat"
|
||||
className={`flex ml-1 items-center justify-center rounded-full transition-opacity duration-375 h-9 w-9 hover:bg-neutral-100 dark:hover:bg-neutral-700 ${
|
||||
settings.sidebarOpen
|
||||
? "opacity-0 pointer-events-none"
|
||||
: "opacity-100"
|
||||
}`}
|
||||
>
|
||||
<svg
|
||||
className="h-5 w-5 fill-current"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<ChatIcon />
|
||||
</Link>
|
||||
)}
|
||||
<path d="M17.0859 3.39949L15.2135 5.27196H7.27028C5.78649 5.27196 4.94684 6.11336 4.94684 7.59716V16.664C4.94684 18.1558 5.78649 18.9892 7.27028 18.9892H16.3406C17.8324 18.9892 18.6623 18.1558 18.6623 16.664V8.79514L20.5428 6.9115C20.567 7.11532 20.5773 7.33066 20.5773 7.55419V16.7149C20.5773 19.4069 19.0818 20.9024 16.3898 20.9024H7.22107C4.53708 20.9024 3.03357 19.4069 3.03357 16.7149V7.55419C3.03357 4.8622 4.53708 3.35869 7.22107 3.35869H16.3898C16.6329 3.35869 16.8662 3.37094 17.0859 3.39949Z" />
|
||||
<path d="M9.92714 14.381L11.914 13.5403L20.8312 4.63114L19.3404 3.1581L10.433 12.0655L9.55234 13.9964C9.45664 14.2169 9.70293 14.4714 9.92714 14.381ZM21.5767 3.89364L22.2588 3.19384C22.6347 2.80184 22.6435 2.2663 22.2711 1.90536L22.0148 1.64287C21.6822 1.31377 21.1334 1.36513 20.7689 1.72158L20.0859 2.39833L21.5767 3.89364Z" />
|
||||
</svg>
|
||||
</Link>
|
||||
</div>
|
||||
<div
|
||||
className={`flex max-h-screen flex-col transition-[width] duration-300 ${
|
||||
sidebarOpen
|
||||
? "w-48 border-r border-neutral-200 bg-neutral-50 dark:border-neutral-800 dark:bg-neutral-950/40"
|
||||
: "w-0"
|
||||
}`}
|
||||
className={`flex flex-col transition-[width] duration-300 max-h-screen ${settings.sidebarOpen ? "w-64" : "w-0"}`}
|
||||
>
|
||||
<div
|
||||
onDoubleClick={() => window.doubleClick && window.doubleClick()}
|
||||
onMouseDown={() => window.drag && window.drag()}
|
||||
className="flex-none h-13 w-full"
|
||||
></div>
|
||||
{sidebarOpen && sidebar}
|
||||
{settings.sidebarOpen && sidebar}
|
||||
</div>
|
||||
<main className="flex min-w-0 flex-1 flex-col transition-all duration-300">
|
||||
<main
|
||||
className={`flex flex-1 flex-col min-w-0 transition-all duration-300`}
|
||||
>
|
||||
<div
|
||||
className={`h-13 z-10 flex w-full flex-none items-center bg-white dark:bg-neutral-900 ${title ? "" : isWindows ? "xl:hidden" : "xl:fixed xl:bg-transparent xl:dark:bg-transparent"}`}
|
||||
className={`h-13 flex-none w-full z-10 flex items-center bg-white dark:bg-neutral-900 ${isWindows ? "xl:hidden" : "xl:fixed xl:bg-transparent xl:dark:bg-transparent"}`}
|
||||
onDoubleClick={() => window.doubleClick && window.doubleClick()}
|
||||
onMouseDown={() => window.drag && window.drag()}
|
||||
>
|
||||
{title && (
|
||||
<h1
|
||||
className={`${sidebarOpen ? "pl-6" : isWindows ? "pl-16" : "pl-36"} transition-[padding-left] duration-300 font-rounded text-md font-medium dark:text-white`}
|
||||
>
|
||||
{title}
|
||||
</h1>
|
||||
)}
|
||||
</div>
|
||||
></div>
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -10,7 +10,6 @@ interface SettingsState {
|
||||
selectedModel: string;
|
||||
sidebarOpen: boolean;
|
||||
lastHomeView: string;
|
||||
onboardingVersion: number;
|
||||
thinkEnabled: boolean;
|
||||
thinkLevel: string;
|
||||
}
|
||||
@@ -24,7 +23,6 @@ type SettingsUpdate = Partial<{
|
||||
SelectedModel: string;
|
||||
SidebarOpen: boolean;
|
||||
LastHomeView: string;
|
||||
OnboardingVersion: number;
|
||||
}>;
|
||||
|
||||
export function useSettings() {
|
||||
@@ -54,8 +52,7 @@ export function useSettings() {
|
||||
thinkLevel: settingsData?.settings?.ThinkLevel ?? "none",
|
||||
selectedModel: settingsData?.settings?.SelectedModel ?? "",
|
||||
sidebarOpen: settingsData?.settings?.SidebarOpen ?? false,
|
||||
lastHomeView: settingsData?.settings?.LastHomeView ?? "chat",
|
||||
onboardingVersion: settingsData?.settings?.OnboardingVersion ?? 0,
|
||||
lastHomeView: settingsData?.settings?.LastHomeView ?? "launch",
|
||||
}),
|
||||
[settingsData?.settings],
|
||||
);
|
||||
|
||||
@@ -2,35 +2,18 @@
|
||||
@plugin "@tailwindcss/typography";
|
||||
@import "katex/dist/katex.min.css";
|
||||
|
||||
/* Retain component class names while making the dark variant unreachable. */
|
||||
@custom-variant dark (@media not all);
|
||||
|
||||
@theme {
|
||||
--font-sans: ui-sans-serif, system-ui, "Segoe UI", sans-serif;
|
||||
--font-rounded:
|
||||
"SF Pro Rounded", ui-sans-serif, system-ui, "Segoe UI", sans-serif;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
@media (prefers-color-scheme: dark) {
|
||||
/* Dark mode styles go here */
|
||||
:root {
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
a[href],
|
||||
button:not(:disabled),
|
||||
[role="button"]:not([aria-disabled="true"]) {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:disabled,
|
||||
[role="button"][aria-disabled="true"] {
|
||||
cursor: not-allowed;
|
||||
/* Example dark mode variables */
|
||||
--bg-color: #1a1a1a;
|
||||
--text-color: #ffffff;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,32 +28,3 @@
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes claude-connected-backdrop-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes claude-connected-dialog-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px) scale(0.98);
|
||||
}
|
||||
}
|
||||
|
||||
.claude-connected-backdrop {
|
||||
animation: claude-connected-backdrop-in 280ms ease-in-out both;
|
||||
}
|
||||
|
||||
.claude-connected-dialog {
|
||||
animation: claude-connected-dialog-in 345ms cubic-bezier(0.4, 0, 0.2, 1) both;
|
||||
will-change: opacity, transform;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.claude-connected-backdrop,
|
||||
.claude-connected-dialog {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
addClaudeModelSelection,
|
||||
claudeDesktopRecoveryMessage,
|
||||
claudeDesktopMaxModels,
|
||||
claudeDesktopMaxModelsMessage,
|
||||
claudeDesktopUsableSelection,
|
||||
defaultClaudeDesktopMaxModels,
|
||||
isClaudeConfigured,
|
||||
} from "./claudeDesktop";
|
||||
|
||||
describe("isClaudeConfigured", () => {
|
||||
it("keeps a failed configured profile switchable off", () => {
|
||||
expect(
|
||||
isClaudeConfigured({
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
configured: true,
|
||||
connected: false,
|
||||
running: false,
|
||||
startFailed: true,
|
||||
portConflict: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("claudeDesktopMaxModels", () => {
|
||||
it("falls back to the five literal Claude slots without a status", () => {
|
||||
expect(claudeDesktopMaxModels(undefined)).toBe(5);
|
||||
expect(
|
||||
claudeDesktopMaxModels({
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
connected: false,
|
||||
running: false,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
}),
|
||||
).toBe(defaultClaudeDesktopMaxModels);
|
||||
});
|
||||
|
||||
it("uses the server-provided limit when present", () => {
|
||||
expect(
|
||||
claudeDesktopMaxModels({
|
||||
supported: true,
|
||||
used: true,
|
||||
installed: true,
|
||||
connected: false,
|
||||
running: false,
|
||||
startFailed: false,
|
||||
portConflict: false,
|
||||
maxModels: 3,
|
||||
}),
|
||||
).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("claudeDesktopRecoveryMessage", () => {
|
||||
it("prefers current native guidance over stale action errors", () => {
|
||||
expect(
|
||||
claudeDesktopRecoveryMessage(
|
||||
"Cloud models are off. Select an installed model in Settings.",
|
||||
"Ollama could not open Claude.",
|
||||
),
|
||||
).toBe("Cloud models are off. Select an installed model in Settings.");
|
||||
});
|
||||
|
||||
it("clears after native recovery when no action error remains", () => {
|
||||
expect(claudeDesktopRecoveryMessage(undefined, null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("addClaudeModelSelection", () => {
|
||||
it("appends models below the limit", () => {
|
||||
expect(addClaudeModelSelection(["kimi-k3:cloud"], "qwen3:8b", 5)).toEqual({
|
||||
selection: ["kimi-k3:cloud", "qwen3:8b"],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a sixth selection with a clear message", () => {
|
||||
const selection = [
|
||||
"glm-5.2:cloud",
|
||||
"kimi-k3:cloud",
|
||||
"deepseek-v4-pro",
|
||||
"deepseek-v4-flash",
|
||||
"gemma4:26b:cloud",
|
||||
];
|
||||
const result = addClaudeModelSelection(selection, "qwen3:8b", 5);
|
||||
expect(result.selection).toBe(selection);
|
||||
expect(result.error).toBe(
|
||||
"Claude supports up to 5 models. Deselect one to add another.",
|
||||
);
|
||||
});
|
||||
|
||||
it("honors a smaller server-provided limit", () => {
|
||||
const result = addClaudeModelSelection(["qwen3:8b"], "llama3.2", 1);
|
||||
expect(result.selection).toEqual(["qwen3:8b"]);
|
||||
expect(result.error).toBe(claudeDesktopMaxModelsMessage(1));
|
||||
});
|
||||
|
||||
it("is a no-op for an already selected model", () => {
|
||||
expect(addClaudeModelSelection(["qwen3:8b"], "qwen3:8b", 5)).toEqual({
|
||||
selection: ["qwen3:8b"],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("claudeDesktopUsableSelection", () => {
|
||||
it("replaces unavailable paid selections with an available free model", () => {
|
||||
expect(
|
||||
claudeDesktopUsableSelection([
|
||||
{
|
||||
name: "glm-5.2:cloud",
|
||||
displayName: "glm-5.2:cloud",
|
||||
selected: true,
|
||||
availability: "unavailable",
|
||||
reason: "upgrade_required",
|
||||
requiredPlan: "pro",
|
||||
},
|
||||
{
|
||||
name: "gemma4:31b-cloud",
|
||||
displayName: "gemma4:31b-cloud",
|
||||
selected: false,
|
||||
availability: "available",
|
||||
requiredPlan: "free",
|
||||
},
|
||||
]),
|
||||
).toEqual(["gemma4:31b-cloud"]);
|
||||
});
|
||||
|
||||
it("preserves selected models that remain available", () => {
|
||||
expect(
|
||||
claudeDesktopUsableSelection([
|
||||
{
|
||||
name: "gemma4:31b-cloud",
|
||||
displayName: "gemma4:31b-cloud",
|
||||
selected: true,
|
||||
availability: "available",
|
||||
},
|
||||
{
|
||||
name: "qwen3:8b",
|
||||
displayName: "qwen3:8b",
|
||||
selected: false,
|
||||
availability: "available",
|
||||
},
|
||||
]),
|
||||
).toEqual(["gemma4:31b-cloud"]);
|
||||
});
|
||||
|
||||
it("selects all available recommendations for a default catalog", () => {
|
||||
expect(
|
||||
claudeDesktopUsableSelection(
|
||||
[
|
||||
{
|
||||
name: "glm-5.2:cloud",
|
||||
displayName: "glm-5.2:cloud",
|
||||
selected: false,
|
||||
availability: "available",
|
||||
},
|
||||
{
|
||||
name: "kimi-k3:cloud",
|
||||
displayName: "kimi-k3:cloud",
|
||||
selected: false,
|
||||
availability: "available",
|
||||
},
|
||||
],
|
||||
true,
|
||||
5,
|
||||
),
|
||||
).toEqual(["glm-5.2:cloud", "kimi-k3:cloud"]);
|
||||
});
|
||||
|
||||
it("returns no selection when no model is available", () => {
|
||||
expect(
|
||||
claudeDesktopUsableSelection([
|
||||
{
|
||||
name: "glm-5.2:cloud",
|
||||
displayName: "glm-5.2:cloud",
|
||||
selected: true,
|
||||
availability: "unavailable",
|
||||
},
|
||||
]),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,82 +0,0 @@
|
||||
import type {
|
||||
ClaudeDesktopModelStatus,
|
||||
ClaudeDesktopStatus,
|
||||
} from "@/types/webview";
|
||||
|
||||
export const CLAUDE_INSTALL_TIMEOUT_MS = 120_000;
|
||||
|
||||
export function isClaudeConnectionComplete(
|
||||
enabled: boolean,
|
||||
status: ClaudeDesktopStatus,
|
||||
) {
|
||||
const configured = isClaudeConfigured(status);
|
||||
return enabled
|
||||
? configured && status.connected && !status.startFailed
|
||||
: !configured;
|
||||
}
|
||||
|
||||
export function isClaudeConfigured(status: ClaudeDesktopStatus): boolean {
|
||||
return status.configured ?? status.connected;
|
||||
}
|
||||
|
||||
export function claudeDesktopRecoveryMessage(
|
||||
statusError?: string,
|
||||
actionError?: string | null,
|
||||
): string | null {
|
||||
return statusError || actionError || null;
|
||||
}
|
||||
|
||||
export function scheduleClaudeInstallTimeout(onTimeout: () => void) {
|
||||
return window.setTimeout(onTimeout, CLAUDE_INSTALL_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
// Claude Desktop has a bounded model list. The app supplies the limit when it
|
||||
// knows it; retain the existing five-model behavior for older app versions.
|
||||
export const defaultClaudeDesktopMaxModels = 5;
|
||||
|
||||
export function claudeDesktopMaxModels(
|
||||
status?: ClaudeDesktopStatus | null,
|
||||
): number {
|
||||
return status?.maxModels && status.maxModels > 0
|
||||
? status.maxModels
|
||||
: defaultClaudeDesktopMaxModels;
|
||||
}
|
||||
|
||||
export function claudeDesktopMaxModelsMessage(maxModels: number): string {
|
||||
return `Claude supports up to ${maxModels} models. Deselect one to add another.`;
|
||||
}
|
||||
|
||||
// Unavailable models remain visible for account guidance, but cannot remain
|
||||
// selected. Choose one available model when filtering would empty the list.
|
||||
export function claudeDesktopUsableSelection(
|
||||
models: ClaudeDesktopModelStatus[],
|
||||
selectAllAvailable = false,
|
||||
maxModels = defaultClaudeDesktopMaxModels,
|
||||
): string[] {
|
||||
const available = models.filter(
|
||||
(model) =>
|
||||
model.availability === undefined || model.availability === "available",
|
||||
);
|
||||
if (selectAllAvailable) {
|
||||
return available.slice(0, maxModels).map((model) => model.name);
|
||||
}
|
||||
const selected = available
|
||||
.filter((model) => model.selected)
|
||||
.map((model) => model.name);
|
||||
if (selected.length > 0) return selected;
|
||||
return available.length > 0 ? [available[0].name] : [];
|
||||
}
|
||||
|
||||
// addClaudeModelSelection returns the selection with name appended, or an
|
||||
// unchanged selection plus an error when the Claude model limit is reached.
|
||||
export function addClaudeModelSelection(
|
||||
selection: string[],
|
||||
name: string,
|
||||
maxModels: number,
|
||||
): { selection: string[]; error?: string } {
|
||||
if (selection.includes(name)) return { selection };
|
||||
if (selection.length >= maxModels) {
|
||||
return { selection, error: claudeDesktopMaxModelsMessage(maxModels) };
|
||||
}
|
||||
return { selection: [...selection, name] };
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
export interface IntegrationIcon {
|
||||
src: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const INTEGRATION_ICONS: Record<string, IntegrationIcon> = {
|
||||
"claude-desktop": { src: "/launch-icons/claude.svg" },
|
||||
claude: { src: "/launch-icons/claude-code.svg" },
|
||||
hermes: { src: "/launch-icons/hermes-agent.svg" },
|
||||
"hermes-desktop": { src: "/launch-icons/hermes-agent.svg" },
|
||||
openclaw: { src: "/launch-icons/openclaw.svg" },
|
||||
opencode: {
|
||||
src: "/launch-icons/opencode.svg",
|
||||
className: "h-7 w-7 rounded",
|
||||
},
|
||||
codex: { src: "/launch-icons/codex.svg" },
|
||||
copilot: { src: "/launch-icons/copilot.svg" },
|
||||
droid: { src: "/launch-icons/droid.svg" },
|
||||
dsh: { src: "/launch-icons/deepseek-harness.svg" },
|
||||
pi: { src: "/launch-icons/pi.svg" },
|
||||
cline: { src: "/launch-icons/cline.svg" },
|
||||
omp: { src: "/launch-icons/oh-my-pi.svg" },
|
||||
pool: { src: "/launch-icons/poolside.svg" },
|
||||
qwen: { src: "/launch-icons/qwen-code.svg" },
|
||||
};
|
||||
@@ -1,51 +0,0 @@
|
||||
// Keep in sync with store.CurrentOnboardingVersion in app/store/store.go.
|
||||
export const CURRENT_ONBOARDING_VERSION = 1;
|
||||
|
||||
export type OnboardingAuthMode = "signin" | "signup";
|
||||
|
||||
export function onboardingConnectUrl(
|
||||
connectUrl: string,
|
||||
mode: OnboardingAuthMode,
|
||||
): string {
|
||||
const url = new URL(connectUrl);
|
||||
url.searchParams.delete("launch");
|
||||
if (mode === "signup") {
|
||||
url.searchParams.set("signup", "true");
|
||||
} else {
|
||||
url.searchParams.delete("signup");
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
export const AUTHENTICATION_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
|
||||
export type OnboardingStep = "intro" | "welcome" | "apps" | "run";
|
||||
|
||||
export type OnboardingAction = "continue" | "authenticated" | "local";
|
||||
export type AuthenticationTimeoutAction = "ignore" | "defer" | "fail";
|
||||
|
||||
export function nextOnboardingStep(
|
||||
step: OnboardingStep,
|
||||
action: OnboardingAction,
|
||||
isAuthenticated: boolean,
|
||||
): OnboardingStep {
|
||||
if (action === "local") return "run";
|
||||
if (step === "intro" && action === "continue") {
|
||||
return isAuthenticated ? "apps" : "welcome";
|
||||
}
|
||||
if (step === "welcome" && action === "authenticated") return "apps";
|
||||
return step;
|
||||
}
|
||||
|
||||
export function authenticationTimeoutAction(
|
||||
settled: boolean,
|
||||
checking: boolean,
|
||||
): AuthenticationTimeoutAction {
|
||||
if (settled) return "ignore";
|
||||
if (checking) return "defer";
|
||||
return "fail";
|
||||
}
|
||||
|
||||
export function homeChatId(): "new" {
|
||||
return "new";
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
export function isWindowsPlatform(): boolean {
|
||||
if (typeof window !== "undefined" && window.OLLAMA_PLATFORM) {
|
||||
return window.OLLAMA_PLATFORM === "windows";
|
||||
}
|
||||
|
||||
return (
|
||||
typeof navigator !== "undefined" &&
|
||||
navigator.platform.toLowerCase().includes("win")
|
||||
);
|
||||
}
|
||||
@@ -12,8 +12,6 @@
|
||||
|
||||
import { Route as rootRoute } from './routes/__root'
|
||||
import { Route as SettingsImport } from './routes/settings'
|
||||
import { Route as OnboardingImport } from './routes/onboarding'
|
||||
import { Route as ConnectImport } from './routes/connect'
|
||||
import { Route as IndexImport } from './routes/index'
|
||||
import { Route as CChatIdImport } from './routes/c.$chatId'
|
||||
|
||||
@@ -25,18 +23,6 @@ const SettingsRoute = SettingsImport.update({
|
||||
getParentRoute: () => rootRoute,
|
||||
} as any)
|
||||
|
||||
const OnboardingRoute = OnboardingImport.update({
|
||||
id: '/onboarding',
|
||||
path: '/onboarding',
|
||||
getParentRoute: () => rootRoute,
|
||||
} as any)
|
||||
|
||||
const ConnectRoute = ConnectImport.update({
|
||||
id: '/connect',
|
||||
path: '/connect',
|
||||
getParentRoute: () => rootRoute,
|
||||
} as any)
|
||||
|
||||
const IndexRoute = IndexImport.update({
|
||||
id: '/',
|
||||
path: '/',
|
||||
@@ -60,20 +46,6 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof IndexImport
|
||||
parentRoute: typeof rootRoute
|
||||
}
|
||||
'/connect': {
|
||||
id: '/connect'
|
||||
path: '/connect'
|
||||
fullPath: '/connect'
|
||||
preLoaderRoute: typeof ConnectImport
|
||||
parentRoute: typeof rootRoute
|
||||
}
|
||||
'/onboarding': {
|
||||
id: '/onboarding'
|
||||
path: '/onboarding'
|
||||
fullPath: '/onboarding'
|
||||
preLoaderRoute: typeof OnboardingImport
|
||||
parentRoute: typeof rootRoute
|
||||
}
|
||||
'/settings': {
|
||||
id: '/settings'
|
||||
path: '/settings'
|
||||
@@ -95,16 +67,12 @@ declare module '@tanstack/react-router' {
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof IndexRoute
|
||||
'/connect': typeof ConnectRoute
|
||||
'/onboarding': typeof OnboardingRoute
|
||||
'/settings': typeof SettingsRoute
|
||||
'/c/$chatId': typeof CChatIdRoute
|
||||
}
|
||||
|
||||
export interface FileRoutesByTo {
|
||||
'/': typeof IndexRoute
|
||||
'/connect': typeof ConnectRoute
|
||||
'/onboarding': typeof OnboardingRoute
|
||||
'/settings': typeof SettingsRoute
|
||||
'/c/$chatId': typeof CChatIdRoute
|
||||
}
|
||||
@@ -112,33 +80,27 @@ export interface FileRoutesByTo {
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRoute
|
||||
'/': typeof IndexRoute
|
||||
'/connect': typeof ConnectRoute
|
||||
'/onboarding': typeof OnboardingRoute
|
||||
'/settings': typeof SettingsRoute
|
||||
'/c/$chatId': typeof CChatIdRoute
|
||||
}
|
||||
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths: '/' | '/connect' | '/onboarding' | '/settings' | '/c/$chatId'
|
||||
fullPaths: '/' | '/settings' | '/c/$chatId'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to: '/' | '/connect' | '/onboarding' | '/settings' | '/c/$chatId'
|
||||
id: '__root__' | '/' | '/connect' | '/onboarding' | '/settings' | '/c/$chatId'
|
||||
to: '/' | '/settings' | '/c/$chatId'
|
||||
id: '__root__' | '/' | '/settings' | '/c/$chatId'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
|
||||
export interface RootRouteChildren {
|
||||
IndexRoute: typeof IndexRoute
|
||||
ConnectRoute: typeof ConnectRoute
|
||||
OnboardingRoute: typeof OnboardingRoute
|
||||
SettingsRoute: typeof SettingsRoute
|
||||
CChatIdRoute: typeof CChatIdRoute
|
||||
}
|
||||
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
IndexRoute: IndexRoute,
|
||||
ConnectRoute: ConnectRoute,
|
||||
OnboardingRoute: OnboardingRoute,
|
||||
SettingsRoute: SettingsRoute,
|
||||
CChatIdRoute: CChatIdRoute,
|
||||
}
|
||||
@@ -154,8 +116,6 @@ export const routeTree = rootRoute
|
||||
"filePath": "__root.tsx",
|
||||
"children": [
|
||||
"/",
|
||||
"/connect",
|
||||
"/onboarding",
|
||||
"/settings",
|
||||
"/c/$chatId"
|
||||
]
|
||||
@@ -163,12 +123,6 @@ export const routeTree = rootRoute
|
||||
"/": {
|
||||
"filePath": "index.tsx"
|
||||
},
|
||||
"/connect": {
|
||||
"filePath": "connect.tsx"
|
||||
},
|
||||
"/onboarding": {
|
||||
"filePath": "onboarding.tsx"
|
||||
},
|
||||
"/settings": {
|
||||
"filePath": "settings.tsx"
|
||||
},
|
||||
|
||||
@@ -1,25 +1,40 @@
|
||||
import { createFileRoute, redirect } from "@tanstack/react-router";
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { useChat } from "@/hooks/useChats";
|
||||
import Chat from "@/components/Chat";
|
||||
import { getChat } from "@/api";
|
||||
import { SidebarLayout } from "@/components/layout/layout";
|
||||
import { ChatSidebar } from "@/components/ChatSidebar";
|
||||
import { useEffect } from "react";
|
||||
import LaunchCommands from "@/components/LaunchCommands";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useSettings } from "@/hooks/useSettings";
|
||||
|
||||
const launchSidebarRequestedKey = "ollama.launchSidebarRequested";
|
||||
const launchSidebarSeenKey = "ollama.launchSidebarSeen";
|
||||
const fallbackSessionState = new Map<string, string>();
|
||||
|
||||
function getSessionState() {
|
||||
if (typeof sessionStorage !== "undefined") {
|
||||
return sessionStorage;
|
||||
}
|
||||
|
||||
return {
|
||||
getItem(key: string) {
|
||||
return fallbackSessionState.get(key) ?? null;
|
||||
},
|
||||
setItem(key: string, value: string) {
|
||||
fallbackSessionState.set(key, value);
|
||||
},
|
||||
removeItem(key: string) {
|
||||
fallbackSessionState.delete(key);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/c/$chatId")({
|
||||
component: RouteComponent,
|
||||
beforeLoad: ({ params }) => {
|
||||
if (params.chatId === "launch") {
|
||||
throw redirect({
|
||||
to: "/c/$chatId",
|
||||
params: { chatId: "new" },
|
||||
mask: { to: "/" },
|
||||
});
|
||||
}
|
||||
},
|
||||
loader: async ({ context, params }) => {
|
||||
if (params.chatId !== "new") {
|
||||
// Skip loading for special non-chat views
|
||||
if (params.chatId !== "new" && params.chatId !== "launch") {
|
||||
context.queryClient.ensureQueryData({
|
||||
queryKey: ["chat", params.chatId],
|
||||
queryFn: () => getChat(params.chatId),
|
||||
@@ -32,19 +47,61 @@ export const Route = createFileRoute("/c/$chatId")({
|
||||
function RouteComponent() {
|
||||
const { chatId } = Route.useParams();
|
||||
const { settingsData, setSettings } = useSettings();
|
||||
const previousChatIdRef = useRef<string | null>(null);
|
||||
|
||||
// Always call hooks at the top level - use a flag to skip data when chatId is a special view
|
||||
const {
|
||||
data: chatData,
|
||||
isLoading: chatLoading,
|
||||
error: chatError,
|
||||
} = useChat(chatId === "new" ? "" : chatId);
|
||||
} = useChat(chatId === "new" || chatId === "launch" ? "" : chatId);
|
||||
|
||||
useEffect(() => {
|
||||
if (!settingsData) {
|
||||
return;
|
||||
}
|
||||
|
||||
const previousChatId = previousChatIdRef.current;
|
||||
previousChatIdRef.current = chatId;
|
||||
|
||||
if (chatId === "launch") {
|
||||
const sessionState = getSessionState();
|
||||
const shouldOpenSidebar =
|
||||
previousChatId !== "launch" &&
|
||||
(() => {
|
||||
if (sessionState.getItem(launchSidebarRequestedKey) === "1") {
|
||||
sessionState.removeItem(launchSidebarRequestedKey);
|
||||
sessionState.setItem(launchSidebarSeenKey, "1");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (sessionState.getItem(launchSidebarSeenKey) !== "1") {
|
||||
sessionState.setItem(launchSidebarSeenKey, "1");
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
})();
|
||||
const updates: { LastHomeView?: string; SidebarOpen?: boolean } = {};
|
||||
|
||||
if (settingsData.LastHomeView !== "launch") {
|
||||
updates.LastHomeView = "launch";
|
||||
}
|
||||
|
||||
if (shouldOpenSidebar && !settingsData.SidebarOpen) {
|
||||
updates.SidebarOpen = true;
|
||||
}
|
||||
|
||||
if (Object.keys(updates).length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSettings(updates).catch(() => {
|
||||
// Best effort persistence for home view preference.
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (settingsData.LastHomeView === "chat") {
|
||||
return;
|
||||
}
|
||||
@@ -63,6 +120,14 @@ function RouteComponent() {
|
||||
);
|
||||
}
|
||||
|
||||
if (chatId === "launch") {
|
||||
return (
|
||||
<SidebarLayout sidebar={<ChatSidebar currentChatId={chatId} />}>
|
||||
<LaunchCommands />
|
||||
</SidebarLayout>
|
||||
);
|
||||
}
|
||||
|
||||
// Handle existing chat case
|
||||
if (chatLoading) {
|
||||
return (
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import { AppSidebar } from "@/components/AppSidebar";
|
||||
import { ConnectAppsScreen } from "@/components/Onboarding";
|
||||
import { SidebarLayout } from "@/components/layout/layout";
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
export const Route = createFileRoute("/connect")({
|
||||
component: ConnectRoute,
|
||||
});
|
||||
|
||||
function ConnectRoute() {
|
||||
return (
|
||||
<SidebarLayout
|
||||
title="Connect your apps"
|
||||
sidebar={<AppSidebar current="apps" />}
|
||||
>
|
||||
<ConnectAppsScreen />
|
||||
</SidebarLayout>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { createFileRoute, redirect } from "@tanstack/react-router";
|
||||
import { getSettings } from "@/api";
|
||||
import { CURRENT_ONBOARDING_VERSION, homeChatId } from "@/lib/onboarding";
|
||||
|
||||
export const Route = createFileRoute("/")({
|
||||
beforeLoad: async ({ context }) => {
|
||||
@@ -8,11 +7,8 @@ export const Route = createFileRoute("/")({
|
||||
queryKey: ["settings"],
|
||||
queryFn: getSettings,
|
||||
});
|
||||
if (settingsData.settings.OnboardingVersion < CURRENT_ONBOARDING_VERSION) {
|
||||
throw redirect({ to: "/onboarding" });
|
||||
}
|
||||
|
||||
const chatId = homeChatId();
|
||||
const chatId =
|
||||
settingsData?.settings?.LastHomeView === "chat" ? "new" : "launch";
|
||||
|
||||
throw redirect({
|
||||
to: "/c/$chatId",
|
||||
|
||||
@@ -1,198 +0,0 @@
|
||||
import Onboarding from "@/components/Onboarding";
|
||||
import { getSettings } from "@/api";
|
||||
import { useSettings } from "@/hooks/useSettings";
|
||||
import { useUser } from "@/hooks/useUser";
|
||||
import {
|
||||
AUTHENTICATION_TIMEOUT_MS,
|
||||
authenticationTimeoutAction,
|
||||
CURRENT_ONBOARDING_VERSION,
|
||||
homeChatId,
|
||||
onboardingConnectUrl,
|
||||
type OnboardingAuthMode,
|
||||
} from "@/lib/onboarding";
|
||||
import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
export const Route = createFileRoute("/onboarding")({
|
||||
beforeLoad: async ({ context }) => {
|
||||
// Let developers review onboarding without resetting their local app data.
|
||||
if (
|
||||
import.meta.env.DEV &&
|
||||
new URLSearchParams(window.location.search).get("preview") === "1"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const settingsData = await context.queryClient.ensureQueryData({
|
||||
queryKey: ["settings"],
|
||||
queryFn: getSettings,
|
||||
});
|
||||
|
||||
if (settingsData.settings.OnboardingVersion >= CURRENT_ONBOARDING_VERSION) {
|
||||
const chatId = homeChatId();
|
||||
throw redirect({
|
||||
to: "/c/$chatId",
|
||||
params: { chatId },
|
||||
mask: { to: "/" },
|
||||
});
|
||||
}
|
||||
},
|
||||
component: OnboardingRoute,
|
||||
});
|
||||
|
||||
function OnboardingRoute() {
|
||||
const navigate = useNavigate();
|
||||
const { settingsData, setSettings } = useSettings();
|
||||
const { fetchConnectUrl, refetchUser, isAuthenticated } = useUser();
|
||||
const [isAwaitingAuth, setIsAwaitingAuth] = useState(false);
|
||||
const [signInError, setSignInError] = useState<string | null>(null);
|
||||
const [completionError, setCompletionError] = useState<string | null>(null);
|
||||
const authAttemptRef = useRef(0);
|
||||
|
||||
const completeOnboarding = useCallback(async (): Promise<boolean> => {
|
||||
setCompletionError(null);
|
||||
|
||||
try {
|
||||
if (!settingsData) {
|
||||
throw new Error("Settings are not loaded");
|
||||
}
|
||||
|
||||
await setSettings({
|
||||
OnboardingVersion: CURRENT_ONBOARDING_VERSION,
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Failed to save onboarding state:", error);
|
||||
setCompletionError("Unable to save setup. Please try again.");
|
||||
return false;
|
||||
}
|
||||
}, [setSettings, settingsData]);
|
||||
|
||||
const finishSetup = useCallback(() => {
|
||||
void completeOnboarding();
|
||||
}, [completeOnboarding]);
|
||||
|
||||
const openApps = useCallback(async (): Promise<boolean> => {
|
||||
if (!(await completeOnboarding())) return false;
|
||||
await navigate({ to: "/connect" });
|
||||
return true;
|
||||
}, [completeOnboarding, navigate]);
|
||||
|
||||
const retryCompletion = useCallback(() => {
|
||||
void completeOnboarding();
|
||||
}, [completeOnboarding]);
|
||||
|
||||
const authenticate = useCallback(
|
||||
async (mode: OnboardingAuthMode) => {
|
||||
setSignInError(null);
|
||||
|
||||
if (isAuthenticated) {
|
||||
return;
|
||||
}
|
||||
|
||||
const authAttempt = ++authAttemptRef.current;
|
||||
setIsAwaitingAuth(true);
|
||||
|
||||
try {
|
||||
const result = await fetchConnectUrl();
|
||||
if (authAttempt !== authAttemptRef.current) return;
|
||||
if (!result.data) {
|
||||
throw new Error("No sign-in URL was returned");
|
||||
}
|
||||
|
||||
window.open(onboardingConnectUrl(result.data, mode), "_blank");
|
||||
} catch (error) {
|
||||
if (authAttempt !== authAttemptRef.current) return;
|
||||
console.error("Failed to start sign in:", error);
|
||||
setIsAwaitingAuth(false);
|
||||
setSignInError("Unable to start sign in. Please try again.");
|
||||
}
|
||||
},
|
||||
[fetchConnectUrl, isAuthenticated],
|
||||
);
|
||||
|
||||
const signIn = useCallback(() => authenticate("signin"), [authenticate]);
|
||||
const signUp = useCallback(() => authenticate("signup"), [authenticate]);
|
||||
|
||||
const useLocal = useCallback(() => {
|
||||
authAttemptRef.current += 1;
|
||||
setIsAwaitingAuth(false);
|
||||
setSignInError(null);
|
||||
finishSetup();
|
||||
}, [finishSetup]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAwaitingAuth) return;
|
||||
|
||||
let checking = false;
|
||||
let settled = false;
|
||||
let timeoutPending = false;
|
||||
const authAttempt = authAttemptRef.current;
|
||||
|
||||
const failConnection = () => {
|
||||
if (settled || authAttempt !== authAttemptRef.current) return;
|
||||
settled = true;
|
||||
setIsAwaitingAuth(false);
|
||||
setSignInError(
|
||||
"Connection is taking longer than expected. Please try again.",
|
||||
);
|
||||
};
|
||||
|
||||
const checkConnection = async () => {
|
||||
if (checking || settled || authAttempt !== authAttemptRef.current) return;
|
||||
checking = true;
|
||||
|
||||
try {
|
||||
const result = await refetchUser();
|
||||
if (
|
||||
!settled &&
|
||||
authAttempt === authAttemptRef.current &&
|
||||
result.data?.name
|
||||
) {
|
||||
settled = true;
|
||||
setIsAwaitingAuth(false);
|
||||
window.activateOllama?.();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to check sign-in status:", error);
|
||||
} finally {
|
||||
checking = false;
|
||||
if (timeoutPending) failConnection();
|
||||
}
|
||||
};
|
||||
|
||||
void checkConnection();
|
||||
const pollingInterval = window.setInterval(checkConnection, 1000);
|
||||
const timeout = window.setTimeout(() => {
|
||||
const action = authenticationTimeoutAction(settled, checking);
|
||||
if (action === "ignore") return;
|
||||
if (action === "defer") {
|
||||
timeoutPending = true;
|
||||
return;
|
||||
}
|
||||
failConnection();
|
||||
}, AUTHENTICATION_TIMEOUT_MS);
|
||||
|
||||
window.addEventListener("focus", checkConnection);
|
||||
return () => {
|
||||
settled = true;
|
||||
window.clearInterval(pollingInterval);
|
||||
window.clearTimeout(timeout);
|
||||
window.removeEventListener("focus", checkConnection);
|
||||
};
|
||||
}, [isAwaitingAuth, refetchUser]);
|
||||
|
||||
return (
|
||||
<Onboarding
|
||||
completionError={completionError}
|
||||
isAuthenticated={isAuthenticated}
|
||||
isSigningIn={isAwaitingAuth}
|
||||
signInError={signInError}
|
||||
onOpenApps={openApps}
|
||||
onSignIn={signIn}
|
||||
onSignUp={signUp}
|
||||
onRetryCompletion={retryCompletion}
|
||||
onUseLocal={useLocal}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,16 +1,6 @@
|
||||
import { AppSidebar } from "@/components/AppSidebar";
|
||||
import { SidebarLayout } from "@/components/layout/layout";
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import Settings from "@/components/Settings";
|
||||
|
||||
export const Route = createFileRoute("/settings")({
|
||||
component: SettingsRoute,
|
||||
component: Settings,
|
||||
});
|
||||
|
||||
function SettingsRoute() {
|
||||
return (
|
||||
<SidebarLayout title="Settings" sidebar={<AppSidebar current="settings" />}>
|
||||
<Settings />
|
||||
</SidebarLayout>
|
||||
);
|
||||
}
|
||||
@@ -12,45 +12,6 @@ interface MenuItem {
|
||||
separator?: boolean;
|
||||
}
|
||||
|
||||
interface ClaudeDesktopStatus {
|
||||
supported: boolean;
|
||||
used: boolean;
|
||||
installed: boolean;
|
||||
configured?: boolean;
|
||||
connected: boolean;
|
||||
running: boolean;
|
||||
startFailed: boolean;
|
||||
portConflict: boolean;
|
||||
gatewayPort?: number;
|
||||
error?: string;
|
||||
modelSource?: "user" | "endpoint" | "fallback";
|
||||
maxModels?: number;
|
||||
models?: ClaudeDesktopModelStatus[];
|
||||
}
|
||||
|
||||
interface ClaudeDesktopModelStatus {
|
||||
name: string;
|
||||
displayName: string;
|
||||
description?: string;
|
||||
cloud?: boolean;
|
||||
selected: boolean;
|
||||
availability?: "unknown" | "available" | "unavailable";
|
||||
reason?:
|
||||
| "cloud_off"
|
||||
| "sign_in_required"
|
||||
| "upgrade_required"
|
||||
| "verification_unavailable"
|
||||
| "model_not_installed";
|
||||
requiredPlan?: string;
|
||||
}
|
||||
|
||||
interface ClaudeDesktopActionResult {
|
||||
status: ClaudeDesktopStatus;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
type ClaudeDesktopInstallResult = "opened" | "cancelled" | "failed";
|
||||
|
||||
interface WebviewAPI {
|
||||
selectFile: () => Promise<ImageData | null>;
|
||||
selectMultipleFiles: () => Promise<ImageData[] | null>;
|
||||
@@ -63,24 +24,9 @@ declare global {
|
||||
webview?: WebviewAPI;
|
||||
drag?: () => void;
|
||||
doubleClick?: () => void;
|
||||
activateOllama?: () => void;
|
||||
getClaudeDesktopStatus?: () => Promise<ClaudeDesktopStatus>;
|
||||
setClaudeDesktopConnected?: (
|
||||
enabled: boolean,
|
||||
) => Promise<ClaudeDesktopActionResult>;
|
||||
prepareClaudeDesktopConnection?: () => Promise<ClaudeDesktopActionResult>;
|
||||
openClaudeDesktop?: () => Promise<string>;
|
||||
installClaudeDesktop?: () => Promise<ClaudeDesktopInstallResult>;
|
||||
getShowAppsInMenu?: () => Promise<boolean>;
|
||||
setShowAppsInMenu?: (visible: boolean) => Promise<void>;
|
||||
restartClaudeDesktop?: (
|
||||
models: string[],
|
||||
) => Promise<ClaudeDesktopActionResult>;
|
||||
setOnboardingWindow?: (enabled: boolean) => void;
|
||||
menu: (items: MenuItem[]) => Promise<string | null>;
|
||||
OLLAMA_TOOLS?: boolean;
|
||||
OLLAMA_WEBSEARCH?: boolean;
|
||||
OLLAMA_PLATFORM?: "darwin" | "windows";
|
||||
}
|
||||
|
||||
namespace JSX {
|
||||
@@ -100,13 +46,4 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
export type {
|
||||
ClaudeDesktopActionResult,
|
||||
ClaudeDesktopInstallResult,
|
||||
ClaudeDesktopModelStatus,
|
||||
ClaudeDesktopStatus,
|
||||
ContextMenuItem,
|
||||
ContextMenuResult,
|
||||
ImageData,
|
||||
WebviewAPI,
|
||||
};
|
||||
export type { ImageData, WebviewAPI, ContextMenuItem, ContextMenuResult };
|
||||
@@ -31,7 +31,6 @@ import (
|
||||
"github.com/ollama/ollama/app/updater"
|
||||
"github.com/ollama/ollama/app/version"
|
||||
ollamaAuth "github.com/ollama/ollama/auth"
|
||||
"github.com/ollama/ollama/cmd/launch"
|
||||
"github.com/ollama/ollama/envconfig"
|
||||
"github.com/ollama/ollama/manifest"
|
||||
"github.com/ollama/ollama/types/model"
|
||||
@@ -111,10 +110,8 @@ type Server struct {
|
||||
Dev bool
|
||||
|
||||
// Updater for checking and downloading updates
|
||||
Updater *updater.Updater
|
||||
UpdateAvailableFunc func()
|
||||
IntegrationInstalled func(string) bool
|
||||
ListCloudModels func(context.Context) (*api.ListResponse, error)
|
||||
Updater *updater.Updater
|
||||
UpdateAvailableFunc func()
|
||||
}
|
||||
|
||||
func (s *Server) log() *slog.Logger {
|
||||
@@ -295,8 +292,6 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.Handle("POST /api/v1/settings", handle(s.settings))
|
||||
mux.Handle("GET /api/v1/cloud", handle(s.getCloudSetting))
|
||||
mux.Handle("POST /api/v1/cloud", handle(s.cloudSetting))
|
||||
mux.Handle("GET /api/v1/models/cloud", handle(s.getCloudModels))
|
||||
mux.Handle("GET /api/v1/integrations", handle(s.getIntegrationStatuses))
|
||||
|
||||
// Ollama proxy endpoints
|
||||
ollamaProxy := s.ollamaProxy()
|
||||
@@ -319,74 +314,6 @@ func (s *Server) Handler() http.Handler {
|
||||
return mux
|
||||
}
|
||||
|
||||
func (s *Server) getIntegrationStatuses(w http.ResponseWriter, _ *http.Request) error {
|
||||
isInstalled := s.IntegrationInstalled
|
||||
if isInstalled == nil {
|
||||
isInstalled = launch.IsIntegrationInstalled
|
||||
}
|
||||
|
||||
type integrationStatus struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Installed *bool `json:"installed,omitempty"`
|
||||
Action string `json:"action"`
|
||||
Command string `json:"command,omitempty"`
|
||||
}
|
||||
|
||||
infos := launch.ListIntegrationInfos()
|
||||
statuses := make([]integrationStatus, 0, len(infos)+2)
|
||||
claudeDesktopInstalled := isInstalled("claude-desktop")
|
||||
statuses = append(statuses, integrationStatus{
|
||||
ID: "claude-desktop",
|
||||
Name: "Claude",
|
||||
Description: "Use Ollama models in Claude Desktop",
|
||||
Installed: &claudeDesktopInstalled,
|
||||
Action: "connect",
|
||||
})
|
||||
|
||||
byName := make(map[string]launch.IntegrationInfo, len(infos))
|
||||
for _, info := range infos {
|
||||
byName[info.Name] = info
|
||||
}
|
||||
seen := map[string]bool{"chatgpt": true}
|
||||
launcherMenuOrder := []string{"claude", "codex", "openclaw", "opencode", "droid", "pi", "cline"}
|
||||
orderedInfos := make([]launch.IntegrationInfo, 0, len(infos))
|
||||
for _, name := range launcherMenuOrder {
|
||||
if info, ok := byName[name]; ok {
|
||||
orderedInfos = append(orderedInfos, info)
|
||||
seen[name] = true
|
||||
}
|
||||
}
|
||||
for _, info := range infos {
|
||||
if !seen[info.Name] {
|
||||
orderedInfos = append(orderedInfos, info)
|
||||
}
|
||||
}
|
||||
|
||||
for _, info := range orderedInfos {
|
||||
installed := isInstalled(info.Name)
|
||||
statuses = append(statuses, integrationStatus{
|
||||
ID: info.Name,
|
||||
Name: info.DisplayName,
|
||||
Description: info.Description,
|
||||
Installed: &installed,
|
||||
Action: "copy",
|
||||
Command: "ollama launch " + info.Name,
|
||||
})
|
||||
}
|
||||
|
||||
statuses = append(statuses, integrationStatus{
|
||||
ID: "terminal",
|
||||
Name: "Terminal",
|
||||
Description: "Run local models from your terminal",
|
||||
Action: "copy",
|
||||
Command: "ollama",
|
||||
})
|
||||
|
||||
return json.NewEncoder(w).Encode(statuses)
|
||||
}
|
||||
|
||||
// handleError renders appropriate error responses based on request type
|
||||
func (s *Server) handleError(w http.ResponseWriter, e error) {
|
||||
// Preserve CORS headers for API requests
|
||||
@@ -1537,27 +1464,11 @@ func (s *Server) settings(w http.ResponseWriter, r *http.Request) error {
|
||||
return fmt.Errorf("failed to load settings: %w", err)
|
||||
}
|
||||
|
||||
var request struct {
|
||||
store.Settings
|
||||
OnboardingVersion *int
|
||||
ClaudeDesktopUsed *bool
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
var settings store.Settings
|
||||
if err := json.NewDecoder(r.Body).Decode(&settings); err != nil {
|
||||
return fmt.Errorf("invalid request body: %w", err)
|
||||
}
|
||||
|
||||
settings := request.Settings
|
||||
if request.OnboardingVersion == nil {
|
||||
settings.OnboardingVersion = old.OnboardingVersion
|
||||
} else {
|
||||
settings.OnboardingVersion = *request.OnboardingVersion
|
||||
}
|
||||
if request.ClaudeDesktopUsed == nil {
|
||||
settings.ClaudeDesktopUsed = old.ClaudeDesktopUsed
|
||||
} else {
|
||||
settings.ClaudeDesktopUsed = *request.ClaudeDesktopUsed
|
||||
}
|
||||
|
||||
if err := s.Store.SetSettings(settings); err != nil {
|
||||
return fmt.Errorf("failed to save settings: %w", err)
|
||||
}
|
||||
@@ -1626,58 +1537,6 @@ func (s *Server) writeCloudStatus(w http.ResponseWriter) error {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) getCloudModels(w http.ResponseWriter, r *http.Request) error {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
disabled, _, err := s.Store.CloudStatus()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load cloud status: %w", err)
|
||||
}
|
||||
if disabled {
|
||||
return json.NewEncoder(w).Encode(api.ListResponse{Models: []api.ListModelResponse{}})
|
||||
}
|
||||
|
||||
list := s.ListCloudModels
|
||||
if list == nil {
|
||||
list = s.listCloudModels
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
models, err := list(ctx)
|
||||
if err != nil {
|
||||
var authErr api.AuthorizationError
|
||||
if errors.As(err, &authErr) && (authErr.StatusCode == http.StatusUnauthorized || authErr.StatusCode == http.StatusForbidden) {
|
||||
return json.NewEncoder(w).Encode(api.ListResponse{Models: []api.ListModelResponse{}})
|
||||
}
|
||||
return fmt.Errorf("failed to list cloud models: %w", err)
|
||||
}
|
||||
if models == nil {
|
||||
models = &api.ListResponse{Models: []api.ListModelResponse{}}
|
||||
}
|
||||
|
||||
return json.NewEncoder(w).Encode(models)
|
||||
}
|
||||
|
||||
func (s *Server) listCloudModels(ctx context.Context) (*api.ListResponse, error) {
|
||||
resp, err := s.doSelfSigned(ctx, http.MethodGet, "/api/tags")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
|
||||
return nil, api.AuthorizationError{StatusCode: resp.StatusCode}
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("ollama.com/api/tags returned %s", resp.Status)
|
||||
}
|
||||
|
||||
var models api.ListResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&models); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse cloud models: %w", err)
|
||||
}
|
||||
return &models, nil
|
||||
}
|
||||
|
||||
func (s *Server) getInferenceCompute(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
@@ -18,7 +18,6 @@ import (
|
||||
"github.com/ollama/ollama/api"
|
||||
"github.com/ollama/ollama/app/store"
|
||||
"github.com/ollama/ollama/app/updater"
|
||||
"github.com/ollama/ollama/cmd/launch"
|
||||
)
|
||||
|
||||
func TestHandlePostApiSettings(t *testing.T) {
|
||||
@@ -120,80 +119,6 @@ func TestHandlePostApiSettings(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetIntegrationStatuses(t *testing.T) {
|
||||
server := &Server{
|
||||
IntegrationInstalled: func(name string) bool {
|
||||
return name == "claude-desktop" || name == "codex"
|
||||
},
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/integrations", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
if err := server.getIntegrationStatuses(rr, req); err != nil {
|
||||
t.Fatalf("getIntegrationStatuses() error = %v", err)
|
||||
}
|
||||
|
||||
var got []struct {
|
||||
ID string `json:"id"`
|
||||
Installed *bool `json:"installed"`
|
||||
Action string `json:"action"`
|
||||
Command string `json:"command"`
|
||||
}
|
||||
if err := json.NewDecoder(rr.Body).Decode(&got); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
|
||||
if len(got) < 5 {
|
||||
t.Fatalf("got %d integrations, want the full registry", len(got))
|
||||
}
|
||||
if got[0].ID != "claude-desktop" || got[0].Action != "connect" || got[0].Command != "" {
|
||||
t.Fatalf("first integration = %+v, want command-free Claude Desktop connect", got[0])
|
||||
}
|
||||
wantPrefix := []string{"claude-desktop", "claude", "codex", "openclaw", "opencode", "droid", "pi", "cline"}
|
||||
for i, want := range wantPrefix {
|
||||
if got[i].ID != want {
|
||||
t.Fatalf("integration %d = %q, want launcher menu order entry %q", i, got[i].ID, want)
|
||||
}
|
||||
}
|
||||
byID := make(map[string]struct {
|
||||
Installed *bool
|
||||
Action string
|
||||
Command string
|
||||
}, len(got))
|
||||
for _, item := range got {
|
||||
byID[item.ID] = struct {
|
||||
Installed *bool
|
||||
Action string
|
||||
Command string
|
||||
}{item.Installed, item.Action, item.Command}
|
||||
}
|
||||
|
||||
for name, want := range map[string]bool{
|
||||
"claude-desktop": true,
|
||||
"opencode": false,
|
||||
"codex": true,
|
||||
} {
|
||||
item, ok := byID[name]
|
||||
if !ok || item.Installed == nil || *item.Installed != want {
|
||||
t.Errorf("%s installed = %v, want %v", name, item.Installed, want)
|
||||
}
|
||||
}
|
||||
if item, ok := byID["claude"]; !ok || item.Command != "ollama launch claude" {
|
||||
t.Fatal("Claude Code should follow Claude Desktop with its launch command")
|
||||
}
|
||||
if _, ok := byID["chatgpt"]; ok {
|
||||
t.Fatal("ChatGPT should be excluded from onboarding integrations")
|
||||
}
|
||||
wantCount := len(launch.ListIntegrationInfos()) + 1 // Claude Desktop and Terminal replace omitted ChatGPT.
|
||||
if len(got) != wantCount {
|
||||
t.Fatalf("got %d integrations, want %d launcher entries", len(got), wantCount)
|
||||
}
|
||||
terminal := got[len(got)-1]
|
||||
if terminal.ID != "terminal" || terminal.Installed != nil || terminal.Command != "ollama" {
|
||||
t.Fatalf("last integration = %+v, want Terminal without install status", terminal)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlePostApiCloudSetting(t *testing.T) {
|
||||
tmpHome := t.TempDir()
|
||||
t.Setenv("HOME", tmpHome)
|
||||
@@ -602,63 +527,6 @@ func TestUserAgentTransport(t *testing.T) {
|
||||
t.Logf("User-Agent transport successfully set: %s", receivedUA)
|
||||
}
|
||||
|
||||
func TestGetCloudModels(t *testing.T) {
|
||||
t.Run("does not call ollama.com when cloud is disabled", func(t *testing.T) {
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
t.Setenv("OLLAMA_NO_CLOUD", "1")
|
||||
testStore := &store.Store{DBPath: filepath.Join(t.TempDir(), "db.sqlite")}
|
||||
defer testStore.Close()
|
||||
|
||||
server := &Server{
|
||||
Store: testStore,
|
||||
ListCloudModels: func(context.Context) (*api.ListResponse, error) {
|
||||
t.Fatal("cloud model list called while cloud was disabled")
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/models/cloud", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
if err := server.getCloudModels(rr, req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var got api.ListResponse
|
||||
if err := json.NewDecoder(rr.Body).Decode(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Models) != 0 {
|
||||
t.Fatalf("models = %+v, want none", got.Models)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("returns no cloud models when account is unauthorized", func(t *testing.T) {
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
t.Setenv("OLLAMA_NO_CLOUD", "")
|
||||
testStore := &store.Store{DBPath: filepath.Join(t.TempDir(), "db.sqlite")}
|
||||
defer testStore.Close()
|
||||
|
||||
server := &Server{
|
||||
Store: testStore,
|
||||
ListCloudModels: func(context.Context) (*api.ListResponse, error) {
|
||||
return nil, api.AuthorizationError{StatusCode: http.StatusUnauthorized}
|
||||
},
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/models/cloud", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
if err := server.getCloudModels(rr, req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var got api.ListResponse
|
||||
if err := json.NewDecoder(rr.Body).Decode(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Models) != 0 {
|
||||
t.Fatalf("models = %+v, want none", got.Models)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestInferenceClientUsesUserAgent(t *testing.T) {
|
||||
var gotUserAgent atomic.Value
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -850,100 +718,6 @@ func TestSettingsToggleAutoUpdateOff_CancelsDownload(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsPreservesOnboardingVersionWhenOmitted(t *testing.T) {
|
||||
testStore := &store.Store{
|
||||
DBPath: filepath.Join(t.TempDir(), "db.sqlite"),
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
settings, err := testStore.Settings()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings.OnboardingVersion = 1
|
||||
if err := testStore.SetSettings(settings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(settings)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var fields map[string]any
|
||||
if err := json.Unmarshal(payload, &fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
delete(fields, "OnboardingVersion")
|
||||
payload, err = json.Marshal(fields)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
server := &Server{
|
||||
Store: testStore,
|
||||
Restart: func() {},
|
||||
}
|
||||
req := httptest.NewRequest("POST", "/api/v1/settings", bytes.NewReader(payload))
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
if err := server.settings(rr, req); err != nil {
|
||||
t.Fatalf("settings() error = %v", err)
|
||||
}
|
||||
|
||||
saved, err := testStore.Settings()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if saved.OnboardingVersion != 1 {
|
||||
t.Fatalf("OnboardingVersion = %d, want 1", saved.OnboardingVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsPreservesClaudeDesktopUsedWhenOmitted(t *testing.T) {
|
||||
testStore := &store.Store{
|
||||
DBPath: filepath.Join(t.TempDir(), "db.sqlite"),
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
settings, err := testStore.Settings()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings.ClaudeDesktopUsed = true
|
||||
if err := testStore.SetSettings(settings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(settings)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var fields map[string]any
|
||||
if err := json.Unmarshal(payload, &fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
delete(fields, "ClaudeDesktopUsed")
|
||||
payload, err = json.Marshal(fields)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
server := &Server{Store: testStore, Restart: func() {}}
|
||||
req := httptest.NewRequest("POST", "/api/v1/settings", bytes.NewReader(payload))
|
||||
rr := httptest.NewRecorder()
|
||||
if err := server.settings(rr, req); err != nil {
|
||||
t.Fatalf("settings() error = %v", err)
|
||||
}
|
||||
|
||||
saved, err := testStore.Settings()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !saved.ClaudeDesktopUsed {
|
||||
t.Fatal("expected ClaudeDesktopUsed to be preserved")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsToggleAutoUpdateOn_WithPendingUpdate_ShowsNotification(t *testing.T) {
|
||||
testStore := &store.Store{
|
||||
DBPath: filepath.Join(t.TempDir(), "db.sqlite"),
|
||||
|
||||
@@ -153,12 +153,10 @@ func (u *Updater) DownloadNewRelease(ctx context.Context, updateResp UpdateRespo
|
||||
return err
|
||||
}
|
||||
|
||||
// In case of slow downloads, continue the update check in the background.
|
||||
// Drain the goroutine before returning: it reads package-level knobs
|
||||
// (e.g. UpdateCheckInterval), which callers may mutate once we return.
|
||||
// In case of slow downloads, continue the update check in the background
|
||||
bgctx, bgcancel := context.WithCancel(downloadCtx)
|
||||
var bgwg sync.WaitGroup
|
||||
bgwg.Go(func() {
|
||||
defer bgcancel()
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-bgctx.Done():
|
||||
@@ -167,10 +165,6 @@ func (u *Updater) DownloadNewRelease(ctx context.Context, updateResp UpdateRespo
|
||||
u.checkForUpdate(bgctx)
|
||||
}
|
||||
}
|
||||
})
|
||||
defer func() {
|
||||
bgcancel()
|
||||
bgwg.Wait()
|
||||
}()
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
|
||||
@@ -434,7 +434,7 @@ func IsUpdatePending() bool {
|
||||
func chownWithAuthorization(user string) bool {
|
||||
u := C.CString(user)
|
||||
defer C.free(unsafe.Pointer(u))
|
||||
return bool(C.chownWithAuthorization(u))
|
||||
return (bool)(C.chownWithAuthorization(u))
|
||||
}
|
||||
|
||||
func verifyExtractedBundle(path string) error {
|
||||
|
||||
@@ -190,23 +190,6 @@ func TestDownloadNewReleaseDoesNotUseRawETagAsPathComponent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// waitDownloadIdle blocks until no download is in flight, so staged-file
|
||||
// handles close before t.TempDir cleanup removes the stage directory. After
|
||||
// the context is cancelled a new download can't write (it aborts at the HEAD
|
||||
// request), so reaching idle makes cleanup race-free.
|
||||
func (u *Updater) waitDownloadIdle() {
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
u.cancelDownloadLock.Lock()
|
||||
idle := u.cancelDownload == nil
|
||||
u.cancelDownloadLock.Unlock()
|
||||
if idle {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackgroundCheckerSkipsAlreadyStagedETagDownload(t *testing.T) {
|
||||
UpdateStageDir = t.TempDir()
|
||||
oldInstaller := Installer
|
||||
@@ -293,7 +276,6 @@ func TestBackgroundCheckerSkipsAlreadyStagedETagDownload(t *testing.T) {
|
||||
callbacks <- ver
|
||||
return nil
|
||||
})
|
||||
t.Cleanup(updater.waitDownloadIdle)
|
||||
|
||||
for range 2 {
|
||||
select {
|
||||
@@ -382,7 +364,6 @@ func TestBackgoundChecker(t *testing.T) {
|
||||
}
|
||||
|
||||
updater.StartBackgroundUpdaterChecker(ctx, cb)
|
||||
t.Cleanup(updater.waitDownloadIdle)
|
||||
select {
|
||||
case <-stallTimer.C:
|
||||
t.Fatal("stalled")
|
||||
@@ -445,7 +426,6 @@ func TestAutoUpdateDisabledSkipsDownload(t *testing.T) {
|
||||
}
|
||||
|
||||
updater.StartBackgroundUpdaterChecker(ctx, cb)
|
||||
t.Cleanup(updater.waitDownloadIdle)
|
||||
|
||||
// Wait enough time for multiple check cycles
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
@@ -508,7 +488,6 @@ func TestAutoUpdateReenabledDownloadsUpdate(t *testing.T) {
|
||||
}
|
||||
|
||||
upd.StartBackgroundUpdaterChecker(ctx, cb)
|
||||
t.Cleanup(upd.waitDownloadIdle)
|
||||
|
||||
// Wait for a few cycles with auto-update disabled - no download should happen
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
@@ -577,9 +556,7 @@ func TestCancelOngoingDownload(t *testing.T) {
|
||||
_, resp := updater.checkForUpdate(ctx)
|
||||
|
||||
// Start download in goroutine
|
||||
downloadDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(downloadDone)
|
||||
_ = updater.DownloadNewRelease(ctx, resp)
|
||||
}()
|
||||
|
||||
@@ -600,10 +577,6 @@ func TestCancelOngoingDownload(t *testing.T) {
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("download cancellation was not received by server")
|
||||
}
|
||||
|
||||
// Wait for the download goroutine to unwind: it drags along a background
|
||||
// update-check loop that reads package-level knobs the next test rewrites.
|
||||
<-downloadDone
|
||||
}
|
||||
|
||||
func TestTriggerImmediateCheck(t *testing.T) {
|
||||
@@ -642,7 +615,6 @@ func TestTriggerImmediateCheck(t *testing.T) {
|
||||
}
|
||||
|
||||
updater.StartBackgroundUpdaterChecker(ctx, cb)
|
||||
t.Cleanup(updater.waitDownloadIdle)
|
||||
|
||||
// Wait for the initial check that fires after the initial delay
|
||||
select {
|
||||
|
||||
@@ -78,7 +78,7 @@ func init() {
|
||||
func loadOSVersion() {
|
||||
UserAgentOS = "Windows"
|
||||
verInfo := OSVERSIONINFOEXW{}
|
||||
verInfo.dwOSVersionInfoSize = uint32(unsafe.Sizeof(verInfo))
|
||||
verInfo.dwOSVersionInfoSize = (uint32)(unsafe.Sizeof(verInfo))
|
||||
ntdll, err := windows.LoadDLL("ntdll.dll")
|
||||
if err != nil {
|
||||
slog.Warn("unable to find ntdll", "error", err)
|
||||
@@ -394,13 +394,13 @@ func IsProcRunning(procName string) []uint32 {
|
||||
defer windows.CloseHandle(hProcess)
|
||||
var module windows.Handle
|
||||
var cbNeeded uint32
|
||||
cb := uint32(unsafe.Sizeof(module))
|
||||
cb := (uint32)(unsafe.Sizeof(module))
|
||||
if err := windows.EnumProcessModules(hProcess, &module, cb, &cbNeeded); err != nil {
|
||||
continue
|
||||
}
|
||||
var sz uint32 = 1024 * 8
|
||||
moduleName := make([]uint16, sz)
|
||||
cb = uint32(len(moduleName)) * uint32(unsafe.Sizeof(uint16(0)))
|
||||
cb = uint32(len(moduleName)) * (uint32)(unsafe.Sizeof(uint16(0)))
|
||||
if err := windows.GetModuleBaseName(hProcess, module, &moduleName[0], cb); err != nil && err != syscall.ERROR_INSUFFICIENT_BUFFER {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -2535,9 +2535,19 @@ inline SIZE make_window_frame_size(HWND window, int width, int height,
|
||||
return {frame_width, frame_height};
|
||||
}
|
||||
|
||||
inline bool is_dark_theme_enabled() {
|
||||
constexpr auto *sub_key =
|
||||
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
|
||||
reg_key key(HKEY_CURRENT_USER, sub_key, 0, KEY_READ);
|
||||
if (!key.is_open()) {
|
||||
// Default is light theme
|
||||
return false;
|
||||
}
|
||||
return key.query_uint(L"AppsUseLightTheme", 1) == 0;
|
||||
}
|
||||
|
||||
inline void apply_window_theme(HWND window) {
|
||||
// Ollama uses a light-only application appearance.
|
||||
constexpr bool dark_theme_enabled = false;
|
||||
auto dark_theme_enabled = is_dark_theme_enabled();
|
||||
|
||||
// Use "immersive dark mode" on systems that support it.
|
||||
// Changes the color of the window's title bar (light or dark).
|
||||
|
||||
@@ -78,9 +78,9 @@ func (t *winTray) wndProc(hWnd windows.Handle, message uint32, wParam, lParam ui
|
||||
t.app.Quit()
|
||||
case updateMenuID:
|
||||
t.app.DoUpdate()
|
||||
case openAppsMenuID:
|
||||
case openUIMenuID:
|
||||
// UI must be initialized on this thread so don't use the callbacks
|
||||
t.app.UIRun("/connect")
|
||||
t.app.UIShow()
|
||||
case settingsUIMenuID:
|
||||
// UI must be initialized on this thread so don't use the callbacks
|
||||
t.app.UIRun("/settings")
|
||||
@@ -174,7 +174,14 @@ func (t *winTray) wndProc(hWnd windows.Handle, message uint32, wParam, lParam ui
|
||||
}
|
||||
}
|
||||
case uint32(FOCUS_WINDOW_MSG_ID):
|
||||
focusUI(t.app)
|
||||
// Handle focus window request from another instance
|
||||
if t.app.UIRunning() {
|
||||
// If UI is already running, just show it
|
||||
t.app.UIShow()
|
||||
} else {
|
||||
// If UI is not running, start it
|
||||
t.app.UIRun("/")
|
||||
}
|
||||
lResult = 1 // Return non-zero to indicate success
|
||||
default:
|
||||
// Calls the default window procedure to provide default processing for any window messages that an application does not process.
|
||||
@@ -190,14 +197,6 @@ func (t *winTray) wndProc(hWnd windows.Handle, message uint32, wParam, lParam ui
|
||||
return
|
||||
}
|
||||
|
||||
func focusUI(app AppCallbacks) {
|
||||
if app.UIRunning() && app.UIOnboarding() {
|
||||
app.UIShow()
|
||||
return
|
||||
}
|
||||
app.UIRun("/connect")
|
||||
}
|
||||
|
||||
func (t *winTray) Quit() {
|
||||
// slog.Debug("XXX in winTray.Quit")
|
||||
t.quitting = true
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package wintray
|
||||
|
||||
import "testing"
|
||||
|
||||
type lifecycleApp struct {
|
||||
running bool
|
||||
onboarding bool
|
||||
runPath string
|
||||
showCall bool
|
||||
}
|
||||
|
||||
func (a *lifecycleApp) UIRun(path string) { a.runPath = path }
|
||||
func (a *lifecycleApp) UIShow() { a.showCall = true }
|
||||
func (a *lifecycleApp) UITerminate() {}
|
||||
func (a *lifecycleApp) UIRunning() bool { return a.running }
|
||||
func (a *lifecycleApp) UIOnboarding() bool { return a.onboarding }
|
||||
func (a *lifecycleApp) Quit() {}
|
||||
func (a *lifecycleApp) DoUpdate() {}
|
||||
|
||||
func TestFocusUICreatesOrShowsWindow(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
running bool
|
||||
onboarding bool
|
||||
wantRun string
|
||||
wantShow bool
|
||||
}{
|
||||
{name: "creates Apps window when tray only", wantRun: "/connect"},
|
||||
{name: "routes existing window to Apps", running: true, wantRun: "/connect"},
|
||||
{name: "preserves onboarding", running: true, onboarding: true, wantShow: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
app := &lifecycleApp{running: tt.running, onboarding: tt.onboarding}
|
||||
focusUI(app)
|
||||
if app.runPath != tt.wantRun {
|
||||
t.Errorf("run path = %q, want %q", app.runPath, tt.wantRun)
|
||||
}
|
||||
if app.showCall != tt.wantShow {
|
||||
t.Errorf("show called = %v, want %v", app.showCall, tt.wantShow)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
|
||||
const (
|
||||
_ = iota
|
||||
openAppsMenuID
|
||||
openUIMenuID
|
||||
settingsUIMenuID
|
||||
updateSeparatorMenuID
|
||||
updateAvailableMenuID
|
||||
@@ -28,7 +28,7 @@ const (
|
||||
)
|
||||
|
||||
func (t *winTray) initMenus() error {
|
||||
if err := t.addOrUpdateMenuItem(openAppsMenuID, 0, openAppsMenuTitle, false); err != nil {
|
||||
if err := t.addOrUpdateMenuItem(openUIMenuID, 0, openUIMenuTitle, false); err != nil {
|
||||
return fmt.Errorf("unable to create menu entries %w", err)
|
||||
}
|
||||
if err := t.addOrUpdateMenuItem(settingsUIMenuID, 0, settingsUIMenuTitle, false); err != nil {
|
||||
|
||||
@@ -12,6 +12,6 @@ const (
|
||||
updateAvailableMenuTitle = "An update is available"
|
||||
updateMenuTitle = "Restart to update"
|
||||
diagLogsMenuTitle = "View logs"
|
||||
openAppsMenuTitle = "Open Ollama"
|
||||
settingsUIMenuTitle = "Settings"
|
||||
openUIMenuTitle = "Open Ollama"
|
||||
settingsUIMenuTitle = "Settings..."
|
||||
)
|
||||
@@ -49,7 +49,6 @@ type AppCallbacks interface {
|
||||
UIShow()
|
||||
UITerminate()
|
||||
UIRunning() bool
|
||||
UIOnboarding() bool
|
||||
Quit()
|
||||
DoUpdate()
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ function(ollama_macos_major_version output)
|
||||
RESULT_VARIABLE _macos_result
|
||||
ERROR_QUIET)
|
||||
if(_macos_result EQUAL 0)
|
||||
string(REGEX MATCH "^[0-9]+(\\.[0-9]+)?" _macos_major "${_macos_version}")
|
||||
string(REGEX MATCH "^[0-9]+" _macos_major "${_macos_version}")
|
||||
endif()
|
||||
set(${output} "${_macos_major}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
@@ -72,7 +72,7 @@ function(ollama_macos_sdk_major_version output)
|
||||
RESULT_VARIABLE _sdk_result
|
||||
ERROR_QUIET)
|
||||
if(_sdk_result EQUAL 0)
|
||||
string(REGEX MATCH "^[0-9]+(\\.[0-9]+)?" _sdk_major "${_sdk_version}")
|
||||
string(REGEX MATCH "^[0-9]+" _sdk_major "${_sdk_version}")
|
||||
endif()
|
||||
set(${output} "${_sdk_major}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
@@ -83,9 +83,7 @@ function(ollama_default_mlx_backends output)
|
||||
ollama_check_metal_toolchain(_metal_version)
|
||||
ollama_macos_major_version(_macos_major)
|
||||
ollama_macos_sdk_major_version(_sdk_major)
|
||||
if(_macos_major AND _sdk_major
|
||||
AND _macos_major VERSION_GREATER_EQUAL 26.2
|
||||
AND _sdk_major VERSION_GREATER_EQUAL 26.2)
|
||||
if(_macos_major AND _sdk_major AND _macos_major GREATER_EQUAL 26 AND _sdk_major GREATER_EQUAL 26)
|
||||
set(_backends "metal_v4")
|
||||
else()
|
||||
set(_backends "metal_v3")
|
||||
@@ -169,14 +167,6 @@ if(OLLAMA_MLX_BACKENDS)
|
||||
list(APPEND _mlx_source_targets ollama-mlx-source)
|
||||
endif()
|
||||
|
||||
# Temporary MLX-C carry patch: regenerated bindings for force_fused and the
|
||||
# thread-local compile cache, carried until they merge upstream into
|
||||
# ml-explore/mlx-c. Then bump MLX_C_VERSION and delete mlx/compat/.
|
||||
find_package(Git REQUIRED)
|
||||
set(OLLAMA_MLX_C_COMPAT_PATCH_COMMAND
|
||||
${GIT_EXECUTABLE} apply ${CMAKE_SOURCE_DIR}/mlx/compat/0001-mlx-c-regen-0.32.1.patch
|
||||
CACHE INTERNAL "MLX-C carry patch")
|
||||
|
||||
if(DEFINED "FETCHCONTENT_SOURCE_DIR_MLX-C" AND NOT "${FETCHCONTENT_SOURCE_DIR_MLX-C}" STREQUAL "")
|
||||
get_filename_component(OLLAMA_MLX_C_SOURCE_DIR
|
||||
"${FETCHCONTENT_SOURCE_DIR_MLX-C}" ABSOLUTE BASE_DIR "${CMAKE_SOURCE_DIR}")
|
||||
@@ -196,35 +186,14 @@ if(OLLAMA_MLX_BACKENDS)
|
||||
CONFIGURE_COMMAND ""
|
||||
BUILD_COMMAND ""
|
||||
INSTALL_COMMAND ""
|
||||
PATCH_COMMAND ${OLLAMA_MLX_C_COMPAT_PATCH_COMMAND}
|
||||
USES_TERMINAL_DOWNLOAD TRUE
|
||||
USES_TERMINAL_PATCH TRUE)
|
||||
USES_TERMINAL_DOWNLOAD TRUE)
|
||||
list(APPEND _mlx_source_targets ollama-mlx-c-source)
|
||||
endif()
|
||||
# Refresh the vendored MLX-C headers once the sources are present. Every MLX
|
||||
# backend variant shares this destination in the source tree, so the copy has
|
||||
# to happen here rather than in each variant's build.
|
||||
add_custom_target(ollama-mlx-vendor-headers
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DMLX_C_HEADERS_DIR=${OLLAMA_MLX_C_SOURCE_DIR}/mlx/c
|
||||
-DMLX_C_HEADERS_DEST=${CMAKE_SOURCE_DIR}/x/mlxrunner/mlx/include/mlx/c
|
||||
-P "${CMAKE_SOURCE_DIR}/cmake/vendor-mlx-c-headers.cmake"
|
||||
DEPENDS ${_mlx_source_targets}
|
||||
COMMENT "Vendoring MLX-C headers"
|
||||
VERBATIM)
|
||||
add_custom_target(ollama-mlx-sources DEPENDS ollama-mlx-vendor-headers)
|
||||
endif()
|
||||
|
||||
set(OLLAMA_BUILD_PARALLEL "" CACHE STRING
|
||||
"Number of parallel jobs for nested native builds (empty = use generator default)")
|
||||
|
||||
set(_native_parallel_args --parallel)
|
||||
if(NOT OLLAMA_BUILD_PARALLEL STREQUAL "")
|
||||
list(APPEND _native_parallel_args ${OLLAMA_BUILD_PARALLEL})
|
||||
add_custom_target(ollama-mlx-sources DEPENDS ${_mlx_source_targets})
|
||||
endif()
|
||||
|
||||
set(OLLAMA_NATIVE_BUILD_TOOL_COMMAND
|
||||
${CMAKE_COMMAND} --build <BINARY_DIR> ${_native_parallel_args})
|
||||
${CMAKE_COMMAND} --build <BINARY_DIR>)
|
||||
set(OLLAMA_NATIVE_BUILD_TARGET_ARG --target)
|
||||
if(CMAKE_GENERATOR MATCHES "Makefiles")
|
||||
set(OLLAMA_NATIVE_BUILD_TOOL_COMMAND
|
||||
@@ -267,67 +236,6 @@ function(ollama_cache_arg_is_set name output)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
function(ollama_backend_cuda_major backend output)
|
||||
if("${backend}" MATCHES "^cuda_v([0-9]+)$")
|
||||
set(${output} "${CMAKE_MATCH_1}" PARENT_SCOPE)
|
||||
else()
|
||||
set(${output} "" PARENT_SCOPE)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
function(ollama_find_windows_cuda_root major output)
|
||||
if(NOT WIN32 OR "${major}" STREQUAL "")
|
||||
set(${output} "" PARENT_SCOPE)
|
||||
return()
|
||||
endif()
|
||||
|
||||
execute_process(
|
||||
COMMAND ${CMAKE_COMMAND} -E environment
|
||||
OUTPUT_VARIABLE _environment)
|
||||
string(REPLACE "\r\n" "\n" _environment "${_environment}")
|
||||
string(REPLACE "\r" "\n" _environment "${_environment}")
|
||||
string(REGEX MATCHALL "CUDA_PATH_V${major}_[0-9]+=[^\n]*" _matches "${_environment}")
|
||||
|
||||
set(_best_minor -1)
|
||||
set(_best_root "")
|
||||
foreach(_entry IN LISTS _matches)
|
||||
if(_entry MATCHES "^CUDA_PATH_V${major}_([0-9]+)=(.*)$")
|
||||
set(_minor "${CMAKE_MATCH_1}")
|
||||
set(_root "${CMAKE_MATCH_2}")
|
||||
if(_minor GREATER _best_minor)
|
||||
set(_best_minor ${_minor})
|
||||
set(_best_root "${_root}")
|
||||
endif()
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
if(_best_root STREQUAL "" AND DEFINED ENV{CUDA_PATH})
|
||||
set(_cuda_path "$ENV{CUDA_PATH}")
|
||||
if(EXISTS "${_cuda_path}/version.json")
|
||||
file(READ "${_cuda_path}/version.json" _version_json)
|
||||
if(_version_json MATCHES "\"cuda\"[ \t\r\n]*:[ \t\r\n]*\"${major}\\.")
|
||||
set(_best_root "${_cuda_path}")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
set(${output} "${_best_root}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
function(ollama_append_cuda_toolkit_args output backend)
|
||||
# If CUDAToolkit_ROOT is already explicitly set, just forward it.
|
||||
ollama_append_cache_arg_if_set(${output} CUDAToolkit_ROOT)
|
||||
if(NOT DEFINED CUDAToolkit_ROOT OR "${CUDAToolkit_ROOT}" STREQUAL "")
|
||||
# Auto-discover CUDA toolkit for the requested backend version on Windows.
|
||||
ollama_backend_cuda_major("${backend}" _cuda_major)
|
||||
ollama_find_windows_cuda_root("${_cuda_major}" _cuda_root)
|
||||
if(NOT "${_cuda_root}" STREQUAL "")
|
||||
ollama_escape_cmake_list("${_cuda_root}" _value)
|
||||
set(${output} ${${output}} "-DCUDAToolkit_ROOT=${_value}" PARENT_SCOPE)
|
||||
endif()
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
function(ollama_llama_cuda_preset backend output)
|
||||
ollama_cache_arg_is_set(CMAKE_CUDA_ARCHITECTURES _has_cuda_arch)
|
||||
if(_has_cuda_arch)
|
||||
@@ -419,28 +327,12 @@ function(ollama_add_llama_server_build name)
|
||||
-DCMAKE_OSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET})
|
||||
endif()
|
||||
endif()
|
||||
# Visual Studio requires -T toolset override to select the correct CUDA toolkit.
|
||||
# MSBuild's CUDA integration ignores -DCUDAToolkit_ROOT for nvcc selection.
|
||||
# Prefer user-specified CUDAToolkit_ROOT before falling back to auto-discovery.
|
||||
set(_generator_args)
|
||||
if(WIN32 AND CMAKE_GENERATOR MATCHES "Visual Studio")
|
||||
set(_cuda_root "${CUDAToolkit_ROOT}")
|
||||
if("${_cuda_root}" STREQUAL "")
|
||||
ollama_backend_cuda_major("${name}" _cuda_major)
|
||||
ollama_find_windows_cuda_root("${_cuda_major}" _cuda_root)
|
||||
endif()
|
||||
if(NOT "${_cuda_root}" STREQUAL "")
|
||||
list(APPEND _generator_args -T cuda=${_cuda_root})
|
||||
endif()
|
||||
endif()
|
||||
set(_configure_command ${CMAKE_COMMAND}
|
||||
${_generator_args}
|
||||
-S ${CMAKE_SOURCE_DIR}/llama/server
|
||||
-B <BINARY_DIR>
|
||||
${_cmake_args})
|
||||
if(ARG_PRESET)
|
||||
set(_configure_command ${CMAKE_COMMAND}
|
||||
${_generator_args}
|
||||
-S ${CMAKE_SOURCE_DIR}/llama/server
|
||||
--preset ${ARG_PRESET}
|
||||
-B <BINARY_DIR>
|
||||
@@ -549,8 +441,15 @@ endfunction()
|
||||
find_program(GO_EXECUTABLE go)
|
||||
|
||||
if(OLLAMA_MLX_BACKENDS)
|
||||
set(_mlx_c_headers_dir "${OLLAMA_MLX_C_SOURCE_DIR}/mlx/c")
|
||||
set(_mlx_c_headers_dest "${CMAKE_SOURCE_DIR}/x/mlxrunner/mlx/include/mlx/c")
|
||||
|
||||
if(GO_EXECUTABLE AND (NOT APPLE OR CMAKE_SYSTEM_PROCESSOR STREQUAL CMAKE_HOST_SYSTEM_PROCESSOR))
|
||||
add_custom_target(ollama-mlx-generate-wrappers
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DMLX_C_HEADERS_DIR=${_mlx_c_headers_dir}
|
||||
-DMLX_C_HEADERS_DEST=${_mlx_c_headers_dest}
|
||||
-P "${CMAKE_SOURCE_DIR}/cmake/vendor-mlx-c-headers.cmake"
|
||||
COMMAND ${CMAKE_COMMAND} -E env
|
||||
CC= CGO_CFLAGS= CGO_CXXFLAGS=
|
||||
${GO_EXECUTABLE} generate ./x/...
|
||||
@@ -645,7 +544,6 @@ if(OLLAMA_HAVE_LLAMA_SERVER)
|
||||
set(_cuda_args)
|
||||
ollama_append_cache_arg_if_set(_cuda_args CMAKE_CUDA_ARCHITECTURES)
|
||||
ollama_append_cache_arg_if_set(_cuda_args CMAKE_CUDA_FLAGS)
|
||||
ollama_append_cuda_toolkit_args(_cuda_args ${_backend})
|
||||
ollama_add_llama_server_build(${_backend}
|
||||
PRESET ${_cuda_preset}
|
||||
RUNNER_DIR ${_backend}
|
||||
@@ -657,7 +555,6 @@ if(OLLAMA_HAVE_LLAMA_SERVER)
|
||||
set(_cuda_args)
|
||||
ollama_append_cache_arg_if_set(_cuda_args CMAKE_CUDA_ARCHITECTURES)
|
||||
ollama_append_cache_arg_if_set(_cuda_args CMAKE_CUDA_FLAGS)
|
||||
ollama_append_cuda_toolkit_args(_cuda_args ${_backend})
|
||||
ollama_add_llama_server_build(${_backend}
|
||||
PRESET ${_cuda_preset}
|
||||
RUNNER_DIR ${_backend}
|
||||
@@ -767,15 +664,14 @@ foreach(_backend IN LISTS OLLAMA_MLX_BACKENDS)
|
||||
endif()
|
||||
ollama_check_metal_toolchain(_metal_version)
|
||||
ollama_macos_sdk_major_version(_ollama_mlx_sdk_major)
|
||||
if(_ollama_mlx_sdk_major
|
||||
AND _ollama_mlx_sdk_major VERSION_GREATER_EQUAL 26.2)
|
||||
if(_ollama_mlx_sdk_major AND _ollama_mlx_sdk_major GREATER_EQUAL 26)
|
||||
ollama_add_mlx_build(metal_v4
|
||||
PRESET mlx_metal_v4
|
||||
RUNNER_DIR mlx_metal_v4)
|
||||
list(APPEND _mlx_targets ollama-mlx-metal_v4)
|
||||
else()
|
||||
message(FATAL_ERROR
|
||||
"OLLAMA_MLX_BACKENDS=metal_v4 requires the macOS 26.2 SDK. "
|
||||
"OLLAMA_MLX_BACKENDS=metal_v4 requires the macOS 26 SDK. "
|
||||
"Install a newer Xcode or use OLLAMA_MLX_BACKENDS=metal_v3.")
|
||||
endif()
|
||||
else()
|
||||
|
||||
@@ -23,10 +23,6 @@ if(APPLE)
|
||||
set(CMAKE_BUILD_RPATH "@loader_path")
|
||||
set(CMAKE_INSTALL_RPATH "@loader_path")
|
||||
set(CMAKE_BUILD_WITH_INSTALL_RPATH ON)
|
||||
elseif(UNIX)
|
||||
set(CMAKE_BUILD_RPATH "$ORIGIN")
|
||||
set(CMAKE_INSTALL_RPATH "$ORIGIN")
|
||||
set(CMAKE_BUILD_WITH_INSTALL_RPATH ON)
|
||||
endif()
|
||||
|
||||
if(NOT DEFINED OLLAMA_SOURCE_DIR OR "${OLLAMA_SOURCE_DIR}" STREQUAL "")
|
||||
@@ -54,12 +50,7 @@ endif()
|
||||
option(OLLAMA_MLX_GENERATE_WRAPPERS "Regenerate MLX Go wrappers" OFF)
|
||||
|
||||
message(STATUS "Setting up MLX (this takes a while...)")
|
||||
foreach(_cudnn_var CUDNN_INCLUDE_PATH CUDNN_LIBRARY_PATH)
|
||||
if((NOT DEFINED ${_cudnn_var} OR "${${_cudnn_var}}" STREQUAL "") AND DEFINED ENV{${_cudnn_var}})
|
||||
set(${_cudnn_var} "$ENV{${_cudnn_var}}" CACHE PATH "")
|
||||
endif()
|
||||
endforeach()
|
||||
add_subdirectory(${OLLAMA_SOURCE_DIR}/x/mlxrunner/mlx ${CMAKE_BINARY_DIR}/x/mlxrunner/mlx)
|
||||
add_subdirectory(${OLLAMA_SOURCE_DIR}/x/imagegen/mlx ${CMAKE_BINARY_DIR}/x/imagegen/mlx)
|
||||
|
||||
# Find CUDA toolkit if MLX is built with CUDA support.
|
||||
find_package(CUDAToolkit)
|
||||
@@ -74,7 +65,6 @@ elseif(DEFINED ENV{CUDNN_ROOT_DIR})
|
||||
set(_cudnn_root "$ENV{CUDNN_ROOT_DIR}")
|
||||
endif()
|
||||
if(_cudnn_root)
|
||||
file(TO_CMAKE_PATH "${_cudnn_root}" _cudnn_root)
|
||||
# cuDNN 9.x has versioned subdirectories under bin/ (e.g., bin/13.0/).
|
||||
file(GLOB CUDNN_BIN_SUBDIRS "${_cudnn_root}/bin/*")
|
||||
list(APPEND MLX_RUNTIME_DIRS ${CUDNN_BIN_SUBDIRS})
|
||||
@@ -112,8 +102,7 @@ install(RUNTIME_DEPENDENCY_SET mlx_runtime_deps
|
||||
LIBRARY DESTINATION ${OLLAMA_INSTALL_DIR} COMPONENT MLX_VENDOR
|
||||
)
|
||||
|
||||
get_target_property(_MLX_LINK_LIBRARIES mlx LINK_LIBRARIES)
|
||||
if(TARGET jaccl AND "jaccl" IN_LIST _MLX_LINK_LIBRARIES)
|
||||
if(TARGET jaccl)
|
||||
install(TARGETS jaccl
|
||||
RUNTIME DESTINATION ${OLLAMA_INSTALL_DIR} COMPONENT MLX
|
||||
LIBRARY DESTINATION ${OLLAMA_INSTALL_DIR} COMPONENT MLX
|
||||
@@ -134,53 +123,29 @@ endif()
|
||||
# --component MLX. Headers are installed alongside libmlx in OLLAMA_INSTALL_DIR.
|
||||
#
|
||||
# Layout:
|
||||
# ${OLLAMA_INSTALL_DIR}/include/cccl/ - CCCL headers
|
||||
# ${OLLAMA_INSTALL_DIR}/include/{cute,cutlass}/ - CUTLASS/CUTE headers
|
||||
# ${OLLAMA_INSTALL_DIR}/include/ - CUDA runtime/core headers
|
||||
# ${OLLAMA_INSTALL_DIR}/include/cccl/{cuda,nv}/ - CCCL headers
|
||||
# ${OLLAMA_INSTALL_DIR}/include/*.h - CUDA toolkit headers
|
||||
#
|
||||
# MLX's jit_module.cpp resolves JIT support headers from the backend-local
|
||||
# include directory. On Linux it also probes current_binary_dir().parent_path()
|
||||
# / "include", so we create a symlink from lib/ollama/include to the backend
|
||||
# include directory for archive packaging.
|
||||
# MLX's jit_module.cpp resolves CCCL via
|
||||
# current_binary_dir()[.parent_path()] / "include" / "cccl"
|
||||
# On Linux, MLX's jit_module.cpp resolves CCCL via
|
||||
# current_binary_dir().parent_path() / "include" / "cccl", so we create a
|
||||
# symlink from lib/ollama/include -> ${OLLAMA_RUNNER_DIR}/include.
|
||||
# This will need refinement if we add multiple CUDA versions for MLX in the future.
|
||||
# CUDA runtime headers are found via CUDA_PATH env var (set by mlxrunner).
|
||||
set(_mlx_jit_cccl_include_dir "")
|
||||
if(CUDAToolkit_FOUND)
|
||||
foreach(_dir ${CUDAToolkit_INCLUDE_DIRS})
|
||||
if(EXISTS "${_dir}/cccl/cuda/std")
|
||||
set(_mlx_jit_cccl_include_dir "${_dir}/cccl")
|
||||
break()
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
if(NOT _mlx_jit_cccl_include_dir AND EXISTS ${CMAKE_BINARY_DIR}/_deps/cccl-src/include/cuda)
|
||||
set(_mlx_jit_cccl_include_dir "${CMAKE_BINARY_DIR}/_deps/cccl-src/include")
|
||||
endif()
|
||||
if(_mlx_jit_cccl_include_dir)
|
||||
foreach(_cccl_dir cuda nv cub thrust)
|
||||
if(EXISTS "${_mlx_jit_cccl_include_dir}/${_cccl_dir}")
|
||||
install(DIRECTORY "${_mlx_jit_cccl_include_dir}/${_cccl_dir}"
|
||||
DESTINATION ${OLLAMA_INSTALL_DIR}/include/cccl
|
||||
COMPONENT MLX)
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
if(EXISTS ${CMAKE_BINARY_DIR}/_deps/cutlass-src/include/cute)
|
||||
install(DIRECTORY ${CMAKE_BINARY_DIR}/_deps/cutlass-src/include/cute
|
||||
DESTINATION ${OLLAMA_INSTALL_DIR}/include
|
||||
if(EXISTS ${CMAKE_BINARY_DIR}/_deps/cccl-src/include/cuda)
|
||||
install(DIRECTORY ${CMAKE_BINARY_DIR}/_deps/cccl-src/include/cuda
|
||||
DESTINATION ${OLLAMA_INSTALL_DIR}/include/cccl
|
||||
COMPONENT MLX)
|
||||
install(DIRECTORY ${CMAKE_BINARY_DIR}/_deps/cutlass-src/include/cutlass
|
||||
DESTINATION ${OLLAMA_INSTALL_DIR}/include
|
||||
install(DIRECTORY ${CMAKE_BINARY_DIR}/_deps/cccl-src/include/nv
|
||||
DESTINATION ${OLLAMA_INSTALL_DIR}/include/cccl
|
||||
COMPONENT MLX)
|
||||
endif()
|
||||
|
||||
# Install CUDA runtime/core headers needed by MLX JIT kernels.
|
||||
# NVIDIA's NVRTC bundled-header model is CUDA Runtime + CCCL, not the entire
|
||||
# toolkit include tree. Keep CCCL coherent above, include CUTLASS/CUTE above,
|
||||
# and avoid shipping unrelated SDK headers such as NPP, CUPTI, cuRAND, NVML,
|
||||
# cuBLAS, cuSPARSE, and cuSOLVER.
|
||||
# Install minimal CUDA toolkit headers needed by MLX JIT kernels.
|
||||
# These are the transitive closure of includes from mlx/backend/cuda/device/*.cuh.
|
||||
# The Go mlxrunner sets CUDA_PATH to OLLAMA_INSTALL_DIR so MLX finds them at
|
||||
# $CUDA_PATH/include via NVRTC --include-path.
|
||||
# $CUDA_PATH/include/*.h via NVRTC --include-path.
|
||||
if(CUDAToolkit_FOUND)
|
||||
# CUDAToolkit_INCLUDE_DIRS may be a semicolon-separated list
|
||||
# (e.g. ".../include;.../include/cccl"). Find the entry that
|
||||
@@ -196,97 +161,39 @@ if(CUDAToolkit_FOUND)
|
||||
message(WARNING "Could not find cuda_runtime_api.h in CUDAToolkit_INCLUDE_DIRS: ${CUDAToolkit_INCLUDE_DIRS}")
|
||||
else()
|
||||
set(_dst "${OLLAMA_INSTALL_DIR}/include")
|
||||
|
||||
set(_mlx_jit_cuda_headers
|
||||
set(_MLX_JIT_CUDA_HEADERS
|
||||
builtin_types.h
|
||||
channel_descriptor.h
|
||||
common_functions.h
|
||||
cooperative_groups.h
|
||||
cuComplex.h
|
||||
cuda.h
|
||||
cudaTypedefs.h
|
||||
cuda_awbarrier.h
|
||||
cuda_awbarrier_helpers.h
|
||||
cuda_awbarrier_primitives.h
|
||||
cuda_bf16.h
|
||||
cuda_bf16.hpp
|
||||
cuda_device_runtime_api.h
|
||||
cuda_fp4.h
|
||||
cuda_fp4.hpp
|
||||
cuda_fp6.h
|
||||
cuda_fp6.hpp
|
||||
cuda_fp8.h
|
||||
cuda_fp8.hpp
|
||||
cuda_fp16.h
|
||||
cuda_fp16.hpp
|
||||
cuda_occupancy.h
|
||||
cuda_pipeline.h
|
||||
cuda_pipeline_helpers.h
|
||||
cuda_pipeline_primitives.h
|
||||
cuda_runtime.h
|
||||
cuda_fp8.h
|
||||
cuda_fp8.hpp
|
||||
cuda_runtime_api.h
|
||||
cuda_stdint.h
|
||||
cudart_platform.h
|
||||
device_atomic_functions.h
|
||||
device_atomic_functions.hpp
|
||||
device_double_functions.h
|
||||
device_functions.h
|
||||
device_launch_parameters.h
|
||||
device_types.h
|
||||
driver_functions.h
|
||||
driver_types.h
|
||||
fatbinary_section.h
|
||||
host_config.h
|
||||
host_defines.h
|
||||
library_types.h
|
||||
math_constants.h
|
||||
math_functions.h
|
||||
mma.h
|
||||
nvrtc_device_runtime.h
|
||||
sm_20_atomic_functions.h
|
||||
sm_20_atomic_functions.hpp
|
||||
sm_20_intrinsics.h
|
||||
sm_20_intrinsics.hpp
|
||||
sm_30_intrinsics.h
|
||||
sm_30_intrinsics.hpp
|
||||
sm_32_atomic_functions.h
|
||||
sm_32_atomic_functions.hpp
|
||||
sm_32_intrinsics.h
|
||||
sm_32_intrinsics.hpp
|
||||
sm_35_atomic_functions.h
|
||||
sm_35_intrinsics.h
|
||||
sm_60_atomic_functions.h
|
||||
sm_60_atomic_functions.hpp
|
||||
sm_61_intrinsics.h
|
||||
sm_61_intrinsics.hpp
|
||||
surface_indirect_functions.h
|
||||
surface_types.h
|
||||
target
|
||||
texture_indirect_functions.h
|
||||
texture_types.h
|
||||
vector_functions.h
|
||||
vector_functions.hpp
|
||||
vector_types.h)
|
||||
set(_mlx_jit_cuda_header_paths "")
|
||||
foreach(_header IN LISTS _mlx_jit_cuda_headers)
|
||||
if(EXISTS "${_cuda_inc}/${_header}")
|
||||
list(APPEND _mlx_jit_cuda_header_paths "${_cuda_inc}/${_header}")
|
||||
endif()
|
||||
endforeach()
|
||||
if(_mlx_jit_cuda_header_paths)
|
||||
install(FILES ${_mlx_jit_cuda_header_paths}
|
||||
vector_types.h
|
||||
)
|
||||
foreach(_hdr ${_MLX_JIT_CUDA_HEADERS})
|
||||
install(FILES "${_cuda_inc}/${_hdr}"
|
||||
DESTINATION ${_dst}
|
||||
COMPONENT MLX)
|
||||
endif()
|
||||
|
||||
foreach(_runtime_dir cooperative_groups crt)
|
||||
if(EXISTS "${_cuda_inc}/${_runtime_dir}")
|
||||
install(DIRECTORY "${_cuda_inc}/${_runtime_dir}"
|
||||
DESTINATION ${_dst}
|
||||
COMPONENT MLX)
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
# Subdirectory headers.
|
||||
install(DIRECTORY "${_cuda_inc}/cooperative_groups"
|
||||
DESTINATION ${_dst}
|
||||
COMPONENT MLX
|
||||
FILES_MATCHING PATTERN "*.h")
|
||||
install(FILES "${_cuda_inc}/crt/host_defines.h"
|
||||
DESTINATION "${_dst}/crt"
|
||||
COMPONENT MLX)
|
||||
if(NOT WIN32 AND NOT APPLE)
|
||||
install(CODE "
|
||||
set(_link \"${CMAKE_INSTALL_PREFIX}/${OLLAMA_LIB_DIR}/include\")
|
||||
@@ -303,10 +210,9 @@ endif()
|
||||
# RUNTIME_DEPENDENCIES auto-excludes it via POST_EXCLUDE_FILES_STRICT because
|
||||
# dlfcn-win32 is a known CMake target with its own install rules (which install
|
||||
# to the wrong destination). We must install it explicitly here.
|
||||
if(WIN32 AND TARGET dl)
|
||||
install(TARGETS dl
|
||||
RUNTIME DESTINATION ${OLLAMA_INSTALL_DIR}
|
||||
LIBRARY DESTINATION ${OLLAMA_INSTALL_DIR}
|
||||
if(WIN32)
|
||||
install(FILES ${OLLAMA_BUILD_DIR}/dl.dll
|
||||
DESTINATION ${OLLAMA_INSTALL_DIR}
|
||||
COMPONENT MLX)
|
||||
endif()
|
||||
|
||||
@@ -320,25 +226,7 @@ if(CUDAToolkit_FOUND)
|
||||
"${CUDAToolkit_LIBRARY_DIR}/libnvrtc.so*"
|
||||
"${CUDAToolkit_LIBRARY_DIR}/libnvrtc-builtins.so*"
|
||||
"${CUDAToolkit_LIBRARY_DIR}/libcufft.so*"
|
||||
"${CUDAToolkit_LIBRARY_DIR}/libcudnn*.so*")
|
||||
if(WIN32)
|
||||
file(GLOB MLX_CUDA_DLLS
|
||||
"${CUDAToolkit_BIN_DIR}/nvrtc-builtins64_*.dll"
|
||||
"${CUDAToolkit_BIN_DIR}/x64/nvrtc-builtins64_*.dll")
|
||||
list(APPEND MLX_CUDA_LIBS ${MLX_CUDA_DLLS})
|
||||
endif()
|
||||
find_library(MLX_CUDNN_LIBRARY NAMES cudnn HINTS "$ENV{CUDNN_LIBRARY_PATH}")
|
||||
if(MLX_CUDNN_LIBRARY)
|
||||
get_filename_component(MLX_CUDNN_LIBRARY_DIR "${MLX_CUDNN_LIBRARY}" DIRECTORY)
|
||||
file(GLOB MLX_CUDNN_LIBS "${MLX_CUDNN_LIBRARY_DIR}/libcudnn*.so*")
|
||||
list(APPEND MLX_CUDA_LIBS ${MLX_CUDNN_LIBS})
|
||||
endif()
|
||||
if(WIN32 AND _cudnn_root)
|
||||
file(GLOB MLX_CUDNN_DLLS
|
||||
"${_cudnn_root}/bin/${CUDAToolkit_VERSION_MAJOR}.0/cudnn*.dll"
|
||||
"${_cudnn_root}/bin/x64/cudnn*.dll")
|
||||
list(APPEND MLX_CUDA_LIBS ${MLX_CUDNN_DLLS})
|
||||
endif()
|
||||
"${CUDAToolkit_LIBRARY_DIR}/libcudnn.so*")
|
||||
if(MLX_CUDA_LIBS)
|
||||
install(FILES ${MLX_CUDA_LIBS}
|
||||
DESTINATION ${OLLAMA_INSTALL_DIR}
|
||||
|
||||
@@ -17,8 +17,6 @@
|
||||
"inherits": [ "default" ],
|
||||
"cacheVariables": {
|
||||
"CMAKE_CUDA_FLAGS": "-t 2",
|
||||
"MLX_BUILD_CUDA": "ON",
|
||||
"MLX_BUILD_METAL": "OFF",
|
||||
"OLLAMA_RUNNER_DIR": "mlx_cuda_v13"
|
||||
}
|
||||
},
|
||||
@@ -57,7 +55,7 @@
|
||||
"inherits": [ "default" ],
|
||||
"binaryDir": "${sourceDir}/../../build/metal-v4",
|
||||
"cacheVariables": {
|
||||
"CMAKE_OSX_DEPLOYMENT_TARGET": "26.2",
|
||||
"CMAKE_OSX_DEPLOYMENT_TARGET": "26.0",
|
||||
"OLLAMA_RUNNER_DIR": "mlx_metal_v4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
//go:build !windows
|
||||
|
||||
package cmd
|
||||
|
||||
import "syscall"
|
||||
|
||||
// backgroundServerSysProcAttr returns SysProcAttr for running the server in the background on Unix.
|
||||
// Setpgid prevents the server from being killed when the parent process exits.
|
||||
func backgroundServerSysProcAttr() *syscall.SysProcAttr {
|
||||
return &syscall.SysProcAttr{
|
||||
Setpgid: true,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package cmd
|
||||
|
||||
import "syscall"
|
||||
|
||||
// backgroundServerSysProcAttr returns SysProcAttr for running the server in the background on Windows.
|
||||
// CREATE_NO_WINDOW (0x08000000) prevents a console window from appearing.
|
||||
func backgroundServerSysProcAttr() *syscall.SysProcAttr {
|
||||
return &syscall.SysProcAttr{
|
||||
CreationFlags: 0x08000000,
|
||||
HideWindow: true,
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/term"
|
||||
|
||||
"github.com/ollama/ollama/api"
|
||||
"github.com/ollama/ollama/cmd/launch"
|
||||
"github.com/ollama/ollama/internal/modelref"
|
||||
"github.com/ollama/ollama/types/model"
|
||||
)
|
||||
|
||||
// for testing
|
||||
var (
|
||||
isInteractiveTerminal = func() bool {
|
||||
return term.IsTerminal(int(os.Stdin.Fd())) && term.IsTerminal(int(os.Stdout.Fd()))
|
||||
}
|
||||
|
||||
confirmCloudSuggestion = func(prompt string) (bool, error) {
|
||||
// Zero-value options default to Yes being preselected.
|
||||
return launch.ConfirmPromptWithOptions(prompt, launch.ConfirmOptions{})
|
||||
}
|
||||
)
|
||||
|
||||
// pullModelNotFoundMessage is how a registry 404 during pull surfaces to
|
||||
// clients: os.ErrNotExist wrapped server-side and flattened into the error
|
||||
// string of the pull stream.
|
||||
const pullModelNotFoundMessage = "pull model manifest: file does not exist"
|
||||
|
||||
// isPullNotFoundErr reports whether err is a pull failure caused by the
|
||||
// requested model or tag not existing in the registry.
|
||||
func isPullNotFoundErr(err error) bool {
|
||||
return err != nil && strings.Contains(err.Error(), pullModelNotFoundMessage)
|
||||
}
|
||||
|
||||
// cloudSuggestionCandidate reports whether a failed pull of name should
|
||||
// trigger a ":cloud" suggestion, and if so returns the cloud model name to
|
||||
// suggest. It only applies to default-tag lookups (e.g. "kimi-k3") against
|
||||
// the default registry whose pull failed because the tag doesn't exist.
|
||||
func cloudSuggestionCandidate(name string, pullErr error, insecure bool) (string, bool) {
|
||||
if !isPullNotFoundErr(pullErr) {
|
||||
return "", false
|
||||
}
|
||||
return cloudSuggestionName(name, insecure)
|
||||
}
|
||||
|
||||
// cloudSuggestionName applies the name-based eligibility checks for the
|
||||
// ":cloud" suggestion, returning the cloud model name to suggest.
|
||||
func cloudSuggestionName(name string, insecure bool) (string, bool) {
|
||||
// --insecure implies a non-default registry, where an ollama.com cloud
|
||||
// model wouldn't be a meaningful suggestion.
|
||||
if insecure {
|
||||
return "", false
|
||||
}
|
||||
|
||||
ref, err := modelref.ParseRef(name)
|
||||
if err != nil || ref.Source != modelref.ModelSourceUnspecified {
|
||||
return "", false
|
||||
}
|
||||
|
||||
if modelref.HasExplicitTag(ref.Base) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Only default-registry names qualify: the existence probe forwards the name
|
||||
// to ollama.com, and custom-registry model names shouldn't be sent there.
|
||||
if n := model.ParseName(ref.Base); !n.IsValid() || !strings.EqualFold(n.Host, model.DefaultName().Host) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return ref.Base + ":cloud", true
|
||||
}
|
||||
|
||||
// pullWithCloudSuggestion pulls `name`, and if the model's default tag
|
||||
// doesn't exist but a ":cloud" tag does, offers it: either interactively via
|
||||
// a confirmation prompt, or by augmenting the returned error when not at a
|
||||
// terminal. It returns the name that was actually pulled. `verb` is the
|
||||
// user-facing command ("run" or "pull") used in the hint text.
|
||||
func pullWithCloudSuggestion(ctx context.Context, client *api.Client, name string, insecure bool, verb string) (string, error) {
|
||||
// If a suggestion prompt may follow a failed pull, erase the failed
|
||||
// attempt's progress display instead of leaving its "pulling manifest"
|
||||
// line to stack up against the accepted pull's identical one.
|
||||
_, eligible := cloudSuggestionName(name, insecure)
|
||||
clearNotFound := eligible && isInteractiveTerminal()
|
||||
|
||||
pullErr := pullModelWithProgress(ctx, client, name, insecure, clearNotFound)
|
||||
if pullErr == nil {
|
||||
return name, nil
|
||||
}
|
||||
|
||||
cloudName, ok := cloudSuggestionCandidate(name, pullErr, insecure)
|
||||
if !ok || ctx.Err() != nil {
|
||||
return "", pullErr
|
||||
}
|
||||
|
||||
// Showing a ":cloud" model is proxied to ollama.com and mirrors its status,
|
||||
// so this reliably answers "does a cloud version exist?". Any error (no
|
||||
// cloud tag, cloud disabled, older server, offline) means no suggestion.
|
||||
if _, err := client.Show(ctx, &api.ShowRequest{Model: cloudName}); err != nil {
|
||||
return "", pullErr
|
||||
}
|
||||
|
||||
if !isInteractiveTerminal() {
|
||||
return "", fmt.Errorf("%w\n\n%q is available as a cloud model. Try:\n ollama %s %s", pullErr, cloudName, verb, cloudName)
|
||||
}
|
||||
|
||||
accepted, err := confirmCloudSuggestion(fmt.Sprintf("Did you mean %q?", cloudName))
|
||||
if err != nil || !accepted {
|
||||
// Declining or cancelling falls back to the original error.
|
||||
return "", pullErr
|
||||
}
|
||||
|
||||
if err := pullModelWithProgress(ctx, client, cloudName, insecure, false); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return cloudName, nil
|
||||
}
|
||||
@@ -1,411 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/ollama/ollama/api"
|
||||
"github.com/ollama/ollama/cmd/launch"
|
||||
"github.com/ollama/ollama/types/model"
|
||||
)
|
||||
|
||||
func TestCloudSuggestionCandidate(t *testing.T) {
|
||||
notFoundErr := errors.New("pull model manifest: file does not exist")
|
||||
suggestedErr := errors.New("pull model manifest: file does not exist\n\nTry one of these models:\n some-model:cloud")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
model string
|
||||
pullErr error
|
||||
insecure bool
|
||||
want string
|
||||
wantOK bool
|
||||
}{
|
||||
{name: "default tag not found", model: "some-model", pullErr: notFoundErr, want: "some-model:cloud", wantOK: true},
|
||||
{name: "composes with server tag suggestions", model: "some-model", pullErr: suggestedErr, want: "some-model:cloud", wantOK: true},
|
||||
{name: "namespaced default tag", model: "user/some-model", pullErr: notFoundErr, want: "user/some-model:cloud", wantOK: true},
|
||||
{name: "nil error", model: "some-model", pullErr: nil},
|
||||
{name: "unrelated error", model: "some-model", pullErr: errors.New("boom")},
|
||||
{name: "insecure registry", model: "some-model", pullErr: notFoundErr, insecure: true},
|
||||
{name: "explicit tag", model: "some-model:9b", pullErr: notFoundErr},
|
||||
{name: "explicit latest tag", model: "some-model:latest", pullErr: notFoundErr},
|
||||
{name: "explicit cloud source", model: "some-model:cloud", pullErr: notFoundErr},
|
||||
{name: "explicit legacy cloud tag", model: "some-model:9b-cloud", pullErr: notFoundErr},
|
||||
{name: "explicit local source", model: "some-model:local", pullErr: notFoundErr},
|
||||
{name: "custom registry host", model: "internal.example.com/team/private-model", pullErr: notFoundErr},
|
||||
{name: "custom registry host with port", model: "registry.example.com:5000/team/private-model", pullErr: notFoundErr},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, ok := cloudSuggestionCandidate(tt.model, tt.pullErr, tt.insecure)
|
||||
if ok != tt.wantOK {
|
||||
t.Fatalf("cloudSuggestionCandidate(%q) ok = %v, want %v", tt.model, ok, tt.wantOK)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("cloudSuggestionCandidate(%q) = %q, want %q", tt.model, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// stubCloudSuggest replaces the TTY check and confirmation prompt for the
|
||||
// duration of the test. If confirm is nil, any prompt fails the test.
|
||||
func stubCloudSuggest(t *testing.T, interactive bool, confirm func(prompt string) (bool, error)) *[]string {
|
||||
t.Helper()
|
||||
|
||||
oldTTY, oldConfirm := isInteractiveTerminal, confirmCloudSuggestion
|
||||
t.Cleanup(func() {
|
||||
isInteractiveTerminal, confirmCloudSuggestion = oldTTY, oldConfirm
|
||||
})
|
||||
|
||||
isInteractiveTerminal = func() bool { return interactive }
|
||||
|
||||
prompts := &[]string{}
|
||||
confirmCloudSuggestion = func(prompt string) (bool, error) {
|
||||
*prompts = append(*prompts, prompt)
|
||||
if confirm == nil {
|
||||
t.Errorf("unexpected cloud suggestion prompt: %q", prompt)
|
||||
return false, nil
|
||||
}
|
||||
return confirm(prompt)
|
||||
}
|
||||
return prompts
|
||||
}
|
||||
|
||||
type cloudSuggestServer struct {
|
||||
cloudName string // model name whose show/pull succeeds (e.g. "some-model:cloud")
|
||||
cloudExists bool // whether showing/pulling cloudName succeeds
|
||||
pullErr string // error message for failing pulls
|
||||
|
||||
showModels []string
|
||||
pullModels []string
|
||||
generateModels []string
|
||||
}
|
||||
|
||||
// start serves mock /api/show, /api/pull, /api/tags, and /api/generate
|
||||
// endpoints: only cloudName is known (when cloudExists), and pulling any other
|
||||
// model fails with pullErr streamed the way real servers do (an in-band error
|
||||
// under HTTP 200).
|
||||
func (s *cloudSuggestServer) start(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/api/show" && r.Method == http.MethodPost:
|
||||
var req api.ShowRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
name := cmp.Or(req.Model, req.Name)
|
||||
s.showModels = append(s.showModels, name)
|
||||
if s.cloudExists && name == s.cloudName {
|
||||
if err := json.NewEncoder(w).Encode(api.ShowResponse{
|
||||
Capabilities: []model.Capability{model.CapabilityCompletion},
|
||||
RemoteModel: strings.TrimSuffix(s.cloudName, ":cloud"),
|
||||
}); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
if err := json.NewEncoder(w).Encode(map[string]string{
|
||||
"error": "model '" + name + "' not found",
|
||||
}); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
case r.URL.Path == "/api/pull" && r.Method == http.MethodPost:
|
||||
var req api.PullRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
name := cmp.Or(req.Model, req.Name)
|
||||
s.pullModels = append(s.pullModels, name)
|
||||
var body any
|
||||
if s.cloudExists && name == s.cloudName {
|
||||
body = api.ProgressResponse{Status: "success"}
|
||||
} else {
|
||||
body = map[string]string{"error": s.pullErr}
|
||||
}
|
||||
if err := json.NewEncoder(w).Encode(body); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
case r.URL.Path == "/api/tags" && r.Method == http.MethodGet:
|
||||
if err := json.NewEncoder(w).Encode(api.ListResponse{
|
||||
Models: []api.ListModelResponse{{Name: s.cloudName}},
|
||||
}); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
case r.URL.Path == "/api/generate" && r.Method == http.MethodPost:
|
||||
var req api.GenerateRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
s.generateModels = append(s.generateModels, req.Model)
|
||||
if err := json.NewEncoder(w).Encode(api.GenerateResponse{Done: true}); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
|
||||
t.Setenv("OLLAMA_HOST", mockServer.URL)
|
||||
t.Cleanup(mockServer.Close)
|
||||
}
|
||||
|
||||
func newCloudSuggestServer(t *testing.T) *cloudSuggestServer {
|
||||
t.Helper()
|
||||
s := &cloudSuggestServer{
|
||||
cloudName: "some-model:cloud",
|
||||
cloudExists: true,
|
||||
pullErr: "pull model manifest: file does not exist",
|
||||
}
|
||||
s.start(t)
|
||||
return s
|
||||
}
|
||||
|
||||
func newPullTestCmd(t *testing.T) *cobra.Command {
|
||||
t.Helper()
|
||||
cmd := &cobra.Command{}
|
||||
cmd.SetContext(t.Context())
|
||||
cmd.Flags().Bool("insecure", false, "")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newRunTestCmd(t *testing.T) *cobra.Command {
|
||||
t.Helper()
|
||||
cmd := &cobra.Command{}
|
||||
cmd.SetContext(t.Context())
|
||||
cmd.Flags().String("keepalive", "", "")
|
||||
cmd.Flags().Bool("truncate", false, "")
|
||||
cmd.Flags().Int("dimensions", 0, "")
|
||||
cmd.Flags().Bool("verbose", false, "")
|
||||
cmd.Flags().Bool("insecure", false, "")
|
||||
cmd.Flags().Bool("nowordwrap", false, "")
|
||||
cmd.Flags().String("format", "", "")
|
||||
cmd.Flags().String("think", "", "")
|
||||
cmd.Flags().Bool("hidethinking", false, "")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func TestPullHandler_SuccessfulPullNoSuggestion(t *testing.T) {
|
||||
server := newCloudSuggestServer(t)
|
||||
server.cloudName = "some-model" // the requested model itself pulls fine
|
||||
stubCloudSuggest(t, true, nil)
|
||||
|
||||
if err := PullHandler(newPullTestCmd(t), []string{"some-model"}); err != nil {
|
||||
t.Fatalf("PullHandler returned error: %v", err)
|
||||
}
|
||||
if want := []string{"some-model"}; !slices.Equal(server.pullModels, want) {
|
||||
t.Fatalf("pulled models = %v, want %v", server.pullModels, want)
|
||||
}
|
||||
if len(server.showModels) != 0 {
|
||||
t.Fatalf("show models = %v, want no probe after a successful pull", server.showModels)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullHandler_CloudSuggestionAccepted(t *testing.T) {
|
||||
server := newCloudSuggestServer(t)
|
||||
prompts := stubCloudSuggest(t, true, func(string) (bool, error) { return true, nil })
|
||||
|
||||
if err := PullHandler(newPullTestCmd(t), []string{"some-model"}); err != nil {
|
||||
t.Fatalf("PullHandler returned error: %v", err)
|
||||
}
|
||||
|
||||
if want := []string{"some-model", "some-model:cloud"}; !slices.Equal(server.pullModels, want) {
|
||||
t.Fatalf("pulled models = %v, want %v", server.pullModels, want)
|
||||
}
|
||||
if len(*prompts) != 1 || !strings.Contains((*prompts)[0], `"some-model:cloud"`) {
|
||||
t.Fatalf("prompts = %v, want one prompt mentioning some-model:cloud", *prompts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullHandler_CloudSuggestionDeclined(t *testing.T) {
|
||||
server := newCloudSuggestServer(t)
|
||||
stubCloudSuggest(t, true, func(string) (bool, error) { return false, nil })
|
||||
|
||||
err := PullHandler(newPullTestCmd(t), []string{"some-model"})
|
||||
if err == nil {
|
||||
t.Fatal("PullHandler returned nil, want an error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "pull model manifest: file does not exist") {
|
||||
t.Fatalf("error = %q, want it to contain the original pull error", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "Try:") {
|
||||
t.Fatalf("error = %q, want no non-interactive hint after declining", err)
|
||||
}
|
||||
if want := []string{"some-model"}; !slices.Equal(server.pullModels, want) {
|
||||
t.Fatalf("pulled models = %v, want %v", server.pullModels, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullHandler_CloudSuggestionCancelled(t *testing.T) {
|
||||
server := newCloudSuggestServer(t)
|
||||
stubCloudSuggest(t, true, func(string) (bool, error) { return false, launch.ErrCancelled })
|
||||
|
||||
err := PullHandler(newPullTestCmd(t), []string{"some-model"})
|
||||
if err == nil {
|
||||
t.Fatal("PullHandler returned nil, want an error")
|
||||
}
|
||||
if errors.Is(err, launch.ErrCancelled) {
|
||||
t.Fatalf("error = %v, want the original pull error rather than ErrCancelled", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "pull model manifest: file does not exist") {
|
||||
t.Fatalf("error = %q, want it to contain the original pull error", err)
|
||||
}
|
||||
if want := []string{"some-model"}; !slices.Equal(server.pullModels, want) {
|
||||
t.Fatalf("pulled models = %v, want %v", server.pullModels, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullHandler_CloudSuggestionNonInteractive(t *testing.T) {
|
||||
server := newCloudSuggestServer(t)
|
||||
stubCloudSuggest(t, false, nil)
|
||||
|
||||
err := PullHandler(newPullTestCmd(t), []string{"some-model"})
|
||||
if err == nil {
|
||||
t.Fatal("PullHandler returned nil, want an error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "pull model manifest: file does not exist") {
|
||||
t.Fatalf("error = %q, want it to contain the original pull error", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "ollama pull some-model:cloud") {
|
||||
t.Fatalf("error = %q, want it to hint at 'ollama pull some-model:cloud'", err)
|
||||
}
|
||||
if want := []string{"some-model"}; !slices.Equal(server.pullModels, want) {
|
||||
t.Fatalf("pulled models = %v, want %v", server.pullModels, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullHandler_CloudSuggestionNoCloudTag(t *testing.T) {
|
||||
server := newCloudSuggestServer(t)
|
||||
server.cloudExists = false
|
||||
stubCloudSuggest(t, true, nil)
|
||||
|
||||
err := PullHandler(newPullTestCmd(t), []string{"some-model"})
|
||||
if err == nil || err.Error() != "pull model manifest: file does not exist" {
|
||||
t.Fatalf("error = %v, want the unmodified pull error", err)
|
||||
}
|
||||
if want := []string{"some-model:cloud"}; !slices.Equal(server.showModels, want) {
|
||||
t.Fatalf("show models = %v, want the cloud existence probe %v", server.showModels, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullHandler_CloudSuggestionExplicitTag(t *testing.T) {
|
||||
server := newCloudSuggestServer(t)
|
||||
stubCloudSuggest(t, true, nil)
|
||||
|
||||
err := PullHandler(newPullTestCmd(t), []string{"some-model:9b"})
|
||||
if err == nil || err.Error() != "pull model manifest: file does not exist" {
|
||||
t.Fatalf("error = %v, want the unmodified pull error", err)
|
||||
}
|
||||
if len(server.showModels) != 0 {
|
||||
t.Fatalf("show models = %v, want no cloud probe for explicitly tagged models", server.showModels)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullHandler_CloudSuggestionExplicitCloud(t *testing.T) {
|
||||
server := newCloudSuggestServer(t)
|
||||
server.cloudExists = false // make the explicit :cloud pull fail too
|
||||
stubCloudSuggest(t, true, nil)
|
||||
|
||||
err := PullHandler(newPullTestCmd(t), []string{"some-model:cloud"})
|
||||
if err == nil || err.Error() != "pull model manifest: file does not exist" {
|
||||
t.Fatalf("error = %v, want the unmodified pull error", err)
|
||||
}
|
||||
if len(server.showModels) != 0 {
|
||||
t.Fatalf("show models = %v, want no probe for explicit :cloud requests", server.showModels)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullHandler_CloudSuggestionInsecure(t *testing.T) {
|
||||
server := newCloudSuggestServer(t)
|
||||
stubCloudSuggest(t, true, nil)
|
||||
|
||||
cmd := newPullTestCmd(t)
|
||||
if err := cmd.Flags().Set("insecure", "true"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := PullHandler(cmd, []string{"some-model"})
|
||||
if err == nil || err.Error() != "pull model manifest: file does not exist" {
|
||||
t.Fatalf("error = %v, want the unmodified pull error", err)
|
||||
}
|
||||
if len(server.showModels) != 0 {
|
||||
t.Fatalf("show models = %v, want no probe for --insecure pulls", server.showModels)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullHandler_CloudSuggestionUnrelatedError(t *testing.T) {
|
||||
server := newCloudSuggestServer(t)
|
||||
server.pullErr = "boom"
|
||||
stubCloudSuggest(t, true, nil)
|
||||
|
||||
err := PullHandler(newPullTestCmd(t), []string{"some-model"})
|
||||
if err == nil || err.Error() != "boom" {
|
||||
t.Fatalf("error = %v, want the unmodified pull error %q", err, "boom")
|
||||
}
|
||||
if len(server.showModels) != 0 {
|
||||
t.Fatalf("show models = %v, want no probe for unrelated pull errors", server.showModels)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunHandler_CloudSuggestionAccepted_RunsCloudModel(t *testing.T) {
|
||||
server := newCloudSuggestServer(t)
|
||||
stubCloudSuggest(t, true, func(string) (bool, error) { return true, nil })
|
||||
|
||||
if err := RunHandler(newRunTestCmd(t), []string{"some-model", "hi"}); err != nil {
|
||||
t.Fatalf("RunHandler returned error: %v", err)
|
||||
}
|
||||
|
||||
if want := []string{"some-model", "some-model:cloud"}; !slices.Equal(server.pullModels, want) {
|
||||
t.Fatalf("pulled models = %v, want %v", server.pullModels, want)
|
||||
}
|
||||
if want := []string{"some-model:cloud"}; !slices.Equal(server.generateModels, want) {
|
||||
t.Fatalf("generate models = %v, want %v", server.generateModels, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunHandler_CloudSuggestionDeclined_ReturnsNotFound(t *testing.T) {
|
||||
server := newCloudSuggestServer(t)
|
||||
stubCloudSuggest(t, true, func(string) (bool, error) { return false, nil })
|
||||
|
||||
err := RunHandler(newRunTestCmd(t), []string{"some-model", "hi"})
|
||||
if err == nil {
|
||||
t.Fatal("RunHandler returned nil, want an error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "pull model manifest: file does not exist") {
|
||||
t.Fatalf("error = %q, want it to contain the original pull error", err)
|
||||
}
|
||||
if len(server.generateModels) != 0 {
|
||||
t.Fatalf("generate models = %v, want none after declining", server.generateModels)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunHandler_CloudSuggestionNonInteractive_Hint(t *testing.T) {
|
||||
server := newCloudSuggestServer(t)
|
||||
stubCloudSuggest(t, false, nil)
|
||||
|
||||
err := RunHandler(newRunTestCmd(t), []string{"some-model", "hi"})
|
||||
if err == nil {
|
||||
t.Fatal("RunHandler returned nil, want an error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "ollama run some-model:cloud") {
|
||||
t.Fatalf("error = %q, want it to hint at 'ollama run some-model:cloud'", err)
|
||||
}
|
||||
if len(server.generateModels) != 0 {
|
||||
t.Fatalf("generate models = %v, want none in non-interactive mode", server.generateModels)
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path"
|
||||
"path/filepath"
|
||||
@@ -54,8 +55,10 @@ import (
|
||||
"github.com/ollama/ollama/types/model"
|
||||
"github.com/ollama/ollama/types/syncmap"
|
||||
"github.com/ollama/ollama/version"
|
||||
xcmd "github.com/ollama/ollama/x/cmd"
|
||||
xcreate "github.com/ollama/ollama/x/create"
|
||||
xcreateclient "github.com/ollama/ollama/x/create/client"
|
||||
"github.com/ollama/ollama/x/imagegen"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -93,8 +96,6 @@ func init() {
|
||||
}
|
||||
|
||||
launch.DefaultConfirmPrompt = tui.RunConfirmWithOptions
|
||||
|
||||
launch.DefaultSpinner = tui.RunSpinner
|
||||
}
|
||||
|
||||
func runTUISingleSelector(title string, items []launch.SelectionItem, current string, updates <-chan []launch.SelectionItem) (string, error) {
|
||||
@@ -191,7 +192,7 @@ func resolveExperimentalLocalModelDir(ref, filename string) string {
|
||||
}
|
||||
|
||||
candidate := filepath.Join(filepath.Dir(filename), ref)
|
||||
if xcreate.IsSafetensorsModelDir(candidate) {
|
||||
if xcreate.IsSafetensorsModelDir(candidate) || xcreate.IsTensorModelDir(candidate) {
|
||||
return candidate
|
||||
}
|
||||
|
||||
@@ -229,7 +230,8 @@ func CreateHandler(cmd *cobra.Command, args []string) error {
|
||||
return fmt.Errorf("invalid model name: %s", modelName)
|
||||
}
|
||||
|
||||
// Check for --experimental flag for safetensors model creation.
|
||||
// Check for --experimental flag for safetensors model creation
|
||||
// This gates both safetensors LLM and imagegen model creation
|
||||
experimental, _ := cmd.Flags().GetBool("experimental")
|
||||
draftQuantize, _ := cmd.Flags().GetString("draft-quantize")
|
||||
if experimental {
|
||||
@@ -707,32 +709,6 @@ func hasListedModelName(models []api.ListModelResponse, name string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// showOrPullModel returns model info for name, pulling the model if it isn't
|
||||
// available locally. If the pull finds no default tag but a ":cloud" tag
|
||||
// exists, the user may be offered the cloud model instead (see
|
||||
// pullWithCloudSuggestion), in which case the returned name is the cloud
|
||||
// name the caller should continue with. verb is the user-facing command
|
||||
// ("run" or "pull") used in hint text.
|
||||
func showOrPullModel(cmd *cobra.Command, client *api.Client, name string, insecure bool, verb string) (*api.ShowResponse, string, error) {
|
||||
info, err := client.Show(cmd.Context(), &api.ShowRequest{Model: name})
|
||||
if err == nil {
|
||||
return info, name, nil
|
||||
}
|
||||
|
||||
var se api.StatusError
|
||||
if !errors.As(err, &se) || se.StatusCode != http.StatusNotFound || modelref.HasExplicitCloudSource(name) {
|
||||
return nil, name, err
|
||||
}
|
||||
|
||||
resolved, err := pullWithCloudSuggestion(cmd.Context(), client, name, insecure, verb)
|
||||
if err != nil {
|
||||
return nil, name, err
|
||||
}
|
||||
|
||||
info, err = client.Show(cmd.Context(), &api.ShowRequest{Model: resolved})
|
||||
return info, resolved, err
|
||||
}
|
||||
|
||||
func RunHandler(cmd *cobra.Command, args []string) error {
|
||||
interactive := true
|
||||
|
||||
@@ -828,21 +804,30 @@ func RunHandler(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
insecure, err := cmd.Flags().GetBool("insecure")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := args[0]
|
||||
requestedCloud := modelref.HasExplicitCloudSource(name)
|
||||
|
||||
info, name, err := showOrPullModel(cmd, client, args[0], insecure, "run")
|
||||
info, err := func() (*api.ShowResponse, error) {
|
||||
showReq := &api.ShowRequest{Name: name}
|
||||
info, err := client.Show(cmd.Context(), showReq)
|
||||
var se api.StatusError
|
||||
if errors.As(err, &se) && se.StatusCode == http.StatusNotFound {
|
||||
if requestedCloud {
|
||||
return nil, err
|
||||
}
|
||||
if err := PullHandler(cmd, []string{name}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client.Show(cmd.Context(), &api.ShowRequest{Name: name})
|
||||
}
|
||||
return info, err
|
||||
}()
|
||||
if err != nil {
|
||||
if handleCloudAuthorizationError(err) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
// The model may have been resolved to a different name (e.g. its ":cloud"
|
||||
// variant), so make sure downstream requests use it.
|
||||
opts.Model = name
|
||||
|
||||
ensureCloudStub(cmd.Context(), client, name)
|
||||
|
||||
@@ -892,10 +877,19 @@ func RunHandler(cmd *cobra.Command, args []string) error {
|
||||
return generateEmbedding(cmd, name, opts.Prompt, opts.KeepAlive, truncate, dimensions)
|
||||
}
|
||||
|
||||
// Check if this is an image generation model
|
||||
if slices.Contains(info.Capabilities, model.CapabilityImage) {
|
||||
return errors.New("image generation models are not currently supported")
|
||||
if opts.Prompt == "" && !interactive {
|
||||
return errors.New("image generation models require a prompt. Usage: ollama run " + name + " \"your prompt here\"")
|
||||
}
|
||||
return imagegen.RunCLI(cmd, name, opts.Prompt, interactive, opts.KeepAlive)
|
||||
}
|
||||
|
||||
// Check for experimental flag
|
||||
isExperimental, _ := cmd.Flags().GetBool("experimental")
|
||||
yoloMode, _ := cmd.Flags().GetBool("experimental-yolo")
|
||||
enableWebsearch, _ := cmd.Flags().GetBool("experimental-websearch")
|
||||
|
||||
if interactive {
|
||||
if err := loadOrUnloadModel(cmd, &opts); err != nil {
|
||||
var sErr api.AuthorizationError
|
||||
@@ -922,6 +916,11 @@ func RunHandler(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
}
|
||||
|
||||
// Use experimental agent loop with tools
|
||||
if isExperimental {
|
||||
return xcmd.GenerateInteractive(cmd, opts.Model, opts.WordWrap, opts.Options, opts.Think, opts.HideThinking, opts.KeepAlive, yoloMode, enableWebsearch)
|
||||
}
|
||||
|
||||
return generateInteractive(cmd, opts)
|
||||
}
|
||||
if err := generate(cmd, opts); err != nil {
|
||||
@@ -1258,10 +1257,6 @@ func ShowHandler(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if slices.Contains(resp.Capabilities, model.CapabilityImage) {
|
||||
return errors.New("image generation models are not currently supported")
|
||||
}
|
||||
|
||||
if flagsSet == 1 {
|
||||
switch showType {
|
||||
case "license":
|
||||
@@ -1523,15 +1518,6 @@ func PullHandler(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = pullWithCloudSuggestion(cmd.Context(), client, args[0], insecure, "pull")
|
||||
return err
|
||||
}
|
||||
|
||||
// pullModelWithProgress pulls name, rendering progress to stderr. When
|
||||
// clearNotFound is set and the pull fails because the model doesn't exist,
|
||||
// the progress display is erased rather than left behind; callers set it
|
||||
// when a ":cloud" suggestion prompt may immediately follow the failure.
|
||||
func pullModelWithProgress(ctx context.Context, client *api.Client, name string, insecure, clearNotFound bool) error {
|
||||
p := progress.NewProgress(os.Stderr)
|
||||
defer p.Stop()
|
||||
|
||||
@@ -1592,13 +1578,8 @@ func pullModelWithProgress(ctx context.Context, client *api.Client, name string,
|
||||
return nil
|
||||
}
|
||||
|
||||
request := api.PullRequest{Name: name, Insecure: insecure}
|
||||
err := client.Pull(ctx, &request, fn)
|
||||
if clearNotFound && isPullNotFoundErr(err) {
|
||||
// The deferred Stop becomes a no-op after this.
|
||||
p.StopAndClear()
|
||||
}
|
||||
return err
|
||||
request := api.PullRequest{Name: args[0], Insecure: insecure}
|
||||
return client.Pull(cmd.Context(), &request, fn)
|
||||
}
|
||||
|
||||
type generateContextKey string
|
||||
@@ -2085,7 +2066,7 @@ func checkServerHeartbeat(cmd *cobra.Command, _ []string) error {
|
||||
if !(strings.Contains(err.Error(), " refused") || strings.Contains(err.Error(), "could not connect")) {
|
||||
return err
|
||||
}
|
||||
if err := startApp(cmd.Context(), client); err != nil { //nolint:staticcheck,nolintlint // startApp always returns non-nil on Linux (start_default.go) but can return nil on macOS/Windows
|
||||
if err := startApp(cmd.Context(), client); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -2127,6 +2108,40 @@ Environment Variables:
|
||||
cmd.SetUsageTemplate(cmd.UsageTemplate() + envUsage)
|
||||
}
|
||||
|
||||
// ensureServerRunning checks if the ollama server is running and starts it in the background if not.
|
||||
func ensureServerRunning(ctx context.Context) error {
|
||||
client, err := api.ClientFromEnvironment()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Check if server is already running
|
||||
if err := client.Heartbeat(ctx); err == nil {
|
||||
return nil // server is already running
|
||||
}
|
||||
|
||||
// Server not running, start it in the background
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not find executable: %w", err)
|
||||
}
|
||||
|
||||
serverCmd := exec.CommandContext(ctx, exe, "serve")
|
||||
serverCmd.Env = os.Environ()
|
||||
serverCmd.SysProcAttr = backgroundServerSysProcAttr()
|
||||
if err := serverCmd.Start(); err != nil {
|
||||
return fmt.Errorf("failed to start server: %w", err)
|
||||
}
|
||||
|
||||
// Wait for the server to be ready
|
||||
for {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
if err := client.Heartbeat(ctx); err == nil {
|
||||
return nil // server has started
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func launchInteractiveModel(cmd *cobra.Command, modelName string) error {
|
||||
opts := runOptions{
|
||||
Model: modelName,
|
||||
@@ -2140,15 +2155,31 @@ func launchInteractiveModel(cmd *cobra.Command, modelName string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
info, resolvedModel, err := showOrPullModel(cmd, client, modelName, false, "run")
|
||||
requestedCloud := modelref.HasExplicitCloudSource(modelName)
|
||||
|
||||
info, err := func() (*api.ShowResponse, error) {
|
||||
showReq := &api.ShowRequest{Name: modelName}
|
||||
info, err := client.Show(cmd.Context(), showReq)
|
||||
var se api.StatusError
|
||||
if errors.As(err, &se) && se.StatusCode == http.StatusNotFound {
|
||||
if requestedCloud {
|
||||
return nil, err
|
||||
}
|
||||
if err := PullHandler(cmd, []string{modelName}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client.Show(cmd.Context(), &api.ShowRequest{Name: modelName})
|
||||
}
|
||||
return info, err
|
||||
}()
|
||||
if err != nil {
|
||||
if handleCloudAuthorizationError(err) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
opts.Model = resolvedModel
|
||||
ensureCloudStub(cmd.Context(), client, opts.Model)
|
||||
|
||||
ensureCloudStub(cmd.Context(), client, modelName)
|
||||
|
||||
opts.Think, err = inferThinkingOption(&info.Capabilities, &opts, false)
|
||||
if err != nil {
|
||||
@@ -2157,11 +2188,15 @@ func launchInteractiveModel(cmd *cobra.Command, modelName string) error {
|
||||
|
||||
audioCapable := slices.Contains(info.Capabilities, model.CapabilityAudio)
|
||||
opts.MultiModal = slices.Contains(info.Capabilities, model.CapabilityVision) || audioCapable
|
||||
|
||||
// TODO: remove the projector info and vision info checks below,
|
||||
// these are left in for backwards compatibility with older servers
|
||||
// that don't have the capabilities field in the model info
|
||||
if len(info.ProjectorInfo) != 0 {
|
||||
opts.MultiModal = true
|
||||
}
|
||||
for key := range info.ModelInfo {
|
||||
if strings.Contains(key, ".vision.") {
|
||||
for k := range info.ModelInfo {
|
||||
if strings.Contains(k, ".vision.") {
|
||||
opts.MultiModal = true
|
||||
break
|
||||
}
|
||||
@@ -2180,9 +2215,9 @@ func launchInteractiveModel(cmd *cobra.Command, modelName string) error {
|
||||
|
||||
// runInteractiveTUI runs the main interactive TUI menu.
|
||||
func runInteractiveTUI(cmd *cobra.Command) {
|
||||
// Ensure the server is running via the shared checkServerHeartbeat path.
|
||||
if err := checkServerHeartbeat(cmd, nil); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
// Ensure the server is running before showing the TUI
|
||||
if err := ensureServerRunning(cmd.Context()); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error starting server: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -2289,7 +2324,7 @@ func runLauncherAction(cmd *cobra.Command, action tui.TUIAction, deps launcherDe
|
||||
|
||||
func launcherActionExitsLoop(integration string) bool {
|
||||
switch integration {
|
||||
case "chatgpt", "codex-app", "vscode":
|
||||
case "codex-app", "vscode":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
@@ -2378,6 +2413,15 @@ func NewCLI() *cobra.Command {
|
||||
runCmd.Flags().Bool("hidethinking", false, "Hide thinking output (if provided)")
|
||||
runCmd.Flags().Bool("truncate", false, "For embedding models: truncate inputs exceeding context length (default: true). Set --truncate=false to error instead")
|
||||
runCmd.Flags().Int("dimensions", 0, "Truncate output embeddings to specified dimension (embedding models only)")
|
||||
runCmd.Flags().Bool("experimental", false, "Enable experimental agent loop with tools")
|
||||
runCmd.Flags().Bool("experimental-yolo", false, "Skip all tool approval prompts (use with caution)")
|
||||
runCmd.Flags().Bool("experimental-websearch", false, "Enable web search tool in experimental mode")
|
||||
|
||||
// Image generation flags (width, height, steps, seed, etc.)
|
||||
imagegen.RegisterFlags(runCmd)
|
||||
|
||||
runCmd.Flags().Bool("imagegen", false, "Use the imagegen runner for LLM inference")
|
||||
runCmd.Flags().MarkHidden("imagegen")
|
||||
|
||||
stopCmd := &cobra.Command{
|
||||
Use: "stop MODEL",
|
||||
@@ -2520,6 +2564,7 @@ func NewCLI() *cobra.Command {
|
||||
} {
|
||||
switch cmd {
|
||||
case runCmd:
|
||||
imagegen.AppendFlagsDocs(cmd)
|
||||
appendEnvDocs(cmd, []envconfig.EnvVar{envVars["OLLAMA_EDITOR"], envVars["OLLAMA_HOST"], envVars["OLLAMA_NOHISTORY"]})
|
||||
case serveCmd:
|
||||
appendEnvDocs(cmd, []envconfig.EnvVar{
|
||||
|
||||
@@ -249,7 +249,7 @@ func TestRunLauncherAction_GUIAppsExitTUILoop(t *testing.T) {
|
||||
cmd := &cobra.Command{}
|
||||
cmd.SetContext(context.Background())
|
||||
|
||||
for _, integration := range []string{"chatgpt", "vscode"} {
|
||||
for _, integration := range []string{"codex-app", "vscode"} {
|
||||
continueLoop, err := runLauncherAction(cmd, tui.TUIAction{Kind: tui.TUIActionLaunchIntegration, Integration: integration}, launcherDeps{
|
||||
resolveRunModel: unexpectedRunModelResolution(t),
|
||||
launchIntegration: func(ctx context.Context, req launch.IntegrationLaunchRequest) error {
|
||||
|
||||
@@ -2079,7 +2079,7 @@ func TestRunOptions_Copy_ThinkValueVariants(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestShowInfoImageCapability(t *testing.T) {
|
||||
func TestShowInfoImageGen(t *testing.T) {
|
||||
var b bytes.Buffer
|
||||
err := showInfo(&api.ShowResponse{
|
||||
Details: api.ModelDetails{
|
||||
@@ -2390,44 +2390,3 @@ func TestIsLocalhost(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCommandHasNoAgentFlags(t *testing.T) {
|
||||
root := NewCLI()
|
||||
run, _, err := root.Find([]string{"run"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, name := range []string{"resume", "headless", "auto-approve-tools", "skill", "experimental", "experimental-yolo", "experimental-websearch"} {
|
||||
if flag := run.Flags().Lookup(name); flag != nil {
|
||||
t.Errorf("run command still exposes former agent flag --%s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormerAgentEntryPointsAreRejected(t *testing.T) {
|
||||
tests := [][]string{
|
||||
{"run", "llama3", "--resume"},
|
||||
{"run", "llama3", "--headless"},
|
||||
{"run", "llama3", "--auto-approve-tools"},
|
||||
{"run", "llama3", "--skill", "release-notes"},
|
||||
{"run", "llama3", "--experimental"},
|
||||
{"run", "llama3", "--experimental-yolo"},
|
||||
{"run", "llama3", "--experimental-websearch"},
|
||||
{"agent"},
|
||||
}
|
||||
|
||||
for _, args := range tests {
|
||||
t.Run(strings.Join(args, " "), func(t *testing.T) {
|
||||
root := NewCLI()
|
||||
root.SetArgs(args)
|
||||
err := root.Execute()
|
||||
if err == nil {
|
||||
t.Fatalf("former agent entry point %q succeeded", args)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "unknown") {
|
||||
t.Fatalf("former agent entry point %q returned %v, want unknown command or flag", args, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -653,12 +653,9 @@ func editInExternalEditor(content string) (string, error) {
|
||||
}
|
||||
|
||||
// Check that the editor binary exists
|
||||
args := strings.Fields(editor)
|
||||
if len(args) == 0 {
|
||||
return "", fmt.Errorf("no editor configured, set OLLAMA_EDITOR to the path of your preferred editor")
|
||||
}
|
||||
if _, err := exec.LookPath(args[0]); err != nil {
|
||||
return "", fmt.Errorf("editor %q not found, set OLLAMA_EDITOR to the path of your preferred editor", args[0])
|
||||
name := strings.Fields(editor)[0]
|
||||
if _, err := exec.LookPath(name); err != nil {
|
||||
return "", fmt.Errorf("editor %q not found, set OLLAMA_EDITOR to the path of your preferred editor", name)
|
||||
}
|
||||
|
||||
tmpFile, err := os.CreateTemp("", "ollama-prompt-*.txt")
|
||||
@@ -675,6 +672,7 @@ func editInExternalEditor(content string) (string, error) {
|
||||
}
|
||||
tmpFile.Close()
|
||||
|
||||
args := strings.Fields(editor)
|
||||
args = append(args, tmpFile.Name())
|
||||
cmd := exec.Command(args[0], args[1:]...)
|
||||
cmd.Stdin = os.Stdin
|
||||
|
||||
@@ -85,39 +85,6 @@ func TestExtractFileDataRemovesQuotedFilepath(t *testing.T) {
|
||||
assert.Equal(t, cleaned, "before after")
|
||||
}
|
||||
|
||||
func TestEditInExternalEditorWhitespaceOnly(t *testing.T) {
|
||||
// A whitespace-only VISUAL or EDITOR is non-empty, so it bypasses the
|
||||
// editor == "" fallbacks, but strings.Fields collapses it to an empty
|
||||
// slice. Indexing that slice must not panic; it must return an error.
|
||||
cases := []struct {
|
||||
name string
|
||||
visual string
|
||||
editor string
|
||||
}{
|
||||
{name: "VISUAL whitespace", visual: "\t "},
|
||||
{name: "EDITOR whitespace", editor: "\t "},
|
||||
}
|
||||
for _, tt := range cases {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Setenv("OLLAMA_EDITOR", "")
|
||||
t.Setenv("VISUAL", tt.visual)
|
||||
t.Setenv("EDITOR", tt.editor)
|
||||
_, err := editInExternalEditor("content")
|
||||
assert.Error(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditInExternalEditorParsesEditorWithArgs(t *testing.T) {
|
||||
// A well-formed editor command with arguments must still be parsed so
|
||||
// its binary is looked up (guards the normal path from regressing).
|
||||
t.Setenv("OLLAMA_EDITOR", "definitely-not-a-real-editor arg1")
|
||||
t.Setenv("VISUAL", "")
|
||||
t.Setenv("EDITOR", "")
|
||||
_, err := editInExternalEditor("content")
|
||||
assert.ErrorContains(t, err, "definitely-not-a-real-editor")
|
||||
}
|
||||
|
||||
func TestExtractFileDataWAV(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
fp := filepath.Join(dir, "sample.wav")
|
||||
|
||||
@@ -20,7 +20,7 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrPlanVerificationUnavailable = errors.New("Could not verify Ollama plan. Try again in a moment or use a local model.")
|
||||
ErrPlanVerificationUnavailable = errors.New("Could not verify your plan. Try again in a moment.")
|
||||
errUpgradeCancelled = errors.New("upgrade cancelled")
|
||||
)
|
||||
|
||||
@@ -247,7 +247,7 @@ func (c *launcherClient) ensureCloudModelAccess(ctx context.Context, model strin
|
||||
c.accountState = &state
|
||||
}
|
||||
if state.Status == accountStateUnknown {
|
||||
return nil
|
||||
return ErrPlanVerificationUnavailable
|
||||
}
|
||||
|
||||
if state.Status == accountStateSignedOut {
|
||||
@@ -259,7 +259,7 @@ func (c *launcherClient) ensureCloudModelAccess(ctx context.Context, model strin
|
||||
c.accountState = &state
|
||||
}
|
||||
if state.Status == accountStateUnknown {
|
||||
return nil
|
||||
return ErrPlanVerificationUnavailable
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/ollama/ollama/envconfig"
|
||||
)
|
||||
@@ -38,21 +37,17 @@ func (c *Claude) findPath() (string, error) {
|
||||
if runtime.GOOS == "windows" {
|
||||
name = "claude.exe"
|
||||
}
|
||||
for _, fallback := range []string{
|
||||
filepath.Join(home, ".local", "bin", name),
|
||||
filepath.Join(home, ".claude", "local", name),
|
||||
} {
|
||||
if _, err := os.Stat(fallback); err == nil {
|
||||
return fallback, nil
|
||||
}
|
||||
fallback := filepath.Join(home, ".claude", "local", name)
|
||||
if _, err := os.Stat(fallback); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "", fmt.Errorf("claude binary not found")
|
||||
return fallback, nil
|
||||
}
|
||||
|
||||
func (c *Claude) Run(model string, _ []LaunchModel, args []string) error {
|
||||
claudePath, err := ensureClaudeInstalled()
|
||||
claudePath, err := c.findPath()
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("claude is not installed, install from https://code.claude.com/docs/en/quickstart")
|
||||
}
|
||||
|
||||
cmd := exec.Command(claudePath, c.args(model, args)...)
|
||||
@@ -60,105 +55,17 @@ func (c *Claude) Run(model string, _ []LaunchModel, args []string) error {
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
cmd.Env = append(os.Environ(), c.envVars(model)...)
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
func (c *Claude) envVars(model string) []string {
|
||||
env := []string{
|
||||
"ANTHROPIC_BASE_URL=" + envconfig.Host().String(),
|
||||
env := append(os.Environ(),
|
||||
"ANTHROPIC_BASE_URL="+envconfig.Host().String(),
|
||||
"ANTHROPIC_API_KEY=",
|
||||
"ANTHROPIC_AUTH_TOKEN=ollama",
|
||||
"CLAUDE_CODE_ATTRIBUTION_HEADER=0",
|
||||
"CLAUDE_CODE_TOTAL_TOKENS_REMINDER=off",
|
||||
"DISABLE_ERROR_REPORTING=1",
|
||||
"DISABLE_FEEDBACK_COMMAND=1",
|
||||
"CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1",
|
||||
}
|
||||
)
|
||||
|
||||
env = append(env, c.modelEnvVars(model)...)
|
||||
return env
|
||||
}
|
||||
|
||||
func ensureClaudeInstalled() (string, error) {
|
||||
if path, err := (&Claude{}).findPath(); err == nil {
|
||||
return path, nil
|
||||
}
|
||||
|
||||
if err := checkClaudeInstallerDependencies(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
ok, err := ConfirmPrompt("Claude Code is not installed. Install now?")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !ok {
|
||||
return "", fmt.Errorf("claude installation cancelled")
|
||||
}
|
||||
|
||||
bin, args, err := claudeInstallerCommand(runtime.GOOS)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "\nInstalling Claude Code...\n")
|
||||
cmd := exec.Command(bin, args...)
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
return "", fmt.Errorf("failed to install claude: %w", err)
|
||||
}
|
||||
|
||||
path, err := (&Claude{}).findPath()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("claude was installed but the binary was not found on PATH\n\nYou may need to restart your shell")
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "%sClaude Code installed successfully%s\n\n", ansiGreen, ansiReset)
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func checkClaudeInstallerDependencies() error {
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
if _, err := exec.LookPath("powershell"); err != nil {
|
||||
return fmt.Errorf("claude is not installed and required dependencies are missing\n\nInstall the following first:\n PowerShell: https://learn.microsoft.com/powershell/\n\nThen re-run:\n ollama launch claude")
|
||||
}
|
||||
default:
|
||||
var missing []string
|
||||
if _, err := exec.LookPath("curl"); err != nil {
|
||||
missing = append(missing, "curl: https://curl.se/")
|
||||
}
|
||||
if _, err := exec.LookPath("bash"); err != nil {
|
||||
missing = append(missing, "bash: https://www.gnu.org/software/bash/")
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
return fmt.Errorf("claude is not installed and required dependencies are missing\n\nInstall the following first:\n %s\n\nThen re-run:\n ollama launch claude", strings.Join(missing, "\n "))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func claudeInstallerCommand(goos string) (string, []string, error) {
|
||||
switch goos {
|
||||
case "windows":
|
||||
return "powershell", []string{
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-Command",
|
||||
"irm https://claude.ai/install.ps1 | iex",
|
||||
}, nil
|
||||
case "darwin", "linux":
|
||||
return "bash", []string{
|
||||
"-c",
|
||||
"curl -fsSL https://claude.ai/install.sh | bash",
|
||||
}, nil
|
||||
default:
|
||||
return "", nil, fmt.Errorf("unsupported platform for claude install: %s", goos)
|
||||
}
|
||||
cmd.Env = env
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
// modelEnvVars returns Claude Code env vars that route all model tiers through Ollama.
|
||||
|
||||
@@ -5,7 +5,8 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -15,25 +16,22 @@ import (
|
||||
|
||||
"github.com/ollama/ollama/cmd/config"
|
||||
"github.com/ollama/ollama/cmd/internal/fileutil"
|
||||
"github.com/ollama/ollama/internal/proxy"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
const (
|
||||
claudeDesktopIntegrationName = "claude-desktop"
|
||||
claudeDesktopProfileName = "Ollama"
|
||||
claudeDesktopProfileID = "00000000-0000-4000-8000-000000000114"
|
||||
claudeDesktopGatewayBaseURL = "http://" + proxy.DefaultClaudeDesktopListenAddr
|
||||
claudeDesktopProbeTimeout = 2 * time.Second
|
||||
claudeDesktopModelLabel = "Default Ollama model"
|
||||
claudeDesktopSuccessMessage = "Claude Desktop profile changed to Ollama."
|
||||
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."
|
||||
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
|
||||
@@ -41,14 +39,17 @@ var (
|
||||
claudeDesktopOpenApp = defaultClaudeDesktopOpenApp
|
||||
claudeDesktopOpenAppPath = defaultClaudeDesktopOpenAppPath
|
||||
claudeDesktopQuitApp = defaultClaudeDesktopQuitApp
|
||||
claudeDesktopIsRunning = defaultClaudeDesktopRunning
|
||||
claudeDesktopIsRunning = defaultClaudeDesktopIsRunning
|
||||
claudeDesktopRunningAppPath = defaultClaudeDesktopRunningAppPath
|
||||
claudeDesktopGlob = filepath.Glob
|
||||
claudeDesktopProbeGateway = proxy.ProbeClaudeDesktop
|
||||
claudeDesktopSleep = time.Sleep
|
||||
claudeDesktopHTTPClient = http.DefaultClient
|
||||
claudeDesktopPromptAPIKey = promptClaudeDesktopAPIKey
|
||||
claudeDesktopValidateAPIKey = validateClaudeDesktopAPIKey
|
||||
)
|
||||
|
||||
// ClaudeDesktop configures and launches Claude Desktop in third-party
|
||||
// inference mode using the Ollama app's local gateway.
|
||||
// inference mode using Ollama Cloud as the gateway.
|
||||
type ClaudeDesktop struct{}
|
||||
|
||||
func (c *ClaudeDesktop) String() string { return "Claude Desktop" }
|
||||
@@ -63,21 +64,38 @@ func (c *ClaudeDesktop) AutodiscoveredModel() string {
|
||||
return claudeDesktopModelLabel
|
||||
}
|
||||
|
||||
// ConfigureAutodiscovery points Claude Desktop at Ollama's local gateway
|
||||
// without pinning a model list, so Claude discovers the selected catalog and
|
||||
// exact Ollama route names the gateway advertises.
|
||||
func (c *ClaudeDesktop) ConfigureAutodiscovery() error {
|
||||
if err := claudeDesktopSupported(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ensureClaudeDesktopGateway(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
targets, err := claudeDesktopTargetPaths()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return configureClaudeDesktopTargets(targets, claudeDesktopGatewayBaseURL, "ollama")
|
||||
|
||||
key, err := claudeDesktopValidatedAPIKey(context.Background(), claudeDesktopTargetProfilePaths(targets))
|
||||
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
|
||||
}
|
||||
|
||||
func (c *ClaudeDesktop) RestoreHint() string {
|
||||
@@ -100,120 +118,10 @@ 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)
|
||||
}
|
||||
|
||||
// RestartWithProfileChange stops Claude before applying a profile-dependent
|
||||
// change, then reopens it after the change is complete.
|
||||
func (c *ClaudeDesktop) RestartWithProfileChange(change func() error) error {
|
||||
if err := claudeDesktopSupported(); err != nil {
|
||||
return err
|
||||
}
|
||||
running, err := claudeDesktopIsRunning(context.Background())
|
||||
if err != nil {
|
||||
return fmt.Errorf("check whether Claude Desktop is running: %w", err)
|
||||
}
|
||||
if !running {
|
||||
if err := change(); err != nil {
|
||||
return err
|
||||
}
|
||||
return claudeDesktopOpenApp()
|
||||
}
|
||||
return restartClaudeDesktop(change)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
// ClaudeDesktopModels returns the user's explicitly saved Claude Desktop
|
||||
// model subset. A nil result means the recommendation source should decide.
|
||||
func ClaudeDesktopModels() []string {
|
||||
return config.IntegrationModels(claudeDesktopIntegrationName)
|
||||
}
|
||||
|
||||
// SaveClaudeDesktopModels persists the user's explicit Claude Desktop model
|
||||
// subset in the shared launcher configuration.
|
||||
func SaveClaudeDesktopModels(models []string) error {
|
||||
if len(models) == 0 {
|
||||
return errors.New("select at least one Claude Desktop model")
|
||||
}
|
||||
return config.SaveIntegration(claudeDesktopIntegrationName, models)
|
||||
}
|
||||
|
||||
// RestoreClaudeDesktopModels restores a previously captured selection. A nil
|
||||
// selection restores the implicit recommendation defaults.
|
||||
func RestoreClaudeDesktopModels(models []string) error {
|
||||
return config.SaveIntegration(claudeDesktopIntegrationName, models)
|
||||
}
|
||||
|
||||
func (c *ClaudeDesktop) RequiresInteractiveOnboarding() bool {
|
||||
return false
|
||||
}
|
||||
@@ -222,21 +130,12 @@ func (c *ClaudeDesktop) SkipModelReadiness() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
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) Run(_ string, _ []LaunchModel, _ []string) error {
|
||||
return errClaudeDesktopUnsupported()
|
||||
}
|
||||
|
||||
func (c *ClaudeDesktop) Restore() error {
|
||||
if err := claudeDesktopRestoreSupported(); err != nil {
|
||||
if err := claudeDesktopSupported(); err != nil {
|
||||
return err
|
||||
}
|
||||
targets, err := claudeDesktopTargetPaths()
|
||||
@@ -244,35 +143,6 @@ 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
|
||||
@@ -289,42 +159,27 @@ func restoreClaudeDesktopTargets(targets claudeDesktopTargets) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return claudeDesktopLaunchOrRestart("Restart Claude Desktop to use the usual Claude profile?")
|
||||
}
|
||||
|
||||
func errClaudeDesktopUnsupported() error {
|
||||
return errors.New(claudeDesktopUnsupported)
|
||||
}
|
||||
|
||||
func claudeDesktopSupported() error {
|
||||
if claudeDesktopGOOS == "darwin" {
|
||||
switch claudeDesktopGOOS {
|
||||
case "darwin", "windows":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("Claude Desktop launch is only supported on macOS and Windows")
|
||||
}
|
||||
return errors.New("Claude Desktop launch is only supported on macOS")
|
||||
}
|
||||
|
||||
func claudeDesktopRestoreSupported() error {
|
||||
if claudeDesktopGOOS == "darwin" || claudeDesktopGOOS == "windows" {
|
||||
return nil
|
||||
func claudeDesktopInstalled() bool {
|
||||
if claudeDesktopAppPath() != "" {
|
||||
return true
|
||||
}
|
||||
return errors.New("Claude Desktop restore is only supported on macOS and Windows")
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
running, _ := claudeDesktopIsRunning(context.Background())
|
||||
if claudeDesktopAppPath() != "" || running {
|
||||
if claudeDesktopGOOS == "windows" && claudeDesktopIsRunning() {
|
||||
return true
|
||||
}
|
||||
for _, dir := range claudeDesktopProfileDirCandidates(false) {
|
||||
@@ -472,7 +327,7 @@ func claudeDesktopWindowsConfigPaths() (claudeDesktopPaths, error) {
|
||||
func claudeDesktopProfileDir(normal bool) (string, error) {
|
||||
candidates := claudeDesktopProfileDirCandidates(normal)
|
||||
if len(candidates) == 0 {
|
||||
return "", errors.New("Claude Desktop profile directory could not be resolved")
|
||||
return "", fmt.Errorf("Claude Desktop profile directory could not be resolved")
|
||||
}
|
||||
for _, candidate := range candidates {
|
||||
if _, err := claudeDesktopStat(candidate); err == nil {
|
||||
@@ -558,6 +413,14 @@ 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
|
||||
@@ -572,6 +435,139 @@ 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 {
|
||||
@@ -608,26 +604,17 @@ func writeClaudeDesktopMeta(path, id, name string) error {
|
||||
return writeClaudeDesktopJSON(path, meta)
|
||||
}
|
||||
|
||||
func writeClaudeDesktopGatewayProfile(path, baseURL, apiKey string, forceChooser bool) error {
|
||||
func writeClaudeDesktopGatewayProfile(path string, 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"] = baseURL
|
||||
cfg["inferenceGatewayBaseUrl"] = claudeDesktopGatewayBaseURL
|
||||
cfg["inferenceGatewayApiKey"] = apiKey
|
||||
cfg["inferenceGatewayAuthScheme"] = "bearer"
|
||||
cfg["deploymentDisplayName"] = claudeDesktopProfileName
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -678,12 +665,7 @@ func restoreClaudeDesktopOllamaProfile(path string) error {
|
||||
delete(cfg, "inferenceProvider")
|
||||
delete(cfg, "inferenceGatewayBaseUrl")
|
||||
delete(cfg, "inferenceGatewayAuthScheme")
|
||||
delete(cfg, "deploymentDisplayName")
|
||||
delete(cfg, "inferenceModels")
|
||||
delete(cfg, "coworkEgressAllowedHosts")
|
||||
delete(cfg, "autoModeEnabled")
|
||||
delete(cfg, "disableEssentialTelemetry")
|
||||
delete(cfg, "disableNonessentialTelemetry")
|
||||
return writeClaudeDesktopJSON(path, cfg)
|
||||
}
|
||||
|
||||
@@ -706,18 +688,6 @@ 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
|
||||
}
|
||||
@@ -730,7 +700,7 @@ func claudeDesktopTargetsUseOllamaGateway(targets claudeDesktopTargets) bool {
|
||||
if readClaudeDesktopDeploymentMode(target.desktopConfig) != "3p" {
|
||||
return false
|
||||
}
|
||||
if !claudeDesktopThirdPartyProfileUsesOllamaGateway(target) {
|
||||
if !claudeDesktopThirdPartyProfileConfigured(target) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -738,39 +708,6 @@ func claudeDesktopTargetsUseOllamaGateway(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
|
||||
}
|
||||
if s, _ := cfg["deploymentDisplayName"].(string); s != claudeDesktopProfileName {
|
||||
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
|
||||
}
|
||||
@@ -782,23 +719,15 @@ func claudeDesktopThirdPartyProfileUsesOllamaGateway(target claudeDesktopThirdPa
|
||||
if s, _ := cfg["inferenceProvider"].(string); s != "gateway" {
|
||||
return false
|
||||
}
|
||||
if s, _ := cfg["inferenceGatewayBaseUrl"].(string); !claudeDesktopGatewayURLMatches(s) {
|
||||
if s, _ := cfg["inferenceGatewayBaseUrl"].(string); strings.TrimRight(s, "/") != claudeDesktopGatewayBaseURL {
|
||||
return false
|
||||
}
|
||||
if s, _ := cfg["inferenceGatewayApiKey"].(string); strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
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
|
||||
}
|
||||
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) {
|
||||
cfg, err := readClaudeDesktopJSON(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
@@ -845,14 +774,15 @@ func claudeDesktopAnySlice(value any) []any {
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
if !running {
|
||||
func claudeDesktopLaunchOrRestart(prompt string) error {
|
||||
if !claudeDesktopIsRunning() {
|
||||
return claudeDesktopOpenApp()
|
||||
}
|
||||
restartAppPath := ""
|
||||
if claudeDesktopGOOS == "windows" {
|
||||
restartAppPath = claudeDesktopRunningAppPath()
|
||||
}
|
||||
|
||||
restart, err := ConfirmPrompt(prompt)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -861,95 +791,41 @@ func claudeDesktopLaunchOrRestart(prompt string, reapplyProfile func() error) er
|
||||
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)
|
||||
}
|
||||
|
||||
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 {
|
||||
if err := claudeDesktopQuitApp(); err != nil {
|
||||
return fmt.Errorf("quit Claude Desktop: %w", err)
|
||||
}
|
||||
if err := waitForClaudeDesktopExit(ctx); err != nil {
|
||||
if err := waitForClaudeDesktopExit(30 * time.Second); 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(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 {
|
||||
func waitForClaudeDesktopExit(timeout time.Duration) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
if !claudeDesktopIsRunning() {
|
||||
return nil
|
||||
}
|
||||
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):
|
||||
}
|
||||
claudeDesktopSleep(200 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("Claude Desktop did not quit; quit it manually and re-run the command")
|
||||
}
|
||||
|
||||
// ClaudeDesktopRunning reports whether Claude Desktop is open.
|
||||
func ClaudeDesktopRunning() bool {
|
||||
running, _ := claudeDesktopIsRunning(context.Background())
|
||||
return running
|
||||
}
|
||||
|
||||
// OpenClaudeDesktop brings the installed Claude Desktop app to the foreground.
|
||||
func OpenClaudeDesktop() error {
|
||||
if err := claudeDesktopSupported(); err != nil {
|
||||
return err
|
||||
}
|
||||
return claudeDesktopOpenApp()
|
||||
}
|
||||
|
||||
func defaultClaudeDesktopRunning(ctx context.Context) (bool, error) {
|
||||
var (
|
||||
out []byte
|
||||
err error
|
||||
)
|
||||
func defaultClaudeDesktopIsRunning() bool {
|
||||
switch claudeDesktopGOOS {
|
||||
case "darwin":
|
||||
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
|
||||
}
|
||||
out, err := exec.Command("pgrep", "-f", "Claude.app/Contents/MacOS/Claude").Output()
|
||||
return err == nil && strings.TrimSpace(string(out)) != ""
|
||||
case "windows":
|
||||
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()
|
||||
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)) != ""
|
||||
default:
|
||||
return false, nil
|
||||
return false
|
||||
}
|
||||
if ctxErr := ctx.Err(); ctxErr != nil {
|
||||
return false, ctxErr
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return strings.TrimSpace(string(out)) != "", nil
|
||||
}
|
||||
|
||||
func defaultClaudeDesktopOpenApp() error {
|
||||
@@ -961,13 +837,9 @@ func defaultClaudeDesktopOpenApp() error {
|
||||
if path := claudeDesktopRunningAppPath(); path != "" {
|
||||
return claudeDesktopOpenAppPath(path)
|
||||
}
|
||||
return errors.New("Claude Desktop executable was not found; open Claude Desktop manually once and re-run 'ollama launch claude-desktop --restore'")
|
||||
return fmt.Errorf("Claude Desktop executable was not found; open Claude Desktop manually once and re-run 'ollama launch claude-desktop --restore'")
|
||||
case "darwin":
|
||||
path := claudeDesktopAppPath()
|
||||
if path == "" {
|
||||
return errors.New("Claude Desktop app was not found")
|
||||
}
|
||||
return openClaudeDesktopDarwin(path)
|
||||
return openClaudeDesktopDarwin()
|
||||
default:
|
||||
return claudeDesktopSupported()
|
||||
}
|
||||
@@ -978,18 +850,14 @@ func defaultClaudeDesktopOpenAppPath(path string) error {
|
||||
case "windows":
|
||||
return exec.Command("powershell.exe", "-NoProfile", "-Command", "Start-Process -FilePath "+quotePowerShellString(path)).Run()
|
||||
case "darwin":
|
||||
return openClaudeDesktopDarwin(path)
|
||||
return openClaudeDesktopDarwin()
|
||||
default:
|
||||
return claudeDesktopSupported()
|
||||
}
|
||||
}
|
||||
|
||||
func claudeDesktopDarwinOpenArgs(path string) []string {
|
||||
return []string{path}
|
||||
}
|
||||
|
||||
func openClaudeDesktopDarwin(path string) error {
|
||||
cmd := exec.Command("/usr/bin/open", claudeDesktopDarwinOpenArgs(path)...)
|
||||
func openClaudeDesktopDarwin() error {
|
||||
cmd := exec.Command("open", "-a", "Claude")
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
return cmd.Run()
|
||||
@@ -1007,12 +875,12 @@ func defaultClaudeDesktopRunningAppPath() string {
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
|
||||
func defaultClaudeDesktopQuitApp(ctx context.Context) error {
|
||||
func defaultClaudeDesktopQuitApp() error {
|
||||
if claudeDesktopGOOS == "windows" {
|
||||
script := `Get-Process claude -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 } | ForEach-Object { [void]$_.CloseMainWindow() }`
|
||||
return exec.CommandContext(ctx, "powershell.exe", "-NoProfile", "-Command", script).Run()
|
||||
return exec.Command("powershell.exe", "-NoProfile", "-Command", script).Run()
|
||||
}
|
||||
return exec.CommandContext(ctx, "osascript", "-e", `tell application "Claude" to quit`).Run()
|
||||
return exec.Command("osascript", "-e", `tell application "Claude" to quit`).Run()
|
||||
}
|
||||
|
||||
func quotePowerShellString(s string) string {
|
||||
|
||||