Files
aigc-home/calliope-web/src/lib/components/agent/LegacyAgentWorkspace.svelte
T

3529 lines
89 KiB
Svelte
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script lang="ts">
import { storageGet, storageSet, storageRemove } from '$lib/storage';
import { resolve } from '$app/paths';
import { onMount, untrack } from 'svelte';
import { SvelteMap } from 'svelte/reactivity';
import { goto } from '$app/navigation';
import { page } from '$app/state';
import {
createMutation,
createQuery,
useQueryClient,
} from '@tanstack/svelte-query';
import { fade } from 'svelte/transition';
import AppShell from '$lib/components/shell/AppShell.svelte';
import Button from '$lib/components/ui/Button.svelte';
import ConfirmDialog from '$lib/components/ui/ConfirmDialog.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import Switch from '$lib/components/ui/Switch.svelte';
import AgentChat from '$lib/components/agent/AgentChat.svelte';
import AgentPlanPanel from '$lib/components/agent/AgentPlanPanel.svelte';
import Modal from '$lib/components/ui/Modal.svelte';
import { spotlight } from '$lib/actions/spotlight';
import { agentStyles, agentThemes } from '$lib/referenceAgent';
import { createUploadManager } from '$lib/comfy/useUpload.svelte';
import type {
AgentAttachment,
AgentComposerPayload,
} from '$lib/agentComposer';
import {
agentApi,
assetUrl,
settings,
type AgentMessage,
type AgentSession,
type NamedAgent,
type SkillAdminEntry,
type SkillVersion,
type WorkbenchStageKey,
canvasApi,
workflows,
workbenchApi,
} from '$lib/api';
import {
AGENT_TASK_PROMPTS,
AGENT_TASK_TITLE_KEYS,
isAgentTaskKind,
} from '$lib/agentTasks';
import { connectEvents } from '$lib/events';
import { stripSkillFrontmatter } from '$lib/skillFrontmatter';
import { toStore } from 'svelte/store';
import { t } from '$lib/i18n.svelte';
import { toast } from '$lib/toast';
const client = useQueryClient();
// ─────────────────────────────────────────────────────────────────────
// Legacy deep-link contract (Project stages): /agents?project=<id>&task=
// story|script still routes into the canvas flow, not this page.
// ─────────────────────────────────────────────────────────────────────
let legacyRedirect = $state<'pending' | 'off' | 'failed'>('pending');
let legacyError = $state('');
onMount(async () => {
const projectParam = page.url.searchParams.get('project');
const taskParam = page.url.searchParams.get('task');
if (projectParam == null && taskParam == null) {
legacyRedirect = 'off';
return;
}
try {
const pid =
projectParam != null && projectParam !== ''
? Number(projectParam)
: null;
const task = isAgentTaskKind(taskParam) ? taskParam : null;
const s = await agentApi.createSession({
...(pid != null && Number.isFinite(pid) ? { project_id: pid } : {}),
...(task ? { title: t(AGENT_TASK_TITLE_KEYS[task]) } : {}),
});
const session = await agentApi.getSession(s.id);
const graph = session.project_id
? await canvasApi.ensureForProject(session.project_id)
: await canvasApi.ensureForSession(session.id);
if (task)
sessionStorage.setItem(
'calliope.canvas.composerPrefill',
AGENT_TASK_PROMPTS[task],
);
goto(resolve(`/canvas/${graph.canvas.id}?session=${session.id}`), { replaceState: true });
} catch (err) {
legacyError = err instanceof Error ? err.message : String(err);
legacyRedirect = 'failed';
}
});
// ─────────────────────────────────────────────────────────────────────
// Registry / sessions / skills / settings
// ─────────────────────────────────────────────────────────────────────
const agentsQuery = createQuery({
queryKey: ['agents-registry'],
queryFn: agentApi.listNamedAgents,
});
const settingsQuery = createQuery({
queryKey: ['settings'],
queryFn: settings.get,
});
const ALL_KEYS = ['script', 'style', 'storyboard', 'assets', 'shot'] as const;
// One query for all five agents' sessions (left-column busy flags and
// the per-agent session selector share it).
const allSessionsQuery = createQuery({
queryKey: ['agents-page-sessions'],
queryFn: async () => {
const lists = await Promise.all(
ALL_KEYS.map((k) => agentApi.listAgentSessions(k)),
);
return lists.flat();
},
});
let activeKey = $state<string>(
(() => {
const stored = storageGet('calliope.agents.activeKey');
return stored && (ALL_KEYS as readonly string[]).includes(stored)
? stored
: 'script';
})(),
);
const agents = $derived($agentsQuery.data ?? []);
const activeAgent: NamedAgent | null = $derived(
agents.find((a) => a.key === activeKey) ?? null,
);
const activeSessions = $derived(
($allSessionsQuery.data ?? []).filter((s) => s.agent_key === activeKey),
);
const busyByAgent = $derived.by(() => {
const map: Record<string, boolean> = {};
for (const s of $allSessionsQuery.data ?? []) {
if (s.running) map[s.agent_key ?? ''] = true;
}
return map;
});
let activeId = $state<number | null>(null);
const sessionQuery = createQuery(
toStore(() => ({
queryKey: ['agent-session', activeId],
queryFn: () => agentApi.getSession(activeId!),
enabled: activeId != null,
})),
);
// Session selection per agent, persisted; falls back to the newest.
$effect(() => {
const list = activeSessions;
const key = activeKey;
if (!list.length) {
activeId = null;
return;
}
const stored = Number(
storageGet(`calliope.agents.session.${key}`),
);
const found = list.find((s) => s.id === stored) ?? list[0];
activeId = found.id;
});
function rememberSession(key: string, id: number | null) {
if (id != null)
storageSet(`calliope.agents.session.${key}`, String(id));
else storageRemove(`calliope.agents.session.${key}`);
}
function selectAgent(key: string) {
if (sendPending || uploadPending || projectPending) return;
storageSet('calliope.agents.activeKey', key);
activeKey = key;
resetStreaming();
}
function selectSession(id: number) {
if (sendPending || uploadPending || projectPending) return;
activeId = id;
rememberSession(activeKey, id);
resetStreaming();
}
async function newSession() {
if (sendPending || uploadPending || projectPending) return;
sendPending = true;
try {
const s = await agentApi.createSession({
agent_key: activeKey,
project_id: currentPreference.project,
});
rememberSession(activeKey, s.id);
await client.invalidateQueries({ queryKey: ['agents-page-sessions'] });
activeId = s.id;
resetStreaming();
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
} finally {
sendPending = false;
}
}
// ─────────────────────────────────────────────────────────────────────
// Chat streaming state (same SSE contract as the canvas page)
// ─────────────────────────────────────────────────────────────────────
let streaming = $state('');
let streamingReasoning = $state('');
let thinkingAgent = $state<string | null>(null);
let liveTools = $state<
{
tool: string;
args?: Record<string, unknown> | null;
result?: unknown;
phase: 'running' | 'done' | 'error';
}[]
>([]);
function resetStreaming() {
streaming = '';
streamingReasoning = '';
thinkingAgent = null;
liveTools = [];
}
function appendMessage(sid: number, msg: AgentMessage) {
if (sid !== activeId) return;
client.setQueryData<AgentSession & { messages: AgentMessage[] }>(
['agent-session', sid],
(old) => {
if (!old || !Array.isArray(old.messages)) return old;
if (old.messages.some((m) => m.id === msg.id)) return old;
return { ...old, messages: [...old.messages, msg] };
},
);
}
onMount(() => {
const stop = connectEvents((ev) => {
if (ev.type === 'events.resync') {
client.invalidateQueries({ queryKey: ['agents-page-sessions'] });
if (activeId != null)
client.invalidateQueries({ queryKey: ['agent-session', activeId] });
client.invalidateQueries({ queryKey: ['agents-registry'] });
return;
}
if (ev.type === 'agent.session.updated') {
client.invalidateQueries({ queryKey: ['agents-page-sessions'] });
if (activeId != null)
client.invalidateQueries({ queryKey: ['agent-session', activeId] });
return;
}
if (ev.type === 'agent.message') {
const msg = ev.data?.message as AgentMessage | undefined;
if (msg) {
appendMessage(msg.session_id, msg);
if (msg.session_id === activeId && msg.role === 'tool')
liveTools = [];
if (msg.session_id === activeId && msg.role === 'assistant')
resetStreaming();
}
return;
}
if (ev.data?.session_id !== activeId) return;
if (ev.type === 'agent.token') {
if (!ev.data?.agent_name) streaming += String(ev.data?.content ?? '');
} else if (ev.type === 'agent.thinking') {
const name = (ev.data?.agent_name as string | undefined) ?? null;
if (name !== thinkingAgent) {
streamingReasoning += `${name ? `${name}: ` : ''}`;
thinkingAgent = name;
}
streamingReasoning += String(ev.data?.content ?? '');
} else if (ev.type === 'agent.tool') {
const name = String(ev.data?.tool ?? '');
const phase = String(ev.data?.phase ?? '');
if (phase === 'start') {
liveTools.push({
tool: name,
args: (ev.data?.args as Record<string, unknown>) ?? null,
phase: 'running',
});
} else if (phase === 'finish') {
const idx = [...liveTools]
.reverse()
.findIndex((x) => x.tool === name && x.phase === 'running');
if (idx >= 0) {
const real = liveTools.length - 1 - idx;
liveTools[real] = {
...liveTools[real],
result: ev.data?.result,
phase:
(ev.data?.result as { ok?: boolean } | undefined)?.ok === false
? 'error'
: 'done',
};
}
}
}
});
return stop;
});
const running = $derived($sessionQuery.data?.running === true);
const messages = $derived($sessionQuery.data?.messages ?? []);
// ─────────────────────────────────────────────────────────────────────
// Composer (spec §4.3: Enter 发送 / Shift+Enter 换行)
// ─────────────────────────────────────────────────────────────────────
let draft = $state('');
async function handleSend() {
const content = draft.trim();
if (
!content ||
running ||
sendPending ||
uploadPending ||
projectPending ||
$assignMutation.isPending
)
return;
const key = activeKey,
originalDraft = draft;
const style = chosenStyle,
skill = chosenSkill,
wf = chosenWorkflow;
const mentions: AgentComposerPayload['mentions'] = [];
if (skill && skill.is_enabled && skill.bindings?.[key])
mentions.push({
type: 'skill',
name: skill.dir,
description: skill.description.slice(0, 500),
});
if (wf)
mentions.push({
type: 'workflow',
id: wf.id,
name: wf.name,
kind: wf.kind as 'image' | 'video',
});
const payload: AgentComposerPayload = {
content:
content + '\n\n视觉方向:' + style.name + '。' + style.prompt + '。',
mentions,
attachments: [...attachments],
};
sendPending = true;
let sid = activeId;
try {
if (sid == null) {
const session = await agentApi.createSession({
agent_key: key,
project_id: currentPreference.project,
});
sid = session.id;
rememberSession(key, sid);
await client.invalidateQueries({ queryKey: ['agents-page-sessions'] });
activeId = sid;
}
await agentApi.postMessage(sid, payload);
draft = '';
agentDrafts = { ...agentDrafts, [key]: '' };
agentAttachments = { ...agentAttachments, [key]: [] };
await client.invalidateQueries({ queryKey: ['agent-session', sid] });
await client.invalidateQueries({ queryKey: ['agents-page-sessions'] });
} catch (err) {
draft = originalDraft;
toast.error(err instanceof Error ? err.message : String(err));
} finally {
sendPending = false;
}
}
function onKeydown(e: KeyboardEvent) {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && !e.isComposing) {
e.preventDefault();
void handleSend();
}
}
function handleAnswer(option: string, _scope: string, questionSeq: number) {
if (running || activeId == null) return;
draft = option;
void (async () => {
const content = option;
draft = '';
try {
await agentApi.postMessage(activeId!, {
content,
mentions: [],
attachments: [],
answer_to: questionSeq,
});
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
}
})();
}
// Per-agent opening suggestions for the empty timeline.
const SUGGESTIONS: Record<string, { labelKey: string; promptKey: string }[]> =
{
script: [
{
labelKey: 'agentsPage.sugScript1',
promptKey: 'agentsPage.sugScript1P',
},
{
labelKey: 'agentsPage.sugScript2',
promptKey: 'agentsPage.sugScript2P',
},
],
style: [
{
labelKey: 'agentsPage.sugStyle1',
promptKey: 'agentsPage.sugStyle1P',
},
{
labelKey: 'agentsPage.sugStyle2',
promptKey: 'agentsPage.sugStyle2P',
},
],
storyboard: [
{
labelKey: 'agentsPage.sugBoard1',
promptKey: 'agentsPage.sugBoard1P',
},
{
labelKey: 'agentsPage.sugBoard2',
promptKey: 'agentsPage.sugBoard2P',
},
],
assets: [
{
labelKey: 'agentsPage.sugAssets1',
promptKey: 'agentsPage.sugAssets1P',
},
{
labelKey: 'agentsPage.sugAssets2',
promptKey: 'agentsPage.sugAssets2P',
},
],
shot: [
{ labelKey: 'agentsPage.sugShot1', promptKey: 'agentsPage.sugShot1P' },
{ labelKey: 'agentsPage.sugShot2', promptKey: 'agentsPage.sugShot2P' },
],
};
const suggestions = $derived(
(SUGGESTIONS[activeKey] ?? []).map((s) => ({
label: t(s.labelKey),
prompt: t(s.promptKey),
})),
);
// ─────────────────────────────────────────────────────────────────────
// 清空 / 导出
// ─────────────────────────────────────────────────────────────────────
let clearOpen = $state(false);
const clearMutation = createMutation({
mutationFn: async () => {
if (activeId == null) return;
await agentApi.deleteSession(activeId);
rememberSession(activeKey, null);
const s = await agentApi.createSession({ agent_key: activeKey });
rememberSession(activeKey, s.id);
return s;
},
onSuccess: (s) => {
clearOpen = false;
resetStreaming();
void client.invalidateQueries({ queryKey: ['agents-page-sessions'] });
if (s) activeId = s.id;
},
onError: (err) =>
toast.error(err instanceof Error ? err.message : String(err)),
});
function exportMarkdown() {
const s = $sessionQuery.data;
if (!s || !messages.length) return;
const name = activeAgent?.name ?? activeKey;
const lines = [`# ${name} · ${s.title}`, ''];
for (const m of messages) {
if (m.role === 'user') lines.push(`## 🧑 用户`, '', m.content, '');
else if (m.role === 'assistant')
lines.push(`## 🤖 ${m.agent_name ?? name}`, '', m.content, '');
else if (m.role === 'tool' && m.tool_name)
lines.push(`> 工具调用 \`${m.tool_name}\``, '');
}
const blob = new Blob([lines.join('\n')], {
type: 'text/markdown;charset=utf-8',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `agents-${activeKey}-${s.id}.md`;
a.click();
URL.revokeObjectURL(url);
}
// ─────────────────────────────────────────────────────────────────────
// Per-agent model binding (shares data with the models page panel)
// ─────────────────────────────────────────────────────────────────────
const assignMutation = createMutation({
mutationFn: (payload: Record<string, string | null>) =>
settings.update({ agent_llm_assignments: payload }),
onSuccess: () => client.invalidateQueries({ queryKey: ['settings'] }),
onError: (err) => {
void client.invalidateQueries({ queryKey: ['settings'] });
toast.error(err instanceof Error ? err.message : String(err));
},
});
function setAgentModel(role: string, value: string) {
// Single-role delta only (HEL-619): the whole-snapshot replay races
// concurrent switches; the server merges per role.
$assignMutation.mutate({ [role]: value === '' ? null : value });
}
// ─────────────────────────────────────────────────────────────────────
// Skill management (right column)
// ─────────────────────────────────────────────────────────────────────
const skillsQuery = createQuery({
queryKey: ['skills-admin'],
queryFn: agentApi.listSkillsAdmin,
});
const skills = $derived($skillsQuery.data ?? []);
type EditorMode = 'idle' | 'add' | 'edit';
let editorMode = $state<EditorMode>('idle');
let editingDir = $state<string | null>(null);
let form = $state({ name: '', type: 'template', desc: '', content: '' });
let formBindings = $state<Record<string, boolean>>({});
let showSkillErrors = $state(false);
let drawerOpen = $state(false);
let versionsOpen = $state(false);
let versions = $state<SkillVersion[]>([]);
const skillErrors = $derived.by(() => {
const errs: Record<string, string> = {};
if (!form.name.trim()) errs.name = t('agentsPage.skillErrName');
if (editorMode === 'edit' && Object.values(formBindings).every((v) => !v))
errs.bindings = t('agentsPage.skillErrAssign');
return errs;
});
function resetEditor() {
editorMode = 'idle';
editingDir = null;
form = { name: '', type: 'template', desc: '', content: '' };
formBindings = {};
showSkillErrors = false;
versionsOpen = false;
versions = [];
drawerOpen = false;
}
function startAddSkill() {
resetEditor();
editorMode = 'add';
// A new skill defaults to the agent being viewed.
formBindings = { [activeKey]: true };
openDrawer();
}
async function startEditSkill(skill: SkillAdminEntry) {
resetEditor();
editorMode = 'edit';
editingDir = skill.dir;
form = {
name: skill.dir,
type: skill.type || 'template',
desc: skill.description,
content: '',
};
formBindings = { ...skill.bindings };
openDrawer();
try {
const res = await agentApi.readSkillFile(skill.dir, 'SKILL.md');
form.content = stripSkillFrontmatter(res.content ?? '');
} catch {
toast.error(t('agentsPage.skillLoadFailed'));
}
}
function openDrawer() {
drawerOpen = true;
}
const saveSkillMutation = createMutation({
mutationFn: async () => {
const dir =
editorMode === 'edit' && editingDir ? editingDir : form.name.trim();
return agentApi.upsertSkill(dir, {
description: form.desc.trim(),
skill_type: form.type,
content: form.content,
bindings: formBindings,
});
},
onSuccess: () => {
toast.success(t('agentsPage.skillSaved'));
void client.invalidateQueries({ queryKey: ['skills-admin'] });
void client.invalidateQueries({ queryKey: ['agents-registry'] });
resetEditor();
},
onError: (err) =>
toast.error(
t('agentsPage.skillSaveFailed', {
detail: err instanceof Error ? err.message : String(err),
}),
),
});
function submitSkill() {
showSkillErrors = true;
if (Object.keys(skillErrors).length || $saveSkillMutation.isPending) return;
$saveSkillMutation.mutate();
}
const toggleSkillMutation = createMutation({
mutationFn: ({ dir, next }: { dir: string; next: boolean }) =>
agentApi.patchSkill(dir, next),
onSuccess: (_d, vars) => {
toast.success(
vars.next
? t('agentsPage.skillEnabled')
: t('agentsPage.skillDisabled'),
);
void client.invalidateQueries({ queryKey: ['skills-admin'] });
void client.invalidateQueries({ queryKey: ['agents-registry'] });
},
onError: (err) => {
void client.invalidateQueries({ queryKey: ['skills-admin'] });
toast.error(err instanceof Error ? err.message : String(err));
},
});
let deleteSkillOpen = $state(false);
let deleteSkillTarget = $state<SkillAdminEntry | null>(null);
const deleteSkillMutation = createMutation({
mutationFn: (dir: string) => agentApi.deleteSkill(dir),
onSuccess: () => {
deleteSkillOpen = false;
toast.success(t('agentsPage.skillDeleted'));
if (editingDir === deleteSkillTarget?.dir) resetEditor();
deleteSkillTarget = null;
void client.invalidateQueries({ queryKey: ['skills-admin'] });
void client.invalidateQueries({ queryKey: ['agents-registry'] });
},
onError: (err) =>
toast.error(err instanceof Error ? err.message : String(err)),
});
async function loadVersions(dir: string) {
try {
versions = await agentApi.listSkillVersions(dir);
versionsOpen = true;
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
}
}
const restoreMutation = createMutation({
mutationFn: ({ dir, id }: { dir: string; id: number }) =>
agentApi.restoreSkillVersion(dir, id),
onSuccess: () => {
toast.success(t('agentsPage.skillRestored'));
void client.invalidateQueries({ queryKey: ['skills-admin'] });
if (editingDir) void loadVersions(editingDir);
// Refresh the open editor body to the restored content.
if (editingDir) {
void (async () => {
const skill = $skillsQuery.data?.find((s) => s.dir === editingDir);
if (skill) await startEditSkill(skill);
})();
}
},
onError: (err) =>
toast.error(err instanceof Error ? err.message : String(err)),
});
function typeLabel(type: string): string {
return type === 'knowledge'
? t('agentsPage.skillTypeKnowledge')
: type === 'rules'
? t('agentsPage.skillTypeRules')
: t('agentsPage.skillTypeTemplate');
}
// Built-in skills ship with English slugs as their directory; show a
// localized name when one exists, otherwise the user's own name.
function skillLabel(dir: string): string {
const key = `skillName.${dir}`;
const label = t(key);
return label === key ? dir : label;
}
/** SQLite CURRENT_TIMESTAMP ships as "YYYY-MM-DD HH:MM:SS" in UTC —
* parse it as such and render in the viewer's local timezone. */
function formatUtcString(raw: string | null | undefined): string {
if (!raw) return '';
const m = raw.match(/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})$/);
const date = m ? new Date(`${m[1]}T${m[2]}Z`) : new Date(raw);
if (Number.isNaN(date.getTime())) return raw;
return date.toLocaleString([], {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
});
}
const installedSkills = $derived(
skills.filter((s) => s.bindings?.[activeKey]),
);
const editingVersion = $derived(
editorMode === 'edit' && editingDir
? (skills.find((s) => s.dir === editingDir)?.version ?? '')
: '',
);
// Reference agent interface: all task actions continue through existing APIs.
let agentSearch = $state(''),
skillSearch = $state('');
let pinnedAgents = $state<string[]>([]);
let styleOpen = $state(false),
skillOpen = $state(false),
modelOpen = $state(false),
sessionsOpen = $state(false),
workflowOpen = $state(false);
let styleDraft = $state(8),
modelDraft = $state(''),
skillDraft = $state('');
let sendPending = $state(false),
uploadPending = $state(false),
projectPending = $state(false);
let resultOpen = $state(false),
resultText = $state(''),
resultKey = $state('script'),
resultProject = $state<number | null>(null),
resultBusy = $state(false),
resultError = $state('');
const latestAssistant = $derived(
[...messages]
.reverse()
.find((m) => m.role === 'assistant' && m.content?.trim()),
);
let workingText = $state('');
let workingIdentity = $state('');
let workingDrafts = $state<Record<string, string>>({});
try {
workingDrafts = JSON.parse(
sessionStorage.getItem('calliope.agent.workingDrafts') ?? '{}',
);
} catch {
// Unavailable or malformed session storage leaves the initial in-memory drafts intact.
}
$effect(() => {
const id = latestAssistant
? String(activeId) + ':' + latestAssistant.id
: '';
const content = latestAssistant?.content ?? '';
untrack(() => {
if (id === workingIdentity) return;
if (workingIdentity)
workingDrafts = { ...workingDrafts, [workingIdentity]: workingText };
workingIdentity = id;
workingText = workingDrafts[id] ?? content;
});
});
function updateWorking(text: string) {
workingText = text;
if (workingIdentity)
workingDrafts = { ...workingDrafts, [workingIdentity]: text };
try {
sessionStorage.setItem(
'calliope.agent.workingDrafts',
JSON.stringify(workingDrafts),
);
} catch {
// Storage quota/access failures do not discard the working in-memory draft.
}
}
let agentFile = $state<HTMLInputElement>(null!);
let agentPrompt = $state<HTMLTextAreaElement>(null!);
let agentPreferences = $state<
Record<
string,
{
style: number;
skill: string;
workflow: number | null;
project: number | null;
}
>
>({});
let agentDrafts = $state<Record<string, string>>({});
let agentAttachments = $state<Record<string, AgentAttachment[]>>({});
let compositionIdentity = $state('');
const compositionCache = new SvelteMap<
string,
{ text: string; files: AgentAttachment[] }
>();
try {
for (const [key, value] of Object.entries(
JSON.parse(sessionStorage.getItem('calliope.agent.compositions') ?? '{}'),
))
compositionCache.set(
key,
value as { text: string; files: AgentAttachment[] },
);
} catch {
// Unavailable or malformed session storage leaves the in-memory composition cache intact.
}
$effect(() => {
const key = activeKey,
sid = activeId;
const identity = key + ':' + (sid ?? 'new');
untrack(() => {
if (compositionIdentity === identity) return;
if (compositionIdentity) {
const previousKey = compositionIdentity.split(':')[0];
compositionCache.set(compositionIdentity, {
text: draft,
files: $state.snapshot(agentAttachments[previousKey] ?? []),
});
}
compositionIdentity = identity;
const cached = compositionCache.get(identity);
draft = cached?.text ?? '';
agentAttachments = { ...agentAttachments, [key]: cached?.files ?? [] };
});
});
$effect(() => {
const text = draft,
files = attachments,
identity = compositionIdentity;
if (!identity) return;
untrack(() => {
compositionCache.set(identity, { text, files: $state.snapshot(files) });
try {
sessionStorage.setItem(
'calliope.agent.compositions',
JSON.stringify(Object.fromEntries(compositionCache)),
);
} catch {
// Persistence is best effort; the in-memory composition remains available.
}
});
});
const uploadManager = createUploadManager();
const theme = $derived(agentThemes[activeKey] ?? agentThemes.script);
const agentChoices = $derived(
agents
.filter((a) => (a.name + a.tagline).includes(agentSearch.trim()))
.toSorted(
(a, b) =>
Number(pinnedAgents.includes(b.key)) -
Number(pinnedAgents.includes(a.key)),
),
);
const currentPreference = $derived(
agentPreferences[activeKey] ?? {
style: 8,
skill: '',
workflow: null,
project: null,
},
);
const chosenStyle = $derived(
agentStyles[currentPreference.style] ?? agentStyles[8],
);
const chosenSkill = $derived(
skills.find((s) => s.dir === currentPreference.skill),
);
const applicableSkills = $derived(
skills.filter((s) => s.is_enabled && s.bindings?.[activeKey]),
);
const selectedModel = $derived(
$settingsQuery.data?.llm_profiles.find(
(p) =>
p.id ===
$settingsQuery.data?.agent_llm_assignments?.[
activeAgent?.llm_role ?? ''
],
),
);
const linkableProjectsQuery = createQuery({
queryKey: ['agent-linkable-projects'],
queryFn: agentApi.listLinkableProjects,
});
const agentWorkflowsQuery = createQuery({
queryKey: ['workflows-meta'],
queryFn: workflows.listMeta,
});
const runnableWorkflows = $derived(
($agentWorkflowsQuery.data ?? []).filter(
(w) =>
w.is_enabled &&
!w.needs_mapping &&
!!w.usage &&
(w.kind === 'image' || w.kind === 'video'),
),
);
const chosenWorkflow = $derived(
runnableWorkflows.find((w) => w.id === currentPreference.workflow),
);
const attachments = $derived(agentAttachments[activeKey] ?? []);
function preferencePatch(patch: Partial<typeof currentPreference>) {
agentPreferences = {
...agentPreferences,
[activeKey]: { ...currentPreference, ...patch },
};
storageSet(
'calliope.reference.agentPreferences',
JSON.stringify(agentPreferences),
);
}
onMount(() => {
try {
pinnedAgents = JSON.parse(
storageGet('calliope.reference.agentPins') || '[]',
);
agentPreferences = JSON.parse(
storageGet('calliope.reference.agentPreferences') || '{}',
);
} catch {
// Unavailable or malformed local storage keeps the default agent preferences.
}
});
function pinAgent(key: string) {
pinnedAgents = pinnedAgents.includes(key)
? pinnedAgents.filter((p) => p !== key)
: [...pinnedAgents, key];
storageSet(
'calliope.reference.agentPins',
JSON.stringify(pinnedAgents),
);
}
function openStyles() {
styleDraft = currentPreference.style;
styleOpen = true;
}
function openModels() {
modelDraft =
$settingsQuery.data?.agent_llm_assignments?.[
activeAgent?.llm_role ?? ''
] ?? '';
modelOpen = true;
}
function openSkills() {
skillDraft = currentPreference.skill;
skillSearch = '';
skillOpen = true;
}
function applySkill() {
preferencePatch({ skill: skillDraft });
skillOpen = false;
}
function removeAttachment(path: string) {
agentAttachments = {
...agentAttachments,
[activeKey]: attachments.filter((a) => a.path !== path),
};
}
async function addAgentFiles(e: Event) {
const input = e.currentTarget as HTMLInputElement;
const files = [...(input.files ?? [])];
input.value = '';
if (!files.length) return;
const key = activeKey;
if (attachments.length + files.length > 8) {
toast.error('最多添加 8 份参考材料');
return;
}
uploadPending = true;
try {
for (const file of files) {
const path = await uploadManager.uploadSafe('agent-reference', file);
if (path) {
const kind = file.type.startsWith('image/')
? 'image'
: file.type.startsWith('video/')
? 'video'
: file.type.startsWith('audio/')
? 'audio'
: 'document';
agentAttachments = {
...agentAttachments,
[key]: [
...(agentAttachments[key] ?? []),
{ path, name: file.name, kind },
],
};
}
}
} finally {
uploadPending = false;
}
}
async function stopAgent() {
if (activeId == null) return;
try {
await agentApi.cancel(activeId);
await client.invalidateQueries({ queryKey: ['agent-session', activeId] });
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
}
}
async function changeProject(id: number | null) {
if (projectPending) return;
const key = activeKey,
sid = activeId;
projectPending = true;
try {
if (sid != null) {
await agentApi.patchSession(sid, {
project_id: id,
...(id == null ? { unlink: true } : {}),
});
await client.invalidateQueries({ queryKey: ['agent-session', sid] });
await client.invalidateQueries({ queryKey: ['agents-page-sessions'] });
}
agentPreferences = {
...agentPreferences,
[key]: {
...(agentPreferences[key] ?? {
style: 8,
skill: '',
workflow: null,
project: null,
}),
project: id,
},
};
storageSet(
'calliope.reference.agentPreferences',
JSON.stringify(agentPreferences),
);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
} finally {
projectPending = false;
}
}
function editResult() {
if (!latestAssistant) return;
resultText = workingText || latestAssistant.content;
resultKey = activeKey;
resultProject = sessionProject;
resultError = '';
resultOpen = true;
}
async function saveResult() {
if (resultProject == null) return;
resultBusy = true;
resultError = '';
try {
if (resultKey === 'script') {
if (resultText.trim().length < 30) {
resultError = '故事文稿至少需要 30 字。';
return;
}
await workbenchApi.patchStage(resultProject, 'script', {
content: { text: resultText.trim() },
});
await client.invalidateQueries({
queryKey: ['workbench', resultProject],
});
resultOpen = false;
await goto(resolve(`/workbench/${resultProject}?stage=script`));
} else {
await workbenchApi.saveNote(
resultProject,
resultKey as WorkbenchStageKey,
resultText,
);
await client.invalidateQueries({
queryKey: ['workbench', resultProject],
});
resultOpen = false;
toast.success('已保存到项目的助手建议区,结构化内容仍由你整理并确认。');
await goto(resolve(`/workbench/${resultProject}?stage=${resultKey}`));
}
} catch (err) {
resultError = err instanceof Error ? err.message : String(err);
} finally {
resultBusy = false;
}
}
const sessionProject = $derived(
$sessionQuery.data
? $sessionQuery.data.project_id
: currentPreference.project,
);
function useInspiration() {
draft =
suggestions[0]?.prompt ??
'一个海边的小女孩折了一艘纸船,想让它替自己去看看远方。请整理成一个温暖、有转折的故事。';
agentDrafts = { ...agentDrafts, [activeKey]: draft };
agentPrompt?.focus();
}
</script>
{#snippet skillRow(skill: SkillAdminEntry, detail: string)}
<div class="skill-row" class:disabled={!skill.is_enabled}>
<div class="skill-row-main">
<button
type="button"
class="skill-name"
title={`${skill.dir} · ${skill.description}`}
onclick={() => startEditSkill(skill)}
>
{skillLabel(skill.dir)}
</button>
<span class="skill-tags">
<span class="skill-type">{typeLabel(skill.type)}</span>
<span class="skill-assign">{detail}</span>
</span>
</div>
<div class="skill-row-actions">
<button
type="button"
class="icon-btn"
aria-label={t('agentsPage.edit')}
onclick={() => startEditSkill(skill)}
>
<Icon name="edit" size={14} />
</button>
<Switch
checked={skill.is_enabled}
label={t('agentsPage.toggleSkill')}
onchange={(next) =>
$toggleSkillMutation.mutate({ dir: skill.dir, next })}
/>
</div>
</div>
{/snippet}
{#if legacyRedirect === 'pending'}
<div class="redirecting">{t('agents.opening')}</div>
{:else if legacyRedirect === 'failed'}
<div class="redirecting error" role="alert">{legacyError}</div>
{:else}
<AppShell active="agents" title="智能体工坊" workspace>
<div class="reference-agents">
<aside class="agent-rail" aria-label="智能体列表">
<header>
<div>
<strong>智能体工坊</strong><small>让创作助手,陪你完成想法</small>
</div>
</header>
<div class="agent-finder">
<input
type="search"
aria-label="搜索智能体"
placeholder="搜索智能体或用途…"
bind:value={agentSearch}
/>
</div>
<p class="agent-list-meta">创作助手 · 可以置顶常用项</p>
<div class="agent-list">
{#each agentChoices as agent (agent.key)}<div
class="agent-entry reference-option"
use:spotlight
class:selected={agent.key === activeKey}
style:--agent-color={agentThemes[agent.key]?.color ?? '#a78bfa'}
>
<button
class="agent-row"
aria-pressed={agent.key === activeKey}
disabled={sendPending || uploadPending || projectPending}
onclick={() => selectAgent(agent.key)}
><span class="avatar">{agent.char}</span><span
class="agent-meta"
><b>{agent.name}</b><small
>{agentThemes[agent.key]?.hint ?? agent.tagline}</small
>{#if busyByAgent[agent.key]}<small class="replying"
>● 正在创作</small
>{/if}</span
></button
><button
class="agent-pin"
class:pinned={pinnedAgents.includes(agent.key)}
aria-pressed={pinnedAgents.includes(agent.key)}
aria-label={(pinnedAgents.includes(agent.key)
? '取消置顶'
: '置顶') + agent.name}
onclick={() => pinAgent(agent.key)}>⌖</button
>
</div>{/each}
{#if !agentChoices.length}<p class="empty-rail">
没有找到这个智能体
</p>{/if}
</div>
<footer>
<button onclick={openDrawer}>♧ 技能库与自定义技能 →</button><small
>{skills.length} 个技能 · {skills.filter((s) => s.is_enabled)
.length} 个启用</small
>
</footer>
</aside>
<section class="agent-stage" aria-label="智能体创作">
<div class="agent-scene" aria-hidden="true">
<img
src="/reference-agent/story-hero.webp"
alt=""
style:filter={'hue-rotate(' + theme.hue + 'deg)'}
/>
</div>
<header class="agent-toolbar">
<button
class="a-btn gold sm"
disabled={sendPending || uploadPending || projectPending}
onclick={() => (sessionsOpen = true)}>◷ 对话记录</button
>
<div class="grow"></div>
<button
class="a-btn secondary sm"
disabled={sendPending || uploadPending || projectPending}
onclick={newSession}>+ 新任务</button
><button class="a-btn secondary sm" onclick={openDrawer}
>智能体设置</button
>{#if messages.length}<button
class="a-btn ghost sm"
onclick={exportMarkdown}>导出对话</button
><button
class="a-btn ghost sm"
disabled={running ||
sendPending ||
uploadPending ||
projectPending}
onclick={() => (clearOpen = true)}>清空</button
>{/if}
</header>
<div
class="agent-content"
class:conversation={messages.length > 0 || running}
>
{#if $agentsQuery.isLoading}<p class="agent-error">
正在载入智能体…
</p>{:else if $agentsQuery.isError}<p
class="agent-error"
role="alert"
>
智能体列表读取失败。<button
class="a-btn secondary sm"
onclick={() => $agentsQuery.refetch()}>重试</button
>
</p>{:else if activeAgent}
{#if !messages.length && !running}<div class="agent-intro">
<div class="agent-kicker">
● AI {activeAgent.name} · 创作助手
</div>
<h1>{theme.title}</h1>
<p>
{activeAgent.tagline} · 选择技能与工具,与智能体一起打磨创作。
</p>
<div class="inspiration-options">
<button onclick={useInspiration}>从一个故事灵感开始 →</button
><button onclick={openSkills}>选择专业技能 →</button><button
onclick={openStyles}>找一个视觉方向 →</button
>
</div>
</div>{/if}
{#if messages.length || running}<div class="agent-dialogue">
<section class="agent-conversation">
<header>
<div>
<span>AI {activeAgent.name}</span>
<h2>{$sessionQuery.data?.title ?? '这次创作'}</h2>
</div>
<span class="session-status"
>{running ? '● 正在创作' : '等待你的下一步'}</span
>{#if sessionProject}<a
class="a-btn secondary sm"
href={resolve(`/workbench/${sessionProject}`)}>回到项目 ↗</a
>{/if}
</header>
{#if $sessionQuery.data?.plan}<AgentPlanPanel
plan={$sessionQuery.data.plan}
/>{/if}
<div class="chat-body">
<AgentChat
{messages}
{liveTools}
{streaming}
{streamingReasoning}
running={running === true}
{suggestions}
loading={activeId != null &&
$sessionQuery.isFetching &&
!messages.length}
onSuggestion={(p) => (draft = p)}
onAnswer={handleAnswer}
/>
</div>
</section>
<aside class="agent-artifact" aria-label="可编辑创作成果">
<header>
<span>创作成果</span><small
>{latestAssistant ? '可编辑草稿' : '等待助手回复'}</small
>
</header>
{#if latestAssistant}
<textarea
id="agent-working-draft"
aria-label="编辑创作成果"
value={workingText}
oninput={(e) => updateWorking(e.currentTarget.value)}
disabled={running}
></textarea>
<footer>
<small>修改保存在当前会话中,带回项目后仍需确认。</small
><button
class="a-btn purple sm"
disabled={running}
onclick={editResult}>带回项目 ↗</button
>
</footer>
{:else}<p>回复完成后,可以在这里编辑并带回项目。</p>{/if}
</aside>
</div>{/if}
<section class="agent-composer" aria-label="智能体任务输入">
<textarea
bind:this={agentPrompt}
aria-label="智能体任务内容"
maxlength="20000"
placeholder="从这里开始讲故事……一段话、一个角色,或一个你想拍下来的瞬间。"
value={draft}
oninput={(e) => {
draft = e.currentTarget.value;
agentDrafts = { ...agentDrafts, [activeKey]: draft };
}}
onkeydown={onKeydown}
disabled={running ||
sendPending ||
uploadPending ||
projectPending}
></textarea>
<div class="agent-input-info">
<button
onclick={useInspiration}
disabled={running ||
sendPending ||
uploadPending ||
projectPending}>♧ 没有头绪?看看创作灵感</button
><small>{draft.length} / 20000</small>
</div>
{#if attachments.length}<div class="agent-attachments">
{#each attachments as a (a.path)}<div>
{#if a.kind === 'image'}<img
src={assetUrl(a.path)}
alt={a.name}
/>{/if}<span>{a.name}</span><button
disabled={running ||
sendPending ||
uploadPending ||
projectPending}
aria-label={'移除' + a.name}
onclick={() => removeAttachment(a.path)}>×</button
>
</div>{/each}
</div>{/if}
<div class="agent-controls">
<button class="agent-option" onclick={openStyles}
><img
src={'/reference-agent/' + chosenStyle.image}
alt=""
/>{chosenStyle.name}</button
><label class="project-option"
><Icon name="folder" size={13} /><select
aria-label="智能体关联项目"
value={sessionProject ?? ''}
disabled={running || sendPending || projectPending}
onchange={(e) =>
changeProject(
e.currentTarget.value
? Number(e.currentTarget.value)
: null,
)}
><option value="">不关联项目</option
>{#each $linkableProjectsQuery.data ?? [] as project (project.id)}<option
value={project.id}>{project.title}</option
>{/each}</select
></label
><button
class="agent-option"
onclick={() => (workflowOpen = true)}
>◇ {chosenWorkflow?.name ?? '引用工作流'}⌄</button
><button class="agent-option" onclick={openSkills}
>♧ {chosenSkill
? skillLabel(chosenSkill.dir)
: '选择技能'}</button
>
<div class="agent-submit-row">
<button class="agent-option" onclick={openModels}
>✦ {selectedModel?.name ?? '默认大模型'}⌄</button
><button
class="agent-option"
disabled={running || sendPending || uploadPending}
onclick={() => agentFile.click()}
>+ {uploadPending ? '正在上传…' : '参考材料'}</button
><small>Ctrl + Enter 发送 · Enter 换行</small
>{#if running}<button
class="a-btn secondary"
onclick={stopAgent}
><Icon name="stop" size={14} />停止创作</button
>{:else}<button
class="agent-send"
disabled={sendPending ||
uploadPending ||
projectPending ||
$assignMutation.isPending ||
!draft.trim()}
onclick={handleSend}
>{sendPending ? '正在提交…' : '开始创作'} ↗</button
>{/if}
</div>
</div>
<input
bind:this={agentFile}
type="file"
accept="image/*,video/*,audio/*,.txt,.md,.docx"
multiple
hidden
onchange={addAgentFiles}
/>
</section>
{/if}
</div>
</section>
</div>
</AppShell>
<Modal bind:open={styleOpen} size="xl" title="视觉风格"
>{#snippet footer()}<div class="dialog-actions">
<small>选定画风会加入这次任务要求</small><button
class="a-btn secondary"
onclick={() => (styleOpen = false)}>取消</button
><button
class="a-btn purple"
onclick={() => {
preferencePatch({ style: styleDraft });
styleOpen = false;
}}>应用风格</button
>
</div>{/snippet}
<div class="style-grid">
{#each agentStyles as style, i (style.name)}<button
class="style-card"
class:selected={styleDraft === i}
aria-pressed={styleDraft === i}
onclick={() => (styleDraft = i)}
><img src={'/reference-agent/' + style.image} alt={style.name} /><span
>{style.name}</span
></button
>{/each}
</div></Modal
>
<Modal bind:open={skillOpen} size="lg" title="选择本次技能"
>{#snippet footer()}<div class="dialog-actions">
<small>由智能体按技能指导完成任务</small><button
class="a-btn secondary"
onclick={() => (skillOpen = false)}>取消</button
><button class="a-btn purple" onclick={applySkill}>应用技能</button>
</div>{/snippet}
<div class="skill-search">
<input
class="a-input"
bind:value={skillSearch}
aria-label="搜索技能"
placeholder="搜索技能或用途…"
/><button
class="a-btn secondary"
onclick={() => {
skillOpen = false;
startAddSkill();
}}>+ 自定义技能</button
>
</div>
<button
class="skill-choice"
class:selected={!skillDraft}
aria-pressed={!skillDraft}
onclick={() => (skillDraft = '')}
><b>自由发挥</b><small>本次不指定额外技能。</small></button
>{#each applicableSkills.filter((s) => (skillLabel(s.dir) + s.description)
.toLowerCase()
.includes(skillSearch.toLowerCase())) as skill (skill.dir)}<button
class="skill-choice"
class:selected={skillDraft === skill.dir}
aria-pressed={skillDraft === skill.dir}
onclick={() => (skillDraft = skill.dir)}
><b>♧ {skillLabel(skill.dir)}</b><small>{skill.description}</small
></button
>{/each}{#if !applicableSkills.length}<p class="empty-skills">
这个智能体还没有启用技能。可从技能管理中绑定已有技能,或新增技能。
</p>{/if}</Modal
>
<Modal bind:open={modelOpen} size="lg" title="选择大模型"
>{#snippet footer()}<div class="dialog-actions">
<small>只修改当前智能体的模型绑定</small><button
class="a-btn secondary"
onclick={() => (modelOpen = false)}>取消</button
><button
class="a-btn purple"
disabled={$assignMutation.isPending}
onclick={() => {
if (activeAgent) setAgentModel(activeAgent.llm_role, modelDraft);
modelOpen = false;
}}>应用模型</button
>
</div>{/snippet}<button
class="model-choice"
class:selected={!modelDraft}
aria-pressed={!modelDraft}
onclick={() => (modelDraft = '')}
><b>✦ 默认大模型</b><small>使用项目设置中的默认模型连接。</small></button
>{#each $settingsQuery.data?.llm_profiles ?? [] as model (model.id)}<button
class="model-choice"
class:selected={modelDraft === model.id}
aria-pressed={modelDraft === model.id}
onclick={() => (modelDraft = model.id)}
><b>✦ {model.name}</b><small>{model.model}</small></button
>{/each}<a class="model-config-link" href={resolve('/models')}>管理模型与连接 ↗</a
></Modal
>
<Modal bind:open={workflowOpen} size="lg" title="引用工作流"
><p class="empty-skills">
用于整理提示词和输入要求,实际图片/视频生成在创作台进行。
</p>
<button
class="model-choice"
onclick={() => {
preferencePatch({ workflow: null });
workflowOpen = false;
}}>不指定工作流</button
>{#each runnableWorkflows as wf (wf.id)}<button
class="model-choice"
class:selected={currentPreference.workflow === wf.id}
onclick={() => {
preferencePatch({ workflow: wf.id });
workflowOpen = false;
}}
><b>{wf.name}</b><small
>{wf.kind === 'image' ? '图片' : '视频'} · {wf.description ??
''}</small
></button
>{/each}<a class="model-config-link" href={resolve('/workflows')}>管理工作流 ↗</a
></Modal
>
<Modal bind:open={sessionsOpen} size="lg" title="对话记录"
>{#each activeSessions as session (session.id)}<button
disabled={sendPending || uploadPending || projectPending}
class="model-choice"
onclick={() => {
selectSession(session.id);
sessionsOpen = false;
}}
><b>{session.title}</b><small
>{session.running ? '正在创作' : '打开这次对话'} · {session.updated_at}</small
></button
>{/each}{#if !activeSessions.length}<p class="empty-skills">
这位智能体还没有对话记录。
</p>{/if}</Modal
>
<Modal
open={editorMode !== 'idle' || drawerOpen}
size="xl"
title="智能体设置与技能管理"
onclose={resetEditor}
>
<div class="agent-management-model">
<b>当前模型:{selectedModel?.name ?? '默认大模型'}</b><button
class="a-btn secondary sm"
onclick={() => {
resetEditor();
openModels();
}}>选择模型</button
>
<p>
长期创作规则通过知识、规则或模板技能维护;绑定后会用于这位智能体的任务。
</p>
</div>
<div class="all-skill-library">
<div class="lib-head">
<b>技能库</b><button class="a-btn purple sm" onclick={startAddSkill}
>+ 自定义技能</button
>
</div>
{#each skills as skill (skill.dir)}{@render skillRow(
skill,
t('agentsPage.assigned', { n: skill.assigned_count }),
)}{/each}
</div>
<aside
class="right reference-skills-editor"
class:open={editorMode !== 'idle' || drawerOpen}
aria-label={t('agentsPage.skillManage')}
>
<div class="right-head">
<p class="col-title">
{activeAgent
? t('agentsPage.installedTitle', { name: activeAgent.name })
: t('agentsPage.skillManage')}
</p>
<span class="col-hint">
{t('agentsPage.installedCount', {
n: installedSkills.length,
m: installedSkills.filter((s) => s.is_enabled).length,
})}
</span>
<div class="right-head-actions">
{#if editorMode === 'edit' && editingDir}
<button
type="button"
class="link-btn"
onclick={() => loadVersions(editingDir!)}
>
<Icon name="clock" size={13} />
{t('agentsPage.versions')}
</button>
{/if}
{#if editorMode !== 'idle' || drawerOpen}
<button
type="button"
class="icon-btn"
aria-label={t('agentsPage.close')}
onclick={resetEditor}
>
<Icon name="close" size={16} />
</button>
{/if}
</div>
</div>
{#if versionsOpen && editingDir}
<div class="versions" transition:fade={{ duration: 200 }}>
<p class="versions-title">{t('agentsPage.versions')}</p>
{#if !versions.length}
<p class="lib-empty">{t('agentsPage.versionsEmpty')}</p>
{/if}
{#each versions as v (v.id)}
<div class="version-row">
<div class="version-meta">
<span class="mono">#{v.id}</span>
<span class="version-time">{formatUtcString(v.created_at)}</span
>
<span class="version-len mono">{v.length}B</span>
</div>
<button
type="button"
class="a-btn secondary xs"
disabled={$restoreMutation.isPending}
onclick={() =>
$restoreMutation.mutate({ dir: editingDir!, id: v.id })}
>
{t('agentsPage.restore')}
</button>
</div>
{/each}
</div>
{/if}
{#if editorMode === 'idle'}
<div class="form-idle">
<Icon name="sparkle" size={20} />
<p>{t('agentsPage.skillIdleHint')}</p>
</div>
{:else}
<div class="editor" class:editing={editorMode === 'edit'}>
<div class="form-head">
<h3>
{editorMode === 'add'
? t('agentsPage.newSkill')
: t('agentsPage.editSkill')}
</h3>
{#if editorMode === 'edit' && editingVersion}
<span class="ver-chip mono">v{editingVersion}</span>
{/if}
</div>
<label class="f-field">
<span class="f-label">{t('agentsPage.skillName')}<em>*</em></span>
<input
class="f-input"
class:invalid={showSkillErrors && skillErrors.name}
value={form.name}
disabled={editorMode === 'edit'}
oninput={(e) => (form.name = e.currentTarget.value)}
placeholder={t('agentsPage.skillNamePh')}
/>
{#if showSkillErrors && skillErrors.name}
<span class="f-error">{skillErrors.name}</span>
{/if}
</label>
<div class="f-field">
<span class="f-label">{t('agentsPage.skillType')}</span>
<div
class="seg"
role="radiogroup"
aria-label={t('agentsPage.skillType')}
>
{#each ['template', 'knowledge', 'rules'] as tp (tp)}
<button
type="button"
class="seg-item"
class:selected={form.type === tp}
role="radio"
aria-checked={form.type === tp}
onclick={() => (form.type = tp)}
>
{typeLabel(tp)}
</button>
{/each}
</div>
</div>
<label class="f-field">
<span class="f-label">{t('agentsPage.skillDesc')}</span>
<input
class="f-input"
value={form.desc}
oninput={(e) => (form.desc = e.currentTarget.value)}
placeholder={t('agentsPage.skillDescPh')}
/>
</label>
<label class="f-field">
<span class="f-label">{t('agentsPage.skillContent')}</span>
<textarea
rows="8"
class="f-input content"
value={form.content}
oninput={(e) => (form.content = e.currentTarget.value)}
placeholder={t('agentsPage.skillContentPh')}
></textarea>
<span class="f-hint">{t('agentsPage.skillContentHint')}</span>
</label>
<div class="f-field">
<span class="f-label">{t('agentsPage.assignTo')}</span>
<div class="capsules">
{#each agents as agent (agent.key)}
<button
type="button"
class="capsule"
class:on={formBindings[agent.key] === true}
onclick={() =>
(formBindings = {
...formBindings,
[agent.key]: !(formBindings[agent.key] === true),
})}
>
{agent.name}
</button>
{/each}
</div>
{#if showSkillErrors && skillErrors.bindings}
<span class="f-error">{skillErrors.bindings}</span>
{/if}
</div>
<div class="editor-actions">
<Button
variant="primary"
size="sm"
loading={$saveSkillMutation.isPending}
onclick={submitSkill}
>
{#if editorMode === 'edit' && editingVersion}
{t('agentsPage.saveNext', { v: editingVersion })}
{:else}
{t('agentsPage.save')}
{/if}
</Button>
{#if editorMode === 'edit'}
<Button
variant="secondary"
size="sm"
onclick={() => {
if (editingDir)
$toggleSkillMutation.mutate({
dir: editingDir,
next: !(
skills.find((s) => s.dir === editingDir)?.is_enabled ??
true
),
});
}}
>
{skills.find((s) => s.dir === editingDir)?.is_enabled === false
? t('agentsPage.enable')
: t('agentsPage.disable')}
</Button>
<button
type="button"
class="link-danger"
onclick={() => {
deleteSkillTarget =
skills.find((s) => s.dir === editingDir) ?? null;
deleteSkillOpen = true;
}}
>
{t('agentsPage.delete')}
</button>
{/if}
</div>
</div>
{/if}
</aside>
</Modal>
<Modal
bind:open={resultOpen}
dismissible={!resultBusy}
size="lg"
title="编辑创作内容"
>{#snippet footer()}<div class="dialog-actions">
<button
class="a-btn secondary"
disabled={resultBusy}
onclick={() => (resultOpen = false)}>取消</button
><button
class="a-btn purple"
disabled={resultBusy || resultProject == null}
onclick={saveResult}
>{resultBusy
? '正在保存…'
: resultKey === 'script'
? '保存到项目草稿'
: '保存建议并打开项目'}</button
>
</div>{/snippet}<label class="result-project-label"
>带回哪个项目<select
class="a-select"
bind:value={resultProject}
disabled={resultBusy}
><option value={null}>请选择项目</option
>{#each $linkableProjectsQuery.data ?? [] as project (project.id)}<option
value={project.id}>{project.title}</option
>{/each}</select
></label
><textarea
class="a-input agent-result-editor"
id="agent-result-editor"
aria-label="编辑智能体创作内容"
bind:value={resultText}
readonly={resultBusy}
></textarea>
<p class="empty-skills">
{resultKey === 'script'
? '保存为故事构思阶段的待确认草稿,不会直接确认或覆盖已确认版本。'
: '内容会保存到这个阶段的助手建议区;镜头、风格和素材等字段仍由你整理并确认。'}
</p>
{#if resultError}<p class="result-error" role="alert">
{resultError}
</p>{/if}</Modal
>
<ConfirmDialog
bind:open={clearOpen}
title={t('agentsPage.clearTitle')}
message={t('agentsPage.clearConfirm', { name: activeAgent?.name ?? '' })}
confirmLabel={t('agentsPage.clear')}
danger
onconfirm={() => $clearMutation.mutate()}
oncancel={() => (clearOpen = false)}
/>
<ConfirmDialog
bind:open={deleteSkillOpen}
title={t('agentsPage.delSkillTitle')}
message={t('agentsPage.delSkillConfirm', {
n: deleteSkillTarget?.assigned_count ?? 0,
})}
confirmLabel={t('agentsPage.delete')}
danger
onconfirm={() =>
deleteSkillTarget && $deleteSkillMutation.mutate(deleteSkillTarget.dir)}
oncancel={() => (deleteSkillTarget = null)}
/>
{/if}
<style>
.redirecting {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
color: var(--text-2);
font-size: 14px;
}
.redirecting.error {
color: var(--error);
}
/* ── 左栏 ─────────────────────────────────────────────── */
.col-title {
font-size: 14.5px;
font-weight: 600;
color: var(--text);
margin: 0;
}
.col-hint {
font-size: 11px;
color: var(--text-3);
white-space: nowrap;
}
.agent-list {
display: flex;
flex-direction: column;
gap: 6px;
}
.agent-row {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
padding: 8px 10px;
border-radius: 10px;
border: 1px solid transparent;
background: transparent;
cursor: pointer;
text-align: left;
transition:
background-color 150ms cubic-bezier(0.16, 1, 0.3, 1),
border-color 150ms;
}
.agent-row:hover {
background: var(--surface-2);
}
.avatar {
width: 34px;
height: 34px;
border-radius: 9px;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 14px;
font-weight: 700;
color: var(--text);
flex-shrink: 0;
}
.agent-meta {
display: flex;
flex-direction: column;
gap: 1px;
min-width: 0;
flex: 1;
}
.lib-head {
display: flex;
align-items: center;
gap: 8px;
margin-top: 6px;
}
.lib-head .a-btn {
margin-left: auto;
}
.lib-empty {
font-size: 11.5px;
color: var(--text-3);
padding: 10px 4px;
margin: 0;
}
/* Skill 行(§3.6):启用 = --run 描边 + 软底;停用 = --text-3 描边。 */
.skill-row {
display: flex;
align-items: center;
gap: 8px;
padding: 7px 8px;
border-radius: var(--r-md);
border: 1px solid color-mix(in srgb, var(--run) 45%, transparent);
background: var(--run-soft);
}
.skill-row.disabled {
border-color: color-mix(in srgb, var(--text-3) 45%, transparent);
background: var(--bg-2);
opacity: 0.75;
}
.skill-row-main {
display: flex;
flex-direction: column;
gap: 3px;
min-width: 0;
flex: 1;
}
.skill-name {
font-size: 12px;
font-weight: 600;
color: var(--text);
background: none;
border: none;
padding: 0;
cursor: pointer;
text-align: left;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.skill-name:hover {
color: var(--text);
}
.skill-tags {
display: flex;
gap: 6px;
align-items: center;
}
.skill-type {
font-size: 10px;
padding: 1px 7px;
border-radius: 999px;
background: var(--surface-3);
color: var(--text-2);
white-space: nowrap;
}
.skill-assign {
font-size: 10px;
color: var(--text-3);
white-space: nowrap;
}
.skill-row-actions {
display: flex;
align-items: center;
gap: 6px;
flex-shrink: 0;
}
/* ── 中栏 ─────────────────────────────────────────────── */
.chat-body {
flex: 1;
min-height: 0;
overflow: hidden;
display: flex;
flex-direction: column;
padding: 10px 14px;
}
/* ── 右栏 ─────────────────────────────────────────────── */
.right {
width: 372px;
flex-shrink: 0;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 12px;
padding: 14px;
overflow-y: auto;
min-height: 0;
display: flex;
flex-direction: column;
gap: 12px;
}
.right-head {
display: flex;
align-items: center;
gap: 8px;
}
.right-head-actions {
display: flex;
align-items: center;
gap: 6px;
margin-left: auto;
}
.link-btn {
display: inline-flex;
align-items: center;
gap: 5px;
background: none;
border: none;
color: var(--text-2);
font-size: 11.5px;
cursor: pointer;
padding: 2px 4px;
}
.link-btn:hover {
color: var(--text);
text-decoration: underline;
text-underline-offset: 3px;
}
.versions {
border: 1px solid var(--border);
border-radius: 10px;
padding: 10px;
display: flex;
flex-direction: column;
gap: 6px;
background: var(--surface-2);
}
.versions-title {
margin: 0 0 2px;
font-size: 11.5px;
font-weight: 600;
color: var(--text-2);
}
.version-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
font-size: 11px;
color: var(--text-2);
}
.version-meta {
display: flex;
gap: 8px;
align-items: center;
min-width: 0;
}
.version-time {
color: var(--text-3);
white-space: nowrap;
}
.version-len {
color: var(--text-3);
}
.form-idle {
margin: auto;
text-align: center;
color: var(--text-3);
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
padding: 32px 12px;
font-size: 12px;
}
.editor {
display: flex;
flex-direction: column;
gap: 12px;
border: 1px solid var(--accent-glow);
border-radius: 10px;
padding: 12px;
background: var(--surface-2);
}
.form-head {
display: flex;
align-items: center;
gap: 8px;
}
.form-head h3 {
margin: 0;
font-size: 13px;
font-weight: 700;
color: var(--text);
}
.ver-chip {
padding: 1px 8px;
border-radius: 999px;
background: var(--accent-dim);
color: var(--accent);
font-size: 10.5px;
}
.f-field {
display: flex;
flex-direction: column;
gap: 5px;
}
.f-label {
font-size: 11.5px;
font-weight: 600;
color: var(--text-2);
}
.f-label em {
color: var(--err);
font-style: normal;
margin-left: 2px;
}
.f-input {
box-sizing: border-box;
width: 100%;
background: var(--bg);
border: 1px solid var(--border-strong);
border-radius: 8px;
padding: 8px 10px;
color: var(--text);
font-family: inherit;
font-size: 12.5px;
}
.f-input:focus-visible {
outline: none;
border-color: var(--accent);
}
.f-input.invalid {
border-color: var(--error);
}
.f-input.content {
resize: vertical;
min-height: 150px;
line-height: 1.55;
}
.f-input::placeholder {
color: var(--text-3);
}
.f-error {
font-size: 11px;
color: var(--error);
}
.f-hint {
font-size: 10.5px;
color: var(--text-3);
}
.seg {
display: inline-flex;
border: 1px solid var(--border-strong);
border-radius: 8px;
overflow: hidden;
}
.seg-item {
padding: 6px 10px;
background: var(--surface-3);
border: none;
color: var(--text-2);
font-size: 11.5px;
cursor: pointer;
}
.seg-item.selected {
background: var(--accent-dim);
color: var(--accent);
font-weight: 600;
}
.seg-item + .seg-item {
border-left: 1px solid var(--border-strong);
}
.capsules {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.capsule {
padding: 4px 11px;
border-radius: 999px;
border: 1px solid var(--border-strong);
background: var(--surface-3);
color: var(--text-2);
font-size: 11.5px;
cursor: pointer;
transition: all 150ms;
}
.capsule.on {
border-color: var(--accent);
color: var(--accent);
background: var(--accent-dim);
}
.editor-actions {
display: flex;
align-items: center;
gap: 8px;
margin-top: 2px;
}
.editor-actions .link-danger {
margin-left: auto;
}
.icon-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 26px;
height: 26px;
border-radius: 7px;
border: none;
background: transparent;
color: var(--text-2);
cursor: pointer;
}
.icon-btn:hover {
background: var(--surface-3);
color: var(--text);
}
.link-danger {
background: none;
border: none;
color: var(--error);
font-size: 12px;
cursor: pointer;
padding: 4px 6px;
}
.link-danger:hover {
text-decoration: underline;
}
@keyframes breathe {
0%,
100% {
opacity: 1;
box-shadow: 0 0 0 0 var(--accent-dim);
}
50% {
opacity: 0.45;
box-shadow: 0 0 0 4px var(--accent-dim);
}
}
/* ── 窄屏(1024–1439px):右栏收为抽屉(spec §4.5)────── */
@media (max-width: 1439px) {
.right {
position: fixed;
top: 0;
right: 0;
bottom: 0;
width: min(372px, 92vw);
z-index: 60;
border-radius: 12px 0 0 12px;
transform: translateX(calc(100% + 18px));
transition: transform 240ms cubic-bezier(0.16, 1, 0.3, 1);
box-shadow: var(--shadow-float);
}
.right.open {
transform: translateX(0);
}
}
@media (max-width: 1179px) {
}
.agent-list {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 14px;
margin-bottom: 25px;
}
.agent-row {
flex-direction: column;
align-items: flex-start;
padding: 22px 18px;
min-height: 153px;
border: 1px solid var(--line);
border-radius: 13px;
background: var(--surface);
gap: 16px;
}
.agent-row .avatar {
width: 43px;
height: 43px;
border-radius: 11px;
font-size: 23px;
color: var(--text);
}
.agent-meta {
gap: 7px;
}
.right {
width: 280px;
border-radius: 14px;
background: var(--surface);
border: 1px solid var(--line);
}
.lib-head {
flex-wrap: wrap;
}
@media (max-width: 1400px) {
.right {
position: absolute;
right: 0;
top: 0;
bottom: 0;
width: 350px;
box-shadow: var(--shadow-float);
z-index: 30;
display: none;
}
.right.open {
display: flex;
}
}
.reference-agents {
display: flex;
flex: 1;
height: 100%;
min-height: 0;
min-width: 0;
}
.agent-rail {
width: 263px;
min-height: 0;
flex-shrink: 0;
display: flex;
flex-direction: column;
border-right: 1px solid var(--line);
background: linear-gradient(#141419, #0f0f12);
}
.agent-rail > header {
height: 76px;
display: flex;
align-items: center;
gap: 12px;
padding: 14px 17px;
border-bottom: 1px solid var(--line);
background: radial-gradient(at 10% 50%, #7850ff24, transparent 70%);
flex-shrink: 0;
}
.agent-rail header strong {
font-size: 17px;
color: #b99aff;
display: block;
}
.agent-rail header small {
display: block;
color: #7f768d;
font-size: 10px;
margin-top: 2px;
}
.agent-finder {
padding: 18px 12px 8px;
}
.agent-finder input {
width: 100%;
border: 1px solid #f5b04266;
background: #f5b0420d;
border-radius: 8px;
font-size: 11px;
padding: 8px 11px;
color: var(--text);
}
.agent-list-meta {
color: #6f6a7d;
font-size: 10px;
padding: 0 17px;
margin: 5px 0 10px;
}
.agent-list {
display: flex;
flex-direction: column;
gap: 6px;
margin: 0;
padding: 0 11px 8px;
overflow: auto;
flex: 1;
min-height: 0;
scrollbar-width: thin;
}
.agent-entry {
position: relative;
border-radius: 11.25px;
border: 1px solid transparent;
transition:
background-color 180ms ease,
border-color 180ms ease;
flex-shrink: 0;
}
.agent-entry.selected {
background: #ffffff26;
}
.agent-row {
display: flex;
flex-direction: row;
width: 100%;
min-height: 75px;
padding: 13px 9px;
gap: 11px;
border: 0;
border-radius: 11px;
background: none;
text-align: left;
align-items: center;
color: var(--text);
position: relative;
cursor: pointer;
}
.agent-row .avatar {
width: 38px;
height: 38px;
flex-shrink: 0;
display: grid;
place-items: center;
background: color-mix(in srgb, var(--agent-color) 15%, transparent);
border: 1px solid color-mix(in srgb, var(--agent-color) 20%, transparent);
color: var(--agent-color);
font-size: 21px;
border-radius: 9px;
transition: transform 180ms var(--ease-out);
}
.agent-meta {
display: block;
min-width: 0;
flex: 1;
padding-right: 6px;
}
.agent-meta b {
font-size: 12.1875px;
line-height: 1.5;
font-weight: 600;
display: block;
}
.agent-meta small {
display: block;
font-size: 10.3125px;
line-height: 1.5;
color: #ffffff88;
margin-top: 4px;
}
.agent-meta .replying {
color: #f5b042;
font-size: 9px;
}
.agent-pin {
position: absolute;
right: 6px;
top: 7px;
z-index: 2;
border: 1px solid #ffffff22;
background: #111827;
border-radius: 50%;
font-size: 10px;
width: 20px;
height: 20px;
color: #78839a;
opacity: 0;
transition:
opacity 180ms ease,
color 180ms ease,
border-color 180ms ease;
cursor: pointer;
padding: 0;
}
.agent-pin.pinned,
.agent-entry:focus-within .agent-pin,
.agent-entry:hover .agent-pin {
opacity: 1;
}
.agent-pin.pinned {
color: #ffd17c;
border-color: #ffd17c77;
}
.agent-rail > footer {
padding: 15px 14px;
border-top: 1px solid var(--line);
flex-shrink: 0;
}
.agent-rail footer button {
border: 0;
background: none;
color: #b99aff;
font-size: 11px;
cursor: pointer;
padding: 4px 0;
}
.agent-rail footer small {
display: block;
color: #76717f;
font-size: 10px;
line-height: 1.8;
}
.empty-rail {
color: #7f718f;
font-size: 11px;
padding: 12px;
}
.agent-stage {
position: relative;
background: #0b0a10;
flex: 1;
min-width: 0;
min-height: 0;
overflow: auto;
scrollbar-width: thin;
isolation: isolate;
}
.agent-scene {
position: absolute;
right: 0;
top: 45px;
width: min(950px, 95%);
height: 590px;
pointer-events: none;
z-index: -1;
overflow: hidden;
}
.agent-scene img {
width: 100%;
height: 100%;
object-fit: cover;
opacity: 0.78;
mask-image: linear-gradient(to right, transparent, #000 42%);
transition: filter 250ms ease;
}
.agent-scene:after {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(to top, #0b0a10, transparent 43%);
}
.agent-toolbar {
position: sticky;
top: 0;
z-index: 4;
display: flex;
gap: 8px;
align-items: center;
padding: 14px 25px;
background: linear-gradient(#0b0a10ef, #0b0a10cc);
backdrop-filter: blur(12px);
flex-wrap: wrap;
}
.agent-toolbar .grow {
flex: 1;
}
.agent-content {
position: relative;
max-width: 960px;
margin: auto;
padding: 35px 30px 35px;
}
.agent-intro {
min-height: 185px;
padding: 0 0 28px;
}
.agent-kicker {
font-size: 10px;
letter-spacing: 2px;
color: #c7a670;
margin-bottom: 14px;
}
.agent-intro h1 {
font-size: 45.75px;
line-height: 1.22;
font-weight: 700;
letter-spacing: -1px;
margin: 0 0 17px;
color: #fffaf2ed;
max-width: 540px;
text-shadow: 0 5px 24px #0006;
white-space: pre-line;
}
.agent-intro p {
font-size: 12px;
line-height: 1.8;
color: #fffaf299;
max-width: 620px;
margin: 0;
}
.agent-composer {
background: rgba(19, 18, 25, 0.82);
backdrop-filter: blur(18px) saturate(1.4);
border: 1px solid #ffffff26;
border-radius: 17.85px;
padding: 20px 21px 15px;
box-shadow:
0 12px 40px #0009,
0 2px 10px #0006;
position: relative;
transition:
border-color 180ms ease,
box-shadow 250ms var(--ease-out);
}
.agent-composer:before {
content: '';
position: absolute;
left: 20px;
right: 20px;
top: 5px;
height: 5px;
background: radial-gradient(circle, #ffffff20 2px, transparent 2.5px) 0
0/18px 5px;
pointer-events: none;
}
.agent-composer:focus-within {
border-color: #f5b04273;
box-shadow:
0 12px 40px #0009,
0 0 0 1px #f5b04259,
0 8px 28px #f5b0422e;
}
.agent-composer textarea {
display: block;
width: 100%;
min-height: 96px;
max-height: 250px;
resize: vertical;
background: none;
border: 0;
outline: none;
font-size: 13.395px;
line-height: 24.111px;
color: #fffaf2ed;
padding: 8px 0;
}
.agent-composer textarea::placeholder {
color: #88838e;
}
.agent-input-info {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 0 10px;
gap: 12px;
}
.agent-input-info button {
color: #f5b042;
border: 0;
background: none;
font-size: 11px;
cursor: pointer;
padding: 0;
}
.agent-input-info small {
font-size: 9px;
color: #716b78;
}
.agent-controls {
display: flex;
gap: 7px;
align-items: center;
flex-wrap: wrap;
border-top: 1px solid #ffffff0a;
padding-top: 10px;
}
.agent-option,
.project-option {
border: 1px solid #ffffff17;
background: #19171f;
color: #ffffffb3;
border-radius: 8.925px;
padding: 7px 10px;
font-size: 11px;
display: inline-flex;
align-items: center;
gap: 6px;
line-height: 1.3;
max-width: 220px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
transition:
background-color 180ms ease,
border-color 180ms ease,
color 180ms ease,
transform 160ms var(--ease-out);
}
.agent-option {
cursor: pointer;
}
.agent-option img {
width: 18px;
height: 18px;
border-radius: 50%;
object-fit: cover;
}
.project-option select {
color: inherit;
background: none;
border: 0;
outline: none;
font-size: 11px;
max-width: 160px;
}
.project-option select option {
background: #19171f;
}
.agent-submit-row {
width: 100%;
display: flex;
align-items: center;
gap: 8px;
margin-top: 1px;
flex-wrap: wrap;
}
.agent-submit-row > small {
margin-left: auto;
color: #6f6879;
font-size: 9px;
}
.agent-send {
margin-left: auto;
border: 1px solid #f5b042;
background: #f5b042;
color: #241a09;
border-radius: 999px;
font-size: 12px;
padding: 10px 17px;
font-weight: 600;
cursor: pointer;
transition:
transform 160ms var(--ease-out),
background-color 180ms ease,
box-shadow 180ms ease;
}
.agent-send:disabled {
opacity: 0.5;
cursor: default;
}
.agent-send:active,
.agent-option:active {
transform: scale(var(--press-scale));
}
.agent-conversation {
border: 1px solid #ffffff12;
background: #13101aeb;
border-radius: 16px;
overflow: hidden;
margin-bottom: 16px;
}
.agent-conversation > header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 18px 20px;
border-bottom: 1px solid #ffffff0d;
background: linear-gradient(120deg, #b784ff0c, #f5b04208);
}
.agent-conversation > header span {
font-size: 10px;
color: #b784ff;
}
.agent-conversation h2 {
font-size: 18px;
color: #fffaf2ed;
margin: 5px 0;
}
.agent-conversation .session-status {
color: #f5b042;
}
.agent-conversation .chat-body {
height: min(45vh, 530px);
min-height: 240px;
display: flex;
padding: 10px;
}
.agent-conversation :global(.plan-panel) {
margin: 10px 14px;
}
.conversation {
padding-top: 18px;
}
.conversation .agent-composer textarea {
min-height: 70px;
}
.agent-attachments {
display: flex;
gap: 8px;
flex-wrap: wrap;
margin-bottom: 12px;
}
.agent-attachments > div {
display: flex;
align-items: center;
gap: 7px;
font-size: 10px;
background: #ffffff06;
border: 1px solid #ffffff12;
border-radius: 8px;
padding: 5px 8px;
}
.agent-attachments img {
width: 30px;
height: 30px;
object-fit: cover;
border-radius: 5px;
}
.agent-attachments span {
max-width: 150px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.agent-attachments button {
border: 0;
background: none;
color: var(--text-3);
cursor: pointer;
}
.style-grid {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 20px 12px;
}
.style-card {
padding: 0;
background: none;
border: 0;
color: #ffffffa0;
font-size: 11px;
position: relative;
text-align: center;
cursor: pointer;
}
.style-card img {
display: block;
width: 100%;
height: 150px;
object-fit: cover;
border-radius: 10px;
border: 2px solid transparent;
transition:
border-color 180ms ease,
transform 180ms var(--ease-out),
box-shadow 180ms ease;
}
.style-card span {
display: block;
margin-top: 8px;
}
.style-card.selected img {
border-color: #f5b042;
box-shadow: 0 0 0 2px #f5b04226;
}
.style-card.selected {
color: #f5b042;
}
.style-card.selected:after {
content: '✓';
position: absolute;
top: 6px;
right: 6px;
background: #f5b042;
color: #2d210d;
width: 20px;
height: 20px;
border-radius: 50%;
display: grid;
place-items: center;
}
.dialog-actions {
display: flex;
justify-content: flex-end;
align-items: center;
gap: 10px;
}
.dialog-actions small {
margin-right: auto;
font-size: 10px;
color: #7f718f;
}
.dialog-actions .purple {
min-width: 140px;
}
.skill-search {
display: flex;
gap: 8px;
margin-bottom: 15px;
}
.skill-search input {
flex: 1;
min-width: 0;
}
.skill-choice,
.model-choice {
padding: 15px 16px;
margin: 10px 0;
border: 1px solid #ffffff0e;
border-radius: 11px;
background: #ffffff03;
color: #d8cbe8;
display: block;
width: 100%;
text-align: left;
cursor: pointer;
transition:
background-color 180ms ease,
border-color 180ms ease;
}
.skill-choice.selected {
border-color: #f5b04266;
background: #f5b04207;
}
.model-choice.selected {
border-color: #b784ff60;
background: #7850ff0f;
}
.skill-choice b,
.model-choice b {
font-size: 13px;
display: block;
font-weight: 600;
}
.skill-choice small,
.model-choice small {
display: block;
color: #8e839a;
font-size: 11px;
line-height: 1.8;
margin-top: 6px;
}
.model-config-link {
color: #b784ff;
font-size: 11px;
display: block;
margin-top: 18px;
text-decoration: none;
}
.empty-skills,
.agent-error {
color: #9d8ca9;
font-size: 12px;
line-height: 1.8;
}
.reference-skills-editor.right {
position: static !important;
width: 100%;
height: auto;
min-height: 0;
max-height: none;
display: flex !important;
transform: none !important;
border: 0;
background: none;
box-shadow: none;
overflow: visible;
border-radius: 0;
padding: 0;
margin-top: 15px;
}
.reference-skills-editor .right-head {
padding: 10px 0;
border-bottom: 1px solid var(--line);
}
.reference-skills-editor .editor {
padding: 16px 0;
overflow: visible;
}
.reference-skills-editor .editor-actions {
position: sticky;
bottom: -22px;
background: #131219;
padding: 14px 0;
border-top: 1px solid var(--line);
z-index: 1;
}
.all-skill-library {
display: flex;
flex-direction: column;
gap: 7px;
}
.agent-management-model {
padding: 14px;
border: 1px solid #ffffff10;
border-radius: 11px;
background: #ffffff04;
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
font-size: 12px;
}
.agent-management-model p {
width: 100%;
color: #8f7d9e;
font-size: 11px;
margin: 0;
line-height: 1.8;
}
.agent-management-model button {
margin-left: auto;
}
@media (hover: hover) and (pointer: fine) {
.agent-entry:hover {
border-color: #ffffff12;
background-color: #ffffff0a;
}
.agent-entry.selected:hover {
background-color: #ffffff26;
}
.agent-entry:hover .avatar {
transform: scale(1.05);
}
.agent-option:hover {
border-color: #f5b04255;
background: #f5b0420d;
color: #ffe0a5;
}
.agent-send:hover:not(:disabled) {
background: #ffc96a;
box-shadow: 0 4px 18px #f5b04235;
transform: translateY(-1px);
}
.style-card:hover img {
transform: translateY(-2px);
box-shadow: 0 5px 20px #0006;
}
.skill-choice:hover,
.model-choice:hover {
border-color: #b784ff44;
background: #ffffff06;
}
}
@media (max-width: 1200px) {
.agent-rail {
width: 240px;
}
.agent-content {
padding: 25px 24px;
}
.agent-intro h1 {
font-size: 38px;
}
.style-grid {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
}
@media (max-height: 760px) {
.agent-intro {
min-height: 155px;
padding-bottom: 22px;
}
.agent-content {
padding-top: 22px;
}
.agent-intro h1 {
font-size: 38px;
}
.agent-composer textarea {
min-height: 84px;
}
.agent-toolbar {
padding-top: 10px;
padding-bottom: 10px;
}
}
:global(:root[data-reduce='1']) .agent-scene img,
:global(:root[data-reduce='1']) .style-card img {
transition: none;
}
:global(:root[data-reduce='1']) .style-card:hover img,
:global(:root[data-reduce='1']) .agent-entry:hover .avatar {
transform: none;
}
.agent-result-editor {
width: 100%;
min-height: 260px;
resize: vertical;
line-height: 1.9;
font-size: 13px;
}
.result-project-label {
display: flex;
align-items: center;
gap: 15px;
font-size: 12px;
margin-bottom: 15px;
}
.result-project-label select {
flex: 1;
}
.result-error {
color: var(--err);
font-size: 12px;
}
.agent-intro {
animation: agent-arrive var(--d-enter) var(--ease-out) both;
}
.agent-content:not(.conversation) .agent-composer {
animation: agent-arrive var(--d-enter) var(--ease-out) both;
}
@keyframes agent-arrive {
from {
opacity: 0;
transform: translateY(18px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.agent-rail {
width: 232px;
background: #121216;
}
.agent-rail > header {
height: auto;
padding: 21px 18px 16px;
background: none;
}
.agent-rail header strong {
color: var(--text);
font-size: 18px;
}
.agent-rail header small {
font-size: 11px;
color: var(--text-3);
}
.agent-entry {
margin: 2px 0;
}
.agent-entry.selected {
background: linear-gradient(120deg, #a98bff16, #a98bff03);
border-color: #a98bff39;
}
.agent-row {
min-height: 55px;
padding: 10px 8px;
}
.agent-row .avatar {
width: 32px;
height: 32px;
font-size: 14px;
}
.agent-stage {
position: relative;
display: grid;
grid-template-rows: 44px minmax(0, 1fr);
padding: 0 22px 14px;
min-height: 0;
overflow: hidden;
flex: 1;
}
.agent-toolbar {
padding: 0;
position: relative;
z-index: 1;
}
.agent-toolbar :global(.a-btn) {
min-height: 28px;
font-size: 11px;
padding: 4px 8px;
}
.agent-scene {
display: none;
}
.agent-content,
.agent-content.conversation {
display: grid;
grid-template-rows: minmax(0, 1fr) 173px;
padding: 0;
gap: 12px;
overflow: hidden;
height: 100%;
min-height: 0;
max-width: none;
position: relative;
}
.agent-intro {
grid-area: 1/1;
padding: 32px 28px 22px;
margin: 0;
min-height: 0;
isolation: isolate;
text-align: left;
overflow: auto;
border-radius: 14px;
}
.agent-intro::before {
content: '';
position: absolute;
inset: 0 0 0 30%;
z-index: -2;
background: url('/reference-agent/story-hero.webp') right top/cover
no-repeat;
opacity: 0.7;
}
.agent-intro::after {
content: '';
position: absolute;
inset: 0;
z-index: -1;
background:
linear-gradient(90deg, #0f0f12 12%, #0f0f12dd 32%, #0f0f1230 80%),
linear-gradient(0deg, #0f0f12, transparent 40%);
}
.agent-intro h1 {
font-size: clamp(25px, 2.6vw, 40px);
line-height: 1.4;
letter-spacing: -1px;
max-width: 560px;
margin: 14px 0;
}
.agent-intro p {
color: #b4adb9;
font-size: 12px;
max-width: 390px;
line-height: 1.8;
}
.agent-composer {
grid-area: 2/1;
height: 100%;
min-height: 0;
margin: 0;
padding: 10px 14px 6px;
max-width: none;
width: 100%;
box-sizing: border-box;
display: flex;
flex-direction: column;
border-color: #a98bff3d;
background: linear-gradient(120deg, #1b1823, #19171d);
}
.agent-composer textarea {
flex: 1;
min-height: 0;
height: auto;
max-height: none;
resize: none;
font-size: 13px;
padding: 2px;
overflow: auto;
}
.agent-input-info {
margin: 2px 0 4px;
padding: 0;
font-size: 10px;
flex-shrink: 0;
}
.agent-input-info button {
font-size: 10px;
}
.agent-controls {
display: flex;
flex-wrap: nowrap;
gap: 5px;
align-items: center;
border-top: 1px solid var(--line);
padding-top: 6px;
flex-shrink: 0;
margin-top: 0;
}
.agent-option,
.project-option {
font-size: 10px;
padding: 5px 7px;
min-height: 28px;
max-width: 140px;
white-space: nowrap;
}
.agent-option img {
width: 17px;
height: 17px;
}
.project-option select {
font-size: 10px;
max-width: 120px;
}
.agent-submit-row {
display: flex;
flex: 1;
gap: 5px;
justify-content: flex-end;
min-width: 0;
width: auto;
margin: 0;
padding: 0;
border: 0;
}
.agent-submit-row small {
display: none;
}
.agent-send {
min-height: 32px;
padding: 6px 16px;
font-size: 11px;
flex-shrink: 0;
}
.agent-attachments {
display: flex;
gap: 5px;
max-height: 30px;
overflow: auto;
flex-shrink: 0;
margin: 0 0 4px;
}
.agent-attachments img {
width: 22px;
height: 22px;
}
.agent-dialogue {
display: grid;
grid-template-columns: minmax(0, 1fr) 310px;
gap: 14px;
min-height: 0;
overflow: hidden;
}
.agent-conversation {
width: 100%;
max-width: none;
padding: 0;
margin: 0;
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.agent-conversation > header {
height: 52px;
flex-shrink: 0;
padding: 8px 12px;
}
.chat-body {
flex: 1;
min-height: 0;
overflow: auto;
}
.agent-artifact {
display: flex;
flex-direction: column;
min-height: 0;
border: 1px solid #a98bff25;
border-radius: 12px;
background: #18171e;
overflow: hidden;
}
.agent-artifact header {
display: flex;
justify-content: space-between;
gap: 8px;
padding: 12px 14px;
border-bottom: 1px solid var(--line);
font-size: 12px;
}
.agent-artifact header small,
.agent-artifact footer small,
.agent-artifact p {
color: var(--text-3);
font-size: 10px;
}
.agent-artifact textarea {
flex: 1;
min-height: 0;
border: 0;
background: none;
padding: 16px;
color: var(--text-2);
font-size: 12px;
line-height: 1.8;
resize: none;
outline: 0;
}
.agent-artifact textarea:focus {
background: #a98bff04;
}
.agent-artifact footer {
padding: 10px 12px;
border-top: 1px solid var(--line);
display: flex;
flex-direction: column;
gap: 8px;
}
.agent-artifact p {
padding: 20px;
}
@media (max-width: 1200px) {
.agent-rail {
width: 210px;
}
.agent-dialogue {
grid-template-columns: minmax(0, 1fr) 260px;
}
.agent-stage {
padding: 0 14px 12px;
}
.agent-controls {
flex-wrap: wrap;
}
.agent-option,
.project-option {
max-width: 135px;
}
}
@media (max-height: 740px) {
.agent-content,
.agent-content.conversation {
grid-template-rows: minmax(0, 1fr) 160px;
}
.agent-intro {
padding: 22px;
}
}
.inspiration-options {
display: flex;
gap: 10px;
margin-top: 28px;
flex-wrap: wrap;
max-width: 600px;
}
.inspiration-options button {
background: #16141bc9;
border: 1px solid #ffffff15;
border-radius: 9px;
padding: 12px 14px;
color: var(--text-2);
font-size: 11px;
cursor: pointer;
}
.agent-content,
.agent-content.conversation {
width: 100%;
max-width: none;
margin: 0;
align-items: stretch;
justify-items: stretch;
}
.agent-intro {
width: auto;
max-width: none;
box-sizing: border-box;
}
.agent-stage {
inset: auto;
position: relative;
}
.reference-agents {
height: 100%;
}
.agent-composer::before {
display: none;
}
</style>