647 lines
20 KiB
Svelte
647 lines
20 KiB
Svelte
<script lang="ts">
|
|
import CloudModels from "./CloudModels.svelte";
|
|
import {
|
|
createMutation,
|
|
createQuery,
|
|
useQueryClient,
|
|
} from "@tanstack/svelte-query";
|
|
import { untrack } from "svelte";
|
|
import { SvelteSet } from "svelte/reactivity";
|
|
import { fade } from "svelte/transition";
|
|
|
|
import Modal from "$lib/components/ui/Modal.svelte";
|
|
import Button from "$lib/components/ui/Button.svelte";
|
|
import ConfirmDialog from "$lib/components/ui/ConfirmDialog.svelte";
|
|
import Icon from "$lib/components/ui/Icon.svelte";
|
|
|
|
import { comfy, settings, workflows, type ComfyEndpoint } from "$lib/api";
|
|
import { toast } from "$lib/toast";
|
|
import { t } from "$lib/i18n.svelte";
|
|
|
|
const client = useQueryClient();
|
|
|
|
// ------------------------------------------------------------------
|
|
// Data
|
|
// ------------------------------------------------------------------
|
|
const settingsQuery = createQuery({
|
|
queryKey: ["settings"],
|
|
queryFn: settings.get,
|
|
});
|
|
// HEL-682: the library browses metadata only (view=meta) — the heavy
|
|
// workflow_json payloads are fetched per-row inside WorkflowLibrary
|
|
// exactly when an action needs them.
|
|
const wfMetaQuery = createQuery({
|
|
queryKey: ["workflows", "meta"],
|
|
queryFn: workflows.listMeta,
|
|
});
|
|
|
|
const endpoints = $derived($settingsQuery.data?.comfyui_endpoints ?? []);
|
|
const activeId = $derived(
|
|
$settingsQuery.data?.comfyui_active_id ?? endpoints[0]?.id ?? "",
|
|
);
|
|
|
|
// ------------------------------------------------------------------
|
|
// Local test records — presentational only; the connectivity facts
|
|
// always come from the server-side probe.
|
|
// ------------------------------------------------------------------
|
|
type TestRec = {
|
|
ok: boolean;
|
|
ms?: number;
|
|
version?: string;
|
|
at: number;
|
|
reason?: string;
|
|
};
|
|
const TESTS_KEY = "calliope.connections.tests";
|
|
let tests = $state<Record<string, TestRec>>({});
|
|
let pendingTests = $state<Record<string, boolean>>({});
|
|
|
|
function loadTests() {
|
|
try {
|
|
const raw = localStorage.getItem(TESTS_KEY);
|
|
if (raw) tests = JSON.parse(raw) as Record<string, TestRec>;
|
|
} catch {
|
|
tests = {};
|
|
}
|
|
}
|
|
function saveTests(map: Record<string, TestRec>) {
|
|
tests = map;
|
|
try {
|
|
localStorage.setItem(TESTS_KEY, JSON.stringify(map));
|
|
} catch {
|
|
/* storage disabled — the page still works without persistence */
|
|
}
|
|
}
|
|
function recordTest(id: string, rec: TestRec) {
|
|
saveTests({ ...tests, [id]: rec });
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// Connection form (a6: right column, add / edit)
|
|
// ------------------------------------------------------------------
|
|
type FormMode = "idle" | "add" | "edit";
|
|
let formMode = $state<FormMode>("idle");
|
|
let editingId = $state<string | null>(null);
|
|
let form = $state({
|
|
name: "",
|
|
baseUrl: "",
|
|
authType: "none" as "none" | "bearer" | "header",
|
|
token: "",
|
|
headerName: "",
|
|
notes: "",
|
|
});
|
|
let formTest = $state<{ ok: boolean; ms?: number; version?: string } | null>(
|
|
null,
|
|
);
|
|
let formTestFailure = $state<{ message: string; detail: string } | null>(
|
|
null,
|
|
);
|
|
let formPending = $state(false);
|
|
let showErrors = $state(false);
|
|
|
|
function resetForm() {
|
|
formMode = "idle";
|
|
editingId = null;
|
|
form = {
|
|
name: "",
|
|
baseUrl: "",
|
|
authType: "none",
|
|
token: "",
|
|
headerName: "",
|
|
notes: "",
|
|
};
|
|
formTest = null;
|
|
formTestFailure = null;
|
|
showErrors = false;
|
|
}
|
|
|
|
export function startAdd() {
|
|
resetForm();
|
|
formMode = "add";
|
|
}
|
|
|
|
function startEdit(ep: ComfyEndpoint) {
|
|
resetForm();
|
|
formMode = "edit";
|
|
editingId = ep.id;
|
|
form = {
|
|
name: ep.name,
|
|
baseUrl: ep.base_url,
|
|
authType: ep.auth_type,
|
|
token: "",
|
|
headerName: ep.header_name ?? "",
|
|
notes: ep.notes ?? "",
|
|
};
|
|
}
|
|
|
|
function touchFormConnectivity() {
|
|
formTest = null;
|
|
formTestFailure = null;
|
|
}
|
|
|
|
const urlValid = $derived.by(() => {
|
|
try {
|
|
const u = new URL(form.baseUrl.trim());
|
|
return u.protocol === "http:" || u.protocol === "https:";
|
|
} catch {
|
|
return false;
|
|
}
|
|
});
|
|
|
|
const formErrors = $derived.by(() => {
|
|
const errs: Record<string, string> = {};
|
|
if (!form.name.trim()) errs.name = t("conn.errName");
|
|
if (!urlValid) errs.baseUrl = t("conn.errUrl");
|
|
if (form.authType === "header" && !form.headerName.trim())
|
|
errs.headerName = t("conn.errHeaderName");
|
|
return errs;
|
|
});
|
|
const formValid = $derived(Object.keys(formErrors).length === 0);
|
|
|
|
const editingEndpoint = $derived.by(() => {
|
|
if (formMode !== "edit" || !editingId) return null;
|
|
return endpoints.find((ep) => ep.id === editingId) ?? null;
|
|
});
|
|
|
|
async function runTest() {
|
|
showErrors = true;
|
|
if (!formValid) return;
|
|
formPending = true;
|
|
formTest = null;
|
|
formTestFailure = null;
|
|
try {
|
|
const res = await comfy.testEndpoint({
|
|
...(formMode === "edit" && editingId ? { endpoint_id: editingId } : {}),
|
|
base_url: form.baseUrl.trim(),
|
|
auth_type: form.authType,
|
|
...(form.authType !== "none" && form.token.trim()
|
|
? { auth_token: form.token.trim() }
|
|
: {}),
|
|
...(form.authType === "header" && form.headerName.trim()
|
|
? { header_name: form.headerName.trim() }
|
|
: {}),
|
|
timeout_sec: 5,
|
|
});
|
|
if (res.ok) {
|
|
formTest = {
|
|
ok: true,
|
|
ms: res.elapsed_ms,
|
|
version: res.comfyui_version,
|
|
};
|
|
} else {
|
|
formTest = { ok: false };
|
|
formTestFailure = {
|
|
message: res.message ?? res.detail ?? res.error ?? "",
|
|
detail: res.detail ?? "",
|
|
};
|
|
}
|
|
} catch (err) {
|
|
formTest = { ok: false };
|
|
formTestFailure = {
|
|
message: err instanceof Error ? err.message : String(err),
|
|
detail: "",
|
|
};
|
|
} finally {
|
|
formPending = false;
|
|
}
|
|
}
|
|
|
|
const saveMutation = createMutation({
|
|
mutationFn: async () => {
|
|
const payload: Record<string, unknown> = {
|
|
name: form.name.trim(),
|
|
base_url: form.baseUrl.trim(),
|
|
auth_type: form.authType,
|
|
notes: form.notes.trim() || null,
|
|
};
|
|
if (form.authType !== "none" && form.token.trim()) {
|
|
payload["auth_token"] = form.token.trim();
|
|
}
|
|
if (form.authType === "header")
|
|
payload["header_name"] = form.headerName.trim();
|
|
if (formMode === "edit" && editingId) {
|
|
return comfy.updateEndpoint(editingId, payload);
|
|
}
|
|
return comfy.createEndpoint(
|
|
payload as Parameters<typeof comfy.createEndpoint>[0],
|
|
);
|
|
},
|
|
onSuccess: (res) => {
|
|
client.invalidateQueries({ queryKey: ["settings"] });
|
|
if (formTest?.ok && editingId) {
|
|
recordTest(editingId, {
|
|
ok: true,
|
|
ms: formTest.ms,
|
|
version: formTest.version,
|
|
at: Date.now(),
|
|
});
|
|
} else if (formTest?.ok && res.endpoints.length) {
|
|
// newest is the one we just created when adding
|
|
const created = res.endpoints.find(
|
|
(ep) => ep.base_url === form.baseUrl.trim(),
|
|
);
|
|
if (created)
|
|
recordTest(created.id, {
|
|
ok: true,
|
|
ms: formTest.ms,
|
|
version: formTest.version,
|
|
at: Date.now(),
|
|
});
|
|
}
|
|
toast.success(t("conn.saved"));
|
|
resetForm();
|
|
},
|
|
onError: (err) => {
|
|
toast.error(
|
|
t("conn.saveFailed", {
|
|
detail: err instanceof Error ? err.message : String(err),
|
|
}),
|
|
);
|
|
},
|
|
});
|
|
|
|
function submitSave() {
|
|
showErrors = true;
|
|
if (!formValid || !formTest?.ok || $saveMutation.isPending) return;
|
|
$saveMutation.mutate();
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// Card actions
|
|
// ------------------------------------------------------------------
|
|
async function testEndpoint(ep: ComfyEndpoint) {
|
|
pendingTests = { ...pendingTests, [ep.id]: true };
|
|
try {
|
|
const res = await comfy.testEndpoint({
|
|
endpoint_id: ep.id,
|
|
timeout_sec: 10,
|
|
});
|
|
if (res.ok) {
|
|
recordTest(ep.id, {
|
|
ok: true,
|
|
ms: res.elapsed_ms,
|
|
version: res.comfyui_version,
|
|
at: Date.now(),
|
|
});
|
|
} else {
|
|
recordTest(ep.id, {
|
|
ok: false,
|
|
at: Date.now(),
|
|
reason: res.message ?? res.detail ?? res.error ?? "unknown",
|
|
});
|
|
}
|
|
} catch (err) {
|
|
recordTest(ep.id, {
|
|
ok: false,
|
|
at: Date.now(),
|
|
reason: err instanceof Error ? err.message : String(err),
|
|
});
|
|
} finally {
|
|
const next = { ...pendingTests };
|
|
delete next[ep.id];
|
|
pendingTests = next;
|
|
}
|
|
}
|
|
|
|
let deleteOpen = $state(false);
|
|
let deleteTarget = $state<ComfyEndpoint | null>(null);
|
|
|
|
function requestDelete(ep: ComfyEndpoint) {
|
|
deleteTarget = ep;
|
|
deleteOpen = true;
|
|
}
|
|
|
|
function workflowsBound(id: string): number {
|
|
return ($wfMetaQuery.data ?? []).filter(
|
|
(wf) => wf.endpoint_id === id || (!wf.endpoint_id && id === activeId),
|
|
).length;
|
|
}
|
|
|
|
const deleteMessage = $derived.by(() => {
|
|
if (!deleteTarget) return "";
|
|
const n = workflowsBound(deleteTarget.id);
|
|
return n > 0
|
|
? t("conn.delConfirmUsed", { name: deleteTarget.name })
|
|
: t("conn.delConfirmFree", { name: deleteTarget.name });
|
|
});
|
|
|
|
const deleteMutation = createMutation({
|
|
mutationFn: () => {
|
|
if (!deleteTarget) throw new Error("no target");
|
|
return comfy.deleteEndpoint(deleteTarget.id);
|
|
},
|
|
onSuccess: () => {
|
|
if (deleteTarget) {
|
|
const next = { ...tests };
|
|
delete next[deleteTarget.id];
|
|
saveTests(next);
|
|
if (editingId === deleteTarget.id) resetForm();
|
|
}
|
|
client.invalidateQueries({ queryKey: ["settings"] });
|
|
toast.success(t("conn.deleted"));
|
|
},
|
|
onError: (err) => {
|
|
toast.error(
|
|
t("conn.saveFailed", {
|
|
detail: err instanceof Error ? err.message : String(err),
|
|
}),
|
|
);
|
|
},
|
|
});
|
|
|
|
const defaultMutation = createMutation({
|
|
mutationFn: (id: string) => comfy.activateEndpoint(id),
|
|
onSuccess: () => {
|
|
client.invalidateQueries({ queryKey: ["settings"] });
|
|
toast.success(t("conn.defaultSetToast"));
|
|
},
|
|
onError: (err) => {
|
|
toast.error(
|
|
t("conn.saveFailed", {
|
|
detail: err instanceof Error ? err.message : String(err),
|
|
}),
|
|
);
|
|
},
|
|
});
|
|
|
|
function tokenTail(ep: ComfyEndpoint): string {
|
|
const tail = ep.token_tail ?? "";
|
|
return tail ? `****${tail}` : "";
|
|
}
|
|
|
|
loadTests();
|
|
$effect(() => {
|
|
// prune stale test records once the endpoint list is known
|
|
const data = $settingsQuery.data;
|
|
if (data) {
|
|
const keep = new Set(data.comfyui_endpoints.map((ep) => ep.id));
|
|
let changed = false;
|
|
const next: Record<string, TestRec> = {};
|
|
for (const [k, v] of Object.entries(tests)) {
|
|
if (keep.has(k)) next[k] = v;
|
|
else changed = true;
|
|
}
|
|
if (changed) saveTests(next);
|
|
}
|
|
});
|
|
|
|
// Probe every connection once per visit so the cards show real state
|
|
// instead of 「未测试」; results younger than a minute are reused.
|
|
const autoProbed = new SvelteSet<string>();
|
|
$effect(() => {
|
|
const list = endpoints;
|
|
untrack(() => {
|
|
const now = Date.now();
|
|
for (const ep of list) {
|
|
if (autoProbed.has(ep.id)) continue;
|
|
autoProbed.add(ep.id);
|
|
const rec = tests[ep.id];
|
|
if (!rec || now - rec.at > 60_000) void testEndpoint(ep);
|
|
}
|
|
});
|
|
});
|
|
</script>
|
|
|
|
{#if $settingsQuery.isLoading}<p class="mg-empty">
|
|
正在读取连接…
|
|
</p>{:else if $settingsQuery.isError}<p class="mg-empty" role="alert">
|
|
连接加载失败<Button onclick={() => $settingsQuery.refetch()}>重试</Button>
|
|
</p>{:else}
|
|
<div class="mg-cards">
|
|
{#each endpoints as ep (ep.id)}{@const rec = tests[ep.id]}
|
|
<article class="mg-card">
|
|
<div class="mg-row">
|
|
<span
|
|
class="mg-dot"
|
|
class:ok={rec?.ok === true}
|
|
class:err={rec?.ok === false}
|
|
></span><b>{ep.name}</b><span class="mg-grow"></span><span
|
|
class="mg-latency"
|
|
>{rec?.ms != null ? Math.round(rec.ms) + "ms" : "—"}</span
|
|
>
|
|
</div>
|
|
<div class="mg-mono">{ep.base_url}</div>
|
|
<div class="mg-muted">
|
|
{rec?.ok === false
|
|
? "连接失败 · " + (rec.reason ?? "原因未知")
|
|
: rec?.ok
|
|
? "连接测试通过"
|
|
: "尚未测试"} · 队列未知 · 显存未知
|
|
</div>
|
|
<div class="mg-row">
|
|
<span class="mg-tag">{workflowsBound(ep.id)} 个工作流使用</span><span
|
|
class="mg-grow"
|
|
></span><Button
|
|
size="sm"
|
|
loading={pendingTests[ep.id]}
|
|
onclick={() => testEndpoint(ep)}>测试连接</Button
|
|
><Button variant="ghost" size="sm" onclick={() => startEdit(ep)}
|
|
>编辑</Button
|
|
>
|
|
</div>
|
|
</article>
|
|
{/each}
|
|
<CloudModels />
|
|
<button class="mg-card pending mg-add" onclick={startAdd}
|
|
><Icon name="plus" size={22} />添加连接</button
|
|
>
|
|
</div>{/if}
|
|
<Modal
|
|
open={formMode !== "idle"}
|
|
title={formMode === "add" ? t("conn.formTitleAdd") : t("conn.formTitleEdit")}
|
|
dismissible={!formPending && !$saveMutation.isPending}
|
|
onclose={resetForm}
|
|
>
|
|
<aside
|
|
class="form-col"
|
|
class:open={formMode !== "idle"}
|
|
aria-label={t("conn.formTitleAdd")}
|
|
>
|
|
{#if formMode !== "idle"}
|
|
<div class="form-head">
|
|
<h2>
|
|
{formMode === "add"
|
|
? t("conn.formTitleAdd")
|
|
: t("conn.formTitleEdit")}
|
|
</h2>
|
|
</div>
|
|
|
|
<label class="f-field">
|
|
<span class="f-label">{t("conn.fName")}<em>*</em></span>
|
|
<input
|
|
class="f-input"
|
|
class:invalid={showErrors && formErrors.name}
|
|
value={form.name}
|
|
disabled={formPending}
|
|
oninput={(e) => (form.name = e.currentTarget.value)}
|
|
placeholder={t("conn.fNamePh")}
|
|
/>
|
|
{#if showErrors && formErrors.name}<span class="f-error"
|
|
>{formErrors.name}</span
|
|
>{/if}
|
|
</label>
|
|
|
|
<label class="f-field">
|
|
<span class="f-label">{t("conn.fBaseUrl")}<em>*</em></span>
|
|
<input
|
|
class="f-input mono"
|
|
class:invalid={showErrors && formErrors.baseUrl}
|
|
value={form.baseUrl}
|
|
disabled={formPending}
|
|
spellcheck="false"
|
|
oninput={(e) => {
|
|
form.baseUrl = e.currentTarget.value;
|
|
touchFormConnectivity();
|
|
}}
|
|
placeholder={t("conn.fBaseUrlPh")}
|
|
/>
|
|
{#if showErrors && formErrors.baseUrl}
|
|
<span class="f-error">{formErrors.baseUrl}</span>
|
|
{/if}
|
|
<span class="f-hint">{t("conn.baseUrlHelp")}</span>
|
|
</label>
|
|
|
|
<div class="f-field">
|
|
<span class="f-label">{t("conn.fAuth")}</span>
|
|
<div class="mg-seg" role="radiogroup" aria-label={t("conn.fAuth")}>
|
|
{#each [["none", t("conn.authNone")], ["bearer", t("conn.authBearer")], ["header", t("conn.authHeader")]] as [value, label] (value)}
|
|
<button
|
|
type="button"
|
|
class="seg-item"
|
|
class:on={form.authType === value}
|
|
aria-pressed={form.authType === value}
|
|
onclick={() => {
|
|
form.authType = value as typeof form.authType;
|
|
touchFormConnectivity();
|
|
}}
|
|
>
|
|
{label}
|
|
</button>
|
|
{/each}
|
|
</div>
|
|
<span class="f-hint">{t("conn.authHelp")}</span>
|
|
</div>
|
|
|
|
{#if form.authType !== "none"}
|
|
{#if form.authType === "header"}
|
|
<label class="f-field">
|
|
<span class="f-label">{t("conn.fHeaderName")}<em>*</em></span>
|
|
<input
|
|
class="f-input mono"
|
|
class:invalid={showErrors && formErrors.headerName}
|
|
value={form.headerName}
|
|
disabled={formPending}
|
|
spellcheck="false"
|
|
oninput={(e) => {
|
|
form.headerName = e.currentTarget.value;
|
|
touchFormConnectivity();
|
|
}}
|
|
placeholder={t("conn.fHeaderNamePh")}
|
|
/>
|
|
{#if showErrors && formErrors.headerName}
|
|
<span class="f-error">{formErrors.headerName}</span>
|
|
{/if}
|
|
</label>
|
|
{/if}
|
|
<label class="f-field">
|
|
<span class="f-label">
|
|
{t("conn.fToken")}
|
|
<span class="kh-inline mono">{t("conn.keyNoEcho")}</span>
|
|
</span>
|
|
<span class="key-wrap">
|
|
<input
|
|
class="f-input key-input"
|
|
type="password"
|
|
value={form.token}
|
|
disabled={formPending}
|
|
autocomplete="off"
|
|
oninput={(e) => {
|
|
form.token = e.currentTarget.value;
|
|
touchFormConnectivity();
|
|
}}
|
|
placeholder={formMode === "edit" && editingEndpoint?.has_token
|
|
? t("conn.tokenSaved")
|
|
: "…"}
|
|
/>
|
|
{#if formMode === "edit" && editingEndpoint?.has_token && tokenTail(editingEndpoint)}
|
|
<span class="kh mono">{tokenTail(editingEndpoint)}</span>
|
|
{/if}
|
|
</span>
|
|
<span class="f-hint">{t("conn.keyHelp")}</span>
|
|
</label>
|
|
{/if}
|
|
|
|
<label class="f-field">
|
|
<span class="f-label">{t("conn.fNotes")}</span>
|
|
<input
|
|
class="f-input"
|
|
value={form.notes}
|
|
disabled={formPending}
|
|
oninput={(e) => (form.notes = e.currentTarget.value)}
|
|
placeholder={t("conn.fNotesPh")}
|
|
/>
|
|
</label>
|
|
|
|
{#if formTest?.ok}
|
|
<div class="result-bar ok" transition:fade={{ duration: 250 }}>
|
|
{t("conn.testOk", {
|
|
ms: formTest.ms ?? "?",
|
|
v: formTest.version ?? "?",
|
|
})}
|
|
</div>
|
|
{:else if formTest?.ok === false && formTestFailure}
|
|
<div class="result-bar err" transition:fade={{ duration: 250 }}>
|
|
<p>{t("conn.testFail", { reason: formTestFailure.message })}</p>
|
|
{#if formTestFailure.detail}
|
|
<p class="mono detail">{formTestFailure.detail}</p>
|
|
{/if}
|
|
</div>
|
|
{/if}
|
|
|
|
<div class="form-actions">
|
|
<span class="need-test" class:passed={formTest?.ok}
|
|
>{t("conn.needTest")}</span
|
|
>
|
|
<Button
|
|
variant="secondary"
|
|
size="sm"
|
|
loading={formPending}
|
|
onclick={runTest}
|
|
>
|
|
{formPending ? t("conn.testing") : t("conn.testBtn")}
|
|
</Button>
|
|
<Button
|
|
variant="primary"
|
|
size="sm"
|
|
disabled={!formValid || !formTest?.ok}
|
|
loading={$saveMutation.isPending}
|
|
onclick={submitSave}
|
|
>
|
|
{t("conn.save")}
|
|
</Button>
|
|
</div>
|
|
{/if}
|
|
{#if formMode === "edit" && editingId}<div class="mg-row">
|
|
{#if editingId !== activeId}<Button
|
|
size="sm"
|
|
onclick={() => $defaultMutation.mutate(editingId!)}>设为默认</Button
|
|
>{/if}<Button
|
|
size="sm"
|
|
variant="danger"
|
|
onclick={() => {
|
|
const target = editingEndpoint;
|
|
if (target) requestDelete(target);
|
|
}}>删除</Button
|
|
>
|
|
</div>{/if}
|
|
</aside></Modal
|
|
>
|
|
<ConfirmDialog
|
|
bind:open={deleteOpen}
|
|
title={t("conn.delTitle")}
|
|
message={deleteMessage}
|
|
confirmLabel={t("conn.delete")}
|
|
danger
|
|
onconfirm={() => $deleteMutation.mutate()}
|
|
oncancel={() => (deleteTarget = null)}
|
|
/>
|