agent-console 1.3.5: Windows reconnect, per-provider model refresh, Magpie per-agent filter (#786)
agent-console 1.3.5: Windows reconnect through wails.localhost (Windows, http, no port only), model picker refresh keyed on a per-provider fingerprint of magpie's and the agent's own files, Magpie per-agent model filter, explicit picks forced past the snapshot, gateway URL anchored after the port.
Reviewed at 44661c8 on mote (fresh HOME, npm ci --ignore-scripts, Node 22): npm run check ok; vitest 535 passed, 17 skipped, 1 known flake also on main 749e9dd1 (claude-cli mid-turn CLI crash, manager.ts lastTurnStatus before idle); verify:build byte for byte; hostile wails.localhost and gateway URLs rejected on win32/darwin/linux; each of 17 new guards broken by hand turned its test red. PR CI green.
This commit is contained in:
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+344
-214
@@ -4206,6 +4206,9 @@ var init_types = __esm({
|
||||
import { homedir as homedir7 } from "node:os";
|
||||
import { dirname as dirname3, isAbsolute as isAbsolute2, join as join9 } from "node:path";
|
||||
import { readFile as readFile8 } from "node:fs/promises";
|
||||
function clearCodexModelCache() {
|
||||
modelCache = null;
|
||||
}
|
||||
function runVersion2(r, args, timeoutMs = 5e3) {
|
||||
return new Promise((resolvePromise, reject) => {
|
||||
let out = "";
|
||||
@@ -5067,13 +5070,13 @@ var init_session3 = __esm({
|
||||
* Switch model → refresh level options from the new config options it returns → then apply the level (as Paseo does).
|
||||
* Cursor connects with parameterizedModelPicker: only the base model name is sent (grok-4.6); level / Fast are separate config options.
|
||||
*/
|
||||
async applySessionModel(model) {
|
||||
async applySessionModel(model, force = false) {
|
||||
if (!this.ctx || !this.active) return;
|
||||
const value = model && this.o.flavor === "cursor" ? model.replace(/\[.*\]$/u, "") : model;
|
||||
if (value) {
|
||||
const modelOption = this.currentConfig().find((o) => o.id === (this.modelConfigId ?? "model"));
|
||||
const values = (modelOption?.options ?? []).flatMap((x) => x.options ? x.options : [x]).map((x) => x.value).filter((x) => typeof x === "string");
|
||||
if (!values.length || values.includes(value)) {
|
||||
if (force || !values.length || values.includes(value)) {
|
||||
await this.setOption(this.modelConfigId ?? "model", value);
|
||||
} else {
|
||||
log("info", `\u5FFD\u7565 ${this.o.binName} \u7684\u65E0\u6548\u6A21\u578B\uFF1A${value}`);
|
||||
@@ -5281,13 +5284,13 @@ var init_session3 = __esm({
|
||||
}
|
||||
await notifyP;
|
||||
}
|
||||
async setModel(model) {
|
||||
async setModel(model, opts) {
|
||||
this.o.model = model;
|
||||
await this.ready();
|
||||
if (this.o.imagesFollowStartModel) {
|
||||
this.promptCaps = model === this.startModel ? this.initCaps : { ...this.initCaps, image: false };
|
||||
}
|
||||
await this.applySessionModel(model);
|
||||
await this.applySessionModel(model, Boolean(opts?.force));
|
||||
}
|
||||
async setMode(mode2) {
|
||||
this.o.mode = mode2;
|
||||
@@ -5749,6 +5752,272 @@ var init_specs = __esm({
|
||||
}
|
||||
});
|
||||
|
||||
// daemon/src/providers/magpieGateway.ts
|
||||
import { readFile as readFile11, stat as stat8 } from "node:fs/promises";
|
||||
import { homedir as homedir8 } from "node:os";
|
||||
import { join as join11 } from "node:path";
|
||||
function magpieTokenFor(agentId) {
|
||||
return `${MAGPIE_GATEWAY_TOKEN}-${agentId}`;
|
||||
}
|
||||
async function readJson(path4) {
|
||||
try {
|
||||
return JSON.parse(await readFile11(path4, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
async function readApplied() {
|
||||
return await readJson(join11(homedir8(), ".config", "magpie", "applied.json")) ?? {};
|
||||
}
|
||||
async function readClaudeEnv() {
|
||||
const s = await readJson(join11(homedir8(), ".claude", "settings.json"));
|
||||
return s?.env ?? {};
|
||||
}
|
||||
async function gatewayBase() {
|
||||
const env = await readClaudeEnv();
|
||||
const raw = env.ANTHROPIC_BASE_URL?.trim();
|
||||
return (raw && /^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?(\/|$)/i.test(raw) ? raw : "http://127.0.0.1:3425").replace(/\/+$/, "");
|
||||
}
|
||||
async function fetchGatewayModelIds(agentId) {
|
||||
const base = await gatewayBase();
|
||||
const token = magpieTokenFor(agentId);
|
||||
try {
|
||||
const res = await fetch(`${base}/v1/models`, {
|
||||
signal: AbortSignal.timeout(5e3),
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"x-api-key": token,
|
||||
// Belt-and-suspenders: AgentOf also maps known User-Agents when the token is plain "magpie".
|
||||
"User-Agent": `agent-console/${agentId}`
|
||||
}
|
||||
});
|
||||
if (!res.ok) return [];
|
||||
const j = await res.json();
|
||||
return (j.data ?? []).map((m) => m.id).filter((id2) => typeof id2 === "string" && !!id2);
|
||||
} catch (e) {
|
||||
log("warn", "\u8BFB\u53D6 magpie \u7F51\u5173\u6A21\u578B\u5217\u8868\u5931\u8D25", { agent: agentId, err: String(e) });
|
||||
return [];
|
||||
}
|
||||
}
|
||||
function parseCapabilities(raw) {
|
||||
const out = /* @__PURE__ */ new Map();
|
||||
for (const part of (raw ?? "").split(";")) {
|
||||
const i = part.indexOf("=");
|
||||
if (i <= 0) continue;
|
||||
const flags = new Set(part.slice(i + 1).split(",").map((s) => s.trim()));
|
||||
if (!flags.has("effort")) continue;
|
||||
const levels = ["low", "medium", "high"];
|
||||
if (flags.has("xhigh_effort")) levels.push("xhigh");
|
||||
if (flags.has("max_effort")) levels.push("max");
|
||||
out.set(part.slice(0, i).trim(), levels);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function isPlaceholder(m) {
|
||||
return !m.id || /^(default|auto)$/i.test(m.id);
|
||||
}
|
||||
async function magpieDefaultModel(providerId) {
|
||||
if (providerId === "dsh") return null;
|
||||
const tool = MAGPIE_TOOLS[providerId];
|
||||
if (!tool) return null;
|
||||
const applied = (await readApplied())[tool.key]?.fields?.model?.trim();
|
||||
return applied || null;
|
||||
}
|
||||
async function magpieConfigFingerprint(providerId) {
|
||||
if (!MAGPIE_TOOLS[providerId]) return "";
|
||||
const home = homedir8();
|
||||
const ownFiles = {
|
||||
claude: [join11(home, ".claude", "settings.json")],
|
||||
codex: [join11(home, ".codex", "config.toml"), join11(home, ".codex", "magpie-models.json"), join11(home, ".codex", "models.json")],
|
||||
opencode: [join11(home, ".config", "opencode", "opencode.json")],
|
||||
pi: [join11(home, ".pi", "agent", "settings.json"), join11(home, ".pi", "agent", "models.json")],
|
||||
// DSH uses YAML under DSH_HOME (default ~/.dsh), not ~/.config/dsh/config.json.
|
||||
dsh: ["config.yaml", "settings.yaml", "cordis.patch.yml", "profiles/desktop/cordis.patch.yml", "profiles/web/cordis.patch.yml"].map((file) => join11(process.env.DSH_HOME?.trim() || join11(home, ".dsh"), file))
|
||||
};
|
||||
const paths = [
|
||||
join11(home, ".config", "magpie", "applied.json"),
|
||||
join11(home, ".config", "magpie", "settings.json"),
|
||||
...ownFiles[providerId]
|
||||
];
|
||||
const parts = [];
|
||||
for (const p of paths) {
|
||||
try {
|
||||
const st = await stat8(p);
|
||||
parts.push(`${p}=${st.mtimeMs}`);
|
||||
} catch {
|
||||
parts.push(`${p}=-`);
|
||||
}
|
||||
}
|
||||
return parts.join("|");
|
||||
}
|
||||
function filterToGatewayShown(list, gatewayIds, prefix, opts) {
|
||||
if (!gatewayIds.length) return list;
|
||||
const shown = new Set(gatewayIds);
|
||||
const shownPrefixed = new Set(gatewayIds.map((id2) => prefix + id2));
|
||||
const codexBare = opts?.providerId === "codex";
|
||||
return list.filter((m) => {
|
||||
if (shown.has(m.id) || shownPrefixed.has(m.id)) return true;
|
||||
if (prefix && m.id.startsWith(prefix) && shown.has(m.id.slice(prefix.length))) return true;
|
||||
if (codexBare && !m.id.includes("/") && shown.has(`codex/${m.id}`)) return true;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
async function withMagpie(providerId, own) {
|
||||
const tool = MAGPIE_TOOLS[providerId];
|
||||
if (!tool) return own;
|
||||
const applied = (await readApplied())[tool.key]?.fields;
|
||||
if (!applied?.model) return own;
|
||||
const caps = parseCapabilities((await readClaudeEnv()).CLAUDE_CODE_MODEL_CAPABILITIES);
|
||||
const real = own.filter((m) => !isPlaceholder(m));
|
||||
if (providerId === "dsh") {
|
||||
const appliedId = applied.model.replace(/^magpie\//, "");
|
||||
const selected = real.find(
|
||||
(m) => m.id === applied.model || m.id === appliedId || appliedId.includes("/") && m.id.includes(appliedId)
|
||||
);
|
||||
const fallback = selected ?? real.find((m) => m.isDefault) ?? real[0];
|
||||
return real.map((m) => ({ ...m, isDefault: m.id === fallback?.id }));
|
||||
}
|
||||
const knowsMagpie = tool.prefix ? real.some((m) => m.id.startsWith(tool.prefix)) : real.length > 0;
|
||||
const gatewayIds = await fetchGatewayModelIds(tool.key);
|
||||
let list;
|
||||
if (knowsMagpie) {
|
||||
const mine = real.filter((m) => !tool.prefix || m.id.startsWith(tool.prefix));
|
||||
const others = tool.prefix ? real.filter((m) => !m.id.startsWith(tool.prefix)) : [];
|
||||
const filteredMine = gatewayIds.length ? filterToGatewayShown(mine, gatewayIds, tool.prefix, { providerId }) : mine;
|
||||
list = [...filteredMine.length ? filteredMine : mine, ...others];
|
||||
} else {
|
||||
list = gatewayIds.map((gid) => ({ id: tool.prefix + gid, name: gid }));
|
||||
}
|
||||
const defId = applied.model;
|
||||
if (!list.some((m) => m.id === defId)) list.unshift({ id: defId, name: defId.slice(tool.prefix.length) || defId });
|
||||
list = list.map((m) => ({ ...m, isDefault: m.id === defId }));
|
||||
list.sort((a, b) => Number(!!b.isDefault) - Number(!!a.isDefault));
|
||||
return list.map((m) => {
|
||||
const name = tool.prefix && m.name.startsWith(tool.prefix) ? m.name.slice(tool.prefix.length) : m.name;
|
||||
if (m.thinkingOptions?.length && providerId !== "claude") return { ...m, name };
|
||||
const levels = caps.get(m.id.slice(tool.prefix.length) || m.id);
|
||||
if (!levels) return { ...m, name, thinkingOptions: providerId === "claude" ? [] : m.thinkingOptions };
|
||||
const def = applied.effort && levels.includes(applied.effort) ? applied.effort : levels.includes("high") ? "high" : levels[0];
|
||||
return {
|
||||
...m,
|
||||
name,
|
||||
thinkingOptions: levels.map((id2) => ({ id: id2, label: EFFORT_LABEL2[id2] ?? id2 })),
|
||||
defaultThinking: m.isDefault ? def : m.defaultThinking ?? def
|
||||
};
|
||||
});
|
||||
}
|
||||
var MAGPIE_TOOLS, MAGPIE_GATEWAY_TOKEN, EFFORT_LABEL2;
|
||||
var init_magpieGateway = __esm({
|
||||
"daemon/src/providers/magpieGateway.ts"() {
|
||||
init_log();
|
||||
MAGPIE_TOOLS = {
|
||||
claude: { key: "claude", prefix: "" },
|
||||
codex: { key: "codex", prefix: "" },
|
||||
opencode: { key: "opencode", prefix: "magpie/" },
|
||||
pi: { key: "pi", prefix: "magpie/" },
|
||||
dsh: { key: "dsh", prefix: "magpie/" }
|
||||
};
|
||||
MAGPIE_GATEWAY_TOKEN = "magpie";
|
||||
EFFORT_LABEL2 = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
xhigh: "Extra High",
|
||||
max: "Max"
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// daemon/src/providers/infoCache.ts
|
||||
function registerProviderCacheClear(hook) {
|
||||
extraClearHooks.add(hook);
|
||||
}
|
||||
function withTimeout2(p, ms, fb) {
|
||||
return Promise.race([p, new Promise((r) => setTimeout(() => r(fb), ms))]);
|
||||
}
|
||||
function fresh(e, ttl, fp) {
|
||||
if (!e || Date.now() - e.at >= ttl) return false;
|
||||
if (fp !== void 0 && e.fp !== void 0 && e.fp !== fp) return false;
|
||||
return true;
|
||||
}
|
||||
function cacheKey(p, launch) {
|
||||
return launch ? `${p.id}\0${launchKey(launch)}` : p.id;
|
||||
}
|
||||
async function cachedDetect(p, launch) {
|
||||
const key = cacheKey(p, launch);
|
||||
const hit = detects.get(key);
|
||||
if (fresh(hit, DETECT_MS)) return hit.value;
|
||||
let job = inflightDetect.get(key);
|
||||
if (!job) {
|
||||
const timedOut = { available: false, reason: tr("provider.timeout") };
|
||||
job = withTimeout2(
|
||||
p.detect(launch).catch((e) => ({ available: false, reason: String(e?.message ?? e) })),
|
||||
STEP_TIMEOUT_MS,
|
||||
timedOut
|
||||
).then((v) => {
|
||||
if (v !== timedOut) detects.set(key, { at: Date.now(), value: v });
|
||||
return v;
|
||||
}).finally(() => inflightDetect.delete(key));
|
||||
inflightDetect.set(key, job);
|
||||
}
|
||||
return job;
|
||||
}
|
||||
async function cachedModels(p, launch) {
|
||||
const key = cacheKey(p, launch);
|
||||
const fp = await magpieConfigFingerprint(p.id).catch(() => "");
|
||||
const hit = models.get(key);
|
||||
if (fresh(hit, MODELS_MS, fp)) return hit.value;
|
||||
let job = inflightModels.get(key);
|
||||
if (!job) {
|
||||
job = withTimeout2(p.listModels(launch).catch(() => []), MODELS_TIMEOUT_MS, null).then(async (v) => {
|
||||
if (v === null) return models.get(key)?.value ?? [];
|
||||
const list = await withMagpie(p.id, dropPlaceholder(v)).catch(() => dropPlaceholder(v));
|
||||
models.set(key, { at: Date.now(), value: list, fp });
|
||||
return list;
|
||||
}).finally(() => inflightModels.delete(key));
|
||||
inflightModels.set(key, job);
|
||||
}
|
||||
return job;
|
||||
}
|
||||
function dropPlaceholder(list) {
|
||||
if (list.length === 1 && list[0].id === "default" && (list[0].name === "\u9ED8\u8BA4" || list[0].name === PLACEHOLDER_MODEL_NAME)) return [];
|
||||
return list;
|
||||
}
|
||||
function clearProviderCache(id2) {
|
||||
if (id2) {
|
||||
for (const m of [detects, models]) {
|
||||
for (const k of [...m.keys()]) if (k === id2 || k.startsWith(id2 + "\0")) m.delete(k);
|
||||
}
|
||||
} else {
|
||||
detects.clear();
|
||||
models.clear();
|
||||
}
|
||||
for (const hook of extraClearHooks) {
|
||||
try {
|
||||
hook(id2);
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
}
|
||||
var DETECT_MS, MODELS_MS, STEP_TIMEOUT_MS, MODELS_TIMEOUT_MS, detects, models, inflightDetect, inflightModels, extraClearHooks;
|
||||
var init_infoCache = __esm({
|
||||
"daemon/src/providers/infoCache.ts"() {
|
||||
init_types();
|
||||
init_magpieGateway();
|
||||
init_launch();
|
||||
init_i18n();
|
||||
DETECT_MS = 60 * 1e3;
|
||||
MODELS_MS = 10 * 60 * 1e3;
|
||||
STEP_TIMEOUT_MS = 15e3;
|
||||
MODELS_TIMEOUT_MS = 35e3;
|
||||
detects = /* @__PURE__ */ new Map();
|
||||
models = /* @__PURE__ */ new Map();
|
||||
inflightDetect = /* @__PURE__ */ new Map();
|
||||
inflightModels = /* @__PURE__ */ new Map();
|
||||
extraClearHooks = /* @__PURE__ */ new Set();
|
||||
}
|
||||
});
|
||||
|
||||
// daemon/src/providers/registry.ts
|
||||
function registerProvider(p) {
|
||||
providers.set(p.id, p);
|
||||
@@ -5760,6 +6029,12 @@ function listProviders() {
|
||||
return [...providers.values()];
|
||||
}
|
||||
function initProviders(version = "") {
|
||||
if (!codexCacheHooked) {
|
||||
registerProviderCacheClear((id2) => {
|
||||
if (!id2 || id2 === "codex") clearCodexModelCache();
|
||||
});
|
||||
codexCacheHooked = true;
|
||||
}
|
||||
providers.clear();
|
||||
for (const entry of PROVIDER_CATALOG) {
|
||||
if (entry.id === "claude") registerProvider(createClaudeProvider());
|
||||
@@ -5773,7 +6048,7 @@ function initProviders(version = "") {
|
||||
registerProvider(createMockProvider());
|
||||
}
|
||||
}
|
||||
var providers;
|
||||
var codexCacheHooked, providers;
|
||||
var init_registry = __esm({
|
||||
"daemon/src/providers/registry.ts"() {
|
||||
init_mock();
|
||||
@@ -5782,6 +6057,8 @@ var init_registry = __esm({
|
||||
init_catalog();
|
||||
init_provider3();
|
||||
init_specs();
|
||||
init_infoCache();
|
||||
codexCacheHooked = false;
|
||||
providers = /* @__PURE__ */ new Map();
|
||||
}
|
||||
});
|
||||
@@ -5890,198 +6167,6 @@ var init_pickFolder = __esm({
|
||||
}
|
||||
});
|
||||
|
||||
// daemon/src/providers/magpieGateway.ts
|
||||
import { readFile as readFile11 } from "node:fs/promises";
|
||||
import { homedir as homedir8 } from "node:os";
|
||||
import { join as join11 } from "node:path";
|
||||
async function readJson(path4) {
|
||||
try {
|
||||
return JSON.parse(await readFile11(path4, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
async function readApplied() {
|
||||
return await readJson(join11(homedir8(), ".config", "magpie", "applied.json")) ?? {};
|
||||
}
|
||||
async function readClaudeEnv() {
|
||||
const s = await readJson(join11(homedir8(), ".claude", "settings.json"));
|
||||
return s?.env ?? {};
|
||||
}
|
||||
async function gatewayBase() {
|
||||
const env = await readClaudeEnv();
|
||||
const raw = env.ANTHROPIC_BASE_URL?.trim();
|
||||
return (raw && /^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?/i.test(raw) ? raw : "http://127.0.0.1:3425").replace(/\/+$/, "");
|
||||
}
|
||||
async function fetchGatewayModelIds() {
|
||||
const base = await gatewayBase();
|
||||
try {
|
||||
const res = await fetch(`${base}/v1/models`, { signal: AbortSignal.timeout(5e3) });
|
||||
if (!res.ok) return [];
|
||||
const j = await res.json();
|
||||
return (j.data ?? []).map((m) => m.id).filter((id2) => typeof id2 === "string" && !!id2);
|
||||
} catch (e) {
|
||||
log("warn", "\u8BFB\u53D6 magpie \u7F51\u5173\u6A21\u578B\u5217\u8868\u5931\u8D25", { err: String(e) });
|
||||
return [];
|
||||
}
|
||||
}
|
||||
function parseCapabilities(raw) {
|
||||
const out = /* @__PURE__ */ new Map();
|
||||
for (const part of (raw ?? "").split(";")) {
|
||||
const i = part.indexOf("=");
|
||||
if (i <= 0) continue;
|
||||
const flags = new Set(part.slice(i + 1).split(",").map((s) => s.trim()));
|
||||
if (!flags.has("effort")) continue;
|
||||
const levels = ["low", "medium", "high"];
|
||||
if (flags.has("xhigh_effort")) levels.push("xhigh");
|
||||
if (flags.has("max_effort")) levels.push("max");
|
||||
out.set(part.slice(0, i).trim(), levels);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function isPlaceholder(m) {
|
||||
return !m.id || /^(default|auto)$/i.test(m.id);
|
||||
}
|
||||
async function withMagpie(providerId, own) {
|
||||
const tool = MAGPIE_TOOLS[providerId];
|
||||
if (!tool) return own;
|
||||
const applied = (await readApplied())[tool.key]?.fields;
|
||||
if (!applied?.model) return own;
|
||||
const caps = parseCapabilities((await readClaudeEnv()).CLAUDE_CODE_MODEL_CAPABILITIES);
|
||||
const real = own.filter((m) => !isPlaceholder(m));
|
||||
if (providerId === "dsh") {
|
||||
const appliedId = applied.model.replace(/^magpie\//, "");
|
||||
const selected = real.find(
|
||||
(m) => m.id === applied.model || m.id === appliedId || appliedId.includes("/") && m.id.includes(appliedId)
|
||||
);
|
||||
const fallback = selected ?? real.find((m) => m.isDefault) ?? real[0];
|
||||
return real.map((m) => ({ ...m, isDefault: m.id === fallback?.id }));
|
||||
}
|
||||
const knowsMagpie = tool.prefix ? real.some((m) => m.id.startsWith(tool.prefix)) : real.length > 0;
|
||||
let list;
|
||||
if (knowsMagpie) {
|
||||
const mine = real.filter((m) => !tool.prefix || m.id.startsWith(tool.prefix));
|
||||
const others = tool.prefix ? real.filter((m) => !m.id.startsWith(tool.prefix)) : [];
|
||||
list = [...mine, ...others];
|
||||
} else {
|
||||
list = (await fetchGatewayModelIds()).map((gid) => ({ id: tool.prefix + gid, name: gid }));
|
||||
}
|
||||
const defId = applied.model;
|
||||
if (!list.some((m) => m.id === defId)) list.unshift({ id: defId, name: defId.slice(tool.prefix.length) || defId });
|
||||
list = list.map((m) => ({ ...m, isDefault: m.id === defId }));
|
||||
list.sort((a, b) => Number(!!b.isDefault) - Number(!!a.isDefault));
|
||||
return list.map((m) => {
|
||||
const name = tool.prefix && m.name.startsWith(tool.prefix) ? m.name.slice(tool.prefix.length) : m.name;
|
||||
if (m.thinkingOptions?.length && providerId !== "claude") return { ...m, name };
|
||||
const levels = caps.get(m.id.slice(tool.prefix.length) || m.id);
|
||||
if (!levels) return { ...m, name, thinkingOptions: providerId === "claude" ? [] : m.thinkingOptions };
|
||||
const def = applied.effort && levels.includes(applied.effort) ? applied.effort : levels.includes("high") ? "high" : levels[0];
|
||||
return {
|
||||
...m,
|
||||
name,
|
||||
thinkingOptions: levels.map((id2) => ({ id: id2, label: EFFORT_LABEL2[id2] ?? id2 })),
|
||||
defaultThinking: m.isDefault ? def : m.defaultThinking ?? def
|
||||
};
|
||||
});
|
||||
}
|
||||
var MAGPIE_TOOLS, EFFORT_LABEL2;
|
||||
var init_magpieGateway = __esm({
|
||||
"daemon/src/providers/magpieGateway.ts"() {
|
||||
init_log();
|
||||
MAGPIE_TOOLS = {
|
||||
claude: { key: "claude", prefix: "" },
|
||||
codex: { key: "codex", prefix: "" },
|
||||
opencode: { key: "opencode", prefix: "magpie/" },
|
||||
pi: { key: "pi", prefix: "magpie/" },
|
||||
dsh: { key: "dsh", prefix: "magpie/" }
|
||||
};
|
||||
EFFORT_LABEL2 = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
xhigh: "Extra High",
|
||||
max: "Max"
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// daemon/src/providers/infoCache.ts
|
||||
function withTimeout2(p, ms, fb) {
|
||||
return Promise.race([p, new Promise((r) => setTimeout(() => r(fb), ms))]);
|
||||
}
|
||||
function fresh(e, ttl) {
|
||||
return !!e && Date.now() - e.at < ttl;
|
||||
}
|
||||
function cacheKey(p, launch) {
|
||||
return launch ? `${p.id}\0${launchKey(launch)}` : p.id;
|
||||
}
|
||||
async function cachedDetect(p, launch) {
|
||||
const key = cacheKey(p, launch);
|
||||
const hit = detects.get(key);
|
||||
if (fresh(hit, DETECT_MS)) return hit.value;
|
||||
let job = inflightDetect.get(key);
|
||||
if (!job) {
|
||||
const timedOut = { available: false, reason: tr("provider.timeout") };
|
||||
job = withTimeout2(
|
||||
p.detect(launch).catch((e) => ({ available: false, reason: String(e?.message ?? e) })),
|
||||
STEP_TIMEOUT_MS,
|
||||
timedOut
|
||||
).then((v) => {
|
||||
if (v !== timedOut) detects.set(key, { at: Date.now(), value: v });
|
||||
return v;
|
||||
}).finally(() => inflightDetect.delete(key));
|
||||
inflightDetect.set(key, job);
|
||||
}
|
||||
return job;
|
||||
}
|
||||
async function cachedModels(p, launch) {
|
||||
const key = cacheKey(p, launch);
|
||||
const hit = models.get(key);
|
||||
if (fresh(hit, MODELS_MS)) return hit.value;
|
||||
let job = inflightModels.get(key);
|
||||
if (!job) {
|
||||
job = withTimeout2(p.listModels(launch).catch(() => []), MODELS_TIMEOUT_MS, null).then(async (v) => {
|
||||
if (v === null) return models.get(key)?.value ?? [];
|
||||
const list = await withMagpie(p.id, dropPlaceholder(v)).catch(() => dropPlaceholder(v));
|
||||
models.set(key, { at: Date.now(), value: list });
|
||||
return list;
|
||||
}).finally(() => inflightModels.delete(key));
|
||||
inflightModels.set(key, job);
|
||||
}
|
||||
return job;
|
||||
}
|
||||
function dropPlaceholder(list) {
|
||||
if (list.length === 1 && list[0].id === "default" && (list[0].name === "\u9ED8\u8BA4" || list[0].name === PLACEHOLDER_MODEL_NAME)) return [];
|
||||
return list;
|
||||
}
|
||||
function clearProviderCache(id2) {
|
||||
if (id2) {
|
||||
for (const m of [detects, models]) {
|
||||
for (const k of [...m.keys()]) if (k === id2 || k.startsWith(id2 + "\0")) m.delete(k);
|
||||
}
|
||||
} else {
|
||||
detects.clear();
|
||||
models.clear();
|
||||
}
|
||||
}
|
||||
var DETECT_MS, MODELS_MS, STEP_TIMEOUT_MS, MODELS_TIMEOUT_MS, detects, models, inflightDetect, inflightModels;
|
||||
var init_infoCache = __esm({
|
||||
"daemon/src/providers/infoCache.ts"() {
|
||||
init_types();
|
||||
init_magpieGateway();
|
||||
init_launch();
|
||||
init_i18n();
|
||||
DETECT_MS = 60 * 1e3;
|
||||
MODELS_MS = 10 * 60 * 1e3;
|
||||
STEP_TIMEOUT_MS = 15e3;
|
||||
MODELS_TIMEOUT_MS = 35e3;
|
||||
detects = /* @__PURE__ */ new Map();
|
||||
models = /* @__PURE__ */ new Map();
|
||||
inflightDetect = /* @__PURE__ */ new Map();
|
||||
inflightModels = /* @__PURE__ */ new Map();
|
||||
}
|
||||
});
|
||||
|
||||
// daemon/src/providers/modes.ts
|
||||
function clampMode(modes, mode2) {
|
||||
if (mode2 && modes.includes(mode2)) return mode2;
|
||||
@@ -6194,7 +6279,7 @@ var init_autoApprove13 = __esm({
|
||||
});
|
||||
|
||||
// daemon/src/util/mentions.ts
|
||||
import { realpath, stat as stat8 } from "node:fs/promises";
|
||||
import { realpath, stat as stat9 } from "node:fs/promises";
|
||||
import { isAbsolute as isAbsolute3, resolve as resolve3, sep as sep2, win32 as win322, posix as posix2 } from "node:path";
|
||||
function insideRoot(root, child, platform = process.platform) {
|
||||
const p = platform === "win32" ? win322 : posix2;
|
||||
@@ -6228,7 +6313,7 @@ async function resolveMentions(projectPath, refs) {
|
||||
let isDir2;
|
||||
try {
|
||||
real = await realpath(abs);
|
||||
isDir2 = (await stat8(real)).isDirectory();
|
||||
isDir2 = (await stat9(real)).isDirectory();
|
||||
} catch {
|
||||
warnings.push(rel);
|
||||
continue;
|
||||
@@ -7150,11 +7235,16 @@ function registerMethods(gw, svc) {
|
||||
return { ok: true };
|
||||
}));
|
||||
gw.method("providers.list", wrap(
|
||||
z.object({ refresh: z.boolean().optional() }).passthrough().optional(),
|
||||
z.object({ refresh: z.boolean().optional(), provider: z.string().optional() }).passthrough().optional(),
|
||||
async (p) => {
|
||||
if (p?.refresh) {
|
||||
clearBinCache();
|
||||
clearProviderCache();
|
||||
if (p.provider) {
|
||||
clearBinCache(p.provider);
|
||||
clearProviderCache(p.provider);
|
||||
} else {
|
||||
clearBinCache();
|
||||
clearProviderCache();
|
||||
}
|
||||
}
|
||||
const settings = await svc.settings.get();
|
||||
const rows = await Promise.all(
|
||||
@@ -8899,6 +8989,7 @@ init_registry();
|
||||
init_catalog();
|
||||
init_enabled();
|
||||
init_infoCache();
|
||||
init_magpieGateway();
|
||||
|
||||
// daemon/src/timeline/coalescer.ts
|
||||
var Coalescer = class {
|
||||
@@ -9194,6 +9285,7 @@ var AgentManager = class {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
await this.syncDefaultModelIfNeeded(threadId, meta, rt);
|
||||
await agentShellReady();
|
||||
if (!rt.bashHinted && bashMissingFor(meta.provider)) {
|
||||
rt.bashHinted = true;
|
||||
@@ -9466,11 +9558,49 @@ var AgentManager = class {
|
||||
});
|
||||
}
|
||||
}
|
||||
const sessionModel = model ?? await this.resolveDefaultSessionModel(meta.provider);
|
||||
await this.threads.patch(threadId, { model, effort });
|
||||
const rt = this.rt(threadId);
|
||||
if (rt.session) await rt.session.setModel(model);
|
||||
if (rt.session) {
|
||||
if (model !== null) await rt.session.setModel(sessionModel, { force: true });
|
||||
else await rt.session.setModel(sessionModel);
|
||||
}
|
||||
rt.syncedDefaultModel = model ? void 0 : sessionModel;
|
||||
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||
}
|
||||
/**
|
||||
* Default model id to push into a live session while the thread is on「默认」.
|
||||
* dsh must use its own ACP model ids from cachedModels (never raw applied.json "magpie/…" strings).
|
||||
*/
|
||||
async resolveDefaultSessionModel(providerId) {
|
||||
if (providerId === "dsh") {
|
||||
const provider = getProvider(providerId);
|
||||
if (!provider) return null;
|
||||
const settings = await this.settings.get();
|
||||
const launch = launchFromSettings(settings, providerId);
|
||||
const available = await cachedModels(provider, launch).catch(() => []);
|
||||
const magpie = available.filter((m) => /magpie/i.test(m.id));
|
||||
return (magpie.find((m) => m.isDefault) ?? magpie[0] ?? available.find((m) => m.isDefault))?.id ?? null;
|
||||
}
|
||||
return magpieDefaultModel(providerId);
|
||||
}
|
||||
/**
|
||||
* Thread on「默认」+ idle live session: if Magpie's applied default changed since we last synced,
|
||||
* push the new id into the session (never interrupts a running turn — caller only invokes while idle/before send).
|
||||
*/
|
||||
async syncDefaultModelIfNeeded(threadId, meta, rt) {
|
||||
if (meta.model) return;
|
||||
if (!rt.session) return;
|
||||
if (rt.status === "running" || rt.status === "initializing") return;
|
||||
const current = await this.resolveDefaultSessionModel(meta.provider);
|
||||
if (current === (rt.syncedDefaultModel ?? null)) return;
|
||||
try {
|
||||
await rt.session.setModel(current);
|
||||
rt.syncedDefaultModel = current;
|
||||
} catch (e) {
|
||||
log("warn", `thread ${threadId} sync default model failed\uFF1A${String(e)}`);
|
||||
}
|
||||
}
|
||||
async setMode(threadId, mode2) {
|
||||
const meta = await this.threads.patch(threadId, { mode: mode2 });
|
||||
const rt = this.rt(threadId);
|
||||
@@ -9645,10 +9775,9 @@ var AgentManager = class {
|
||||
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||
}
|
||||
} else if (meta.provider === "dsh" && !model) {
|
||||
const available = await cachedModels(provider).catch(() => []);
|
||||
const magpie = available.filter((m) => /magpie/i.test(m.id));
|
||||
model = (magpie.find((m) => m.isDefault) ?? magpie[0] ?? available.find((m) => m.isDefault))?.id ?? null;
|
||||
model = await this.resolveDefaultSessionModel("dsh");
|
||||
}
|
||||
const sessionModel = model ?? await this.resolveDefaultSessionModel(meta.provider);
|
||||
if (opts.updateStatus) await this.setStatus(threadId, "initializing");
|
||||
const settings = await this.settings.get();
|
||||
const launch = launchFromSettings(settings, meta.provider);
|
||||
@@ -9657,7 +9786,7 @@ var AgentManager = class {
|
||||
rt.session = await provider.createSession({
|
||||
threadId,
|
||||
cwd: proj.path,
|
||||
model,
|
||||
model: sessionModel,
|
||||
mode: clampMode(provider.capabilities.modes, meta.mode),
|
||||
effort: meta.effort,
|
||||
resumeId: meta.providerSessionId,
|
||||
@@ -9665,6 +9794,7 @@ var AgentManager = class {
|
||||
cursorAutoReview: meta.cursorAutoReview,
|
||||
launch
|
||||
});
|
||||
rt.syncedDefaultModel = model ? void 0 : sessionModel;
|
||||
void this.pumpEvents(threadId, rt.session);
|
||||
return rt.session;
|
||||
}
|
||||
@@ -9755,7 +9885,7 @@ init_i18n();
|
||||
init_decode();
|
||||
import { execFile as execFile5 } from "node:child_process";
|
||||
import { existsSync as existsSync11 } from "node:fs";
|
||||
import { cp, mkdir as mkdir7, readFile as readFile16, rename as rename4, rm, stat as stat10 } from "node:fs/promises";
|
||||
import { cp, mkdir as mkdir7, readFile as readFile16, rename as rename4, rm, stat as stat11 } from "node:fs/promises";
|
||||
import { join as join16, normalize as normalize2, sep as sep3 } from "node:path";
|
||||
var TIMEOUT2 = 15e3;
|
||||
var DIFF_LIMIT = 1024 * 1024;
|
||||
@@ -9822,7 +9952,7 @@ var GitService = class {
|
||||
if (ls.code !== 0) {
|
||||
const full = join16(projectPath, rel);
|
||||
if (!existsSync11(full)) return { error: tr("fs.fileMissing") };
|
||||
const s = await stat10(full);
|
||||
const s = await stat11(full);
|
||||
if (!s.isFile()) return { error: tr("fs.notFile") };
|
||||
if (s.size > DIFF_LIMIT) return { tooLarge: true };
|
||||
const text = await readFile16(full, "utf8").catch(() => null);
|
||||
@@ -9870,7 +10000,7 @@ ${lines}` };
|
||||
|
||||
// daemon/src/files/service.ts
|
||||
init_i18n();
|
||||
import { readdir as readdir5, readFile as readFile17, stat as stat11 } from "node:fs/promises";
|
||||
import { readdir as readdir5, readFile as readFile17, stat as stat12 } from "node:fs/promises";
|
||||
import { join as join17, normalize as normalize3, sep as sep4, extname as extname3 } from "node:path";
|
||||
import ignore from "ignore";
|
||||
function decodeText(buf) {
|
||||
@@ -9945,7 +10075,7 @@ var FileService = class {
|
||||
igCache = /* @__PURE__ */ new Map();
|
||||
async igFor(projectPath) {
|
||||
const gi = join17(projectPath, ".gitignore");
|
||||
const st = await stat11(gi).catch(() => null);
|
||||
const st = await stat12(gi).catch(() => null);
|
||||
const mtime = st?.isFile() ? st.mtimeMs : -1;
|
||||
const hit = this.igCache.get(projectPath);
|
||||
if (hit && hit.mtime === mtime) return hit.ig;
|
||||
@@ -9964,7 +10094,7 @@ var FileService = class {
|
||||
const rel = insidePath2(projectPath, dir);
|
||||
if (rel === null) return { error: tr("fs.pathDenied") };
|
||||
const abs = join17(projectPath, rel);
|
||||
const s = await stat11(abs).catch(() => null);
|
||||
const s = await stat12(abs).catch(() => null);
|
||||
if (!s?.isDirectory()) return { error: tr("fs.dirMissing") };
|
||||
const ig = await this.igFor(projectPath);
|
||||
const dirents = await readdir5(abs, { withFileTypes: true }).catch(() => null);
|
||||
@@ -9977,7 +10107,7 @@ var FileService = class {
|
||||
const childRel = rel === "." ? name : `${rel}/${name}`;
|
||||
let isDir2 = d.isDirectory();
|
||||
if (d.isSymbolicLink()) {
|
||||
const st = await stat11(join17(projectPath, childRel)).catch(() => null);
|
||||
const st = await stat12(join17(projectPath, childRel)).catch(() => null);
|
||||
if (!st) continue;
|
||||
isDir2 = st.isDirectory();
|
||||
} else if (!d.isFile() && !isDir2) {
|
||||
@@ -9995,7 +10125,7 @@ var FileService = class {
|
||||
const rel = insidePath2(projectPath, p);
|
||||
if (rel === null) return { error: tr("fs.pathDenied") };
|
||||
const abs = join17(projectPath, rel);
|
||||
const s = await stat11(abs).catch(() => null);
|
||||
const s = await stat12(abs).catch(() => null);
|
||||
if (!s) return { error: tr("fs.fileMissing") };
|
||||
if (!s.isFile()) return { error: tr("fs.notFile") };
|
||||
if (s.size > MAX_READ) return { tooLarge: true };
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
@@ -14,6 +14,7 @@ import { getProvider } from "../providers/registry.js";
|
||||
import { catalogById, providerCreatable } from "../providers/catalog.js";
|
||||
import { isProviderEnabled } from "../providers/enabled.js";
|
||||
import { cachedDetect, cachedModels } from "../providers/infoCache.js";
|
||||
import { magpieDefaultModel } from "../providers/magpieGateway.js";
|
||||
import type { ProviderEvent, TimelineEvent } from "../timeline/types.js";
|
||||
import { Coalescer } from "../timeline/coalescer.js";
|
||||
import { ApiError } from "../ws/methods.js";
|
||||
@@ -68,6 +69,11 @@ type Runtime = {
|
||||
deltasOnly: boolean;
|
||||
/** 1.3: the "Git Bash not found" hint was already shown in this conversation during this daemon run */
|
||||
bashHinted?: boolean;
|
||||
/**
|
||||
* When the thread is on「默认」(meta.model null), the Magpie / agent default id last pushed into the live session.
|
||||
* Used to adopt a Magpie default-model change on the next turn without interrupting a running one.
|
||||
*/
|
||||
syncedDefaultModel?: string | null;
|
||||
};
|
||||
|
||||
type DeltaType = "assistant_delta" | "reasoning_delta" | "tool_output_delta";
|
||||
@@ -337,6 +343,8 @@ export class AgentManager {
|
||||
}
|
||||
}
|
||||
// A live session needs no detection: the Agent is running (the 60 s detect cache used to re-run "--version" on later sends)
|
||||
//「默认」threads: adopt Magpie's latest default before this turn (session is still idle here)
|
||||
await this.syncDefaultModelIfNeeded(threadId, meta, rt);
|
||||
|
||||
// Windows without Git Bash: say so before the agent's first command fails on the WSL launcher
|
||||
await agentShellReady();
|
||||
@@ -640,11 +648,57 @@ export class AgentManager {
|
||||
});
|
||||
}
|
||||
}
|
||||
// Thread stays on「默认」when model is null; the live session still gets the resolved default id
|
||||
// so switching back to Default (and Magpie default changes) take effect on the next turn.
|
||||
const sessionModel = model ?? await this.resolveDefaultSessionModel(meta.provider);
|
||||
await this.threads.patch(threadId, { model, effort });
|
||||
const rt = this.rt(threadId);
|
||||
if (rt.session) await rt.session.setModel(model);
|
||||
if (rt.session) {
|
||||
// Only an explicit user pick may bypass ACP's session/new model validation.
|
||||
if (model !== null) await rt.session.setModel(sessionModel, { force: true });
|
||||
else await rt.session.setModel(sessionModel);
|
||||
}
|
||||
rt.syncedDefaultModel = model ? undefined : sessionModel;
|
||||
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||
}
|
||||
|
||||
/**
|
||||
* Default model id to push into a live session while the thread is on「默认」.
|
||||
* dsh must use its own ACP model ids from cachedModels (never raw applied.json "magpie/…" strings).
|
||||
*/
|
||||
private async resolveDefaultSessionModel(providerId: string): Promise<string | null> {
|
||||
if (providerId === "dsh") {
|
||||
const provider = getProvider(providerId);
|
||||
if (!provider) return null;
|
||||
const settings = await this.settings.get();
|
||||
const launch = launchFromSettings(settings, providerId);
|
||||
const available = await cachedModels(provider, launch).catch(() => []);
|
||||
const magpie = available.filter((m) => /magpie/i.test(m.id));
|
||||
return (magpie.find((m) => m.isDefault) ?? magpie[0] ?? available.find((m) => m.isDefault))?.id ?? null;
|
||||
}
|
||||
return magpieDefaultModel(providerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Thread on「默认」+ idle live session: if Magpie's applied default changed since we last synced,
|
||||
* push the new id into the session (never interrupts a running turn — caller only invokes while idle/before send).
|
||||
*/
|
||||
private async syncDefaultModelIfNeeded(threadId: string, meta: ThreadMeta, rt: Runtime): Promise<void> {
|
||||
if (meta.model) return; // explicit model pick — leave it alone
|
||||
if (!rt.session) return;
|
||||
// Only skip a turn that is already running / initializing. rt.starting is true for the whole
|
||||
// startTurnInner (including this sync-before-send), so it must not block adoption of a new Magpie default.
|
||||
if (rt.status === "running" || rt.status === "initializing") return;
|
||||
const current = await this.resolveDefaultSessionModel(meta.provider);
|
||||
if (current === (rt.syncedDefaultModel ?? null)) return;
|
||||
try {
|
||||
await rt.session.setModel(current);
|
||||
rt.syncedDefaultModel = current;
|
||||
} catch (e) {
|
||||
log("warn", `thread ${threadId} sync default model failed:${String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async setMode(threadId: string, mode: Mode): Promise<void> {
|
||||
const meta = await this.threads.patch(threadId, { mode });
|
||||
const rt = this.rt(threadId);
|
||||
@@ -851,10 +905,10 @@ export class AgentManager {
|
||||
}
|
||||
} else if (meta.provider === "dsh" && !model) {
|
||||
// No model picked: start dsh on the route a new conversation would use (its ACP takes images only for the route it starts on)
|
||||
const available = await cachedModels(provider).catch(() => []);
|
||||
const magpie = available.filter((m) => /magpie/i.test(m.id));
|
||||
model = (magpie.find((m) => m.isDefault) ?? magpie[0] ?? available.find((m) => m.isDefault))?.id ?? null;
|
||||
model = await this.resolveDefaultSessionModel("dsh");
|
||||
}
|
||||
//「默认」: pass the resolved Magpie / agent default into the session so a live process doesn't stick on an old spawn-time default
|
||||
const sessionModel = model ?? await this.resolveDefaultSessionModel(meta.provider);
|
||||
if (opts.updateStatus) await this.setStatus(threadId, "initializing");
|
||||
const settings = await this.settings.get();
|
||||
const launch = launchFromSettings(settings, meta.provider);
|
||||
@@ -864,7 +918,7 @@ export class AgentManager {
|
||||
rt.session = await provider.createSession({
|
||||
threadId,
|
||||
cwd: proj.path,
|
||||
model,
|
||||
model: sessionModel,
|
||||
mode: clampMode(provider.capabilities.modes, meta.mode),
|
||||
effort: meta.effort,
|
||||
resumeId: meta.providerSessionId,
|
||||
@@ -872,6 +926,7 @@ export class AgentManager {
|
||||
cursorAutoReview: meta.cursorAutoReview,
|
||||
launch,
|
||||
});
|
||||
rt.syncedDefaultModel = model ? undefined : sessionModel;
|
||||
void this.pumpEvents(threadId, rt.session);
|
||||
return rt.session;
|
||||
}
|
||||
|
||||
@@ -315,15 +315,16 @@ export class AcpSession implements ProviderSession {
|
||||
* Switch model → refresh level options from the new config options it returns → then apply the level (as Paseo does).
|
||||
* Cursor connects with parameterizedModelPicker: only the base model name is sent (grok-4.6); level / Fast are separate config options.
|
||||
*/
|
||||
private async applySessionModel(model: string | null): Promise<void> {
|
||||
private async applySessionModel(model: string | null, force = false): Promise<void> {
|
||||
if (!this.ctx || !this.active) return;
|
||||
const value = model && this.o.flavor === "cursor" ? model.replace(/\[.*\]$/u, "") : model;
|
||||
if (value) {
|
||||
const modelOption = this.currentConfig().find((o) => o.id === (this.modelConfigId ?? "model"));
|
||||
const values = (modelOption?.options ?? []).flatMap((x) => x.options ? x.options : [x])
|
||||
.map((x) => x.value).filter((x): x is string => typeof x === "string");
|
||||
// Old sessions may have saved another Agent's model ID. Skip invalid values and let ACP keep its current model.
|
||||
if (!values.length || values.includes(value)) {
|
||||
// Startup/default sync (!force): validate against the session/new snapshot.
|
||||
// Explicit user pick (force): models may have been enabled since boot.
|
||||
if (force || !values.length || values.includes(value)) {
|
||||
await this.setOption(this.modelConfigId ?? "model", value);
|
||||
} else {
|
||||
log("info", `忽略 ${this.o.binName} 的无效模型:${value}`);
|
||||
@@ -564,14 +565,14 @@ export class AcpSession implements ProviderSession {
|
||||
await notifyP;
|
||||
}
|
||||
|
||||
async setModel(model: string | null): Promise<void> {
|
||||
async setModel(model: string | null, opts?: { force?: boolean }): Promise<void> {
|
||||
this.o.model = model;
|
||||
await this.ready();
|
||||
if (this.o.imagesFollowStartModel) {
|
||||
// dsh answered initialize for the model it started on; another model may not take image blocks (it refuses the prompt)
|
||||
this.promptCaps = model === this.startModel ? this.initCaps : { ...this.initCaps, image: false };
|
||||
}
|
||||
await this.applySessionModel(model);
|
||||
await this.applySessionModel(model, Boolean(opts?.force));
|
||||
}
|
||||
|
||||
async setMode(mode: Mode): Promise<void> {
|
||||
|
||||
@@ -33,6 +33,11 @@ export const codexCapabilities: Capabilities = {
|
||||
let modelCache: { at: number; models: ModelInfo[] } | null = null;
|
||||
const MODEL_CACHE_MS = 10 * 60 * 1000;
|
||||
|
||||
/** Cleared by clearProviderCache so a Magpie refresh doesn't keep Codex's own 10-minute list. */
|
||||
export function clearCodexModelCache(): void {
|
||||
modelCache = null;
|
||||
}
|
||||
|
||||
function runVersion(r: ResolveResult & { ok: true }, args: string[], timeoutMs = 5000): Promise<string> {
|
||||
return new Promise((resolvePromise, reject) => {
|
||||
let out = "";
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// detect / listModels often have to start a CLI (seconds); without a cache every page open and model pick would wait.
|
||||
import type { Provider, DetectResult, ModelInfo, LaunchCommand } from "./types.js";
|
||||
import { PLACEHOLDER_MODEL_NAME } from "./types.js";
|
||||
import { withMagpie } from "./magpieGateway.js";
|
||||
import { magpieConfigFingerprint, withMagpie } from "./magpieGateway.js";
|
||||
import { launchKey } from "./launch.js";
|
||||
import { tr } from "../util/i18n.js";
|
||||
|
||||
@@ -13,19 +13,29 @@ const STEP_TIMEOUT_MS = 15000;
|
||||
// Fetching models may start an ACP session (Cursor launches slowly through PowerShell), so it gets a longer timeout
|
||||
const MODELS_TIMEOUT_MS = 35000;
|
||||
|
||||
type Entry<T> = { at: number; value: T } | undefined;
|
||||
type Entry<T> = { at: number; value: T; fp?: string } | undefined;
|
||||
const detects = new Map<string, Entry<DetectResult>>();
|
||||
const models = new Map<string, Entry<ModelInfo[]>>();
|
||||
// Concurrent requests for the same Provider share one in-flight detection
|
||||
const inflightDetect = new Map<string, Promise<DetectResult>>();
|
||||
const inflightModels = new Map<string, Promise<ModelInfo[]>>();
|
||||
|
||||
/** Extra provider-local caches (e.g. Codex's own 10-minute modelCache) cleared together with ours. */
|
||||
const extraClearHooks = new Set<(id?: string) => void>();
|
||||
|
||||
export function registerProviderCacheClear(hook: (id?: string) => void): void {
|
||||
extraClearHooks.add(hook);
|
||||
}
|
||||
|
||||
function withTimeout<T>(p: Promise<T>, ms: number, fb: T): Promise<T> {
|
||||
return Promise.race([p, new Promise<T>((r) => setTimeout(() => r(fb), ms))]);
|
||||
}
|
||||
|
||||
function fresh<T>(e: Entry<T>, ttl: number): e is { at: number; value: T } {
|
||||
return !!e && Date.now() - e.at < ttl;
|
||||
function fresh<T>(e: Entry<T>, ttl: number, fp?: string): e is { at: number; value: T; fp?: string } {
|
||||
if (!e || Date.now() - e.at >= ttl) return false;
|
||||
// Magpie / agent config changed on disk since we cached → treat as stale even inside the TTL
|
||||
if (fp !== undefined && e.fp !== undefined && e.fp !== fp) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function cacheKey(p: Provider, launch?: LaunchCommand): string {
|
||||
@@ -55,8 +65,9 @@ export async function cachedDetect(p: Provider, launch?: LaunchCommand): Promise
|
||||
|
||||
export async function cachedModels(p: Provider, launch?: LaunchCommand): Promise<ModelInfo[]> {
|
||||
const key = cacheKey(p, launch);
|
||||
const fp = await magpieConfigFingerprint(p.id).catch(() => "");
|
||||
const hit = models.get(key);
|
||||
if (fresh(hit, MODELS_MS)) return hit.value;
|
||||
if (fresh(hit, MODELS_MS, fp)) return hit.value;
|
||||
let job = inflightModels.get(key);
|
||||
if (!job) {
|
||||
job = withTimeout<ModelInfo[] | null>(p.listModels(launch).catch(() => []), MODELS_TIMEOUT_MS, null)
|
||||
@@ -65,7 +76,8 @@ export async function cachedModels(p: Provider, launch?: LaunchCommand): Promise
|
||||
if (v === null) return models.get(key)?.value ?? [];
|
||||
// Agents behind the magpie gateway: fill in gateway models, the default model and thinking levels
|
||||
const list = await withMagpie(p.id, dropPlaceholder(v)).catch(() => dropPlaceholder(v));
|
||||
models.set(key, { at: Date.now(), value: list });
|
||||
// Keep the pre-list fingerprint: a config change during listing must invalidate the next read.
|
||||
models.set(key, { at: Date.now(), value: list, fp });
|
||||
return list;
|
||||
})
|
||||
.finally(() => inflightModels.delete(key));
|
||||
@@ -95,4 +107,7 @@ export function clearProviderCache(id?: string): void {
|
||||
detects.clear();
|
||||
models.clear();
|
||||
}
|
||||
for (const hook of extraClearHooks) {
|
||||
try { hook(id); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// magpie gateway: magpie points each Agent's models at the local gateway (applied.json records the model currently applied to each).
|
||||
// Here we fill in, for those Agents, the model list, the default model and each model's thinking levels. Read-only; no configuration is changed.
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { ModelInfo } from "./types.js";
|
||||
@@ -15,6 +15,17 @@ const MAGPIE_TOOLS: Record<string, { key: string; prefix: string }> = {
|
||||
dsh: { key: "dsh", prefix: "magpie/" },
|
||||
};
|
||||
|
||||
/** Magpie gateway.TokenFor(agent) = "magpie-" + agent; CatalogFor / ModelOff key off that agent id. */
|
||||
export const MAGPIE_GATEWAY_TOKEN = "magpie";
|
||||
export function magpieTokenFor(agentId: string): string {
|
||||
return `${MAGPIE_GATEWAY_TOKEN}-${agentId}`;
|
||||
}
|
||||
|
||||
/** Magpie agent id for a Magpie-managed Agent Console provider (same strings Magpie uses in HiddenModels / Visible). */
|
||||
export function magpieAgentId(providerId: string): string | null {
|
||||
return MAGPIE_TOOLS[providerId]?.key ?? null;
|
||||
}
|
||||
|
||||
const EFFORT_LABEL: Record<string, string> = {
|
||||
low: "Low", medium: "Medium", high: "High", xhigh: "Extra High", max: "Max",
|
||||
};
|
||||
@@ -42,18 +53,33 @@ async function readClaudeEnv(): Promise<Record<string, string>> {
|
||||
async function gatewayBase(): Promise<string> {
|
||||
const env = await readClaudeEnv();
|
||||
const raw = env.ANTHROPIC_BASE_URL?.trim();
|
||||
return (raw && /^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?/i.test(raw) ? raw : "http://127.0.0.1:3425").replace(/\/+$/, "");
|
||||
return (raw && /^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?(\/|$)/i.test(raw) ? raw : "http://127.0.0.1:3425").replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
async function fetchGatewayModelIds(): Promise<string[]> {
|
||||
/**
|
||||
* Magpie's /v1/models is filtered per agent via agentOf(r):
|
||||
* Authorization Bearer magpie-<agent> (TokenFor) → CatalogFor(agent) + ModelOff(agent).
|
||||
* Without that token Magpie returns the anonymous / global catalog, so models the user hid
|
||||
* for Claude Code (etc.) still appear in our picker.
|
||||
*/
|
||||
export async function fetchGatewayModelIds(agentId: string): Promise<string[]> {
|
||||
const base = await gatewayBase();
|
||||
const token = magpieTokenFor(agentId);
|
||||
try {
|
||||
const res = await fetch(`${base}/v1/models`, { signal: AbortSignal.timeout(5000) });
|
||||
const res = await fetch(`${base}/v1/models`, {
|
||||
signal: AbortSignal.timeout(5000),
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"x-api-key": token,
|
||||
// Belt-and-suspenders: AgentOf also maps known User-Agents when the token is plain "magpie".
|
||||
"User-Agent": `agent-console/${agentId}`,
|
||||
},
|
||||
});
|
||||
if (!res.ok) return [];
|
||||
const j = (await res.json()) as { data?: { id?: unknown }[] };
|
||||
return (j.data ?? []).map((m) => m.id).filter((id): id is string => typeof id === "string" && !!id);
|
||||
} catch (e) {
|
||||
log("warn", "读取 magpie 网关模型列表失败", { err: String(e) });
|
||||
log("warn", "读取 magpie 网关模型列表失败", { agent: agentId, err: String(e) });
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -78,11 +104,78 @@ function isPlaceholder(m: ModelInfo): boolean {
|
||||
return !m.id || /^(default|auto)$/i.test(m.id);
|
||||
}
|
||||
|
||||
/** The model Magpie currently applies to this Agent (applied.json), or null when Magpie doesn't manage it.
|
||||
* dsh is excluded: its ACP session needs its own JSON-array model ids, never raw applied.json "magpie/…" strings. */
|
||||
export async function magpieDefaultModel(providerId: string): Promise<string | null> {
|
||||
if (providerId === "dsh") return null;
|
||||
const tool = MAGPIE_TOOLS[providerId];
|
||||
if (!tool) return null;
|
||||
const applied = (await readApplied())[tool.key]?.fields?.model?.trim();
|
||||
return applied || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fingerprint of Magpie / agent config files that change when the user toggles models or the default.
|
||||
* Used by the provider model cache: a changed mtime invalidates without waiting for the 10-minute TTL.
|
||||
*/
|
||||
export async function magpieConfigFingerprint(providerId: string): Promise<string> {
|
||||
// Only our Magpie overlay consumes applied.json / settings.json. Native-only model lists
|
||||
// (Cursor, Copilot, Devin) must not spawn a new probe for an unrelated Magpie edit.
|
||||
if (!MAGPIE_TOOLS[providerId]) return "";
|
||||
const home = homedir();
|
||||
const ownFiles: Record<string, string[]> = {
|
||||
claude: [join(home, ".claude", "settings.json")],
|
||||
codex: [join(home, ".codex", "config.toml"), join(home, ".codex", "magpie-models.json"), join(home, ".codex", "models.json")],
|
||||
opencode: [join(home, ".config", "opencode", "opencode.json")],
|
||||
pi: [join(home, ".pi", "agent", "settings.json"), join(home, ".pi", "agent", "models.json")],
|
||||
// DSH uses YAML under DSH_HOME (default ~/.dsh), not ~/.config/dsh/config.json.
|
||||
dsh: ["config.yaml", "settings.yaml", "cordis.patch.yml", "profiles/desktop/cordis.patch.yml", "profiles/web/cordis.patch.yml"]
|
||||
.map((file) => join(process.env.DSH_HOME?.trim() || join(home, ".dsh"), file)),
|
||||
};
|
||||
const paths = [
|
||||
join(home, ".config", "magpie", "applied.json"),
|
||||
join(home, ".config", "magpie", "settings.json"),
|
||||
...ownFiles[providerId],
|
||||
];
|
||||
const parts: string[] = [];
|
||||
for (const p of paths) {
|
||||
try {
|
||||
const st = await stat(p);
|
||||
parts.push(`${p}=${st.mtimeMs}`);
|
||||
} catch {
|
||||
parts.push(`${p}=-`);
|
||||
}
|
||||
}
|
||||
return parts.join("|");
|
||||
}
|
||||
|
||||
/** Keep models Magpie still shows this agent (gateway catalog), matching prefix-aware ids.
|
||||
* Codex ChatGPT-own rows use bare slugs in model/list while Magpie lists them as "codex/<slug>". */
|
||||
export function filterToGatewayShown(
|
||||
list: ModelInfo[],
|
||||
gatewayIds: string[],
|
||||
prefix: string,
|
||||
opts?: { providerId?: string },
|
||||
): ModelInfo[] {
|
||||
if (!gatewayIds.length) return list;
|
||||
const shown = new Set(gatewayIds);
|
||||
const shownPrefixed = new Set(gatewayIds.map((id) => prefix + id));
|
||||
const codexBare = opts?.providerId === "codex";
|
||||
return list.filter((m) => {
|
||||
if (shown.has(m.id) || shownPrefixed.has(m.id)) return true;
|
||||
if (prefix && m.id.startsWith(prefix) && shown.has(m.id.slice(prefix.length))) return true;
|
||||
// Codex + ChatGPT sign-in: bare "gpt-5.3-codex" matches gateway "codex/gpt-5.3-codex"
|
||||
if (codexBare && !m.id.includes("/") && shown.has(`codex/${m.id}`)) return true;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill in model info for Agents managed by magpie; if magpie doesn't manage this Agent (not in applied.json) return it unchanged.
|
||||
* - The Agent's own list knows magpie models (e.g. OpenCode, Codex): keep its list with magpie's first (only what it knows, so picks never fail)
|
||||
* - The Agent can't report models (Claude, Pi, dsh): use the gateway's /v1/models with the prefix that Agent uses
|
||||
* - Default model = the model magpie currently applies to it; thinking levels from magpie's capability table
|
||||
* - Gateway fetch always sends TokenFor(agent) so HiddenModels / PickedModels / Visible apply
|
||||
*/
|
||||
export async function withMagpie(providerId: string, own: ModelInfo[]): Promise<ModelInfo[]> {
|
||||
const tool = MAGPIE_TOOLS[providerId];
|
||||
@@ -108,14 +201,19 @@ export async function withMagpie(providerId: string, own: ModelInfo[]): Promise<
|
||||
}
|
||||
|
||||
const knowsMagpie = tool.prefix ? real.some((m) => m.id.startsWith(tool.prefix)) : real.length > 0;
|
||||
// Always ask the gateway as this agent so per-agent visibility (HiddenModels / PickedModels) applies.
|
||||
const gatewayIds = await fetchGatewayModelIds(tool.key);
|
||||
|
||||
let list: ModelInfo[];
|
||||
if (knowsMagpie) {
|
||||
const mine = real.filter((m) => !tool.prefix || m.id.startsWith(tool.prefix));
|
||||
const others = tool.prefix ? real.filter((m) => !m.id.startsWith(tool.prefix)) : [];
|
||||
list = [...mine, ...others];
|
||||
// Prefer Magpie's shown catalog when the gateway answered: drops models the user turned off for this agent
|
||||
// even if the Agent's own config file is briefly stale.
|
||||
const filteredMine = gatewayIds.length ? filterToGatewayShown(mine, gatewayIds, tool.prefix, { providerId }) : mine;
|
||||
list = [...(filteredMine.length ? filteredMine : mine), ...others];
|
||||
} else {
|
||||
list = (await fetchGatewayModelIds()).map((gid) => ({ id: tool.prefix + gid, name: gid }));
|
||||
list = gatewayIds.map((gid) => ({ id: tool.prefix + gid, name: gid }));
|
||||
}
|
||||
|
||||
// Default model = the one magpie currently applies; if it's not in the list, add it at the top
|
||||
|
||||
@@ -2,10 +2,13 @@
|
||||
import type { Provider } from "./types.js";
|
||||
import { createMockProvider } from "./mock.js";
|
||||
import { createClaudeProvider } from "./claude/provider.js";
|
||||
import { createCodexProvider } from "./codex/provider.js";
|
||||
import { createCodexProvider, clearCodexModelCache } from "./codex/provider.js";
|
||||
import { PROVIDER_CATALOG } from "./catalog.js";
|
||||
import { createAcpProvider } from "./acp/provider.js";
|
||||
import { acpConfigForEntry } from "./acp/specs.js";
|
||||
import { registerProviderCacheClear } from "./infoCache.js";
|
||||
|
||||
let codexCacheHooked = false;
|
||||
|
||||
const providers = new Map<string, Provider>();
|
||||
|
||||
@@ -22,6 +25,12 @@ export function listProviders(): Provider[] {
|
||||
}
|
||||
|
||||
export function initProviders(version: string = ""): void {
|
||||
if (!codexCacheHooked) {
|
||||
registerProviderCacheClear((id) => {
|
||||
if (!id || id === "codex") clearCodexModelCache();
|
||||
});
|
||||
codexCacheHooked = true;
|
||||
}
|
||||
providers.clear();
|
||||
for (const entry of PROVIDER_CATALOG) {
|
||||
if (entry.id === "claude") registerProvider(createClaudeProvider());
|
||||
|
||||
@@ -70,7 +70,7 @@ export interface ProviderSession {
|
||||
send(input: SendInput): Promise<void>;
|
||||
steer?(input: SendInput): Promise<void>;
|
||||
interrupt(): Promise<void>;
|
||||
setModel(model: string | null): Promise<void>;
|
||||
setModel(model: string | null, opts?: { force?: boolean }): Promise<void>;
|
||||
setMode(mode: Mode): Promise<void>;
|
||||
setEffort(effort: string | null): Promise<void>;
|
||||
respond(requestId: string, answer: RespondAnswer): void;
|
||||
|
||||
@@ -190,12 +190,18 @@ export function registerMethods(gw: Gateway, svc: Services): void {
|
||||
|
||||
// ---- providers.list (§6): detection + model list + capabilities ----
|
||||
// detect/listModels in parallel; 8s total per provider (listModels may start a temporary process).
|
||||
// refresh+provider: clear/reload only that Agent (model picker ↻ inside < Claude Code); refresh alone: all.
|
||||
gw.method("providers.list", wrap(
|
||||
z.object({ refresh: z.boolean().optional() }).passthrough().optional(),
|
||||
z.object({ refresh: z.boolean().optional(), provider: z.string().optional() }).passthrough().optional(),
|
||||
async (p) => {
|
||||
if (p?.refresh) {
|
||||
clearBinCache();
|
||||
clearProviderCache();
|
||||
if (p.provider) {
|
||||
clearBinCache(p.provider);
|
||||
clearProviderCache(p.provider);
|
||||
} else {
|
||||
clearBinCache();
|
||||
clearProviderCache();
|
||||
}
|
||||
}
|
||||
const settings = await svc.settings.get();
|
||||
const rows = await Promise.all(
|
||||
|
||||
@@ -64,18 +64,22 @@ export function failureHtml(error) {
|
||||
|
||||
/**
|
||||
* The Magpie plugin page boot.js came from (?back=), so the daemon page can go back through it after the plugin host restarts
|
||||
* (fresh session.js → new gate → new daemon). Only a loopback Magpie plugin page is accepted, so the daemon page can't be turned
|
||||
* into an open redirect; it travels in the 302's # fragment next to the token and never reaches a server.
|
||||
* Keep in sync with web/src/api/backToMagpie.ts.
|
||||
* (fresh session.js → new gate → new daemon). Only a Magpie plugin page on loopback (magpie web) or the Windows desktop
|
||||
* host (exact hostname wails.localhost) is accepted, so the daemon page can't be turned into an open redirect; it travels
|
||||
* in the 302's # fragment next to the token and never reaches a server.
|
||||
* Keep in sync with web/src/api/backToMagpie.ts and lib/wrapper.mjs SAFE_BACK_SRC.
|
||||
*/
|
||||
export function safeBackUrl(raw) {
|
||||
export function safeBackUrl(raw, platform = process.platform) {
|
||||
if (typeof raw !== "string" || !raw || raw.length > 2048) return null;
|
||||
let u;
|
||||
try { u = new URL(raw); } catch { return null; }
|
||||
if (u.protocol !== "http:" && u.protocol !== "https:") return null;
|
||||
if (u.username || u.password) return null;
|
||||
const hostname = u.hostname.toLowerCase();
|
||||
if (hostname !== "127.0.0.1" && hostname !== "localhost" && hostname !== "[::1]") return null;
|
||||
// Exact hosts only: never evil-wails.localhost / wails.localhost.evil.com / 127.0.0.1.evil…
|
||||
const loopback = hostname === "127.0.0.1" || hostname === "localhost" || hostname === "[::1]";
|
||||
const magpieWin = platform === "win32" && hostname === "wails.localhost" && u.protocol === "http:" && u.port === "";
|
||||
if (!loopback && !magpieWin) return null;
|
||||
if (!/^\/_magpie\/plugin\/[A-Za-z0-9_-]{1,128}\/(?:page\/)?index\.html$/.test(u.pathname)) return null;
|
||||
return `${u.protocol}//${u.host}${u.pathname}${u.search}`;
|
||||
}
|
||||
|
||||
@@ -17,12 +17,16 @@
|
||||
// the 3 automatic tries are used up), so the user never returns to a dead button.
|
||||
// - every disconnect / invalid-link end state shows a Reconnect button. A missing #b= is filled from sessionStorage
|
||||
// (last safe Magpie back URL written when this page first saw a valid b; read/write re-run safeBack). With a stored
|
||||
// back, recover navigates via go(false). With none, the button reloads and the copy tells the user to flip Magpie's
|
||||
// top-bar page and open Agent Console again if reload is not enough.
|
||||
// back, recover navigates via go(false). With none: if this page is framed by Magpie (window.parent !== window), it
|
||||
// posts { magpie: 1, method: "error", params: { message } } so the host shows its Try-again card and rebuilds the
|
||||
// plugin iframe; Reconnect does the same and falls back to location.reload() after 300 ms if the frame was not
|
||||
// unloaded. The copy tells the user to turn the Agent Console plugin off and on again in Magpie's Plugins page if
|
||||
// that is still not enough (switching Magpie top-bar tabs does not rebuild the iframe within IDLE_MS).
|
||||
//
|
||||
// Security: this page holds no secret of its own. The daemon token arrives only in its # fragment (as before, never sent to a
|
||||
// server, not in Referer) and is handed to the child in the child's fragment; the gate key is never here. The child is always
|
||||
// http://127.0.0.1:<integer port>/, b must pass the same loopback Magpie-page check as everywhere else (no open redirect),
|
||||
// http://127.0.0.1:<integer port>/, b must pass the same Magpie-page check as everywhere else (http(s) on loopback or exact
|
||||
// Windows desktop host wails.localhost, path /_magpie/plugin/<id>/(page/)?index.html, no credentials — no open redirect),
|
||||
// and only the Magpie theme protocol is relayed (theme events / hello answers down, the hello call up). The page runs inside
|
||||
// Magpie's sandboxed plugin frame (opaque origin) and is served with a nonce-only CSP.
|
||||
|
||||
@@ -33,7 +37,10 @@ const SAFE_BACK_SRC = String.raw`function safeBack(raw) {
|
||||
if (u.protocol !== "http:" && u.protocol !== "https:") return null;
|
||||
if (u.username || u.password) return null;
|
||||
var h = u.hostname.toLowerCase();
|
||||
if (h !== "127.0.0.1" && h !== "localhost" && h !== "[::1]") return null;
|
||||
var loopback = h === "127.0.0.1" || h === "localhost" || h === "[::1]";
|
||||
var magpieWin = /Windows/.test(typeof navigator !== "undefined" ? navigator.userAgent : "") &&
|
||||
h === "wails.localhost" && u.protocol === "http:" && u.port === "";
|
||||
if (!loopback && !magpieWin) return null;
|
||||
if (!/^\/_magpie\/plugin\/[A-Za-z0-9_-]{1,128}\/(?:page\/)?index\.html$/.test(u.pathname)) return null;
|
||||
return u.protocol + "//" + u.host + u.pathname + u.search;
|
||||
}`;
|
||||
@@ -81,23 +88,39 @@ const SCRIPT = String.raw`(function () {
|
||||
box.hidden = false;
|
||||
if (button) { btn.textContent = zh ? button[0] : button[1]; btn.hidden = false; }
|
||||
}
|
||||
// Ask Magpie's parent frame to show its native "Try again" card (pluginpages.js → broke → rebuild iframe).
|
||||
// Used when #b= is missing (e.g. macOS/Linux wails:// origin cannot navigate from this http gate page).
|
||||
function askMagpieRetry(why) {
|
||||
if (window.parent === window) return false;
|
||||
try {
|
||||
window.parent.postMessage({ magpie: 1, method: "error", params: { message: why || (zh ? "本地服务已断开" : "Local service disconnected") } }, "*");
|
||||
return true;
|
||||
} catch (e) { return false; }
|
||||
}
|
||||
// The Reconnect action of the end state on screen (null while none is): coming back to the page runs it once
|
||||
var ended = null;
|
||||
function wireReconnect(targetBack) {
|
||||
ended = btn.onclick = function () {
|
||||
if (btn.disabled) return;
|
||||
btn.disabled = true;
|
||||
if (targetBack) location.replace(targetBack);
|
||||
else location.reload();
|
||||
if (targetBack) { location.replace(targetBack); return; }
|
||||
// Framed in Magpie: ask the host to rebuild the plugin iframe; if it does not unload us, fall back to reload.
|
||||
if (askMagpieRetry()) {
|
||||
setTimeout(function () { location.reload(); }, 300);
|
||||
} else {
|
||||
location.reload();
|
||||
}
|
||||
};
|
||||
}
|
||||
if (!/^[0-9a-f]{32,128}$/i.test(token) || !(port > 0 && port < 65536 && Math.floor(port) === port)) {
|
||||
msg(
|
||||
"链接已失效。请点重新连接;若仍不行,可在 Magpie 顶栏先切到别的页再点回「Agent 控制台」。",
|
||||
"This link is no longer valid. Click Reconnect; if that fails, switch to another Magpie top-bar page, then open Agent Console again.",
|
||||
"链接已失效。请点重新连接;若仍不行,可在 Magpie「插件」页关闭再打开「Agent 控制台」。",
|
||||
"This link is no longer valid. Click Reconnect; if that fails, turn the Agent Console plugin off and on again in Magpie's Plugins page.",
|
||||
RECONNECT
|
||||
);
|
||||
wireReconnect(back || readStoredBack());
|
||||
var invalidBack = back || readStoredBack();
|
||||
wireReconnect(invalidBack);
|
||||
if (!invalidBack) askMagpieRetry(zh ? "链接已失效" : "This link is no longer valid");
|
||||
onReturn(function () { if (ended) ended(); });
|
||||
return;
|
||||
}
|
||||
@@ -139,11 +162,13 @@ const SCRIPT = String.raw`(function () {
|
||||
return;
|
||||
}
|
||||
msg(
|
||||
"本地服务已断开。请点重新连接;若仍不行,可在 Magpie 顶栏先切到别的页再点回「Agent 控制台」。",
|
||||
"The local service disconnected. Click Reconnect; if that fails, switch to another Magpie top-bar page, then open Agent Console again.",
|
||||
"本地服务已断开。请点重新连接;若仍不行,可在 Magpie「插件」页关闭再打开「Agent 控制台」。",
|
||||
"The local service disconnected. Click Reconnect; if that fails, turn the Agent Console plugin off and on again in Magpie's Plugins page.",
|
||||
RECONNECT
|
||||
);
|
||||
wireReconnect(null);
|
||||
// Magpie iframe with no usable #b=: notify the host immediately so its Try-again card appears (one click rebuilds the frame).
|
||||
askMagpieRetry(zh ? "本地服务已断开" : "Local service disconnected");
|
||||
return;
|
||||
}
|
||||
var go = function (auto) {
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.4",
|
||||
"version": "1.3.5",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.4",
|
||||
"version": "1.3.5",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "2.1.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.4",
|
||||
"version": "1.3.5",
|
||||
"description": "在 magpie 窗口里加一个「Agent 控制台」页面:用常驻本地服务驱动本机的 Agent CLI(Claude Code、Codex、Cursor 等),带结构化时间线。A Magpie page that drives local Agent CLIs (Claude Code, Codex, Cursor, and others) with a persistent local daemon and a structured timeline.",
|
||||
"author": "qingnian108 (https://github.com/qingnian108)",
|
||||
"homepage": "https://github.com/qingnian108/magpie-agent-console",
|
||||
|
||||
@@ -148,23 +148,43 @@ describe("self-heal back URL (host restart)", () => {
|
||||
[good + "#frag", good],
|
||||
["http://localhost:3425/_magpie/plugin/abc/page/index.html?x=1", "http://localhost:3425/_magpie/plugin/abc/page/index.html?x=1"],
|
||||
["http://[::1]:3430/_magpie/plugin/abc/index.html", "http://[::1]:3430/_magpie/plugin/abc/index.html"],
|
||||
// Windows Magpie desktop (exact host only)
|
||||
["http://wails.localhost/_magpie/plugin/abc/index.html", "http://wails.localhost/_magpie/plugin/abc/index.html"],
|
||||
["https://wails.localhost/_magpie/plugin/abc/page/index.html?x=1", null],
|
||||
["http://wails.localhost:8080/_magpie/plugin/a/index.html", null],
|
||||
["https://localhost:4430/_magpie/plugin/a/index.html", "https://localhost:4430/_magpie/plugin/a/index.html"],
|
||||
["http://wails.localhost/_magpie/plugin/abc/evil.html", null],
|
||||
["http://evil-wails.localhost/_magpie/plugin/abc/index.html", null],
|
||||
["http://wails.localhost.evil.com/_magpie/plugin/abc/index.html", null],
|
||||
["http://sub.wails.localhost/_magpie/plugin/abc/index.html", null],
|
||||
["https://evil.example/_magpie/plugin/abc/index.html", null],
|
||||
["http://127.0.0.1.evil.example/_magpie/plugin/abc/index.html", null],
|
||||
["http://user:pw@127.0.0.1:3430/_magpie/plugin/abc/index.html", null],
|
||||
["http://user:pw@wails.localhost/_magpie/plugin/abc/index.html", null],
|
||||
["javascript:alert(1)//127.0.0.1/_magpie/plugin/a/index.html", null],
|
||||
["file:///_magpie/plugin/abc/index.html", null],
|
||||
["wails://localhost/_magpie/plugin/abc/index.html", null], // macOS/Linux: no http nav from gate; use Magpie error postMessage
|
||||
["http://127.0.0.1:3430/other/index.html", null],
|
||||
["http://127.0.0.1:3430/_magpie/plugin/../../x/index.html", null],
|
||||
["http://127.0.0.1:3430/_magpie/plugin/abc/evil.html", null],
|
||||
["", null],
|
||||
];
|
||||
it("web and gate accept only a loopback Magpie plugin page", async () => {
|
||||
it("web and gate accept only Magpie plugin pages on loopback or exact wails.localhost", async () => {
|
||||
const { safeBackUrl } = await import(/* @vite-ignore */ gateUrl);
|
||||
for (const [input, want] of cases) {
|
||||
expect(webSafeBackUrl(input), input).toBe(want);
|
||||
expect(safeBackUrl(input), input).toBe(want);
|
||||
expect(webSafeBackUrl(input, "Windows NT 10.0"), input).toBe(want);
|
||||
expect(safeBackUrl(input, "win32"), input).toBe(want);
|
||||
}
|
||||
});
|
||||
it("rejects Windows virtual host on non-Windows, including the default platform / UA", async () => {
|
||||
const { safeBackUrl } = await import(/* @vite-ignore */ gateUrl);
|
||||
const win = "http://wails.localhost/_magpie/plugin/a/page/index.html";
|
||||
for (const os of ["linux", "darwin"]) expect(safeBackUrl(win, os)).toBeNull();
|
||||
for (const ua of ["Macintosh", "X11; Linux x86_64", ""]) expect(webSafeBackUrl(win, ua)).toBeNull();
|
||||
expect(safeBackUrl(win)).toBe(process.platform === "win32" ? win : null);
|
||||
const isWindows = /Windows/.test(typeof navigator !== "undefined" ? navigator.userAgent : "");
|
||||
expect(webSafeBackUrl(win)).toBe(isWindows ? win : null);
|
||||
});
|
||||
it("reads b= from the fragment next to the token", () => {
|
||||
expect(backUrlFromHash(`#t=abc&b=${encodeURIComponent(good)}`)).toBe(good);
|
||||
expect(backUrlFromHash("#t=abc")).toBeNull();
|
||||
@@ -191,6 +211,13 @@ describe("self-heal back URL (host restart)", () => {
|
||||
expect(bad.headers.location).toBe(`http://127.0.0.1:${port}/app?#t=${token}&p=${daemonPort}`);
|
||||
// without the key there's still nothing
|
||||
expect((await request(port, `/open?back=${encodeURIComponent(good)}`)).status).toBe(403);
|
||||
const wails = "http://wails.localhost/_magpie/plugin/tok123/index.html";
|
||||
const win = await request(port, `/open?k=${key}&back=${encodeURIComponent(wails)}`);
|
||||
expect(win.status).toBe(302);
|
||||
expect(win.headers.location).toBe(`http://127.0.0.1:${port}/app?#t=${token}&p=${daemonPort}` +
|
||||
(process.platform === "win32" ? `&b=${encodeURIComponent(wails)}` : ""));
|
||||
const lookalike = await request(port, `/open?k=${key}&back=${encodeURIComponent("http://evil-wails.localhost/_magpie/plugin/tok/index.html")}`);
|
||||
expect(lookalike.headers.location).toBe(`http://127.0.0.1:${port}/app?#t=${token}&p=${daemonPort}`);
|
||||
} finally {
|
||||
await gate.close();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { createAcpProvider } from "../../daemon/src/providers/acp/provider.js";
|
||||
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
describe("ACP explicit model pick vs default validation", () => {
|
||||
it("validates saved/default models but sends a newly enabled explicit pick beyond the startup snapshot", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "acp-model-switch-"));
|
||||
const log = join(dir, "config.jsonl");
|
||||
vi.stubEnv("FAKE_ACP_CONFIG_OPTIONS", JSON.stringify([
|
||||
{ id: "model", category: "model", type: "select", currentValue: "magpie/old", options: [{ value: "magpie/old" }] },
|
||||
]));
|
||||
vi.stubEnv("FAKE_ACP_CONFIG_LOG", log);
|
||||
const p = createAcpProvider({ id: "fake-model", name: "Fake ACP", binName: "fake-acp", acpArgs: [], installHint: "" });
|
||||
const session = await p.createSession({
|
||||
threadId: "t1", cwd: dir, model: "bogus-saved-model", mode: "default", effort: null, resumeId: null,
|
||||
launch: { cmd: process.execPath, prefixArgs: [resolve(__dirname, "fixtures/fake-acp-agent.mjs")] },
|
||||
});
|
||||
const calls = () => existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").map((x) => JSON.parse(x)) : [];
|
||||
try {
|
||||
await session.setModel("bogus-unprefixed-model");
|
||||
expect(calls()).toEqual([]); // Both startup and unchecked defaults are rejected.
|
||||
await session.setModel("magpie/old");
|
||||
expect(calls().map((c) => c.value)).toEqual(["magpie/old"]);
|
||||
await session.setModel("magpie/new", { force: true });
|
||||
expect(calls().map((c) => c.value)).toEqual(["magpie/old", "magpie/new"]);
|
||||
} finally {
|
||||
await session.close();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,7 @@
|
||||
// FAKE_ACP_CANCEL_SETTLE_MS Devin-like: after session/cancel, wait this many ms (emit STALE_FROM_TURN_1 chunk)
|
||||
// before settling cancelled. A new session/prompt that arrives while cancelling is
|
||||
// itself answered stopReason cancelled (0ms-resend race).
|
||||
// FAKE_ACP_CONFIG_OPTIONS JSON session/new config snapshot; FAKE_ACP_CONFIG_LOG logs set_config_option params
|
||||
// Every prompt is answered with one agent_message_chunk ("ok: <n> blocks") and stopReason end_turn.
|
||||
import { appendFileSync } from "node:fs";
|
||||
import { createInterface } from "node:readline";
|
||||
@@ -28,6 +29,8 @@ const caps = process.env.FAKE_ACP_PROMPT_CAPS ? JSON.parse(process.env.FAKE_ACP_
|
||||
const session = process.env.FAKE_ACP_SESSION ? JSON.parse(process.env.FAKE_ACP_SESSION) : {};
|
||||
const logFile = process.env.FAKE_ACP_LOG;
|
||||
const sessionLog = process.env.FAKE_ACP_SESSION_LOG;
|
||||
const configOptions = JSON.parse(process.env.FAKE_ACP_CONFIG_OPTIONS || "[]");
|
||||
const configLog = process.env.FAKE_ACP_CONFIG_LOG;
|
||||
const cancelLog = process.env.FAKE_ACP_CANCEL_LOG;
|
||||
const permMode = process.env.FAKE_ACP_PERM;
|
||||
const permLog = process.env.FAKE_ACP_PERM_LOG;
|
||||
@@ -78,7 +81,7 @@ createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
case "session/new": {
|
||||
const sessionId = "fake-session-1";
|
||||
logSession("session/new", sessionId);
|
||||
return answer(m.id, { sessionId });
|
||||
return answer(m.id, { sessionId, configOptions });
|
||||
}
|
||||
case "session/load": {
|
||||
if (!agentCapabilities.loadSession) {
|
||||
@@ -97,7 +100,8 @@ createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
case "session/set_mode":
|
||||
return answer(m.id, {});
|
||||
case "session/set_config_option":
|
||||
return answer(m.id, { configOptions: [] });
|
||||
if (configLog) appendFileSync(configLog, JSON.stringify(p) + "\n");
|
||||
return answer(m.id, { configOptions });
|
||||
case "session/prompt": {
|
||||
if (logFile) appendFileSync(logFile, JSON.stringify(p.prompt) + "\n");
|
||||
out({
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { parseCapabilities } from "../../daemon/src/providers/magpieGateway.js";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
const config = vi.hoisted(() => ({ base: "" }));
|
||||
vi.mock("node:fs/promises", async (importOriginal) => ({
|
||||
...await importOriginal<typeof import("node:fs/promises")>(),
|
||||
readFile: vi.fn(async () => JSON.stringify({ env: { ANTHROPIC_BASE_URL: config.base } })),
|
||||
}));
|
||||
|
||||
import {
|
||||
parseCapabilities,
|
||||
magpieTokenFor,
|
||||
magpieAgentId,
|
||||
filterToGatewayShown,
|
||||
fetchGatewayModelIds,
|
||||
magpieDefaultModel,
|
||||
} from "../../daemon/src/providers/magpieGateway.js";
|
||||
|
||||
describe("magpie gateway capability table", () => {
|
||||
it("effort / xhigh_effort / max_effort become levels", () => {
|
||||
@@ -15,3 +28,95 @@ describe("magpie gateway capability table", () => {
|
||||
expect(parseCapabilities("").size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("magpie per-agent gateway identity", () => {
|
||||
it("TokenFor matches Magpie gateway.TokenFor", () => {
|
||||
expect(magpieTokenFor("claude")).toBe("magpie-claude");
|
||||
expect(magpieTokenFor("codex")).toBe("magpie-codex");
|
||||
expect(magpieTokenFor("opencode")).toBe("magpie-opencode");
|
||||
expect(magpieTokenFor("pi")).toBe("magpie-pi");
|
||||
expect(magpieTokenFor("dsh")).toBe("magpie-dsh");
|
||||
});
|
||||
|
||||
it("provider ids map to Magpie agent ids (CatalogFor / HiddenModels keys)", () => {
|
||||
expect(magpieAgentId("claude")).toBe("claude");
|
||||
expect(magpieAgentId("codex")).toBe("codex");
|
||||
expect(magpieAgentId("opencode")).toBe("opencode");
|
||||
expect(magpieAgentId("pi")).toBe("pi");
|
||||
expect(magpieAgentId("dsh")).toBe("dsh");
|
||||
expect(magpieAgentId("cursor")).toBeNull();
|
||||
});
|
||||
|
||||
it("magpieDefaultModel never returns applied.json strings for dsh", async () => {
|
||||
expect(await magpieDefaultModel("dsh")).toBeNull();
|
||||
});
|
||||
|
||||
it("filterToGatewayShown drops models Magpie hid for the agent", () => {
|
||||
const list = [
|
||||
{ id: "hub-ccttt99/gpt-6.1-sol", name: "hub" },
|
||||
{ id: "deepseek/deepseek-flash", name: "flash" },
|
||||
{ id: "cursor/auto", name: "cursor" },
|
||||
];
|
||||
const shown = filterToGatewayShown(list, ["deepseek/deepseek-flash"], "");
|
||||
expect(shown.map((m) => m.id)).toEqual(["deepseek/deepseek-flash"]);
|
||||
});
|
||||
|
||||
it("filterToGatewayShown respects magpie/ prefix used by OpenCode / Pi", () => {
|
||||
const list = [
|
||||
{ id: "magpie/deepseek/deepseek-flash", name: "flash" },
|
||||
{ id: "magpie/cursor/auto", name: "cursor" },
|
||||
{ id: "local/other", name: "other" },
|
||||
];
|
||||
const shown = filterToGatewayShown(list, ["deepseek/deepseek-flash"], "magpie/");
|
||||
expect(shown.map((m) => m.id)).toEqual(["magpie/deepseek/deepseek-flash"]);
|
||||
});
|
||||
|
||||
it("filterToGatewayShown keeps Codex ChatGPT bare slugs that Magpie lists as codex/<slug>", () => {
|
||||
const list = [
|
||||
{ id: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
|
||||
{ id: "gpt-5-mini", name: "GPT-5 mini" },
|
||||
{ id: "deepseek/deepseek-flash", name: "flash" },
|
||||
];
|
||||
// Magpie CatalogFor("codex") shows ChatGPT-own as "codex/<slug>"; gpt-5-mini was hidden via ModelOff
|
||||
const shown = filterToGatewayShown(
|
||||
list,
|
||||
["codex/gpt-5.3-codex", "deepseek/deepseek-flash"],
|
||||
"",
|
||||
{ providerId: "codex" },
|
||||
);
|
||||
expect(shown.map((m) => m.id)).toEqual(["gpt-5.3-codex", "deepseek/deepseek-flash"]);
|
||||
});
|
||||
|
||||
it("rejects a gateway base with a loopback-looking hostile hostname", async () => {
|
||||
const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => ({ ok: true, json: async () => ({ data: [] }) }) as Response);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
config.base = "http://localhost.evil.com";
|
||||
try {
|
||||
await fetchGatewayModelIds("claude");
|
||||
expect(fetchMock.mock.calls[0]?.[0]).toBe("http://127.0.0.1:3425/v1/models");
|
||||
} finally {
|
||||
config.base = "";
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it("fetchGatewayModelIds sends TokenFor Authorization / x-api-key", async () => {
|
||||
const fetchMock = vi.fn<(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>>(async () => ({
|
||||
ok: true,
|
||||
json: async () => ({ data: [{ id: "deepseek/deepseek-flash" }, { id: "hub/hidden" }] }),
|
||||
} as Response));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
try {
|
||||
const ids = await fetchGatewayModelIds("claude");
|
||||
expect(ids).toEqual(["deepseek/deepseek-flash", "hub/hidden"]);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
const call = fetchMock.mock.calls[0]!;
|
||||
expect(String(call[0])).toMatch(/\/v1\/models$/);
|
||||
const headers = call[1]?.headers as Record<string, string>;
|
||||
expect(headers.Authorization).toBe("Bearer magpie-claude");
|
||||
expect(headers["x-api-key"]).toBe("magpie-claude");
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
magpieDefaultModel: vi.fn(async (_providerId: string): Promise<string | null> => "hub/model-a"),
|
||||
}));
|
||||
|
||||
vi.mock("../../daemon/src/providers/magpieGateway.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../../daemon/src/providers/magpieGateway.js")>();
|
||||
return {
|
||||
...actual,
|
||||
magpieDefaultModel: mocks.magpieDefaultModel,
|
||||
};
|
||||
});
|
||||
|
||||
import { AgentManager } from "../../daemon/src/agents/manager.js";
|
||||
import { ThreadsStore } from "../../daemon/src/store/threads.js";
|
||||
import { ProjectsStore } from "../../daemon/src/store/projects.js";
|
||||
import { SettingsStore } from "../../daemon/src/store/settings.js";
|
||||
import { AttachmentStore } from "../../daemon/src/store/attachments.js";
|
||||
import { Gateway } from "../../daemon/src/ws/gateway.js";
|
||||
import { initProviders } from "../../daemon/src/providers/registry.js";
|
||||
import { MockSession, mockProviderMetrics } from "../../daemon/src/providers/mock.js";
|
||||
import type { Config } from "../../daemon/src/config.js";
|
||||
|
||||
process.env.AGENT_CONSOLE_MOCK = "1";
|
||||
|
||||
const cfg: Config = { port: 0, dataDir: "", token: "t", version: "0.0.0", idleExitMinutes: 60, buildStamp: "0" };
|
||||
|
||||
let dir: string;
|
||||
let threads: ThreadsStore;
|
||||
let projects: ProjectsStore;
|
||||
let settings: SettingsStore;
|
||||
let gw: Gateway;
|
||||
let manager: AgentManager;
|
||||
let threadId: string;
|
||||
let setModelSpy: ReturnType<typeof vi.spyOn>;
|
||||
let sendSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = mkdtempSync(join(tmpdir(), "ac-defmodel-"));
|
||||
mockProviderMetrics.createSessionCalls = 0;
|
||||
mocks.magpieDefaultModel.mockReset();
|
||||
mocks.magpieDefaultModel.mockResolvedValue("hub/model-a");
|
||||
threads = new ThreadsStore(dir);
|
||||
projects = new ProjectsStore(dir);
|
||||
settings = new SettingsStore(dir);
|
||||
gw = new Gateway(cfg);
|
||||
initProviders();
|
||||
manager = new AgentManager(gw, threads, projects, settings, new AttachmentStore(join(dir, "attachments")));
|
||||
const proj = await projects.create(dir);
|
||||
const meta = await threads.create({ projectId: proj.id, provider: "mock" });
|
||||
threadId = meta.id;
|
||||
setModelSpy = vi.spyOn(MockSession.prototype, "setModel");
|
||||
sendSpy = vi.spyOn(MockSession.prototype, "send");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setModelSpy.mockRestore();
|
||||
sendSpy.mockRestore();
|
||||
manager.shutdown();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
const waitFor = async (fn: () => boolean | Promise<boolean>, ms = 15000) => {
|
||||
const t0 = Date.now();
|
||||
while (Date.now() - t0 < ms) {
|
||||
if (await fn()) return;
|
||||
await sleep(40);
|
||||
}
|
||||
throw new Error("waitFor timeout");
|
||||
};
|
||||
|
||||
describe("AgentManager Magpie default-model sync", () => {
|
||||
it("starts「默认」session with Magpie default, syncs on next idle send, and setModel(null) resolves again", async () => {
|
||||
// First turn: createSession gets hub/model-a (no prior setModel needed)
|
||||
await manager.send(threadId, { text: "hi" });
|
||||
await waitFor(async () => (await threads.get(threadId))?.status === "idle");
|
||||
expect(mockProviderMetrics.createSessionCalls).toBe(1);
|
||||
// turn_started uses o.model from createSession
|
||||
const evs1 = await threads.readEvents(threadId, 0, 50000);
|
||||
const started1 = evs1.find((e) => e.type === "turn_started") as { model?: string | null } | undefined;
|
||||
expect(started1?.model).toBe("hub/model-a");
|
||||
expect(mocks.magpieDefaultModel).toHaveBeenCalled();
|
||||
|
||||
// Magpie default changes while idle
|
||||
mocks.magpieDefaultModel.mockResolvedValue("hub/model-b");
|
||||
setModelSpy.mockClear();
|
||||
sendSpy.mockClear();
|
||||
|
||||
await manager.send(threadId, { text: "again" });
|
||||
await waitFor(async () => (await threads.get(threadId))?.status === "idle");
|
||||
|
||||
// syncDefaultModelIfNeeded must call setModel before send
|
||||
expect(setModelSpy).toHaveBeenCalled();
|
||||
expect(setModelSpy.mock.calls[0]).toEqual(["hub/model-b"]);
|
||||
const setOrder = setModelSpy.mock.invocationCallOrder[0]!;
|
||||
const sendOrder = sendSpy.mock.invocationCallOrder[0]!;
|
||||
expect(setOrder).toBeLessThan(sendOrder);
|
||||
|
||||
// Explicit pick
|
||||
setModelSpy.mockClear();
|
||||
await manager.setModel(threadId, "magpie/newly-enabled");
|
||||
expect(setModelSpy.mock.calls).toEqual([["magpie/newly-enabled", { force: true }]]);
|
||||
expect((await threads.get(threadId))?.model).toBe("magpie/newly-enabled");
|
||||
|
||||
// Back to「默认」→ resolve current Magpie default (hub/model-b)
|
||||
setModelSpy.mockClear();
|
||||
await manager.setModel(threadId, null);
|
||||
expect(setModelSpy.mock.calls).toEqual([["hub/model-b"]]);
|
||||
expect((await threads.get(threadId))?.model).toBeNull();
|
||||
}, 30000);
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { Provider } from "../../daemon/src/providers/types.js";
|
||||
|
||||
const home = vi.hoisted(() => ({ path: "" }));
|
||||
vi.mock("node:os", async (importOriginal) => ({
|
||||
...await importOriginal<typeof import("node:os")>(),
|
||||
homedir: () => home.path,
|
||||
}));
|
||||
import { cachedModels, clearProviderCache } from "../../daemon/src/providers/infoCache.js";
|
||||
import { magpieConfigFingerprint } from "../../daemon/src/providers/magpieGateway.js";
|
||||
|
||||
let tick: number;
|
||||
beforeEach(() => {
|
||||
home.path = mkdtempSync(join(tmpdir(), "ac-cache-fp-"));
|
||||
tick = 2000;
|
||||
clearProviderCache();
|
||||
});
|
||||
afterEach(() => {
|
||||
clearProviderCache();
|
||||
rmSync(home.path, { recursive: true, force: true });
|
||||
});
|
||||
function change(file: string) {
|
||||
const path = join(home.path, file);
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, "{}");
|
||||
// Deterministic mtime changes; no filesystem timestamp resolution or sleep dependency.
|
||||
utimesSync(path, tick, tick++);
|
||||
}
|
||||
function fake(id: string) {
|
||||
const listModels = vi.fn(async () => [{ id: "native/model", name: "Native" }]);
|
||||
return { id, listModels } as unknown as Provider & { listModels: typeof listModels };
|
||||
}
|
||||
|
||||
describe("per-provider Magpie model cache fingerprint", () => {
|
||||
it("a change during listing invalidates the very next read (pre-list fingerprint)", async () => {
|
||||
let enter!: () => void;
|
||||
let release!: () => void;
|
||||
const entered = new Promise<void>((r) => { enter = r; });
|
||||
const barrier = new Promise<void>((r) => { release = r; });
|
||||
const p = fake("claude");
|
||||
p.listModels.mockImplementationOnce(async () => {
|
||||
enter();
|
||||
await barrier;
|
||||
return [{ id: "stale/model", name: "Stale" }];
|
||||
});
|
||||
const first = cachedModels(p);
|
||||
await entered;
|
||||
change(".claude/settings.json");
|
||||
release();
|
||||
expect((await first)[0].id).toBe("stale/model");
|
||||
expect((await cachedModels(p))[0].id).toBe("native/model");
|
||||
expect(p.listModels).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[".claude/settings.json", ["claude"]],
|
||||
[".codex/models.json", ["codex"]],
|
||||
[".config/magpie/settings.json", ["claude", "codex", "dsh"]],
|
||||
])("%s invalidates only relevant providers", async (file, invalidated) => {
|
||||
const providers = ["claude", "codex", "dsh", "cursor", "copilot", "devin"].map(fake);
|
||||
await Promise.all(providers.map((p) => cachedModels(p)));
|
||||
change(file);
|
||||
await Promise.all(providers.map((p) => cachedModels(p)));
|
||||
for (const p of providers) {
|
||||
expect(p.listModels, p.id).toHaveBeenCalledTimes(invalidated.includes(p.id) ? 2 : 1);
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["cursor", "copilot", "devin"])("%s has no Magpie-overlay fingerprint", async (id) => {
|
||||
change(".config/magpie/applied.json");
|
||||
expect(await magpieConfigFingerprint(id)).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -51,3 +51,21 @@ describe("Provider info cache", () => {
|
||||
expect(dropPlaceholder([{ id: "gpt", name: "GPT" }])).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Codex modelCache clears with clearProviderCache", () => {
|
||||
it("registerProviderCacheClear hook runs for codex and for a full clear", async () => {
|
||||
const { registerProviderCacheClear, clearProviderCache } = await import("../../daemon/src/providers/infoCache.js");
|
||||
const { clearCodexModelCache } = await import("../../daemon/src/providers/codex/provider.js");
|
||||
// clearCodexModelCache is idempotent; calling clearProviderCache must invoke registered hooks
|
||||
let hits = 0;
|
||||
registerProviderCacheClear((id) => {
|
||||
if (!id || id === "codex") {
|
||||
clearCodexModelCache();
|
||||
hits++;
|
||||
}
|
||||
});
|
||||
clearProviderCache("codex");
|
||||
clearProviderCache();
|
||||
expect(hits).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,7 +14,7 @@ type Msg = { source: unknown; data: unknown };
|
||||
async function runWrapper(
|
||||
hash: string,
|
||||
search = "",
|
||||
opts: { visible?: boolean; sessionStorage?: Record<string, string> } = {},
|
||||
opts: { visible?: boolean; sessionStorage?: Record<string, string>; framed?: boolean; ua?: string } = {},
|
||||
) {
|
||||
const { wrapperHtml, WRAP_TIMING } = await import(/* @vite-ignore */ wrapperUrl);
|
||||
const html: string = wrapperHtml("n0nce", WRAP_TIMING);
|
||||
@@ -50,21 +50,39 @@ async function runWrapper(
|
||||
else (winOn[t] ??= []).push(fn as unknown as () => void);
|
||||
},
|
||||
};
|
||||
// Magpie hosts the wrapper in an iframe (parent !== window). Top-level /app uses framed: false.
|
||||
if (opts.framed === false) win.parent = win;
|
||||
const doc = {
|
||||
getElementById: (id: string) => els[id], documentElement: { className: "" },
|
||||
visibilityState: opts.visible === false ? "hidden" : "visible",
|
||||
addEventListener: (t: string, fn: () => void) => { (docOn[t] ??= []).push(fn); },
|
||||
};
|
||||
const DateFake = { now: () => now };
|
||||
const fn = new Function("window", "document", "location", "setInterval", "Date", "URL", "URLSearchParams", "sessionStorage", script);
|
||||
fn(win, doc, loc, (f: () => void) => { intervals.push(f); return 1; }, DateFake, URL, URLSearchParams, sessionStorage);
|
||||
const tick = (ms: number, step = 1000) => { for (let t = 0; t < ms; t += step) { now += step; intervals.forEach((f) => f()); } };
|
||||
type TO = { at: number; fn: () => void };
|
||||
const timeouts: TO[] = [];
|
||||
const setTimeoutFake = (f: () => void, ms = 0) => { timeouts.push({ at: now + ms, fn: f }); return timeouts.length; };
|
||||
const flushTimeouts = () => {
|
||||
let ran = true;
|
||||
while (ran) {
|
||||
ran = false;
|
||||
for (let i = timeouts.length - 1; i >= 0; i--) {
|
||||
if (timeouts[i]!.at <= now) {
|
||||
const t = timeouts.splice(i, 1)[0]!;
|
||||
t.fn();
|
||||
ran = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
const fn = new Function("window", "document", "location", "setInterval", "setTimeout", "Date", "URL", "URLSearchParams", "sessionStorage", "navigator", script);
|
||||
fn(win, doc, loc, (f: () => void) => { intervals.push(f); return 1; }, setTimeoutFake, DateFake, URL, URLSearchParams, sessionStorage, { userAgent: opts.ua ?? "X11; Linux x86_64" });
|
||||
const tick = (ms: number, step = 1000) => { for (let t = 0; t < ms; t += step) { now += step; intervals.forEach((f) => f()); flushTimeouts(); } };
|
||||
return {
|
||||
els, loc, childWin, parentWin, tick, doc, store,
|
||||
els, loc, childWin, parentWin, tick, doc, store, flushTimeouts,
|
||||
fromChild: (data: unknown) => onMessage({ source: childWin, data }),
|
||||
fromParent: (data: unknown) => onMessage({ source: parentWin, data }),
|
||||
fromOther: (data: unknown) => onMessage({ source: {}, data }),
|
||||
jump: (ms: number) => { now += ms; },
|
||||
jump: (ms: number) => { now += ms; flushTimeouts(); },
|
||||
hide: () => { doc.visibilityState = "hidden"; (docOn.visibilitychange ?? []).forEach((f) => f()); },
|
||||
show: () => { doc.visibilityState = "visible"; (docOn.visibilitychange ?? []).forEach((f) => f()); },
|
||||
focus: () => { (winOn.focus ?? []).forEach((f) => f()); },
|
||||
@@ -140,7 +158,7 @@ describe("wrapper page", () => {
|
||||
expect(w2.els.r!.textContent).toBe("Reconnect");
|
||||
expect(w2.els.s!.textContent).toContain("Click Reconnect");
|
||||
|
||||
const w3 = await runWrapper(hash({ t: TOKEN, p: "4321", b: "https://evil.example/_magpie/plugin/a/index.html" }));
|
||||
const w3 = await runWrapper(hash({ t: TOKEN, p: "4321", b: "https://evil.example/_magpie/plugin/a/index.html" }), "", { framed: false });
|
||||
expect(w3.store.has("ac_wrap_back")).toBe(false);
|
||||
w3.fromChild({ ac_console: "lost", at: 5 });
|
||||
expect(w3.loc.replaced).toBeNull();
|
||||
@@ -228,30 +246,91 @@ describe("wrapper page", () => {
|
||||
|
||||
it("ignores an unsafe sessionStorage back and still offers Reconnect via reload", async () => {
|
||||
const evil = "https://evil.example/_magpie/plugin/a/index.html";
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321" }), "?lang=en", { sessionStorage: { ac_wrap_back: evil } });
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321" }), "?lang=en", { sessionStorage: { ac_wrap_back: evil }, framed: false });
|
||||
w.fromChild({ ac_console: "lost", at: 1 });
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
expect(w.els.r!.hidden).toBe(false);
|
||||
expect(w.els.r!.textContent).toBe("Reconnect");
|
||||
expect(w.els.s!.textContent).toMatch(/Click Reconnect/);
|
||||
expect(w.els.s!.textContent).toMatch(/top-bar/);
|
||||
expect(w.els.s!.textContent).toMatch(/Plugins page/);
|
||||
expect(w.els.s!.textContent).not.toMatch(/top-bar/);
|
||||
w.els.r!.onclick!();
|
||||
expect(w.loc.reloaded).toBe(1);
|
||||
});
|
||||
|
||||
it("with no back at all, Reconnect reloads and the copy explains the Magpie top-bar fallback", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321" }));
|
||||
it("with no back at all (top-level), Reconnect reloads and the copy points at Magpie Plugins", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321" }), "", { framed: false });
|
||||
w.fromChild({ ac_console: "lost", at: 1 });
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
expect(w.els.r!.hidden).toBe(false);
|
||||
expect(w.els.r!.textContent).toBe("重新连接");
|
||||
expect(w.els.s!.textContent).toContain("重新连接");
|
||||
expect(w.els.s!.textContent).toContain("Agent 控制台");
|
||||
expect(w.els.s!.textContent).toContain("顶栏");
|
||||
expect(w.els.s!.textContent).toContain("插件");
|
||||
expect(w.els.s!.textContent).not.toContain("顶栏");
|
||||
expect(w.parentWin.posted).toEqual([]);
|
||||
w.els.r!.onclick!();
|
||||
expect(w.loc.reloaded).toBe(1);
|
||||
});
|
||||
|
||||
it("with no back in a Magpie iframe, auto-notifies the parent with method error and Reconnect does too", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321" }));
|
||||
w.fromChild({ ac_console: "lost", at: 1 });
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
expect(w.els.r!.hidden).toBe(false);
|
||||
expect(w.parentWin.posted).toEqual([
|
||||
{ magpie: 1, method: "error", params: { message: "本地服务已断开" } },
|
||||
]);
|
||||
w.parentWin.posted.length = 0;
|
||||
w.els.r!.onclick!();
|
||||
expect(w.parentWin.posted).toEqual([
|
||||
{ magpie: 1, method: "error", params: { message: "本地服务已断开" } },
|
||||
]);
|
||||
expect(w.loc.reloaded).toBe(0);
|
||||
w.tick(300);
|
||||
expect(w.loc.reloaded).toBe(1);
|
||||
});
|
||||
|
||||
it("Windows wails.localhost #b= is kept and recover navigates back through it", async () => {
|
||||
const WAILS = "http://wails.localhost/_magpie/plugin/abc123/index.html";
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: WAILS }), "", { ua: "Windows NT 10.0" });
|
||||
expect(w.store.get("ac_wrap_back")).toBe(WAILS);
|
||||
w.fromChild({ ac_console: "lost", at: 42 });
|
||||
const u = new URL(w.loc.replaced!);
|
||||
expect(u.origin + u.pathname).toBe("http://wails.localhost/_magpie/plugin/abc123/index.html");
|
||||
expect(u.searchParams.get("ac_lost")).toBe("42");
|
||||
expect(u.searchParams.get("ac_try")).toMatch(/^\d+\.1$/);
|
||||
});
|
||||
|
||||
it("Windows wails.localhost: after max auto tries, Reconnect still replaces to #b=", async () => {
|
||||
const WAILS = "http://wails.localhost/_magpie/plugin/tok/page/index.html";
|
||||
const start = 1_800_000_000_000 - 30_000;
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: WAILS }), `?ac_try=${start}.3`, { ua: "Windows NT 10.0" });
|
||||
w.fromChild({ ac_console: "lost", at: 1 });
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
w.els.r!.onclick!();
|
||||
expect(w.loc.replaced!.startsWith("http://wails.localhost/_magpie/plugin/tok/page/index.html")).toBe(true);
|
||||
expect(new URL(w.loc.replaced!).searchParams.has("ac_try")).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["https://wails.localhost/_magpie/plugin/a/page/index.html", "Windows NT 10.0"],
|
||||
["http://wails.localhost:8080/_magpie/plugin/a/index.html", "Windows NT 10.0"],
|
||||
["http://wails.localhost/_magpie/plugin/a/index.html", "Macintosh"],
|
||||
["http://wails.localhost/_magpie/plugin/a/index.html", "X11; Linux"],
|
||||
["http://evil-wails.localhost/_magpie/plugin/a/index.html", "Windows NT 10.0"],
|
||||
["http://wails.localhost.evil.com/_magpie/plugin/a/index.html", "Windows NT 10.0"],
|
||||
])("rejects unsafe Wails back %s (%s), from hash and storage", async (back, ua) => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: back }), "", {
|
||||
ua, framed: false, sessionStorage: { ac_wrap_back: back },
|
||||
});
|
||||
w.fromChild({ ac_console: "lost", at: 42 });
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
w.els.r!.onclick!();
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
expect(w.loc.reloaded).toBe(1);
|
||||
});
|
||||
|
||||
it("an invalid link with only a stored back still Reconnects through Magpie", async () => {
|
||||
const w = await runWrapper(hash({ t: "nope", p: "1" }), "", { sessionStorage: { ac_wrap_back: BACK } });
|
||||
expect(w.els.f!.src).toBe("");
|
||||
@@ -358,8 +437,8 @@ describe("wrapper page", () => {
|
||||
expect(w.loc.replaced).toBeNull(); // already on its way: not twice
|
||||
});
|
||||
|
||||
it("no back at all: coming back to the end state reloads like the button", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321" }));
|
||||
it("no back at all (top-level): coming back to the end state reloads like the button", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321" }), "", { framed: false });
|
||||
w.fromChild({ ac_console: "lost", at: 1 });
|
||||
expect(w.loc.reloaded).toBe(0);
|
||||
w.focus();
|
||||
@@ -369,12 +448,25 @@ describe("wrapper page", () => {
|
||||
expect(w.loc.reloaded).toBe(1);
|
||||
});
|
||||
|
||||
it("no back in Magpie iframe: coming back re-asks the parent (then reload fallback)", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321" }));
|
||||
w.fromChild({ ac_console: "lost", at: 1 });
|
||||
w.parentWin.posted.length = 0;
|
||||
w.focus();
|
||||
expect(w.parentWin.posted).toEqual([
|
||||
{ magpie: 1, method: "error", params: { message: "本地服务已断开" } },
|
||||
]);
|
||||
expect(w.loc.reloaded).toBe(0);
|
||||
w.tick(300);
|
||||
expect(w.loc.reloaded).toBe(1);
|
||||
});
|
||||
|
||||
it("invalid link: coming back runs Reconnect through the stored back; unsafe stored back is never followed", async () => {
|
||||
const w = await runWrapper(hash({ t: "nope", p: "1" }), "", { sessionStorage: { ac_wrap_back: BACK } });
|
||||
w.show();
|
||||
expect(w.loc.replaced).toBe(BACK);
|
||||
const evil = await runWrapper(hash({ t: "nope", p: "1", b: "https://evil.example/_magpie/plugin/a/index.html" }), "",
|
||||
{ sessionStorage: { ac_wrap_back: "http://evil.example/_magpie/plugin/a/index.html" } });
|
||||
{ sessionStorage: { ac_wrap_back: "http://evil.example/_magpie/plugin/a/index.html" }, framed: false });
|
||||
evil.focus();
|
||||
expect(evil.loc.replaced).toBeNull();
|
||||
expect(evil.loc.reloaded).toBe(1);
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
// Self-heal after the plugin host restarts (Magpie restarts its Bun plugin host from time to time; the old host's daemon exits with it
|
||||
// and the gate key / port change). This page was opened by the gate with the Magpie plugin page URL in the fragment (#t=…&b=…).
|
||||
// When the daemon can't be reached for a few seconds, the page goes back to that Magpie page: boot.js reads the fresh session.js and
|
||||
// opens the new gate, which starts a new daemon. Only a loopback Magpie plugin page URL is ever followed (no open redirect),
|
||||
// opens the new gate, which starts a new daemon. Only a Magpie plugin page URL on loopback or exact wails.localhost is ever followed (no open redirect),
|
||||
// and the token is never put anywhere but this page's own fragment.
|
||||
|
||||
/** The same check as lib/gate.mjs safeBackUrl: http(s), loopback host, no credentials, /_magpie/plugin/<id>/[page/]index.html */
|
||||
export function safeBackUrl(raw: string | null | undefined): string | null {
|
||||
/** Same check as lib/gate.mjs safeBackUrl: http(s), loopback or exact wails.localhost, no credentials, /_magpie/plugin/<id>/[page/]index.html */
|
||||
export function safeBackUrl(raw: string | null | undefined, ua = typeof navigator !== "undefined" ? navigator.userAgent : ""): string | null {
|
||||
if (typeof raw !== "string" || !raw || raw.length > 2048) return null;
|
||||
let u: URL;
|
||||
try { u = new URL(raw); } catch { return null; }
|
||||
if (u.protocol !== "http:" && u.protocol !== "https:") return null;
|
||||
if (u.username || u.password) return null;
|
||||
const host = u.hostname.toLowerCase();
|
||||
if (host !== "127.0.0.1" && host !== "localhost" && host !== "[::1]") return null;
|
||||
const loopback = host === "127.0.0.1" || host === "localhost" || host === "[::1]";
|
||||
const magpieWin = /Windows/.test(ua) && host === "wails.localhost" && u.protocol === "http:" && u.port === "";
|
||||
if (!loopback && !magpieWin) return null;
|
||||
if (!/^\/_magpie\/plugin\/[A-Za-z0-9_-]{1,128}\/(?:page\/)?index\.html$/.test(u.pathname)) return null;
|
||||
return `${u.protocol}//${u.host}${u.pathname}${u.search}`;
|
||||
}
|
||||
|
||||
@@ -48,6 +48,9 @@ export function Composer() {
|
||||
const [agentPop, setAgentPop] = useState(false);
|
||||
const [pickerProviderId, setPickerProviderId] = useState<string | null>(null);
|
||||
const [modelQ, setModelQ] = useState("");
|
||||
const [modelsRefreshing, setModelsRefreshing] = useState(false);
|
||||
const modelsRefreshSeq = useRef(0);
|
||||
const modelsForceSeq = useRef(0);
|
||||
const pickerRef = useRef<HTMLDivElement>(null);
|
||||
const taRef = useRef<HTMLTextAreaElement>(null);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
@@ -114,11 +117,40 @@ export function Composer() {
|
||||
const providerOk = (p: (typeof visibleProviders)[0]) =>
|
||||
p.enabled !== false && p.available && p.status !== "planned";
|
||||
|
||||
/** Soft sync (silent) or forced ↻ refresh; Magpie config mtime invalidates the daemon cache automatically.
|
||||
* Soft sync never disables ↻; a forced click is never coalesced onto an in-flight soft sync. */
|
||||
const refreshModels = (opts?: { force?: boolean; provider?: string | null }) => {
|
||||
const force = !!opts?.force;
|
||||
const seq = ++modelsRefreshSeq.current;
|
||||
let forceSeq = 0;
|
||||
if (force) {
|
||||
forceSeq = ++modelsForceSeq.current;
|
||||
setModelsRefreshing(true);
|
||||
}
|
||||
const args: { refresh?: boolean; provider?: string } = {};
|
||||
if (force) args.refresh = true;
|
||||
if (opts?.provider) args.provider = opts.provider;
|
||||
return (ws.call("providers.list", Object.keys(args).length ? args : undefined) as Promise<import("../types/models").ProviderInfo[]>)
|
||||
.then((list) => {
|
||||
if (seq !== modelsRefreshSeq.current) return; // a newer soft/force request won
|
||||
useData.setState({ providers: list });
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
// Soft sync must not clear (or leave stuck) the forced spinner
|
||||
if (force && forceSeq === modelsForceSeq.current) setModelsRefreshing(false);
|
||||
});
|
||||
};
|
||||
|
||||
const openPicker = (open: boolean) => {
|
||||
setAgentPop(open);
|
||||
if (open) {
|
||||
setPickerProviderId(null);
|
||||
setModelQ("");
|
||||
// Opening the picker: silent soft sync (does not disable ↻)
|
||||
void refreshModels({
|
||||
provider: started ? (thread?.provider ?? null) : null,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -590,6 +622,23 @@ export function Composer() {
|
||||
value={modelQ}
|
||||
onChange={(e) => setModelQ(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className={`ap-refresh${modelsRefreshing ? " spinning" : ""}`}
|
||||
title={modelsRefreshing ? tr("composer.refreshingModels") : tr("composer.refreshModels")}
|
||||
aria-label={tr("composer.refreshModels")}
|
||||
disabled={modelsRefreshing}
|
||||
onMouseDown={(ev) => ev.preventDefault()}
|
||||
onClick={() => {
|
||||
// Inside an Agent's model list: refresh only that provider (avoids waiting on every CLI)
|
||||
void refreshModels({
|
||||
force: true,
|
||||
provider: inModelList ? (pickerProviderId ?? thread?.provider ?? null) : null,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Icon name="refresh" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{modelQ.trim() ? (
|
||||
|
||||
@@ -86,6 +86,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
agentLockedHint: "已开始的对话不能更换 Agent;要用别的 Agent 请新建对话。",
|
||||
providersLoading: "正在检测 Agent…", moreModels: "还有 {n} 个模型,请用上方搜索",
|
||||
pickModel: "选择模型", noModelMatch: "没有匹配的模型",
|
||||
refreshModels: "刷新模型列表", refreshingModels: "正在刷新…",
|
||||
// Options below the composer are English throughout (as in Paseo); hint text stays Chinese
|
||||
defaultModel: "默认", defaultEffort: "默认", defaultEffortNamed: "默认({level})",
|
||||
effortTitle: "思考强度", modeTitle: "权限模式", attachTitle: "附件(图片/文本)",
|
||||
@@ -306,6 +307,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
agentLockedHint: "The agent can't change after the conversation starts. Start a new conversation to use another agent.",
|
||||
providersLoading: "Detecting agents…", moreModels: "{n} more models — use search above",
|
||||
pickModel: "Choose model", noModelMatch: "No matching models",
|
||||
refreshModels: "Refresh models", refreshingModels: "Refreshing…",
|
||||
defaultModel: "Default", defaultEffort: "Default", defaultEffortNamed: "Default ({level})",
|
||||
effortTitle: "Reasoning effort", modeTitle: "Permission mode", attachTitle: "Attachments (images / text)",
|
||||
failSwitchAgent: "Could not switch agent: ", failSend: "Send failed: ",
|
||||
|
||||
@@ -142,6 +142,17 @@
|
||||
font-size: var(--fs-s); color: var(--fg);
|
||||
}
|
||||
.agent-picker .ap-search-in::placeholder { color: var(--muted); }
|
||||
.agent-picker .ap-refresh {
|
||||
flex: none; width: 24px; height: 24px; margin: -2px -4px -2px 0; padding: 0;
|
||||
border: 0; border-radius: var(--r-s); background: transparent; color: var(--muted);
|
||||
display: inline-flex; align-items: center; justify-content: center; cursor: pointer;
|
||||
}
|
||||
.agent-picker .ap-refresh:hover:not(:disabled) { color: var(--fg); background: var(--surface-hover); }
|
||||
.agent-picker .ap-refresh:disabled { opacity: .45; cursor: default; }
|
||||
.agent-picker .ap-refresh.spinning svg { animation: ac-spin .8s linear infinite; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.agent-picker .ap-refresh.spinning svg { animation-duration: 2.4s; }
|
||||
}
|
||||
.agent-picker .ap-scroll {
|
||||
overflow-y: auto; padding: 4px; flex: 1; min-height: 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user