gui: Google Vertex AI is added and edited with its Google Cloud project, location, credentials file and service account in place of a key
The Add sheet's Google Vertex AI tile opens an editor with Project ID, Location, Credentials file and Service account where another provider's has API key. The project is focused first, and a Save without one is refused in the page's language. Endpoints shows the address the project and location make as they are typed (Gemini generateContent), with its Test, and is hidden until there is a project to make one of. Refresh and Test before a Save ask with the values typed, spelled as a Save keeps them (typed, Vertex.Normal); an edit that sends none keeps the saved ones. The Providers row's pill names the service account requests go as, else the credentials file, else "Google ADC", and "needs a project" until it has one, never "needs a key". Add another and Duplicate say they carry the project and credentials. zh, ja and de.
This commit is contained in:
@@ -4889,6 +4889,14 @@ function renderProviders() {
|
||||
const plan = accountPlan(p.account), bare = plan.startsWith(p.name + " ") ? plan.slice(p.name.length + 1) : "";
|
||||
key = el("span", "key acct", bare && plan.length > 15 ? bare : plan);
|
||||
key.title = t("{agent} is signed in; its models are here for every other agent", { agent: p.account.agentName });
|
||||
} else if (p.vertex) {
|
||||
// Vertex AI signs with the user's Google credentials, never a key;
|
||||
// the pill says which: the service account it acts as, else the
|
||||
// credentials file, else Application Default Credentials (ADC)
|
||||
const v = p.vertex;
|
||||
key = el("span", "key " + (p.ready ? "acct" : "none"), !p.ready ? t("needs a project") : v.impersonate || (v.credentials ? baseName(v.credentials) : t("Google ADC")));
|
||||
key.title = !p.ready ? t("Open the row and give your Google Cloud project's id")
|
||||
: (v.impersonate ? t("Signed as the service account {account}, with your Google credentials", { account: v.impersonate }) : t("Signed with your Google credentials")) + " · " + (v.credentials || t("Application Default Credentials"));
|
||||
} else {
|
||||
key = el("span", "key " + (p.key.set ? (keyPill(p) === p.key.masked ? "on" : "on acct") : p.ready ? "free" : "none"), p.key.set ? keyPill(p) : p.ready ? t("no key") : t("needs a key"));
|
||||
key.title = p.key.set ? t("API key {masked}", { masked: p.key.masked }) : p.ready ? t("Local servers need no key") : t("Open the row and paste an API key");
|
||||
@@ -7243,6 +7251,9 @@ function asTyped() {
|
||||
const body = { typed: true, key: keys.length > 1 ? keys[0] : (draft.key || "").trim(), chat: (draft.chat || "").trim(), responses: (draft.responses || "").trim(), anthropic: (draft.anthropic || "").trim(), gemini: (draft.gemini || "").trim(), modelsURL: (draft.modelsURL || "").trim() };
|
||||
// a System One base is asked at POST …/systemone, not on the three APIs
|
||||
if (draft.api === "decide") body.decide = (draft.decide || "").trim();
|
||||
// a Vertex AI provider is asked at the project typed, with the
|
||||
// credentials typed, as a pasted key is
|
||||
if (draft.vertex) body.vertex = vertexOfDraft();
|
||||
if (draft.headers) body.headers = headersOf(draft.headers);
|
||||
const proxy = draft.proxyMode === undefined ? null : proxyOfDraft();
|
||||
if (proxy !== null) body.proxy = proxy;
|
||||
@@ -7801,8 +7812,25 @@ function slide(box, key) {
|
||||
}
|
||||
|
||||
const PROTOS = [["chat", "OpenAI", "Chat Completions — most agents"], ["responses", "Responses", "OpenAI Responses — what Codex speaks"], ["anthropic", "Anthropic", "Anthropic Messages — what Claude Code speaks"], ["gemini", "Gemini", "Gemini generateContent — what the Gemini CLI speaks"], ["decide", "System One", "A decision API on System One (TypeSafe's Jev, a gateway's, or Bailian's decision model) — what a routing group asks as a turn begins"]];
|
||||
// Gemini generateContent at a Vertex AI provider's project, as its
|
||||
// endpoint is shown and tested
|
||||
const VERTEX_EP_HINT = "Gemini generateContent — what Vertex AI serves at your Google Cloud project";
|
||||
// apiLabel: the name an API (a protocol) goes by in the editor
|
||||
const apiLabel = (proto) => (PROTOS.find(([k]) => k === proto) || [])[1] || proto;
|
||||
// vertexBase is where a Vertex AI provider's requests go, the address its
|
||||
// project and location make (provider.vertexBase): "" until the project
|
||||
// typed is one an address can be made of
|
||||
function vertexBase(v) {
|
||||
const project = (v?.project || "").trim().toLowerCase(), loc = (v?.location || "").trim().toLowerCase() || "global";
|
||||
if (!/^[a-z0-9][a-z0-9.:-]*[a-z0-9]$/.test(project) || !/^[a-z]+(-[a-z0-9]+)*$/.test(loc)) return "";
|
||||
const host = loc === "global" ? "aiplatform.googleapis.com" : loc === "us" || loc === "eu" ? `aiplatform.${loc}.rep.googleapis.com` : `${loc}-aiplatform.googleapis.com`;
|
||||
return `https://${host}/v1/projects/${project}/locations/${loc}`;
|
||||
}
|
||||
// vertexOfDraft is the editor's Vertex AI fields as a Save sends them
|
||||
function vertexOfDraft() {
|
||||
const v = draft.vertex || {};
|
||||
return { project: (v.project || "").trim(), location: (v.location || "").trim(), credentials: (v.credentials || "").trim(), impersonate: (v.impersonate || "").trim() };
|
||||
}
|
||||
const decideOnly = (p) => !!p?.decide && !(p.chat || p.responses || p.anthropic || p.gemini);
|
||||
// a provider that lists its decision models apart (OpenRouter) says which
|
||||
// they are: its Jev Router (typesafe/jev-router) is a chat model
|
||||
@@ -7854,6 +7882,7 @@ function duplicateProvider(p) {
|
||||
const d = draftOf(p);
|
||||
draft = { ...d, id: slug(name), name, chosen: [], extra: d.chosen, copyOf: p.id };
|
||||
if (p.zhipuTeam) draft.zhipuTeam = { org: p.zhipuTeam.org || "", project: p.zhipuTeam.project || "" };
|
||||
if (p.vertex) draft.vertex = { project: p.vertex.project || "", location: p.vertex.location || "", credentials: p.vertex.credentials || "", impersonate: p.vertex.impersonate || "" };
|
||||
renderProviders();
|
||||
}
|
||||
|
||||
@@ -8212,8 +8241,32 @@ function drawEditor(p, presetID) {
|
||||
}
|
||||
const keyWrap = el("div", "pair");
|
||||
keyWrap.append(key, side);
|
||||
// Google Vertex AI takes no key: it is asked at the user's own Google
|
||||
// Cloud project with a token their Google credentials mint, so its
|
||||
// project, location, credentials file and a service account to go as
|
||||
// are asked in its place, the project first
|
||||
const vertex = p ? !!p.vertex : !!pr?.vertex;
|
||||
let vertexProject = null;
|
||||
if (vertex) draft.vertex = draft.vertex || { project: p?.vertex?.project || "", location: p?.vertex?.location || "", credentials: p?.vertex?.credentials || "", impersonate: p?.vertex?.impersonate || "" };
|
||||
const vertexFields = () => {
|
||||
const box = (k, placeholder, cls) => {
|
||||
const i = input(draft.vertex[k], placeholder);
|
||||
i.classList.add(cls);
|
||||
i.oninput = () => { draft.vertex[k] = i.value; refreshEndpoints(); };
|
||||
i.onkeydown = key.onkeydown; // Enter adds it, as from the key's box
|
||||
return i;
|
||||
};
|
||||
vertexProject = box("project", "my-project-123", "vertex-project");
|
||||
return [
|
||||
...field(t("Project ID"), vertexProject, t("Your Google Cloud project, with the Agent Platform API (aiplatform.googleapis.com) enabled: requests are made, and billed, there")),
|
||||
...field(t("Location"), box("location", "global", "vertex-location"), t("global, us, eu or a region such as us-central1. Each location serves its own models; global serves them all.")),
|
||||
...field(t("Credentials file"), box("credentials", "~/.config/gcloud/application_default_credentials.json", "vertex-credentials"), t("Optional. Left empty, gcloud's Application Default Credentials are used (gcloud auth application-default login), or the file GOOGLE_APPLICATION_CREDENTIALS names. A service account's key file works too.")),
|
||||
...field(t("Service account"), box("impersonate", t("optional · a service account's email"), "vertex-impersonate"), t("Requests are then made as this service account, impersonated with the credentials above: their account needs roles/iam.serviceAccountTokenCreator on it.")),
|
||||
];
|
||||
};
|
||||
if (p?.keyList?.length) ed.append(...field(t("Accounts"), renderKeyAccounts(p), p.routing ? t("Tick every key to use; Routing says how requests spread over them.") : t("Tick every key to use. Requests go to the first; when it runs out of quota or hits a rate limit, the next ticked key takes over.")));
|
||||
if (p?.keyList?.filter((k) => k.on).length > 1) ed.append(...renderRouting(p));
|
||||
else if (vertex) ed.append(...vertexFields());
|
||||
else ed.append(...field(t("API key"), keyWrap, isNew ? t("Kept in ~/.config/magpie/providers.json, readable by you alone. Nothing is read from your shell.") : ""));
|
||||
|
||||
// A user-defined provider can have its own picture; presets keep theirs.
|
||||
@@ -8426,13 +8479,21 @@ function drawEditor(p, presetID) {
|
||||
|
||||
if (!custom && !(decides && !p)) {
|
||||
const ebox = el("div");
|
||||
const row = field(t("Endpoints"), ebox, "");
|
||||
refreshEndpoints = () => {
|
||||
const base = p || pr || {};
|
||||
const src = { chat: draft.chat || base.chat || "", responses: draft.responses || base.responses || "", anthropic: draft.anthropic || base.anthropic || "", decide: base.decide || "" };
|
||||
// Vertex AI's is the address its project and location make, shown
|
||||
// with its Test once a project is typed, saved one or not: with none
|
||||
// there is nowhere to ask
|
||||
if (vertex) {
|
||||
src.gemini = vertexBase(draft.vertex);
|
||||
for (const x of row) x.hidden = !src.gemini;
|
||||
}
|
||||
ebox.replaceChildren(renderEndpoints(p, src));
|
||||
};
|
||||
refreshEndpoints();
|
||||
ed.append(...field(t("Endpoints"), ebox, ""));
|
||||
ed.append(...row);
|
||||
}
|
||||
|
||||
if (custom) {
|
||||
@@ -8511,13 +8572,13 @@ function drawEditor(p, presetID) {
|
||||
if (p && pr) {
|
||||
// another key of the vendor, or the same key for another workspace
|
||||
const more = el("button", "text", t("Add another {name}", { name: pr.name }));
|
||||
more.title = t("One more {name} provider, with its own key, headers and models", { name: pr.name });
|
||||
more.title = vertex ? t("One more {name} provider, with its own project, credentials, headers and models", { name: pr.name }) : t("One more {name} provider, with its own key, headers and models", { name: pr.name });
|
||||
more.onclick = () => { editing = { preset: pr.id }; draft = null; renderProviders(); };
|
||||
bar.append(more);
|
||||
}
|
||||
if (p) {
|
||||
const dup = el("button", "text", t("Duplicate"));
|
||||
dup.title = t("A new provider with {name}'s URLs, key, headers, models and balance settings, to change before adding", { name: p.name });
|
||||
dup.title = vertex ? t("A new provider with {name}'s project, credentials, headers and models, to change before adding", { name: p.name }) : t("A new provider with {name}'s URLs, key, headers, models and balance settings, to change before adding", { name: p.name });
|
||||
dup.onclick = () => duplicateProvider(p);
|
||||
bar.append(dup);
|
||||
}
|
||||
@@ -8591,9 +8652,11 @@ function drawEditor(p, presetID) {
|
||||
else if (draft.clearAccessKey) body.clearAccessKey = true;
|
||||
if (body.accessKeyID && !body.secretAccessKey && !(access.secretSet && !draft.clearAccessKey)) { ed.querySelector(".volc-sk")?.focus({ preventScroll: true }); return editorError(t("Give the access key's Secret too"), "warn"); }
|
||||
}
|
||||
if (vertex) body.vertex = vertexOfDraft();
|
||||
if (isNew && custom && !body.name) { name.focus(); return editorError(t("Give it a name"), "warn"); }
|
||||
if (isNew && custom && !body.chat && !body.anthropic && !body.responses && !body.decide) { url.focus(); return editorError(t("A base URL is needed"), "warn"); }
|
||||
if (endpoint && !body.chat && !body.responses) { endpoint.focus(); return editorError(t(pr.endpointNeeded || "Your resource's endpoint is needed"), "warn"); }
|
||||
if (vertex && !body.vertex.project) { vertexProject?.focus({ preventScroll: true }); return editorError(t("Google Vertex AI needs the id of your Google Cloud project"), "warn"); }
|
||||
editorError("");
|
||||
saving(saveBtn, t(isNew ? "Adding…" : "Saving…"));
|
||||
providerAction("save", body, t(isNew ? "{name} added" : "{name} saved", { name: draft.name || draft.id }));
|
||||
@@ -8601,7 +8664,7 @@ function drawEditor(p, presetID) {
|
||||
saveBtn.onclick = save;
|
||||
bar.append(cancel, saveBtn);
|
||||
ed.append(bar);
|
||||
setTimeout(() => (isNew ? (custom || another ? name : endpoint || key) : null)?.focus(), 0);
|
||||
setTimeout(() => (isNew ? (custom || another ? name : endpoint || vertexProject || key) : null)?.focus(), 0);
|
||||
return ed;
|
||||
}
|
||||
|
||||
@@ -9104,7 +9167,7 @@ function renderEndpoints(p, src) {
|
||||
if (!urls[proto]) continue;
|
||||
const e = el("div", "ep");
|
||||
const pl = el("span", "pl", label);
|
||||
pl.title = t(hint);
|
||||
pl.title = t(proto === "gemini" && draft?.vertex ? VERTEX_EP_HINT : hint);
|
||||
e.append(pl, el("code", "", urls[proto]), slots[proto] = el("span", "res"));
|
||||
eps.append(e);
|
||||
}
|
||||
|
||||
@@ -1741,6 +1741,26 @@ const I18N = {
|
||||
"another computer's magpie, shared on its network": "另一台电脑上的 magpie,局域网共享",
|
||||
"The address and API key the other computer's magpie shows in Settings, under Share on local network. Its models and routing groups are listed here; each request goes on in the API the agent spoke.": "另一台电脑的 magpie 在「设置 → 局域网共享」中显示的地址和 API 密钥。其模型和路由组会列在这里;请求按 Agent 所用的 API 原样转发。",
|
||||
"The other magpie's address is needed": "需要填写另一台 magpie 的地址",
|
||||
"your Google Cloud project, with gcloud's sign-in": "你的 Google Cloud 项目,通过 gcloud 登录",
|
||||
"Project ID": "项目 ID",
|
||||
"Your Google Cloud project, with the Agent Platform API (aiplatform.googleapis.com) enabled: requests are made, and billed, there": "你的 Google Cloud 项目,需已启用 Agent Platform API(aiplatform.googleapis.com):请求在这个项目中发出并计费",
|
||||
"Location": "位置",
|
||||
"global, us, eu or a region such as us-central1. Each location serves its own models; global serves them all.": "global、us、eu,或 us-central1 这样的区域。每个位置提供的模型各不相同;global 提供全部模型。",
|
||||
"Credentials file": "凭据文件",
|
||||
"Optional. Left empty, gcloud's Application Default Credentials are used (gcloud auth application-default login), or the file GOOGLE_APPLICATION_CREDENTIALS names. A service account's key file works too.": "可选。留空时使用 gcloud 的应用默认凭据(gcloud auth application-default login),或 GOOGLE_APPLICATION_CREDENTIALS 指定的文件。也可以填写服务账号的密钥文件。",
|
||||
"Service account": "服务账号",
|
||||
"optional · a service account's email": "可选 · 服务账号的邮箱",
|
||||
"Requests are then made as this service account, impersonated with the credentials above: their account needs roles/iam.serviceAccountTokenCreator on it.": "请求将以这个服务账号的身份发出,由上方的凭据模拟:凭据所属的账号需要在这个服务账号上拥有 roles/iam.serviceAccountTokenCreator 角色。",
|
||||
"Google Vertex AI needs the id of your Google Cloud project": "Google Vertex AI 需要你的 Google Cloud 项目 ID",
|
||||
"Gemini generateContent — what Vertex AI serves at your Google Cloud project": "Gemini generateContent — Vertex AI 在你的 Google Cloud 项目中提供",
|
||||
"Google ADC": "Google 默认凭据",
|
||||
"needs a project": "需要项目",
|
||||
"Open the row and give your Google Cloud project's id": "展开这一行并填写你的 Google Cloud 项目 ID",
|
||||
"Signed with your Google credentials": "使用你的 Google 凭据签名",
|
||||
"Signed as the service account {account}, with your Google credentials": "使用你的 Google 凭据,以服务账号 {account} 的身份签名",
|
||||
"Application Default Credentials": "应用默认凭据",
|
||||
"One more {name} provider, with its own project, credentials, headers and models": "再添加一个 {name} 供应商,使用各自的项目、凭据、请求头和模型",
|
||||
"A new provider with {name}'s project, credentials, headers and models, to change before adding": "新建供应商,沿用 {name} 的项目、凭据、请求头和模型,添加前可修改",
|
||||
"Test": "测试",
|
||||
"Send a tiny request through each endpoint": "向每个端点发送一个小请求",
|
||||
"model {model}": "模型 {model}",
|
||||
@@ -9723,6 +9743,26 @@ const I18N = {
|
||||
"another computer's magpie, shared on its network": "別のコンピューターの magpie(ネットワークで共有)",
|
||||
"The address and API key the other computer's magpie shows in Settings, under Share on local network. Its models and routing groups are listed here; each request goes on in the API the agent spoke.": "別のコンピューターの magpie が「設定」の「ローカルネットワークで共有」に表示するアドレスと API キーです。そのモデルとルーティンググループがここに一覧表示され、各リクエストはエージェントが使った API のまま転送されます。",
|
||||
"The other magpie's address is needed": "もう一方の magpie のアドレスが必要です",
|
||||
"your Google Cloud project, with gcloud's sign-in": "Google Cloud プロジェクトと gcloud のログインで",
|
||||
"Project ID": "プロジェクト ID",
|
||||
"Your Google Cloud project, with the Agent Platform API (aiplatform.googleapis.com) enabled: requests are made, and billed, there": "Agent Platform API(aiplatform.googleapis.com)を有効にした Google Cloud プロジェクトです。リクエストはこのプロジェクトで行われ、課金されます",
|
||||
"Location": "ロケーション",
|
||||
"global, us, eu or a region such as us-central1. Each location serves its own models; global serves them all.": "global、us、eu、または us-central1 などのリージョンです。ロケーションごとに提供されるモデルが異なり、global ではすべてのモデルを利用できます。",
|
||||
"Credentials file": "認証ファイル",
|
||||
"Optional. Left empty, gcloud's Application Default Credentials are used (gcloud auth application-default login), or the file GOOGLE_APPLICATION_CREDENTIALS names. A service account's key file works too.": "任意。空欄のときは gcloud のアプリケーションのデフォルト認証情報(gcloud auth application-default login)か、GOOGLE_APPLICATION_CREDENTIALS が指すファイルを使います。サービス アカウントのキーファイルも使えます。",
|
||||
"Service account": "権限借用",
|
||||
"optional · a service account's email": "任意 · サービス アカウントのメール",
|
||||
"Requests are then made as this service account, impersonated with the credentials above: their account needs roles/iam.serviceAccountTokenCreator on it.": "リクエストは、上の認証情報でこのサービス アカウントの権限を借用して行われます。認証情報のアカウントには、このサービス アカウントに対する roles/iam.serviceAccountTokenCreator ロールが必要です。",
|
||||
"Google Vertex AI needs the id of your Google Cloud project": "Google Vertex AI には Google Cloud プロジェクトの ID が必要です",
|
||||
"Gemini generateContent — what Vertex AI serves at your Google Cloud project": "Gemini generateContent — Vertex AI が Google Cloud プロジェクトで提供する形式",
|
||||
"Google ADC": "Google ADC",
|
||||
"needs a project": "要プロジェクト",
|
||||
"Open the row and give your Google Cloud project's id": "行を開いて Google Cloud プロジェクトの ID を入力してください",
|
||||
"Signed with your Google credentials": "Google 認証情報で署名します",
|
||||
"Signed as the service account {account}, with your Google credentials": "Google 認証情報を使い、サービス アカウント {account} として署名します",
|
||||
"Application Default Credentials": "アプリケーションのデフォルト認証情報",
|
||||
"One more {name} provider, with its own project, credentials, headers and models": "独自のプロジェクト、認証情報、ヘッダー、モデルを持つ {name} プロバイダをもう1つ追加します",
|
||||
"A new provider with {name}'s project, credentials, headers and models, to change before adding": "{name} のプロジェクト、認証情報、ヘッダー、モデルを引き継いだ新しいプロバイダです。追加前に変更できます",
|
||||
"Test": "テスト",
|
||||
"Send a tiny request through each endpoint": "各エンドポイントに小さなリクエストを送信します",
|
||||
"model {model}": "モデル {model}",
|
||||
@@ -13722,6 +13762,26 @@ const I18N = {
|
||||
"another computer's magpie, shared on its network": "magpie auf einem anderen Computer, im Netzwerk freigegeben",
|
||||
"The address and API key the other computer's magpie shows in Settings, under Share on local network. Its models and routing groups are listed here; each request goes on in the API the agent spoke.": "Adresse und API-Schlüssel, die magpie auf dem anderen Computer unter Einstellungen bei „Im lokalen Netzwerk freigeben“ anzeigt. Seine Modelle und Weiterleitungsgruppen werden hier aufgeführt; jede Anfrage wird in der API weitergeleitet, die der Agent verwendet hat.",
|
||||
"The other magpie's address is needed": "Die Adresse des anderen magpie ist erforderlich",
|
||||
"your Google Cloud project, with gcloud's sign-in": "Ihr Google-Cloud-Projekt, mit der Anmeldung von gcloud",
|
||||
"Project ID": "Projekt-ID",
|
||||
"Your Google Cloud project, with the Agent Platform API (aiplatform.googleapis.com) enabled: requests are made, and billed, there": "Ihr Google-Cloud-Projekt mit aktivierter Agent Platform API (aiplatform.googleapis.com): Anfragen werden dort gestellt und abgerechnet",
|
||||
"Location": "Standort",
|
||||
"global, us, eu or a region such as us-central1. Each location serves its own models; global serves them all.": "global, us, eu oder eine Region wie us-central1. Jeder Standort bietet eigene Modelle; global bietet alle.",
|
||||
"Credentials file": "Anmelde\u00addatei",
|
||||
"Optional. Left empty, gcloud's Application Default Credentials are used (gcloud auth application-default login), or the file GOOGLE_APPLICATION_CREDENTIALS names. A service account's key file works too.": "Optional. Leer gelassen, werden die Standardanmeldedaten für Anwendungen von gcloud verwendet (gcloud auth application-default login) oder die Datei, die GOOGLE_APPLICATION_CREDENTIALS nennt. Die Schlüsseldatei eines Dienstkontos geht auch.",
|
||||
"Service account": "Dienstkonto",
|
||||
"optional · a service account's email": "optional · E-Mail des Dienstkontos",
|
||||
"Requests are then made as this service account, impersonated with the credentials above: their account needs roles/iam.serviceAccountTokenCreator on it.": "Anfragen werden dann als dieses Dienstkonto gestellt, dessen Identität die Anmeldedaten oben übernehmen: Deren Konto braucht dafür roles/iam.serviceAccountTokenCreator auf diesem Dienstkonto.",
|
||||
"Google Vertex AI needs the id of your Google Cloud project": "Google Vertex AI braucht die ID Ihres Google-Cloud-Projekts",
|
||||
"Gemini generateContent — what Vertex AI serves at your Google Cloud project": "Gemini generateContent – bietet Vertex AI in Ihrem Google-Cloud-Projekt",
|
||||
"Google ADC": "Google-ADC",
|
||||
"needs a project": "Projekt fehlt",
|
||||
"Open the row and give your Google Cloud project's id": "Zeile aufklappen und die ID Ihres Google-Cloud-Projekts angeben",
|
||||
"Signed with your Google credentials": "Signiert mit Ihren Google-Anmeldedaten",
|
||||
"Signed as the service account {account}, with your Google credentials": "Signiert als Dienstkonto {account}, mit Ihren Google-Anmeldedaten",
|
||||
"Application Default Credentials": "Standardanmeldedaten für Anwendungen",
|
||||
"One more {name} provider, with its own project, credentials, headers and models": "Ein weiterer {name}-Anbieter mit eigenem Projekt, eigenen Anmeldedaten, Headern und Modellen",
|
||||
"A new provider with {name}'s project, credentials, headers and models, to change before adding": "Ein neuer Anbieter mit Projekt, Anmeldedaten, Headern und Modellen von {name}, vor dem Hinzufügen änderbar",
|
||||
"Test": "Testen",
|
||||
"Send a tiny request through each endpoint": "Eine winzige Anfrage über jeden Endpunkt senden",
|
||||
"model {model}": "Modell {model}",
|
||||
|
||||
@@ -119,6 +119,10 @@ type providerJSON struct {
|
||||
// read with (provider.TakesVolcAccessKey): whether the provider takes
|
||||
// one, its ID, and whether a Secret is saved; never the Secret itself
|
||||
AccessKey *accessKeyJSON `json:"accessKey,omitempty"`
|
||||
// a Google Vertex AI provider's project, location and Google
|
||||
// credentials, which it is asked with in place of a key: set for it
|
||||
// alone, which the editor asks them of
|
||||
Vertex *provider.Vertex `json:"vertex,omitempty"`
|
||||
// ModelTest is why its models can't each be sent a test request, ""
|
||||
// when they can (provider.ModelTest): the editor says so on a chip's
|
||||
// right-click rather than offer no menu
|
||||
@@ -312,6 +316,9 @@ type presetJSON struct {
|
||||
// AccessKey: a Volcengine Ark plan, whose windows are read with the
|
||||
// account's access key, which the editor offers to take
|
||||
AccessKey bool `json:"accessKey,omitempty"`
|
||||
// Vertex: it is Google Vertex AI, whose editor asks for a Google Cloud
|
||||
// project and the Google credentials to sign with, not a key
|
||||
Vertex bool `json:"vertex,omitempty"`
|
||||
// a partner's tagline by language, and the languages it is listed in
|
||||
Notes map[string]string `json:"notes,omitempty"`
|
||||
Langs []string `json:"langs,omitempty"`
|
||||
@@ -477,6 +484,12 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON {
|
||||
if provider.TakesVolcAccessKey(p) || p.AccessKeyID != "" || p.SecretAccessKey != "" {
|
||||
out.AccessKey = &accessKeyJSON{ID: p.AccessKeyID, SecretSet: p.SecretAccessKey != ""}
|
||||
}
|
||||
if p.IsVertex() {
|
||||
out.Vertex = &provider.Vertex{}
|
||||
if p.Vertex != nil {
|
||||
*out.Vertex = *p.Vertex
|
||||
}
|
||||
}
|
||||
if site := provider.StepFunSite(p); site != "" {
|
||||
out.StepPlan = &stepPlanJSON{site, provider.StepFunSignedIn(site), provider.StepFunSignInURL(site), provider.StepFunBookmarklet()}
|
||||
}
|
||||
@@ -699,7 +712,7 @@ func providersState() providersJSON {
|
||||
for _, pr := range provider.Presets() {
|
||||
bases := provider.Provider{Chat: pr.Chat, Responses: pr.Responses, Anthropic: pr.Anthropic}
|
||||
team := provider.TakesZhipuTeam(bases)
|
||||
s.Presets = append(s.Presets, presetJSON{PresetDef: pr, Added: have[pr.ID], ZhipuTeam: team, AccessKey: provider.TakesVolcAccessKey(bases)})
|
||||
s.Presets = append(s.Presets, presetJSON{PresetDef: pr, Added: have[pr.ID], ZhipuTeam: team, AccessKey: provider.TakesVolcAccessKey(bases), Vertex: pr.ID == provider.VertexPreset})
|
||||
}
|
||||
cat := provider.Catalog()
|
||||
s.Gateway = gatewayJSON{URL: gateway.URL(), OnNetwork: gateway.OnNetwork(), Models: len(cat), Calls: []gateway.Call{}, Groups: []gwGroupJSON{}}
|
||||
@@ -1064,6 +1077,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
pr.Key, pr.Models, pr.Fallback, pr.Headers, pr.BalanceToken, pr.Contexts = in.Key, in.Models, in.Fallback, in.Headers, in.BalanceToken, in.Contexts
|
||||
pr.ZhipuTeam = in.ZhipuTeam
|
||||
pr.SecretAccessKey = in.SecretAccessKey
|
||||
pr.Vertex = in.Vertex
|
||||
pr.Searches = in.Searches
|
||||
pr.PinUpstream = in.PinUpstream
|
||||
pr.Unredacted = in.Unredacted
|
||||
@@ -1210,6 +1224,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
if in.SecretAccessKey == "" && old != nil && !req.ClearAccessKey {
|
||||
in.SecretAccessKey = old.SecretAccessKey
|
||||
}
|
||||
// and a Vertex AI provider's project and credentials
|
||||
if in.Vertex == nil && old != nil {
|
||||
in.Vertex = old.Vertex
|
||||
}
|
||||
if in.Key == "" && old != nil {
|
||||
in.Key = old.Key
|
||||
}
|
||||
@@ -1862,11 +1880,16 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
// Refresh and Test models before a Save: a key pasted to replace the saved
|
||||
// one is the one asked with, and the URLs, headers and proxy typed are
|
||||
// where and how. Nothing is saved. What the form left blank (the key above
|
||||
// all) is the saved one's; the provider's other keys are kept.
|
||||
// all) is the saved one's; the provider's other keys are kept. A Vertex AI
|
||||
// provider's project, location, credentials file and service account are
|
||||
// the ones typed, spelled as a Save keeps them, unless no project is.
|
||||
func typed(p, in provider.Provider, proxy *string) provider.Provider {
|
||||
if k := strings.TrimSpace(in.Key); k != "" && k != p.Key {
|
||||
p.Key, p.KeyName, p.KeyProtocol, p.KeyWeight = k, "", "", 0
|
||||
}
|
||||
if v := in.Vertex.Normal(); v != nil && p.IsVertex() && v.Project != "" {
|
||||
p.Vertex = v
|
||||
}
|
||||
for _, f := range []struct {
|
||||
to *string
|
||||
v string
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// Google Vertex AI's editor asks for a project, a location, a credentials
|
||||
// file and a service account in place of a key. Its preset says so, a
|
||||
// Save sends them as vertex and the provider's row has them back as they
|
||||
// are kept; an edit that sends none keeps them. Test before a Save asks at
|
||||
// the project typed, with the credentials typed, and saves nothing.
|
||||
func TestVertexProviderEditor(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
t.Setenv("GOOGLE_APPLICATION_CREDENTIALS", "")
|
||||
t.Setenv("CLOUDSDK_CONFIG", "")
|
||||
|
||||
// Google's token endpoint and Vertex AI, both here
|
||||
var mu sync.Mutex
|
||||
var asked []string
|
||||
google := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.URL.Path == "/token" {
|
||||
w.Write([]byte(`{"access_token":"ya29.typed","expires_in":3600}`))
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
asked = append(asked, r.URL.Path)
|
||||
mu.Unlock()
|
||||
if r.Header.Get("Authorization") != "Bearer ya29.typed" {
|
||||
http.Error(w, `{"error":{"code":401,"message":"no token"}}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Write([]byte(`{"candidates":[{"content":{"role":"model","parts":[{"text":"hi"}]},"finishReason":"STOP"}]}`))
|
||||
}))
|
||||
defer google.Close()
|
||||
defer provider.VertexForTest(google.URL, google.URL+"/token", google.URL+"/iam")()
|
||||
|
||||
mux := http.NewServeMux()
|
||||
providerRoutes(mux, nil)
|
||||
post := func(action, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/"+action, strings.NewReader(body)))
|
||||
return w
|
||||
}
|
||||
type row struct {
|
||||
ID string `json:"id"`
|
||||
Vertex *provider.Vertex `json:"vertex"`
|
||||
Ready bool `json:"ready"`
|
||||
Key struct {
|
||||
Set bool `json:"set"`
|
||||
} `json:"key"`
|
||||
}
|
||||
state := func() (map[string]row, map[string]bool) {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/providers", nil))
|
||||
var s struct {
|
||||
Providers []row `json:"providers"`
|
||||
Presets []struct {
|
||||
ID string `json:"id"`
|
||||
Vertex bool `json:"vertex"`
|
||||
} `json:"presets"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &s); err != nil {
|
||||
t.Fatalf("providers: %v %s", err, w.Body)
|
||||
}
|
||||
rows, presets := map[string]row{}, map[string]bool{}
|
||||
for _, p := range s.Providers {
|
||||
rows[p.ID] = p
|
||||
}
|
||||
for _, p := range s.Presets {
|
||||
presets[p.ID] = p.Vertex
|
||||
}
|
||||
return rows, presets
|
||||
}
|
||||
|
||||
_, presets := state()
|
||||
if !presets[provider.VertexPreset] || presets["google"] || presets["openai"] {
|
||||
t.Fatalf("the presets that say they are Vertex AI's: %v", presets)
|
||||
}
|
||||
|
||||
if w := post("save", `{"preset":"google-vertex","new":true,"vertex":{"project":" My-Project ","location":"US-Central1","credentials":" ~/keys/sa.json ","impersonate":"Bot@My-Project.iam.gserviceaccount.com"}}`); w.Code != 200 {
|
||||
t.Fatalf("add: %d %s", w.Code, w.Body)
|
||||
}
|
||||
want := provider.Vertex{Project: "my-project", Location: "us-central1", Credentials: "~/keys/sa.json", Impersonate: "bot@my-project.iam.gserviceaccount.com"}
|
||||
rows, _ := state()
|
||||
got := rows[provider.VertexPreset]
|
||||
if got.Vertex == nil || *got.Vertex != want || !got.Ready || got.Key.Set {
|
||||
t.Fatalf("the row: %+v vertex %+v", got, got.Vertex)
|
||||
}
|
||||
|
||||
// an edit that sends none keeps them; one that does changes them
|
||||
if w := post("save", `{"id":"google-vertex","preset":"google-vertex","name":"Google Vertex AI","headers":{"X-Vertex-AI-LLM-Request-Type":"shared"}}`); w.Code != 200 {
|
||||
t.Fatalf("edit: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if rows, _ = state(); rows[provider.VertexPreset].Vertex == nil || *rows[provider.VertexPreset].Vertex != want {
|
||||
t.Fatalf("an edit without them lost them: %+v", rows[provider.VertexPreset].Vertex)
|
||||
}
|
||||
if w := post("save", `{"id":"google-vertex","preset":"google-vertex","name":"Google Vertex AI","vertex":{"project":"my-project","location":"","credentials":"","impersonate":""}}`); w.Code != 200 {
|
||||
t.Fatalf("edit: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if rows, _ = state(); rows[provider.VertexPreset].Vertex == nil || *rows[provider.VertexPreset].Vertex != (provider.Vertex{Project: "my-project", Location: "global"}) {
|
||||
t.Fatalf("the edit's: %+v", rows[provider.VertexPreset].Vertex)
|
||||
}
|
||||
|
||||
// Test before a Save: at the project typed, with the credentials typed
|
||||
creds := filepath.Join(t.TempDir(), "adc.json")
|
||||
if err := os.WriteFile(creds, []byte(`{"type":"authorized_user","client_id":"c","client_secret":"s","refresh_token":"r"}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vertex, _ := json.Marshal(provider.Vertex{Project: " Typed-Project ", Location: "", Credentials: creds})
|
||||
w := post("test", `{"id":"google-vertex","typed":true,"vertex":`+string(vertex)+`}`)
|
||||
var res struct {
|
||||
Results []provider.Result `json:"results"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil || len(res.Results) != 1 || !res.Results[0].OK || res.Results[0].Protocol != provider.Gemini {
|
||||
t.Fatalf("test: %d %s", w.Code, w.Body)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(asked) != 1 || !strings.HasPrefix(asked[0], "/v1/projects/typed-project/locations/global/publishers/google/models/") {
|
||||
t.Fatalf("asked at %q, not the project typed", asked)
|
||||
}
|
||||
if p, err := provider.Find(provider.VertexPreset); err != nil || p.Vertex == nil || p.Vertex.Project != "my-project" || p.Vertex.Credentials != "" {
|
||||
t.Fatalf("the test saved what was typed: %v %+v", err, p)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Google Vertex AI is asked at the user's own Google Cloud project with
|
||||
// their Google credentials, not a key. Its editor, adding one or editing
|
||||
// one saved, has Project ID (focused first, and needed), Location,
|
||||
// Credentials file and Service account where another's has API key; Save
|
||||
// posts them trimmed as vertex, with no key, and Test asks with what is
|
||||
// typed. Endpoints shows the address the project and location make. Its
|
||||
// rows say which credentials sign it, never that a key is missing. A click
|
||||
// leaves the page where it is. English and Chinese; the pills and the fields
|
||||
// fit 560px and 440px windows in Japanese and German too. No backend, the
|
||||
// API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const SA = "magpie@my-project-123.iam.gserviceaccount.com";
|
||||
const presets = (added) => [
|
||||
{ id: "google", name: "Google Gemini", icon: "gemini-color", kind: "vendor", chat: "https://generativelanguage.googleapis.com/v1beta/openai", note: "Gemini Developer API", added: false },
|
||||
{
|
||||
id: "google-vertex", name: "Google Vertex AI", short: "Vertex AI", icon: "vertexai-color", kind: "vendor", added, noList: true, vertex: true,
|
||||
note: "your Google Cloud project, with gcloud's sign-in", website: "https://docs.cloud.google.com/gemini-enterprise-agent-platform/models",
|
||||
headerHints: ["X-Vertex-AI-LLM-Request-Type", "X-Vertex-AI-LLM-Shared-Request-Type"], models: ["gemini-3.8-flash", "gemini-2.5-pro"],
|
||||
},
|
||||
];
|
||||
// a Vertex AI provider as /api/providers has it: no key, its vertex as kept
|
||||
const vertexRow = (id, name, host, vertex, ready = true) => ({
|
||||
id, name, icon: "vertexai-color", preset: "google-vertex", chat: "", responses: "", anthropic: "", catalog: "", host,
|
||||
models: [{ id: "gemini-3.8-flash", name: "gemini-3.8-flash", on: true }], agents: [], fallback: [], headers: {},
|
||||
key: { set: false, masked: "", optional: true }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", ready, vertex,
|
||||
});
|
||||
const saved = vertexRow("google-vertex", "Google Vertex AI", "aiplatform.us.rep.googleapis.com", { project: "my-project-123", location: "us", credentials: "~/keys/vertex-sa.json", impersonate: SA });
|
||||
const adc = vertexRow("google-vertex-2", "Vertex EU", "aiplatform.eu.rep.googleapis.com", { project: "team-prod", location: "eu" });
|
||||
const file = vertexRow("google-vertex-3", "Vertex dev", "aiplatform.googleapis.com", { project: "team-dev", location: "global", credentials: "~/keys/dev-sa.json" });
|
||||
// providers.json edited by hand to have no project: nowhere to ask
|
||||
const bare = vertexRow("google-vertex-4", "Vertex draft", "", {}, false);
|
||||
const relay = {
|
||||
id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", host: "relay.example.com",
|
||||
models: [{ id: "model-a", name: "Model A", on: true }], agents: [], fallback: [], headers: {},
|
||||
key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", ready: true,
|
||||
};
|
||||
|
||||
function serve(lang, web, provs, pres, posts) {
|
||||
const providers = { providers: provs, presets: pres, excluded: [], gateway: { running: true, window: true } };
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/providers") return json(providers);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") {
|
||||
const action = url.pathname.slice("/api/provider/".length);
|
||||
posts.push({ action, body: route.request().postDataJSON() });
|
||||
// Vertex AI's one endpoint answers
|
||||
if (action === "test") return json({ results: [{ protocol: "gemini", ok: true, ms: 412, model: "gemini-3.8-flash" }] });
|
||||
return json(providers);
|
||||
}
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: {
|
||||
labels: ["Project ID", "Location", "Credentials file", "Service account"], key: "API key", endpoints: "Endpoints",
|
||||
account: "optional · a service account's email",
|
||||
hints: [/^Your Google Cloud project, with the Agent Platform API \(aiplatform\.googleapis\.com\) enabled: requests are made, and billed, there$/, /^global, us, eu or a region such as us-central1\. Each location serves its own models/,
|
||||
/Application Default Credentials are used \(gcloud auth application-default login\)/, /impersonated with the credentials above.*roles\/iam\.serviceAccountTokenCreator/],
|
||||
needed: "Google Vertex AI needs the id of your Google Cloud project", add: "Add", save: "Save", dup: "Duplicate", another: "Add another Google Vertex AI",
|
||||
more: "One more Google Vertex AI provider, with its own project, credentials, headers and models",
|
||||
copy: "A new provider with Google Vertex AI's project, credentials, headers and models, to change before adding",
|
||||
gemini: "Gemini generateContent — what Vertex AI serves at your Google Cloud project", ms: "412 ms",
|
||||
adc: "Google ADC", needsProject: "needs a project", noKey: ["no key", "needs a key"],
|
||||
as: `Signed as the service account ${SA}, with your Google credentials`, signed: "Signed with your Google credentials",
|
||||
adcLong: "Application Default Credentials", open: "Open the row and give your Google Cloud project's id",
|
||||
},
|
||||
zh: {
|
||||
labels: ["项目 ID", "位置", "凭据文件", "服务账号"], key: "API 密钥", endpoints: "端点",
|
||||
account: "可选 · 服务账号的邮箱",
|
||||
hints: [/^你的 Google Cloud 项目,需已启用 Agent Platform API(aiplatform\.googleapis\.com):请求在这个项目中发出并计费$/, /^global、us、eu,或 us-central1 这样的区域。每个位置提供的模型各不相同/,
|
||||
/gcloud 的应用默认凭据(gcloud auth application-default login)/, /由上方的凭据模拟.*roles\/iam\.serviceAccountTokenCreator/],
|
||||
needed: "Google Vertex AI 需要你的 Google Cloud 项目 ID", add: "添加", save: "保存", dup: "复制", another: "再添加一个 Google Vertex AI",
|
||||
more: "再添加一个 Google Vertex AI 供应商,使用各自的项目、凭据、请求头和模型",
|
||||
copy: "新建供应商,沿用 Google Vertex AI 的项目、凭据、请求头和模型,添加前可修改",
|
||||
gemini: "Gemini generateContent — Vertex AI 在你的 Google Cloud 项目中提供", ms: "412 毫秒",
|
||||
adc: "Google 默认凭据", needsProject: "需要项目", noKey: ["无需密钥", "需要密钥"],
|
||||
as: `使用你的 Google 凭据,以服务账号 ${SA} 的身份签名`, signed: "使用你的 Google 凭据签名",
|
||||
adcLong: "应用默认凭据", open: "展开这一行并填写你的 Google Cloud 项目 ID",
|
||||
},
|
||||
};
|
||||
const FIELDS = ["vertex-project", "vertex-location", "vertex-credentials", "vertex-impersonate"];
|
||||
const STRINGS = [
|
||||
"your Google Cloud project, with gcloud's sign-in", "Project ID", "Location", "Credentials file", "Service account", "optional · a service account's email",
|
||||
"Your Google Cloud project, with the Agent Platform API (aiplatform.googleapis.com) enabled: requests are made, and billed, there",
|
||||
"global, us, eu or a region such as us-central1. Each location serves its own models; global serves them all.",
|
||||
"Optional. Left empty, gcloud's Application Default Credentials are used (gcloud auth application-default login), or the file GOOGLE_APPLICATION_CREDENTIALS names. A service account's key file works too.",
|
||||
"Requests are then made as this service account, impersonated with the credentials above: their account needs roles/iam.serviceAccountTokenCreator on it.",
|
||||
"Google Vertex AI needs the id of your Google Cloud project", "Gemini generateContent — what Vertex AI serves at your Google Cloud project",
|
||||
"Google ADC", "needs a project", "Open the row and give your Google Cloud project's id", "Signed with your Google credentials",
|
||||
"Signed as the service account {account}, with your Google credentials", "Application Default Credentials",
|
||||
"One more {name} provider, with its own project, credentials, headers and models",
|
||||
"A new provider with {name}'s project, credentials, headers and models, to change before adding",
|
||||
];
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
const start = async (t, lang, name, provs, pres, { web = false, width = 900 } = {}) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${name}-vertex.png`) });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
// short, so the editor scrolls and a click that moved it would show
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 560 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [], posts = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, web, provs, pres, posts));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
return { page, errors, posts };
|
||||
};
|
||||
const edit = async (page, id) => {
|
||||
await page.locator(`.row.provider[data-id="${id}"]`).click();
|
||||
const ed = page.locator(".editor");
|
||||
await ed.locator("input.vertex-project").waitFor();
|
||||
return ed;
|
||||
};
|
||||
const values = (ed) => Promise.all(FIELDS.map((cls) => ed.locator("input." + cls).inputValue()));
|
||||
const endpointsOf = (ed) => ed.locator(".eps .ep").evaluateAll((es) => es.map((e) => [e.querySelector(".pl").textContent, e.querySelector("code").textContent]));
|
||||
// a click, the page left where it was
|
||||
const click = async (page, loc) => {
|
||||
await loc.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(200);
|
||||
const before = await loc.evaluate((e) => e.getBoundingClientRect().top);
|
||||
await loc.click();
|
||||
await page.waitForTimeout(250);
|
||||
const after = await loc.evaluate((e) => e.getBoundingClientRect().top);
|
||||
assert(Math.abs(after - before) <= 1, `moved from ${before} to ${after}`);
|
||||
};
|
||||
// the body of the first post of action after the n-th, null if none comes
|
||||
const posted = async (page, posts, action, n, ms = 5000) => {
|
||||
for (let i = 0; i < ms / 50 && !posts.slice(n).some((p) => p.action === action); i++) await page.waitForTimeout(50);
|
||||
return posts.slice(n).find((p) => p.action === action)?.body ?? null;
|
||||
};
|
||||
const press = async (page, posts, label, action = "save", ms) => {
|
||||
const n = posts.length;
|
||||
await page.locator(".editor .bar").getByRole("button", { name: label, exact: true }).click();
|
||||
return posted(page, posts, action, n, ms);
|
||||
};
|
||||
const focused = (page, cls) => page.evaluate((cls) => !!document.activeElement?.classList.contains(cls), cls);
|
||||
|
||||
for (const lang of ["en", "zh"]) {
|
||||
const w = words[lang];
|
||||
test(`${engine} ${lang}: Google Vertex AI is added with its project, not a key`, async (t) => {
|
||||
const { page, errors, posts } = await start(t, lang, "add", [relay], presets(false));
|
||||
await page.locator("#addProvider").click();
|
||||
await page.locator('#addSheet .tile[data-pick="Vertex AI"]').click();
|
||||
const ed = page.locator(".editor.new");
|
||||
await ed.locator(".ehead b", { hasText: "Google Vertex AI" }).waitFor();
|
||||
await page.waitForFunction(() => document.activeElement?.classList.contains("vertex-project"));
|
||||
|
||||
// its four fields where the key would be, in order, each labelled,
|
||||
// with its example and what it is for
|
||||
assert.equal(await ed.locator("input[type=password]").count(), 0, "no key to paste");
|
||||
const labels = await ed.locator("label").allTextContents();
|
||||
assert(!labels.includes(w.key), labels.join(" | "));
|
||||
const placeholders = ["my-project-123", "global", "~/.config/gcloud/application_default_credentials.json", w.account];
|
||||
let above = -Infinity;
|
||||
for (const [i, cls] of FIELDS.entries()) {
|
||||
const box = ed.locator("input." + cls);
|
||||
assert.equal(await box.getAttribute("placeholder"), placeholders[i]);
|
||||
assert.equal(await box.inputValue(), "");
|
||||
assert.equal(await ed.locator(`label[for="${await box.getAttribute("id")}"]`).textContent(), w.labels[i]);
|
||||
assert.match(await box.locator("xpath=following-sibling::div[contains(@class,'hint')]").textContent(), w.hints[i]);
|
||||
const y = (await box.boundingBox()).y;
|
||||
assert(y > above, cls + " below the field before it");
|
||||
above = y;
|
||||
}
|
||||
// no address until there is a project to make one of
|
||||
const endpoints = ed.locator("label", { hasText: new RegExp("^" + w.endpoints + "$") });
|
||||
assert.equal(await endpoints.isVisible(), false);
|
||||
|
||||
// none typed: said, nothing sent, the project focused and the
|
||||
// editor left where it was scrolled to
|
||||
await click(page, ed.locator("input.vertex-location"));
|
||||
const scroller = page.locator(".modal .editor > .ebody");
|
||||
await scroller.evaluate((e) => { e.scrollTop = e.scrollHeight; });
|
||||
await page.waitForTimeout(100);
|
||||
const top = await scroller.evaluate((e) => e.scrollTop);
|
||||
assert(top > 0, "the editor scrolls");
|
||||
assert.equal(await press(page, posts, w.add, "save", 400), null);
|
||||
assert.equal(await ed.locator(".editor-error").textContent(), w.needed);
|
||||
assert(await focused(page, "vertex-project"));
|
||||
assert.equal(await scroller.evaluate((e) => e.scrollTop), top, "the Add moved the editor");
|
||||
|
||||
// typed with stray spaces: the address shows, and Enter sends them
|
||||
// trimmed as vertex, with no key
|
||||
const box = (cls) => ed.locator("input." + cls);
|
||||
await box("vertex-project").fill(" My-Project-123 ");
|
||||
assert.equal(await endpoints.isVisible(), true);
|
||||
assert.deepEqual(await endpointsOf(ed), [["Gemini", "https://aiplatform.googleapis.com/v1/projects/my-project-123/locations/global"]]);
|
||||
await box("vertex-location").fill(" us-central1 ");
|
||||
assert.deepEqual(await endpointsOf(ed), [["Gemini", "https://us-central1-aiplatform.googleapis.com/v1/projects/my-project-123/locations/us-central1"]]);
|
||||
await box("vertex-credentials").fill(" ~/keys/sa.json ");
|
||||
await box("vertex-impersonate").fill(` ${SA} `);
|
||||
const n = posts.length;
|
||||
await box("vertex-impersonate").press("Enter");
|
||||
const added = await posted(page, posts, "save", n);
|
||||
assert.equal(added.new, true);
|
||||
assert.equal(added.preset, "google-vertex");
|
||||
assert.deepEqual(added.vertex, { project: "My-Project-123", location: "us-central1", credentials: "~/keys/sa.json", impersonate: SA });
|
||||
assert.equal(added.key, "");
|
||||
|
||||
// another preset's editor asks for its key, and none of these
|
||||
await page.locator(".editor.new").waitFor({ state: "detached" });
|
||||
await page.locator("#addProvider").click();
|
||||
await page.locator('#addSheet .tile[data-pick="Google Gemini"]').click();
|
||||
await ed.locator(".ehead b", { hasText: "Google Gemini" }).waitFor();
|
||||
assert.equal(await ed.locator("input[type=password]").count(), 1);
|
||||
assert.equal(await ed.locator(FIELDS.map((c) => "input." + c).join(", ")).count(), 0);
|
||||
|
||||
for (const l of ["zh", "ja", "de"]) {
|
||||
const missing = await page.evaluate(([l, keys]) => keys.filter((k) => !I18N[l][k]), [l, STRINGS]);
|
||||
assert.deepEqual(missing, [], `every string has its ${l}`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang}: a saved Vertex AI provider's project is shown, tested and saved`, async (t) => {
|
||||
const { page, errors, posts } = await start(t, lang, "edit", [saved, adc, relay], presets(true));
|
||||
let ed = await edit(page, "google-vertex");
|
||||
assert.equal(await ed.locator("input[type=password]").count(), 0);
|
||||
assert.deepEqual(await values(ed), ["my-project-123", "us", "~/keys/vertex-sa.json", SA]);
|
||||
assert.deepEqual(await endpointsOf(ed), [["Gemini", "https://aiplatform.us.rep.googleapis.com/v1/projects/my-project-123/locations/us"]]);
|
||||
assert.equal(await ed.locator(".eps .ep .pl").getAttribute("title"), w.gemini);
|
||||
// the headers Vertex AI's pay-as-you-go tiers are asked with, a click away
|
||||
const hints = await ed.locator(".headers .hadds button").allTextContents();
|
||||
assert(hints.includes("+ X-Vertex-AI-LLM-Request-Type") && hints.includes("+ X-Vertex-AI-LLM-Shared-Request-Type"), hints.join(" | "));
|
||||
const bar = ed.locator(".bar");
|
||||
assert.equal(await bar.getByRole("button", { name: w.another, exact: true }).getAttribute("title"), w.more);
|
||||
assert.equal(await bar.getByRole("button", { name: w.dup, exact: true }).getAttribute("title"), w.copy);
|
||||
|
||||
// a click in a field leaves the page where it is; the address
|
||||
// follows the location typed
|
||||
const box = (cls) => ed.locator("input." + cls);
|
||||
await click(page, box("vertex-location"));
|
||||
await box("vertex-location").fill("eu");
|
||||
assert.deepEqual(await endpointsOf(ed), [["Gemini", "https://aiplatform.eu.rep.googleapis.com/v1/projects/my-project-123/locations/eu"]]);
|
||||
await click(page, box("vertex-impersonate"));
|
||||
await box("vertex-impersonate").fill("");
|
||||
|
||||
// Test asks with what is typed, before any Save
|
||||
const n = posts.length;
|
||||
await click(page, ed.locator(".eps button.action"));
|
||||
const tested = await posted(page, posts, "test", n);
|
||||
assert.equal(tested.id, "google-vertex");
|
||||
assert.equal(tested.typed, true);
|
||||
assert.deepEqual(tested.vertex, { project: "my-project-123", location: "eu", credentials: "~/keys/vertex-sa.json", impersonate: "" });
|
||||
assert(!tested.key);
|
||||
await ed.locator(".eps .ep .res.ok").waitFor();
|
||||
assert.equal(await ed.locator(".eps .ep .res.ok").textContent(), w.ms);
|
||||
|
||||
// a header hint adds its header, its value typed next
|
||||
await ed.locator(".headers .hadds button", { hasText: "+ X-Vertex-AI-LLM-Request-Type" }).click();
|
||||
await page.waitForFunction(() => !!document.activeElement?.closest(".headers"));
|
||||
await page.keyboard.type("shared");
|
||||
const body = await press(page, posts, w.save);
|
||||
assert.equal(body.id, "google-vertex");
|
||||
assert.equal(body.preset, "google-vertex");
|
||||
assert.equal(body.key, "");
|
||||
assert.deepEqual(body.vertex, { project: "my-project-123", location: "eu", credentials: "~/keys/vertex-sa.json", impersonate: "" });
|
||||
assert.deepEqual(body.headers, { "X-Vertex-AI-LLM-Request-Type": "shared" });
|
||||
|
||||
// Duplicate: a new one on the same project and credentials
|
||||
await page.locator(".editor").waitFor({ state: "detached" });
|
||||
ed = await edit(page, "google-vertex");
|
||||
await ed.locator(".bar").getByRole("button", { name: w.dup, exact: true }).click();
|
||||
await page.locator(".editor.new input.vertex-project").waitFor();
|
||||
assert.deepEqual(await values(page.locator(".editor.new")), ["my-project-123", "us", "~/keys/vertex-sa.json", SA]);
|
||||
const copy = await press(page, posts, w.add);
|
||||
assert.equal(copy.new, true);
|
||||
assert.equal(copy.copyOf, "google-vertex");
|
||||
assert.deepEqual(copy.vertex, { project: "my-project-123", location: "us", credentials: "~/keys/vertex-sa.json", impersonate: SA });
|
||||
|
||||
// another saved one's editor has its own
|
||||
await page.locator(".editor").waitFor({ state: "detached" });
|
||||
ed = await edit(page, "google-vertex-2");
|
||||
assert.deepEqual(await values(ed), ["team-prod", "eu", "", ""]);
|
||||
assert.deepEqual(await endpointsOf(ed), [["Gemini", "https://aiplatform.eu.rep.googleapis.com/v1/projects/team-prod/locations/eu"]]);
|
||||
|
||||
// its project taken out: no address and no Test, and a Save is
|
||||
// refused, nothing sent
|
||||
await box("vertex-project").fill(" ");
|
||||
assert.equal(await ed.locator("label", { hasText: new RegExp("^" + w.endpoints + "$") }).isVisible(), false);
|
||||
assert.equal(await ed.locator(".eps button.action").isVisible(), false);
|
||||
assert.equal(await press(page, posts, w.save, "save", 400), null);
|
||||
assert.equal(await ed.locator(".editor-error").textContent(), w.needed);
|
||||
assert(await focused(page, "vertex-project"));
|
||||
|
||||
const border = await page.evaluate(() => [...document.querySelectorAll(".editor, .editor *")].map((e) => getComputedStyle(e).borderLeftWidth).filter((b) => parseFloat(b) > 1));
|
||||
assert.deepEqual(border, [], "no border stripes");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang}: a Vertex AI row names its Google credentials, never a missing key`, async (t) => {
|
||||
const { page, errors } = await start(t, lang, "rows", [saved, adc, file, bare, relay], presets(true));
|
||||
await page.locator(".row.provider .key").first().waitFor();
|
||||
const pills = await page.evaluate(() => Object.fromEntries([...document.querySelectorAll(".row.provider")].map((r) => {
|
||||
const k = r.querySelector(".key"), s = k.firstElementChild;
|
||||
return [r.dataset.id, { cls: k.className, text: k.textContent, title: k.title, cut: s.scrollWidth > s.clientWidth }];
|
||||
})));
|
||||
// the service account it acts as, too long for the pill and said whole on hover
|
||||
assert.deepEqual(pills["google-vertex"], { cls: "key acct", text: SA, title: `${w.as} · ~/keys/vertex-sa.json`, cut: true });
|
||||
assert.deepEqual(pills["google-vertex-2"], { cls: "key acct", text: w.adc, title: `${w.adc} · ${w.signed} · ${w.adcLong}`, cut: false });
|
||||
assert.deepEqual(pills["google-vertex-3"], { cls: "key acct", text: "dev-sa.json", title: `${w.signed} · ~/keys/dev-sa.json`, cut: false });
|
||||
assert.deepEqual(pills["google-vertex-4"], { cls: "key none", text: w.needsProject, title: `${w.needsProject} · ${w.open}`, cut: false });
|
||||
assert.equal(pills.relay.text, "sk-…one");
|
||||
for (const id of ["google-vertex", "google-vertex-2", "google-vertex-3", "google-vertex-4"]) assert(!w.noKey.includes(pills[id].text), id);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
|
||||
// every language, German's the longest: the pills say it whole, but for
|
||||
// a service account's email, longer than any pill holds, and the fields fit
|
||||
for (const lang of ["en", "zh", "ja", "de"]) for (const web of [false, true]) {
|
||||
test(`${engine} ${lang}: Vertex AI's pills and fields fit a narrow ${web ? "browser" : "window"}`, async (t) => {
|
||||
const { page, errors } = await start(t, lang, web ? "narrow-web" : "narrow", [saved, adc, bare, relay], presets(true), { web, width: 560 });
|
||||
await page.locator(".row.provider .key").first().waitFor();
|
||||
const cut = await page.evaluate(() => [...document.querySelectorAll(".row.provider .key > span")].filter((s) => s.scrollWidth > s.clientWidth).map((s) => s.textContent));
|
||||
assert.deepEqual(cut, [SA], "the pills cut");
|
||||
const ed = await edit(page, "google-vertex");
|
||||
for (const width of [560, 440]) {
|
||||
await page.setViewportSize({ width, height: 760 });
|
||||
await page.waitForTimeout(150);
|
||||
const bad = await ed.evaluate((ed, fields) => {
|
||||
const box = ed.getBoundingClientRect(), out = [];
|
||||
const inside = (e, what) => {
|
||||
const r = e.getBoundingClientRect();
|
||||
if (!r.width || r.left < box.left - 0.5 || r.right > box.right + 0.5) out.push(`${what} outside the editor: ${r.left}–${r.right} of ${box.left}–${box.right}`);
|
||||
return r;
|
||||
};
|
||||
for (const cls of fields) {
|
||||
const i = ed.querySelector("input." + cls), l = ed.querySelector(`label[for="${i.id}"]`), h = i.parentElement.querySelector(".hint");
|
||||
const ir = inside(i, cls), lr = inside(l, cls + "'s label");
|
||||
inside(h, cls + "'s hint");
|
||||
if (l.scrollWidth > l.clientWidth || l.scrollHeight > l.clientHeight) out.push(`${cls}'s label cut: ${l.textContent}`);
|
||||
if (h.scrollWidth > h.clientWidth) out.push(`${cls}'s hint cut`);
|
||||
if (lr.right > ir.left && lr.bottom > ir.top && lr.top < ir.bottom) out.push(`${cls}'s label over its box`);
|
||||
if (ir.width < 140) out.push(`${cls} ${ir.width}px wide`);
|
||||
}
|
||||
inside(ed.querySelector(".eps .ep"), "the endpoint");
|
||||
if (document.scrollingElement.scrollWidth > innerWidth) out.push("the page scrolls sideways");
|
||||
return out;
|
||||
}, FIELDS);
|
||||
assert.deepEqual(bad, [], `${width}px`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user