From 7d9d59732b64a8c5ff119c1bbbaa8b8f3b7732bb Mon Sep 17 00:00:00 2001 From: yuhuanowo Date: Mon, 16 Nov 2026 21:29:37 +0800 Subject: [PATCH 1/5] Never make room on this machine for a model it does not start A model served by another machine can be reached today by a hand-written llama-swap entry: a placeholder cmd, an explicit proxy, a checkEndpoint. The console read such an entry as a local one: makeRoom sized "the whole card" for it and freed -- or waited on -- every ComfyUI on the machine before any request naming it, and readModels polled /props on the foreign server twice a poll as if it were llama-server. Neither helps the model, and both cost the machine. Recognise the form (a proxy that is explicit, not loopback, and carries no ${PORT} or macro) as llamaswap.Store.RemoteProxy, keep makeRoom out of such entries, and stop polling them as llama-server. docs/remote-models.md records the entry, measured against llama-swap v273 with the OpenAI-API stub it forwards to, and the MLX section of adding-a-gpu-vendor.md points at it: until that port exists, this is how a server on another platform joins the machine. --- docs/adding-a-gpu-vendor.md | 4 ++ docs/remote-models.md | 72 +++++++++++++++++++++++++++++ internal/httpapi/comfy.go | 7 +++ internal/httpapi/comfy_room_test.go | 22 +++++++++ internal/httpapi/models.go | 5 +- internal/llamaswap/remote_test.go | 46 ++++++++++++++++++ internal/llamaswap/store.go | 39 ++++++++++++++++ 7 files changed, 193 insertions(+), 2 deletions(-) create mode 100644 docs/remote-models.md create mode 100644 internal/llamaswap/remote_test.go diff --git a/docs/adding-a-gpu-vendor.md b/docs/adding-a-gpu-vendor.md index a51ca54..d3fdab2 100644 --- a/docs/adding-a-gpu-vendor.md +++ b/docs/adding-a-gpu-vendor.md @@ -243,6 +243,10 @@ VRAM policy that has to be rethought rather than parameterised. That is a port, and it should be opened as one — with the unified-memory question answered first, because everything else follows from it. +Until that port exists, an inference server on such a machine can already be +used from a console on a supported one: a hand-written proxy entry, described +in [remote-models.md](remote-models.md). + ## Where to look in the code | Question | File | diff --git a/docs/remote-models.md b/docs/remote-models.md new file mode 100644 index 0000000..f53cbf6 --- /dev/null +++ b/docs/remote-models.md @@ -0,0 +1,72 @@ +# Models on another machine + +The console starts and supervises the engines it knows (llama.cpp, vLLM, +SGLang) on the cards of this machine. A model served by a machine it does +not run — a Mac running [Yunshu](https://github.com/YuhuanStudio/Yunshu), +a second box, a friend's server — can still be used through the console's +`/v1` by writing one entry into llama-swap's `config.yaml` by hand. The +console preserves hand-written entries when it writes the file +(`internal/llamaswap` reads and writes it without losing what a person +wrote), and as of the change this document ships with it never frees or waits on ComfyUI +to "make room" for such an entry, and never polls it as llama-server. + +## The entry + +llama-swap requires a `cmd` on every entry, so the entry hangs its +lifecycle on a placeholder and points its `proxy` at the other machine: + +```yaml +models: + mac-qwen: + name: Qwen3.8 on the Mac + cmd: sleep 3600 + proxy: http://192.168.1.30:8000 + checkEndpoint: /v1/models + ttl: 0 + aliases: + - qwen-mac +``` + +`proxy` is where every `/v1` request for this id goes; `checkEndpoint` is +what llama-swap probes before forwarding (use `none` to skip it); the +placeholder process is what llama-swap starts, health-checks and kills on +unload, which is why `ttl: 0` is the plain reading — there is nothing to +time out. The console recognises an entry as remote when its `proxy` is +explicit, names something other than a loopback address, and contains no +`${PORT}` or macro; that is what keeps it out of the card and VRAM +arithmetic. + +Measured on llama-swap v273 (container image `cpu`, built 2026-11-15): +with that entry, `GET /v1/models` lists the id and +`POST /v1/chat/completions` for it answers from the other machine. +Nothing here has been run against a real Mac yet — the forwarding target +was a local stub speaking the OpenAI API, so treat the Yunshu pairing as +written-from-the-protocol until someone says otherwise, and say so in +your report if you do run it. + +## What works and what does not + +- Works: the console's `/v1/chat/completions` and `/v1/messages`, the + chat panel, API keys, the model id appearing in `/v1/models`. +- Not managed: the Engines and Models pages never install, size, + benchmark, quantise or GPU-place it; the Models page may group it + under llama.cpp and its load/unload buttons act on the placeholder, + not on the real server. +- No credential: a model entry cannot send an `Authorization` header. + Serve the remote endpoint on a network you trust (LAN, Tailscale), or + bring your own tunnel. llama-swap's `peers` can reach a machine behind + NAT over a tailcat:// key; that is llama-swap's own feature, not the + console's. +- One llama-swap quirk to know: because the placeholder "loads" instantly + and never dies on its own, the Models page shows the entry as loaded + once anything has referenced it until llama-swap is told to unload it. + +## Why this is not "an engine" + +`internal/providers/engines/README.md` explains the engine record: an +image, a launcher, cards. A server on another machine has none of those +to manage. The console does not yet have a form for adding these from +the Models page; that is a separate design — until it exists, this file +is the supported way, and it is what anyone porting to a platform the +console's container story does not cover (see the MLX section of +`docs/adding-a-gpu-vendor.md`) should be pointed at first. diff --git a/internal/httpapi/comfy.go b/internal/httpapi/comfy.go index 7d057b9..aa9645b 100644 --- a/internal/httpapi/comfy.go +++ b/internal/httpapi/comfy.go @@ -833,6 +833,13 @@ func (s *Server) makeRoom(ctx gocontext.Context, modelID string) (int, string) { // An aliased name is a different string for a model that may already be // loaded; resolved so every Codex request does not look like a cold load. modelID = s.Config.CanonicalModel(modelID) + // An entry that names a server on another machine (docs/remote-models.md) + // is nobody's load on this one: without this a request to it would free + // -- or wait on -- every ComfyUI on the machine for a model that needs + // no card at all. + if s.Config.RemoteProxy(modelID) != "" { + return 0, "" + } for _, entry := range s.LlamaSwap.Running(ctx) { if m, _ := entry["model"].(string); m == modelID { return 0, "" diff --git a/internal/httpapi/comfy_room_test.go b/internal/httpapi/comfy_room_test.go index 44136f4..14d4108 100644 --- a/internal/httpapi/comfy_room_test.go +++ b/internal/httpapi/comfy_room_test.go @@ -13,6 +13,28 @@ import ( "github.com/NoobBandi/TenkStack/internal/store/storetest" ) +// A model served by another machine (docs/remote-models.md) needs no card +// here, so the guard in makeRoom returns before anything that could free +// or wait on ComfyUI: with no probe wired up at all, asking for room for +// a remote model answering cleanly is the point of this test, since the +// unguarded path reaches the nil probe. +func TestMakeRoomSkipsRemote(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + os.WriteFile(path, []byte(`models: + mac: + cmd: sleep 3600 + proxy: http://192.168.1.30:8000 + aliases: + - mac-alias +`), 0o644) + s := &Server{Config: llamaswap.NewStore(path)} + for _, id := range []string{"mac", "mac-alias"} { + if status, detail := s.makeRoom(context.Background(), id); status != 0 || detail != "" { + t.Errorf("makeRoom(%s): %d %s", id, status, detail) + } + } +} + // busyB70s is the two cards as they were on 2026-10-10 20:13: card 1 with // 9.4 GiB of idle ComfyUI on it. type busyB70s struct{ twoB70s } diff --git a/internal/httpapi/models.go b/internal/httpapi/models.go index 1e62c1b..9268cc3 100644 --- a/internal/httpapi/models.go +++ b/internal/httpapi/models.go @@ -41,8 +41,9 @@ func (s *Server) readModels(w http.ResponseWriter, r *http.Request) { for id, entry := range byID { proxy, _ := entry["proxy"].(string) // /props and /slots are llama-server's; another provider answers - // 404 twice a poll, which is noise in its log for nothing. - if proxy == "" || formOf(providerOf[id]) != providers.FormLlama { + // 404 twice a poll, which is noise in its log for nothing. So does + // a server on another machine, which is not llama-server either. + if proxy == "" || s.Config.RemoteProxy(id) != "" || formOf(providerOf[id]) != providers.FormLlama { continue } wg.Add(1) diff --git a/internal/llamaswap/remote_test.go b/internal/llamaswap/remote_test.go new file mode 100644 index 0000000..c9218ff --- /dev/null +++ b/internal/llamaswap/remote_test.go @@ -0,0 +1,46 @@ +package llamaswap + +import ( + "os" + "path/filepath" + "testing" +) + +// A hand-written entry that routes to a server on another machine (the +// form docs/remote-models.md prescribes) is remote; every other shape of +// proxy -- absent, ${PORT}, a macro, loopback -- stays with the behaviour +// of an entry this machine starts. +func TestRemoteProxy(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + os.WriteFile(path, []byte(`models: + mac-yunshu: + cmd: sleep 3600 + proxy: http://192.168.1.30:8000 + checkEndpoint: /v1/models + fixed-local: + cmd: ${llama-sycl} --port 8999 + proxy: http://127.0.0.1:8999 + ported: + cmd: ${llama-sycl} + proxy: http://127.0.0.1:${PORT} + macro: + cmd: sleep 3600 + proxy: ${mac-server} + plain: + cmd: ${llama-sycl} + broken-url: + cmd: sleep 3600 + proxy: "http://%zz" +`), 0o644) + s := NewStore(path) + + if got := s.RemoteProxy("mac-yunshu"); got != "http://192.168.1.30:8000" { + t.Errorf("mac-yunshu: got %q", got) + } + for _, id := range []string{"fixed-local", "ported", "macro", "plain", "broken-url", "absent"} { + if got := s.RemoteProxy(id); got != "" { + t.Errorf("%s: got %q, want no match", id, got) + } + } +} diff --git a/internal/llamaswap/store.go b/internal/llamaswap/store.go index 422c88d..87c5e14 100644 --- a/internal/llamaswap/store.go +++ b/internal/llamaswap/store.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "log" + "net/url" "os" "os/exec" "path/filepath" @@ -294,6 +295,44 @@ func EnvMap(n *yaml.Node) map[string]string { return out } +// RemoteProxy is the proxy URL of an entry that names a server on another +// machine rather than one this machine starts: an explicit proxy with no +// ${PORT} in it, pointing somewhere that is not this host. llama-swap +// still wants a cmd such an entry can hang its lifecycle on (see +// docs/remote-models.md for the recipe), but the console starts nothing +// for it: there is no load to size against a card, no llama-server to +// ask /props, and no room to make by evicting ComfyUI. An entry whose +// proxy names loopback is a locally started server on a fixed port, and +// one that uses a macro is somebody's own arrangement; both keep the +// behaviour of any other entry. +func (s *Store) RemoteProxy(modelID string) string { + c, err := s.Load() + if err != nil { + return "" + } + models := c.Root().Map("models") + if models == nil { + return "" + } + entry := models.Map(modelID) + if entry == nil { + return "" + } + raw := strings.TrimSpace(Scalar(entry.Get("proxy"))) + if raw == "" || strings.Contains(raw, "${") { + return "" + } + u, err := url.Parse(raw) + if err != nil { + return "" + } + switch u.Hostname() { + case "", "localhost", "127.0.0.1", "0.0.0.0", "::1": + return "" + } + return raw +} + // CanonicalModel follows aliases to the config key a request's model names, // so an already-loaded model is not mistaken for an absent one. func (s *Store) CanonicalModel(name string) string { From d65c258dc0c68f60f37f8e774f495e75cbac7ff6 Mon Sep 17 00:00:00 2001 From: yuhuanowo Date: Mon, 16 Nov 2026 22:13:48 +0800 Subject: [PATCH 2/5] Read the config's remote entries once per change, not once per request The guard in makeRoom asks RemoteProxy on every /v1 request that names a model, and parsing the YAML there would charge a parse per request for something that changes once a config edit. Cache the remote view between file changes exactly as CanonicalModel caches the aliases: same mtime stamp, same lock, same failure behaviour. --- internal/llamaswap/store.go | 42 ++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/internal/llamaswap/store.go b/internal/llamaswap/store.go index 87c5e14..936c5e2 100644 --- a/internal/llamaswap/store.go +++ b/internal/llamaswap/store.go @@ -49,6 +49,14 @@ type Store struct { aliasMu sync.Mutex aliases map[string]string aliasStamp time.Time + + // The remote entries of the config, cached between changes exactly as + // the aliases are: the guard in makeRoom asks on every /v1 request, and + // parsing the YAML there would be a cost per request for something that + // changes once a config edit. + proxyMu sync.Mutex + proxies map[string]string + proxyStamp time.Time } func NewStore(path string) *Store { return &Store{Path: path} } @@ -306,18 +314,36 @@ func EnvMap(n *yaml.Node) map[string]string { // one that uses a macro is somebody's own arrangement; both keep the // behaviour of any other entry. func (s *Store) RemoteProxy(modelID string) string { - c, err := s.Load() + st, err := os.Stat(s.Path) if err != nil { return "" } - models := c.Root().Map("models") - if models == nil { - return "" - } - entry := models.Map(modelID) - if entry == nil { - return "" + s.proxyMu.Lock() + defer s.proxyMu.Unlock() + if !st.ModTime().Equal(s.proxyStamp) { + c, err := s.Load() + if err != nil { + log.Printf("could not read the config while looking for remote entries: %v", err) + return "" + } + out := map[string]string{} + if models := c.Root().Map("models"); models != nil { + for _, id := range models.Keys() { + if spec := models.Map(id); spec != nil { + if p := remoteProxyURL(spec); p != "" { + out[id] = p + } + } + } + } + s.proxies, s.proxyStamp = out, st.ModTime() } + return s.proxies[modelID] +} + +// remoteProxyURL is an entry's proxy when it names a server the console +// does not start (the rule is documented on RemoteProxy), "" otherwise. +func remoteProxyURL(entry *Mapping) string { raw := strings.TrimSpace(Scalar(entry.Get("proxy"))) if raw == "" || strings.Contains(raw, "${") { return "" From 030477aa16ade49b3e2ba821d16f49b08ab56fbf Mon Sep 17 00:00:00 2001 From: yuhuanowo Date: Mon, 16 Nov 2026 22:19:50 +0800 Subject: [PATCH 3/5] remote-models.md: the pairing run on a real Mac The recipe was written from the protocol and measured against a stub; now it has been run end to end -- a Linux console, llama-swap v273, and Yunshu on an Apple Silicon Mac serving Qwen3-4B-MLX-4bit -- through chat (streaming and not), the legacy completions, Anthropic messages and count_tokens, a tool call, unload and reload, and the admin and member accounts. useModelName joins the example: servers that check the model field refuse the entry's id otherwise. --- docs/remote-models.md | 41 +++++++++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/docs/remote-models.md b/docs/remote-models.md index f53cbf6..789269d 100644 --- a/docs/remote-models.md +++ b/docs/remote-models.md @@ -18,31 +18,40 @@ lifecycle on a placeholder and points its `proxy` at the other machine: ```yaml models: mac-qwen: - name: Qwen3.8 on the Mac + name: Qwen3.4B on the Mac cmd: sleep 3600 proxy: http://192.168.1.30:8000 + useModelName: Qwen3-4B-MLX-4bit checkEndpoint: /v1/models ttl: 0 aliases: - qwen-mac ``` -`proxy` is where every `/v1` request for this id goes; `checkEndpoint` is -what llama-swap probes before forwarding (use `none` to skip it); the -placeholder process is what llama-swap starts, health-checks and kills on -unload, which is why `ttl: 0` is the plain reading — there is nothing to -time out. The console recognises an entry as remote when its `proxy` is -explicit, names something other than a loopback address, and contains no -`${PORT}` or macro; that is what keeps it out of the card and VRAM -arithmetic. +`proxy` is where every `/v1` request for this id goes; `checkEndpoint` +is what llama-swap probes before forwarding (use `none` to skip it); +`useModelName` is what the server is sent in the `model` field, which +servers that validate it (vLLM, SGLang, Yunshu's single-model mode) +otherwise refuse; the placeholder process is what llama-swap starts, +health-checks and kills on unload, which is why `ttl: 0` is the plain +reading — there is nothing to time out. The console recognises an entry +as remote when its `proxy` is explicit, names something other than a +loopback address, and contains no `${PORT}` or macro; that is what keeps +it out of the card and VRAM arithmetic. -Measured on llama-swap v273 (container image `cpu`, built 2026-11-15): -with that entry, `GET /v1/models` lists the id and -`POST /v1/chat/completions` for it answers from the other machine. -Nothing here has been run against a real Mac yet — the forwarding target -was a local stub speaking the OpenAI API, so treat the Yunshu pairing as -written-from-the-protocol until someone says otherwise, and say so in -your report if you do run it. +Measured on llama-swap v273 (container image `cpu`, built 2026-11-15) +against a real Mac running Yunshu 0.1.8.dev4 with +`lmstudio-community/Qwen3-4B-MLX-4bit`, through a console on a Linux +box: `GET /v1/models` listed the id and a request by its alias answered +from the Mac; chat answered streaming and not, as did the legacy +`/v1/completions`, Anthropic `/v1/messages` with `count_tokens`, and a +tool-call round trip; unloading the entry killed the placeholder and the +next request health-checked and answered again. Two console accounts +were tried against it — the member was refused the model editor and its +API key worked on `/v1`, while an administrator's key got 403 on `/api`. +The Models page was refreshed for two minutes and the Mac saw nothing. +On the ComfyUI question this was not a GPU machine and ComfyUI was not +running, so the eviction guard is tested by unit tests only there. ## What works and what does not From c0ddeccff27b4f94f612161d56eb4bad26454e59 Mon Sep 17 00:00:00 2001 From: yuhuanowo Date: Mon, 16 Nov 2026 22:38:34 +0800 Subject: [PATCH 4/5] The model editor adds remote servers too, and the list says what they are MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The recipe in docs/remote-models.md worked only as hand-written YAML and the Models page then filed it under llama.cpp -- a lie about where the weights are. The form now asks where the model lives (本機模型 or 遠端服務器) and its answer retires the fields a server elsewhere makes meaningless: file, card, context, layers, quantisation. Upsert writes the documented shape -- placeholder cmd, explicit proxy, useModelName, health check -- ReadSpec reads the same fields back, and one rule (the RemoteProxy view, already what makeRoom and the /props guard use) decides everywhere: ProviderKeys, the group dropdown and the table's tag all say 遠端模型; the Engines page keeps its three installable records; a moved-back-to-local entry loses the keys the console wrote and nobody's hand-written proxy is ever touched. Loopback with the placeholder (ssh -L, a tailscale serve) is remote; loopback without it is still a local server on a fixed port, as before. --- docs/remote-models.md | 29 +++++++----- internal/api/models.go | 10 +++++ internal/httpapi/models.go | 28 ++++++++++-- internal/llamaswap/models.go | 55 +++++++++++++++++++++++ internal/llamaswap/remote_test.go | 75 +++++++++++++++++++++++++++++++ internal/llamaswap/store.go | 31 ++++++++++++- web/src/api.ts | 11 ++++- web/src/pages/Models.tsx | 62 +++++++++++++++++++++---- 8 files changed, 276 insertions(+), 25 deletions(-) diff --git a/docs/remote-models.md b/docs/remote-models.md index 789269d..9c3f6dc 100644 --- a/docs/remote-models.md +++ b/docs/remote-models.md @@ -57,10 +57,10 @@ running, so the eviction guard is tested by unit tests only there. - Works: the console's `/v1/chat/completions` and `/v1/messages`, the chat panel, API keys, the model id appearing in `/v1/models`. -- Not managed: the Engines and Models pages never install, size, - benchmark, quantise or GPU-place it; the Models page may group it - under llama.cpp and its load/unload buttons act on the placeholder, - not on the real server. +- Not managed: the console never installs, sizes, benchmarks, quantises + or GPU-places it. It is grouped under its own 遠端模型 engine rather + than mistaken for llama.cpp, and the load/unload buttons act on the + placeholder and the forwarding side only, never on the other machine. - No credential: a model entry cannot send an `Authorization` header. Serve the remote endpoint on a network you trust (LAN, Tailscale), or bring your own tunnel. llama-swap's `peers` can reach a machine behind @@ -70,12 +70,21 @@ running, so the eviction guard is tested by unit tests only there. and never dies on its own, the Models page shows the entry as loaded once anything has referenced it until llama-swap is told to unload it. -## Why this is not "an engine" +## Why this is not "an engine", and how it joins the model list anyway `internal/providers/engines/README.md` explains the engine record: an image, a launcher, cards. A server on another machine has none of those -to manage. The console does not yet have a form for adding these from -the Models page; that is a separate design — until it exists, this file -is the supported way, and it is what anyone porting to a platform the -console's container story does not cover (see the MLX section of -`docs/adding-a-gpu-vendor.md`) should be pointed at first. +to manage, which is why it is a kind of model and not a row on the +Engines page -- but it is not filed under llama.cpp either: the Models +page gives it its own group, 遠端模型, so the list says where the +weights are rather than implying they are here. + +The Models page can add and edit these itself: 新增模型 → 模型來源 → +遠端服務器 asks for the server's URL and the name the server is sent, +and writes the placeholder, proxy, `useModelName` and health check as +above; editing such an entry reads the same fields back. The +hand-written form remains the way to reach what the form does not ask +for -- aliases, a custom `checkEndpoint`, timeouts -- and the MLX +section of `docs/adding-a-gpu-vendor.md` points here because until +that port exists, this is how a server on another platform joins the +machine. diff --git a/internal/api/models.go b/internal/api/models.go index a2213a1..0e0c891 100644 --- a/internal/api/models.go +++ b/internal/api/models.go @@ -24,6 +24,12 @@ type ModelSpec struct { // card it pre-allocates. Quantization string `json:"quantization"` GpuMemoryUtilization float64 `json:"gpu_memory_utilization"` + // Endpoint makes the entry a server on another machine (docs/remote- + // models.md): the URL /v1 requests go to. UpstreamName is the model + // name that server is sent, which the ones that check it (vLLM, SGLang, + // Yunshu's single-model mode) otherwise refuse the entry's id against. + Endpoint string `json:"endpoint"` + UpstreamName string `json:"upstream_name"` } // ModelSpecOut is a configured entry parsed back into the editor's fields. @@ -48,6 +54,10 @@ type ModelSpecOut struct { Group *string `json:"group"` Sampling map[string]any `json:"sampling"` Extra string `json:"extra"` + // Endpoint and UpstreamName are set for a remote entry (the Provider is + // then "remote"): the server's URL and the name it is sent. + Endpoint string `json:"endpoint"` + UpstreamName string `json:"upstream_name"` } type ModelFile struct { diff --git a/internal/httpapi/models.go b/internal/httpapi/models.go index 9268cc3..61cc87b 100644 --- a/internal/httpapi/models.go +++ b/internal/httpapi/models.go @@ -4,6 +4,7 @@ import ( "encoding/json" "errors" "net/http" + "net/url" "os" "strconv" "strings" @@ -119,6 +120,14 @@ func (s *Server) readModels(w http.ResponseWriter, r *http.Request) { if p := providers.Get(providerOf[id]); p != nil && p.Tools { caps.Tools = true } + // The servers people host elsewhere -- vLLM, SGLang, llama.cpp, an + // engine like Yunshu -- all carry tools once started with them, and + // the console cannot ask a server it does not start. Assuming true + // keeps the chat panel's switch available; a remote without tools + // answers with the error, which the panel already shows. + if providerOf[id] == llamaswap.RemoteKey { + caps.Tools = true + } if live != nil { caps.Source = "live" caps.Vision, _ = modalities["vision"].(bool) @@ -134,6 +143,9 @@ func (s *Server) readModels(w http.ResponseWriter, r *http.Request) { row["capabilities"] = caps // Which inference engine starts the entry, so the list can be // grouped by it; an entry named by hand is llama.cpp. + // A server on another machine answers for its own engine, not for + // llama.cpp's; grouping it under llama.cpp would be a lie the Models + // page tells about where the weights are. key := providerOf[id] if key == "" { key = providers.DefaultProvider().Key @@ -141,6 +153,8 @@ func (s *Server) readModels(w http.ResponseWriter, r *http.Request) { row["provider"] = key if p := providers.Get(key); p != nil { row["provider_name"] = p.Name + } else if key == llamaswap.RemoteKey { + row["provider_name"] = "遠端模型" } out = append(out, row) } @@ -232,15 +246,21 @@ func (s *Server) createModel(w http.ResponseWriter, r *http.Request) { return } spec := api.ModelSpec{CtxSize: 16384, NGpuLayers: 99, TTL: 900, Group: strp("large")} - if _, has := raw["model_file"]; !has { - fail(w, http.StatusUnprocessableEntity, "model_file is required") - return - } body, _ := json.Marshal(raw) if err := json.Unmarshal(body, &spec); err != nil || spec.ID == "" { fail(w, http.StatusUnprocessableEntity, "id is required") return } + if spec.Endpoint != "" { + u, err := url.Parse(spec.Endpoint) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + fail(w, http.StatusUnprocessableEntity, "endpoint 必須是完整的 http(s) URL") + return + } + } else if spec.ModelFile == "" { + fail(w, http.StatusUnprocessableEntity, "model_file is required") + return + } chosen, present := chosenDevices(spec.Device) env := s.deviceEnv(r, chosen) var managed map[string]bool diff --git a/internal/llamaswap/models.go b/internal/llamaswap/models.go index b4ec87c..c2b56d8 100644 --- a/internal/llamaswap/models.go +++ b/internal/llamaswap/models.go @@ -176,6 +176,39 @@ func (s *Store) Upsert(ctx context.Context, spec api.ModelSpec, env map[string]s } entry.Set("name", Str(name)) entry.Set("description", Str(spec.Description)) + // Was this the remote form before the write? Only then are its keys + // the console's to remove when an entry moves back to a local + // server; a hand-written proxy for a fixed local port stays alone, + // being somebody else's arrangement. + wasRemote := remoteProxyURL(entry) != "" + // Remote: the console writing the form docs/remote-models.md + // describes. Nothing here concerns a card or a container: the + // placeholder is what llama-swap starts, health-checks and kills; + // proxy is where requests go; useModelName is the name a server that + // checks its model field (vLLM, SGLang, Yunshu) expects, the entry's + // id otherwise. + if spec.Endpoint != "" { + entry.Set("cmd", Literal("# served elsewhere; this only anchors llama-swap's lifecycle\n"+RemoteCmd+"\n")) + entry.Set("proxy", Str(spec.Endpoint)) + up := spec.UpstreamName + if up == "" { + up = spec.ID + } + entry.Set("useModelName", Str(up)) + entry.Set("checkEndpoint", Str("/health")) + entry.Set("ttl", Int(0)) + entry.Delete("cmdStop") + entry.Delete("env") + // No group: a server elsewhere occupies no card here, and group + // membership is what the eviction policy reads. + syncGroupMembership(c, spec.ID, nil) + return nil + } + if wasRemote { + entry.Delete("proxy") + entry.Delete("useModelName") + entry.Delete("checkEndpoint") + } if wrapper == "" { wrapper = WrapperIn(Scalar(entry.Get("cmd"))) } @@ -539,6 +572,13 @@ func (m *Models) ProviderKeys() map[string]string { } for _, e := range entries { p, _, _ := ProviderOf(e.cmd) + if remoteProxyURL(e.spec) != "" { + // Read as remote by the same rule RemoteProxy applies, so the + // Models page groups it where makeRoom and readModels already + // treat it. + out[e.id] = RemoteKey + continue + } out[e.id] = p.Key } return out @@ -1053,6 +1093,21 @@ func (m *Models) ReadSpec(modelID string) *api.ModelSpecOut { if e == nil || e.spec == nil { return nil } + if proxy := remoteProxyURL(e.spec); proxy != "" { + out := &api.ModelSpecOut{ + ID: modelID, Provider: RemoteKey, Endpoint: proxy, + UpstreamName: Scalar(e.spec.Get("useModelName")), + Name: Scalar(e.spec.Get("name")), + Description: Scalar(e.spec.Get("description")), + } + if out.Name == "" { + out.Name = modelID + } + if ttl := e.spec.Get("ttl"); ttl != nil && ttl.Kind == yaml.ScalarNode { + out.TTL, _ = strconv.Atoi(ttl.Value) + } + return out + } p, _, _ := ProviderOf(e.cmd) patterns, owns := argPatterns, managed if p.Form == providers.FormServer { diff --git a/internal/llamaswap/remote_test.go b/internal/llamaswap/remote_test.go index c9218ff..dfb3b5a 100644 --- a/internal/llamaswap/remote_test.go +++ b/internal/llamaswap/remote_test.go @@ -1,9 +1,13 @@ package llamaswap import ( + "context" "os" "path/filepath" + "strings" "testing" + + "github.com/NoobBandi/TenkStack/internal/api" ) // A hand-written entry that routes to a server on another machine (the @@ -29,6 +33,12 @@ func TestRemoteProxy(t *testing.T) { proxy: ${mac-server} plain: cmd: ${llama-sycl} + tunnel: + cmd: | + # ssh -L lands on loopback; the placeholder is what says this is a + # server elsewhere reached through it, not one of ours on a fixed port. + sleep 3600 + proxy: http://127.0.0.1:8100 broken-url: cmd: sleep 3600 proxy: "http://%zz" @@ -38,9 +48,74 @@ func TestRemoteProxy(t *testing.T) { if got := s.RemoteProxy("mac-yunshu"); got != "http://192.168.1.30:8000" { t.Errorf("mac-yunshu: got %q", got) } + // Loopback with the console's placeholder is a tunnel to a server + // elsewhere; loopback without it is a local server on a fixed port. + if got := s.RemoteProxy("tunnel"); got != "http://127.0.0.1:8100" { + t.Errorf("tunnel: got %q", got) + } for _, id := range []string{"fixed-local", "ported", "macro", "plain", "broken-url", "absent"} { if got := s.RemoteProxy(id); got != "" { t.Errorf("%s: got %q, want no match", id, got) } } } + +// The console writing the remote form itself: the shape docs/remote-models.md +// describes, read back by every rule that treats it -- and an entry moved +// back to local keeps its hand-written fixed-port proxy while losing the +// keys the console wrote for the remote form. +func TestUpsertRemoteRoundTrip(t *testing.T) { + s, m := tempStore(t) + ctx := context.Background() + spec := api.ModelSpec{ID: "mac-qwen", Name: "Mac Qwen", Description: "on the Mac", + Endpoint: "http://192.168.1.30:8000", UpstreamName: "Qwen3-4B-MLX-4bit", + CtxSize: 16384, TTL: 900, Group: strp("large")} + if err := s.Upsert(ctx, spec, map[string]string{}, map[string]bool{}, ""); err != nil { + t.Fatal(err) + } + out, _ := s.Raw() + for _, want := range []string{ + "proxy: http://192.168.1.30:8000", + "useModelName: Qwen3-4B-MLX-4bit", + "checkEndpoint: /health", + "sleep 3600", + "ttl: 0", + } { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } + // No card, no container: no env for this entry, no group for it to + // evict through. + if strings.Contains(out, "members:\n - mac-qwen") { + t.Errorf("remote entry joined a group:\n%s", out) + } + if got := s.RemoteProxy("mac-qwen"); got != "http://192.168.1.30:8000" { + t.Errorf("RemoteProxy: %q", got) + } + if pk := m.ProviderKeys(); pk["mac-qwen"] != RemoteKey { + t.Errorf("ProviderKeys: %v", pk["mac-qwen"]) + } + read := m.ReadSpec("mac-qwen") + if read == nil || read.Provider != RemoteKey || read.Endpoint != "http://192.168.1.30:8000" || + read.UpstreamName != "Qwen3-4B-MLX-4bit" || read.Name != "Mac Qwen" { + t.Errorf("ReadSpec = %+v", read) + } + // Moved back to a local server: the remote keys go, the cmd comes. + back := api.ModelSpec{ID: "mac-qwen", Name: "Mac Qwen", ModelFile: "local.gguf", + CtxSize: 8192, TTL: 300} + if err := s.Upsert(ctx, back, map[string]string{}, map[string]bool{}, ""); err != nil { + t.Fatal(err) + } + out, _ = s.Raw() + if strings.Contains(out, "proxy: http://192.168.1.30:8000") || strings.Contains(out, "useModelName") { + t.Errorf("remote keys outlived the move back:\n%s", out) + } + if !strings.Contains(out, "--model ${models-dir}/local.gguf") { + t.Errorf("local cmd not written:\n%s", out) + } + // An ordinary local entry of the sample config is not remote. + if got := s.RemoteProxy("small-q4"); got != "" { + t.Errorf("local entry read as remote: %q", got) + } +} diff --git a/internal/llamaswap/store.go b/internal/llamaswap/store.go index 936c5e2..ac02602 100644 --- a/internal/llamaswap/store.go +++ b/internal/llamaswap/store.go @@ -341,6 +341,17 @@ func (s *Store) RemoteProxy(modelID string) string { return s.proxies[modelID] } +// RemoteCmd is the placeholder llama-swap needs to hang a remote model's +// lifecycle on (it insists every entry has a cmd; docs/remote-models.md +// explains the form) and the mark that lets a loopback proxy -- an ssh +// tunnel onto this machine, say -- count as remote too. +const RemoteCmd = "sleep 3600" + +// RemoteKey names the pseudo-provider of a remote entry wherever a provider +// key is read from (the Models page groups by it, the chat panel asks by +// it). It is not a providers.All() record: there is no engine to install. +const RemoteKey = "remote" + // remoteProxyURL is an entry's proxy when it names a server the console // does not start (the rule is documented on RemoteProxy), "" otherwise. func remoteProxyURL(entry *Mapping) string { @@ -353,12 +364,30 @@ func remoteProxyURL(entry *Mapping) string { return "" } switch u.Hostname() { - case "", "localhost", "127.0.0.1", "0.0.0.0", "::1": + case "": return "" + case "localhost", "127.0.0.1", "0.0.0.0", "::1": + // Loopback with no placeholder is somebody's own server on a fixed + // port of this machine; keep treating it as one of the local ones. + if firstCmdLine(Scalar(entry.Get("cmd"))) != RemoteCmd { + return "" + } } return raw } +// firstCmdLine is the first meaningful line of a cmd block: llama-swap's +// own comment stripping, so a comment in the block does not hide what the +// entry runs. +func firstCmdLine(cmd string) string { + for _, line := range strings.Split(cmd, "\n") { + if t := strings.TrimSpace(line); t != "" && !strings.HasPrefix(t, "#") { + return t + } + } + return "" +} + // CanonicalModel follows aliases to the config key a request's model names, // so an already-loaded model is not mistaken for an absent one. func (s *Store) CanonicalModel(name string) string { diff --git a/web/src/api.ts b/web/src/api.ts index 3e6230c..c742ac6 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -574,8 +574,15 @@ export interface ModelSpec { /** The launcher macro the entry starts through: llama-sycl, vllm-intel. * Empty on save keeps the entry's launcher, or takes the default. */ runtime?: string; - /** Which software that launcher is, read back with a spec. */ - provider?: 'llamacpp' | 'vllm' | string; + /** Which software that launcher is, read back with a spec. "remote" is a + * server on another machine (docs/remote-models.md), named by endpoint + * rather than by a launcher. */ + provider?: 'llamacpp' | 'vllm' | 'remote' | string; + /** A remote entry: the URL /v1 requests go to, and the model name that + * server is sent -- vLLM, SGLang and Yunshu all refuse the entry's own + * id if the name is not theirs. */ + endpoint?: string; + upstream_name?: string; /** What the entry's weights are: a GGUF file or a safetensors directory. */ format?: 'gguf' | 'safetensors'; /** vLLM only. Empty quantisation serves the weights as published. */ diff --git a/web/src/pages/Models.tsx b/web/src/pages/Models.tsx index 1056148..3b065cb 100644 --- a/web/src/pages/Models.tsx +++ b/web/src/pages/Models.tsx @@ -1,7 +1,7 @@ import { Fragment, useCallback, useEffect, useMemo, useState } from 'react'; import { Alert, App as AntApp, Button, Card, Checkbox, Descriptions, Drawer, Empty, Form, Input, - InputNumber, Modal, Popconfirm, Popover, Select, Space, Table, Tag, Tooltip, Typography, + InputNumber, Modal, Popconfirm, Popover, Segmented, Select, Space, Table, Tag, Tooltip, Typography, } from 'antd'; import { DeleteOutlined, EditOutlined, ImportOutlined, PlayCircleOutlined, PlusOutlined, @@ -267,7 +267,10 @@ export default function Models() { const [editing, setEditing] = useState(null); const [busy, setBusy] = useState(null); const [importing, setImporting] = useState(false); - const [form] = Form.useForm(); + // `kind` is the form's own question -- local entry or remote server -- + // not a field of the stored spec; the save handler drops the answer into + // the one or the other shape. + const [form] = Form.useForm(); /** * The cards a llama-server here can actually drive. * @@ -291,6 +294,12 @@ export default function Models() { const [runtimes, setRuntimes] = useState([]); const [engineCards, setEngineCards] = useState([]); const runtime = Form.useWatch('runtime', form); + // A remote model is a server on another machine (docs/remote-models.md): + // the entry names where requests go, not what this machine starts, so + // the form's local half -- file, card, context, sampling, quantisation + // -- has nothing to say about it and the fields go with it. + const kind = Form.useWatch('kind', form); + const remote = (kind ?? 'local') === 'remote'; const current = runtimes.find((r) => r.macro === runtime) ?? runtimes[0]; const provider = current?.provider ?? 'llamacpp'; const formEngine = engineCards.find((e) => e.key === provider); @@ -470,11 +479,12 @@ export default function Models() { await saveModel({ ...values, name: values.name || values.id, - device: devices.length > 1 ? values.device ?? [] : undefined, + device: remote ? undefined : (devices.length > 1 ? values.device ?? [] : undefined), // The only launcher is sent too: the entry then says which it uses, - // rather than falling back to whatever the config's default is. - runtime: values.runtime || runtimes[0]?.macro || '', - quantization: folder?.quantized ? '' : values.quantization, + // rather than falling back to whatever the config's default is. A + // remote entry has no launcher at all. + runtime: remote ? '' : (values.runtime || runtimes[0]?.macro || ''), + quantization: remote ? '' : (folder?.quantized ? '' : values.quantization), }); message.success('已寫入設定,llama-swap 會自動重載'); setOpen(false); @@ -528,7 +538,10 @@ export default function Models() { try { const spec = await fetchModelSpec(id); const device = deviceOf(spec.env); - form.setFieldsValue({ ...spec, device }); + form.setFieldsValue({ + ...EMPTY, ...spec, device, + kind: spec.provider === 'remote' ? 'remote' : 'local', + }); setEditing(id); setOpen(true); } catch (error) { @@ -709,7 +722,7 @@ export default function Models() {