release: publish ImageStudio 1.0.8
这个提交存在于:
父节点
d4ad94eae9
当前提交
b5dd6c5d26
共有 24 个文件被更改,包括 500 次插入 和 176 次删除
|
|
@ -6,6 +6,7 @@ import json
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import urllib.error
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
import urllib.request
|
import urllib.request
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
@ -231,6 +232,7 @@ def _live_probe(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
custom_headers = custom_headers if isinstance(custom_headers, dict) else {}
|
custom_headers = custom_headers if isinstance(custom_headers, dict) else {}
|
||||||
headers = {
|
headers = {
|
||||||
"Accept": "application/json",
|
"Accept": "application/json",
|
||||||
|
"User-Agent": "AstrBot-ImageStudio/1.0.8",
|
||||||
**{str(key): str(value) for key, value in custom_headers.items()},
|
**{str(key): str(value) for key, value in custom_headers.items()},
|
||||||
**({"Authorization": f"Bearer {api_key}"} if api_key else {}),
|
**({"Authorization": f"Bearer {api_key}"} if api_key else {}),
|
||||||
}
|
}
|
||||||
|
|
@ -247,27 +249,37 @@ def _live_probe(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
result["resolved_api_base"] = api_prefix
|
result["resolved_api_base"] = api_prefix
|
||||||
result["image_endpoint"] = "/images/generations" if base_url.lower().endswith("/v1") else "/v1/images/generations"
|
result["image_endpoint"] = "/images/generations" if base_url.lower().endswith("/v1") else "/v1/images/generations"
|
||||||
try:
|
try:
|
||||||
request = urllib.request.Request(models_url, headers=headers, method="GET")
|
status, raw_body, response_headers = _http_request(
|
||||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
"GET",
|
||||||
body = response.read(2 * 1024 * 1024).decode("utf-8-sig")
|
models_url,
|
||||||
|
headers=headers,
|
||||||
|
timeout=timeout,
|
||||||
|
max_bytes=2 * 1024 * 1024,
|
||||||
|
)
|
||||||
|
body = raw_body.decode("utf-8-sig", errors="replace")
|
||||||
|
result["http_status"] = status
|
||||||
|
if 200 <= status < 300:
|
||||||
parsed = json.loads(body)
|
parsed = json.loads(body)
|
||||||
items = parsed.get("data", []) if isinstance(parsed, dict) else []
|
items = parsed.get("data", []) if isinstance(parsed, dict) else []
|
||||||
result["models"] = [str(item.get("id")) for item in items if isinstance(item, dict) and item.get("id")][:200]
|
result["models"] = [str(item.get("id")) for item in items if isinstance(item, dict) and item.get("id")][:200]
|
||||||
result["connected"] = True
|
result["connected"] = True
|
||||||
result["http_status"] = response.status
|
else:
|
||||||
except urllib.error.HTTPError as exc:
|
result["error"] = f"models endpoint returned HTTP {status}"
|
||||||
try:
|
result["error_body"] = _redact_probe_error(body[:500])
|
||||||
error_body = exc.read(4096).decode("utf-8-sig", errors="replace")
|
content_type = response_headers.get("content-type")
|
||||||
except Exception:
|
if content_type:
|
||||||
error_body = ""
|
result["content_type"] = content_type
|
||||||
result.update(
|
location = response_headers.get("location")
|
||||||
{
|
if location:
|
||||||
"http_status": exc.code,
|
redirect_target = urllib.parse.urljoin(models_url, location)
|
||||||
"error": f"models endpoint returned HTTP {exc.code}",
|
result["redirect_target"] = redirect_target
|
||||||
"error_body": _redact_probe_error(error_body[:500]),
|
result["warnings"].append(
|
||||||
}
|
{
|
||||||
)
|
"message": "models endpoint redirected; authorization was not forwarded across origins",
|
||||||
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError, UnicodeDecodeError) as exc:
|
"target": redirect_target,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError, UnicodeDecodeError, OSError) as exc:
|
||||||
result["error"] = str(exc)
|
result["error"] = str(exc)
|
||||||
|
|
||||||
if payload.get("allow_lightweight_test") and result["connected"]:
|
if payload.get("allow_lightweight_test") and result["connected"]:
|
||||||
|
|
@ -278,16 +290,62 @@ def _live_probe(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
model_id = str(payload.get("model_id") or "").strip()
|
model_id = str(payload.get("model_id") or "").strip()
|
||||||
for size in ("1920x1080", "2560x1440", "3840x2160"):
|
for size in ("1920x1080", "2560x1440", "3840x2160"):
|
||||||
data = json.dumps({"model": model_id, "prompt": "A plain gray circle on white background, capability test", "size": size, "n": 1, "response_format": "b64_json"}).encode("utf-8")
|
data = json.dumps({"model": model_id, "prompt": "A plain gray circle on white background, capability test", "size": size, "n": 1, "response_format": "b64_json"}).encode("utf-8")
|
||||||
request = urllib.request.Request(endpoint_url, data=data, headers={**headers, "Content-Type": "application/json"}, method="POST")
|
|
||||||
try:
|
try:
|
||||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
status, _, _ = _http_request(
|
||||||
response.read(1024)
|
"POST",
|
||||||
|
endpoint_url,
|
||||||
|
headers={**headers, "Content-Type": "application/json"},
|
||||||
|
timeout=timeout,
|
||||||
|
data=data,
|
||||||
|
max_bytes=1024,
|
||||||
|
)
|
||||||
|
if not 200 <= status < 300:
|
||||||
|
raise RuntimeError(f"HTTP {status}")
|
||||||
|
else:
|
||||||
result["supported_sizes"].append(size)
|
result["supported_sizes"].append(size)
|
||||||
except Exception as exc: # Provider dialects expose inconsistent errors; retain a short diagnostic only.
|
except Exception as exc: # Provider dialects expose inconsistent errors; retain a short diagnostic only.
|
||||||
result["warnings"].append({"size": size, "message": str(exc)[:180]})
|
result["warnings"].append({"size": size, "message": str(exc)[:180]})
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _http_request(
|
||||||
|
method: str,
|
||||||
|
url: str,
|
||||||
|
*,
|
||||||
|
headers: dict[str, str],
|
||||||
|
timeout: int,
|
||||||
|
data: bytes | None = None,
|
||||||
|
max_bytes: int,
|
||||||
|
) -> tuple[int, bytes, dict[str, str]]:
|
||||||
|
try:
|
||||||
|
import httpx
|
||||||
|
except ImportError:
|
||||||
|
request = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||||
|
return response.status, response.read(max_bytes), {key.lower(): value for key, value in response.headers.items()}
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
return exc.code, exc.read(max_bytes), {key.lower(): value for key, value in exc.headers.items()}
|
||||||
|
|
||||||
|
with httpx.stream(
|
||||||
|
method,
|
||||||
|
url,
|
||||||
|
headers=headers,
|
||||||
|
content=data,
|
||||||
|
timeout=timeout,
|
||||||
|
follow_redirects=False,
|
||||||
|
) as response:
|
||||||
|
chunks: list[bytes] = []
|
||||||
|
total = 0
|
||||||
|
for chunk in response.iter_bytes():
|
||||||
|
if total >= max_bytes:
|
||||||
|
break
|
||||||
|
remaining = max_bytes - total
|
||||||
|
chunks.append(chunk[:remaining])
|
||||||
|
total += min(len(chunk), remaining)
|
||||||
|
return response.status_code, b"".join(chunks), {key.lower(): value for key, value in response.headers.items()}
|
||||||
|
|
||||||
|
|
||||||
def _redact_probe_error(value: str) -> str:
|
def _redact_probe_error(value: str) -> str:
|
||||||
redacted = re.sub(r"(?i)bearer\s+[a-z0-9._-]+", "Bearer ***", value)
|
redacted = re.sub(r"(?i)bearer\s+[a-z0-9._-]+", "Bearer ***", value)
|
||||||
return re.sub(r"(?i)sk[-_][a-z0-9._-]{8,}", "sk-***", redacted)
|
return re.sub(r"(?i)sk[-_][a-z0-9._-]{8,}", "sk-***", redacted)
|
||||||
|
|
|
||||||
|
|
@ -653,11 +653,41 @@ def _merge_masked(current: Mapping[str, Any], incoming: Mapping[str, Any]) -> di
|
||||||
continue
|
continue
|
||||||
if isinstance(value, Mapping) and isinstance(result.get(key), Mapping):
|
if isinstance(value, Mapping) and isinstance(result.get(key), Mapping):
|
||||||
result[str(key)] = _merge_masked(result[key], value)
|
result[str(key)] = _merge_masked(result[key], value)
|
||||||
|
elif isinstance(value, list) and isinstance(result.get(key), list):
|
||||||
|
result[str(key)] = _merge_masked_list(result[key], value)
|
||||||
else:
|
else:
|
||||||
result[str(key)] = value
|
result[str(key)] = value
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_masked_list(current: list[Any], incoming: list[Any]) -> list[Any]:
|
||||||
|
merged: list[Any] = []
|
||||||
|
for index, item in enumerate(incoming):
|
||||||
|
existing = _matching_list_mapping(current, item, index)
|
||||||
|
if isinstance(item, Mapping):
|
||||||
|
merged.append(_merge_masked(existing if isinstance(existing, Mapping) else {}, item))
|
||||||
|
elif isinstance(item, str) and item in {"***MASKED***", "***PATH***"} and index < len(current):
|
||||||
|
merged.append(current[index])
|
||||||
|
else:
|
||||||
|
merged.append(item)
|
||||||
|
return merged
|
||||||
|
|
||||||
|
|
||||||
|
def _matching_list_mapping(current: list[Any], incoming: Any, index: int) -> Mapping[str, Any] | None:
|
||||||
|
if not isinstance(incoming, Mapping):
|
||||||
|
return None
|
||||||
|
for identity_key in ("id", "provider_id", "route_id", "category_id", "category", "key"):
|
||||||
|
identity = incoming.get(identity_key)
|
||||||
|
if identity in (None, ""):
|
||||||
|
continue
|
||||||
|
for item in current:
|
||||||
|
if isinstance(item, Mapping) and item.get(identity_key) == identity:
|
||||||
|
return item
|
||||||
|
if index < len(current) and isinstance(current[index], Mapping):
|
||||||
|
return current[index]
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _runtime_override_conflicts(incoming: Mapping[str, Any], config_path: Path) -> list[str]:
|
def _runtime_override_conflicts(incoming: Mapping[str, Any], config_path: Path) -> list[str]:
|
||||||
if not is_default_config_path(config_path):
|
if not is_default_config_path(config_path):
|
||||||
return []
|
return []
|
||||||
|
|
@ -665,7 +695,21 @@ def _runtime_override_conflicts(incoming: Mapping[str, Any], config_path: Path)
|
||||||
if not overrides:
|
if not overrides:
|
||||||
return []
|
return []
|
||||||
candidate = _flatten(incoming)
|
candidate = _flatten(incoming)
|
||||||
return sorted(path for path, value in overrides.items() if path in candidate and candidate[path] != value)
|
generation = incoming.get("generation") if isinstance(incoming.get("generation"), Mapping) else {}
|
||||||
|
uses_plugin_adapters = isinstance(generation.get("adapters"), list)
|
||||||
|
|
||||||
|
def is_plugin_adapter_compatibility_field(path: str) -> bool:
|
||||||
|
if not uses_plugin_adapters:
|
||||||
|
return False
|
||||||
|
return path == "generation.default_model" or path.startswith("generation.provider.")
|
||||||
|
|
||||||
|
return sorted(
|
||||||
|
path
|
||||||
|
for path, value in overrides.items()
|
||||||
|
if path in candidate
|
||||||
|
and candidate[path] != value
|
||||||
|
and not is_plugin_adapter_compatibility_field(path)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _restore_runtime_managed_fields(
|
def _restore_runtime_managed_fields(
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
plugin:
|
plugin:
|
||||||
name: astrbot_plugin_imagestudio
|
name: astrbot_plugin_imagestudio
|
||||||
display_name: ImageStudio
|
display_name: ImageStudio
|
||||||
version: 1.0.6
|
version: 1.0.8
|
||||||
|
|
||||||
features:
|
features:
|
||||||
quick_profile: true
|
quick_profile: true
|
||||||
|
|
|
||||||
|
|
@ -10,11 +10,14 @@ from core.runtime_paths import resolve_config_path
|
||||||
from database.db_helper import load_config_payload
|
from database.db_helper import load_config_payload
|
||||||
|
|
||||||
|
|
||||||
|
PLUGIN_VERSION = "1.0.8"
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class PluginConfig:
|
class PluginConfig:
|
||||||
name: str = "astrbot_plugin_imagestudio"
|
name: str = "astrbot_plugin_imagestudio"
|
||||||
display_name: str = "ImageStudio"
|
display_name: str = "ImageStudio"
|
||||||
version: str = "3.0.0"
|
version: str = PLUGIN_VERSION
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
|
|
@ -61,7 +64,10 @@ class ConfigService:
|
||||||
plugin=PluginConfig(
|
plugin=PluginConfig(
|
||||||
name=str(plugin.get("name", "astrbot_plugin_imagestudio")),
|
name=str(plugin.get("name", "astrbot_plugin_imagestudio")),
|
||||||
display_name=str(plugin.get("display_name", "ImageStudio")),
|
display_name=str(plugin.get("display_name", "ImageStudio")),
|
||||||
version=str(plugin.get("version", "3.0.0")),
|
# The installed package version is immutable metadata. A
|
||||||
|
# writable AstrBot config may survive plugin upgrades, so it
|
||||||
|
# must not override the version shown by ui/bootstrap.
|
||||||
|
version=PLUGIN_VERSION,
|
||||||
),
|
),
|
||||||
features={key: bool(value) for key, value in features.items()},
|
features={key: bool(value) for key, value in features.items()},
|
||||||
storage=StorageConfig(
|
storage=StorageConfig(
|
||||||
|
|
|
||||||
|
|
@ -76,4 +76,8 @@ def _format_scalar(value: Any) -> str:
|
||||||
return "null"
|
return "null"
|
||||||
if isinstance(value, (int, float)):
|
if isinstance(value, (int, float)):
|
||||||
return str(value)
|
return str(value)
|
||||||
|
if isinstance(value, (Mapping, list)):
|
||||||
|
# JSON flow collections are valid YAML and preserve nested adapter
|
||||||
|
# objects without requiring a full YAML dependency.
|
||||||
|
return json.dumps(value, ensure_ascii=False)
|
||||||
return json.dumps(str(value), ensure_ascii=False)
|
return json.dumps(str(value), ensure_ascii=False)
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,9 @@ from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
import ast
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Iterable, Mapping
|
from typing import Any, Iterable, Mapping
|
||||||
|
|
@ -145,10 +147,12 @@ class Database:
|
||||||
self._ensure_schema_migrations(conn)
|
self._ensure_schema_migrations(conn)
|
||||||
for migration_path in self._iter_migrations(migrations_dir):
|
for migration_path in self._iter_migrations(migrations_dir):
|
||||||
version = migration_path.stem
|
version = migration_path.stem
|
||||||
if self._migration_applied(conn, version):
|
script = migration_path.read_text(encoding="utf-8")
|
||||||
|
if self._migration_applied(conn, version) and self._migration_tables_exist(conn, script):
|
||||||
continue
|
continue
|
||||||
self._execute_script(conn, migration_path.read_text(encoding="utf-8"))
|
self._execute_script(conn, script)
|
||||||
self._mark_migration_applied(conn, version)
|
if not self._migration_applied(conn, version):
|
||||||
|
self._mark_migration_applied(conn, version)
|
||||||
if self.backend == "postgresql":
|
if self.backend == "postgresql":
|
||||||
conn.commit()
|
conn.commit()
|
||||||
else:
|
else:
|
||||||
|
|
@ -226,6 +230,24 @@ class Database:
|
||||||
(version,),
|
(version,),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _migration_tables_exist(self, conn, script: str) -> bool:
|
||||||
|
table_names = re.findall(
|
||||||
|
r"CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS\s+([A-Za-z_][A-Za-z0-9_]*)",
|
||||||
|
script,
|
||||||
|
flags=re.IGNORECASE,
|
||||||
|
)
|
||||||
|
if not table_names:
|
||||||
|
return True
|
||||||
|
placeholder = self._placeholder
|
||||||
|
if self.backend == "sqlite":
|
||||||
|
query = f"SELECT name FROM sqlite_master WHERE type = 'table' AND name = {placeholder}"
|
||||||
|
else:
|
||||||
|
query = (
|
||||||
|
"SELECT table_name FROM information_schema.tables "
|
||||||
|
f"WHERE table_schema = current_schema() AND table_name = {placeholder}"
|
||||||
|
)
|
||||||
|
return all(conn.execute(query, (table_name,)).fetchone() is not None for table_name in table_names)
|
||||||
|
|
||||||
def _execute_script(self, conn, script: str) -> None:
|
def _execute_script(self, conn, script: str) -> None:
|
||||||
if self.backend == "sqlite":
|
if self.backend == "sqlite":
|
||||||
conn.executescript(script)
|
conn.executescript(script)
|
||||||
|
|
@ -360,9 +382,22 @@ def _load_yaml_subset(text: str) -> dict[str, Any]:
|
||||||
def _parse_scalar(value: str) -> Any:
|
def _parse_scalar(value: str) -> Any:
|
||||||
if len(value) >= 2 and value[0] == value[-1] == '"':
|
if len(value) >= 2 and value[0] == value[-1] == '"':
|
||||||
try:
|
try:
|
||||||
return json.loads(value)
|
parsed = json.loads(value)
|
||||||
|
if isinstance(parsed, str) and parsed.lstrip().startswith(("{", "[")):
|
||||||
|
try:
|
||||||
|
legacy = ast.literal_eval(parsed)
|
||||||
|
except (SyntaxError, ValueError):
|
||||||
|
return parsed
|
||||||
|
if isinstance(legacy, (dict, list)):
|
||||||
|
return legacy
|
||||||
|
return parsed
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
return value[1:-1]
|
return value[1:-1]
|
||||||
|
if value.startswith(("{", "[")):
|
||||||
|
try:
|
||||||
|
return json.loads(value)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
if len(value) >= 2 and value[0] == value[-1] == "'":
|
if len(value) >= 2 and value[0] == value[-1] == "'":
|
||||||
return value[1:-1].replace("''", "'")
|
return value[1:-1].replace("''", "'")
|
||||||
lowered = value.lower()
|
lowered = value.lower()
|
||||||
|
|
|
||||||
4
frontend/package-lock.json
自动生成
4
frontend/package-lock.json
自动生成
|
|
@ -1,12 +1,12 @@
|
||||||
{
|
{
|
||||||
"name": "astrbot-plugin-imagestudio-frontend",
|
"name": "astrbot-plugin-imagestudio-frontend",
|
||||||
"version": "1.0.6",
|
"version": "1.0.8",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "astrbot-plugin-imagestudio-frontend",
|
"name": "astrbot-plugin-imagestudio-frontend",
|
||||||
"version": "1.0.6",
|
"version": "1.0.8",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@vitejs/plugin-vue": "^5.2.0",
|
"@vitejs/plugin-vue": "^5.2.0",
|
||||||
"pinia": "^2.3.0",
|
"pinia": "^2.3.0",
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "astrbot-plugin-imagestudio-frontend",
|
"name": "astrbot-plugin-imagestudio-frontend",
|
||||||
"version": "1.0.6",
|
"version": "1.0.8",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,6 @@
|
||||||
import { createApp } from "vue"
|
import { createApp } from "vue"
|
||||||
import App from "./App.vue"
|
import App from "./App.vue"
|
||||||
|
import { installAstrBotPluginPageBridge } from "../../shared/api/astrbot-page-bridge"
|
||||||
|
|
||||||
|
installAstrBotPluginPageBridge()
|
||||||
createApp(App).mount("#app")
|
createApp(App).mount("#app")
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,101 @@
|
||||||
|
const CHANNEL = "astrbot-plugin-page"
|
||||||
|
const READY_RETRY_MS = 250
|
||||||
|
const REQUEST_TIMEOUT_MS = 15000
|
||||||
|
|
||||||
|
type PendingRequest = {
|
||||||
|
resolve(value: unknown): void
|
||||||
|
reject(error: Error): void
|
||||||
|
timer: ReturnType<typeof window.setTimeout>
|
||||||
|
}
|
||||||
|
|
||||||
|
type BridgeMessage = {
|
||||||
|
channel?: string
|
||||||
|
kind?: string
|
||||||
|
requestId?: string
|
||||||
|
ok?: boolean
|
||||||
|
data?: unknown
|
||||||
|
error?: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
export function installAstrBotPluginPageBridge() {
|
||||||
|
if (typeof window === "undefined" || window.parent === window) return
|
||||||
|
|
||||||
|
const pending = new Map<string, PendingRequest>()
|
||||||
|
let ready = false
|
||||||
|
let readyTimer: ReturnType<typeof window.setInterval> | undefined
|
||||||
|
let resolveReady: (() => void) | undefined
|
||||||
|
const readyPromise = new Promise<void>((resolve) => {
|
||||||
|
resolveReady = resolve
|
||||||
|
})
|
||||||
|
|
||||||
|
const postReady = () => {
|
||||||
|
window.parent.postMessage({ channel: CHANNEL, kind: "ready" }, "*")
|
||||||
|
}
|
||||||
|
|
||||||
|
const markReady = () => {
|
||||||
|
if (ready) return
|
||||||
|
ready = true
|
||||||
|
if (readyTimer !== undefined) {
|
||||||
|
window.clearInterval(readyTimer)
|
||||||
|
readyTimer = undefined
|
||||||
|
}
|
||||||
|
resolveReady?.()
|
||||||
|
}
|
||||||
|
|
||||||
|
const onMessage = (event: MessageEvent<BridgeMessage>) => {
|
||||||
|
if (event.source !== window.parent) return
|
||||||
|
const message = event.data
|
||||||
|
if (!message || message.channel !== CHANNEL) return
|
||||||
|
if (message.kind === "context") {
|
||||||
|
markReady()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (message.kind !== "response" || !message.requestId) return
|
||||||
|
const request = pending.get(message.requestId)
|
||||||
|
if (!request) return
|
||||||
|
pending.delete(message.requestId)
|
||||||
|
window.clearTimeout(request.timer)
|
||||||
|
if (message.ok) {
|
||||||
|
request.resolve(message.data)
|
||||||
|
} else {
|
||||||
|
request.reject(new Error(typeof message.error === "string" ? message.error : "AstrBot plugin bridge request failed"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const request = async <T>(action: "api:get" | "api:post", endpoint: string, payload?: unknown): Promise<T> => {
|
||||||
|
await readyPromise
|
||||||
|
const requestId = `imagestudio_${Date.now()}_${Math.random().toString(36).slice(2)}`
|
||||||
|
return new Promise<T>((resolve, reject) => {
|
||||||
|
const timer = window.setTimeout(() => {
|
||||||
|
pending.delete(requestId)
|
||||||
|
reject(new Error(`AstrBot plugin bridge request timed out: ${endpoint}`))
|
||||||
|
}, REQUEST_TIMEOUT_MS)
|
||||||
|
pending.set(requestId, {
|
||||||
|
resolve: (value) => resolve(value as T),
|
||||||
|
reject,
|
||||||
|
timer,
|
||||||
|
})
|
||||||
|
window.parent.postMessage(
|
||||||
|
{
|
||||||
|
channel: CHANNEL,
|
||||||
|
kind: "request",
|
||||||
|
requestId,
|
||||||
|
action,
|
||||||
|
endpoint,
|
||||||
|
...(action === "api:get" ? { params: payload ?? {} } : { body: payload ?? {} }),
|
||||||
|
},
|
||||||
|
"*",
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener("message", onMessage)
|
||||||
|
window.AstrBotPluginPage = {
|
||||||
|
ready: () => readyPromise,
|
||||||
|
apiGet: <T>(path: string, params?: Record<string, unknown>) => request<T>("api:get", path, params),
|
||||||
|
apiPost: <T>(path: string, body?: unknown) => request<T>("api:post", path, body),
|
||||||
|
}
|
||||||
|
|
||||||
|
postReady()
|
||||||
|
readyTimer = window.setInterval(postReady, READY_RETRY_MS)
|
||||||
|
}
|
||||||
|
|
@ -6,6 +6,11 @@ export type ApiMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"
|
||||||
|
|
||||||
const METHOD_OVERRIDE_KEY = "__imagestudio_method"
|
const METHOD_OVERRIDE_KEY = "__imagestudio_method"
|
||||||
const METHOD_OVERRIDE_BODY_KEY = "__imagestudio_body"
|
const METHOD_OVERRIDE_BODY_KEY = "__imagestudio_body"
|
||||||
|
const PLUGIN_BRIDGE_DISCOVERY_TIMEOUT_MS = 2500
|
||||||
|
const PLUGIN_BRIDGE_READY_TIMEOUT_MS = 1200
|
||||||
|
const PLUGIN_BRIDGE_REQUEST_TIMEOUT_MS = 5000
|
||||||
|
|
||||||
|
type PluginBridge = NonNullable<Window["AstrBotPluginPage"]>
|
||||||
|
|
||||||
export class ApiClientError extends Error {
|
export class ApiClientError extends Error {
|
||||||
readonly code: string
|
readonly code: string
|
||||||
|
|
@ -54,9 +59,9 @@ export async function request<T>(
|
||||||
body?: unknown
|
body?: unknown
|
||||||
} = {},
|
} = {},
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
const hasPluginBridge = typeof window !== "undefined" && Boolean(window.AstrBotPluginPage)
|
const bridge = await pluginBridgeForRequest()
|
||||||
const bridgePayload = await requestViaPluginBridge<T>(endpoint, options)
|
if (bridge) {
|
||||||
if (hasPluginBridge) {
|
const bridgePayload = await requestViaPluginBridge<T>(bridge, endpoint, options)
|
||||||
if (bridgePayload === undefined) {
|
if (bridgePayload === undefined) {
|
||||||
throw new ApiClientError("invalid_api_response", "AstrBot Plugin Page bridge returned no response", {
|
throw new ApiClientError("invalid_api_response", "AstrBot Plugin Page bridge returned no response", {
|
||||||
endpoint,
|
endpoint,
|
||||||
|
|
@ -98,6 +103,7 @@ export async function request<T>(
|
||||||
}
|
}
|
||||||
|
|
||||||
async function requestViaPluginBridge<T>(
|
async function requestViaPluginBridge<T>(
|
||||||
|
bridge: PluginBridge,
|
||||||
endpoint: string,
|
endpoint: string,
|
||||||
options: {
|
options: {
|
||||||
method?: ApiMethod
|
method?: ApiMethod
|
||||||
|
|
@ -105,19 +111,33 @@ async function requestViaPluginBridge<T>(
|
||||||
body?: unknown
|
body?: unknown
|
||||||
},
|
},
|
||||||
): Promise<T | ApiResponse<T> | AstrBotApiResponse<T> | undefined> {
|
): Promise<T | ApiResponse<T> | AstrBotApiResponse<T> | undefined> {
|
||||||
const bridge = window.AstrBotPluginPage
|
|
||||||
if (!bridge) {
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
const method = options.method ?? "GET"
|
const method = options.method ?? "GET"
|
||||||
if (typeof bridge.ready === "function") {
|
if (typeof bridge.ready === "function") {
|
||||||
await bridge.ready()
|
try {
|
||||||
|
await withClientTimeout(
|
||||||
|
Promise.resolve(bridge.ready()),
|
||||||
|
PLUGIN_BRIDGE_READY_TIMEOUT_MS,
|
||||||
|
"AstrBot Plugin Page bridge readiness timed out",
|
||||||
|
)
|
||||||
|
} catch {
|
||||||
|
// Some AstrBot builds leave ready() pending even though apiGet/apiPost
|
||||||
|
// are already usable. Continue with the concrete bridge method, which
|
||||||
|
// has its own timeout and can be retried by the app bootstrap loop.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (method === "GET" && typeof bridge.apiGet === "function") {
|
if (method === "GET" && typeof bridge.apiGet === "function") {
|
||||||
return bridge.apiGet<T | ApiResponse<T> | AstrBotApiResponse<T>>(endpoint, compactQuery(options.query))
|
return withClientTimeout(
|
||||||
|
bridge.apiGet<T | ApiResponse<T> | AstrBotApiResponse<T>>(endpoint, compactQuery(options.query)),
|
||||||
|
PLUGIN_BRIDGE_REQUEST_TIMEOUT_MS,
|
||||||
|
"AstrBot Plugin Page GET request timed out",
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if (method === "POST" && typeof bridge.apiPost === "function") {
|
if (method === "POST" && typeof bridge.apiPost === "function") {
|
||||||
return bridge.apiPost<T | ApiResponse<T> | AstrBotApiResponse<T>>(endpoint, options.body)
|
return withClientTimeout(
|
||||||
|
bridge.apiPost<T | ApiResponse<T> | AstrBotApiResponse<T>>(endpoint, options.body),
|
||||||
|
PLUGIN_BRIDGE_REQUEST_TIMEOUT_MS,
|
||||||
|
"AstrBot Plugin Page POST request timed out",
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if (method === "PUT" && typeof bridge.apiPut === "function") {
|
if (method === "PUT" && typeof bridge.apiPut === "function") {
|
||||||
return bridge.apiPut<T | ApiResponse<T> | AstrBotApiResponse<T>>(endpoint, options.body)
|
return bridge.apiPut<T | ApiResponse<T> | AstrBotApiResponse<T>>(endpoint, options.body)
|
||||||
|
|
@ -141,6 +161,34 @@ async function requestViaPluginBridge<T>(
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function pluginBridgeForRequest(): Promise<PluginBridge | undefined> {
|
||||||
|
if (typeof window === "undefined") return undefined
|
||||||
|
if (window.AstrBotPluginPage) return window.AstrBotPluginPage
|
||||||
|
if (window.parent === window) return undefined
|
||||||
|
const deadline = Date.now() + PLUGIN_BRIDGE_DISCOVERY_TIMEOUT_MS
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
await new Promise<void>((resolve) => window.setTimeout(resolve, 100))
|
||||||
|
if (window.AstrBotPluginPage) return window.AstrBotPluginPage
|
||||||
|
}
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
function withClientTimeout<T>(promise: Promise<T>, timeoutMs: number, message: string): Promise<T> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const timer = window.setTimeout(() => reject(new ApiClientError("bridge_timeout", message)), timeoutMs)
|
||||||
|
promise.then(
|
||||||
|
(value) => {
|
||||||
|
window.clearTimeout(timer)
|
||||||
|
resolve(value)
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
window.clearTimeout(timer)
|
||||||
|
reject(error)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
function unwrapApiResponse<T>(payload: T | ApiResponse<T> | AstrBotApiResponse<T>): T {
|
function unwrapApiResponse<T>(payload: T | ApiResponse<T> | AstrBotApiResponse<T>): T {
|
||||||
let current: unknown = payload
|
let current: unknown = payload
|
||||||
for (let depth = 0; depth < 4; depth += 1) {
|
for (let depth = 0; depth < 4; depth += 1) {
|
||||||
|
|
|
||||||
|
|
@ -4223,6 +4223,9 @@ onMounted(() => {
|
||||||
document.addEventListener("pointercancel", cancelOutsideOverlayClick, true)
|
document.addEventListener("pointercancel", cancelOutsideOverlayClick, true)
|
||||||
document.addEventListener("pointermove", handleNavigationRailPointerMove, true)
|
document.addEventListener("pointermove", handleNavigationRailPointerMove, true)
|
||||||
document.addEventListener("keydown", handleGlobalKeyboard)
|
document.addEventListener("keydown", handleGlobalKeyboard)
|
||||||
|
document.addEventListener("visibilitychange", reconnectBackendWhenVisible)
|
||||||
|
window.addEventListener("focus", reconnectBackendWhenVisible)
|
||||||
|
window.addEventListener("online", reconnectBackendWhenVisible)
|
||||||
if (!navigationRailPinned.value) {
|
if (!navigationRailPinned.value) {
|
||||||
scheduleNavigationRailHide(NAV_RAIL_INITIAL_HIDE_DELAY)
|
scheduleNavigationRailHide(NAV_RAIL_INITIAL_HIDE_DELAY)
|
||||||
}
|
}
|
||||||
|
|
@ -4238,6 +4241,9 @@ onBeforeUnmount(() => {
|
||||||
document.removeEventListener("pointercancel", cancelOutsideOverlayClick, true)
|
document.removeEventListener("pointercancel", cancelOutsideOverlayClick, true)
|
||||||
document.removeEventListener("pointermove", handleNavigationRailPointerMove, true)
|
document.removeEventListener("pointermove", handleNavigationRailPointerMove, true)
|
||||||
document.removeEventListener("keydown", handleGlobalKeyboard)
|
document.removeEventListener("keydown", handleGlobalKeyboard)
|
||||||
|
document.removeEventListener("visibilitychange", reconnectBackendWhenVisible)
|
||||||
|
window.removeEventListener("focus", reconnectBackendWhenVisible)
|
||||||
|
window.removeEventListener("online", reconnectBackendWhenVisible)
|
||||||
clearNavigationRailHide()
|
clearNavigationRailHide()
|
||||||
clearQuickProfileImageCarousel()
|
clearQuickProfileImageCarousel()
|
||||||
if (eventStreamTimer !== undefined) window.clearInterval(eventStreamTimer)
|
if (eventStreamTimer !== undefined) window.clearInterval(eventStreamTimer)
|
||||||
|
|
@ -4613,6 +4619,15 @@ function scheduleBackendReconnect() {
|
||||||
}, delay)
|
}, delay)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function reconnectBackendWhenVisible() {
|
||||||
|
if (document.hidden || backendConnection.value.state === "connected" || backendConnection.value.state === "checking") {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
backendReconnectAttempt = 0
|
||||||
|
clearBackendReconnect()
|
||||||
|
void loadAll()
|
||||||
|
}
|
||||||
|
|
||||||
async function loadDashboard() {
|
async function loadDashboard() {
|
||||||
loadingDashboard.value = true
|
loadingDashboard.value = true
|
||||||
dashboardError.value = ""
|
dashboardError.value = ""
|
||||||
|
|
@ -8843,26 +8858,35 @@ function clampNumber(value: number, min: number, max: number) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function restorePreferences() {
|
function restorePreferences() {
|
||||||
const storedTheme = localStorage.getItem(STORAGE_KEYS.theme)
|
try {
|
||||||
if (storedTheme === "light" || storedTheme === "dark") {
|
const storedTheme = localStorage.getItem(STORAGE_KEYS.theme)
|
||||||
themeMode.value = storedTheme
|
if (storedTheme === "light" || storedTheme === "dark") {
|
||||||
|
themeMode.value = storedTheme
|
||||||
|
}
|
||||||
|
primaryColor.value = localStorage.getItem(STORAGE_KEYS.primary) || primaryColor.value
|
||||||
|
accentColor.value = localStorage.getItem(STORAGE_KEYS.accent) || accentColor.value
|
||||||
|
const storedNavigationPinned = localStorage.getItem(STORAGE_KEYS.navigationPinned)
|
||||||
|
navigationRailPinned.value = storedNavigationPinned === null || storedNavigationPinned === "true"
|
||||||
|
readNotificationIds.value = parseStringList(localStorage.getItem(STORAGE_KEYS.readNotifications))
|
||||||
|
dismissedNotificationIds.value = parseStringList(localStorage.getItem(STORAGE_KEYS.dismissedNotifications))
|
||||||
|
} catch {
|
||||||
|
// AstrBot plugin pages run in an opaque sandbox without localStorage.
|
||||||
|
// Preferences are optional and must never block backend bootstrap.
|
||||||
}
|
}
|
||||||
primaryColor.value = localStorage.getItem(STORAGE_KEYS.primary) || primaryColor.value
|
|
||||||
accentColor.value = localStorage.getItem(STORAGE_KEYS.accent) || accentColor.value
|
|
||||||
const storedNavigationPinned = localStorage.getItem(STORAGE_KEYS.navigationPinned)
|
|
||||||
navigationRailPinned.value = storedNavigationPinned === null || storedNavigationPinned === "true"
|
|
||||||
navigationRailExpanded.value = navigationRailPinned.value
|
navigationRailExpanded.value = navigationRailPinned.value
|
||||||
readNotificationIds.value = parseStringList(localStorage.getItem(STORAGE_KEYS.readNotifications))
|
|
||||||
dismissedNotificationIds.value = parseStringList(localStorage.getItem(STORAGE_KEYS.dismissedNotifications))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function persistPreferences() {
|
function persistPreferences() {
|
||||||
localStorage.setItem(STORAGE_KEYS.theme, themeMode.value)
|
try {
|
||||||
localStorage.setItem(STORAGE_KEYS.primary, primaryColor.value)
|
localStorage.setItem(STORAGE_KEYS.theme, themeMode.value)
|
||||||
localStorage.setItem(STORAGE_KEYS.accent, accentColor.value)
|
localStorage.setItem(STORAGE_KEYS.primary, primaryColor.value)
|
||||||
localStorage.setItem(STORAGE_KEYS.navigationPinned, String(navigationRailPinned.value))
|
localStorage.setItem(STORAGE_KEYS.accent, accentColor.value)
|
||||||
localStorage.setItem(STORAGE_KEYS.readNotifications, JSON.stringify(readNotificationIds.value))
|
localStorage.setItem(STORAGE_KEYS.navigationPinned, String(navigationRailPinned.value))
|
||||||
localStorage.setItem(STORAGE_KEYS.dismissedNotifications, JSON.stringify(dismissedNotificationIds.value))
|
localStorage.setItem(STORAGE_KEYS.readNotifications, JSON.stringify(readNotificationIds.value))
|
||||||
|
localStorage.setItem(STORAGE_KEYS.dismissedNotifications, JSON.stringify(dismissedNotificationIds.value))
|
||||||
|
} catch {
|
||||||
|
// Preference persistence is unavailable in AstrBot's sandboxed iframe.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseStringList(value: string | null) {
|
function parseStringList(value: string | null) {
|
||||||
|
|
|
||||||
|
|
@ -79,7 +79,7 @@ function persistAdapters(list:Adapter[]){const next=clone(draft.value);const gen
|
||||||
function updateAdapter(id:string,key:keyof Adapter,value:string|number|boolean){persistAdapters(adapters.value.map(a=>a.id===id?{...a,[key]:value}:a))}
|
function updateAdapter(id:string,key:keyof Adapter,value:string|number|boolean){persistAdapters(adapters.value.map(a=>a.id===id?{...a,[key]:value}:a))}
|
||||||
function updateProbeApiKey(id:string,value:string){probeApiKeys.value={...probeApiKeys.value,[id]:value}}
|
function updateProbeApiKey(id:string,value:string){probeApiKeys.value={...probeApiKeys.value,[id]:value}}
|
||||||
function setProbeApiKeyInput(id:string,element:unknown){if(element instanceof HTMLInputElement)probeApiKeyInputs.set(id,element);else probeApiKeyInputs.delete(id)}
|
function setProbeApiKeyInput(id:string,element:unknown){if(element instanceof HTMLInputElement)probeApiKeyInputs.set(id,element);else probeApiKeyInputs.delete(id)}
|
||||||
function probeApiKeyValue(id:string){return probeApiKeys.value[id]||probeApiKeyInputs.get(id)?.value||""}
|
function probeApiKeyValue(id:string){const value=probeApiKeys.value[id]||probeApiKeyInputs.get(id)?.value||"";return value==="***MASKED***"||value==="***REDACTED***"?"":value}
|
||||||
function updateAdapterCredential(id:string,value:string){if(/^sk[-_]/i.test(value.trim())){probeApiKeys.value={...probeApiKeys.value,[id]:value.trim()};updateAdapter(id,"api_key_env_var","");return}updateAdapter(id,"api_key_env_var",value)}
|
function updateAdapterCredential(id:string,value:string){if(/^sk[-_]/i.test(value.trim())){probeApiKeys.value={...probeApiKeys.value,[id]:value.trim()};updateAdapter(id,"api_key_env_var","");return}updateAdapter(id,"api_key_env_var",value)}
|
||||||
function addAdapter(){const id=`adapter-${Date.now()}`;persistAdapters([...adapters.value,{id,name:"",provider_type:"openai_compatible",base_url:"",image_endpoint:"",model_id:"",route_name:"",api_key_env_var:"",api_key_plaintext:"",timeout_seconds:180,enabled:true}]);expandedAdapter.value=id}
|
function addAdapter(){const id=`adapter-${Date.now()}`;persistAdapters([...adapters.value,{id,name:"",provider_type:"openai_compatible",base_url:"",image_endpoint:"",model_id:"",route_name:"",api_key_env_var:"",api_key_plaintext:"",timeout_seconds:180,enabled:true}]);expandedAdapter.value=id}
|
||||||
function removeAdapter(id:string){const remaining=adapters.value.filter(a=>a.id!==id);persistAdapters(remaining);expandedAdapter.value="";const logs={...probeLogs.value};delete logs[id];probeLogs.value=logs;const results={...probeResults.value};delete results[id];probeResults.value=results;const keys={...probeApiKeys.value};delete keys[id];probeApiKeys.value=keys;probeApiKeyInputs.delete(id)}
|
function removeAdapter(id:string){const remaining=adapters.value.filter(a=>a.id!==id);persistAdapters(remaining);expandedAdapter.value="";const logs={...probeLogs.value};delete logs[id];probeLogs.value=logs;const results={...probeResults.value};delete results[id];probeResults.value=results;const keys={...probeApiKeys.value};delete keys[id];probeApiKeys.value=keys;probeApiKeyInputs.delete(id)}
|
||||||
|
|
@ -87,7 +87,7 @@ function makeDefaultAdapter(id:string){const selected=adapters.value.find(item=>
|
||||||
function beginAdapterBackdropClick(event:PointerEvent){if(event.button!==0)return;adapterBackdropPress={pointerId:event.pointerId,x:event.clientX,y:event.clientY}}
|
function beginAdapterBackdropClick(event:PointerEvent){if(event.button!==0)return;adapterBackdropPress={pointerId:event.pointerId,x:event.clientX,y:event.clientY}}
|
||||||
function finishAdapterBackdropClick(event:PointerEvent){const press=adapterBackdropPress;adapterBackdropPress=undefined;if(!press||press.pointerId!==event.pointerId)return;if(Math.hypot(event.clientX-press.x,event.clientY-press.y)>6)return;const selection=window.getSelection();if(selection&&!selection.isCollapsed)return;expandedAdapter.value=""}
|
function finishAdapterBackdropClick(event:PointerEvent){const press=adapterBackdropPress;adapterBackdropPress=undefined;if(!press||press.pointerId!==event.pointerId)return;if(Math.hypot(event.clientX-press.x,event.clientY-press.y)>6)return;const selection=window.getSelection();if(selection&&!selection.isCollapsed)return;expandedAdapter.value=""}
|
||||||
function cancelAdapterBackdropClick(){adapterBackdropPress=undefined}
|
function cancelAdapterBackdropClick(){adapterBackdropPress=undefined}
|
||||||
async function saveAndProbeAdapter(a:Adapter,lightweight=false){probingAdapter.value=a.id;probeError.value="";try{const config=clone(draft.value);const generation=obj(config.generation);const key=probeApiKeyValue(a.id).trim();if(Array.isArray(generation.adapters)){generation.adapters=generation.adapters.map(item=>{const adapter=obj(item);if(String(adapter.id||adapter.provider_id)!==a.id)return item;return{...adapter,...(key?{api_key_plaintext:key}:{})}})}const provider=obj(generation.provider);if(String(provider.id||provider.provider_id)===a.id&&key)generation.provider={...provider,api_key_plaintext:key};config.generation=generation;const validation=await postJson<ValidateSettingsResult>(endpoints.settingsValidate,{config});if(!validation.valid)throw new Error(validation.errors?.map(item=>String(item.message||"配置字段无效")).join(";")||"配置校验失败");const saved=await postJson<SaveSettingsResult>(endpoints.settingsSave,{config});draft.value=clone(saved.config);emit("refresh");const result=await postJson<CapabilityProfile>(endpoints.apiDiscoveryProbeProvider,{provider_id:a.id,model_id:a.model_id||"auto-discovery",dialect:"openai_images",use_saved_provider:true,allow_lightweight_test:lightweight});probeResults.value={...probeResults.value,[a.id]:result};const probe=obj(result.probe_result);const connected=probe.connected===true;const details=[`目标:${String(probe.resolved_api_base||a.base_url)}`,`鉴权:${probe.auth_source==="request"?"已保存 API Key":probe.auth_source==="environment"?"环境变量":"未提供"}`,probe.http_status?`HTTP:${String(probe.http_status)}`:"",probe.error?`原因:${String(probe.error)}`:"",probe.error_body?`响应:${String(probe.error_body)}`:"",`模型:${probeModelsFromResult(result).length} 个`].filter(Boolean);probeLogs.value={...probeLogs.value,[a.id]:{time:new Date().toLocaleString(),level:connected?"success":"error",summary:connected?"保存并探测成功":"保存成功,但连接探测失败",details}};const detectedEndpoint=probe.image_endpoint;if(typeof detectedEndpoint==="string"&&detectedEndpoint&&connected)updateAdapter(a.id,"image_endpoint",detectedEndpoint);const models=probeModelsFromResult(result);if(!a.model_id&&models.length)updateAdapter(a.id,"model_id",models[0])}catch(e){const message=e instanceof Error?e.message:String(e);probeError.value=message;probeLogs.value={...probeLogs.value,[a.id]:{time:new Date().toLocaleString(),level:"error",summary:message,details:[]}}}finally{probingAdapter.value=""}}
|
async function saveAndProbeAdapter(a:Adapter,lightweight=false){probingAdapter.value=a.id;probeError.value="";try{const config=clone(draft.value);const generation=obj(config.generation);const key=probeApiKeyValue(a.id).trim();if(Array.isArray(generation.adapters)){generation.adapters=generation.adapters.map(item=>{const adapter=obj(item);if(String(adapter.id||adapter.provider_id)!==a.id)return item;return{...adapter,...(key?{api_key_plaintext:key}:{})}})}const provider=obj(generation.provider);if(String(provider.id||provider.provider_id)===a.id&&key)generation.provider={...provider,api_key_plaintext:key};config.generation=generation;const validation=await postJson<ValidateSettingsResult>(endpoints.settingsValidate,{config});if(!validation.valid)throw new Error(validation.errors?.map(item=>String(item.message||"配置字段无效")).join(";")||"配置校验失败");const saved=await postJson<SaveSettingsResult>(endpoints.settingsSave,{config});draft.value=clone(saved.config);const result=await postJson<CapabilityProfile>(endpoints.apiDiscoveryProbeProvider,{provider_id:a.id,model_id:a.model_id||"auto-discovery",dialect:"openai_images",use_saved_provider:true,allow_lightweight_test:lightweight});probeResults.value={...probeResults.value,[a.id]:result};const probe=obj(result.probe_result);const connected=probe.connected===true;const details=[`目标:${String(probe.resolved_api_base||a.base_url)}`,`鉴权:${probe.auth_source==="request"?"已保存 API Key":probe.auth_source==="environment"?"环境变量":"未提供"}`,probe.http_status?`HTTP:${String(probe.http_status)}`:"",probe.error?`原因:${String(probe.error)}`:"",probe.error_body?`响应:${String(probe.error_body)}`:"",`模型:${probeModelsFromResult(result).length} 个`].filter(Boolean);probeLogs.value={...probeLogs.value,[a.id]:{time:new Date().toLocaleString(),level:connected?"success":"error",summary:connected?"保存并探测成功":"保存成功,但连接探测失败",details}};const detectedEndpoint=probe.image_endpoint;if(typeof detectedEndpoint==="string"&&detectedEndpoint&&connected)updateAdapter(a.id,"image_endpoint",detectedEndpoint);const models=probeModelsFromResult(result);if(!a.model_id&&models.length)updateAdapter(a.id,"model_id",models[0])}catch(e){const message=e instanceof Error?e.message:String(e);probeError.value=message;probeLogs.value={...probeLogs.value,[a.id]:{time:new Date().toLocaleString(),level:"error",summary:message,details:[]}}}finally{probingAdapter.value=""}}
|
||||||
function probeModelsFromResult(result:CapabilityProfile):string[]{const value=result.probe_result.models;return Array.isArray(value)?value.map(String):[]}
|
function probeModelsFromResult(result:CapabilityProfile):string[]{const value=result.probe_result.models;return Array.isArray(value)?value.map(String):[]}
|
||||||
function probeConnected(id:string){return probeResults.value[id]?.probe_result.connected===true}
|
function probeConnected(id:string){return probeResults.value[id]?.probe_result.connected===true}
|
||||||
function probeModels(id:string):string[]{const value=probeResults.value[id]?.probe_result.models;return Array.isArray(value)?value.map(String):[]}
|
function probeModels(id:string):string[]{const value=probeResults.value[id]?.probe_result.models;return Array.isArray(value)?value.map(String):[]}
|
||||||
|
|
|
||||||
8
main.py
8
main.py
|
|
@ -79,6 +79,7 @@ from backend.services.model_provider_bootstrap import (
|
||||||
)
|
)
|
||||||
from backend.services.model_provider_service import ModelProviderService
|
from backend.services.model_provider_service import ModelProviderService
|
||||||
from backend.services.ui_service import API_BASE
|
from backend.services.ui_service import API_BASE
|
||||||
|
from core.config_service import PLUGIN_VERSION
|
||||||
from core.identity import RequestContext
|
from core.identity import RequestContext
|
||||||
from core.media_proxy import MediaProxy
|
from core.media_proxy import MediaProxy
|
||||||
from database import db_helper as _database_db_helper
|
from database import db_helper as _database_db_helper
|
||||||
|
|
@ -98,7 +99,6 @@ load_database_settings = _database_db_helper.load_database_settings
|
||||||
|
|
||||||
PLUGIN_NAME = "astrbot_plugin_imagestudio"
|
PLUGIN_NAME = "astrbot_plugin_imagestudio"
|
||||||
PLUGIN_DESC = "AstrBot ImageStudio role asset production and image-generation workspace."
|
PLUGIN_DESC = "AstrBot ImageStudio role asset production and image-generation workspace."
|
||||||
PLUGIN_VERSION = "1.0.6"
|
|
||||||
BRIDGE_PERMISSIONS = frozenset(
|
BRIDGE_PERMISSIONS = frozenset(
|
||||||
{"can_write", "can_manage_config", "can_manage_materials", "can_retry_tasks"}
|
{"can_write", "can_manage_config", "can_manage_materials", "can_retry_tasks"}
|
||||||
)
|
)
|
||||||
|
|
@ -304,10 +304,12 @@ class Main(AstrBotStar):
|
||||||
|
|
||||||
async def initialize(self) -> None:
|
async def initialize(self) -> None:
|
||||||
self.runtime_config_result = apply_astrbot_config_overrides(self.astrbot_config)
|
self.runtime_config_result = apply_astrbot_config_overrides(self.astrbot_config)
|
||||||
|
# Database migrations must complete before AstrBot registers or inspects
|
||||||
|
# any route handlers. Registration is not guaranteed to be passive on
|
||||||
|
# every supported AstrBot version.
|
||||||
|
self.database_result = initialize_runtime_database()
|
||||||
if self.context is not None:
|
if self.context is not None:
|
||||||
self.registration_result = register_plugin(self.context)
|
self.registration_result = register_plugin(self.context)
|
||||||
if self.registration_result.get("bridge_api", {}).get("registered"):
|
|
||||||
self.database_result = initialize_runtime_database()
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
async def terminate(self) -> None:
|
async def terminate(self) -> None:
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ name: astrbot_plugin_imagestudio
|
||||||
display_name: ImageStudio
|
display_name: ImageStudio
|
||||||
desc: AstrBot >=4.25 ImageStudio role asset and image-generation workspace for Windows, Linux, macOS and Docker.
|
desc: AstrBot >=4.25 ImageStudio role asset and image-generation workspace for Windows, Linux, macOS and Docker.
|
||||||
short_desc: AstrBot 内的角色资产、工作流与图片生成管理工作台。
|
short_desc: AstrBot 内的角色资产、工作流与图片生成管理工作台。
|
||||||
version: 1.0.6
|
version: 1.0.8
|
||||||
author: YokiiroBW
|
author: YokiiroBW
|
||||||
repo: "http://192.168.31.210:18085/YokiiroBW/astrbot_plugin_imagestudio"
|
repo: "http://192.168.31.210:18085/YokiiroBW/astrbot_plugin_imagestudio"
|
||||||
astrbot_version: ">=4.25.0,<5"
|
astrbot_version: ">=4.25.0,<5"
|
||||||
|
|
|
||||||
文件差异因一行或多行过长而隐藏
文件差异因一行或多行过长而隐藏
文件差异因一行或多行过长而隐藏
|
|
@ -4,8 +4,8 @@
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>AstrBot ImageStudio</title>
|
<title>AstrBot ImageStudio</title>
|
||||||
<script type="module" crossorigin src="./assets/index-CnWbapd1.js"></script>
|
<script type="module" crossorigin src="./assets/index-Bucku_VS.js"></script>
|
||||||
<link rel="stylesheet" crossorigin href="./assets/index-DkCEFRMc.css">
|
<link rel="stylesheet" crossorigin href="./assets/index-BwIaxZs-.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
|
|
|
||||||
二进制文件未显示。
54
web/assets/index-CNsCn8ZX.js
普通文件
54
web/assets/index-CNsCn8ZX.js
普通文件
文件差异因一行或多行过长而隐藏
文件差异因一行或多行过长而隐藏
文件差异因一行或多行过长而隐藏
|
|
@ -4,8 +4,8 @@
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>AstrBot ImageStudio</title>
|
<title>AstrBot ImageStudio</title>
|
||||||
<script type="module" crossorigin src="/api/v1/plugins/extensions/astrbot_plugin_imagestudio/web/assets/index-CjffA5xb.js"></script>
|
<script type="module" crossorigin src="/api/v1/plugins/extensions/astrbot_plugin_imagestudio/web/assets/index-CNsCn8ZX.js"></script>
|
||||||
<link rel="stylesheet" crossorigin href="/api/v1/plugins/extensions/astrbot_plugin_imagestudio/web/assets/index-D57O7ZT7.css">
|
<link rel="stylesheet" crossorigin href="/api/v1/plugins/extensions/astrbot_plugin_imagestudio/web/assets/index-hzc-FWPP.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
|
|
|
||||||
正在加载…
添加表格
在新工单中引用