diff --git a/calliope-web/src/routes/agents/+page.svelte b/calliope-web/src/routes/agents/+page.svelte index fb7b3dc0..f0fc4c7a 100644 --- a/calliope-web/src/routes/agents/+page.svelte +++ b/calliope-web/src/routes/agents/+page.svelte @@ -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(null); - let streaming = $state(''); - let streamingReasoning = $state(''); - let liveTools = $state< - { tool: string; args?: Record | null; result?: unknown; phase: 'running' | 'done' | 'error' }[] - >([]); - let showLinkPicker = $state(false); - let livePlan = $state(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( - ($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=&task= - $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( - ['agent-session', activeId], - (old) => (old ? { ...old, plan: null } : old), - ); + if (projectParam != null || taskParam != null) { + // Deep-link contract from the Project stages: /agents?project=&task= + 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(['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( - ['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) ?? 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; }); -
- - -
- { - activeId = id; - streaming = ''; - streamingReasoning = ''; - liveTools = []; - livePlan = null; - showLinkPicker = false; - resetComposer(); - }} - onNewSandbox={newSandbox} - onNewProjectChat={newProjectChat} - onDelete={removeSession} - /> - -
-
-
- {#if activeSession} -

{activeSession.title}

- {#if activeSession.project} - - - {activeSession.project.title} - - - {#if !running} - - {/if} - {:else} - - - Sandbox — no project yet - - {#if !running} - - {/if} - {/if} - {:else} -

New chat

- - Calliope — your production agent - - {/if} -
- {#if running} -
- Agent working… -
- {/if} -
- - {#if activeSession && showLinkPicker && !activeSession.project && !running} - - {/if} - - {#if $sessionQuery.isError} - - {/if} - - - {#if running && plan && plan.tasks.length > 0} - - {/if} - - {#key activeId} - - {/key} -
-
-
+{#if failed} + +{:else} +
Opening canvas…
+{/if} diff --git a/calliope-web/src/routes/canvas/[id]/+page.svelte b/calliope-web/src/routes/canvas/[id]/+page.svelte index d9f793ec..40051708 100644 --- a/calliope-web/src/routes/canvas/[id]/+page.svelte +++ b/calliope-web/src/routes/canvas/[id]/+page.svelte @@ -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; } diff --git a/calliope-web/src/routes/playground/+page.svelte b/calliope-web/src/routes/playground/+page.svelte index 0a68bb34..daf5c526 100644 --- a/calliope-web/src/routes/playground/+page.svelte +++ b/calliope-web/src/routes/playground/+page.svelte @@ -1,869 +1,40 @@ -
- - -
- -
- - -
- -
- - -
-
-

Artifacts

-

- {jobs.length} - {doneCount} ready -

-
- - {#if jobsLoading} -
- - -
- {:else if jobs.length === 0} -
-

Nothing queued yet

-

Generations land here — pending first, then the media.

-
- {:else} -
    - {#each jobs as job (job.id)} - {@const primaryPath = job.output_paths?.[0] ?? null} - {@const primaryMedia = primaryPath ? assetUrl(primaryPath) : null} -
  • -
    - #{job.id} - {statusWord(job.status)} - {job.kind} -
    - - {#if job.status === 'pending' || job.status === 'running'} - {@const prog = progressFor(job.id)} -
    - -
    - - {job.status === 'running' ? (prog?.message ?? 'Generating…') : 'Queued'} - - {#if job.status === 'running'} - - {/if} -
    -
    - {/if} - - {#if job.error} -

    {job.error}

    - {/if} - - {#if primaryMedia && primaryPath} - {#if isVideoPath(primaryPath, job.kind)} - - {:else} - - {/if} - {:else if job.status === 'done'} -
    -

    File missing on disk

    - {#if primaryPath} -

    {primaryPath.split(/[/\\]/).pop()}

    - {/if} -
    - {/if} - -
    - {#if primaryPath && primaryMedia} - - {/if} - {#if job.status === 'failed'} - - {/if} - -
    -
  • - {/each} -
- {/if} -
- - -
- {#if modeWorkflows.length === 0} -
-

No enabled {mode === 'video' ? 'video' : 'image'} workflows

-

- Enable a workflow in Settings → Workflows. -

-
- {:else if selected} - (workflowId = id)} - allowUpload - showErrors={attempted} - onValidityChange={(m) => (missingLabels = m)} - onSubmit={tryGenerate} - submitting={$generateMutation.isPending} - /> - {#if formError} - - {/if} - {/if} -
-
-
- - { - previewSrc = null; - previewAlt = ''; - }} -/> +{#if failed} + +{:else} +
Opening sandbox canvas…
+{/if}