Files
aigc-home/calliope-web/src/lib/components/agent/AgentChat.svelte
T
2026-10-23 18:46:06 +08:00

701 lines
22 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 type { AgentMessage, Job } from '$lib/api';
import { assetUrl } from '$lib/api';
import type { WorkflowMention } from '$lib/agentComposer';
import AgentToolCard from './AgentToolCard.svelte';
import AgentArtifactCard, { type ArtifactJob } from './AgentArtifactCard.svelte';
import ReasoningPanel from './ReasoningPanel.svelte';
import { agentColor, agentDisplayName } from './agentPalette';
import Icon from '$lib/components/ui/Icon.svelte';
import { t } from '$lib/i18n.svelte';
interface Props {
studio?: boolean;
messages: AgentMessage[];
/** In-flight tool calls for the current turn (from agent.tool SSE). */
liveTools: { tool: string; args?: Record<string, unknown> | null; result?: unknown; phase: 'running' | 'done' | 'error' }[];
/** Streaming assistant text for the current turn (from agent.token SSE). */
streaming: string;
/** Streaming reasoning text for the current turn (from agent.thinking SSE). */
streamingReasoning: string;
/** Live jobs for the linked project (to resolve enqueued artifacts). */
jobs?: Job[];
running: boolean;
/** Welcome suggestions shown only on an empty (new-chat) timeline. */
suggestions?: { label: string; prompt: string }[];
/** True while the selected session's history is still fetching. */
loading?: boolean;
/** Called with a suggestion's prompt to pre-fill the composer. */
onSuggestion?: (prompt: string) => void;
/** Called with an option's label + scope when a question-card option is clicked. */
onAnswer?: (option: string, scope: string, questionSeq: number) => void;
}
let {
studio = false,
messages,
liveTools,
streaming,
streamingReasoning,
jobs = [],
running,
suggestions = [],
loading = false,
onSuggestion,
onAnswer,
}: Props = $props();
let listEl = $state<HTMLDivElement | null>(null);
let pinned = $state(true);
// A user message starts a turn; keep different named assistants distinct.
const studioGroups = $derived.by(() => {
const groups: AgentMessage[][] = [];
for (const message of messages) {
if (!['user', 'assistant', 'tool'].includes(message.role)) continue;
const previous = groups.at(-1);
const author = previous?.find(m => m.role === 'assistant')?.agent_name;
if (!previous || message.role === 'user' || previous[0].role === 'user' ||
(message.role === 'assistant' && author !== undefined && message.agent_name !== author)) {
groups.push([message]);
} else previous.push(message);
}
return groups;
});
// Derived tool rows carry no status — infer failure from the result shape,
// same as the live SSE path does.
function toolPhase(m: AgentMessage): 'done' | 'error' {
if (m.status === 'error') return 'error';
const r = m.tool_result as { ok?: boolean } | null | undefined;
return r && typeof r === 'object' && r.ok === false ? 'error' : 'done';
}
// Tool results that enqueue render jobs expose their job ids — these render
// as inline artifact cards (Playground-style) that track live job status.
const ENQUEUE_TOOLS = new Set(['enqueue_asset_jobs', 'enqueue_video_jobs', 'run_workflow']);
const jobsById = $derived(new Map((jobs ?? []).map((j) => [j.id, j])));
/** Later tool results (wait_for_jobs) often have the finished status + paths. */
const trailJobsById = $derived.by(() => {
// eslint-disable-next-line svelte/prefer-svelte-reactivity -- Each derivation rebuilds this tool-result lookup from messages; only the completed Map escapes, with no later mutation.
const map = new Map<number, ArtifactJob>();
for (const row of messages) {
if (row.role !== 'tool' || !row.tool_result || typeof row.tool_result !== 'object') continue;
const listed = (row.tool_result as { jobs?: unknown }).jobs;
if (!Array.isArray(listed)) continue;
for (const raw of listed) {
if (!raw || typeof raw !== 'object') continue;
const j = raw as ArtifactJob;
if (typeof j.id !== 'number') continue;
const prev = map.get(j.id);
map.set(j.id, prev ? { ...prev, ...j } : j);
}
}
return map;
});
function artifactJobs(m: AgentMessage): ArtifactJob[] {
const result = m.tool_result;
if (!result || typeof result !== 'object') return [];
const stubs = (result as { jobs?: unknown }).jobs;
if (!Array.isArray(stubs)) return [];
return stubs
.filter((j) => j && typeof j === 'object' && typeof (j as { id?: unknown }).id === 'number')
.map((j) => {
const stub = j as ArtifactJob;
return jobsById.get(stub.id) ?? trailJobsById.get(stub.id) ?? {
id: stub.id,
kind: stub.kind ?? 'image',
status: stub.status ?? 'pending',
output_paths: stub.output_paths,
error: stub.error,
};
});
}
// Keep pinned to bottom on new content unless the user scrolled up.
$effect(() => {
void messages.length;
void streaming;
void streamingReasoning;
void liveTools.length;
void jobs.length;
if (listEl && pinned) {
requestAnimationFrame(() => {
listEl?.scrollTo({ top: listEl.scrollHeight });
});
}
});
function onScroll() {
const el = listEl;
if (!el) return;
pinned = el.scrollHeight - el.scrollTop - el.clientHeight < 60;
}
function escapeRegExp(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// ── ask_user question cards ──────────────────────────────────────────
// The card is DERIVED from the message stream: the persisted ask_user
// tool row carries {question_seq, options, scope}; it stays actionable
// until a later user message (the card answer or any prose reply).
interface OpenQuestion {
questionSeq: number;
question: string;
options: string[];
scope: string;
}
const lastQuestion = $derived.by<OpenQuestion | null>(() => {
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i];
if (m.role === 'user') return null;
if (m.role === 'tool' && m.tool_name === 'ask_user' && m.tool_result) {
const r = m.tool_result as {
ok?: boolean;
question_seq?: number;
question?: string;
options?: unknown;
scope?: string;
};
if (r.ok !== false && Array.isArray(r.options)) {
return {
questionSeq: r.question_seq ?? m.id,
question: r.question ?? '',
options: r.options as string[],
scope: r.scope ?? 'info',
};
}
return null;
}
}
return null;
});
function answerLabel(scope: string): string {
if (scope === 'render') return t('agentChat.approveRender');
if (scope === 'destructive_replace') return t('agentChat.approveReplace');
return '';
}
function bubbleParts(
content: string,
mentions: WorkflowMention[],
): Array<{ type: 'text' | 'chip'; text: string }> {
if (!mentions.length) return [{ type: 'text', text: content }];
const names = [...new Set(mentions.map((m) => m.name).filter(Boolean))].sort(
(a, b) => b.length - a.length,
);
if (names.length === 0) return [{ type: 'text', text: content }];
const re = new RegExp(`(@(?:${names.map(escapeRegExp).join('|')}))`, 'g');
const parts: Array<{ type: 'text' | 'chip'; text: string }> = [];
let last = 0;
for (const match of content.matchAll(re)) {
const idx = match.index ?? 0;
if (idx > last) parts.push({ type: 'text', text: content.slice(last, idx) });
parts.push({ type: 'chip', text: match[1] ?? '' });
last = idx + (match[0]?.length ?? 0);
}
if (last < content.length) parts.push({ type: 'text', text: content.slice(last) });
return parts.length ? parts : [{ type: 'text', text: content }];
}
</script>
<div class="chat" bind:this={listEl} onscroll={onScroll}>
{#if studio}
{#if loading}<p class="studio-empty">{t('agentChat.loading')}</p>{/if}
{#each studioGroups as group (group[0].id)}
<div class="studio-msg" class:me={group[0].role==='user'}>
<div class="studio-avatar" title={group[0].role==='user'?'我':agentDisplayName(group[0].agent_name)}>{#if group[0].role==='user'}我{:else}<Icon name="project-agent" size={14}/>{/if}</div>
<div class="studio-message-body">
{#each group as m (m.id)}
{#if m.role==='tool'}
<AgentToolCard studio name={m.tool_name??'tool'} args={m.tool_args} result={m.tool_result} phase={toolPhase(m)}/>
{#each artifactJobs(m) as job(job.id)}<AgentArtifactCard {job}/>{/each}
{:else}
{#if m.reasoning}<ReasoningPanel reasoning={m.reasoning}/>{/if}
<div class="studio-bubble" data-message-id={m.id} class:failed={m.status==='error'||m.status==='cancelled'}>{#if m.status==='steering'}<small>{t('agentChat.steering')}</small>{/if}{#each m.attachments??[] as a (a.path)}<a href={assetUrl(a.path)??'#'} target="_blank" rel="noopener external">{a.name}</a>{/each}{#each bubbleParts(m.content,(m.mentions??[]) as WorkflowMention[]) as part,i (`${i}-${part.type}`)}{#if part.type==='chip'}<span class="wf-chip">{part.text}</span>{:else}{part.text}{/if}{/each}</div>
{/if}
{/each}
</div>
</div>
{/each}
{#if lastQuestion && !running}<div class="question-card"><p>{lastQuestion.question}</p><div class="question-options">{#each lastQuestion.options as opt(opt)}<button type="button" class="question-option" onclick={()=>onAnswer?.(opt,lastQuestion.scope,lastQuestion.questionSeq)}>{opt}</button>{/each}</div></div>{/if}
{#if running && (liveTools.length || streamingReasoning || streaming)}
<div class="studio-msg"><div class="studio-avatar"><Icon name="project-agent" size={14}/></div><div class="studio-message-body">
{#each liveTools as tool,i(i)}<AgentToolCard studio name={tool.tool} args={tool.args} result={tool.result} phase={tool.phase}/>{/each}
{#if streamingReasoning}<ReasoningPanel reasoning={streamingReasoning}/>{/if}
{#if streaming}<div class="studio-bubble">{streaming}</div>{/if}
</div></div>
{/if}
{#if !loading&&!messages.length&&!running}<p class="studio-empty">{t('agentChat.emptyHint')}</p>{/if}
{:else}
{#if loading}
<div class="empty">
<p class="empty-hint">{t('agentChat.loading')}</p>
</div>
{:else if messages.length === 0 && !running}
<div class="empty">
<div class="empty-mark"><Icon name="sparkle" size={22} /></div>
<p class="empty-title">{t('agentChat.emptyTitle')}</p>
<p class="empty-hint">{t('agentChat.emptyHint')}</p>
{#if suggestions.length > 0}
<div class="suggestions">
{#each suggestions as s (s.label)}
<button type="button" class="suggestion" onclick={() => onSuggestion?.(s.prompt)}>
{s.label}
</button>
{/each}
</div>
{/if}
</div>
{/if}
{#each messages as m (m.id)}
{#if m.role === 'user'}
<div class="row user">
<div class="bubble user-bubble" class:steering={m.status === 'steering'}>
{#if m.status === 'steering'}
<span class="steer-tag">{t('agentChat.steering')}</span>
{/if}
{#if (m.attachments ?? []).length > 0}
<div class="user-thumbs">
{#each (m.attachments ?? []) as a (a.path)}
{@const href = assetUrl(a.path)}
{#if a.kind === 'image' && href}
<img class="user-thumb" src={href} alt={a.name} />
{:else}
<span class="user-thumb file" title={a.name}>
<Icon name={a.kind === 'audio' ? 'music' : 'video'} size={14} />
</span>
{/if}
{/each}
</div>
{/if}
<span class="user-text">
{#each bubbleParts(m.content, (m.mentions ?? []) as WorkflowMention[]) as part, i (`${i}-${part.type}`)}
{#if part.type === 'chip'}
<span class="wf-chip">{part.text}</span>
{:else}{part.text}{/if}
{/each}
</span>
</div>
</div>
{:else if m.role === 'tool'}
<div class="row tool-row">
<AgentToolCard
name={m.tool_name ?? 'tool'}
args={m.tool_args}
result={m.tool_result}
phase={toolPhase(m)}
/>
{#if m.tool_name === 'ask_user' && lastQuestion && m.id === messages.findLast((x) => x.role === 'tool' && x.tool_name === 'ask_user')?.id}
<div class="question-card">
{#if lastQuestion.question}
<p class="question-text">{lastQuestion.question}</p>
{/if}
<div class="question-options">
{#each lastQuestion.options as opt (opt)}
<button
type="button"
class="question-option"
class:affirmative={/^yes\b|^ok\b|^sure\b|^go\b|^do it\b|^confirm\b/i.test(opt)}
disabled={running}
onclick={() => onAnswer?.(opt, lastQuestion.scope, lastQuestion.questionSeq)}
>
{opt}
</button>
{/each}
</div>
<p class="question-hint">
{answerLabel(lastQuestion.scope) || t('agentChat.pickOption')}
</p>
</div>
{/if}
{#if m.tool_name && ENQUEUE_TOOLS.has(m.tool_name)}
{@const arts = artifactJobs(m)}
{#if arts.length > 0}
<div class="artifacts">
{#each arts as job (job.id)}
<AgentArtifactCard {job} />
{/each}
</div>
{/if}
{/if}
</div>
{:else if m.role === 'assistant'}
{@const color = agentColor(m.agent_name)}
<div class="row assistant" style:--agent={color}>
<div class="agent-tag">
<span class="agent-dot" style:background={color}></span>
{agentDisplayName(m.agent_name)}
</div>
{#if m.reasoning}
<div class="reasoning-wrap">
<ReasoningPanel reasoning={m.reasoning} />
</div>
{/if}
<div
class="bubble assistant-bubble"
class:err={m.status === 'error' || m.status === 'cancelled'}
>
{m.content}
</div>
</div>
{/if}
{/each}
{#if running}
<div class="row assistant" style:--agent={agentColor(null)}>
<div class="agent-tag">
<span class="agent-dot" style:background={agentColor(null)}></span>
{agentDisplayName(null)}
</div>
<div class="bubble assistant-bubble live">
{#if liveTools.length > 0}
<div class="tools">
{#each liveTools as t, i (i)}
<AgentToolCard name={t.tool} args={t.args} result={t.result} phase={t.phase} />
{/each}
</div>
{/if}
{#if streaming}
<div class="stream-text">{streaming}<span class="caret"></span></div>
{:else}
<div class="thinking"><span class="pulse"></span> {t('agentChat.working')}</div>
{/if}
{#if streamingReasoning}
<ReasoningPanel streaming={streamingReasoning} />
{/if}
</div>
</div>
{/if}
{/if}
</div>
<style>
.studio-msg {display:flex;gap:10px;max-width:760px;}
.studio-msg.me {align-self:flex-end;flex-direction:row-reverse;}
.studio-avatar {width:28px;height:28px;border-radius:var(--agent-radius-8);flex:none;display:grid;place-items:center;background:color-mix(in srgb,var(--sc-agent) 18%,transparent);color:var(--sc-agent);}
.studio-msg.me .studio-avatar {background:var(--bg-3);color:var(--tx-2);}
.studio-message-body {flex:var(--agent-message-flex);display:flex;flex-direction:column;gap:10px;min-width:0;}
.studio-bubble {padding:10px 13px;border-radius:var(--agent-bubble-radius);background:var(--bg-2);border:1px solid var(--line);font-size:13px;line-height:1.65;white-space:pre-wrap;word-break:break-word;}
.studio-msg.me .studio-bubble {background:color-mix(in srgb,var(--gold) 10%,transparent);border-color:color-mix(in srgb,var(--gold) 25%,transparent);}
.studio-bubble.failed {color:var(--err);border-color:var(--err);}
.studio-empty {color:var(--tx-3);font-size:12px;}
.chat {
flex: 1;
min-height: 0;
min-width: 0;
width: 100%;
overflow-y: auto;
overflow-x: hidden;
display: flex;
flex-direction: column;
gap: 14px;
padding: var(--chat-padding, 4px 4px 12px);
}
.empty {
margin: auto;
max-width: 540px;
text-align: center;
color: var(--text-muted);
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
padding: 40px 16px;
}
.empty-mark {
width: 48px;
height: 48px;
border-radius: var(--r-md);
display: flex;
align-items: center;
justify-content: center;
color: var(--text-2);
background: var(--bg-3);
border: 1px solid var(--line-2);
margin-bottom: 6px;
}
.empty-title {
margin: 0;
font-family: var(--font-display);
font-size: 26px;
font-weight: 700;
letter-spacing: -0.02em;
color: var(--text-primary);
}
.empty-hint {
margin: 0;
font-size: 13.5px;
line-height: 1.6;
max-width: 420px;
}
.suggestions {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 8px;
margin-top: 16px;
}
.suggestion {
border: 1px solid var(--line);
background: var(--bg-2);
color: var(--text-2);
border-radius: var(--r-pill);
padding: var(--sp-3) var(--sp-6);
font-size: var(--fs-body);
font-weight: 500;
font-family: inherit;
cursor: pointer;
transition:
color var(--d-state) ease,
border-color var(--d-state) ease,
background-color var(--d-state) ease;
}
.suggestion:hover {
color: var(--text);
border-color: var(--line-2);
background: var(--bg-4);
}
.suggestion:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.row {
display: flex;
flex-direction: column;
}
.row.user {
align-items: flex-end;
}
.row.assistant {
align-items: flex-start;
}
.row.tool-row {
align-items: flex-start;
padding-left: 6px;
width: 100%;
}
.agent-tag {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: var(--chat-tag-size, var(--fs-mini));
font-weight: var(--chat-tag-weight, 700);
letter-spacing: var(--chat-tag-spacing, 0.06em);
text-transform: var(--chat-tag-transform, uppercase);
color: var(--agent, var(--text-2));
margin-bottom: 4px;
padding-left: 2px;
}
.agent-dot {
width: var(--chat-dot-size, 8px);
height: var(--chat-dot-size, 8px);
border-radius: 999px;
flex-shrink: 0;
box-shadow: var(--chat-identity-shadow, 0 0 0 2px color-mix(in srgb, var(--agent, var(--text-2)) 25%, transparent));
}
.reasoning-wrap {
margin-bottom: 4px;
max-width: 86%;
}
.bubble {
max-width: var(--chat-bubble-width, 86%);
border-radius: var(--chat-bubble-radius, var(--r-lg));
padding: var(--chat-bubble-padding, 10px 14px);
font-size: var(--chat-bubble-font, 13.5px);
line-height: 1.6;
white-space: pre-wrap;
word-break: break-word;
}
/* 对话气泡按规范 §3.2/§3.6:用户 --bg-3,Agent --bg-2 + --line 描边。 */
.user-bubble {
background: var(--chat-user-bg, var(--bg-3));
border: 1px solid var(--chat-user-border, var(--line));
color: var(--text);
}
.user-bubble.steering {
border-style: dashed;
}
.steer-tag {
display: inline-block;
font-size: var(--fs-mini);
font-weight: 600;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--text-3);
margin-bottom: 4px;
}
.user-thumbs {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 8px;
}
.user-thumb {
display: block;
width: 48px;
height: 48px;
object-fit: cover;
border-radius: var(--r-sm);
border: 1px solid var(--line-2);
background: var(--bg-3);
}
.user-thumb.file {
display: inline-flex;
align-items: center;
justify-content: center;
color: var(--text-3);
}
.user-text {
white-space: pre-wrap;
}
/* 工作流提及为次级内容:中性底 + --text,不占金色。 */
.wf-chip {
display: inline;
padding: 1px 7px;
margin: 0 1px;
border-radius: var(--r-pill);
background: var(--bg-4);
border: 1px solid var(--line-2);
color: var(--text);
font-weight: 600;
font-size: var(--fs-body);
white-space: nowrap;
}
.assistant-bubble {
background: var(--bg-2);
border: 1px solid var(--line);
border-left: var(--chat-agent-border-width, 3px) solid var(--chat-agent-border, var(--agent, var(--text-2)));
color: var(--text);
}
.question-card {
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
max-width: 420px;
margin: 2px 0 6px;
padding: 12px 14px;
border: 1px solid var(--line);
border-radius: var(--r-md);
background: var(--bg-2);
}
.question-text {
margin: 0;
font-size: var(--fs-body);
line-height: 1.5;
color: var(--text);
white-space: pre-wrap;
}
.question-options {
display: flex;
flex-direction: column;
gap: 6px;
}
.question-option {
border: 1px solid var(--line-2);
background: var(--bg-3);
color: var(--text);
border-radius: var(--r-sm);
padding: 8px 12px;
font-size: var(--fs-body);
font-weight: 600;
cursor: pointer;
text-align: left;
transition:
background-color var(--d-press) ease,
border-color var(--d-press) ease;
}
.question-option:hover:enabled {
background: var(--bg-4);
border-color: var(--agent, var(--text-2));
}
.question-option:disabled {
opacity: 0.5;
cursor: default;
}
.question-option.affirmative {
border-color: var(--line-2);
}
.question-hint {
margin: 0;
font-size: var(--fs-mini);
color: var(--text-3);
}
.assistant-bubble.err {
border-color: var(--err-line);
border-left-color: var(--err);
color: var(--err);
}
.bubble.live {
display: flex;
flex-direction: column;
gap: 8px;
max-width: 92%;
width: 100%;
}
.tools {
display: flex;
flex-direction: column;
gap: 6px;
}
.artifacts {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 8px;
padding-left: 4px;
}
.stream-text {
white-space: pre-wrap;
}
.caret {
display: inline-block;
width: 7px;
height: 14px;
margin-left: 2px;
background: var(--run);
animation: var(--decorative-loop-name, motion-agentchat-blink) 1s step-end infinite;
vertical-align: text-bottom;
}
@keyframes -global-motion-agentchat-blink {
50% {
opacity: 0;
}
}
.thinking {
display: flex;
align-items: center;
gap: 8px;
color: var(--text-2);
font-size: var(--fs-body);
}
/* 进行中指示 = 信号青(§1.3),不占金色。 */
.pulse {
opacity: var(--thinking-opacity, 1);
width: 8px;
height: 8px;
border-radius: 999px;
background: var(--run);
animation: var(--decorative-loop-name, motion-agentchat-pulse) 1.1s ease-in-out infinite;
}
@keyframes -global-motion-agentchat-pulse {
0%,
100% {
opacity: 0.35;
}
50% {
opacity: 1;
}
}
</style>