Compare commits

...
Author SHA1 Message Date
shigongyuan-agentandmultica-agent 25d1e05a30 fix: survive missing crypto.randomUUID on insecure LAN HTTP (HEL-610)
Co-authored-by: multica-agent <github@multica.ai>
2026-09-27 22:37:42 +08:00
shigongyuan-agentandmultica-agent 4945d29e52 feat: A darkroom shell + projects overview home, models page into the shell (HEL-608)
Co-authored-by: multica-agent <github@multica.ai>
2026-09-27 21:42:06 +08:00
multica-builderandmultica-agent 5d909aca3b feat: models settings page per approved A darkroom spec (HEL-605)
- New /models page: LLM cards (type tag, agent-default badge, test state
  with latency/consecutive failures), add/edit form (OpenAI-compatible
  segment, mono base URL/model, masked key with sk-****tail, timeout
  dropdown, save gated on a passing test), agent default-model panel for
  the five AIGC agents, dashed server-connectivity notice, disabled
  image/video tabs as future placeholders; responsive 1440/1024/768
  breakpoints per spec-v2 §9.
- Scoped A darkroom design tokens in app.css (.a-darkroom) + Noto Sans SC.
- Top nav: add Agents and Models entries before Settings.
- Backend: add 'style' agent role, llm-test timeout_sec (5-60, default 10),
  api_key_tail (last 4 chars) in public profiles; 4 new tests.
- i18n: 84 models.* keys + nav.agents/nav.models in all 7 dictionaries.

Co-authored-by: multica-agent <github@multica.ai>
2026-09-27 20:49:59 +08:00
multica-builder 786b349752 feat: default UI language to zh and add LLM connection test
- First-open default language is now Simplified Chinese (i18n.svelte.ts);
  stored language choice still wins.
- New POST /api/settings/llm-test endpoint probes an OpenAI-compatible
  endpoint with a 1-token chat completion; falls back to a saved profile's
  secret so keys never travel back to the browser.
- Settings LLM cards gain a connection-test button with readable
  success/failure feedback (auth / timeout / connect / HTTP detail),
  localized in all seven dictionaries.
- Backend tests cover success, saved-secret reuse, 401, connection
  refused, and input validation against a local fake OpenAI server.
