From 22de7dcc9cc87d6c4aaf046f59b347e6db6967bb Mon Sep 17 00:00:00 2001 From: yuez Date: Wed, 28 Oct 2026 08:14:05 +0800 Subject: [PATCH] feat(daemon): resolve /api/v1/models without spawning an instance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `GET /api/v1/models?workspaceId=` could only answer for a named workspace, and naming one is enough to spawn its Neovim — fine for the chat picker, wrong for the status page, which has no session to offer and would sit in E_INSTANCE_STARTING forever. The parameter is now optional. With one, the read is relayed exactly as before. Without one, src/daemon/models.ts scans only instances that are already `ready`, prefers the one with live sessions and the longest uptime, and relays `workspace.query{kind:"models"}` to it, falling through to the next candidate on failure. No instance is ever created. The plugin's answer is lazy: the first call returns `{providers:[], pending:true}` while its cache fills. The response therefore carries `pending`, the `workspaceId` that answered (or null) and a `pendingReason` of `fetching`, `no-instance` or `no-live-session`, so a client can poll with a bound and explain itself instead of showing an empty list. The workspaceId-scoped answer now also echoes `workspaceId` back. --- src/core/interfaces.ts | 2 + src/daemon/http.ts | 38 ++++- src/daemon/models.ts | 167 ++++++++++++++++++++ test/daemon/fakes.ts | 4 + test/daemon/http.test.ts | 20 +++ test/daemon/models.test.ts | 308 +++++++++++++++++++++++++++++++++++++ 6 files changed, 535 insertions(+), 4 deletions(-) create mode 100644 src/daemon/models.ts create mode 100644 test/daemon/models.test.ts diff --git a/src/core/interfaces.ts b/src/core/interfaces.ts index b2612ca..31f9e0c 100644 --- a/src/core/interfaces.ts +++ b/src/core/interfaces.ts @@ -31,6 +31,8 @@ export interface PluginConnection { ): Promise<{ seq?: number; disposition?: string } & Record>; subscribe(sessionId: string): void; unsubscribe(sessionId: string): void; + /** Session IDs currently known by the plugin. */ + sessionIds(): string[]; /** Last snapshot received for a session (render cache, may be undefined). */ snapshot(sessionId: string): SessionState | undefined; /** Last seq received for a session. */ diff --git a/src/daemon/http.ts b/src/daemon/http.ts index bb866a3..0789d7e 100644 --- a/src/daemon/http.ts +++ b/src/daemon/http.ts @@ -1,5 +1,6 @@ /** Hono application factory for the daemon HTTP surface. */ import { existsSync, readFileSync } from "node:fs"; +import { randomUUID } from "node:crypto"; import { hostname as osHostname, platform as osPlatform, release as osRelease } from "node:os"; import { fileURLToPath } from "node:url"; import { Hono, type Context } from "hono"; @@ -18,6 +19,7 @@ import { PairRateLimiter } from "./rate-limit.js"; import { CommandRouter } from "./router.js"; import { createSseHandler } from "./sse.js"; import { serveStatic } from "./static.js"; +import { resolveModels, type ModelsCandidate } from "./models.js"; type Env = { Bindings: HttpBindings }; @@ -318,10 +320,38 @@ export function createApp(deps: AppDeps): Hono { app.get("/api/v1/models", async (c) => { const workspaceId = c.req.query("workspaceId"); - if (!workspaceId) throw DaemonError.badRequest("workspaceId is required"); - if (!workspaces.get(workspaceId)) throw DaemonError.notFound(`unknown workspace ${workspaceId}`); - const ack = await router.relayWorkspaceQuery(workspaceId, "models"); - return json(200, ack); + if (workspaceId) { + if (!workspaces.get(workspaceId)) throw DaemonError.notFound(`unknown workspace ${workspaceId}`); + const ack = await router.relayWorkspaceQuery(workspaceId, "models"); + return json(200, { ...ack, workspaceId }); + } + const candidates: ModelsCandidate[] = instances.instanceStates().map((state) => ({ + workspaceId: state.workspaceId, + status: state.status, + startedAt: state.startedAt ?? 0, + sessions: instances.get(state.workspaceId)?.sessionIds().length ?? 0, + })); + const resolution = await resolveModels({ + candidates, + query: async (ws) => { + const connection = instances.get(ws); + if (connection === undefined) { + throw new DaemonError(ERROR_CODES.INSTANCE_UNAVAILABLE, `no instance for workspace ${ws}`); + } + return (await connection.command( + { id: `req-${randomUUID()}`, method: "workspace.query", params: { kind: "models" } }, + 2500, + )) as unknown as Record; + }, + log: (event, detail) => deps.logger?.debug(event, detail), + }); + const { providers, pending, workspaceId: resolvedWorkspaceId, pendingReason } = resolution; + return c.json({ + providers, + pending, + workspaceId: resolvedWorkspaceId, + ...(pendingReason === undefined ? {} : { pendingReason }), + }); }); app.get("/api/v1/devices", (c) => c.json(auth.listDevices())); diff --git a/src/daemon/models.ts b/src/daemon/models.ts new file mode 100644 index 0000000..86ab4e3 --- /dev/null +++ b/src/daemon/models.ts @@ -0,0 +1,167 @@ +/** + * Pure routing module for resolving the model catalogue without spawning Neovim. + * + * `resolveModels` picks the best ready workspace instance, queries it, and + * falls through to the next candidate on failure or a pending answer. + * No Node I/O, no unref'd timers, no imports from http.ts. + */ + +export interface ModelsCandidate { + workspaceId: string; + status: string; + sessions: number; + startedAt: number; +} + +export type ModelsPendingReason = "fetching" | "no-instance" | "no-live-session"; + +export interface ModelsResolution { + providers: unknown[]; + pending: boolean; + workspaceId: string | null; + pendingReason?: ModelsPendingReason; + attempted: string[]; +} + +export interface ResolveModelsInput { + candidates: ModelsCandidate[]; + preferredWorkspaceId?: string | null; + query: (workspaceId: string) => Promise>; + /** default 2500 */ + timeoutMs?: number; + log?: (event: string, detail: Record) => void; +} + +/** + * Race `query(workspaceId)` against a timeout. + * Always resolves — rejects are caught and re-thrown as Error. + * Every timer is cleared in a finally block. + */ +function queryWithTimeout( + query: (ws: string) => Promise>, + workspaceId: string, + timeoutMs: number, +): Promise> { + return new Promise>((resolve, reject) => { + let timer: ReturnType | undefined; + + const cleanup = () => { + if (timer !== undefined) { + clearTimeout(timer); + timer = undefined; + } + }; + + timer = setTimeout(() => { + timer = undefined; + reject(new Error(`models query timed out after ${timeoutMs}ms`)); + }, timeoutMs); + + Promise.resolve() + .then(() => query(workspaceId)) + .then( + (result) => { + cleanup(); + resolve(result); + }, + (err: unknown) => { + cleanup(); + reject(err instanceof Error ? err : new Error(String(err))); + }, + ); + }); +} + +export async function resolveModels(input: ResolveModelsInput): Promise { + const { candidates, preferredWorkspaceId, query, timeoutMs = 2500, log } = input; + + // --- 1. Only ready candidates are eligible (no-spawn guarantee) --- + const ready = candidates.filter((c) => c.status === "ready"); + + if (ready.length === 0) { + return { + providers: [], + pending: true, + workspaceId: preferredWorkspaceId ?? null, + pendingReason: "no-instance", + attempted: [], + }; + } + + // --- 2. Order: preferred first (if ready), then sessions desc, startedAt desc --- + const preferred = preferredWorkspaceId != null + ? ready.find((c) => c.workspaceId === preferredWorkspaceId) + : undefined; + + const rest = ready + .filter((c) => c.workspaceId !== preferred?.workspaceId) + .sort((a, b) => b.sessions - a.sessions || b.startedAt - a.startedAt); + + const ordered: ModelsCandidate[] = preferred ? [preferred, ...rest] : rest; + + // Deduplicate (rule 7: never query the same workspace twice) + const seen = new Set(); + const queue: ModelsCandidate[] = []; + for (const c of ordered) { + if (!seen.has(c.workspaceId)) { + seen.add(c.workspaceId); + queue.push(c); + } + } + + // --- 3. Query in order --- + const attempted: string[] = []; + + for (const candidate of queue) { + const { workspaceId } = candidate; + let ack: Record; + try { + ack = await queryWithTimeout(query, workspaceId, timeoutMs); + } catch (err) { + attempted.push(workspaceId); + log?.("models.candidate_failed", { + workspaceId, + error: err instanceof Error ? err.message : String(err), + }); + continue; + } + + // --- 4. Success condition --- + if (Array.isArray(ack["providers"]) && (ack["providers"] as unknown[]).length > 0 && ack["pending"] !== true) { + return { + providers: ack["providers"] as unknown[], + pending: false, + workspaceId, + attempted, + }; + } + + // Not a success — counts as attempted + attempted.push(workspaceId); + log?.("models.candidate_failed", { + workspaceId, + reason: "pending-or-empty", + pending: ack["pending"], + providerCount: Array.isArray(ack["providers"]) ? (ack["providers"] as unknown[]).length : 0, + }); + } + + // --- 5. Nothing succeeded --- + // pendingReason: fetching when any candidate had sessions > 0, else no-live-session + const hasSessions = queue.some((c) => c.sessions > 0); + + // Best workspaceId to surface: first attempted, else preferred, else best ready candidate + const bestWorkspaceId = + attempted[0] ?? + preferredWorkspaceId ?? + queue[0]?.workspaceId ?? + null; + + return { + providers: [], + pending: true, + workspaceId: bestWorkspaceId, + pendingReason: hasSessions ? "fetching" : "no-live-session", + attempted, + }; +} diff --git a/test/daemon/fakes.ts b/test/daemon/fakes.ts index 8db2b4a..f38ceda 100644 --- a/test/daemon/fakes.ts +++ b/test/daemon/fakes.ts @@ -65,6 +65,10 @@ export class FakeConnection implements PluginConnection { this.subscribed.delete(sessionId); } + sessionIds(): string[] { + return [...this.snapshots.keys()]; + } + snapshot(sessionId: string): SessionState | undefined { return this.snapshots.get(sessionId); } diff --git a/test/daemon/http.test.ts b/test/daemon/http.test.ts index 54149ba..8f3e3fd 100644 --- a/test/daemon/http.test.ts +++ b/test/daemon/http.test.ts @@ -275,6 +275,7 @@ describe("HTTP API", () => { expect(attention.status).toBe(200); const models = await fetch(`${h.url}/api/v1/models?workspaceId=ws-1`, authed()); expect(models.status).toBe(200); + expect(await models.json()).toEqual(expect.objectContaining({ workspaceId: "ws-1" })); expect(conn.commands.some((call) => call.method === "workspace.query" && call.params?.kind === "models")).toBe( true, ); @@ -451,6 +452,25 @@ describe("HTTP API", () => { })); }); + it("resolves bare models without spawning when no instance is ready", async () => { + const bare = await createHarness(); + try { + const bareToken = bare.createToken(); + const response = await fetch(`${bare.url}/api/v1/models`, { + headers: { Authorization: `Bearer ${bareToken}` }, + }); + expect(response.status).toBe(200); + const body = (await response.json()) as Record; + expect(body).toEqual({ + providers: [], pending: true, workspaceId: null, pendingReason: "no-instance", + }); + expect(body).not.toHaveProperty("attempted"); + expect(bare.instances.ensureCalls).toEqual([]); + } finally { + await bare.cleanup(); + } + }); + it("redirects a scanned /pair/ link to the zero-input connect page", async () => { const res = await fetch(`${h.url}/pair/abcd2345`, { redirect: "manual" }); expect(res.status).toBe(302); diff --git a/test/daemon/models.test.ts b/test/daemon/models.test.ts new file mode 100644 index 0000000..69ab5dd --- /dev/null +++ b/test/daemon/models.test.ts @@ -0,0 +1,308 @@ +import { describe, expect, it, vi } from "vitest"; +import { resolveModels, type ModelsCandidate } from "../../src/daemon/models.js"; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function makeCandidate( + workspaceId: string, + opts: Partial> = {}, +): ModelsCandidate { + return { + workspaceId, + status: opts.status ?? "ready", + sessions: opts.sessions ?? 1, + startedAt: opts.startedAt ?? 1000, + }; +} + +function okQuery(providers: unknown[] = [{ id: "openai" }]) { + return vi.fn((_ws: string) => + Promise.resolve({ providers, pending: false }), + ); +} + +function pendingQuery() { + return vi.fn((_ws: string) => + Promise.resolve({ providers: [], pending: true }), + ); +} + +function rejectingQuery(msg = "connection refused") { + return vi.fn((_ws: string) => Promise.reject(new Error(msg))); +} + +function hangingQuery() { + return vi.fn((_ws: string) => new Promise>(() => undefined)); +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +describe("resolveModels", () => { + // 1. Preferred-first ordering + it("queries the preferred workspace first", async () => { + const callOrder: string[] = []; + const query = vi.fn((ws: string) => { + callOrder.push(ws); + // Only "ws-b" returns a real answer so we can verify ordering + if (ws === "ws-b") return Promise.resolve({ providers: [{ id: "openai" }], pending: false }); + return Promise.resolve({ providers: [], pending: true }); + }); + + const candidates = [ + makeCandidate("ws-a", { sessions: 5, startedAt: 2000 }), + makeCandidate("ws-b", { sessions: 1, startedAt: 1000 }), + ]; + + const result = await resolveModels({ + candidates, + preferredWorkspaceId: "ws-b", + query, + }); + + expect(callOrder[0]).toBe("ws-b"); + expect(result.pending).toBe(false); + expect(result.workspaceId).toBe("ws-b"); + }); + + // 2. Sessions desc then startedAt desc when no preferred + it("orders by sessions desc, then startedAt desc when no preferred", async () => { + const callOrder: string[] = []; + const query = vi.fn((ws: string) => { + callOrder.push(ws); + return Promise.resolve({ providers: [], pending: true }); + }); + + const candidates = [ + makeCandidate("ws-low-old", { sessions: 1, startedAt: 500 }), + makeCandidate("ws-low-new", { sessions: 1, startedAt: 2000 }), + makeCandidate("ws-high", { sessions: 10, startedAt: 1000 }), + ]; + + await resolveModels({ candidates, query }); + + expect(callOrder).toEqual(["ws-high", "ws-low-new", "ws-low-old"]); + }); + + // 3. Non-ready candidates are never queried + it("never queries non-ready candidates", async () => { + const query = vi.fn((_ws: string) => + Promise.resolve({ providers: [{ id: "x" }], pending: false }), + ); + + const candidates = [ + makeCandidate("ws-starting", { status: "starting" }), + makeCandidate("ws-stopped", { status: "stopped" }), + makeCandidate("ws-ready", { status: "ready" }), + ]; + + const result = await resolveModels({ candidates, query }); + + expect(query).toHaveBeenCalledTimes(1); + expect(query).toHaveBeenCalledWith("ws-ready"); + expect(result.pending).toBe(false); + expect(result.workspaceId).toBe("ws-ready"); + }); + + // 4. Empty candidate list → no-instance + it("returns no-instance when candidate list is empty", async () => { + const query = vi.fn(); + + const result = await resolveModels({ + candidates: [], + preferredWorkspaceId: "ws-x", + query, + }); + + expect(query).not.toHaveBeenCalled(); + expect(result).toEqual({ + providers: [], + pending: true, + workspaceId: "ws-x", + pendingReason: "no-instance", + attempted: [], + }); + }); + + // 5. All ready + pending with sessions → fetching + it("returns fetching when all candidates are pending and have sessions", async () => { + const query = pendingQuery(); + const candidates = [ + makeCandidate("ws-a", { sessions: 2 }), + makeCandidate("ws-b", { sessions: 3 }), + ]; + + const result = await resolveModels({ candidates, query }); + + expect(result.pending).toBe(true); + expect(result.pendingReason).toBe("fetching"); + expect(result.attempted).toHaveLength(2); + }); + + // 6. All ready + pending with zero sessions → no-live-session + it("returns no-live-session when all candidates have zero sessions", async () => { + const query = pendingQuery(); + const candidates = [ + makeCandidate("ws-a", { sessions: 0 }), + makeCandidate("ws-b", { sessions: 0 }), + ]; + + const result = await resolveModels({ candidates, query }); + + expect(result.pending).toBe(true); + expect(result.pendingReason).toBe("no-live-session"); + expect(result.attempted).toHaveLength(2); + }); + + // 7. Rejecting candidate falls through and is listed in attempted + it("falls through a rejecting candidate and records it in attempted", async () => { + const query = vi.fn((ws: string) => { + if (ws === "ws-bad") return Promise.reject(new Error("kaboom")); + return Promise.resolve({ providers: [{ id: "anthropic" }], pending: false }); + }); + + const candidates = [ + makeCandidate("ws-bad", { sessions: 5, startedAt: 2000 }), + makeCandidate("ws-good", { sessions: 1, startedAt: 1000 }), + ]; + + const result = await resolveModels({ candidates, query }); + + expect(result.pending).toBe(false); + expect(result.workspaceId).toBe("ws-good"); + expect(result.attempted).toContain("ws-bad"); + expect(result.attempted).not.toContain("ws-good"); + }); + + // 8. Hanging candidate times out and falls through + it("times out a hanging candidate and falls through to the next", async () => { + const query = vi.fn((ws: string) => { + if (ws === "ws-hang") return hangingQuery()(ws); + return Promise.resolve({ providers: [{ id: "gemini" }], pending: false }); + }); + + const candidates = [ + makeCandidate("ws-hang", { sessions: 2, startedAt: 2000 }), + makeCandidate("ws-ok", { sessions: 1, startedAt: 1000 }), + ]; + + const result = await resolveModels({ + candidates, + query, + timeoutMs: 30, // very small — should fire quickly + }); + + expect(result.pending).toBe(false); + expect(result.workspaceId).toBe("ws-ok"); + expect(result.attempted).toContain("ws-hang"); + }, 3000); + + it("falls through when a candidate query throws synchronously", async () => { + const query = vi.fn((ws: string) => { + if (ws === "ws-bad") throw new Error("synchronous failure"); + return Promise.resolve({ providers: [{ id: "fallback" }], pending: false }); + }); + + const result = await resolveModels({ + candidates: [makeCandidate("ws-bad", { sessions: 2 }), makeCandidate("ws-good", { sessions: 1 })], + query, + }); + + expect(result.workspaceId).toBe("ws-good"); + expect(result.attempted).toEqual(["ws-bad"]); + }); + + // 9. First non-pending non-empty answer wins; later candidates are not queried + it("stops at the first successful answer and does not query later candidates", async () => { + const query = vi.fn((ws: string) => { + if (ws === "ws-a") return Promise.resolve({ providers: [{ id: "openai" }], pending: false }); + return Promise.resolve({ providers: [{ id: "should-not-appear" }], pending: false }); + }); + + const candidates = [ + makeCandidate("ws-a", { sessions: 2 }), + makeCandidate("ws-b", { sessions: 1 }), + ]; + + const result = await resolveModels({ candidates, query }); + + expect(query).toHaveBeenCalledTimes(1); + expect(query).toHaveBeenCalledWith("ws-a"); + expect(result.providers).toEqual([{ id: "openai" }]); + expect(result.workspaceId).toBe("ws-a"); + }); + + // 10. Provider order inside the winning ack is preserved + it("preserves provider order from the winning ack", async () => { + const providers = [{ id: "z" }, { id: "a" }, { id: "m" }]; + const query = okQuery(providers); + + const result = await resolveModels({ + candidates: [makeCandidate("ws-1")], + query, + }); + + expect(result.providers).toEqual(providers); + }); + + // Extra: preferred workspace that is not ready is ignored (falls to ready pool) + it("ignores a preferred workspace that is not ready", async () => { + const query = okQuery(); + + const candidates = [ + makeCandidate("ws-preferred", { status: "starting" }), + makeCandidate("ws-ready", { status: "ready" }), + ]; + + const result = await resolveModels({ + candidates, + preferredWorkspaceId: "ws-preferred", + query, + }); + + expect(query).not.toHaveBeenCalledWith("ws-preferred"); + expect(query).toHaveBeenCalledWith("ws-ready"); + expect(result.pending).toBe(false); + }); + + // Extra: log callback is called on failure + it("calls the log callback when a candidate fails", async () => { + const logs: { event: string; detail: Record }[] = []; + const log = vi.fn((event: string, detail: Record) => { + logs.push({ event, detail }); + }); + + const query = rejectingQuery("boom"); + const candidates = [makeCandidate("ws-fail")]; + + await resolveModels({ candidates, query, log }); + + expect(log).toHaveBeenCalledOnce(); + expect(logs[0]!.event).toBe("models.candidate_failed"); + expect(logs[0]!.detail["workspaceId"]).toBe("ws-fail"); + }); + + // Extra: no-instance returns null workspaceId when no preferred given + it("returns null workspaceId when no candidates and no preferred", async () => { + const result = await resolveModels({ candidates: [], query: vi.fn() }); + expect(result.workspaceId).toBeNull(); + expect(result.pendingReason).toBe("no-instance"); + }); + + // Extra: attempted list in fallback resolution uses first attempted ws + it("uses the first attempted workspace as workspaceId in the fallback", async () => { + const query = pendingQuery(); + const candidates = [ + makeCandidate("ws-first", { sessions: 3, startedAt: 2000 }), + makeCandidate("ws-second", { sessions: 1, startedAt: 1000 }), + ]; + + const result = await resolveModels({ candidates, query }); + + expect(result.workspaceId).toBe("ws-first"); + expect(result.attempted).toEqual(["ws-first", "ws-second"]); + }); +});