feat(canvas): redirect /agents and /playground into the merged canvas surface

This commit is contained in:
Benjiyaya
2026-09-06 05:15:00 +08:00
parent 86d99b86d9
commit d3a2d397be
3 changed files with 69 additions and 1557 deletions
+42 -707
View File
@@ -2,730 +2,65 @@
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { page } from '$app/state';
import { toStore } from 'svelte/store';
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import AppHeader from '$lib/components/AppHeader.svelte';
import AgentChat from '$lib/components/agent/AgentChat.svelte';
import AgentComposer from '$lib/components/agent/AgentComposer.svelte';
import AgentSessionSidebar from '$lib/components/agent/AgentSessionSidebar.svelte';
import AgentPlanPanel from '$lib/components/agent/AgentPlanPanel.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import {
agentApi,
jobsApi,
playgroundApi,
workflows,
type AgentMessage,
type AgentPlan,
type AgentSession,
type AgentTask,
type Job,
} from '$lib/api';
import type { AgentComposerPayload, WorkflowOption } from '$lib/agentComposer';
import { agentApi, canvasApi } from '$lib/api';
import { AGENT_TASK_PROMPTS, AGENT_TASK_TITLES, isAgentTaskKind } from '$lib/agentTasks';
import { connectEvents } from '$lib/events';
import { toast } from '$lib/toast';
const client = useQueryClient();
let failed = $state('');
let activeId = $state<number | null>(null);
let streaming = $state('');
let streamingReasoning = $state('');
let liveTools = $state<
{ tool: string; args?: Record<string, unknown> | null; result?: unknown; phase: 'running' | 'done' | 'error' }[]
>([]);
let showLinkPicker = $state(false);
let livePlan = $state<AgentPlan | null>(null);
// Pre-filled composer text (deep-link handoff + welcome suggestions). The
// nonce forces re-application even when the same text is requested twice.
let composerDraft = $state('');
let composerNonce = $state(0);
let deepLinkHandled = $state(false);
const SUGGESTIONS: { label: string; prompt: string }[] = [
{
label: 'Create a new film',
prompt: 'Create a new film project and guide me through drafting the story.',
},
{
label: 'Draft a storyline',
prompt: 'Draft a storyline — beats, characters, environments, and misc. items.',
},
{
label: 'Write a script',
prompt: 'Write the full script — turn the storyline into ordered scenes.',
},
];
const SESSION_KEY = 'calliope.agents.activeSession';
function readStoredSession(): number | null {
const raw = typeof localStorage !== 'undefined' ? localStorage.getItem(SESSION_KEY) : null;
const n = raw == null ? Number.NaN : Number(raw);
return Number.isFinite(n) ? n : null;
}
const sessionsQuery = createQuery({
queryKey: ['agent-sessions'],
queryFn: () => agentApi.listSessions(),
refetchInterval: 5000, // survives SSE drop: running state + new sessions keep flowing
});
const sessions = $derived($sessionsQuery.data ?? []);
const activeSession = $derived(
activeId != null ? (sessions.find((s) => s.id === activeId) ?? null) : null,
);
const running = $derived(Boolean(activeSession?.running || activeSession?.status === 'running'));
const sessionQuery = createQuery(
toStore(() => ({
queryKey: ['agent-session', activeId],
queryFn: () => agentApi.getSession(activeId!),
enabled: activeId != null,
// While the agent runs, poll the persisted trail so navigating away
// and back still shows every intermediate message.
refetchInterval: () => (running ? 1500 : false),
})),
);
const messages = $derived($sessionQuery.data?.messages ?? []);
const sessionPlan = $derived($sessionQuery.data?.plan ?? null);
const plan = $derived(livePlan ?? sessionPlan);
const projectId = $derived(activeSession?.project?.id ?? null);
// Live jobs for the linked project — resolves enqueued artifacts to their
// current status + output paths, refreshing while anything is in flight.
const jobsQuery = createQuery(
toStore(() => ({
queryKey: ['agent-project-jobs', projectId ?? 'sandbox'],
queryFn: () => (projectId != null ? jobsApi.list(projectId) : playgroundApi.jobs()),
enabled: activeId != null,
refetchInterval: (q: { state: { data?: Job[] } }) => {
const list = q.state.data ?? [];
return list.some((j) => j.status === 'pending' || j.status === 'running')
? 2500
: false;
},
})),
);
const jobs = $derived($jobsQuery.data ?? []);
const linkableQuery = createQuery(
toStore(() => ({
queryKey: ['agent-linkable-projects'],
queryFn: agentApi.listLinkableProjects,
enabled: showLinkPicker,
})),
);
const workflowsQuery = createQuery({
queryKey: ['workflows'],
queryFn: workflows.list,
});
const enabledWorkflows = $derived<WorkflowOption[]>(
($workflowsQuery.data ?? [])
.filter((w) => w.is_enabled)
.map((w) => ({
id: w.id,
name: w.name,
kind: w.kind,
description: w.description,
is_enabled: w.is_enabled,
})),
);
// Restore last-open session (or pick the newest) — survives page switches.
// Skipped while a deep-link handoff is in flight so it doesn't clobber the
// freshly created, project-linked session.
$effect(() => {
if (activeId != null || sessions.length === 0 || deepLinkHandled) return;
const stored = readStoredSession();
activeId = sessions.some((s) => s.id === stored) ? stored! : sessions[0].id;
});
$effect(() => {
if (activeId != null) localStorage.setItem(SESSION_KEY, String(activeId));
});
// Deep-link contract from the Project stages: /agents?project=<id>&task=<story|script>
$effect(() => {
if (deepLinkHandled) return;
const projectParam = page.url.searchParams.get('project');
const taskParam = page.url.searchParams.get('task');
if (projectParam == null && taskParam == null) return;
deepLinkHandled = true;
void openDeepLink(projectParam, taskParam);
});
function setComposerDraft(text: string) {
composerDraft = text;
composerNonce++;
}
function resetComposer() {
composerDraft = '';
composerNonce = 0;
}
function seedEmptySession(s: AgentSession) {
client.setQueryData(['agent-session', s.id], { ...s, messages: [], plan: null });
}
async function newSandbox() {
resetComposer();
onMount(async () => {
try {
const s = await agentApi.createSession({});
seedEmptySession(s);
await client.invalidateQueries({ queryKey: ['agent-sessions'] });
activeId = s.id;
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Could not create session');
}
}
const projectParam = page.url.searchParams.get('project');
const taskParam = page.url.searchParams.get('task');
let sessionId: number;
let prefill = '';
async function newProjectChat(projectId: number) {
resetComposer();
try {
const s = await agentApi.createSession({ project_id: projectId });
seedEmptySession(s);
await client.invalidateQueries({ queryKey: ['agent-sessions'] });
activeId = s.id;
toast.success('Linked chat created');
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Could not create session');
}
}
async function openDeepLink(projectParam: string | null, taskParam: string | null) {
const projectId =
projectParam != null && projectParam !== '' ? Number(projectParam) : null;
const task = isAgentTaskKind(taskParam) ? taskParam : null;
const prompt = task ? AGENT_TASK_PROMPTS[task] : '';
const title = task ? AGENT_TASK_TITLES[task] : undefined;
try {
const s = await agentApi.createSession({
...(projectId != null && Number.isFinite(projectId) ? { project_id: projectId } : {}),
...(title ? { title } : {}),
});
await client.invalidateQueries({ queryKey: ['agent-sessions'] });
activeId = s.id;
if (prompt) setComposerDraft(prompt);
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Could not open linked chat');
} finally {
goto('/agents', { replaceState: true, keepFocus: true, noScroll: true });
}
}
async function removeSession(id: number) {
if (!confirm('Delete this chat and its message history?')) return;
try {
await agentApi.deleteSession(id);
if (activeId === id) activeId = null;
await client.invalidateQueries({ queryKey: ['agent-sessions'] });
toast.success('Session deleted');
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Could not delete session');
}
}
async function linkSession(projectId: number) {
if (activeId == null) return;
try {
await agentApi.patchSession(activeId, { project_id: projectId });
showLinkPicker = false;
await client.invalidateQueries({ queryKey: ['agent-sessions'] });
toast.success('Session linked to project');
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Link failed');
}
}
async function unlinkSession() {
if (activeId == null) return;
if (!confirm('Unlink this chat from its project? The chat stays, but the agent loses project access.')) return;
try {
await agentApi.patchSession(activeId, { unlink: true });
await client.invalidateQueries({ queryKey: ['agent-sessions'] });
toast.info('Session unlinked — back to sandbox');
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Unlink failed');
}
}
const sendMutation = createMutation({
mutationFn: (payload: AgentComposerPayload) => agentApi.postMessage(activeId!, payload),
onMutate: () => {
streaming = '';
streamingReasoning = '';
liveTools = [];
livePlan = null;
// Drop the cached plan too so a prior turn's checklist doesn't
// flash while the planner computes the new one.
if (activeId != null) {
client.setQueryData<AgentSession & { messages: AgentMessage[]; plan?: AgentPlan | null }>(
['agent-session', activeId],
(old) => (old ? { ...old, plan: null } : old),
);
if (projectParam != null || taskParam != null) {
// Deep-link contract from the Project stages: /agents?project=<id>&task=<story|script>
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: AGENT_TASK_TITLES[task] } : {}),
});
sessionId = s.id;
prefill = task ? AGENT_TASK_PROMPTS[task] : '';
} else {
const sessions = await agentApi.listSessions();
const stored = Number(localStorage.getItem('calliope.agents.activeSession'));
const found = sessions.find((s) => s.id === stored) ?? sessions[0];
sessionId = found?.id ?? (await agentApi.createSession({})).id;
}
},
onSuccess: async () => {
await client.invalidateQueries({ queryKey: ['agent-session', activeId] });
await client.invalidateQueries({ queryKey: ['agent-sessions'] });
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : 'Failed to send');
},
});
async function cancelRun() {
if (activeId == null) return;
try {
await agentApi.cancel(activeId);
toast.info('Run cancelled');
const session = await agentApi.getSession(sessionId);
const graph = session.project_id
? await canvasApi.ensureForProject(session.project_id)
: await canvasApi.ensureForSession(session.id);
const url = `/canvas/${graph.canvas.id}?session=${session.id}`;
if (prefill) sessionStorage.setItem('calliope.canvas.composerPrefill', prefill);
goto(url, { replaceState: true });
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Cancel failed');
failed = err instanceof Error ? err.message : 'Could not open canvas';
}
}
/** Send from the landing (no session yet): lazily create a sandbox, then post. */
async function handleSend(payload: AgentComposerPayload) {
if (activeId != null) {
$sendMutation.mutate(payload);
return;
}
try {
const s = await agentApi.createSession({});
await client.invalidateQueries({ queryKey: ['agent-sessions'] });
activeId = s.id;
$sendMutation.mutate(payload);
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Could not create session');
}
}
function upsertSession(s: AgentSession) {
client.setQueryData<AgentSession[]>(['agent-sessions'], (old) => {
const list = Array.isArray(old) ? old : [];
return list.some((x) => x.id === s.id)
? list.map((x) => (x.id === s.id ? { ...x, ...s } : x))
: [...list, s];
});
}
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; // wait for refetch
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 === 'agent.session.updated') {
const s = ev.data?.session as AgentSession | undefined;
if (s) upsertSession(s);
} else if (ev.type === 'agent.message') {
const msg = ev.data?.message as AgentMessage | undefined;
if (msg) {
appendMessage(msg.session_id, msg);
// Persisted trail supersedes the live views (no duplicates).
if (msg.session_id === activeId) {
if (msg.role === 'tool') liveTools = [];
if (msg.role === 'assistant' && !msg.agent_name) {
streaming = '';
streamingReasoning = '';
}
}
}
client.invalidateQueries({ queryKey: ['agent-sessions'] });
} else if (ev.type === 'agent.token') {
if (ev.data?.session_id === activeId && !ev.data?.agent_name) {
streaming += String(ev.data?.content ?? '');
}
} else if (ev.type === 'agent.thinking') {
if (ev.data?.session_id === activeId && !ev.data?.agent_name) {
streamingReasoning += String(ev.data?.content ?? '');
}
} else if (ev.type === 'agent.tool') {
if (ev.data?.session_id !== activeId) return;
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((t) => t.tool === name && t.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',
};
}
}
} else if (ev.type === 'agent.plan') {
if (ev.data?.session_id !== activeId) return;
const tasks = (ev.data?.tasks as AgentTask[] | undefined) ?? [];
livePlan = {
tasks: tasks.map((t) => ({ ...t, status: t.status ?? 'pending' })),
note: (ev.data?.note as string | null) ?? null,
};
} else if (ev.type === 'agent.task') {
if (ev.data?.session_id !== activeId) return;
const index = ev.data?.index;
const status = ev.data?.status as AgentTask['status'] | undefined;
if (typeof index === 'number' && status) {
livePlan = livePlan
? {
...livePlan,
tasks: livePlan.tasks.map((t, i) =>
i === index ? { ...t, status } : t,
),
}
: livePlan;
}
} else if (
ev.type === 'story.ready' ||
ev.type === 'job.created' ||
ev.type === 'job.started' ||
ev.type === 'job.completed' ||
ev.type === 'job.failed'
) {
client.invalidateQueries({ queryKey: ['agent-sessions'] });
client.invalidateQueries({ queryKey: ['agent-project-jobs'] });
client.invalidateQueries({ queryKey: ['playground-jobs'] });
}
});
return stop;
});
</script>
<div class="shell">
<AppHeader active="agents" />
<div class="workspace">
<AgentSessionSidebar
{sessions}
activeId={activeId}
onSelect={(id) => {
activeId = id;
streaming = '';
streamingReasoning = '';
liveTools = [];
livePlan = null;
showLinkPicker = false;
resetComposer();
}}
onNewSandbox={newSandbox}
onNewProjectChat={newProjectChat}
onDelete={removeSession}
/>
<main class="panel">
<header class="ws-head">
<div class="ws-title-block">
{#if activeSession}
<h2>{activeSession.title}</h2>
{#if activeSession.project}
<a class="ws-project" href="/project/{activeSession.project.id}">
<Icon name="folder" size={13} />
{activeSession.project.title}
<Icon name="external-link" size={12} />
</a>
{#if !running}
<button
type="button"
class="link-btn"
onclick={unlinkSession}
title="Unlink from project (back to sandbox)"
>
<Icon name="link-off" size={12} /> Unlink
</button>
{/if}
{:else}
<span class="ws-sandbox">
<Icon name="sparkle" size={13} />
Sandbox — no project yet
</span>
{#if !running}
<button
type="button"
class="link-btn"
onclick={() => (showLinkPicker = !showLinkPicker)}
title="Link this chat to an existing project"
>
<Icon name="link" size={12} /> Link a project
</button>
{/if}
{/if}
{:else}
<h2>New chat</h2>
<span class="ws-sandbox">
<Icon name="sparkle" size={13} /> Calliope — your production agent
</span>
{/if}
</div>
{#if running}
<div class="ws-status">
<span class="run-dot"></span> Agent working…
</div>
{/if}
</header>
{#if activeSession && showLinkPicker && !activeSession.project && !running}
<div class="link-picker">
<div class="lp-head">Link this chat to a project</div>
{#if $linkableQuery.isLoading}
<div class="lp-empty">Loading projects…</div>
{:else if ($linkableQuery.data ?? []).length === 0}
<div class="lp-empty">No projects yet — ask the agent to create one instead.</div>
{:else}
<div class="lp-list">
{#each $linkableQuery.data ?? [] as p (p.id)}
<button type="button" class="lp-item" onclick={() => linkSession(p.id)}>
<Icon name="folder" size={13} />
<span class="lp-title">{p.title}</span>
<span class="lp-status">{p.status}</span>
</button>
{/each}
</div>
{/if}
</div>
{/if}
{#if $sessionQuery.isError}
<div class="session-error" role="alert">
Could not load this chat
{#if $sessionQuery.error instanceof Error}
— {$sessionQuery.error.message}
{/if}
</div>
{/if}
<AgentChat
{messages}
{liveTools}
{streaming}
{streamingReasoning}
{jobs}
{running}
loading={activeId != null && $sessionQuery.isLoading}
suggestions={SUGGESTIONS}
onSuggestion={setComposerDraft}
/>
{#if running && plan && plan.tasks.length > 0}
<AgentPlanPanel {plan} />
{/if}
{#key activeId}
<AgentComposer
{running}
draft={composerDraft}
draftNonce={composerNonce}
workflows={enabledWorkflows}
onSend={handleSend}
onCancel={cancelRun}
/>
{/key}
</main>
</div>
</div>
{#if failed}
<div class="redirect-error" role="alert">{failed}</div>
{:else}
<div class="redirecting">Opening canvas…</div>
{/if}
<style>
.shell {
.redirecting,
.redirect-error {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
overflow: hidden;
}
.workspace {
flex: 1;
display: flex;
min-height: 0;
}
.panel {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
padding: 16px 24px 18px;
gap: 10px;
overflow-x: hidden;
}
.ws-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-md);
flex-shrink: 0;
padding-bottom: 8px;
border-bottom: 1px solid var(--border);
}
.ws-title-block {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
flex-wrap: wrap;
}
.ws-head h2 {
margin: 0;
font-size: 16px;
font-weight: 700;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 40vw;
}
.ws-project {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12.5px;
color: var(--accent);
text-decoration: none;
border: 1px solid color-mix(in srgb, var(--accent) 35%, transparent);
background: color-mix(in srgb, var(--accent) 10%, transparent);
padding: 3px 10px;
border-radius: 999px;
}
.ws-project:hover {
background: color-mix(in srgb, var(--accent) 18%, transparent);
}
.ws-sandbox {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: var(--text-muted);
border: 1px dashed var(--border);
padding: 3px 10px;
border-radius: 999px;
}
.link-btn {
display: inline-flex;
align-items: center;
gap: 5px;
font-size: 11.5px;
color: var(--text-secondary);
background: transparent;
border: 1px solid var(--border);
border-radius: 999px;
padding: 3px 10px;
cursor: pointer;
font-size: 14px;
}
.link-btn:hover {
color: var(--text-primary);
border-color: var(--accent);
color: var(--accent);
}
.link-btn:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.link-picker {
border: 1px solid var(--border);
border-radius: var(--radius-md);
background: var(--bg-surface);
padding: 10px;
flex-shrink: 0;
max-height: 200px;
overflow-y: auto;
}
.lp-head {
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--text-muted);
margin-bottom: 8px;
}
.lp-empty {
font-size: 12.5px;
color: var(--text-muted);
padding: 4px 0;
}
.lp-list {
display: flex;
flex-direction: column;
gap: 4px;
}
.lp-item {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 7px 10px;
border-radius: var(--radius-sm);
border: 1px solid transparent;
background: transparent;
color: var(--text-primary);
font-size: 13px;
cursor: pointer;
text-align: left;
}
.lp-item:hover {
background: var(--bg-elevated);
border-color: var(--accent);
}
.lp-title {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.lp-status {
font-size: 11px;
color: var(--text-muted);
flex-shrink: 0;
}
.ws-status {
display: flex;
align-items: center;
gap: 8px;
font-size: 12.5px;
color: var(--warning);
flex-shrink: 0;
}
.run-dot {
width: 8px;
height: 8px;
border-radius: 999px;
background: var(--warning);
animation: pulse 1.1s ease-in-out infinite;
}
@keyframes pulse {
0%,
100% {
opacity: 0.35;
}
50% {
opacity: 1;
}
}
.session-error {
flex-shrink: 0;
font-size: 12.5px;
color: var(--error);
padding: 8px 10px;
border: 1px solid color-mix(in srgb, var(--error) 35%, transparent);
border-radius: var(--radius-sm);
background: color-mix(in srgb, var(--error) 8%, transparent);
.redirect-error {
color: #f87171;
}
</style>
@@ -275,6 +275,12 @@
const pid = Number(paramSession);
if (paramSession != null && Number.isFinite(pid)) {
activeId = sessions.some((s) => s.id === pid) ? pid : null;
// Deep-link handoff (/agents?project=&task=) pre-fills the composer once.
const prefill = sessionStorage.getItem('calliope.canvas.composerPrefill');
if (prefill) {
sessionStorage.removeItem('calliope.canvas.composerPrefill');
setComposerDraft(prefill);
}
replaceUrlParam('session');
return;
}
+21 -850
View File
@@ -1,869 +1,40 @@
<script lang="ts">
import { onMount } from 'svelte';
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import AppHeader from '$lib/components/AppHeader.svelte';
import OmniComposer from '$lib/components/OmniComposer.svelte';
import AttachToProject from '$lib/components/AttachToProject.svelte';
import ImageLightbox from '$lib/components/ImageLightbox.svelte';
import SafeMedia from '$lib/components/SafeMedia.svelte';
import { assetUrl, jobsApi, playgroundApi, workflows, type Job, type Workflow } from '$lib/api';
import { connectEvents } from '$lib/events';
import { handleJobEvent, progressFor } from '$lib/jobProgress';
import ProgressBar from '$lib/components/ui/ProgressBar.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import { toast } from '$lib/toast';
import { goto } from '$app/navigation';
import { agentApi, canvasApi } from '$lib/api';
const client = useQueryClient();
let failed = $state('');
let workflowId = $state<number | ''>('');
let formValues = $state<Record<string, string | number>>({});
let formError = $state('');
let lastWorkflowId = $state<number | '' | null>(null);
let previewSrc = $state<string | null>(null);
let previewAlt = $state('');
let previewKind = $state<'image' | 'video'>('image');
let deletingId = $state<number | null>(null);
let attempted = $state(false);
let missingLabels = $state<string[]>([]);
const workflowsQuery = createQuery({
queryKey: ['workflows'],
queryFn: workflows.list,
});
const jobsQuery = createQuery({
queryKey: ['playground-jobs'],
queryFn: playgroundApi.jobs,
refetchInterval: (q) => {
const list = (q.state.data as Job[] | undefined) ?? [];
const busy = list.some((j) => j.status === 'pending' || j.status === 'running');
return busy ? 5000 : false;
},
placeholderData: (prev) => prev,
});
const enabledWorkflows = $derived(
($workflowsQuery.data ?? []).filter((w: Workflow) => w.is_enabled),
);
const selected = $derived(enabledWorkflows.find((w) => w.id === workflowId) ?? null);
// Mode: filter by workflow kind — Video Generation / Image Generation
let mode = $state<'video' | 'image'>('video');
const modeWorkflows = $derived(enabledWorkflows.filter((w) => w.kind === mode));
// When mode changes, keep workflowId valid within the mode's list
$effect(() => {
const list = modeWorkflows;
if (list.length === 0) return;
if (workflowId === '' || !list.some((w) => w.id === workflowId)) {
workflowId = list[0].id;
}
});
// If default mode 'video' has no workflows but image does, flip
$effect(() => {
if (workflowId === '' && enabledWorkflows.length > 0) {
const hasVideo = enabledWorkflows.some((w) => w.kind === 'video');
if (!hasVideo) mode = 'image';
}
});
$effect(() => {
if (workflowId === lastWorkflowId) return;
lastWorkflowId = workflowId;
formValues = {};
formError = '';
attempted = false;
});
const generateMutation = createMutation({
mutationFn: () => {
if (workflowId === '') throw new Error('Select a workflow');
// Seed defaults for required-but-unset fields from schema
const withDefaults: Record<string, string | number> = { ...formValues };
for (const inp of selected?.input_schema ?? []) {
if (
withDefaults[inp.nodeId] === undefined &&
inp.defaultValue !== undefined &&
inp.defaultValue !== ''
) {
withDefaults[inp.nodeId] = inp.defaultValue;
}
}
return playgroundApi.generate({
workflow_id: Number(workflowId),
input_values: withDefaults,
});
},
onSuccess: () => {
formError = '';
client.invalidateQueries({ queryKey: ['playground-jobs'] });
toast.success('Generation queued');
},
onError: (err) => {
formError = err instanceof Error ? err.message : 'Generate failed';
toast.error(formError);
},
});
function tryGenerate() {
if ($generateMutation.isPending) return;
if (workflowId === '') {
toast.error('Select a workflow first');
return;
}
if (missingLabels.length > 0) {
attempted = true;
toast.error(`Missing required inputs: ${missingLabels.join(', ')}`);
return;
}
$generateMutation.mutate();
}
async function deleteJob(job: Job) {
const n = job.output_paths?.length ?? 0;
const msg =
n > 0
? `Delete artifact #${job.id}? This removes the DB record and ${n} file(s) on disk.`
: `Delete artifact #${job.id}? This removes the DB record.`;
if (!confirm(msg)) return;
deletingId = job.id;
onMount(async () => {
try {
const r = await playgroundApi.deleteJob(job.id);
await client.invalidateQueries({ queryKey: ['playground-jobs'] });
const gone = r.deleted_files?.length ?? 0;
const miss = r.missing_files?.length ?? 0;
if (gone && miss) {
toast.success(`Deleted #${job.id} (${gone} file(s); ${miss} already missing)`);
} else if (gone) {
toast.success(`Deleted #${job.id} and ${gone} file(s)`);
} else {
toast.success(`Deleted #${job.id}`);
}
const sessions = await agentApi.listSessions();
const sandbox = sessions.find((s) => s.project_id == null);
const s = sandbox ?? (await agentApi.createSession({}));
const graph = await canvasApi.ensureForSession(s.id);
goto(`/canvas/${graph.canvas.id}?session=${s.id}`, { replaceState: true });
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Delete failed');
} finally {
deletingId = null;
failed = err instanceof Error ? err.message : 'Could not open sandbox canvas';
}
}
onMount(() => {
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
const scheduleRefresh = () => {
if (refreshTimer) return;
refreshTimer = setTimeout(() => {
refreshTimer = null;
client.invalidateQueries({ queryKey: ['playground-jobs'] });
}, 400);
};
const stop = connectEvents((ev) => {
// Feed the shared progress store (ProgressBars read it live)
handleJobEvent(ev);
if (ev.type === 'job.progress') return;
if (
ev.type === 'job.created' ||
ev.type === 'job.started' ||
ev.type === 'job.completed' ||
ev.type === 'job.failed' ||
ev.type === 'job.deleted' ||
ev.type === 'asset.ready'
) {
scheduleRefresh();
}
});
return () => {
if (refreshTimer) clearTimeout(refreshTimer);
stop();
};
});
const jobs = $derived(($jobsQuery.data ?? []) as Job[]);
const jobsLoading = $derived($jobsQuery.isLoading && jobs.length === 0);
const doneCount = $derived(jobs.filter((j) => j.status === 'done').length);
function isVideoPath(path: string, kind: string) {
const lower = path.toLowerCase();
return kind === 'video' || lower.endsWith('.mp4') || lower.endsWith('.webm');
}
function statusWord(status: string) {
if (status === 'done') return 'Ready';
if (status === 'running') return 'Running';
if (status === 'pending') return 'Queued';
if (status === 'failed') return 'Failed';
return status;
}
function switchMode(next: 'video' | 'image') {
mode = next;
}
function resetAll() {
formValues = {};
formError = '';
attempted = false;
missingLabels = [];
}
</script>
<div class="shell">
<AppHeader active="playground" />
<main class="omni-layout">
<!-- Mode tabs (Kling-style) -->
<div class="mode-tabs" role="tablist" aria-label="Generation mode">
<button
type="button"
role="tab"
aria-selected={mode === 'video'}
class="mode-tab"
class:active={mode === 'video'}
onclick={() => switchMode('video')}
>
<Icon name="video" size={15} />
Video Generation
</button>
<button
type="button"
role="tab"
aria-selected={mode === 'image'}
class="mode-tab"
class:active={mode === 'image'}
onclick={() => switchMode('image')}
>
<Icon name="image" size={15} />
Image Generation
</button>
<div class="spacer"></div>
<button type="button" class="mode-tab reset" onclick={resetAll} title="Clear all inputs">
<Icon name="retry" size={14} />
Reset
</button>
</div>
<!-- Results scroll above the docked composer -->
<section class="results" aria-labelledby="pg-artifacts">
<header class="artifacts-head">
<h2 id="pg-artifacts">Artifacts</h2>
<p class="count-block">
<span class="count mono">{jobs.length}</span>
<span class="count-label">{doneCount} ready</span>
</p>
</header>
{#if jobsLoading}
<div class="rail">
<div class="skeleton" aria-hidden="true"></div>
<div class="skeleton" aria-hidden="true"></div>
</div>
{:else if jobs.length === 0}
<div class="empty-rail">
<p class="empty-title">Nothing queued yet</p>
<p class="muted">Generations land here — pending first, then the media.</p>
</div>
{:else}
<ul class="rail">
{#each jobs as job (job.id)}
{@const primaryPath = job.output_paths?.[0] ?? null}
{@const primaryMedia = primaryPath ? assetUrl(primaryPath) : null}
<li
class="card"
class:done={job.status === 'done'}
class:failed={job.status === 'failed'}
>
<div class="card-meta">
<span class="id mono">#{job.id}</span>
<span class="badge {job.status}">{statusWord(job.status)}</span>
<span class="kind muted">{job.kind}</span>
</div>
{#if job.status === 'pending' || job.status === 'running'}
{@const prog = progressFor(job.id)}
<div class="waiting" aria-busy="true">
<span class="pulse"></span>
<div class="waiting-main">
<span class="waiting-text">
{job.status === 'running' ? (prog?.message ?? 'Generating…') : 'Queued'}
</span>
{#if job.status === 'running'}
<ProgressBar
size="sm"
value={prog?.progress ?? 0}
indeterminate={prog == null}
/>
{/if}
</div>
</div>
{/if}
{#if job.error}
<p class="err">{job.error}</p>
{/if}
{#if primaryMedia && primaryPath}
{#if isVideoPath(primaryPath, job.kind)}
<button
type="button"
class="media-hit"
aria-label="Play video, artifact {job.id}"
title="Play in viewer"
onclick={() => {
previewSrc = primaryMedia;
previewAlt = `Artifact #${job.id}`;
previewKind = 'video';
}}
>
<div class="media-frame">
<SafeMedia
class="artifact"
src={primaryMedia}
kind="video"
label="Video unavailable"
controls={false}
/>
<span class="play-badge" aria-hidden="true">
<Icon name="play" size={22} />
</span>
</div>
</button>
{:else}
<button
type="button"
class="media-hit"
aria-label="View image, artifact {job.id}"
onclick={() => {
previewSrc = primaryMedia;
previewAlt = `Artifact #${job.id}`;
previewKind = 'image';
}}
>
<div class="media-frame">
<SafeMedia
class="artifact"
src={primaryMedia}
alt="Artifact {job.id}"
label="Image unavailable"
/>
</div>
</button>
{/if}
{:else if job.status === 'done'}
<div class="missing">
<p>File missing on disk</p>
{#if primaryPath}
<p class="mono path-hint">{primaryPath.split(/[/\\]/).pop()}</p>
{/if}
</div>
{/if}
<div class="card-actions">
{#if primaryPath && primaryMedia}
<AttachToProject path={primaryPath} kind={job.kind} />
{/if}
{#if job.status === 'failed'}
<button
class="btn btn-secondary"
type="button"
onclick={() =>
jobsApi.retry(job.id).then(() =>
client.invalidateQueries({ queryKey: ['playground-jobs'] }),
)}
>
Retry
</button>
{/if}
<button
class="btn btn-ghost danger"
type="button"
disabled={deletingId === job.id}
onclick={() => deleteJob(job)}
>
{deletingId === job.id ? 'Deleting…' : 'Delete'}
</button>
</div>
</li>
{/each}
</ul>
{/if}
</section>
<!-- Composer docked at bottom — always visible (Kling Omni style) -->
<div class="composer-dock">
{#if modeWorkflows.length === 0}
<div class="empty-mode">
<p class="empty-title">No enabled {mode === 'video' ? 'video' : 'image'} workflows</p>
<p class="muted">
Enable a workflow in <a href="/settings?tab=workflows">Settings → Workflows</a>.
</p>
</div>
{:else if selected}
<OmniComposer
inputs={selected.input_schema}
bind:values={formValues}
workflow={selected}
workflows={modeWorkflows}
onWorkflowChange={(id) => (workflowId = id)}
allowUpload
showErrors={attempted}
onValidityChange={(m) => (missingLabels = m)}
onSubmit={tryGenerate}
submitting={$generateMutation.isPending}
/>
{#if formError}
<p class="err" role="alert">{formError}</p>
{/if}
{/if}
</div>
</main>
</div>
<ImageLightbox
src={previewSrc}
alt={previewAlt}
kind={previewKind}
caption={previewKind === 'video' ? `Video ${previewAlt}` : undefined}
onClose={() => {
previewSrc = null;
previewAlt = '';
}}
/>
{#if failed}
<div class="redirect-error" role="alert">{failed}</div>
{:else}
<div class="redirecting">Opening sandbox canvas…</div>
{/if}
<style>
.shell {
height: 100vh;
display: flex;
flex-direction: column;
background: var(--bg-primary);
overflow: hidden;
}
/* Fixed viewport column: tabs + scrollable results + docked composer */
.omni-layout {
flex: 1;
display: flex;
flex-direction: column;
gap: 12px;
padding: 12px var(--space-xl) 16px;
min-height: 0;
overflow: hidden;
background: var(--bg-primary);
max-width: 980px;
width: 100%;
margin: 0 auto;
box-sizing: border-box;
}
/* ── Mode tabs ───────────────────────────────────────────── */
.mode-tabs {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.spacer {
flex: 1;
}
.mode-tab {
display: inline-flex;
align-items: center;
gap: 7px;
height: 36px;
padding: 0 14px;
border-radius: 9999px;
background: var(--bg-elevated);
border: 1px solid var(--border);
color: var(--text-secondary);
font-size: 13px;
font-weight: 500;
font-family: var(--font-body);
cursor: pointer;
transition:
border-color 0.15s,
color 0.15s,
background 0.15s;
}
.mode-tab:hover {
color: var(--text-primary);
border-color: var(--text-muted);
}
.mode-tab.active {
background: var(--bg-surface);
color: var(--text-primary);
border-color: var(--accent);
}
.mode-tab.reset {
color: var(--text-muted);
}
.mode-tab:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
/* ── Scrollable results ──────────────────────────────────── */
.results {
flex: 1;
min-height: 0;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: var(--space-md);
padding-right: 2px;
}
.artifacts-head {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: var(--space-md);
padding-bottom: var(--space-sm);
border-bottom: 1px solid var(--border);
flex-shrink: 0;
position: sticky;
top: 0;
background: var(--bg-primary);
z-index: 1;
}
h2 {
margin: 0;
font-family: var(--font-display);
font-size: 18px;
font-weight: 700;
letter-spacing: -0.03em;
color: var(--text-primary);
}
.count-block {
margin: 0;
display: flex;
align-items: baseline;
gap: 6px;
}
.count {
font-size: 15px;
color: var(--text-primary);
font-weight: 600;
}
.count-label {
font-size: 12px;
color: var(--text-muted);
}
.rail {
list-style: none;
margin: 0;
padding: 0 0 8px;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: var(--space-md);
align-items: start;
}
.card {
background: var(--bg-surface);
border: 1px solid var(--border);
border-radius: var(--radius-md);
padding: 10px;
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
overflow: hidden;
}
.card-meta {
display: flex;
align-items: center;
gap: 8px;
}
.id {
font-size: 12px;
color: var(--text-muted);
}
.kind {
font-size: 11px;
margin-left: auto;
}
.badge {
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: 9999px;
font-size: 11px;
font-weight: 600;
}
.badge.done {
background: color-mix(in srgb, var(--success) 15%, transparent);
color: var(--success);
}
.badge.failed {
background: color-mix(in srgb, var(--error) 15%, transparent);
color: var(--error);
}
.badge.pending,
.badge.running {
background: color-mix(in srgb, var(--warning) 15%, transparent);
color: var(--warning);
}
.err {
color: var(--error);
font-size: 13px;
margin: 0;
}
.waiting {
display: flex;
align-items: center;
gap: 10px;
}
.waiting-main {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 6px;
}
.waiting-text {
font-size: 13px;
color: var(--text-secondary);
}
.pulse {
width: 8px;
height: 8px;
flex-shrink: 0;
border-radius: 9999px;
background: var(--warning);
animation: pulse 1.2s ease-in-out infinite;
}
@keyframes pulse {
0%,
100% {
opacity: 0.4;
}
50% {
opacity: 1;
}
}
.media-hit {
padding: 0;
border: none;
background: transparent;
cursor: zoom-in;
display: block;
width: 100%;
min-width: 0;
}
/* Video thumb: native controls off, custom play affordance instead */
.media-hit:has(:global(video)) {
cursor: pointer;
}
.media-hit:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
border-radius: var(--radius-sm);
}
.play-badge {
position: absolute;
inset: 0;
.redirecting,
.redirect-error {
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
transition: background 0.15s;
}
.play-badge::before {
content: '';
width: 52px;
height: 52px;
border-radius: 9999px;
background: rgba(0, 0, 0, 0.55);
backdrop-filter: blur(2px);
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.18);
transition:
transform 0.15s ease,
background 0.15s;
}
.play-badge :global(svg) {
position: absolute;
color: #fff;
fill: currentColor;
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.6));
/* optical centering for a solid play triangle */
margin-left: 3px;
}
.media-hit:hover .play-badge::before,
.media-hit:focus-visible .play-badge::before {
background: rgba(0, 0, 0, 0.72);
transform: scale(1.06);
}
.media-frame {
position: relative;
width: 100%;
aspect-ratio: 4 / 3;
border-radius: var(--radius-sm);
overflow: hidden;
background: var(--bg-elevated);
}
.media-frame :global(.artifact),
.media-frame :global(img),
.media-frame :global(video) {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
border-radius: 0;
}
.missing {
padding: 12px;
border-radius: var(--radius-sm);
background: var(--bg-elevated);
color: var(--text-muted);
font-size: 13px;
}
.path-hint {
font-size: 11px;
margin: 4px 0 0;
overflow-wrap: anywhere;
}
.card-actions {
display: flex;
gap: 8px;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
margin-top: 2px;
}
.skeleton {
height: 180px;
border-radius: var(--radius-md);
background: linear-gradient(
90deg,
var(--bg-surface) 25%,
var(--bg-elevated) 50%,
var(--bg-surface) 75%
);
background-size: 200% 100%;
animation: shimmer 1.5s infinite;
}
@keyframes shimmer {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
.btn {
border-radius: 9999px;
font-size: 12px;
font-weight: 600;
padding: 6px 14px;
cursor: pointer;
transition: all 0.15s;
}
.btn-secondary {
background: transparent;
border: 1px solid var(--border);
height: 100vh;
color: var(--text-secondary);
font-size: 14px;
}
.btn-secondary:hover {
border-color: var(--text-muted);
color: var(--text-primary);
}
.btn-ghost.danger {
background: transparent;
border: 1px solid transparent;
color: var(--text-muted);
}
.btn-ghost.danger:hover {
color: var(--error);
border-color: rgba(239, 68, 68, 0.4);
}
.empty-rail {
padding: 40px 24px;
text-align: center;
border: 1px dashed var(--border);
border-radius: var(--radius-lg);
margin: auto 0;
}
.empty-title {
margin: 0 0 4px;
font-size: 15px;
font-weight: 600;
color: var(--text-primary);
}
.muted {
color: var(--text-secondary);
font-size: 13px;
line-height: 1.5;
margin: 0;
}
.muted a {
color: var(--accent);
}
/* ── Composer dock (never shrinks away) ──────────────────── */
.composer-dock {
flex-shrink: 0;
min-height: 0;
}
.composer-dock :global(.omni-shell) {
/* overflow:hidden + flex shrink was collapsing this to 2px */
flex-shrink: 0;
}
.empty-mode {
padding: 28px 20px;
text-align: center;
border: 1px dashed var(--border);
border-radius: var(--radius-lg);
background: var(--bg-surface);
.redirect-error {
color: #f87171;
}
</style>