2026-09-27 20:04:46 +08:00
26 changed files with 5308 additions and 27 deletions
+12 -1
View File
@@ -59,7 +59,15 @@ DEFAULT_AGENT_HARDENING_PROMPT = """You are operating under additional operator-
# Agent roles that can be pinned to a specific LLM profile. Values live in
# Settings.agent_llm_assignments (role -> profile id or None). A missing or
# None entry means "use the Active LLM".
AGENT_LLM_ROLES: tuple[str, ...] = ("main", "planner", "story", "script", "assets", "video")
AGENT_LLM_ROLES: tuple[str, ...] = (
"main",
"planner",
"story",
"style",
"script",
"assets",
"video",
)
def is_ephemeral_path(path: Path | str | None) -> bool:
@@ -318,6 +326,9 @@ class Settings(BaseSettings):
"base_url": p["base_url"],
"model": p["model"],
"api_key": bool(p.get("api_key")),
# Last 4 characters only — enough to recognise a saved key in
# the UI without ever exposing it (GitHub/Stripe convention).
"api_key_tail": (p.get("api_key") or "")[-4:] or None,
}
for p in self.llm_profiles
]
@@ -1,7 +1,9 @@
from __future__ import annotations
import time
from typing import Any
import httpx
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
@@ -11,6 +13,9 @@ router = APIRouter()
_LEGACY_LLM_KEYS = {"llm_base_url", "llm_model", "llm_api_key"}
_LLM_TEST_TIMEOUT_SEC = 15.0
_LLM_TEST_TIMEOUT_RANGE = (5, 60)
class LlmProfileIn(BaseModel):
id: str | None = None
@@ -20,6 +25,18 @@ class LlmProfileIn(BaseModel):
api_key: str | None = None
class LlmTestIn(BaseModel):
profile_id: str | None = None
base_url: str | None = None
model: str | None = None
api_key: str | None = None
# Probe timeout requested by the caller (models settings page dropdown).
# Clamped server-side regardless of what the client sends.
timeout_sec: float | None = Field(
None, ge=_LLM_TEST_TIMEOUT_RANGE[0], le=_LLM_TEST_TIMEOUT_RANGE[1]
)
class SettingsUpdate(BaseModel):
llm_base_url: str | None = None
llm_model: str | None = None
@@ -106,3 +123,76 @@ async def update_settings(payload: SettingsUpdate) -> dict[str, Any]:
settings.save_config_file()
return settings.to_public_dict()
@router.post("/llm-test")
async def test_llm_connection(payload: LlmTestIn) -> dict[str, Any]:
settings.ensure_llm_profiles()
base_url = (payload.base_url or "").strip()
model = (payload.model or "").strip()
api_key = (payload.api_key or "").strip() or None
if payload.profile_id:
profile = next(
(p for p in settings.llm_profiles if p.get("id") == payload.profile_id), None
)
if profile is None:
raise HTTPException(status_code=404, detail="Unknown LLM profile")
if not base_url:
base_url = str(profile.get("base_url") or "").strip()
if not model:
model = str(profile.get("model") or "").strip()
if api_key is None:
key = profile.get("api_key")
if isinstance(key, str) and key.strip():
api_key = key
if not base_url or not model:
raise HTTPException(status_code=400, detail="base_url and model are required")
url = f"{base_url.rstrip('/')}/chat/completions"
headers = {"Content-Type": "application/json"}
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
body = {
"model": model,
"messages": [{"role": "user", "content": "ping"}],
"max_tokens": 1,
"stream": False,
"temperature": 0,
}
timeout_sec = payload.timeout_sec if payload.timeout_sec is not None else _LLM_TEST_TIMEOUT_SEC
timeout_sec = min(
max(timeout_sec, _LLM_TEST_TIMEOUT_RANGE[0]),
_LLM_TEST_TIMEOUT_RANGE[1],
)
started = time.perf_counter()
try:
async with httpx.AsyncClient(timeout=timeout_sec) as client:
resp = await client.post(url, headers=headers, json=body)
except httpx.TimeoutException:
return {
"ok": False,
"error": "timeout",
"detail": f"no response within {timeout_sec:.0f}s",
"timeout_sec": timeout_sec,
}
except httpx.HTTPError as exc:
return {"ok": False, "error": "connect", "detail": str(exc) or exc.__class__.__name__}
elapsed_ms = int((time.perf_counter() - started) * 1000)
if resp.status_code in (401, 403):
return {"ok": False, "error": "auth", "detail": f"HTTP {resp.status_code}"}
if resp.status_code == 404:
return {
"ok": False,
"error": "not_found",
"detail": "HTTP 404 — check base URL (OpenAI-compatible servers usually end with /v1)",
}
if resp.status_code >= 400:
text = resp.text[:200].strip().replace("\n", " ")
return {"ok": False, "error": "http", "detail": f"HTTP {resp.status_code}: {text}"}
try:
data = resp.json()
except ValueError:
return {"ok": False, "error": "http", "detail": "response is not JSON"}
if not (isinstance(data, dict) and data.get("choices")):
return {"ok": False, "error": "http", "detail": "response has no choices"}
return {"ok": True, "elapsed_ms": elapsed_ms}
@@ -0,0 +1,260 @@
"""LLM connection test endpoint: probe an OpenAI-compatible endpoint without paid keys."""
from __future__ import annotations
import json
import socket
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
from calliope.config import settings
class _FakeOpenAIHandler(BaseHTTPRequestHandler):
server_version = "FakeOpenAI/1.0"
def do_POST(self):
length = int(self.headers.get("Content-Length") or 0)
body = json.loads(self.rfile.read(length) or b"{}")
auth = self.headers.get("Authorization") or ""
seen = {"path": self.path, "auth": auth, "body": body}
self.server.requests.append(seen)
if self.path != "/v1/chat/completions":
self._send(404, {"error": "not found"})
return
if self.server.require_auth and auth != f"Bearer {self.server.api_key}":
self._send(401, {"error": {"message": "Incorrect API key"}})
return
self._send(
200,
{
"id": "chatcmpl-test",
"object": "chat.completion",
"model": body.get("model", "fake"),
"choices": [
{"index": 0, "message": {"role": "assistant", "content": "pong"}, "finish_reason": "stop"}
],
},
)
def _send(self, status: int, payload: dict) -> None:
data = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, format, *args):
pass
@pytest.fixture
def fake_openai():
server = ThreadingHTTPServer(("127.0.0.1", 0), _FakeOpenAIHandler)
server.requests = []
server.require_auth = False
server.api_key = ""
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
yield server
finally:
server.shutdown()
server.server_close()
def _url(server) -> str:
return f"http://127.0.0.1:{server.server_address[1]}/v1"
def _snapshot() -> dict:
return {
"llm_profiles": [dict(p) for p in (settings.llm_profiles or [])],
"llm_active_id": settings.llm_active_id,
"llm_base_url": settings.llm_base_url,
"llm_model": settings.llm_model,
"llm_api_key": settings.llm_api_key,
}
def _restore(prev: dict) -> None:
for key, value in prev.items():
setattr(settings, key, value)
def test_llm_test_success(client, fake_openai):
r = client.post(
"/api/settings/llm-test",
json={"base_url": _url(fake_openai), "model": "fake-model", "api_key": "sk-test"},
)
assert r.status_code == 200
body = r.json()
assert body["ok"] is True
assert isinstance(body["elapsed_ms"], int)
assert fake_openai.requests[0]["path"] == "/v1/chat/completions"
assert fake_openai.requests[0]["auth"] == "Bearer sk-test"
assert fake_openai.requests[0]["body"]["model"] == "fake-model"
def test_llm_test_uses_saved_profile_secret(client, fake_openai):
prev = _snapshot()
fake_openai.require_auth = True
fake_openai.api_key = "sk-saved-secret"
try:
pid = "cccccccc-cccc-cccc-cccc-cccccccccccc"
r = client.post(
"/api/settings",
json={
"llm_profiles": [
{
"id": pid,
"name": "Fake",
"base_url": _url(fake_openai),
"model": "fake-model",
"api_key": "sk-saved-secret",
}
],
"llm_active_id": pid,
},
)
assert r.status_code == 200
assert r.json()["llm_profiles"][0]["api_key"] is True
r = client.post("/api/settings/llm-test", json={"profile_id": pid})
assert r.status_code == 200
assert r.json()["ok"] is True
assert fake_openai.requests[-1]["auth"] == "Bearer sk-saved-secret"
finally:
_restore(prev)
def test_llm_test_auth_rejected(client, fake_openai):
fake_openai.require_auth = True
fake_openai.api_key = "sk-right-one"
r = client.post(
"/api/settings/llm-test",
json={"base_url": _url(fake_openai), "model": "fake-model", "api_key": "sk-wrong-one"},
)
assert r.status_code == 200
body = r.json()
assert body["ok"] is False
assert body["error"] == "auth"
assert "401" in body["detail"]
def test_llm_test_connection_refused(client):
sock = socket.socket()
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
sock.close()
r = client.post(
"/api/settings/llm-test",
json={"base_url": f"http://127.0.0.1:{port}/v1", "model": "fake-model"},
)
assert r.status_code == 200
body = r.json()
assert body["ok"] is False
assert body["error"] == "connect"
assert body["detail"]
def test_llm_test_validation(client):
r = client.post("/api/settings/llm-test", json={"model": "only-model"})
assert r.status_code == 400
r = client.post("/api/settings/llm-test", json={"profile_id": "does-not-exist"})
assert r.status_code == 404
def test_llm_test_accepts_timeout_sec(client, fake_openai):
r = client.post(
"/api/settings/llm-test",
json={
"base_url": _url(fake_openai),
"model": "fake-model",
"api_key": "sk-test",
"timeout_sec": 10,
},
)
assert r.status_code == 200
assert r.json()["ok"] is True
def test_llm_test_timeout_sec_bounds(client):
for bad in (0, 4, 61):
r = client.post(
"/api/settings/llm-test",
json={"base_url": "http://127.0.0.1:1/v1", "model": "m", "timeout_sec": bad},
)
assert r.status_code == 422, bad
def test_settings_hide_key_but_expose_tail(client, fake_openai):
prev = _snapshot()
try:
pid = "dddddddd-dddd-dddd-dddd-dddddddddddd"
r = client.post(
"/api/settings",
json={
"llm_profiles": [
{
"id": pid,
"name": "Tail",
"base_url": _url(fake_openai),
"model": "fake-model",
"api_key": "sk-tail-3f2a",
}
],
"llm_active_id": pid,
},
)
assert r.status_code == 200
profile = r.json()["llm_profiles"][0]
assert profile["api_key"] is True
assert profile["api_key_tail"] == "3f2a"
assert "sk-tail" not in r.text
finally:
_restore(prev)
def test_style_role_assignment_round_trip(client, fake_openai):
"""视觉设计 (style) is one of the five AIGC agents on the models page."""
prev = _snapshot()
prev_assign = dict(settings.agent_llm_assignments or {})
try:
pid = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"
r = client.post(
"/api/settings",
json={
"llm_profiles": [
{
"id": pid,
"name": "StyleLLM",
"base_url": _url(fake_openai),
"model": "fake-model",
}
],
"llm_active_id": pid,
"agent_llm_assignments": {
"main": None,
"planner": None,
"story": pid,
"style": pid,
"script": None,
"assets": None,
"video": None,
},
},
)
assert r.status_code == 200
body = r.json()
assert body["agent_llm_assignments"]["style"] == pid
assert body["agent_llm_assignments"]["story"] == pid
resolved = settings.resolve_llm_for_role("style")
assert resolved["id"] == pid
finally:
_restore(prev)
settings.agent_llm_assignments = prev_assign
+1 -1
View File
@@ -7,7 +7,7 @@
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"test": "node scripts/check-storage-ssr.mjs",
"test": "node scripts/check-storage-ssr.mjs && node scripts/check-random-uuid.mjs",
"lint": "prettier --check . && eslint .",
"format": "prettier --write ."
},
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env node
/**
* Regression guard for the "crypto.randomUUID is not a function" crash.
*
* `crypto.randomUUID()` only exists in secure contexts (HTTPS, localhost,
* 127.0.0.1). On a LAN HTTP page — e.g. http://192.168.200.15:8080 — the
* browser exposes `crypto` WITHOUT `randomUUID`, so any direct call throws
* and model saving dies. `crypto.getRandomValues()` has no secure-context
* requirement, so the shared helper can always mint a proper v4 UUID.
*
* Two layers of protection, mirroring check-storage-ssr.mjs:
* 1. behavioural — lib/ids.ts must produce unique, well-formed v4 UUIDs
* under every crypto shape a browser can present, including the exact
* insecure-context shape that produced the original crash.
* 2. static — direct `crypto.randomUUID(` calls are banned outside
* lib/ids.ts, so the crash cannot be reintroduced by copying the old
* pattern into a new page.
*
* Run with `npm test` (or `node scripts/check-random-uuid.mjs`).
*/
import { readFileSync, readdirSync } from "node:fs";
import { dirname, join, relative } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, "..");
const SRC = join(ROOT, "src");
const HELPER = join(SRC, "lib", "ids.ts");
let failures = 0;
function fail(message) {
failures += 1;
console.error(`FAIL ${message}`);
}
function ok(message) {
console.log(`ok ${message}`);
}
const UUID_V4 =
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
/** Capture the platform crypto before any test replaces it. */
const REAL_CRYPTO = globalThis.crypto;
/** Replace the global under test. Node's own binding may be getter-only. */
function setGlobalCrypto(value) {
Object.defineProperty(globalThis, "crypto", {
value,
configurable: true,
writable: true,
});
}
const { randomId } = await import(pathToFileURL(HELPER).href);
// ---- 1. behavioural ----------------------------------------------------
// The exact shape a LAN HTTP browser presents: crypto WITHOUT randomUUID.
// This is the configuration that produced the original crash.
const insecureContextCrypto = {
getRandomValues: REAL_CRYPTO.getRandomValues.bind(REAL_CRYPTO),
};
setGlobalCrypto(insecureContextCrypto);
try {
const ids = new Set(Array.from({ length: 1000 }, randomId));
if (ids.size !== 1000)
fail(`insecure context: duplicate ids (${1000 - ids.size} collisions)`);
else if (![...ids].every((id) => UUID_V4.test(id))) {
fail("insecure context: ids are not all well-formed v4 UUIDs");
} else {
ok("insecure-context crypto (getRandomValues only) yields unique v4 UUIDs");
}
} catch (err) {
fail(`insecure-context crypto threw: ${err.message}`);
}
// crypto present but BOTH sources missing (exotic embed / ancient runtime).
setGlobalCrypto({});
try {
const ids = new Set(Array.from({ length: 1000 }, randomId));
if (ids.size !== 1000)
fail(`method-less crypto: duplicate ids (${1000 - ids.size} collisions)`);
else if (![...ids].every((id) => id.length >= 16)) {
fail("method-less crypto: ids too short to be collision-resistant");
} else {
ok(
"method-less crypto degrades to unique best-effort ids without throwing",
);
}
} catch (err) {
fail(`method-less crypto threw: ${err.message}`);
}
// crypto entirely absent.
setGlobalCrypto(undefined);
try {
const ids = new Set(Array.from({ length: 1000 }, randomId));
if (ids.size !== 1000)
fail(`absent crypto: duplicate ids (${1000 - ids.size} collisions)`);
else ok("absent crypto degrades to unique best-effort ids without throwing");
} catch (err) {
fail(`absent crypto threw: ${err.message}`);
}
// A fully-featured crypto (secure context / Node default) must still be used
// directly — guards against a helper that ignores randomUUID.
setGlobalCrypto(REAL_CRYPTO);
try {
const probe = { used: false };
setGlobalCrypto({
randomUUID: () => {
probe.used = true;
return REAL_CRYPTO.randomUUID();
},
getRandomValues: REAL_CRYPTO.getRandomValues.bind(REAL_CRYPTO),
});
const id = randomId();
if (!probe.used) fail("native randomUUID available but not preferred");
else if (!UUID_V4.test(id)) fail(`secure-context id malformed: ${id}`);
else ok("native randomUUID preferred when available");
} catch (err) {
fail(`secure-context crypto threw: ${err.message}`);
} finally {
setGlobalCrypto(REAL_CRYPTO);
}
// ---- 2. static ---------------------------------------------------------
const UNSAFE = /crypto\.randomUUID\s*\(/;
const EXTENSIONS = [".ts", ".js", ".svelte"];
function walk(dir) {
const found = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
if (entry.name === "node_modules") continue;
found.push(...walk(full));
} else if (EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {
found.push(full);
}
}
return found;
}
const offenders = [];
for (const file of walk(SRC)) {
if (file === HELPER) continue; // the one place allowed to call the native API
const lines = readFileSync(file, "utf8").split("\n");
lines.forEach((line, i) => {
if (UNSAFE.test(line))
offenders.push(`${relative(ROOT, file)}:${i + 1}: ${line.trim()}`);
});
}
if (offenders.length) {
fail(
`direct \`crypto.randomUUID()\` call outside lib/ids.ts — use randomId() instead (insecure contexts crash on it):\n ${offenders.join("\n ")}`,
);
} else {
ok("no direct `crypto.randomUUID()` calls in src/");
}
// ---- result ------------------------------------------------------------
if (failures) {
console.error(`\n${failures} randomId/insecure-context check(s) failed.`);
process.exit(1);
}
console.log("\nrandomId insecure-context checks passed.");
+1 -1
View File
@@ -8,7 +8,7 @@
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700&family=IBM+Plex+Sans:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap"
href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700&family=IBM+Plex+Sans:wght@400;500;600&family=JetBrains+Mono:wght@400;500&family=Noto+Sans+SC:wght@400;500;600&display=swap"
rel="stylesheet"
/>
%sveltekit.head%
+19
View File
@@ -81,6 +81,8 @@ export interface LlmProfile {
base_url: string;
model: string;
api_key: boolean;
/** Last 4 chars of the stored key, for masked display only. */
api_key_tail?: string | null;
}
export interface Settings {
@@ -267,6 +269,23 @@ export const settings = {
get: () => api<Settings>('/api/settings'),
update: (payload: Record<string, unknown>) =>
api<Settings>('/api/settings', { method: 'POST', body: JSON.stringify(payload) }),
testLlm: (payload: {
profile_id?: string;
base_url?: string;
model?: string;
api_key?: string;
timeout_sec?: number;
}) =>
api<{
ok: boolean;
elapsed_ms?: number;
error?: string;
detail?: string;
timeout_sec?: number;
}>('/api/settings/llm-test', {
method: 'POST',
body: JSON.stringify(payload),
}),
};
export const workflows = {
@@ -3,7 +3,7 @@
import { t } from '$lib/i18n.svelte';
interface Props {
active?: 'projects' | 'canvas' | 'build-scene' | 'library' | 'settings';
active?: 'projects' | 'canvas' | 'build-scene' | 'library' | 'agents' | 'models' | 'settings';
crumb?: string;
/** Optional status content rendered between the crumb and the nav. */
status?: import('svelte').Snippet;
@@ -31,6 +31,8 @@ interface Props {
<a class="nav-link" class:active={active === 'projects'} href="/projects">{t('nav.projects')}</a>
<a class="nav-link" class:active={active === 'build-scene'} href="/build-scene">{t('nav.buildScene')}</a>
<a class="nav-link" class:active={active === 'library'} href="/library">{t('nav.library')}</a>
<a class="nav-link" class:active={active === 'agents'} href="/agents">{t('nav.agents')}</a>
<a class="nav-link" class:active={active === 'models'} href="/models">{t('nav.models')}</a>
<a class="nav-link" class:active={active === 'settings'} href="/settings">{t('nav.settings')}</a>
</nav>
</div>
@@ -0,0 +1,469 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { createMutation, useQueryClient } from '@tanstack/svelte-query';
import { assetUrl, projects, type Project } from '$lib/api';
import { toast } from '$lib/toast';
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 Modal from '$lib/components/ui/Modal.svelte';
import { t } from '$lib/i18n.svelte';
/**
* A「片场暗房」project card for the home overview (a1, HEL-608).
* All numbers come from the real project record — no sample progress.
*/
interface Props {
project: Project;
}
let { project }: Props = $props();
const client = useQueryClient();
const stats = $derived(
project.stats ?? {
scene_count: 0,
character_count: 0,
asset_ready_count: 0,
asset_total_count: 0,
},
);
// Spec §2.1 allows the five avatar gradients as cover placeholders.
const PLACEHOLDER_GRADIENTS = [
'linear-gradient(135deg, #e8a33d, #b96a1b)',
'linear-gradient(135deg, #5b8def, #3a5fa9)',
'linear-gradient(135deg, #3fb97f, #2a7a54)',
'linear-gradient(135deg, #b98be0, #7a4fa9)',
'linear-gradient(135deg, #d98e6a, #a95535)',
];
const placeholder = $derived(PLACEHOLDER_GRADIENTS[project.id % PLACEHOLDER_GRADIENTS.length]);
const coverUrl = $derived(assetUrl(project.cover_path));
let coverFailed = $state(false);
const STATUS_CLASS: Record<string, string> = {
draft: 'st-draft',
in_progress: 'st-progress',
completed: 'st-done',
};
const STATUS_KEY: Record<string, string> = {
draft: 'home.statusDraft',
in_progress: 'home.statusProgress',
completed: 'home.statusDone',
};
const statusClass = $derived(STATUS_CLASS[project.status] ?? 'st-draft');
const statusLabel = $derived(
project.status in STATUS_KEY ? t(STATUS_KEY[project.status]) : project.status,
);
function relativeTime(iso: string): string {
const then = new Date(iso).getTime();
if (Number.isNaN(then)) return '';
const mins = Math.max(0, Math.round((Date.now() - then) / 60000));
if (mins < 1) return t('projectCard.timeJustNow');
if (mins < 60) return t('projectCard.timeM', { count: mins });
const hours = Math.round(mins / 60);
if (hours < 24) return t('projectCard.timeH', { count: hours });
const days = Math.round(hours / 24);
if (days < 30) return t('projectCard.timeD', { count: days });
const months = Math.round(days / 30);
if (months < 12) return t('projectCard.timeMo', { count: months });
return t('projectCard.timeY', { count: Math.round(months / 12) });
}
const updatedLabel = $derived(relativeTime(project.updated_at));
// ---- overflow menu (rename / delete), pattern from ProjectCard ----
let menuOpen = $state(false);
let menuEl = $state<HTMLDivElement | null>(null);
$effect(() => {
if (!menuOpen) return;
const onDocClick = (e: MouseEvent) => {
if (menuEl && !menuEl.contains(e.target as Node)) menuOpen = false;
};
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') menuOpen = false;
};
window.addEventListener('click', onDocClick);
window.addEventListener('keydown', onKey);
return () => {
window.removeEventListener('click', onDocClick);
window.removeEventListener('keydown', onKey);
};
});
let renameOpen = $state(false);
let renameValue = $state('');
function openRename() {
menuOpen = false;
renameValue = project.title;
renameOpen = true;
}
const renameMutation = createMutation({
mutationFn: (title: string) => projects.update(project.id, { title }),
onSuccess: () => {
client.invalidateQueries({ queryKey: ['projects'] });
toast.success(t('projectCard.renamedTo', { title: renameValue }));
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : t('projectCard.renameFailed'));
},
});
function submitRename() {
const title = renameValue.trim();
renameOpen = false;
if (!title || title === project.title) return;
$renameMutation.mutate(title);
}
let deleteOpen = $state(false);
const deleteMutation = createMutation({
mutationFn: () => projects.delete(project.id),
onSuccess: () => {
client.invalidateQueries({ queryKey: ['projects'] });
toast.success(t('projectCard.deleted', { title: project.title }));
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : t('projectCard.deleteFailed'));
},
});
</script>
<article class="a-card">
<button
type="button"
class="card-main"
aria-label={t('projectCard.open', { title: project.title })}
onclick={() => goto(`/project/${project.id}`)}
>
<span class="cover">
{#if coverUrl && !coverFailed}
<img
class="cover-img"
src={coverUrl}
alt=""
loading="lazy"
onerror={() => (coverFailed = true)}
/>
{:else}
<span class="cover-ph" style:background={placeholder} aria-hidden="true">
<Icon name="film" size={22} />
</span>
{/if}
<span class="status-tag {statusClass}">{statusLabel}</span>
</span>
<span class="body">
<span class="title-row">
<span class="title">{project.title}</span>
<span class="arrow" aria-hidden="true">→</span>
</span>
<span class="idea">{project.idea || t('home.noIdea')}</span>
<span class="meta">
<span class="meta-stats mono">
{t('home.statScenes', { n: stats.scene_count })}
· {t('home.statCharacters', { n: stats.character_count })}
· {t('home.statAssets', {
ready: stats.asset_ready_count,
total: stats.asset_total_count,
})}
</span>
<span class="meta-time">{updatedLabel}</span>
</span>
</span>
</button>
<div class="menu-wrap" bind:this={menuEl}>
<button
type="button"
class="menu-btn"
aria-label={t('projectCard.actions', { title: project.title })}
aria-haspopup="menu"
aria-expanded={menuOpen}
onclick={() => (menuOpen = !menuOpen)}
>
⋯
</button>
{#if menuOpen}
<div class="menu" role="menu">
<button type="button" role="menuitem" class="menu-item" onclick={openRename}>
<Icon name="edit" size={14} />
{t('common.rename')}
</button>
<button
type="button"
role="menuitem"
class="menu-item danger"
onclick={() => {
menuOpen = false;
deleteOpen = true;
}}
>
<Icon name="trash" size={14} />
{t('common.delete')}
</button>
</div>
{/if}
</div>
</article>
<Modal bind:open={renameOpen} title={t('projectCard.renameTitle')}>
<form
onsubmit={(e) => {
e.preventDefault();
submitRename();
}}
>
<label class="field">
<span class="field-label">{t('common.title')}</span>
<input class="field-input" bind:value={renameValue} required />
</label>
</form>
{#snippet footer()}
<Button variant="ghost" onclick={() => (renameOpen = false)}>{t('common.cancel')}</Button>
<Button
variant="primary"
disabled={!renameValue.trim() || $renameMutation.isPending}
onclick={submitRename}
>
{t('common.rename')}
</Button>
{/snippet}
</Modal>
<ConfirmDialog
bind:open={deleteOpen}
title={t('projectCard.deleteTitle')}
message={t('projectCard.deleteMessage', { title: project.title })}
confirmLabel={t('common.delete')}
danger
onconfirm={() => $deleteMutation.mutate()}
/>
<style>
.a-card {
position: relative;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
overflow: hidden;
transition: border-color 150ms cubic-bezier(0.16, 1, 0.3, 1);
}
.a-card:hover {
border-color: var(--border-strong);
}
.a-card:hover .arrow {
opacity: 1;
transform: translateX(0);
}
.card-main {
display: flex;
flex-direction: column;
width: 100%;
padding: 0;
border: none;
background: transparent;
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
}
.card-main:focus-visible {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.cover {
position: relative;
display: block;
height: 132px;
background: var(--surface-2);
overflow: hidden;
}
.cover-img {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
.cover-ph {
position: absolute;
inset: 0;
display: inline-flex;
align-items: center;
justify-content: center;
color: rgba(22, 19, 10, 0.82);
opacity: 0.9;
}
.status-tag {
position: absolute;
top: 8px;
right: 8px;
padding: 2px 9px;
border-radius: 999px;
font-size: 10.5px;
font-weight: 600;
backdrop-filter: blur(4px);
}
.st-draft {
color: var(--text-2);
background: rgba(27, 30, 37, 0.85);
border: 1px solid var(--border-strong);
}
.st-progress {
color: var(--accent);
background: var(--accent-dim);
}
.st-done {
color: var(--success);
background: var(--success-dim);
}
.body {
display: flex;
flex-direction: column;
gap: 6px;
padding: 14px 16px 15px;
}
.title-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.title {
font-size: 14px;
font-weight: 600;
color: var(--text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.arrow {
color: var(--accent);
font-size: 13px;
opacity: 0;
transform: translateX(-6px);
transition:
opacity 150ms cubic-bezier(0.16, 1, 0.3, 1),
transform 150ms cubic-bezier(0.16, 1, 0.3, 1);
}
.idea {
font-size: 12px;
color: var(--text-2);
line-height: 1.6;
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
min-height: 2.2em;
}
.meta {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.meta-stats {
font-size: 11px;
color: var(--text-3);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.meta-time {
font-size: 11px;
color: var(--text-3);
flex-shrink: 0;
}
.menu-wrap {
position: absolute;
top: 8px;
left: 8px;
z-index: 3;
}
.menu-btn {
width: 28px;
height: 28px;
border: 1px solid transparent;
border-radius: 7px;
background: rgba(13, 14, 17, 0.6);
color: var(--text-2);
font-size: 15px;
line-height: 1;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
transition: opacity 150ms;
}
.a-card:hover .menu-btn,
.menu-btn:focus-visible,
.menu-btn[aria-expanded='true'] {
opacity: 1;
}
.menu-btn:hover {
background: var(--surface-3);
color: var(--text);
}
.menu {
position: absolute;
top: 32px;
left: 0;
min-width: 132px;
background: var(--surface-2);
border: 1px solid var(--border-strong);
border-radius: 8px;
padding: 4px;
display: flex;
flex-direction: column;
}
.menu-item {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 7px 9px;
border: none;
border-radius: 6px;
background: transparent;
color: var(--text);
font-size: 12.5px;
font-family: inherit;
cursor: pointer;
text-align: left;
}
.menu-item:hover {
background: var(--surface-3);
}
.menu-item.danger {
color: var(--error);
}
.menu-item.danger:hover {
background: var(--error-dim);
}
/* restyle reused ui/Button + form primitives inside the darkroom scope */
.a-card :global(.btn-primary) {
background: var(--accent);
color: var(--accent-contrast);
}
.a-card :global(.field-input) {
background: var(--surface-2);
border-color: var(--border-strong);
color: var(--text);
}
</style>
@@ -0,0 +1,458 @@
<script lang="ts">
import { createQuery } from '@tanstack/svelte-query';
import LanguageSwitcher from '$lib/components/LanguageSwitcher.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import type { IconName } from '$lib/components/ui/icons';
import { settings } from '$lib/api';
import { t } from '$lib/i18n.svelte';
/**
* A「片场暗房」application shell — spec-v2 §3 (HEL-608).
*
* 216px left navigation with the confirmed item order, the 影工坊 brand,
* a ComfyUI address row pinned to the nav bottom, and a per-page top bar
* (title 20/600 + gray blurb + page actions). Unbuilt pages stay in the
* nav with an honest 「开发中」 pill instead of pretending to work.
*/
type NavId =
| 'projects'
| 'workbench'
| 'image'
| 'video'
| 'tasks'
| 'agents'
| 'connections'
| 'models'
| 'settings';
interface NavItem {
id: NavId;
labelKey: string;
icon: IconName;
href?: string;
wip?: boolean;
}
// Order is fixed by spec-v2 §3: 项目 / 创作工作台 / 生图 / 生视频 /
// 生成任务 / 智能体 / ComfyUI 连接 / 模型设置 / 设置.
const NAV: NavItem[] = [
{ id: 'projects', labelKey: 'shell.navProjects', icon: 'home', href: '/' },
{ id: 'workbench', labelKey: 'shell.navWorkbench', icon: 'story', href: '/canvas' },
{ id: 'image', labelKey: 'shell.navImage', icon: 'image', wip: true },
{ id: 'video', labelKey: 'shell.navVideo', icon: 'film', wip: true },
{ id: 'tasks', labelKey: 'shell.navTasks', icon: 'queue', wip: true },
{ id: 'agents', labelKey: 'shell.navAgents', icon: 'sparkle', href: '/agents' },
{ id: 'connections', labelKey: 'shell.navConnections', icon: 'link', wip: true },
{ id: 'models', labelKey: 'shell.navModels', icon: 'assets', href: '/models' },
{ id: 'settings', labelKey: 'shell.navSettings', icon: 'settings', href: '/settings' },
];
interface Props {
active: NavId;
title: string;
subtitle?: string;
/** Page-level actions rendered right of the top bar (chips / buttons). */
actions?: import('svelte').Snippet;
children?: import('svelte').Snippet;
}
let { active, title, subtitle, actions, children }: Props = $props();
// Real ComfyUI address from settings — shown honestly without a fake
// "connected" claim; the standalone connections page is not built yet.
const settingsQuery = createQuery({
queryKey: ['settings'],
queryFn: settings.get,
staleTime: 60_000,
});
const comfyUrl = $derived.by(() => {
const raw = ($settingsQuery.data?.comfyui_base_url ?? '').trim();
if (!raw) return '';
try {
const u = new URL(raw.includes('://') ? raw : `http://${raw}`);
return u.host;
} catch {
return raw;
}
});
</script>
<svelte:head>
<title>{title} · {t('shell.brand')}</title>
</svelte:head>
<div class="a-shell a-darkroom">
<!-- Mobile guard: this is a desktop-first tool (spec §4.5). -->
<div class="desktop-only-notice" data-testid="mobile-notice">
<Icon name="film" size={22} />
<p>{t('shell.mobileNotice')}</p>
</div>
<div class="shell-frame">
<aside class="side">
<a class="brand" href="/" title={t('shell.brandHome')}>
<span class="brand-mark"><Icon name="film" size={17} /></span>
<span class="brand-name">{t('shell.brand')}</span>
</a>
<nav class="nav" aria-label={t('shell.navAria')}>
{#each NAV as item (item.id)}
{#if item.href}
<a
class="nav-item"
class:active={active === item.id}
href={item.href}
aria-current={active === item.id ? 'page' : undefined}
>
<span class="nav-icon"><Icon name={item.icon} size={17} /></span>
<span class="nav-label">{t(item.labelKey)}</span>
</a>
{:else}
<span class="nav-item disabled" title={t('shell.wipHint')} aria-disabled="true">
<span class="nav-icon"><Icon name={item.icon} size={17} /></span>
<span class="nav-label">{t(item.labelKey)}</span>
<span class="wip-pill">{t('shell.wip')}</span>
</span>
{/if}
{/each}
</nav>
<div class="side-foot">
<a class="comfy-row" href="/settings" title={t('shell.comfyManage')}>
<span class="dot" aria-hidden="true"></span>
<span class="comfy-text">
{#if comfyUrl}
{t('shell.comfyAt', { host: comfyUrl })}
{:else}
{t('shell.comfyUnset')}
{/if}
</span>
</a>
<div class="lang-row">
<LanguageSwitcher />
</div>
</div>
</aside>
<div class="main">
<header class="topbar">
<div class="topbar-copy">
<h1>{title}</h1>
{#if subtitle}<p class="sub">{subtitle}</p>{/if}
</div>
{#if actions}
<div class="topbar-actions">
{@render actions()}
</div>
{/if}
</header>
<div class="body">
{@render children?.()}
</div>
</div>
</div>
</div>
<style>
.a-shell {
position: fixed;
inset: 0;
}
.desktop-only-notice {
display: none;
}
.shell-frame {
height: 100%;
display: flex;
min-width: 0;
}
/* ---------------- side navigation (§3, 216px) ---------------- */
.side {
width: 216px;
flex-shrink: 0;
background: var(--surface);
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
padding: 16px 12px 12px;
gap: 14px;
box-sizing: border-box;
overflow-y: auto;
}
.brand {
display: flex;
align-items: center;
gap: 9px;
padding: 2px 8px;
text-decoration: none;
color: var(--text);
}
.brand-mark {
width: 30px;
height: 30px;
border-radius: 8px;
background: linear-gradient(135deg, #e8a33d, #b96a1b);
color: #16130a;
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.brand-name {
font-size: 15.5px;
font-weight: 700;
letter-spacing: 0.02em;
white-space: nowrap;
}
.nav {
display: flex;
flex-direction: column;
gap: 2px;
}
.nav-item {
display: flex;
align-items: center;
gap: 10px;
min-height: 38px;
padding: 0 10px;
border-radius: 8px;
color: var(--text-2);
font-size: 13px;
text-decoration: none;
transition:
background-color 150ms cubic-bezier(0.16, 1, 0.3, 1),
color 150ms;
}
.nav-item .nav-icon {
display: inline-flex;
flex-shrink: 0;
}
a.nav-item:hover {
background: var(--surface-3);
color: var(--text);
}
.nav-item.active {
background: var(--surface-3);
color: var(--text);
font-weight: 600;
}
.nav-item.disabled {
cursor: default;
user-select: none;
color: var(--text-3);
}
.wip-pill {
margin-left: auto;
padding: 1px 8px;
border-radius: 999px;
background: var(--surface-3);
color: var(--text-3);
font-size: 10px;
white-space: nowrap;
}
.side-foot {
margin-top: auto;
display: flex;
flex-direction: column;
gap: 8px;
padding-top: 12px;
border-top: 1px solid var(--border);
}
.comfy-row {
display: flex;
align-items: center;
gap: 8px;
padding: 7px 10px;
border-radius: 7px;
text-decoration: none;
color: var(--text-2);
font-size: 11.5px;
transition:
background-color 150ms cubic-bezier(0.16, 1, 0.3, 1),
color 150ms;
}
.comfy-row:hover {
background: var(--surface-3);
color: var(--text);
}
/* Untested by default — the connections page (a6) is not built yet, so
no green "connected" claim is made (honesty rule on HEL-608). */
.dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--text-3);
flex-shrink: 0;
}
.comfy-text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.lang-row :global(.lang-switcher) {
background: var(--surface-2);
color: var(--text-2);
border-color: var(--border-strong);
width: 100%;
box-sizing: border-box;
}
/* ---------------- main column ---------------- */
.main {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
background: var(--bg);
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 14px 28px;
border-bottom: 1px solid var(--border);
background: var(--bg);
flex-shrink: 0;
min-height: 64px;
box-sizing: border-box;
}
.topbar-copy h1 {
margin: 0;
font-size: 20px;
font-weight: 600;
color: var(--text);
line-height: 1.3;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.sub {
margin: 3px 0 0;
font-size: 12.5px;
color: var(--text-3);
line-height: 1.5;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.topbar-actions {
display: flex;
align-items: center;
gap: 10px;
flex-shrink: 0;
}
.body {
flex: 1;
min-height: 0;
overflow-y: auto;
}
/* ---------------- responsive (§4.5) ---------------- */
@media (max-width: 1023px) {
.side {
width: 64px;
padding: 14px 8px 10px;
align-items: center;
}
.brand {
padding: 0;
justify-content: center;
}
.brand-name {
display: none;
}
.nav {
width: 100%;
}
.nav-item {
justify-content: center;
padding: 0;
}
.nav-label {
display: none;
}
.wip-pill {
display: none;
}
/* icon-only rail: a small dot marks unbuilt entries */
.nav-item.disabled .nav-icon {
position: relative;
}
.nav-item.disabled .nav-icon::after {
content: '';
position: absolute;
top: -2px;
right: -4px;
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--text-3);
}
.comfy-text,
.lang-row {
display: none;
}
.comfy-row {
justify-content: center;
padding: 6px;
}
.topbar {
padding: 12px 18px;
}
.sub {
white-space: normal;
}
}
@media (max-width: 767px) {
.shell-frame {
display: none;
}
.desktop-only-notice {
display: flex;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
padding: 32px;
text-align: center;
color: var(--text-2);
}
.desktop-only-notice p {
margin: 0;
font-size: 14px;
line-height: 1.7;
}
.desktop-only-notice :global(.icon) {
color: var(--accent);
}
}
</style>
+1 -1
View File
@@ -25,7 +25,7 @@ function initialLanguage(): Language {
// language this build no longer ships must not blank the UI. This runs on
// the server too, where storage is absent and we render the default.
const stored = storageGet(STORAGE_KEY);
return isLanguage(stored) ? stored : 'en';
return isLanguage(stored) ? stored : 'zh';
}
export const language = $state<{ current: Language }>({ current: initialLanguage() });
+154
View File
@@ -34,6 +34,8 @@ export const de: Dict = {
'nav.projects': 'Projekte',
'nav.buildScene': 'Szene bauen',
'nav.settings': 'Einstellungen',
'nav.agents': 'Agenten',
'nav.models': 'Modelle',
'nav.home': 'Start',
'nav.primary': 'Primär',
'nav.projectStages': 'Projektphasen',
@@ -995,6 +997,12 @@ export const de: Dict = {
'settings.removeLlmTitle': 'LLM entfernen',
'settings.name': 'Name',
'settings.active': 'Aktiv',
'settings.testLlm': 'Verbindung testen',
'settings.llmTestOk': 'Verbindung erfolgreich ({ms} ms)',
'settings.llmTestFail': 'Verbindung fehlgeschlagen: {detail}',
'settings.llmTestAuth': 'Schlüssel abgelehnt ({detail})',
'settings.llmTestTimeout': 'Keine Antwort innerhalb von 15 s',
'settings.llmTestConnect': 'Server nicht erreichbar ({detail})',
'settings.agentModelsSection': 'Agentenmodell',
'settings.agentModelsLead': 'Modell für Story-Entwürfe und Agenten-Aufgaben.',
'settings.agentMaxStepsField': 'Max. Schritte',
@@ -1128,4 +1136,150 @@ export const de: Dict = {
'shot.errBlob': 'Der aufgenommene Frame konnte nicht gelesen werden',
'shot.errRecorder': 'Recorder konnte nicht gestartet werden',
'shot.errNoData': 'Keine Szenendaten zum Exportieren',
// Models settings page (spec-v2 §9)
'models.title': 'Modelle',
'models.subtitle': 'Eigene LLMs für Agenten anlegen · Phase 1 nur LLMs; Bild-/Videomodelle folgen später',
'models.statusCount': '{n} Modelle · {m} verfügbar',
'models.add': '+ Modell hinzufügen',
'models.tabLlm': 'Sprachmodelle',
'models.tabImage': 'Bildmodelle',
'models.tabVideo': 'Videomodelle',
'models.comingSoon': 'Später',
'models.empty': 'Noch keine Modelle — oben rechts auf „Modell hinzufügen“ klicken, um das erste LLM anzubinden',
'models.typeLocal': 'Lokal',
'models.typeLan': 'LAN',
'models.typeCloud': 'Cloud',
'models.defaultBadge': 'Agenten-Standard',
'models.setDefault': 'Als Standard',
'models.defaultSetToast': 'Als Agenten-Standardmodell gesetzt',
'models.test': 'Verbindung testen',
'models.testing': 'Teste…',
'models.edit': 'Bearbeiten',
'models.delete': 'Löschen',
'models.statusUntested': 'Nicht getestet',
'models.statusConnected': 'Verbunden',
'models.statusFailed': 'Verbindung fehlgeschlagen',
'models.latency': '{ms}ms Latenz',
'models.agentsUsing': 'von {n} Agenten genutzt',
'models.lastTestAt': 'letzter Test {time}',
'models.consecutiveFails': '{n} Fehlversuche in Folge',
'models.cloudPaused': 'Cloud-Aufrufe pausiert',
'models.formTitleAdd': 'Modell hinzufügen',
'models.formTitleEdit': 'Modell bearbeiten',
'models.formClose': 'Schließen',
'models.fName': 'Name',
'models.fNamePh': 'Modell benennen, z. B. DeepSeek offiziell',
'models.fApiType': 'API-Typ',
'models.apiOpenai': 'OpenAI-kompatibel',
'models.apiAnthropic': 'Anthropic',
'models.apiOther': 'Andere',
'models.apiTypeHelp': 'Phase 1 unterstützt nur OpenAI-kompatible APIs; weitere Protokolle kommen mit Bild-/Videomodellen',
'models.fBaseUrl': 'Basis-URL',
'models.baseUrlHelp': 'Mit Protokoll und Port, z. B. http://192.168.200.18:11434/v1',
'models.fModel': 'Modellname',
'models.modelHelp': 'Modell-ID des Anbieters verwenden',
'models.fApiKey': 'API-Schlüssel',
'models.keyNoEcho': 'wird nie angezeigt',
'models.keyHelp': 'Wird nur auf diesem Server gespeichert; der vollständige Schlüssel erscheint nie in der Oberfläche',
'models.keyKeepHint': 'Schlüssel gespeichert — leer lassen zum Behalten',
'models.fTimeout': 'Zeitüberschreitung',
'models.timeoutSec': '{n}s',
'models.testOk': '✓ Test bestanden · {ms}ms · {model} verfügbar',
'models.testFail': '✕ Test fehlgeschlagen · {reason}',
'models.needTest': 'Speichern erst nach bestandenem Test',
'models.testBtn': 'Verbindung testen',
'models.save': 'Modell speichern',
'models.errName': 'Bitte benennen Sie das Modell',
'models.errUrl': 'Ungültige URL — Protokoll und Pfad nötig, z. B. https://api.deepseek.com/v1',
'models.errModel': 'Bitte den Modellnamen des Anbieters eingeben',
'models.errKey': 'Bitte den API-Schlüssel eingeben',
'models.failTimeout': 'Zeitüberschreitung ({sec}s, keine Antwort): der Server erreicht diese Adresse nicht — Adresse, Port und Firewall prüfen',
'models.failAuth': 'Authentifizierung fehlgeschlagen (401): API-Schlüssel prüfen; bei Aggregatoren die Modellfreischaltung bestätigen',
'models.failNotFound': 'Erreichbar, Modell aber nicht gefunden (404): Modellnamen prüfen',
'models.failNotOpenai': 'Erreichbar, aber keine OpenAI-kompatible API — Pfad muss auf /v1 enden',
'models.failConnect': 'Der Server kann diese Adresse nicht erreichen — Adresse und Port prüfen',
'models.failHttp': 'Test failed (HTTP {status})',
'models.delTitle': 'Modell löschen',
'models.delConfirmUsed': '{n} Agenten nutzen dieses Modell; nach dem Löschen nutzen sie den Agenten-Standard. Löschen?',
'models.delConfirmFree': 'Dieses Modell löschen? Kann nicht widerrufen werden.',
'models.delDefaultHint': 'Dies ist der Agenten-Standard — zuerst einen anderen Standard wählen',
'models.agentsTitle': 'Agenten-Standardmodelle',
'models.agentsHint': 'Gilt für neue Sitzungen · individuelle Auswahl auf der Agenten-Seite',
'models.agentDefault': 'Agenten-Standard',
'models.agentStory': 'Drehbuch',
'models.agentStyle': 'Visuelles Design',
'models.agentScript': 'Storyboards',
'models.agentAssets': 'Asset-Bibliothek',
'models.agentVideo': 'Shotlisten',
'models.unavailable': '(nicht verfügbar)',
'models.noticeStrong': 'Erreichbarkeit gilt vom Workbench-Server aus:',
'models.noticeBody': 'eine im Browser öffnungsfähige Adresse ist nicht automatisch vom Server erreichbar; Verbindungs- und Dialoganfragen stellt der Server. API-Schlüssel liegen nur auf dem Server und werden nie angezeigt.',
'models.saved': 'Modell gespeichert',
'models.deleted': 'Modell gelöscht',
'models.assignSaved': 'Agentenmodelle aktualisiert',
'models.saveFailed': 'Speichern fehlgeschlagen: {detail}',
'models.loading': 'Lädt…',
'models.loadFailed': 'Einstellungen konnten nicht geladen werden',
'models.idleFormHint': '„Bearbeiten“ auf einer Karte wählen oder oben „Modell hinzufügen“ klicken',
// --- A shell + projects overview (HEL-608) ---
'shell.brand': 'Film-Atelier',
'shell.brandHome': 'Zur Projektübersicht',
'shell.navAria': 'Hauptnavigation',
'shell.navProjects': 'Projekte',
'shell.navWorkbench': 'Werkstatt',
'shell.navImage': 'Bilderzeugen',
'shell.navVideo': 'Videoerzeugen',
'shell.navTasks': 'Aufträge',
'shell.navAgents': 'Agenten',
'shell.navConnections': 'ComfyUI-Verbindungen',
'shell.navModels': 'Modelle',
'shell.navSettings': 'Einstellungen',
'shell.wip': 'In Entwicklung',
'shell.wipHint': 'Diese Seite ist noch im Bau und folgt später',
'shell.comfyAt': 'ComfyUI · {host}',
'shell.comfyUnset': 'ComfyUI · nicht konfiguriert',
'shell.comfyManage': 'ComfyUI-Adresse in den Einstellungen pflegen',
'shell.mobileNotice': 'Bitte öffne diese Werkbank in einem Desktop-Browser (mindestens 768px breit); Handys werden noch nicht unterstützt.',
'home.title': 'Projektübersicht',
'home.subtitle': 'Verwalte deine Projekte — starte mit einer Idee oder einem fertigen Drehbuch.',
'home.projectCount': '{n} Projekte · {m} in Arbeit',
'home.startIdea': 'Mit einer Idee starten',
'home.importScript': 'Drehbuch importieren',
'home.entryIdeaTitle': 'Mit einer Idee starten',
'home.entryIdeaBody': 'Beschreibe eine Idee; die Agenten führen sie Schritt für Schritt durch Story, Storyboard und Clips.',
'home.entryScriptTitle': 'Drehbuch importieren',
'home.entryScriptBody': 'Schon ein Drehbuch? Einfügen, Projekt anlegen und der Drehbuch-Agent zerlegt es in geordnete Szenen.',
'home.ideaPlaceholder': 'Ein regnerischer kleiner Hafen, in dem der Leuchtfeuerwärter …',
'home.scriptField': 'Vollständiges Drehbuch',
'home.scriptPlaceholder': 'Das vollständige Drehbuch hier einfügen …',
'home.scriptHint': 'Nach dem Anlegen öffnet sich die Agenten-Seite; der Drehbuch-Agent macht aus dem Text geordnete Szenen.',
'home.errTitle': 'Bitte gib dem Projekt einen Titel',
'home.errScript': 'Bitte füge das vollständige Drehbuch ein',
'home.myProjects': 'Meine Projekte',
'home.myProjectsHint': 'Projekt anklicken, um weiterzuarbeiten',
'home.emptyProjects': 'Noch keine Projekte. Lege oben über „Mit einer Idee starten“ oder „Drehbuch importieren“ das erste an.',
'home.noIdea': 'Noch keine Ideenbeschreibung',
'home.statScenes': '{n} Szenen',
'home.statCharacters': '{n} Figuren',
'home.statAssets': 'Assets {ready}/{total}',
'home.statusDraft': 'Entwurf',
'home.statusProgress': 'In Arbeit',
'home.statusDone': 'Abgeschlossen',
'home.tasksTitle': 'Aufträge',
'home.activeJobs': '{n} aktiv',
'home.emptyJobs': 'Noch keine Generierungsaufträge',
'home.emptyJobsSub': 'Aufträge aus Projekten oder der Werkstatt erscheinen hier.',
'home.tasksNote': 'Die eigenständige Auftragsseite ist in Entwicklung; die vollständige Historie liegt derzeit in jedem Projekt.',
'home.kindImage': 'Bild',
'home.kindVideo': 'Video',
'home.kindExport': 'Film',
'home.jobDone': 'fertig',
'home.jobRunning': 'läuft',
'home.jobQueued': 'wartet',
'home.jobFailed': 'fehlgeschlagen',
'home.jobRequeued': 'Auftrag erneut eingereiht',
'home.jobRetryFailed': 'Erneutes Einreihen fehlgeschlagen',
'home.jobProject': 'Projekt #{id}',
};
+154 -1
View File
@@ -32,6 +32,8 @@ export const en = {
'nav.projects': 'Projects',
'nav.buildScene': 'Build Scene',
'nav.settings': 'Settings',
'nav.agents': 'Agents',
'nav.models': 'Models',
'nav.home': 'Home',
'nav.primary': 'Primary',
'nav.projectStages': 'Project stages',
@@ -995,6 +997,12 @@ export const en = {
'settings.removeLlmTitle': 'Remove LLM',
'settings.name': 'Name',
'settings.active': 'Active',
'settings.testLlm': 'Test connection',
'settings.llmTestOk': 'Connected ({ms} ms)',
'settings.llmTestFail': 'Connection failed: {detail}',
'settings.llmTestAuth': 'API key rejected ({detail})',
'settings.llmTestTimeout': 'No response within 15 s',
'settings.llmTestConnect': 'Could not reach the server ({detail})',
'settings.agentModelsSection': 'Agent model',
'settings.agentModelsLead': 'Model used for story drafting and agent tasks.',
'settings.agentMaxStepsField': 'Max steps',
@@ -1128,6 +1136,151 @@ export const en = {
'shot.errBlob': 'Could not read the captured frame',
'shot.errRecorder': 'Could not start recorder',
'shot.errNoData': 'No scene data to export',
};
// Models settings page (spec-v2 §9)
'models.title': 'Models',
'models.subtitle': 'Add custom LLMs for your agents · phase 1 covers LLMs only; image / video models come later',
'models.statusCount': '{n} models · {m} available',
'models.add': '+ Add model',
'models.tabLlm': 'Language models',
'models.tabImage': 'Image models',
'models.tabVideo': 'Video models',
'models.comingSoon': 'Coming later',
'models.empty': 'No models yet — click "Add model" in the top right to connect your first LLM',
'models.typeLocal': 'Local',
'models.typeLan': 'LAN',
'models.typeCloud': 'Cloud',
'models.defaultBadge': 'Agent default',
'models.setDefault': 'Set as default',
'models.defaultSetToast': 'Set as agent default model',
'models.test': 'Test connection',
'models.testing': 'Testing…',
'models.edit': 'Edit',
'models.delete': 'Delete',
'models.statusUntested': 'Not tested',
'models.statusConnected': 'Connected',
'models.statusFailed': 'Connection failed',
'models.latency': '{ms}ms latency',
'models.agentsUsing': 'used by {n} agents',
'models.lastTestAt': 'last test {time}',
'models.consecutiveFails': '{n} consecutive failures',
'models.cloudPaused': 'Cloud calls paused',
'models.formTitleAdd': 'Add model',
'models.formTitleEdit': 'Edit model',
'models.formClose': 'Close',
'models.fName': 'Name',
'models.fNamePh': 'Name this model, e.g. DeepSeek official',
'models.fApiType': 'API type',
'models.apiOpenai': 'OpenAI-compatible',
'models.apiAnthropic': 'Anthropic',
'models.apiOther': 'Other',
'models.apiTypeHelp': 'Phase 1 supports OpenAI-compatible APIs only; other protocols arrive with image / video models',
'models.fBaseUrl': 'Base URL',
'models.baseUrlHelp': 'Include protocol and port, e.g. http://192.168.200.18:11434/v1',
'models.fModel': 'Model name',
'models.modelHelp': 'Use the model ID from your provider',
'models.fApiKey': 'API key',
'models.keyNoEcho': 'never echoed',
'models.keyHelp': 'Stored on this server only; the full key is never shown in the UI',
'models.keyKeepHint': 'Key saved — leave empty to keep it',
'models.fTimeout': 'Timeout',
'models.timeoutSec': '{n}s',
'models.testOk': '✓ Test passed · {ms}ms · {model} available',
'models.testFail': '✕ Test failed · {reason}',
'models.needTest': 'Save unlocks after a passing test',
'models.testBtn': 'Test connection',
'models.save': 'Save model',
'models.errName': 'Please name this model',
'models.errUrl': 'Invalid URL — it needs protocol and path, e.g. https://api.deepseek.com/v1',
'models.errModel': 'Please enter the model name from your provider',
'models.errKey': 'Please enter the API key',
'models.failTimeout': 'Timed out ({sec}s, no response): the server cannot reach this address — check the address, port and firewall',
'models.failAuth': 'Authentication failed (401): check that the API key is correct and not expired; with aggregators, confirm the model is enabled for your account',
'models.failNotFound': 'Reachable but model not found (404): check the model name spelling',
'models.failNotOpenai': 'Reachable but not recognized as an OpenAI-compatible API — make sure the path ends with /v1',
'models.failConnect': 'The server cannot connect to this address — check the address and port',
'models.failHttp': 'Test failed (HTTP {status})',
'models.delTitle': 'Delete model',
'models.delConfirmUsed': '{n} agents use this model; after deletion they fall back to the agent default. Delete?',
'models.delConfirmFree': 'Delete this model? This cannot be undone.',
'models.delDefaultHint': 'This is the agent default — pick another default first',
'models.agentsTitle': 'Agent default models',
'models.agentsHint': 'Changes apply to new sessions · per-agent overrides live on the Agents page',
'models.agentDefault': 'Agent default',
'models.agentStory': 'Screenplay',
'models.agentStyle': 'Visual design',
'models.agentScript': 'Storyboards',
'models.agentAssets': 'Asset library',
'models.agentVideo': 'Shot lists',
'models.unavailable': '(unavailable)',
'models.noticeStrong': 'Connectivity is measured from the workbench server:',
'models.noticeBody': 'a URL opening in your browser does not mean the server running this workbench can reach it; connection tests and chat requests are made by the server. API keys are stored on the server only and never echoed in the UI.',
'models.saved': 'Model saved',
'models.deleted': 'Model deleted',
'models.assignSaved': 'Agent models updated',
'models.saveFailed': 'Save failed: {detail}',
'models.loading': 'Loading…',
'models.loadFailed': 'Failed to load settings',
'models.idleFormHint': 'Pick "Edit" on a card, or click "Add model" above',
// --- A shell + projects overview (HEL-608) ---
'shell.brand': 'Film Atelier',
'shell.brandHome': 'Back to project overview',
'shell.navAria': 'Primary',
'shell.navProjects': 'Projects',
'shell.navWorkbench': 'Workbench',
'shell.navImage': 'Image Gen',
'shell.navVideo': 'Video Gen',
'shell.navTasks': 'Jobs',
'shell.navAgents': 'Agents',
'shell.navConnections': 'ComfyUI Connections',
'shell.navModels': 'Models',
'shell.navSettings': 'Settings',
'shell.wip': 'In development',
'shell.wipHint': 'This page is under construction and will open later',
'shell.comfyAt': 'ComfyUI · {host}',
'shell.comfyUnset': 'ComfyUI · not configured',
'shell.comfyManage': 'Configure the ComfyUI address in Settings',
'shell.mobileNotice': 'Please open this workbench in a desktop browser (at least 768px wide). Phones are not supported yet.',
'home.title': 'Projects overview',
'home.subtitle': 'Manage your projects — start from an idea or a ready-made script.',
'home.projectCount': '{n} projects · {m} in progress',
'home.startIdea': 'Start from an idea',
'home.importScript': 'Import a script',
'home.entryIdeaTitle': 'Start from an idea',
'home.entryIdeaBody': 'Describe an idea once; the agents take it through story, boards and clips step by step.',
'home.entryScriptTitle': 'Import a script',
'home.entryScriptBody': 'Already have a script? Paste it in, create the project, and let the script agent break it into ordered scenes.',
'home.ideaPlaceholder': 'A rainy little harbor where the lighthouse keeper finds…',
'home.scriptField': 'Full script',
'home.scriptPlaceholder': 'Paste the complete script here…',
'home.scriptHint': 'After creating, the Agents page opens and the script agent turns the pasted script into ordered scenes.',
'home.errTitle': 'Please give the project a title',
'home.errScript': 'Please paste the full script',
'home.myProjects': 'My projects',
'home.myProjectsHint': 'Click a project to continue working',
'home.emptyProjects': 'No projects yet. Use “Start from an idea” or “Import a script” above to create the first one.',
'home.noIdea': 'No idea description yet',
'home.statScenes': '{n} scenes',
'home.statCharacters': '{n} characters',
'home.statAssets': 'assets {ready}/{total}',
'home.statusDraft': 'Draft',
'home.statusProgress': 'In progress',
'home.statusDone': 'Completed',
'home.tasksTitle': 'Jobs',
'home.activeJobs': '{n} active',
'home.emptyJobs': 'No generation jobs yet',
'home.emptyJobsSub': 'Jobs started from a project or the workbench will show up here.',
'home.tasksNote': 'The standalone Jobs page is under development; for now full job history lives inside each project.',
'home.kindImage': 'image',
'home.kindVideo': 'video',
'home.kindExport': 'film',
'home.jobDone': 'done',
'home.jobRunning': 'running',
'home.jobQueued': 'queued',
'home.jobFailed': 'failed',
'home.jobRequeued': 'Job requeued',
'home.jobRetryFailed': 'Could not requeue the job',
'home.jobProject': 'Project #{id}',
};
export type Dict = typeof en;
+154
View File
@@ -34,6 +34,8 @@ export const es: Dict = {
'nav.projects': 'Proyectos',
'nav.buildScene': 'Componer escena',
'nav.settings': 'Ajustes',
'nav.agents': 'Agentes',
'nav.models': 'Modelos',
'nav.home': 'Inicio',
'nav.primary': 'Principal',
'nav.projectStages': 'Etapas del proyecto',
@@ -995,6 +997,12 @@ export const es: Dict = {
'settings.removeLlmTitle': 'Quitar LLM',
'settings.name': 'Nombre',
'settings.active': 'Activo',
'settings.testLlm': 'Probar conexión',
'settings.llmTestOk': 'Conexión correcta ({ms} ms)',
'settings.llmTestFail': 'Error de conexión: {detail}',
'settings.llmTestAuth': 'Clave rechazada ({detail})',
'settings.llmTestTimeout': 'Sin respuesta en 15 s',
'settings.llmTestConnect': 'No se pudo conectar al servidor ({detail})',
'settings.agentModelsSection': 'Modelo del agente',
'settings.agentModelsLead': 'Modelo usado para redactar la historia y para las tareas del agente.',
'settings.agentMaxStepsField': 'Pasos máximos',
@@ -1128,4 +1136,150 @@ export const es: Dict = {
'shot.errBlob': 'No se pudo leer el fotograma capturado',
'shot.errRecorder': 'No se pudo iniciar el grabador',
'shot.errNoData': 'No hay datos de escena para exportar',
// Models settings page (spec-v2 §9)
'models.title': 'Modelos',
'models.subtitle': 'Añade LLM personalizados para tus agentes · la fase 1 solo incluye LLM; los modelos de imagen / vídeo llegarán después',
'models.statusCount': '{n} modelos · {m} disponibles',
'models.add': '+ Añadir modelo',
'models.tabLlm': 'Modelos de lenguaje',
'models.tabImage': 'Modelos de imagen',
'models.tabVideo': 'Modelos de vídeo',
'models.comingSoon': 'Próximamente',
'models.empty': 'Aún no hay modelos: pulsa «Añadir modelo» arriba a la derecha para conectar tu primer LLM',
'models.typeLocal': 'Local',
'models.typeLan': 'LAN',
'models.typeCloud': 'Nube',
'models.defaultBadge': 'Predeterminado',
'models.setDefault': 'Predeterminar',
'models.defaultSetToast': 'Modelo predeterminado de agentes actualizado',
'models.test': 'Probar conexión',
'models.testing': 'Probando…',
'models.edit': 'Editar',
'models.delete': 'Eliminar',
'models.statusUntested': 'Sin probar',
'models.statusConnected': 'Conectado',
'models.statusFailed': 'Conexión fallida',
'models.latency': '{ms}ms de latencia',
'models.agentsUsing': 'usado por {n} agentes',
'models.lastTestAt': 'última prueba {time}',
'models.consecutiveFails': '{n} fallos consecutivos',
'models.cloudPaused': 'Llamadas en la nube en pausa',
'models.formTitleAdd': 'Añadir modelo',
'models.formTitleEdit': 'Editar modelo',
'models.formClose': 'Cerrar',
'models.fName': 'Nombre',
'models.fNamePh': 'Nombra el modelo, p. ej. DeepSeek oficial',
'models.fApiType': 'Tipo de API',
'models.apiOpenai': 'Compatible con OpenAI',
'models.apiAnthropic': 'Anthropic',
'models.apiOther': 'Otro',
'models.apiTypeHelp': 'La fase 1 solo admite APIs compatibles con OpenAI; otros protocolos llegarán con los modelos de imagen / vídeo',
'models.fBaseUrl': 'URL base',
'models.baseUrlHelp': 'Incluye protocolo y puerto, p. ej. http://192.168.200.18:11434/v1',
'models.fModel': 'Nombre del modelo',
'models.modelHelp': 'Usa el ID de modelo que indica tu proveedor',
'models.fApiKey': 'Clave API',
'models.keyNoEcho': 'nunca se muestra',
'models.keyHelp': 'Se guarda solo en este servidor; la clave completa nunca aparece en la interfaz',
'models.keyKeepHint': 'Clave guardada: déjalo vacío para conservarla',
'models.fTimeout': 'Tiempo de espera',
'models.timeoutSec': '{n}s',
'models.testOk': '✓ Prueba superada · {ms}ms · {model} disponible',
'models.testFail': '✕ Prueba fallida · {reason}',
'models.needTest': 'Guardar se habilita tras superar la prueba',
'models.testBtn': 'Test connection',
'models.save': 'Guardar modelo',
'models.errName': 'Ponle nombre al modelo',
'models.errUrl': 'URL no válida: debe incluir protocolo y ruta, p. ej. https://api.deepseek.com/v1',
'models.errModel': 'Introduce el nombre del modelo de tu proveedor',
'models.errKey': 'Introduce la clave API',
'models.failTimeout': 'Tiempo de espera agotado ({sec}s sin respuesta): el servidor no llega a esta dirección; revisa dirección, puerto y cortafuegos',
'models.failAuth': 'Autenticación fallida (401): comprueba que la clave API sea correcta y no haya caducado; con agregadores, confirma que el modelo esté activado',
'models.failNotFound': 'Accesible pero modelo no encontrado (404): revisa cómo se escribe el nombre',
'models.failNotOpenai': 'Accesible pero no parece una API compatible con OpenAI: comprueba que la ruta termine en /v1',
'models.failConnect': 'El servidor no puede conectarse a esta dirección: revisa dirección y puerto',
'models.failHttp': 'Prueba fallida (HTTP {status})',
'models.delTitle': 'Eliminar modelo',
'models.delConfirmUsed': '{n} agentes usan este modelo; tras eliminarlo usarán el predeterminado. ¿Eliminar?',
'models.delConfirmFree': '¿Eliminar este modelo? No se puede deshacer.',
'models.delDefaultHint': 'Es el modelo predeterminado: elige otro predeterminado primero',
'models.agentsTitle': 'Modelos predeterminados de agentes',
'models.agentsHint': 'Los cambios aplican a sesiones nuevas · ajustes por agente en la página Agentes',
'models.agentDefault': 'Predeterminado',
'models.agentStory': 'Guion',
'models.agentStyle': 'Diseño visual',
'models.agentScript': 'Storyboards',
'models.agentAssets': 'Biblioteca de assets',
'models.agentVideo': 'Listas de planos',
'models.unavailable': '(no disponible)',
'models.noticeStrong': 'La conectividad se mide desde el servidor del workbench:',
'models.noticeBody': 'que una URL abra en tu navegador no significa que el servidor pueda acceder a ella; las pruebas de conexión y las peticiones las hace el servidor. Las claves API se guardan solo en el servidor y nunca se muestran.',
'models.saved': 'Modelo guardado',
'models.deleted': 'Modelo eliminado',
'models.assignSaved': 'Modelos de agentes actualizados',
'models.saveFailed': 'Error al guardar: {detail}',
'models.loading': 'Cargando…',
'models.loadFailed': 'No se pudieron cargar los ajustes',
'models.idleFormHint': 'Pulsa «Editar» en una tarjeta o «Añadir modelo» arriba',
// --- A shell + projects overview (HEL-608) ---
'shell.brand': 'Atelier de Cine',
'shell.brandHome': 'Volver al resumen de proyectos',
'shell.navAria': 'Navegación principal',
'shell.navProjects': 'Proyectos',
'shell.navWorkbench': 'Taller',
'shell.navImage': 'Generar imagen',
'shell.navVideo': 'Generar vídeo',
'shell.navTasks': 'Tareas',
'shell.navAgents': 'Agentes',
'shell.navConnections': 'Conexiones ComfyUI',
'shell.navModels': 'Modelos',
'shell.navSettings': 'Ajustes',
'shell.wip': 'En desarrollo',
'shell.wipHint': 'Esta página está en construcción y llegará más adelante',
'shell.comfyAt': 'ComfyUI · {host}',
'shell.comfyUnset': 'ComfyUI · sin configurar',
'shell.comfyManage': 'Configura la dirección de ComfyUI en Ajustes',
'shell.mobileNotice': 'Abre este banco de trabajo en un navegador de escritorio (mínimo 768 px); los móviles aún no se admiten.',
'home.title': 'Resumen de proyectos',
'home.subtitle': 'Gestiona tus proyectos: empieza con una idea o un guion terminado.',
'home.projectCount': '{n} proyectos · {m} en curso',
'home.startIdea': 'Empezar con una idea',
'home.importScript': 'Importar guion',
'home.entryIdeaTitle': 'Empezar con una idea',
'home.entryIdeaBody': 'Describe una idea; los agentes la llevan por historia, storyboard y clips paso a paso.',
'home.entryScriptTitle': 'Importar guion',
'home.entryScriptBody': '¿Ya tienes guion? Pégalo, crea el proyecto y el agente de guion lo dividirá en escenas ordenadas.',
'home.ideaPlaceholder': 'Un pequeño puerto lluvioso donde el farero descubre…',
'home.scriptField': 'Guion completo',
'home.scriptPlaceholder': 'Pega aquí el guion completo…',
'home.scriptHint': 'Al crearlo se abre la página de Agentes; el agente de guion convierte el texto en escenas ordenadas.',
'home.errTitle': 'Ponle un título al proyecto',
'home.errScript': 'Pega el guion completo',
'home.myProjects': 'Mis proyectos',
'home.myProjectsHint': 'Haz clic en un proyecto para continuar',
'home.emptyProjects': 'Aún no hay proyectos. Crea el primero con «Empezar con una idea» o «Importar guion».',
'home.noIdea': 'Sin descripción de la idea',
'home.statScenes': '{n} escenas',
'home.statCharacters': '{n} personajes',
'home.statAssets': 'recursos {ready}/{total}',
'home.statusDraft': 'Borrador',
'home.statusProgress': 'En curso',
'home.statusDone': 'Terminado',
'home.tasksTitle': 'Tareas',
'home.activeJobs': '{n} activas',
'home.emptyJobs': 'Aún no hay tareas de generación',
'home.emptyJobsSub': 'Las tareas iniciadas en un proyecto o en el taller aparecerán aquí.',
'home.tasksNote': 'La página independiente de tareas está en desarrollo; el historial completo vive por ahora en cada proyecto.',
'home.kindImage': 'imagen',
'home.kindVideo': 'vídeo',
'home.kindExport': 'película',
'home.jobDone': 'lista',
'home.jobRunning': 'en curso',
'home.jobQueued': 'en cola',
'home.jobFailed': 'fallida',
'home.jobRequeued': 'Tarea reencolada',
'home.jobRetryFailed': 'No se pudo reencolar la tarea',
'home.jobProject': 'Proyecto #{id}',
};
+154
View File
@@ -34,6 +34,8 @@ export const fr: Dict = {
'nav.projects': 'Projets',
'nav.buildScene': 'Composer la scène',
'nav.settings': 'Paramètres',
'nav.agents': 'Agents',
'nav.models': 'Modèles',
'nav.home': 'Accueil',
'nav.primary': 'Principal',
'nav.projectStages': 'Étapes du projet',
@@ -995,6 +997,12 @@ export const fr: Dict = {
'settings.removeLlmTitle': 'Retirer le LLM',
'settings.name': 'Nom',
'settings.active': 'Actif',
'settings.testLlm': 'Tester la connexion',
'settings.llmTestOk': 'Connexion réussie ({ms} ms)',
'settings.llmTestFail': 'Échec de connexion : {detail}',
'settings.llmTestAuth': 'Clé refusée ({detail})',
'settings.llmTestTimeout': 'Aucune réponse sous 15 s',
'settings.llmTestConnect': 'Serveur injoignable ({detail})',
'settings.agentModelsSection': 'Modèle agent',
'settings.agentModelsLead': "Modèle utilisé pour la rédaction de l'histoire et les tâches de l'agent.",
'settings.agentMaxStepsField': 'Étapes max.',
@@ -1128,4 +1136,150 @@ export const fr: Dict = {
'shot.errBlob': "Impossible de lire l'image capturée",
'shot.errRecorder': "Impossible de démarrer l'enregistreur",
'shot.errNoData': 'Aucune donnée de scène à exporter',
// Models settings page (spec-v2 §9)
'models.title': 'Modèles',
'models.subtitle': 'Ajoutez des LLM personnalisés pour vos agents · la phase 1 ne couvre que les LLM ; les modèles image / vidéo arriveront ensuite',
'models.statusCount': '{n} modèles · {m} disponibles',
'models.add': '+ Ajouter un modèle',
'models.tabLlm': 'Modèles de langage',
'models.tabImage': "Modèles d'image",
'models.tabVideo': 'Modèles vidéo',
'models.comingSoon': 'À venir',
'models.empty': 'Aucun modèle pour l’instant — cliquez sur « Ajouter un modèle » en haut à droite pour connecter votre premier LLM',
'models.typeLocal': 'Local',
'models.typeLan': 'LAN',
'models.typeCloud': 'Cloud',
'models.defaultBadge': 'Par défaut',
'models.setDefault': 'Définir par défaut',
'models.defaultSetToast': 'Modèle par défaut des agents défini',
'models.test': 'Tester la connexion',
'models.testing': 'Test en cours…',
'models.edit': 'Modifier',
'models.delete': 'Supprimer',
'models.statusUntested': 'Non testé',
'models.statusConnected': 'Connecté',
'models.statusFailed': 'Échec de connexion',
'models.latency': 'latence {ms}ms',
'models.agentsUsing': 'utilisé par {n} agents',
'models.lastTestAt': 'dernier test {time}',
'models.consecutiveFails': '{n} échecs consécutifs',
'models.cloudPaused': 'Appels cloud suspendus',
'models.formTitleAdd': 'Ajouter un modèle',
'models.formTitleEdit': 'Modifier le modèle',
'models.formClose': 'Fermer',
'models.fName': 'Nom',
'models.fNamePh': 'Nommez le modèle, ex. DeepSeek officiel',
'models.fApiType': 'Type d’API',
'models.apiOpenai': 'Compatible OpenAI',
'models.apiAnthropic': 'Anthropic',
'models.apiOther': 'Autre',
'models.apiTypeHelp': 'La phase 1 ne prend en charge que les API compatibles OpenAI ; les autres protocoles arriveront avec les modèles image / vidéo',
'models.fBaseUrl': 'URL de base',
'models.baseUrlHelp': 'Avec protocole et port, ex. http://192.168.200.18:11434/v1',
'models.fModel': 'Nom du modèle',
'models.modelHelp': 'Utilisez l’identifiant de modèle fourni par votre prestataire',
'models.fApiKey': 'Clé API',
'models.keyNoEcho': 'jamais affichée',
'models.keyHelp': 'Stockée uniquement sur ce serveur ; la clé complète n’apparaît jamais dans l’interface',
'models.keyKeepHint': 'Clé enregistrée — laissez vide pour la conserver',
'models.fTimeout': 'Délai d’attente',
'models.timeoutSec': '{n}s',
'models.testOk': '✓ Test réussi · {ms}ms · {model} disponible',
'models.testFail': '✕ Échec du test · {reason}',
'models.needTest': 'Enregistrement possible après un test réussi',
'models.testBtn': 'Test connection',
'models.save': 'Enregistrer le modèle',
'models.errName': 'Veuillez nommer le modèle',
'models.errUrl': 'URL invalide — protocole et chemin requis, ex. https://api.deepseek.com/v1',
'models.errModel': 'Saisissez le nom du modèle fourni par votre prestataire',
'models.errKey': 'Saisissez la clé API',
'models.failTimeout': 'Délai dépassé ({sec}s sans réponse) : le serveur n’atteint pas cette adresse — vérifiez adresse, port et pare-feu',
'models.failAuth': 'Échec d’authentification (401) : vérifiez que la clé API est correcte et non expirée ; avec les agrégateurs, confirmez que le modèle est activé',
'models.failNotFound': 'Joignable mais modèle introuvable (404) : vérifiez l’orthographe du nom',
'models.failNotOpenai': 'Joignable mais non reconnue comme API compatible OpenAI — le chemin doit se terminer par /v1',
'models.failConnect': 'Le serveur ne peut pas se connecter à cette adresse — vérifiez adresse et port',
'models.failHttp': 'Test failed (HTTP {status})',
'models.delTitle': 'Supprimer le modèle',
'models.delConfirmUsed': '{n} agents utilisent ce modèle ; après suppression ils reviendront au modèle par défaut. Supprimer ?',
'models.delConfirmFree': 'Supprimer ce modèle ? Action irréversible.',
'models.delDefaultHint': 'Ce modèle est celui par défaut — choisissez d’abord un autre défaut',
'models.agentsTitle': 'Modèles par défaut des agents',
'models.agentsHint': 'Appliqué aux nouvelles sessions · réglage par agent sur la page Agents',
'models.agentDefault': 'Par défaut',
'models.agentStory': 'Scénario',
'models.agentStyle': 'Direction visuelle',
'models.agentScript': 'Storyboards',
'models.agentAssets': 'Bibliothèque d’assets',
'models.agentVideo': 'Plans de tournage',
'models.unavailable': '(indisponible)',
'models.noticeStrong': 'La connectivité est mesurée depuis le serveur du workbench :',
'models.noticeBody': 'une URL qui s’ouvre dans votre navigateur n’est pas forcément accessible au serveur ; les tests de connexion et les requêtes sont faits par le serveur. Les clés API restent sur le serveur et ne sont jamais affichées.',
'models.saved': 'Modèle enregistré',
'models.deleted': 'Modèle supprimé',
'models.assignSaved': 'Modèles des agents mis à jour',
'models.saveFailed': 'Échec de l’enregistrement : {detail}',
'models.loading': 'Chargement…',
'models.loadFailed': 'Impossible de charger les paramètres',
'models.idleFormHint': 'Cliquez « Modifier » sur une carte ou « Ajouter un modèle » ci-dessus',
// --- A shell + projects overview (HEL-608) ---
'shell.brand': 'Atelier Cinéma',
'shell.brandHome': 'Retour à l\'aperçu des projets',
'shell.navAria': 'Navigation principale',
'shell.navProjects': 'Projets',
'shell.navWorkbench': 'Atelier',
'shell.navImage': 'Génération d\'image',
'shell.navVideo': 'Génération vidéo',
'shell.navTasks': 'Tâches',
'shell.navAgents': 'Agents',
'shell.navConnections': 'Connexions ComfyUI',
'shell.navModels': 'Modèles',
'shell.navSettings': 'Réglages',
'shell.wip': 'En développement',
'shell.wipHint': 'Cette page est en construction et arrivera plus tard',
'shell.comfyAt': 'ComfyUI · {host}',
'shell.comfyUnset': 'ComfyUI · non configuré',
'shell.comfyManage': 'Configurez l\'adresse ComfyUI dans les Réglages',
'shell.mobileNotice': 'Ouvrez cet atelier dans un navigateur de bureau (largeur minimum 768 px) ; les téléphones ne sont pas encore pris en charge.',
'home.title': 'Aperçu des projets',
'home.subtitle': 'Gérez vos projets — commencez avec une idée ou un scénario prêt.',
'home.projectCount': '{n} projets · {m} en cours',
'home.startIdea': 'Commencer avec une idée',
'home.importScript': 'Importer un scénario',
'home.entryIdeaTitle': 'Commencer avec une idée',
'home.entryIdeaBody': 'Décrivez une idée ; les agents la mènent étape par étape à travers l\'histoire, le storyboard et les plans.',
'home.entryScriptTitle': 'Importer un scénario',
'home.entryScriptBody': 'Vous avez déjà un scénario ? Collez-le, créez le projet et l\'agent scénario le découpe en scènes ordonnées.',
'home.ideaPlaceholder': 'Un petit port pluvieux où le gardien de phare découvre…',
'home.scriptField': 'Scénario complet',
'home.scriptPlaceholder': 'Collez ici le scénario complet…',
'home.scriptHint': 'Après création, la page Agents s\'ouvre et l\'agent scénario transforme le texte en scènes ordonnées.',
'home.errTitle': 'Donnez un titre au projet',
'home.errScript': 'Collez le scénario complet',
'home.myProjects': 'Mes projets',
'home.myProjectsHint': 'Cliquez sur un projet pour continuer',
'home.emptyProjects': 'Aucun projet pour le moment. Créez le premier avec « Commencer avec une idée » ou « Importer un scénario ».',
'home.noIdea': 'Pas encore de description',
'home.statScenes': '{n} scènes',
'home.statCharacters': '{n} personnages',
'home.statAssets': 'ressources {ready}/{total}',
'home.statusDraft': 'Brouillon',
'home.statusProgress': 'En cours',
'home.statusDone': 'Terminé',
'home.tasksTitle': 'Tâches',
'home.activeJobs': '{n} actives',
'home.emptyJobs': 'Aucune tâche de génération',
'home.emptyJobsSub': 'Les tâches lancées depuis un projet ou l\'atelier s\'afficheront ici.',
'home.tasksNote': 'La page Tâches autonome est en développement ; l\'historique complet reste pour l\'instant dans chaque projet.',
'home.kindImage': 'image',
'home.kindVideo': 'vidéo',
'home.kindExport': 'film',
'home.jobDone': 'terminée',
'home.jobRunning': 'en cours',
'home.jobQueued': 'en attente',
'home.jobFailed': 'échouée',
'home.jobRequeued': 'Tâche remise en file',
'home.jobRetryFailed': 'Impossible de remettre la tâche en file',
'home.jobProject': 'Projet #{id}',
};
+154
View File
@@ -34,6 +34,8 @@ export const ja: Dict = {
'nav.projects': 'プロジェクト',
'nav.buildScene': 'シーン構築',
'nav.settings': '設定',
'nav.agents': 'エージェント',
'nav.models': 'モデル設定',
'nav.home': 'ホーム',
'nav.primary': 'メイン',
'nav.projectStages': 'プロジェクトの段階',
@@ -995,6 +997,12 @@ export const ja: Dict = {
'settings.removeLlmTitle': 'LLM を削除',
'settings.name': '名前',
'settings.active': '有効',
'settings.testLlm': '接続テスト',
'settings.llmTestOk': '接続成功({ms} ms)',
'settings.llmTestFail': '接続失敗:{detail}',
'settings.llmTestAuth': 'キーが拒否されました({detail})',
'settings.llmTestTimeout': '15 秒以内に応答なし',
'settings.llmTestConnect': 'サーバーに接続できません({detail})',
'settings.agentModelsSection': 'エージェントモデル',
'settings.agentModelsLead': 'ストーリーの下書きやエージェントタスクに使用するモデル。',
'settings.agentMaxStepsField': '最大ステップ数',
@@ -1128,4 +1136,150 @@ export const ja: Dict = {
'shot.errBlob': 'キャプチャしたフレームを読み取れませんでした',
'shot.errRecorder': 'レコーダーを開始できませんでした',
'shot.errNoData': '書き出すシーンデータがありません',
// Models settings page (spec-v2 §9)
'models.title': 'モデル設定',
'models.subtitle': 'エージェントが使うカスタム LLM を追加 · 第一段階は LLM のみ、画像 / 動画モデルは後日',
'models.statusCount': 'モデル {n} 件 · 利用可能 {m} 件',
'models.add': '+ モデルを追加',
'models.tabLlm': '大規模言語モデル',
'models.tabImage': '画像モデル',
'models.tabVideo': '動画モデル',
'models.comingSoon': '近日公開',
'models.empty': 'モデルが未設定です。右上の「モデルを追加」から最初の LLM を登録してください',
'models.typeLocal': 'ローカル',
'models.typeLan': 'LAN',
'models.typeCloud': 'クラウド',
'models.defaultBadge': 'エージェント既定',
'models.setDefault': '既定にする',
'models.defaultSetToast': 'エージェント既定モデルを設定しました',
'models.test': '接続テスト',
'models.testing': 'テスト中…',
'models.edit': '編集',
'models.delete': '削除',
'models.statusUntested': '未テスト',
'models.statusConnected': '接続済み',
'models.statusFailed': '接続失敗',
'models.latency': '遅延 {ms}ms',
'models.agentsUsing': '{n} 個のエージェントが使用',
'models.lastTestAt': '前回テスト {time}',
'models.consecutiveFails': '連続失敗 {n} 回',
'models.cloudPaused': 'クラウド呼び出しを一時停止',
'models.formTitleAdd': 'モデルを追加',
'models.formTitleEdit': 'モデルを編集',
'models.formClose': '閉じる',
'models.fName': '名前',
'models.fNamePh': 'モデルの名前(例:DeepSeek 公式)',
'models.fApiType': 'API タイプ',
'models.apiOpenai': 'OpenAI 互換',
'models.apiAnthropic': 'Anthropic',
'models.apiOther': 'その他',
'models.apiTypeHelp': '第一段階は OpenAI 互換 API のみ対応。他のプロトコルは画像 / 動画モデルと同時に提供予定',
'models.fBaseUrl': 'API アドレス',
'models.baseUrlHelp': 'プロトコルとポートを含めてください(例:http://192.168.200.18:11434/v1)',
'models.fModel': 'モデル名',
'models.modelHelp': 'プロバイダ提供のモデル ID を指定してください',
'models.fApiKey': 'API キー',
'models.keyNoEcho': '表示されません',
'models.keyHelp': 'このサーバーにのみ保存され、完全なキーが画面に表示されることはありません',
'models.keyKeepHint': 'キー保存済み — 空欄のままなら変更されません',
'models.fTimeout': 'タイムアウト',
'models.timeoutSec': '{n} 秒',
'models.testOk': '✓ テスト成功 · {ms}ms · {model} 利用可能',
'models.testFail': '✕ テスト失敗 · {reason}',
'models.needTest': 'テスト成功後に保存できます',
'models.testBtn': '接続テスト',
'models.save': 'モデルを保存',
'models.errName': 'モデルに名前を付けてください',
'models.errUrl': 'アドレス形式が不正です。プロトコルとパスを含めてください(例:https://api.deepseek.com/v1)',
'models.errModel': 'プロバイダ提供のモデル名を入力してください',
'models.errKey': 'API キーを入力してください',
'models.failTimeout': 'タイムアウト({sec} 秒無応答):サーバーからこのアドレスに届きません。アドレス・ポート・ファイアウォールを確認してください',
'models.failAuth': '認証失敗(401):API キーが正しいか・期限切れでないか確認してください。集約サービスの場合はモデル権限もご確認ください',
'models.failNotFound': '接続はできるがモデルが見つかりません(404):モデル名の綴りを確認してください',
'models.failNotOpenai': 'アドレスにはアクセスできるものの OpenAI 互換 API と識別できません。パスが /v1 で終わるか確認してください',
'models.failConnect': 'サーバーからこのアドレスに接続できません。アドレスとポートを確認してください',
'models.failHttp': 'Test failed (HTTP {status})',
'models.delTitle': 'モデルを削除',
'models.delConfirmUsed': '{n} 個のエージェントが使用中です。削除後は「エージェント既定」に切り替わります。削除しますか?',
'models.delConfirmFree': 'このモデルを削除しますか?取り消せません。',
'models.delDefaultHint': 'このモデルは「エージェント既定」です。先に別の既定モデルを指定してください',
'models.agentsTitle': 'エージェント既定モデル',
'models.agentsHint': '新しいセッションから適用 · 個別設定はエージェントページで',
'models.agentDefault': 'エージェント既定',
'models.agentStory': '脚本制作',
'models.agentStyle': 'ビジュアルデザイン',
'models.agentScript': '絵コンテ',
'models.agentAssets': '素材アセット',
'models.agentVideo': 'ショットリスト',
'models.unavailable': '(利用不可)',
'models.noticeStrong': '接続性はワークベンチのサーバー基準です:',
'models.noticeBody': 'ブラウザで開けるアドレスでも、ワークベンチのサーバーからアクセスできるとは限りません。接続テストと対話リクエストはサーバーが行います。API キーはサーバーにのみ保存され、画面に表示されることはありません。',
'models.saved': 'モデルを保存しました',
'models.deleted': 'モデルを削除しました',
'models.assignSaved': 'エージェントのモデルを更新しました',
'models.saveFailed': '保存に失敗しました:{detail}',
'models.loading': '読み込み中…',
'models.loadFailed': '設定の読み込みに失敗しました',
'models.idleFormHint': 'カードの「編集」を選ぶか、上の「モデルを追加」をクリックしてください',
// --- A shell + projects overview (HEL-608) ---
'shell.brand': '映画工房',
'shell.brandHome': 'プロジェクト概要へ戻る',
'shell.navAria': 'メインナビゲーション',
'shell.navProjects': 'プロジェクト',
'shell.navWorkbench': '制作ワークベンチ',
'shell.navImage': '画像生成',
'shell.navVideo': '動画生成',
'shell.navTasks': '生成タスク',
'shell.navAgents': 'エージェント',
'shell.navConnections': 'ComfyUI 接続',
'shell.navModels': 'モデル設定',
'shell.navSettings': '設定',
'shell.wip': '開発中',
'shell.wipHint': 'このページは準備中です。後ほど公開されます',
'shell.comfyAt': 'ComfyUI · {host}',
'shell.comfyUnset': 'ComfyUI · 未設定',
'shell.comfyManage': '「設定」で ComfyUI のアドレスを設定できます',
'shell.mobileNotice': 'このワークベンチはデスクトップブラウザ(幅 768px 以上)で開いてください。スマートフォンには未対応です。',
'home.title': 'プロジェクト概要',
'home.subtitle': '創作プロジェクトを管理 — アイデアでも完成台本でも始められます。',
'home.projectCount': 'プロジェクト {n} 件 · 進行中 {m} 件',
'home.startIdea': 'アイデアから始める',
'home.importScript': '台本を取り込む',
'home.entryIdeaTitle': 'アイデアから始める',
'home.entryIdeaBody': 'アイデアを書くと、エージェントが物語・絵コンテ・クリップへ順を追って仕上げます。',
'home.entryScriptTitle': '台本を取り込む',
'home.entryScriptBody': '完成した台本があれば貼り付けてプロジェクトを作成。台本エージェントが順序立ったシーンに整理します。',
'home.ideaPlaceholder': '雨の夜の小さな港で、灯台守が見つけたものは……',
'home.scriptField': '台本全文',
'home.scriptPlaceholder': '台本の全文をここに貼り付けてください……',
'home.scriptHint': '作成後「エージェント」ページが開き、台本エージェントが順序立ったシーンに整理します。',
'home.errTitle': 'プロジェクトにタイトルを付けてください',
'home.errScript': '台本の全文を貼り付けてください',
'home.myProjects': 'マイプロジェクト',
'home.myProjectsHint': 'プロジェクトをクリックして作業を続ける',
'home.emptyProjects': 'まだプロジェクトがありません。上の「アイデアから始める」か「台本を取り込む」で最初のプロジェクトを作成しましょう。',
'home.noIdea': 'アイデアの説明はまだありません',
'home.statScenes': 'シーン {n}',
'home.statCharacters': '登場人物 {n}',
'home.statAssets': '素材 {ready}/{total}',
'home.statusDraft': '下書き',
'home.statusProgress': '進行中',
'home.statusDone': '完了',
'home.tasksTitle': '生成タスク',
'home.activeJobs': '{n} 件実行中',
'home.emptyJobs': '生成タスクはまだありません',
'home.emptyJobsSub': 'プロジェクトやワークベンチから生成を開始すると、ここに表示されます。',
'home.tasksNote': '独立した「生成タスク」ページは開発中。現在は各プロジェクト内で完全な履歴を確認できます。',
'home.kindImage': '画像',
'home.kindVideo': '動画',
'home.kindExport': '映画',
'home.jobDone': '完了',
'home.jobRunning': '実行中',
'home.jobQueued': '待機中',
'home.jobFailed': '失敗',
'home.jobRequeued': 'タスクを再び待機列に入れました',
'home.jobRetryFailed': 'タスクを再待機できませんでした',
'home.jobProject': 'プロジェクト #{id}',
};
+154
View File
@@ -34,6 +34,8 @@ export const ko: Dict = {
'nav.projects': '프로젝트',
'nav.buildScene': '장면 구성',
'nav.settings': '설정',
'nav.agents': '에이전트',
'nav.models': '모델 설정',
'nav.home': '홈',
'nav.primary': '기본',
'nav.projectStages': '프로젝트 단계',
@@ -995,6 +997,12 @@ export const ko: Dict = {
'settings.removeLlmTitle': 'LLM 제거',
'settings.name': '이름',
'settings.active': '활성',
'settings.testLlm': '연결 테스트',
'settings.llmTestOk': '연결 성공 ({ms}ms)',
'settings.llmTestFail': '연결 실패: {detail}',
'settings.llmTestAuth': '키가 거부됨 ({detail})',
'settings.llmTestTimeout': '15초 내 응답 없음',
'settings.llmTestConnect': '서버에 연결할 수 없음 ({detail})',
'settings.agentModelsSection': '에이전트 모델',
'settings.agentModelsLead': '스토리 초안 작성과 에이전트 작업에 사용하는 모델입니다.',
'settings.agentMaxStepsField': '최대 단계',
@@ -1128,4 +1136,150 @@ export const ko: Dict = {
'shot.errBlob': '캡처한 프레임을 읽지 못했습니다',
'shot.errRecorder': '녹화를 시작하지 못했습니다',
'shot.errNoData': '내보낼 장면 데이터가 없습니다',
// Models settings page (spec-v2 §9)
'models.title': '모델 설정',
'models.subtitle': '에이전트가 사용할 사용자 지정 LLM을 추가합니다 · 1단계는 LLM만 지원, 이미지 / 동영상 모델은 추후 제공',
'models.statusCount': '모델 {n}개 · 사용 가능 {m}개',
'models.add': '+ 모델 추가',
'models.tabLlm': '대규모 언어 모델',
'models.tabImage': '이미지 모델',
'models.tabVideo': '동영상 모델',
'models.comingSoon': '추후 제공',
'models.empty': '아직 모델이 없습니다. 오른쪽 위 «모델 추가»를 눌러 첫 LLM을 연결하세요',
'models.typeLocal': '로컬',
'models.typeLan': 'LAN',
'models.typeCloud': '클라우드',
'models.defaultBadge': '에이전트 기본',
'models.setDefault': '기본으로 설정',
'models.defaultSetToast': '에이전트 기본 모델로 설정했습니다',
'models.test': '연결 테스트',
'models.testing': '테스트 중…',
'models.edit': '편집',
'models.delete': '삭제',
'models.statusUntested': '미테스트',
'models.statusConnected': '연결됨',
'models.statusFailed': '연결 실패',
'models.latency': '지연 {ms}ms',
'models.agentsUsing': '{n}개 에이전트 사용 중',
'models.lastTestAt': '마지막 테스트 {time}',
'models.consecutiveFails': '{n}회 연속 실패',
'models.cloudPaused': '클라우드 호출 일시 중지',
'models.formTitleAdd': '모델 추가',
'models.formTitleEdit': '모델 편집',
'models.formClose': '닫기',
'models.fName': '이름',
'models.fNamePh': '모델 이름, 예: DeepSeek 공식',
'models.fApiType': 'API 유형',
'models.apiOpenai': 'OpenAI 호환',
'models.apiAnthropic': 'Anthropic',
'models.apiOther': '기타',
'models.apiTypeHelp': '1단계는 OpenAI 호환 API만 지원하며, 다른 프로토콜은 이미지 / 동영상 모델과 함께 제공됩니다',
'models.fBaseUrl': 'API 주소',
'models.baseUrlHelp': '프로토콜과 포트를 포함하세요, 예: http://192.168.200.18:11434/v1',
'models.fModel': '모델 이름',
'models.modelHelp': '공급자가 제공하는 모델 ID를 사용하세요',
'models.fApiKey': 'API 키',
'models.keyNoEcho': '표시되지 않음',
'models.keyHelp': '이 서버에만 저장되며 전체 키는 화면에 절대 표시되지 않습니다',
'models.keyKeepHint': '키 저장됨 — 비워 두면 유지됩니다',
'models.fTimeout': '시간 제한',
'models.timeoutSec': '{n}초',
'models.testOk': '✓ 테스트 통과 · {ms}ms · {model} 사용 가능',
'models.testFail': '✕ 테스트 실패 · {reason}',
'models.needTest': '테스트 통과 후 저장할 수 있습니다',
'models.testBtn': '연결 테스트',
'models.save': '모델 저장',
'models.errName': '모델 이름을 입력하세요',
'models.errUrl': '주소 형식이 올바르지 않습니다. 프로토콜과 경로를 포함하세요, 예: https://api.deepseek.com/v1',
'models.errModel': '공급자가 제공하는 모델 이름을 입력하세요',
'models.errKey': 'API 키를 입력하세요',
'models.failTimeout': '시간 초과({sec}초 무응답): 서버가 이 주소에 접근할 수 없습니다. 주소·포트·방화벽을 확인하세요',
'models.failAuth': '인증 실패(401): API 키가 올바르고 만료되지 않았는지 확인하세요. 통합 서비스라면 모델 권한도 확인하세요',
'models.failNotFound': '접속은 되지만 모델을 찾을 수 없음(404): 모델 이름 철자를 확인하세요',
'models.failNotOpenai': '주소에 접근할 수 있으나 OpenAI 호환 API로 식별되지 않습니다. 경로가 /v1로 끝나는지 확인하세요',
'models.failConnect': '서버가 이 주소에 연결할 수 없습니다. 주소와 포트를 확인하세요',
'models.failHttp': 'Test failed (HTTP {status})',
'models.delTitle': '모델 삭제',
'models.delConfirmUsed': '{n}개 에이전트가 이 모델을 사용 중입니다. 삭제 후에는 «에이전트 기본»으로 전환됩니다. 삭제할까요?',
'models.delConfirmFree': '이 모델을 삭제할까요? 되돌릴 수 없습니다.',
'models.delDefaultHint': '이 모델은 «에이전트 기본»입니다. 먼저 다른 기본 모델을 지정하세요',
'models.agentsTitle': '에이전트 기본 모델',
'models.agentsHint': '새 세션부터 적용 · 에이전트별 설정은 에이전트 페이지에서',
'models.agentDefault': '에이전트 기본',
'models.agentStory': '시나리오',
'models.agentStyle': '비주얼 디자인',
'models.agentScript': '스토리보드',
'models.agentAssets': '에셋 라이브러리',
'models.agentVideo': '숏리스트',
'models.unavailable': '(사용 불가)',
'models.noticeStrong': '연결성은 워크벤치 서버 기준입니다:',
'models.noticeBody': '브라우저에서 열리는 주소라도 워크벤치 서버가 접근 가능한 것은 아닙니다. 연결 테스트와 대화 요청은 서버가 수행합니다. API 키는 서버에만 저장되며 화면에 표시되지 않습니다.',
'models.saved': '모델을 저장했습니다',
'models.deleted': '모델을 삭제했습니다',
'models.assignSaved': '에이전트 모델을 업데이트했습니다',
'models.saveFailed': '저장 실패: {detail}',
'models.loading': '불러오는 중…',
'models.loadFailed': '설정을 불러오지 못했습니다',
'models.idleFormHint': '카드의 «편집»을 누르거나 위의 «모델 추가»를 클릭하세요',
// --- A shell + projects overview (HEL-608) ---
'shell.brand': '영화 공작소',
'shell.brandHome': '프로젝트 개요로 돌아가기',
'shell.navAria': '주요 탐색',
'shell.navProjects': '프로젝트',
'shell.navWorkbench': '창작 워크벤치',
'shell.navImage': '이미지 생성',
'shell.navVideo': '영상 생성',
'shell.navTasks': '생성 작업',
'shell.navAgents': '에이전트',
'shell.navConnections': 'ComfyUI 연결',
'shell.navModels': '모델 설정',
'shell.navSettings': '설정',
'shell.wip': '개발 중',
'shell.wipHint': '이 페이지는 준비 중이며 곧 열립니다',
'shell.comfyAt': 'ComfyUI · {host}',
'shell.comfyUnset': 'ComfyUI · 미설정',
'shell.comfyManage': '「설정」에서 ComfyUI 주소를 설정하세요',
'shell.mobileNotice': '이 워크벤치는 데스크톱 브라우저(폭 768px 이상)에서 열어 주세요. 휴대폰은 아직 지원되지 않습니다.',
'home.title': '프로젝트 개요',
'home.subtitle': '창작 프로젝트를 관리하세요 — 아이디어나 완성된 대본으로 시작할 수 있습니다.',
'home.projectCount': '프로젝트 {n}개 · 진행 중 {m}개',
'home.startIdea': '아이디어로 시작',
'home.importScript': '대본 가져오기',
'home.entryIdeaTitle': '아이디어로 시작',
'home.entryIdeaBody': '아이디어를 적으면 에이전트가 이야기·스토리보드·클립을 단계별로 완성합니다.',
'home.entryScriptTitle': '대본 가져오기',
'home.entryScriptBody': '이미 대본이 있나요? 붙여넣어 프로젝트를 만들면 대본 에이전트가 순서 있는 장면으로 정리합니다.',
'home.ideaPlaceholder': '비 내리는 밤의 작은 항구, 등대지기가 발견한 것은……',
'home.scriptField': '대본 전문',
'home.scriptPlaceholder': '대본 전문을 여기에 붙여넣으세요……',
'home.scriptHint': '만들면 「에이전트」 페이지가 열리고 대본 에이전트가 순서 있는 장면으로 정리합니다.',
'home.errTitle': '프로젝트 제목을 입력하세요',
'home.errScript': '대본 전문을 붙여넣으세요',
'home.myProjects': '내 프로젝트',
'home.myProjectsHint': '프로젝트를 클릭해 이어서 작업',
'home.emptyProjects': '아직 프로젝트가 없습니다. 위의 「아이디어로 시작」 또는 「대본 가져오기」로 첫 프로젝트를 만들어 보세요.',
'home.noIdea': '아이디어 설명이 아직 없습니다',
'home.statScenes': '장면 {n}',
'home.statCharacters': '등장인물 {n}',
'home.statAssets': '소재 {ready}/{total}',
'home.statusDraft': '초안',
'home.statusProgress': '진행 중',
'home.statusDone': '완료',
'home.tasksTitle': '생성 작업',
'home.activeJobs': '{n}개 실행 중',
'home.emptyJobs': '아직 생성 작업이 없습니다',
'home.emptyJobsSub': '프로젝트나 워크벤치에서 생성을 시작하면 여기에 표시됩니다.',
'home.tasksNote': '독립적인 「생성 작업」 페이지는 개발 중입니다. 현재는 각 프로젝트에서 전체 기록을 볼 수 있습니다.',
'home.kindImage': '이미지',
'home.kindVideo': '영상',
'home.kindExport': '필름',
'home.jobDone': '완료',
'home.jobRunning': '실행 중',
'home.jobQueued': '대기 중',
'home.jobFailed': '실패',
'home.jobRequeued': '작업이 다시 대기열에 추가되었습니다',
'home.jobRetryFailed': '작업을 다시 대기열에 넣지 못했습니다',
'home.jobProject': '프로젝트 #{id}',
};
+154
View File
@@ -34,6 +34,8 @@ export const zh: Dict = {
'nav.projects': '项目',
'nav.buildScene': '搭建场景',
'nav.settings': '设置',
'nav.agents': '智能体',
'nav.models': '模型设置',
'nav.home': '首页',
'nav.primary': '主导航',
'nav.projectStages': '项目阶段',
@@ -995,6 +997,12 @@ export const zh: Dict = {
'settings.removeLlmTitle': '移除 LLM',
'settings.name': '名称',
'settings.active': '激活',
'settings.testLlm': '测试连接',
'settings.llmTestOk': '连接成功({ms} 毫秒)',
'settings.llmTestFail': '连接失败:{detail}',
'settings.llmTestAuth': '密钥被拒绝({detail})',
'settings.llmTestTimeout': '15 秒内无响应',
'settings.llmTestConnect': '无法连接服务器({detail})',
'settings.agentModelsSection': '智能体模型',
'settings.agentModelsLead': '用于故事起草和智能体任务的模型。',
'settings.agentMaxStepsField': '最大步数',
@@ -1128,4 +1136,150 @@ export const zh: Dict = {
'shot.errBlob': '无法读取截取的帧',
'shot.errRecorder': '无法启动录制器',
'shot.errNoData': '没有可导出的场景数据',
// Models settings page (spec-v2 §9)
'models.title': '模型设置',
'models.subtitle': '添加自定义大语言模型(LLM),供智能体选用 · 第一阶段仅开放 LLM,图片 / 视频模型后续接入',
'models.statusCount': '{n} 个模型 · {m} 个可用',
'models.add': '+ 添加模型',
'models.tabLlm': '大语言模型',
'models.tabImage': '图片模型',
'models.tabVideo': '视频模型',
'models.comingSoon': '后续开放',
'models.empty': '还没有配置模型,点右上角「添加模型」接入第一个大语言模型',
'models.typeLocal': '本机',
'models.typeLan': '局域网',
'models.typeCloud': '云端',
'models.defaultBadge': '智能体默认',
'models.setDefault': '设为默认',
'models.defaultSetToast': '已设为智能体默认模型',
'models.test': '测试连接',
'models.testing': '测试中…',
'models.edit': '编辑',
'models.delete': '删除',
'models.statusUntested': '未测试',
'models.statusConnected': '已连接',
'models.statusFailed': '连接失败',
'models.latency': '延迟 {ms}ms',
'models.agentsUsing': '{n} 个智能体选用',
'models.lastTestAt': '上次测试 {time}',
'models.consecutiveFails': '已连续失败 {n} 次',
'models.cloudPaused': '云端调用已暂停',
'models.formTitleAdd': '添加模型',
'models.formTitleEdit': '编辑模型',
'models.formClose': '关闭',
'models.fName': '名称',
'models.fNamePh': '给模型起个名字,如 DeepSeek 官方',
'models.fApiType': '接口类型',
'models.apiOpenai': 'OpenAI 兼容',
'models.apiAnthropic': 'Anthropic',
'models.apiOther': '其他协议',
'models.apiTypeHelp': '第一阶段仅支持 OpenAI 兼容接口,其余协议随图片 / 视频模型一同开放',
'models.fBaseUrl': '接口地址',
'models.baseUrlHelp': '需含协议与端口,如 http://192.168.200.18:11434/v1',
'models.fModel': '模型名称',
'models.modelHelp': '以服务商提供的模型 ID 为准',
'models.fApiKey': 'API 密钥',
'models.keyNoEcho': '密钥不回显',
'models.keyHelp': '仅保存在本机服务器,页面永不显示完整密钥',
'models.keyKeepHint': '已保存密钥,留空表示不修改',
'models.fTimeout': '超时时间',
'models.timeoutSec': '{n} 秒',
'models.testOk': '✓ 测试通过 · 延迟 {ms}ms · {model} 可用',
'models.testFail': '✕ 测试失败 · {reason}',
'models.needTest': '未测试通过前无法保存',
'models.testBtn': '测试连接',
'models.save': '保存模型',
'models.errName': '请给模型起个名字',
'models.errUrl': '地址格式不正确,需含协议与路径,示例:https://api.deepseek.com/v1',
'models.errModel': '请填写模型名称,以服务商提供的模型 ID 为准',
'models.errKey': '请填写 API 密钥',
'models.failTimeout': '连接超时({sec} 秒无响应):服务器无法访问该地址,请检查地址、端口与防火墙',
'models.failAuth': '鉴权失败(401):请检查 API 密钥是否正确或已过期;使用聚合服务时,请确认账号已开通该模型权限',
'models.failNotFound': '连接正常但未找到该模型(404):请核对模型名称拼写',
'models.failNotOpenai': '地址可访问但未识别为 OpenAI 兼容接口,请确认路径是否以 /v1 结尾',
'models.failConnect': '服务器无法连接到该地址,请检查地址与端口',
'models.failHttp': '测试失败(HTTP {status})',
'models.delTitle': '删除模型',
'models.delConfirmUsed': '该模型正被 {n} 个智能体使用,删除后这些智能体将改用「智能体默认」。确定删除?',
'models.delConfirmFree': '确定删除该模型?删除后不可恢复。',
'models.delDefaultHint': '该模型是「智能体默认」,请先指定其他默认模型',
'models.agentsTitle': '智能体默认模型',
'models.agentsHint': '更改后新会话立即生效 · 也可在「智能体」页单独调整',
'models.agentDefault': '智能体默认',
'models.agentStory': '剧本创作',
'models.agentStyle': '视觉设计',
'models.agentScript': '分镜设计',
'models.agentAssets': '素材资产',
'models.agentVideo': '镜头脚本',
'models.unavailable': '(不可用)',
'models.noticeStrong': '连通性以工作台服务器为准:',
'models.noticeBody': '浏览器能打开某个地址,不代表运行工作台的服务器也能访问;连接测试与对话请求均由服务器发起。API 密钥仅保存在服务器本地,任何页面不回显。',
'models.saved': '模型已保存',
'models.deleted': '模型已删除',
'models.assignSaved': '智能体模型已更新',
'models.saveFailed': '保存失败:{detail}',
'models.loading': '加载中…',
'models.loadFailed': '设置加载失败',
'models.idleFormHint': '从左侧选择「编辑」,或点上方「添加模型」新增配置',
// --- A shell + projects overview (HEL-608) ---
'shell.brand': '影工坊',
'shell.brandHome': '返回项目总览',
'shell.navAria': '主导航',
'shell.navProjects': '项目',
'shell.navWorkbench': '创作工作台',
'shell.navImage': '生图',
'shell.navVideo': '生视频',
'shell.navTasks': '生成任务',
'shell.navAgents': '智能体',
'shell.navConnections': 'ComfyUI 连接',
'shell.navModels': '模型设置',
'shell.navSettings': '设置',
'shell.wip': '开发中',
'shell.wipHint': '该页面正在开发中,稍后开放',
'shell.comfyAt': 'ComfyUI · {host}',
'shell.comfyUnset': 'ComfyUI · 未配置',
'shell.comfyManage': '在「设置」中配置 ComfyUI 地址',
'shell.mobileNotice': '请用桌面浏览器(宽 768px 以上)打开影工坊,手机端暂不适配。',
'home.title': '项目总览',
'home.subtitle': '管理创作项目,从一个创意或一份现成剧本开始。',
'home.projectCount': '{n} 个项目 · {m} 个进行中',
'home.startIdea': '从创意开始',
'home.importScript': '导入剧本',
'home.entryIdeaTitle': '从创意开始',
'home.entryIdeaBody': '填一个想法,交给智能体逐步完成故事、分镜与成片。',
'home.entryScriptTitle': '导入剧本',
'home.entryScriptBody': '已有现成剧本?粘贴进来创建项目,交给剧本智能体整理为有序场景。',
'home.ideaPlaceholder': '一个雨夜的小港,灯塔看守人发现了……',
'home.scriptField': '剧本全文',
'home.scriptPlaceholder': '把完整剧本粘贴到这里……',
'home.scriptHint': '创建后会打开「智能体」,由剧本智能体把剧本整理成有序场景。',
'home.errTitle': '请给项目起个标题',
'home.errScript': '请粘贴剧本全文',
'home.myProjects': '我的项目',
'home.myProjectsHint': '点击项目继续创作',
'home.emptyProjects': '还没有项目。从上方「从创意开始」或「导入剧本」创建第一个项目。',
'home.noIdea': '暂无创意描述',
'home.statScenes': '场景 {n}',
'home.statCharacters': '角色 {n}',
'home.statAssets': '素材 {ready}/{total}',
'home.statusDraft': '待开始',
'home.statusProgress': '进行中',
'home.statusDone': '已完成',
'home.tasksTitle': '生成任务',
'home.activeJobs': '{n} 进行中',
'home.emptyJobs': '还没有生成任务',
'home.emptyJobsSub': '进入项目或创作工作台发起生成后,任务会显示在这里。',
'home.tasksNote': '独立「生成任务」页开发中;当前可在各项目内查看完整任务。',
'home.kindImage': '图片',
'home.kindVideo': '视频',
'home.kindExport': '成片',
'home.jobDone': '完成',
'home.jobRunning': '进行中',
'home.jobQueued': '排队',
'home.jobFailed': '失败',
'home.jobRequeued': '任务已重新排队',
'home.jobRetryFailed': '重新排队失败',
'home.jobProject': '项目 #{id}',
};
+31
View File
@@ -0,0 +1,31 @@
/**
* ID generation that survives insecure contexts.
*
* `crypto.randomUUID()` is only exposed on secure contexts (HTTPS or
* localhost/127.0.0.1). On a LAN HTTP deployment (e.g.
* `http://192.168.200.15:8080`) the method is missing and direct calls crash
* with "crypto.randomUUID is not a function". `crypto.getRandomValues()` has
* no secure-context requirement, so the fallback builds a real RFC 4122 v4
* UUID from it; only when `crypto` is absent entirely do we degrade to a
* best-effort Math.random id.
*/
export function randomId(): string {
const c = globalThis.crypto;
if (c && typeof c.randomUUID === "function") return c.randomUUID();
if (c && typeof c.getRandomValues === "function")
return uuidV4(c.getRandomValues.bind(c));
return `id-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}${Math.random()
.toString(36)
.slice(2)}${Math.random().toString(36).slice(2)}`;
}
/** RFC 4122 version 4 UUID from a crypto-strength byte source. */
function uuidV4(getRandomValues: (array: Uint8Array) => Uint8Array): string {
const bytes = getRandomValues(new Uint8Array(16));
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
"",
);
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
@@ -21,6 +21,7 @@ import {
} from './helpers/posture';
import { sampleTrack } from './motion/sampleTrack';
import { normalizeShotParams, type ShotParams } from './calibration/shotSolver';
import { randomId } from '$lib/ids';
export type ComposerTool = 'select' | 'move' | 'rotate' | 'scale' | 'pose';
export type CharacterType = 'male' | 'female' | 'child';
@@ -117,9 +118,7 @@ export function isCharacterType(type: ObjectType): type is CharacterType {
}
function uid(): string {
return typeof crypto !== 'undefined' && 'randomUUID' in crypto
? crypto.randomUUID()
: `id-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
return randomId();
}
function findNearKeyframeIndex(keyframes: Keyframe[], time: number): number {
+975 -3
View File
@@ -1,5 +1,977 @@
<script lang="ts">
// The root route redirects to /agents in +page.ts. This empty component only
// exists to satisfy the leaf-route requirement; it is never rendered because
// load() throws redirect first. Kept as a defensive fallback.
// A「片场暗房」项目总览 — the confirmed a1 layout (HEL-608).
// Everything on this page is driven by real project / job records; when
// there is nothing yet, honest Chinese empty states are shown instead of
// the sample progress rendered in the mockup.
import { goto } from '$app/navigation';
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import { jobsApi, projects, type Project } from '$lib/api';
import { agentDeepLink } from '$lib/agentTasks';
import AppShell from '$lib/components/shell/AppShell.svelte';
import AProjectCard from '$lib/components/home/AProjectCard.svelte';
import Button from '$lib/components/ui/Button.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import Skeleton from '$lib/components/ui/Skeleton.svelte';
import { toast } from '$lib/toast';
import { t } from '$lib/i18n.svelte';
const client = useQueryClient();
const projectsQuery = createQuery({
queryKey: ['projects'],
queryFn: projects.list,
});
const jobsQuery = createQuery({
queryKey: ['jobs', 'recent'],
queryFn: () => jobsApi.list(),
refetchInterval: 8000,
});
const allProjects = $derived($projectsQuery.data ?? []);
const inProgressCount = $derived(allProjects.filter((p) => p.status === 'in_progress').length);
// ------------------------------------------------------------------
// Entry flows — both lead to already-working Calliope flows:
// 从创意开始 → create project → project stage workspace (/project/:id)
// 导入剧本 → create project with the script stored → hand off to the
// project-linked script agent (/agents?project=…&task=script)
// ------------------------------------------------------------------
type EntryMode = 'none' | 'idea' | 'script';
let entryMode = $state<EntryMode>('none');
const GENRES = [
'Adventure / Mystery',
'Drama',
'Sci-Fi',
'Fantasy',
'Horror',
'Romance',
'Thriller',
];
const TONES = [
'Cinematic, atmospheric',
'Dark, tense',
'Whimsical, warm',
'Gritty, realistic',
'Epic, sweeping',
];
const DURATIONS = ['30 seconds', '1 minute', '2 minutes', '5 minutes', '10 minutes'];
let ideaForm = $state({
title: '',
idea: '',
genre: GENRES[0],
tone: TONES[0],
duration: DURATIONS[2],
});
let scriptForm = $state({ title: '', script: '' });
let showErrors = $state(false);
function openIdea() {
entryMode = 'idea';
showErrors = false;
ideaForm = {
title: '',
idea: '',
genre: GENRES[0],
tone: TONES[0],
duration: DURATIONS[2],
};
}
function openScript() {
entryMode = 'script';
showErrors = false;
scriptForm = { title: '', script: '' };
}
function closeEntry() {
entryMode = 'none';
showErrors = false;
}
const ideaErrors = $derived.by(() => {
const errs: Record<string, string> = {};
if (!ideaForm.title.trim()) errs.title = t('home.errTitle');
return errs;
});
const scriptErrors = $derived.by(() => {
const errs: Record<string, string> = {};
if (!scriptForm.title.trim()) errs.title = t('home.errTitle');
if (!scriptForm.script.trim()) errs.script = t('home.errScript');
return errs;
});
function onIdeaCreated(p: Project) {
client.invalidateQueries({ queryKey: ['projects'] });
toast.success(t('projects.created', { title: p.title }));
goto(`/project/${p.id}`);
}
function onScriptCreated(p: Project) {
client.invalidateQueries({ queryKey: ['projects'] });
toast.success(t('projects.created', { title: p.title }));
goto(agentDeepLink(p.id, 'script'));
}
const ideaMutation = createMutation({
mutationFn: () =>
projects.create({
title: ideaForm.title.trim(),
idea: ideaForm.idea.trim() || undefined,
genre: ideaForm.genre || undefined,
tone: ideaForm.tone || undefined,
target_duration: ideaForm.duration || undefined,
}),
onSuccess: onIdeaCreated,
onError: (err) => {
toast.error(err instanceof Error ? err.message : t('projects.createFailed'));
},
});
const scriptMutation = createMutation({
mutationFn: () =>
projects.create({
title: scriptForm.title.trim(),
idea: scriptForm.script.trim(),
}),
onSuccess: onScriptCreated,
onError: (err) => {
toast.error(err instanceof Error ? err.message : t('projects.createFailed'));
},
});
function submitIdea(e: Event) {
e.preventDefault();
showErrors = true;
if (Object.keys(ideaErrors).length || $ideaMutation.isPending) return;
$ideaMutation.mutate();
}
function submitScript(e: Event) {
e.preventDefault();
showErrors = true;
if (Object.keys(scriptErrors).length || $scriptMutation.isPending) return;
$scriptMutation.mutate();
}
// ------------------------------------------------------------------
// Right task area — real queue records only (spec §5 four states).
// ------------------------------------------------------------------
const recentJobs = $derived(($jobsQuery.data ?? []).slice(0, 10));
const activeJobCount = $derived(
($jobsQuery.data ?? []).filter((j) => j.status === 'pending' || j.status === 'running').length,
);
const projectTitles = $derived.by(() => {
const map = new Map<number, string>();
for (const p of allProjects) map.set(p.id, p.title);
return map;
});
const retryMutation = createMutation({
mutationFn: (id: number) => jobsApi.retry(id),
onSuccess: () => {
client.invalidateQueries({ queryKey: ['jobs'] });
toast.success(t('home.jobRequeued'));
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : t('home.jobRetryFailed'));
},
});
const KIND_KEY: Record<string, string> = {
image: 'home.kindImage',
video: 'home.kindVideo',
export: 'home.kindExport',
};
function jobStatusLabel(status: string): string {
if (status === 'done') return t('home.jobDone');
if (status === 'running') return t('home.jobRunning');
if (status === 'pending') return t('home.jobQueued');
if (status === 'failed') return t('home.jobFailed');
return status;
}
function formatJobTime(iso: string): string {
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return '';
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
// English values are the backend contract; display labels come from the
// dictionary — same mapping as the legacy projects page.
function genreKey(value: string): string {
const map: Record<string, string> = {
'Adventure / Mystery': 'adventure',
Drama: 'drama',
'Sci-Fi': 'scifi',
Fantasy: 'fantasy',
Horror: 'horror',
Romance: 'romance',
Thriller: 'thriller',
};
return map[value] ?? 'adventure';
}
function toneKey(value: string): string {
const map: Record<string, string> = {
'Cinematic, atmospheric': 'cinematic',
'Dark, tense': 'dark',
'Whimsical, warm': 'whimsical',
'Gritty, realistic': 'gritty',
'Epic, sweeping': 'epic',
};
return map[value] ?? 'cinematic';
}
function durationKey(value: string): string {
const map: Record<string, string> = {
'30 seconds': '30',
'1 minute': '1m',
'2 minutes': '2m',
'5 minutes': '5m',
'10 minutes': '10',
};
return map[value] ?? '2m';
}
</script>
<AppShell active="projects" title={t('home.title')} subtitle={t('home.subtitle')}>
{#snippet actions()}
<span class="chip">{t('home.projectCount', { n: allProjects.length, m: inProgressCount })}</span
>
<button
class="entry-btn"
class:primary={entryMode === 'none'}
class:secondary={entryMode !== 'none'}
onclick={openIdea}
>
<Icon name="sparkle" size={14} />
{t('home.startIdea')}
</button>
{/snippet}
<div class="home">
<section class="main-col">
{#if entryMode === 'none'}
<div class="entries">
<article class="entry-card">
<span class="entry-icon"><Icon name="sparkle" size={18} /></span>
<h2>{t('home.entryIdeaTitle')}</h2>
<p>{t('home.entryIdeaBody')}</p>
<button type="button" class="entry-btn secondary full" onclick={openIdea}>
{t('home.startIdea')}
</button>
</article>
<article class="entry-card">
<span class="entry-icon"><Icon name="script" size={18} /></span>
<h2>{t('home.entryScriptTitle')}</h2>
<p>{t('home.entryScriptBody')}</p>
<button type="button" class="entry-btn secondary full" onclick={openScript}>
{t('home.importScript')}
</button>
</article>
</div>
{:else if entryMode === 'idea'}
<form class="entry-form" onsubmit={submitIdea}>
<div class="form-head">
<h2>{t('home.entryIdeaTitle')}</h2>
<button
type="button"
class="icon-btn"
aria-label={t('projects.close')}
onclick={closeEntry}
>
<Icon name="close" size={16} />
</button>
</div>
<label class="f-field">
<span class="f-label">{t('projects.titleField')}<em>*</em></span>
<input
class="f-input"
class:invalid={showErrors && ideaErrors.title}
bind:value={ideaForm.title}
placeholder={t('projects.titlePlaceholder')}
/>
{#if showErrors && ideaErrors.title}<span class="f-error">{ideaErrors.title}</span>{/if}
</label>
<label class="f-field">
<span class="f-label">{t('projects.ideaField')}</span>
<textarea
class="f-input textarea"
bind:value={ideaForm.idea}
placeholder={t('home.ideaPlaceholder')}
rows={4}
></textarea>
<span class="f-hint">{t('projects.ideaHint')}</span>
</label>
<div class="f-grid">
<label class="f-field">
<span class="f-label">{t('projects.genre')}</span>
<select class="f-input" bind:value={ideaForm.genre}>
{#each GENRES as v (v)}<option value={v}>{t('genres.' + genreKey(v))}</option
>{/each}
</select>
</label>
<label class="f-field">
<span class="f-label">{t('projects.tone')}</span>
<select class="f-input" bind:value={ideaForm.tone}>
{#each TONES as v (v)}<option value={v}>{t('tones.' + toneKey(v))}</option>{/each}
</select>
</label>
<label class="f-field">
<span class="f-label">{t('projects.duration')}</span>
<select class="f-input" bind:value={ideaForm.duration}>
{#each DURATIONS as v (v)}<option value={v}
>{t('durations.' + durationKey(v))}</option
>{/each}
</select>
</label>
</div>
<div class="form-actions">
<Button variant="ghost" onclick={closeEntry}>{t('projects.cancel')}</Button>
<Button variant="primary" type="submit" loading={$ideaMutation.isPending}>
{t('projects.create')}
</Button>
</div>
</form>
{:else}
<form class="entry-form" onsubmit={submitScript}>
<div class="form-head">
<h2>{t('home.entryScriptTitle')}</h2>
<button
type="button"
class="icon-btn"
aria-label={t('projects.close')}
onclick={closeEntry}
>
<Icon name="close" size={16} />
</button>
</div>
<label class="f-field">
<span class="f-label">{t('projects.titleField')}<em>*</em></span>
<input
class="f-input"
class:invalid={showErrors && scriptErrors.title}
bind:value={scriptForm.title}
placeholder={t('projects.titlePlaceholder')}
/>
{#if showErrors && scriptErrors.title}<span class="f-error">{scriptErrors.title}</span
>{/if}
</label>
<label class="f-field">
<span class="f-label">{t('home.scriptField')}<em>*</em></span>
<textarea
class="f-input textarea"
class:invalid={showErrors && scriptErrors.script}
bind:value={scriptForm.script}
placeholder={t('home.scriptPlaceholder')}
rows={9}
></textarea>
{#if showErrors && scriptErrors.script}<span class="f-error">{scriptErrors.script}</span
>{/if}
<span class="f-hint">{t('home.scriptHint')}</span>
</label>
<div class="form-actions">
<Button variant="ghost" onclick={closeEntry}>{t('projects.cancel')}</Button>
<Button variant="primary" type="submit" loading={$scriptMutation.isPending}>
{t('home.importScript')}
</Button>
</div>
</form>
{/if}
<div class="projects-head">
<h2>{t('home.myProjects')}</h2>
{#if allProjects.length > 0}
<span class="projects-hint">{t('home.myProjectsHint')}</span>
{/if}
</div>
{#if $projectsQuery.isLoading}
<div class="cards" aria-busy="true">
{#each [1, 2, 3] as n (n)}
<div class="skel-card">
<Skeleton height="132px" />
<div class="skel-body">
<Skeleton width="55%" height="15px" />
<Skeleton width="90%" />
<Skeleton width="40%" height="11px" />
</div>
</div>
{/each}
</div>
{:else if $projectsQuery.isError}
<div class="panel-empty error">
<Icon name="alert" size={18} />
<p>{t('projects.loadError')}</p>
<Button variant="secondary" onclick={() => $projectsQuery.refetch()}>
<Icon name="retry" size={14} />
{t('common.retry')}
</Button>
</div>
{:else if allProjects.length === 0}
<div class="panel-empty">
<Icon name="folder" size={20} />
<p>{t('home.emptyProjects')}</p>
</div>
{:else}
<div class="cards">
{#each allProjects as project (project.id)}
<AProjectCard {project} />
{/each}
</div>
{/if}
</section>
<aside class="tasks">
<div class="tasks-head">
<h2>{t('home.tasksTitle')}</h2>
<span class="chip" class:amber={activeJobCount > 0}>
{t('home.activeJobs', { n: activeJobCount })}
</span>
</div>
{#if $jobsQuery.isLoading}
<div class="tasks-loading">{t('common.loading')}…</div>
{:else if recentJobs.length === 0}
<div class="tasks-empty">
<Icon name="queue" size={20} />
<p>{t('home.emptyJobs')}</p>
<p class="tasks-empty-sub">{t('home.emptyJobsSub')}</p>
</div>
{:else}
<ul class="job-list">
{#each recentJobs as job (job.id)}
{@const kindKey = KIND_KEY[job.kind] ?? null}
<li class="job-row" class:failed={job.status === 'failed'}>
<span class="job-main">
{#if kindKey}<span class="tag">{t(kindKey)}</span>{/if}
<span
class="job-name"
title={projectTitles.get(job.project_id) ?? `#${job.project_id}`}
>
{projectTitles.get(job.project_id) ??
t('home.jobProject', { id: job.project_id })}
</span>
</span>
<span class="job-side">
{#if job.status === 'failed' && job.error && job.error !== 'cancelled'}
<span class="job-status mono failed-text" title={job.error}
>{jobStatusLabel(job.status)}</span
>
<button
type="button"
class="retry-link"
onclick={() => $retryMutation.mutate(job.id)}
>
{t('common.retry')}
</button>
{:else}
<span
class="job-status mono {job.status === 'done'
? 'done-text'
: job.status === 'running'
? 'running-text'
: 'queued-text'}"
>
{#if job.status === 'running'}<span class="dot breathe" aria-hidden="true"
></span>{/if}
{jobStatusLabel(job.status)}
</span>
<span class="job-time mono">{formatJobTime(job.created_at)}</span>
{/if}
</span>
</li>
{/each}
</ul>
{/if}
<p class="tasks-note">{t('home.tasksNote')}</p>
</aside>
</div>
</AppShell>
<style>
.home {
display: grid;
grid-template-columns: minmax(0, 1fr) 344px;
gap: 24px;
padding: 24px 28px 40px;
max-width: 1560px;
width: 100%;
box-sizing: border-box;
margin: 0 auto;
align-items: start;
}
.main-col {
min-width: 0;
display: flex;
flex-direction: column;
gap: 22px;
}
/* ---------------- topbar chip + buttons ---------------- */
.chip {
padding: 5px 12px;
border-radius: 999px;
background: var(--surface-3);
color: var(--text-2);
font-size: 11.5px;
white-space: nowrap;
}
.chip.amber {
background: var(--accent-dim);
color: var(--accent);
}
.entry-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
min-height: 34px;
padding: 0 16px;
border-radius: 8px;
font-family: inherit;
font-size: 13px;
font-weight: 600;
cursor: pointer;
border: 1px solid transparent;
transition:
background-color 150ms cubic-bezier(0.16, 1, 0.3, 1),
border-color 150ms,
transform 100ms;
}
.entry-btn.primary {
background: var(--accent);
color: var(--accent-contrast);
}
.entry-btn.primary:hover {
background: var(--accent-hover);
}
.entry-btn.secondary {
background: var(--surface-2);
border-color: var(--border-strong);
color: var(--text);
}
.entry-btn.secondary:hover {
border-color: rgba(255, 255, 255, 0.24);
}
.entry-btn:active {
transform: scale(0.98);
}
.entry-btn.full {
width: 100%;
margin-top: auto;
}
/* ---------------- entry cards / forms (a1 双入口) ---------------- */
.entries {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
}
.entry-card {
display: flex;
flex-direction: column;
gap: 8px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
padding: 18px 20px 20px;
min-height: 168px;
}
.entry-icon {
width: 38px;
height: 38px;
border-radius: 9px;
background: var(--surface-2);
border: 1px solid var(--border-strong);
display: inline-flex;
align-items: center;
justify-content: center;
color: var(--accent);
}
.entry-card h2 {
margin: 4px 0 0;
font-size: 14.5px;
font-weight: 600;
color: var(--text);
}
.entry-card p {
margin: 0;
font-size: 12.5px;
line-height: 1.65;
color: var(--text-2);
}
.entry-form {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
padding: 18px 20px 20px;
}
.form-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 14px;
}
.form-head h2 {
margin: 0;
font-size: 15px;
font-weight: 600;
color: var(--text);
}
.icon-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border: none;
border-radius: 7px;
background: transparent;
color: var(--text-3);
cursor: pointer;
}
.icon-btn:hover {
background: var(--surface-3);
color: var(--text);
}
.f-field {
display: block;
margin-bottom: 13px;
}
.f-label {
display: flex;
align-items: center;
gap: 4px;
font-size: 12px;
font-weight: 600;
color: var(--text-2);
margin-bottom: 6px;
}
.f-label em {
color: var(--error);
font-style: normal;
}
.f-input {
width: 100%;
box-sizing: border-box;
background: var(--surface-2);
border: 1px solid var(--border-strong);
border-radius: 7px;
padding: 9px 11px;
color: var(--text);
font-family: inherit;
font-size: 13px;
}
.f-input.textarea {
resize: vertical;
min-height: 88px;
line-height: 1.6;
}
.f-input:focus {
outline: none;
border-color: rgba(232, 163, 61, 0.6);
}
.f-input.invalid {
border-color: rgba(229, 72, 77, 0.65);
}
.f-hint {
display: block;
margin-top: 5px;
font-size: 11px;
color: var(--text-3);
}
.f-error {
display: block;
margin-top: 5px;
font-size: 11.5px;
color: var(--error);
}
.f-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
}
.f-grid .f-field {
margin-bottom: 0;
}
.form-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 16px;
padding-top: 12px;
border-top: 1px solid var(--border);
}
/* restyle reused ui/Button inside the darkroom scope (§5) */
.home :global(.btn-primary) {
background: var(--accent);
color: var(--accent-contrast);
}
.home :global(.btn-primary:hover:not(:disabled)) {
background: var(--accent-hover);
}
.home :global(.btn-secondary) {
background: var(--surface-2);
border-color: var(--border-strong);
color: var(--text);
}
.home :global(.btn-secondary:hover:not(:disabled)) {
background: var(--surface-3);
}
.home :global(.btn-ghost) {
color: var(--text-2);
}
.home :global(.btn-ghost:hover:not(:disabled)) {
background: var(--surface-3);
color: var(--text);
}
/* ---------------- project cards ---------------- */
.projects-head {
display: flex;
align-items: baseline;
gap: 12px;
}
.projects-head h2 {
margin: 0;
font-size: 14.5px;
font-weight: 600;
color: var(--text);
}
.projects-hint {
font-size: 11.5px;
color: var(--text-3);
}
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 16px;
}
.skel-card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
overflow: hidden;
}
.skel-card :global(.skeleton) {
border-radius: 0;
}
.skel-body {
display: flex;
flex-direction: column;
gap: 9px;
padding: 14px 16px;
}
.panel-empty {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
padding: 36px 20px;
border: 1.5px dashed var(--border-strong);
border-radius: 10px;
color: var(--text-3);
text-align: center;
}
.panel-empty p {
margin: 0;
font-size: 12.5px;
line-height: 1.65;
color: var(--text-2);
}
.panel-empty.error p {
color: var(--error);
}
/* ---------------- right task area ---------------- */
.tasks {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
padding: 16px 18px 14px;
position: sticky;
top: 24px;
display: flex;
flex-direction: column;
gap: 12px;
min-width: 0;
}
.tasks-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.tasks-head h2 {
margin: 0;
font-size: 14px;
font-weight: 600;
color: var(--text);
white-space: nowrap;
}
.tasks-loading {
color: var(--text-3);
font-size: 12px;
padding: 12px 0;
}
.tasks-empty {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
padding: 22px 10px 16px;
color: var(--text-3);
text-align: center;
}
.tasks-empty p {
margin: 0;
font-size: 12px;
line-height: 1.65;
color: var(--text-2);
}
.tasks-empty-sub {
font-size: 11px;
color: var(--text-3);
}
.job-list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
.job-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 10px 0;
border-bottom: 1px solid var(--border);
min-height: 44px;
}
.job-row:last-child {
border-bottom: none;
}
.job-main {
display: inline-flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.tag {
padding: 1px 8px;
border-radius: 999px;
background: var(--info-dim);
color: var(--info);
font-size: 10.5px;
font-weight: 600;
flex-shrink: 0;
}
.job-name {
font-size: 12.5px;
color: var(--text);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.job-side {
display: inline-flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.job-status {
display: inline-flex;
align-items: center;
gap: 5px;
font-size: 11px;
}
.done-text {
color: var(--success);
}
.running-text {
color: var(--accent);
}
.queued-text {
color: var(--text-3);
}
.failed-text {
color: var(--error);
max-width: 120px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 10px var(--accent-glow);
}
.dot.breathe {
animation: breathe 2s ease-in-out infinite;
}
@keyframes breathe {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.35;
}
}
.job-time {
font-size: 10.5px;
color: var(--text-3);
}
.retry-link {
background: none;
border: none;
padding: 0;
font-family: inherit;
font-size: 11px;
color: var(--error);
cursor: pointer;
text-decoration: underline;
text-underline-offset: 3px;
}
.tasks-note {
margin: 0;
padding-top: 10px;
border-top: 1px solid var(--border);
font-size: 10.5px;
line-height: 1.6;
color: var(--text-3);
}
/* ---------------- responsive ---------------- */
@media (max-width: 1439px) {
.home {
grid-template-columns: minmax(0, 1fr) 320px;
padding: 20px 22px 36px;
}
}
@media (max-width: 1023px) {
.home {
grid-template-columns: minmax(0, 1fr);
padding: 16px 16px 32px;
}
.tasks {
position: static;
}
.entries {
grid-template-columns: minmax(0, 1fr);
}
.f-grid {
grid-template-columns: minmax(0, 1fr);
}
}
</style>
+2 -3
View File
@@ -1,8 +1,7 @@
import { redirect } from '@sveltejs/kit';
export const prerender = false;
export const ssr = false;
// The root route is the A「片场暗房」项目总览 (HEL-608) — no redirect.
export function load() {
redirect(302, '/agents');
return {};
}
+56
View File
@@ -49,6 +49,62 @@ body {
min-height: 100vh;
}
/* ------------------------------------------------------------------
* A「片场暗房」scoped design tokens — spec-v2 §2 (HEL-603 confirmed).
* Adopted incrementally by new A-style pages via the `.a-darkroom`
* wrapper; graduates to :root when the full A shell (216px nav) lands.
* Values are the single source of truth for A pages — do not hardcode
* colors inside pages, and do not override these with ad-hoc CSS.
* ------------------------------------------------------------------ */
.a-darkroom {
--bg: #0d0e11;
--surface: #14161b;
--surface-2: #1b1e25;
--surface-3: #22262f;
--border: rgba(255, 255, 255, 0.07);
--border-strong: rgba(255, 255, 255, 0.14);
--text: #edeef0;
--text-2: #9ba1ab;
--text-3: #5c626c;
--accent: #e8a33d;
--accent-hover: #f1b155; /* +8% brightness (§5 主按钮) */
--accent-contrast: #16130a;
--accent-dim: rgba(232, 163, 61, 0.14);
--accent-glow: rgba(232, 163, 61, 0.35);
--success: #3fb97f;
--success-dim: rgba(63, 185, 127, 0.14);
--info: #5b8def;
--info-dim: rgba(91, 141, 239, 0.14);
--error: #e5484d;
--error-dim: rgba(229, 72, 77, 0.14);
--cloud: #b98be0;
--cloud-dim: rgba(185, 139, 224, 0.14);
/* Typography (§2.2) */
--font-ui: 'Noto Sans SC', 'Noto Sans CJK SC', var(--font-body);
--font-a-mono: 'JetBrains Mono', 'IBM Plex Mono', ui-monospace, monospace;
/* Avatar five-color set (§2.1) — five agents only */
--avatar-1: linear-gradient(135deg, #e8a33d, #b96a1b);
--avatar-2: linear-gradient(135deg, #5b8def, #3a5fa9);
--avatar-3: linear-gradient(135deg, #3fb97f, #2a7a54);
--avatar-4: linear-gradient(135deg, #b98be0, #7a4fa9);
--avatar-5: linear-gradient(135deg, #d98e6a, #a95535);
background: var(--bg);
color: var(--text);
font-family: var(--font-ui);
font-size: 13.5px;
line-height: 1.6;
}
.a-darkroom .mono,
.a-darkroom code,
.a-darkroom .kh {
font-family: var(--font-a-mono);
font-variant-numeric: tabular-nums;
}
h1,
h2,
h3,
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
export const ssr = false;
export const prerender = false;
+93 -12
View File
@@ -11,6 +11,7 @@
import Icon from '$lib/components/ui/Icon.svelte';
import StatusChip from '$lib/components/ui/StatusChip.svelte';
import { settings, type LlmProfile, type Settings } from '$lib/api';
import { randomId } from '$lib/ids';
import { toast } from '$lib/toast';
import { t } from '$lib/i18n.svelte';
@@ -33,6 +34,7 @@
let draft = $state<Record<string, unknown>>({});
let apiKeyDrafts = $state<Record<string, string>>({});
let llmTestState = $state<Record<string, { pending: boolean; ok?: boolean; message: string }>>({});
// Dirty tracking: any staged field (draft map or a typed API key) counts.
const dirtyKeys = $derived([
@@ -325,7 +327,7 @@
function addProfile(s: Settings) {
ensureLlmDraft(s);
const id = crypto.randomUUID();
const id = randomId();
draft.llm_profiles = [
...(draft.llm_profiles as LlmProfile[]),
{
@@ -349,6 +351,53 @@
const nextKeys = { ...apiKeyDrafts };
delete nextKeys[id];
apiKeyDrafts = nextKeys;
const nextTests = { ...llmTestState };
delete nextTests[id];
llmTestState = nextTests;
}
function llmTestFailureText(res: { error?: string; detail?: string }): string {
let detail = res.detail ?? res.error ?? '';
if (res.error === 'auth') detail = t('settings.llmTestAuth', { detail });
else if (res.error === 'timeout') detail = t('settings.llmTestTimeout');
else if (res.error === 'connect') detail = t('settings.llmTestConnect', { detail });
return t('settings.llmTestFail', { detail });
}
async function testLlmConnection(s: Settings, profile: LlmProfile) {
ensureLlmDraft(s);
const typedKey = apiKeyDrafts[profile.id];
const savedOnServer = s.llm_profiles?.some((p) => p.id === profile.id) ?? false;
llmTestState = { ...llmTestState, [profile.id]: { pending: true, message: '' } };
try {
const res = await settings.testLlm({
...(typedKey || !savedOnServer ? {} : { profile_id: profile.id }),
base_url: profile.base_url.trim(),
model: profile.model.trim(),
...(typedKey ? { api_key: typedKey } : {}),
});
llmTestState = {
...llmTestState,
[profile.id]: res.ok
? {
pending: false,
ok: true,
message: t('settings.llmTestOk', { ms: res.elapsed_ms ?? '?' }),
}
: { pending: false, ok: false, message: llmTestFailureText(res) },
};
} catch (err) {
llmTestState = {
...llmTestState,
[profile.id]: {
pending: false,
ok: false,
message: t('settings.llmTestFail', {
detail: err instanceof Error ? err.message : String(err),
}),
},
};
}
}
</script>
@@ -389,16 +438,25 @@
{#each workingProfiles(s) as profile (profile.id)}
{@const active = workingActiveId(s) === profile.id}
<article class="llm-card" class:active>
<header class="llm-card-head">
<label class="llm-active">
<input
type="radio"
name="llm-active"
checked={active}
onchange={() => setActiveProfile(s, profile.id)}
/>
<span>{active ? t('settings.active') : t('settings.useThis')}</span>
</label>
<header class="llm-card-head">
<label class="llm-active">
<input
type="radio"
name="llm-active"
checked={active}
onchange={() => setActiveProfile(s, profile.id)}
/>
<span>{active ? t('settings.active') : t('settings.useThis')}</span>
</label>
<div class="llm-card-actions">
<Button
variant="secondary"
size="sm"
loading={llmTestState[profile.id]?.pending}
onclick={() => testLlmConnection(s, profile)}
>
{t('settings.testLlm')}
</Button>
{#if workingProfiles(s).length > 1}
<Button
variant="ghost"
@@ -410,7 +468,17 @@
{t('settings.remove')}
</Button>
{/if}
</header>
</div>
</header>
{#if llmTestState[profile.id] && !llmTestState[profile.id].pending && llmTestState[profile.id].message}
<p
class="test-result"
class:ok={llmTestState[profile.id].ok}
class:err={llmTestState[profile.id].ok === false}
>
{llmTestState[profile.id].message}
</p>
{/if}
<label class="field">
<span class="field-label">{t('settings.name')}</span>
<input
@@ -950,6 +1018,19 @@
gap: 12px;
margin-bottom: var(--space-sm);
}
.llm-card-actions {
display: flex;
align-items: center;
gap: 8px;
}
.test-result {
margin: 0 0 var(--space-sm);
font-size: 12px;
color: var(--error);
}
.test-result.ok {
color: var(--success);
}
.llm-active {
display: inline-flex;
align-items: center;