feat(daemon): resolve /api/v1/models without spawning an instance
`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.
This commit is contained in:
1 parent
88354ec078
commit
22de7dcc9c
6 files changed
+535
-4
No files matched your search
+34
-4
@@ -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<Env> {
|
||||
|
||||
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<string, unknown>;
|
||||
},
|
||||
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()));
|
||||
|
||||
@@ -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<Record<string, unknown>>;
|
||||
/** default 2500 */
|
||||
timeoutMs?: number;
|
||||
log?: (event: string, detail: Record<string, unknown>) => 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<Record<string, unknown>>,
|
||||
workspaceId: string,
|
||||
timeoutMs: number,
|
||||
): Promise<Record<string, unknown>> {
|
||||
return new Promise<Record<string, unknown>>((resolve, reject) => {
|
||||
let timer: ReturnType<typeof setTimeout> | 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<ModelsResolution> {
|
||||
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<string>();
|
||||
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<string, unknown>;
|
||||
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,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user