+ {shown.map((item) => {
+ const active = item.id === activeId;
+ const count = active ? messageCount : item.messageCount;
+ return (
+
void choose(item.id)}
+ >
+
+ {titleText(item)}
+
+ {count
+ ? t("assistant.sessions.messageCount", { count })
+ : t("assistant.sessions.noMessages")}
+ {(active ? hasDraft : item.hasDraft)
+ ? ` · ${t("assistant.sessions.hasDraft")}`
+ : ""}
+
- )}
-
- ))}
+ {active && (
+
+
+ {t("assistant.sessions.current")}
+
+ )}
+
+ );
+ })}
{!shown.length && (
{query.trim()
diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx
index f21454680..58f6f6149 100644
--- a/src/canvas/AssistantPanel.tsx
+++ b/src/canvas/AssistantPanel.tsx
@@ -5,11 +5,17 @@ import { assistantModelSelection } from "./agentPreferences";
import { creationClient } from "../backend/creationClient.ts";
import { fingerprint } from "../backend/generation.ts";
import type { BackendModels } from "../backend/models";
+import type { Asset } from "../contracts/generated.ts";
import { loadReferenceCatalog } from "../backend/referenceCatalog.ts";
import "./assistant-panel.css";
import "./assistant-experience.css";
+import "./assistant-workspace.css";
import { AttachmentStrip, AttachmentHover } from "./AssistantMedia";
import { AssistantReply } from "./AssistantReply";
+import type { ProjectEditorTarget } from "./assistantResultEditors.ts";
+import { AssistantResultCard, AssistantTimelineResultCard } from "./AssistantResultCard";
+import { useAssistantResults } from "./useAssistantResults.ts";
+import { CreationAssetList } from "./CreationAssetList.tsx";
import { AssistantConversations } from "./AssistantConversations";
import { AgentPicker } from "./AgentPicker";
import { ModelPicker } from "./AssistantPickers";
@@ -26,6 +32,7 @@ import {
type ChatReferenceEditorHandle,
} from "./ChatReferenceEditor";
import { nodeReferenceAsset } from "./generationReferenceContent.ts";
+import { pinnedReferenceAsset } from "./pinnedReferenceAssets.ts";
import type { CanvasNode } from "./model";
import {
pendingCanvasReferences,
@@ -54,7 +61,7 @@ function kindOf(asset: ChatAsset) {
: "text";
}
-/** OpenDirector conversation tools in an OpenDirector floating canvas window. */
+/** Shared conversation and composer for chat creation and the canvas assistant. */
export function AssistantPanel({
documentId,
readOnly = false,
@@ -64,6 +71,7 @@ export function AssistantPanel({
visibleNodes,
selectedNodes,
open,
+ collapsible = true,
layout,
selectionRequest,
onClose,
@@ -72,6 +80,11 @@ export function AssistantPanel({
onAgentModel,
onOpenSettings,
onPrepareReferences,
+ onCreateProjectTimeline,
+ onOpenProjectTimeline,
+ onPreviewResult,
+ onViewResultOnCanvas,
+ onEditResult,
}: {
documentId: string;
readOnly?: boolean;
@@ -81,6 +94,7 @@ export function AssistantPanel({
visibleNodes: CanvasNode[];
selectedNodes: CanvasNode[];
open: boolean;
+ collapsible?: boolean;
layout: AssistantLayout;
selectionRequest: number;
onClose: () => void;
@@ -88,12 +102,18 @@ export function AssistantPanel({
/** Lets the canvas default new nodes to the model this dialog is using. */
onModelSelections?: (selections: ModelSelections) => void;
onAgentModel?: (projectId: string, selection: AssistantModelSelection | null) => void;
- onOpenSettings: () => void;
+ onOpenSettings: (kind: keyof ModelSelections) => void;
onPrepareReferences: () => Promise;
+ onCreateProjectTimeline: () => Promise;
+ onOpenProjectTimeline: (itemId: string) => Promise;
+ onPreviewResult: (asset: Asset) => void;
+ onEditResult: (target: ProjectEditorTarget, signal?: AbortSignal) => Promise;
+ onViewResultOnCanvas: (asset: Asset, itemId?: string | null) => Promise;
}) {
const t = useT();
const chat = useAssistantChat(documentId, catalog, onTurnEnd, t, open, readOnly);
const { value } = chat;
+ const { results, timelines, snapshot } = useAssistantResults(documentId, open && !collapsible, value.messages);
const [deepseekLabels, setDeepseekLabels] = useState>({});
const hasDeepseekMessages = value.messages.some((message) => message.runtime === "deepseek");
useEffect(() => {
@@ -114,6 +134,8 @@ export function AssistantPanel({
const uploads = useReferenceUploads(documentId);
const projectReferences = useProjectMentionAssets(documentId);
const editor = useRef(null);
+ const assetListAnchor = useRef(null);
+ const [projectAssetsOpen, setProjectAssetsOpen] = useState(false);
const [slashQuery, setSlashQuery] = useState(null);
const [dragOver, setDragOver] = useState(false);
const [mediaPreview, setMediaPreview] = useState<{assetId: string; anchor: DOMRect} | null>(null);
@@ -156,7 +178,7 @@ export function AssistantPanel({
const currentRuntime = chat.runtimes.find((item) => item.id === (value.runtime ?? "default"));
const missingAgentModel = needsAgentModel(chat.loaded, currentRuntime, !!chat.agent);
const referenceDisabled =
- !chat.loaded || chat.adding || checkingReferences || chat.sending;
+ readOnly || !chat.loaded || chat.adding || checkingReferences || chat.sending;
const sessionDisabledReason = readOnly ? t("canvas.workspace.preview.mode") : chat.changing
? t("assistant.sessions.disabled.switching")
: !chat.loaded
@@ -187,8 +209,27 @@ export function AssistantPanel({
chat.setContent(content, projectReferences.assets);
}, [projectReferences.assets]);
+ const previouslyOpen = useRef(open);
+ const openFocusTarget = useRef(null);
useEffect(() => {
- if (open && chat.loaded) editor.current?.focus();
+ if (open && !previouslyOpen.current) {
+ // A mode change can reveal chat while the user is still editing elsewhere.
+ openFocusTarget.current = collapsible ? document.activeElement : null;
+ }
+ previouslyOpen.current = open;
+ if (!open) {
+ openFocusTarget.current = null;
+ return;
+ }
+ if (!chat.loaded) return;
+ const active = document.activeElement;
+ // Loading a default-open chat must not dismiss a project menu or rename.
+ // An explicit open retains focus intent until the user chooses another control.
+ if (!active?.closest('[aria-modal="true"]') &&
+ (active === document.body || active?.closest("#canvas-assistant") ||
+ active === openFocusTarget.current))
+ editor.current?.focus();
+ openFocusTarget.current = null;
}, [open, chat.loaded, value.conversationId]);
const displayedAssets = [
...new Map(
@@ -232,7 +273,7 @@ export function AssistantPanel({
useEffect(() => {
if (nearBottom.current && log.current)
log.current.scrollTop = log.current.scrollHeight;
- }, [value.messages, open]);
+ }, [value.messages, open, results]);
useEffect(() => () => confirming.current?.abort(), [pending?.id]);
const confirmPending = async (end: number) => {
if (!pending || referenceDisabled || confirming.current) return;
@@ -317,6 +358,21 @@ export function AssistantPanel({
(assets) => editor.current?.insert(assets) ?? false,
);
+ function referenceResult(asset: Asset) {
+ const input = editor.current;
+ if (!input || referenceDisabled || chat.changing) return;
+ if (value.draftContent?.some((part) =>
+ part.type === "reference" && part.binding === "asset" &&
+ part.assetId === asset.id && part.fingerprint === asset.fingerprint
+ )) {
+ input.focus();
+ return;
+ }
+ // Insert beside a selection so clicking a result keeps any highlighted draft.
+ const end = input.caret().end;
+ input.insert([pinnedReferenceAsset(asset)], { start: end, end });
+ }
+
useEffect(() => {setMediaPreview(null);}, [documentId, value.conversationId, open]);
useEffect(() => {
const closePreview = () => setMediaPreview(null);
@@ -333,6 +389,17 @@ export function AssistantPanel({
}
const hoveredAsset = mediaPreview && displayedAssets.find(item => item.id === mediaPreview.assetId);
+ const projectAssetsButton = !collapsible && (
+
+ setProjectAssetsOpen((previous) => !previous)}>
+
+
+
+ );
+
const latestUser = value.messages.at(-2);
const latestTrace = latestReply?.role === "assistant" && latestUser?.role === "user" &&
new URLSearchParams({
@@ -347,6 +414,8 @@ export function AssistantPanel({
setMediaPreview(null)}
@@ -360,14 +429,14 @@ export function AssistantPanel({
event.preventDefault();
event.stopPropagation();
if (mediaPreview) setMediaPreview(null);
- else onClose();
+ else if (collapsible) onClose();
}
}}
onDragOver={(event) => {
if (event.dataTransfer.types.includes("Files")) {
event.preventDefault();
event.stopPropagation();
- setDragOver(true);
+ if (!readOnly) setDragOver(true);
}
}}
onDragLeave={(event) => {
@@ -387,7 +456,8 @@ export function AssistantPanel({
{message.role === "assistant" && (
+ {!collapsible &&
}
OpenDirector
{(message.modelIsCliDefault || message.model) &&
{message.modelIsCliDefault
? t("assistant.agent.cliDefault")
@@ -504,6 +577,27 @@ export function AssistantPanel({
: t("assistant.reply.empty"))
)}
+ {!collapsible && message.role === "assistant" && previous?.role === "user" &&
+ results.get(previous.id)?.map((result) => (
+
node.id === result.itemId)}
+ referenceDisabled={referenceDisabled || chat.changing}
+ onPreview={onPreviewResult}
+ onReference={referenceResult}
+ onViewOnCanvas={onViewResultOnCanvas}
+ timelines={timelines.get(result.assetId) ?? []}
+ onEdit={onEditResult}
+ />
+ ))}
+ {!collapsible && message.role === "assistant" && message.publishedTimelines?.projectId === documentId &&
+ message.publishedTimelines.timelines.map(result => (
+
+ ))}
{trace && (
@@ -524,6 +618,7 @@ export function AssistantPanel({
})}
+ {readOnly && projectAssetsButton}
{chat.error && (
{chat.error}
@@ -703,15 +798,23 @@ export function AssistantPanel({
/>
+ {!readOnly && projectAssetsButton}
= 64}
onClick={() => fileInput.current?.click()}
>
- +
+ {collapsible ? (
+ +
+ ) : (
+ <>
+
+ {t("assistant.panel.upload")}
+ >
+ )}
onOpenSettings("agent")}
/>
{t("assistant.agent.noAgentModels")}{" · "}
-
+ onOpenSettings("agent")}>
{t("assistant.agent.configureModel")}
>
@@ -805,7 +908,7 @@ export function AssistantPanel({
)}
- {!layout.mobile && (
+ {collapsible && !layout.mobile && !layout.floating && (
{t("assistant.panel.dropHint")}
)}
+ {projectAssetsOpen &&
setProjectAssetsOpen(false)}
+ actions={readOnly ? { kind: "preview", onPreview: onPreviewResult } : {
+ kind: "chat",
+ referenceDisabled: referenceDisabled || chat.changing,
+ onReference: referenceResult,
+ onCreateTimeline: onCreateProjectTimeline,
+ onOpenTimeline: onOpenProjectTimeline,
+ }}
+ />}
{uploads.dialog}
);
diff --git a/src/canvas/AssistantPickers.tsx b/src/canvas/AssistantPickers.tsx
index 3ca2095ca..f7465eca6 100644
--- a/src/canvas/AssistantPickers.tsx
+++ b/src/canvas/AssistantPickers.tsx
@@ -51,7 +51,7 @@ export function ModelPicker({
models: ModelConfig[];
selections: ModelSelections;
onChange: (kind: AssistantKind, id: string) => void;
- onConfigure: () => void;
+ onConfigure: (kind: AssistantKind) => void;
disabled: boolean;
includeAgent?: boolean;
}) {
@@ -97,7 +97,7 @@ export function ModelPicker({
}
function configure() {
setOpen(false);
- onConfigure();
+ onConfigure(kind);
}
function tabKeys(event: KeyboardEvent) {
const buttons = [
diff --git a/src/canvas/AssistantResultCard.tsx b/src/canvas/AssistantResultCard.tsx
new file mode 100644
index 000000000..fe9c955d0
--- /dev/null
+++ b/src/canvas/AssistantResultCard.tsx
@@ -0,0 +1,162 @@
+import { useEffect, useRef, useState } from "react";
+import type { Asset, ProjectSnapshot } from "../contracts/generated.ts";
+import { useT } from "../i18n/I18nProvider.tsx";
+import { deliveredTimelineState, type DeliveredTimeline, type ProjectEditorTarget, type ProjectTimelineTarget } from "./assistantResultEditors.ts";
+import type { AssistantResult } from "./assistantResults.ts";
+import { AssetThumbnail } from "./CreationAssetPreview.tsx";
+import { CanvasIcon } from "./CanvasIcon.tsx";
+import { assetDisplayName } from "./assetNames.ts";
+
+function useResultAction() {
+ const t = useT();
+ const [busy, setBusy] = useState(false);
+ const pending = useRef(null);
+ useEffect(() => () => pending.current?.abort(), []);
+ const [error, setError] = useState("");
+ async function open(action: (signal: AbortSignal) => Promise) {
+ if (pending.current) return;
+ const controller = new AbortController();
+ pending.current = controller;
+ setBusy(true);
+ setError("");
+ try {
+ await action(controller.signal);
+ } catch (cause) {
+ if (!controller.signal.aborted)
+ setError(cause instanceof Error ? cause.message : t("canvas.workspace.error.editorUnavailable"));
+ } finally {
+ pending.current = null;
+ if (!controller.signal.aborted) setBusy(false);
+ }
+ }
+ return { open, busy, error };
+}
+
+export function AssistantResultCard({
+ projectId, result, timelines, readOnly, locateDisabled, referenceDisabled, onPreview, onReference, onViewOnCanvas, onEdit,
+}: {
+ projectId: string;
+ result: AssistantResult;
+ timelines: (ProjectTimelineTarget & { itemId: string; title: string })[];
+ onEdit: (target: ProjectEditorTarget, signal: AbortSignal) => Promise;
+ readOnly: boolean;
+ locateDisabled: boolean;
+ referenceDisabled: boolean;
+ onPreview: (asset: Asset) => void;
+ onReference: (asset: Asset) => void;
+ onViewOnCanvas: (asset: Asset, itemId?: string | null) => Promise;
+}) {
+ const t = useT();
+ const { open, busy, error } = useResultAction();
+ const [timelineId, setTimelineId] = useState("");
+ const timeline = timelines.length === 1 ? timelines[0] : timelines.find(item => item.itemId === timelineId);
+ const { asset, status } = result;
+ const title = assetDisplayName(asset?.name ?? result.name ?? t("assistant.result.unavailable"));
+ if (!asset) {
+ return (
+
+
+
+ {title}
+ {result.name && {t("assistant.result.unavailable")} }
+
+
+
+ );
+ }
+ return (
+
+ onPreview(asset)}>
+
+
+ {title}
+
+ {t(`canvasNodes.kind.${asset.kind}`)}
+ {status !== "asset" && <> · {t(`assistant.result.${status}`)}>}
+
+
+ {t("assistant.result.preview")}
+
+
+
+
+ onReference(asset)}>
+ {t("assistant.result.reference")}
+
+ {["image", "audio", "video"].includes(asset.kind) && (
+ void open(signal => onEdit({ kind: "media", asset, itemId: result.itemId }, signal))}>
+ {t("assistant.result.editMedia")}
+
+ )}
+ void open(() => onViewOnCanvas(asset, result.itemId))}>
+ {t("assistant.result.viewOnCanvas")}
+
+
+ {timelines.length > 0 && (
+
+ {timelines.length > 1 && (
+ setTimelineId(event.target.value)}>
+ {t("assistant.result.timeline")}
+ {timelines.map(target => (
+
+ {target.title || t("assistant.result.timeline")}
+ {(!target.title || timelines.some(other => other !== target && other.title === target.title)) &&
+ ` · ${target.itemId}`}
+
+ ))}
+
+ )}
+ timeline && void open(signal => onEdit(timeline, signal))}>
+ {t("assistant.result.openTimeline")}
+
+
+ )}
+ {error && {error}
}
+
+ );
+}
+
+export function AssistantTimelineResultCard({ result, projectId, eventCursor, snapshot, readOnly, onEdit }: {
+ result: DeliveredTimeline;
+ readOnly: boolean;
+ projectId: string;
+ eventCursor?: number;
+ snapshot?: ProjectSnapshot;
+ onEdit: (target: ProjectEditorTarget, signal: AbortSignal) => Promise;
+}) {
+ const t = useT();
+ const { open, busy, error } = useResultAction();
+ const current = deliveredTimelineState(result, projectId, eventCursor, snapshot);
+ const title = current.title || t("assistant.result.timeline");
+ return (
+
+
+
+
+ {title}
+ {t("assistant.result.timelineVersion", { revision: result.revision })}
+ {current.status === "pending" && {t("assistant.result.syncingTimeline")} }
+ {current.status === "missing" && {t("errors.backend.timelineSourceMissing")} }
+
+
+ {current.status === "available" && (
+
+ void open(signal => onEdit({
+ kind: "timeline", projectId, itemId: result.itemId,
+ editorId: result.editorId, revision: current.revision,
+ }, signal))}>
+ {current.revision === result.revision ? t("assistant.result.openTimeline")
+ : t("assistant.result.openTimelineVersion", { revision: current.revision })}
+
+
+ )}
+ {error && {error}
}
+
+ );
+}
diff --git a/src/canvas/CanvasCreationMenu.tsx b/src/canvas/CanvasCreationMenu.tsx
index cc165d4fc..9bd3dc7ce 100644
--- a/src/canvas/CanvasCreationMenu.tsx
+++ b/src/canvas/CanvasCreationMenu.tsx
@@ -50,12 +50,18 @@ export function CreationMenuContent({
onAssets,
onUpload,
allowedKinds,
-}: CreationActions & { allowedKinds?: readonly CanvasNodeKind[] }) {
+ nodesOnly = false,
+}: CreationActions & {
+ allowedKinds?: readonly CanvasNodeKind[];
+ nodesOnly?: boolean;
+}) {
const t = useT();
return (
<>
{t("canvas.menu.newNode")}
- {CANVAS_CREATION_TOOLS.map((tool) =>
+ {CANVAS_CREATION_TOOLS.filter(
+ (tool) => !nodesOnly || !tool.unavailable,
+ ).map((tool) =>
tool.unavailable ? (
{t(tool.labelKey)}
+ {nodesOnly && tool.kind === "text" && (
+ T
+ )}
),
)}
- {!allowedKinds && (
+ {!allowedKinds && !nodesOnly && (
<>
@@ -108,6 +120,7 @@ export function CreationMenuContent({
export function CanvasCreationMenu({
x,
y,
+ anchor,
mode,
canPaste,
canUndo,
@@ -121,6 +134,7 @@ export function CanvasCreationMenu({
}: CreationActions & {
x: number;
y: number;
+ anchor?: HTMLButtonElement;
mode: "create" | "context";
canPaste: boolean;
canUndo: boolean;
@@ -167,7 +181,11 @@ export function CanvasCreationMenu({
useEffect(() => {
const dismiss = (event: PointerEvent) => {
const target = event.target as Node;
- if (!root.current?.contains(target) && !submenu.current?.contains(target))
+ if (
+ !root.current?.contains(target) &&
+ !submenu.current?.contains(target) &&
+ !anchor?.contains(target)
+ )
close.current();
};
document.addEventListener("pointerdown", dismiss, true);
@@ -175,7 +193,7 @@ export function CanvasCreationMenu({
document.removeEventListener("pointerdown", dismiss, true);
cancelClose();
};
- }, []);
+ }, [anchor]);
useLayoutEffect(() => {
root.current
?.querySelector('[role="menuitem"]')
@@ -199,15 +217,15 @@ export function CanvasCreationMenu({
closeSubmenu();
trigger.current?.focus();
} else {
- root.current
- ?.closest(".cw-workspace")
- ?.focus({ preventScroll: true });
+ (anchor ?? root.current?.closest(".cw-workspace"))?.focus({
+ preventScroll: true,
+ });
close.current();
}
};
document.addEventListener("keydown", escape);
return () => document.removeEventListener("keydown", escape);
- }, [expanded]);
+ }, [expanded, anchor]);
const run = (action: () => void) => {
action();
onClose();
@@ -225,6 +243,7 @@ export function CanvasCreationMenu({
{
- if (event.key === "Escape") {
+ if (
+ anchor &&
+ event.key.toLowerCase() === "t" &&
+ !event.ctrlKey &&
+ !event.metaKey &&
+ !event.altKey &&
+ !event.nativeEvent.isComposing
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ creationActions.onCreate("text");
+ } else if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
if (expanded) {
closeSubmenu();
trigger.current?.focus();
} else {
- root.current
- ?.closest(".cw-workspace")
- ?.focus({ preventScroll: true });
+ (
+ anchor ?? root.current?.closest(".cw-workspace")
+ )?.focus({ preventScroll: true });
onClose();
}
} else menuKeys(event);
@@ -254,7 +284,12 @@ export function CanvasCreationMenu({
return (
<>
{mode === "create"
- ? shell( )
+ ? shell(
+ ,
+ )
: shell(
<>
= {
plus: ,
cube: ,
collapse: ,
+ grip: ,
+ floatPanel: (
+ <>
+
+
+ >
+ ),
+ dockLeft: (
+ <>
+
+
+ >
+ ),
+ dockRight: (
+ <>
+
+
+ >
+ ),
thinking: (
),
diff --git a/src/canvas/CanvasToolRail.tsx b/src/canvas/CanvasToolRail.tsx
index 55b701846..bd2f132d8 100644
--- a/src/canvas/CanvasToolRail.tsx
+++ b/src/canvas/CanvasToolRail.tsx
@@ -1,170 +1,93 @@
-import { useRef, useState, type ButtonHTMLAttributes } from "react";
-import { CanvasIcon } from "./CanvasIcon";
-import { TooltipButton } from "./TooltipButton";
+import { useState, type KeyboardEvent } from "react";
import { useT } from "../i18n/I18nProvider";
+import { CanvasIcon } from "./CanvasIcon";
-export type CanvasToolRailItem = {
- name: string;
- icon?: string;
- label: string;
- actionLabel?: string;
- shortcut?: string;
- active?: boolean;
- separatorBefore?: boolean;
- preserveCollapsedOnFocusRestore?: boolean;
- unavailable?: boolean;
- onClick?: () => void;
-};
-
-/** Reveal tool labels together and explain unavailable entries on hover or focus. */
export function CanvasToolRail({
- items,
- holdCollapsed,
+ menuOpen,
+ libraryOpen,
+ onToggleMenu,
+ onAssets,
+ onUpload,
}: {
- items: CanvasToolRailItem[];
- holdCollapsed: boolean;
+ menuOpen: boolean;
+ libraryOpen: boolean;
+ onToggleMenu: (trigger: HTMLButtonElement) => void;
+ onAssets: () => void;
+ onUpload: () => void;
}) {
const t = useT();
- const [hovered, setHovered] = useState(false);
- const [focused, setFocused] = useState(false);
- const [dismissed, setDismissed] = useState(false);
- const [activeIndex, setActiveIndex] = useState(0);
- const focusRestoreTarget = useRef(null);
- const [restoreSuppressed, setRestoreSuppressed] = useState(false);
- const reveal = () => {
- focusRestoreTarget.current = null;
- setRestoreSuppressed(false);
- setDismissed(false);
+ const [tabStop, setTabStop] = useState(0);
+ const navigate = (event: KeyboardEvent) => {
+ const buttons = Array.from(event.currentTarget.querySelectorAll("button"));
+ const index = buttons.indexOf(event.target as HTMLButtonElement);
+ let next: number;
+ switch (event.key) {
+ case "Home":
+ next = 0;
+ break;
+ case "End":
+ next = buttons.length - 1;
+ break;
+ case "ArrowDown":
+ next = (index + 1) % buttons.length;
+ break;
+ case "ArrowUp":
+ next = (index - 1 + buttons.length) % buttons.length;
+ break;
+ default:
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ buttons[next].focus({ preventScroll: true });
};
- const revealed =
- !holdCollapsed && !dismissed && !restoreSuppressed && (hovered || focused);
-
return (
{
- setHovered(true);
- if (!focusRestoreTarget.current && !restoreSuppressed)
- setDismissed(false);
- }}
- onMouseLeave={() => setHovered(false)}
- onPointerMove={(event) => {
- if (!event.buttons && (focusRestoreTarget.current || restoreSuppressed))
- reveal();
- }}
+ className="cw-rail"
+ role="toolbar"
+ aria-label={t("canvas.rail.tools")}
+ aria-orientation="vertical"
+ onKeyDown={navigate}
>
-
-
-
{
- setFocused(true);
- // Restoring focus after a picker or panel closes must not reopen the labels.
- if (event.target === focusRestoreTarget.current) {
- focusRestoreTarget.current = null;
- setRestoreSuppressed(true);
- setDismissed(false);
- } else reveal();
- }}
- onBlurCapture={(event) => {
- if (
- !event.currentTarget.contains(event.relatedTarget as Node | null)
- ) {
- setFocused(false);
- setDismissed(false);
- if (!focusRestoreTarget.current) setRestoreSuppressed(false);
- }
- }}
- onKeyDown={(event) => {
- if (event.key === "Escape") {
- event.preventDefault();
- event.stopPropagation();
- setDismissed(true);
- return;
- }
- const buttons = Array.from(
- event.currentTarget.querySelectorAll("button"),
- );
- const index = buttons.indexOf(event.target as HTMLButtonElement);
- const next =
- event.key === "Home"
- ? 0
- : event.key === "End"
- ? buttons.length - 1
- : event.key === "ArrowDown"
- ? (index + 1) % buttons.length
- : event.key === "ArrowUp"
- ? (index - 1 + buttons.length) % buttons.length
- : null;
- if (next !== null) {
- event.preventDefault();
- reveal();
- buttons[next]?.focus({ preventScroll: true });
- buttons[next]?.scrollIntoView({ block: "nearest" });
- } else if (event.key === "Tab") {
- reveal();
- }
- }}
- >
- {items.map((item, index) => {
- const props: ButtonHTMLAttributes = {
- type: "button",
- className: `cw-rail-button ${item.active ? "is-active" : ""}`,
- "aria-label": item.actionLabel ?? item.label,
- "aria-keyshortcuts": item.shortcut,
- "aria-pressed": item.active,
- "aria-disabled": item.unavailable || undefined,
- tabIndex: index === activeIndex ? 0 : -1,
- onFocus: () => setActiveIndex(index),
- onClick: (event) => {
- if (item.unavailable) {
- event.preventDefault();
- return;
- }
- focusRestoreTarget.current =
- item.preserveCollapsedOnFocusRestore
- ? event.currentTarget
- : null;
- setRestoreSuppressed(false);
- setDismissed(true);
- item.onClick?.();
- },
- };
- const content = (
- <>
-
-
-
-
- {item.label}
-
- >
- );
- return (
-
- {item.separatorBefore && }
- {item.unavailable ? (
-
- {content}
-
- ) : (
- {content}
- )}
-
- );
- })}
-
-
+
setTabStop(0)}
+ onClick={(event) => onToggleMenu(event.currentTarget)}
+ >
+
+ {t("canvas.rail.addNode")}
+
+
+
setTabStop(1)}
+ onClick={onAssets}
+ >
+
+ {t("canvas.rail.assets")}
+
+
setTabStop(2)}
+ onClick={onUpload}
+ >
+
+ {t("canvas.rail.upload")}
+
);
}
diff --git a/src/canvas/CreationAssetList.tsx b/src/canvas/CreationAssetList.tsx
index 5940a7b23..95eb71196 100644
--- a/src/canvas/CreationAssetList.tsx
+++ b/src/canvas/CreationAssetList.tsx
@@ -3,25 +3,22 @@ import {
useDeferredValue,
useEffect,
useId,
+ useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
-import type {
- Asset,
- CanvasItem,
- ProjectSnapshot,
-} from "../contracts/generated.ts";
+import type { Asset, ProjectSnapshot } from "../contracts/generated.ts";
import {
- assetReference,
creationClient,
creationPath,
- currentAsset,
objectVersion,
- visibleItems,
} from "../backend/creationClient.ts";
import { errorMessage, json, request } from "../backend/api.ts";
-import { createNode, type Point } from "./model.ts";
+import { classifyImportFile } from "./editorMedia.ts";
+import { readImportBatch } from "./importBatch.ts";
+import type { Point } from "./model.ts";
+import { findAssetItem, showExistingItem, showNewAssetItem } from "./canvasAssetPlacement.ts";
import { CanvasIcon } from "./CanvasIcon.tsx";
import {
AssetThumbnail,
@@ -127,15 +124,24 @@ interface Impact {
export function CreationAssetList({
projectId,
anchor,
+ hidden = false,
onClose,
- onLocate,
- position,
+ actions,
}: {
projectId: string;
anchor: HTMLElement | null;
+ hidden?: boolean;
onClose: () => void;
- onLocate: (id: string) => void;
- position: Point;
+ actions:
+ | { kind: "preview"; onPreview: (asset: Asset) => void }
+ | { kind: "canvas"; onLocate: (id: string) => void; position: Point }
+ | {
+ kind: "chat";
+ referenceDisabled: boolean;
+ onReference: (asset: Asset) => void;
+ onCreateTimeline: () => Promise;
+ onOpenTimeline: (itemId: string) => Promise;
+ };
}) {
const t = useT();
const previewLabel = (label: string) => {
@@ -184,6 +190,8 @@ export function CreationAssetList({
// The whole unfiltered listing; search, visibility and type only narrow it.
const [loaded, setLoaded] = useState(null),
[error, setError] = useState("");
+ const [actionError, setActionError] = useState("");
+ const [importing, setImporting] = useState(false);
const [revision, setRevision] = useState(0);
// The project whose complete list is on screen, and whether it changed
// again while a load was already running.
@@ -213,6 +221,12 @@ export function CreationAssetList({
impact: Impact;
} | null>(null);
const dialog = useRef(null);
+ const fileInput = useRef(null);
+ const importController = useRef(null);
+ useLayoutEffect(() => {
+ if (actions.kind === "preview") importController.current?.abort();
+ }, [actions.kind]);
+ const [createdTimelineId, setCreatedTimelineId] = useState(null);
const alive = useRef(true);
useEffect(() => {
alive.current = true;
@@ -221,6 +235,7 @@ export function CreationAssetList({
};
}, []);
useEffect(() => {
+ if (hidden) return;
const dismiss = (event: PointerEvent) => {
if (busy || !(event.target instanceof Node)) return;
if (
@@ -246,7 +261,7 @@ export function CreationAssetList({
document.removeEventListener("pointerdown", dismiss, true);
document.removeEventListener("keydown", escape, true);
};
- }, [anchor, busy, onClose]);
+ }, [anchor, busy, hidden, onClose]);
useEffect(() => {
const controller = new AbortController();
let active = true;
@@ -401,11 +416,11 @@ export function CreationAssetList({
useEffect(clearPreview, [category, query, visibility, clearPreview]);
const perform = async (action: () => Promise) => {
setBusy(true);
- setError("");
+ setActionError("");
try {
await action();
} catch (reason) {
- if (alive.current) setError(errorMessage(reason));
+ if (alive.current) setActionError(errorMessage(reason));
} finally {
if (alive.current) setBusy(false);
}
@@ -464,69 +479,63 @@ export function CreationAssetList({
setAttempt((n) => n + 1);
}
};
+ const importFiles = async (files: File[]) => {
+ const client = creationClient(projectId);
+ setImporting(true);
+ const controller = new AbortController();
+ importController.current = controller;
+ try {
+ const { failures } = await readImportBatch(files, async (file, signal) => {
+ await client.importBlob(file, file.name, classifyImportFile(file).kind, undefined, undefined, signal);
+ }, controller.signal);
+ if (failures.length) throw new Error(failures.map(({ name, message }) =>
+ t("canvas.workspace.toast.assetIssue", { name, reason: message }),
+ ).join(t("canvas.workspace.list.separator")));
+ } catch (cause) {
+ if (!controller.signal.aborted) throw cause;
+ } finally {
+ importController.current = null;
+ if (alive.current) {
+ setAttempt((value) => value + 1);
+ setImporting(false);
+ }
+ }
+ };
const open = async (row: Row) => {
+ if (actions.kind === "preview") {
+ onClose();
+ actions.onPreview(row.asset);
+ return;
+ }
+ if (actions.kind === "chat") {
+ actions.onReference(row.asset);
+ onClose();
+ return;
+ }
const client = creationClient(projectId);
await client.refresh();
- const visible = visibleItems(client.snapshot);
- const owners = client.snapshot.canvasItems.filter(
- (item) => currentAsset(client.snapshot, item)?.id === row.asset.id,
- );
- let item = owners.find((item) => visible.has(item.id)) ?? owners[0];
+ const item = findAssetItem(client.snapshot, row.asset.id);
if (row.owners.length && !item) {
setAttempt((n) => n + 1);
throw new Error(t("canvasNodes.assets.versionChanged"));
}
- if (item && !visible.has(item.id)) {
- const versions = [objectVersion("canvas_item", item)];
- let parentId = item.parentId;
- while (parentId) {
- const parent = client.snapshot.canvasItems.find(
- (item) => item.id === parentId,
- )!;
- versions.push(objectVersion("canvas_item", parent));
- parentId = parent.parentId;
- }
- await client.command("canvas.show", { item }, versions);
- } else if (!item) {
- const node = createNode(
- row.asset.kind,
- { x: position.x - 150, y: position.y - 150 },
- {
- media: {
- width: row.asset.metadata.width ?? undefined,
- height: row.asset.metadata.height ?? undefined,
- },
- },
- );
- item = {
- id: node.id,
- projectId,
- revision: 1,
- kind: row.asset.kind,
- title: row.asset.name,
- position: node.position,
- width: node.width,
- height: node.height,
- zIndex: 0,
- locked: false,
- visible: true,
- parentId: null,
- tags: [],
- editors: [],
- binding: row.specId
- ? {
- role: "generation",
- objectRef: { objectType: "generation_spec", id: row.specId },
- materialOverride: null,
- }
- : { role: "material", objectRef: assetReference(row.asset) },
- } as CanvasItem;
- await client.command("canvas.show", { item });
- }
- onLocate(item.id);
+ const itemId = item ? await showExistingItem(client, item)
+ : await showNewAssetItem(client, row.asset, actions.position, row.specId);
+ actions.onLocate(itemId);
onClose();
};
const openNode = async (row: NodeRow) => {
+ if (actions.kind === "preview") {
+ if (row.asset) actions.onPreview(row.asset);
+ onClose();
+ return;
+ }
+ if (actions.kind === "chat") {
+ if (row.kind === "timeline") await actions.onOpenTimeline(row.itemId);
+ else if (row.asset) actions.onReference(row.asset);
+ onClose();
+ return;
+ }
const client = creationClient(projectId);
await client.refresh();
const item = client.snapshot.canvasItems.find(
@@ -536,19 +545,8 @@ export function CreationAssetList({
setAttempt((value) => value + 1);
throw new Error(t("canvasNodes.assets.nodeChanged"));
}
- if (!visibleItems(client.snapshot).has(item.id)) {
- const versions = [objectVersion("canvas_item", item)];
- let parentId = item.parentId;
- while (parentId) {
- const parent = client.snapshot.canvasItems.find(
- (item) => item.id === parentId,
- )!;
- versions.push(objectVersion("canvas_item", parent));
- parentId = parent.parentId;
- }
- await client.command("canvas.show", { item }, versions);
- }
- onLocate(item.id);
+ await showExistingItem(client, item);
+ actions.onLocate(item.id);
onClose();
};
const labels: Record = {
@@ -565,7 +563,10 @@ export function CreationAssetList({
<>
event.stopPropagation()}
@@ -633,6 +634,32 @@ export function CreationAssetList({
>
) : (
<>
+ {actions.kind === "chat" && (
+
+ fileInput.current?.click()}>
+ {t(importing ? "workspaceModes.importingMedia" : "workspaceModes.importMedia")}
+
+ {
+ const files = Array.from(event.target.files ?? []);
+ event.target.value = "";
+ if (files.length) void perform(() => importFiles(files));
+ }}
+ />
+ void perform(async () => {
+ const itemId = createdTimelineId ?? await actions.onCreateTimeline();
+ if (!alive.current) return;
+ // Creation has committed. An opening failure must retry this item.
+ setCreatedTimelineId(itemId);
+ await actions.onOpenTimeline(itemId);
+ onClose();
+ })}>
+ {t(createdTimelineId ? "workspaceModes.retryOpenTimeline" : "workspaceModes.createTimeline")}
+
+
+ )}
void perform(() => openNode(row))}
onMouseEnter={(event) =>
showPreview(event.currentTarget, {
@@ -775,7 +803,11 @@ export function CreationAssetList({
{row.title}
- {row.visible
+ {actions.kind === "preview"
+ ? row.asset && t("assistant.result.preview")
+ : actions.kind === "chat"
+ ? t(row.kind === "timeline" ? "canvas.workspace.menu.openEditor" : "workspaceModes.referenceAsset")
+ : row.visible
? t("canvasNodes.assets.locate")
: t("canvasNodes.assets.restore")}
@@ -788,7 +820,7 @@ export function CreationAssetList({
const name = owner?.title.trim() || row.asset.name;
return (
-
+ />}
void perform(() => open(row))}
onMouseEnter={(event) =>
showPreview(event.currentTarget, {
@@ -861,7 +894,11 @@ export function CreationAssetList({
{name}
- {owner?.visible
+ {actions.kind === "preview"
+ ? t("assistant.result.preview")
+ : actions.kind === "chat"
+ ? t("workspaceModes.referenceAsset")
+ : owner?.visible
? t("canvasNodes.assets.locate")
: owner
? t("canvasNodes.assets.restore")
@@ -879,7 +916,7 @@ export function CreationAssetList({
)}
- {(!!listing?.items.length || !!selected.length) && (
+ {actions.kind === "canvas" && (!!listing?.items.length || !!selected.length) && (
)}
- {error && (
+ {(error || actionError) && (
- {error}
+ {actionError || error}
{
+ setActionError("");
if (deleting) void perform(() => inspect(deleting.ids));
else setAttempt((n) => n + 1);
}}
@@ -925,7 +963,7 @@ export function CreationAssetList({
)}
- {preview && (
+ {!hidden && preview && (
(null),
closeRef = useRef(onClose),
id = useId();
@@ -103,6 +105,7 @@ export function EditorModal({
{title}
{subtitle}
+ {modeSwitch}
diff --git a/src/canvas/ImageEditor.tsx b/src/canvas/ImageEditor.tsx
index bcacee416..2fff4988f 100644
--- a/src/canvas/ImageEditor.tsx
+++ b/src/canvas/ImageEditor.tsx
@@ -1,4 +1,5 @@
import {
+ useContext,
useEffect,
useId,
useMemo,
@@ -10,6 +11,7 @@ import { useT } from "../i18n/I18nProvider.tsx";
import type { Translate } from "../i18n/I18nProvider.tsx";
import type { CanvasNode } from "./model";
import { LayerBoard } from "./LayerBoard";
+import { EditorModeSwitchContext } from "./workspace/WorkspaceModeSwitch";
import type { LayerDocument } from "./layerDocument";
import "./image-editor.css";
import { INITIAL_CROP_OPTIONS, type ImageCropState } from "./imageCrop.ts";
@@ -171,6 +173,7 @@ function CropEditor({
onOpenLayers: (src: string, unchanged: boolean) => void;
}) {
const t = useT();
+ const modeSwitch = useContext(EditorModeSwitchContext);
const [image, setImage] = useState(null);
const [options, setOptions] = useState({ ...INITIAL_OPTIONS });
const [loadError, setLoadError] = useState("");
@@ -327,6 +330,7 @@ function CropEditor({
document.body.style.overflow = "hidden";
dialogRef.current?.focus();
const handleKey = (event: KeyboardEvent) => {
+ if (!dialogRef.current?.contains(event.target as Node)) return;
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
@@ -459,6 +463,7 @@ function CropEditor({
{node.data.title}
+ {modeSwitch}
(null);
const document = history?.present;
const state = useRef(history);
@@ -781,6 +784,7 @@ export function LayerBoard({
{t("editors.layers.title")} {title}
+ {modeSwitch}
{onBack && (
diff --git a/src/canvas/ModelSetup.tsx b/src/canvas/ModelSetup.tsx
index efa67ec2c..c5b7bd1c1 100644
--- a/src/canvas/ModelSetup.tsx
+++ b/src/canvas/ModelSetup.tsx
@@ -2,20 +2,23 @@ import type { BackendModels } from "../backend/models";
import { isGenerationModel, type ModelConfig } from "../backend/rules";
import { useI18n } from "../i18n/I18nProvider";
import { CanvasIcon } from "./CanvasIcon";
+import type { WorkspaceMode } from "./workspaceMode";
import "./model-setup.css";
const kinds = ["agent", "image", "video", "audio"] as const;
type SetupKind = typeof kinds[number];
const preference = "opendirector.modelSetup.v1";
-let dismissed = false;
-export function dismissModelSetup() {
- dismissed = true;
- try { localStorage.setItem(preference, "dismissed"); } catch { /* Session fallback. */ }
+let sessionProgress: string | null = null;
+function modelSetupProgress() {
+ try { return sessionProgress ?? localStorage.getItem(preference); } catch { return sessionProgress; }
}
-export function shouldShowModelSetup() {
- if (dismissed) return false;
- try { return !localStorage.getItem(preference); } catch { return true; }
+export function dismissModelSetup(mode: WorkspaceMode) {
+ const progress = mode === "agent" ? "chat-ready" : "dismissed";
+ try { localStorage.setItem(preference, progress); sessionProgress = null; }
+ catch { sessionProgress = progress; }
}
+export function shouldShowModelSetup() { return !modelSetupProgress(); }
+export function needsFirstCanvasSetup() { return modelSetupProgress() === "chat-ready"; }
function modelSetupMissing(models: ModelConfig[]) {
return kinds.filter(kind => !models.some(model => model.kind === kind && isGenerationModel(model)));
}
diff --git a/src/canvas/SelectionBarAnchor.tsx b/src/canvas/SelectionBarAnchor.tsx
index 0e9196b69..07b57d548 100644
--- a/src/canvas/SelectionBarAnchor.tsx
+++ b/src/canvas/SelectionBarAnchor.tsx
@@ -27,10 +27,14 @@ export function SelectionBarAnchor({
const viewport = useViewport();
const [element, setElement] = useState(null);
const [size, setSize] = useState({ width: 0, height: 0 });
+ const [region, setRegion] = useState({ width: window.innerWidth, height: window.innerHeight });
useLayoutEffect(() => {
if (!element) return;
const measure = () => {
const rect = element.getBoundingClientRect();
+ const host = element.closest(".cw-canvas-region")?.getBoundingClientRect();
+ if (host) setRegion(current => current.width === host.width && current.height === host.height
+ ? current : { width: host.width, height: host.height });
setSize((current) =>
current.width === rect.width && current.height === rect.height
? current
@@ -40,17 +44,19 @@ export function SelectionBarAnchor({
measure();
const observer = new ResizeObserver(measure);
observer.observe(element);
+ const host = element.closest(".cw-canvas-region");
+ if (host) observer.observe(host);
return () => observer.disconnect();
}, [element]);
const bounds = boundsOfNodes(nodes, allNodes);
if (!bounds) return null;
- const narrow = window.innerWidth < 700;
+ const narrow = region.width < 700;
const left = narrow ? SAFE_LEFT_NARROW : SAFE_LEFT;
const safe = {
x: left,
y: SAFE_TOP,
- width: Math.max(1, window.innerWidth - left - SAFE_RIGHT),
- height: Math.max(1, window.innerHeight - SAFE_TOP - SAFE_BOTTOM),
+ width: Math.max(1, region.width - left - SAFE_RIGHT),
+ height: Math.max(1, region.height - SAFE_TOP - SAFE_BOTTOM),
};
// Node coordinates start at the media frame; the title sits above it.
const envelope = {
diff --git a/src/canvas/SettingsDialog.tsx b/src/canvas/SettingsDialog.tsx
index aa7c22c09..29bcda06b 100644
--- a/src/canvas/SettingsDialog.tsx
+++ b/src/canvas/SettingsDialog.tsx
@@ -128,12 +128,14 @@ export function SettingsDialog({
theme,
initialCategory,
initialModelKind = null,
+ canvasEntry,
onClose,
}: {
catalog: BackendModels;
theme: ThemeControls;
initialCategory: "general" | "models";
initialModelKind?: SettingsModelKind | null;
+ canvasEntry?: { ready: boolean; onContinue: () => void };
onClose: () => void;
}) {
const { t } = useI18n();
@@ -219,6 +221,12 @@ export function SettingsDialog({
+ {canvasEntry && (
+
+ {t(canvasEntry.ready ? "firstRun.canvasModelReady" : "firstRun.canvasModelRequired")}
+ {t("firstRun.enterCanvas")}
+
+ )}
{theme.error && (
{theme.error}
diff --git a/src/canvas/SkillPicker.tsx b/src/canvas/SkillPicker.tsx
index 31361d505..fee82e30d 100644
--- a/src/canvas/SkillPicker.tsx
+++ b/src/canvas/SkillPicker.tsx
@@ -83,17 +83,22 @@ export function SkillPicker({
useLayoutEffect(() => {
if (!open || !root.current) return;
const popover = root.current.querySelector(".cw-skill-popover")!;
- const bounds = root.current.closest(".cw-assistant-composer")!.getBoundingClientRect();
- const width = Math.min(420, bounds.width, window.innerWidth - 16);
- popover.style.width = `${width}px`;
- popover.style.left = `${Math.max(8, Math.min(bounds.left, window.innerWidth - width - 8))}px`;
- popover.style.bottom = `${window.innerHeight - bounds.top + 8}px`;
- popover.style.maxHeight = `${Math.max(120, bounds.top - 24)}px`;
+ const composer = root.current.closest(".cw-assistant-composer")!;
+ const position = () => {
+ const bounds = composer.getBoundingClientRect();
+ const width = Math.min(420, bounds.width, window.innerWidth - 16);
+ popover.style.width = `${width}px`;
+ popover.style.left = `${Math.max(8, Math.min(bounds.left, window.innerWidth - width - 8))}px`;
+ popover.style.bottom = `${window.innerHeight - bounds.top + 8}px`;
+ popover.style.maxHeight = `${Math.max(120, bounds.top - 24)}px`;
+ };
+ position();
popover.showPopover();
if (!slash) popover.querySelector("input")?.focus({preventScroll: true});
- const dismiss = () => {setManual(false); setDismissed(true);};
- window.addEventListener("resize", dismiss);
- return () => window.removeEventListener("resize", dismiss);
+ const observer = new ResizeObserver(position);
+ observer.observe(composer);
+ window.addEventListener("resize", position);
+ return () => { observer.disconnect(); window.removeEventListener("resize", position); };
}, [open, slash]);
function close() {
diff --git a/src/canvas/TimelineEditor.tsx b/src/canvas/TimelineEditor.tsx
index 86046413d..4e116a10b 100644
--- a/src/canvas/TimelineEditor.tsx
+++ b/src/canvas/TimelineEditor.tsx
@@ -68,6 +68,8 @@ export interface TimelineEditorProps {
node: CanvasNode;
readOnly?: boolean;
resources?: CanvasResource[];
+ projectResources?: CanvasResource[];
+ onReadProjectMedia?: (assetId: string, signal: AbortSignal) => Promise;
/** Returns false when the canvas rejected the edit, so the session stays open. */
onApply: (data: TimelineData) => boolean | void | Promise;
onRender: (result: LinkedMediaResult) => boolean | Promise;
@@ -109,6 +111,8 @@ export function TimelineEditor({
node,
readOnly = false,
resources = [],
+ projectResources = [],
+ onReadProjectMedia,
onApply,
onRender,
onPrepareRender,
@@ -178,13 +182,18 @@ export function TimelineEditor({
[busy, setBusy] = useState(false),
[audioTrack, setAudioTrack] = useState("");
const [inserted, setInserted] = useState(false);
+ const [publishing, setPublishing] = useState(false);
+ const [downloadStarted, setDownloadStarted] = useState(false);
const [renderProgress, setRenderProgress] = useState(null);
const [rendered, setRendered] = useState(null);
const [textSourceId, setTextSourceId] = useState("");
const fontInput = useRef(null);
- const textResources = resources.filter(
- (r) => r.kind === "text" && !/\.(srt|ass|vtt)$/i.test(r.title),
- );
+ const textResources = useMemo(() => {
+ const canvasText = resources.filter((r) => r.kind === "text");
+ const canvasIds = new Set(canvasText.map((r) => r.assetId));
+ const projectText = projectResources.filter((r) => r.kind === "text" && !canvasIds.has(r.assetId));
+ return [...canvasText, ...projectText].filter((r) => !/\.(srt|ass|vtt)$/i.test(r.title));
+ }, [resources, projectResources]);
const jsonInput = useRef(null),
history = useRef<{ past: TimelineData[]; future: TimelineData[] }>({
past: [],
@@ -308,8 +317,8 @@ export function TimelineEditor({
[librarySource, setLibrarySource] = useState("all");
const libraryResources = useMemo(
() =>
- timelineLibraryResources(timeline, resources, librarySource, libraryKind),
- [resources, timeline, libraryKind, librarySource],
+ timelineLibraryResources(timeline, resources, librarySource, libraryKind, projectResources),
+ [resources, projectResources, timeline, libraryKind, librarySource],
);
const segments = useMemo(
() => timelineSegments(dragPreview ?? timeline),
@@ -605,7 +614,10 @@ export function TimelineEditor({
const addResource = async (resource: CanvasResource) => {
const controller = beginLoad();
try {
- const resolved = await withMediaDuration(resource, controller.signal);
+ const source = !resource.src && resource.assetId && onReadProjectMedia
+ ? { ...resource, src: await onReadProjectMedia(resource.assetId, controller.signal) }
+ : resource;
+ const resolved = await withMediaDuration(source, controller.signal);
if (ownsLoad(controller))
change((current) =>
addTimelineClip(
@@ -1065,6 +1077,7 @@ export function TimelineEditor({
setPlaying(false);
setRendered(null);
setInserted(false);
+ setDownloadStarted(false);
setRenderProgress(0);
try {
const publish = onPrepareRender
@@ -1100,6 +1113,7 @@ export function TimelineEditor({
};
const insertRender = async () => {
if (!rendered) return;
+ setPublishing(true);
const controller = beginLoad();
try {
const src = await mediaBlobDataUrl(rendered, controller.signal);
@@ -1132,7 +1146,20 @@ export function TimelineEditor({
: t("timeline.error.addCanvasFailed"),
);
} finally {
- if (ownsLoad(controller)) setBusy(false);
+ if (ownsLoad(controller)) {
+ setPublishing(false);
+ setBusy(false);
+ }
+ }
+ };
+ const downloadRender = () => {
+ if (!rendered) return;
+ try {
+ downloadFile(rendered, downloadFilename(node.data.title, "video/mp4"));
+ setDownloadStarted(true);
+ } catch (cause) {
+ setDownloadStarted(false);
+ setError(cause instanceof Error ? cause.message : t("canvas.workspace.toast.downloadFailed"));
}
};
const editableAtPlayhead =
@@ -1448,12 +1475,7 @@ export function TimelineEditor({
- downloadFile(
- rendered,
- downloadFilename(node.data.title, "video/mp4"),
- )
- }
+ onClick={downloadRender}
>
{t("timeline.action.downloadMp4")}
@@ -1461,10 +1483,11 @@ export function TimelineEditor({
disabled={busy || node.locked || inserted}
onClick={() => void insertRender()}
>
- {inserted
+ {publishing ? t("timeline.output.publishing") : inserted
? t("timeline.action.addedToCanvas")
: t("timeline.action.addToCanvas")}
+ {downloadStarted && {t("timeline.render.downloadStarted")} }
)}
= { intro: 0, assistant: 1, language: 2, harness: 2, tasks: 3 };
+type Screen = "intro" | "assistant" | "language" | "harness" | "mode" | "tasks";
+const screenDepth: Record = { intro: 0, assistant: 1, language: 2, harness: 2, mode: 3, tasks: 4 };
type ModelEditor = { capability: FirstRunCapability; existing?: ModelConfig };
type SelectedTask = { type: "models" } | { type: "configure"; existing?: ModelConfig };
type TaskAction = "create" | "import" | "examples";
@@ -72,9 +73,10 @@ function TaskOption({ capability, icon, title, description, checked, onChange }:
);
}
-export function WelcomeScreen({ catalog, projectId, onCreate, onImport, exampleStatus, onExamples, onCancelExample }: {
+export function WelcomeScreen({ catalog, projectId, onEnterWorkspace, onCreate, onImport, exampleStatus, onExamples, onCancelExample }: {
catalog: BackendModels;
projectId: string;
+ onEnterWorkspace: (mode: WorkspaceMode) => void;
onCreate: (selections: FirstRunSelection[]) => Promise;
onImport: (files: File[]) => Promise;
exampleStatus?: ExampleStatus;
@@ -125,6 +127,7 @@ export function WelcomeScreen({ catalog, projectId, onCreate, onImport, exampleS
const agents = languageModels.ready;
const isIntro = screen === "intro";
const isTaskStep = screen === "tasks";
+ const choosingWork = screen === "mode" || isTaskStep;
const selected = taskChoices.flatMap(({ capability }) => {
const task = tasks[capability];
if (!task) return [];
@@ -136,6 +139,7 @@ export function WelcomeScreen({ catalog, projectId, onCreate, onImport, exampleS
const openEditors = selected.filter(({ task }) => task.type === "configure");
const canUseCatalog = catalog.connected && !catalog.loading;
const taskDisabled = !canUseCatalog || Boolean(taskAction) || lockedEditor !== null;
+ const canvasReady = isTaskStep && canUseCatalog && hasFirstCanvasModel(catalog.models);
const downloadingExample = taskAction === "examples" && exampleStatus?.phase === "downloading";
const exampleProgress = downloadingExample ? examplePercent(exampleStatus) : null;
const updateEditorLock = useCallback((capability: FirstRunCapability, locked: boolean) => {
@@ -250,7 +254,7 @@ export function WelcomeScreen({ catalog, projectId, onCreate, onImport, exampleS
await saveChatDraft(projectId, next);
rememberAgentSelection(projectId, { ...next, messages });
setAssistant(label);
- navigate("tasks");
+ navigate("mode");
} catch (error) {
setAssistantError(errorMessage(error));
} finally {
@@ -260,7 +264,7 @@ export function WelcomeScreen({ catalog, projectId, onCreate, onImport, exampleS
}
async function runTask(action: TaskAction, run: () => Promise) {
- if (!assistant || taskDisabled || taskRunning.current) return;
+ if (!assistant || !canvasReady || taskDisabled || taskRunning.current) return;
taskRunning.current = true;
setTaskAction(action);
setTaskError("");
@@ -372,7 +376,8 @@ export function WelcomeScreen({ catalog, projectId, onCreate, onImport, exampleS
? editingTitle
: t(screen === "assistant" ? "firstRun.assistantTitle" :
screen === "language" ? "firstRun.languageTitle" :
- screen === "harness" ? "firstRun.harnessTitle" : "firstRun.tasksTitle");
+ screen === "harness" ? "firstRun.harnessTitle" :
+ screen === "mode" ? "firstRun.modeTitle" : "firstRun.tasksTitle");
const catalogFeedback = catalog.loading
? {t("modelSetup.loading")}
: !catalog.connected && (
@@ -396,6 +401,7 @@ export function WelcomeScreen({ catalog, projectId, onCreate, onImport, exampleS
);
const cancel = editing?.capability ?? activeEditor?.capability ?? openEditors.at(-1)?.capability;
if (cancel) cancelModelButtons.current.get(cancel)?.click();
+ else if (isTaskStep) navigate("mode");
else if (screen === "assistant") navigate("intro");
else if (!isIntro) navigate("assistant");
}
@@ -445,8 +451,8 @@ export function WelcomeScreen({ catalog, projectId, onCreate, onImport, exampleS
) :
- {isTaskStep ? "✓" : "1"} {t("firstRun.assistantTitle")}
- 2 {t("firstRun.stepTask")}
+ {choosingWork ? "✓" : "1"} {t("firstRun.assistantTitle")}
+ 2 {t(isTaskStep ? "firstRun.stepTask" : "workspaceModes.label")}
{title}
@@ -510,10 +516,32 @@ export function WelcomeScreen({ catalog, projectId, onCreate, onImport, exampleS
: setRuntimeAttempt((attempt) => attempt + 1)}>{t("modelSetup.retry")} }
>
+ ) : screen === "mode" ? (
+ <>
+ {assistant && {t("firstRun.assistantSelected", { assistant })}
}
+
+ {t("workspaceModes.label")}
+ {(["agent", "canvas"] as const).map(mode => (
+ mode === "canvas" ? navigate("tasks") : onEnterWorkspace("agent")}>
+
+
+ {t(`workspaceModes.${mode}`)}
+ {t(`firstRun.modeHint.${mode}`)}
+
+
+
+ ))}
+
+
+ navigate("assistant")}>{t("firstRun.back")}
+
+ >
) : (
<>
{t("firstRun.tasksHint")}
- {assistant && {t("firstRun.assistantSelected", { assistant })}
}
+ {!canvasReady && canUseCatalog && {t("firstRun.canvasModelRequired")}
}
{t("firstRun.tasksTitle")}
{taskChoices.map((choice) => (
@@ -529,6 +557,7 @@ export function WelcomeScreen({ catalog, projectId, onCreate, onImport, exampleS
))}
{shortcutChoices.map((choice) => (
{exampleFailureText(t, exampleStatus)}
- void runTask("examples", onExamples)}>{t("canvas.example.action.retry")}
)}
@@ -625,12 +654,17 @@ export function WelcomeScreen({ catalog, projectId, onCreate, onImport, exampleS
})}
{selected.length > 0 && catalog.availabilityError && {catalog.availabilityError}
}
-
0} onClick={() => navigate("assistant")}>
+ 0} onClick={() => navigate("mode")}>
{t("firstRun.back")}
- {selected.length > 0 && (
+ {selected.length === 0 ? (
+ onEnterWorkspace("canvas")}>
+ {t("firstRun.enterCanvas")}
+
+ ) : (
0 || selected.length !== selections.length}
+ disabled={!assistant || !canvasReady || taskDisabled || openEditors.length > 0 || selected.length !== selections.length}
onClick={() => void runTask("create", () => onCreate(selections))}>
{t("firstRun.start")}
diff --git a/src/canvas/assistant-experience.css b/src/canvas/assistant-experience.css
index 579727913..45178aecb 100644
--- a/src/canvas/assistant-experience.css
+++ b/src/canvas/assistant-experience.css
@@ -1,6 +1,56 @@
.cw-assistant-message.is-assistant .cw-assistant-message-text {
white-space: normal;
}
+.cw-chat-result {
+ width: min(100%, 360px);
+ margin-top: 12px;
+ overflow: hidden;
+ border: 1px solid var(--chat-border);
+ border-radius: 12px;
+ background: var(--chat-surface);
+}
+.cw-chat-result-preview {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ width: 100%;
+ padding: 10px;
+ text-align: start;
+}
+.cw-chat-result-preview .cw-creation-asset-thumbnail {
+ flex: none;
+ width: 84px;
+ height: 70px;
+}
+.cw-chat-result-details {
+ display: grid;
+ min-width: 0;
+ gap: 3px;
+}
+.cw-chat-result-details strong {
+ overflow-wrap: anywhere;
+ font-size: 14px;
+}
+.cw-chat-result-details small { color: var(--chat-muted); }
+.cw-chat-result-preview-label,
+.cw-chat-result-actions button {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ font-size: 12px;
+}
+.cw-chat-result-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 2px 8px;
+ padding: 4px 7px;
+ border-top: 1px solid var(--chat-border);
+}
+.cw-chat-result-actions button { padding: 6px; border-radius: 6px; }
+.cw-chat-result button:hover:enabled { background: var(--chat-hover); }
+.cw-chat-result button:focus-visible { outline-offset: -2px; }
+.cw-chat-result p[role="alert"] { margin: 0; padding: 6px 12px; }
+
.cw-chat-markdown {
font-size: 14px;
line-height: 1.8;
diff --git a/src/canvas/assistant-panel.css b/src/canvas/assistant-panel.css
index 25b7d2a17..ccb538459 100644
--- a/src/canvas/assistant-panel.css
+++ b/src/canvas/assistant-panel.css
@@ -151,6 +151,24 @@
white-space: nowrap;
text-overflow: ellipsis;
}
+.cw-assistant-move-handle {
+ display: flex;
+ flex: 1;
+ align-items: center;
+ gap: 7px;
+ min-height: 32px;
+ border-radius: 5px;
+ cursor: grab;
+ touch-action: none;
+ user-select: none;
+}
+.cw-assistant-move-handle:active { cursor: grabbing; }
+.cw-assistant-move-handle:focus-visible {
+ outline: 2px solid #8daed4;
+ outline-offset: 2px;
+}
+.cw-assistant-move-handle svg { flex: none; color: var(--chat-muted); }
+.cw-assistant-move-handle span { overflow: hidden; text-overflow: ellipsis; }
.cw-assistant-sessions { display: contents; }
.cw-assistant-header-actions { display: flex; align-items: center; gap: 4px; flex-shrink: 0; }
.cw-assistant-panel .cw-assistant-new-session {
@@ -802,6 +820,13 @@
}
}
@container (max-width: 400px) {
+ .cw-assistant-header:has(.cw-assistant-move-handle) {
+ gap: 4px;
+ padding-inline: 12px;
+ }
+ .cw-assistant-move-handle + .cw-assistant-header-actions { gap: 1px; }
+ .cw-assistant-move-handle + .cw-assistant-header-actions .cw-assistant-new-session { padding-inline: 7px; }
+ .cw-assistant-move-handle + .cw-assistant-header-actions .cw-assistant-new-session span { display: none; }
.cw-assistant-panel .chat-picker-trigger {
max-width: min(100%, 100px);
}
diff --git a/src/canvas/assistant-workspace.css b/src/canvas/assistant-workspace.css
new file mode 100644
index 000000000..1012c6983
--- /dev/null
+++ b/src/canvas/assistant-workspace.css
@@ -0,0 +1,130 @@
+/* The conversation owns the space below the project toolbar in chat creation. */
+[data-workspace-mode="agent"] .cw-assistant-panel:not([hidden]) {
+ --chat-inset: clamp(14px, 3.5cqi, 52px);
+ --chat-reading-width: min(960px, calc(100% - var(--chat-inset) * 2));
+ --chat-background: #121213;
+ --chat-composer: #202022;
+ --chat-muted: #aaa9af;
+ display: grid;
+ grid-template:
+ "title" auto
+ "messages" minmax(0, 1fr)
+ "composer" auto / minmax(0, 1fr);
+ border: 0;
+ border-radius: 0;
+ box-shadow: none;
+}
+
+:root[data-theme="light"] [data-workspace-mode="agent"] .cw-assistant-panel {
+ --chat-background: #fff;
+ --chat-composer: #f7f7f9;
+ --chat-surface: #efeff2;
+ --chat-border: #dadade;
+ --chat-hover: #e7e7eb;
+ --chat-muted: #62636c;
+}
+
+[data-workspace-mode="agent"] .cw-assistant-sessions,
+[data-workspace-mode="agent"] .cw-assistant-log,
+[data-workspace-mode="agent"] .cw-assistant-composer-area {
+ justify-self: center;
+ width: var(--chat-reading-width);
+ min-width: 0;
+}
+
+[data-workspace-mode="agent"] .cw-assistant-sessions {
+ grid-area: title;
+ display: block;
+ position: relative;
+ z-index: 2;
+}
+[data-workspace-mode="agent"] .cw-assistant-session-history {
+ top: 100%;
+ right: 0;
+ left: auto;
+ width: min(360px, 100%);
+ max-height: min(440px, calc(100dvh - 180px));
+}
+[data-workspace-mode="agent"] .cw-assistant-header {
+ padding: clamp(12px, 2.5vh, 26px) 0 12px;
+}
+[data-workspace-mode="agent"] .cw-assistant-header h2 {
+ font-size: clamp(17px, 1.6cqi, 22px);
+ letter-spacing: -.02em;
+}
+[data-workspace-mode="agent"] .cw-assistant-log {
+ grid-area: messages;
+ gap: clamp(18px, 2.4vh, 32px);
+ padding: 12px 0 24px;
+}
+[data-workspace-mode="agent"] .cw-assistant-welcome {
+ margin: auto;
+ padding: 18px 0;
+ text-align: center;
+}
+[data-workspace-mode="agent"] .cw-assistant-avatar {
+ margin: 0 auto 14px;
+ background: transparent;
+}
+[data-workspace-mode="agent"] .cw-assistant-avatar img { width: 44px; height: 44px; }
+[data-workspace-mode="agent"] .cw-assistant-welcome h1 {
+ margin-bottom: 10px;
+ font-size: clamp(24px, 3cqi, 36px);
+ line-height: 1.25;
+}
+[data-workspace-mode="agent"] .cw-assistant-welcome p {
+ max-width: 48ch;
+ font-size: 14px;
+}
+
+[data-workspace-mode="agent"] .cw-assistant-message.is-user {
+ max-width: 84%;
+ padding: 11px 17px;
+ border-radius: 18px 18px 5px 18px;
+}
+[data-workspace-mode="agent"] .cw-assistant-message,
+[data-workspace-mode="agent"] .cw-chat-markdown { font-size: 15px; }
+[data-workspace-mode="agent"] .cw-assistant-message-heading {
+ align-items: center;
+ font-size: 13px;
+}
+
+[data-workspace-mode="agent"] .cw-assistant-composer-area {
+ grid-area: composer;
+ padding: 6px 0 max(8px, env(safe-area-inset-bottom));
+}
+[data-workspace-mode="agent"] .cw-assistant-composer {
+ padding: clamp(12px, 1.6cqi, 22px);
+ border-radius: clamp(16px, 2cqi, 22px);
+}
+[data-workspace-mode="agent"] .cw-assistant-panel .cw-chat-reference-editor {
+ min-height: clamp(48px, 8vh, 88px);
+ font-size: 15px;
+}
+[data-workspace-mode="agent"] .cw-assistant-panel .chat-picker-trigger {
+ height: 30px;
+ font-size: 12px;
+}
+[data-workspace-mode="agent"] .cw-assistant-upload {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ width: auto;
+ padding: 0 6px;
+ font-size: 12px;
+}
+[data-workspace-mode="agent"] .cw-assistant-panel .cw-agent-picker .chat-picker-trigger > span {
+ display: inline;
+}
+[data-workspace-mode="agent"] .model-picker { margin-inline-start: auto; }
+[data-workspace-mode="agent"] .cw-assistant-toolbar-spacer { display: none; }
+[data-workspace-mode="agent"] .cw-assistant-panel .model-picker-panel {
+ left: auto;
+ right: 0;
+ width: min(100%, 420px);
+}
+@container (max-width: 700px) {
+ [data-workspace-mode="agent"] .cw-assistant-upload > span { display: none; }
+ [data-workspace-mode="agent"] .cw-assistant-panel .cw-agent-picker { max-width: 90px; }
+}
diff --git a/src/canvas/assistantResultEditors.ts b/src/canvas/assistantResultEditors.ts
new file mode 100644
index 000000000..ec7a4e896
--- /dev/null
+++ b/src/canvas/assistantResultEditors.ts
@@ -0,0 +1,128 @@
+import type { ChatMessage } from "../backend/chat.ts";
+import type { Asset, AssetRef, CanvasItem, ProjectSnapshot } from "../contracts/generated.ts";
+import { pendingPlacement } from "../backend/pendingMediaPlacement.ts";
+import { currentAsset, type CreationClient } from "../backend/creationClient.ts";
+import { findAssetItem, newAssetItem, showExistingItem, showTimelineEditorItem } from "./canvasAssetPlacement.ts";
+import { indexNodes, isNodeLocked } from "./hierarchy.ts";
+import type { Point } from "./model.ts";
+import { tNow } from "../i18n/messages.ts";
+
+export interface ProjectTimelineTarget {
+ kind: "timeline";
+ projectId: string;
+ itemId: string | null;
+ editorId: string;
+ revision: number;
+}
+export type ProjectEditorTarget = ProjectTimelineTarget | {
+ kind: "media";
+ asset: Asset;
+ itemId: string | null;
+};
+
+export type DeliveredTimeline = NonNullable["timelines"][number];
+
+/** A turn can finish before its project notification reaches the browser. */
+export function deliveredTimelineState(
+ result: DeliveredTimeline, projectId: string, eventCursor: number | undefined, snapshot?: ProjectSnapshot,
+) {
+ if (snapshot?.project.id !== projectId || (eventCursor !== undefined && snapshot.eventCursor < eventCursor))
+ return { status: "pending", title: result.title } as const;
+ const editor = snapshot.editorDocuments.find(doc => doc.id === result.editorId && doc.kind === "timeline");
+ const item = snapshot.canvasItems.find(candidate => candidate.id === result.itemId);
+ if (!editor || (result.itemId && (item?.kind !== "timeline" || item.binding.objectRef.id !== editor.id)))
+ return { status: "missing", title: result.title } as const;
+ return { status: "available", title: item?.title || result.title, revision: editor.revision } as const;
+}
+
+export function timelinesForResultAssets(snapshot: ProjectSnapshot | undefined) {
+ const byAsset = new Map();
+ if (!snapshot) return byAsset;
+ const documents = new Map(snapshot.editorDocuments.map(doc => [doc.id, doc]));
+ const assets = new Map(snapshot.assets.map(asset => [asset.id, asset]));
+ const renders = new Map();
+ for (const asset of snapshot.assets) {
+ const { source, editorDocumentId } = asset.provenance;
+ if (source !== "rendered" || !editorDocumentId) continue;
+ const group = renders.get(editorDocumentId);
+ if (group) group.push(asset);
+ else renders.set(editorDocumentId, [asset]);
+ }
+ for (const item of snapshot.canvasItems) {
+ if (item.kind !== "timeline" || item.binding.role !== "editor") continue;
+ const doc = documents.get(item.binding.objectRef.id);
+ if (doc?.kind !== "timeline") continue;
+ const ids = new Set();
+ const include = (ref?: AssetRef | null) => {
+ if (ref && assets.get(ref.assetId)?.fingerprint === ref.fingerprint) ids.add(ref.assetId);
+ };
+ for (const track of doc.data.tracks)
+ for (const clip of track.clips) include(clip.resource.asset);
+ for (const connection of doc.inputConnections) include(connection.asset);
+ for (const resource of doc.data.importedAssets) include(resource.asset);
+ for (const overlay of doc.data.overlays ?? []) include(overlay.sourceAsset);
+ for (const asset of renders.get(doc.id) ?? []) {
+ if (!asset.provenance.sourceItemId || asset.provenance.sourceItemId === item.id) ids.add(asset.id);
+ }
+ const target = {
+ kind: "timeline" as const, projectId: snapshot.project.id,
+ itemId: item.id, editorId: doc.id, revision: doc.revision, title: item.title,
+ };
+ for (const id of ids) {
+ const targets = byAsset.get(id);
+ if (targets) targets.push(target);
+ else byAsset.set(id, [target]);
+ }
+ }
+ return byAsset;
+}
+
+function boundProjectEditorItem(snapshot: ProjectSnapshot, target: ProjectEditorTarget) {
+ if (target.kind === "timeline") {
+ const item = target.itemId ? snapshot.canvasItems.find(candidate => candidate.id === target.itemId)
+ : snapshot.canvasItems.find(candidate => candidate.kind === "timeline" && candidate.binding.objectRef.id === target.editorId);
+ const editor = snapshot.editorDocuments.find(candidate => candidate.id === target.editorId);
+ if (snapshot.project.id !== target.projectId || editor?.kind !== "timeline"
+ || (target.itemId && (item?.kind !== "timeline" || item.binding.objectRef.id !== target.editorId)))
+ throw new Error(tNow("errors.backend.timelineSourceMissing"));
+ if (editor.revision !== target.revision) throw new Error(tNow("assistant.result.timelineChanged"));
+ return item;
+ }
+ const { asset, itemId } = target;
+ const saved = snapshot.assets.find(candidate => candidate.id === asset.id);
+ if (snapshot.project.id !== asset.projectId || !saved) throw new Error(tNow("canvas.workspace.error.assetMissing"));
+ if (saved.revision !== asset.revision || saved.fingerprint !== asset.fingerprint)
+ throw new Error(tNow("canvasNodes.assets.versionChanged"));
+ if (!itemId) return findAssetItem(snapshot, asset.id);
+ const item = snapshot.canvasItems.find(candidate => candidate.id === itemId);
+ if (!item || currentAsset(snapshot, item)?.id !== asset.id)
+ throw new Error(tNow("canvasNodes.assets.versionChanged"));
+ return item;
+}
+
+/** Hidden ancestors participate in the same lock checks as visible parents. */
+export function resolveProjectEditorItem(snapshot: ProjectSnapshot, target: ProjectEditorTarget, provisionalId?: string) {
+ const bound = boundProjectEditorItem(snapshot, target);
+ if (provisionalId && bound) throw new Error(tNow("assistant.result.editorChanged"));
+ // A lost reply can leave the already-edited output at the provisional ID.
+ // It still participates in lock and revision checks while the fixed command is resolved.
+ const item = provisionalId ? snapshot.canvasItems.find(candidate => candidate.id === provisionalId) : bound;
+ if (item && isNodeLocked(item, indexNodes(snapshot.canvasItems)))
+ throw new Error(tNow("canvas.workspace.toast.unlockFirst"));
+ return item;
+}
+
+export async function prepareProjectEditorItem(
+ client: CreationClient, target: ProjectEditorTarget, center: () => Point,
+): Promise<{ itemId: string; unplaced?: CanvasItem }> {
+ const item = resolveProjectEditorItem(client.snapshot, target);
+ if (target.kind === "media") {
+ if (item) return { itemId: item.id };
+ // No project object is needed to inspect or cancel an unplaced candidate.
+ const unplaced = pendingPlacement(target.asset) ?? newAssetItem(target.asset, center());
+ return { itemId: unplaced.id, unplaced };
+ }
+ const itemId = item ? await showExistingItem(client, item)
+ : await showTimelineEditorItem(client, target.editorId, target.revision, center());
+ return { itemId };
+}
diff --git a/src/canvas/assistantResults.ts b/src/canvas/assistantResults.ts
new file mode 100644
index 000000000..360394f4c
--- /dev/null
+++ b/src/canvas/assistantResults.ts
@@ -0,0 +1,103 @@
+import { displayedAssetId, visibleItems } from "../backend/creationClient.ts";
+import type { ChatMessage } from "../backend/chat.ts";
+import type { Asset, ProjectSnapshot } from "../contracts/generated.ts";
+
+export interface AssistantResult {
+ assetId: string;
+ asset: Asset | null;
+ name?: string;
+ resultId: string | null;
+ status: "current" | "candidate" | "historical" | "asset";
+ /** A canvas item displaying this exact asset, including a hidden item. */
+ itemId: string | null;
+}
+
+/** The persisted user message ID is the agent's turn ID. Read only committed
+ * outputs with that provenance, including jobs which finish after the reply. */
+export function assistantResultsByTurn(snapshot: ProjectSnapshot | undefined) {
+ const turns = new Map();
+ if (!snapshot) return turns;
+ const add = (turnId: string, card: AssistantResult) => {
+ const cards = turns.get(turnId);
+ if (cards) cards.push(card);
+ else turns.set(turnId, [card]);
+ };
+ const assets = new Map(snapshot.assets.map((asset) => [asset.id, asset]));
+ const results = new Map(snapshot.results.map((result) => [result.id, result]));
+ const adopted = new Map(snapshot.generationSpecs.map((spec) => [spec.id, spec.currentResultId]));
+ const adoptedAsset = (specId: string) => {
+ const resultId = adopted.get(specId);
+ return resultId ? results.get(resultId)?.asset.assetId : undefined;
+ };
+ const visible = visibleItems(snapshot);
+ const displayedByItem = new Map();
+ const itemForAsset = new Map();
+ for (const item of snapshot.canvasItems) {
+ const assetId = displayedAssetId(item, adoptedAsset);
+ if (!assetId) continue;
+ displayedByItem.set(item.id, assetId);
+ const existing = itemForAsset.get(assetId);
+ if (!existing || (!visible.has(existing) && visible.has(item.id)))
+ itemForAsset.set(assetId, item.id);
+ }
+
+ const jobs = new Map(snapshot.jobs.map((job) => [job.id, job]));
+ for (const result of snapshot.results) {
+ const job = jobs.get(result.jobId);
+ if (!job?.agentRunId || job.status !== "succeeded") continue;
+ const { assetId, fingerprint } = result.asset;
+ const asset = assets.get(assetId);
+ const available = asset?.fingerprint === fingerprint;
+ const origin = job.originItemId;
+ const itemId = origin && displayedByItem.get(origin) === assetId
+ ? origin : itemForAsset.get(assetId);
+ const current = adopted.get(result.specId) === result.id;
+ add(job.agentRunId, {
+ assetId,
+ resultId: result.id,
+ asset: available ? asset : null,
+ status: current ? "current" : job.adopted ? "historical" : "candidate",
+ itemId: available ? itemId ?? null : null,
+ });
+ }
+ for (const asset of snapshot.assets) {
+ const { source, agentRunId } = asset.provenance;
+ if (source !== "agent_written" || !agentRunId) continue;
+ add(agentRunId, {
+ assetId: asset.id, resultId: null, asset, status: "asset",
+ itemId: itemForAsset.get(asset.id) ?? null,
+ });
+ }
+ return turns;
+}
+
+/** Restore the identity of a deleted direct publication once project changes
+ * through its delivery are visible. A lagging snapshot does not prove deletion. */
+export function withPublishedAssistantResults(
+ live: Map, messages: readonly ChatMessage[], snapshot?: ProjectSnapshot,
+) {
+ let turns = live;
+ if (!snapshot) return turns;
+ for (const [index, message] of messages.entries()) {
+ const receipt = message.publishedAssets;
+ const turn = messages[index - 1];
+ if (message.role !== "assistant" || turn?.role !== "user" || !receipt
+ || receipt.projectId !== snapshot.project.id || receipt.eventCursor > snapshot.eventCursor) continue;
+ const cards = live.get(turn.id) ?? [];
+ const byId = new Map(cards.map((card, i) => [card.assetId, i]));
+ let merged = cards;
+ for (const { id, name, fingerprint } of receipt.assets) {
+ const at = byId.get(id);
+ if (at !== undefined && cards[at].asset?.fingerprint === fingerprint) continue;
+ if (merged === cards) merged = [...cards];
+ const missing: AssistantResult = { assetId: id, name, asset: null, resultId: null, itemId: null, status: "asset" };
+ if (at === undefined) merged.push(missing);
+ else merged[at] = missing;
+ }
+ if (merged !== cards) {
+ if (turns === live) turns = new Map(live);
+ turns.set(turn.id, merged);
+ }
+ }
+ return turns;
+}
diff --git a/src/canvas/canvasAssetPlacement.ts b/src/canvas/canvasAssetPlacement.ts
new file mode 100644
index 000000000..11e585a86
--- /dev/null
+++ b/src/canvas/canvasAssetPlacement.ts
@@ -0,0 +1,62 @@
+import { assetReference, displayedAssetId, objectVersion, visibleItems, type CreationClient } from "../backend/creationClient.ts";
+import type { Asset, CanvasItem, ProjectSnapshot } from "../contracts/generated.ts";
+import { createNode, type Point } from "./model.ts";
+
+/** Prefer the original binding, then a visible item showing the same asset. */
+export function findAssetItem(snapshot: ProjectSnapshot, assetId: string, preferredId?: string | null) {
+ const resultAssets = new Map(snapshot.results.map(result => [result.id, result.asset.assetId]));
+ const adopted = new Map(snapshot.generationSpecs.map(spec =>
+ [spec.id, spec.currentResultId ? resultAssets.get(spec.currentResultId) : undefined]));
+ const owners = snapshot.canvasItems.filter(item => displayedAssetId(item, id => adopted.get(id)) === assetId);
+ const preferred = owners.find(item => item.id === preferredId);
+ if (preferred || owners.length < 2) return preferred ?? owners[0];
+ const visible = visibleItems(snapshot);
+ return owners.find(item => visible.has(item.id)) ?? owners[0];
+}
+
+/** Restore the existing item and its hidden ancestors under their current revisions. */
+export async function showExistingItem(client: CreationClient, item: CanvasItem) {
+ if (visibleItems(client.snapshot).has(item.id)) return item.id;
+ const versions = [objectVersion("canvas_item", item)];
+ let parentId = item.parentId;
+ while (parentId) {
+ const parent = client.snapshot.canvasItems.find(candidate => candidate.id === parentId)!;
+ versions.push(objectVersion("canvas_item", parent));
+ parentId = parent.parentId;
+ }
+ await client.command("canvas.show", { item }, versions);
+ return item.id;
+}
+
+/** Attach an unplaced timeline to the existing editor document. */
+export async function showTimelineEditorItem(client: CreationClient, editorId: string, revision: number, position: Point) {
+ const node = createNode("timeline", position);
+ await client.command("canvas.show", { item: {
+ id: node.id, projectId: client.id, kind: "timeline", title: node.data.title,
+ position, width: node.width, height: node.height,
+ binding: { role: "editor", objectRef: { objectType: "editor_document", kind: "timeline", id: editorId } },
+ } }, [objectVersion("editor_document", { id: editorId, revision })]);
+ return node.id;
+}
+
+export function newAssetItem(asset: Asset, position: Point, specId?: string | null): CanvasItem {
+ const node = createNode(asset.kind, { x: position.x - 150, y: position.y - 150 }, {
+ media: { width: asset.metadata.width ?? undefined, height: asset.metadata.height ?? undefined },
+ });
+ return {
+ id: node.id, projectId: asset.projectId, revision: 1, kind: asset.kind, title: asset.name,
+ position: node.position, width: node.width, height: node.height,
+ zIndex: 0, locked: false, visible: true, parentId: null, tags: [], editors: [],
+ binding: specId
+ ? { role: "generation", objectRef: { objectType: "generation_spec", id: specId }, materialOverride: null }
+ : { role: "material", objectRef: assetReference(asset) },
+ } as CanvasItem;
+}
+
+export async function showNewAssetItem(
+ client: CreationClient, asset: Asset, position: Point, specId?: string | null,
+) {
+ const item = newAssetItem(asset, position, specId);
+ await client.command("canvas.show", { item }, [objectVersion("asset", asset)]);
+ return item.id;
+}
diff --git a/src/canvas/creation-assets.css b/src/canvas/creation-assets.css
index 191d26fb8..3793b994f 100644
--- a/src/canvas/creation-assets.css
+++ b/src/canvas/creation-assets.css
@@ -19,6 +19,14 @@
box-shadow: 0 12px 40px #0006;
font-size: 12px;
}
+.cw-creation-assets[hidden] { display: none; }
+.cw-project-asset-actions {
+ display: flex;
+ gap: 8px;
+ margin-bottom: 8px;
+}
+.cw-project-asset-actions button { padding: 5px 8px; }
+.cw-workspace[data-workspace-mode="agent"] .cw-creation-assets { right: 16px; }
.cw-asset-list-anchor {
display: inline-flex;
}
diff --git a/src/canvas/creationTools.ts b/src/canvas/creationTools.ts
index 8e46595cc..44352dbd7 100644
--- a/src/canvas/creationTools.ts
+++ b/src/canvas/creationTools.ts
@@ -1,7 +1,7 @@
import type { MessageKey } from "../i18n/types";
import type { CanvasNodeKind } from "./model.ts";
-/** Keep the creation menu and the left rail in the same order. */
+/** Shared node types and labels for canvas creation menus. */
export const CANVAS_CREATION_TOOLS: readonly {
kind: CanvasNodeKind;
labelKey: MessageKey;
diff --git a/src/canvas/desktop-chrome.css b/src/canvas/desktop-chrome.css
index 800c1ca8f..652e81cc2 100644
--- a/src/canvas/desktop-chrome.css
+++ b/src/canvas/desktop-chrome.css
@@ -8,11 +8,12 @@ html[data-desktop-platform="darwin"] .cw-workspace {
html[data-desktop-chrome] {
--desktop-toolbar-height: 48px;
}
-html[data-desktop-chrome] .cw-workspace .react-flow {
+html[data-desktop-chrome] .cw-workspace .cw-canvas-region {
top: var(--desktop-toolbar-height);
+ left: calc(var(--od-sidebar-width) + var(--chat-left-inset));
+}
+html[data-desktop-chrome] .cw-workspace .react-flow {
background: #0d0d0d;
- left: var(--od-sidebar-width);
- transition: left 200ms ease;
}
html[data-desktop-chrome][data-theme="light"] .cw-workspace .react-flow {
background: #f7f8fa;
@@ -80,7 +81,7 @@ html[data-desktop-chrome] .cw-topbar .cw-language-toggle button.is-active {
html[data-desktop-chrome] .cw-topbar .cw-top-actions {
gap: 2px;
}
-html[data-desktop-chrome] .cw-topbar .cw-top-actions button {
+html[data-desktop-chrome] .cw-topbar .cw-top-actions .cw-icon-button {
width: 30px;
height: 30px;
}
@@ -206,7 +207,6 @@ html[data-desktop-chrome][data-theme="light"] .od-sidebar-create-shortcut { colo
.od-project-sidebar button:focus-visible, .od-caption-actions button:focus-visible { outline: 2px solid #8ab4f8; outline-offset: 2px; }
.od-project-sidebar .od-sidebar-settings { align-self: flex-start; margin-left: 8px; background: transparent; box-shadow: none; }
.od-sidebar-error { color: #e7a4a4; font-size: 11px; overflow-wrap: anywhere; }
-html[data-desktop-chrome] .cw-workspace[data-desktop-sidebar="open"] .cw-bottom-left { left: 260px; }
html[data-desktop-chrome] .cw-workspace[data-desktop-sidebar="open"] .cw-bottom-left > .cw-settings-control { visibility: hidden; }
html[data-desktop-chrome][data-theme="light"] .od-project-sidebar { background: linear-gradient(155deg, #8e8dda20, #98afcd18), #f4f4f780; color: #282b33; }
html[data-desktop-chrome][data-theme="light"] .od-project-sidebar nav button { color: #3c414d; }
@@ -214,17 +214,36 @@ html[data-desktop-chrome][data-theme="light"] .od-project-sidebar nav button[ari
html[data-desktop-chrome][data-desktop-fullscreen] .od-caption-actions { left: 12px; }
html[data-desktop-chrome][data-desktop-fullscreen] [data-desktop-sidebar="open"] .od-caption-actions { left: 196px; }
html[data-desktop-chrome][data-desktop-fullscreen] .cw-workspace[data-desktop-sidebar="closed"] .cw-topbar { padding-left: 92px; }
+html[data-desktop-chrome] .cw-workspace[data-workspace-mode="agent"] .cw-topbar { padding-left: 16px; }
+html[data-desktop-platform="darwin"]:not([data-desktop-fullscreen]) .cw-workspace[data-workspace-mode="agent"] .cw-topbar { padding-left: 92px; }
@media (prefers-reduced-motion: reduce) {
.od-project-sidebar, .od-caption-actions,
- html[data-desktop-chrome] .cw-workspace .cw-topbar,
- html[data-desktop-chrome] .cw-workspace .react-flow { transition: none; }
+ html[data-desktop-chrome] .cw-workspace .cw-topbar { transition: none; }
}
@media (prefers-reduced-transparency: reduce) { .od-project-sidebar { background: #272735; } }
-html[data-desktop-chrome] .cw-workspace .cw-rail-shell { left: var(--od-sidebar-width); transition: left 200ms ease; }
-html[data-desktop-chrome] .cw-workspace .cw-empty { left: calc(50% + var(--od-sidebar-width) / 2); width: min(calc(80vw - var(--od-sidebar-width)), 600px); }
+html[data-desktop-chrome] .cw-workspace .cw-empty { width: min(80%, 600px); }
html[data-desktop-chrome] .cw-workspace:not([data-assistant-open="true"]) .cw-top-actions { transform: none; }
html[data-desktop-chrome] .cw-workspace .cw-assistant-panel {
top: calc(var(--desktop-toolbar-height) + 14px);
+ left: calc(var(--od-sidebar-width) + 14px);
+}
+html[data-desktop-chrome] .cw-workspace[data-workspace-mode="agent"] .cw-assistant-panel {
+ top: var(--desktop-toolbar-height);
+ left: var(--od-sidebar-width);
+}
+html[data-desktop-chrome] .cw-workspace[data-narrow="true"][data-workspace-mode="canvas"] .cw-assistant-panel {
+ bottom: 62px;
+}
+html[data-desktop-chrome] .cw-workspace[data-narrow="true"] .cw-canvas-top-actions {
+ position: absolute;
+ top: calc(var(--desktop-toolbar-height) + 6px);
+ right: 12px;
+ padding: 4px;
+ border-radius: 9px;
+ background: var(--cw-surface);
+}
+html[data-desktop-chrome] .cw-workspace[data-narrow="true"][data-canvas-visible="false"] .cw-canvas-top-actions {
+ display: none;
}
.od-sidebar-heading {
diff --git a/src/canvas/firstRunModels.ts b/src/canvas/firstRunModels.ts
index e7c98cc02..f792b0b5b 100644
--- a/src/canvas/firstRunModels.ts
+++ b/src/canvas/firstRunModels.ts
@@ -33,6 +33,11 @@ export function firstRunModelIssue(model: ModelConfig, capability: FirstRunCapab
return issues.some((issue) => issue === null) ? null : issues[0];
}
+export function hasFirstCanvasModel(models: readonly ModelConfig[]) {
+ return models.some(model => (["text_to_image", "video_generation"] as const).some(capability =>
+ firstRunModelKind(model, capability) && firstRunModelIssue(model, capability) === null));
+}
+
function supportsVideoProfile(model: ModelConfig, capability: "text_to_video" | "image_to_video") {
const hasImage = capability === "image_to_video";
const rules = model.inputRules;
diff --git a/src/canvas/hierarchy.ts b/src/canvas/hierarchy.ts
index a0d09503e..2bbd1a0b4 100644
--- a/src/canvas/hierarchy.ts
+++ b/src/canvas/hierarchy.ts
@@ -1,20 +1,23 @@
-import type { CanvasNode } from "./model.ts";
import { tNow } from "../i18n/messages.ts";
-export function indexNodes(
- nodes: readonly CanvasNode[],
-): Map {
+interface HierarchyNode {
+ id: string;
+ parentId?: string | null;
+ locked?: boolean;
+}
+
+export function indexNodes(nodes: readonly T[]): Map {
const byId = new Map(nodes.map((node) => [node.id, node]));
if (byId.size !== nodes.length) throw new Error(tNow("errors.hierarchy.duplicate"));
return byId;
}
/** Nearest parent first. Invalid hierarchies fail before any document changes. */
-export function ancestors(
- node: CanvasNode,
- byId: ReadonlyMap,
-): CanvasNode[] {
- const result: CanvasNode[] = [];
+export function ancestors(
+ node: T,
+ byId: ReadonlyMap,
+): T[] {
+ const result: T[] = [];
const visited = new Set([node.id]);
let parentId = node.parentId;
while (parentId) {
@@ -30,8 +33,8 @@ export function ancestors(
/** Locking a container protects its descendants without changing their own lock flags. */
export function isNodeLocked(
- node: CanvasNode,
- byId: ReadonlyMap,
+ node: HierarchyNode,
+ byId: ReadonlyMap,
): boolean {
return (
Boolean(node.locked) ||
@@ -39,7 +42,7 @@ export function isNodeLocked(
);
}
-export function lockedNodeIds(nodes: readonly CanvasNode[]): Set {
+export function lockedNodeIds(nodes: readonly HierarchyNode[]): Set {
const byId = indexNodes(nodes);
return new Set(
nodes.filter((node) => isNodeLocked(node, byId)).map((node) => node.id),
diff --git a/src/canvas/model-settings.css b/src/canvas/model-settings.css
index b529fd5e5..9ddb679f1 100644
--- a/src/canvas/model-settings.css
+++ b/src/canvas/model-settings.css
@@ -1,11 +1,16 @@
/* Service connections and model selection share the settings theme. */
.cw-settings-body:has(.cw-model-settings) {
display: flex;
+ flex-direction: column;
overflow: hidden;
padding-bottom: 0;
}
+.cw-settings-body > .cw-settings-notice {
+ flex-shrink: 0;
+}
.cw-model-settings {
display: flex;
+ flex: 1 1 auto;
flex-direction: column;
width: 100%;
min-height: 0;
@@ -13,7 +18,8 @@
}
.cw-model-categories {
display: flex;
- gap: 20px;
+ flex-wrap: wrap;
+ column-gap: 20px;
border-bottom: 1px solid var(--settings-border);
flex-shrink: 0;
}
@@ -514,7 +520,7 @@
}
@media (max-width: 600px) {
.cw-model-categories {
- gap: 22px;
+ column-gap: 22px;
}
.cw-model-overview-heading {
padding: 18px 0;
diff --git a/src/canvas/pinnedReferenceAssets.ts b/src/canvas/pinnedReferenceAssets.ts
index 1193e189f..8ec99757d 100644
--- a/src/canvas/pinnedReferenceAssets.ts
+++ b/src/canvas/pinnedReferenceAssets.ts
@@ -1,6 +1,18 @@
-import type { ProjectSnapshot } from "../contracts/generated.ts";
+import type { Asset, ProjectSnapshot } from "../contracts/generated.ts";
import type { ReferenceAsset } from "./chatReferenceContent.ts";
+export function pinnedReferenceAsset(asset: Asset): ReferenceAsset {
+ return {
+ id: asset.id,
+ name: asset.name,
+ binding: "asset",
+ kind: asset.kind,
+ type: asset.metadata.mimeType,
+ size: asset.metadata.size,
+ fingerprint: asset.fingerprint,
+ };
+}
+
/** Presentation metadata only: the reference continues to bind its fixed asset. */
export function pinnedReferenceAssets(
snapshot: ProjectSnapshot,
@@ -22,16 +34,10 @@ export function pinnedReferenceAssets(
);
return [
{
- id: asset.id,
- name: asset.name,
+ ...pinnedReferenceAsset(asset),
nodeTitle: source?.title,
logicalNodeId: source?.id,
referenceId: ref.id,
- binding: "asset" as const,
- kind: asset.kind,
- type: asset.metadata.mimeType,
- size: asset.metadata.size,
- fingerprint: asset.fingerprint,
},
];
});
diff --git a/src/canvas/selectionPresentation.ts b/src/canvas/selectionPresentation.ts
index 780e430e8..461fb5a0d 100644
--- a/src/canvas/selectionPresentation.ts
+++ b/src/canvas/selectionPresentation.ts
@@ -33,6 +33,70 @@ export function projectSelectionRect(
};
}
+/** Keep the current fit when it clears the floating panel. Otherwise pick a
+ * free strip that holds the node and its controls with the least shrinking. */
+export function visibleSelectionArea(
+ node: Rect,
+ view: Viewport,
+ chrome: SelectionChrome,
+ overlay: Rect | null,
+): Rect {
+ const { safe, toolbar, composer } = chrome;
+ if (!overlay) return safe;
+ const { x, y, width: nodeWidth, height: nodeHeight } =
+ projectSelectionRect(node, view, chrome.canvasOrigin);
+ const placement = selectionPlacement(node, view, chrome);
+ const scale = chrome.scaleComposer ? view.zoom : 1;
+ const boxes: Rect[] = [
+ { x, y: y - TITLE_SPACE, width: nodeWidth, height: nodeHeight + TITLE_SPACE },
+ { x: placement.toolbar.left, y: placement.toolbar.top, ...toolbar },
+ {
+ x: placement.composer.left,
+ y: placement.composer.top,
+ width: composer.width * scale,
+ height: composer.height * scale,
+ },
+ ];
+ const right = overlay.x + overlay.width;
+ const bottom = overlay.y + overlay.height;
+ const overlaps = boxes.some(box =>
+ box.width > 0 && box.height > 0 &&
+ box.x < right && box.y < bottom &&
+ box.x + box.width > overlay.x && box.y + box.height > overlay.y,
+ );
+ if (!overlaps) return safe;
+ const afterX = Math.max(safe.x, right);
+ const afterY = Math.max(safe.y, bottom);
+ const candidates = [
+ { ...safe, width: Math.min(safe.width, overlay.x - safe.x) },
+ { ...safe, x: afterX, width: safe.x + safe.width - afterX },
+ { ...safe, height: Math.min(safe.height, overlay.y - safe.y) },
+ { ...safe, y: afterY, height: safe.y + safe.height - afterY },
+ ];
+ const wantedWidth = Math.max(nodeWidth, toolbar.width, composer.width * scale, 1);
+ const wantedHeight = nodeHeight + TITLE_SPACE + (toolbar.height ? toolbar.height + TOOLBAR_GAP : 0) +
+ (composer.height ? (composer.height + COMPOSER_GAP) * scale : 0);
+ const centerX = x + nodeWidth / 2;
+ const centerY = y + nodeHeight / 2;
+ let best = safe;
+ let bestFit = 0;
+ let leastDistance = Infinity;
+ for (const rect of candidates) {
+ const fit = Math.min(1, rect.width / wantedWidth, rect.height / wantedHeight);
+ if (fit <= 0) continue;
+ const distance = Math.hypot(
+ centerX - clamp(centerX, rect.x, rect.x + rect.width),
+ centerY - clamp(centerY, rect.y, rect.y + rect.height),
+ );
+ if (fit > bestFit || (fit === bestFit && distance < leastDistance)) {
+ best = rect;
+ bestFit = fit;
+ leastDistance = distance;
+ }
+ }
+ return best;
+}
+
/** Center content in the usable canvas, preserving zoom unless it cannot fit. */
export function centeredViewport(node: Rect, viewport: Viewport, chrome: SelectionChrome): Viewport {
return selectionViewport(node, {
diff --git a/src/canvas/themes.css b/src/canvas/themes.css
index 6aaf75228..e8096fc82 100644
--- a/src/canvas/themes.css
+++ b/src/canvas/themes.css
@@ -56,9 +56,6 @@
:root[data-theme="light"] .cw-language-toggle > span {
color: #c3c7cf;
}
-:root[data-theme="light"] .cw-rail-mask {
- background: linear-gradient(90deg, #f7f8faf5 20%, #f7f8fad9 55%, #f7f8fa00);
-}
:root[data-theme="light"]
:is(
.cw-rail,
@@ -150,7 +147,6 @@
:is(
.cw-project-row:hover .cw-project-option,
.cw-project-option[aria-checked="true"],
- .cw-rail-button:hover,
.cw-icon-button:hover,
.cw-selection-toolbar button:hover
) {
@@ -216,8 +212,6 @@
:is(
.cw-node-title,
.cw-node-heading,
- .cw-rail-label,
- .cw-empty h1,
.cw-zoom-button,
.cw-side-panel h3
) {
@@ -299,18 +293,6 @@
background: #f3f4f6 !important;
color: #23262c;
}
-:root[data-theme="light"] .cw-empty p,
-:root[data-theme="light"] .cw-empty small {
- color: #77808e;
-}
-:root[data-theme="light"] .cw-empty button {
- background: #fff;
- color: #404957;
- border-color: #dfe2e7;
-}
-:root[data-theme="light"] .cw-aurora {
- opacity: 0.35;
-}
:root[data-theme="light"]
:is(
.cw-composer,
diff --git a/src/canvas/timeline-editor.css b/src/canvas/timeline-editor.css
index 6a9804aa1..1a2646c40 100644
--- a/src/canvas/timeline-editor.css
+++ b/src/canvas/timeline-editor.css
@@ -1,3 +1,11 @@
+.cw-timeline-dialog .cw-domain-header {
+ gap: 10px;
+}
+.cw-timeline-dialog .cw-domain-header > :first-child {
+ flex: 1;
+ min-width: 0;
+ overflow-wrap: anywhere;
+}
.cw-timeline-dialog {
/* Neutral editing surfaces; accents remain consistent with workspace controls. */
--cw-timeline-surface: #242528;
diff --git a/src/canvas/timeline.ts b/src/canvas/timeline.ts
index f38efaba1..6702fdba6 100644
--- a/src/canvas/timeline.ts
+++ b/src/canvas/timeline.ts
@@ -59,17 +59,18 @@ export function timelineLibraryResources(
canvasResources: readonly CanvasResource[],
source: TimelineLibrarySource = "all",
kind: TimelineLibraryKind = "all",
+ projectResources: readonly CanvasResource[] = [],
): CanvasResource[] {
const owned =
source === "canvas"
? canvasResources
: source === "imported"
? timelineImportedAssets(timeline)
- : [...canvasResources, ...timelineImportedAssets(timeline)];
+ : [...projectResources, ...canvasResources, ...timelineImportedAssets(timeline)];
return [
...new Map(
owned.map((resource) => [
- `${resource.kind}:${resource.src ?? resource.id}`,
+ `${resource.kind}:${resource.assetId ?? resource.src ?? resource.id}`,
resource,
]),
).values(),
diff --git a/src/canvas/useAssistantChat.ts b/src/canvas/useAssistantChat.ts
index 6534ceb09..2a2bbb169 100644
--- a/src/canvas/useAssistantChat.ts
+++ b/src/canvas/useAssistantChat.ts
@@ -366,6 +366,7 @@ export function useAssistantChat(
commit?: (assets: ReferenceAsset[]) => boolean | Promise,
) => {
if (
+ !canWrite.current ||
!loaded ||
switching.current ||
uploading.current ||
@@ -383,7 +384,7 @@ export function useAssistantChat(
try {
const assets = await read(abort.signal);
abort.signal.throwIfAborted();
- if (!alive.current) return false;
+ if (!alive.current || !canWrite.current) return false;
if (
new Set([...current.current.assets, ...assets].map((asset) => asset.id))
.size > 64
diff --git a/src/canvas/useAssistantLayout.ts b/src/canvas/useAssistantLayout.ts
index 54b2a9c3a..eb573194f 100644
--- a/src/canvas/useAssistantLayout.ts
+++ b/src/canvas/useAssistantLayout.ts
@@ -7,90 +7,114 @@ import {
type PointerEvent,
type RefObject,
} from "react";
+import {
+ useFloatingAssistant,
+ type AssistantSurface,
+} from "./useFloatingAssistant";
+import type { WorkspaceMode } from "./workspaceMode";
const KEY = "opendirector.assistant-layout.v1";
-const DEFAULT_WIDTH = 420;
const DESKTOP_MIN_WIDTH = 320;
const MAX_WIDTH = 720;
const COLLAPSE_AT = 200;
+const GUTTER = 28;
+
+type DockSide = "left" | "right";
+type DockPreference = { width: number | null; side: DockSide };
-function readWidth() {
+function readDockPreference(): DockPreference {
try {
- const width = JSON.parse(localStorage.getItem(KEY) ?? "null")?.width;
- return typeof width === "number" &&
- Number.isFinite(width) &&
- width > COLLAPSE_AT
- ? Math.min(width, MAX_WIDTH)
- : DEFAULT_WIDTH;
+ const saved = JSON.parse(localStorage.getItem(KEY) ?? "null");
+ const width = saved?.width;
+ return {
+ width: typeof width === "number" && Number.isFinite(width) && width > COLLAPSE_AT ? width : null,
+ side: saved?.side === "right" ? "right" : "left",
+ };
} catch {
- return DEFAULT_WIDTH;
+ return { width: null, side: "left" };
}
}
-/** OpenDirector's drag, keyboard, reset and collapse behavior, with room for the canvas header. */
export function useAssistantLayout(
root: RefObject,
open: boolean,
onCollapse: () => void,
+ mode: WorkspaceMode,
) {
- const [preferredWidth, setPreferredWidth] = useState(readWidth);
- const [bounds, setBounds] = useState({
- viewport: window.innerWidth,
- heading: 260,
- actions: 200,
- });
+ const [dock, setDock] = useState(readDockPreference);
+ const { width: preferredWidth, side } = dock;
+ const setPreferredWidth = (width: number | null) => setDock(previous => ({ ...previous, width }));
+ const resizeDirection = side === "left" ? 1 : -1;
+ const [surface, setSurface] = useState(() => ({
+ left: 0,
+ top: 0,
+ width: window.innerWidth,
+ height: window.innerHeight,
+ }));
+ const viewport = surface.width;
const [dragging, setDragging] = useState(false);
- const drag = useRef<{ x: number; width: number; restore: number } | null>(
- null,
- );
- const mobile = bounds.viewport <= 700;
- const headerSpace = bounds.viewport - bounds.heading - bounds.actions - 72;
- const desktop = Boolean(window.opendirectorDesktop);
- const belowHeader = desktop || mobile || headerSpace <= COLLAPSE_AT;
+ const drag = useRef<{
+ x: number;
+ width: number;
+ restore: number | null;
+ } | null>(null);
+ const mobile = viewport <= 700;
+ const defaultWidth = Math.max(COLLAPSE_AT + 1, viewport / 3 - GUTTER);
+ const minWidth = window.opendirectorDesktop ? DESKTOP_MIN_WIDTH : COLLAPSE_AT;
const maxWidth = Math.min(
- MAX_WIDTH,
- belowHeader ? bounds.viewport - (mobile ? 20 : 28) : headerSpace,
+ Math.max(MAX_WIDTH, defaultWidth),
+ Math.max(COLLAPSE_AT + 1, viewport - 360 - GUTTER),
);
const width = mobile
- ? maxWidth
- : Math.min(Math.max(preferredWidth, desktop ? DESKTOP_MIN_WIDTH : COLLAPSE_AT), maxWidth);
-
+ ? Math.max(1, viewport - GUTTER)
+ : Math.min(Math.max(preferredWidth ?? defaultWidth, minWidth), maxWidth);
+ const floatingLayout = useFloatingAssistant(
+ mode === "canvas" && open && !mobile,
+ surface,
+ width,
+ );
const stop = () => {
drag.current = null;
setDragging(false);
};
useLayoutEffect(() => {
- const heading = root.current?.querySelector(
- ".cw-project-heading",
- );
- const actions = root.current?.querySelector(".cw-top-actions");
- const measure = () =>
- setBounds({
- viewport: window.innerWidth,
- heading: heading?.offsetWidth ?? 260,
- actions: actions?.offsetWidth ?? 200,
- });
- const resize = () => {
- stop();
- measure();
+ const host = root.current;
+ if (!host) return;
+ // The native project sidebar takes space from the header and both columns.
+ const topbar = host.querySelector(".cw-topbar");
+ if (!topbar) return;
+ const measure = () => {
+ const bounds = host.getBoundingClientRect();
+ const header = topbar.getBoundingClientRect();
+ const next = {
+ left: header.left - bounds.left,
+ top: header.bottom - bounds.top,
+ width: topbar.clientWidth,
+ height: Math.max(0, bounds.bottom - header.bottom),
+ };
+ setSurface((previous) =>
+ previous.left === next.left &&
+ previous.top === next.top &&
+ previous.width === next.width &&
+ previous.height === next.height
+ ? previous
+ : next,
+ );
};
const observer = new ResizeObserver(measure);
- if (heading) observer.observe(heading);
- if (actions) observer.observe(actions);
- window.addEventListener("resize", resize);
+ observer.observe(host);
+ observer.observe(topbar);
measure();
- return () => {
- observer.disconnect();
- window.removeEventListener("resize", resize);
- };
+ return () => observer.disconnect();
}, [root]);
useEffect(() => {
+ if (dragging) return;
try {
- localStorage.setItem(KEY, JSON.stringify({ width: preferredWidth }));
+ localStorage.setItem(KEY, JSON.stringify(dock));
} catch {
- /* Keep usable without storage. */
+ /* The active layout remains usable without storage. */
}
- }, [preferredWidth]);
+ }, [dock, dragging]);
useEffect(() => {
document.body.classList.toggle("cw-resizing-assistant", dragging);
return () => document.body.classList.remove("cw-resizing-assistant");
@@ -98,7 +122,6 @@ export function useAssistantLayout(
useEffect(() => {
if (!open) stop();
}, [open]);
-
const resize = (next: number, restore = preferredWidth) => {
if (next <= COLLAPSE_AT) {
stop();
@@ -117,7 +140,7 @@ export function useAssistantLayout(
const onPointerMove = (event: PointerEvent) => {
if (drag.current)
resize(
- drag.current.width + drag.current.x - event.clientX,
+ drag.current.width + resizeDirection * (event.clientX - drag.current.x),
drag.current.restore,
);
};
@@ -128,9 +151,9 @@ export function useAssistantLayout(
: event.key === "End"
? maxWidth
: event.key === "ArrowLeft"
- ? width + 10
+ ? width - 10 * resizeDirection
: event.key === "ArrowRight"
- ? width - 10
+ ? width + 10 * resizeDirection
: null;
if (next !== null) {
event.preventDefault();
@@ -139,12 +162,20 @@ export function useAssistantLayout(
}
};
return {
+ ...floatingLayout,
+ surface,
+ preferredWidth,
+ side,
+ dockTo(next: DockSide) {
+ setDock(previous => ({ ...previous, side: next }));
+ if (floatingLayout.floating) floatingLayout.toggleFloating();
+ },
width,
maxWidth,
mobile,
dragging,
- belowHeader,
- toolbarOffset: open && !belowHeader ? width + 6 : 0,
+ columnWidth:
+ open && !mobile && !floatingLayout.floating ? width + GUTTER : 0,
resizer: {
onPointerDown,
onPointerMove,
@@ -152,9 +183,8 @@ export function useAssistantLayout(
onPointerCancel: stop,
onLostPointerCapture: stop,
onKeyDown,
- onDoubleClick: () => setPreferredWidth(DEFAULT_WIDTH),
+ onDoubleClick: () => setPreferredWidth(null),
},
};
}
-
export type AssistantLayout = ReturnType;
diff --git a/src/canvas/useAssistantResults.ts b/src/canvas/useAssistantResults.ts
new file mode 100644
index 000000000..e4d545a17
--- /dev/null
+++ b/src/canvas/useAssistantResults.ts
@@ -0,0 +1,18 @@
+import { useCallback, useMemo, useSyncExternalStore } from "react";
+import { creationClient } from "../backend/creationClient";
+import type { ChatMessage } from "../backend/chat";
+import { timelinesForResultAssets } from "./assistantResultEditors.ts";
+import { assistantResultsByTurn, withPublishedAssistantResults } from "./assistantResults";
+
+export function useAssistantResults(projectId: string, enabled: boolean, messages: readonly ChatMessage[]) {
+ const client = enabled ? creationClient(projectId) : null;
+ const subscribe = useCallback(
+ (notify: () => void) => client ? client.listen(notify) : () => {},
+ [client],
+ );
+ const snapshot = useSyncExternalStore(subscribe, () => client?.snapshot);
+ const live = useMemo(() => assistantResultsByTurn(snapshot), [snapshot]);
+ const timelines = useMemo(() => timelinesForResultAssets(snapshot), [snapshot]);
+ const results = useMemo(() => withPublishedAssistantResults(live, messages, snapshot), [live, messages, snapshot]);
+ return { results, timelines, snapshot };
+}
diff --git a/src/canvas/useCanvasWheelBoundary.ts b/src/canvas/useCanvasWheelBoundary.ts
index 14618236d..093e2c878 100644
--- a/src/canvas/useCanvasWheelBoundary.ts
+++ b/src/canvas/useCanvasWheelBoundary.ts
@@ -6,6 +6,7 @@ import { MIN_ZOOM, MAX_ZOOM } from "./model.ts";
export function useCanvasWheelBoundary(
root: RefObject,
onNavigate: () => void,
+ enabled = true,
) {
const flow = useReactFlow();
const navigate = useRef(onNavigate);
@@ -19,8 +20,9 @@ export function useCanvasWheelBoundary(
let pointer = { x: 0, y: 0 };
const wheel = (event: WheelEvent) => {
if (!(event.ctrlKey || event.metaKey)) return;
- // A React wheel handler can be passive. Capture natively so browser page
- // zoom is cancelled even over controls rendered through a portal.
+ if (!enabled || !(event.target instanceof Node) || !root.current?.contains(event.target)) return;
+ // A React wheel handler can be passive. Capture natively so canvas
+ // controls zoom the canvas without also zooming the browser page.
event.preventDefault();
// Own every modified wheel, including those over inputs and portals, so
// React Flow cannot apply a second zoom or pan the underlying canvas.
@@ -68,5 +70,5 @@ export function useCanvasWheelBoundary(
document.removeEventListener("wheel", wheel, true);
if (frame) window.cancelAnimationFrame(frame);
};
- }, [root, flow]);
+ }, [root, flow, enabled]);
}
diff --git a/src/canvas/useFloatingAssistant.ts b/src/canvas/useFloatingAssistant.ts
new file mode 100644
index 000000000..3e4fa6030
--- /dev/null
+++ b/src/canvas/useFloatingAssistant.ts
@@ -0,0 +1,256 @@
+import {
+ useLayoutEffect,
+ useRef,
+ useState,
+ type CSSProperties,
+ type KeyboardEvent,
+ type PointerEvent,
+} from "react";
+
+export type AssistantSurface = {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+};
+type Position = { x: number; y: number };
+type Preference = { floating: boolean; position: Position };
+const KEY = "opendirector.assistant-floating.v1";
+const GUTTER = 14;
+const clamp = (value: number, max: number) => Math.min(Math.max(0, value), max);
+
+function readPreference(): Preference {
+ try {
+ const saved = JSON.parse(localStorage.getItem(KEY) ?? "null");
+ if (
+ typeof saved?.floating === "boolean" &&
+ Number.isFinite(saved.position?.x) &&
+ Number.isFinite(saved.position?.y)
+ ) {
+ return {
+ floating: saved.floating,
+ position: {
+ x: clamp(saved.position.x, 1),
+ y: clamp(saved.position.y, 1),
+ },
+ };
+ }
+ } catch {
+ /* Storage is optional. */
+ }
+ return { floating: false, position: { x: 1, y: 0 } };
+}
+
+type Move = {
+ panel: HTMLElement;
+ handle: HTMLElement;
+ pointerId: number;
+ startX: number;
+ startY: number;
+ origin: Position;
+ point: Position;
+ active: boolean;
+};
+
+function paintMove(move: Move) {
+ move.panel.style.setProperty("--cw-chat-drag-x", `${move.point.x}px`);
+ move.panel.style.setProperty("--cw-chat-drag-y", `${move.point.y}px`);
+}
+
+/** Panel coordinates are local to the workspace, independent of canvas pan and zoom. */
+export function useFloatingAssistant(
+ available: boolean,
+ surface: AssistantSurface,
+ dockedWidth: number,
+) {
+ const [preference, setPreference] = useState(readPreference);
+ const [moving, setMoving] = useState(false);
+ const gesture = useRef(null);
+ const frame = useRef(null);
+ const floating = available && (preference.floating || moving);
+ const width = Math.min(
+ 460,
+ Math.max(320, dockedWidth),
+ Math.max(1, surface.width - 2 * GUTTER),
+ );
+ const room = Math.max(1, surface.height - 2 * GUTTER);
+ const height = Math.min(room, 620, Math.max(320, Math.round(room * 0.75)));
+ const left = surface.left + GUTTER;
+ const top = surface.top + GUTTER;
+ const travelX = Math.max(0, surface.width - 2 * GUTTER - width);
+ const travelY = room - height;
+ const place = (x: number, y: number): Position => ({
+ x: left + clamp(x - left, travelX),
+ y: top + clamp(y - top, travelY),
+ });
+ const position = {
+ x: left + preference.position.x * travelX,
+ y: top + preference.position.y * travelY,
+ };
+
+ function save(next: Preference) {
+ setPreference(next);
+ try {
+ localStorage.setItem(KEY, JSON.stringify(next));
+ } catch {
+ /* Keep the in-memory layout. */
+ }
+ }
+ function savePosition(point: Position) {
+ save({
+ floating: true,
+ position: {
+ x: travelX
+ ? clamp((point.x - left) / travelX, 1)
+ : preference.position.x,
+ y: travelY
+ ? clamp((point.y - top) / travelY, 1)
+ : preference.position.y,
+ },
+ });
+ }
+ function finish(commit: boolean) {
+ const move = gesture.current;
+ if (!move) return;
+ gesture.current = null;
+ if (frame.current !== null) cancelAnimationFrame(frame.current);
+ frame.current = null;
+ if (move.handle.hasPointerCapture(move.pointerId)) {
+ move.handle.releasePointerCapture(move.pointerId);
+ }
+ if (move.active && commit) savePosition(move.point);
+ move.panel.style.removeProperty("--cw-chat-drag-x");
+ move.panel.style.removeProperty("--cw-chat-drag-y");
+ setMoving(false);
+ }
+ // A sidebar toggle or viewport change can invalidate the geometry mid-gesture.
+ useLayoutEffect(() => {
+ if (!available) return;
+ const cancel = () => finish(false);
+ window.addEventListener("blur", cancel);
+ return () => {
+ window.removeEventListener("blur", cancel);
+ cancel();
+ };
+ }, [available, surface, width]);
+
+ function onPointerDown(event: PointerEvent) {
+ if (!available || !event.isPrimary || event.button !== 0 || gesture.current)
+ return;
+ const panel = event.currentTarget.closest("#canvas-assistant");
+ if (!panel) return;
+ const rect = panel.getBoundingClientRect();
+ // Preserve the point grabbed on the title, including when the docked title is wider.
+ const origin = {
+ x:
+ panel.offsetLeft +
+ Math.max(0, event.clientX - rect.left - width + GUTTER),
+ y: panel.offsetTop,
+ };
+ event.preventDefault();
+ event.stopPropagation();
+ event.currentTarget.focus({ preventScroll: true });
+ event.currentTarget.setPointerCapture(event.pointerId);
+ gesture.current = {
+ pointerId: event.pointerId,
+ startX: event.clientX,
+ startY: event.clientY,
+ panel,
+ handle: event.currentTarget,
+ origin,
+ point: origin,
+ active: false,
+ };
+ }
+ function onPointerMove(event: PointerEvent) {
+ const move = gesture.current;
+ if (!move || move.pointerId !== event.pointerId) return;
+ const dx = event.clientX - move.startX;
+ const dy = event.clientY - move.startY;
+ move.point = place(move.origin.x + dx, move.origin.y + dy);
+ if (!move.active) {
+ if (Math.hypot(dx, dy) < 5) return;
+ move.active = true;
+ // On detachment the next render must start at the grip, even before its first frame.
+ paintMove(move);
+ setMoving(true);
+ return;
+ }
+ if (frame.current === null) {
+ frame.current = requestAnimationFrame(() => {
+ frame.current = null;
+ paintMove(move);
+ });
+ }
+ }
+ function onKeyDown(event: KeyboardEvent) {
+ if (!available) return;
+ if (event.key === "Escape" && gesture.current) {
+ event.preventDefault();
+ event.stopPropagation();
+ finish(false);
+ return;
+ }
+ const step = event.shiftKey ? 48 : 16;
+ const offset: Record = {
+ ArrowLeft: { x: -step, y: 0 },
+ ArrowRight: { x: step, y: 0 },
+ ArrowUp: { x: 0, y: -step },
+ ArrowDown: { x: 0, y: step },
+ };
+ const delta = offset[event.key];
+ if (!delta) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const panel = event.currentTarget.closest("#canvas-assistant");
+ const origin =
+ !floating && panel
+ ? { x: panel.offsetLeft, y: panel.offsetTop }
+ : position;
+ savePosition(place(origin.x + delta.x, origin.y + delta.y));
+ }
+ const floatingStyle: CSSProperties | undefined = floating
+ ? {
+ left: `var(--cw-chat-drag-x, ${position.x}px)`,
+ top: `var(--cw-chat-drag-y, ${position.y}px)`,
+ right: "auto",
+ bottom: "auto",
+ width,
+ height,
+ }
+ : undefined;
+ return {
+ floating,
+ floatingStyle,
+ enableFloating() {
+ finish(false);
+ save({ ...preference, floating: true });
+ },
+ toggleFloating() {
+ if (available) {
+ finish(false);
+ save({ ...preference, floating: !floating });
+ }
+ },
+ moveHandle: {
+ onPointerDown,
+ onPointerMove,
+ onKeyDown,
+ onPointerUp: (event: PointerEvent) => {
+ const move = gesture.current;
+ if (!move || event.pointerId !== move.pointerId) return;
+ move.point = place(
+ move.origin.x + event.clientX - move.startX,
+ move.origin.y + event.clientY - move.startY,
+ );
+ finish(true);
+ },
+ onPointerCancel: (event: PointerEvent) => {
+ if (event.pointerId === gesture.current?.pointerId) finish(false);
+ },
+ onLostPointerCapture: (event: PointerEvent) => {
+ if (event.pointerId === gesture.current?.pointerId) finish(false);
+ },
+ },
+ };
+}
diff --git a/src/canvas/usePendingCanvasReferences.ts b/src/canvas/usePendingCanvasReferences.ts
index d441811fb..c7d9f5e64 100644
--- a/src/canvas/usePendingCanvasReferences.ts
+++ b/src/canvas/usePendingCanvasReferences.ts
@@ -75,7 +75,7 @@ export function usePendingCanvasReferences(
if (
!latest.current ||
target.closest(
- "[data-pending-references],.cw-chat-reference-editor,.cw-chat-button",
+ '[data-pending-references],.cw-chat-reference-editor,.cw-chat-button,.cw-chat-result,.cw-preview,.cw-domain-overlay,[aria-modal="true"]',
)
)
return;
@@ -93,6 +93,12 @@ export function usePendingCanvasReferences(
return;
}
if (!latest.current || event.isComposing || event.keyCode === 229) return;
+ // Menus and open editors own their dismissal, including ARIA-based modals.
+ if (
+ event.target instanceof Element &&
+ event.target.closest('[role="menu"],dialog:modal,[aria-modal="true"]')
+ )
+ return;
event.preventDefault();
suppressed.current = true;
cancel();
diff --git a/src/canvas/useSelectionPresentation.ts b/src/canvas/useSelectionPresentation.ts
index 3d68a7d45..8c1bb5bd3 100644
--- a/src/canvas/useSelectionPresentation.ts
+++ b/src/canvas/useSelectionPresentation.ts
@@ -12,9 +12,39 @@ import {
projectSelectionRect,
selectionPlacement,
selectionViewport,
+ visibleSelectionArea,
type SelectionChrome,
} from "./selectionPresentation";
+function floatingPanelRect(host: HTMLElement | null): Rect | null {
+ const floating = host?.closest(".cw-workspace")?.querySelector(
+ '#canvas-assistant[data-floating="true"]:not([hidden])',
+ );
+ if (!host || !floating) return null;
+ const canvas = host.getBoundingClientRect();
+ const panel = floating.getBoundingClientRect();
+ return {
+ x: panel.left - canvas.left - 8,
+ y: panel.top - canvas.top - 8,
+ width: panel.width + 16,
+ height: panel.height + 16,
+ };
+}
+
+function fitOutsidePanel(
+ bounds: Rect, view: Viewport, chrome: SelectionChrome, panel: Rect | null,
+): SelectionChrome {
+ const safe = visibleSelectionArea(bounds, view, chrome, panel);
+ if (safe === chrome.safe) return chrome;
+ return {
+ ...chrome, safe,
+ toolbar: { ...chrome.toolbar, width: Math.min(chrome.toolbar.width, safe.width) },
+ composer: chrome.scaleComposer ? chrome.composer : {
+ ...chrome.composer, width: Math.min(chrome.composer.width, safe.width),
+ },
+ };
+}
+
/** One geometry owner for the node, upper action bar and lower generator. */
export function useSelectionPresentation({
root,
@@ -29,6 +59,8 @@ export function useSelectionPresentation({
controlsKey,
preferredZoom,
scaleComposer = false,
+ preserveViewportKey = "",
+ workspaceSize,
}: {
root: RefObject;
toolbar: RefObject;
@@ -43,6 +75,9 @@ export function useSelectionPresentation({
/** Dedicated media editing may enlarge its source; ordinary selection preserves zoom. */
preferredZoom?: number;
scaleComposer?: boolean;
+ /** Explicit chat layout changes preserve the user's viewport until the workspace resizes. */
+ preserveViewportKey?: string;
+ workspaceSize: { width: number; height: number };
}) {
const flow = useReactFlow();
const viewport = useViewport();
@@ -57,10 +92,12 @@ export function useSelectionPresentation({
const [measurement, setMeasurement] = useState<{
key: string;
obscured: boolean;
+ fullSafe: Rect;
chrome: SelectionChrome;
}>({
key: "",
obscured: false,
+ fullSafe: { x: 80, y: 72, width: 0, height: 0 },
chrome: {
safe: { x: 80, y: 72, width: 0, height: 0 },
toolbar: { width: 0, height: 0 },
@@ -72,6 +109,7 @@ export function useSelectionPresentation({
useLayoutEffect(() => {
const host = root.current;
if (!host) return;
+ const startingViewport = flow.getViewport();
const measure = () => {
const rect = host.getBoundingClientRect();
const panels = [...host.querySelectorAll(".cw-side-panel,.cw-assistant-panel:not([hidden])")];
@@ -111,16 +149,21 @@ export function useSelectionPresentation({
: (box?.height ?? 0),
};
};
+ const measured: SelectionChrome = {
+ safe,
+ canvasOrigin,
+ toolbar: size(toolbar.current),
+ composer: size(composer.current, scaleComposer),
+ scaleComposer,
+ };
+ const overlay = floatingPanelRect(host);
const next = {
key: measurementKey,
obscured: covered,
- chrome: {
- safe,
- canvasOrigin,
- toolbar: size(toolbar.current),
- composer: size(composer.current, scaleComposer),
- scaleComposer,
- },
+ fullSafe: safe,
+ chrome: bounds && overlay
+ ? fitOutsidePanel(bounds, selectionViewport(bounds, startingViewport, measured), measured, overlay)
+ : measured,
};
setMeasurement((previous) =>
JSON.stringify(previous) === JSON.stringify(next) ? previous : next,
@@ -137,6 +180,8 @@ export function useSelectionPresentation({
}, [root, canvas, toolbar, composer, measurementKey, scaleComposer]);
const lastLayout = useRef("");
+ const lastAssistantLayout = useRef(preserveViewportKey);
+ const preservedIntent = useRef(null);
const origin = useRef<{ key: string; viewport: Viewport } | null>(null);
const animation = useRef(null);
const stopPresentation = useCallback(() => {
@@ -160,6 +205,13 @@ export function useSelectionPresentation({
};
useLayoutEffect(() => stopPresentation, [stopPresentation]);
useLayoutEffect(() => {
+ const intent = JSON.stringify([nodeId, focusRequest, panel]);
+ const layoutIntent = JSON.stringify([intent, workspaceSize.width, workspaceSize.height]);
+ if (lastAssistantLayout.current !== preserveViewportKey) {
+ preservedIntent.current = layoutIntent;
+ lastAssistantLayout.current = preserveViewportKey;
+ origin.current = { key: intent, viewport: flow.getViewport() };
+ }
if (!bounds || blocked || obscured) stopPresentation();
// A new node must not be fitted using the previous node's generator height.
if (measurement.key !== measurementKey) return;
@@ -174,7 +226,11 @@ export function useSelectionPresentation({
if (!bounds || blocked || obscured || chrome.safe.width === 0) return;
lastLayout.current = key;
const current = flow.getViewport();
- const intent = JSON.stringify([nodeId, focusRequest, panel]);
+ if (preservedIntent.current === layoutIntent) {
+ stopPresentation();
+ return;
+ }
+ preservedIntent.current = null;
if (origin.current?.key !== intent)
origin.current = {
key: intent,
@@ -212,11 +268,18 @@ export function useSelectionPresentation({
measurement.key,
measurementKey,
preferredZoom,
+ preserveViewportKey,
+ workspaceSize.width,
+ workspaceSize.height,
]);
- const placement = bounds
+ let placement = bounds
? selectionPlacement(bounds, viewport, chrome)
: null;
+ // A manually panned node is still editable anywhere on the canvas.
+ if (bounds && placement && !placement.visible && chrome.safe !== measurement.fullSafe) {
+ placement = selectionPlacement(bounds, viewport, { ...chrome, safe: measurement.fullSafe });
+ }
const media = mediaBounds
? projectSelectionRect(mediaBounds, viewport, chrome.canvasOrigin)
: null;
@@ -227,23 +290,32 @@ export function useSelectionPresentation({
},
fitSelection: (maxZoom = 1.5) => {
if (!bounds || obscured || !chrome.safe.width) return;
+ const full = { ...chrome, safe: measurement.fullSafe };
const view = { ...flow.getViewport(), zoom: maxZoom };
+ const proposed = centeredViewport(bounds, view, full);
+ const visible = fitOutsidePanel(bounds, proposed, full, floatingPanelRect(root.current));
+ const safe = visible.safe;
// The explicit Fit command may enlarge; normal selection only contains.
- view.x = chrome.safe.x + chrome.safe.width / 2 -
+ view.x = safe.x + safe.width / 2 -
(bounds.x + bounds.width / 2) * maxZoom - (chrome.canvasOrigin?.x ?? 0);
- view.y = chrome.safe.y + chrome.safe.height / 2 -
+ view.y = safe.y + safe.height / 2 -
(bounds.y + bounds.height / 2) * maxZoom - (chrome.canvasOrigin?.y ?? 0);
origin.current = {
key: JSON.stringify([nodeId, focusRequest, panel]),
viewport: view,
};
- present(selectionViewport(bounds, view, chrome));
+ present(selectionViewport(bounds, view, visible));
},
reveal: (bounds: Rect) => {
if (obscured || !chrome.safe.width) return;
- present(centeredViewport(bounds, flow.getViewport(), {
- safe: chrome.safe, canvasOrigin: chrome.canvasOrigin, toolbar: { width: 0, height: 0 }, composer: { width: 0, height: 0 },
- }));
+ const view = flow.getViewport();
+ const full = {
+ safe: measurement.fullSafe, canvasOrigin: chrome.canvasOrigin,
+ toolbar: { width: 0, height: 0 }, composer: { width: 0, height: 0 },
+ };
+ const proposed = centeredViewport(bounds, view, full);
+ const visible = fitOutsidePanel(bounds, proposed, full, floatingPanelRect(root.current));
+ present(visible === full ? proposed : centeredViewport(bounds, view, visible));
},
placement,
mediaRect: media
diff --git a/src/canvas/welcome-screen.css b/src/canvas/welcome-screen.css
index 652d54229..aba621074 100644
--- a/src/canvas/welcome-screen.css
+++ b/src/canvas/welcome-screen.css
@@ -74,11 +74,10 @@ html[data-desktop-platform="win32"]:not([data-desktop-fullscreen]) .cw-welcome {
font-size: 16px;
line-height: 1.7;
}
-.cw-welcome-intro-copy .cw-welcome-primary {
- width: min(100%, 206px);
+.cw-welcome-intro-copy > .cw-welcome-primary {
+ margin-top: 20px;
min-height: 46px;
padding: 10px 20px;
- margin-top: 36px;
border-radius: 10px;
font: inherit;
font-weight: 600;
@@ -108,11 +107,22 @@ html[data-desktop-platform="win32"]:not([data-desktop-fullscreen]) .cw-welcome {
@media (max-width: 780px) {
.cw-welcome-shell.is-intro { width: min(100% - 32px, 600px); }
.cw-welcome-intro { grid-template-columns: minmax(0, 1fr); min-height: auto; gap: 24px; padding: clamp(32px, 7vh, 68px) 0 24px; }
- .cw-welcome-intro-copy .cw-welcome-primary { margin-top: 22px; }
}
.cw-welcome-description { margin: 12px 0 20px; color: var(--settings-muted); font-size: 14px; line-height: 1.6; }
-.cw-welcome-connected { color: var(--settings-text); font-size: 13px; margin: -4px 0 16px; overflow-wrap: anywhere; }
.cw-welcome-options { display: grid; gap: 8px; min-width: 0; margin: 0; padding: 0; border: 0; }
+.cw-welcome-mode-connected { margin: 8px 0 28px; color: var(--settings-muted); overflow-wrap: anywhere; }
+.cw-welcome-modes { gap: 10px; }
+.cw-welcome-modes .cw-welcome-option { padding: 16px 20px; }
+.cw-welcome-modes .cw-welcome-option > span { flex: 1; }
+.cw-welcome-modes .cw-welcome-mode-agent {
+ min-height: 104px;
+ background: color-mix(in srgb, var(--cw-control-accent) 13%, var(--settings-input));
+ border-color: var(--cw-control-accent);
+}
+.cw-welcome-modes .cw-welcome-mode-agent > svg { color: var(--cw-control-accent); }
+.cw-welcome-modes .cw-welcome-mode-agent strong { font-size: 20px; }
+.cw-welcome-modes .cw-welcome-mode-agent small { font-size: 14px; }
+.cw-welcome-modes .cw-welcome-mode-canvas { background: transparent; }
.cw-welcome-option {
box-sizing: border-box;
display: flex;
@@ -141,7 +151,6 @@ html[data-desktop-platform="win32"]:not([data-desktop-fullscreen]) .cw-welcome {
.cw-welcome-content.is-task-step { width: 100%; padding-top: clamp(28px, 9vh, 88px); text-align: center; }
.is-task-step .cw-welcome-steps { justify-content: center; }
.is-task-step .cw-welcome-description { margin-bottom: 24px; }
-.is-task-step .cw-welcome-connected { color: var(--settings-muted); margin-bottom: 24px; }
.cw-welcome-task-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
@@ -358,7 +367,6 @@ html[data-desktop-platform="win32"]:not([data-desktop-fullscreen]) .cw-welcome {
.cw-welcome-content.is-task-step { padding-top: 24px; }
.is-task-step .cw-welcome-steps { margin-bottom: 14px; }
.is-task-step .cw-welcome-description { margin: 8px 0 14px; }
- .is-task-step .cw-welcome-connected { margin-bottom: 14px; }
.cw-welcome-task-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
.cw-welcome-task-grid .cw-welcome-task-card {
grid-column: span 1;
diff --git a/src/canvas/workspace-modes.css b/src/canvas/workspace-modes.css
new file mode 100644
index 000000000..6b1b75201
--- /dev/null
+++ b/src/canvas/workspace-modes.css
@@ -0,0 +1,162 @@
+/* One project surface with stable conversation and editor instances. */
+.cw-workspace {
+ --chat-left-inset: var(--assistant-column-width, 0px);
+ --chat-right-inset: 0px;
+}
+.cw-workspace[data-chat-dock="right"] {
+ --chat-left-inset: 0px;
+ --chat-right-inset: var(--assistant-column-width);
+}
+.cw-canvas-region {
+ position: absolute;
+ inset: 0 var(--chat-right-inset) 0 var(--chat-left-inset);
+ overflow: clip;
+ min-width: 0;
+}
+.cw-canvas-region[data-visible="false"] {
+ opacity: 0;
+ visibility: hidden;
+ pointer-events: none;
+}
+.cw-workspace .cw-top-actions {
+ transform: none;
+ transition: none;
+}
+.cw-canvas-top-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+.cw-canvas-top-actions[hidden],
+.cw-language-toggle[hidden] { display: none; }
+.cw-float-on-canvas {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 7px 9px;
+ border-radius: 7px;
+ color: var(--settings-muted);
+ white-space: nowrap;
+}
+.cw-float-on-canvas:hover {
+ background: var(--settings-hover);
+ color: var(--settings-text);
+}
+.cw-workspace-mode-switch {
+ display: flex;
+ flex-shrink: 0;
+ padding: 3px;
+ border: 1px solid var(--cw-border);
+ border-radius: 10px;
+ background: var(--cw-surface);
+}
+.cw-workspace-mode-switch button {
+ padding: 7px 12px;
+ border-radius: 7px;
+ color: #99999e;
+ white-space: nowrap;
+}
+.cw-workspace-mode-switch button[aria-pressed="true"] {
+ color: #fff;
+ background: #414145;
+ font-weight: 600;
+}
+:is(.cw-editor-header, .lb-header):has(> .cw-workspace-mode-switch) {
+ flex-wrap: wrap;
+}
+:is(.cw-editor-header, .lb-header, .cw-domain-header):has(> .cw-workspace-mode-switch) > :first-child {
+ flex: 1 1 auto;
+ min-width: 0;
+ overflow-wrap: anywhere;
+}
+:is(.cw-editor-header-actions, .lb-header-actions) {
+ margin-inline-start: auto;
+}
+.cw-workspace .cw-assistant-panel {
+ top: 78px;
+ left: 14px;
+ right: auto;
+ bottom: 14px;
+}
+.cw-workspace[data-workspace-mode="agent"] .cw-assistant-panel {
+ inset: var(--cw-topbar-height) 0 0;
+ width: auto;
+}
+:root:not([data-desktop-chrome]) .cw-workspace[data-workspace-mode="agent"] .cw-topbar {
+ border-bottom: 1px solid var(--cw-border);
+}
+.cw-workspace .cw-assistant-resizer {
+ left: auto;
+ right: 0;
+}
+.cw-workspace[data-chat-dock="right"] .cw-assistant-panel:not([data-floating]) {
+ left: auto;
+ right: 14px;
+}
+.cw-workspace[data-chat-dock="right"] .cw-assistant-resizer {
+ left: 0;
+ right: auto;
+}
+.cw-workspace[data-assistant-open="true"] .cw-side-panel:not(.from-left) {
+ right: 20px;
+}
+.cw-workspace[data-workspace-mode="canvas"] .cw-creation-assets {
+ right: calc(20px + var(--chat-right-inset));
+ width: min(370px, calc(100vw - var(--assistant-column-width, 0px) - 40px));
+}
+.cw-canvas-region .cw-side-panel.from-left {
+ max-width: calc(100% - 96px);
+}
+.cw-narrow-region-toggle {
+ position: absolute;
+ z-index: 35;
+ bottom: 14px;
+ right: 14px;
+ padding: 9px 16px;
+ border: 1px solid var(--cw-border);
+ border-radius: 20px;
+ background: var(--cw-surface);
+ color: inherit;
+}
+:root[data-theme="light"] .cw-workspace-mode-switch button { color: #757b86; }
+:root[data-theme="light"] .cw-workspace-mode-switch button[aria-pressed="true"] {
+ color: #30343c;
+ background: #e4e7ed;
+}
+@media (max-width: 1000px) {
+ .cw-workspace .cw-topbar { gap: 8px; padding-inline: 12px; }
+ .cw-workspace .cw-project-heading { gap: 5px; }
+ .cw-workspace .cw-project-title { max-width: 180px; }
+ .cw-workspace .cw-save-status { display: none; }
+ .cw-workspace .cw-top-actions { gap: 5px; }
+ .cw-canvas-top-actions { gap: 2px; }
+ .cw-workspace-mode-switch button { padding-inline: 9px; }
+}
+@media (max-width: 700px) {
+ .cw-workspace .cw-canvas-region { left: 0; }
+ .cw-workspace[data-workspace-mode="canvas"] .cw-assistant-panel {
+ width: calc(100% - 28px);
+ bottom: 62px;
+ }
+ .cw-workspace .cw-project-title { max-width: 110px; }
+ .cw-workspace .cw-brand { width: 26px; height: 26px; margin-right: 0; }
+ .cw-workspace .cw-language-toggle,
+ .cw-workspace .cw-node-info { display: none; }
+ .cw-workspace[data-canvas-visible="false"] .cw-canvas-top-actions { display: none; }
+ .cw-canvas-top-actions {
+ position: absolute;
+ top: 72px;
+ right: 12px;
+ padding: 4px;
+ border-radius: 9px;
+ background: var(--cw-surface);
+ }
+ .cw-workspace[data-workspace-mode="canvas"] .cw-creation-assets {
+ top: 120px;
+ max-height: min(760px, calc(100dvh - 182px));
+ }
+ .cw-workspace .cw-side-panel:not(.from-left) {
+ top: 120px;
+ }
+ .cw-workspace-mode-switch button { font-size: 12px; padding: 7px; }
+}
diff --git a/src/canvas/workspace.css b/src/canvas/workspace.css
index d8c4f545a..2ccc50495 100644
--- a/src/canvas/workspace.css
+++ b/src/canvas/workspace.css
@@ -1,4 +1,5 @@
.cw-workspace {
+ --cw-topbar-height: 68px;
position: fixed;
inset: 0;
overflow: clip;
@@ -308,7 +309,7 @@
top: 0;
left: 0;
right: 0;
- height: 68px;
+ height: var(--cw-topbar-height);
padding: 14px 20px;
display: flex;
align-items: center;
@@ -928,152 +929,62 @@
.cw-import-button:hover {
background: #333336;
}
-.cw-rail-shell {
+.cw-rail {
position: absolute;
z-index: 10;
- top: 76px;
- bottom: 76px;
- left: 0;
- width: min(248px, calc(100vw - 24px));
- display: flex;
- align-items: center;
- pointer-events: none;
-}
-.cw-rail-mask {
- position: absolute;
- top: -76px;
- bottom: -76px;
- left: 0;
- right: 0;
- background: linear-gradient(90deg, #0d0d0df5 20%, #0d0d0dd9 55%, #0d0d0d00);
- opacity: 0;
- transition: opacity 300ms ease;
- pointer-events: none;
-}
-.cw-rail-scroll {
- position: relative;
- max-height: 100%;
- width: 100%;
- overflow-y: auto;
- scrollbar-width: none;
- padding: 4px 0;
- pointer-events: none;
-}
-.cw-rail-scroll::-webkit-scrollbar {
- display: none;
-}
-.cw-rail {
- position: relative;
- margin-left: 10px;
- width: 46px;
- padding: 4px;
+ top: 82px;
+ left: 14px;
display: flex;
flex-direction: column;
- gap: 3px;
- border: 1px solid #ffffff0b;
- border-radius: 10px;
- background: #202022;
- box-shadow: 0 8px 24px #0003;
- pointer-events: auto;
+ width: max-content;
+ padding: 4px;
+ gap: 2px;
+ border: 1px solid var(--cw-border);
+ border-radius: 14px;
+ background: var(--cw-surface);
+ box-shadow: 0 4px 18px #0002;
}
-.cw-rail-item {
- flex-shrink: 0;
+html[data-desktop-chrome] .cw-rail {
+ top: 16px;
}
.cw-rail-button {
- position: relative;
display: flex;
+ flex-direction: column;
align-items: center;
- width: 36px;
- height: 36px;
- padding: 0;
+ justify-content: center;
+ gap: 5px;
+ min-height: 54px;
+ padding: 5px 8px;
border: 0;
- border-radius: 8px;
- color: #eee;
+ border-radius: 9px;
background: transparent;
+ color: var(--settings-muted);
}
-.cw-rail-icon {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 36px;
- height: 36px;
- flex-shrink: 0;
- border-radius: 8px;
+.cw-rail-button:hover,
+.cw-rail-button[aria-expanded="true"] {
+ background: var(--settings-active);
+ color: var(--settings-text);
+}
+.cw-rail .cw-rail-add {
+ background: var(--cw-control-active);
+ color: var(--cw-control-highlight);
+}
+.cw-rail .cw-rail-add:hover,
+.cw-rail .cw-rail-add[aria-expanded="true"] {
+ background: var(--cw-control-accent);
+ color: var(--cw-control-on-accent);
}
.cw-rail-label {
- position: absolute;
- left: 60px;
- white-space: nowrap;
- opacity: 0;
- transform: translateX(-16px);
- transition:
- opacity 300ms ease,
- transform 300ms ease;
font-size: var(--cw-ui-font-size);
+ line-height: 1.15;
font-weight: 500;
- color: #a5a5a9;
- pointer-events: none;
-}
-.cw-rail-shell[data-revealed="true"] .cw-rail-mask,
-.cw-rail-shell[data-revealed="true"] .cw-rail-label {
- opacity: 1;
-}
-.cw-rail-shell[data-revealed="true"] .cw-rail-label {
- transform: translateX(0);
-}
-.cw-rail-shell[data-revealed="true"] .cw-rail-scroll {
- pointer-events: auto;
-}
-.cw-rail-shell[data-revealed="true"] .cw-rail-button {
- width: min(210px, calc(100vw - 52px));
-}
-.cw-rail-button:hover {
- color: #fff;
-}
-.cw-rail-button:hover .cw-rail-label {
- color: #fff;
-}
-.cw-rail-button[aria-disabled="true"],
-.cw-rail-button[aria-disabled="true"]:hover {
- color: #77777d;
- cursor: not-allowed;
-}
-.cw-rail-button[aria-disabled="true"] .cw-rail-label {
- color: inherit;
-}
-.cw-rail-button[aria-disabled="true"]:hover .cw-rail-icon {
- background: transparent;
- color: inherit;
-}
-:root[data-theme="light"] .cw-rail-button {
- color: #58616e;
-}
-:root[data-theme="light"] .cw-rail-button[aria-disabled="true"],
-:root[data-theme="light"] .cw-rail-button[aria-disabled="true"]:hover,
-:root[data-theme="light"] .cw-rail-button[aria-disabled="true"] .cw-rail-label {
- color: #a0a6af;
-}
-:root[data-theme="light"] .cw-rail-button[aria-disabled="true"]:hover {
- background: transparent;
-}
-.cw-rail-button:hover .cw-rail-icon,
-.cw-rail-button.is-active .cw-rail-icon {
- background: #ffffff10;
- color: #fff;
-}
-.cw-rail-button:focus-visible {
- outline-offset: 0 !important;
+ white-space: nowrap;
}
.cw-rail .cw-divider {
- display: block;
- margin: 4px 2px;
-}
-@media (prefers-reduced-motion: reduce) {
- .cw-rail-mask,
- .cw-rail-label {
- transition: none;
- }
+ margin: 2px 6px;
+ background: var(--cw-border);
}
+
.cw-divider {
height: 1px;
background: #ffffff10;
@@ -1176,95 +1087,40 @@
position: absolute;
z-index: 2;
left: 50%;
- top: 45%;
+ top: 48%;
+ width: min(calc(100% - 48px), 430px);
transform: translate(-50%, -50%);
text-align: center;
pointer-events: none;
- width: min(80vw, 600px);
-}
-.cw-empty > * {
- position: relative;
-}
-.cw-empty .cw-aurora {
- position: absolute;
- left: 50%;
- top: 50%;
- width: 560px;
- height: 360px;
- transform: translate(-50%, -50%);
- background:
- radial-gradient(ellipse at 30% 50%, #22382f28, transparent 58%),
- radial-gradient(ellipse at 70% 50%, #42333222, transparent 58%);
- filter: blur(18px);
- border-radius: 50%;
-}
-.cw-empty-orb {
- color: #c9cbd0;
- opacity: 0.65;
- margin-bottom: 12px;
- line-height: 0;
}
.cw-empty h1 {
- font-size: 23px;
- letter-spacing: 3px;
- font-weight: 450;
- margin: 0 0 16px;
- color: #dfdfe0;
+ margin: 0 0 9px;
+ font-size: 22px;
+ font-weight: 550;
+ letter-spacing: -0.035em;
+ color: var(--settings-text);
}
.cw-empty p {
- font-size: 12px;
- color: #727277;
- margin-bottom: 26px;
-}
-.cw-empty > div:not(.cw-aurora):not(.cw-empty-orb) {
- display: flex;
- justify-content: center;
- gap: 12px;
+ margin: 0 auto 13px;
+ font-size: 14px;
+ line-height: 1.65;
+ color: var(--settings-muted);
+ text-wrap: balance;
}
.cw-empty button {
- pointer-events: auto;
- display: flex;
+ display: inline-flex;
align-items: center;
- gap: 6px;
- border: 1px solid #ffffff16;
- background: #1b1b1dd9;
- border-radius: 8px;
- padding: 10px 16px;
- font-size: 12px;
-}
-
-.cw-empty-example-status {
- gap: 8px;
- margin: 16px auto 0;
- max-width: 320px;
- font-size: 12px;
- color: #9599a8;
-}
-
-.cw-empty-example-status .cw-example-progress {
- flex: 1;
- min-width: 120px;
-}
-
-/* Specificity beats the shared .cw-empty small tagline rule. */
-.cw-empty small.cw-empty-example-error {
- display: block;
- margin: 12px auto 0;
- max-width: 420px;
- color: #e08a8a;
- font-size: 12px;
- line-height: 1.6;
+ gap: 4px;
+ padding: 7px 10px;
+ border: 0;
+ border-radius: 7px;
+ background: transparent;
+ color: var(--settings-muted);
+ pointer-events: auto;
}
-
.cw-empty button:hover {
- background: #2a2a2d;
-}
-.cw-empty small {
- display: block;
- margin-top: 27px;
- color: #49494d;
- font-size: 10px;
- letter-spacing: 1px;
+ background: var(--settings-hover);
+ color: var(--settings-text);
}
.cw-loading {
position: absolute;
@@ -1904,6 +1760,13 @@
margin: 0;
}
.cw-preview {
+ width: 100%;
+ height: 100%;
+ max-width: none;
+ max-height: none;
+ margin: 0;
+ border: 0;
+ color: inherit;
background: #0a0a0bf2;
}
.cw-preview > header {
@@ -1921,7 +1784,9 @@
.cw-preview > div {
max-width: 92vw;
max-height: 84vh;
+ overflow: auto;
}
+.cw-preview pre { white-space: pre-wrap; overflow-wrap: anywhere; }
.cw-preview img,
.cw-preview video {
max-width: 92vw;
@@ -1943,16 +1808,10 @@
}
}
@media (max-width: 700px) {
- .cw-rail-shell {
- top: 68px;
- bottom: 116px;
- }
- .cw-rail-mask {
- top: -68px;
- bottom: -116px;
+ .cw-workspace {
+ --cw-topbar-height: 58px;
}
.cw-topbar {
- height: 58px;
padding: 10px;
}
.cw-project-title {
@@ -1978,30 +1837,16 @@
width: 30px;
}
.cw-rail {
- margin-left: 8px;
- width: 42px;
- padding: 3px;
+ top: 72px;
+ left: 8px;
}
- .cw-rail-button,
- .cw-rail-icon {
- width: 34px;
- }
- .cw-rail-label {
- left: 58px;
+ .cw-rail-button {
+ min-height: 46px;
+ gap: 3px;
+ padding: 4px 6px;
}
.cw-empty h1 {
- font-size: 19px;
- }
- .cw-empty {
- top: 40%;
- width: 70vw;
- }
- .cw-empty button {
- font-size: 10px;
- padding: 9px;
- }
- .cw-empty small {
- font-size: 9px;
+ font-size: 20px;
}
.cw-bottom-left {
left: 10px;
@@ -2057,6 +1902,7 @@
}
}
.cw-context-menu {
+ position: fixed;
max-height: calc(100vh - 80px);
overflow-y: auto;
}
diff --git a/src/canvas/workspace/WorkspaceModeSwitch.tsx b/src/canvas/workspace/WorkspaceModeSwitch.tsx
new file mode 100644
index 000000000..bb8d061e8
--- /dev/null
+++ b/src/canvas/workspace/WorkspaceModeSwitch.tsx
@@ -0,0 +1,62 @@
+import { createContext, useLayoutEffect, useRef, type PointerEvent, type ReactNode } from "react";
+import { useT } from "../../i18n/I18nProvider";
+import type { WorkspaceMode } from "../workspaceMode";
+
+/** An open modal hosts the same mode choices as the workspace header. */
+export const EditorModeSwitchContext = createContext(null);
+
+export function preserveModeInput(event: PointerEvent) {
+ const input = document.activeElement;
+ if (event.button === 0 && input instanceof HTMLElement &&
+ (input.isContentEditable || input.matches("input, textarea"))) {
+ // Preserve the native caret and selection direction through the layout update.
+ event.preventDefault();
+ }
+}
+
+export function focusAfterModeChange(target?: HTMLElement | null) {
+ const active = document.activeElement;
+ if (!active || active === document.body || active.closest("[inert], [hidden]") ||
+ !active.checkVisibility({ visibilityProperty: true })) {
+ target?.focus({ preventScroll: true });
+ }
+}
+
+export function WorkspaceModeSwitch({
+ mode,
+ onChange,
+}: {
+ mode: WorkspaceMode;
+ onChange: (mode: WorkspaceMode) => void;
+}) {
+ const t = useT();
+ const activatedButton = useRef(null);
+ useLayoutEffect(() => {
+ const button = activatedButton.current;
+ activatedButton.current = null;
+ if (button) focusAfterModeChange(button);
+ }, [mode]);
+ return (
+
+ {(["agent", "canvas"] as const).map((value) => (
+ {
+ if (mode !== value) activatedButton.current = event.currentTarget;
+ onChange(value);
+ }}
+ >
+ {t(`workspaceModes.short.${value}`)}
+
+ ))}
+
+ );
+}
diff --git a/src/canvas/workspace/WorkspacePreview.tsx b/src/canvas/workspace/WorkspacePreview.tsx
new file mode 100644
index 000000000..295a53747
--- /dev/null
+++ b/src/canvas/workspace/WorkspacePreview.tsx
@@ -0,0 +1,77 @@
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import { errorMessage } from "../../backend/api.ts";
+import { creationClient } from "../../backend/creationClient.ts";
+import type { Asset } from "../../contracts/generated.ts";
+import { useT } from "../../i18n/I18nProvider.tsx";
+import { downloadFile, downloadFilename } from "../assets.ts";
+import type { CanvasNode } from "../model.ts";
+import { AssetMedia } from "../useAssetMedia.tsx";
+import { IconButton } from "./workspaceChrome.tsx";
+
+export function WorkspacePreview({ preview, onClose, onDownloadNode }: {
+ preview: CanvasNode | Asset;
+ onClose: () => void;
+ onDownloadNode: (node: CanvasNode) => void;
+}) {
+ const t = useT();
+ const dialog = useRef(null);
+ const isNode = "data" in preview;
+ const asset = isNode ? null : preview;
+ const title = isNode ? preview.data.title : preview.name;
+ const kind = isNode ? preview.type : preview.kind;
+ const [content, setContent] = useState();
+ const [error, setError] = useState("");
+ const [downloadError, setDownloadError] = useState("");
+ useLayoutEffect(() => {
+ const element = dialog.current!;
+ element.showModal();
+ return () => element.close();
+ }, []);
+ useEffect(() => {
+ if (!asset || asset.kind === "file") return;
+ let active = true;
+ const client = creationClient(asset.projectId);
+ const read = asset.kind === "text" ? client.textContent(asset.id) : client.mediaUrl(asset.id);
+ void read.then(value => { if (active) setContent(value); })
+ .catch(reason => { if (active) setError(errorMessage(reason)); });
+ return () => { active = false; };
+ }, [asset]);
+ const download = async () => {
+ if (isNode) return onDownloadNode(preview);
+ setDownloadError("");
+ try {
+ const blob = await creationClient(preview.projectId).blob(preview.id);
+ downloadFile(blob, downloadFilename(preview.name, preview.metadata.mimeType));
+ } catch (reason) {
+ setDownloadError(errorMessage(reason));
+ }
+ };
+ const src = isNode ? preview.data.src : content;
+ const text = isNode ? preview.data.text : content;
+ const unavailable = () => setError(t("errors.preview.unavailable"));
+ let body;
+ if (error) body = {error}
;
+ else if (asset && kind !== "file" && content === undefined)
+ body = {t("errors.preview.loading")}
;
+ else if (kind === "image" && src) body = ;
+ else if (kind === "video" && src) body = ;
+ else if (kind === "audio" && src) body = ;
+ else if (text) body = {text} ;
+ else body = {src || kind === "file" ? t("canvas.workspace.preview.fileHint") : t("canvas.workspace.preview.emptyHint")}
;
+ return (
+ { if (event.target === event.currentTarget) onClose(); }}>
+
+
+ {body}
+ {downloadError &&
{downloadError}
}
+
+
+ );
+}
diff --git a/src/canvas/workspace/WorkspaceView.tsx b/src/canvas/workspace/WorkspaceView.tsx
index b04959e07..79e33f120 100644
--- a/src/canvas/workspace/WorkspaceView.tsx
+++ b/src/canvas/workspace/WorkspaceView.tsx
@@ -1,3 +1,6 @@
+import { EditorModeSwitchContext, WorkspaceModeSwitch, focusAfterModeChange, preserveModeInput } from "./WorkspaceModeSwitch";
+import { WorkspacePreview } from "./WorkspacePreview";
+import { useChatResultLocation } from "./useChatResultLocation";
import type { EditingState } from "../../backend/editSession.ts";
import type { EditSession } from "./EditSession.tsx";
import { projectDisplayName } from "../projectDisplayName";
@@ -13,7 +16,9 @@ import { NodeVersionHistory } from "../NodeVersionHistory";
import openDirectorLogoAnimation from "../../assets/open_director_logo_anim.gif";
import { request as apiRequest, errorMessage, json as apiJson } from "../../backend/api.ts";
-import { creationClient, objectVersion, visibleItems } from "../../backend/creationClient.ts";
+import { projectAssetMetadata } from "../../backend/creationProjection.ts";
+import { creationClient, objectVersion } from "../../backend/creationClient.ts";
+import { showExistingItem } from "../canvasAssetPlacement.ts";
import { previewImageSelection } from "../../backend/imageSelections";
import { MediaPublication } from "../../backend/mediaPublication";
@@ -27,13 +32,11 @@ import { createWorkspaceProject, listWorkspaceProjects, openWorkspaceProject, sa
import { studyImage } from "../assets";
import { ExampleCanvasDialog } from "./example/ExampleCanvasDialog.tsx";
import {
- IMAGE_EXAMPLE_ID,
VIDEO_EXAMPLE_ID,
availableExamples,
loadExampleCatalog,
type ExampleEntry,
} from "./example/exampleCatalog.ts";
-import { exampleFailureText, examplePercent } from "./example/exampleFailure.ts";
import { useExampleImport } from "./example/useExampleImport.ts";
import { AssistantPanel } from "../AssistantPanel";
@@ -89,10 +92,11 @@ import { layoutGroup, orderNodesForCanvas, unstackSelection, type GroupLayout }
import { ProjectSelector } from "../ProjectSelector";
import "../settings.css";
-import { dismissModelSetup } from "../ModelSetup";
+import { dismissModelSetup, needsFirstCanvasSetup } from "../ModelSetup";
+import type { WorkspaceMode } from "../workspaceMode";
import { WelcomeScreen } from "../WelcomeScreen";
-import { firstRunCapabilities } from "../firstRunModels";
+import { firstRunCapabilities, hasFirstCanvasModel } from "../firstRunModels";
import { newNodeGenerationSettings } from "../modelResolution";
import { SettingsDialog } from "../SettingsDialog";
import { alignNodes, type Alignment } from "../snapping";
@@ -113,6 +117,7 @@ import { TooltipButton } from "../TooltipButton";
import { VideoActionEditor } from "../VideoActionEditor";
import { captureVideoEndpoint, extractVideoAudio } from "../videoActionRuntime";
import "../workspace.css";
+import "../workspace-modes.css";
import "../desktop-chrome.css";
import type { WorkspaceRuntime } from "./runtimeTypes.ts";
import { DirectorStage, IconButton, helpShortcuts, nodeKindKeys, nodeTypes, edgeTypes, referenceSideKeys, incomingNodes } from "./workspaceChrome.tsx";
@@ -141,6 +146,11 @@ export function WorkspaceView({ rt, editingState, editSession }: {
addNode,
assetListAnchor,
assistantLayout,
+ assistantVisible,
+ canvasRegion,
+ canvasVisible,
+ workspaceMode,
+ changeWorkspaceMode,
assistantOpen,
assistantSelectionRequest,
backendCatalog,
@@ -347,18 +357,33 @@ export function WorkspaceView({ rt, editingState, editSession }: {
zoomMenu,
} = rt;
+ const canvasEntry = useRef<((ready: boolean) => void) | null>(null);
+ function resolveCanvasEntry(ready: boolean) {
+ canvasEntry.current?.(ready);
+ canvasEntry.current = null;
+ }
+ useEffect(() => () => resolveCanvasEntry(false), [doc.id]);
+ const canvasModelReady = () => backendCatalog.connected && !backendCatalog.loading && hasFirstCanvasModel(backendCatalog.models);
+ function requestCanvasEntry(): boolean | Promise {
+ if (readOnly || !needsFirstCanvasSetup() || canvasModelReady()) return true;
+ if (canvasEntry.current) return false;
+ setSettingsCategory("models");
+ setSettingsModelKind("image");
+ setSettingsOpen(true);
+ return new Promise(resolve => { canvasEntry.current = resolve; });
+ }
+ const viewChatResult = useChatResultLocation(rt, requestCanvasEntry);
- /**
- * Example canvases: one cached catalog feeds both the empty-state buttons and
- * the picker in the project menu.
- */
const [exampleEntries, setExampleEntries] = useState(null);
const [welcomeExampleId, setWelcomeExampleId] = useState(null);
const [firstRunArriving, setFirstRunArriving] = useState(false);
const pendingFirstNodes = useRef<{ projectId: string; selection: string; nodes: CanvasNode[] } | null>(null);
- const finishFirstRun = () => {
+ const finishFirstRun = (mode: WorkspaceMode = "canvas") => {
pendingFirstNodes.current = null;
- dismissModelSetup();
+ dismissModelSetup(mode);
+ changeWorkspaceMode(mode);
+ // On narrow screens, open the canvas pane. The chat layout always shows the conversation.
+ if (assistantLayout.mobile) setAssistantOpen(false);
const url = new URL(window.location.href);
if (url.searchParams.get("setup") === "welcome") {
url.searchParams.delete("setup");
@@ -397,30 +422,6 @@ export function WorkspaceView({ rt, editingState, editSession }: {
setWelcomeExampleId(entry.id);
await welcomeExampleImport.start(entry);
};
- const exampleImport = useExampleImport({ importCanvas: importCanvasArchive });
- const [exampleMissing, setExampleMissing] = useState(false);
- const runExampleButton = async (id: string) => {
- setExampleMissing(false);
- exampleImport.reset(IMAGE_EXAMPLE_ID);
- exampleImport.reset(VIDEO_EXAMPLE_ID);
- const entry = (await loadExamples()).find((item) => item.id === id);
- if (!entry) {
- setExampleMissing(true);
- return;
- }
- // A finished import switches the document, so the bar disappears with it.
- if (await exampleImport.start(entry)) exampleImport.reset(entry.id);
- };
- const exampleButtonStatus =
- exampleImport.statuses[IMAGE_EXAMPLE_ID] ??
- exampleImport.statuses[VIDEO_EXAMPLE_ID];
- const exampleBusy =
- exampleButtonStatus?.phase === "downloading" ||
- exampleButtonStatus?.phase === "importing";
- const exampleProgress = exampleButtonStatus
- ? examplePercent(exampleButtonStatus)
- : null;
-
const outputState = timelineOutput.state;
const outputSource = outputState ? doc.nodes.find((node) => node.id === outputState.itemId) : undefined;
@@ -525,6 +526,7 @@ export function WorkspaceView({ rt, editingState, editSession }: {
}, [doc.id, doc.nodes]);
const desktop = !!window.opendirectorDesktop;
+ const showDesktopNavigation = desktop && workspaceMode === "canvas";
const [desktopSidebarOpen, setDesktopSidebarOpen] = useState(() => {
try { return desktop && localStorage.getItem("opendirector.desktop.sidebar.v1") === "open"; }
catch { return false; }
@@ -609,6 +611,11 @@ export function WorkspaceView({ rt, editingState, editSession }: {
? t("canvas.workspace.loading.switching")
: "";
+ const timelineOpen = editing?.type === "timeline" && editorMode === "default";
+ const modeSwitch = {
+ if (mode !== "canvas" || await requestCanvasEntry()) changeWorkspaceMode(mode);
+ }} />;
+
const canvasItems = creationClient(doc.id).snapshot?.canvasItems;
const selectedGroup = single?.type === "group" ? canvasItems?.find((item) => item.id === single.id) : undefined;
const planNode = selectedGroup?.kind === "group" && selectedGroup.runPlanItemId
@@ -626,16 +633,19 @@ export function WorkspaceView({ rt, editingState, editSession }: {
ref={root}
data-testid="canvas-workspace"
data-edit-mode={readOnly ? "preview" : "edit"}
- data-desktop-sidebar={desktop && desktopSidebarOpen ? "open" : "closed"}
- data-edge-motion={pageVisible}
- data-assistant-open={assistantOpen}
+ data-desktop-sidebar={showDesktopNavigation && desktopSidebarOpen ? "open" : "closed"}
+ data-edge-motion={pageVisible && canvasVisible}
+ data-assistant-open={assistantVisible}
+ data-chat-dock={workspaceMode === "canvas" && !assistantLayout.mobile ? assistantLayout.side : undefined}
+ data-workspace-mode={workspaceMode}
+ data-narrow={assistantLayout.mobile}
+ data-canvas-visible={canvasVisible}
data-assistant-resizing={assistantLayout.dragging}
data-canvas-interacting={interacting}
style={
{
"--assistant-width": `${assistantLayout.width}px`,
- "--assistant-toolbar-offset": `${assistantLayout.toolbarOffset}px`,
- "--assistant-top": assistantLayout.belowHeader ? "78px" : "14px",
+ "--assistant-column-width": `${assistantLayout.columnWidth}px`,
"--cw-selection-padding": `${SELECTION_PADDING / zoom}px`,
} as CSSProperties
}
@@ -732,7 +742,9 @@ export function WorkspaceView({ rt, editingState, editSession }: {
}}
onDrop={(event) => {
if (
- readOnly || event.defaultPrevented ||
+ readOnly || !canvasVisible ||
+ !(event.target as HTMLElement).closest(".cw-canvas-region") ||
+ event.defaultPrevented ||
(event.target as HTMLElement).closest("[role=dialog]")
)
return;
@@ -746,12 +758,196 @@ export function WorkspaceView({ rt, editingState, editSession }: {
}
}}
>
+
+
+
+
+ switchDocument(() => openWorkspaceProject(project))
+ }
+ onCreate={createDesktopProject}
+ onExamples={() => void openExamplePicker()}
+ onRename={renameCurrentProject}
+ onRenameProject={renameProject}
+ onDeleteProject={deleteProject}
+ />
+
+ setLocale("zh-CN")}
+ >
+ {t("common.chinese")}
+
+ |
+ setLocale("en-US")}
+ >
+ {t("common.englishShort")}
+
+
+ {workspaceMode === "canvas" && }
+ {editingState?.mode === "preview" ? <>
+ {t("canvas.workspace.preview.mode")}
+ void editSession.request()}
+ >
+ {t("canvas.workspace.preview.request")}
+
+ {editSession.error && {editSession.error} }
+ > :
+
+ {showDesktopNavigation && desktopSidebarOpen ? saveStatusText : switchingStatus || saveStatusText}
+ }
+ {saveStatus.state === "failed" && (
+
+ void exportDocument()}>
+ {t("canvas.workspace.save.exportCopy")}
+
+ {
+ if (
+ !window.confirm(
+ t("canvas.workspace.save.reloadConfirm"),
+ )
+ )
+ return;
+ void workspaceProjection(doc.id)
+ .open()
+ .then((next) => {
+ installDocument(next);
+ setSaveStatus({ state: "saved" });
+ })
+ .catch((error) => notify(errorMessage(error)));
+ }}
+ >
+ {t("canvas.workspace.save.reload")}
+
+
+ )}
+
+
+
+
+ {
+ if (readOnly) {
+ togglePanel("search");
+ return;
+ }
+ void persist(historyRef.current.present, false).then(
+ (saved) => {
+ if (saved) togglePanel("search");
+ },
+ );
+ }}
+ />
+
+ togglePanel("history")}
+ />
+ importInput.current?.click()}
+ />
+
+ {
+ const file = event.target.files?.[0];
+ event.target.value = "";
+ if (file) void importDocument(file);
+ }}
+ />
+
+ {workspaceMode === "agent" && !assistantLayout.mobile && (
+
{
+ if (!await requestCanvasEntry()) return;
+ assistantLayout.enableFloating();
+ setAssistantOpen(true);
+ changeWorkspaceMode("canvas");
+ requestAnimationFrame(() =>
+ focusAfterModeChange(root.current?.querySelector(".cw-assistant-move-handle")),
+ );
+ }}
+ >
+
+ {t("workspaceModes.floatOnCanvas")}
+
+ )}
+ {workspaceMode === "agent" &&
{ setSettingsCategory("general"); setSettingsOpen(true); }}
+ />}
+ {desktop && window.opendirectorDesktop?.showMore && window.opendirectorDesktop?.showMore?.()} />}
+ {!editing && modeSwitch}
+
+
+ {showDesktopNavigation && setDesktopSidebarOpen(value => !value)}
+ onCreate={createDesktopProject}
+ onDelete={deleteProject}
+ onSelect={project => switchDocument(() => openWorkspaceProject(project))}
+ onSettings={() => setSettingsOpen(true)} />}
+
)}
-
-
-
-
- switchDocument(() => openWorkspaceProject(project))
- }
- onCreate={createDesktopProject}
- onExamples={() => void openExamplePicker()}
- onRename={renameCurrentProject}
- onRenameProject={renameProject}
- onDeleteProject={deleteProject}
- />
-
- setLocale("zh-CN")}
- >
- {t("common.chinese")}
-
- |
- setLocale("en-US")}
- >
- {t("common.englishShort")}
-
-
-
- {editingState?.mode === "preview" ? <>
- {t("canvas.workspace.preview.mode")}
- void editSession.request()}
- >
- {t("canvas.workspace.preview.request")}
-
- {editSession.error && {editSession.error} }
- > :
-
- {desktop && desktopSidebarOpen ? saveStatusText : switchingStatus || saveStatusText}
- }
- {saveStatus.state === "failed" && (
-
- void exportDocument()}>
- {t("canvas.workspace.save.exportCopy")}
-
- {
- if (
- !window.confirm(
- t("canvas.workspace.save.reloadConfirm"),
- )
- )
- return;
- void workspaceProjection(doc.id)
- .open()
- .then((next) => {
- installDocument(next);
- setSaveStatus({ state: "saved" });
- })
- .catch((error) => notify(errorMessage(error)));
- }}
- >
- {t("canvas.workspace.save.reload")}
-
-
- )}
-
-
-
- {
- if (readOnly) {
- togglePanel("search");
- return;
- }
- void persist(historyRef.current.present, false).then(
- (saved) => {
- if (saved) togglePanel("search");
- },
- );
- }}
- />
-
- togglePanel("history")}
- />
- importInput.current?.click()}
- />
-
- {desktop && window.opendirectorDesktop?.showMore && window.opendirectorDesktop?.showMore?.()} />}
- {
- const file = event.target.files?.[0];
- event.target.value = "";
- if (file) void importDocument(file);
- }}
- />
-
-
- {desktop &&
setDesktopSidebarOpen(value => !value)}
- onCreate={createDesktopProject}
- onDelete={deleteProject}
- onSelect={project => switchDocument(() => openWorkspaceProject(project))}
- onSettings={() => setSettingsOpen(true)} />}
({
- name: tool.kind,
- icon: tool.icon,
- label: t(tool.labelKey),
- actionLabel: tool.unavailable
- ? t(tool.labelKey)
- : t("canvas.rail.add", { label: t(tool.labelKey) }),
- shortcut: tool.kind === "text" ? "T" : undefined,
- unavailable: tool.unavailable,
- onClick: tool.unavailable ? undefined : () => addNode(tool.kind),
- })),
- {
- name: "folder",
- icon: "rail-folder",
- label: t("canvas.rail.assets"),
- preserveCollapsedOnFocusRestore: true,
- separatorBefore: true,
- active: libraryOpen,
- onClick: () => setLibraryOpen(true),
- },
- {
- name: "upload",
- icon: "rail-upload",
- label: t("canvas.rail.upload"),
- preserveCollapsedOnFocusRestore: true,
- actionLabel: t("canvas.rail.uploadLocal"),
- shortcut: navigator.platform.includes("Mac")
- ? "Meta+O"
- : "Control+O",
- onClick: () => openFilePicker(),
- },
- ]}
+ menuOpen={Boolean(menu?.trigger)}
+ libraryOpen={libraryOpen}
+ onToggleMenu={(trigger) => {
+ if (menu?.trigger === trigger) {
+ setMenu(null);
+ return;
+ }
+ const { right, top } = trigger.getBoundingClientRect();
+ setMenu({ mode: "create", trigger, x: right, y: top, world: center() });
+ }}
+ onAssets={() => setLibraryOpen(true)}
+ onUpload={() => openFilePicker()}
/>
{!doc.nodes.length && ready && (
-
-
-
-
{t("canvas.workspace.empty.title")}
{t("canvas.workspace.empty.hint")}
-
- {
- setSettingsCategory("models");
- setSettingsOpen(true);
- }}
- >
-
- {t("canvas.workspace.empty.configureModels")}
-
- void runExampleButton(IMAGE_EXAMPLE_ID)}
- >
-
- {t("canvas.workspace.empty.tryImage")}
-
- void runExampleButton(VIDEO_EXAMPLE_ID)}
- >
-
- {t("canvas.workspace.empty.tryVideo")}
-
-
- {exampleBusy && exampleButtonStatus && (
-
-
-
- {exampleButtonStatus.phase === "importing"
- ? t("canvas.example.state.importing")
- : exampleProgress === null
- ? t("canvas.example.state.downloading")
- : t("canvas.example.state.downloadingPercent", {
- percent: exampleProgress,
- })}
-
-
- )}
- {(exampleMissing || exampleButtonStatus?.phase === "failed") && (
-
- {exampleMissing
- ? t("canvas.example.error.unknown")
- : exampleFailureText(t, exampleButtonStatus!)}
-
- )}
-
{t("canvas.workspace.empty.tagline")}
+
void openExamplePicker()}
+ >
+ {t("canvas.workspace.empty.browseExamples")}
+
+
)}
{!ready && {t("canvas.workspace.loading.opening")}
}
@@ -1651,7 +1614,7 @@ export function WorkspaceView({ rt, editingState, editSession }: {
node={single}
locked={readOnly || lockedIds.has(single.id)}
style={{ maxWidth: selectionPresentation.toolbarMaxWidth }}
- onOutput={single.type === "timeline" ? () => void timelineOutput.run(single, () => persist(doc, false)) : undefined}
+ onOutput={!readOnly && single.type === "timeline" ? () => void timelineOutput.run(single, () => persist(doc, false)) : undefined}
outputBusy={timelineOutput.busy || !!(timelineOutput.blockedItemId && timelineOutput.blockedItemId !== single.id)}
onTool={openNodeAction}
presets={toolCatalog.capabilities["image-presets"]?.fields
@@ -1940,7 +1903,7 @@ export function WorkspaceView({ rt, editingState, editSession }: {
>
)}
- {hasToolbar && single?.type === "timeline" && !lockedIds.has(single.id) && (
+ {!readOnly && canvasVisible && hasToolbar && single?.type === "timeline" && !lockedIds.has(single.id) && (
void timelineOutput.run(single, () => persist(doc, false))} />
@@ -2184,6 +2147,7 @@ export function WorkspaceView({ rt, editingState, editSession }: {
x={menu.x}
y={menu.y}
mode={menu.mode ?? "context"}
+ anchor={menu.trigger}
canPaste={Boolean(clipboard.current?.nodes.length)}
canUndo={businessHistory.undo && !historyReplaying}
canRedo={businessHistory.redo && !historyReplaying}
@@ -2336,9 +2300,8 @@ export function WorkspaceView({ rt, editingState, editSession }: {
key={`assets:${doc.id}`}
projectId={doc.id}
anchor={assetListAnchor.current}
- position={center()}
onClose={() => setPanel(null)}
- onLocate={(id) => {
+ actions={{ kind: "canvas", position: center(), onLocate: (id) => {
void workspaceProjection(doc.id)
.read()
.then((next) => {
@@ -2359,7 +2322,7 @@ export function WorkspaceView({ rt, editingState, editSession }: {
);
})
.catch((error) => notify(errorMessage(error)));
- }}
+ } }}
/>
)}
{panel && !(panel === "search") && (
@@ -2585,18 +2548,7 @@ export function WorkspaceView({ rt, editingState, editSession }: {
notify(t("canvas.workspace.toast.configNotVisible"));
return;
}
- if (!visibleItems(client.snapshot).has(id)) {
- const versions = [objectVersion("canvas_item", item)];
- let parentId = item.parentId;
- while (parentId) {
- const parent = client.snapshot.canvasItems.find(
- (item) => item.id === parentId,
- )!;
- versions.push(objectVersion("canvas_item", parent));
- parentId = parent.parentId;
- }
- await client.command("canvas.show", { item }, versions);
- }
+ await showExistingItem(client, item);
const projection = workspaceProjection(doc.id),
snapshot = client.snapshot,
next = await projection.read(snapshot);
@@ -2716,6 +2668,16 @@ export function WorkspaceView({ rt, editingState, editSession }: {
)}
+
+ {workspaceMode === "canvas" && assistantLayout.mobile && assistantOpen && (
+ setAssistantOpen(false)}
+ >
+ {t("workspaceModes.showCanvas")}
+
+ )}
+
{ready && !welcomeOpen && (
selected.includes(node.id))}
- open={assistantOpen}
+ open={assistantVisible}
+ collapsible={workspaceMode === "canvas"}
layout={assistantLayout}
selectionRequest={assistantSelectionRequest}
+ onCreateProjectTimeline={async () => {
+ const node = createNode("timeline", center());
+ await commitCanvasCommand({
+ type: "add-nodes", nodes: [node], titlePrefix: t(nodeKindKeys.timeline),
+ }, t("canvas.workspace.error.timelineUnsaved"));
+ return node.id;
+ }}
+ onOpenProjectTimeline={async (itemId) => {
+ const projectId = doc.id;
+ if (rt.doc.id !== projectId || rt.switchPending.current) return;
+ const snapshot = creationClient(projectId).snapshot;
+ const item = snapshot.canvasItems.find((candidate) => candidate.id === itemId);
+ const editorId = item?.binding.role === "editor" ? item.binding.objectRef.id : undefined;
+ const target = snapshot.editorDocuments.find((candidate) => candidate.id === editorId && candidate.kind === "timeline");
+ if (!target) throw new Error(t("timeline.package.targetMissing"));
+ await rt.openProjectEditor({ kind: "timeline", projectId, itemId, editorId: target.id, revision: target.revision });
+ }}
onClose={() => {
+ if (workspaceMode === "agent") return;
setAssistantOpen(false);
requestAnimationFrame(() =>
root.current
@@ -2738,11 +2719,15 @@ export function WorkspaceView({ rt, editingState, editSession }: {
);
}}
onTurnEnd={() => void syncServiceResults()}
+ onPreviewResult={setPreview}
+ onViewResultOnCanvas={viewChatResult}
+ onEditResult={rt.openProjectEditor}
onModelSelections={setAssistantModels}
onAgentModel={onAgentModel}
onPrepareReferences={() => persist(historyRef.current.present)}
- onOpenSettings={() => {
+ onOpenSettings={(kind) => {
setSettingsCategory("models");
+ setSettingsModelKind(kind ?? null);
setSettingsOpen(true);
}}
/>
@@ -2801,44 +2786,10 @@ export function WorkspaceView({ rt, editingState, editSession }: {
/>
)}
{preview && (
- setPreview(null)}
- >
-
- {preview.data.title}
- downloadNode(preview)}
- />
- setPreview(null)}
- />
-
-
e.stopPropagation()}>
- {preview.type === "image" && preview.data.src ? (
-
- ) : preview.type === "video" && preview.data.src ? (
-
- ) : preview.type === "audio" && preview.data.src ? (
-
- ) : (
-
- {preview.data.text ||
- (preview.data.src
- ? t("canvas.workspace.preview.fileHint")
- : t("canvas.workspace.preview.emptyHint"))}
-
- )}
-
-
+ setPreview(null)} />
)}
- {editing && editorMode === "default" && editing.type === "timeline" && (
+ {timelineOpen && (
node.id === editing.id)}
@@ -2857,6 +2808,8 @@ export function WorkspaceView({ rt, editingState, editSession }: {
setEditing(node);
}
}}
+ projectResources={creationClient(doc.id).snapshot.assets.map((asset) => projectAssetMetadata(asset))}
+ onReadProjectMedia={(assetId, signal) => creationClient(doc.id).mediaUrl(assetId, { signal })}
resources={[
...resources,
...doc.nodes
@@ -3168,6 +3121,7 @@ export function WorkspaceView({ rt, editingState, editSession }: {
{welcomeOpen && !readOnly && {
@@ -3215,7 +3169,17 @@ export function WorkspaceView({ rt, editingState, editSession }: {
theme={theme}
initialCategory={settingsCategory}
initialModelKind={settingsModelKind}
+ canvasEntry={canvasEntry.current ? {
+ ready: canvasModelReady(),
+ onContinue: () => {
+ if (!canvasModelReady()) return;
+ setSettingsOpen(false);
+ setSettingsModelKind(null);
+ resolveCanvasEntry(true);
+ },
+ } : undefined}
onClose={() => {
+ resolveCanvasEntry(false);
setSettingsModelKind(null);
setSettingsOpen(false);
}}
@@ -3264,7 +3228,7 @@ export function WorkspaceView({ rt, editingState, editSession }: {
);
return (
<>
- {workspace}
+ {workspace}
{subjectImport && (
;
*/
export interface WorkspaceRuntime extends WorkspaceState, WorkspaceSetters {
doc: CanvasDocument;
+ openProjectEditor: (target: ProjectEditorTarget, signal?: AbortSignal) => Promise;
single: CanvasNode | null;
composerNode: CanvasNode | undefined;
textWindowNode: CanvasNode | undefined;
@@ -99,6 +102,11 @@ export interface WorkspaceRuntime extends WorkspaceState, WorkspaceSetters {
>;
selectionAtPointerDown: RefObject;
root: RefObject;
+ canvasRegion: RefObject;
+ workspaceMode: WorkspaceMode;
+ changeWorkspaceMode: (mode: WorkspaceMode) => boolean;
+ assistantVisible: boolean;
+ canvasVisible: boolean;
composerElement: RefObject;
toolbarElement: RefObject;
fileInput: RefObject;
diff --git a/src/canvas/workspace/state.ts b/src/canvas/workspace/state.ts
index dc181ba07..4ad304506 100644
--- a/src/canvas/workspace/state.ts
+++ b/src/canvas/workspace/state.ts
@@ -7,6 +7,7 @@ import {
type SetStateAction,
} from "react";
import type { ModelSelections } from "../../backend/chat.ts";
+import type { Asset } from "../../contracts/generated.ts";
import type { ActiveGeneration } from "../generationActivity.ts";
import { createHistory, type CanvasHistory } from "../history.ts";
import type { ResultSource } from "../linkedResults.ts";
@@ -21,6 +22,7 @@ export type WorkspacePanel = "assets" | "search" | "history" | null;
export type WorkspaceMenu = {
mode?: "create" | "context";
+ trigger?: HTMLButtonElement;
x: number;
y: number;
world: Point;
@@ -110,7 +112,7 @@ export type WorkspaceState = {
showEdges: boolean;
menu: WorkspaceMenu | null;
saveStatus: WorkspaceSaveStatus;
- preview: CanvasNode | null;
+ preview: CanvasNode | Asset | null;
editing: CanvasNode | null;
editorMode: WorkspaceEditorMode;
actionSession: WorkspaceActionSession | null;
@@ -256,7 +258,7 @@ export function createWorkspaceState(): WorkspaceState {
welcomeOpen: false,
activeGenerations: [],
arrivingNodes: new Set(),
- assistantOpen: false,
+ assistantOpen: true,
assistantSelectionRequest: 0,
presentationFocus: 0,
zoom: 1,
diff --git a/src/canvas/workspace/useChatResultLocation.ts b/src/canvas/workspace/useChatResultLocation.ts
new file mode 100644
index 000000000..64b5bff08
--- /dev/null
+++ b/src/canvas/workspace/useChatResultLocation.ts
@@ -0,0 +1,68 @@
+import { useEffect, useRef, useState } from "react";
+import { getEditingState } from "../../backend/editSession.ts";
+import type { Asset } from "../../contracts/generated.ts";
+import { creationClient, currentAsset, visibleItems } from "../../backend/creationClient.ts";
+import { findAssetItem, showExistingItem, showNewAssetItem } from "../canvasAssetPlacement.ts";
+import type { WorkspaceRuntime } from "./runtimeTypes.ts";
+
+export function useChatResultLocation(rt: WorkspaceRuntime, requestCanvasEntry: () => boolean | Promise) {
+ const [destination, setDestination] = useState<{ projectId: string; itemId: string; assetId: string } | null>(null);
+ const queue = useRef(Promise.resolve());
+ const { doc, canvasVisible, workspaceMode } = rt;
+
+ // The ordinary mode switch preserves the viewport. Apply explicit focus only
+ // after the canvas and the acknowledged display item have both been rendered.
+ useEffect(() => {
+ if (!destination) return;
+ if (doc.id !== destination.projectId || !canvasVisible) {
+ setDestination(null);
+ return;
+ }
+ const snapshot = creationClient(doc.id).snapshot;
+ const item = snapshot.canvasItems.find(candidate => candidate.id === destination.itemId);
+ if (!item || currentAsset(snapshot, item)?.id !== destination.assetId || !visibleItems(snapshot).has(item.id)) {
+ rt.notify(rt.t("canvasNodes.assets.versionChanged"));
+ setDestination(null);
+ return;
+ }
+ const node = doc.nodes.find(candidate => candidate.id === item.id);
+ if (!node) return;
+ rt.selectAndFocus(node);
+ rt.root.current?.focus({ preventScroll: true });
+ setDestination(null);
+ }, [rt, destination, doc, canvasVisible]);
+
+ const locate = async (asset: Asset, preferredId?: string | null) => {
+ const active = () => rt.mounted.current && !rt.switchPending.current &&
+ rt.doc.id === asset.projectId && rt.workspaceMode === workspaceMode;
+ if (!active() || !await requestCanvasEntry() || !active()) return;
+ const client = creationClient(asset.projectId);
+ await rt.saveQueue.current?.wait();
+ if (!active()) return;
+ const snapshot = await client.refresh();
+ if (!active()) return;
+ const saved = snapshot.assets.find(candidate => candidate.id === asset.id);
+ if (!saved) throw new Error(rt.t("canvas.workspace.error.assetMissing"));
+ if (saved.revision !== asset.revision || saved.fingerprint !== asset.fingerprint)
+ throw new Error(rt.t("canvasNodes.assets.versionChanged"));
+
+ const item = findAssetItem(snapshot, saved.id, preferredId);
+ // A handoff or a remote hide may have occurred while refreshing the snapshot.
+ if (getEditingState(asset.projectId)?.mode === "preview" && (!item || !visibleItems(snapshot).has(item.id)))
+ throw new Error(rt.t("canvas.workspace.preview.mode"));
+ // Showing an unadopted candidate creates a material binding to this version.
+ const itemId = item ? await showExistingItem(client, item)
+ : await showNewAssetItem(client, saved, rt.center());
+ if (!active()) return;
+ rt.setPanel(null);
+ rt.changeWorkspaceMode("canvas");
+ if (rt.assistantLayout.mobile) rt.setAssistantOpen(false);
+ setDestination({ projectId: saved.projectId, assetId: saved.id, itemId });
+ };
+
+ return (asset: Asset, preferredId?: string | null) => {
+ const next = queue.current.then(() => locate(asset, preferredId));
+ queue.current = next.catch(() => {});
+ return next;
+ };
+}
diff --git a/src/canvas/workspace/useWorkspaceChrome.ts b/src/canvas/workspace/useWorkspaceChrome.ts
index 1d0b70773..00265223d 100644
--- a/src/canvas/workspace/useWorkspaceChrome.ts
+++ b/src/canvas/workspace/useWorkspaceChrome.ts
@@ -24,6 +24,7 @@ export function useWorkspaceChrome(rt: WorkspaceRuntime) {
setWelcomeOpen,
setupChecked,
switching,
+ workspaceMode,
} = rt;
useEffect(() => {
@@ -33,7 +34,8 @@ export function useWorkspaceChrome(rt: WorkspaceRuntime) {
if (preview === "models") {
setSettingsCategory("models");
setSettingsOpen(true);
- } else if (preview === "welcome" || shouldShowModelSetup()) {
+ }
+ if (preview === "welcome" || shouldShowModelSetup()) {
setWelcomeOpen(true);
}
}, [ready, setupChecked, setSettingsCategory, setSettingsOpen, setWelcomeOpen]);
@@ -44,7 +46,11 @@ export function useWorkspaceChrome(rt: WorkspaceRuntime) {
const assistantReturnFocus = useRef(null);
const toggleAssistantShortcut = useRef(() => {});
toggleAssistantShortcut.current = () => {
- if (!ready || switching || document.querySelector("dialog[open], .cw-modal-backdrop")) return;
+ if (!ready || switching || document.querySelector('dialog[open], .cw-modal-backdrop, [aria-modal="true"]')) return;
+ if (workspaceMode === "agent") {
+ root.current?.querySelector(".cw-assistant-composer [contenteditable=true]")?.focus({ preventScroll: true });
+ return;
+ }
if (assistantOpen) {
setAssistantOpen(false);
const target = assistantReturnFocus.current;
@@ -91,6 +97,7 @@ export function useWorkspaceChrome(rt: WorkspaceRuntime) {
?.focus({ preventScroll: true });
}
const close = (event: PointerEvent) => {
+ if (event.target instanceof Node && menu.trigger?.contains(event.target)) return;
if (
!(event.target instanceof Element) ||
!event.target.closest(".cw-context-menu")
diff --git a/src/canvas/workspace/useWorkspaceDocument.ts b/src/canvas/workspace/useWorkspaceDocument.ts
index e5aa18ac8..0556172b6 100644
--- a/src/canvas/workspace/useWorkspaceDocument.ts
+++ b/src/canvas/workspace/useWorkspaceDocument.ts
@@ -2,6 +2,7 @@
import { pinnedReferenceAssets } from "../pinnedReferenceAssets.ts";
import { SaveQueue } from "../saveQueue.ts";
import { useCallback, useEffect, useRef } from "react";
+import { flushSync } from "react-dom";
import { errorMessage } from "../../backend/api.ts";
import { creationClient, CreationCommandError, itemSpec } from "../../backend/creationClient.ts";
import { fingerprint } from "../../backend/generation.ts";
@@ -50,7 +51,6 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime, readOnly: boolean) {
saveQueue,
setActionSession,
setArrivingNodes,
- setAssistantOpen,
setAssistantSelectionRequest,
setBusinessHistory,
setComposerNodeId,
@@ -246,7 +246,9 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime, readOnly: boolean) {
invalidateScheduledAutosave();
if (!(await persist(next, false))) throw new Error(saveError.current || failureMessage);
if (historyRef.current.present.id !== next.id) throw new Error(failureMessage);
- command(value);
+ // A caller may open an editor immediately and flush the current document.
+ // Publish the acknowledged command before that caller can read the old one.
+ flushSync(() => command(value));
};
const replayHistory = (forward = false) => {
@@ -301,7 +303,6 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime, readOnly: boolean) {
flowSurface.current?.cancel();
setSelectedEdges([]);
setPanel(null);
- setAssistantOpen(false);
setAssistantSelectionRequest(0);
setMenu(null);
setRename(null);
diff --git a/src/canvas/workspace/useWorkspaceEditor.ts b/src/canvas/workspace/useWorkspaceEditor.ts
index 37c20a4d8..e91f2aadb 100644
--- a/src/canvas/workspace/useWorkspaceEditor.ts
+++ b/src/canvas/workspace/useWorkspaceEditor.ts
@@ -1,13 +1,17 @@
-import { useEffect, useMemo } from "react";
+import { useEffect, useMemo, useRef } from "react";
import { currentAsset } from "../../backend/creationClient";
import { creationClient } from "../../backend/creationClient.ts";
+import { getEditingState } from "../../backend/editSession.ts";
+import { CreationProjection } from "../../backend/creationProjection";
import { CreationEditorSession } from "../../backend/creationEditorSession";
import { MediaPublication } from "../../backend/mediaPublication";
import { backendModel } from "../../backend/rules.ts";
import { workspaceProjection } from "../../backend/workspace";
+import { prepareProjectEditorItem, resolveProjectEditorItem, type ProjectEditorTarget } from "../assistantResultEditors.ts";
+import type { CanvasItem, ProjectSnapshot } from "../../contracts/generated.ts";
import { lockedNodeIds } from "../hierarchy";
import { captureEditorSource, validateNodeActionSource, type LinkedMediaResult, type ResultSource } from "../linkedResults";
import { type CanvasDocument, type CanvasNode, type CanvasNodeData } from "../model";
@@ -80,6 +84,18 @@ export function useWorkspaceEditor(rt: WorkspaceRuntime, readOnly: boolean) {
}),
[doc.nodes],
);
+ const showEditor = (document: CanvasDocument, node: CanvasNode, mode: EditorMode, basis?: ProjectSnapshot, unplaced?: CanvasItem) => {
+ editorSession.current = ["image", "timeline", "stack", "tool", "external"].includes(node.type)
+ ? new CreationEditorSession(creationClient(document.id), document, node.id, basis, unplaced) : null;
+ const source = captureEditorSource(document.id, node);
+ editorOrigin.current = source;
+ if (basis && (node.type === "video" || node.type === "audio"))
+ mediaPublications.current.set(source, new MediaPublication(creationClient(document.id), basis, node.id, unplaced));
+ setActionSession(null);
+ setEditorMode(mode);
+ setEditing(node);
+ setMenu(null);
+ };
const openEditor = async (node: CanvasNode, mode: EditorMode = "default") => {
if (node.type === "text" && node.data.backendAssetId && node.data.assetState !== "ready") return;
if (readOnly) {
@@ -101,7 +117,6 @@ export function useWorkspaceEditor(rt: WorkspaceRuntime, readOnly: boolean) {
return;
}
const projectId = historyRef.current.present.id;
- editorSession.current = null;
if (
["image", "timeline", "stack", "tool", "external"].includes(node.type)
) {
@@ -118,18 +133,50 @@ export function useWorkspaceEditor(rt: WorkspaceRuntime, readOnly: boolean) {
if (current.id !== projectId) return;
node = current.nodes.find((item) => item.id === node.id)!;
if (!node || lockedNodeIds(current.nodes).has(node.id)) return;
- editorSession.current = new CreationEditorSession(
- creationClient(projectId),
- current,
- node.id,
- );
}
- editorOrigin.current = captureEditorSource(projectId, node);
- setActionSession(null);
- setEditorMode(mode);
- setEditing(node);
- setMenu(null);
+ showEditor(historyRef.current.present, node, mode);
};
+
+ // Cards and the project menu can target items outside the visible projection.
+ // Hydrate the exact acknowledged item, without installing another workspace.
+ const openingProjectEditor = useRef(false);
+ const openProjectEditor = async (target: ProjectEditorTarget, signal?: AbortSignal) => {
+ const projectId = target.kind === "media" ? target.asset.projectId : target.projectId;
+ const active = () => rt.mounted.current && !signal?.aborted && !rt.switchPending.current
+ && rt.doc.id === projectId && getEditingState(projectId)?.mode !== "preview" && !rt.editing;
+ if (!active() || openingProjectEditor.current) throw new Error(t("canvas.workspace.error.editorUnavailable"));
+ openingProjectEditor.current = true;
+ try {
+ if (!(await persistCurrentDocument(() => historyRef.current.present, persist)))
+ throw new Error(t("canvas.workspace.toast.editorUnsaved"));
+ if (!active()) return;
+ const client = creationClient(projectId);
+ await client.refresh();
+ if (!active()) return;
+ const { itemId, unplaced } = await prepareProjectEditorItem(client, target, rt.center);
+ if (!active()) return;
+ const snapshot = client.snapshot;
+ const source = unplaced ? target : { ...target, itemId };
+ const bound = resolveProjectEditorItem(snapshot, source, unplaced?.id);
+ const basis = unplaced ? {
+ ...snapshot, canvasItems: [...snapshot.canvasItems.filter(item => item.id !== unplaced.id), unplaced],
+ } : snapshot;
+ // Only this modal sees the provisional item. The workspace keeps the real projection.
+ const projection = unplaced ? new CreationProjection(client) : workspaceProjection(projectId);
+ const document = await projection.read(basis);
+ if (!active()) return;
+ const latest = resolveProjectEditorItem(client.snapshot, source, unplaced?.id);
+ if ((!unplaced && !latest) || bound?.revision !== latest?.revision)
+ throw new Error(t("assistant.result.editorChanged"));
+ const node = document.nodes.find(candidate => candidate.id === itemId)
+ ?? document.hiddenNodes?.find(candidate => candidate.id === itemId);
+ if (!node) throw new Error(t("canvas.workspace.error.editorUnavailable"));
+ showEditor(document, node, node.type === "audio" || node.type === "video" ? "trim" : "default", basis, unplaced);
+ } finally {
+ openingProjectEditor.current = false;
+ }
+ };
+
const closeEditor = () => {
if (editorSaving.current) return;
setEditing(null);
@@ -171,7 +218,8 @@ export function useWorkspaceEditor(rt: WorkspaceRuntime, readOnly: boolean) {
projection.baseline = merged;
projection.basis = snapshot;
setHistory((history) => ({ ...history, present: merged }));
- const node = merged.nodes.find((item) => item.id === session.itemId);
+ const node = merged.nodes.find((item) => item.id === session.itemId)
+ ?? merged.hiddenNodes?.find((item) => item.id === session.itemId);
if (node) editorOrigin.current = captureEditorSource(projectId, node);
}
notify(t("canvas.workspace.toast.editorSaved"));
@@ -387,6 +435,7 @@ export function useWorkspaceEditor(rt: WorkspaceRuntime, readOnly: boolean) {
};
rt.resources = resources;
rt.openEditor = openEditor;
+ rt.openProjectEditor = openProjectEditor;
rt.closeEditor = closeEditor;
rt.commitEditorData = commitEditorData;
rt.addLinkedOutputs = addLinkedOutputs;
diff --git a/src/canvas/workspace/useWorkspaceInteraction.tsx b/src/canvas/workspace/useWorkspaceInteraction.tsx
index 540d3328d..ca494c1f5 100644
--- a/src/canvas/workspace/useWorkspaceInteraction.tsx
+++ b/src/canvas/workspace/useWorkspaceInteraction.tsx
@@ -37,6 +37,9 @@ export function useWorkspaceInteraction(rt: WorkspaceRuntime, readOnly: boolean)
arrivingNodes,
assistantLayout,
assistantOpen,
+ canvasRegion,
+ canvasVisible,
+ workspaceMode,
begin,
bypassSnapping,
cancelResultImport,
@@ -601,7 +604,7 @@ export function useWorkspaceInteraction(rt: WorkspaceRuntime, readOnly: boolean)
}
: mediaBounds;
const selectionPresentation = useSelectionPresentation({
- root,
+ root: canvasRegion,
toolbar: toolbarElement,
composer: composerElement,
// Generators are screen-space UI, like the toolbar and sidebar. Only their
@@ -614,6 +617,7 @@ export function useWorkspaceInteraction(rt: WorkspaceRuntime, readOnly: boolean)
panel,
focusRequest: presentationFocus,
blocked:
+ !canvasVisible ||
composerExpanded ||
interacting ||
references.connecting ||
@@ -621,9 +625,11 @@ export function useWorkspaceInteraction(rt: WorkspaceRuntime, readOnly: boolean)
pointerGesture.current.moved ||
!selectionControls,
controlsKey: `${assistantOpen}:${assistantLayout.width}:${hasComposer}:${hasToolbar}:${composerExpanded}:${activeAction?.token ?? ""}:${activeAction?.tool === "outpaint" ? JSON.stringify(presentationBounds) : ""}`,
+ preserveViewportKey: `${workspaceMode}:${canvasVisible}:${assistantOpen}:${assistantLayout.floating}:${assistantLayout.preferredWidth}:${assistantLayout.side}`,
+ workspaceSize: assistantLayout.surface,
});
revealCreatedNodes.current = (nodes, allNodes) => {
- if (switchPending.current || viewportMoving.current || interacting || pointerGesture.current.active ||
+ if (!canvasVisible || switchPending.current || viewportMoving.current || interacting || pointerGesture.current.active ||
references.connecting || spacePressed || selectedRef.current.length > 1 ||
editing || preview || activeAction || textEditingId || composerExpanded) return;
const focused = document.activeElement;
@@ -632,7 +638,7 @@ export function useWorkspaceInteraction(rt: WorkspaceRuntime, readOnly: boolean)
const bounds = boundsOfNodes(nodes, allNodes);
if (bounds) selectionPresentation.reveal(bounds);
};
- useCanvasWheelBoundary(root, selectionPresentation.userNavigation);
+ useCanvasWheelBoundary(canvasRegion, selectionPresentation.userNavigation, canvasVisible);
const managedRunIds = useMemo(
() => new Set(doc.nodes.filter((node) => node.autoLayout).map((node) => node.id)),
[doc.nodes],
@@ -785,7 +791,7 @@ export function useWorkspaceInteraction(rt: WorkspaceRuntime, readOnly: boolean)
const onWorkspaceKey = (event: React.KeyboardEvent) => {
const el = event.target as HTMLElement;
- if (el.closest("dialog[open]")) return;
+ if (!canvasVisible || el.closest("dialog[open]")) return;
bypassSnapping.current = event.metaKey || event.ctrlKey;
if (bypassSnapping.current) clearGuides();
if (!ready || switchPending.current || event.nativeEvent.isComposing) return;
@@ -817,7 +823,7 @@ export function useWorkspaceInteraction(rt: WorkspaceRuntime, readOnly: boolean)
// These components own their keyboard shortcuts and cancellation lifecycle.
if (
el.closest(
- ".od-desktop-navigation,.cw-composer-dock,.cw-composer-popover,.cw-text-window-backdrop,.cw-node-toolbar-anchor,.cw-domain-dialog,.cw-selection-menu,.cw-action-media-host,.cw-project-selector,.cw-project-dialog,.cw-settings-dialog,.cw-assistant-panel,.cw-context-menu,.cw-node-title-input,.cw-subject-description",
+ ".od-desktop-navigation,.cw-composer-dock,.cw-composer-popover,.cw-text-window-backdrop,.cw-node-toolbar-anchor,.cw-domain-dialog,.cw-preview,.cw-selection-menu,.cw-action-media-host,.cw-project-selector,.cw-project-dialog,.cw-settings-dialog,.cw-assistant-panel,.cw-context-menu,.cw-node-title-input,.cw-subject-description",
)
)
return;
diff --git a/src/canvas/workspace/useWorkspaceRuntime.ts b/src/canvas/workspace/useWorkspaceRuntime.ts
index b223eb3c5..4a0843842 100644
--- a/src/canvas/workspace/useWorkspaceRuntime.ts
+++ b/src/canvas/workspace/useWorkspaceRuntime.ts
@@ -1,7 +1,9 @@
import { SaveQueue } from "../saveQueue.ts";
import { useKeyPress, useReactFlow, type Edge } from "@xyflow/react";
-import { useEffect, useMemo, useRef } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { readWorkspaceMode, saveWorkspaceMode, type WorkspaceMode } from "../workspaceMode";
+import { dismissModelSetup, needsFirstCanvasSetup } from "../ModelSetup";
import { useNodeVersionCounts } from "../NodeVersionHistory";
import { CreationEditorSession } from "../../backend/creationEditorSession";
@@ -117,6 +119,24 @@ export function useWorkspaceRuntime(): WorkspaceRuntime {
}
})();
const { notifications, notify, dismiss } = useCanvasNotifications();
+ const [workspaceMode, setWorkspaceMode] = useState(() => needsFirstCanvasSetup() ? "agent" : readWorkspaceMode());
+ const preferenceWarningShown = useRef(false);
+ const changeWorkspaceMode = (mode: WorkspaceMode) => {
+ if (mode !== workspaceMode) {
+ pointerGesture.current.cancel();
+ flowSurface.current?.cancel();
+ runtime.references?.cancel();
+ runtime.setMenu(null);
+ setWorkspaceMode(mode);
+ }
+ if (mode === "canvas" && needsFirstCanvasSetup()) dismissModelSetup("canvas");
+ const saved = saveWorkspaceMode(mode);
+ if (!saved && !preferenceWarningShown.current) {
+ preferenceWarningShown.current = true;
+ notify(t("workspaceModes.preferenceFailed"));
+ }
+ return saved;
+ };
const editorOrigin = useRef(null);
const mediaPublications = useRef(
new WeakMap(),
@@ -206,6 +226,7 @@ export function useWorkspaceRuntime(): WorkspaceRuntime {
} | null>(null);
const referenceTarget = useRef(null);
const root = useRef(null);
+ const canvasRegion = useRef(null);
const assistantLayout = useAssistantLayout(root, assistantOpen, () => {
setAssistantOpen(false);
requestAnimationFrame(() =>
@@ -213,7 +234,9 @@ export function useWorkspaceRuntime(): WorkspaceRuntime {
?.querySelector(".cw-chat-button")
?.focus(),
);
- });
+ }, workspaceMode);
+ const assistantVisible = workspaceMode === "agent" || assistantOpen;
+ const canvasVisible = workspaceMode === "canvas" && (!assistantLayout.mobile || !assistantOpen);
const toolbarElement = useRef(null);
const composerElement = useRef(null);
const focusSelection = (id: string) => {
@@ -260,11 +283,13 @@ export function useWorkspaceRuntime(): WorkspaceRuntime {
[backendCatalog.models],
);
- const center = (): Point =>
- flow.screenToFlowPosition({
- x: window.innerWidth / 2 - (panel ? 150 : 0),
- y: window.innerHeight * 0.32,
+ const center = (): Point => {
+ const bounds = canvasRegion.current?.getBoundingClientRect();
+ return flow.screenToFlowPosition({
+ x: (bounds?.left ?? 0) + (bounds?.width ?? window.innerWidth) / 2 - (panel ? 150 : 0),
+ y: (bounds?.top ?? 0) + (bounds?.height ?? window.innerHeight) * 0.32,
});
+ };
// A node freezes the dialog's model at creation. Changing the picker later
// must not rewrite a model the viewer already has on the canvas, so this is
// the only place the assistant selection is read.
@@ -354,6 +379,11 @@ export function useWorkspaceRuntime(): WorkspaceRuntime {
runtime.uploadSource = uploadSource;
runtime.referenceTarget = referenceTarget;
runtime.root = root;
+ runtime.canvasRegion = canvasRegion;
+ runtime.workspaceMode = workspaceMode;
+ runtime.changeWorkspaceMode = changeWorkspaceMode;
+ runtime.assistantVisible = assistantVisible;
+ runtime.canvasVisible = canvasVisible;
runtime.assistantLayout = assistantLayout;
runtime.toolbarElement = toolbarElement;
runtime.composerElement = composerElement;
diff --git a/src/canvas/workspace/useWorkspaceTransfer.ts b/src/canvas/workspace/useWorkspaceTransfer.ts
index 94c83ff89..d43980f85 100644
--- a/src/canvas/workspace/useWorkspaceTransfer.ts
+++ b/src/canvas/workspace/useWorkspaceTransfer.ts
@@ -917,7 +917,7 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) {
};
useEffect(() => {
const onPaste = (event: ClipboardEvent) => {
- if (readOnly || event.defaultPrevented || !ready || switchPending.current) return;
+ if (readOnly || !rt.canvasVisible || event.defaultPrevented || !ready || switchPending.current) return;
const target = event.target;
if (!(target instanceof HTMLElement)) return;
if (
diff --git a/src/canvas/workspaceMode.ts b/src/canvas/workspaceMode.ts
new file mode 100644
index 000000000..ec6499691
--- /dev/null
+++ b/src/canvas/workspaceMode.ts
@@ -0,0 +1,29 @@
+export type WorkspaceMode = "agent" | "canvas";
+
+export const WORKSPACE_MODE_KEY = "opendirector.workspaceMode.v1";
+
+/** A browser preference: never part of project content or undo history. */
+export function readWorkspaceMode(
+ storage?: Pick,
+): WorkspaceMode {
+ try {
+ return (storage ?? window.localStorage).getItem(WORKSPACE_MODE_KEY) === "agent"
+ ? "agent"
+ : "canvas";
+ } catch {
+ return "canvas";
+ }
+}
+
+/** Report preference failures separately from successful in-memory switching. */
+export function saveWorkspaceMode(
+ mode: WorkspaceMode,
+ storage?: Pick,
+): boolean {
+ try {
+ (storage ?? window.localStorage).setItem(WORKSPACE_MODE_KEY, mode);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/i18n/messages/en-US/assistant.ts b/src/i18n/messages/en-US/assistant.ts
index d49944397..2fe513f6c 100644
--- a/src/i18n/messages/en-US/assistant.ts
+++ b/src/i18n/messages/en-US/assistant.ts
@@ -76,6 +76,10 @@ export const assistant = {
"assistant.panel.pendingDisabled": "The input is unavailable right now. Please wait.",
"assistant.panel.pendingHint": "Click the message to insert; click outside or press Esc to cancel",
"assistant.panel.resize": "Resize AI chat",
+ "assistant.panel.float": "Float chat",
+ "assistant.panel.dockRight": "Dock chat to the right",
+ "assistant.panel.dock": "Dock chat to the left",
+ "assistant.panel.moveHint": "Drag to move chat, or use the arrow keys. Hold Shift to move farther.",
"assistant.panel.resizeValue": "{width} pixels; shrink to 200 pixels to collapse",
"assistant.panel.resizeHint": "Drag to resize; double-click to restore the default width",
@@ -108,6 +112,22 @@ export const assistant = {
},
"assistant.reply.arguments": "Call arguments",
"assistant.reply.result": "Result",
+ "assistant.result.editorChanged": "The project changed while the editor was opening. Check the result and try again.",
+ "assistant.result.editMedia": "Edit media",
+ "assistant.result.syncingTimeline": "Loading the timeline from the project…",
+ "assistant.result.timelineVersion": "Delivered revision {revision}",
+ "assistant.result.openTimelineVersion": "Open current timeline (revision {revision})",
+ "assistant.result.openTimeline": "Open timeline",
+ "assistant.result.timeline": "Timeline",
+ "assistant.result.timelineChanged": "The timeline has changed. Check the updated timeline before opening it.",
+ "assistant.result.preview": "Preview",
+ "assistant.result.reference": "Reference in chat",
+ "assistant.result.viewOnCanvas": "View on canvas",
+ "assistant.result.current": "Currently used",
+ "assistant.result.candidate": "Candidate",
+ "assistant.result.historical": "Earlier version",
+ "assistant.result.unavailable": "This result asset is unavailable",
+ "assistant.result.locateFailed": "Could not show this result on the canvas.",
"assistant.reply.truncated": " (truncated)",
"assistant.reply.truncatedDetail":
"Only the first 65,536 characters are shown here; the full result is in this turn's trace.",
diff --git a/src/i18n/messages/en-US/canvas.ts b/src/i18n/messages/en-US/canvas.ts
index 58e2f5659..8fb622281 100644
--- a/src/i18n/messages/en-US/canvas.ts
+++ b/src/i18n/messages/en-US/canvas.ts
@@ -24,7 +24,7 @@ export const canvas = {
"canvas.menu.redo": "Redo",
"canvas.menu.undo": "Undo",
"canvas.rail.tools": "Canvas creation tools",
- "canvas.rail.add": "Add {label}",
+ "canvas.rail.addNode": "Add node",
"canvas.rail.assets": "Asset library",
"canvas.rail.upload": "Upload",
"canvas.rail.uploadLocal": "Upload local asset",
diff --git a/src/i18n/messages/en-US/canvasWorkspace.ts b/src/i18n/messages/en-US/canvasWorkspace.ts
index 76e6f1b54..ccbd340ca 100644
--- a/src/i18n/messages/en-US/canvasWorkspace.ts
+++ b/src/i18n/messages/en-US/canvasWorkspace.ts
@@ -85,12 +85,10 @@ export const canvasWorkspace = {
"canvas.workspace.toolbar.help": "Help",
"canvas.workspace.toolbar.chat": "Chat with AI",
- "canvas.workspace.empty.title": "Your story, directed by you",
+ "canvas.workspace.empty.title": "Empty canvas",
"canvas.workspace.empty.hint":
- "Double-click the canvas to create a node, or drop in your assets",
- "canvas.workspace.empty.configureModels": "Configure models",
- "canvas.workspace.empty.tagline":
- "Reference connections · Free arrangement · Autosaved locally",
+ "Choose Add node on the left, or drag your files onto the canvas.",
+ "canvas.workspace.empty.browseExamples": "Browse example canvases",
"canvas.workspace.loading.opening": "Opening canvas…",
"canvas.workspace.loading.switching": "Switching canvas…",
@@ -481,6 +479,4 @@ export const canvasWorkspace = {
"canvas.example.state.downloadingPercent": "Downloading… {percent}%",
"canvas.example.progress.label": "Download progress",
// The empty canvas imports the two hosted samples directly.
- "canvas.workspace.empty.tryImage": "Try image example",
- "canvas.workspace.empty.tryVideo": "Try video example",
} as const;
diff --git a/src/i18n/messages/en-US/firstRun.ts b/src/i18n/messages/en-US/firstRun.ts
index a4e280eda..e953974d5 100644
--- a/src/i18n/messages/en-US/firstRun.ts
+++ b/src/i18n/messages/en-US/firstRun.ts
@@ -1,6 +1,12 @@
export const firstRun = {
"firstRun.welcomeTitle": "Welcome to OpenDirector",
"firstRun.welcomeIntro": "Make videos with AI, from first idea to final cut. Connect an assistant, then pick what you want to make.",
+ "firstRun.modeTitle": "Choose how to create",
+ "firstRun.canvasModelRequired": "Set up an image or video generation model before entering the canvas for the first time.",
+ "firstRun.canvasModelReady": "An image or video generation model is configured. You can enter the canvas.",
+ "firstRun.modeHint.agent": "Start with an idea. No video experience needed. Set up image, video, or audio models as you chat.",
+ "firstRun.modeHint.canvas": "For creators with video experience. Choose how to start and set up an image or video model for your first canvas.",
+ "firstRun.enterCanvas": "Enter canvas",
"firstRun.welcomeStart": "Get started",
"firstRun.welcomeCanvasAlt": "OpenDirector canvas screenshot with six storyboard shots and the editing timeline below",
"firstRun.steps": "First-time setup steps",
@@ -21,8 +27,8 @@ export const firstRun = {
"firstRun.assistantUnavailable": "This assistant isn’t available right now. Check its setup or choose another way to connect.",
"firstRun.assistantBusy": "Wait for the current assistant reply before switching.",
"firstRun.saving": "Saving your assistant selection…",
- "firstRun.tasksTitle": "What do you want to do first?",
- "firstRun.tasksHint": "Choose one or more tasks. Set up only the models you need now.",
+ "firstRun.tasksTitle": "How would you like to start your canvas?",
+ "firstRun.tasksHint": "Choose Generate an image or Make a video to set up a model. You can select several tasks to start together.",
"firstRun.assistantSelected": "Selected assistant: {assistant}",
"firstRun.video.title": "Make a video",
"firstRun.video.hint": "Generate a clip from text or an image you already have",
diff --git a/src/i18n/messages/en-US/index.ts b/src/i18n/messages/en-US/index.ts
index 86adf91ae..9eb468705 100644
--- a/src/i18n/messages/en-US/index.ts
+++ b/src/i18n/messages/en-US/index.ts
@@ -1,3 +1,4 @@
+import { workspaceModes } from "./workspaceModes.ts";
import { availability } from "./availability.ts";
import { voiceLibrary } from "./voiceLibrary.ts";
import { trace } from "./trace.ts";
@@ -25,6 +26,7 @@ type ZhCatalog = typeof import("../zh-CN/index.ts").zhCN;
/** `Record` makes a missing English key a compile error. */
export const enUS: Record = {
...common,
+ ...workspaceModes,
...availability,
...voiceLibrary,
...settings,
diff --git a/src/i18n/messages/en-US/timeline.ts b/src/i18n/messages/en-US/timeline.ts
index 2ee232259..e51dc439f 100644
--- a/src/i18n/messages/en-US/timeline.ts
+++ b/src/i18n/messages/en-US/timeline.ts
@@ -40,6 +40,7 @@ export const timeline = {
"timeline.action.addedToCanvas": "Added to canvas",
"timeline.pack.progress": "Packaging media {percent}%",
"timeline.render.progress": "Rendering {percent}%",
+ "timeline.render.downloadStarted": "Download started",
"timeline.render.done": "MP4 complete · {size} MB (timeline at render time)",
"timeline.library.title": "Media library",
diff --git a/src/i18n/messages/en-US/workspaceModes.ts b/src/i18n/messages/en-US/workspaceModes.ts
new file mode 100644
index 000000000..b0a73d107
--- /dev/null
+++ b/src/i18n/messages/en-US/workspaceModes.ts
@@ -0,0 +1,16 @@
+export const workspaceModes = {
+ "workspaceModes.label": "Creation mode",
+ "workspaceModes.agent": "Create with chat",
+ "workspaceModes.canvas": "Create on canvas",
+ "workspaceModes.short.agent": "Chat",
+ "workspaceModes.short.canvas": "Canvas",
+ "workspaceModes.preferenceFailed": "Switched modes. This browser could not save your preference.",
+ "workspaceModes.showCanvas": "Show canvas",
+ "workspaceModes.floatOnCanvas": "Float on canvas",
+ "workspaceModes.projectAssets": "Project assets",
+ "workspaceModes.importMedia": "Import media",
+ "workspaceModes.createTimeline": "New timeline",
+ "workspaceModes.retryOpenTimeline": "Retry opening the new timeline",
+ "workspaceModes.referenceAsset": "Reference in chat",
+ "workspaceModes.importingMedia": "Importing media…",
+} as const;
diff --git a/src/i18n/messages/zh-CN/assistant.ts b/src/i18n/messages/zh-CN/assistant.ts
index c225e5df2..6efcc195c 100644
--- a/src/i18n/messages/zh-CN/assistant.ts
+++ b/src/i18n/messages/zh-CN/assistant.ts
@@ -75,6 +75,10 @@ export const assistant = {
"assistant.panel.pendingDisabled": "输入框暂不可用,请稍候",
"assistant.panel.pendingHint": "点击正文插入,点击外部或 Esc 取消",
"assistant.panel.resize": "调整 AI 对话宽度",
+ "assistant.panel.float": "浮动聊天",
+ "assistant.panel.dockRight": "停靠到右侧",
+ "assistant.panel.dock": "停靠到左侧",
+ "assistant.panel.moveHint": "拖动标题或按方向键移动聊天,按住 Shift 可加大移动距离。",
"assistant.panel.resizeValue": "{width} 像素;缩至 200 像素收起",
"assistant.panel.resizeHint": "拖动调整宽度,双击恢复默认宽度",
@@ -107,6 +111,22 @@ export const assistant = {
},
"assistant.reply.arguments": "调用参数",
"assistant.reply.result": "返回结果",
+ "assistant.result.editorChanged": "打开编辑器期间项目已更新。请核对结果后重试。",
+ "assistant.result.editMedia": "编辑媒体",
+ "assistant.result.syncingTimeline": "正在从项目同步时间线…",
+ "assistant.result.timelineVersion": "当时交付的版本 {revision}",
+ "assistant.result.openTimelineVersion": "打开当前时间线(版本 {revision})",
+ "assistant.result.openTimeline": "打开时间线",
+ "assistant.result.timeline": "时间线",
+ "assistant.result.timelineChanged": "时间线版本已变化,请核对更新后的时间线再打开。",
+ "assistant.result.preview": "预览",
+ "assistant.result.reference": "继续引用",
+ "assistant.result.viewOnCanvas": "在画布中查看",
+ "assistant.result.current": "当前采用",
+ "assistant.result.candidate": "候选结果",
+ "assistant.result.historical": "历史版本",
+ "assistant.result.unavailable": "此结果的素材已不可用",
+ "assistant.result.locateFailed": "暂时无法在画布中显示此结果。",
"assistant.reply.truncated": "(已截断)",
"assistant.reply.truncatedDetail":
"此处仅展示前 65,536 个字符,完整结果见本轮轨迹。",
diff --git a/src/i18n/messages/zh-CN/canvas.ts b/src/i18n/messages/zh-CN/canvas.ts
index 78d352755..2027d1267 100644
--- a/src/i18n/messages/zh-CN/canvas.ts
+++ b/src/i18n/messages/zh-CN/canvas.ts
@@ -24,7 +24,7 @@ export const canvas = {
"canvas.menu.redo": "重做",
"canvas.menu.undo": "撤销",
"canvas.rail.tools": "画布创作工具",
- "canvas.rail.add": "添加{label}",
+ "canvas.rail.addNode": "添加节点",
"canvas.rail.assets": "资产库",
"canvas.rail.upload": "上传",
"canvas.rail.uploadLocal": "上传本地素材",
diff --git a/src/i18n/messages/zh-CN/canvasWorkspace.ts b/src/i18n/messages/zh-CN/canvasWorkspace.ts
index 5d83405a9..e73ed2335 100644
--- a/src/i18n/messages/zh-CN/canvasWorkspace.ts
+++ b/src/i18n/messages/zh-CN/canvasWorkspace.ts
@@ -86,10 +86,9 @@ export const canvasWorkspace = {
"canvas.workspace.toolbar.help": "使用帮助",
"canvas.workspace.toolbar.chat": "与 AI 对话",
- "canvas.workspace.empty.title": "你的故事,由你执导",
- "canvas.workspace.empty.hint": "双击画布创建节点,或拖入你的素材",
- "canvas.workspace.empty.configureModels": "配置模型",
- "canvas.workspace.empty.tagline": "参考连接 · 自由编排 · 本机自动保存",
+ "canvas.workspace.empty.title": "空白画布",
+ "canvas.workspace.empty.hint": "从左侧「添加节点」开始,或将素材拖到画布上。",
+ "canvas.workspace.empty.browseExamples": "浏览示例画布",
"canvas.workspace.loading.opening": "正在打开画布…",
"canvas.workspace.loading.switching": "正在切换画布…",
@@ -436,6 +435,4 @@ export const canvasWorkspace = {
"canvas.example.state.downloadingPercent": "正在下载… {percent}%",
"canvas.example.progress.label": "下载进度",
// The empty canvas imports the two hosted samples directly.
- "canvas.workspace.empty.tryImage": "体验图片示例",
- "canvas.workspace.empty.tryVideo": "体验视频示例",
} as const;
diff --git a/src/i18n/messages/zh-CN/firstRun.ts b/src/i18n/messages/zh-CN/firstRun.ts
index c98be7e4c..10ac5d065 100644
--- a/src/i18n/messages/zh-CN/firstRun.ts
+++ b/src/i18n/messages/zh-CN/firstRun.ts
@@ -1,6 +1,12 @@
export const firstRun = {
"firstRun.welcomeTitle": "欢迎使用 OpenDirector",
"firstRun.welcomeIntro": "和 AI 一起把想法做成视频。先连接助手,再选择你想做的第一件事。",
+ "firstRun.modeTitle": "选择创作方式",
+ "firstRun.canvasModelRequired": "首次进入画布前,请先配置一个图片或视频生成模型。",
+ "firstRun.canvasModelReady": "已配置图片或视频生成模型,可以进入画布。",
+ "firstRun.modeHint.agent": "从一个想法开始,无需视频创作经验。图片、视频和音频模型可以在对话过程中按需配置。",
+ "firstRun.modeHint.canvas": "适合有视频创作经验的用户。选择开始方式,首次进入需配置图片或视频模型。",
+ "firstRun.enterCanvas": "进入画布",
"firstRun.welcomeStart": "开始设置",
"firstRun.welcomeCanvasAlt": "OpenDirector 画布截图:六个分镜和下方的剪辑时间线",
"firstRun.steps": "首次设置步骤",
@@ -21,8 +27,8 @@ export const firstRun = {
"firstRun.assistantUnavailable": "这个助手目前不可用。请检查配置,或换一种接入方式。",
"firstRun.assistantBusy": "请先等当前助手回复结束,再切换助手。",
"firstRun.saving": "正在保存助手选择…",
- "firstRun.tasksTitle": "你想先做什么?",
- "firstRun.tasksHint": "可以勾选多项,只配置所选任务需要的模型。",
+ "firstRun.tasksTitle": "如何开始画布创作?",
+ "firstRun.tasksHint": "点“生成一张图片”或“做一段视频”可设置模型。也可以勾选多个任务一起开始。",
"firstRun.assistantSelected": "已选助手:{assistant}",
"firstRun.video.title": "做一段视频",
"firstRun.video.hint": "用文字或一张已有图片生成视频",
diff --git a/src/i18n/messages/zh-CN/index.ts b/src/i18n/messages/zh-CN/index.ts
index 96bde2cda..a5842a58d 100644
--- a/src/i18n/messages/zh-CN/index.ts
+++ b/src/i18n/messages/zh-CN/index.ts
@@ -1,3 +1,4 @@
+import { workspaceModes } from "./workspaceModes.ts";
import { availability } from "./availability.ts";
import { voiceLibrary } from "./voiceLibrary.ts";
import { trace } from "./trace.ts";
@@ -22,6 +23,7 @@ import { tools } from "./tools.ts";
/** Canonical copy. Every other locale must provide the same keys. */
export const zhCN = {
...common,
+ ...workspaceModes,
...availability,
...voiceLibrary,
...settings,
diff --git a/src/i18n/messages/zh-CN/timeline.ts b/src/i18n/messages/zh-CN/timeline.ts
index c96ae3a39..15177a7ac 100644
--- a/src/i18n/messages/zh-CN/timeline.ts
+++ b/src/i18n/messages/zh-CN/timeline.ts
@@ -36,6 +36,7 @@ export const timeline = {
"timeline.action.addedToCanvas": "已加入画布",
"timeline.pack.progress": "素材打包 {percent}%",
"timeline.render.progress": "正在合成 {percent}%",
+ "timeline.render.downloadStarted": "已开始下载",
"timeline.render.done": "MP4 已完成 · {size} MB(合成时的时间线)",
"timeline.library.title": "素材库",
diff --git a/src/i18n/messages/zh-CN/workspaceModes.ts b/src/i18n/messages/zh-CN/workspaceModes.ts
new file mode 100644
index 000000000..680eab5e2
--- /dev/null
+++ b/src/i18n/messages/zh-CN/workspaceModes.ts
@@ -0,0 +1,16 @@
+export const workspaceModes = {
+ "workspaceModes.label": "创作方式",
+ "workspaceModes.agent": "对话创作",
+ "workspaceModes.canvas": "画布创作",
+ "workspaceModes.short.agent": "对话",
+ "workspaceModes.short.canvas": "画布",
+ "workspaceModes.preferenceFailed": "已切换,本浏览器未能保存模式偏好。",
+ "workspaceModes.showCanvas": "查看画布",
+ "workspaceModes.floatOnCanvas": "在画布中浮动",
+ "workspaceModes.projectAssets": "项目素材",
+ "workspaceModes.importMedia": "导入素材",
+ "workspaceModes.createTimeline": "新建时间线",
+ "workspaceModes.retryOpenTimeline": "重试打开已创建的时间线",
+ "workspaceModes.referenceAsset": "在对话中引用",
+ "workspaceModes.importingMedia": "正在导入素材…",
+} as const;
diff --git a/tests/assistantResults.test.ts b/tests/assistantResults.test.ts
new file mode 100644
index 000000000..a79f74e92
--- /dev/null
+++ b/tests/assistantResults.test.ts
@@ -0,0 +1,195 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { assistantResultsByTurn, withPublishedAssistantResults } from "../src/canvas/assistantResults.ts";
+import { deliveredTimelineState, prepareProjectEditorItem, resolveProjectEditorItem, timelinesForResultAssets } from "../src/canvas/assistantResultEditors.ts";
+import { findAssetItem } from "../src/canvas/canvasAssetPlacement.ts";
+import type { CreationClient } from "../src/backend/creationClient.ts";
+import type { ChatMessage } from "../src/backend/chat.ts";
+import type { ProjectSnapshot } from "../src/contracts/generated.ts";
+import projectFixture from "./fixtures/creation-project.json" with { type: "json" };
+
+const project = structuredClone(projectFixture) as ProjectSnapshot;
+const result = project.results[0]!;
+const output = project.assets.find((asset) => asset.id === result.asset.assetId)!;
+const owner = project.canvasItems.find((item) => item.binding.role === "generation"
+ && item.binding.objectRef.id === result.specId)!;
+const job = { ...project.jobs[0]!, agentRunId: "turn-one", agentCallId: "call", originItemId: owner.id };
+
+test("only the submitting turn gets its registered result, including after asynchronous completion", () => {
+ assert.equal(assistantResultsByTurn(project).size, 0); // Ordinary canvas job.
+ assert.equal(assistantResultsByTurn({ ...project, jobs: [job], results: [] }).size, 0);
+ const cards = assistantResultsByTurn({ ...project, jobs: [job] });
+ assert.deepEqual([...cards.keys()], [job.agentRunId]);
+ assert.deepEqual(cards.get(job.agentRunId), [{
+ assetId: output.id, asset: output, resultId: result.id, status: "current", itemId: owner.id,
+ }]);
+});
+
+test("candidate and historical cards keep their produced asset when the owner shows another version", () => {
+ const changed = {
+ ...project,
+ generationSpecs: project.generationSpecs.map((spec) => ({ ...spec, currentResultId: null })),
+ };
+ const [candidate] = assistantResultsByTurn({ ...changed, jobs: [job] }).get(job.agentRunId)!;
+ assert.equal(candidate.status, "candidate");
+ assert.equal(candidate.asset?.id, output.id);
+ assert.equal(candidate.itemId, null);
+
+ const placement = project.canvasItems.find((item) => item.kind === "image")!;
+ const hidden = { ...placement, id: "hidden-copy", visible: false, binding: { role: "material" as const, objectRef: result.asset } };
+ const visible = { ...hidden, id: "visible-copy", visible: true };
+ const historical = (canvasItems: ProjectSnapshot["canvasItems"]) => assistantResultsByTurn({
+ ...changed, canvasItems, jobs: [{ ...job, adopted: true }],
+ }).get(job.agentRunId)![0];
+ assert.equal(historical([hidden]).itemId, hidden.id);
+ assert.equal(historical([hidden, visible]).itemId, visible.id);
+ assert.equal(historical([hidden, visible]).status, "historical");
+});
+
+test("written assets use trusted turn provenance and a missing or replaced result cannot redirect its actions", () => {
+ const written = {
+ ...project.assets[0], provenance: {
+ ...project.assets[0].provenance, source: "agent_written" as const, agentRunId: "another-turn",
+ },
+ };
+ const cards = assistantResultsByTurn({
+ ...project, jobs: [job], assets: [written, { ...output, fingerprint: "different-bytes" }],
+ });
+ const [text] = cards.get("another-turn")!;
+ assert.equal(text.asset, written);
+ assert.equal(text.status, "asset");
+ const [unavailable] = cards.get(job.agentRunId)!;
+ assert.equal(unavailable.resultId, result.id);
+ assert.equal(unavailable.asset, null);
+ assert.equal(unavailable.itemId, null);
+});
+
+test("locating a card after its original node changed reuses another item showing the same version", () => {
+ assert.equal(owner.kind, "image");
+ const lastOwner = { ...owner, id: "previous", binding: { role: "empty" as const, draftSpec: null, manualText: null } };
+ const hidden = { ...owner, visible: false };
+ const visible = { ...owner, id: "other", visible: true };
+ const snapshot = { ...project, canvasItems: [lastOwner, hidden, visible] };
+ assert.equal(findAssetItem(snapshot, output.id, lastOwner.id)?.id, visible.id);
+ assert.equal(findAssetItem(snapshot, output.id, hidden.id)?.id, hidden.id);
+ assert.equal(findAssetItem(snapshot, "no-longer-displayed", lastOwner.id), undefined);
+});
+
+test("direct publication receipts preserve deleted identities only in their project and after their cursor", () => {
+ const asset = {
+ ...project.assets[0], provenance: {
+ ...project.assets[0].provenance, source: "agent_written" as const, agentRunId: "turn",
+ },
+ };
+ const snapshot = { ...project, assets: [asset] };
+ const live = assistantResultsByTurn(snapshot);
+ const { id, name, fingerprint } = asset;
+ const messages: ChatMessage[] = [
+ { id: "turn", role: "user", status: "complete", text: "" },
+ { id: "reply", role: "assistant", status: "interrupted", text: "", publishedAssets: {
+ projectId: project.project.id, eventCursor: project.eventCursor, assets: [{ id, name, fingerprint }],
+ } },
+ ];
+ assert.equal(withPublishedAssistantResults(live, messages, snapshot), live);
+ const deleted = { ...snapshot, assets: [] };
+ const empty = assistantResultsByTurn(deleted);
+ const missing = { assetId: id, name, asset: null, resultId: null, itemId: null, status: "asset" };
+ assert.deepEqual(withPublishedAssistantResults(empty, messages, deleted).get("turn"), [missing]);
+ const replaced = { ...snapshot, assets: [{ ...asset, fingerprint: "other-content" }] };
+ assert.deepEqual(withPublishedAssistantResults(assistantResultsByTurn(replaced), messages, replaced).get("turn"), [missing]);
+ assert.equal(withPublishedAssistantResults(empty, messages, { ...deleted, eventCursor: project.eventCursor - 1 }), empty);
+ assert.equal(withPublishedAssistantResults(empty, messages, {
+ ...deleted, project: { ...project.project, id: "different-project" },
+ }), empty);
+ assert.equal(withPublishedAssistantResults(empty, messages.slice(1), snapshot), empty);
+});
+
+test("result editors bind the actual item and immutable media; a changed owner never redirects editing", () => {
+ const selected = { kind: "media" as const, asset: output, itemId: owner.id };
+ assert.equal(resolveProjectEditorItem(project, selected)?.id, owner.id);
+ const rebound = { ...project, canvasItems: project.canvasItems.filter(item => item.id !== owner.id) };
+ assert.throws(() => resolveProjectEditorItem(rebound, selected));
+ assert.throws(() => resolveProjectEditorItem(project, { ...selected, asset: { ...output, revision: output.revision + 1 } }));
+ assert.throws(() => resolveProjectEditorItem(project, { ...selected, asset: { ...output, fingerprint: "replaced" } }));
+ assert.throws(() => resolveProjectEditorItem(project, { ...selected, asset: { ...output, projectId: "other" } }));
+});
+
+test("result timelines match pinned inputs and render provenance across same-named edits and hidden items", () => {
+ const timeline = project.editorDocuments.find(doc => doc.kind === "timeline")!;
+ const item = project.canvasItems.find(item => item.kind === "timeline")!;
+ const imported = timeline.data.importedAssets[0].asset.assetId;
+ const clip = timeline.data.tracks[0].clips[0].resource.asset.assetId;
+ const other = { ...timeline, id: "second" };
+ const hidden = { ...item, id: "hidden", visible: false,
+ binding: { ...item.binding, objectRef: { ...item.binding.objectRef, id: other.id } } };
+ const rendered = { ...output, provenance: { ...output.provenance, source: "rendered" as const,
+ editorDocumentId: other.id, sourceItemId: hidden.id } };
+ const snapshot = { ...project, assets: [...project.assets.filter(asset => asset.id !== output.id), rendered],
+ canvasItems: [item, hidden], editorDocuments: [timeline, other] };
+ const targets = timelinesForResultAssets(snapshot);
+ for (const id of [imported, clip])
+ assert.deepEqual(targets.get(id)?.map(target => target.itemId), [item.id, hidden.id]);
+ assert.deepEqual(targets.get(rendered.id)?.map(target => target.itemId), [hidden.id]);
+ const selected = targets.get(clip)![1];
+ assert.equal(resolveProjectEditorItem(snapshot, selected)?.id, hidden.id);
+ assert.throws(() => resolveProjectEditorItem(snapshot, { ...selected, editorId: timeline.id }));
+ assert.throws(() => resolveProjectEditorItem(snapshot, { ...selected, revision: 99 }));
+ const orphan = { ...snapshot, canvasItems: [item] };
+ assert.throws(() => resolveProjectEditorItem(orphan, selected));
+ assert.equal(resolveProjectEditorItem(orphan, { ...selected, itemId: null }), undefined);
+ const replaced = { ...snapshot, assets: snapshot.assets.map(a => a.id === clip ? { ...a, fingerprint: "new" } : a) };
+ assert.equal(timelinesForResultAssets(replaced).has(clip), false);
+});
+
+test("a delivered timeline waits for its project cursor before reporting deletion or offering a revision", () => {
+ const editor = project.editorDocuments.find(doc => doc.kind === "timeline")!;
+ const item = project.canvasItems.find(item => item.kind === "timeline")!;
+ const receipt = { editorId: editor.id, revision: editor.revision + 1, itemId: item.id, title: "Cut" };
+ const projectId = project.project.id, cursor = project.eventCursor + 1;
+ const state = (snapshot?: ProjectSnapshot) => deliveredTimelineState(receipt, projectId, cursor, snapshot);
+ const delivered = { ...project, eventCursor: cursor,
+ editorDocuments: [{ ...editor, revision: receipt.revision }] };
+ const pending = { title: receipt.title, status: "pending" };
+ assert.deepEqual(state(), pending);
+ assert.deepEqual(state(project), pending); // The cached editor still has the earlier revision.
+ assert.deepEqual(state({ ...project, editorDocuments: [] }), pending);
+ assert.deepEqual(state(delivered), { status: "available", title: receipt.title, revision: receipt.revision });
+ assert.deepEqual(state({ ...delivered, editorDocuments: [] }), { status: "missing", title: receipt.title });
+ const edited = { ...delivered, eventCursor: cursor + 1,
+ editorDocuments: [{ ...editor, revision: receipt.revision + 1 }] };
+ assert.equal(state(edited).revision, receipt.revision + 1);
+ assert.deepEqual(deliveredTimelineState(receipt, projectId, undefined, edited), state(edited));
+});
+
+test("opening a result inside a hidden locked group rejects before changing visibility or history", async () => {
+ const group = project.canvasItems.find(item => item.kind === "group")!;
+ const timeline = project.editorDocuments.find(doc => doc.kind === "timeline")!;
+ const item = project.canvasItems.find(item => item.kind === "timeline")!;
+ const snapshot = { ...project, canvasItems: [
+ { ...group, parentId: null, locked: true, visible: false },
+ { ...item, parentId: group.id, locked: false, visible: true },
+ { ...owner, parentId: group.id, locked: false, visible: true },
+ ] };
+ let writes = 0;
+ const client = { snapshot, command: async () => { ++writes; } } as unknown as CreationClient;
+ const center = () => ({ x: 0, y: 0 });
+ await assert.rejects(prepareProjectEditorItem(client, {
+ kind: "timeline", projectId: project.project.id, itemId: item.id, editorId: timeline.id, revision: timeline.revision,
+ }, center));
+ await assert.rejects(prepareProjectEditorItem(client, { kind: "media", asset: output, itemId: owner.id }, center));
+ assert.equal(writes, 0);
+});
+
+test("opening existing hidden media or an unplaced candidate prepares an editor without project commands", async () => {
+ const hidden = { ...owner, visible: false };
+ const snapshot = { ...project, canvasItems: [hidden] };
+ const client = { snapshot, command: () => assert.fail("read-only editor open") } as unknown as CreationClient;
+ const center = () => ({ x: 250, y: 400 });
+ const target = { kind: "media" as const, asset: output, itemId: hidden.id };
+ assert.deepEqual(await prepareProjectEditorItem(client, target, center), { itemId: hidden.id });
+ client.snapshot = { ...snapshot, canvasItems: [] };
+ const candidate = await prepareProjectEditorItem(client, { ...target, itemId: null }, center);
+ assert.equal(candidate.unplaced?.id, candidate.itemId);
+ assert.deepEqual(candidate.unplaced?.binding, { role: "material", objectRef: result.asset });
+ assert.deepEqual(client.snapshot.canvasItems, []);
+});
diff --git a/tests/browser/assistant_auxiliary_panels.mjs b/tests/browser/assistant_auxiliary_panels.mjs
index b75a9a624..9bc6bebf6 100644
--- a/tests/browser/assistant_auxiliary_panels.mjs
+++ b/tests/browser/assistant_auxiliary_panels.mjs
@@ -1,6 +1,7 @@
/** Search/history preserve chat visibility and work alongside it (#118).
* Run against creation_server.py --assistant-fixture; no real models are used.
*/
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
import { join } from "node:path";
@@ -129,15 +130,15 @@ try {
async function assertLayout(panel) {
const chat = await assistant.boundingBox();
const box = await panel.boundingBox();
- assert.ok(box && chat);
+ assert.ok(box);
assert.ok(
box.x >= 0 && box.x + box.width <= page.viewportSize().width,
"auxiliary panel must stay inside the viewport",
);
- if (page.viewportSize().width >= chat.width + box.width + 52)
+ if (await assistant.isVisible() && chat && page.viewportSize().width >= chat.width + box.width + 52)
assert.ok(
- box.x + box.width <= chat.x - 10,
- "with room available, auxiliary panel must sit left of chat",
+ box.x >= chat.x + chat.width + 10,
+ `with room available, auxiliary panel must sit right of chat: ${JSON.stringify({ width: page.viewportSize().width, chat, panel: box })}`,
);
// A visible DOM node can still be hidden behind the assistant.
await panel.locator("button").first().click({ trial: true });
@@ -156,7 +157,7 @@ try {
await auxiliary(kind).waitFor({ state: "detached" });
}
- await chatButton.click();
+ if (!(await assistant.isVisible())) await chatButton.click();
await editor.fill(draft);
for (const locale of ["zh-CN", "en-US"]) {
// Use the actual language switch rather than reloading with new storage.
@@ -170,11 +171,16 @@ try {
assert.equal(await page.locator("html").getAttribute("lang"), locale);
for (const width of [1720, 1024, 800, 600, 390]) {
await page.setViewportSize({ width, height: 1120 });
+ // Narrow canvas mode switches between chat and canvas. Its auxiliary
+ // controls belong to the canvas; returning to chat retains the draft.
+ const alongsideChat = width > 700;
+ if (!alongsideChat && await assistant.isVisible())
+ await page.locator(".cw-narrow-region-toggle").click();
for (const kind of ["search", "history"]) {
await openAuxiliary(kind, locale);
await assertChat(
- true,
- `${locale}/${width}: opening ${kind} preserves chat`,
+ alongsideChat,
+ `${locale}/${width}: opening ${kind} preserves the chosen region`,
);
await assertLayout(auxiliary(kind));
if (
@@ -191,11 +197,15 @@ try {
});
}
await closeAuxiliary(kind, locale);
- await assertChat(true, `closing ${kind} preserves chat`);
+ await assertChat(alongsideChat, `closing ${kind} preserves the chosen region`);
await openAuxiliary(kind, locale);
await trigger(kind, locale).click();
await auxiliary(kind).waitFor({ state: "detached" });
- await assertChat(true, `toggling ${kind} preserves chat`);
+ await assertChat(alongsideChat, `toggling ${kind} preserves the chosen region`);
+ }
+ if (!alongsideChat) {
+ await chatButton.click();
+ await assertChat(true, "returning from narrow canvas preserves the chat draft");
}
}
await page.setViewportSize({ width: 1720, height: 1120 });
@@ -261,10 +271,7 @@ try {
.click();
await api("/creation-test-gate", { open: false });
await api("/creation-test-assistant-gate", { open: false });
- await page
- .getByRole("toolbar", { name: "画布创作工具" })
- .getByRole("button", { name: "添加图片", exact: true })
- .click();
+ await addCanvasNode(page, "图片");
await chooseGenerationModel(page, { label: "fixture-image" });
await page
.getByRole("textbox", { name: "生成提示词", exact: true })
diff --git a/tests/browser/assistant_result_cards.mjs b/tests/browser/assistant_result_cards.mjs
new file mode 100644
index 000000000..2b16d597c
--- /dev/null
+++ b/tests/browser/assistant_result_cards.mjs
@@ -0,0 +1,608 @@
+/** Exercise Agent result cards through the real project, assistant and asset APIs. */
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { mkdir } from "node:fs/promises";
+import { join } from "node:path";
+import { launchBrowser } from "./engine.mjs";
+import { playDownloadedMp4 } from "./play_downloaded_mp4.mjs";
+
+const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5180";
+const setupSession = crypto.randomUUID();
+async function api(path, { body, method = body ? "POST" : "GET", session = setupSession } = {}) {
+ const response = await fetch(base + "/api" + path, {
+ method,
+ headers: {
+ "X-OpenDirector-Request": "1", "X-OpenDirector-Session": session,
+ "Content-Type": "application/json",
+ },
+ ...(body && { body: JSON.stringify(body) }),
+ });
+ assert.ok(response.ok, await response.clone().text());
+ return response.status === 204 ? null : response.json();
+}
+async function until(read, matches, label) {
+ const deadline = Date.now() + 20000;
+ for (;;) {
+ const value = await read();
+ if (matches(value)) return value;
+ assert.ok(Date.now() < deadline, label);
+ await new Promise(resolve => setTimeout(resolve, 80));
+ }
+}
+
+async function verifyPreviewWindow({ page, locale, labels, result, root, visibleItemId, timelineId }) {
+ const preview = await page.context().newPage();
+ try {
+ await preview.goto(page.url());
+ const workspace = preview.locator('[data-testid="canvas-workspace"][data-edit-mode="preview"][aria-busy="false"]');
+ await workspace.waitFor();
+ await preview.getByTestId("workspace-mode-agent").click();
+ const card = workspace.locator(`.cw-chat-result[data-asset-id="${result.asset.assetId}"]`);
+ const button = name => card.getByRole("button", { name, exact: true });
+ await card.waitFor();
+ assert.ok(await workspace.locator(".cw-edit-request").isVisible());
+ assert.ok(await button(labels.reference).isDisabled());
+ assert.ok(await button(locale === "zh-CN" ? "编辑媒体" : "Edit media").isDisabled());
+
+ const writes = [];
+ preview.on("request", req => {
+ const path = new URL(req.url()).pathname;
+ if (req.method() !== "GET" && path.startsWith("/api" + root + "/") &&
+ /\/(commands|uploads|assistant)(\/|$)/.test(path)) writes.push(`${req.method()} ${path}`);
+ });
+ const before = await api(root);
+ const chat = await api(root + "/assistant");
+ const media = preview.locator("dialog.cw-preview");
+ await button(labels.preview).click();
+ await media.locator("img").evaluate(element => element.decode());
+ await preview.keyboard.press("Escape");
+ await media.waitFor({ state: "hidden" });
+
+ const isAssetList = url => new URL(url).pathname === "/api" + root + "/asset-list";
+ const initialListing = preview.waitForResponse(response => isAssetList(response.url()));
+ await workspace.locator("[data-chat-project-assets]").click();
+ const list = workspace.locator('.cw-creation-assets[data-actions="preview"]');
+ const response = await initialListing;
+ assert.ok(response.ok(), await response.text());
+ const items = (await response.json()).items;
+ await workspace.locator('.cw-creation-assets[data-actions="preview"][aria-busy="false"]').waitFor();
+ assert.equal(await list.locator("[data-project-import], [data-reference-asset], [data-create-timeline], [data-open-timeline]").count(), 0);
+ const name = before.assets.find(asset => asset.id === result.asset.assetId).name;
+ const searchRequests = [];
+ const trackListRead = req => { if (isAssetList(req.url())) searchRequests.push(req.url()); };
+ preview.on("request", trackListRead);
+ await list.getByRole("textbox").fill(name);
+ const matches = items.filter(entry => entry.asset.name === name);
+ const row = list.getByTitle(name, { exact: true });
+ await until(() => row.count(), count => count === matches.length, "the filter must show the matching assets");
+ preview.off("request", trackListRead);
+ assert.deepEqual(searchRequests, [], "filtering results in the loaded asset list must not send another query");
+ if (labels.policy === "candidate_only" && !visibleItemId) {
+ // Unadopted generation candidates live in the results inventory until placed.
+ assert.ok(!items.some(entry => entry.asset.id === result.asset.assetId));
+ assert.equal(await row.count(), 0);
+ await preview.keyboard.press("Escape");
+ await list.waitFor({ state: "hidden" });
+ } else {
+ const index = matches.findIndex(entry => entry.asset.id === result.asset.assetId);
+ assert.ok(index >= 0);
+ await row.nth(index).click();
+ const hash = await media.locator("img").evaluate(async element => {
+ await element.decode();
+ const bytes = await (await fetch(element.currentSrc)).arrayBuffer();
+ return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)),
+ value => value.toString(16).padStart(2, "0")).join("");
+ });
+ assert.equal("sha256:" + hash, result.asset.fingerprint);
+ await preview.keyboard.press("Escape");
+ await media.waitFor({ state: "hidden" });
+ }
+
+ await workspace.locator("#canvas-assistant").evaluate(panel => {
+ const dataTransfer = new DataTransfer();
+ dataTransfer.items.add(new File(["preview"], "preview-drop.txt", { type: "text/plain" }));
+ panel.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer }));
+ });
+ if (timelineId) {
+ const timelineAction = workspace.locator(`.cw-chat-result[data-editor-id="${timelineId}"] button`);
+ assert.ok(await timelineAction.isDisabled());
+ }
+ if (visibleItemId) {
+ await button(labels.locate).click();
+ await workspace.locator(`.react-flow__node.selected[data-id="${visibleItemId}"]`).waitFor();
+ } else {
+ assert.ok(await button(labels.locate).isDisabled(), "a preview cannot show a hidden or unplaced result");
+ await preview.getByTestId("workspace-mode-canvas").click();
+ }
+ await until(() => preview.getByTestId("workspace-mode-canvas").getAttribute("aria-pressed"),
+ value => value === "true", "the preview must remain navigable");
+ assert.equal((await api(root)).eventCursor, before.eventCursor);
+ assert.deepEqual((await api(root + "/assistant")).draftContent, chat.draftContent);
+ assert.deepEqual(writes, [], "viewing results and dropping a file in preview must not send business writes");
+ } finally {
+ await preview.close();
+ }
+}
+
+async function openResultImage(page, card, locale) {
+ await card.getByRole("button", { name: locale === "zh-CN" ? "编辑媒体" : "Edit media", exact: true }).click();
+ const media = page.locator(".cw-image-editor");
+ try {
+ await media.waitFor();
+ } catch (error) {
+ console.error("Result editor did not open", {
+ locale, card: await card.innerText(), workspace: await page.locator(".cw-workspace").getAttribute("data-workspace-mode"),
+ dialogs: await page.getByRole("dialog").allTextContents(),
+ alerts: await page.getByRole("alert").allTextContents(),
+ });
+ throw error;
+ }
+ const image = media.locator("canvas").first();
+ await until(() => image.evaluate(canvas => {
+ const pixel = canvas.getContext("2d").getImageData(canvas.width >> 1, canvas.height >> 1, 1, 1).data;
+ return pixel[0] > 64 && pixel[1] < 32 && pixel[2] > 64;
+ }), Boolean, "the existing image editor must decode the pinned purple result");
+ return media;
+}
+
+async function verifyReadOnlyImage({ page, card, locale, root, conversation }) {
+ const original = await conversation();
+ const before = await api(root);
+ const history = await api(root + "/history");
+ const assertReadOnly = async () => {
+ const snapshot = await api(root);
+ assert.deepEqual(snapshot.canvasItems, before.canvasItems,
+ "opening or canceling Edit media must preserve every item, including visibility and revision");
+ assert.deepEqual(await api(root + "/history"), history, "opening or canceling must preserve undo history");
+ assert.equal(snapshot.project.revision, before.project.revision, "opening or canceling must preserve the project revision");
+ assert.equal(snapshot.eventCursor, before.eventCursor, "the editor must open without committing a command");
+ };
+ const media = await openResultImage(page, card, locale);
+ await assertReadOnly();
+ await media.locator(".cw-editor-close").click();
+ await media.waitFor({ state: "hidden" });
+ await assertReadOnly();
+ assert.equal(await page.getByTestId("workspace-mode-agent").getAttribute("aria-pressed"), "true");
+ const returned = await conversation();
+ assert.equal(returned.conversationId, original.conversationId);
+ assert.deepEqual(returned.draftContent, original.draftContent);
+ assert.deepEqual(returned.messages, original.messages);
+}
+
+async function verifyImageSaveAndUndo({ page, card, locale, root, result, itemId, adopted }) {
+ const zh = locale === "zh-CN";
+ const before = await api(root);
+ const history = await api(root + "/history");
+ let media = await openResultImage(page, card, locale);
+ await media.getByRole("button", { name: zh ? "旋转 90°" : "Rotate 90°", exact: true }).click();
+ const viewport = page.viewportSize();
+ await page.setViewportSize({ width: 390, height: 844 });
+ const canvas = media.locator("canvas").first();
+ await until(() => canvas.evaluate(element => [element.width, element.height]),
+ size => size[0] === 240 && size[1] === 320, "the quarter-turn draft must appear in the preview");
+ const modal = await media.elementHandle();
+ for (const mode of ["canvas", "agent"]) {
+ const toggle = media.getByTestId("workspace-mode-" + mode);
+ const clipped = await media.locator("header button").evaluateAll(buttons => buttons.flatMap(button => {
+ const { left, right } = button.getBoundingClientRect();
+ return left < 0 || right > window.innerWidth ? [{ button: button.textContent, left, right }] : [];
+ }));
+ assert.deepEqual(clipped, [], "all editor header controls must fit at 390px");
+ if (mode === "canvas") await toggle.click();
+ else {
+ await toggle.focus();
+ await toggle.press("Enter");
+ }
+ await until(() => page.getByTestId("canvas-workspace").getAttribute("data-workspace-mode"),
+ value => value === mode, "the open editor must allow mode changes");
+ assert.ok(await media.evaluate((element, original) => element === original, modal), "preserve the editor instance");
+ assert.ok(await toggle.evaluate(element => document.activeElement === element), "retain keyboard focus in the editor");
+ assert.deepEqual(await canvas.evaluate(element => [element.width, element.height]), [240, 320]);
+ assert.equal((await api(root)).eventCursor, before.eventCursor, "switching must preserve the editor's version basis");
+ assert.deepEqual(await api(root + "/history"), history);
+ }
+ await page.setViewportSize(viewport);
+ if (adopted) {
+ await media.locator(".cw-editor-close").click();
+ await media.waitFor({ state: "hidden" });
+ assert.equal((await api(root)).eventCursor, before.eventCursor);
+ assert.deepEqual(await api(root + "/history"), history);
+ media = await openResultImage(page, card, locale);
+ assert.deepEqual(await media.locator("canvas").first().evaluate(element => [element.width, element.height]), [320, 240],
+ "cancel must discard the rotated draft");
+ await media.getByRole("button", { name: "旋转 90°", exact: true }).click();
+ }
+ await media.locator(".cw-editor-apply").click();
+ await until(async () => {
+ if (!(await media.isVisible())) return true;
+ const error = media.getByRole("alert");
+ if (await error.isVisible()) assert.fail(await error.innerText());
+ return false;
+ }, Boolean, "the rotated image must be saved and the modal closed");
+ assert.equal(await page.getByTestId("workspace-mode-agent").getAttribute("aria-pressed"), "true");
+
+ const saved = await api(root);
+ const crop = saved.editorDocuments.find(doc => doc.kind === "image_crop");
+ assert.ok(crop);
+ assert.equal(crop.data.options.rotation, 90);
+ assert.deepEqual(crop.data.source, result.asset);
+ const output = saved.assets.find(asset => asset.provenance.editorDocumentId === crop.id);
+ assert.ok(output);
+ assert.deepEqual([output.metadata.width, output.metadata.height], [240, 320]);
+ assert.equal(output.provenance.source, "edited");
+ assert.ok(output.provenance.sources.some(ref => ref.assetId === result.asset.assetId && ref.fingerprint === result.asset.fingerprint));
+ assert.equal(output.provenance.editorRevision, crop.revision);
+ assert.notEqual(output.fingerprint, result.asset.fingerprint);
+ assert.deepEqual(saved.assets.find(asset => asset.id === result.asset.assetId), before.assets.find(asset => asset.id === result.asset.assetId));
+ assert.deepEqual(saved.results, before.results);
+ assert.deepEqual(saved.generationSpecs, before.generationSpecs);
+ const editedItem = saved.canvasItems.find(item => item.editors?.some(editor => editor.id === crop.id));
+ assert.ok(editedItem);
+ if (adopted) {
+ assert.equal(editedItem.id, itemId);
+ assert.equal(editedItem.visible, false);
+ assert.equal(editedItem.binding.materialOverride.assetId, output.id);
+ assert.equal(editedItem.revision, before.canvasItems.find(item => item.id === itemId).revision + 1);
+ assert.equal(saved.canvasItems.length, before.canvasItems.length);
+ } else {
+ assert.equal(editedItem.binding.objectRef.assetId, output.id);
+ assert.equal(editedItem.visible, true);
+ assert.deepEqual(saved.canvasItems.filter(item => item.id !== editedItem.id), before.canvasItems);
+ }
+ const afterSave = await api(root + "/history");
+ assert.equal(afterSave.length, history.length + 1, "the explicit save must be one reversible edit");
+ const [edit] = afterSave;
+ assert.equal(edit.state, "applied");
+ await page.getByTestId("workspace-mode-canvas").click();
+ const showCanvas = page.getByRole("button", { name: zh ? "查看画布" : "Show canvas", exact: true });
+ if (await showCanvas.isVisible()) await showCanvas.click();
+ await page.getByRole("button", { name: zh ? "撤销" : "Undo", exact: true }).click();
+ await until(() => api(root + "/history"), entries => entries.some(entry =>
+ entry.commandId === edit.commandId && entry.state === "undone"), "the single save must be undoable");
+ const undone = await api(root);
+ if (adopted) {
+ const original = before.canvasItems.find(item => item.id === itemId);
+ const restored = undone.canvasItems.find(item => item.id === itemId);
+ assert.equal(restored.revision, editedItem.revision + 1);
+ assert.deepEqual({ ...restored, revision: original.revision }, original);
+ console.log("Hidden result item revisions", { afterCancel: original.revision, saved: editedItem.revision, undone: restored.revision });
+ } else {
+ assert.equal(undone.canvasItems.find(item => item.id === editedItem.id).visible, false);
+ assert.deepEqual(undone.canvasItems.filter(item => item.id !== editedItem.id), before.canvasItems);
+ }
+ await page.getByTestId("workspace-mode-agent").click();
+ return undone;
+}
+
+async function verifyResultEditors({ page, card, result, projectId, command, state, conversation, locale }) {
+ const zh = locale === "zh-CN";
+ const button = (container, name) => container.getByRole("button", { name, exact: true });
+ const original = await conversation();
+ const chatMode = page.getByTestId("workspace-mode-agent");
+ const media = await openResultImage(page, card, locale);
+ await media.locator(".cw-editor-close").click();
+ await media.waitFor({ state: "hidden" });
+ assert.equal(await chatMode.getAttribute("aria-pressed"), "true");
+ assert.equal((await conversation()).conversationId, original.conversationId);
+
+ // Same title and source in two timelines; only their stable identities and edits differ.
+ const targets = [0.5, 1].map(duration => ({
+ itemId: crypto.randomUUID(), editorId: crypto.randomUUID(), duration,
+ }));
+ const session = await page.evaluate(() => sessionStorage.getItem("opendirector.session.v1"));
+ for (const { itemId, editorId, duration } of targets) {
+ const document = { id: editorId, projectId, kind: "timeline", data: {
+ fps: 12, width: 128, height: 96,
+ tracks: [{ id: "visual", kind: "visual", title: "Cut", clips: [{
+ id: "result-shot", inPoint: 0, outPoint: duration,
+ resource: { asset: result.asset, title: "Result shot" },
+ }] }],
+ } };
+ const item = { id: itemId, projectId, kind: "timeline", title: "Result cut",
+ binding: { role: "editor", objectRef: { id: editorId, kind: "timeline" } } };
+ assert.equal((await command("creation.batch", { operations: [
+ { type: "editor.create", payload: { document } }, { type: "canvas.show", payload: { item } },
+ ] }, [], session)).status, "applied");
+ }
+ await page.reload();
+ const choice = card.getByRole("combobox", { name: zh ? "时间线" : "Timeline", exact: true });
+ await choice.waitFor();
+ assert.equal(await choice.inputValue(), "", "multiple timelines require an explicit choice");
+ assert.ok(await button(card, zh ? "打开时间线" : "Open timeline").isDisabled());
+ const options = await choice.locator("option").evaluateAll(items => items.filter(item => item.value)
+ .map(item => ({ value: item.value, label: item.textContent })));
+ assert.deepEqual(new Set(options.map(option => option.value)), new Set(targets.map(item => item.itemId)));
+ assert.equal(new Set(options.map(option => option.label)).size, targets.length, "identically named targets must be distinguishable");
+ const target = targets[1];
+ await choice.selectOption(target.itemId);
+ await button(card, zh ? "打开时间线" : "Open timeline").click();
+ const timeline = page.locator(".cw-timeline-dialog");
+ const clip = timeline.locator(".cw-timeline-clip");
+ await clip.waitFor();
+ assert.ok((await clip.textContent()).includes("Result shot"));
+ const download = button(timeline, zh ? "下载 MP4" : "Download MP4");
+ const publish = button(timeline, zh ? "将合成视频加入画布" : "Add rendered video to canvas");
+ await button(timeline, zh ? "合成 MP4" : "Render MP4").click();
+ await download.waitFor({ timeout: 90000 });
+ assert.ok(!(await state()).assets.some(asset => asset.provenance.source === "rendered"));
+ const decoded = await playDownloadedMp4(page, download);
+ assert.equal(decoded.width, 128);
+ assert.equal(decoded.height, 96);
+ assert.ok(Math.abs(decoded.duration - target.duration) < 0.12);
+ assert.ok(decoded.pixel[0] > 64 && decoded.pixel[1] < 32 && decoded.pixel[2] > 64);
+
+ let rejected;
+ const refuse = async route => {
+ const body = route.request().postDataJSON();
+ if (body?.type !== "timeline.publishRender" || rejected) return route.continue();
+ rejected = body;
+ await route.fulfill({ status: 503, json: { detail: "fixture: retry publication" } });
+ };
+ await page.route("**/commands", refuse);
+ try {
+ await publish.click();
+ await timeline.getByRole("alert").filter({ hasText: "fixture: retry publication" }).waitFor();
+ assert.ok(await download.isEnabled());
+ assert.ok(!(await state()).assets.some(asset => asset.provenance.source === "rendered"));
+ const retry = page.waitForRequest(request => request.url().endsWith("/commands") &&
+ request.postDataJSON()?.type === "timeline.publishRender");
+ await publish.click();
+ assert.deepEqual((await retry).postDataJSON(), rejected);
+ await button(timeline, zh ? "已加入画布" : "Added to canvas").waitFor();
+ } finally {
+ await page.unroute("**/commands", refuse);
+ }
+ const snapshot = await state();
+ const output = snapshot.assets.filter(asset => asset.provenance.source === "rendered");
+ assert.equal(output.length, 1);
+ assert.equal(output[0].provenance.editorDocumentId, target.editorId);
+ assert.equal(output[0].provenance.sourceItemId, target.itemId);
+ assert.equal(output[0].fingerprint, decoded.fingerprint);
+ await button(timeline, zh ? "关闭编辑器" : "Close editor").click();
+ await timeline.waitFor({ state: "hidden" });
+ assert.equal(await chatMode.getAttribute("aria-pressed"), "true");
+ const returned = await conversation();
+ assert.equal(returned.conversationId, original.conversationId);
+ assert.deepEqual(returned.messages, original.messages);
+}
+
+const health = await api("/creation-test-health");
+assert.ok(health.isolated && health.assistantFixture);
+const model = (await api("/model-configs")).find(item => item.modelId === "fixture-image");
+assert.ok(model);
+const locales = {
+ "en-US": { policy: "candidate_only", status: "Candidate", send: "Send message", preview: "Preview", reference: "Reference in chat", locate: "View on canvas", download: "Download preview asset" },
+ "zh-CN": { policy: "if_current", status: "当前采用", send: "发送消息", preview: "预览", reference: "继续引用", locate: "在画布中查看", download: "下载预览素材" },
+};
+const browser = await launchBrowser();
+try {
+ for (const [locale, labels] of Object.entries(locales)) {
+ const projectId = crypto.randomUUID(), specId = crypto.randomUUID(), itemId = crypto.randomUUID();
+ const root = `/creation/projects/${projectId}`;
+ const command = (type, payload, expectedVersions = [], session = setupSession) => api(root + "/commands", {
+ body: { commandId: crypto.randomUUID(), projectId, type, payload, expectedVersions }, session,
+ });
+ await command("project.create", { name: `Result cards ${projectId.slice(0, 8)}` });
+ await api(root + "/open", { body: {} });
+ assert.equal((await command("creation.batch", { operations: [
+ { type: "generationSpec.create", payload: { spec: {
+ id: specId, projectId, kind: "image", purpose: "generation", modelConfigId: model.id, prompt: "A purple frame",
+ } } },
+ { type: "canvas.show", payload: { item: {
+ id: itemId, projectId, kind: "image", title: "Result source",
+ position: { x: 2100, y: 500 }, binding: { role: "generation", objectRef: { id: specId } },
+ } } },
+ ] })).status, "applied");
+ await api(`/creation/sessions/${setupSession}`, { method: "DELETE" });
+
+ const context = await browser.newContext({ locale, viewport: { width: 1440, height: 900 } });
+ const page = await context.newPage();
+ const errors = [];
+ page.on("pageerror", error => errors.push(error.message));
+ await page.addInitScript(language => {
+ if (!localStorage.getItem("opendirector.modelSetup.v1"))
+ localStorage.setItem("opendirector.modelSetup.v1", "dismissed");
+ localStorage.setItem("opendirector.locale.v1", language);
+ }, locale);
+ await page.goto(`${base}/ai-tool/ai-canvas/${projectId}`);
+ const mode = key => page.getByTestId(`workspace-mode-${key}`);
+ await mode("agent").click();
+ const assistant = page.locator("#canvas-assistant");
+ const editor = assistant.getByRole("textbox", { name: locale === "zh-CN" ? "消息内容" : "Message content", exact: true });
+ const conversation = () => api(root + "/assistant");
+ await until(conversation, c => !!c.modelSelections.agent, "The Agent model must be ready");
+ // The provider gate lets the turn finish before its job has produced any asset.
+ await api("/creation-test-gate", { body: { open: false } });
+ await editor.fill("Result card: " + labels.policy);
+ await assistant.getByRole("button", { name: labels.send, exact: true }).click();
+ const turn = await until(conversation, c => c.messages.at(-1)?.status === "complete", "The Agent reply must finish");
+ const turnId = turn.messages[0].id;
+ const running = await api(root);
+ assert.equal(running.jobs[0].agentRunId, turnId);
+ assert.equal(running.results.length, 0);
+ const cards = assistant.locator(".cw-chat-result");
+ assert.equal(await cards.count(), 0);
+ await api("/creation-test-gate", { body: { open: true } });
+ const generated = await until(() => api(root), s => s.results.length === 1, "The image result must commit");
+ const [result] = generated.results;
+ assert.equal(result.jobId, running.jobs[0].id);
+ const card = assistant.locator(`.cw-chat-result[data-asset-id="${result.asset.assetId}"]`);
+ await card.waitFor();
+ assert.equal(await cards.count(), 1);
+ assert.ok((await card.textContent()).includes(labels.status));
+ if (process.env.CREATION_SCREENSHOTS) {
+ await mkdir(process.env.CREATION_SCREENSHOTS, { recursive: true });
+ await card.locator("img").evaluate(image => image.decode());
+ await page.screenshot({ path: join(process.env.CREATION_SCREENSHOTS, `chat-result-${locale}.png`) });
+ }
+ const action = name => card.getByRole("button", { name, exact: true });
+ await action(labels.preview).click();
+ const preview = page.locator("dialog.cw-preview");
+ await preview.locator("img").evaluate(image => image.decode());
+ assert.equal(await preview.locator("img").evaluate(image => image.naturalWidth), 320);
+ const downloaded = page.waitForEvent("download");
+ await preview.getByRole("button", { name: labels.download }).click();
+ const bytes = await (await downloaded).createReadStream();
+ const hash = createHash("sha256");
+ for await (const chunk of bytes) hash.update(chunk);
+ assert.equal("sha256:" + hash.digest("hex"), result.asset.fingerprint);
+ await page.keyboard.press("Escape");
+ await preview.waitFor({ state: "hidden" });
+ await editor.fill("Keep my draft");
+ await action(labels.reference).click();
+ const draft = await until(conversation, c => c.assets.some(a => a.id === result.asset.assetId), "Reference must persist in the draft");
+ assert.ok(draft.draft.includes("Keep my draft"));
+ assert.equal(draft.assets[0].fingerprint, result.asset.fingerprint);
+ const reference = draft.draftContent.find(part => part.type === "reference");
+ assert.equal(reference.assetId, result.asset.assetId);
+ assert.equal(reference.fingerprint, result.asset.fingerprint);
+ assert.equal(reference.binding, "asset");
+ assert.deepEqual(draft.messages, turn.messages);
+ assert.deepEqual((await api(root)).canvasItems, generated.canvasItems);
+
+ await page.reload();
+ await card.waitFor();
+ const adopted = labels.policy === "if_current";
+ // Locate historical results with their original binding, even after hiding the origin.
+ if (adopted) {
+ assert.equal(generated.generationSpecs[0].currentResultId, result.id);
+ const session = await page.evaluate(() => sessionStorage.getItem("opendirector.session.v1"));
+ const version = generated.canvasItems[0].revision;
+ assert.equal((await command("canvas.hide", { itemId }, [{ objectType: "canvas_item", id: itemId, revision: version }], session)).status, "applied");
+ await page.reload();
+ await card.waitFor();
+ await page.setViewportSize({ width: 600, height: 850 });
+ }
+ await verifyPreviewWindow({ page, locale, labels, result, root });
+ await verifyReadOnlyImage({ page, card, locale, root, conversation });
+ if (!adopted) {
+ const configs = "**/api/model-configs";
+ await page.route(configs, async route => {
+ const response = await route.fetch();
+ await route.fulfill({ response, json: (await response.json()).filter(model => model.kind === "agent") });
+ });
+ await page.evaluate(() => localStorage.setItem("opendirector.modelSetup.v1", "chat-ready"));
+ await page.reload();
+ await action(labels.locate).click();
+ const settings = page.locator("#settings-dialog");
+ await settings.waitFor();
+ assert.ok(await settings.getByRole("button", { name: "Enter canvas" }).isDisabled());
+ await page.keyboard.press("Escape");
+ await settings.waitFor({ state: "hidden" });
+ assert.equal(await mode("agent").getAttribute("aria-pressed"), "true");
+ assert.deepEqual((await api(root)).canvasItems, generated.canvasItems);
+ assert.deepEqual((await conversation()).draftContent, draft.draftContent);
+ const crop = await openResultImage(page, card, locale);
+ await crop.getByRole("button", { name: "Rotate 90°", exact: true }).click();
+ await crop.getByTestId("workspace-mode-canvas").click();
+ await settings.waitFor();
+ await page.keyboard.press("Escape");
+ await settings.waitFor({ state: "hidden" });
+ assert.ok(await crop.isVisible(), "canceling required model setup must keep the editor open");
+ assert.equal(await crop.getByTestId("workspace-mode-agent").getAttribute("aria-pressed"), "true");
+ assert.deepEqual(await crop.locator("canvas").first().evaluate(element => [element.width, element.height]), [240, 320]);
+ await crop.locator(".cw-editor-close").click();
+ await crop.waitFor({ state: "hidden" });
+ await page.unroute(configs);
+ await page.reload();
+ }
+ const afterUndo = await verifyImageSaveAndUndo({ page, card, locale, root, result, itemId, adopted });
+ await action(labels.locate).click();
+ const selected = page.locator(".react-flow__node.selected");
+ await selected.waitFor();
+ const selectedId = await selected.getAttribute("data-id");
+ assert.equal(await mode("canvas").getAttribute("aria-pressed"), "true");
+ assert.equal(await page.getByTestId("canvas-region").isVisible(), true);
+ const located = await api(root);
+ const item = located.canvasItems.find(i => i.id === selectedId);
+ assert.ok(item?.visible);
+ if (adopted) {
+ assert.equal(selectedId, itemId);
+ const undoneRevision = afterUndo.canvasItems.find(source => source.id === itemId).revision;
+ assert.equal(item.revision, undoneRevision + 1);
+ assert.equal(located.canvasItems.length, 1);
+ console.log("Located result item revision", item.revision);
+ } else {
+ assert.equal(item.binding.role, "material");
+ assert.deepEqual(item.binding.objectRef, result.asset);
+ assert.equal(located.canvasItems.length, afterUndo.canvasItems.length + 1);
+ }
+ assert.deepEqual(located.assets, afterUndo.assets);
+ assert.deepEqual(located.generationSpecs, generated.generationSpecs);
+ assert.deepEqual(located.results, generated.results);
+ // Move the existing item outside the actual viewport before locating it again.
+ const pane = page.locator(".react-flow__pane");
+ const hitSelected = () => selected.evaluate(node => {
+ const box = node.getBoundingClientRect();
+ return node.contains(document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2));
+ });
+ await until(hitSelected, Boolean, "locating a result must reveal an actionable node");
+ const point = await pane.evaluate(element => {
+ const box = element.getBoundingClientRect();
+ for (let y = box.bottom - 90; y > box.top + box.height / 2; y -= 60)
+ for (let x = box.left + 90; x < box.right - 40; x += 60)
+ if (document.elementFromPoint(x, y) === element) return { x, y, endY: box.top + 90 };
+ });
+ assert.ok(point, "a blank canvas area is available for panning");
+ await page.mouse.move(point.x, point.y);
+ await page.mouse.down({ button: "middle" });
+ await page.mouse.move(point.x, point.endY, { steps: 12 });
+ await page.mouse.up({ button: "middle" });
+ await until(hitSelected, hit => !hit, "manual pan must move the result offscreen");
+ await mode("agent").click();
+ if (adopted) {
+ const pending = assistant.locator("[data-pending-references]");
+ await pending.waitFor();
+ await action(labels.preview).click();
+ await preview.waitFor();
+ await page.keyboard.press("Escape");
+ await preview.waitFor({ state: "hidden" });
+ assert.equal(await pending.isVisible(), true, "closing a result preview must preserve pending canvas references");
+ }
+ await action(labels.locate).click();
+ await until(() => mode("canvas").getAttribute("aria-pressed"), pressed => pressed === "true",
+ "clicking a result with a pending selection must switch to Canvas");
+ assert.equal(await selected.getAttribute("data-id"), selectedId);
+ await until(hitSelected, Boolean, "View on canvas must bring the existing offscreen item back");
+ assert.deepEqual((await api(root)).canvasItems, located.canvasItems);
+ await mode("agent").click();
+ const submitted = page.waitForRequest(request =>
+ request.method() === "POST" && request.url().endsWith("/assistant/turns"));
+ await assistant.getByRole("button", { name: labels.send, exact: true }).click();
+ const turnRequest = (await submitted).postDataJSON();
+ assert.deepEqual(turnRequest.assets, [result.asset.assetId]);
+ assert.deepEqual(turnRequest.content.find(part => part.type === "reference"), reference);
+ const continued = await until(conversation, c => c.messages.length === 4 && c.messages.at(-1)?.status === "complete",
+ "the next turn must complete with the result reference");
+ assert.equal(continued.messages[2].assets[0].id, result.asset.assetId);
+ assert.equal(await cards.count(), 1, "reusing an asset as input must not make it an output of the new reply");
+ await verifyResultEditors({ page, card, result, projectId, command, state: () => api(root), conversation, locale });
+ await editor.fill("Result card: timeline");
+ await assistant.getByRole("button", { name: labels.send, exact: true }).click();
+ const delivered = await until(conversation, c => c.messages.length === 6 && c.messages.at(-1)?.status === "complete",
+ "the timeline-only Agent turn must finish");
+ const reply = delivered.messages.at(-1);
+ assert.equal(reply.publishedTimelines?.projectId, projectId);
+ const [target] = reply.publishedTimelines.timelines;
+ const project = await api(root);
+ assert.ok(project.editorDocuments.some(doc => doc.id === target.editorId && doc.revision === target.revision));
+ assert.ok(project.canvasItems.some(item => item.id === target.itemId && item.binding.objectRef.id === target.editorId));
+ const timelineCard = assistant.locator('[data-editor-id="' + target.editorId + '"]');
+ await page.reload();
+ await timelineCard.getByRole("button", { name: locale === "zh-CN" ? "打开时间线" : "Open timeline", exact: true }).click();
+ const timeline = page.locator(".cw-timeline-dialog");
+ await timeline.getByText("Agent cut track", { exact: true }).waitFor();
+ await timeline.getByRole("button", { name: locale === "zh-CN" ? "关闭编辑器" : "Close editor", exact: true }).click();
+ await timeline.waitFor({ state: "hidden" });
+ await verifyPreviewWindow({ page, locale, labels, result, root, visibleItemId: selectedId, timelineId: target.editorId });
+ const returned = await conversation();
+ assert.equal(returned.conversationId, delivered.conversationId);
+ assert.deepEqual(returned.messages, delivered.messages);
+ assert.deepEqual(errors, []);
+ await context.close();
+ console.log(`PASS ${locale}: read-only open and cancel, unsaved media draft and focus across modes at 390px, rotated image save and undo, canvas identity, chosen timeline, playable MP4, publication retry, and timeline-only reply (${labels.policy})`);
+ }
+} finally {
+ await api("/creation-test-gate", { body: { open: true } });
+ await browser.close();
+}
diff --git a/tests/browser/assistant_run_navigation.mjs b/tests/browser/assistant_run_navigation.mjs
index 073df3268..a439dfd6d 100644
--- a/tests/browser/assistant_run_navigation.mjs
+++ b/tests/browser/assistant_run_navigation.mjs
@@ -109,10 +109,9 @@ try {
});
const editor = panel.getByRole("textbox", { name: "消息内容", exact: true });
const show = async () => {
- if (!(await panel.isVisible()))
- await page
- .getByRole("button", { name: "与 AI 对话", exact: true })
- .click();
+ await page.locator('[data-testid="canvas-workspace"][aria-busy="false"]').waitFor();
+ const openChat = page.getByRole("button", { name: "与 AI 对话", exact: true, expanded: false });
+ if (await openChat.isVisible()) await openChat.click();
await editor.waitFor();
};
const switchTo = async (name) => {
diff --git a/tests/browser/assistant_sessions.mjs b/tests/browser/assistant_sessions.mjs
index bd4b9dce5..87879c53c 100644
--- a/tests/browser/assistant_sessions.mjs
+++ b/tests/browser/assistant_sessions.mjs
@@ -127,16 +127,66 @@ try {
await panel.getByRole("button", { name: "停止回复", exact: true }).waitFor({ state: "hidden" });
await editor.fill("海边草稿");
- await panel.getByLabel("选择对话参考文件", { exact: true }).setInputFiles({
- name: "story-reference.txt",
- mimeType: "text/plain",
- buffer: Buffer.from("A private reference for the first session"),
- });
+ // Keep the real upload in flight across both layouts. Check its handle and
+ // registration, so a restart or an accepted upload with lost draft is visible.
+ const uploadPath = `**/projects/${projectId}/uploads/*`;
+ const uploadRequests = [];
+ let releaseUpload;
+ const uploadGate = new Promise((resolve) => { releaseUpload = resolve; });
+ const holdUpload = async (route) => {
+ const request = route.request();
+ uploadRequests.push({ method: request.method(), url: request.url() });
+ if (request.method() === "PUT") await uploadGate;
+ return route.continue();
+ };
+ await page.route(uploadPath, holdUpload);
+ const imports = [];
+ const recordImport = (request) => {
+ if (request.method() !== "POST" || !request.url().endsWith("/commands")) return;
+ const command = request.postDataJSON();
+ if (command.type === "asset.import") imports.push(command);
+ };
+ page.on("request", recordImport);
+ const messagesBeforeUpload = (await api(path)).messages;
+ try {
+ await panel.getByLabel("选择对话参考文件", { exact: true }).setInputFiles({
+ name: "story-reference.txt",
+ mimeType: "text/plain",
+ buffer: Buffer.from("A private reference for the first session"),
+ });
+ await until(() => uploadRequests.length, Boolean, "Reference upload starts");
+ for (const mode of ["agent", "canvas"]) {
+ await page.getByTestId(`workspace-mode-${mode}`).click();
+ await until(
+ () => page.locator(".cw-workspace").getAttribute("data-workspace-mode"),
+ (value) => value === mode,
+ `Upload-time switch to ${mode} (page errors: ${errors.join(", ")})`,
+ );
+ const current = await api(path);
+ assert.equal(current.conversationId, first.conversationId);
+ assert.deepEqual(current.messages, messagesBeforeUpload);
+ assert.equal(current.assets.length, 0, "unacknowledged upload stays pending");
+ }
+ } finally {
+ releaseUpload();
+ await page.unroute(uploadPath, holdUpload);
+ }
const draft = await until(
() => api(path),
(value) => value.draft.includes("海边草稿") && value.assets.length === 1,
"Reference draft must persist",
);
+ page.off("request", recordImport);
+ assert.deepEqual(uploadRequests.map(({ method }) => method), ["PUT"]);
+ assert.equal(imports.length, 1);
+ assert.equal(imports[0].projectId, projectId);
+ assert.equal(imports[0].payload.uploadHandle, uploadRequests[0].url.split("/").at(-1));
+ const imported = (await api(`/creation/projects/${projectId}`)).assets.find(
+ (asset) => asset.name === "story-reference.txt",
+ );
+ assert.equal(draft.assets[0].id, imported.id);
+ assert.equal(draft.conversationId, first.conversationId);
+ assert.deepEqual(draft.messages, messagesBeforeUpload);
await create.click();
const second = await until(
() => api(path),
@@ -306,13 +356,13 @@ try {
);
await page.mouse.move(x, y);
await page.mouse.down();
- await page.mouse.move(x - 240, y, { steps: 5 });
+ await page.mouse.move(x + 240, y, { steps: 5 });
await page.mouse.up();
const wideRows = await rows();
const wideBounds = await resize.boundingBox();
await page.mouse.move(wideBounds.x + wideBounds.width / 2, y);
await page.mouse.down();
- await page.mouse.move(x + 170, y, { steps: 5 });
+ await page.mouse.move(x - 170, y, { steps: 5 });
await page.mouse.up();
assert.ok(await rows() > wideRows, "Suggested reply buttons should wrap as the panel narrows");
await resize.press("End");
@@ -366,7 +416,9 @@ try {
await editor.fill("建议回复验收");
await send.click();
await choiceButton.waitFor();
- await panel.getByLabel("选择对话参考文件", { exact: true }).setInputFiles({
+ const chooser = page.waitForEvent("filechooser");
+ await panel.getByRole("button", { name: "上传参考", exact: true }).click();
+ await (await chooser).setFiles({
name: "shot-notes.txt", mimeType: "text/plain", buffer: Buffer.from("Storyboard notes"),
});
const attached = await until(() => api(path), (value) => value.assets.length === 1, "Save attachment");
diff --git a/tests/browser/bilingual_defaults.mjs b/tests/browser/bilingual_defaults.mjs
index be644a3f6..5cc04524e 100644
--- a/tests/browser/bilingual_defaults.mjs
+++ b/tests/browser/bilingual_defaults.mjs
@@ -20,6 +20,13 @@ try {
const projectName = page.locator(".cw-project-name");
const welcome = page.locator("#welcome-language");
const setup = page.locator("dialog.cw-welcome");
+ async function checkModeChoices(groupName, chat, canvas) {
+ const choices = setup.getByRole("group", { name: groupName, exact: true });
+ for (const label of [chat, canvas]) {
+ assert.ok(await choices.getByRole("button", { name: label, exact: true }).isVisible());
+ }
+ assert.equal(await setup.getByRole("checkbox").count(), 0);
+ }
await page.route("**/assistant/runtimes/default/status", (route) => route.fulfill({ json: {
id: "default", label: "Default Agent", group: "default", modelSource: "settings",
modelOverride: false, available: true, status: "ready",
@@ -27,11 +34,13 @@ try {
await projectName.filter({ hasText: /^未命名项目$/ }).waitFor();
await page.getByRole("heading", { name: "欢迎使用 OpenDirector" }).waitFor();
assert.ok(await page.getByRole("button", { name: "开始设置" }).isVisible());
+ assert.equal(await setup.getByRole("button", { name: "进入画布", exact: true }).count(), 0);
const chineseCanvas = page.getByRole("img", { name: "OpenDirector 画布截图:六个分镜和下方的剪辑时间线" });
await chineseCanvas.evaluate((element) => element.decode());
const chineseCanvasSrc = await chineseCanvas.getAttribute("src");
await welcome.selectOption("en-US");
await page.getByRole("heading", { name: "Welcome to OpenDirector" }).waitFor();
+ assert.equal(await setup.getByRole("radio").count(), 0);
const englishCanvas = page.getByRole("img", { name: "OpenDirector canvas screenshot with six storyboard shots and the editing timeline below" });
await englishCanvas.evaluate((element) => element.decode());
assert.notEqual(await englishCanvas.getAttribute("src"), chineseCanvasSrc);
@@ -45,8 +54,15 @@ try {
await setup.getByText("OpenDirector needs a configured language model to understand what you want to create, plan the work, and use tools.", { exact: true }).waitFor();
await setup.getByRole("button", { name: "Set up a language model", exact: true }).click();
await page.getByRole("button", { name: /^fixture-agent/ }).click();
- await page.getByRole("heading", { name: "What do you want to do first?" }).waitFor();
+ await page.getByRole("heading", { name: "Choose how to create" }).waitFor();
+ await welcome.selectOption("zh-CN");
+ await checkModeChoices("创作方式", "对话创作", "画布创作");
+ await setup.getByText(/图片、视频和音频模型可以在对话过程中按需配置/).waitFor();
+ await welcome.selectOption("en-US");
+ await checkModeChoices("Creation mode", "Create with chat", "Create on canvas");
+ await setup.getByText(/set up an image or video model for your first canvas/).waitFor();
await welcome.selectOption("zh-CN");
+ await setup.getByRole("button", { name: "画布创作", exact: true }).click();
const videoTask = setup.getByRole("checkbox", { name: "做一段视频" });
await videoTask.check();
await setup.getByRole("heading", { name: "配置视频模型", exact: true }).waitFor();
@@ -71,7 +87,9 @@ try {
await page.locator(`html[lang="${locale}"]`).waitFor({ state: "attached" });
};
const showChat = async () => {
- await page.locator(".cw-chat-button").click();
+ const toggle = page.locator(".cw-chat-button");
+ if (await toggle.getAttribute("aria-expanded") === "true") await toggle.click();
+ await toggle.click();
await page.locator('#canvas-assistant [contenteditable="true"]:focus').waitFor();
};
const heading = page.locator(".cw-assistant-header h2");
diff --git a/tests/browser/canvas_creation.mjs b/tests/browser/canvas_creation.mjs
new file mode 100644
index 000000000..9d530edd4
--- /dev/null
+++ b/tests/browser/canvas_creation.mjs
@@ -0,0 +1,7 @@
+/** Create a node through the same tool and type picker used on the canvas. */
+export async function addCanvasNode(page, label) {
+ const toolbar = page.getByRole("toolbar", { name: /^(Canvas creation tools|画布创作工具)$/ });
+ await toolbar.getByRole("button", { name: /^(Add node|添加节点)$/ }).click();
+ const menu = page.getByRole("menu", { name: /^(New node|新建节点)$/ });
+ await menu.getByRole("menuitem", { name: label, exact: true }).click();
+}
diff --git a/tests/browser/canvas_crop.mjs b/tests/browser/canvas_crop.mjs
index cada38470..28023fb03 100644
--- a/tests/browser/canvas_crop.mjs
+++ b/tests/browser/canvas_crop.mjs
@@ -1,3 +1,4 @@
+import { addCanvasNode } from "./canvas_creation.mjs";
import { chooseGenerationModel } from "./model_picker.mjs";
/** Real image/layer editing against the isolated creation fixture; no model calls. */
import assert from "node:assert/strict";
@@ -63,9 +64,9 @@ async function saved() {
await page.getByText("Saved on this device", { exact: true }).waitFor();
}
async function menu(itemId, action) {
- await page
- .locator(".react-flow__pane")
- .click({ position: { x: 1400, y: 800 } });
+ const pane = page.locator(".react-flow__pane");
+ const canvas = await pane.boundingBox();
+ await pane.click({ position: { x: canvas.width - 200, y: canvas.height - 200 } });
await page.keyboard.press("Escape");
await page
.locator(`.react-flow__node[data-id="${itemId}"] .cw-node-title`)
@@ -86,10 +87,7 @@ async function apply() {
try {
await page.goto(`${base}/ai-tool/ai-canvas/${projectId}`);
await saved();
- await page
- .getByRole("toolbar", { name: "Canvas creation tools" })
- .getByRole("button", { name: "Add Image", exact: true })
- .click();
+ await addCanvasNode(page, "Image");
await chooseGenerationModel(page, { label: "fixture-image" });
await page
.getByRole("textbox", { name: "Prompt", exact: true })
diff --git a/tests/browser/canvas_keyboard.mjs b/tests/browser/canvas_keyboard.mjs
index b5f3d178d..8dd3cec70 100644
--- a/tests/browser/canvas_keyboard.mjs
+++ b/tests/browser/canvas_keyboard.mjs
@@ -1,3 +1,4 @@
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE ?? "playwright-core");
@@ -28,8 +29,7 @@ try {
await page.goto(`${base}/ai-tool/ai-canvas/${id}`);
const nodes = page.locator(".react-flow__node");
const selected = page.locator(".react-flow__node.selected");
- const addVideo = page.getByRole("button", { name: "添加视频", exact: true });
- await addVideo.click();
+ await addCanvasNode(page, "视频");
await selected.waitFor();
const source = await selected.getAttribute("data-id");
await page.keyboard.press("Control+c");
@@ -41,7 +41,7 @@ try {
await page.waitForFunction(() => document.querySelectorAll(".react-flow__node").length === 1);
assert.equal(await nodes.first().getAttribute("data-id"), source);
- await addVideo.click();
+ await addCanvasNode(page, "视频");
await selected.waitFor();
await page.keyboard.press("Backspace");
await page.waitForFunction(() => document.querySelectorAll(".react-flow__node").length === 1);
diff --git a/tests/browser/canvas_layers.mjs b/tests/browser/canvas_layers.mjs
index d08de6809..b01444406 100644
--- a/tests/browser/canvas_layers.mjs
+++ b/tests/browser/canvas_layers.mjs
@@ -1,3 +1,4 @@
+import { addCanvasNode } from "./canvas_creation.mjs";
import { chooseGenerationModel } from "./model_picker.mjs";
/** Real image/layer editing against the isolated creation fixture; no model calls. */
import assert from "node:assert/strict";
@@ -74,10 +75,7 @@ try {
await page.goto(`${base}/ai-tool/ai-canvas/${projectId}`);
await page.getByText("Saved on this device", { exact: true }).waitFor();
if (generated) {
- await page
- .getByRole("toolbar", { name: "Canvas creation tools" })
- .getByRole("button", { name: "Add Image", exact: true })
- .click();
+ await addCanvasNode(page, "Image");
await chooseGenerationModel(page, { label: "fixture-image" });
await page
.getByRole("textbox", { name: "Prompt", exact: true })
diff --git a/tests/browser/canvas_node_titles.mjs b/tests/browser/canvas_node_titles.mjs
index d254027c0..828540fc3 100644
--- a/tests/browser/canvas_node_titles.mjs
+++ b/tests/browser/canvas_node_titles.mjs
@@ -1,4 +1,5 @@
/** Isolated API/Vite: hidden sources reserve default node numbers. */
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
const { chromium } = await import(
process.env.PLAYWRIGHT_MODULE ?? "playwright-core"
@@ -69,9 +70,6 @@ try {
await page.unroute(bootstrap);
await page.goto(`${base}/ai-tool/ai-canvas/${fixture.id}`);
await page.getByText("已保存到本机", { exact: true }).waitFor();
- const add = page
- .getByRole("toolbar", { name: "画布创作工具" })
- .getByRole("button", { name: "添加图片", exact: true });
const savedTitle = async (title) => {
const deadline = Date.now() + 15000;
while (Date.now() < deadline) {
@@ -91,10 +89,11 @@ try {
}
throw new Error(`Default title was not persisted: ${title}`);
};
- await add.click();
+ await addCanvasNode(page, "图片");
await savedTitle("图片 5");
// Two requests in one browser callback must use sequential applied state.
- await add.evaluate((button) => {
+ await page.getByRole("button", { name: "添加节点", exact: true }).click();
+ await page.getByRole("menuitem", { name: "图片", exact: true }).evaluate((button) => {
button.click();
button.click();
});
@@ -127,7 +126,7 @@ try {
.count(),
0,
);
- await add.click();
+ await addCanvasNode(page, "图片");
await savedTitle("图片 9");
assert.deepEqual(errors, []);
console.log(
diff --git a/tests/browser/canvas_notifications.mjs b/tests/browser/canvas_notifications.mjs
index 9b1781c5f..1f864da71 100644
--- a/tests/browser/canvas_notifications.mjs
+++ b/tests/browser/canvas_notifications.mjs
@@ -1,4 +1,5 @@
/** Isolated UI regression: missing models and independent notification lifetimes. */
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
const { chromium } = await import(
process.env.PLAYWRIGHT_MODULE ?? "playwright-core"
@@ -57,10 +58,7 @@ try {
// Without a configured model, submitting is disabled and the button itself
// explains where to add one; the draft prompt is kept.
for (const kind of ["图片", "视频", "音频"]) {
- await page
- .getByRole("toolbar", { name: "画布创作工具" })
- .getByRole("button", { name: `添加${kind}`, exact: true })
- .click();
+ await addCanvasNode(page, kind);
const prompt = page.getByRole("textbox", {
name: "生成提示词",
exact: true,
diff --git a/tests/browser/canvas_progressive_load.mjs b/tests/browser/canvas_progressive_load.mjs
index 1c5ae22d5..e2e6b5767 100644
--- a/tests/browser/canvas_progressive_load.mjs
+++ b/tests/browser/canvas_progressive_load.mjs
@@ -148,8 +148,33 @@ async function verifyLocale(browser, locale) {
await decoded(fixture.failed);
// A late read belongs to its project and cannot appear in another one.
+ const otherProject = await snapshot(fixture.b.id);
+ const otherAssetId = assetOf(otherProject, fixture.other);
+ const otherAsset = otherProject.assets.find(asset => asset.id === otherAssetId);
+ const contentPath = `/api/creation/projects/${fixture.b.id}/assets/${otherAssetId}/content`;
+ const read = page.waitForResponse(response => new URL(response.url()).pathname === contentPath);
await open(fixture.b);
await decoded(fixture.other);
+ assert.equal((await read).status(), 200);
+ // The open project supplies a stable asset key to both the node and the modal.
+ const source = await page.evaluate(async ({ projectId, nodeId }) => {
+ const { workspaceProjection } = await import("/src/backend/workspace.ts");
+ return workspaceProjection(projectId).baseline.nodes.find(node => node.id === nodeId).data.src;
+ }, { projectId: fixture.b.id, nodeId: fixture.other });
+ assert.equal(source, `opendirector-asset://${fixture.b.id}/${otherAssetId}`);
+ await node(fixture.other).locator("img.cw-image-preview").click();
+ await page.locator(`[data-node-id="${fixture.other}"] [data-action="preview"]`).click();
+ const preview = page.locator("dialog.cw-preview");
+ const displayed = await preview.locator("img").evaluate(async image => {
+ await image.decode();
+ const bytes = await (await fetch(image.currentSrc)).arrayBuffer();
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
+ return { protocol: new URL(image.currentSrc).protocol, width: image.naturalWidth, height: image.naturalHeight,
+ fingerprint: "sha256:" + Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("") };
+ });
+ assert.deepEqual(displayed, { protocol: "blob:", width: 96, height: 96, fingerprint: otherAsset.fingerprint });
+ await page.keyboard.press("Escape");
+ await preview.waitFor({ state: "hidden" });
release.resolve();
await page.waitForTimeout(250);
assert.equal(await node(fixture.delayed).count(), 0);
diff --git a/tests/browser/canvas_reference_sources.mjs b/tests/browser/canvas_reference_sources.mjs
index af07b2ed4..51b2e4400 100644
--- a/tests/browser/canvas_reference_sources.mjs
+++ b/tests/browser/canvas_reference_sources.mjs
@@ -235,6 +235,17 @@ try {
fixture.source,
);
await page.locator(".react-flow__edge").first().waitFor();
+ // The edge is optimistic. Start the next mention after the first reference
+ // is stored and the picker has returned the caret to the prompt.
+ await page.waitForFunction(async ({ projectId, sourceId }) => {
+ if (document.activeElement?.getAttribute("aria-label") !== "生成提示词") return false;
+ const response = await fetch(`/api/creation/projects/${projectId}`, {
+ headers: { "X-OpenDirector-Request": "1" },
+ });
+ if (!response.ok) throw new Error(`Project read failed: ${response.status}`);
+ const project = await response.json();
+ return project.references.some((ref) => ref.active && ref.source.id === sourceId);
+ }, { projectId: fixture.id, sourceId: fixture.source }, { polling: 100 });
await editor.press("End");
await editor.press("Enter");
await editor.pressSequentially("@");
diff --git a/tests/browser/canvas_selection_history.mjs b/tests/browser/canvas_selection_history.mjs
index 5eb44b9d6..e6ec98b79 100644
--- a/tests/browser/canvas_selection_history.mjs
+++ b/tests/browser/canvas_selection_history.mjs
@@ -1,4 +1,5 @@
/** Selection owns canvas shortcuts; only explicit editing owns text input. */
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
import { chooseGenerationModel } from "./model_picker.mjs";
const { chromium } = await import(
@@ -72,10 +73,7 @@ try {
await saved();
return snapshot;
}
- await page
- .getByRole("toolbar", { name: "画布创作工具" })
- .getByRole("button", { name: `添加${kind}`, exact: true })
- .click();
+ await addCanvasNode(page, kind);
const original = (await count(1)).canvasItems[0];
const specId =
original.binding.draftSpec?.id ?? original.binding.objectRef?.id;
diff --git a/tests/browser/canvas_switch.mjs b/tests/browser/canvas_switch.mjs
index 8a7d3045f..faff75f1a 100644
--- a/tests/browser/canvas_switch.mjs
+++ b/tests/browser/canvas_switch.mjs
@@ -62,8 +62,34 @@ try {
await page.getByText("Saved on this device", { exact: true }).waitFor();
await picker.click({ trial: true });
};
- await page.goto(`${web}/ai-tool/ai-canvas/${projects[0].id}`);
- await ready(projects[0]);
+ // A slow default-open chat must not steal focus and dismiss the project picker.
+ let releaseAssistant;
+ const assistantGate = new Promise(resolve => { releaseAssistant = resolve; });
+ const assistantPath = `**/creation/projects/${projects[0].id}/assistant`;
+ await page.route(assistantPath, async route => {
+ const response = await route.fetch();
+ await assistantGate;
+ await route.fulfill({ response });
+ }, { times: 1 });
+ const releaseDeadline = setTimeout(() => releaseAssistant(), 15000);
+ try {
+ await page.goto(`${web}/ai-tool/ai-canvas/${projects[0].id}`);
+ await ready(projects[0]);
+ await picker.click();
+ const target = page.getByRole("menuitemradio", { name: projects[1].name, exact: true });
+ await target.waitFor();
+ releaseAssistant();
+ await page.waitForFunction(() => document.querySelector('#canvas-assistant [role="textbox"]')?.isContentEditable);
+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
+ assert.equal(await picker.getAttribute("aria-expanded"), "true", "chat loading must keep the project picker open");
+ assert.equal(await page.locator('.cw-project-search input').evaluate(element => element === document.activeElement), true);
+ await target.click({ trial: true });
+ await page.keyboard.press("Escape");
+ } finally {
+ clearTimeout(releaseDeadline);
+ releaseAssistant();
+ await page.unroute(assistantPath);
+ }
const samples = [];
for (let index = 0; index < 12; index++) {
const target = projects[(index + 1) % 2];
diff --git a/tests/browser/canvas_text_markdown.mjs b/tests/browser/canvas_text_markdown.mjs
index 7705c1a2c..0b620cf4f 100644
--- a/tests/browser/canvas_text_markdown.mjs
+++ b/tests/browser/canvas_text_markdown.mjs
@@ -128,9 +128,12 @@ async function checkTextNode(resizeZoom) {
// Normal selection can still fit before the next resize begins.
await page.locator(".react-flow__pane").click({ position: { x: 20, y: 80 } });
const fitBox = await node.boundingBox();
- await page.mouse.move(1000, 800);
+ const canvas = await page.locator(".react-flow__pane").boundingBox();
+ const panStart = { x: canvas.x + canvas.width / 2, y: canvas.y + canvas.height * 0.8 };
+ await page.mouse.move(panStart.x, panStart.y);
await page.mouse.down({ button: "middle" });
- await page.mouse.move(1000 + 100 - fitBox.x, 800 + 140 - fitBox.y, { steps: 8 });
+ await page.mouse.move(panStart.x + canvas.x + 100 - fitBox.x,
+ panStart.y + canvas.y + 140 - fitBox.y, { steps: 8 });
await page.mouse.up({ button: "middle" });
const beforeFit = await page.locator(".react-flow__viewport").evaluate((element) => element.style.transform);
await node.click({ position: { x: 30, y: 40 } });
diff --git a/tests/browser/canvas_wheel.mjs b/tests/browser/canvas_wheel.mjs
index cc6405362..70797b130 100644
--- a/tests/browser/canvas_wheel.mjs
+++ b/tests/browser/canvas_wheel.mjs
@@ -1,4 +1,5 @@
-/** Isolated fixture only: modified wheels belong to the canvas, never page UI. */
+/** Isolated fixture only: modified wheels zoom only within the canvas region. */
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
const { chromium } = await import(
process.env.PLAYWRIGHT_MODULE ?? "playwright-core"
@@ -63,17 +64,28 @@ try {
);
});
const metrics = () =>
- page.evaluate(() => ({
- zoom: new DOMMatrix(
+ page.evaluate(() => {
+ const viewport = new DOMMatrix(
getComputedStyle(document.querySelector(".react-flow__viewport"))
.transform,
- ).a,
- width: window.innerWidth,
- ratio: window.devicePixelRatio,
- scale: window.visualViewport.scale,
- }));
+ );
+ return {
+ zoom: viewport.a,
+ x: viewport.e,
+ y: viewport.f,
+ width: window.innerWidth,
+ ratio: window.devicePixelRatio,
+ scale: window.visualViewport.scale,
+ };
+ });
const controls = [];
- async function zoomWheel(locator, name) {
+ const outsideCanvas = [];
+ async function modifiedWheel(locator, name, zoomCanvas = true) {
+ assert.equal(
+ await locator.evaluate((element) => Boolean(element.closest(".cw-canvas-region"))),
+ zoomCanvas,
+ `${name}: verify the wheel target's region`,
+ );
await locator.hover();
await page.waitForTimeout(100);
const before = await metrics();
@@ -96,50 +108,69 @@ try {
}
await page.waitForTimeout(180);
const after = await metrics();
- assert.ok(after.zoom > before.zoom, `${name}: wheel must zoom the canvas`);
- assert.deepEqual(
- { ...after, zoom: before.zoom },
- before,
- `${name}: page UI must stay fixed`,
- );
+ if (zoomCanvas) {
+ assert.ok(after.zoom > before.zoom, `${name}: wheel must zoom the canvas`);
+ assert.deepEqual(
+ { ...after, zoom: before.zoom, x: before.x, y: before.y },
+ before,
+ `${name}: page UI must stay fixed`,
+ );
+ } else {
+ assert.deepEqual(
+ { zoom: after.zoom, x: after.x, y: after.y },
+ { zoom: before.zoom, x: before.x, y: before.y },
+ `${name}: wheel must preserve the canvas viewport`,
+ );
+ }
const prevented = await page.evaluate(
(count) => window.__modifiedWheels.slice(count),
count,
);
- assert.ok(
- prevented.length && prevented.every(Boolean),
- `${name}: native default must be cancelled`,
- );
+ if (zoomCanvas) {
+ assert.ok(
+ prevented.length && prevented.every(Boolean),
+ `${name}: native default must be cancelled`,
+ );
+ }
// Meta+wheel follows the same boundary without changing ordinary scrolling.
- assert.equal(
- await locator.evaluate((element) => {
- const rect = element.getBoundingClientRect();
- return !element.dispatchEvent(
- new WheelEvent("wheel", {
- bubbles: true,
- cancelable: true,
- deltaY: 120,
- metaKey: true,
- clientX: rect.left + rect.width / 2,
- clientY: rect.top + rect.height / 2,
- }),
- );
- }),
- true,
- );
- await page.waitForFunction(
- (zoom) =>
- Math.abs(
- new DOMMatrix(
- getComputedStyle(document.querySelector(".react-flow__viewport"))
- .transform,
- ).a - zoom,
- ) < 0.001,
- before.zoom,
- );
- controls.push(name);
+ const metaPrevented = await locator.evaluate((element) => {
+ const rect = element.getBoundingClientRect();
+ return !element.dispatchEvent(
+ new WheelEvent("wheel", {
+ bubbles: true,
+ cancelable: true,
+ deltaY: 120,
+ metaKey: true,
+ clientX: rect.left + rect.width / 2,
+ clientY: rect.top + rect.height / 2,
+ }),
+ );
+ });
+ if (zoomCanvas) {
+ assert.equal(metaPrevented, true);
+ await page.waitForFunction(
+ (zoom) =>
+ Math.abs(
+ new DOMMatrix(
+ getComputedStyle(document.querySelector(".react-flow__viewport"))
+ .transform,
+ ).a - zoom,
+ ) < 0.001,
+ before.zoom,
+ );
+ controls.push(name);
+ } else {
+ await page.waitForTimeout(180);
+ const afterMeta = await metrics();
+ assert.deepEqual(
+ { zoom: afterMeta.zoom, x: afterMeta.x, y: afterMeta.y },
+ { zoom: before.zoom, x: before.x, y: before.y },
+ `${name}: Meta+wheel must preserve the canvas viewport`,
+ );
+ outsideCanvas.push(name);
+ }
}
- await zoomWheel(
+ await modifiedWheel(
page.getByRole("toolbar", { name: "画布创作工具" }),
"left toolbar",
);
@@ -159,21 +190,18 @@ try {
await material.waitFor();
await material.click();
await page.getByRole("toolbar", { name: "节点操作", exact: true }).waitFor();
- await zoomWheel(
+ await modifiedWheel(
page.getByRole("toolbar", { name: "节点操作", exact: true }),
"node toolbar",
);
- await page
- .getByRole("toolbar", { name: "画布创作工具" })
- .getByRole("button", { name: "添加视频", exact: true })
- .click();
+ await addCanvasNode(page, "视频");
const editor = page.getByRole("textbox", { name: "生成提示词", exact: true });
await editor.fill(
Array.from({ length: 60 }, (_, i) => `镜头${i + 1}:保持动作与镜头。`).join(
"\n",
),
);
- await zoomWheel(editor, "node composer");
+ await modifiedWheel(editor, "node composer");
await editor.evaluate((element) => (element.scrollTop = 0));
const originalZoom = (await metrics()).zoom;
await editor.hover();
@@ -188,7 +216,7 @@ try {
exact: true,
});
await parameters.waitFor();
- await zoomWheel(parameters, "portaled parameters");
+ await modifiedWheel(parameters, "portaled parameters", false);
await parameters
.getByRole("button", { name: "关闭参数", exact: true })
.evaluate((element) => element.click());
@@ -204,18 +232,20 @@ try {
await page
.getByRole("dialog", { name: "展开的节点会话框", exact: true })
.waitFor();
- await zoomWheel(editor, "expanded composer");
+ await modifiedWheel(editor, "expanded composer");
await page.getByRole("button", { name: "收起会话框", exact: true }).click();
- await page.locator(".cw-chat-button").click();
- await zoomWheel(
+ const chatToggle = page.locator(".cw-chat-button");
+ if (await chatToggle.getAttribute("aria-expanded") === "false") await chatToggle.click();
+ await modifiedWheel(
page.locator('.cw-assistant-composer [role="textbox"]'),
"assistant sidebar",
+ false,
);
await page.getByRole("button", { name: "收起 AI 对话", exact: true }).click();
await page.getByRole("button", { name: "资产库", exact: true }).click();
const library = page.getByRole("dialog", { name: "资产库", exact: true });
await library.waitFor();
- await zoomWheel(library, "asset library dialog");
+ await modifiedWheel(library, "asset library dialog", false);
await page.getByRole("button", { name: "关闭资产库", exact: true }).click();
// The same trusted wheel still changes React Flow zoom over real canvas areas.
async function canvasWheel(point, name) {
@@ -270,8 +300,9 @@ try {
JSON.stringify({
isolated: true,
controlsZoomCanvasOnly: controls,
+ outsideCanvasRetainsViewport: outsideCanvas,
canvasAndNodeZoom: true,
- nativePageZoomPrevented: true,
+ nativePageZoomPreventedOnCanvas: true,
ordinaryEditorScroll: true,
errors,
}),
diff --git a/tests/browser/chat_local_editing.mjs b/tests/browser/chat_local_editing.mjs
new file mode 100644
index 000000000..e50e5ef2f
--- /dev/null
+++ b/tests/browser/chat_local_editing.mjs
@@ -0,0 +1,195 @@
+/** A new chat project can import, reference, and edit local media without sending a turn. */
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { readFile } from "node:fs/promises";
+import { launchBrowser } from "./engine.mjs";
+import { playDownloadedMp4 } from "./play_downloaded_mp4.mjs";
+
+const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179";
+const headers = { "X-OpenDirector-Request": "1", "Content-Type": "application/json" };
+async function api(path, body) {
+ const response = await fetch(base + "/api" + path, {
+ headers, ...(body && { method: "POST", body: JSON.stringify(body) }),
+ });
+ assert.ok(response.ok, await response.clone().text());
+ return response.json();
+}
+assert.ok((await api("/creation-test-health")).isolated);
+const models = await api("/model-configs");
+const projectId = crypto.randomUUID();
+const root = "/creation/projects/" + projectId;
+const state = () => api(root);
+const conversation = () => api(root + "/assistant");
+assert.equal((await api(root + "/commands", {
+ projectId, commandId: crypto.randomUUID(), type: "project.create",
+ payload: { name: "Local editing " + projectId.slice(0, 8) },
+})).status, "applied");
+const name = "Local shot.mp4";
+const buffer = await readFile(new URL("../fixtures/timeline-text/visual-a.mp4", import.meta.url));
+const fingerprint = "sha256:" + createHash("sha256").update(buffer).digest("hex");
+const browser = await launchBrowser();
+try {
+ const page = await browser.newPage({ locale: "en-US", viewport: { width: 390, height: 844 } });
+ page.setDefaultTimeout(20000);
+ const errors = [], mutations = [];
+ page.on("pageerror", error => errors.push(error.message));
+ page.on("request", request => {
+ if (request.method() === "POST" && /\/assistant\/turns$|\/model-configs(?:\/batch)?$/.test(request.url())) {
+ mutations.push(request.url());
+ }
+ });
+ // Run creation_server.py --empty-models for a genuinely empty model database.
+ // Shared CI services seed fixture models for other journeys. A fresh service with
+ // an empty catalog exercises the same path without any network substitution.
+ if (models.length) {
+ await page.route("**/api/model-configs", route => route.request().method() === "GET"
+ ? route.fulfill({ json: [] }) : route.continue());
+ }
+ // A returning creator can edit local media after the model configuration is removed.
+ await page.addInitScript(() => localStorage.setItem("opendirector.modelSetup.v1", "dismissed"));
+ await page.goto(base + "/ai-tool/ai-canvas/" + projectId);
+ const mode = page.getByTestId("workspace-mode-agent");
+ await mode.click();
+ const assets = page.locator(".cw-creation-assets");
+ const openAssets = () => page.locator("button[data-chat-project-assets]").click();
+ const draft = page.locator("#canvas-assistant").getByRole("textbox", { name: "Message content", exact: true });
+ await draft.fill("Use this clip");
+ await openAssets();
+ const imported = page.waitForResponse(response => response.url().endsWith("/commands") &&
+ response.request().postDataJSON()?.type === "asset.import");
+ const uploadPath = "**/api" + root + "/uploads/*";
+ const firstUpload = page.waitForRequest(request =>
+ request.method() === "PUT" && request.url().includes(root + "/uploads/"));
+ let release;
+ const holdFirstUpload = new Promise(resolve => { release = resolve; });
+ let uploadCount = 0;
+ await page.route(uploadPath, async route => {
+ if (route.request().method() !== "PUT") return route.continue();
+ if (++uploadCount === 1) {
+ await holdFirstUpload;
+ return route.continue();
+ }
+ await route.fulfill({ status: 422, json: { detail: "Controlled upload refusal" } });
+ });
+ try {
+ await assets.locator("input[data-project-import]").setInputFiles(
+ [name, "Rejected shot.mp4"].map(name => ({ name, mimeType: "video/mp4", buffer })),
+ );
+ await firstUpload;
+ await page.getByTestId("workspace-mode-canvas").click();
+ await assets.waitFor({ state: "hidden" });
+ await mode.click();
+ await assets.getByRole("button", { name: "Importing media…", exact: true }).waitFor();
+ assert.equal(uploadCount, 1);
+ release();
+ await assets.getByRole("alert").filter({ hasText: "Rejected shot.mp4" }).waitFor();
+ assert.equal(uploadCount, 2);
+ } finally {
+ release();
+ await page.unroute(uploadPath);
+ }
+ const receipt = await (await imported).json();
+ assert.equal(receipt.status, "applied");
+ const initial = await state();
+ assert.deepEqual(initial.assets.map(asset => asset.name), [name]);
+ const [asset] = initial.assets;
+ assert.equal(asset.fingerprint, fingerprint);
+ assert.deepEqual(initial.canvasItems, []);
+ assert.deepEqual(initial.jobs, []);
+ const reference = assets.locator('[data-reference-asset="' + asset.id + '"]');
+ await reference.waitFor();
+ assert.match(await assets.getByRole("alert").innerText(), /Rejected shot\.mp4/);
+ const search = assets.getByRole("textbox", { name: "Find assets" });
+ await search.fill("no such video");
+ await reference.waitFor({ state: "hidden" });
+ await search.fill("Local shot");
+ await reference.click();
+ await assets.waitFor({ state: "hidden" });
+ const deadline = Date.now() + 10000;
+ let chat;
+ do {
+ chat = await conversation();
+ if (chat.assets?.some(record => record.id === asset.id)) break;
+ assert.ok(Date.now() < deadline, "the referenced asset must be persisted to the unsent draft");
+ await new Promise(resolve => setTimeout(resolve, 80));
+ } while (true);
+ assert.deepEqual(chat.messages, []);
+ const part = chat.draftContent.find(part => part.type === "reference");
+ assert.equal(part.assetId, asset.id);
+ assert.equal(part.fingerprint, fingerprint);
+ assert.equal(part.binding, "asset");
+ assert.equal((await state()).canvasItems.length, 0);
+
+ await page.setViewportSize({ width: 1540, height: 960 });
+ await openAssets();
+ const retryOpen = assets.getByRole("button", { name: "Retry opening the new timeline" });
+ const projection = new URL("/api" + root + "/canvas", base).href;
+ const rejectOpening = async route => {
+ if (await retryOpen.isVisible()) {
+ await route.fulfill({ status: 503, json: { detail: "Opening interrupted" } });
+ } else {
+ await route.continue();
+ }
+ };
+ await page.route(projection, rejectOpening);
+ await assets.locator("button[data-create-timeline]").click();
+ await assets.getByRole("alert").filter({ hasText: "Opening interrupted" }).waitFor();
+ const created = await state();
+ assert.equal(created.editorDocuments.length, 1);
+ assert.equal(created.canvasItems.length, 1);
+ await page.unroute(projection, rejectOpening);
+ await retryOpen.click();
+ const timeline = page.locator(".cw-timeline-dialog");
+ const add = timeline.locator(".cw-timeline-library-item").getByRole("button", { name, exact: true });
+ await add.click();
+ const clip = timeline.locator(".cw-timeline-clip");
+ await clip.click();
+ await timeline.getByLabel("Playback speed").selectOption("2");
+ await timeline.getByRole("button", { name: "Apply edits", exact: true }).click();
+ await timeline.waitFor({ state: "hidden" });
+ assert.equal(await mode.getAttribute("aria-pressed"), "true");
+ const saved = await state();
+ const [item] = saved.canvasItems;
+ const [document] = saved.editorDocuments;
+ assert.deepEqual(saved.editorDocuments.map(editor => editor.id), [created.editorDocuments[0].id]);
+ assert.deepEqual(saved.canvasItems.map(node => node.id), [created.canvasItems[0].id]);
+ assert.equal(item.kind, "timeline");
+ assert.equal(item.binding.objectRef.id, document.id);
+ const [savedClip] = document.data.tracks[0].clips;
+ assert.equal(savedClip.resource.asset.assetId, asset.id);
+ assert.equal(savedClip.resource.asset.fingerprint, fingerprint);
+ assert.equal(savedClip.speed, 2);
+ await page.reload();
+ await openAssets();
+ await assets.getByRole("tab", { name: /^Timelines/ }).click();
+ await assets.locator('[data-open-timeline="' + item.id + '"]').click();
+ await clip.click();
+ assert.equal(await timeline.getByLabel("Playback speed").inputValue(), "2");
+ assert.deepEqual((await state()).editorDocuments, [document]);
+ await timeline.getByRole("button", { name: "Render MP4", exact: true }).click();
+ const download = timeline.getByRole("button", { name: "Download MP4", exact: true });
+ await download.waitFor({ timeout: 120000 });
+ const decoded = await playDownloadedMp4(page, download);
+ assert.equal(decoded.width, document.data.width);
+ assert.equal(decoded.height, document.data.height);
+ assert.ok(Math.abs(decoded.duration - (savedClip.outPoint - savedClip.inPoint) / savedClip.speed) < 0.12);
+ const [r, g, b] = decoded.pixel;
+ assert.ok(Math.max(r, b) > 100 && Math.min(r, b) < 32 && g < 32, "the solid-color imported video must play");
+ await timeline.getByRole("button", { name: "Add rendered video to canvas", exact: true }).click();
+ await timeline.getByRole("button", { name: "Added to canvas", exact: true }).waitFor();
+ const [output] = (await state()).assets.filter(a => a.provenance.source === "rendered");
+ assert.equal(output.provenance.editorDocumentId, document.id);
+ assert.equal(output.fingerprint, decoded.fingerprint);
+ await timeline.getByRole("button", { name: "Close editor", exact: true }).click();
+ await timeline.waitFor({ state: "hidden" });
+ const returned = await conversation();
+ assert.equal(returned.conversationId, chat.conversationId);
+ assert.deepEqual(returned.draftContent, chat.draftContent);
+ assert.deepEqual(returned.messages, []);
+ assert.deepEqual((await state()).jobs, []);
+ assert.deepEqual(mutations, []);
+ assert.deepEqual(errors, []);
+ console.log(`PASS local chat editing: ${projectId}, imported asset ${asset.id}, reopened timeline ${document.id}; ${models.length ? "empty catalog simulated" : "empty catalog on server"}`);
+} finally {
+ await browser.close();
+}
diff --git a/tests/browser/composer_configure_model.mjs b/tests/browser/composer_configure_model.mjs
index 1aa6ac3ac..8fd8bb7b8 100644
--- a/tests/browser/composer_configure_model.mjs
+++ b/tests/browser/composer_configure_model.mjs
@@ -1,5 +1,6 @@
/** Isolated API only: an empty model selector offers a way to configure that model type. */
import assert from "node:assert/strict";
+import { addCanvasNode } from "./canvas_creation.mjs";
import { launchBrowser } from "./engine.mjs";
const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179";
const api = process.env.CREATION_API_URL ?? "http://127.0.0.1:8019";
@@ -25,6 +26,7 @@ assert.equal(
true,
"needs a fixture API with an image model",
);
+assert.ok(configs.some((item) => item.kind === "agent"), "needs a fixture chat model");
const projectId = crypto.randomUUID();
await call(`/api/creation/projects/${projectId}/commands`, {
commandId: crypto.randomUUID(),
@@ -44,6 +46,7 @@ try {
});
// The shared fixture may already contain video models from other tests.
// Scope the empty video catalog to this page and keep the real image models.
+ let onlyChatModel = false;
await page.route("**/api/model-configs", async (route) => {
if (route.request().method() !== "GET") return route.fallback();
const response = await route.fetch();
@@ -51,7 +54,7 @@ try {
const models = await response.json();
await route.fulfill({
response,
- json: models.filter((item) => item.kind !== "video"),
+ json: models.filter((item) => onlyChatModel ? item.kind === "agent" : item.kind !== "video"),
});
});
page.setDefaultTimeout(15000);
@@ -75,17 +78,16 @@ try {
);
throw error;
});
- const rail = page.getByRole("toolbar", { name: "画布创作工具" });
// Another category being configured must not hide the action.
- await rail.getByRole("button", { name: "添加图片", exact: true }).click();
+ await addCanvasNode(page, "图片");
await page.getByRole("textbox", { name: "生成提示词", exact: true }).waitFor();
assert.equal(
await page.getByRole("button", { name: "配置图片模型", exact: true }).count(),
0,
);
- await rail.getByRole("button", { name: "添加视频", exact: true }).click();
+ await addCanvasNode(page, "视频");
const prompt = page.getByRole("textbox", { name: "生成提示词", exact: true });
await prompt.fill("保留这段提示词");
const action = page.getByRole("button", { name: "配置视频模型", exact: true });
@@ -105,6 +107,41 @@ try {
await dialog.waitFor({ state: "detached" });
assert.equal((await prompt.innerText()).trim(), "保留这段提示词");
await action.waitFor();
+ // Reopen the same project with only its chat model exposed to this page.
+ await page.getByTestId("workspace-mode-agent").click();
+ onlyChatModel = true;
+ await page.reload();
+ const chat = page.locator("#canvas-assistant");
+ const draft = chat.getByRole("textbox", { name: "消息内容", exact: true });
+ const unsent = "等配置好模型后再发送";
+ const draftSaved = page.waitForResponse((response) =>
+ response.url().endsWith(`/creation/projects/${projectId}/assistant/draft`) &&
+ response.request().method() === "PUT" && response.request().postDataJSON().draft === unsent);
+ await draft.fill(unsent);
+ for (const category of ["视频", "图片", "音频"]) {
+ await chat.getByRole("button", { name: "模型配置:媒体模型", exact: true }).click();
+ await chat.getByRole("tab", { name: new RegExp("^" + category) }).click();
+ await chat.getByRole("button", { name: "添加模型", exact: true }).click();
+ await dialog.getByRole("button", { name: category, exact: true, pressed: true }).waitFor();
+ await dialog.getByRole("button", { name: "关闭设置", exact: true }).click();
+ assert.equal(await draft.innerText(), unsent);
+ }
+
+ await chat.getByRole("button", { name: /^Agent:/ }).click();
+ await chat.getByRole("button", { name: "管理模型", exact: true }).click();
+ await dialog.getByRole("button", { name: "对话", exact: true, pressed: true }).waitFor();
+ await dialog.getByRole("button", { name: "关闭设置", exact: true }).click();
+
+ // The normal Settings entry retains General and the model overview.
+ await page.getByRole("button", { name: "设置", exact: true }).click();
+ assert.equal(await dialog.getByRole("button", { name: "通用" }).getAttribute("aria-current"), "page");
+ await dialog.getByRole("button", { name: "模型接入", exact: true }).click();
+ await dialog.locator(".cw-model-setup").waitFor();
+ await dialog.getByRole("button", { name: "关闭设置", exact: true }).click();
+ assert.ok((await draftSaved).ok());
+ const saved = await call(`/api/creation/projects/${projectId}/assistant`);
+ assert.equal(saved.draft, unsent);
+ assert.deepEqual(saved.messages, []);
assert.deepEqual(generation, []);
assert.deepEqual(errors, []);
} finally {
diff --git a/tests/browser/composer_duration.mjs b/tests/browser/composer_duration.mjs
index f20dcf3e6..0d553d639 100644
--- a/tests/browser/composer_duration.mjs
+++ b/tests/browser/composer_duration.mjs
@@ -1,3 +1,4 @@
+import { addCanvasNode } from "./canvas_creation.mjs";
import { chooseGenerationModel } from "./model_picker.mjs";
/** Isolated API only: independent duration control obeys model choices and persists. */
import assert from "node:assert/strict";
@@ -107,10 +108,7 @@ try {
page.on("pageerror", (error) => errors.push(error.message));
await page.goto(`${base}/ai-tool/ai-canvas/${projectId}`);
await page.getByText("已保存到本机", { exact: true }).waitFor();
- await page
- .getByRole("toolbar", { name: "画布创作工具" })
- .getByRole("button", { name: "添加视频", exact: true })
- .click();
+ await addCanvasNode(page, "视频");
const editor = page.getByRole("textbox", { name: "生成提示词", exact: true });
await chooseGenerationModel(page, `config:${fastConfig.id}`);
await editor.fill(
diff --git a/tests/browser/composer_expansion.mjs b/tests/browser/composer_expansion.mjs
index e640151d8..bbc29da4d 100644
--- a/tests/browser/composer_expansion.mjs
+++ b/tests/browser/composer_expansion.mjs
@@ -1,4 +1,5 @@
/** Isolated fixture only: compact spacing and an expanded editor keep one draft. */
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
import { join } from "node:path";
import { chooseGenerationModel } from "./model_picker.mjs";
@@ -55,10 +56,7 @@ try {
await page.getByText("已保存到本机", { exact: true }).waitFor();
const checked = [];
for (const kind of ["视频", "图片"]) {
- await page
- .getByRole("toolbar", { name: "画布创作工具" })
- .getByRole("button", { name: `添加${kind}`, exact: true })
- .click();
+ await addCanvasNode(page, kind);
if (kind === "图片") {
const model = (await call("/api/model-configs")).find(
(model) => model.modelId === "Qwen/Qwen-Image-2.1",
diff --git a/tests/browser/context_menu_dismissal.mjs b/tests/browser/context_menu_dismissal.mjs
index 28c242613..9c64fbdc1 100644
--- a/tests/browser/context_menu_dismissal.mjs
+++ b/tests/browser/context_menu_dismissal.mjs
@@ -55,6 +55,17 @@ try {
await page.getByText("Saved on this device", { exact: true }).waitFor();
const node = page.locator(`.react-flow__node[data-id="${fixture.node}"]`);
const menu = page.locator(".cw-context-menu");
+ const canvasPoint = async () => {
+ const point = await page.locator(".react-flow__pane").evaluate((pane) => {
+ const rect = pane.getBoundingClientRect();
+ return [
+ { x: rect.right - 100, y: rect.bottom - 180 },
+ { x: rect.left + 100, y: rect.bottom - 180 },
+ ].find(({ x, y }) => document.elementFromPoint(x, y) === pane);
+ });
+ assert.ok(point, "Dismissal starts on the visible canvas outside menus and nodes");
+ return point;
+ };
const openNodeMenu = async () => {
await node.click({ button: "right" });
await menu.waitFor();
@@ -67,10 +78,11 @@ try {
const before = await page
.locator(".react-flow__viewport")
.getAttribute("style");
- await page.mouse.move(1100, 750);
+ const dragStart = await canvasPoint();
+ await page.mouse.move(dragStart.x, dragStart.y);
await page.mouse.down();
await menu.waitFor({ state: "detached" });
- await page.mouse.move(1170, 800, { steps: 10 });
+ await page.mouse.move(dragStart.x + 70, dragStart.y + 50, { steps: 10 });
await page.mouse.up();
assert.notEqual(
await page.locator(".react-flow__viewport").getAttribute("style"),
@@ -80,16 +92,25 @@ try {
(await node.getAttribute("class")).split(" ").includes("selected"),
);
await openNodeMenu();
- await page.mouse.click(1100, 750);
+ const clickPoint = await canvasPoint();
+ await page.mouse.click(clickPoint.x, clickPoint.y);
await menu.waitFor({ state: "detached" });
await openNodeMenu();
const menuItem = menu.getByRole("menuitem").first();
+ const pending = page.locator("[data-pending-references]");
+ await pending.waitFor();
await menuItem.focus();
await page.keyboard.press("Escape");
await menu.waitFor({ state: "detached" });
+ assert.equal(await pending.isVisible(), true, "Menu Escape preserves staged chat references");
assert.ok(
(await node.getAttribute("class")).split(" ").includes("selected"),
);
+ await page.locator("#canvas-assistant [contenteditable=true]").focus();
+ await page.keyboard.press("Escape");
+ await pending.waitFor({ state: "detached" });
+ assert.equal(await page.locator("#canvas-assistant").isVisible(), true,
+ "Chat Escape clears staged references while keeping the conversation open");
// The node composer stops pointerdown propagation; clicking it must still
// dismiss the menu instead of leaving it stuck open over the canvas. The
// menu can cover the composer, so send the pointerdown straight at it.
@@ -125,7 +146,8 @@ try {
await page.keyboard.press("Escape");
await menu.waitFor({ state: "detached" });
await openPortMenu();
- await page.mouse.click(1100, 750);
+ const portClickPoint = await canvasPoint();
+ await page.mouse.click(portClickPoint.x, portClickPoint.y);
await menu.waitFor({ state: "detached" });
console.log(JSON.stringify({ mode: "unified", passed: true }));
}
diff --git a/tests/browser/created_node_focus.mjs b/tests/browser/created_node_focus.mjs
index d33af2ccd..42ae7dd78 100644
--- a/tests/browser/created_node_focus.mjs
+++ b/tests/browser/created_node_focus.mjs
@@ -23,7 +23,8 @@ try {
type: "project.create", payload: { name: `Viewport focus ${projectId.slice(0, 8)}` } });
await page.goto(`${base}/ai-tool/ai-canvas/${projectId}?creation=unified`);
await page.getByText("Saved on this device", { exact: true }).waitFor();
- await page.locator(".cw-chat-button").click();
+ const chatToggle = page.locator(".cw-chat-button");
+ if (await chatToggle.getAttribute("aria-expanded") === "false") await chatToggle.click();
await page.locator(".cw-assistant-panel:not([hidden])").waitFor();
headers["X-OpenDirector-Session"] = await page.evaluate(async () => (await import("/src/backend/api.ts")).sessionId);
const create = async (x, y) => {
@@ -38,9 +39,10 @@ try {
const checkCentered = async (id) => {
await page.waitForFunction((id) => {
const node = document.querySelector(`.react-flow__node[data-id="${id}"]`).getBoundingClientRect();
- const panel = document.querySelector(".cw-assistant-panel").getBoundingClientRect();
- return node.left > 75 && node.right < panel.left - 10 && node.top > 72 && node.bottom < innerHeight - 65 &&
- Math.abs((node.left + node.right) / 2 - (80 + panel.left - 16) / 2) < 50;
+ const canvas = document.querySelector(".cw-canvas-region").getBoundingClientRect();
+ const left = canvas.left + (canvas.width < 700 ? 64 : 80), right = canvas.right - 20;
+ return node.left > left - 5 && node.right < right + 10 && node.top > canvas.top + 72 && node.bottom < canvas.bottom - 65 &&
+ Math.abs((node.left + node.right) / 2 - (left + right) / 2) < 50;
}, id);
};
const editor = page.locator(".cw-assistant-panel [contenteditable=true]").first();
@@ -51,7 +53,8 @@ try {
assert.equal(await page.locator(".react-flow__node.selected").count(), 0);
await page.screenshot({ path: "/tmp/created-node-focus.png" });
await page.waitForTimeout(250);
- await page.mouse.move(100, 800);
+ const canvas = await page.locator(".cw-canvas-region").boundingBox();
+ await page.mouse.move(canvas.x + 100, 800);
await page.mouse.down();
const before = await transform();
await create(5000, 5000);
@@ -128,9 +131,24 @@ try {
await assertViewRetained(beforeUndo, selectedBeforeUndo, 'redoing a hide must retain the view');
// Restoring again after reload also uses the persisted hidden identity.
await page.waitForTimeout(1200); // Flush independent viewport preferences.
- await page.reload();
- await page.getByText('Saved on this device', { exact: true }).waitFor();
- if (!(await editor.isVisible())) await page.locator('.cw-chat-button').click();
+ // The chat can already be open while its saved draft is still loading.
+ const { promise: assistantRead, resolve: resumeRead } = Promise.withResolvers();
+ await page.route(`**/creation/projects/${projectId}/assistant`, async route => {
+ await assistantRead;
+ await route.continue();
+ }, { times: 1 });
+ try {
+ await page.reload();
+ await page.getByText('Saved on this device', { exact: true }).waitFor();
+ const loadingEditor = page.locator('#canvas-assistant').getByRole('textbox', { name: 'Message content', exact: true });
+ await loadingEditor.waitFor();
+ assert.equal(await chatToggle.getAttribute('aria-expanded'), 'true');
+ assert.equal(await loadingEditor.getAttribute('contenteditable'), 'false');
+ } finally {
+ resumeRead();
+ }
+ await editor.waitFor();
+ assert.ok((await editor.innerText()).includes('保留我的视图和输入焦点'), 'reload must restore the saved draft');
await editor.fill('重开后仍保留视图');
headers['X-OpenDirector-Session'] = await page.evaluate(async () => (await import('/src/backend/api.ts')).sessionId);
const beforeShow = await transform(), selectedBeforeShow = await selection();
diff --git a/tests/browser/creation_history.mjs b/tests/browser/creation_history.mjs
index ca848f318..978f5bec0 100644
--- a/tests/browser/creation_history.mjs
+++ b/tests/browser/creation_history.mjs
@@ -1,4 +1,5 @@
/** Real UI copy/paste and history against an isolated creation server. */
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
const { chromium } = await import(
process.env.PLAYWRIGHT_MODULE ?? "playwright-core"
@@ -81,10 +82,7 @@ try {
await page.getByText("已保存到本机", { exact: true }).waitFor();
return snapshot;
}
- await page
- .getByRole("toolbar", { name: "画布创作工具" })
- .getByRole("button", { name: "添加文本", exact: true })
- .click();
+ await addCanvasNode(page, "文本");
const original = (await count(1)).canvasItems[0];
await page
.locator(`.react-flow__node[data-id="${original.id}"] .cw-node-title`)
diff --git a/tests/browser/creation_journey.mjs b/tests/browser/creation_journey.mjs
index 9cd3e34ac..e6a86d036 100644
--- a/tests/browser/creation_journey.mjs
+++ b/tests/browser/creation_journey.mjs
@@ -1,3 +1,4 @@
+import { addCanvasNode } from "./canvas_creation.mjs";
import { chooseGenerationModel } from "./model_picker.mjs";
/** Shared full-workflow prelude: genuine UI upload, reference, candidate and layers. */
import assert from "node:assert/strict";
@@ -17,10 +18,7 @@ export async function creationJourney(
(await state()).canvasItems.find((i) => i.kind === "image"),
);
await saved();
- await page
- .getByRole("toolbar", { name: "Canvas creation tools" })
- .getByRole("button", { name: "Add Image", exact: true })
- .click();
+ await addCanvasNode(page, "Image");
const target = await until(async () =>
(await state()).canvasItems.find(
(i) => i.kind === "image" && i.id !== source.id,
diff --git a/tests/browser/creation_server.py b/tests/browser/creation_server.py
index 4a8e950b5..aa57f9ba3 100644
--- a/tests/browser/creation_server.py
+++ b/tests/browser/creation_server.py
@@ -10,6 +10,7 @@
import tempfile
import subprocess
from urllib.parse import urlsplit
+from uuid import uuid4
from fastapi import Request
from PIL import Image
@@ -28,6 +29,7 @@
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--port', type=int, default=8019)
parser.add_argument('--root', type=Path)
+parser.add_argument('--empty-models', action='store_true', help='Start a fresh local-editing fixture without model configurations')
parser.add_argument('--assistant-fixture', action='store_true', help='Use a gated assistant response without a real model')
parser.add_argument('--http-generation-fixture', action='store_true',
help='Use real generation adapters against loopback HTTP test servers only')
@@ -40,19 +42,20 @@
# These configurations use the in-process adapters below and have no HTTP
# capability service. Keep their checks explicit so they do not occupy the
# bounded query workers used by a browser test's real capability fixture.
-if not configs.list():
- for kind in ('agent', 'image'):
- configs.save(kind, 'http://127.0.0.1:12345/v1', f'fixture-{kind}', '',
+if not args.empty_models:
+ if not configs.list():
+ for kind in ('agent', 'image'):
+ configs.save(kind, 'http://127.0.0.1:12345/v1', f'fixture-{kind}', '',
+ connection_type='self_hosted', protocol='openai', auth_mode='none', capability_auto_check=False)
+
+ # Test-only adapters let the real preview and tool services exercise owned
+ # assets, model selection and cancellation without contacting a GPU endpoint.
+ if not any(model['kind'] == 'vision' for model in configs.list()):
+ configs.save('vision', 'http://127.0.0.1:12345/v1', 'facebook/sam3', '',
+ connection_type='self_hosted', protocol='vllm_omni', auth_mode='none', capability_auto_check=False)
+ if not any(model['modelId'] == 'Qwen/Qwen-Image-2.1' for model in configs.list()):
+ configs.save('image', 'http://127.0.0.1:12345/v1', 'Qwen/Qwen-Image-2.1', '',
connection_type='self_hosted', protocol='openai', auth_mode='none', capability_auto_check=False)
-
-# Test-only adapters let the real preview and tool services exercise owned
-# assets, model selection and cancellation without contacting a GPU endpoint.
-if not any(model['kind'] == 'vision' for model in configs.list()):
- configs.save('vision', 'http://127.0.0.1:12345/v1', 'facebook/sam3', '',
- connection_type='self_hosted', protocol='vllm_omni', auth_mode='none', capability_auto_check=False)
-if not any(model['modelId'] == 'Qwen/Qwen-Image-2.1' for model in configs.list()):
- configs.save('image', 'http://127.0.0.1:12345/v1', 'Qwen/Qwen-Image-2.1', '',
- connection_type='self_hosted', protocol='openai', auth_mode='none', capability_auto_check=False)
selection_gate = asyncio.Event()
selection_gate.set()
selection_calls, image_edit_calls = [], []
@@ -154,11 +157,63 @@ async def generate(self, config, task, submitted, *, result_ready=None):
assistant_gate.set()
assistant_contexts = []
if args.assistant_fixture:
+ from opendirector.agent.gateway import ToolGateway
from opendirector_api import agent
async def fixture_agent(self, run):
assistant_contexts.append(run.messages)
- if run.messages[-1]['content'].partition('\n')[0] == '建议回复验收':
+ prompt = run.messages[-1]['content'].partition('\n')[0]
+ if prompt == 'Result card: timeline':
+ # A timeline-only delivery uses the same command and run ledger as an Agent turn.
+ editor_id, item_id = str(uuid4()), str(uuid4())
+ project_id = str(run.project_id)
+ gateway = ToolGateway(self.business, run)
+ try:
+ submitted = await gateway.call('result-card-timeline', 'execute_command', {
+ 'type': 'creation.batch', 'expectedVersions': [],
+ 'payload': {'operations': [
+ {'type': 'editor.create', 'payload': {'document': {
+ 'id': editor_id, 'projectId': project_id, 'kind': 'timeline',
+ 'data': {'fps': 24, 'width': 128, 'height': 96, 'tracks': [
+ {'id': 'visual', 'kind': 'visual', 'title': 'Agent cut track', 'clips': []},
+ ]},
+ }}},
+ {'type': 'canvas.show', 'payload': {'item': {
+ 'id': item_id, 'projectId': project_id, 'kind': 'timeline', 'title': 'Agent cut',
+ 'binding': {'role': 'editor', 'objectRef': {'id': editor_id, 'kind': 'timeline'}},
+ }}},
+ ]},
+ })
+ if submitted.error:
+ raise ProjectError(submitted.error)
+ yield {'type': 'delta', 'text': 'Timeline created.'}
+ finally:
+ await gateway.close()
+ return
+ if prompt in {'Result card: if_current', 'Result card: candidate_only'}:
+ # The model response is scripted. The job, provenance, persisted result
+ # and adoption all go through the normal Agent command gateway.
+ snapshot = self.business.projects.snapshot(run.project_id)
+ [spec] = snapshot.generationSpecs
+ [item] = snapshot.canvasItems
+ gateway = ToolGateway(self.business, run)
+ try:
+ submitted = await gateway.call('result-card-image', 'execute_command', {
+ 'type': 'generation.submit',
+ 'expectedVersions': [
+ {'objectType': 'generation_spec', 'id': str(spec.id), 'revision': spec.revision},
+ {'objectType': 'canvas_item', 'id': str(item.id), 'revision': item.revision},
+ ],
+ 'payload': {'specId': str(spec.id), 'expectedSpecRevision': spec.revision,
+ 'originItemId': str(item.id), 'adoptionPolicy': prompt.split(': ')[1]},
+ })
+ if submitted.error:
+ raise ProjectError(submitted.error)
+ yield {'type': 'delta', 'text': 'Image requested.'}
+ finally:
+ await gateway.close()
+ return
+ if prompt == '建议回复验收':
yield {'type': 'delta', 'text': (
'- 展开海边重逢的完整分镜\n'
'- 换一个安静克制的结尾\n'
diff --git a/tests/browser/cross_canvas_paste.mjs b/tests/browser/cross_canvas_paste.mjs
index dd162ee92..19de6035f 100644
--- a/tests/browser/cross_canvas_paste.mjs
+++ b/tests/browser/cross_canvas_paste.mjs
@@ -1,4 +1,5 @@
/** Isolated model double + real project storage: copy media between canvases (#69). */
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
import { launchBrowser } from "./engine.mjs";
import { chooseGenerationModel } from "./model_picker.mjs";
@@ -49,7 +50,7 @@ try {
await page.goto(`${base}/ai-tool/ai-canvas/${source.id}`);
await saved();
// One generated image and one upload.
- await page.getByRole("toolbar", { name: "Canvas creation tools" }).getByRole("button", { name: "Add Image", exact: true }).click();
+ await addCanvasNode(page, "Image");
await chooseGenerationModel(page, { label: "fixture-image" });
await page.getByRole("textbox", { name: "Prompt", exact: true }).fill("Copied generation");
await until(async () => (await source.state()).generationSpecs[0]?.modelConfigId);
diff --git a/tests/browser/default_entry.mjs b/tests/browser/default_entry.mjs
index 8a204e3c4..11bca0adf 100644
--- a/tests/browser/default_entry.mjs
+++ b/tests/browser/default_entry.mjs
@@ -193,7 +193,8 @@ try {
await page
.getByRole("button", { name: name + " renamed", exact: true })
.waitFor();
- await page.getByRole("button", { name: "与 AI 对话", exact: true }).click();
+ const chatToggle = page.getByRole("button", { name: "与 AI 对话", exact: true });
+ if (await chatToggle.getAttribute("aria-expanded") === "false") await chatToggle.click();
const message = page.getByRole("textbox", { name: "消息内容", exact: true });
await message.waitFor();
assert.equal((await message.innerText()).replace(/\u200b/g, "").trim(), "");
diff --git a/tests/browser/double_shift_chat.mjs b/tests/browser/double_shift_chat.mjs
index ababd2006..634fe0cd0 100644
--- a/tests/browser/double_shift_chat.mjs
+++ b/tests/browser/double_shift_chat.mjs
@@ -24,6 +24,9 @@ try {
const trigger = page.locator(".cw-project-chevron");
await trigger.waitFor();
await page.locator('.cw-workspace[aria-busy="false"]').waitFor();
+ // Canvas mode now starts with chat expanded; establish the closed state
+ // before testing the shortcut's open/focus/close cycle.
+ await page.getByRole("button", { name: "Collapse AI chat", exact: true }).click();
await trigger.focus();
const tap = async () => { await page.keyboard.press("Shift"); await page.keyboard.press("Shift"); };
await tap();
diff --git a/tests/browser/example_canvas_picker.mjs b/tests/browser/example_canvas_picker.mjs
index 1e419d5ba..435d25776 100644
--- a/tests/browser/example_canvas_picker.mjs
+++ b/tests/browser/example_canvas_picker.mjs
@@ -1,7 +1,6 @@
/**
- * Isolated UI regression: the empty canvas imports the two hosted samples
- * directly with a progress bar, the project menu still opens the full picker,
- * and a blocked page is reported instead of imported.
+ * The empty canvas and project menu share one example picker. Verify download
+ * progress, import, and the error shown when a download serves a blocked page.
*
* The download route returns either a ZIP around one `.canvas` or an HTML
* page like a blocked share link does.
@@ -87,23 +86,22 @@ try {
const openCanvas = async () => {
await page.goto(`${base}/ai-tool/ai-canvas/${projectId}`);
await page.getByText("已保存到本机", { exact: true }).waitFor();
- // The example buttons enable once the canvas is ready.
- await page.waitForFunction(() => {
- const button = [...document.querySelectorAll("button")].find((item) =>
- item.textContent?.includes("体验图片示例"),
- );
- return !!button && !button.disabled;
- });
+ };
+ const dialog = page.locator(".cw-example-dialog");
+ const image = dialog.getByRole("listitem").filter({ hasText: "图像创作示例画布" });
+ const chooseImageExample = async () => {
+ await page.getByRole("button", { name: "浏览示例画布", exact: true }).click();
+ await image.getByRole("button", { name: "下载并导入", exact: true }).click();
};
- // 1. The empty-state button downloads, shows progress, imports and closes the bar.
+ // 1. Choose the image example from the empty canvas and watch its progress.
await openCanvas();
- await page.getByRole("button", { name: "体验图片示例" }).click();
- await page.locator(".cw-empty-example-status").waitFor();
+ await chooseImageExample();
+ await image.getByRole("progressbar", { name: "下载进度" }).waitFor();
await page.waitForFunction(() => document.querySelectorAll(".react-flow__node").length === 2);
assert.equal(await page.locator(".react-flow__node").count(), 2);
- // The progress block lives in the empty state, which the imported canvas replaces.
- assert.equal(await page.locator(".cw-empty-example-status").count(), 0);
+ await image.getByRole("progressbar").waitFor({ state: "hidden" });
+ await dialog.getByRole("button", { name: "关闭", exact: true }).last().click();
// 2. The project menu still reaches the full picker.
// The switch saves the new project first; the switcher is disabled until then.
@@ -113,7 +111,6 @@ try {
});
await page.getByRole("button", { name: "切换项目", exact: true }).click();
await page.getByRole("menuitem", { name: "示例画布", exact: true }).click();
- const dialog = page.locator(".cw-example-dialog");
await dialog.waitFor();
// The catalog ships with the app, so the rows carry its titles.
await dialog.getByText("图像创作示例画布", { exact: true }).waitFor();
@@ -123,8 +120,8 @@ try {
await page.unroute(samplePattern);
await page.route(samplePattern, (route) => route.fulfill(served("text/html")));
await openCanvas();
- await page.getByRole("button", { name: "体验图片示例" }).click();
- await page.getByText(/服务器返回的是网页/).waitFor();
+ await chooseImageExample();
+ await image.getByRole("alert").filter({ hasText: /服务器返回的是网页/ }).waitFor();
assert.equal(await page.locator(".react-flow__node").count(), 0);
// 4. A single click in setup starts the video example on step two.
@@ -150,6 +147,7 @@ try {
await welcome.getByRole("button", { name: "开始设置", exact: true }).click();
await welcome.getByRole("button", { name: "配置语言模型", exact: true }).click();
await welcome.getByRole("button", { name: /^fixture-agent/ }).click();
+ await welcome.getByRole("button", { name: "画布创作", exact: true }).click();
const openSample = welcome.getByRole("button", { name: "打开示例画布", exact: true });
const videoTask = welcome.getByRole("checkbox", { name: "做一段视频" });
await videoTask.check();
diff --git a/tests/browser/first_last_frame_connections.mjs b/tests/browser/first_last_frame_connections.mjs
index e7c299d86..7cf2f7195 100644
--- a/tests/browser/first_last_frame_connections.mjs
+++ b/tests/browser/first_last_frame_connections.mjs
@@ -2,6 +2,7 @@
* both frame slots when the model declares a last frame (#83).
* Uses the isolated creation_server.py; no remote generation.
*/
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
import { launchBrowser } from "./engine.mjs";
import { chooseGenerationModel } from "./model_picker.mjs";
@@ -93,10 +94,7 @@ try {
// A blank video node on the MiniMax model in first-last mode. The frame
// pickers are left untouched: the connections alone must fill them.
- await page
- .getByRole("toolbar", { name: "画布创作工具" })
- .getByRole("button", { name: "添加视频", exact: true })
- .click();
+ await addCanvasNode(page, "视频");
const created = await until(
snapshot,
(value) => value.canvasItems.length === 3,
diff --git a/tests/browser/first_run.mjs b/tests/browser/first_run.mjs
index fb3f629d5..b69f06545 100644
--- a/tests/browser/first_run.mjs
+++ b/tests/browser/first_run.mjs
@@ -20,7 +20,11 @@ assert.ok(create.ok, await create.text());
const browser = await launchBrowser();
const configuredIds = [];
try {
- const page = await browser.newPage({ locale: "en-US", viewport: { width: 1440, height: 900 } });
+ const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
+ await page.addInitScript(() => {
+ if (localStorage.getItem("opendirector.locale.v1") === null)
+ localStorage.setItem("opendirector.locale.v1", "en-US");
+ });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
@@ -44,8 +48,10 @@ try {
const languageModel = `first-run-agent-${projectId.slice(0, 8)}`;
const videoModels = ["alpha", "beta"].map((suffix) => `first-run-video-${projectId.slice(0, 8)}-${suffix}`);
const imageModel = `first-run-image-${projectId.slice(0, 8)}`;
+ const chatImageModel = `chat-canvas-image-${projectId.slice(0, 8)}`;
let failCatalog = true;
let showBlockedImage = false;
+ let onlyLanguage = false;
let blockedImage;
await page.route(/\/api\/model-configs$/, async (route) => {
if (failCatalog) {
@@ -54,9 +60,9 @@ try {
}
const response = await route.fetch();
const configs = await response.json();
- const models = configs.filter((item) => item.modelId === languageModel ||
- videoModels.includes(item.modelId) || (!showBlockedImage && item.modelId === imageModel));
- if (showBlockedImage) {
+ const models = configs.filter((item) => item.modelId === languageModel || item.modelId === chatImageModel ||
+ (!onlyLanguage && !showBlockedImage && (videoModels.includes(item.modelId) || item.modelId === imageModel)));
+ if (showBlockedImage && !onlyLanguage) {
const image = configs.find((item) => item.modelId === "fixture-image");
blockedImage = {
...image.availability,
@@ -75,6 +81,9 @@ try {
const welcome = page.locator("dialog.cw-welcome");
const welcomeTitle = welcome.getByRole("heading", { name: "Welcome to OpenDirector" });
const getStarted = welcome.getByRole("button", { name: "Get started" });
+ const canvasMode = welcome.getByRole("button", { name: "Create on canvas", exact: true });
+ const agentMode = welcome.getByRole("button", { name: "Create with chat", exact: true });
+ const savedMode = () => page.evaluate(() => localStorage.getItem("opendirector.workspaceMode.v1"));
const assistantTitle = welcome.getByRole("heading", { name: "Connect an LLM" });
const chooseHarness = async () => {
await welcome.getByRole("button", { name: "Use an existing harness", exact: true }).click();
@@ -82,8 +91,11 @@ try {
await codexButton.waitFor();
assert.equal(await welcome.getByRole("button", { name: /^Claude Code/ }).isDisabled(), true);
await codexButton.click();
- await welcome.getByRole("heading", { name: "What do you want to do first?" }).waitFor();
+ await welcome.getByRole("heading", { name: "Choose how to create" }).waitFor();
};
+ await page.goto(`${url}?setup=models`);
+ await page.locator("#settings-dialog .cw-settings-close").click();
+ await welcomeTitle.waitFor();
await page.goto(`${url}?setup=welcome&from=onboarding`);
await welcomeTitle.waitFor();
await welcome.getByRole("alert").getByText("Could not read model configuration. Try again.").waitFor();
@@ -95,13 +107,17 @@ try {
await page.keyboard.press("Escape");
assert.ok(await welcomeTitle.isVisible());
assert.equal(await assistantTitle.count(), 0);
- assert.equal(await welcome.getByRole("button").count(), 1);
+ assert.equal(await canvasMode.count(), 0);
+ const enter = welcome.getByRole("button", { name: "Enter canvas", exact: true });
+ assert.equal(await enter.count(), 0);
+ assert.equal(await savedMode(), null);
await page.setViewportSize({ width: 375, height: 640 });
assert.ok(await getStarted.evaluate((element) => element.getBoundingClientRect().bottom <= window.innerHeight));
- await page.keyboard.press("Tab");
- assert.ok(await getStarted.evaluate((element) => document.activeElement === element));
- await page.keyboard.press("Enter");
+ await getStarted.press("Enter");
await assistantTitle.waitFor();
+ assert.equal(await agentMode.count(), 0);
+ assert.equal(await enter.count(), 0);
+ assert.equal(await savedMode(), null);
await welcome.getByRole("button", { name: "Back", exact: true }).click();
await welcomeTitle.waitFor();
await page.setViewportSize({ width: 1440, height: 900 });
@@ -140,7 +156,21 @@ try {
assert.ok(languageReceipt.ok(), await languageReceipt.text());
const [savedLanguage] = await languageReceipt.json();
configuredIds.push(savedLanguage.id);
- await welcome.getByRole("heading", { name: "What do you want to do first?" }).waitFor();
+ await welcome.getByRole("heading", { name: "Choose how to create" }).waitFor();
+ assert.ok(await agentMode.isVisible() && await canvasMode.isVisible());
+ assert.equal(await welcome.getByRole("checkbox").count(), 0);
+ assert.equal(await welcome.getByRole("button", { name: "Import media" }).count(), 0);
+ assert.equal(await welcome.getByRole("button", { name: "More ways to start" }).count(), 0);
+ await agentMode.focus();
+ await page.keyboard.press("Tab");
+ assert.ok(await canvasMode.evaluate(button => button === document.activeElement));
+ await canvasMode.click();
+ await welcome.getByRole("heading", { name: "How would you like to start your canvas?" }).waitFor();
+ assert.ok(await enter.isDisabled());
+ assert.ok(await welcome.getByRole("button", { name: "Import media", exact: true }).isDisabled());
+ assert.ok(await welcome.getByRole("button", { name: "Open an example canvas", exact: true }).isDisabled());
+ assert.equal(await savedMode(), null);
+ await welcome.getByRole("button", { name: "Back" }).click();
const languageAssistant = await page.request.get(base + projectPath + "/assistant", { headers });
assert.ok(languageAssistant.ok(), await languageAssistant.text());
assert.equal((await languageAssistant.json()).modelSelections.agent, savedLanguage.id);
@@ -155,6 +185,7 @@ try {
assert.equal((await assistant.json()).runtime, "codex");
assert.equal(await welcome.getByRole("checkbox", { checked: true }).count(), 0);
+ await canvasMode.click();
const videoTask = welcome.getByRole("checkbox", { name: "Make a video" });
await page.setViewportSize({ width: 375, height: 720 });
await videoTask.check();
@@ -179,6 +210,7 @@ try {
assert.equal(configured.kind, "video");
const videoPicker = welcome.getByRole("combobox", { name: "Choose a video model" });
await videoPicker.waitFor();
+ assert.ok(await welcome.getByRole("button", { name: "Import media", exact: true }).isEnabled(), "One saved video model unlocks the canvas");
assert.ok(await videoTask.isChecked());
const start = welcome.getByRole("button", { name: "Start creating" });
assert.ok(await start.isDisabled());
@@ -284,6 +316,8 @@ try {
await page.goto(url + "?setup=welcome");
await getStarted.click();
await chooseHarness();
+ await canvasMode.click();
+ assert.ok(await enter.isDisabled(), "A paused image model cannot unlock the canvas");
await imageTask.check();
const blocked = welcome.getByRole("listitem").filter({ hasText: "fixture-image" });
await blocked.getByText("Service paused").waitFor();
@@ -305,8 +339,133 @@ try {
await blocked.getByRole("button", { name: "Retry", exact: true }).click();
await recheck;
await welcome.getByRole("combobox", { name: "Choose a text-to-image model" }).waitFor();
+ assert.ok(await welcome.getByRole("button", { name: "Import media", exact: true }).isEnabled(), "One ready image model unlocks the canvas");
+
+ onlyLanguage = true;
+ // An unavailable model catalog cannot be bypassed, even on a project deep link.
+ failCatalog = true;
+ await page.evaluate(() => {
+ localStorage.removeItem("opendirector.modelSetup.v1");
+ localStorage.removeItem("opendirector.workspaceMode.v1");
+ });
+ await page.setViewportSize({ width: 375, height: 640 });
+ await page.goto(url + "?from=mode-choice");
+ await welcomeTitle.waitFor();
+ await welcome.getByRole("alert").waitFor();
+ assert.equal(await enter.count(), 0);
+ await getStarted.click();
+ assert.equal(await agentMode.count(), 0);
+ assert.ok(await configureLanguage.isDisabled());
+ failCatalog = false;
+ await welcome.getByRole("button", { name: "Reload", exact: true }).click();
+ await chooseHarness();
+ assert.ok(await canvasMode.isVisible());
+ const commands = [];
+ page.on("request", (request) => {
+ if (request.method() === "POST" && request.url().endsWith(projectPath + "/commands"))
+ commands.push(request.postDataJSON());
+ });
+ const canvasRegion = page.getByTestId("canvas-region");
+ const chat = page.locator("#canvas-assistant");
+ await agentMode.press("Enter");
+ await welcome.waitFor({ state: "hidden" });
+ await chat.waitFor();
+ assert.equal(await canvasRegion.isVisible(), false);
+ assert.equal(await savedMode(), "agent");
+ assert.equal(await dismissed(), "chat-ready");
+ assert.equal(new URL(page.url()).search, "?from=mode-choice");
+ await page.reload();
+ await page.locator('.cw-workspace[aria-busy="false"][data-workspace-mode="agent"]').waitFor();
+ assert.equal(await welcome.isVisible(), false);
+ const settings = page.locator("#settings-dialog");
+ for (const locale of ["en-US", "zh-CN"]) {
+ const zh = locale === "zh-CN";
+ for (const width of [390, 1440]) {
+ await page.setViewportSize({ width, height: width === 390 ? 844 : 900 });
+ await page.getByTestId("workspace-mode-canvas").click();
+ const notice = settings.locator(".cw-settings-notice");
+ await notice.getByText(zh ? "首次进入画布前,请先配置一个图片或视频生成模型。" :
+ "Set up an image or video generation model before entering the canvas for the first time.").waitFor();
+ assert.ok(await notice.getByRole("button", { name: zh ? "进入画布" : "Enter canvas" }).isDisabled());
+ const categories = settings.locator(".cw-model-categories");
+ const bounds = await settings.locator(".cw-settings-body").boundingBox();
+ const message = await notice.boundingBox();
+ for (const button of await categories.getByRole("button").all()) {
+ const rect = await button.boundingBox();
+ assert.ok(rect && rect.y >= message.y + message.height &&
+ rect.x >= bounds.x && rect.x + rect.width <= bounds.x + bounds.width &&
+ rect.y + rect.height <= bounds.y + bounds.height,
+ `${locale} ${width}px: ${await button.innerText()} must be fully inside settings and below the notice`);
+ assert.ok(await button.evaluate(el => {
+ const { x, y, width, height } = el.getBoundingClientRect();
+ return el.contains(document.elementFromPoint(x + width / 2, y + height / 2));
+ }), "The visible category must receive the pointer");
+ }
+ const audio = categories.getByRole("button", { name: zh ? "音频" : "Audio", exact: true });
+ await audio.click();
+ assert.equal(await audio.getAttribute("aria-pressed"), "true");
+ await categories.getByRole("button", { name: zh ? "概览" : "Overview", exact: true }).click();
+ const language = settings.locator("#model-setup-language");
+ assert.equal(await language.inputValue(), locale);
+ if (width === 1440) await language.selectOption(zh ? "en-US" : "zh-CN");
+ await page.keyboard.press("Escape");
+ await settings.waitFor({ state: "hidden" });
+ }
+ }
+ assert.equal(await savedMode(), "agent");
+ await page.setViewportSize({ width: 1440, height: 900 });
+ await page.getByTestId("workspace-float-chat").click();
+ await settings.waitFor();
+ assert.equal(await dismissed(), "chat-ready");
+ await page.keyboard.press("Escape");
+ assert.equal(await chat.getAttribute("data-floating"), null);
+ await page.getByTestId("workspace-float-chat").click();
+ await settings.getByRole("button", { name: "Add service", exact: true }).click();
+ await settings.getByLabel("Service URL (Base URL)").fill("http://127.0.0.1:12345/v1");
+ await settings.getByRole("button", { name: "Add manually", exact: true }).click();
+ await settings.getByLabel(manualModelId, { exact: true }).fill(chatImageModel);
+ await settings.getByRole("button", { name: "Add", exact: true }).click();
+ const chatModelSaved = page.waitForResponse(response => response.url().endsWith("/api/model-configs/batch"));
+ await settings.getByRole("button", { name: "Save service", exact: true }).click();
+ const receiptFromSettings = await chatModelSaved;
+ assert.ok(receiptFromSettings.ok());
+ configuredIds.push(...(await receiptFromSettings.json()).map(model => model.id));
+ await settings.getByRole("button", { name: "Enter canvas" }).click();
+ await page.locator('.cw-workspace[data-workspace-mode="canvas"] #canvas-assistant[data-floating="true"]').waitFor();
+ assert.equal(await dismissed(), "dismissed");
+ onlyLanguage = false;
+ showBlockedImage = false;
+ await page.setViewportSize({ width: 375, height: 640 });
+ await page.goto(url + "?setup=welcome");
+ await getStarted.click();
+ await chooseHarness();
+ assert.ok(await agentMode.isVisible());
+ await canvasMode.click();
+ await enter.click();
+ await welcome.waitFor({ state: "hidden" });
+ await canvasRegion.waitFor();
+ assert.equal(await chat.isVisible(), false);
+ assert.equal(await savedMode(), "canvas");
+
+ await page.goto(url + "?setup=welcome");
+ await getStarted.click();
+ await chooseHarness();
+ await page.evaluate(() => {
+ const setItem = Storage.prototype.setItem;
+ Storage.prototype.setItem = function (key, value) {
+ if (key === "opendirector.workspaceMode.v1")
+ throw new DOMException("Storage write denied", "SecurityError");
+ return setItem.call(this, key, value);
+ };
+ });
+ await agentMode.click();
+ await welcome.waitFor({ state: "hidden" });
+ await page.getByText("Switched modes. This browser could not save your preference.", { exact: true }).waitFor();
+ assert.equal(await page.locator(".cw-workspace").getAttribute("data-workspace-mode"), "agent");
+ assert.equal(await savedMode(), "canvas");
+ assert.deepEqual(commands, []);
assert.deepEqual(errors, []);
- console.log("Browser first-run setup, cancellation, retry, and model availability passed");
+ console.log("Browser first-run workspace selection, model setup, cancellation and retry passed");
} finally {
await browser.close();
for (const id of configuredIds) await fetch(base + "/api/model-configs/" + id, { method: "DELETE", headers });
diff --git a/tests/browser/generation_feedback.mjs b/tests/browser/generation_feedback.mjs
index 9e48d923d..79d4cae1d 100644
--- a/tests/browser/generation_feedback.mjs
+++ b/tests/browser/generation_feedback.mjs
@@ -1,3 +1,4 @@
+import { addCanvasNode } from "./canvas_creation.mjs";
import { chooseGenerationModel } from "./model_picker.mjs";
/** Isolated model double + real project storage. Deliberately stalled network reads. */
import assert from "node:assert/strict";
@@ -80,13 +81,7 @@ async function setup(kind = "image") {
const state = () => call(`/api/creation/projects/${id}`);
await page.goto(`${base}/ai-tool/ai-canvas/${id}`);
await page.getByText("已保存到本机", { exact: true }).waitFor();
- await page
- .getByRole("toolbar", { name: "画布创作工具" })
- .getByRole("button", {
- name: kind === "video" ? "添加视频" : "添加图片",
- exact: true,
- })
- .click();
+ await addCanvasNode(page, kind === "video" ? "视频" : "图片");
await chooseGenerationModel(page, kind === "video" ? `config:${config.id}` : { label: "fixture-image" });
await page
.getByRole("textbox", { name: "生成提示词", exact: true })
diff --git a/tests/browser/generation_parameters.mjs b/tests/browser/generation_parameters.mjs
index 79f3782c4..65b349a63 100644
--- a/tests/browser/generation_parameters.mjs
+++ b/tests/browser/generation_parameters.mjs
@@ -1,3 +1,4 @@
+import { addCanvasNode } from "./canvas_creation.mjs";
import { chooseGenerationModel } from "./model_picker.mjs";
/** UI -> saved intent -> frozen request -> real media -> reload, with isolated models. */
import assert from "node:assert/strict";
@@ -86,13 +87,7 @@ try {
page.on("pageerror", (e) => errors.push(e.message));
await page.goto(`${base}/ai-tool/ai-canvas/${id}`);
await page.getByText("已保存到本机", { exact: true }).waitFor();
- await page
- .getByRole("toolbar", { name: "画布创作工具" })
- .getByRole("button", {
- name: { image: "添加图片", video: "添加视频", audio: "添加音频" }[kind],
- exact: true,
- })
- .click();
+ await addCanvasNode(page, { image: "图片", video: "视频", audio: "音频" }[kind]);
await chooseGenerationModel(page, `config:${config.id}`);
await page
.getByRole("textbox", {
diff --git a/tests/browser/heif_upload_recovery.mjs b/tests/browser/heif_upload_recovery.mjs
index e82473451..8f73cfbbc 100644
--- a/tests/browser/heif_upload_recovery.mjs
+++ b/tests/browser/heif_upload_recovery.mjs
@@ -1,4 +1,5 @@
/** HEIF upload failures and save acknowledgements, including the production build. */
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
import { mkdir, readFile } from "node:fs/promises";
import { basename } from "node:path";
@@ -77,8 +78,8 @@ try {
if (freshNode) {
await page.route("**/commands", commandRoute);
await page.route("**/browser-image", previewRoute);
- await page.getByRole("button", { name: mode === "video-reference"
- ? (en ? "Add Video" : "添加视频") : (en ? "Add Image" : "添加图片"), exact: true }).click();
+ const label = mode === "video-reference" ? (en ? "Video" : "视频") : (en ? "Image" : "图片");
+ await addCanvasNode(page, label);
targetNodeId = await page.locator(".react-flow__node").getAttribute("data-id");
assert.ok(targetNodeId, "capture the original upload target identity");
} else if (mode === "failure") await page.route("**/browser-image", previewRoute);
diff --git a/tests/browser/image_quality_test.mjs b/tests/browser/image_quality_test.mjs
index 3e052aa23..66f86d3d7 100644
--- a/tests/browser/image_quality_test.mjs
+++ b/tests/browser/image_quality_test.mjs
@@ -1,3 +1,4 @@
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
import { launchBrowser } from "./engine.mjs";
@@ -31,12 +32,12 @@ const errors = [];
try {
for (const locale of ["zh-CN", "en-US"]) {
const labels = locale === "zh-CN" ? {
- saved: "已保存到本机", toolbar: "画布创作工具", add: "添加图片",
+ saved: "已保存到本机", nodeType: "图片",
prompt: "生成提示词", parameters: "生成参数", panel: "生成参数设置",
close: "关闭参数", quality: "图片质量", values: ["自动", "低", "中", "高"],
generate: "提交生成",
} : {
- saved: "Saved on this device", toolbar: "Canvas creation tools", add: "Add Image",
+ saved: "Saved on this device", nodeType: "Image",
prompt: "Prompt", parameters: "Generation settings", panel: "Generation settings",
close: "Close settings", quality: "Image quality", values: ["Auto", "Low", "Medium", "High"],
generate: "Generate",
@@ -64,7 +65,7 @@ try {
try {
await page.goto(`${base}/ai-tool/ai-canvas/${id}`);
await page.getByText(labels.saved, { exact: true }).waitFor();
- await page.getByRole("toolbar", { name: labels.toolbar }).getByRole("button", { name: labels.add, exact: true }).click();
+ await addCanvasNode(page, labels.nodeType);
await chooseGenerationModel(page, `config:${models[0].id}`);
await page.getByRole("textbox", { name: labels.prompt, exact: true }).fill("A lighthouse by the sea");
const open = () => page.getByRole("button", { name: labels.parameters, exact: true }).click();
diff --git a/tests/browser/jiuwenswarm_picker.mjs b/tests/browser/jiuwenswarm_picker.mjs
index 9e60fcd5c..c5e0a3c08 100644
--- a/tests/browser/jiuwenswarm_picker.mjs
+++ b/tests/browser/jiuwenswarm_picker.mjs
@@ -99,7 +99,8 @@ try {
);
await page.goto(`${base}/ai-tool/ai-canvas/${projectId}`);
await page.getByText("已保存到本机", { exact: true }).waitFor();
- await page.getByRole("button", { name: "与 AI 对话", exact: true }).click();
+ const chatToggle = page.getByRole("button", { name: "与 AI 对话", exact: true });
+ if (await chatToggle.getAttribute("aria-expanded") === "false") await chatToggle.click();
const trigger = page.getByRole("button", { name: /^Agent:/ });
await trigger.click();
await page
@@ -166,7 +167,7 @@ try {
await page.waitForTimeout(100);
}
await page.reload();
- await page.getByRole("button", { name: "与 AI 对话", exact: true }).click();
+ if (await chatToggle.getAttribute("aria-expanded") === "false") await chatToggle.click();
await page
.getByRole("button", {
name: "Agent:JiuwenSwarm · Swarm Alternate",
diff --git a/tests/browser/kimi_real.mjs b/tests/browser/kimi_real.mjs
index 8cb8ccb15..e6f634d60 100644
--- a/tests/browser/kimi_real.mjs
+++ b/tests/browser/kimi_real.mjs
@@ -119,7 +119,10 @@ try {
await page.locator(".cw-model-setup-row")
.filter({ hasText: locale === "zh-CN" ? "文本模型" : "Text model" })
.getByRole("button").click();
- await page.getByRole("button", { name: locale === "zh-CN" ? "对话" : "Chat", exact: true }).click();
+ const modelCategories = page.getByRole("navigation", {
+ name: locale === "zh-CN" ? "模型用途" : "Model categories", exact: true,
+ });
+ await modelCategories.getByRole("button", { name: locale === "zh-CN" ? "对话" : "Chat", exact: true }).click();
await page.getByRole("button", { name: locale === "zh-CN" ? "添加服务" : "Add service", exact: true }).click();
await page.getByRole("combobox", { name: locale === "zh-CN" ? "提供商" : "Provider", exact: true }).click();
await page.getByRole("listbox", { name: locale === "zh-CN" ? "提供商" : "Provider", exact: true })
diff --git a/tests/browser/kling_video.mjs b/tests/browser/kling_video.mjs
index 7b9518c2f..06f9e85b2 100644
--- a/tests/browser/kling_video.mjs
+++ b/tests/browser/kling_video.mjs
@@ -1,3 +1,4 @@
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
import { join } from "node:path";
@@ -56,7 +57,7 @@ const copy = {
close: "Close settings",
summary: "Text-to-video / first-last frame / image references",
flashSummary: "Text-to-video / first frame / image references",
- addVideo: "Add Video",
+ videoNode: "Video",
saved: "Saved on this device",
first: "Choose First frame",
last: "Choose Last frame",
@@ -76,7 +77,7 @@ const copy = {
close: "关闭设置",
summary: "文生视频 / 首尾帧 / 图片参考",
flashSummary: "文生视频 / 首帧 / 图片参考",
- addVideo: "添加视频",
+ videoNode: "视频",
saved: "已保存到本机",
first: "选择首帧",
last: "选择尾帧",
@@ -126,13 +127,13 @@ try {
});
await page.goto(`${base}/ai-tool/ai-canvas/${projectId}?creation=unified`);
await page.getByText(text.saved, { exact: true }).waitFor();
+ const chatToggle = page.locator(".cw-chat-button");
+ if (await chatToggle.getAttribute("aria-expanded") === "true") await chatToggle.click();
assert.equal(
await page.locator(".cw-chat-button").getAttribute("aria-expanded"),
"false",
);
- await page
- .getByRole("button", { name: text.addVideo, exact: true })
- .click();
+ await addCanvasNode(page, text.videoNode);
const initial = await until(
snapshot,
(value) => value.generationSpecs.length === 1,
@@ -198,9 +199,7 @@ try {
await page.getByRole("button", { name: text.close, exact: true }).click();
await page.reload();
await page.getByText(text.saved, { exact: true }).waitFor();
- await page
- .getByRole("button", { name: text.addVideo, exact: true })
- .click();
+ await addCanvasNode(page, text.videoNode);
const defaults = await until(
snapshot,
(value) => value.generationSpecs.length === 2,
@@ -501,13 +500,14 @@ try {
);
await unopened.getByText(text.saved, { exact: true }).waitFor();
await until(async () => assistantHeld, Boolean, "assistant read held");
+ // Keep the canvas-only path while the assistant's model selection is loading.
+ const chatToggle = unopened.locator(".cw-chat-button");
+ if (await chatToggle.getAttribute("aria-expanded") === "true") await chatToggle.click();
assert.equal(
await unopened.locator(".cw-chat-button").getAttribute("aria-expanded"),
"false",
);
- await unopened
- .getByRole("button", { name: text.addVideo, exact: true })
- .click();
+ await addCanvasNode(unopened, text.videoNode);
const defaultAfterAdding = await until(
() => call(`/api/creation/projects/${unopenedId}`),
(value) => value.generationSpecs.length === 1,
@@ -525,9 +525,7 @@ try {
(value) => Boolean(value.modelSelections?.video),
"assistant picker persisted",
);
- await unopened
- .getByRole("button", { name: text.addVideo, exact: true })
- .click();
+ await addCanvasNode(unopened, text.videoNode);
const afterLoading = await until(
() => call(`/api/creation/projects/${unopenedId}`),
(value) => value.generationSpecs.length === 2,
diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json
index ed6da9bc3..ade4e7490 100644
--- a/tests/browser/manifest.json
+++ b/tests/browser/manifest.json
@@ -1,5 +1,9 @@
{
"scripts": [
+ {
+ "file": "canvas_creation.mjs",
+ "helper": true
+ },
{
"file": "higgsfield_open.mjs",
"lanes": ["manual"],
@@ -94,6 +98,29 @@
],
"note": "Needs --assistant-fixture services; holds the fixture gate."
},
+ {
+ "file": "prompt_optimizer_workspace.mjs",
+ "previewSafe": true,
+ "lanes": ["extended", "production"],
+ "note": "Chat-selected loopback providers receive capability-appropriate media for canvas prompt rewrites; undo and delayed replies preserve the targeted draft."
+ },
+ {
+ "file": "play_downloaded_mp4.mjs",
+ "helper": true
+ },
+ {
+ "file": "chat_local_editing.mjs",
+ "previewSafe": true,
+ "lanes": ["extended", "production"],
+ "note": "Edits and reopens imported project media from an unsent chat with an empty model catalog."
+ },
+ {
+ "file": "assistant_result_cards.mjs",
+ "fixture": true,
+ "previewSafe": true,
+ "lanes": ["extendedFixture", "production"],
+ "note": "Exercises output cards with actual Agent jobs and isolated assistant and generation providers."
+ },
{
"file": "assistant_turn_timing.mjs",
"fixture": true,
@@ -124,6 +151,19 @@
],
"note": "Needs --assistant-fixture services."
},
+ {
+ "file": "workspace_mode_performance.mjs",
+ "previewSafe": true,
+ "lanes": ["manual"],
+ "note": "RFC #386 mode-switch timing in a production preview. Run alone on the target machine; prints first and warm samples for empty and twelve-image projects."
+ },
+ {
+ "file": "workspace_modes.mjs",
+ "fixture": true,
+ "previewSafe": true,
+ "lanes": ["extendedFixture", "production"],
+ "note": "Mode layout, drafts, references, viewport and active turn/job preservation in both languages; needs --assistant-fixture services."
+ },
{
"file": "bilingual_defaults.mjs",
"fixture": true,
@@ -135,7 +175,7 @@
"file": "first_run.mjs",
"previewSafe": true,
"lanes": ["gate"],
- "note": "First launch: assistant prerequisite, task-specific model setup and direct access to examples."
+ "note": "First launch: workspace mode, assistant prerequisite, task-specific model setup and direct access to examples."
},
{
"file": "selection_toolbar_hover.mjs",
diff --git a/tests/browser/new_image_node_outputs.mjs b/tests/browser/new_image_node_outputs.mjs
index 53ba0a6ad..a74c3857b 100644
--- a/tests/browser/new_image_node_outputs.mjs
+++ b/tests/browser/new_image_node_outputs.mjs
@@ -2,6 +2,7 @@
* unsent draft never makes the canvas query fail (#86).
* Uses the isolated creation_server.py; no generation is submitted.
*/
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
import { launchBrowser } from "./engine.mjs";
@@ -98,10 +99,7 @@ try {
.getByText("已保存到本机", { exact: true })
.waitFor({ state: "attached" });
- await page
- .getByRole("toolbar", { name: "画布创作工具" })
- .getByRole("button", { name: "添加图片", exact: true })
- .click();
+ await addCanvasNode(page, "图片");
assert.match(
await page
.getByRole("combobox", { name: "生成模型", exact: true })
diff --git a/tests/browser/play_downloaded_mp4.mjs b/tests/browser/play_downloaded_mp4.mjs
new file mode 100644
index 000000000..d47d676a8
--- /dev/null
+++ b/tests/browser/play_downloaded_mp4.mjs
@@ -0,0 +1,36 @@
+import { createHash } from "node:crypto";
+
+/** Decode a frame from the actual downloaded file, independently of the editor preview. */
+export async function playDownloadedMp4(page, button) {
+ const pending = page.waitForEvent("download");
+ await button.click();
+ const stream = await (await pending).createReadStream();
+ const chunks = [];
+ for await (const chunk of stream) chunks.push(chunk);
+ const bytes = Buffer.concat(chunks);
+ const playback = await page.evaluate(async encoded => {
+ const video = document.createElement("video");
+ video.muted = true;
+ video.src = "data:video/mp4;base64," + encoded;
+ let timer;
+ try {
+ const frame = new Promise((resolve, reject) => {
+ timer = setTimeout(() => reject(new Error("Downloaded MP4 produced no frame")), 10000);
+ video.requestVideoFrameCallback(resolve);
+ });
+ await Promise.all([frame, video.play()]);
+ const canvas = document.createElement("canvas");
+ canvas.width = canvas.height = 1;
+ const context = canvas.getContext("2d");
+ context.drawImage(video, 0, 0, 1, 1);
+ return { width: video.videoWidth, height: video.videoHeight, duration: video.duration,
+ pixel: [...context.getImageData(0, 0, 1, 1).data] };
+ } finally {
+ clearTimeout(timer);
+ video.pause();
+ video.removeAttribute("src");
+ video.load();
+ }
+ }, bytes.toString("base64"));
+ return { ...playback, fingerprint: "sha256:" + createHash("sha256").update(bytes).digest("hex") };
+}
diff --git a/tests/browser/prompt_optimizer_workspace.mjs b/tests/browser/prompt_optimizer_workspace.mjs
new file mode 100644
index 000000000..934f3584a
--- /dev/null
+++ b/tests/browser/prompt_optimizer_workspace.mjs
@@ -0,0 +1,288 @@
+/** Chat's selected Agent model handles canvas prompt rewrites. Every provider is loopback-only. */
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { once } from "node:events";
+import { createServer } from "node:http";
+import { setTimeout as delay } from "node:timers/promises";
+import { launchBrowser } from "./engine.mjs";
+
+const web = new URL(process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179");
+assert.ok(["http:", "https:"].includes(web.protocol) && ["127.0.0.1", "[::1]", "localhost"].includes(web.hostname),
+ "CREATION_WEB_URL must be a loopback HTTP origin");
+const base = web.origin;
+const setupSession = crypto.randomUUID();
+const headers = { "X-OpenDirector-Request": "1", "X-OpenDirector-Session": setupSession };
+async function api(path, body, method = body === undefined ? "GET" : "POST") {
+ const response = await fetch(base + "/api" + path, {
+ method, redirect: "error", headers: { ...headers, "Content-Type": "application/json" },
+ ...(body !== undefined && { body: JSON.stringify(body) }),
+ });
+ assert.ok(response.ok, await response.clone().text());
+ return response.status === 204 ? null : response.json();
+}
+
+async function until(check, label) {
+ const end = Date.now() + 20000;
+ while (Date.now() < end) {
+ if (await check()) return;
+ await delay(50);
+ }
+ throw new Error(label);
+}
+
+async function provider(name, inputModalities) {
+ const calls = [];
+ let hold;
+ const modelId = name + "-" + setupSession.slice(0, 8);
+ const server = createServer(async (req, res) => {
+ if (req.method !== "POST" || req.url !== "/v1/chat/completions") {
+ res.writeHead(404).end();
+ return;
+ }
+ let text = "";
+ for await (const chunk of req) text += chunk;
+ const payload = JSON.parse(text);
+ calls.push(payload);
+ const parts = payload.messages.find(message => message.role === "user").content;
+ const draft = typeof parts === "string" ? parts : parts.find(part => part.type === "text" && part.text.includes("Draft:")).text;
+ const markers = draft.match(/\[\[OD_REF_\d+\]\]/g) ?? [];
+ const gate = hold;
+ if (gate) {
+ await gate.release.promise;
+ }
+ if (res.destroyed) return;
+ const content = gate ? "A late rewrite that must never reach another draft." : "A steady tracking shot from " + name + ".";
+ const delta = { choices: [{ delta: { content: [content, ...markers].join(" ") }, finish_reason: "stop" }] };
+ res.writeHead(200, { "Content-Type": "text/event-stream" });
+ res.end("data: " + JSON.stringify(delta) + "\n\ndata: [DONE]\n\n");
+ });
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+ return {
+ modelId, calls, inputModalities, url: "http://127.0.0.1:" + server.address().port + "/v1",
+ holdNext() {
+ const gate = { release: Promise.withResolvers() };
+ hold = gate;
+ return { release() { hold = undefined; gate.release.resolve(); } };
+ },
+ async close() {
+ hold?.release.resolve();
+ const closed = once(server, "close");
+ server.close();
+ server.closeAllConnections();
+ await closed;
+ },
+ };
+}
+
+assert.ok((await api("/creation-test-health")).isolated);
+const clip = execFileSync("ffmpeg", [
+ "-nostdin", "-v", "error", "-f", "lavfi", "-i", "testsrc2=size=96x64:rate=8", "-t", "3",
+ "-c:v", "libx264", "-threads", "1", "-pix_fmt", "yuv420p", "-movflags", "frag_keyframe+empty_moov", "-f", "mp4", "pipe:1",
+]);
+const sound = execFileSync("ffmpeg", [
+ "-nostdin", "-v", "error", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=16000", "-t", "2",
+ "-c:a", "pcm_s16le", "-f", "wav", "pipe:1",
+]);
+const original = "Track the harbor at sunrise.";
+const otherDraft = "Leave this other shot alone.";
+async function project(withMedia) {
+ const id = crypto.randomUUID();
+ const root = "/creation/projects/" + id;
+ const name = "Prompt routing " + id.slice(0, 8);
+ const command = async (type, payload) => {
+ const receipt = await api(root + "/commands", { type, payload, projectId: id, commandId: crypto.randomUUID() });
+ assert.equal(receipt.status, "applied", JSON.stringify(receipt));
+ };
+ const state = () => api(root);
+ await command("project.create", { name });
+ await api(root + "/open", {});
+ if (withMedia) {
+ for (const [label, kind, bytes] of [["harbor.mp4", "video", clip], ["harbor.wav", "audio", sound]]) {
+ const handle = crypto.randomUUID();
+ const upload = await fetch(base + "/api" + root + "/uploads/" + handle, {
+ method: "PUT", redirect: "error", headers: { ...headers, "X-Asset-Name": label, "X-Asset-Kind": kind }, body: bytes,
+ });
+ assert.ok(upload.ok, await upload.text());
+ await command("asset.import", { uploadHandle: handle, name: label, expectedKind: kind });
+ }
+ }
+ const nodes = (withMedia ? [original, otherDraft] : [otherDraft]).map(prompt => ({
+ prompt, itemId: crypto.randomUUID(), specId: crypto.randomUUID(),
+ }));
+ const operations = nodes.flatMap(({ prompt, itemId, specId }, index) => [
+ { type: "generationSpec.create", payload: { spec: {
+ id: specId, projectId: id, kind: "video", purpose: "generation", prompt,
+ } } },
+ { type: "canvas.show", payload: { item: {
+ id: itemId, projectId: id, kind: "video", title: "Shot " + (index + 1),
+ position: { x: 60 + index * 380, y: 80 }, binding: { role: "generation", objectRef: { id: specId } },
+ } } },
+ ]);
+ (await state()).assets.forEach((asset, order) => operations.push({
+ type: "reference.add", payload: { reference: {
+ id: crypto.randomUUID(), projectId: id, targetSpecId: nodes[0].specId, binding: "pinned", order,
+ source: { assetId: asset.id, revision: asset.revision, kind: asset.kind, fingerprint: asset.fingerprint },
+ } },
+ }));
+ await command("creation.batch", { operations });
+ await api("/creation/sessions/" + setupSession, undefined, "DELETE");
+ return { id, name, root, nodes, state };
+}
+
+const providers = [], configs = [];
+let browser;
+try {
+ for (const [name, modalities] of [["native-media", ["text", "video", "audio"]], ["frames-only", ["text", "image"]]]) {
+ const fixture = await provider(name, modalities);
+ providers.push(fixture);
+ const config = await api("/model-configs", {
+ kind: "agent", modelId: fixture.modelId, url: fixture.url, inputModalities: fixture.inputModalities,
+ connectionType: "self_hosted", protocol: "openai", authMode: "none", capabilityAutoCheck: false,
+ });
+ configs.push(config);
+ }
+ const [native, frames] = providers;
+ const [first, second] = configs;
+ const source = await project(true), destination = await project(false);
+ const [target, bystander] = source.nodes;
+ const originalState = await source.state();
+ const destinationState = await destination.state();
+ browser = await launchBrowser();
+ const page = await browser.newPage({ locale: "en-US", viewport: { width: 1720, height: 1080 } });
+ page.setDefaultTimeout(20000);
+ const pageErrors = [];
+ page.on("pageerror", error => pageErrors.push(error.message));
+ await page.addInitScript(() => {
+ localStorage.setItem("opendirector.modelSetup.v1", "dismissed");
+ localStorage.setItem("opendirector.locale.v1", "en-US");
+ });
+ await page.goto(base + "/ai-tool/ai-canvas/" + source.id);
+ const mode = name => page.getByTestId("workspace-mode-" + name);
+ const selectModel = async config => {
+ await mode("agent").click();
+ const picker = page.locator("#canvas-assistant .cw-agent-picker .chat-picker-trigger");
+ await picker.click();
+ await page.getByRole("menuitemradio", { name: config.modelId, exact: true }).click();
+ await until(async () => (await api(source.root + "/assistant")).modelSelections.agent === config.id,
+ "Chat must persist the explicit choice " + config.modelId);
+ assert.ok((await picker.innerText()).includes(config.modelId));
+ await mode("canvas").click();
+ };
+ const prompt = page.getByRole("textbox", { name: "Prompt", exact: true });
+ const selectNode = async node => {
+ await page.locator('.react-flow__node[data-id="' + node.itemId + '"] .cw-placeholder-symbol').click();
+ await prompt.waitFor();
+ };
+ const visiblePrompt = () => prompt.evaluate(el => el.textContent.replaceAll("\u200b", ""));
+ const savedSpec = async () => (await source.state()).generationSpecs.find(spec => spec.id === target.specId);
+ const optimize = page.getByRole("button", { name: "Optimize prompt", exact: true });
+ const rewriteUrl = "/api" + source.root + "/items/" + target.itemId + "/optimize-prompt";
+ async function optimizeAndUndo(config, audioOmitted) {
+ const before = await visiblePrompt();
+ const savedBefore = await savedSpec();
+ const response = page.waitForResponse(r => r.url().endsWith(rewriteUrl));
+ await optimize.click();
+ const rewritten = await response;
+ assert.equal(rewritten.request().postDataJSON().assistantModel.modelId, config.id);
+ assert.ok(rewritten.ok(), await rewritten.text());
+ const result = await rewritten.json();
+ assert.equal(result.audioOmitted, audioOmitted);
+ const rewrittenText = result.prompt.split(" [[OD_REF_")[0];
+ assert.ok(rewrittenText.startsWith("A steady tracking shot from "));
+ await until(async () => (await visiblePrompt()).includes(rewrittenText) && (await savedSpec()).prompt.includes(rewrittenText),
+ "The rewrite must appear in the original editor and persist to its spec");
+ await prompt.press("ControlOrMeta+z");
+ await until(async () => await visiblePrompt() === before && (await savedSpec()).prompt === savedBefore.prompt,
+ "Undo must restore the original prompt in the editor and saved project");
+ assert.deepEqual((await savedSpec()).promptContent, savedBefore.promptContent);
+ }
+
+ await selectModel(second);
+ await selectNode(target);
+ // Author the draft in the real editor so both inline references and prose have a saved baseline.
+ await prompt.press("ControlOrMeta+End");
+ await page.keyboard.insertText(" Hold the frame.");
+ await until(async () => (await savedSpec()).prompt.endsWith("Hold the frame."), "the edited draft must persist");
+ const authored = await savedSpec();
+ assert.equal(authored.promptContent.filter(part => part.type === "reference").length, 2);
+ await optimizeAndUndo(second, true);
+ assert.equal(native.calls.length, 0, "the more capable first provider cannot replace Chat's chosen model");
+ assert.equal(frames.calls.length, 1);
+ const framePayload = frames.calls[0];
+ assert.equal(framePayload.model, frames.modelId);
+ const parts = framePayload.messages.find(message => message.role === "user").content;
+ const media = parts.filter(part => part.type !== "text");
+ assert.deepEqual(media.map(part => part.type), ["image_url", "image_url", "image_url"]);
+ for (const frame of media) {
+ assert.match(frame.image_url.url, /^data:image\/jpeg;base64,/);
+ const jpg = Buffer.from(frame.image_url.url.split(",")[1], "base64");
+ assert.equal(jpg.readUInt16BE(), 0xffd8);
+ assert.equal(jpg.readUInt16BE(jpg.length - 2), 0xffd9);
+ }
+ assert.ok(!JSON.stringify(parts).includes("harbor.wav"));
+
+ await selectModel(first);
+ await selectNode(target);
+ await optimizeAndUndo(first, false);
+ assert.equal(frames.calls.length, 1);
+ assert.equal(native.calls.length, 1);
+ const nativePayload = native.calls[0];
+ assert.equal(nativePayload.model, native.modelId);
+ const content = nativePayload.messages.find(message => message.role === "user").content;
+ assert.deepEqual(Buffer.from(content.find(part => part.type === "video_url").video_url.url.split(",")[1], "base64"), clip);
+ const audio = content.find(part => part.type === "input_audio").input_audio;
+ assert.equal(audio.format, "wav");
+ assert.deepEqual(Buffer.from(audio.data, "base64"), sound);
+
+ const switchProject = async project => {
+ await page.getByRole("button", { name: "Switch project", exact: true }).click();
+ await page.getByRole("menuitemradio", { name: project.name, exact: true }).click();
+ await page.locator(".cw-project-name").getByText(project.name, { exact: true }).waitFor();
+ };
+ // Deliver the old provider reply only after the new node/project has its own editor.
+ for (const change of ["node", "project"]) {
+ await selectNode(target);
+ const beforeCalls = native.calls.length;
+ const gate = native.holdNext();
+ const request = page.waitForRequest(r => r.url().endsWith(rewriteUrl));
+ try {
+ await optimize.click();
+ const sent = await request;
+ await until(() => native.calls.length === beforeCalls + 1, "the provider must receive the held request");
+ if (change === "project") await switchProject(destination);
+ await selectNode(change === "node" ? bystander : destination.nodes[0]);
+ assert.equal(await visiblePrompt(), otherDraft);
+ gate.release();
+ const reply = await sent.response();
+ if (reply) await reply.finished();
+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
+ assert.equal(await visiblePrompt(), otherDraft);
+ assert.deepEqual((await savedSpec()).promptContent, authored.promptContent);
+ } finally {
+ gate.release();
+ }
+ }
+ // Leaving the destination flushes pending document saves before checking the project snapshot.
+ await switchProject(source);
+ await selectNode(target);
+ assert.ok((await visiblePrompt()).includes("Track the harbor at sunrise."));
+ const final = await source.state();
+ assert.equal(final.generationSpecs.find(spec => spec.id === bystander.specId).prompt, otherDraft);
+ assert.deepEqual(final.references, originalState.references);
+ assert.deepEqual(final.jobs, []);
+ const targetState = await destination.state();
+ assert.deepEqual(targetState.generationSpecs, destinationState.generationSpecs);
+ assert.deepEqual(targetState.jobs, []);
+ assert.deepEqual((await api(source.root + "/assistant")).messages, []);
+ assert.deepEqual(pageErrors, []);
+ console.log("PASS Chat provider choice -> Canvas: three JPEG frames vs original MP4/WAV bytes, Ctrl+Z persisted twice, late node/project replies isolated",
+ { source: source.id, destination: destination.id, framesModel: frames.modelId, nativeModel: native.modelId });
+} finally {
+ await browser?.close();
+ try {
+ for (const config of configs) await api("/model-configs/" + config.id, undefined, "DELETE");
+ } finally {
+ await Promise.all(providers.map(item => item.close()));
+ }
+}
diff --git a/tests/browser/provider_settings.mjs b/tests/browser/provider_settings.mjs
index 4c7fdc90a..512154a19 100644
--- a/tests/browser/provider_settings.mjs
+++ b/tests/browser/provider_settings.mjs
@@ -36,12 +36,13 @@ try {
await page.getByRole("button", { name: "Settings", exact: true }).click();
await page.getByRole("button", { name: "Model connections", exact: true }).click();
await page.locator(".cw-model-setup-row").filter({ hasText: "Image model" }).getByRole("button").click();
+ const modelCategories = page.getByRole("navigation", { name: "Model categories", exact: true });
for (const [category, interfaces] of [
["Image", ["vLLM-Omni image API", "vLLM-Omni segmentation API"]],
["Audio", ["vLLM-Omni speech synthesis API", "vLLM-Omni music generation API", "vLLM-Omni transcription API"]],
["Chat", ["OpenAI compatible"]],
]) {
- await page.getByRole("button", { name: category, exact: true }).click();
+ await modelCategories.getByRole("button", { name: category, exact: true }).click();
await page.getByRole("button", { name: "Add service", exact: true }).click();
for (const name of interfaces) {
await page.getByRole("combobox", { name: "Provider", exact: true }).click();
@@ -53,7 +54,7 @@ try {
await page.screenshot({ path: `/tmp/provider-${category}.png` });
await page.getByRole("button", { name: "Cancel", exact: true }).click();
}
- await page.getByRole("button", { name: "Video", exact: true }).click();
+ await modelCategories.getByRole("button", { name: "Video", exact: true }).click();
await page.getByRole("button", { name: "Add service", exact: true }).click();
await page.getByRole("combobox", { name: "Provider", exact: true }).click();
assert.equal(await page.getByRole("option", { name: "Custom service", exact: true }).count(), 0);
@@ -116,7 +117,7 @@ try {
await page.screenshot({ path: "/tmp/provider-settings-video.png" });
await page.getByRole("button", { name: "Save service", exact: true }).click();
await page.getByRole("button", { name: "Add service", exact: true }).waitFor();
- await page.getByRole("button", { name: "Chat", exact: true }).click();
+ await modelCategories.getByRole("button", { name: "Chat", exact: true }).click();
await page.getByRole("button", { name: "Add service", exact: true }).click();
await page.getByRole("combobox", { name: "Provider", exact: true }).click();
await page.getByRole("option", { name: "DeepSeek", exact: true }).click();
@@ -186,7 +187,8 @@ try {
await page.getByRole("button", { name: "Cancel", exact: true }).click();
assert.equal((await call("/api/model-configs")).length, models.length);
await page.getByRole("button", { name: "Close settings", exact: true }).click();
- await page.locator(".cw-chat-button").click();
+ const chatToggle = page.locator(".cw-chat-button");
+ if (await chatToggle.getAttribute("aria-expanded") === "false") await chatToggle.click();
await page.getByRole("button", { name: "Model settings: Multimodal", exact: true }).click();
const picker = page.getByRole("dialog", { name: "Model settings", exact: true });
await picker.getByRole("tab", { name: /Video/ }).click();
diff --git a/tests/browser/reference_picker.mjs b/tests/browser/reference_picker.mjs
index 4af3cf582..de279d592 100644
--- a/tests/browser/reference_picker.mjs
+++ b/tests/browser/reference_picker.mjs
@@ -1,4 +1,5 @@
/** Isolated fixture only: native caret movement, dismissal and asset labels. */
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
const { chromium } = await import(
process.env.PLAYWRIGHT_MODULE ?? "playwright-core"
@@ -163,10 +164,7 @@ try {
const checked = [];
const persistedReferences = [];
for (const kind of ["图片", "视频"]) {
- await page
- .getByRole("toolbar", { name: "画布创作工具" })
- .getByRole("button", { name: `添加${kind}`, exact: true })
- .click();
+ await addCanvasNode(page, kind);
const editor = page.getByRole("textbox", {
name: "生成提示词",
exact: true,
diff --git a/tests/browser/reference_reconnect.mjs b/tests/browser/reference_reconnect.mjs
index 41f631f6d..15df90c5c 100644
--- a/tests/browser/reference_reconnect.mjs
+++ b/tests/browser/reference_reconnect.mjs
@@ -58,7 +58,8 @@ try {
context.fillRect(0, 0, 96, 64);
const source = createNode(
"image",
- { x: 150, y: 160 },
+ // Keep both nodes reachable after the canvas focuses the generated video.
+ { x: 390, y: 160 },
{
title: "Source",
mediaRole: "asset",
@@ -108,22 +109,14 @@ try {
const target = page.locator(
`.react-flow__node[data-id="${fixture.target}"]`,
);
+ const sourcePort = page.locator(
+ `.cw-node-reference-port[data-reference-source="${fixture.source}"][data-side="right"]`,
+ );
const connect = async (steps = 15) => {
- const sourceBox = await source.boundingBox(),
- targetBox = await target.boundingBox();
- assert.ok(sourceBox && targetBox);
- await page.mouse.move(
- sourceBox.x + sourceBox.width + 7,
- sourceBox.y + sourceBox.height / 2,
- );
- const port = page.getByRole("button", {
- name: "Add downstream reference node",
- exact: true,
- });
- await port.waitFor();
- const box = await port.boundingBox();
- assert.ok(box);
- await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await source.hover();
+ await sourcePort.hover();
+ const targetBox = await target.boundingBox();
+ assert.ok(targetBox);
await page.mouse.down();
await page.mouse.move(
targetBox.x + targetBox.width / 2,
diff --git a/tests/browser/structured_editors.mjs b/tests/browser/structured_editors.mjs
index dddbec9a2..b7dce78e6 100644
--- a/tests/browser/structured_editors.mjs
+++ b/tests/browser/structured_editors.mjs
@@ -113,8 +113,10 @@ try {
await page.getByLabel("Camera name", { exact: true }).fill("Saved camera");
const before = await state();
let blocked = true;
+ const commands = [];
const route = async (r) => {
const body = r.request().postDataJSON();
+ commands.push(body);
if (
blocked &&
body.payload?.operations?.some((op) => op.type === "editor.save")
@@ -128,15 +130,28 @@ try {
};
await page.route("**/commands", route);
await page.getByRole("button", { name: "Apply edits", exact: true }).click();
- await page
+ const refusal = page
.getByRole("alert")
- .filter({ hasText: "fixture: structured save rejected" })
- .waitFor();
+ .filter({ hasText: "fixture: structured save rejected" });
+ await refusal.waitFor();
assert.deepEqual((await state()).editorDocuments, before.editorDocuments);
assert.equal(
await page.getByRole("button", { name: "Apply edits", exact: true }).count(),
1,
);
+ if (kind === "tool") {
+ const dialog = page.locator(".cw-domain-dialog");
+ const commandCount = commands.length;
+ const message = await refusal.innerText();
+ for (const mode of ["agent", "canvas"]) {
+ await dialog.getByTestId(`workspace-mode-${mode}`).click();
+ await page.locator(`.cw-workspace[data-workspace-mode="${mode}"]`).waitFor();
+ assert.equal(await dialog.locator(".cw-tool-field textarea").inputValue(), "50mm\n85mm");
+ assert.equal(await refusal.innerText(), message);
+ assert.equal(commands.length, commandCount, "switching must not retry or save the rejected edit");
+ }
+ assert.deepEqual((await state()).editorDocuments, before.editorDocuments);
+ }
blocked = false;
await page.getByRole("button", { name: "Apply edits", exact: true }).click();
await page.locator(".cw-domain-dialog").waitFor({ state: "hidden" });
@@ -144,6 +159,16 @@ try {
await page.unroute("**/commands", route);
const committed = await state();
assert.notDeepEqual(committed.editorDocuments, before.editorDocuments);
+ if (kind === "tool") {
+ const saves = commands.filter((c) => c.payload.operations?.some((op) => op.type === "editor.save"));
+ assert.equal(saves.length, 2);
+ const editorId = before.canvasItems.find((item) => item.id === f.tool).binding.objectRef.id;
+ const original = before.editorDocuments.find((doc) => doc.id === editorId);
+ assert.deepEqual(saves[0].expectedVersions.find((version) => version.id === editorId),
+ { objectType: "editor_document", id: editorId, revision: original.revision });
+ assert.deepEqual(saves[1].expectedVersions, saves[0].expectedVersions,
+ "the explicit retry must use the original editor revision");
+ }
await page.reload();
await saved();
await open(f[kind]);
diff --git a/tests/browser/timeline_text_installed.mjs b/tests/browser/timeline_text_installed.mjs
index 6cb97ebbd..e0fda398b 100644
--- a/tests/browser/timeline_text_installed.mjs
+++ b/tests/browser/timeline_text_installed.mjs
@@ -1,3 +1,4 @@
+import { addCanvasNode } from "./canvas_creation.mjs";
import { spawnOwned as spawn, stopOwned, installedServerEnv } from "./host.mjs";
/** Actual installed-wheel UI; no Vite, repository imports, models, or user projects. */
import assert from "node:assert/strict";
@@ -114,10 +115,7 @@ try {
});
await page.goto(base + `/ai-tool/ai-canvas/${pid}`);
await page.getByText("Saved on this device", { exact: true }).waitFor();
- await page
- .getByRole("toolbar", { name: "Canvas creation tools", exact: true })
- .getByRole("button", { name: "Add Timeline", exact: true })
- .click();
+ await addCanvasNode(page, "Timeline");
const state = async () =>
await (
await page.request.get(base + `/api/creation/projects/${pid}`, {
diff --git a/tests/browser/timeline_workflow.mjs b/tests/browser/timeline_workflow.mjs
index 8b78dac51..92c8d8857 100644
--- a/tests/browser/timeline_workflow.mjs
+++ b/tests/browser/timeline_workflow.mjs
@@ -1,9 +1,11 @@
+import { addCanvasNode } from "./canvas_creation.mjs";
import { spawnOwned as spawn, stopOwned, pythonExecutable, sourcePythonPath, executable } from "./host.mjs";
/** Owns isolated API/Vite processes; restarts the API over the SAME project root. */
import assert from "node:assert/strict";
import { creationJourney } from "./creation_journey.mjs";
const full = process.argv.includes("--full-creation");
import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
import { mkdir, mkdtemp, readFile, writeFile, rename } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -325,37 +327,72 @@ try {
const state = () => call(`/api/creation/projects/${pid}`);
const doc = (s) => s.editorDocuments.find((d) => d.id === editorId);
+ const dialog = page.locator(".cw-timeline-dialog");
+ const playhead = dialog.locator(".cw-timeline-seek");
+ const mutations = [];
+ page.on("request", (request) => {
+ if (request.method() === "POST" && request.url().endsWith("/commands"))
+ mutations.push(request.postDataJSON());
+ });
+ async function switchWithEditorOpen(check) {
+ const count = mutations.length;
+ const position = await playhead.inputValue();
+ for (const mode of ["agent", "canvas"]) {
+ await dialog.getByTestId(`workspace-mode-${mode}`).click();
+ await page.locator(`.cw-workspace[data-workspace-mode="${mode}"]`).waitFor();
+ assert.equal(await dialog.isVisible(), true);
+ assert.equal(await playhead.inputValue(), position);
+ await check();
+ }
+ assert.equal(mutations.length, count, "mode switches submit no project command");
+ }
async function open() {
- await page
- .locator(`.react-flow__node[data-id="${itemId}"] .cw-node-title`)
- .click({ button: "right" });
- await page
- .getByRole("menuitem", { name: "Open editor", exact: true })
- .click();
+ const item = page.locator(`.react-flow__node[data-id="${itemId}"]`);
+ await item.getByRole("button", { name: "Open timeline", exact: true }).click();
await page.getByRole("button", { name: "Render MP4", exact: true }).waitFor();
}
await page.goto(full ? base + "/" : url);
await saved();
if (full) {
- await page.getByRole("button", { name: "Switch project", exact: true }).click();
- const [response] = await Promise.all([
- page.waitForResponse((r) => r.url().endsWith("/commands") &&
- r.request().postDataJSON()?.type === "project.create"),
- page.getByRole("menuitem", { name: "New canvas project", exact: true }).click(),
- ]);
- assert.equal((await response.json()).status, "applied");
- pid = response.request().postDataJSON().projectId;
- url = base + `/ai-tool/ai-canvas/${pid}`;
- const projectName = page.getByRole("textbox", { name: "Project name", exact: true });
- const name = "Full creation " + crypto.randomUUID().slice(0, 8);
- await projectName.fill(name);
- await projectName.press("Enter");
- await page.getByRole("button", { name, exact: true }).waitFor();
- await saved();
- await page
- .getByRole("toolbar", { name: "Canvas creation tools" })
- .getByRole("button", { name: "Add Timeline", exact: true })
- .click();
+ await page.waitForFunction(() => document.querySelector('#canvas-assistant [role="textbox"]')?.isContentEditable);
+ // The new project's chat can load after its name editor has already opened.
+ let releaseAssistant;
+ const assistantGate = new Promise(resolve => { releaseAssistant = resolve; });
+ const assistantPath = /\/creation\/projects\/[^/]+\/assistant$/;
+ await page.route(assistantPath, async route => {
+ const response = await route.fetch();
+ await assistantGate;
+ await route.fulfill({ response });
+ }, { times: 1 });
+ const releaseDeadline = setTimeout(() => releaseAssistant(), 20000);
+ try {
+ await page.getByRole("button", { name: "Switch project", exact: true }).click();
+ const [response] = await Promise.all([
+ page.waitForResponse((r) => r.url().endsWith("/commands") &&
+ r.request().postDataJSON()?.type === "project.create"),
+ page.getByRole("menuitem", { name: "New canvas project", exact: true }).click(),
+ ]);
+ assert.equal((await response.json()).status, "applied");
+ pid = response.request().postDataJSON().projectId;
+ url = base + `/ai-tool/ai-canvas/${pid}`;
+ const projectName = page.getByRole("textbox", { name: "Project name", exact: true });
+ await projectName.waitFor();
+ releaseAssistant();
+ await page.waitForFunction(() => document.querySelector('#canvas-assistant [role="textbox"]')?.isContentEditable);
+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
+ assert.equal(await projectName.isVisible(), true, "chat loading must keep the new project's name editor open");
+ assert.equal(await projectName.evaluate(element => element === document.activeElement), true);
+ const name = "Full creation " + crypto.randomUUID().slice(0, 8);
+ await projectName.fill(name);
+ await projectName.press("Enter");
+ await page.getByRole("button", { name, exact: true }).waitFor();
+ await saved();
+ } finally {
+ clearTimeout(releaseDeadline);
+ releaseAssistant();
+ await page.unroute(assistantPath);
+ }
+ await addCanvasNode(page, "Timeline");
const timelineItem = await until(async () =>
(await state()).canvasItems.find((i) => i.kind === "timeline"),
);
@@ -408,17 +445,28 @@ try {
});
return route.continue();
});
+ await playhead.press("ArrowRight");
+ assert.ok(Number(await playhead.inputValue()) > 0);
await page.getByRole("button", { name: "Apply edits", exact: true }).click();
- await page
- .getByRole("alert")
- .filter({ hasText: "fixture: editor save refused" })
- .waitFor();
- assert.equal(await page.locator(".cw-timeline-clip").count(), full ? 4 : 3);
- assert.equal(doc(await state()).data.tracks[0].clips.length, 0);
+ const refusal = dialog.getByRole("alert").filter({ hasText: "fixture: editor save refused" });
+ await refusal.waitFor();
+ const rejectedSave = mutations.at(-1);
+ const beforeRetry = doc(await state());
+ assert.equal(beforeRetry.data.tracks[0].clips.length, 0);
+ assert.deepEqual(rejectedSave.expectedVersions.find((v) => v.id === editorId), {
+ objectType: "editor_document", id: editorId, revision: beforeRetry.revision,
+ });
+ await switchWithEditorOpen(async () => {
+ assert.equal(await refusal.isVisible(), true);
+ assert.equal(await page.locator(".cw-timeline-clip").count(), full ? 4 : 3);
+ assert.deepEqual(doc(await state()), beforeRetry);
+ });
reject = false;
await page.getByRole("button", { name: "Apply edits", exact: true }).click();
await page.locator(".cw-timeline-dialog").waitFor({ state: "hidden" });
await saved();
+ const retriedSave = mutations.findLast((entry) => entry.payload.operations?.some((op) => op.type === "editor.save"));
+ assert.deepEqual(retriedSave, rejectedSave, "retry replays the same draft, CAS basis and command ID");
const first = doc(await state());
assert.equal(first.data.tracks[0].clips[0].speed, 2);
assert.equal(first.data.tracks[1].clips[0].volume, 0.3);
@@ -432,8 +480,34 @@ try {
await open();
const reopened = doc(await state());
assert.deepEqual(reopened, first);
- async function renderAndDownload(name) {
- await page.getByRole("button", { name: "Render MP4", exact: true }).click();
+
+ // Give the real player headroom so the natural end cannot mask a reset.
+ await dialog.locator(".cw-timeline-clip.visual").first().click();
+ const clipSpeed = dialog.getByLabel(/Playback speed/);
+ const originalSpeed = await clipSpeed.inputValue();
+ await clipSpeed.selectOption("0.25");
+ await playhead.press("Home");
+ await playhead.press("PageUp");
+ const readPosition = () => playhead.evaluate((slider) => slider.valueAsNumber);
+ const start = await readPosition();
+ assert.ok(start > 0 && start < Number(await playhead.getAttribute("max")) / 2);
+ const pause = dialog.getByRole("button", { name: "Pause the timeline", exact: true });
+ await dialog.getByRole("button", { name: "Play the timeline", exact: true }).click();
+ const commandCount = mutations.length;
+ for (const mode of ["agent", "canvas"]) {
+ await pause.waitFor();
+ const before = await readPosition();
+ await dialog.getByTestId(`workspace-mode-${mode}`).click();
+ await page.locator(`.cw-workspace[data-workspace-mode="${mode}"]`).waitFor();
+ assert.equal(await pause.isVisible(), true);
+ assert.ok(await readPosition() >= before, "playing timeline does not jump backwards");
+ await until(async () => await readPosition() > before);
+ }
+ await pause.click();
+ assert.equal(mutations.length, commandCount, "playing through both mode switches sends no project command");
+ await clipSpeed.selectOption(originalSpeed);
+
+ async function downloadRender(name) {
await page
.getByRole("button", { name: "Download MP4", exact: true })
.waitFor({ timeout: 60000 });
@@ -443,7 +517,43 @@ try {
await (await download).saveAs(path);
return path;
}
- const one = await renderAndDownload("first.mp4");
+ // Let the first second of this clip render, then hold the next real audio
+ // buffer so the two mode clicks happen partway through the same encode.
+ let releaseMix;
+ let mixStarted = false;
+ let mixedSeconds = 0;
+ const mixGate = new Promise((resolve) => { releaseMix = resolve; });
+ await page.exposeFunction("observeTimelineMix", (seconds) => {
+ const firstBuffer = mixedSeconds === 0;
+ mixedSeconds += seconds;
+ if (firstBuffer) return;
+ mixStarted = true;
+ return mixGate;
+ });
+ await page.evaluate(() => {
+ const proto = OfflineAudioContext.prototype;
+ const start = proto.startRendering;
+ proto.startRendering = async function () {
+ const buffer = await start.call(this);
+ await window.observeTimelineMix(buffer.duration);
+ return buffer;
+ };
+ });
+ try {
+ await dialog.getByRole("button", { name: "Render MP4", exact: true }).click();
+ await until(() => mixStarted);
+ const progress = () => dialog.getByRole("progressbar").evaluate((bar) => bar.value);
+ const beforeSwitch = await progress();
+ assert.ok(beforeSwitch > 0 && beforeSwitch < 1, "the encode must be in progress before switching");
+ await switchWithEditorOpen(async () => {
+ assert.equal(await dialog.getByRole("button", { name: "Cancel rendering", exact: true }).isEnabled(), true);
+ assert.equal(await dialog.getByRole("button", { name: "Download MP4", exact: true }).count(), 0);
+ assert.ok(await progress() >= beforeSwitch, "switching must retain render progress");
+ });
+ } finally {
+ releaseMix();
+ }
+ const one = await downloadRender("first.mp4");
const info = probe(one);
assert.ok(Math.abs(Number(info.format.duration) - (full ? 2 : 1.5)) < 0.12);
assert.ok(info.streams.some((s) => s.codec_type === "audio"));
@@ -476,14 +586,62 @@ try {
energy += samples.readFloatLE(i) ** 2;
const rms = Math.sqrt(energy / (samples.length / 4));
assert.ok(rms > 0.015 && rms < 0.04, rms);
- await page
- .getByRole("button", { name: "Add rendered video to canvas", exact: true })
- .click();
+ const publish = dialog.getByRole("button", { name: "Add rendered video to canvas", exact: true });
+ const download = dialog.getByRole("button", { name: "Download MP4", exact: true });
+ await switchWithEditorOpen(async () => {
+ assert.equal(await publish.isEnabled(), true);
+ assert.equal(await download.isEnabled(), true);
+ });
+ let releasePublication;
+ const publicationGate = new Promise((resolve) => { releasePublication = resolve; });
+ const publicationAttempts = [];
+ const delayPublication = async (route) => {
+ const body = route.request().postDataJSON();
+ if (body.type !== "timeline.publishRender") return route.continue();
+ publicationAttempts.push(body);
+ if (publicationAttempts.length === 1) {
+ await publicationGate;
+ return route.fulfill({ status: 503, json: { detail: "fixture: publication unavailable" } });
+ }
+ return route.continue();
+ };
+ await page.route("**/commands", delayPublication);
+ try {
+ await publish.click();
+ await until(() => publicationAttempts.length === 1);
+ await switchWithEditorOpen(async () => {
+ const publishing = dialog.getByRole("button", { name: "Adding video to canvas…", exact: true });
+ assert.equal(await publishing.isDisabled(), true);
+ assert.equal(publicationAttempts.length, 1);
+ });
+ } finally {
+ releasePublication();
+ }
+ const publicationError = dialog.getByRole("alert").filter({ hasText: "fixture: publication unavailable" });
+ await publicationError.waitFor();
+ const pendingAssets = (await state()).assets.length;
+ await switchWithEditorOpen(async () => {
+ assert.equal(await publicationError.isVisible(), true);
+ assert.equal(await publish.isEnabled(), true);
+ assert.equal(await download.isEnabled(), true);
+ });
+ await publish.click();
await page.getByRole("button", { name: "Added to canvas", exact: true }).waitFor();
- const published = await state(),
- output = published.assets.find((a) => a.provenance.source === "rendered");
- assert.ok(output);
- assert.equal(output.provenance.editorDocumentId, editorId);
+ await page.unroute("**/commands", delayPublication);
+ assert.equal(publicationAttempts.length, 2);
+ assert.deepEqual(publicationAttempts[1], publicationAttempts[0]);
+ const published = await state();
+ const outputs = published.assets.filter((a) =>
+ a.provenance.source === "rendered" && a.provenance.editorDocumentId === editorId);
+ assert.equal(outputs.length, 1, "the timeline must publish a single rendered asset");
+ const [output] = outputs;
+ assert.equal(published.assets.length, pendingAssets, "publication retry uses the same rendered bytes");
+ assert.equal(publicationAttempts[0].payload.editorId, editorId);
+ assert.equal(publicationAttempts[0].payload.itemId, itemId);
+ assert.equal(output.projectId, pid);
+ assert.equal(output.fingerprint, "sha256:" + createHash("sha256").update(await readFile(one)).digest("hex"));
+ assert.ok(Math.abs(mixedSeconds - Number(info.format.duration)) < 0.12,
+ "mode switches and publication retries must mix only one timeline's worth of audio");
assert.equal(output.provenance.editorRevision, first.revision);
assert.equal(output.provenance.sources.length, full ? 4 : 3);
console.log(
@@ -531,9 +689,16 @@ try {
};
await page.route("**/commands", hold);
await page.getByRole("button", { name: "Render MP4", exact: true }).click();
- await until(() => saveStarted);
- await page.getByRole("button", { name: "Cancel rendering", exact: true }).click();
- releaseSave();
+ try {
+ await until(() => saveStarted);
+ await switchWithEditorOpen(async () => {
+ assert.equal(await dialog.getByRole("button", { name: "Cancel rendering", exact: true }).isEnabled(), true);
+ assert.equal(await dialog.getByRole("button", { name: "Render MP4", exact: true }).isDisabled(), true);
+ });
+ await dialog.getByRole("button", { name: "Cancel rendering", exact: true }).click();
+ } finally {
+ releaseSave();
+ }
await page
.getByRole("button", { name: "Cancel rendering", exact: true })
.waitFor({ state: "hidden" });
@@ -542,7 +707,36 @@ try {
await page.getByRole("button", { name: "Download MP4", exact: true }).count(),
0,
);
- const two = await renderAndDownload("second.mp4");
+ const outputId = publicationAttempts[0].payload.outputId;
+ // A second writer locks the existing output before rendering captures it.
+ async function setOutputLocked(locked) {
+ await page.evaluate(async ({ pid, outputId, locked }) => {
+ const { creationClient, objectVersion } = await import("/src/backend/creationClient.ts");
+ const client = creationClient(pid);
+ const output = (await client.refresh()).canvasItems.find((item) => item.id === outputId);
+ await client.command("canvas.update", { itemId: outputId, locked }, [objectVersion("canvas_item", output)]);
+ }, { pid, outputId, locked });
+ }
+ await setOutputLocked(true);
+ await dialog.getByRole("button", { name: "Render MP4", exact: true }).click();
+ const two = await downloadRender("second.mp4");
+ const publishReply = page.waitForResponse((r) => r.url().endsWith("/commands") &&
+ r.request().method() === "POST" && r.request().postDataJSON().type === "timeline.publishRender");
+ await publish.click();
+ const lockedReceipt = await (await publishReply).json();
+ assert.equal(lockedReceipt.status, "rejected");
+ assert.ok(lockedReceipt.issues.some((issue) => issue.code === "role_restricted"));
+ const lockError = dialog.getByRole("alert");
+ await lockError.waitFor();
+ const lockMessage = await lockError.innerText();
+ await switchWithEditorOpen(async () => {
+ assert.equal(await lockError.innerText(), lockMessage);
+ assert.equal(await download.isEnabled(), true);
+ const target = (await state()).canvasItems.find((item) => item.id === outputId);
+ assert.equal(target.locked, true);
+ assert.equal(target.binding.objectRef.assetId, output.id);
+ });
+ await setOutputLocked(false);
const updated = doc(await state());
assert.deepEqual(
updated.data.tracks[0].clips.map((c) => c.id),
@@ -596,9 +790,47 @@ try {
} finally {
await rename(sourcePath + ".held", sourcePath);
}
+
+ // After an external edit, switching must not silently advance the dirty
+ // editor's version basis. Its retry still conflicts with the saved revision.
+ await dialog.locator(".cw-timeline-clip.visual").first().click();
+ const speed = dialog.getByLabel(/Playback speed/);
+ await speed.selectOption("2");
+ const changedDoc = await page.evaluate(async ({ pid, editorId }) => {
+ const { creationClient, objectVersion } = await import("/src/backend/creationClient.ts");
+ const client = creationClient(pid);
+ const current = (await client.refresh()).editorDocuments.find((entry) => entry.id === editorId);
+ await client.command("editor.save", {
+ document: { ...current, data: { ...current.data, fps: 30 } },
+ }, [objectVersion("editor_document", current)]);
+ return client.snapshot.editorDocuments.find((entry) => entry.id === editorId);
+ }, { pid, editorId });
+ async function attemptStaleSave() {
+ const response = page.waitForResponse((r) => r.url().endsWith("/commands") &&
+ r.request().method() === "POST" &&
+ r.request().postDataJSON().payload.operations?.some((op) => op.type === "editor.save"));
+ await dialog.getByRole("button", { name: "Apply edits", exact: true }).click();
+ const reply = await response;
+ const receipt = await reply.json();
+ assert.equal(receipt.status, "rejected");
+ assert.ok(receipt.issues.some((issue) => issue.code === "revision_conflict"));
+ return reply.request().postDataJSON().expectedVersions.find((version) => version.id === editorId);
+ }
+ const staleBasis = await attemptStaleSave();
+ assert.ok(staleBasis.revision < changedDoc.revision);
+ const conflict = dialog.getByRole("alert");
+ await conflict.waitFor();
+ const conflictMessage = await conflict.innerText();
+ await switchWithEditorOpen(async () => {
+ assert.equal(await speed.inputValue(), "2");
+ assert.equal(await conflict.innerText(), conflictMessage);
+ assert.deepEqual(doc(await state()), changedDoc);
+ });
+ assert.deepEqual(await attemptStaleSave(), staleBasis);
+ assert.deepEqual(doc(await state()), changedDoc);
assert.deepEqual(errors, []);
console.log(
- "PASS cancelled render produces no result; missing source refuses rendering and preserves the editor",
+ "PASS workspace switches preserve playhead, refused drafts, conflicting versions, locked output and retryable publication",
);
console.log(
"PASS actual service restart, stable source identities, UI speed/order edits and second playable export",
diff --git a/tests/browser/tool_drafts.mjs b/tests/browser/tool_drafts.mjs
index b1f05d973..08d84134f 100644
--- a/tests/browser/tool_drafts.mjs
+++ b/tests/browser/tool_drafts.mjs
@@ -1,3 +1,4 @@
+import { addCanvasNode } from "./canvas_creation.mjs";
import { chooseGenerationModel } from "./model_picker.mjs";
/** Saved parameters and real PNG mask -> fixed tool input -> editable output. */
import assert from "node:assert/strict";
@@ -67,10 +68,7 @@ async function open(id) {
try {
await page.goto(`${base}/ai-tool/ai-canvas/${projectId}`);
await saved();
- await page
- .getByRole("toolbar", { name: "画布创作工具" })
- .getByRole("button", { name: "添加图片", exact: true })
- .click();
+ await addCanvasNode(page, "图片");
await chooseGenerationModel(page, { label: "fixture-image" });
await page
.getByRole("textbox", { name: "生成提示词", exact: true })
diff --git a/tests/browser/voice_library.mjs b/tests/browser/voice_library.mjs
index 783dd4348..b02b722b4 100644
--- a/tests/browser/voice_library.mjs
+++ b/tests/browser/voice_library.mjs
@@ -1,4 +1,5 @@
/** Full bilingual voice-library UI with real storage/media and mocked provider HTTP. */
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdir } from "node:fs/promises";
@@ -157,8 +158,7 @@ const copy = {
url: "Service URL (Base URL)", saveService: "Save service", manage: "Manage",
addModel: "Add manually", unsupportedModel: "Unsupported MiniMax speech model. Choose a model from the preset.",
cancel: "Cancel", closeSettings: "Close settings",
- tools: "Canvas creation tools",
- add: "Add Audio",
+ nodeType: "Audio",
model: "Generation model",
prompt: "Text to read",
textLimit: "This model accepts up to 3000 prompt characters. Shorten the prompt and try again.",
@@ -202,8 +202,7 @@ const copy = {
url: "服务地址(Base URL)", saveService: "保存服务", manage: "管理",
addModel: "手动添加", unsupportedModel: "不支持该 MiniMax 语音型号,请选择预设中的型号。",
cancel: "取消", closeSettings: "关闭设置",
- tools: "画布创作工具",
- add: "添加音频",
+ nodeType: "音频",
model: "生成模型",
prompt: "朗读文本",
textLimit: "当前模型的提示词最多 3000 个字符,请缩短后重试。",
@@ -505,10 +504,7 @@ try {
timeout: reopenTimeout,
});
await waitForSaved(page, L.saved);
- await page
- .getByRole("toolbar", { name: L.tools })
- .getByRole("button", { name: L.add, exact: true })
- .click();
+ await addCanvasNode(page, L.nodeType);
await selectModel(normal);
await page
.getByRole("textbox", { name: L.prompt, exact: true })
diff --git a/tests/browser/workspace_mode_performance.mjs b/tests/browser/workspace_mode_performance.mjs
new file mode 100644
index 000000000..d929fe6e7
--- /dev/null
+++ b/tests/browser/workspace_mode_performance.mjs
@@ -0,0 +1,194 @@
+/** RFC #386 mode-switch budgets. Run with CREATION_WEB_URL pointing to
+ * a production preview and an isolated creation API. No model calls.
+ */
+import assert from "node:assert/strict";
+import { launchBrowser } from "./engine.mjs";
+
+const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179";
+const headers = { "X-OpenDirector-Request": "1", "Content-Type": "application/json" };
+const viewport = { width: 1700, height: 1100 };
+const sampleCount = Number(process.env.WORKSPACE_MODE_SAMPLES ?? 10);
+assert.ok(Number.isInteger(sampleCount) && sampleCount > 0);
+
+async function api(path, options) {
+ const response = await fetch(base + "/api" + path, { headers, ...options });
+ assert.ok(response.ok, await response.clone().text());
+ return response;
+}
+
+async function createProject() {
+ const projectId = crypto.randomUUID();
+ await api(`/creation/projects/${projectId}/commands`, {
+ method: "POST",
+ body: JSON.stringify({ projectId, commandId: crypto.randomUUID(),
+ type: "project.create", payload: { name: "Mode budget " + projectId } }),
+ });
+ return projectId;
+}
+
+async function openPage(browser, id, start) {
+ const page = await browser.newPage({ viewport, locale: "en-US" });
+ await page.addInitScript(mode => {
+ localStorage.setItem("opendirector.modelSetup.v1", "dismissed");
+ localStorage.setItem("opendirector.workspaceMode.v1", mode);
+ }, start);
+ await page.goto(`${base}/ai-tool/ai-canvas/${id}`);
+ await page.locator(`.cw-workspace[data-workspace-mode="${start}"][aria-busy="false"]`).waitFor();
+ return page;
+}
+
+async function closePage(page) {
+ // Each sample uses an empty browser cache. Release only this sample's lease.
+ const session = await page.evaluate(() => sessionStorage.getItem("opendirector.session.v1"));
+ assert.ok(session);
+ await page.close();
+ await api("/creation/sessions/" + session, { method: "DELETE" });
+}
+
+async function populateImages(browser, id) {
+ const page = await browser.newPage({ locale: "en-US" });
+ const session = crypto.randomUUID();
+ const root = `/creation/projects/${id}`;
+ const setupHeaders = { ...headers, "X-OpenDirector-Session": session };
+ async function command(type, payload) {
+ const response = await api(root + "/commands", { method: "POST", headers: setupHeaders,
+ body: JSON.stringify({ projectId: id, commandId: crypto.randomUUID(), type, payload }) });
+ const receipt = await response.json();
+ assert.equal(receipt.status, "applied", JSON.stringify(receipt));
+ }
+ try {
+ await api(root + "/open", { method: "POST", headers: setupHeaders, body: "{}" });
+ const files = await page.evaluate(() => {
+ const canvas = document.createElement("canvas");
+ canvas.width = canvas.height = 512;
+ const ctx = canvas.getContext("2d");
+ const pixels = ctx.createImageData(512, 512);
+ let seed = 77;
+ return Array.from({ length: 12 }, () => {
+ for (let i = 0; i < pixels.data.length; i += 4) {
+ seed = (Math.imul(1664525, seed) + 1013904223) >>> 0;
+ pixels.data.set([seed & 255, (seed >>> 8) & 255, (seed >>> 16) & 255, 255], i);
+ }
+ ctx.putImageData(pixels, 0, 0);
+ return canvas.toDataURL("image/png").split(",")[1];
+ });
+ });
+ let bytes = 0;
+ for (const [index, encoded] of files.entries()) {
+ const handle = crypto.randomUUID(), name = `frame-${index}.png`;
+ const body = Buffer.from(encoded, "base64");
+ bytes += body.length;
+ await api(root + "/uploads/" + handle, { method: "PUT", body, headers: {
+ ...setupHeaders, "Content-Type": "image/png", "X-Asset-Kind": "image", "X-Asset-Name": name,
+ } });
+ await command("asset.import", { uploadHandle: handle, name, expectedKind: "image" });
+ }
+ const { assets } = await (await api(root)).json();
+ assert.equal(new Set(assets.map(asset => asset.fingerprint)).size, files.length);
+ await command("creation.batch", { operations: assets.map((asset, i) => ({
+ type: "canvas.show", payload: { item: {
+ id: crypto.randomUUID(), projectId: id, kind: "image", title: asset.name,
+ width: 180, height: 180, position: { x: 80 + (i % 4) * 220, y: 100 + Math.floor(i / 4) * 230 },
+ binding: { role: "material", objectRef: { assetId: asset.id, revision: asset.revision,
+ fingerprint: asset.fingerprint, kind: asset.kind } },
+ } },
+ })) });
+ const { canvasItems } = await (await api(root)).json();
+ assert.deepEqual(new Set(canvasItems.map(item => item.binding.objectRef.assetId)),
+ new Set(assets.map(asset => asset.id)));
+ return { images: files.length, bytes };
+ } finally {
+ await page.close();
+ await api("/creation/sessions/" + session, { method: "DELETE" });
+ }
+}
+
+async function sample(page, destination, imageCount) {
+ const button = page.getByTestId(`workspace-mode-${destination}`);
+ await button.evaluate((button, { destination, imageCount }) => {
+ // Start at the trusted click timestamp, including any dispatch delay. Stop
+ // one frame after each observed DOM state to give it a rendering opportunity.
+ window.modeTiming = new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => reject(new Error(`No usable ${destination} layout`)), 10_000);
+ function hit(element) {
+ if (!element || element.closest("[inert]") || element.matches(":disabled")) return false;
+ const rect = element.getBoundingClientRect();
+ return element.contains(document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2));
+ }
+ button.addEventListener("click", event => {
+ if (!event.isTrusted) throw new Error("Expected a browser pointer click");
+ let feedback, ready, feedbackSeen = false, readySeen = false;
+ function frame() {
+ const elapsed = performance.now() - event.timeStamp;
+ if (feedbackSeen) feedback ??= elapsed;
+ if (readySeen) ready ??= elapsed;
+ if (ready !== undefined) {
+ clearTimeout(timeout);
+ resolve({ feedback, ready });
+ return;
+ }
+ feedbackSeen = button.getAttribute("aria-pressed") === "true" && hit(button);
+ if (feedbackSeen && document.querySelector(`.cw-workspace[aria-busy="false"][data-workspace-mode="${destination}"]`)) {
+ if (destination === "agent") {
+ readySeen = hit(document.querySelector('#canvas-assistant [contenteditable="true"]'));
+ } else {
+ const images = [...document.querySelectorAll(".cw-node-media .cw-image-preview")];
+ readySeen = hit(document.querySelector(".cw-rail-add")) && images.length === imageCount
+ && images.every(image => image.complete && image.naturalWidth > 0);
+ }
+ }
+ requestAnimationFrame(frame);
+ }
+ requestAnimationFrame(frame);
+ }, { capture: true, once: true });
+ });
+ }, { destination, imageCount });
+ await button.click();
+ return page.evaluate(() => window.modeTiming);
+}
+
+const health = await (await api("/creation-test-health")).json();
+assert.equal(health.isolated, true);
+const browser = await launchBrowser();
+try {
+ const report = { browser: browser.version(), viewport, fixtures: [], cases: [] };
+ for (const fixture of ["empty", "images"]) {
+ const id = await createProject();
+ const media = fixture === "images" ? await populateImages(browser, id) : { images: 0, bytes: 0 };
+ report.fixtures.push({ fixture, project: id, ...media });
+ for (const from of ["canvas", "agent"]) {
+ const to = from === "agent" ? "canvas" : "agent";
+ const rows = { first: [], warm: [] };
+ for (let n = 0; n < sampleCount; n++) {
+ const page = await openPage(browser, id, from);
+ try {
+ await page.locator('#canvas-assistant [contenteditable="true"]').waitFor();
+ if (from === "canvas" && media.images) {
+ await page.waitForFunction(count => {
+ const images = [...document.querySelectorAll(".cw-node-media .cw-image-preview")];
+ return images.length === count && images.every(image => image.complete && image.naturalWidth > 0);
+ }, media.images);
+ }
+ rows.first.push(await sample(page, to, media.images));
+ await sample(page, from, media.images);
+ rows.warm.push(await sample(page, to, media.images));
+ } finally {
+ await closePage(page);
+ }
+ }
+ for (const [phase, samples] of Object.entries(rows)) {
+ const ordered = metric => samples.map(row => row[metric]).sort((a, b) => a - b);
+ const p90 = values => values[Math.ceil(values.length * 0.9) - 1];
+ const ready = ordered("ready");
+ const middle = Math.floor(ready.length / 2);
+ const median = ready.length % 2 ? ready[middle] : (ready[middle - 1] + ready[middle]) / 2;
+ const feedbackP90 = p90(ordered("feedback")), readyP90 = p90(ready);
+ report.cases.push({ fixture, from, to, phase, feedbackP90, readyMedian: median, readyP90,
+ withinBudget: feedbackP90 <= 100 && median <= 500 && readyP90 <= 1000, samples });
+ }
+ }
+ }
+ console.log(JSON.stringify(report));
+} finally {
+ await browser.close();
+}
diff --git a/tests/browser/workspace_modes.mjs b/tests/browser/workspace_modes.mjs
new file mode 100644
index 000000000..f53a93cbf
--- /dev/null
+++ b/tests/browser/workspace_modes.mjs
@@ -0,0 +1,752 @@
+/** Mode changes preserve the same workspace and running work (#386).
+ * Requires creation_server.py --assistant-fixture; no real models are used.
+ */
+import { addCanvasNode } from "./canvas_creation.mjs";
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { mkdir } from "node:fs/promises";
+import { join } from "node:path";
+import { launchBrowser } from "./engine.mjs";
+import { chooseGenerationModel } from "./model_picker.mjs";
+
+const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5180";
+const headers = {
+ "X-OpenDirector-Request": "1",
+ "X-OpenDirector-Session": crypto.randomUUID(),
+ "Content-Type": "application/json",
+};
+async function api(path, body) {
+ const response = await fetch(base + "/api" + path, {
+ headers,
+ ...(body ? { method: "POST", body: JSON.stringify(body) } : {}),
+ });
+ assert.ok(response.ok, await response.clone().text());
+ return response.json();
+}
+async function until(read, matches, label) {
+ const deadline = Date.now() + 20000;
+ while (true) {
+ const value = await read();
+ if (matches(value)) return value;
+ assert.ok(Date.now() < deadline, `${label}: ${JSON.stringify(value)}`);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+}
+const health = await api("/creation-test-health");
+assert.equal(health.isolated, true);
+assert.equal(health.assistantFixture, true);
+const projectId = crypto.randomUUID();
+const root = `/creation/projects/${projectId}`;
+await api(root + "/commands", {
+ projectId,
+ commandId: crypto.randomUUID(),
+ type: "project.create",
+ payload: { name: `Workspace modes ${projectId.slice(0, 8)}` },
+});
+const state = () => api(root);
+const conversation = () => api(root + "/assistant");
+const browser = await launchBrowser();
+let page;
+const errors = [];
+try {
+ page = await browser.newPage({
+ locale: "zh-CN",
+ viewport: { width: 1720, height: 1120 },
+ });
+ page.setDefaultTimeout(15000);
+ const commands = [], stops = [];
+ page.on("pageerror", (error) => errors.push(error.message));
+ page.on("request", (request) => {
+ if (/\/assistant\/turns\/[^/]+\/stop$/.test(request.url()))
+ stops.push(request.url());
+ if (request.method() === "POST" && request.url().endsWith("/commands"))
+ commands.push(request.postDataJSON());
+ });
+ await page.route(/\/assistant\/runtimes(?:\?.*)?$/, (route) =>
+ route.fulfill({ json: [{
+ id: "default", label: "Default", group: "default", modelSource: "settings",
+ available: true, status: "ready", modelOverride: false, supportsSkills: true,
+ }] }),
+ );
+ await page.addInitScript(() => {
+ localStorage.setItem("opendirector.modelSetup.v1", "dismissed");
+ });
+ await page.goto(`${base}/ai-tool/ai-canvas/${projectId}`);
+ await page.locator('.cw-workspace[aria-busy="false"]').waitFor();
+ const workspace = page.locator("[data-workspace-mode]");
+ const canvas = page.getByTestId("canvas-region");
+ const assistant = page.locator("#canvas-assistant");
+ const editor = assistant.locator('[contenteditable="true"]').first();
+ const moveChat = assistant.locator(".cw-assistant-move-handle");
+ const placement = assistant.locator(".cw-assistant-placement-toggle");
+ const mode = (value) => page.getByTestId(`workspace-mode-${value}`);
+ const settleLayout = () => page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
+ const selectMode = async (value) => {
+ await mode(value).click();
+ await until(() => workspace.getAttribute("data-workspace-mode"), (current) => current === value, `mode ${value}`);
+ await settleLayout();
+ };
+ const viewport = () => page.locator(".react-flow__viewport").evaluate((element) => {
+ const value = new DOMMatrix(getComputedStyle(element).transform);
+ return [value.a, value.d, value.e, value.f];
+ });
+ const selection = () => page.locator(".react-flow__node.selected").evaluateAll((nodes) => nodes.map((node) => node.dataset.id).sort());
+ const editorText = () => editor.evaluate((element) => element.textContent.replaceAll("\u200b", ""));
+ async function setLocale(locale) {
+ const current = await page.locator("html").getAttribute("lang");
+ await page.getByRole("button", { name: current === "zh-CN" ? "设置" : "Settings", exact: true }).click();
+ await page.locator("#settings-language").selectOption(locale);
+ const theme = locale === "zh-CN" ? "dark" : "light";
+ await page.locator("#settings-theme").selectOption(theme);
+ await page.locator(".cw-settings-close").click();
+ assert.equal(await page.locator("html").getAttribute("lang"), locale);
+ assert.equal(await page.locator("html").getAttribute("data-theme"), theme);
+ }
+ async function screenshot(name) {
+ if (!process.env.CREATION_SCREENSHOTS) return;
+ await mkdir(process.env.CREATION_SCREENSHOTS, { recursive: true });
+ await page.screenshot({ path: join(process.env.CREATION_SCREENSHOTS, `workspace-${name}.png`) });
+ }
+ async function dragChat(destination) {
+ const handle = await moveChat.boundingBox();
+ const start = { x: handle.x + handle.width / 2, y: handle.y + handle.height / 2 };
+ await page.mouse.move(start.x, start.y);
+ await page.mouse.down();
+ const end = destination(start);
+ await page.mouse.move(end.x, end.y, { steps: 8 });
+ await page.mouse.up();
+ await settleLayout();
+ return assistant.boundingBox();
+ }
+ async function assertLayout(value) {
+ const chat = await assistant.boundingBox();
+ assert.ok(chat && await assistant.isVisible(), "chat remains visible");
+ if (value === "canvas") {
+ const area = await canvas.boundingBox();
+ assert.ok(area && await canvas.isVisible());
+ assert.ok(chat.x + chat.width <= area.x + 2, "chat is left of the canvas without overlapping it");
+ assert.ok(Math.abs(area.width / chat.width - 2) < 0.15, "default canvas/chat widths are 2:1");
+ } else {
+ assert.equal(await canvas.isVisible(), false, "agent mode hides the canvas");
+ assert.equal(await canvas.locator(".react-flow__node").evaluateAll((nodes) => nodes.some((node) => node.checkVisibility({ opacityProperty: true, visibilityProperty: true }))), false, "React Flow children must not paint through the hidden canvas");
+ assert.equal(await assistant.getByRole("navigation").count(), 0);
+ assert.ok(await assistant.locator("button[data-session-history]").isVisible());
+ const contentLeft = chat.x;
+ const contentRight = chat.x + chat.width;
+ for (const column of [assistant.locator(".cw-assistant-log"), assistant.locator(".cw-assistant-composer")]) {
+ const box = await column.boundingBox();
+ assert.ok(box && box.x >= contentLeft && box.x + box.width <= contentRight);
+ assert.ok(box.width <= 961, "messages and input keep a readable width");
+ assert.ok(Math.abs(box.x + box.width / 2 - (contentLeft + contentRight) / 2) < 3, "messages and input are centered in the conversation");
+ }
+ }
+ }
+
+ // A fresh browser starts in canvas mode with chat already expanded.
+ assert.equal(await workspace.getAttribute("data-workspace-mode"), "canvas");
+ await editor.waitFor();
+ assert.equal(await page.locator(".cw-chat-button").getAttribute("aria-expanded"), "true");
+ await assertLayout("canvas");
+ const dockRight = assistant.getByRole("button", { name: "停靠到右侧", exact: true });
+ assert.equal(await dockRight.innerText(), "");
+ assert.ok(await dockRight.locator("svg").isVisible());
+ await dockRight.hover();
+ await page.getByRole("tooltip", { name: "停靠到右侧", exact: true }).waitFor();
+ await dockRight.click();
+ await page.reload();
+ await page.locator('.cw-workspace[aria-busy="false"][data-chat-dock="right"]').waitFor();
+ const rightBox = await assistant.boundingBox();
+ const leftArea = await canvas.boundingBox();
+ assert.ok(leftArea.x + leftArea.width <= rightBox.x && leftArea.x <= 2);
+ const rightSeparator = assistant.getByRole("separator");
+ const rightWidth = Number(await rightSeparator.getAttribute("aria-valuenow"));
+ await rightSeparator.press("ArrowLeft");
+ assert.equal(Number(await rightSeparator.getAttribute("aria-valuenow")), rightWidth + 10);
+ const edge = await rightSeparator.boundingBox();
+ assert.ok(Math.abs(edge.x - rightBox.x) < 16);
+ await page.mouse.move(edge.x + edge.width / 2, edge.y + 80);
+ await page.mouse.down();
+ await page.mouse.move(edge.x - 45 + edge.width / 2, edge.y + 80, { steps: 5 });
+ await page.mouse.up();
+ assert.ok(Math.abs(Number(await rightSeparator.getAttribute("aria-valuenow")) - rightWidth - 55) <= 2);
+ await rightSeparator.dblclick();
+ await placement.click();
+ await assistant.locator(".cw-assistant-move-handle").press("ArrowLeft");
+ await dockRight.click();
+ assert.equal(await assistant.getAttribute("data-floating"), null);
+ await assistant.getByRole("button", { name: "停靠到左侧", exact: true }).click();
+ await assertLayout("canvas");
+ await page.setViewportSize({ width: 2560, height: 1440 });
+ await settleLayout();
+ await assertLayout("canvas");
+ await page.setViewportSize({ width: 1720, height: 1120 });
+ await settleLayout();
+ await until(conversation, (value) => !!value.modelSelections.agent, "default agent model must be ready");
+
+ await addCanvasNode(page, "图片");
+ await chooseGenerationModel(page, { label: "fixture-image" });
+ const prompt = "Keep the node composer prompt across modes";
+ await page.getByRole("textbox", { name: "生成提示词", exact: true }).fill(prompt);
+ const prepared = await until(state, (value) => value.generationSpecs.some((spec) => spec.prompt === prompt && spec.modelConfigId), "image configuration must persist");
+ const specId = prepared.generationSpecs.find((spec) => spec.prompt === prompt).id;
+ const selected = await selection();
+ assert.equal(selected.length, 1);
+
+ // Change zoom through the real canvas gesture, then wait for its view save.
+ const beforeZoom = await viewport();
+ const viewSaved = page.waitForResponse((response) => response.request().method() === "PUT" && response.url().includes(`${root}/views/`) && response.ok());
+ const canvasBox = await canvas.boundingBox();
+ await page.mouse.move(canvasBox.x + canvasBox.width * 0.8, canvasBox.y + canvasBox.height * 0.7);
+ await page.keyboard.down("Control");
+ try { await page.mouse.wheel(0, -180); } finally { await page.keyboard.up("Control"); }
+ await until(viewport, (value) => value[0] !== beforeZoom[0], "canvas zoom must change");
+ await viewSaved;
+ const savedViewport = await viewport();
+
+ const draft = "Keep this draft / 保留这份草稿";
+ await editor.fill(draft);
+ const beforeUpload = await until(conversation, (value) => value.draft === draft, "draft must be saved before upload");
+ const referenceName = "mode-reference.txt";
+ const referenceBytes = Buffer.from("Mode switch reference");
+ const uploadPath = `**/api${root}/uploads/*`;
+ const uploads = [];
+ const resumeUpload = Promise.withResolvers();
+ await page.route(uploadPath, async (route) => {
+ if (route.request().method() === "PUT") {
+ uploads.push(new URL(route.request().url()).pathname.split("/").at(-1));
+ await resumeUpload.promise;
+ }
+ await route.continue();
+ });
+ try {
+ const [chooser] = await Promise.all([
+ page.waitForEvent("filechooser"),
+ assistant.locator(".cw-assistant-upload").click(),
+ ]);
+ await chooser.setFiles({
+ name: referenceName, mimeType: "text/plain", buffer: referenceBytes,
+ });
+ await until(() => uploads.length, (count) => count > 0, "reference upload must be in flight");
+ for (const layout of ["agent", "canvas"]) {
+ await selectMode(layout);
+ const composer = assistant.locator(".cw-chat-reference-editor");
+ assert.ok(await composer.isVisible());
+ assert.equal(await composer.getAttribute("aria-disabled"), "true");
+ assert.ok((await composer.innerText()).includes(draft));
+ }
+ } finally {
+ resumeUpload.resolve();
+ }
+ const savedChat = await until(conversation, (value) => value.draft.includes(draft) && value.assets.length === 1, "draft and reference must persist");
+ await page.unroute(uploadPath);
+ const registered = commands.filter((command) => command.type === "asset.import" && command.payload.name === referenceName);
+ assert.equal(registered.length, 1);
+ assert.deepEqual(uploads, [registered[0].payload.uploadHandle], "one upload must register its original handle once");
+ assert.equal(savedChat.conversationId, beforeUpload.conversationId);
+ assert.deepEqual(savedChat.messages, beforeUpload.messages);
+ const [attachment] = savedChat.assets;
+ const fingerprint = "sha256:" + createHash("sha256").update(referenceBytes).digest("hex");
+ assert.equal(attachment.fingerprint, fingerprint);
+ const references = savedChat.draftContent.filter((part) => part.type === "reference");
+ assert.deepEqual(references.map((part) => [part.assetId, part.fingerprint]), [[attachment.id, fingerprint]]);
+ const imported = (await state()).assets.filter((asset) => asset.name === referenceName);
+ assert.deepEqual(imported.map((asset) => [asset.id, asset.fingerprint]), [[attachment.id, fingerprint]]);
+ const content = await page.request.get(`${base}/api${root}/assets/${attachment.id}/content`, { headers });
+ assert.ok(content.ok());
+ assert.deepEqual(await content.body(), referenceBytes);
+ const draftText = await editorText();
+ await editor.evaluate((element) => { window.__workspaceModeEditor = element; });
+ const snapshotBeforeSwitch = await state();
+ const commandCount = commands.length;
+
+ for (const locale of ["zh-CN", "en-US"]) {
+ await setLocale(locale);
+ const zh = locale === "zh-CN";
+ const floatLabel = zh ? "浮动聊天" : "Float chat";
+ const dockLabel = zh ? "停靠到左侧" : "Dock chat to the left";
+ assert.ok(await assistant.getByRole("button", { name: floatLabel, exact: true }).isVisible());
+ await assistant.getByRole("button", { name: zh ? "停靠到右侧" : "Dock chat to the right", exact: true }).click();
+ await settleLayout();
+ const rightPanel = await assistant.boundingBox();
+ const leftCanvas = await canvas.boundingBox();
+ assert.ok(leftCanvas.x + leftCanvas.width <= rightPanel.x + 1);
+ assert.deepEqual(await viewport(), savedViewport, "switching the dock side preserves the canvas viewport");
+ assert.deepEqual(await selection(), selected);
+ assert.equal(await editorText(), draftText);
+ const dockLeft = assistant.getByRole("button", { name: dockLabel, exact: true });
+ assert.equal(await dockLeft.innerText(), "");
+ await dockLeft.hover();
+ await page.getByRole("tooltip", { name: dockLabel, exact: true }).waitFor();
+ await dockLeft.click();
+ await settleLayout();
+ const separator = assistant.getByRole("separator");
+ const originalWidth = Number(await separator.getAttribute("aria-valuenow"));
+ const split = await separator.boundingBox();
+ const splitX = split.x + split.width / 2;
+ const splitY = split.y + split.height / 2;
+ await page.mouse.move(splitX, splitY);
+ await page.mouse.down();
+ await page.mouse.move(splitX - 72, splitY, { steps: 5 });
+ await page.mouse.up();
+ await settleLayout();
+ const resizedWidth = Number(await separator.getAttribute("aria-valuenow"));
+ assert.ok(Math.abs(resizedWidth - originalWidth + 72) <= 2);
+ await separator.dblclick();
+ assert.equal(Number(await separator.getAttribute("aria-valuenow")), originalWidth);
+ const docked = await assistant.boundingBox();
+ const undocked = await dragChat(({ x, y }) => ({ x: x + 240, y: y + 110 }));
+ assert.equal(await assistant.getAttribute("data-floating"), "true", "dragging the docked handle detaches chat");
+ assert.ok(undocked.x > docked.x + 50 && undocked.y > docked.y + 40);
+ assert.deepEqual([undocked.width, undocked.height], [460, 620]);
+ assert.equal(await separator.count(), 0, "the split resizer is only available when docked");
+ const expandedCanvas = await canvas.boundingBox();
+ assert.ok(expandedCanvas.x < 2 && expandedCanvas.width >= page.viewportSize().width - 2, "the floating chat releases its canvas column");
+ const offset = await dragChat(({ x, y }) => ({ x: x + 76, y: y - 44 }));
+ assert.deepEqual([offset.width, offset.height], [undocked.width, undocked.height]);
+ console.log("Chat layout", { locale, originalWidth, resizedWidth, undocked, offset });
+ assert.ok(Math.abs(offset.x - undocked.x - 76) <= 2 && Math.abs(offset.y - undocked.y + 44) <= 2, "the panel follows the pointer on both axes");
+ await moveChat.focus();
+ await page.keyboard.press("ArrowLeft");
+ await page.keyboard.press("ArrowDown");
+ await settleLayout();
+ const nudged = await assistant.boundingBox();
+ assert.ok(nudged.x < offset.x && nudged.y > offset.y, "arrow keys move the floating chat");
+ const view = page.viewportSize();
+ const lowerRight = await dragChat(() => ({ x: view.width - 1, y: view.height - 1 }));
+ assert.ok(lowerRight.x + lowerRight.width <= view.width && lowerRight.y + lowerRight.height <= view.height);
+ assert.ok(lowerRight.x + lowerRight.width >= view.width - 32 && lowerRight.y + lowerRight.height >= view.height - 32, "the bottom and right edges clamp to the workspace");
+ const upperLeft = await dragChat(() => ({ x: 1, y: 1 }));
+ const topbar = await page.locator(".cw-topbar").boundingBox();
+ assert.ok(upperLeft.x >= 0 && upperLeft.x <= 32 && upperLeft.y >= topbar.y + topbar.height && upperLeft.y <= topbar.y + topbar.height + 32, "the handle stays below the top bar and inside the left edge");
+ assert.equal(await dockLeft.innerText(), "");
+ assert.ok(await dockLeft.locator("svg").isVisible());
+ await dockLeft.focus();
+ await page.keyboard.press("Shift+Tab");
+ await page.keyboard.press("Tab");
+ const dockTip = page.getByRole("tooltip", { name: dockLabel, exact: true });
+ await dockTip.waitFor();
+ await page.keyboard.press("Escape");
+ await dockTip.waitFor({ state: "hidden" });
+ await dockLeft.press("Enter");
+ await assertLayout("canvas");
+ assert.deepEqual(await viewport(), savedViewport, "moving chat does not move the canvas");
+ assert.deepEqual(await selection(), selected);
+ assert.equal(await editorText(), draftText);
+ assert.equal(await editor.evaluate((element) => element === window.__workspaceModeEditor), true);
+ const rail = canvas.getByRole("toolbar", { name: zh ? "画布创作工具" : "Canvas creation tools" });
+ assert.equal(await rail.getByRole("button").count(), 3);
+ const add = rail.getByRole("button", { name: zh ? "添加节点" : "Add node", exact: true });
+ await add.click();
+ const nodeMenu = page.getByRole("menu", { name: zh ? "新建节点" : "New node", exact: true });
+ for (const name of zh ? ["文本", "图片", "视频", "音频", "时间线", "主体"] : ["Text", "Image", "Video", "Audio", "Timeline", "Subject"]) {
+ assert.ok(await nodeMenu.getByRole("menuitem", { name, exact: true }).isVisible());
+ }
+ assert.equal(await nodeMenu.getByRole("menuitem").count(), 6);
+ await page.keyboard.press("Escape");
+ assert.equal(await add.evaluate((element) => element === document.activeElement), true);
+ const switcher = page.getByRole("group", { name: locale === "zh-CN" ? "创作方式" : "Creation mode", exact: true });
+ for (const label of locale === "zh-CN" ? ["对话", "画布"] : ["Chat", "Canvas"]) {
+ assert.equal(await switcher.getByRole("button", { name: label, exact: true }).innerText(), label);
+ }
+ // Mouse activation keeps the editor's backwards selection and collapsed caret.
+ await editor.focus();
+ await editor.evaluate((element) => {
+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
+ let text;
+ while ((text = walker.nextNode())) {
+ if (text.textContent.includes("Keep this draft")) {
+ getSelection().setBaseAndExtent(text, 9, text, 2);
+ return;
+ }
+ }
+ throw Error("missing draft text");
+ });
+ const inputSelection = () => editor.evaluate((element) => {
+ const selection = getSelection();
+ return [document.activeElement === element, element.contains(selection.anchorNode),
+ selection.anchorOffset, selection.focusOffset, selection.toString()];
+ });
+ const backwards = await inputSelection();
+ assert.deepEqual(backwards.slice(0, 4), [true, true, 9, 2]);
+ await selectMode("agent");
+ assert.deepEqual(await inputSelection(), backwards);
+ await page.keyboard.press("ArrowRight");
+ const caret = await inputSelection();
+ assert.equal(caret[2], caret[3]);
+ await selectMode("canvas");
+ assert.deepEqual(await inputSelection(), caret);
+ // Revealing a collapsed chat via the keyboard keeps navigation in the switch.
+ await separator.press("Home");
+ assert.equal(await assistant.isVisible(), false);
+ // The same toolbar field stays editable in both layouts. Blurring it would save.
+ await page.locator(".cw-project-name").click();
+ const rename = page.locator(".cw-project-name-field input");
+ await rename.fill("Unsaved project name");
+ await rename.evaluate((input) => input.setSelectionRange(2, 8, "backward"));
+ await selectMode("agent");
+ assert.deepEqual(await rename.evaluate((input) => [
+ input === document.activeElement, input.selectionStart, input.selectionEnd, input.selectionDirection,
+ ]), [true, 2, 8, "backward"]);
+ await selectMode("canvas");
+ assert.equal(await rename.inputValue(), "Unsaved project name");
+ await rename.press("Escape");
+ await page.waitForFunction(() => document.activeElement?.matches(".cw-project-name"));
+ await mode("agent").focus();
+ await page.keyboard.press("Enter");
+ await settleLayout();
+ assert.equal(await mode("agent").evaluate((button) => document.activeElement === button), true);
+ await page.keyboard.press("Tab");
+ assert.equal(await mode("canvas").evaluate((button) => document.activeElement === button), true);
+ await page.keyboard.press("Enter");
+ await page.locator(".cw-chat-button").click();
+ await assertLayout("canvas");
+ for (const value of ["agent", "canvas", "agent", "canvas"]) {
+ await selectMode(value);
+ await assertLayout(value);
+ assert.equal(await editor.evaluate((element) => element === window.__workspaceModeEditor), true, "mode and language changes keep the input DOM instance");
+ assert.equal(await editorText(), draftText);
+ const current = await conversation();
+ assert.equal(current.conversationId, savedChat.conversationId);
+ assert.deepEqual(current.assets, savedChat.assets);
+ if (value === "canvas") {
+ assert.deepEqual(await selection(), selected);
+ assert.deepEqual(await viewport(), savedViewport);
+ assert.equal(await page.getByRole("textbox", { name: locale === "zh-CN" ? "生成提示词" : "Prompt", exact: true }).evaluate((element) => element.isContentEditable ? element.textContent.replaceAll("\u200b", "") : element.value), prompt);
+ }
+ }
+ await screenshot(`${locale}-canvas`);
+ await selectMode("agent");
+ await screenshot(`${locale}-agent`);
+ await editor.focus();
+ const beforeFloat = await inputSelection();
+ await page.getByTestId("workspace-float-chat").click();
+ await settleLayout();
+ assert.deepEqual(await inputSelection(), beforeFloat);
+ await page.locator('#canvas-assistant[data-floating="true"]').waitFor();
+ assert.equal(await workspace.getAttribute("data-workspace-mode"), "canvas");
+ assert.equal(await editor.evaluate((element) => element === window.__workspaceModeEditor), true);
+ assert.equal(await editorText(), draftText);
+ await placement.click();
+ await selectMode("agent");
+ await page.getByTestId("workspace-float-chat").press("Enter");
+ await settleLayout();
+ assert.equal(await moveChat.evaluate((handle) => document.activeElement === handle), true);
+ await placement.click();
+ await selectMode("agent");
+ // Hidden canvas handlers must not act on its retained selection.
+ await mode("agent").focus();
+ await page.keyboard.press("Delete");
+ await assistant.hover();
+ await page.keyboard.down("Control");
+ try { await page.mouse.wheel(0, -120); } finally { await page.keyboard.up("Control"); }
+ assert.deepEqual(await viewport(), savedViewport, "wheel over agent chat must not zoom the hidden canvas");
+ await page.keyboard.press("Shift");
+ await page.keyboard.press("Shift");
+ await until(() => editor.evaluate((element) => element === document.activeElement || element.contains(document.activeElement)), Boolean, "double Shift focuses the agent composer");
+ assert.equal(await assistant.isVisible(), true);
+ await selectMode("canvas");
+ assert.deepEqual(await selection(), selected, "Delete in agent mode leaves canvas selection intact");
+ }
+ assert.deepEqual(await state(), snapshotBeforeSwitch, "layout changes preserve project objects, versions and history cursor");
+ assert.equal(commands.length, commandCount, "mode changes do not submit project commands");
+
+ // The language control remains usable in agent mode through Settings.
+ await selectMode("agent");
+ await setLocale("zh-CN");
+ assert.equal(await page.locator(".cw-language-toggle").isVisible(), false);
+ assert.equal(await page.evaluate(() => localStorage.getItem("opendirector.workspaceMode.v1")), "agent");
+ const historyButton = assistant.getByRole("button", { name: "历史会话", exact: true });
+ await historyButton.click();
+ const history = assistant.getByRole("dialog", { name: "历史会话" });
+ const search = history.getByRole("textbox", { name: "搜索会话" });
+ await search.fill("missing-conversation-title");
+ await history.getByText("没有找到匹配的会话", { exact: true }).waitFor();
+ await search.fill("");
+ await search.press("Escape");
+ assert.equal(await historyButton.getAttribute("aria-expanded"), "false");
+ await assistant.getByRole("button", { name: "新建会话", exact: true }).click();
+ const nextChat = await until(conversation, (value) => value.conversationId !== savedChat.conversationId, "chat header opens a new conversation");
+ assert.deepEqual(nextChat.assets, []);
+ await until(editorText, (value) => value === "", "new conversation has a fresh editor");
+ await historyButton.click();
+ await history.getByRole("button", { name: /有草稿/ }).click();
+ const restored = await until(conversation, (value) => value.conversationId === savedChat.conversationId, "chat history restores the original conversation");
+ assert.deepEqual(restored.assets, savedChat.assets);
+ await until(editorText, (value) => value === draftText, "chat history restores the original draft");
+ await page.reload();
+ await page.locator('.cw-workspace[aria-busy="false"]').waitFor();
+ await editor.waitFor();
+ assert.equal(await workspace.getAttribute("data-workspace-mode"), "agent");
+ assert.equal((await conversation()).conversationId, savedChat.conversationId);
+ await until(editorText, (value) => value === draftText, "reload restores the same draft");
+ assert.deepEqual((await conversation()).assets, savedChat.assets);
+ await selectMode("canvas");
+
+ // Narrow layouts still expose both mode controls and the same input instance.
+ await placement.click();
+ await moveChat.focus();
+ await page.keyboard.press("ArrowRight");
+ await page.keyboard.press("ArrowDown");
+ await settleLayout();
+ const savedFloat = await assistant.boundingBox();
+ await page.reload();
+ await page.locator('.cw-workspace[aria-busy="false"]').waitFor();
+ await page.locator('#canvas-assistant[data-floating="true"]').waitFor();
+ await until(() => assistant.boundingBox(), (box) => Math.abs(box.x - savedFloat.x) <= 2 && Math.abs(box.y - savedFloat.y) <= 2, "reload restores the floating position");
+ await until(editorText, (value) => value === draftText, "reload preserves the floating chat draft");
+ await editor.evaluate((element) => { window.__workspaceModeEditor = element; });
+ for (const width of [600, 390]) {
+ await page.setViewportSize({ width, height: 900 });
+ await selectMode("agent");
+ for (const locale of ["zh-CN", "en-US"]) {
+ await setLocale(locale);
+ for (const value of ["agent", "canvas"]) {
+ await mode(value).click({ trial: true });
+ const button = await mode(value).boundingBox();
+ assert.ok(button.x >= 0 && button.x + button.width <= width, "mode buttons stay inside the narrow window");
+ }
+ assert.equal(await editor.evaluate((element) => element === window.__workspaceModeEditor && element.isContentEditable), true);
+ assert.equal(await assistant.getByRole("navigation").count(), 0);
+ assert.equal(await page.getByTestId("workspace-float-chat").isVisible(), false);
+ assert.ok(await assistant.locator(".cw-assistant-header").isVisible());
+ const historyName = locale === "zh-CN" ? "历史会话" : "Conversation history";
+ const history = assistant.getByRole("button", { name: historyName, exact: true });
+ await history.click();
+ await assistant.getByRole("dialog", { name: historyName }).getByRole("textbox").waitFor();
+ await page.keyboard.press("Escape");
+ assert.equal(await history.getAttribute("aria-expanded"), "false");
+ await editor.click({ trial: true });
+ assert.equal(await editorText(), draftText);
+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "narrow page must not overflow horizontally");
+ await screenshot(`${locale}-${width}-agent`);
+ await selectMode("canvas");
+ assert.notEqual(await assistant.getAttribute("data-floating"), "true");
+ assert.equal(await placement.isVisible(), false);
+ await page.locator(".cw-narrow-region-toggle").click();
+ assert.equal(await canvas.isVisible(), true);
+ assert.equal(await assistant.isVisible(), false);
+ assert.equal(await page.locator(".cw-narrow-region-toggle").isVisible(), false, "narrow canvas has only the existing chat toggle");
+ await page.locator(".cw-chat-button").click();
+ assert.equal(await assistant.isVisible(), true);
+ assert.equal(await editorText(), draftText);
+ await selectMode("agent");
+ }
+ }
+ await page.setViewportSize({ width: 1720, height: 1120 });
+ await setLocale("zh-CN");
+ await selectMode("canvas");
+ await page.locator('#canvas-assistant[data-floating="true"]').waitFor();
+ const restoredFloat = await assistant.boundingBox();
+ assert.ok(Math.abs(restoredFloat.x - savedFloat.x) <= 2 && Math.abs(restoredFloat.y - savedFloat.y) <= 2, "returning to a wide window restores the floating position");
+ await placement.click();
+
+ // The earlier narrow-window checks deliberately preserve the zoom/pan.
+ // Start this separate execution scenario by explicitly fitting the canvas.
+ await workspace.focus();
+ await page.keyboard.press("Shift+1");
+ const node = page.locator(`.react-flow__node[data-id="${selected[0]}"]`);
+ const nodeSurface = node.locator(".cw-placeholder-symbol");
+ await nodeSurface.click();
+ await page.getByRole("button", { name: "提交生成", exact: true }).waitFor();
+ const beforeDrag = (await state()).canvasItems.find((item) => item.id === selected[0]).position;
+ const dragZoom = (await viewport())[0];
+ const handle = await nodeSurface.boundingBox();
+ const origin = { x: handle.x + handle.width / 2, y: handle.y + handle.height / 2 };
+ await page.mouse.move(origin.x, origin.y);
+ await page.mouse.down();
+ await page.mouse.move(origin.x + 80, origin.y + 40, { steps: 12 });
+ await page.mouse.up();
+ const moved = await until(state, (value) => {
+ const position = value.canvasItems.find((item) => item.id === selected[0]).position;
+ return position.x !== beforeDrag.x || position.y !== beforeDrag.y;
+ }, "drag in the right canvas must persist its new position");
+ const afterDrag = moved.canvasItems.find((item) => item.id === selected[0]).position;
+ assert.ok(Math.abs((afterDrag.x - beforeDrag.x) * dragZoom - 80) < 16);
+ assert.ok(Math.abs((afterDrag.y - beforeDrag.y) * dragZoom - 40) < 16);
+
+ // Context menus use screen coordinates even inside the offset canvas region.
+ const surface = await nodeSurface.boundingBox();
+ const point = { x: surface.x + surface.width / 2, y: surface.y + surface.height / 2 };
+ await page.mouse.click(point.x, point.y, { button: "right" });
+ const menu = page.locator(".cw-context-menu").first();
+ await menu.waitFor();
+ const menuBox = await menu.boundingBox();
+ assert.ok(Math.abs(menuBox.x - Math.max(8, Math.min(point.x, 1720 - menuBox.width - 8))) < 3, "node context menu uses the click's screen x");
+ assert.ok(menuBox.x >= 0 && menuBox.x + menuBox.width <= 1720);
+ await page.keyboard.press("Escape");
+ await menu.waitFor({ state: "detached" });
+ const area = await canvas.boundingBox();
+ const blank = { x: area.x + area.width * 0.6, y: area.y + 170 };
+ await page.mouse.click(blank.x, blank.y, { button: "right" });
+ await menu.waitFor();
+ const blankMenu = await menu.boundingBox();
+ assert.ok(Math.abs(blankMenu.x - blank.x) < 20 && Math.abs(blankMenu.y - blank.y) < 20, "blank canvas menu opens beside the actual pointer");
+ assert.ok(blankMenu.x + blankMenu.width <= 1720 && blankMenu.y + blankMenu.height <= 1120);
+ await page.keyboard.press("Escape");
+ await menu.waitFor({ state: "detached" });
+
+ // Hold an actual stored Job and Agent turn while changing modes.
+ await api("/creation-test-gate", { open: false });
+ await api("/creation-test-assistant-gate", { open: false });
+ const callsBefore = await api("/creation-test-health");
+ await nodeSurface.click();
+ await page.getByRole("button", { name: "提交生成", exact: true }).click();
+ const running = await until(state, (value) => value.jobs.some((job) => job.status === "running" && job.inputSnapshot.spec.id === specId), "image job must be running");
+ const jobId = running.jobs.find((job) => job.inputSnapshot.spec.id === specId).id;
+ // Send the same persisted draft and reference that crossed both layouts during upload.
+ await assistant.getByRole("button", { name: "发送消息", exact: true }).click();
+ const turn = await until(conversation, (value) => !!value.activeTurnId && value.messages.at(-1)?.status === "streaming", "assistant turn must be running");
+ const sent = turn.messages.at(-2);
+ assert.equal(sent.role, "user");
+ assert.ok(sent.text.includes(draft));
+ assert.deepEqual(sent.assets.map((asset) => [asset.id, asset.fingerprint]), [[attachment.id, fingerprint]]);
+ await editor.fill(draft);
+ const runningCommandCount = commands.length;
+ await placement.click();
+ await dragChat(({ x, y }) => ({ x: x + 80, y: y + 30 }));
+ await placement.click();
+ for (const value of ["agent", "canvas", "agent", "canvas"]) {
+ await selectMode(value);
+ assert.equal(await editor.evaluate((element) => element === window.__workspaceModeEditor), true);
+ assert.equal((await conversation()).activeTurnId, turn.activeTurnId);
+ assert.equal((await state()).jobs.find((job) => job.id === jobId).status, "running");
+ }
+ assert.equal(commands.length, runningCommandCount);
+ assert.deepEqual(stops, []);
+ assert.equal(commands.filter((command) => command.type === "job.cancel").length, 0);
+ await api("/creation-test-assistant-gate", { open: true });
+ await api("/creation-test-gate", { open: true });
+ const complete = await until(conversation, (value) => value.messages.at(-1)?.status === "complete", "original assistant turn must complete");
+ assert.equal(complete.messages.length, turn.messages.length);
+ const finished = await until(state, (value) => value.jobs.find((job) => job.id === jobId)?.status === "succeeded", "original image job must complete");
+ assert.equal(finished.jobs.length, running.jobs.length);
+ const callsAfter = await api("/creation-test-health");
+ assert.equal(callsAfter.calls.length, callsBefore.calls.length + 1);
+ assert.equal(callsAfter.assistantContexts.length, callsBefore.assistantContexts.length + 1);
+ assert.ok((await editorText()).includes(draft));
+ if (process.env.CREATION_SCREENSHOTS) {
+ for (const locale of ["zh-CN", "en-US"]) {
+ await setLocale(locale);
+ await selectMode("canvas");
+ await workspace.focus();
+ await page.keyboard.press("Shift+1");
+ let previous, stable = 0;
+ await until(viewport, (value) => {
+ stable = JSON.stringify(value) === JSON.stringify(previous) ? stable + 1 : 0;
+ previous = value;
+ return stable >= 3;
+ }, "fit viewport must settle before the review screenshot");
+ const dismissNotification = page.locator(".cw-toast:not(.cw-toast-exiting) .cw-toast-close");
+ while (await dismissNotification.count()) {
+ await dismissNotification.first().click();
+ }
+ await page.waitForFunction(() => !document.querySelector(".cw-toast"));
+ await screenshot(`${locale}-canvas-final`);
+ await placement.click();
+ await dragChat(() => ({ x: 1370, y: 200 }));
+ await screenshot(`${locale}-floating-chat`);
+ await placement.click();
+ await selectMode("agent");
+ await screenshot(`${locale}-agent-final`);
+ }
+ }
+ // A node created while chat covers the center must still have a reachable surface.
+ await selectMode("canvas");
+ await placement.click();
+ const screen = page.viewportSize();
+ await dragChat(() => ({ x: screen.width * 0.5, y: screen.height * 0.25 }));
+ const oldIds = new Set((await state()).canvasItems.map((item) => item.id));
+ const textKind = await page.locator("html").getAttribute("lang") === "zh-CN" ? "文本" : "Text";
+ await addCanvasNode(page, textKind);
+ const withText = await until(state, (value) => value.canvasItems.some((item) => !oldIds.has(item.id)), "text node created beside floating chat");
+ const created = withText.canvasItems.find((item) => !oldIds.has(item.id));
+ await page.waitForFunction((nodeId) => {
+ const node = document.querySelector(`.react-flow__node[data-id="${nodeId}"]`);
+ if (!node) return false;
+ const box = node.getBoundingClientRect();
+ return node.contains(document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2));
+ }, created.id);
+ await placement.click();
+ await setLocale("en-US");
+ await addCanvasNode(page, "Timeline");
+ await until(state, (value) => value.canvasItems.some((item) => item.kind === "timeline"), "timeline created");
+ const pending = assistant.locator("[data-pending-references]");
+ await pending.waitFor();
+ const pendingText = await pending.innerText();
+ const editTimeline = page.getByRole("button", { name: "Edit timeline", exact: true });
+ await editTimeline.press("Enter");
+ const dialog = page.locator(".cw-timeline-dialog");
+ await dialog.waitFor();
+ await page.keyboard.press("Escape");
+ await dialog.waitFor({ state: "detached" });
+ assert.equal(await pending.innerText(), pendingText, "the modal owns Escape while a canvas reference is pending");
+ await editTimeline.press("Enter");
+ await dialog.waitFor();
+ await dialog.evaluate((el) => { window.__workspaceTimeline = el; });
+ const beforeDialogSwitch = commands.length;
+ for (const width of [1720, 390]) {
+ await page.setViewportSize({ width, height: 900 });
+ await dialog.focus();
+ await page.keyboard.press("Tab");
+ const chatMode = dialog.getByRole("button", { name: "Chat", exact: true });
+ assert.equal(await chatMode.evaluate((el) => document.activeElement === el), true);
+ await page.keyboard.press("Enter");
+ await settleLayout();
+ assert.equal(await workspace.getAttribute("data-workspace-mode"), "agent");
+ await page.keyboard.press("Shift");
+ await page.keyboard.press("Shift");
+ assert.equal(await chatMode.evaluate((el) => document.activeElement === el), true);
+ await dialog.getByRole("button", { name: "Canvas", exact: true }).click();
+ assert.equal(await workspace.getAttribute("data-workspace-mode"), "canvas");
+ assert.equal(await dialog.evaluate((el) => el === window.__workspaceTimeline && el.contains(document.activeElement)), true);
+ }
+ assert.equal(commands.length, beforeDialogSwitch);
+ await page.keyboard.press("Escape");
+ await dialog.waitFor({ state: "detached" });
+ assert.equal(await pending.innerText(), pendingText, "pointer interactions in the modal preserve the pending reference");
+ // Exercise the desktop project's sidebar alongside the same chat components.
+ await page.setViewportSize({ width: 1720, height: 900 });
+ await page.addInitScript(() => {
+ window.opendirectorDesktop = { registerSession() {}, setLocale() {}, setExporting() {} };
+ localStorage.setItem("opendirector.desktop.sidebar.v1", "open");
+ const markDesktop = () => { document.documentElement.dataset.desktopChrome = ""; };
+ if (document.documentElement) markDesktop();
+ else window.addEventListener("DOMContentLoaded", markDesktop, { once: true });
+ });
+ await page.reload();
+ await page.locator('.cw-workspace[data-desktop-sidebar="open"][aria-busy="false"]').waitFor();
+ await selectMode("agent");
+ assert.equal(await page.locator(".od-desktop-navigation").count(), 0);
+ const fullChat = await assistant.boundingBox();
+ assert.ok(Math.abs(fullChat.x) <= 1 && Math.abs(fullChat.width - page.viewportSize().width) <= 1);
+ await assertLayout("agent");
+ await page.reload();
+ await page.locator('.cw-workspace[data-workspace-mode="agent"][aria-busy="false"]').waitFor();
+ assert.equal(await page.locator(".od-project-sidebar").count(), 0);
+ await selectMode("canvas");
+ await page.locator('.cw-workspace[data-desktop-sidebar="open"]').waitFor();
+ const sidebar = await page.locator(".od-project-sidebar").boundingBox();
+ const dockRightButton = assistant.getByRole("button", { name: "Dock chat to the right", exact: true });
+ assert.equal(await dockRightButton.innerText(), "");
+ await dockRightButton.hover();
+ await page.getByRole("tooltip", { name: "Dock chat to the right", exact: true }).waitFor();
+ await dockRightButton.click();
+ await settleLayout();
+ const desktopCanvas = await canvas.boundingBox();
+ const desktopChat = await assistant.boundingBox();
+ assert.ok(Math.abs(desktopCanvas.x - (sidebar.x + sidebar.width)) <= 1);
+ assert.ok(desktopCanvas.x + desktopCanvas.width <= desktopChat.x + 1);
+ assert.deepEqual(errors, []);
+ console.log("PASS workspace modes: bilingual chat docking, dragging, keyboard movement, bounds, persistence, shared draft, uninterrupted reference upload and running tasks");
+} catch (error) {
+ console.error(error);
+ if (page) console.error({ errors, page: (await page.locator("body").innerText()).slice(-6000) });
+ throw error;
+} finally {
+ try {
+ await api("/creation-test-assistant-gate", { open: true });
+ await api("/creation-test-gate", { open: true });
+ } finally {
+ await browser.close();
+ }
+}
diff --git a/tests/browser/zhipu_real.mjs b/tests/browser/zhipu_real.mjs
index 086798f4f..44ae629de 100644
--- a/tests/browser/zhipu_real.mjs
+++ b/tests/browser/zhipu_real.mjs
@@ -3,6 +3,7 @@
* ZHIPU_API_KEY for a funded BigModel account, and ZHIPU_SAMPLE pointing to a 3–30 s WAV.
* Contacts the real service and incurs charges; it deletes the voice it creates.
*/
+import { addCanvasNode } from "./canvas_creation.mjs";
import assert from "node:assert/strict";
import { mkdir, readFile } from "node:fs/promises";
import { launchBrowser } from "./engine.mjs";
@@ -27,11 +28,11 @@ async function until(check, attempts = 900) {
throw Error("Expected state was not observed");
}
const copy = {
- "zh-CN": { tools: "画布创作工具", add: "添加音频", model: "生成模型", prompt: "朗读文本", library: "音色库",
+ "zh-CN": { nodeType: "音频", model: "生成模型", prompt: "朗读文本", library: "音色库",
mine: "我的音色", create: "创建音色", name: "音色名称", recording: "参考录音", transcript: "录音逐字稿(选填)",
generate: "提交生成", saved: "已保存到本机", delete: "删除音色",
presetText: "这是 OpenDirector 使用智谱预置音色彤彤生成的旁白。", cloneText: "这是使用刚刚复刻的音色生成的旁白。" },
- "en-US": { tools: "Canvas creation tools", add: "Add Audio", model: "Generation model", prompt: "Text to read",
+ "en-US": { nodeType: "Audio", model: "Generation model", prompt: "Text to read",
library: "Voice library", mine: "My voices", create: "Create voice", name: "Voice name", recording: "Reference recording",
transcript: "Recording transcript (optional)", generate: "Generate", saved: "Saved on this device", delete: "Delete voice",
presetText: "OpenDirector narration with the Zhipu preset voice Tongtong.", cloneText: "Narration with the voice that was just cloned." },
@@ -75,7 +76,7 @@ try {
};
await page.goto(`${base}/ai-tool/ai-canvas/${id}?creation=unified`);
await page.getByText(L.saved, { exact: true }).waitFor();
- await page.getByRole("toolbar", { name: L.tools }).getByRole("button", { name: L.add, exact: true }).click();
+ await addCanvasNode(page, L.nodeType);
await page.getByRole("combobox", { name: L.model, exact: true }).click();
await page.getByRole("listbox", { name: L.model, exact: true }).locator(`[data-option-id="config:${config.id}"]`).click();
await until(async () => (await state()).generationSpecs[0]?.modelConfigId === config.id);
diff --git a/tests/canvasSelectionPresentation.test.ts b/tests/canvasSelectionPresentation.test.ts
index 3b305ecab..6c8f54267 100644
--- a/tests/canvasSelectionPresentation.test.ts
+++ b/tests/canvasSelectionPresentation.test.ts
@@ -5,9 +5,33 @@ import {
projectSelectionRect,
selectionPlacement,
selectionViewport,
+ visibleSelectionArea,
type SelectionChrome,
} from "../src/canvas/selectionPresentation.ts";
+test("a floating chat only changes the usable area when it covers the selection or its controls", () => {
+ const chrome = {
+ safe: { x: 80, y: 72, width: 1200, height: 700 },
+ toolbar: { width: 160, height: 32 },
+ composer: { width: 300, height: 100 },
+ };
+ const node = { x: 370, y: 200, width: 160, height: 130 };
+ const view = { x: 0, y: 0, zoom: 1 };
+ const away = { x: 850, y: 100, width: 410, height: 480 };
+ assert.equal(visibleSelectionArea(node, view, chrome, null), chrome.safe);
+ assert.equal(visibleSelectionArea(node, view, chrome, away), chrome.safe);
+ const overlap = { x: 440, y: 355, width: 480, height: 360 };
+ const safe = visibleSelectionArea(node, view, chrome, overlap);
+ assert.notEqual(safe, chrome.safe, "the composer alone intersects chat");
+ const target = selectionViewport(node, view, { ...chrome, safe });
+ const placed = selectionPlacement(node, target, { ...chrome, safe });
+ assert.equal(target.zoom, view.zoom);
+ assert.ok(placed.composer.left + chrome.composer.width <= overlap.x);
+ const wideOverlay = { x: 80, y: 250, width: 1200, height: 165 };
+ const below = visibleSelectionArea(node, view, chrome, wideOverlay);
+ assert.equal(below.y, wideOverlay.y + wideOverlay.height, "can use space below a wide panel");
+});
+
test("selection fits node and both fixed-size controls without changing authored geometry", () => {
const node = { x: 840, y: 620, width: 720, height: 480 };
const before = { ...node };
@@ -183,3 +207,32 @@ test("desktop origin offsets selection controls and fitting in both axes", () =>
assert.ok(Math.abs(fittedNode.x + fittedNode.width / 2 - (chrome.safe.x + chrome.safe.width / 2)) < 1e-6);
assert.deepEqual(selectionViewport(node, fitted, chrome), fitted);
});
+
+test("floating chat and selected content use the same desktop coordinates when fitting", () => {
+ const chrome: SelectionChrome = {
+ canvasOrigin: { x: 224, y: 48 },
+ safe: { x: 304, y: 72, width: 1000, height: 700 },
+ toolbar: { width: 160, height: 40 },
+ composer: { width: 240, height: 80 },
+ };
+ const node = Object.freeze({ x: 300, y: 250, width: 200, height: 150 });
+ const view = { x: 0, y: 0, zoom: 1 };
+
+ // This panel covers the canvas-local coordinates but clears the actual node.
+ const away = { x: 360, y: 280, width: 110, height: 90 };
+ assert.equal(visibleSelectionArea(node, view, chrome, away), chrome.safe);
+ assert.deepEqual(selectionViewport(node, view, chrome), view);
+
+ // Only the projected node intersects the panel; both controls are clear.
+ const panel = { x: 600, y: 314, width: 300, height: 100 };
+ const safe = visibleSelectionArea(node, view, chrome, panel);
+ assert.notEqual(safe, chrome.safe);
+ const fitted = selectionViewport(node, view, { ...chrome, safe });
+ const media = projectSelectionRect(node, fitted, chrome.canvasOrigin);
+ const placed = selectionPlacement(node, fitted, { ...chrome, safe });
+ assert.equal(fitted.zoom, view.zoom);
+ assert.ok(media.x + media.width <= panel.x);
+ assert.ok(placed.toolbar.left + chrome.toolbar.width <= panel.x);
+ assert.ok(placed.composer.left + chrome.composer.width <= panel.x);
+ assert.equal(placed.composer.top, media.y + media.height + 16);
+});
diff --git a/tests/canvasTimelineLibrary.test.ts b/tests/canvasTimelineLibrary.test.ts
index de40f9672..b302a13db 100644
--- a/tests/canvasTimelineLibrary.test.ts
+++ b/tests/canvasTimelineLibrary.test.ts
@@ -36,6 +36,15 @@ const picture = {
height: 64,
};
+test("project-only media uses the asset identity before its bytes load", () => {
+ const timeline = createNode("timeline").data.timeline!;
+ const asset = { ...picture, assetId: "a1", src: undefined };
+ const canvas = { ...picture, assetId: "a1", src: "blob:loaded" };
+ assert.deepEqual(timelineLibraryResources(timeline, [], "all", "image", [asset]), [asset]);
+ assert.deepEqual(timelineLibraryResources(timeline, [canvas], "all", "image", [asset]), [canvas]);
+ assert.deepEqual(timelineLibraryResources(timeline, [], "canvas", "image", [asset]), []);
+});
+
test("same bytes on canvas and in imported library remain available after final clip deletion and restore", () => {
const canvasAsset = {
...picture,
diff --git a/tests/creationEditorSession.test.ts b/tests/creationEditorSession.test.ts
index 66275f5e3..c5f805d4b 100644
--- a/tests/creationEditorSession.test.ts
+++ b/tests/creationEditorSession.test.ts
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
-import test from "node:test";
+import test, { type TestContext } from "node:test";
+import { prepareProjectEditorItem } from "../src/canvas/assistantResultEditors.ts";
import {
CreationClient,
CreationCommandError,
@@ -143,7 +144,7 @@ test("unchanged editor inputs still validate their original versions before rend
);
});
-test("a lost delivery survives a new editor session and resolves before a changed draft can be submitted", async (t) => {
+function sessionStore(t: TestContext) {
const original = Object.getOwnPropertyDescriptor(
globalThis,
"sessionStorage",
@@ -161,6 +162,11 @@ test("a lost delivery survives a new editor session and resolves before a change
if (original) Object.defineProperty(globalThis, "sessionStorage", original);
else Reflect.deleteProperty(globalThis, "sessionStorage");
});
+ return saved;
+}
+
+test("a lost delivery survives a new editor session and resolves before a changed draft can be submitted", async (t) => {
+ const saved = sessionStore(t);
const { client, document, item } = await fixture();
const timeline = structuredClone(
document.nodes.find((n) => n.id === item.id)!.data.timeline!,
@@ -363,3 +369,31 @@ test("unavailable text source keeps its immutable identity and fails saving rath
const session = new CreationEditorSession(client, doc, item.id);
await assert.rejects(session.apply({ timeline: view.timeline! }));
});
+
+test("reopening an unplaced image resumes its prepared edit; a later independent edit uses a fresh item", async (t) => {
+ const saved = sessionStore(t);
+ const { client, snapshot } = await fixture();
+ const asset = snapshot.assets.find(candidate => candidate.kind === "image")!;
+ client.install({ ...snapshot, canvasItems: [] });
+ const open = async () => {
+ const target = { kind: "media" as const, asset, itemId: null };
+ const { itemId, unplaced } = await prepareProjectEditorItem(client, target, () => ({ x: 0, y: 0 }));
+ const basis = { ...client.snapshot, canvasItems: [unplaced!] };
+ const document = await new CreationProjection(client).read(basis);
+ return new CreationEditorSession(client, document, itemId, basis, unplaced);
+ };
+ const calls: Parameters[] = [];
+ client.command = async (...args) => {
+ calls.push(structuredClone(args));
+ if (calls.length === 1) throw Error("lost before submit");
+ return { status: "applied" } as CommandReceipt;
+ };
+ const original = await open();
+ await assert.rejects(original.apply({ title: "Edited" }), /lost before submit/);
+ const resumed = await open();
+ assert.equal(resumed.itemId, original.itemId);
+ await resumed.apply({ title: "Edited" });
+ assert.deepEqual(calls[0], calls[1]);
+ assert.equal(saved.size, 0);
+ assert.notEqual((await open()).itemId, original.itemId);
+});
diff --git a/tests/creationJobs.test.ts b/tests/creationJobs.test.ts
index ec8db13af..61e06844d 100644
--- a/tests/creationJobs.test.ts
+++ b/tests/creationJobs.test.ts
@@ -1,5 +1,4 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import test from "node:test";
import {
creationJobs,
@@ -8,14 +7,10 @@ import {
} from "../src/backend/creationJobs.ts";
import { creationClient } from "../src/backend/creationClient.ts";
import type { ProjectSnapshot } from "../src/contracts/generated.ts";
+import projectFixture from "./fixtures/creation-project.json" with { type: "json" };
function fixture() {
- const snapshot = JSON.parse(
- readFileSync(
- new URL("./fixtures/creation-project.json", import.meta.url),
- "utf8",
- ),
- ) as ProjectSnapshot;
+ const snapshot = structuredClone(projectFixture) as ProjectSnapshot;
const active = {
...structuredClone(snapshot.jobs[0]!),
diff --git a/tests/mediaPublication.test.ts b/tests/mediaPublication.test.ts
index 543e437d0..4c76de711 100644
--- a/tests/mediaPublication.test.ts
+++ b/tests/mediaPublication.test.ts
@@ -1,5 +1,4 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import test, { type TestContext } from "node:test";
import {
CreationClient,
@@ -7,11 +6,13 @@ import {
assetReference,
} from "../src/backend/creationClient.ts";
import { CreationProjection } from "../src/backend/creationProjection.ts";
+import { prepareProjectEditorItem } from "../src/canvas/assistantResultEditors.ts";
import { MediaPublication } from "../src/backend/mediaPublication.ts";
import type {
CommandReceipt,
ProjectSnapshot,
} from "../src/contracts/generated.ts";
+import projectFixture from "./fixtures/creation-project.json" with { type: "json" };
const output = [
{
@@ -22,12 +23,7 @@ const output = [
},
];
function setup(t: TestContext) {
- let snapshot = JSON.parse(
- readFileSync(
- new URL("./fixtures/creation-project.json", import.meta.url),
- "utf8",
- ),
- ) as ProjectSnapshot;
+ let snapshot = structuredClone(projectFixture) as ProjectSnapshot;
const source = snapshot.assets.find((a) => a.kind === "image")!;
const item = {
...snapshot.canvasItems.find((i) => i.kind === "image")!,
@@ -46,6 +42,26 @@ function setup(t: TestContext) {
});
return { client, snapshot, item, imports: () => imports };
}
+function sessionStore(t: TestContext) {
+ const original = Object.getOwnPropertyDescriptor(
+ globalThis,
+ "sessionStorage",
+ );
+ const saved = new Map();
+ Object.defineProperty(globalThis, "sessionStorage", {
+ configurable: true,
+ value: {
+ getItem: (k: string) => saved.get(k) ?? null,
+ setItem: (k: string, v: string) => saved.set(k, v),
+ removeItem: (k: string) => saved.delete(k),
+ },
+ });
+ t.after(() => {
+ if (original) Object.defineProperty(globalThis, "sessionStorage", original);
+ else Reflect.deleteProperty(globalThis, "sessionStorage");
+ });
+ return saved;
+}
test("unknown publication repeats exact fixed input and identities, acknowledged output does not submit twice", async (t) => {
const { client, snapshot, item, imports } = setup(t);
const calls: unknown[] = [];
@@ -81,23 +97,7 @@ test("confirmed rejection retries the same imported outputs, keeps the original
assert.notEqual(calls[0][4], calls[1][4]);
});
test("a new editor session resolves a lost publication before sending changed output", async (t) => {
- const original = Object.getOwnPropertyDescriptor(
- globalThis,
- "sessionStorage",
- );
- const saved = new Map();
- Object.defineProperty(globalThis, "sessionStorage", {
- configurable: true,
- value: {
- getItem: (k: string) => saved.get(k) ?? null,
- setItem: (k: string, v: string) => saved.set(k, v),
- removeItem: (k: string) => saved.delete(k),
- },
- });
- t.after(() => {
- if (original) Object.defineProperty(globalThis, "sessionStorage", original);
- else Reflect.deleteProperty(globalThis, "sessionStorage");
- });
+ const saved = sessionStore(t);
const { client, snapshot, item, imports } = setup(t);
const calls: unknown[] = [];
client.command = async (...args) => {
@@ -169,23 +169,7 @@ test("new local results retain normal node dimensions and avoid earlier publishe
});
test("reopening a refused publication reuses prepared assets instead of importing duplicate files", async (t) => {
- const original = Object.getOwnPropertyDescriptor(
- globalThis,
- "sessionStorage",
- );
- const saved = new Map();
- Object.defineProperty(globalThis, "sessionStorage", {
- configurable: true,
- value: {
- getItem: (k: string) => saved.get(k) ?? null,
- setItem: (k: string, v: string) => saved.set(k, v),
- removeItem: (k: string) => saved.delete(k),
- },
- });
- t.after(() => {
- if (original) Object.defineProperty(globalThis, "sessionStorage", original);
- else Reflect.deleteProperty(globalThis, "sessionStorage");
- });
+ const saved = sessionStore(t);
const { client, snapshot, item, imports } = setup(t);
const calls: unknown[][] = [];
client.command = async (...args) => {
@@ -206,3 +190,44 @@ test("reopening a refused publication reuses prepared assets instead of importin
assert.notEqual(calls[0]![4], calls[1]![4]);
assert.equal(saved.size, 0);
});
+
+test("unplaced media keeps one hidden source across lost placement and publication replies", async (t) => {
+ const saved = sessionStore(t);
+ const { client, snapshot, imports } = setup(t);
+ const audio = snapshot.assets.find(asset => asset.kind === "audio")!;
+ const target = { kind: "media" as const, asset: audio, itemId: null };
+ client.install({ ...snapshot, canvasItems: [] });
+ const open = async () => {
+ const targetItem = await prepareProjectEditorItem(client, target, () => ({ x: 200, y: 200 }));
+ const item = targetItem.unplaced!;
+ const basis = { ...client.snapshot, canvasItems: [item] };
+ return { item, publication: new MediaPublication(client, basis, item.id, item) };
+ };
+ const { item, publication } = await open();
+ const trimmed = [{ ...output[0], kind: "audio" as const, mimeType: "audio/wav", title: "Trim" }];
+ const calls: Parameters[] = [];
+ client.command = async (...args) => {
+ calls.push(structuredClone(args));
+ if (calls.length === 1 || calls.length === 3) throw Error("lost reply");
+ return { status: "applied" } as CommandReceipt;
+ };
+ assert.equal(calls.length, 0);
+ await assert.rejects(publication.publish(trimmed), /lost reply/);
+ const reopened = await open();
+ assert.deepEqual(reopened.item, item);
+ await assert.rejects(reopened.publication.publish(trimmed), /lost reply/);
+ const ids = await reopened.publication.publish(trimmed);
+ assert.deepEqual(calls[0], calls[1], "retry the same atomic show/hide command");
+ assert.equal(calls[0][0], "creation.batch");
+ assert.deepEqual(calls[0][1], { operations: [
+ { type: "canvas.show", payload: { item } },
+ { type: "canvas.hide", payload: { itemId: item.id } },
+ ] });
+ assert.deepEqual(calls[2], calls[3], "retry publication without creating the source again");
+ assert.equal(calls[2][0], "canvas.publishMedia");
+ assert.equal(calls[2][2]?.find(version => version.objectType === "canvas_item")?.id, item.id);
+ assert.deepEqual(await reopened.publication.publish(trimmed), ids);
+ assert.equal(saved.size, 0);
+ assert.equal(imports(), 1);
+ assert.equal(calls.length, 4);
+});
diff --git a/tests/modelResolution.test.ts b/tests/modelResolution.test.ts
index 1704d2d13..1b031a706 100644
--- a/tests/modelResolution.test.ts
+++ b/tests/modelResolution.test.ts
@@ -11,6 +11,7 @@ import {
resolveGenerationModel,
} from "../src/canvas/modelResolution.ts";
import { backendAspectRatios } from "../src/backend/rules.ts";
+import { hasFirstCanvasModel } from "../src/canvas/firstRunModels.ts";
const config = (
kind: ModelConfig["kind"],
@@ -40,6 +41,12 @@ const alpha = config("video", "alpha-video");
const image = config("image", "alpha-image");
const vision: ModelConfig = config("vision", "sam", { protocol: "openai" });
+test("first canvas entry requires an image or supported video generator", () => {
+ assert.equal(hasFirstCanvasModel([config("agent", "chat"), config("audio", "speech"), vision]), false);
+ assert.equal(hasFirstCanvasModel([image]), true);
+ assert.equal(hasFirstCanvasModel([alpha]), true);
+});
+
test("a configured model that still exists is kept", () => {
const resolution = resolveGenerationModel(
{ modelConfigId: zeta.id },
diff --git a/tests/test_assistant_conversations.py b/tests/test_assistant_conversations.py
index 288c5c8ac..a8b66d248 100644
--- a/tests/test_assistant_conversations.py
+++ b/tests/test_assistant_conversations.py
@@ -3,12 +3,13 @@
import json
import threading
import time
-from uuid import uuid4
+from uuid import UUID, uuid4, uuid5
from fastapi.testclient import TestClient
import pytest
from opendirector.agent.native import NativeRuntime
+from opendirector.infrastructure.creation_projects import CreationProjects
from opendirector.infrastructure.local_projects import LocalProjects
from opendirector_api.main import create_app
from opendirector_api import agent
@@ -61,6 +62,241 @@ def send(client, path, conversation_id, text):
return response
+def test_conversation_reads_remain_available_during_canvas_publication(assistant, monkeypatch):
+ client, path, _ = assistant
+ project = path.removesuffix('/assistant')
+ pid = project.rsplit('/', 1)[1]
+ saved = client.put(path + '/draft', json={'draft': 'Keep this draft'}).json()
+ journaled, resume = threading.Event(), threading.Event()
+
+ def pause(self, stage):
+ if stage == 'bundle_written':
+ journaled.set()
+ assert resume.wait(10)
+
+ monkeypatch.setattr(CreationProjects, '_checkpoint', pause)
+ command = {'type': 'canvas.show', 'commandId': str(uuid4()), 'projectId': pid, 'payload': {'item': {
+ 'id': str(uuid4()), 'projectId': pid, 'kind': 'text', 'title': 'Writing', 'binding': {'role': 'empty'}}}}
+ with ThreadPoolExecutor() as pool:
+ publication = pool.submit(client.post, project + '/commands', json=command)
+ try:
+ assert journaled.wait(5)
+ response = client.get(path)
+ assert response.status_code == 200, response.text
+ assert response.json() == saved
+ assert client.get(path + '/conversations').json()['activeId'] == saved['conversationId']
+ refused = client.put(path + '/draft', json={'draft': 'Concurrent edit'})
+ assert refused.status_code == 409 and refused.json()['code'] == 'storage_busy'
+ finally:
+ resume.set()
+ assert publication.result(timeout=5).json()['status'] == 'applied'
+ assert client.get(path).json() == saved
+
+
+
+def test_timeline_edit_finishes_in_its_original_conversation_after_switching_projects(assistant, monkeypatch, tmp_path):
+ client, path, _ = assistant
+ project = path.removesuffix('/assistant')
+ pid = project.rsplit('/', 1)[1]
+ origin = client.get(path).json()['conversationId']
+ other_id, editor_id, turn, follow_up = (str(uuid4()) for _ in range(4))
+ other = f'/api/creation/projects/{other_id}'
+ created = client.post(other + '/commands', json={'type': 'project.create', 'projectId': other_id,
+ 'commandId': str(uuid4()), 'payload': {'name': 'Other project'}}).json()
+ assert created['status'] == 'applied', created
+ assert client.post(project + '/open').status_code == 200
+ document = {'id': editor_id, 'projectId': pid, 'kind': 'timeline', 'data': {
+ 'fps': 24, 'width': 128, 'height': 96, 'tracks': [{'id': 'v', 'kind': 'visual', 'title': 'Visual'}]}}
+ created = client.post(project + '/commands', json={'type': 'editor.create', 'projectId': pid,
+ 'commandId': str(uuid4()), 'payload': {'document': document}}).json()
+ assert created['status'] == 'applied', created
+
+ resume = threading.Event()
+ sessions = []
+ async def edit(self, run, gateway):
+ sessions.append(run.session)
+ if str(run.turn_id) == follow_up:
+ assert run.messages[-1]['content'] == 'Write the note'
+ yield {'type': 'tool', 'id': 'note', 'name': 'execute_command', 'status': 'running'}
+ result = await gateway.call('note', 'execute_command', {'type': 'asset.writeText',
+ 'payload': {'name': 'note.md', 'text': 'Follow-up'}})
+ assert result.value.get('status') == 'applied', result
+ yield {'type': 'tool', 'id': 'note', 'name': 'execute_command', 'status': 'complete'}
+ yield {'type': 'delta', 'text': 'Note ready'}
+ return
+ assert str(run.turn_id) == turn
+ yield {'type': 'delta', 'text': 'Editing'}
+ assert await asyncio.to_thread(resume.wait, 10)
+ yield {'type': 'tool', 'id': 'cut', 'name': 'execute_command', 'status': 'running'}
+ result = await gateway.call('cut', 'execute_command', {'type': 'editor.save',
+ 'expectedVersions': [{'objectType': 'editor_document', 'id': editor_id, 'revision': 1}],
+ 'payload': {'document': {**document, 'revision': 1, 'data': {**document['data'], 'fps': 30}}}})
+ assert result.value.get('status') == 'applied', result
+ yield {'type': 'tool', 'id': 'cut', 'name': 'execute_command', 'status': 'complete'}
+ yield {'type': 'delta', 'text': ' complete'}
+
+ monkeypatch.setattr(agent.AgentRuntimes, 'stream', runtime_stream)
+ monkeypatch.setattr(NativeRuntime, 'stream', edit)
+ monkeypatch.setattr(LocalProjects, 'LEASE_SECONDS', 1.5)
+ store = LocalProjects(tmp_path)
+ def agent_lease():
+ with store.transaction() as db:
+ return db.execute('SELECT project_id, expires FROM sessions WHERE id=?',
+ (store.agent_session_key(sessions[0]),)).fetchone()
+
+ disconnect_turn(client, path, turn, conversation_id=origin)
+ try:
+ queued = client.post(path + '/messages', json={'id': follow_up, 'runtime': 'default',
+ 'conversationId': origin, 'text': 'Write the note', 'modelId': str(uuid4())})
+ assert queued.status_code == 202 and queued.json()['turnId'] == turn, queued.text
+ initial = agent_lease()
+ assert initial[0] == pid
+ assert client.post(other + '/open').status_code == 200
+ other_chat = client.get(other + '/assistant').json()
+ assert other_chat['conversationId'] != origin
+ assert not other_chat['messages']
+ late = client.post(path + '/messages', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': origin, 'text': 'No longer editing this project'})
+ assert late.status_code == 409 and late.json()['code'] == 'session_expired'
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline and agent_lease()[1] == initial[1]:
+ time.sleep(0.02)
+ assert agent_lease()[1] > initial[1], 'the source project lease must renew while the browser is away'
+ finally:
+ resume.set()
+ settled = client.get(path + f'/turns/{turn}/events')
+ assert settled.status_code in (200, 404), settled.text
+ if settled.status_code == 200:
+ assert frames(settled)[-1]['error'] is None
+ assert agent_lease() is None
+ assert client.get(other + '/assistant').json() == other_chat
+ snapshot = client.get(project).json()
+ edited, = snapshot['editorDocuments']
+ assert (edited['id'], edited['revision'], edited['data']['fps']) == (editor_id, 2, 30)
+ user, reply, queued, note = client.get(path).json()['messages']
+ assert [user['id'], queued['id']] == [turn, follow_up]
+ assert [reply['id'], note['id']] == [str(uuid5(UUID(key), 'assistant')) for key in (turn, follow_up)]
+ assert reply['status'] == 'complete' and reply['text'] == 'Editing complete'
+ assert note['status'] == 'complete' and note['text'] == 'Note ready'
+ assert 'publishedAssets' not in reply and 'publishedTimelines' not in note
+ timeline = reply['publishedTimelines']
+ assert timeline['projectId'] == pid and timeline['eventCursor'] < snapshot['eventCursor']
+ assert timeline['timelines'] == [{'editorId': editor_id, 'revision': 2, 'itemId': None, 'title': ''}]
+ asset, = snapshot['assets']
+ assert asset['provenance']['agentRunId'] == follow_up
+ assert note['publishedAssets'] == {'projectId': pid, 'eventCursor': snapshot['eventCursor'],
+ 'assets': [{key: asset[key] for key in ('id', 'name', 'fingerprint')}]}
+ trace = client.get(f'{path}/conversations/{origin}/trace').json()['turns']
+ assert [entry['id'] for entry in trace] == [turn, follow_up]
+ for entry, message in zip(trace, [reply, note], strict=True):
+ assert message['startedAt'] and message['finishedAt'] and message['durationMs'] >= 0
+ assert all(entry[key] == message[key] for key in ('startedAt', 'finishedAt', 'durationMs'))
+ assert len(set(sessions)) == 2
+ with store.transaction() as db:
+ assert db.execute('SELECT 1 FROM sessions WHERE project_id=?', (pid,)).fetchone() is None
+ for key, call_id in [(turn, 'cut'), (follow_up, 'note')]:
+ ledger = json.loads(next(tmp_path.glob(f'**/agent-runs/timing/{key}.json')).read_text(encoding='utf-8'))
+ assert ledger['summary']['calls'] == ledger['summary']['measured'] == 1
+ assert ledger['calls'][0]['id'] == call_id and ledger['calls'][0]['status'] == 'complete'
+ assert client.post(project + '/open').status_code == 200
+ assert client.post(path + '/conversations', json={'id': str(uuid4())}).json()['messages'] == []
+ for key in (turn, follow_up):
+ assert client.get(path + f'/traces/{key}/conversation').json() == {'conversationId': origin}
+ assert client.post(path + f'/conversations/{origin}/activate').json()['messages'] == [user, reply, queued, note]
+
+
+def test_timeline_reply_uses_committed_tool_versions_and_survives_reopening(assistant, monkeypatch):
+ from opendirector.agent.gateway import ToolGateway
+ client, path, _ = assistant
+ cid = client.get(path).json()['conversationId']
+ editor_id, item_id = str(uuid4()), str(uuid4())
+
+ async def make_timeline(self, run):
+ gateway = ToolGateway(self.business, run)
+ document = {'id': editor_id, 'projectId': str(run.project_id), 'kind': 'timeline',
+ 'data': {'fps': 24, 'width': 128, 'height': 96, 'tracks': [{'id': 'v', 'kind': 'visual', 'title': 'Visual'}]}}
+ command = {'type': 'creation.batch', 'expectedVersions': [], 'payload': {'operations': [
+ {'type': 'editor.create', 'payload': {'document': document}},
+ {'type': 'canvas.show', 'payload': {'item': {'id': item_id, 'projectId': str(run.project_id),
+ 'kind': 'timeline', 'title': 'Cut', 'binding': {'role': 'editor',
+ 'objectRef': {'id': editor_id, 'kind': 'timeline'}}}}},
+ ]}}
+ try:
+ for _ in range(2):
+ outcome = await gateway.call('make-cut', 'execute_command', command)
+ assert outcome.value.get('status') == 'applied', outcome
+ # Another call with stale expectations cannot replace the committed revision.
+ stale = {'type': 'editor.save', 'payload': {'document': {**document, 'revision': 9}},
+ 'expectedVersions': [{'objectType': 'editor_document', 'id': editor_id, 'revision': 9}]}
+ rejected = await gateway.call('stale-cut', 'execute_command', stale)
+ assert rejected.value.get('status') == 'rejected', rejected
+ yield {'type': 'delta', 'text': 'Cut'}
+ raise RuntimeError('interrupted after the commit')
+ finally:
+ await gateway.close()
+
+ monkeypatch.setattr(agent.AgentRuntimes, 'stream', make_timeline)
+ reply = frames(send(client, path, cid, 'Edit'))[-1]['conversation']['messages'][-1]
+ assert reply['text'] == 'Cut'
+ assert reply['status'] == 'interrupted'
+ assert 'publishedAssets' not in reply
+ assert reply['publishedTimelines'] == {
+ 'projectId': path.split('/')[-2],
+ 'eventCursor': client.get(path.removesuffix('/assistant')).json()['eventCursor'],
+ 'timelines': [{'editorId': editor_id, 'itemId': item_id, 'revision': 1, 'title': 'Cut'}],
+ }
+ async def discuss(self, run):
+ yield {'type': 'delta', 'text': editor_id}
+ monkeypatch.setattr(agent.AgentRuntimes, 'stream', discuss)
+ later = frames(send(client, path, cid, 'Discuss'))[-1]['conversation']['messages']
+ assert 'publishedTimelines' not in later[-1]
+ assert client.post(path + '/conversations', json={'id': str(uuid4())}).status_code == 200
+ reopened = client.post(path + f'/conversations/{cid}/activate').json()
+ assert reopened['messages'][1]['publishedTimelines'] == reply['publishedTimelines']
+
+
+@pytest.mark.parametrize('interrupted', [False, True])
+def test_direct_publication_identity_survives_deletion_and_reopening(assistant, monkeypatch, interrupted):
+ client, path, _ = assistant
+ project = path.removesuffix('/assistant')
+ cid = client.get(path).json()['conversationId']
+ async def publish(self, run):
+ command = {'type': 'asset.writeText', 'payload': {'name': 'shot.md', 'text': 'wide shot'}}
+ for _ in range(2): # Replaying a tool call must still deliver one immutable output.
+ receipt = await self.business.execute(run.project_id, run.turn_id, run.session,
+ 'write', 'execute_command', command, [], run.config)
+ assert receipt['status'] == 'applied'
+ yield {'type': 'delta', 'text': 'Written'}
+ if interrupted:
+ raise RuntimeError('injected failure after publication')
+ monkeypatch.setattr(agent.AgentRuntimes, 'stream', publish)
+ saved = frames(send(client, path, cid, 'Write'))[-1]['conversation']['messages'][-1]
+ snapshot = client.get(project).json()
+ asset, = snapshot['assets']
+ assert saved['status'] == ('interrupted' if interrupted else 'complete')
+ assert saved['publishedAssets'] == {'projectId': snapshot['project']['id'],
+ 'eventCursor': snapshot['eventCursor'], 'assets': [{key: asset[key] for key in ('id', 'name', 'fingerprint')}]}
+
+ # A different turn can discuss an existing file without delivering it again.
+ async def discuss(self, run):
+ yield {'type': 'delta', 'text': asset['id']}
+ monkeypatch.setattr(agent.AgentRuntimes, 'stream', discuss)
+ assert 'publishedAssets' not in frames(send(client, path, cid, 'Discuss'))[-1]['conversation']['messages'][-1]
+ assert client.post(path + '/conversations', json={'id': str(uuid4())}).status_code == 200
+ payload = {'assetIds': [asset['id']], 'clearHistory': True}
+ preview = client.post(project + '/asset-delete-preview', json=payload).json()
+ assert preview['canDelete']
+ deleted = client.post(project + '/commands', json={'type': 'asset.delete', 'commandId': str(uuid4()),
+ 'projectId': snapshot['project']['id'], 'payload': {**payload, 'clearHistory': preview['clearsAllUndoRedo']},
+ 'expectedVersions': [{'objectType': 'asset', 'id': asset['id'], 'revision': asset['revision']}],
+ 'expectedPreview': preview['fingerprint']}).json()
+ assert deleted['status'] == 'applied', deleted
+ assert client.get(project).json()['assets'] == []
+ reopened = client.post(path + f'/conversations/{cid}/activate').json()
+ assert reopened['messages'][1] == saved
+ assert client.get(path).json()['messages'] == reopened['messages']
+
+
def test_citation_metadata_streams_and_persists_without_changing_raw_text_or_offsets(assistant, monkeypatch, tmp_path):
client, path, _ = assistant
source = {'id': 'turn1search0', 'url': 'https://example.test/source', 'title': 'Source'}
@@ -343,6 +579,30 @@ def test_stale_draft_and_stale_turn_cannot_modify_active_thread(assistant):
headers={'X-OpenDirector-Session': str(uuid4())}).status_code == 409
+def test_concurrent_and_archived_replays_cannot_share_a_turn_between_conversations(assistant):
+ client, path, contexts = assistant
+ first = client.get(path).json()['conversationId']
+ turn = {'id': str(uuid4()), 'conversationId': first, 'runtime': 'default', 'text': 'One output'}
+ ready = threading.Barrier(2)
+ def submit():
+ ready.wait(timeout=10)
+ return client.post(path + '/turns', json=turn)
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ requests = [pool.submit(submit) for _ in range(2)]
+ replies = [request.result(timeout=20) for request in requests]
+ assert sum(reply.status_code == 200 and frames(reply)[-1]['error'] is None for reply in replies) == 1
+ assert len(contexts) == 1
+ original = client.get(path).json()['messages']
+ assert len(original) == 2 and original[0]['id'] == turn['id']
+
+ second = client.post(path + '/conversations', json={'id': str(uuid4())}).json()['conversationId']
+ replay = frames(client.post(path + '/turns', json={**turn, 'conversationId': second}))[-1]
+ assert replay['error'] and replay['conversation'] is None
+ assert client.post(path + '/messages', json={**turn, 'conversationId': second}).status_code == 409
+ assert len(contexts) == 1 and client.get(path).json()['messages'] == []
+ assert client.post(path + f'/conversations/{first}/activate').json()['messages'] == original
+
+
def test_history_identifies_unsent_drafts_and_replays_creation_without_duplicates(assistant):
client, path, _ = assistant
first = client.get(path).json()['conversationId']
@@ -525,11 +785,12 @@ async def stream(self, run):
assert client.post(path + '/conversations', json={'id': str(uuid4())}).status_code == 200
-def disconnect_turn(client, path, turn_id):
+def disconnect_turn(client, path, turn_id, *, conversation_id=None):
"""Start a turn over raw ASGI and close the stream after its first delta."""
async def disconnect():
disconnected = asyncio.Event()
- body = json.dumps({'id': turn_id, 'runtime': 'default', 'text': '断线测试'}).encode()
+ body = json.dumps({'id': turn_id, 'runtime': 'default', 'text': '断线测试',
+ 'conversationId': conversation_id}).encode()
requested = False
async def receive():
nonlocal requested
diff --git a/tests/test_creation_image_edits.py b/tests/test_creation_image_edits.py
index b2c440d8e..896a9c729 100644
--- a/tests/test_creation_image_edits.py
+++ b/tests/test_creation_image_edits.py
@@ -217,3 +217,34 @@ async def test_direct_edit_requires_document_version_and_available_output(projec
assert applied.status == 'applied', applied
finally:
await runner.close()
+
+@pytest.mark.anyio
+@pytest.mark.parametrize('changed', ['parent_lock', 'item_revision'])
+async def test_hidden_result_edit_rechecks_original_version_and_current_parent_lock_on_save(project, changed):
+ store, pid, session = project
+ runner, _ = await generated(project)
+ try:
+ item_id = store.snapshot(pid).canvasItems[0].id
+ parent_id = uuid4()
+ assert send(store, pid, 'creation.batch', session=session, versions=versions(store.snapshot(pid)), operations=[
+ dict(type='canvas.show', payload=dict(item=dict(id=parent_id, kind='group', projectId=pid))),
+ dict(type='canvas.update', payload=dict(itemId=item_id, parentId=parent_id)),
+ dict(type='canvas.hide', payload=dict(itemId=item_id)),
+ dict(type='canvas.hide', payload=dict(itemId=parent_id)),
+ ]).status == 'applied'
+ edit = edit_command(project)
+ # The modal pins its item and asset versions; the ancestor is checked by
+ # the service at commit even though its version is absent from the draft.
+ edit = parse_command({**edit.model_dump(), 'expectedVersions':
+ [v for v in edit.expectedVersions if v.id != parent_id]})
+ patch = dict(itemId=parent_id, locked=True) if changed == 'parent_lock' else dict(itemId=item_id, title='Renamed')
+ assert send(store, pid, 'canvas.update', session=session, versions=versions(store.snapshot(pid)), **patch).status == 'applied'
+ before = store.snapshot(pid)
+ receipt = store.execute(edit, session=session)
+ assert receipt.status == 'rejected'
+ assert receipt.issues[0].code == ('role_restricted' if changed == 'parent_lock' else 'revision_conflict')
+ assert store.snapshot(pid) == before
+ assert all(not item.visible for item in before.canvasItems)
+ assert not before.editorDocuments
+ finally:
+ await runner.close()
diff --git a/tests/test_creation_media_publication.py b/tests/test_creation_media_publication.py
index 70a4eb13e..f259388e1 100644
--- a/tests/test_creation_media_publication.py
+++ b/tests/test_creation_media_publication.py
@@ -76,3 +76,52 @@ def test_refusal_keeps_all_outputs_unpublished(project,change):
receipt=send(store,pid,'canvas.publishMedia',session=session,versions=versions,**payload)
assert receipt.status=='rejected',receipt
assert store.snapshot(pid)==before
+
+def test_unplaced_audio_publication_retries_with_one_hidden_source_and_preserves_undo(project):
+ from test_creation_node_versions import versions
+ from test_voice_library import wav
+
+ store, pid, session = project
+ service = CreationToolAssets(store)
+ def upload(seconds):
+ record = service.import_file(pid, uuid4(), 'clip.wav', wav(seconds), session, provenance=AssetProvenance(source='upload'))
+ return service.assets.get(pid, record['id'])
+
+ source, output = upload(2), upload(1)
+ previous_id, anchor_id, output_id = uuid4(), uuid4(), uuid4()
+ earlier = send(store, pid, 'canvas.show', session=session, item=dict(id=previous_id, projectId=pid, kind='group'))
+ anchor = send(store, pid, 'creation.batch', session=session, versions=[ver('asset', source)], operations=[
+ dict(type='canvas.show', payload=dict(item=dict(id=anchor_id, kind='audio', projectId=pid,
+ binding=dict(role='material', objectRef=asset_ref(source))))),
+ dict(type='canvas.hide', payload=dict(itemId=anchor_id)),
+ ])
+ assert earlier.status == anchor.status == 'applied'
+ def node(item_id):
+ return next(item for item in store.snapshot(pid).canvasItems if item.id == item_id)
+ assert not node(anchor_id).visible and node(anchor_id).revision == 1
+ assert anchor.commandId not in CreationHistory(store).states(pid)
+ document = dict(id=uuid4(), projectId=pid, kind='media_edit', data=dict(tool='audio-trim',
+ sourceItems=[anchor_id], sources=[asset_ref(source)], parameters={}))
+ payload = dict(itemId=anchor_id, source=asset_ref(source), document=document,
+ outputs=[dict(itemId=output_id, asset=asset_ref(output), title='Trim')])
+ current = [ver('canvas_item', node(anchor_id)), ver('asset', output)]
+ stale = [{**current[0], 'revision': 2}, current[1]]
+ before = store.snapshot(pid)
+ refusal = send(store, pid, 'canvas.publishMedia', session=session, versions=stale, **payload)
+ assert refusal.status == 'rejected' and store.snapshot(pid) == before
+ publish = parse_command(dict(commandId=uuid4(), projectId=pid, type='canvas.publishMedia', payload=payload, expectedVersions=current))
+ receipt = store.execute(publish, session=session)
+ assert receipt.status == 'applied', receipt
+ assert store.execute(publish, session=session) == receipt
+ persisted = next(a for a in store.snapshot(pid).assets if a.id == output.id)
+ assert persisted.provenance.sources == (asset_ref(source),) and persisted.provenance.sourceItemId == anchor_id
+ for transition, target, expected in [('undo', receipt, (True, False)), ('undo', earlier, (False, False)),
+ ('redo', earlier, (True, False)), ('redo', receipt, (True, True))]:
+ state = 'applied' if transition == 'undo' else 'undone'
+ offered = next(entry for entry in CreationHistory(store).operations(pid) if entry['state'] == state)
+ assert offered['commandId'] == target.commandId
+ result = send(store, pid, 'history.' + transition, session=session, versions=versions(store.snapshot(pid)),
+ targetCommandId=target.commandId)
+ assert result.status == 'applied', result
+ assert not node(anchor_id).visible and node(anchor_id).revision == 1
+ assert (node(previous_id).visible, node(output_id).visible) == expected
diff --git a/tests/workspaceMode.test.ts b/tests/workspaceMode.test.ts
new file mode 100644
index 000000000..acc26636b
--- /dev/null
+++ b/tests/workspaceMode.test.ts
@@ -0,0 +1,42 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ readWorkspaceMode,
+ saveWorkspaceMode,
+ WORKSPACE_MODE_KEY,
+} from "../src/canvas/workspaceMode.ts";
+
+test("an unset or unsupported preference keeps the canvas entry point", () => {
+ for (const value of [null, "", "simple", "professional", '"agent"']) {
+ assert.equal(readWorkspaceMode({ getItem: () => value }), "canvas");
+ }
+});
+
+test("each saved mode is restored without writing project or other preferences", () => {
+ const values = new Map([["opendirector.locale.v1", "zh-CN"]]);
+ const storage = {
+ getItem: (key: string) => values.get(key) ?? null,
+ setItem: (key: string, value: string) => { values.set(key, value); },
+ };
+ for (const mode of ["agent", "canvas"] as const) {
+ assert.equal(saveWorkspaceMode(mode, storage), true);
+ assert.equal(readWorkspaceMode(storage), mode);
+ assert.deepEqual([...values], [
+ ["opendirector.locale.v1", "zh-CN"],
+ [WORKSPACE_MODE_KEY, mode],
+ ]);
+ }
+});
+
+test("a denied storage read still opens the canvas", () => {
+ assert.equal(readWorkspaceMode({ getItem: () => { throw new Error("denied"); } }), "canvas");
+});
+
+test("a failed write is reported without replacing the previous preference", () => {
+ const storage = {
+ getItem: () => "canvas",
+ setItem: () => { throw new Error("quota exceeded"); },
+ };
+ assert.equal(saveWorkspaceMode("agent", storage), false);
+ assert.equal(readWorkspaceMode(storage), "canvas");
+});